blob: abe1704e95d62543f963632c2ef6f2529236c118 [file] [log] [blame]
Joel Fernandesd76a2002018-10-16 13:19:58 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "LibBpfLoader"
18
19#include <errno.h>
20#include <linux/bpf.h>
21#include <linux/elf.h>
22#include <log/log.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Maciej Żenczykowski83f29772020-01-27 03:11:51 -080027#include <sys/stat.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070028#include <sys/utsname.h>
29#include <unistd.h>
30
Paul Lawrence9548f9f2021-11-09 16:32:43 +000031// This is BpfLoader v0.8
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080032#define BPFLOADER_VERSION_MAJOR 0u
Paul Lawrence9548f9f2021-11-09 16:32:43 +000033#define BPFLOADER_VERSION_MINOR 8u
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080034#define BPFLOADER_VERSION ((BPFLOADER_VERSION_MAJOR << 16) | BPFLOADER_VERSION_MINOR)
35
Maciej Żenczykowski07375e22020-02-19 14:23:59 -080036#include "bpf/BpfUtils.h"
Ken Chend5689472021-12-20 18:07:21 +080037#include "bpf/bpf_map_def.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070038#include "include/libbpf_android.h"
39
40#include <cstdlib>
41#include <fstream>
42#include <iostream>
Connor O'Brien3278a162020-02-13 21:45:22 -080043#include <optional>
Joel Fernandesd76a2002018-10-16 13:19:58 -070044#include <string>
Christopher Ferrisc151c672019-02-01 15:31:26 -080045#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070046
47#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070048#include <android-base/unique_fd.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070049
50#define BPF_FS_PATH "/sys/fs/bpf/"
51
52// Size of the BPF log buffer for verifier logging
Stephane Leeeb61b732021-10-21 17:03:11 -070053#define BPF_LOAD_LOG_SZ 0xfffff
Joel Fernandesd76a2002018-10-16 13:19:58 -070054
55using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070056using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070057using std::ifstream;
58using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080059using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080060using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070061using std::vector;
62
63namespace android {
64namespace bpf {
65
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -080066static string pathToFilename(const string& path, bool noext = false) {
67 vector<string> spath = android::base::Split(path, "/");
68 string ret = spath.back();
69
70 if (noext) {
71 size_t lastindex = ret.find_last_of('.');
72 return ret.substr(0, lastindex);
73 }
74 return ret;
75}
76
Joel Fernandesd76a2002018-10-16 13:19:58 -070077typedef struct {
78 const char* name;
79 enum bpf_prog_type type;
80} sectionType;
81
82/*
83 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070084 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -070085 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070086 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -070087 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070088 *
89 * However, be aware that you should not be directly using the SECTION() macro.
90 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -070091 */
92sectionType sectionNameTypes[] = {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -080093 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
94 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
95 {"cgroupsockaddr/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR},
96 {"kprobe/", BPF_PROG_TYPE_KPROBE},
97 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
98 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
99 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
100 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT},
101 {"xdp/", BPF_PROG_TYPE_XDP},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700102};
103
104typedef struct {
105 enum bpf_prog_type type;
106 string name;
107 vector<char> data;
108 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800109 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700110
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700111 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700112} codeSection;
113
Joel Fernandesd76a2002018-10-16 13:19:58 -0700114static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
115 elfFile.seekg(0);
116 if (elfFile.fail()) return -1;
117
118 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
119
120 return 0;
121}
122
123/* Reads all section header tables into an Shdr array */
124static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
125 Elf64_Ehdr eh;
126 int ret = 0;
127
128 ret = readElfHeader(elfFile, &eh);
129 if (ret) return ret;
130
131 elfFile.seekg(eh.e_shoff);
132 if (elfFile.fail()) return -1;
133
134 /* Read shdr table entries */
135 shTable.resize(eh.e_shnum);
136
137 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
138
139 return 0;
140}
141
142/* Read a section by its index - for ex to get sec hdr strtab blob */
143static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
144 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800145 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700146 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700147
148 elfFile.seekg(shTable[id].sh_offset);
149 if (elfFile.fail()) return -1;
150
151 sec.resize(shTable[id].sh_size);
152 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
153
154 return 0;
155}
156
157/* Read whole section header string table */
158static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
159 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800160 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700161 if (ret) return ret;
162
163 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
164 if (ret) return ret;
165
166 return 0;
167}
168
169/* Get name from offset in strtab */
170static int getSymName(ifstream& elfFile, int nameOff, string& name) {
171 int ret;
172 vector<char> secStrTab;
173
174 ret = readSectionHeaderStrtab(elfFile, secStrTab);
175 if (ret) return ret;
176
177 if (nameOff >= (int)secStrTab.size()) return -1;
178
179 name = string((char*)secStrTab.data() + nameOff);
180 return 0;
181}
182
183/* Reads a full section by name - example to get the GPL license */
184static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
185 vector<char> secStrTab;
186 vector<Elf64_Shdr> shTable;
187 int ret;
188
189 ret = readSectionHeadersAll(elfFile, shTable);
190 if (ret) return ret;
191
192 ret = readSectionHeaderStrtab(elfFile, secStrTab);
193 if (ret) return ret;
194
195 for (int i = 0; i < (int)shTable.size(); i++) {
196 char* secname = secStrTab.data() + shTable[i].sh_name;
197 if (!secname) continue;
198
199 if (!strcmp(secname, name)) {
200 vector<char> dataTmp;
201 dataTmp.resize(shTable[i].sh_size);
202
203 elfFile.seekg(shTable[i].sh_offset);
204 if (elfFile.fail()) return -1;
205
206 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
207
208 data = dataTmp;
209 return 0;
210 }
211 }
212 return -2;
213}
214
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700215unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800216 vector<char> theBytes;
217 int ret = readSectionByName(name, elfFile, theBytes);
218 if (ret) {
219 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).\n", name, defVal, defVal);
220 return defVal;
221 } else if (theBytes.size() < sizeof(unsigned int)) {
222 ALOGE("Section %s too short (defaulting to %u [0x%x]).\n", name, defVal, defVal);
223 return defVal;
224 } else {
225 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
226 unsigned int value = static_cast<unsigned char>(theBytes[3]);
227 value <<= 8;
228 value += static_cast<unsigned char>(theBytes[2]);
229 value <<= 8;
230 value += static_cast<unsigned char>(theBytes[1]);
231 value <<= 8;
232 value += static_cast<unsigned char>(theBytes[0]);
233 ALOGI("Section %s value is %u [0x%x]\n", name, value, value);
234 return value;
235 }
236}
237
Joel Fernandesd76a2002018-10-16 13:19:58 -0700238static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
239 int ret;
240 vector<Elf64_Shdr> shTable;
241
242 ret = readSectionHeadersAll(elfFile, shTable);
243 if (ret) return ret;
244
245 for (int i = 0; i < (int)shTable.size(); i++) {
246 if ((int)shTable[i].sh_type != type) continue;
247
248 vector<char> dataTmp;
249 dataTmp.resize(shTable[i].sh_size);
250
251 elfFile.seekg(shTable[i].sh_offset);
252 if (elfFile.fail()) return -1;
253
254 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
255
256 data = dataTmp;
257 return 0;
258 }
259 return -2;
260}
261
262static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
263 return (a.st_value < b.st_value);
264}
265
266static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
267 int ret, numElems;
268 Elf64_Sym* buf;
269 vector<char> secData;
270
271 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
272 if (ret) return ret;
273
274 buf = (Elf64_Sym*)secData.data();
275 numElems = (secData.size() / sizeof(Elf64_Sym));
276 data.assign(buf, buf + numElems);
277
278 if (sort) std::sort(data.begin(), data.end(), symCompare);
279 return 0;
280}
281
282static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800283 for (auto& snt : sectionNameTypes)
284 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700285
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000286 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
287 if (StartsWith(name, "fuse/")) {
288 int result = BPF_PROG_TYPE_UNSPEC;
289 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
290 return static_cast<bpf_prog_type>(result);
291 }
292
Joel Fernandesd76a2002018-10-16 13:19:58 -0700293 return BPF_PROG_TYPE_UNSPEC;
294}
295
296/* If ever needed
297static string getSectionName(enum bpf_prog_type type)
298{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800299 for (auto& snt : sectionNameTypes)
300 if (snt.type == type)
301 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700302
303 return NULL;
304}
305*/
306
307static bool isRelSection(codeSection& cs, string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800308 for (auto& snt : sectionNameTypes) {
309 if (snt.type != cs.type) continue;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700310
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800311 if (StartsWith(name, string(".rel") + snt.name))
Joel Fernandesd76a2002018-10-16 13:19:58 -0700312 return true;
313 else
314 return false;
315 }
316 return false;
317}
318
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800319static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
320 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800321 vector<char> pdData;
322 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800323 // Older file formats do not require a 'progs' section at all.
324 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800325 if (ret == -2) return 0;
326 if (ret) return ret;
327
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800328 if (pdData.size() % sizeOfBpfProgDef) {
329 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0\n",
330 pdData.size(), sizeOfBpfProgDef);
331 return -1;
332 };
333
334 int progCount = pdData.size() / sizeOfBpfProgDef;
335 pd.resize(progCount);
336 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
337
338 const char* dataPtr = pdData.data();
339 for (auto& p : pd) {
340 // First we zero initialize
341 memset(&p, 0, sizeof(p));
342 // Then we set non-zero defaults
343 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
344 // Then we copy over the structure prefix from the ELF file.
345 memcpy(&p, dataPtr, trimmedSize);
346 // Move to next struct in the ELF file
347 dataPtr += sizeOfBpfProgDef;
348 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800349 return 0;
350}
351
352static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names) {
353 int ret;
354 string name;
355 vector<Elf64_Sym> symtab;
356 vector<Elf64_Shdr> shTable;
357
358 ret = readSymTab(elfFile, 1 /* sort */, symtab);
359 if (ret) return ret;
360
361 /* Get index of section */
362 ret = readSectionHeadersAll(elfFile, shTable);
363 if (ret) return ret;
364
365 int sec_idx = -1;
366 for (int i = 0; i < (int)shTable.size(); i++) {
367 ret = getSymName(elfFile, shTable[i].sh_name, name);
368 if (ret) return ret;
369
370 if (!name.compare(sectionName)) {
371 sec_idx = i;
372 break;
373 }
374 }
375
376 /* No section found with matching name*/
377 if (sec_idx == -1) {
Maciej Żenczykowski21f34cb2020-07-20 18:44:33 -0700378 ALOGW("No %s section could be found in elf object\n", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800379 return -1;
380 }
381
382 for (int i = 0; i < (int)symtab.size(); i++) {
383 if (symtab[i].st_shndx == sec_idx) {
384 string s;
385 ret = getSymName(elfFile, symtab[i].st_name, s);
386 if (ret) return ret;
387 names.push_back(s);
388 }
389 }
390
391 return 0;
392}
393
Joel Fernandesd76a2002018-10-16 13:19:58 -0700394/* Read a section by its index - for ex to get sec hdr strtab blob */
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800395static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700396 vector<Elf64_Shdr> shTable;
397 int entries, ret = 0;
398
399 ret = readSectionHeadersAll(elfFile, shTable);
400 if (ret) return ret;
401 entries = shTable.size();
402
Connor O'Brien3278a162020-02-13 21:45:22 -0800403 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800404 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800405 if (ret) return ret;
406 vector<string> progDefNames;
407 ret = getSectionSymNames(elfFile, "progs", progDefNames);
408 if (!pd.empty() && ret) return ret;
409
Joel Fernandesd76a2002018-10-16 13:19:58 -0700410 for (int i = 0; i < entries; i++) {
411 string name;
412 codeSection cs_temp;
413 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
414
415 ret = getSymName(elfFile, shTable[i].sh_name, name);
416 if (ret) return ret;
417
418 enum bpf_prog_type ptype = getSectionType(name);
419 if (ptype != BPF_PROG_TYPE_UNSPEC) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800420 string oldName = name;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800421
422 // convert all slashes to underscores
423 std::replace(name.begin(), name.end(), '/', '_');
424
Joel Fernandesd76a2002018-10-16 13:19:58 -0700425 cs_temp.type = ptype;
426 cs_temp.name = name;
427
428 ret = readSectionByIdx(elfFile, i, cs_temp.data);
429 if (ret) return ret;
430 ALOGD("Loaded code section %d (%s)\n", i, name.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800431
432 vector<string> csSymNames;
433 ret = getSectionSymNames(elfFile, oldName, csSymNames);
434 if (ret || !csSymNames.size()) return ret;
435 for (size_t i = 0; i < progDefNames.size(); ++i) {
436 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
437 cs_temp.prog_def = pd[i];
438 break;
439 }
440 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700441 }
442
443 /* Check for rel section */
444 if (cs_temp.data.size() > 0 && i < entries) {
445 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
446 if (ret) return ret;
447
448 if (isRelSection(cs_temp, name)) {
449 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
450 if (ret) return ret;
451 ALOGD("Loaded relo section %d (%s)\n", i, name.c_str());
452 }
453 }
454
455 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700456 cs.push_back(std::move(cs_temp));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700457 ALOGD("Adding section %d to cs list\n", i);
458 }
459 }
460 return 0;
461}
462
463static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
464 vector<Elf64_Sym> symtab;
465 int ret = 0;
466
467 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
468 if (ret) return ret;
469
470 if (index >= (int)symtab.size()) return -1;
471
472 return getSymName(elfFile, symtab[index].st_name, name);
473}
474
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800475static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800476 const char* prefix, size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700477 int ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700478 vector<char> mdData;
479 vector<struct bpf_map_def> md;
480 vector<string> mapNames;
481 string fname = pathToFilename(string(elfPath), true);
482
483 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800484 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700485 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800486
487 if (mdData.size() % sizeOfBpfMapDef) {
488 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0\n",
489 mdData.size(), sizeOfBpfMapDef);
490 return -1;
491 };
492
493 int mapCount = mdData.size() / sizeOfBpfMapDef;
494 md.resize(mapCount);
495 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
496
497 const char* dataPtr = mdData.data();
498 for (auto& m : md) {
499 // First we zero initialize
500 memset(&m, 0, sizeof(m));
501 // Then we set non-zero defaults
502 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700503 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800504 // Then we copy over the structure prefix from the ELF file.
505 memcpy(&m, dataPtr, trimmedSize);
506 // Move to next struct in the ELF file
507 dataPtr += sizeOfBpfMapDef;
508 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700509
Connor O'Brien3278a162020-02-13 21:45:22 -0800510 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700511 if (ret) return ret;
512
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700513 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700514
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700515 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800516 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
517 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x\n", mapNames[i].c_str(),
518 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700519 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800520 continue;
521 }
522
523 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
524 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x\n", mapNames[i].c_str(),
525 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700526 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800527 continue;
528 }
529
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700530 if (kvers < md[i].min_kver) {
531 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x\n",
532 mapNames[i].c_str(), kvers, md[i].min_kver);
533 mapFds.push_back(unique_fd());
534 continue;
535 }
536
537 if (kvers >= md[i].max_kver) {
538 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x\n",
539 mapNames[i].c_str(), kvers, md[i].max_kver);
540 mapFds.push_back(unique_fd());
541 continue;
542 }
543
544 // Format of pin location is /sys/fs/bpf/<prefix>map_<filename>_<mapname>
545 string mapPinLoc =
546 string(BPF_FS_PATH) + prefix + "map_" + fname + "_" + string(mapNames[i]);
547 bool reuse = false;
548 unique_fd fd;
549 int saved_errno;
550
Joel Fernandesd76a2002018-10-16 13:19:58 -0700551 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700552 fd.reset(bpf_obj_get(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800553 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700554 ALOGD("bpf_create_map reusing map %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700555 reuse = true;
556 } else {
Maciej Żenczykowskicb358de2021-03-04 07:27:38 -0800557 enum bpf_map_type type = md[i].type;
558 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
559 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
560 // of be approximated: ARRAY has the same userspace api, though it is not usable
561 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
562 // helper doesn't exist on 4.9 anyway (so the bpf program would fail to load,
563 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
564 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
565 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
566 type = BPF_MAP_TYPE_ARRAY;
567 }
568 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
569 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
570 // of be approximated: HASH has the same userspace visible api.
571 // However it cannot be used by ebpf programs in the same way.
572 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
573 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
574 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
575 // programs as being 5.4+...
576 type = BPF_MAP_TYPE_HASH;
577 }
578 fd.reset(bpf_create_map(type, mapNames[i].c_str(), md[i].key_size, md[i].value_size,
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700579 md[i].max_entries, md[i].map_flags));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800580 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700581 ALOGD("bpf_create_map name %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700582 }
583
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800584 if (fd < 0) return -saved_errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700585
586 if (!reuse) {
587 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800588 if (ret) return -errno;
589 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
590 if (ret) return -errno;
591 ret = chmod(mapPinLoc.c_str(), md[i].mode);
592 if (ret) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700593 }
594
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700595 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700596 }
597
598 return ret;
599}
600
601/* For debugging, dump all instructions */
602static void dumpIns(char* ins, int size) {
603 for (int row = 0; row < size / 8; row++) {
604 ALOGE("%d: ", row);
605 for (int j = 0; j < 8; j++) {
606 ALOGE("%3x ", ins[(row * 8) + j]);
607 }
608 ALOGE("\n");
609 }
610}
611
612/* For debugging, dump all code sections from cs list */
613static void dumpAllCs(vector<codeSection>& cs) {
614 for (int i = 0; i < (int)cs.size(); i++) {
615 ALOGE("Dumping cs %d, name %s\n", int(i), cs[i].name.c_str());
616 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
617 ALOGE("-----------\n");
618 }
619}
620
621static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
622 int insnIndex;
623 struct bpf_insn *insn, *insns;
624
625 insns = (struct bpf_insn*)(insnsPtr);
626
627 insnIndex = offset / sizeof(struct bpf_insn);
628 insn = &insns[insnIndex];
629
630 ALOGD(
631 "applying relo to instruction at byte offset: %d, \
632 insn offset %d , insn %lx\n",
633 (int)offset, (int)insnIndex, *(unsigned long*)insn);
634
635 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
636 ALOGE("Dumping all instructions till ins %d\n", insnIndex);
637 ALOGE("invalid relo for insn %d: code 0x%x\n", insnIndex, insn->code);
638 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
639 return;
640 }
641
642 insn->imm = fd;
643 insn->src_reg = BPF_PSEUDO_MAP_FD;
644}
645
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700646static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700647 vector<string> mapNames;
648
Connor O'Brien3278a162020-02-13 21:45:22 -0800649 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700650 if (ret) return;
651
652 for (int k = 0; k != (int)cs.size(); k++) {
653 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
654 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
655
656 for (int i = 0; i < n_rel; i++) {
657 int symIndex = ELF64_R_SYM(rel[i].r_info);
658 string symName;
659
660 ret = getSymNameByIdx(elfFile, symIndex, symName);
661 if (ret) return;
662
663 /* Find the map fd and apply relo */
664 for (int j = 0; j < (int)mapNames.size(); j++) {
665 if (!mapNames[j].compare(symName)) {
666 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
667 break;
668 }
669 }
670 }
671 }
672}
673
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800674static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
675 const char* prefix) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800676 unsigned kvers = kernelVersion();
677 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700678
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800679 if (!kvers) return -1;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700680
681 string fname = pathToFilename(string(elfPath), true);
682
683 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700684 string name = cs[i].name;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800685 unsigned bpfMinVer = DEFAULT_BPFLOADER_MIN_VER; // v0.0
686 unsigned bpfMaxVer = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Joel Fernandesd76a2002018-10-16 13:19:58 -0700687
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800688 if (cs[i].prog_def.has_value()) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700689 unsigned min_kver = cs[i].prog_def->min_kver;
690 unsigned max_kver = cs[i].prog_def->max_kver;
691 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)\n", i, name.c_str(), min_kver,
692 max_kver, kvers);
693 if (kvers < min_kver) continue;
694 if (kvers >= max_kver) continue;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800695
696 bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
697 bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800698 }
699
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800700 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)\n", i, name.c_str(),
701 bpfMinVer, bpfMaxVer);
702 if (BPFLOADER_VERSION < bpfMinVer) continue;
703 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
704
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700705 // strip any potential $foo suffix
706 // this can be used to provide duplicate programs
707 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700708 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700709
710 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700711 // Format of pin location is
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800712 // /sys/fs/bpf/<prefix>prog_<filename>_<mapname>
713 string progPinLoc = BPF_FS_PATH;
714 progPinLoc += prefix;
715 progPinLoc += "prog_";
Maciej Żenczykowski6c7871b2020-04-23 12:46:00 -0700716 progPinLoc += fname;
717 progPinLoc += '_';
718 progPinLoc += name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700719 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700720 fd = retrieveProgram(progPinLoc.c_str());
721 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)\n", progPinLoc.c_str(), fd,
722 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700723 reuse = true;
724 } else {
725 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
726
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700727 fd = bpf_prog_load(cs[i].type, name.c_str(), (struct bpf_insn*)cs[i].data.data(),
728 cs[i].data.size(), license.c_str(), kvers, 0, log_buf.data(),
729 log_buf.size());
Steven Moreland804bca02019-12-12 17:21:23 -0800730 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)\n", elfPath,
731 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700732
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800733 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800734 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800735
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700736 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
737 for (const auto& line : lines) ALOGW("%s", line.c_str());
738 ALOGW("bpf_prog_load - END log_buf contents.");
739
740 if (cs[i].prog_def->optional) {
741 ALOGW("failed program is marked optional - continuing...");
742 continue;
743 }
744 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800745 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700746 }
747
748 if (fd < 0) return fd;
749 if (fd == 0) return -EINVAL;
750
751 if (!reuse) {
752 ret = bpf_obj_pin(fd, progPinLoc.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800753 if (ret) return -errno;
754 if (cs[i].prog_def.has_value()) {
755 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
756 (gid_t)cs[i].prog_def->gid)) {
757 return -errno;
758 }
759 }
760 if (chmod(progPinLoc.c_str(), 0440)) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700761 }
762
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700763 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700764 }
765
766 return 0;
767}
768
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800769int loadProg(const char* elfPath, bool* isCritical, const char* prefix) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700770 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700771 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700772 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700773 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700774 int ret;
775
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700776 if (!isCritical) return -1;
777 *isCritical = false;
778
Joel Fernandesd76a2002018-10-16 13:19:58 -0700779 ifstream elfFile(elfPath, ios::in | ios::binary);
780 if (!elfFile.is_open()) return -1;
781
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700782 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700783 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700784
Joel Fernandesd76a2002018-10-16 13:19:58 -0700785 ret = readSectionByName("license", elfFile, license);
786 if (ret) {
787 ALOGE("Couldn't find license in %s\n", elfPath);
788 return ret;
789 } else {
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700790 ALOGD("Loading %s%s ELF object %s with license %s\n",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700791 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700792 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700793 }
794
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800795 // the following default values are for bpfloader V0.0 format which does not include them
796 unsigned int bpfLoaderMinVer =
797 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
798 unsigned int bpfLoaderMaxVer =
799 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
800 size_t sizeOfBpfMapDef =
801 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
802 size_t sizeOfBpfProgDef =
803 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
804
805 // inclusive lower bound check
806 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
807 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x\n",
808 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
809 return 0;
810 }
811
812 // exclusive upper bound check
813 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
814 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x\n",
815 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
816 return 0;
817 }
818
819 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)\n",
820 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
821
822 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
823 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)\n", sizeOfBpfMapDef,
824 DEFAULT_SIZEOF_BPF_MAP_DEF);
825 return -1;
826 }
827
828 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
829 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)\n", sizeOfBpfProgDef,
830 DEFAULT_SIZEOF_BPF_PROG_DEF);
831 return -1;
832 }
833
834 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700835 if (ret) {
836 ALOGE("Couldn't read all code sections in %s\n", elfPath);
837 return ret;
838 }
839
840 /* Just for future debugging */
841 if (0) dumpAllCs(cs);
842
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800843 ret = createMaps(elfPath, elfFile, mapFds, prefix, sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700844 if (ret) {
845 ALOGE("Failed to create maps: (ret=%d) in %s\n", ret, elfPath);
846 return ret;
847 }
848
849 for (int i = 0; i < (int)mapFds.size(); i++)
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700850 ALOGD("map_fd found at %d is %d in %s\n", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700851
852 applyMapRelo(elfFile, mapFds, cs);
853
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800854 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700855 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d\n", ret);
856
857 return ret;
858}
859
Joel Fernandesd76a2002018-10-16 13:19:58 -0700860} // namespace bpf
861} // namespace android