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