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