blob: 8a66c298eb09e252093cff50981be3c12998604f [file] [log] [blame]
Joel Fernandesd76a2002018-10-16 13:19:58 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "LibBpfLoader"
18
19#include <errno.h>
20#include <linux/bpf.h>
21#include <linux/elf.h>
22#include <log/log.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Maciej Żenczykowski83f29772020-01-27 03:11:51 -080027#include <sys/stat.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070028#include <sys/utsname.h>
29#include <unistd.h>
30
Maciej Żenczykowski730a3862020-01-27 01:10:48 -080031#include "../progs/include/bpf_map_def.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070032#include "LoaderUtils.h"
Maciej Żenczykowski07375e22020-02-19 14:23:59 -080033#include "bpf/BpfUtils.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070034#include "include/libbpf_android.h"
35
36#include <cstdlib>
37#include <fstream>
38#include <iostream>
Connor O'Brien3278a162020-02-13 21:45:22 -080039#include <optional>
Joel Fernandesd76a2002018-10-16 13:19:58 -070040#include <string>
Christopher Ferrisc151c672019-02-01 15:31:26 -080041#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070042
Steven Moreland4891e612020-01-10 15:35:52 -080043#include <android-base/properties.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070044#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070045#include <android-base/unique_fd.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070046
47#define BPF_FS_PATH "/sys/fs/bpf/"
48
49// Size of the BPF log buffer for verifier logging
50#define BPF_LOAD_LOG_SZ 0x1ffff
51
52using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070053using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070054using std::ifstream;
55using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080056using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080057using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070058using std::vector;
59
60namespace android {
61namespace bpf {
62
63typedef struct {
64 const char* name;
65 enum bpf_prog_type type;
66} sectionType;
67
68/*
69 * Map section name prefixes to program types, the section name will be:
70 * SEC(<prefix>/<name-of-program>)
71 * For example:
72 * SEC("tracepoint/sched_switch_func") where sched_switch_funcs
73 * is the name of the program, and tracepoint is the type.
74 */
75sectionType sectionNameTypes[] = {
Maciej Żenczykowskiaa462222021-01-07 14:24:45 -080076 {"kprobe", BPF_PROG_TYPE_KPROBE},
77 {"tracepoint", BPF_PROG_TYPE_TRACEPOINT},
78 {"skfilter", BPF_PROG_TYPE_SOCKET_FILTER},
79 {"cgroupskb", BPF_PROG_TYPE_CGROUP_SKB},
80 {"schedcls", BPF_PROG_TYPE_SCHED_CLS},
81 {"cgroupsock", BPF_PROG_TYPE_CGROUP_SOCK},
82 {"xdp", BPF_PROG_TYPE_XDP},
Joel Fernandesd76a2002018-10-16 13:19:58 -070083
Maciej Żenczykowskiaa462222021-01-07 14:24:45 -080084 /* End of table */
85 {"END", BPF_PROG_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -070086};
87
88typedef struct {
89 enum bpf_prog_type type;
90 string name;
91 vector<char> data;
92 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -080093 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -070094
Connor O'Brien8d49fc72019-10-24 18:23:49 -070095 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -070096} codeSection;
97
Joel Fernandesd76a2002018-10-16 13:19:58 -070098static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
99 elfFile.seekg(0);
100 if (elfFile.fail()) return -1;
101
102 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
103
104 return 0;
105}
106
107/* Reads all section header tables into an Shdr array */
108static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
109 Elf64_Ehdr eh;
110 int ret = 0;
111
112 ret = readElfHeader(elfFile, &eh);
113 if (ret) return ret;
114
115 elfFile.seekg(eh.e_shoff);
116 if (elfFile.fail()) return -1;
117
118 /* Read shdr table entries */
119 shTable.resize(eh.e_shnum);
120
121 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
122
123 return 0;
124}
125
126/* Read a section by its index - for ex to get sec hdr strtab blob */
127static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
128 vector<Elf64_Shdr> shTable;
129 int entries, ret = 0;
130
131 ret = readSectionHeadersAll(elfFile, shTable);
132 if (ret) return ret;
133 entries = shTable.size();
134
135 elfFile.seekg(shTable[id].sh_offset);
136 if (elfFile.fail()) return -1;
137
138 sec.resize(shTable[id].sh_size);
139 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
140
141 return 0;
142}
143
144/* Read whole section header string table */
145static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
146 Elf64_Ehdr eh;
147 int ret = 0;
148
149 ret = readElfHeader(elfFile, &eh);
150 if (ret) return ret;
151
152 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
153 if (ret) return ret;
154
155 return 0;
156}
157
158/* Get name from offset in strtab */
159static int getSymName(ifstream& elfFile, int nameOff, string& name) {
160 int ret;
161 vector<char> secStrTab;
162
163 ret = readSectionHeaderStrtab(elfFile, secStrTab);
164 if (ret) return ret;
165
166 if (nameOff >= (int)secStrTab.size()) return -1;
167
168 name = string((char*)secStrTab.data() + nameOff);
169 return 0;
170}
171
172/* Reads a full section by name - example to get the GPL license */
173static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
174 vector<char> secStrTab;
175 vector<Elf64_Shdr> shTable;
176 int ret;
177
178 ret = readSectionHeadersAll(elfFile, shTable);
179 if (ret) return ret;
180
181 ret = readSectionHeaderStrtab(elfFile, secStrTab);
182 if (ret) return ret;
183
184 for (int i = 0; i < (int)shTable.size(); i++) {
185 char* secname = secStrTab.data() + shTable[i].sh_name;
186 if (!secname) continue;
187
188 if (!strcmp(secname, name)) {
189 vector<char> dataTmp;
190 dataTmp.resize(shTable[i].sh_size);
191
192 elfFile.seekg(shTable[i].sh_offset);
193 if (elfFile.fail()) return -1;
194
195 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
196
197 data = dataTmp;
198 return 0;
199 }
200 }
201 return -2;
202}
203
204static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
205 int ret;
206 vector<Elf64_Shdr> shTable;
207
208 ret = readSectionHeadersAll(elfFile, shTable);
209 if (ret) return ret;
210
211 for (int i = 0; i < (int)shTable.size(); i++) {
212 if ((int)shTable[i].sh_type != type) continue;
213
214 vector<char> dataTmp;
215 dataTmp.resize(shTable[i].sh_size);
216
217 elfFile.seekg(shTable[i].sh_offset);
218 if (elfFile.fail()) return -1;
219
220 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
221
222 data = dataTmp;
223 return 0;
224 }
225 return -2;
226}
227
228static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
229 return (a.st_value < b.st_value);
230}
231
232static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
233 int ret, numElems;
234 Elf64_Sym* buf;
235 vector<char> secData;
236
237 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
238 if (ret) return ret;
239
240 buf = (Elf64_Sym*)secData.data();
241 numElems = (secData.size() / sizeof(Elf64_Sym));
242 data.assign(buf, buf + numElems);
243
244 if (sort) std::sort(data.begin(), data.end(), symCompare);
245 return 0;
246}
247
248static enum bpf_prog_type getSectionType(string& name) {
249 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++)
250 if (StartsWith(name, sectionNameTypes[i].name)) return sectionNameTypes[i].type;
251
252 return BPF_PROG_TYPE_UNSPEC;
253}
254
255/* If ever needed
256static string getSectionName(enum bpf_prog_type type)
257{
258 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++)
259 if (sectionNameTypes[i].type == type)
260 return std::string(sectionNameTypes[i].name);
261
262 return NULL;
263}
264*/
265
266static bool isRelSection(codeSection& cs, string& name) {
267 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++) {
268 sectionType st = sectionNameTypes[i];
269
270 if (st.type != cs.type) continue;
271
272 if (StartsWith(name, std::string(".rel") + st.name + "/"))
273 return true;
274 else
275 return false;
276 }
277 return false;
278}
279
Connor O'Brien3278a162020-02-13 21:45:22 -0800280static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
281 vector<char> pdData;
282 int ret = readSectionByName("progs", elfFile, pdData);
283 if (ret == -2) return 0;
284 if (ret) return ret;
285
286 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
287 memcpy(pd.data(), pdData.data(), pdData.size());
288 return 0;
289}
290
291static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names) {
292 int ret;
293 string name;
294 vector<Elf64_Sym> symtab;
295 vector<Elf64_Shdr> shTable;
296
297 ret = readSymTab(elfFile, 1 /* sort */, symtab);
298 if (ret) return ret;
299
300 /* Get index of section */
301 ret = readSectionHeadersAll(elfFile, shTable);
302 if (ret) return ret;
303
304 int sec_idx = -1;
305 for (int i = 0; i < (int)shTable.size(); i++) {
306 ret = getSymName(elfFile, shTable[i].sh_name, name);
307 if (ret) return ret;
308
309 if (!name.compare(sectionName)) {
310 sec_idx = i;
311 break;
312 }
313 }
314
315 /* No section found with matching name*/
316 if (sec_idx == -1) {
Maciej Żenczykowski21f34cb2020-07-20 18:44:33 -0700317 ALOGW("No %s section could be found in elf object\n", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800318 return -1;
319 }
320
321 for (int i = 0; i < (int)symtab.size(); i++) {
322 if (symtab[i].st_shndx == sec_idx) {
323 string s;
324 ret = getSymName(elfFile, symtab[i].st_name, s);
325 if (ret) return ret;
326 names.push_back(s);
327 }
328 }
329
330 return 0;
331}
332
Joel Fernandesd76a2002018-10-16 13:19:58 -0700333/* Read a section by its index - for ex to get sec hdr strtab blob */
334static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
335 vector<Elf64_Shdr> shTable;
336 int entries, ret = 0;
337
338 ret = readSectionHeadersAll(elfFile, shTable);
339 if (ret) return ret;
340 entries = shTable.size();
341
Connor O'Brien3278a162020-02-13 21:45:22 -0800342 vector<struct bpf_prog_def> pd;
343 ret = readProgDefs(elfFile, pd);
344 if (ret) return ret;
345 vector<string> progDefNames;
346 ret = getSectionSymNames(elfFile, "progs", progDefNames);
347 if (!pd.empty() && ret) return ret;
348
Joel Fernandesd76a2002018-10-16 13:19:58 -0700349 for (int i = 0; i < entries; i++) {
350 string name;
351 codeSection cs_temp;
352 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
353
354 ret = getSymName(elfFile, shTable[i].sh_name, name);
355 if (ret) return ret;
356
357 enum bpf_prog_type ptype = getSectionType(name);
358 if (ptype != BPF_PROG_TYPE_UNSPEC) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800359 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700360 deslash(name);
361 cs_temp.type = ptype;
362 cs_temp.name = name;
363
364 ret = readSectionByIdx(elfFile, i, cs_temp.data);
365 if (ret) return ret;
366 ALOGD("Loaded code section %d (%s)\n", i, name.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800367
368 vector<string> csSymNames;
369 ret = getSectionSymNames(elfFile, oldName, csSymNames);
370 if (ret || !csSymNames.size()) return ret;
371 for (size_t i = 0; i < progDefNames.size(); ++i) {
372 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
373 cs_temp.prog_def = pd[i];
374 break;
375 }
376 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700377 }
378
379 /* Check for rel section */
380 if (cs_temp.data.size() > 0 && i < entries) {
381 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
382 if (ret) return ret;
383
384 if (isRelSection(cs_temp, name)) {
385 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
386 if (ret) return ret;
387 ALOGD("Loaded relo section %d (%s)\n", i, name.c_str());
388 }
389 }
390
391 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700392 cs.push_back(std::move(cs_temp));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700393 ALOGD("Adding section %d to cs list\n", i);
394 }
395 }
396 return 0;
397}
398
399static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
400 vector<Elf64_Sym> symtab;
401 int ret = 0;
402
403 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
404 if (ret) return ret;
405
406 if (index >= (int)symtab.size()) return -1;
407
408 return getSymName(elfFile, symtab[index].st_name, name);
409}
410
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700411static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds) {
412 int ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700413 vector<char> mdData;
414 vector<struct bpf_map_def> md;
415 vector<string> mapNames;
416 string fname = pathToFilename(string(elfPath), true);
417
418 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800419 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700420 if (ret) return ret;
421 md.resize(mdData.size() / sizeof(struct bpf_map_def));
422 memcpy(md.data(), mdData.data(), mdData.size());
423
Connor O'Brien3278a162020-02-13 21:45:22 -0800424 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700425 if (ret) return ret;
426
Joel Fernandesd76a2002018-10-16 13:19:58 -0700427 for (int i = 0; i < (int)mapNames.size(); i++) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700428 unique_fd fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700429 // Format of pin location is /sys/fs/bpf/map_<filename>_<mapname>
430 string mapPinLoc;
431 bool reuse = false;
432
433 mapPinLoc = string(BPF_FS_PATH) + "map_" + fname + "_" + string(mapNames[i]);
434 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700435 fd.reset(bpf_obj_get(mapPinLoc.c_str()));
436 ALOGD("bpf_create_map reusing map %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700437 reuse = true;
438 } else {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700439 fd.reset(bpf_create_map(md[i].type, mapNames[i].c_str(), md[i].key_size, md[i].value_size,
440 md[i].max_entries, md[i].map_flags));
441 ALOGD("bpf_create_map name %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700442 }
443
444 if (fd < 0) return fd;
445 if (fd == 0) return -EINVAL;
446
447 if (!reuse) {
448 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800449 if (ret) return -errno;
450 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
451 if (ret) return -errno;
452 ret = chmod(mapPinLoc.c_str(), md[i].mode);
453 if (ret) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700454 }
455
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700456 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700457 }
458
459 return ret;
460}
461
462/* For debugging, dump all instructions */
463static void dumpIns(char* ins, int size) {
464 for (int row = 0; row < size / 8; row++) {
465 ALOGE("%d: ", row);
466 for (int j = 0; j < 8; j++) {
467 ALOGE("%3x ", ins[(row * 8) + j]);
468 }
469 ALOGE("\n");
470 }
471}
472
473/* For debugging, dump all code sections from cs list */
474static void dumpAllCs(vector<codeSection>& cs) {
475 for (int i = 0; i < (int)cs.size(); i++) {
476 ALOGE("Dumping cs %d, name %s\n", int(i), cs[i].name.c_str());
477 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
478 ALOGE("-----------\n");
479 }
480}
481
482static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
483 int insnIndex;
484 struct bpf_insn *insn, *insns;
485
486 insns = (struct bpf_insn*)(insnsPtr);
487
488 insnIndex = offset / sizeof(struct bpf_insn);
489 insn = &insns[insnIndex];
490
491 ALOGD(
492 "applying relo to instruction at byte offset: %d, \
493 insn offset %d , insn %lx\n",
494 (int)offset, (int)insnIndex, *(unsigned long*)insn);
495
496 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
497 ALOGE("Dumping all instructions till ins %d\n", insnIndex);
498 ALOGE("invalid relo for insn %d: code 0x%x\n", insnIndex, insn->code);
499 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
500 return;
501 }
502
503 insn->imm = fd;
504 insn->src_reg = BPF_PSEUDO_MAP_FD;
505}
506
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700507static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700508 vector<string> mapNames;
509
Connor O'Brien3278a162020-02-13 21:45:22 -0800510 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700511 if (ret) return;
512
513 for (int k = 0; k != (int)cs.size(); k++) {
514 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
515 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
516
517 for (int i = 0; i < n_rel; i++) {
518 int symIndex = ELF64_R_SYM(rel[i].r_info);
519 string symName;
520
521 ret = getSymNameByIdx(elfFile, symIndex, symName);
522 if (ret) return;
523
524 /* Find the map fd and apply relo */
525 for (int j = 0; j < (int)mapNames.size(); j++) {
526 if (!mapNames[j].compare(symName)) {
527 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
528 break;
529 }
530 }
531 }
532 }
533}
534
Christopher Ferrisc151c672019-02-01 15:31:26 -0800535static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800536 unsigned kvers = kernelVersion();
537 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700538
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800539 if (!kvers) return -1;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700540
541 string fname = pathToFilename(string(elfPath), true);
542
543 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700544 string name = cs[i].name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700545
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800546 if (cs[i].prog_def.has_value()) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700547 unsigned min_kver = cs[i].prog_def->min_kver;
548 unsigned max_kver = cs[i].prog_def->max_kver;
549 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)\n", i, name.c_str(), min_kver,
550 max_kver, kvers);
551 if (kvers < min_kver) continue;
552 if (kvers >= max_kver) continue;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800553 }
554
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700555 // strip any potential $foo suffix
556 // this can be used to provide duplicate programs
557 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700558 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700559
560 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700561 // Format of pin location is
562 // /sys/fs/bpf/prog_<filename>_<mapname>
Maciej Żenczykowski6c7871b2020-04-23 12:46:00 -0700563 string progPinLoc = BPF_FS_PATH "prog_";
564 progPinLoc += fname;
565 progPinLoc += '_';
566 progPinLoc += name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700567 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700568 fd = retrieveProgram(progPinLoc.c_str());
569 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)\n", progPinLoc.c_str(), fd,
570 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700571 reuse = true;
572 } else {
573 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
574
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700575 fd = bpf_prog_load(cs[i].type, name.c_str(), (struct bpf_insn*)cs[i].data.data(),
576 cs[i].data.size(), license.c_str(), kvers, 0, log_buf.data(),
577 log_buf.size());
Steven Moreland804bca02019-12-12 17:21:23 -0800578 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)\n", elfPath,
579 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700580
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800581 if (fd < 0) {
582 std::vector<std::string> lines = android::base::Split(log_buf.data(), "\n");
583
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700584 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
585 for (const auto& line : lines) ALOGW("%s", line.c_str());
586 ALOGW("bpf_prog_load - END log_buf contents.");
587
588 if (cs[i].prog_def->optional) {
589 ALOGW("failed program is marked optional - continuing...");
590 continue;
591 }
592 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800593 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700594 }
595
596 if (fd < 0) return fd;
597 if (fd == 0) return -EINVAL;
598
599 if (!reuse) {
600 ret = bpf_obj_pin(fd, progPinLoc.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800601 if (ret) return -errno;
602 if (cs[i].prog_def.has_value()) {
603 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
604 (gid_t)cs[i].prog_def->gid)) {
605 return -errno;
606 }
607 }
608 if (chmod(progPinLoc.c_str(), 0440)) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700609 }
610
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700611 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700612 }
613
614 return 0;
615}
616
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700617int loadProg(const char* elfPath, bool* isCritical) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700618 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700619 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700620 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700621 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700622 int ret;
623
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700624 if (!isCritical) return -1;
625 *isCritical = false;
626
Joel Fernandesd76a2002018-10-16 13:19:58 -0700627 ifstream elfFile(elfPath, ios::in | ios::binary);
628 if (!elfFile.is_open()) return -1;
629
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700630 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700631 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700632
Joel Fernandesd76a2002018-10-16 13:19:58 -0700633 ret = readSectionByName("license", elfFile, license);
634 if (ret) {
635 ALOGE("Couldn't find license in %s\n", elfPath);
636 return ret;
637 } else {
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700638 ALOGD("Loading %s%s ELF object %s with license %s\n",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700639 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700640 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700641 }
642
643 ret = readCodeSections(elfFile, cs);
644 if (ret) {
645 ALOGE("Couldn't read all code sections in %s\n", elfPath);
646 return ret;
647 }
648
649 /* Just for future debugging */
650 if (0) dumpAllCs(cs);
651
652 ret = createMaps(elfPath, elfFile, mapFds);
653 if (ret) {
654 ALOGE("Failed to create maps: (ret=%d) in %s\n", ret, elfPath);
655 return ret;
656 }
657
658 for (int i = 0; i < (int)mapFds.size(); i++)
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700659 ALOGD("map_fd found at %d is %d in %s\n", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700660
661 applyMapRelo(elfFile, mapFds, cs);
662
663 ret = loadCodeSections(elfPath, cs, string(license.data()));
664 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d\n", ret);
665
666 return ret;
667}
668
Maciej Żenczykowski2090e342020-06-16 17:56:16 -0700669static bool waitSecondsForProgsLoaded(int seconds) {
670 bool ok =
671 android::base::WaitForProperty("bpf.progs_loaded", "1", std::chrono::seconds(seconds));
672 if (!ok) ALOGW("Waited %ds for bpf.progs_loaded, still waiting...", seconds);
673 return ok;
674}
675
Steven Moreland4891e612020-01-10 15:35:52 -0800676void waitForProgsLoaded() {
Maciej Żenczykowski567dc562020-06-10 15:56:07 -0700677 if (!android::bpf::isBpfSupported()) return;
678
Maciej Żenczykowski2090e342020-06-16 17:56:16 -0700679 if (waitSecondsForProgsLoaded(5)) return;
680 if (waitSecondsForProgsLoaded(10)) return;
681 if (waitSecondsForProgsLoaded(20)) return;
682 while (!waitSecondsForProgsLoaded(60))
683 ; // loop until success
Steven Moreland4891e612020-01-10 15:35:52 -0800684}
685
Joel Fernandesd76a2002018-10-16 13:19:58 -0700686} // namespace bpf
687} // namespace android