blob: b1af34f98fc157ec2e29fd59ad142591d9321f6a [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
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080031// This is BpfLoader 0.1, we need to define this prior to including bpf_map_def.h
32// to get the 0.1 struct definitions
33#define BPFLOADER_VERSION_MAJOR 0u
34#define BPFLOADER_VERSION_MINOR 1u
35#define BPFLOADER_VERSION ((BPFLOADER_VERSION_MAJOR << 16) | BPFLOADER_VERSION_MINOR)
36
Maciej Żenczykowski730a3862020-01-27 01:10:48 -080037#include "../progs/include/bpf_map_def.h"
Maciej Żenczykowski07375e22020-02-19 14:23:59 -080038#include "bpf/BpfUtils.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070039#include "include/libbpf_android.h"
40
41#include <cstdlib>
42#include <fstream>
43#include <iostream>
Connor O'Brien3278a162020-02-13 21:45:22 -080044#include <optional>
Joel Fernandesd76a2002018-10-16 13:19:58 -070045#include <string>
Christopher Ferrisc151c672019-02-01 15:31:26 -080046#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070047
48#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070049#include <android-base/unique_fd.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070050
51#define BPF_FS_PATH "/sys/fs/bpf/"
52
53// Size of the BPF log buffer for verifier logging
54#define BPF_LOAD_LOG_SZ 0x1ffff
55
56using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070057using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070058using std::ifstream;
59using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080060using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080061using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070062using std::vector;
63
64namespace android {
65namespace bpf {
66
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -080067static string pathToFilename(const string& path, bool noext = false) {
68 vector<string> spath = android::base::Split(path, "/");
69 string ret = spath.back();
70
71 if (noext) {
72 size_t lastindex = ret.find_last_of('.');
73 return ret.substr(0, lastindex);
74 }
75 return ret;
76}
77
Joel Fernandesd76a2002018-10-16 13:19:58 -070078typedef struct {
79 const char* name;
80 enum bpf_prog_type type;
81} sectionType;
82
83/*
84 * Map section name prefixes to program types, the section name will be:
85 * SEC(<prefix>/<name-of-program>)
86 * For example:
87 * SEC("tracepoint/sched_switch_func") where sched_switch_funcs
88 * is the name of the program, and tracepoint is the type.
89 */
90sectionType sectionNameTypes[] = {
Maciej Żenczykowskiaa462222021-01-07 14:24:45 -080091 {"kprobe", BPF_PROG_TYPE_KPROBE},
92 {"tracepoint", BPF_PROG_TYPE_TRACEPOINT},
93 {"skfilter", BPF_PROG_TYPE_SOCKET_FILTER},
94 {"cgroupskb", BPF_PROG_TYPE_CGROUP_SKB},
95 {"schedcls", BPF_PROG_TYPE_SCHED_CLS},
96 {"cgroupsock", BPF_PROG_TYPE_CGROUP_SOCK},
97 {"xdp", BPF_PROG_TYPE_XDP},
Joel Fernandesd76a2002018-10-16 13:19:58 -070098
Maciej Żenczykowskiaa462222021-01-07 14:24:45 -080099 /* End of table */
100 {"END", BPF_PROG_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700101};
102
103typedef struct {
104 enum bpf_prog_type type;
105 string name;
106 vector<char> data;
107 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800108 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700109
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700110 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700111} codeSection;
112
Joel Fernandesd76a2002018-10-16 13:19:58 -0700113static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
114 elfFile.seekg(0);
115 if (elfFile.fail()) return -1;
116
117 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
118
119 return 0;
120}
121
122/* Reads all section header tables into an Shdr array */
123static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
124 Elf64_Ehdr eh;
125 int ret = 0;
126
127 ret = readElfHeader(elfFile, &eh);
128 if (ret) return ret;
129
130 elfFile.seekg(eh.e_shoff);
131 if (elfFile.fail()) return -1;
132
133 /* Read shdr table entries */
134 shTable.resize(eh.e_shnum);
135
136 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
137
138 return 0;
139}
140
141/* Read a section by its index - for ex to get sec hdr strtab blob */
142static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
143 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800144 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700145 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700146
147 elfFile.seekg(shTable[id].sh_offset);
148 if (elfFile.fail()) return -1;
149
150 sec.resize(shTable[id].sh_size);
151 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
152
153 return 0;
154}
155
156/* Read whole section header string table */
157static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
158 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800159 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700160 if (ret) return ret;
161
162 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
163 if (ret) return ret;
164
165 return 0;
166}
167
168/* Get name from offset in strtab */
169static int getSymName(ifstream& elfFile, int nameOff, string& name) {
170 int ret;
171 vector<char> secStrTab;
172
173 ret = readSectionHeaderStrtab(elfFile, secStrTab);
174 if (ret) return ret;
175
176 if (nameOff >= (int)secStrTab.size()) return -1;
177
178 name = string((char*)secStrTab.data() + nameOff);
179 return 0;
180}
181
182/* Reads a full section by name - example to get the GPL license */
183static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
184 vector<char> secStrTab;
185 vector<Elf64_Shdr> shTable;
186 int ret;
187
188 ret = readSectionHeadersAll(elfFile, shTable);
189 if (ret) return ret;
190
191 ret = readSectionHeaderStrtab(elfFile, secStrTab);
192 if (ret) return ret;
193
194 for (int i = 0; i < (int)shTable.size(); i++) {
195 char* secname = secStrTab.data() + shTable[i].sh_name;
196 if (!secname) continue;
197
198 if (!strcmp(secname, name)) {
199 vector<char> dataTmp;
200 dataTmp.resize(shTable[i].sh_size);
201
202 elfFile.seekg(shTable[i].sh_offset);
203 if (elfFile.fail()) return -1;
204
205 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
206
207 data = dataTmp;
208 return 0;
209 }
210 }
211 return -2;
212}
213
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800214static unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
215 vector<char> theBytes;
216 int ret = readSectionByName(name, elfFile, theBytes);
217 if (ret) {
218 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).\n", name, defVal, defVal);
219 return defVal;
220 } else if (theBytes.size() < sizeof(unsigned int)) {
221 ALOGE("Section %s too short (defaulting to %u [0x%x]).\n", name, defVal, defVal);
222 return defVal;
223 } else {
224 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
225 unsigned int value = static_cast<unsigned char>(theBytes[3]);
226 value <<= 8;
227 value += static_cast<unsigned char>(theBytes[2]);
228 value <<= 8;
229 value += static_cast<unsigned char>(theBytes[1]);
230 value <<= 8;
231 value += static_cast<unsigned char>(theBytes[0]);
232 ALOGI("Section %s value is %u [0x%x]\n", name, value, value);
233 return value;
234 }
235}
236
Joel Fernandesd76a2002018-10-16 13:19:58 -0700237static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
238 int ret;
239 vector<Elf64_Shdr> shTable;
240
241 ret = readSectionHeadersAll(elfFile, shTable);
242 if (ret) return ret;
243
244 for (int i = 0; i < (int)shTable.size(); i++) {
245 if ((int)shTable[i].sh_type != type) continue;
246
247 vector<char> dataTmp;
248 dataTmp.resize(shTable[i].sh_size);
249
250 elfFile.seekg(shTable[i].sh_offset);
251 if (elfFile.fail()) return -1;
252
253 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
254
255 data = dataTmp;
256 return 0;
257 }
258 return -2;
259}
260
261static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
262 return (a.st_value < b.st_value);
263}
264
265static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
266 int ret, numElems;
267 Elf64_Sym* buf;
268 vector<char> secData;
269
270 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
271 if (ret) return ret;
272
273 buf = (Elf64_Sym*)secData.data();
274 numElems = (secData.size() / sizeof(Elf64_Sym));
275 data.assign(buf, buf + numElems);
276
277 if (sort) std::sort(data.begin(), data.end(), symCompare);
278 return 0;
279}
280
281static enum bpf_prog_type getSectionType(string& name) {
282 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++)
283 if (StartsWith(name, sectionNameTypes[i].name)) return sectionNameTypes[i].type;
284
285 return BPF_PROG_TYPE_UNSPEC;
286}
287
288/* If ever needed
289static string getSectionName(enum bpf_prog_type type)
290{
291 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++)
292 if (sectionNameTypes[i].type == type)
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800293 return string(sectionNameTypes[i].name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700294
295 return NULL;
296}
297*/
298
299static bool isRelSection(codeSection& cs, string& name) {
300 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++) {
301 sectionType st = sectionNameTypes[i];
302
303 if (st.type != cs.type) continue;
304
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800305 if (StartsWith(name, string(".rel") + st.name + "/"))
Joel Fernandesd76a2002018-10-16 13:19:58 -0700306 return true;
307 else
308 return false;
309 }
310 return false;
311}
312
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800313static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
314 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800315 vector<char> pdData;
316 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800317 // Older file formats do not require a 'progs' section at all.
318 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800319 if (ret == -2) return 0;
320 if (ret) return ret;
321
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800322 if (pdData.size() % sizeOfBpfProgDef) {
323 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0\n",
324 pdData.size(), sizeOfBpfProgDef);
325 return -1;
326 };
327
328 int progCount = pdData.size() / sizeOfBpfProgDef;
329 pd.resize(progCount);
330 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
331
332 const char* dataPtr = pdData.data();
333 for (auto& p : pd) {
334 // First we zero initialize
335 memset(&p, 0, sizeof(p));
336 // Then we set non-zero defaults
337 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
338 // Then we copy over the structure prefix from the ELF file.
339 memcpy(&p, dataPtr, trimmedSize);
340 // Move to next struct in the ELF file
341 dataPtr += sizeOfBpfProgDef;
342 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800343 return 0;
344}
345
346static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names) {
347 int ret;
348 string name;
349 vector<Elf64_Sym> symtab;
350 vector<Elf64_Shdr> shTable;
351
352 ret = readSymTab(elfFile, 1 /* sort */, symtab);
353 if (ret) return ret;
354
355 /* Get index of section */
356 ret = readSectionHeadersAll(elfFile, shTable);
357 if (ret) return ret;
358
359 int sec_idx = -1;
360 for (int i = 0; i < (int)shTable.size(); i++) {
361 ret = getSymName(elfFile, shTable[i].sh_name, name);
362 if (ret) return ret;
363
364 if (!name.compare(sectionName)) {
365 sec_idx = i;
366 break;
367 }
368 }
369
370 /* No section found with matching name*/
371 if (sec_idx == -1) {
Maciej Żenczykowski21f34cb2020-07-20 18:44:33 -0700372 ALOGW("No %s section could be found in elf object\n", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800373 return -1;
374 }
375
376 for (int i = 0; i < (int)symtab.size(); i++) {
377 if (symtab[i].st_shndx == sec_idx) {
378 string s;
379 ret = getSymName(elfFile, symtab[i].st_name, s);
380 if (ret) return ret;
381 names.push_back(s);
382 }
383 }
384
385 return 0;
386}
387
Joel Fernandesd76a2002018-10-16 13:19:58 -0700388/* Read a section by its index - for ex to get sec hdr strtab blob */
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800389static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700390 vector<Elf64_Shdr> shTable;
391 int entries, ret = 0;
392
393 ret = readSectionHeadersAll(elfFile, shTable);
394 if (ret) return ret;
395 entries = shTable.size();
396
Connor O'Brien3278a162020-02-13 21:45:22 -0800397 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800398 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800399 if (ret) return ret;
400 vector<string> progDefNames;
401 ret = getSectionSymNames(elfFile, "progs", progDefNames);
402 if (!pd.empty() && ret) return ret;
403
Joel Fernandesd76a2002018-10-16 13:19:58 -0700404 for (int i = 0; i < entries; i++) {
405 string name;
406 codeSection cs_temp;
407 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
408
409 ret = getSymName(elfFile, shTable[i].sh_name, name);
410 if (ret) return ret;
411
412 enum bpf_prog_type ptype = getSectionType(name);
413 if (ptype != BPF_PROG_TYPE_UNSPEC) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800414 string oldName = name;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800415
416 // convert all slashes to underscores
417 std::replace(name.begin(), name.end(), '/', '_');
418
Joel Fernandesd76a2002018-10-16 13:19:58 -0700419 cs_temp.type = ptype;
420 cs_temp.name = name;
421
422 ret = readSectionByIdx(elfFile, i, cs_temp.data);
423 if (ret) return ret;
424 ALOGD("Loaded code section %d (%s)\n", i, name.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800425
426 vector<string> csSymNames;
427 ret = getSectionSymNames(elfFile, oldName, csSymNames);
428 if (ret || !csSymNames.size()) return ret;
429 for (size_t i = 0; i < progDefNames.size(); ++i) {
430 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
431 cs_temp.prog_def = pd[i];
432 break;
433 }
434 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700435 }
436
437 /* Check for rel section */
438 if (cs_temp.data.size() > 0 && i < entries) {
439 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
440 if (ret) return ret;
441
442 if (isRelSection(cs_temp, name)) {
443 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
444 if (ret) return ret;
445 ALOGD("Loaded relo section %d (%s)\n", i, name.c_str());
446 }
447 }
448
449 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700450 cs.push_back(std::move(cs_temp));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700451 ALOGD("Adding section %d to cs list\n", i);
452 }
453 }
454 return 0;
455}
456
457static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
458 vector<Elf64_Sym> symtab;
459 int ret = 0;
460
461 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
462 if (ret) return ret;
463
464 if (index >= (int)symtab.size()) return -1;
465
466 return getSymName(elfFile, symtab[index].st_name, name);
467}
468
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800469static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800470 const char* prefix, size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700471 int ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700472 vector<char> mdData;
473 vector<struct bpf_map_def> md;
474 vector<string> mapNames;
475 string fname = pathToFilename(string(elfPath), true);
476
477 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800478 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700479 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800480
481 if (mdData.size() % sizeOfBpfMapDef) {
482 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0\n",
483 mdData.size(), sizeOfBpfMapDef);
484 return -1;
485 };
486
487 int mapCount = mdData.size() / sizeOfBpfMapDef;
488 md.resize(mapCount);
489 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
490
491 const char* dataPtr = mdData.data();
492 for (auto& m : md) {
493 // First we zero initialize
494 memset(&m, 0, sizeof(m));
495 // Then we set non-zero defaults
496 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
497 // Then we copy over the structure prefix from the ELF file.
498 memcpy(&m, dataPtr, trimmedSize);
499 // Move to next struct in the ELF file
500 dataPtr += sizeOfBpfMapDef;
501 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700502
Connor O'Brien3278a162020-02-13 21:45:22 -0800503 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700504 if (ret) return ret;
505
Joel Fernandesd76a2002018-10-16 13:19:58 -0700506 for (int i = 0; i < (int)mapNames.size(); i++) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700507 unique_fd fd;
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800508 int saved_errno;
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800509 // Format of pin location is /sys/fs/bpf/<prefix>map_<filename>_<mapname>
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800510 string mapPinLoc =
511 string(BPF_FS_PATH) + prefix + "map_" + fname + "_" + string(mapNames[i]);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700512 bool reuse = false;
513
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800514 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
515 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x\n", mapNames[i].c_str(),
516 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700517 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800518 continue;
519 }
520
521 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
522 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x\n", mapNames[i].c_str(),
523 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700524 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800525 continue;
526 }
527
Joel Fernandesd76a2002018-10-16 13:19:58 -0700528 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700529 fd.reset(bpf_obj_get(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800530 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700531 ALOGD("bpf_create_map reusing map %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700532 reuse = true;
533 } else {
Maciej Żenczykowskicb358de2021-03-04 07:27:38 -0800534 enum bpf_map_type type = md[i].type;
535 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
536 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
537 // of be approximated: ARRAY has the same userspace api, though it is not usable
538 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
539 // helper doesn't exist on 4.9 anyway (so the bpf program would fail to load,
540 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
541 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
542 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
543 type = BPF_MAP_TYPE_ARRAY;
544 }
545 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
546 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
547 // of be approximated: HASH has the same userspace visible api.
548 // However it cannot be used by ebpf programs in the same way.
549 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
550 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
551 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
552 // programs as being 5.4+...
553 type = BPF_MAP_TYPE_HASH;
554 }
555 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 -0700556 md[i].max_entries, md[i].map_flags));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800557 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700558 ALOGD("bpf_create_map name %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700559 }
560
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800561 if (fd < 0) return -saved_errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700562
563 if (!reuse) {
564 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800565 if (ret) return -errno;
566 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
567 if (ret) return -errno;
568 ret = chmod(mapPinLoc.c_str(), md[i].mode);
569 if (ret) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700570 }
571
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700572 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700573 }
574
575 return ret;
576}
577
578/* For debugging, dump all instructions */
579static void dumpIns(char* ins, int size) {
580 for (int row = 0; row < size / 8; row++) {
581 ALOGE("%d: ", row);
582 for (int j = 0; j < 8; j++) {
583 ALOGE("%3x ", ins[(row * 8) + j]);
584 }
585 ALOGE("\n");
586 }
587}
588
589/* For debugging, dump all code sections from cs list */
590static void dumpAllCs(vector<codeSection>& cs) {
591 for (int i = 0; i < (int)cs.size(); i++) {
592 ALOGE("Dumping cs %d, name %s\n", int(i), cs[i].name.c_str());
593 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
594 ALOGE("-----------\n");
595 }
596}
597
598static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
599 int insnIndex;
600 struct bpf_insn *insn, *insns;
601
602 insns = (struct bpf_insn*)(insnsPtr);
603
604 insnIndex = offset / sizeof(struct bpf_insn);
605 insn = &insns[insnIndex];
606
607 ALOGD(
608 "applying relo to instruction at byte offset: %d, \
609 insn offset %d , insn %lx\n",
610 (int)offset, (int)insnIndex, *(unsigned long*)insn);
611
612 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
613 ALOGE("Dumping all instructions till ins %d\n", insnIndex);
614 ALOGE("invalid relo for insn %d: code 0x%x\n", insnIndex, insn->code);
615 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
616 return;
617 }
618
619 insn->imm = fd;
620 insn->src_reg = BPF_PSEUDO_MAP_FD;
621}
622
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700623static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700624 vector<string> mapNames;
625
Connor O'Brien3278a162020-02-13 21:45:22 -0800626 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700627 if (ret) return;
628
629 for (int k = 0; k != (int)cs.size(); k++) {
630 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
631 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
632
633 for (int i = 0; i < n_rel; i++) {
634 int symIndex = ELF64_R_SYM(rel[i].r_info);
635 string symName;
636
637 ret = getSymNameByIdx(elfFile, symIndex, symName);
638 if (ret) return;
639
640 /* Find the map fd and apply relo */
641 for (int j = 0; j < (int)mapNames.size(); j++) {
642 if (!mapNames[j].compare(symName)) {
643 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
644 break;
645 }
646 }
647 }
648 }
649}
650
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800651static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
652 const char* prefix) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800653 unsigned kvers = kernelVersion();
654 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700655
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800656 if (!kvers) return -1;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700657
658 string fname = pathToFilename(string(elfPath), true);
659
660 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700661 string name = cs[i].name;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800662 unsigned bpfMinVer = DEFAULT_BPFLOADER_MIN_VER; // v0.0
663 unsigned bpfMaxVer = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Joel Fernandesd76a2002018-10-16 13:19:58 -0700664
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800665 if (cs[i].prog_def.has_value()) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700666 unsigned min_kver = cs[i].prog_def->min_kver;
667 unsigned max_kver = cs[i].prog_def->max_kver;
668 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)\n", i, name.c_str(), min_kver,
669 max_kver, kvers);
670 if (kvers < min_kver) continue;
671 if (kvers >= max_kver) continue;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800672
673 bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
674 bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800675 }
676
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800677 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)\n", i, name.c_str(),
678 bpfMinVer, bpfMaxVer);
679 if (BPFLOADER_VERSION < bpfMinVer) continue;
680 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
681
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700682 // strip any potential $foo suffix
683 // this can be used to provide duplicate programs
684 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700685 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700686
687 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700688 // Format of pin location is
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800689 // /sys/fs/bpf/<prefix>prog_<filename>_<mapname>
690 string progPinLoc = BPF_FS_PATH;
691 progPinLoc += prefix;
692 progPinLoc += "prog_";
Maciej Żenczykowski6c7871b2020-04-23 12:46:00 -0700693 progPinLoc += fname;
694 progPinLoc += '_';
695 progPinLoc += name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700696 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700697 fd = retrieveProgram(progPinLoc.c_str());
698 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)\n", progPinLoc.c_str(), fd,
699 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700700 reuse = true;
701 } else {
702 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
703
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700704 fd = bpf_prog_load(cs[i].type, name.c_str(), (struct bpf_insn*)cs[i].data.data(),
705 cs[i].data.size(), license.c_str(), kvers, 0, log_buf.data(),
706 log_buf.size());
Steven Moreland804bca02019-12-12 17:21:23 -0800707 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)\n", elfPath,
708 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700709
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800710 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800711 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800712
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700713 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
714 for (const auto& line : lines) ALOGW("%s", line.c_str());
715 ALOGW("bpf_prog_load - END log_buf contents.");
716
717 if (cs[i].prog_def->optional) {
718 ALOGW("failed program is marked optional - continuing...");
719 continue;
720 }
721 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800722 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700723 }
724
725 if (fd < 0) return fd;
726 if (fd == 0) return -EINVAL;
727
728 if (!reuse) {
729 ret = bpf_obj_pin(fd, progPinLoc.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800730 if (ret) return -errno;
731 if (cs[i].prog_def.has_value()) {
732 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
733 (gid_t)cs[i].prog_def->gid)) {
734 return -errno;
735 }
736 }
737 if (chmod(progPinLoc.c_str(), 0440)) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700738 }
739
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700740 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700741 }
742
743 return 0;
744}
745
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800746int loadProg(const char* elfPath, bool* isCritical, const char* prefix) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700747 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700748 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700749 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700750 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700751 int ret;
752
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700753 if (!isCritical) return -1;
754 *isCritical = false;
755
Joel Fernandesd76a2002018-10-16 13:19:58 -0700756 ifstream elfFile(elfPath, ios::in | ios::binary);
757 if (!elfFile.is_open()) return -1;
758
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700759 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700760 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700761
Joel Fernandesd76a2002018-10-16 13:19:58 -0700762 ret = readSectionByName("license", elfFile, license);
763 if (ret) {
764 ALOGE("Couldn't find license in %s\n", elfPath);
765 return ret;
766 } else {
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700767 ALOGD("Loading %s%s ELF object %s with license %s\n",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700768 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700769 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700770 }
771
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800772 // the following default values are for bpfloader V0.0 format which does not include them
773 unsigned int bpfLoaderMinVer =
774 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
775 unsigned int bpfLoaderMaxVer =
776 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
777 size_t sizeOfBpfMapDef =
778 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
779 size_t sizeOfBpfProgDef =
780 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
781
782 // inclusive lower bound check
783 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
784 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x\n",
785 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
786 return 0;
787 }
788
789 // exclusive upper bound check
790 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
791 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x\n",
792 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
793 return 0;
794 }
795
796 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)\n",
797 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
798
799 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
800 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)\n", sizeOfBpfMapDef,
801 DEFAULT_SIZEOF_BPF_MAP_DEF);
802 return -1;
803 }
804
805 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
806 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)\n", sizeOfBpfProgDef,
807 DEFAULT_SIZEOF_BPF_PROG_DEF);
808 return -1;
809 }
810
811 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700812 if (ret) {
813 ALOGE("Couldn't read all code sections in %s\n", elfPath);
814 return ret;
815 }
816
817 /* Just for future debugging */
818 if (0) dumpAllCs(cs);
819
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800820 ret = createMaps(elfPath, elfFile, mapFds, prefix, sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700821 if (ret) {
822 ALOGE("Failed to create maps: (ret=%d) in %s\n", ret, elfPath);
823 return ret;
824 }
825
826 for (int i = 0; i < (int)mapFds.size(); i++)
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700827 ALOGD("map_fd found at %d is %d in %s\n", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700828
829 applyMapRelo(elfFile, mapFds, cs);
830
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800831 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700832 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d\n", ret);
833
834 return ret;
835}
836
Joel Fernandesd76a2002018-10-16 13:19:58 -0700837} // namespace bpf
838} // namespace android