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