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