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