blob: f4533cba41f6ccbbc2dfb25a4b971d477bd0dadb [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>
27#include <sys/utsname.h>
28#include <unistd.h>
29
30#include "LoaderUtils.h"
31#include "include/libbpf_android.h"
32
33#include <cstdlib>
34#include <fstream>
35#include <iostream>
36#include <string>
Christopher Ferrisc151c672019-02-01 15:31:26 -080037#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070038
Steven Moreland4891e612020-01-10 15:35:52 -080039#include <android-base/properties.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070040#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070041#include <android-base/unique_fd.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070042
43#define BPF_FS_PATH "/sys/fs/bpf/"
44
45// Size of the BPF log buffer for verifier logging
46#define BPF_LOAD_LOG_SZ 0x1ffff
47
48using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070049using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070050using std::ifstream;
51using std::ios;
Christopher Ferrisc151c672019-02-01 15:31:26 -080052using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070053using std::vector;
54
55namespace android {
56namespace bpf {
57
58typedef struct {
59 const char* name;
60 enum bpf_prog_type type;
61} sectionType;
62
63/*
64 * Map section name prefixes to program types, the section name will be:
65 * SEC(<prefix>/<name-of-program>)
66 * For example:
67 * SEC("tracepoint/sched_switch_func") where sched_switch_funcs
68 * is the name of the program, and tracepoint is the type.
69 */
70sectionType sectionNameTypes[] = {
Chenbo Feng5aee2f12018-12-26 16:14:05 -080071 {"kprobe", BPF_PROG_TYPE_KPROBE},
72 {"tracepoint", BPF_PROG_TYPE_TRACEPOINT},
73 {"skfilter", BPF_PROG_TYPE_SOCKET_FILTER},
74 {"cgroupskb", BPF_PROG_TYPE_CGROUP_SKB},
75 {"schedcls", BPF_PROG_TYPE_SCHED_CLS},
76 {"cgroupsock", BPF_PROG_TYPE_CGROUP_SOCK},
Joel Fernandesd76a2002018-10-16 13:19:58 -070077
78 /* End of table */
Chenbo Feng5aee2f12018-12-26 16:14:05 -080079 {"END", BPF_PROG_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -070080};
81
82typedef struct {
83 enum bpf_prog_type type;
84 string name;
85 vector<char> data;
86 vector<char> rel_data;
87
Connor O'Brien8d49fc72019-10-24 18:23:49 -070088 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -070089} codeSection;
90
91/* Common with the eBPF C program */
92struct bpf_map_def {
93 enum bpf_map_type type;
94 unsigned int key_size;
95 unsigned int value_size;
96 unsigned int max_entries;
97 unsigned int map_flags;
98 unsigned int inner_map_idx;
99 unsigned int numa_node;
100};
101
102static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
103 elfFile.seekg(0);
104 if (elfFile.fail()) return -1;
105
106 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
107
108 return 0;
109}
110
111/* Reads all section header tables into an Shdr array */
112static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
113 Elf64_Ehdr eh;
114 int ret = 0;
115
116 ret = readElfHeader(elfFile, &eh);
117 if (ret) return ret;
118
119 elfFile.seekg(eh.e_shoff);
120 if (elfFile.fail()) return -1;
121
122 /* Read shdr table entries */
123 shTable.resize(eh.e_shnum);
124
125 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
126
127 return 0;
128}
129
130/* Read a section by its index - for ex to get sec hdr strtab blob */
131static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
132 vector<Elf64_Shdr> shTable;
133 int entries, ret = 0;
134
135 ret = readSectionHeadersAll(elfFile, shTable);
136 if (ret) return ret;
137 entries = shTable.size();
138
139 elfFile.seekg(shTable[id].sh_offset);
140 if (elfFile.fail()) return -1;
141
142 sec.resize(shTable[id].sh_size);
143 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
144
145 return 0;
146}
147
148/* Read whole section header string table */
149static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
150 Elf64_Ehdr eh;
151 int ret = 0;
152
153 ret = readElfHeader(elfFile, &eh);
154 if (ret) return ret;
155
156 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
157 if (ret) return ret;
158
159 return 0;
160}
161
162/* Get name from offset in strtab */
163static int getSymName(ifstream& elfFile, int nameOff, string& name) {
164 int ret;
165 vector<char> secStrTab;
166
167 ret = readSectionHeaderStrtab(elfFile, secStrTab);
168 if (ret) return ret;
169
170 if (nameOff >= (int)secStrTab.size()) return -1;
171
172 name = string((char*)secStrTab.data() + nameOff);
173 return 0;
174}
175
176/* Reads a full section by name - example to get the GPL license */
177static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
178 vector<char> secStrTab;
179 vector<Elf64_Shdr> shTable;
180 int ret;
181
182 ret = readSectionHeadersAll(elfFile, shTable);
183 if (ret) return ret;
184
185 ret = readSectionHeaderStrtab(elfFile, secStrTab);
186 if (ret) return ret;
187
188 for (int i = 0; i < (int)shTable.size(); i++) {
189 char* secname = secStrTab.data() + shTable[i].sh_name;
190 if (!secname) continue;
191
192 if (!strcmp(secname, name)) {
193 vector<char> dataTmp;
194 dataTmp.resize(shTable[i].sh_size);
195
196 elfFile.seekg(shTable[i].sh_offset);
197 if (elfFile.fail()) return -1;
198
199 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
200
201 data = dataTmp;
202 return 0;
203 }
204 }
205 return -2;
206}
207
208static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
209 int ret;
210 vector<Elf64_Shdr> shTable;
211
212 ret = readSectionHeadersAll(elfFile, shTable);
213 if (ret) return ret;
214
215 for (int i = 0; i < (int)shTable.size(); i++) {
216 if ((int)shTable[i].sh_type != type) continue;
217
218 vector<char> dataTmp;
219 dataTmp.resize(shTable[i].sh_size);
220
221 elfFile.seekg(shTable[i].sh_offset);
222 if (elfFile.fail()) return -1;
223
224 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
225
226 data = dataTmp;
227 return 0;
228 }
229 return -2;
230}
231
232static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
233 return (a.st_value < b.st_value);
234}
235
236static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
237 int ret, numElems;
238 Elf64_Sym* buf;
239 vector<char> secData;
240
241 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
242 if (ret) return ret;
243
244 buf = (Elf64_Sym*)secData.data();
245 numElems = (secData.size() / sizeof(Elf64_Sym));
246 data.assign(buf, buf + numElems);
247
248 if (sort) std::sort(data.begin(), data.end(), symCompare);
249 return 0;
250}
251
252static enum bpf_prog_type getSectionType(string& name) {
253 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++)
254 if (StartsWith(name, sectionNameTypes[i].name)) return sectionNameTypes[i].type;
255
256 return BPF_PROG_TYPE_UNSPEC;
257}
258
259/* If ever needed
260static string getSectionName(enum bpf_prog_type type)
261{
262 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++)
263 if (sectionNameTypes[i].type == type)
264 return std::string(sectionNameTypes[i].name);
265
266 return NULL;
267}
268*/
269
270static bool isRelSection(codeSection& cs, string& name) {
271 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++) {
272 sectionType st = sectionNameTypes[i];
273
274 if (st.type != cs.type) continue;
275
276 if (StartsWith(name, std::string(".rel") + st.name + "/"))
277 return true;
278 else
279 return false;
280 }
281 return false;
282}
283
284/* Read a section by its index - for ex to get sec hdr strtab blob */
285static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
286 vector<Elf64_Shdr> shTable;
287 int entries, ret = 0;
288
289 ret = readSectionHeadersAll(elfFile, shTable);
290 if (ret) return ret;
291 entries = shTable.size();
292
293 for (int i = 0; i < entries; i++) {
294 string name;
295 codeSection cs_temp;
296 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
297
298 ret = getSymName(elfFile, shTable[i].sh_name, name);
299 if (ret) return ret;
300
301 enum bpf_prog_type ptype = getSectionType(name);
302 if (ptype != BPF_PROG_TYPE_UNSPEC) {
303 deslash(name);
304 cs_temp.type = ptype;
305 cs_temp.name = name;
306
307 ret = readSectionByIdx(elfFile, i, cs_temp.data);
308 if (ret) return ret;
309 ALOGD("Loaded code section %d (%s)\n", i, name.c_str());
310 }
311
312 /* Check for rel section */
313 if (cs_temp.data.size() > 0 && i < entries) {
314 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
315 if (ret) return ret;
316
317 if (isRelSection(cs_temp, name)) {
318 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
319 if (ret) return ret;
320 ALOGD("Loaded relo section %d (%s)\n", i, name.c_str());
321 }
322 }
323
324 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700325 cs.push_back(std::move(cs_temp));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700326 ALOGD("Adding section %d to cs list\n", i);
327 }
328 }
329 return 0;
330}
331
332static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
333 vector<Elf64_Sym> symtab;
334 int ret = 0;
335
336 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
337 if (ret) return ret;
338
339 if (index >= (int)symtab.size()) return -1;
340
341 return getSymName(elfFile, symtab[index].st_name, name);
342}
343
344static int getMapNames(ifstream& elfFile, vector<string>& names) {
345 int ret;
346 string mapName;
347 vector<Elf64_Sym> symtab;
348 vector<Elf64_Shdr> shTable;
349
350 ret = readSymTab(elfFile, 1 /* sort */, symtab);
351 if (ret) return ret;
352
353 /* Get index of maps section */
354 ret = readSectionHeadersAll(elfFile, shTable);
355 if (ret) return ret;
356
357 int maps_idx = -1;
358 for (int i = 0; i < (int)shTable.size(); i++) {
359 ret = getSymName(elfFile, shTable[i].sh_name, mapName);
360 if (ret) return ret;
361
362 if (!mapName.compare("maps")) {
363 maps_idx = i;
364 break;
365 }
366 }
367
368 /* No maps found */
369 if (maps_idx == -1) {
370 ALOGE("No maps could be found in elf object\n");
371 return -1;
372 }
373
374 for (int i = 0; i < (int)symtab.size(); i++) {
375 if (symtab[i].st_shndx == maps_idx) {
376 string s;
377 ret = getSymName(elfFile, symtab[i].st_name, s);
378 if (ret) return ret;
379 names.push_back(s);
380 }
381 }
382
383 return 0;
384}
385
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700386static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds) {
387 int ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700388 vector<char> mdData;
389 vector<struct bpf_map_def> md;
390 vector<string> mapNames;
391 string fname = pathToFilename(string(elfPath), true);
392
393 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800394 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700395 if (ret) return ret;
396 md.resize(mdData.size() / sizeof(struct bpf_map_def));
397 memcpy(md.data(), mdData.data(), mdData.size());
398
399 ret = getMapNames(elfFile, mapNames);
400 if (ret) return ret;
401
Joel Fernandesd76a2002018-10-16 13:19:58 -0700402 for (int i = 0; i < (int)mapNames.size(); i++) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700403 unique_fd fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700404 // Format of pin location is /sys/fs/bpf/map_<filename>_<mapname>
405 string mapPinLoc;
406 bool reuse = false;
407
408 mapPinLoc = string(BPF_FS_PATH) + "map_" + fname + "_" + string(mapNames[i]);
409 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700410 fd.reset(bpf_obj_get(mapPinLoc.c_str()));
411 ALOGD("bpf_create_map reusing map %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700412 reuse = true;
413 } else {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700414 fd.reset(bpf_create_map(md[i].type, mapNames[i].c_str(), md[i].key_size, md[i].value_size,
415 md[i].max_entries, md[i].map_flags));
416 ALOGD("bpf_create_map name %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700417 }
418
419 if (fd < 0) return fd;
420 if (fd == 0) return -EINVAL;
421
422 if (!reuse) {
423 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
424 if (ret < 0) return ret;
425 }
426
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700427 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700428 }
429
430 return ret;
431}
432
433/* For debugging, dump all instructions */
434static void dumpIns(char* ins, int size) {
435 for (int row = 0; row < size / 8; row++) {
436 ALOGE("%d: ", row);
437 for (int j = 0; j < 8; j++) {
438 ALOGE("%3x ", ins[(row * 8) + j]);
439 }
440 ALOGE("\n");
441 }
442}
443
444/* For debugging, dump all code sections from cs list */
445static void dumpAllCs(vector<codeSection>& cs) {
446 for (int i = 0; i < (int)cs.size(); i++) {
447 ALOGE("Dumping cs %d, name %s\n", int(i), cs[i].name.c_str());
448 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
449 ALOGE("-----------\n");
450 }
451}
452
453static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
454 int insnIndex;
455 struct bpf_insn *insn, *insns;
456
457 insns = (struct bpf_insn*)(insnsPtr);
458
459 insnIndex = offset / sizeof(struct bpf_insn);
460 insn = &insns[insnIndex];
461
462 ALOGD(
463 "applying relo to instruction at byte offset: %d, \
464 insn offset %d , insn %lx\n",
465 (int)offset, (int)insnIndex, *(unsigned long*)insn);
466
467 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
468 ALOGE("Dumping all instructions till ins %d\n", insnIndex);
469 ALOGE("invalid relo for insn %d: code 0x%x\n", insnIndex, insn->code);
470 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
471 return;
472 }
473
474 insn->imm = fd;
475 insn->src_reg = BPF_PSEUDO_MAP_FD;
476}
477
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700478static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700479 vector<string> mapNames;
480
481 int ret = getMapNames(elfFile, mapNames);
482 if (ret) return;
483
484 for (int k = 0; k != (int)cs.size(); k++) {
485 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
486 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
487
488 for (int i = 0; i < n_rel; i++) {
489 int symIndex = ELF64_R_SYM(rel[i].r_info);
490 string symName;
491
492 ret = getSymNameByIdx(elfFile, symIndex, symName);
493 if (ret) return;
494
495 /* Find the map fd and apply relo */
496 for (int j = 0; j < (int)mapNames.size(); j++) {
497 if (!mapNames[j].compare(symName)) {
498 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
499 break;
500 }
501 }
502 }
503 }
504}
505
Christopher Ferrisc151c672019-02-01 15:31:26 -0800506static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700507 int ret, fd, kvers;
508
509 if ((kvers = getMachineKvers()) < 0) return -1;
510
511 string fname = pathToFilename(string(elfPath), true);
512
513 for (int i = 0; i < (int)cs.size(); i++) {
514 string progPinLoc;
515 bool reuse = false;
516
517 // Format of pin location is
518 // /sys/fs/bpf/prog_<filename>_<mapname>
519 progPinLoc = string(BPF_FS_PATH) + "prog_" + fname + "_" + cs[i].name;
520 if (access(progPinLoc.c_str(), F_OK) == 0) {
521 fd = bpf_obj_get(progPinLoc.c_str());
522 ALOGD("New bpf prog load reusing prog %s, ret: %d\n", cs[i].name.c_str(), fd);
523 reuse = true;
524 } else {
525 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
526
527 fd = bpf_prog_load(cs[i].type, cs[i].name.c_str(), (struct bpf_insn*)cs[i].data.data(),
528 cs[i].data.size(), license.c_str(), kvers, 0,
529 log_buf.data(), log_buf.size());
Steven Moreland804bca02019-12-12 17:21:23 -0800530 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)\n", elfPath,
531 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700532
533 if (fd <= 0)
534 ALOGE("bpf_prog_load: log_buf contents: %s\n", (char *)log_buf.data());
535 }
536
537 if (fd < 0) return fd;
538 if (fd == 0) return -EINVAL;
539
540 if (!reuse) {
541 ret = bpf_obj_pin(fd, progPinLoc.c_str());
542 if (ret < 0) return ret;
543 }
544
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700545 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700546 }
547
548 return 0;
549}
550
551int loadProg(const char* elfPath) {
552 vector<char> license;
553 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700554 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700555 int ret;
556
557 ifstream elfFile(elfPath, ios::in | ios::binary);
558 if (!elfFile.is_open()) return -1;
559
560 ret = readSectionByName("license", elfFile, license);
561 if (ret) {
562 ALOGE("Couldn't find license in %s\n", elfPath);
563 return ret;
564 } else {
565 ALOGD("Loading ELF object %s with license %s\n", elfPath, (char*)license.data());
566 }
567
568 ret = readCodeSections(elfFile, cs);
569 if (ret) {
570 ALOGE("Couldn't read all code sections in %s\n", elfPath);
571 return ret;
572 }
573
574 /* Just for future debugging */
575 if (0) dumpAllCs(cs);
576
577 ret = createMaps(elfPath, elfFile, mapFds);
578 if (ret) {
579 ALOGE("Failed to create maps: (ret=%d) in %s\n", ret, elfPath);
580 return ret;
581 }
582
583 for (int i = 0; i < (int)mapFds.size(); i++)
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700584 ALOGD("map_fd found at %d is %d in %s\n", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700585
586 applyMapRelo(elfFile, mapFds, cs);
587
588 ret = loadCodeSections(elfPath, cs, string(license.data()));
589 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d\n", ret);
590
591 return ret;
592}
593
Steven Moreland4891e612020-01-10 15:35:52 -0800594void waitForProgsLoaded() {
595 while (!android::base::WaitForProperty("bpf.progs_loaded", "1", std::chrono::seconds(5))) {
596 ALOGW("Waited 5s for bpf.progs_loaded, still waiting...");
597 }
598}
599
Joel Fernandesd76a2002018-10-16 13:19:58 -0700600} // namespace bpf
601} // namespace android