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