blob: b7f38ce442d38aecf07425665259584cc335f3e2 [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
Tyler Wear25c02852021-10-26 15:38:48 -070031// This is BpfLoader v0.5
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080032#define BPFLOADER_VERSION_MAJOR 0u
Tyler Wear25c02852021-10-26 15:38:48 -070033#define BPFLOADER_VERSION_MINOR 5u
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},
Tyler Wear25c02852021-10-26 15:38:48 -070098 {"cgroupsockaddr", BPF_PROG_TYPE_CGROUP_SOCK_ADDR},
Joel Fernandesd76a2002018-10-16 13:19:58 -070099
Maciej Żenczykowskiaa462222021-01-07 14:24:45 -0800100 /* End of table */
101 {"END", BPF_PROG_TYPE_UNSPEC},
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) {
283 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++)
284 if (StartsWith(name, sectionNameTypes[i].name)) return sectionNameTypes[i].type;
285
286 return BPF_PROG_TYPE_UNSPEC;
287}
288
289/* If ever needed
290static string getSectionName(enum bpf_prog_type type)
291{
292 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++)
293 if (sectionNameTypes[i].type == type)
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800294 return string(sectionNameTypes[i].name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700295
296 return NULL;
297}
298*/
299
300static bool isRelSection(codeSection& cs, string& name) {
301 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++) {
302 sectionType st = sectionNameTypes[i];
303
304 if (st.type != cs.type) continue;
305
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800306 if (StartsWith(name, string(".rel") + st.name + "/"))
Joel Fernandesd76a2002018-10-16 13:19:58 -0700307 return true;
308 else
309 return false;
310 }
311 return false;
312}
313
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800314static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
315 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800316 vector<char> pdData;
317 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800318 // Older file formats do not require a 'progs' section at all.
319 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800320 if (ret == -2) return 0;
321 if (ret) return ret;
322
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800323 if (pdData.size() % sizeOfBpfProgDef) {
324 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0\n",
325 pdData.size(), sizeOfBpfProgDef);
326 return -1;
327 };
328
329 int progCount = pdData.size() / sizeOfBpfProgDef;
330 pd.resize(progCount);
331 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
332
333 const char* dataPtr = pdData.data();
334 for (auto& p : pd) {
335 // First we zero initialize
336 memset(&p, 0, sizeof(p));
337 // Then we set non-zero defaults
338 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
339 // Then we copy over the structure prefix from the ELF file.
340 memcpy(&p, dataPtr, trimmedSize);
341 // Move to next struct in the ELF file
342 dataPtr += sizeOfBpfProgDef;
343 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800344 return 0;
345}
346
347static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names) {
348 int ret;
349 string name;
350 vector<Elf64_Sym> symtab;
351 vector<Elf64_Shdr> shTable;
352
353 ret = readSymTab(elfFile, 1 /* sort */, symtab);
354 if (ret) return ret;
355
356 /* Get index of section */
357 ret = readSectionHeadersAll(elfFile, shTable);
358 if (ret) return ret;
359
360 int sec_idx = -1;
361 for (int i = 0; i < (int)shTable.size(); i++) {
362 ret = getSymName(elfFile, shTable[i].sh_name, name);
363 if (ret) return ret;
364
365 if (!name.compare(sectionName)) {
366 sec_idx = i;
367 break;
368 }
369 }
370
371 /* No section found with matching name*/
372 if (sec_idx == -1) {
Maciej Żenczykowski21f34cb2020-07-20 18:44:33 -0700373 ALOGW("No %s section could be found in elf object\n", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800374 return -1;
375 }
376
377 for (int i = 0; i < (int)symtab.size(); i++) {
378 if (symtab[i].st_shndx == sec_idx) {
379 string s;
380 ret = getSymName(elfFile, symtab[i].st_name, s);
381 if (ret) return ret;
382 names.push_back(s);
383 }
384 }
385
386 return 0;
387}
388
Joel Fernandesd76a2002018-10-16 13:19:58 -0700389/* Read a section by its index - for ex to get sec hdr strtab blob */
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800390static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700391 vector<Elf64_Shdr> shTable;
392 int entries, ret = 0;
393
394 ret = readSectionHeadersAll(elfFile, shTable);
395 if (ret) return ret;
396 entries = shTable.size();
397
Connor O'Brien3278a162020-02-13 21:45:22 -0800398 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800399 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800400 if (ret) return ret;
401 vector<string> progDefNames;
402 ret = getSectionSymNames(elfFile, "progs", progDefNames);
403 if (!pd.empty() && ret) return ret;
404
Joel Fernandesd76a2002018-10-16 13:19:58 -0700405 for (int i = 0; i < entries; i++) {
406 string name;
407 codeSection cs_temp;
408 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
409
410 ret = getSymName(elfFile, shTable[i].sh_name, name);
411 if (ret) return ret;
412
413 enum bpf_prog_type ptype = getSectionType(name);
414 if (ptype != BPF_PROG_TYPE_UNSPEC) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800415 string oldName = name;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800416
417 // convert all slashes to underscores
418 std::replace(name.begin(), name.end(), '/', '_');
419
Joel Fernandesd76a2002018-10-16 13:19:58 -0700420 cs_temp.type = ptype;
421 cs_temp.name = name;
422
423 ret = readSectionByIdx(elfFile, i, cs_temp.data);
424 if (ret) return ret;
425 ALOGD("Loaded code section %d (%s)\n", i, name.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800426
427 vector<string> csSymNames;
428 ret = getSectionSymNames(elfFile, oldName, csSymNames);
429 if (ret || !csSymNames.size()) return ret;
430 for (size_t i = 0; i < progDefNames.size(); ++i) {
431 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
432 cs_temp.prog_def = pd[i];
433 break;
434 }
435 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700436 }
437
438 /* Check for rel section */
439 if (cs_temp.data.size() > 0 && i < entries) {
440 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
441 if (ret) return ret;
442
443 if (isRelSection(cs_temp, name)) {
444 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
445 if (ret) return ret;
446 ALOGD("Loaded relo section %d (%s)\n", i, name.c_str());
447 }
448 }
449
450 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700451 cs.push_back(std::move(cs_temp));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700452 ALOGD("Adding section %d to cs list\n", i);
453 }
454 }
455 return 0;
456}
457
458static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
459 vector<Elf64_Sym> symtab;
460 int ret = 0;
461
462 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
463 if (ret) return ret;
464
465 if (index >= (int)symtab.size()) return -1;
466
467 return getSymName(elfFile, symtab[index].st_name, name);
468}
469
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800470static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800471 const char* prefix, size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700472 int ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700473 vector<char> mdData;
474 vector<struct bpf_map_def> md;
475 vector<string> mapNames;
476 string fname = pathToFilename(string(elfPath), true);
477
478 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800479 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700480 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800481
482 if (mdData.size() % sizeOfBpfMapDef) {
483 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0\n",
484 mdData.size(), sizeOfBpfMapDef);
485 return -1;
486 };
487
488 int mapCount = mdData.size() / sizeOfBpfMapDef;
489 md.resize(mapCount);
490 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
491
492 const char* dataPtr = mdData.data();
493 for (auto& m : md) {
494 // First we zero initialize
495 memset(&m, 0, sizeof(m));
496 // Then we set non-zero defaults
497 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700498 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800499 // Then we copy over the structure prefix from the ELF file.
500 memcpy(&m, dataPtr, trimmedSize);
501 // Move to next struct in the ELF file
502 dataPtr += sizeOfBpfMapDef;
503 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700504
Connor O'Brien3278a162020-02-13 21:45:22 -0800505 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700506 if (ret) return ret;
507
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700508 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700509
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700510 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800511 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
512 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x\n", mapNames[i].c_str(),
513 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700514 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800515 continue;
516 }
517
518 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
519 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x\n", mapNames[i].c_str(),
520 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700521 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800522 continue;
523 }
524
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700525 if (kvers < md[i].min_kver) {
526 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x\n",
527 mapNames[i].c_str(), kvers, md[i].min_kver);
528 mapFds.push_back(unique_fd());
529 continue;
530 }
531
532 if (kvers >= md[i].max_kver) {
533 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x\n",
534 mapNames[i].c_str(), kvers, md[i].max_kver);
535 mapFds.push_back(unique_fd());
536 continue;
537 }
538
539 // Format of pin location is /sys/fs/bpf/<prefix>map_<filename>_<mapname>
540 string mapPinLoc =
541 string(BPF_FS_PATH) + prefix + "map_" + fname + "_" + string(mapNames[i]);
542 bool reuse = false;
543 unique_fd fd;
544 int saved_errno;
545
Joel Fernandesd76a2002018-10-16 13:19:58 -0700546 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700547 fd.reset(bpf_obj_get(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800548 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700549 ALOGD("bpf_create_map reusing map %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700550 reuse = true;
551 } else {
Maciej Żenczykowskicb358de2021-03-04 07:27:38 -0800552 enum bpf_map_type type = md[i].type;
553 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
554 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
555 // of be approximated: ARRAY has the same userspace api, though it is not usable
556 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
557 // helper doesn't exist on 4.9 anyway (so the bpf program would fail to load,
558 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
559 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
560 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
561 type = BPF_MAP_TYPE_ARRAY;
562 }
563 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
564 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
565 // of be approximated: HASH has the same userspace visible api.
566 // However it cannot be used by ebpf programs in the same way.
567 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
568 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
569 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
570 // programs as being 5.4+...
571 type = BPF_MAP_TYPE_HASH;
572 }
573 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 -0700574 md[i].max_entries, md[i].map_flags));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800575 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700576 ALOGD("bpf_create_map name %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700577 }
578
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800579 if (fd < 0) return -saved_errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700580
581 if (!reuse) {
582 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800583 if (ret) return -errno;
584 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
585 if (ret) return -errno;
586 ret = chmod(mapPinLoc.c_str(), md[i].mode);
587 if (ret) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700588 }
589
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700590 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700591 }
592
593 return ret;
594}
595
596/* For debugging, dump all instructions */
597static void dumpIns(char* ins, int size) {
598 for (int row = 0; row < size / 8; row++) {
599 ALOGE("%d: ", row);
600 for (int j = 0; j < 8; j++) {
601 ALOGE("%3x ", ins[(row * 8) + j]);
602 }
603 ALOGE("\n");
604 }
605}
606
607/* For debugging, dump all code sections from cs list */
608static void dumpAllCs(vector<codeSection>& cs) {
609 for (int i = 0; i < (int)cs.size(); i++) {
610 ALOGE("Dumping cs %d, name %s\n", int(i), cs[i].name.c_str());
611 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
612 ALOGE("-----------\n");
613 }
614}
615
616static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
617 int insnIndex;
618 struct bpf_insn *insn, *insns;
619
620 insns = (struct bpf_insn*)(insnsPtr);
621
622 insnIndex = offset / sizeof(struct bpf_insn);
623 insn = &insns[insnIndex];
624
625 ALOGD(
626 "applying relo to instruction at byte offset: %d, \
627 insn offset %d , insn %lx\n",
628 (int)offset, (int)insnIndex, *(unsigned long*)insn);
629
630 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
631 ALOGE("Dumping all instructions till ins %d\n", insnIndex);
632 ALOGE("invalid relo for insn %d: code 0x%x\n", insnIndex, insn->code);
633 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
634 return;
635 }
636
637 insn->imm = fd;
638 insn->src_reg = BPF_PSEUDO_MAP_FD;
639}
640
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700641static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700642 vector<string> mapNames;
643
Connor O'Brien3278a162020-02-13 21:45:22 -0800644 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700645 if (ret) return;
646
647 for (int k = 0; k != (int)cs.size(); k++) {
648 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
649 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
650
651 for (int i = 0; i < n_rel; i++) {
652 int symIndex = ELF64_R_SYM(rel[i].r_info);
653 string symName;
654
655 ret = getSymNameByIdx(elfFile, symIndex, symName);
656 if (ret) return;
657
658 /* Find the map fd and apply relo */
659 for (int j = 0; j < (int)mapNames.size(); j++) {
660 if (!mapNames[j].compare(symName)) {
661 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
662 break;
663 }
664 }
665 }
666 }
667}
668
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800669static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
670 const char* prefix) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800671 unsigned kvers = kernelVersion();
672 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700673
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800674 if (!kvers) return -1;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700675
676 string fname = pathToFilename(string(elfPath), true);
677
678 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700679 string name = cs[i].name;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800680 unsigned bpfMinVer = DEFAULT_BPFLOADER_MIN_VER; // v0.0
681 unsigned bpfMaxVer = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Joel Fernandesd76a2002018-10-16 13:19:58 -0700682
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800683 if (cs[i].prog_def.has_value()) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700684 unsigned min_kver = cs[i].prog_def->min_kver;
685 unsigned max_kver = cs[i].prog_def->max_kver;
686 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)\n", i, name.c_str(), min_kver,
687 max_kver, kvers);
688 if (kvers < min_kver) continue;
689 if (kvers >= max_kver) continue;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800690
691 bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
692 bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800693 }
694
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800695 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)\n", i, name.c_str(),
696 bpfMinVer, bpfMaxVer);
697 if (BPFLOADER_VERSION < bpfMinVer) continue;
698 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
699
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700700 // strip any potential $foo suffix
701 // this can be used to provide duplicate programs
702 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700703 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700704
705 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700706 // Format of pin location is
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800707 // /sys/fs/bpf/<prefix>prog_<filename>_<mapname>
708 string progPinLoc = BPF_FS_PATH;
709 progPinLoc += prefix;
710 progPinLoc += "prog_";
Maciej Żenczykowski6c7871b2020-04-23 12:46:00 -0700711 progPinLoc += fname;
712 progPinLoc += '_';
713 progPinLoc += name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700714 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700715 fd = retrieveProgram(progPinLoc.c_str());
716 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)\n", progPinLoc.c_str(), fd,
717 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700718 reuse = true;
719 } else {
720 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
721
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700722 fd = bpf_prog_load(cs[i].type, name.c_str(), (struct bpf_insn*)cs[i].data.data(),
723 cs[i].data.size(), license.c_str(), kvers, 0, log_buf.data(),
724 log_buf.size());
Steven Moreland804bca02019-12-12 17:21:23 -0800725 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)\n", elfPath,
726 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700727
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800728 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800729 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800730
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700731 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
732 for (const auto& line : lines) ALOGW("%s", line.c_str());
733 ALOGW("bpf_prog_load - END log_buf contents.");
734
735 if (cs[i].prog_def->optional) {
736 ALOGW("failed program is marked optional - continuing...");
737 continue;
738 }
739 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800740 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700741 }
742
743 if (fd < 0) return fd;
744 if (fd == 0) return -EINVAL;
745
746 if (!reuse) {
747 ret = bpf_obj_pin(fd, progPinLoc.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800748 if (ret) return -errno;
749 if (cs[i].prog_def.has_value()) {
750 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
751 (gid_t)cs[i].prog_def->gid)) {
752 return -errno;
753 }
754 }
755 if (chmod(progPinLoc.c_str(), 0440)) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700756 }
757
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700758 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700759 }
760
761 return 0;
762}
763
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800764int loadProg(const char* elfPath, bool* isCritical, const char* prefix) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700765 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700766 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700767 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700768 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700769 int ret;
770
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700771 if (!isCritical) return -1;
772 *isCritical = false;
773
Joel Fernandesd76a2002018-10-16 13:19:58 -0700774 ifstream elfFile(elfPath, ios::in | ios::binary);
775 if (!elfFile.is_open()) return -1;
776
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700777 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700778 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700779
Joel Fernandesd76a2002018-10-16 13:19:58 -0700780 ret = readSectionByName("license", elfFile, license);
781 if (ret) {
782 ALOGE("Couldn't find license in %s\n", elfPath);
783 return ret;
784 } else {
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700785 ALOGD("Loading %s%s ELF object %s with license %s\n",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700786 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700787 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700788 }
789
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800790 // the following default values are for bpfloader V0.0 format which does not include them
791 unsigned int bpfLoaderMinVer =
792 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
793 unsigned int bpfLoaderMaxVer =
794 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
795 size_t sizeOfBpfMapDef =
796 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
797 size_t sizeOfBpfProgDef =
798 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
799
800 // inclusive lower bound check
801 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
802 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x\n",
803 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
804 return 0;
805 }
806
807 // exclusive upper bound check
808 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
809 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x\n",
810 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
811 return 0;
812 }
813
814 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)\n",
815 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
816
817 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
818 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)\n", sizeOfBpfMapDef,
819 DEFAULT_SIZEOF_BPF_MAP_DEF);
820 return -1;
821 }
822
823 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
824 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)\n", sizeOfBpfProgDef,
825 DEFAULT_SIZEOF_BPF_PROG_DEF);
826 return -1;
827 }
828
829 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700830 if (ret) {
831 ALOGE("Couldn't read all code sections in %s\n", elfPath);
832 return ret;
833 }
834
835 /* Just for future debugging */
836 if (0) dumpAllCs(cs);
837
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800838 ret = createMaps(elfPath, elfFile, mapFds, prefix, sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700839 if (ret) {
840 ALOGE("Failed to create maps: (ret=%d) in %s\n", ret, elfPath);
841 return ret;
842 }
843
844 for (int i = 0; i < (int)mapFds.size(); i++)
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700845 ALOGD("map_fd found at %d is %d in %s\n", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700846
847 applyMapRelo(elfFile, mapFds, cs);
848
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800849 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700850 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d\n", ret);
851
852 return ret;
853}
854
Joel Fernandesd76a2002018-10-16 13:19:58 -0700855} // namespace bpf
856} // namespace android