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