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