blob: d2380a24c01f0228e3ad7b8e23f57f2e0935ded1 [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
Stephane Leeeb61b732021-10-21 17:03:11 -070031// This is BpfLoader v0.4
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080032#define BPFLOADER_VERSION_MAJOR 0u
Stephane Leeeb61b732021-10-21 17:03:11 -070033#define BPFLOADER_VERSION_MINOR 4u
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080034#define BPFLOADER_VERSION ((BPFLOADER_VERSION_MAJOR << 16) | BPFLOADER_VERSION_MINOR)
35
Maciej Żenczykowski730a3862020-01-27 01:10:48 -080036#include "../progs/include/bpf_map_def.h"
Maciej Żenczykowski07375e22020-02-19 14:23:59 -080037#include "bpf/BpfUtils.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:
84 * SEC(<prefix>/<name-of-program>)
85 * For example:
86 * SEC("tracepoint/sched_switch_func") where sched_switch_funcs
87 * is the name of the program, and tracepoint is the type.
88 */
89sectionType sectionNameTypes[] = {
Maciej Żenczykowskiaa462222021-01-07 14:24:45 -080090 {"kprobe", BPF_PROG_TYPE_KPROBE},
91 {"tracepoint", BPF_PROG_TYPE_TRACEPOINT},
92 {"skfilter", BPF_PROG_TYPE_SOCKET_FILTER},
93 {"cgroupskb", BPF_PROG_TYPE_CGROUP_SKB},
94 {"schedcls", BPF_PROG_TYPE_SCHED_CLS},
Patrick Rohrb28bf2a2021-10-13 08:26:50 +020095 {"schedact", BPF_PROG_TYPE_SCHED_ACT},
Maciej Żenczykowskiaa462222021-01-07 14:24:45 -080096 {"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 Żenczykowski7ed94ef2021-07-06 01:47:15 -0700214unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800215 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
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700497 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800498 // Then we copy over the structure prefix from the ELF file.
499 memcpy(&m, dataPtr, trimmedSize);
500 // Move to next struct in the ELF file
501 dataPtr += sizeOfBpfMapDef;
502 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700503
Connor O'Brien3278a162020-02-13 21:45:22 -0800504 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700505 if (ret) return ret;
506
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700507 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700508
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700509 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800510 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
511 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x\n", mapNames[i].c_str(),
512 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700513 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800514 continue;
515 }
516
517 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
518 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x\n", mapNames[i].c_str(),
519 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700520 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800521 continue;
522 }
523
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700524 if (kvers < md[i].min_kver) {
525 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x\n",
526 mapNames[i].c_str(), kvers, md[i].min_kver);
527 mapFds.push_back(unique_fd());
528 continue;
529 }
530
531 if (kvers >= md[i].max_kver) {
532 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x\n",
533 mapNames[i].c_str(), kvers, md[i].max_kver);
534 mapFds.push_back(unique_fd());
535 continue;
536 }
537
538 // Format of pin location is /sys/fs/bpf/<prefix>map_<filename>_<mapname>
539 string mapPinLoc =
540 string(BPF_FS_PATH) + prefix + "map_" + fname + "_" + string(mapNames[i]);
541 bool reuse = false;
542 unique_fd fd;
543 int saved_errno;
544
Joel Fernandesd76a2002018-10-16 13:19:58 -0700545 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700546 fd.reset(bpf_obj_get(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800547 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700548 ALOGD("bpf_create_map reusing map %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700549 reuse = true;
550 } else {
Maciej Żenczykowskicb358de2021-03-04 07:27:38 -0800551 enum bpf_map_type type = md[i].type;
552 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
553 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
554 // of be approximated: ARRAY has the same userspace api, though it is not usable
555 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
556 // helper doesn't exist on 4.9 anyway (so the bpf program would fail to load,
557 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
558 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
559 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
560 type = BPF_MAP_TYPE_ARRAY;
561 }
562 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
563 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
564 // of be approximated: HASH has the same userspace visible api.
565 // However it cannot be used by ebpf programs in the same way.
566 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
567 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
568 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
569 // programs as being 5.4+...
570 type = BPF_MAP_TYPE_HASH;
571 }
572 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 -0700573 md[i].max_entries, md[i].map_flags));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800574 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700575 ALOGD("bpf_create_map name %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700576 }
577
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800578 if (fd < 0) return -saved_errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700579
580 if (!reuse) {
581 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800582 if (ret) return -errno;
583 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
584 if (ret) return -errno;
585 ret = chmod(mapPinLoc.c_str(), md[i].mode);
586 if (ret) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700587 }
588
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700589 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700590 }
591
592 return ret;
593}
594
595/* For debugging, dump all instructions */
596static void dumpIns(char* ins, int size) {
597 for (int row = 0; row < size / 8; row++) {
598 ALOGE("%d: ", row);
599 for (int j = 0; j < 8; j++) {
600 ALOGE("%3x ", ins[(row * 8) + j]);
601 }
602 ALOGE("\n");
603 }
604}
605
606/* For debugging, dump all code sections from cs list */
607static void dumpAllCs(vector<codeSection>& cs) {
608 for (int i = 0; i < (int)cs.size(); i++) {
609 ALOGE("Dumping cs %d, name %s\n", int(i), cs[i].name.c_str());
610 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
611 ALOGE("-----------\n");
612 }
613}
614
615static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
616 int insnIndex;
617 struct bpf_insn *insn, *insns;
618
619 insns = (struct bpf_insn*)(insnsPtr);
620
621 insnIndex = offset / sizeof(struct bpf_insn);
622 insn = &insns[insnIndex];
623
624 ALOGD(
625 "applying relo to instruction at byte offset: %d, \
626 insn offset %d , insn %lx\n",
627 (int)offset, (int)insnIndex, *(unsigned long*)insn);
628
629 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
630 ALOGE("Dumping all instructions till ins %d\n", insnIndex);
631 ALOGE("invalid relo for insn %d: code 0x%x\n", insnIndex, insn->code);
632 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
633 return;
634 }
635
636 insn->imm = fd;
637 insn->src_reg = BPF_PSEUDO_MAP_FD;
638}
639
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700640static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700641 vector<string> mapNames;
642
Connor O'Brien3278a162020-02-13 21:45:22 -0800643 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700644 if (ret) return;
645
646 for (int k = 0; k != (int)cs.size(); k++) {
647 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
648 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
649
650 for (int i = 0; i < n_rel; i++) {
651 int symIndex = ELF64_R_SYM(rel[i].r_info);
652 string symName;
653
654 ret = getSymNameByIdx(elfFile, symIndex, symName);
655 if (ret) return;
656
657 /* Find the map fd and apply relo */
658 for (int j = 0; j < (int)mapNames.size(); j++) {
659 if (!mapNames[j].compare(symName)) {
660 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
661 break;
662 }
663 }
664 }
665 }
666}
667
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800668static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
669 const char* prefix) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800670 unsigned kvers = kernelVersion();
671 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700672
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800673 if (!kvers) return -1;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700674
675 string fname = pathToFilename(string(elfPath), true);
676
677 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700678 string name = cs[i].name;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800679 unsigned bpfMinVer = DEFAULT_BPFLOADER_MIN_VER; // v0.0
680 unsigned bpfMaxVer = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Joel Fernandesd76a2002018-10-16 13:19:58 -0700681
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800682 if (cs[i].prog_def.has_value()) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700683 unsigned min_kver = cs[i].prog_def->min_kver;
684 unsigned max_kver = cs[i].prog_def->max_kver;
685 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)\n", i, name.c_str(), min_kver,
686 max_kver, kvers);
687 if (kvers < min_kver) continue;
688 if (kvers >= max_kver) continue;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800689
690 bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
691 bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800692 }
693
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800694 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)\n", i, name.c_str(),
695 bpfMinVer, bpfMaxVer);
696 if (BPFLOADER_VERSION < bpfMinVer) continue;
697 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
698
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700699 // strip any potential $foo suffix
700 // this can be used to provide duplicate programs
701 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700702 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700703
704 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700705 // Format of pin location is
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800706 // /sys/fs/bpf/<prefix>prog_<filename>_<mapname>
707 string progPinLoc = BPF_FS_PATH;
708 progPinLoc += prefix;
709 progPinLoc += "prog_";
Maciej Żenczykowski6c7871b2020-04-23 12:46:00 -0700710 progPinLoc += fname;
711 progPinLoc += '_';
712 progPinLoc += name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700713 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700714 fd = retrieveProgram(progPinLoc.c_str());
715 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)\n", progPinLoc.c_str(), fd,
716 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700717 reuse = true;
718 } else {
719 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
720
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700721 fd = bpf_prog_load(cs[i].type, name.c_str(), (struct bpf_insn*)cs[i].data.data(),
722 cs[i].data.size(), license.c_str(), kvers, 0, log_buf.data(),
723 log_buf.size());
Steven Moreland804bca02019-12-12 17:21:23 -0800724 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)\n", elfPath,
725 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700726
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800727 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800728 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800729
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700730 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
731 for (const auto& line : lines) ALOGW("%s", line.c_str());
732 ALOGW("bpf_prog_load - END log_buf contents.");
733
734 if (cs[i].prog_def->optional) {
735 ALOGW("failed program is marked optional - continuing...");
736 continue;
737 }
738 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800739 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700740 }
741
742 if (fd < 0) return fd;
743 if (fd == 0) return -EINVAL;
744
745 if (!reuse) {
746 ret = bpf_obj_pin(fd, progPinLoc.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800747 if (ret) return -errno;
748 if (cs[i].prog_def.has_value()) {
749 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
750 (gid_t)cs[i].prog_def->gid)) {
751 return -errno;
752 }
753 }
754 if (chmod(progPinLoc.c_str(), 0440)) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700755 }
756
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700757 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700758 }
759
760 return 0;
761}
762
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800763int loadProg(const char* elfPath, bool* isCritical, const char* prefix) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700764 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700765 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700766 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700767 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700768 int ret;
769
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700770 if (!isCritical) return -1;
771 *isCritical = false;
772
Joel Fernandesd76a2002018-10-16 13:19:58 -0700773 ifstream elfFile(elfPath, ios::in | ios::binary);
774 if (!elfFile.is_open()) return -1;
775
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700776 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700777 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700778
Joel Fernandesd76a2002018-10-16 13:19:58 -0700779 ret = readSectionByName("license", elfFile, license);
780 if (ret) {
781 ALOGE("Couldn't find license in %s\n", elfPath);
782 return ret;
783 } else {
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700784 ALOGD("Loading %s%s ELF object %s with license %s\n",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700785 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700786 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700787 }
788
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800789 // the following default values are for bpfloader V0.0 format which does not include them
790 unsigned int bpfLoaderMinVer =
791 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
792 unsigned int bpfLoaderMaxVer =
793 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
794 size_t sizeOfBpfMapDef =
795 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
796 size_t sizeOfBpfProgDef =
797 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
798
799 // inclusive lower bound check
800 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
801 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x\n",
802 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
803 return 0;
804 }
805
806 // exclusive upper bound check
807 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
808 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x\n",
809 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
810 return 0;
811 }
812
813 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)\n",
814 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
815
816 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
817 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)\n", sizeOfBpfMapDef,
818 DEFAULT_SIZEOF_BPF_MAP_DEF);
819 return -1;
820 }
821
822 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
823 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)\n", sizeOfBpfProgDef,
824 DEFAULT_SIZEOF_BPF_PROG_DEF);
825 return -1;
826 }
827
828 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700829 if (ret) {
830 ALOGE("Couldn't read all code sections in %s\n", elfPath);
831 return ret;
832 }
833
834 /* Just for future debugging */
835 if (0) dumpAllCs(cs);
836
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800837 ret = createMaps(elfPath, elfFile, mapFds, prefix, sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700838 if (ret) {
839 ALOGE("Failed to create maps: (ret=%d) in %s\n", ret, elfPath);
840 return ret;
841 }
842
843 for (int i = 0; i < (int)mapFds.size(); i++)
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700844 ALOGD("map_fd found at %d is %d in %s\n", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700845
846 applyMapRelo(elfFile, mapFds, cs);
847
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800848 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700849 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d\n", ret);
850
851 return ret;
852}
853
Joel Fernandesd76a2002018-10-16 13:19:58 -0700854} // namespace bpf
855} // namespace android