blob: d817614523c5258e96a0b411b357a7f0b1069cc1 [file] [log] [blame]
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -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 <fcntl.h>
21#include <linux/bpf.h>
22#include <linux/elf.h>
23#include <log/log.h>
24#include <stdint.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <sysexits.h>
29#include <sys/stat.h>
30#include <sys/utsname.h>
31#include <sys/wait.h>
32#include <unistd.h>
33
34// This is BpfLoader v0.41
35// WARNING: If you ever hit cherrypick conflicts here you're doing it wrong:
36// You are NOT allowed to cherrypick bpfloader related patches out of order.
37// (indeed: cherrypicking is probably a bad idea and you should merge instead)
38// Mainline supports ONLY the published versions of the bpfloader for each Android release.
39#define BPFLOADER_VERSION_MAJOR 0u
40#define BPFLOADER_VERSION_MINOR 41u
41#define BPFLOADER_VERSION ((BPFLOADER_VERSION_MAJOR << 16) | BPFLOADER_VERSION_MINOR)
42
43#include "BpfSyscallWrappers.h"
44#include "bpf/BpfUtils.h"
45#include "bpf/bpf_map_def.h"
46#include "include/libbpf_android.h"
47
48#if BPFLOADER_VERSION < COMPILE_FOR_BPFLOADER_VERSION
49#error "BPFLOADER_VERSION is less than COMPILE_FOR_BPFLOADER_VERSION"
50#endif
51
52#include <cstdlib>
53#include <fstream>
54#include <iostream>
55#include <optional>
56#include <string>
57#include <unordered_map>
58#include <vector>
59
60#include <android-base/cmsg.h>
61#include <android-base/file.h>
62#include <android-base/strings.h>
63#include <android-base/unique_fd.h>
64#include <cutils/properties.h>
65
66#define BPF_FS_PATH "/sys/fs/bpf/"
67
68// Size of the BPF log buffer for verifier logging
69#define BPF_LOAD_LOG_SZ 0xfffff
70
71// Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
72#define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
73
74using android::base::StartsWith;
75using android::base::unique_fd;
76using std::ifstream;
77using std::ios;
78using std::optional;
79using std::string;
80using std::vector;
81
82static std::string getBuildTypeInternal() {
83 char value[PROPERTY_VALUE_MAX] = {};
84 (void)property_get("ro.build.type", value, "unknown"); // ignore length
85 return value;
86}
87
88namespace android {
89namespace bpf {
90
91const std::string& getBuildType() {
92 static std::string t = getBuildTypeInternal();
93 return t;
94}
95
96static unsigned int page_size = static_cast<unsigned int>(getpagesize());
97
98constexpr const char* lookupSelinuxContext(const domain d, const char* const unspecified = "") {
99 switch (d) {
100 case domain::unspecified: return unspecified;
101 case domain::platform: return "fs_bpf";
102 case domain::tethering: return "fs_bpf_tethering";
103 case domain::net_private: return "fs_bpf_net_private";
104 case domain::net_shared: return "fs_bpf_net_shared";
105 case domain::netd_readonly: return "fs_bpf_netd_readonly";
106 case domain::netd_shared: return "fs_bpf_netd_shared";
107 case domain::vendor: return "fs_bpf_vendor";
108 case domain::loader: return "fs_bpf_loader";
109 default: return "(unrecognized)";
110 }
111}
112
113domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
114 for (domain d : AllDomains) {
115 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
116 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
117 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
118 }
119 ALOGW("ignoring unrecognized selinux_context '%-32s'", s);
120 // We should return 'unrecognized' here, however: returning unspecified will
121 // result in the system simply using the default context, which in turn
122 // will allow future expansion by adding more restrictive selinux types.
123 // Older bpfloader will simply ignore that, and use the less restrictive default.
124 // This does mean you CANNOT later add a *less* restrictive type than the default.
125 //
126 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
127 return domain::unspecified;
128}
129
130constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
131 switch (d) {
132 case domain::unspecified: return unspecified;
133 case domain::platform: return "/";
134 case domain::tethering: return "tethering/";
135 case domain::net_private: return "net_private/";
136 case domain::net_shared: return "net_shared/";
137 case domain::netd_readonly: return "netd_readonly/";
138 case domain::netd_shared: return "netd_shared/";
139 case domain::vendor: return "vendor/";
140 case domain::loader: return "loader/";
141 default: return "(unrecognized)";
142 }
143};
144
145domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
146 for (domain d : AllDomains) {
147 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
148 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
149 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
150 }
151 ALOGE("unrecognized pin_subdir '%-32s'", s);
152 // pin_subdir affects the object's full pathname,
153 // and thus using the default would change the location and thus our code's ability to find it,
154 // hence this seems worth treating as a true error condition.
155 //
156 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
157 // However, our callers will treat this as an error, and stop loading the specific .o,
158 // which will fail bpfloader if the .o is marked critical.
159 return domain::unrecognized;
160}
161
162static string pathToObjName(const string& path) {
163 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
164 string filename = android::base::Split(path, "/").back();
165 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
166 string name = filename.substr(0, filename.find_last_of('.'));
167 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
168 // this can be used to provide duplicate programs (mux based on the bpfloader version)
169 return name.substr(0, name.find_last_of('@'));
170}
171
172typedef struct {
173 const char* name;
174 enum bpf_prog_type type;
175 enum bpf_attach_type expected_attach_type;
176} sectionType;
177
178/*
179 * Map section name prefixes to program types, the section name will be:
180 * SECTION(<prefix>/<name-of-program>)
181 * For example:
182 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
183 * is the name of the program, and tracepoint is the type.
184 *
185 * However, be aware that you should not be directly using the SECTION() macro.
186 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
187 */
188sectionType sectionNameTypes[] = {
189 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
190 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
191 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB, BPF_ATTACH_TYPE_UNSPEC},
192 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_ATTACH_TYPE_UNSPEC},
193 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
194 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
195 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
196 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
197 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
198 {"kprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
199 {"kretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
200 {"lwt_in/", BPF_PROG_TYPE_LWT_IN, BPF_ATTACH_TYPE_UNSPEC},
201 {"lwt_out/", BPF_PROG_TYPE_LWT_OUT, BPF_ATTACH_TYPE_UNSPEC},
202 {"lwt_seg6local/", BPF_PROG_TYPE_LWT_SEG6LOCAL, BPF_ATTACH_TYPE_UNSPEC},
203 {"lwt_xmit/", BPF_PROG_TYPE_LWT_XMIT, BPF_ATTACH_TYPE_UNSPEC},
204 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT, BPF_ATTACH_TYPE_UNSPEC},
205 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
206 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
207 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
208 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
209 {"schedact/", BPF_PROG_TYPE_SCHED_ACT, BPF_ATTACH_TYPE_UNSPEC},
210 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS, BPF_ATTACH_TYPE_UNSPEC},
211 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
212 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
213 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
214 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
215 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
216 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
217 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
218 {"uprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
219 {"uretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
220 {"xdp/", BPF_PROG_TYPE_XDP, BPF_ATTACH_TYPE_UNSPEC},
221};
222
223typedef struct {
224 enum bpf_prog_type type;
225 enum bpf_attach_type expected_attach_type;
226 string name;
227 vector<char> data;
228 vector<char> rel_data;
229 optional<struct bpf_prog_def> prog_def;
230
231 unique_fd prog_fd; /* fd after loading */
232} codeSection;
233
234static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
235 elfFile.seekg(0);
236 if (elfFile.fail()) return -1;
237
238 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
239
240 return 0;
241}
242
243/* Reads all section header tables into an Shdr array */
244static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
245 Elf64_Ehdr eh;
246 int ret = 0;
247
248 ret = readElfHeader(elfFile, &eh);
249 if (ret) return ret;
250
251 elfFile.seekg(eh.e_shoff);
252 if (elfFile.fail()) return -1;
253
254 /* Read shdr table entries */
255 shTable.resize(eh.e_shnum);
256
257 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
258
259 return 0;
260}
261
262/* Read a section by its index - for ex to get sec hdr strtab blob */
263static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
264 vector<Elf64_Shdr> shTable;
265 int ret = readSectionHeadersAll(elfFile, shTable);
266 if (ret) return ret;
267
268 elfFile.seekg(shTable[id].sh_offset);
269 if (elfFile.fail()) return -1;
270
271 sec.resize(shTable[id].sh_size);
272 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
273
274 return 0;
275}
276
277/* Read whole section header string table */
278static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
279 Elf64_Ehdr eh;
280 int ret = readElfHeader(elfFile, &eh);
281 if (ret) return ret;
282
283 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
284 if (ret) return ret;
285
286 return 0;
287}
288
289/* Get name from offset in strtab */
290static int getSymName(ifstream& elfFile, int nameOff, string& name) {
291 int ret;
292 vector<char> secStrTab;
293
294 ret = readSectionHeaderStrtab(elfFile, secStrTab);
295 if (ret) return ret;
296
297 if (nameOff >= (int)secStrTab.size()) return -1;
298
299 name = string((char*)secStrTab.data() + nameOff);
300 return 0;
301}
302
303/* Reads a full section by name - example to get the GPL license */
304static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
305 vector<char> secStrTab;
306 vector<Elf64_Shdr> shTable;
307 int ret;
308
309 ret = readSectionHeadersAll(elfFile, shTable);
310 if (ret) return ret;
311
312 ret = readSectionHeaderStrtab(elfFile, secStrTab);
313 if (ret) return ret;
314
315 for (int i = 0; i < (int)shTable.size(); i++) {
316 char* secname = secStrTab.data() + shTable[i].sh_name;
317 if (!secname) continue;
318
319 if (!strcmp(secname, name)) {
320 vector<char> dataTmp;
321 dataTmp.resize(shTable[i].sh_size);
322
323 elfFile.seekg(shTable[i].sh_offset);
324 if (elfFile.fail()) return -1;
325
326 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
327
328 data = dataTmp;
329 return 0;
330 }
331 }
332 return -2;
333}
334
335unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
336 vector<char> theBytes;
337 int ret = readSectionByName(name, elfFile, theBytes);
338 if (ret) {
339 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
340 return defVal;
341 } else if (theBytes.size() < sizeof(unsigned int)) {
342 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
343 return defVal;
344 } else {
345 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
346 unsigned int value = static_cast<unsigned char>(theBytes[3]);
347 value <<= 8;
348 value += static_cast<unsigned char>(theBytes[2]);
349 value <<= 8;
350 value += static_cast<unsigned char>(theBytes[1]);
351 value <<= 8;
352 value += static_cast<unsigned char>(theBytes[0]);
353 ALOGI("Section %s value is %u [0x%x]", name, value, value);
354 return value;
355 }
356}
357
358static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
359 int ret;
360 vector<Elf64_Shdr> shTable;
361
362 ret = readSectionHeadersAll(elfFile, shTable);
363 if (ret) return ret;
364
365 for (int i = 0; i < (int)shTable.size(); i++) {
366 if ((int)shTable[i].sh_type != type) continue;
367
368 vector<char> dataTmp;
369 dataTmp.resize(shTable[i].sh_size);
370
371 elfFile.seekg(shTable[i].sh_offset);
372 if (elfFile.fail()) return -1;
373
374 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
375
376 data = dataTmp;
377 return 0;
378 }
379 return -2;
380}
381
382static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
383 return (a.st_value < b.st_value);
384}
385
386static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
387 int ret, numElems;
388 Elf64_Sym* buf;
389 vector<char> secData;
390
391 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
392 if (ret) return ret;
393
394 buf = (Elf64_Sym*)secData.data();
395 numElems = (secData.size() / sizeof(Elf64_Sym));
396 data.assign(buf, buf + numElems);
397
398 if (sort) std::sort(data.begin(), data.end(), symCompare);
399 return 0;
400}
401
402static enum bpf_prog_type getFuseProgType() {
403 int result = BPF_PROG_TYPE_UNSPEC;
404 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
405 return static_cast<bpf_prog_type>(result);
406}
407
408static enum bpf_prog_type getSectionType(string& name) {
409 for (auto& snt : sectionNameTypes)
410 if (StartsWith(name, snt.name)) return snt.type;
411
412 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
413 if (StartsWith(name, "fuse/")) return getFuseProgType();
414
415 return BPF_PROG_TYPE_UNSPEC;
416}
417
418static enum bpf_attach_type getExpectedAttachType(string& name) {
419 for (auto& snt : sectionNameTypes)
420 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
421 return BPF_ATTACH_TYPE_UNSPEC;
422}
423
424static string getSectionName(enum bpf_prog_type type)
425{
426 for (auto& snt : sectionNameTypes)
427 if (snt.type == type)
428 return string(snt.name);
429
430 return "UNKNOWN SECTION NAME " + std::to_string(type);
431}
432
433static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
434 size_t sizeOfBpfProgDef) {
435 vector<char> pdData;
436 int ret = readSectionByName("progs", elfFile, pdData);
437 // Older file formats do not require a 'progs' section at all.
438 // (We should probably figure out whether this is behaviour which is safe to remove now.)
439 if (ret == -2) return 0;
440 if (ret) return ret;
441
442 if (pdData.size() % sizeOfBpfProgDef) {
443 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
444 pdData.size(), sizeOfBpfProgDef);
445 return -1;
446 };
447
448 int progCount = pdData.size() / sizeOfBpfProgDef;
449 pd.resize(progCount);
450 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
451
452 const char* dataPtr = pdData.data();
453 for (auto& p : pd) {
454 // First we zero initialize
455 memset(&p, 0, sizeof(p));
456 // Then we set non-zero defaults
457 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
458 // Then we copy over the structure prefix from the ELF file.
459 memcpy(&p, dataPtr, trimmedSize);
460 // Move to next struct in the ELF file
461 dataPtr += sizeOfBpfProgDef;
462 }
463 return 0;
464}
465
466static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
467 optional<unsigned> symbolType = std::nullopt) {
468 int ret;
469 string name;
470 vector<Elf64_Sym> symtab;
471 vector<Elf64_Shdr> shTable;
472
473 ret = readSymTab(elfFile, 1 /* sort */, symtab);
474 if (ret) return ret;
475
476 /* Get index of section */
477 ret = readSectionHeadersAll(elfFile, shTable);
478 if (ret) return ret;
479
480 int sec_idx = -1;
481 for (int i = 0; i < (int)shTable.size(); i++) {
482 ret = getSymName(elfFile, shTable[i].sh_name, name);
483 if (ret) return ret;
484
485 if (!name.compare(sectionName)) {
486 sec_idx = i;
487 break;
488 }
489 }
490
491 /* No section found with matching name*/
492 if (sec_idx == -1) {
493 ALOGW("No %s section could be found in elf object", sectionName.c_str());
494 return -1;
495 }
496
497 for (int i = 0; i < (int)symtab.size(); i++) {
498 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
499
500 if (symtab[i].st_shndx == sec_idx) {
501 string s;
502 ret = getSymName(elfFile, symtab[i].st_name, s);
503 if (ret) return ret;
504 names.push_back(s);
505 }
506 }
507
508 return 0;
509}
510
511static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
512 if (allowed == nullptr) return true;
513
514 for (size_t i = 0; i < numAllowed; i++) {
515 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
516 if (type == getFuseProgType()) return true;
517 } else if (type == allowed[i])
518 return true;
519 }
520
521 return false;
522}
523
524/* Read a section by its index - for ex to get sec hdr strtab blob */
525static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef,
526 const bpf_prog_type* allowed, size_t numAllowed) {
527 vector<Elf64_Shdr> shTable;
528 int entries, ret = 0;
529
530 ret = readSectionHeadersAll(elfFile, shTable);
531 if (ret) return ret;
532 entries = shTable.size();
533
534 vector<struct bpf_prog_def> pd;
535 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
536 if (ret) return ret;
537 vector<string> progDefNames;
538 ret = getSectionSymNames(elfFile, "progs", progDefNames);
539 if (!pd.empty() && ret) return ret;
540
541 for (int i = 0; i < entries; i++) {
542 string name;
543 codeSection cs_temp;
544 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
545
546 ret = getSymName(elfFile, shTable[i].sh_name, name);
547 if (ret) return ret;
548
549 enum bpf_prog_type ptype = getSectionType(name);
550
551 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
552
553 if (!IsAllowed(ptype, allowed, numAllowed)) {
554 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
555 return -1;
556 }
557
558 // This must be done before '/' is replaced with '_'.
559 cs_temp.expected_attach_type = getExpectedAttachType(name);
560
561 string oldName = name;
562
563 // convert all slashes to underscores
564 std::replace(name.begin(), name.end(), '/', '_');
565
566 cs_temp.type = ptype;
567 cs_temp.name = name;
568
569 ret = readSectionByIdx(elfFile, i, cs_temp.data);
570 if (ret) return ret;
571 ALOGD("Loaded code section %d (%s)", i, name.c_str());
572
573 vector<string> csSymNames;
574 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
575 if (ret || !csSymNames.size()) return ret;
576 for (size_t i = 0; i < progDefNames.size(); ++i) {
577 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
578 cs_temp.prog_def = pd[i];
579 break;
580 }
581 }
582
583 /* Check for rel section */
584 if (cs_temp.data.size() > 0 && i < entries) {
585 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
586 if (ret) return ret;
587
588 if (name == (".rel" + oldName)) {
589 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
590 if (ret) return ret;
591 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
592 }
593 }
594
595 if (cs_temp.data.size() > 0) {
596 cs.push_back(std::move(cs_temp));
597 ALOGD("Adding section %d to cs list", i);
598 }
599 }
600 return 0;
601}
602
603static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
604 vector<Elf64_Sym> symtab;
605 int ret = 0;
606
607 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
608 if (ret) return ret;
609
610 if (index >= (int)symtab.size()) return -1;
611
612 return getSymName(elfFile, symtab[index].st_name, name);
613}
614
615static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
616 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
617 // Assuming fd is a valid Bpf Map file descriptor then
618 // all the following should always succeed on a 4.14+ kernel.
619 // If they somehow do fail, they'll return -1 (and set errno),
620 // which should then cause (among others) a key_size mismatch.
621 int fd_type = bpfGetFdMapType(fd);
622 int fd_key_size = bpfGetFdKeySize(fd);
623 int fd_value_size = bpfGetFdValueSize(fd);
624 int fd_max_entries = bpfGetFdMaxEntries(fd);
625 int fd_map_flags = bpfGetFdMapFlags(fd);
626
627 // DEVMAPs are readonly from the bpf program side's point of view, as such
628 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
629 int desired_map_flags = (int)mapDef.map_flags;
630 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
631 desired_map_flags |= BPF_F_RDONLY_PROG;
632
633 // The .h file enforces that this is a power of two, and page size will
634 // also always be a power of two, so this logic is actually enough to
635 // force it to be a multiple of the page size, as required by the kernel.
636 unsigned int desired_max_entries = mapDef.max_entries;
637 if (type == BPF_MAP_TYPE_RINGBUF) {
638 if (desired_max_entries < page_size) desired_max_entries = page_size;
639 }
640
641 // The following checks should *never* trigger, if one of them somehow does,
642 // it probably means a bpf .o file has been changed/replaced at runtime
643 // and bpfloader was manually rerun (normally it should only run *once*
644 // early during the boot process).
645 // Another possibility is that something is misconfigured in the code:
646 // most likely a shared map is declared twice differently.
647 // But such a change should never be checked into the source tree...
648 if ((fd_type == type) &&
649 (fd_key_size == (int)mapDef.key_size) &&
650 (fd_value_size == (int)mapDef.value_size) &&
651 (fd_max_entries == (int)desired_max_entries) &&
652 (fd_map_flags == desired_map_flags)) {
653 return true;
654 }
655
656 ALOGE("bpf map name %s mismatch: desired/found: "
657 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
658 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
659 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
660 return false;
661}
662
663static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
664 const char* prefix, const unsigned long long allowedDomainBitmask,
665 const size_t sizeOfBpfMapDef) {
666 int ret;
667 vector<char> mdData;
668 vector<struct bpf_map_def> md;
669 vector<string> mapNames;
670 string objName = pathToObjName(string(elfPath));
671
672 ret = readSectionByName("maps", elfFile, mdData);
673 if (ret == -2) return 0; // no maps to read
674 if (ret) return ret;
675
676 if (mdData.size() % sizeOfBpfMapDef) {
677 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
678 mdData.size(), sizeOfBpfMapDef);
679 return -1;
680 };
681
682 int mapCount = mdData.size() / sizeOfBpfMapDef;
683 md.resize(mapCount);
684 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
685
686 const char* dataPtr = mdData.data();
687 for (auto& m : md) {
688 // First we zero initialize
689 memset(&m, 0, sizeof(m));
690 // Then we set non-zero defaults
691 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
692 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
693 // Then we copy over the structure prefix from the ELF file.
694 memcpy(&m, dataPtr, trimmedSize);
695 // Move to next struct in the ELF file
696 dataPtr += sizeOfBpfMapDef;
697 }
698
699 ret = getSectionSymNames(elfFile, "maps", mapNames);
700 if (ret) return ret;
701
702 unsigned kvers = kernelVersion();
703
704 for (int i = 0; i < (int)mapNames.size(); i++) {
705 if (md[i].zero != 0) abort();
706
707 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
708 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
709 md[i].bpfloader_min_ver);
710 mapFds.push_back(unique_fd());
711 continue;
712 }
713
714 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
715 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
716 md[i].bpfloader_max_ver);
717 mapFds.push_back(unique_fd());
718 continue;
719 }
720
721 if (kvers < md[i].min_kver) {
722 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
723 mapNames[i].c_str(), kvers, md[i].min_kver);
724 mapFds.push_back(unique_fd());
725 continue;
726 }
727
728 if (kvers >= md[i].max_kver) {
729 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
730 mapNames[i].c_str(), kvers, md[i].max_kver);
731 mapFds.push_back(unique_fd());
732 continue;
733 }
734
735 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
736 (md[i].ignore_on_userdebug && isUserdebug())) {
737 ALOGI("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
738 getBuildType().c_str());
739 mapFds.push_back(unique_fd());
740 continue;
741 }
742
743 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
744 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
745 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
746 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
747 (isRiscV() && md[i].ignore_on_riscv64)) {
748 ALOGI("skipping map %s which is ignored on %s", mapNames[i].c_str(),
749 describeArch());
750 mapFds.push_back(unique_fd());
751 continue;
752 }
753
754 enum bpf_map_type type = md[i].type;
755 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
756 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
757 // of be approximated: HASH has the same userspace visible api.
758 // However it cannot be used by ebpf programs in the same way.
759 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
760 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
761 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
762 // programs as being 5.4+...
763 type = BPF_MAP_TYPE_HASH;
764 }
765
766 // The .h file enforces that this is a power of two, and page size will
767 // also always be a power of two, so this logic is actually enough to
768 // force it to be a multiple of the page size, as required by the kernel.
769 unsigned int max_entries = md[i].max_entries;
770 if (type == BPF_MAP_TYPE_RINGBUF) {
771 if (max_entries < page_size) max_entries = page_size;
772 }
773
774 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
775 if (specified(selinux_context)) {
776 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
777 ALOGE("map %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
778 mapNames[i].c_str(), selinux_context, allowedDomainBitmask);
779 return -EINVAL;
780 }
781 ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
782 md[i].selinux_context, selinux_context, lookupSelinuxContext(selinux_context),
783 lookupPinSubdir(selinux_context));
784 }
785
786 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
787 if (unrecognized(pin_subdir)) return -ENOTDIR;
788 if (specified(pin_subdir)) {
789 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
790 ALOGE("map %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)",
791 mapNames[i].c_str(), pin_subdir, allowedDomainBitmask);
792 return -EINVAL;
793 }
794 ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
795 pin_subdir, lookupPinSubdir(pin_subdir));
796 }
797
798 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
799 // except that maps shared across .o's have empty <objName>
800 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
801 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
802 (md[i].shared ? "" : objName) + "_" + mapNames[i];
803 bool reuse = false;
804 unique_fd fd;
805 int saved_errno;
806
807 if (access(mapPinLoc.c_str(), F_OK) == 0) {
808 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
809 saved_errno = errno;
810 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
811 reuse = true;
812 } else {
813 union bpf_attr req = {
814 .map_type = type,
815 .key_size = md[i].key_size,
816 .value_size = md[i].value_size,
817 .max_entries = max_entries,
818 .map_flags = md[i].map_flags,
819 };
820 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
821 fd.reset(bpf(BPF_MAP_CREATE, req));
822 saved_errno = errno;
823 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
824 }
825
826 if (!fd.ok()) return -saved_errno;
827
828 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
829 // safety (since reuse code path is rare) run these checks even if we just created it.
830 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
831 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
832
833 if (!reuse) {
834 if (specified(selinux_context)) {
835 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
836 "tmp_map_" + objName + "_" + mapNames[i];
837 ret = bpfFdPin(fd, createLoc.c_str());
838 if (ret) {
839 int err = errno;
840 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
841 return -err;
842 }
843 ret = renameat2(AT_FDCWD, createLoc.c_str(),
844 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
845 if (ret) {
846 int err = errno;
847 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
848 err, strerror(err));
849 return -err;
850 }
851 } else {
852 ret = bpfFdPin(fd, mapPinLoc.c_str());
853 if (ret) {
854 int err = errno;
855 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
856 return -err;
857 }
858 }
859 ret = chmod(mapPinLoc.c_str(), md[i].mode);
860 if (ret) {
861 int err = errno;
862 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
863 strerror(err));
864 return -err;
865 }
866 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
867 if (ret) {
868 int err = errno;
869 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
870 ret, err, strerror(err));
871 return -err;
872 }
873 }
874
875 int mapId = bpfGetFdMapId(fd);
876 if (mapId == -1) {
877 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
878 } else {
879 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
880 }
881
882 mapFds.push_back(std::move(fd));
883 }
884
885 return ret;
886}
887
888/* For debugging, dump all instructions */
889static void dumpIns(char* ins, int size) {
890 for (int row = 0; row < size / 8; row++) {
891 ALOGE("%d: ", row);
892 for (int j = 0; j < 8; j++) {
893 ALOGE("%3x ", ins[(row * 8) + j]);
894 }
895 ALOGE("\n");
896 }
897}
898
899/* For debugging, dump all code sections from cs list */
900static void dumpAllCs(vector<codeSection>& cs) {
901 for (int i = 0; i < (int)cs.size(); i++) {
902 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
903 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
904 ALOGE("-----------");
905 }
906}
907
908static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
909 int insnIndex;
910 struct bpf_insn *insn, *insns;
911
912 insns = (struct bpf_insn*)(insnsPtr);
913
914 insnIndex = offset / sizeof(struct bpf_insn);
915 insn = &insns[insnIndex];
916
917 // Occasionally might be useful for relocation debugging, but pretty spammy
918 if (0) {
919 ALOGD("applying relo to instruction at byte offset: %llu, "
920 "insn offset %d, insn %llx",
921 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
922 }
923
924 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
925 ALOGE("Dumping all instructions till ins %d", insnIndex);
926 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
927 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
928 return;
929 }
930
931 insn->imm = fd;
932 insn->src_reg = BPF_PSEUDO_MAP_FD;
933}
934
935static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
936 vector<string> mapNames;
937
938 int ret = getSectionSymNames(elfFile, "maps", mapNames);
939 if (ret) return;
940
941 for (int k = 0; k != (int)cs.size(); k++) {
942 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
943 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
944
945 for (int i = 0; i < n_rel; i++) {
946 int symIndex = ELF64_R_SYM(rel[i].r_info);
947 string symName;
948
949 ret = getSymNameByIdx(elfFile, symIndex, symName);
950 if (ret) return;
951
952 /* Find the map fd and apply relo */
953 for (int j = 0; j < (int)mapNames.size(); j++) {
954 if (!mapNames[j].compare(symName)) {
955 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
956 break;
957 }
958 }
959 }
960 }
961}
962
963static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
964 const char* prefix, const unsigned long long allowedDomainBitmask) {
965 unsigned kvers = kernelVersion();
966
967 if (!kvers) {
968 ALOGE("unable to get kernel version");
969 return -EINVAL;
970 }
971
972 string objName = pathToObjName(string(elfPath));
973
974 for (int i = 0; i < (int)cs.size(); i++) {
975 unique_fd& fd = cs[i].prog_fd;
976 int ret;
977 string name = cs[i].name;
978
979 if (!cs[i].prog_def.has_value()) {
980 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
981 return -EINVAL;
982 }
983
984 unsigned min_kver = cs[i].prog_def->min_kver;
985 unsigned max_kver = cs[i].prog_def->max_kver;
986 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
987 max_kver, kvers);
988 if (kvers < min_kver) continue;
989 if (kvers >= max_kver) continue;
990
991 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
992 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
993 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
994 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
995 // Note: make sure to only check for unrecognized *after* verifying bpfloader
996 // version limits include this bpfloader's version.
997
998 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
999 bpfMinVer, bpfMaxVer);
1000 if (BPFLOADER_VERSION < bpfMinVer) continue;
1001 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
1002
1003 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1004 (cs[i].prog_def->ignore_on_user && isUser()) ||
1005 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1006 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1007 getBuildType().c_str());
1008 continue;
1009 }
1010
1011 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
1012 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
1013 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
1014 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
1015 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
1016 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
1017 continue;
1018 }
1019
1020 if (unrecognized(pin_subdir)) return -ENOTDIR;
1021
1022 if (specified(selinux_context)) {
1023 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
1024 ALOGE("prog %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
1025 name.c_str(), selinux_context, allowedDomainBitmask);
1026 return -EINVAL;
1027 }
1028 ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
1029 cs[i].prog_def->selinux_context, selinux_context,
1030 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1031 }
1032
1033 if (specified(pin_subdir)) {
1034 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
1035 ALOGE("prog %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)", name.c_str(),
1036 pin_subdir, allowedDomainBitmask);
1037 return -EINVAL;
1038 }
1039 ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
1040 cs[i].prog_def->pin_subdir, pin_subdir, lookupPinSubdir(pin_subdir));
1041 }
1042
1043 // strip any potential $foo suffix
1044 // this can be used to provide duplicate programs
1045 // conditionally loaded based on running kernel version
1046 name = name.substr(0, name.find_last_of('$'));
1047
1048 bool reuse = false;
1049 // Format of pin location is
1050 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1051 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1052 objName + '_' + string(name);
1053 if (access(progPinLoc.c_str(), F_OK) == 0) {
1054 fd.reset(retrieveProgram(progPinLoc.c_str()));
1055 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
1056 (!fd.ok() ? std::strerror(errno) : "no error"));
1057 reuse = true;
1058 } else {
1059 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1060
1061 union bpf_attr req = {
1062 .prog_type = cs[i].type,
1063 .kern_version = kvers,
1064 .license = ptr_to_u64(license.c_str()),
1065 .insns = ptr_to_u64(cs[i].data.data()),
1066 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
1067 .log_level = 1,
1068 .log_buf = ptr_to_u64(log_buf.data()),
1069 .log_size = static_cast<__u32>(log_buf.size()),
1070 .expected_attach_type = cs[i].expected_attach_type,
1071 };
1072 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1073 fd.reset(bpf(BPF_PROG_LOAD, req));
1074
1075 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
1076 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
1077
1078 if (!fd.ok()) {
1079 vector<string> lines = android::base::Split(log_buf.data(), "\n");
1080
1081 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1082 for (const auto& line : lines) ALOGW("%s", line.c_str());
1083 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1084
1085 if (cs[i].prog_def->optional) {
1086 ALOGW("failed program is marked optional - continuing...");
1087 continue;
1088 }
1089 ALOGE("non-optional program failed to load.");
1090 }
1091 }
1092
1093 if (!fd.ok()) return fd.get();
1094
1095 if (!reuse) {
1096 if (specified(selinux_context)) {
1097 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1098 "tmp_prog_" + objName + '_' + string(name);
1099 ret = bpfFdPin(fd, createLoc.c_str());
1100 if (ret) {
1101 int err = errno;
1102 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1103 return -err;
1104 }
1105 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1106 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1107 if (ret) {
1108 int err = errno;
1109 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1110 err, strerror(err));
1111 return -err;
1112 }
1113 } else {
1114 ret = bpfFdPin(fd, progPinLoc.c_str());
1115 if (ret) {
1116 int err = errno;
1117 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1118 return -err;
1119 }
1120 }
1121 if (chmod(progPinLoc.c_str(), 0440)) {
1122 int err = errno;
1123 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1124 return -err;
1125 }
1126 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1127 (gid_t)cs[i].prog_def->gid)) {
1128 int err = errno;
1129 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1130 cs[i].prog_def->gid, err, strerror(err));
1131 return -err;
1132 }
1133 }
1134
1135 int progId = bpfGetFdProgId(fd);
1136 if (progId == -1) {
1137 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
1138 } else {
1139 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
1140 }
1141 }
1142
1143 return 0;
1144}
1145
1146int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
1147 vector<char> license;
1148 vector<char> critical;
1149 vector<codeSection> cs;
1150 vector<unique_fd> mapFds;
1151 int ret;
1152
1153 if (!isCritical) return -1;
1154 *isCritical = false;
1155
1156 ifstream elfFile(elfPath, ios::in | ios::binary);
1157 if (!elfFile.is_open()) return -1;
1158
1159 ret = readSectionByName("critical", elfFile, critical);
1160 *isCritical = !ret;
1161
1162 ret = readSectionByName("license", elfFile, license);
1163 if (ret) {
1164 ALOGE("Couldn't find license in %s", elfPath);
1165 return ret;
1166 } else {
1167 ALOGD("Loading %s%s ELF object %s with license %s",
1168 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
1169 elfPath, (char*)license.data());
1170 }
1171
1172 // the following default values are for bpfloader V0.0 format which does not include them
1173 unsigned int bpfLoaderMinVer =
1174 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1175 unsigned int bpfLoaderMaxVer =
1176 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
1177 unsigned int bpfLoaderMinRequiredVer =
1178 readSectionUint("bpfloader_min_required_ver", elfFile, 0);
1179 size_t sizeOfBpfMapDef =
1180 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1181 size_t sizeOfBpfProgDef =
1182 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1183
1184 // inclusive lower bound check
1185 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
1186 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
1187 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
1188 return 0;
1189 }
1190
1191 // exclusive upper bound check
1192 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
1193 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
1194 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
1195 return 0;
1196 }
1197
1198 if (BPFLOADER_VERSION < bpfLoaderMinRequiredVer) {
1199 ALOGI("BpfLoader version 0x%05x failing due to ELF object %s with required min ver 0x%05x",
1200 BPFLOADER_VERSION, elfPath, bpfLoaderMinRequiredVer);
1201 return -1;
1202 }
1203
1204 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
1205 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1206
1207 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
1208 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
1209 DEFAULT_SIZEOF_BPF_MAP_DEF);
1210 return -1;
1211 }
1212
1213 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
1214 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
1215 DEFAULT_SIZEOF_BPF_PROG_DEF);
1216 return -1;
1217 }
1218
1219 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, location.allowedProgTypes,
1220 location.allowedProgTypesLength);
1221 if (ret) {
1222 ALOGE("Couldn't read all code sections in %s", elfPath);
1223 return ret;
1224 }
1225
1226 /* Just for future debugging */
1227 if (0) dumpAllCs(cs);
1228
1229 ret = createMaps(elfPath, elfFile, mapFds, location.prefix, location.allowedDomainBitmask,
1230 sizeOfBpfMapDef);
1231 if (ret) {
1232 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1233 return ret;
1234 }
1235
1236 for (int i = 0; i < (int)mapFds.size(); i++)
1237 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1238
1239 applyMapRelo(elfFile, mapFds, cs);
1240
1241 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix,
1242 location.allowedDomainBitmask);
1243 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1244
1245 return ret;
1246}
1247
1248} // namespace bpf
1249} // namespace android