blob: 3e84733c4fd49f4979180383a079b7839ad1c51d [file] [log] [blame]
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001/*
Maciej Żenczykowski49140b92024-08-07 15:06:07 -07002 * Copyright (C) 2018-2024 The Android Open Source Project
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -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 Żenczykowski49140b92024-08-07 15:06:07 -070017#define LOG_TAG "NetBpfLoad"
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070018
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070019#include <arpa/inet.h>
20#include <cstdlib>
21#include <dirent.h>
22#include <elf.h>
23#include <errno.h>
24#include <error.h>
25#include <fcntl.h>
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070026#include <fstream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070027#include <inttypes.h>
28#include <iostream>
29#include <linux/bpf.h>
30#include <linux/elf.h>
31#include <linux/unistd.h>
32#include <log/log.h>
33#include <net/if.h>
34#include <optional>
35#include <stdint.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <string>
40#include <sys/mman.h>
41#include <sys/socket.h>
42#include <sys/stat.h>
43#include <sys/types.h>
44#include <sys/utsname.h>
45#include <sys/wait.h>
46#include <sysexits.h>
47#include <unistd.h>
48#include <unordered_map>
49#include <vector>
50
51#include <android-base/cmsg.h>
52#include <android-base/file.h>
53#include <android-base/logging.h>
54#include <android-base/macros.h>
55#include <android-base/properties.h>
56#include <android-base/stringprintf.h>
57#include <android-base/strings.h>
58#include <android-base/unique_fd.h>
59#include <android/api-level.h>
60
61#include "BpfSyscallWrappers.h"
62#include "bpf/BpfUtils.h"
63#include "bpf/bpf_map_def.h"
64
65using android::base::EndsWith;
66using android::base::StartsWith;
67using android::base::unique_fd;
68using std::ifstream;
69using std::ios;
70using std::optional;
71using std::string;
72using std::vector;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070073
74namespace android {
75namespace bpf {
76
77// Bpf programs may specify per-program & per-map selinux_context and pin_subdir.
78//
79// The BpfLoader needs to convert these bpf.o specified strings into an enum
80// for internal use (to check that valid values were specified for the specific
81// location of the bpf.o file).
82//
83// It also needs to map selinux_context's into pin_subdir's.
84// This is because of how selinux_context is actually implemented via pin+rename.
85//
86// Thus 'domain' enumerates all selinux_context's/pin_subdir's that the BpfLoader
87// is aware of. Thus there currently needs to be a 1:1 mapping between the two.
88//
89enum class domain : int {
90 unrecognized = -1, // invalid for this version of the bpfloader
91 unspecified = 0, // means just use the default for that specific pin location
92 tethering, // (S+) fs_bpf_tethering /sys/fs/bpf/tethering
93 net_private, // (T+) fs_bpf_net_private /sys/fs/bpf/net_private
94 net_shared, // (T+) fs_bpf_net_shared /sys/fs/bpf/net_shared
95 netd_readonly, // (T+) fs_bpf_netd_readonly /sys/fs/bpf/netd_readonly
96 netd_shared, // (T+) fs_bpf_netd_shared /sys/fs/bpf/netd_shared
97};
98
99// Note: this does not include domain::unrecognized, but does include domain::unspecified
100static constexpr domain AllDomains[] = {
101 domain::unspecified,
102 domain::tethering,
103 domain::net_private,
104 domain::net_shared,
105 domain::netd_readonly,
106 domain::netd_shared,
107};
108
109static constexpr bool unrecognized(domain d) {
110 return d == domain::unrecognized;
111}
112
113// Note: this doesn't handle unrecognized, handle it first.
114static constexpr bool specified(domain d) {
115 return d != domain::unspecified;
116}
117
118struct Location {
119 const char* const dir = "";
120 const char* const prefix = "";
121};
122
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700123// Returns the build type string (from ro.build.type).
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700124const std::string& getBuildType() {
125 static std::string t = android::base::GetProperty("ro.build.type", "unknown");
126 return t;
127}
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700128
129// The following functions classify the 3 Android build types.
130inline bool isEng() {
131 return getBuildType() == "eng";
132}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700133
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700134inline bool isUser() {
135 return getBuildType() == "user";
136}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700137
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700138inline bool isUserdebug() {
139 return getBuildType() == "userdebug";
140}
141
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700142#define BPF_FS_PATH "/sys/fs/bpf/"
143
144// Size of the BPF log buffer for verifier logging
145#define BPF_LOAD_LOG_SZ 0xfffff
146
147// Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
148#define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
149
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700150static unsigned int page_size = static_cast<unsigned int>(getpagesize());
151
152constexpr const char* lookupSelinuxContext(const domain d, const char* const unspecified = "") {
153 switch (d) {
154 case domain::unspecified: return unspecified;
155 case domain::tethering: return "fs_bpf_tethering";
156 case domain::net_private: return "fs_bpf_net_private";
157 case domain::net_shared: return "fs_bpf_net_shared";
158 case domain::netd_readonly: return "fs_bpf_netd_readonly";
159 case domain::netd_shared: return "fs_bpf_netd_shared";
160 default: return "(unrecognized)";
161 }
162}
163
164domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
165 for (domain d : AllDomains) {
166 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
167 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
168 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
169 }
170 ALOGW("ignoring unrecognized selinux_context '%-32s'", s);
171 // We should return 'unrecognized' here, however: returning unspecified will
172 // result in the system simply using the default context, which in turn
173 // will allow future expansion by adding more restrictive selinux types.
174 // Older bpfloader will simply ignore that, and use the less restrictive default.
175 // This does mean you CANNOT later add a *less* restrictive type than the default.
176 //
177 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
178 return domain::unspecified;
179}
180
181constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
182 switch (d) {
183 case domain::unspecified: return unspecified;
184 case domain::tethering: return "tethering/";
185 case domain::net_private: return "net_private/";
186 case domain::net_shared: return "net_shared/";
187 case domain::netd_readonly: return "netd_readonly/";
188 case domain::netd_shared: return "netd_shared/";
189 default: return "(unrecognized)";
190 }
191};
192
193domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
194 for (domain d : AllDomains) {
195 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
196 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
197 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
198 }
199 ALOGE("unrecognized pin_subdir '%-32s'", s);
200 // pin_subdir affects the object's full pathname,
201 // and thus using the default would change the location and thus our code's ability to find it,
202 // hence this seems worth treating as a true error condition.
203 //
204 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
205 // However, our callers will treat this as an error, and stop loading the specific .o,
206 // which will fail bpfloader if the .o is marked critical.
207 return domain::unrecognized;
208}
209
210static string pathToObjName(const string& path) {
211 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
212 string filename = android::base::Split(path, "/").back();
213 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
214 string name = filename.substr(0, filename.find_last_of('.'));
215 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
216 // this can be used to provide duplicate programs (mux based on the bpfloader version)
217 return name.substr(0, name.find_last_of('@'));
218}
219
220typedef struct {
221 const char* name;
222 enum bpf_prog_type type;
223 enum bpf_attach_type expected_attach_type;
224} sectionType;
225
226/*
227 * Map section name prefixes to program types, the section name will be:
228 * SECTION(<prefix>/<name-of-program>)
229 * For example:
230 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
231 * is the name of the program, and tracepoint is the type.
232 *
233 * However, be aware that you should not be directly using the SECTION() macro.
234 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
235 *
236 * Programs shipped inside the tethering apex should be limited to networking stuff,
237 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
238 * since they are less stable abi/api and may conflict with platform uses of bpf.
239 */
240sectionType sectionNameTypes[] = {
241 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
242 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
243 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB, BPF_ATTACH_TYPE_UNSPEC},
244 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_ATTACH_TYPE_UNSPEC},
245 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
246 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
247 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
248 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
249 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
250 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
251 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
252 {"lwt_in/", BPF_PROG_TYPE_LWT_IN, BPF_ATTACH_TYPE_UNSPEC},
253 {"lwt_out/", BPF_PROG_TYPE_LWT_OUT, BPF_ATTACH_TYPE_UNSPEC},
254 {"lwt_seg6local/", BPF_PROG_TYPE_LWT_SEG6LOCAL, BPF_ATTACH_TYPE_UNSPEC},
255 {"lwt_xmit/", BPF_PROG_TYPE_LWT_XMIT, BPF_ATTACH_TYPE_UNSPEC},
256 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
257 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
258 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
259 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
260 {"schedact/", BPF_PROG_TYPE_SCHED_ACT, BPF_ATTACH_TYPE_UNSPEC},
261 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS, BPF_ATTACH_TYPE_UNSPEC},
262 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
263 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
264 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
265 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
266 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
267 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
268 {"xdp/", BPF_PROG_TYPE_XDP, BPF_ATTACH_TYPE_UNSPEC},
269};
270
271typedef struct {
272 enum bpf_prog_type type;
273 enum bpf_attach_type expected_attach_type;
274 string name;
275 vector<char> data;
276 vector<char> rel_data;
277 optional<struct bpf_prog_def> prog_def;
278
279 unique_fd prog_fd; /* fd after loading */
280} codeSection;
281
282static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
283 elfFile.seekg(0);
284 if (elfFile.fail()) return -1;
285
286 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
287
288 return 0;
289}
290
291/* Reads all section header tables into an Shdr array */
292static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
293 Elf64_Ehdr eh;
294 int ret = 0;
295
296 ret = readElfHeader(elfFile, &eh);
297 if (ret) return ret;
298
299 elfFile.seekg(eh.e_shoff);
300 if (elfFile.fail()) return -1;
301
302 /* Read shdr table entries */
303 shTable.resize(eh.e_shnum);
304
305 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
306
307 return 0;
308}
309
310/* Read a section by its index - for ex to get sec hdr strtab blob */
311static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
312 vector<Elf64_Shdr> shTable;
313 int ret = readSectionHeadersAll(elfFile, shTable);
314 if (ret) return ret;
315
316 elfFile.seekg(shTable[id].sh_offset);
317 if (elfFile.fail()) return -1;
318
319 sec.resize(shTable[id].sh_size);
320 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
321
322 return 0;
323}
324
325/* Read whole section header string table */
326static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
327 Elf64_Ehdr eh;
328 int ret = readElfHeader(elfFile, &eh);
329 if (ret) return ret;
330
331 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
332 if (ret) return ret;
333
334 return 0;
335}
336
337/* Get name from offset in strtab */
338static int getSymName(ifstream& elfFile, int nameOff, string& name) {
339 int ret;
340 vector<char> secStrTab;
341
342 ret = readSectionHeaderStrtab(elfFile, secStrTab);
343 if (ret) return ret;
344
345 if (nameOff >= (int)secStrTab.size()) return -1;
346
347 name = string((char*)secStrTab.data() + nameOff);
348 return 0;
349}
350
351/* Reads a full section by name - example to get the GPL license */
352static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
353 vector<char> secStrTab;
354 vector<Elf64_Shdr> shTable;
355 int ret;
356
357 ret = readSectionHeadersAll(elfFile, shTable);
358 if (ret) return ret;
359
360 ret = readSectionHeaderStrtab(elfFile, secStrTab);
361 if (ret) return ret;
362
363 for (int i = 0; i < (int)shTable.size(); i++) {
364 char* secname = secStrTab.data() + shTable[i].sh_name;
365 if (!secname) continue;
366
367 if (!strcmp(secname, name)) {
368 vector<char> dataTmp;
369 dataTmp.resize(shTable[i].sh_size);
370
371 elfFile.seekg(shTable[i].sh_offset);
372 if (elfFile.fail()) return -1;
373
374 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
375
376 data = dataTmp;
377 return 0;
378 }
379 }
380 return -2;
381}
382
383unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
384 vector<char> theBytes;
385 int ret = readSectionByName(name, elfFile, theBytes);
386 if (ret) {
387 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
388 return defVal;
389 } else if (theBytes.size() < sizeof(unsigned int)) {
390 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
391 return defVal;
392 } else {
393 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
394 unsigned int value = static_cast<unsigned char>(theBytes[3]);
395 value <<= 8;
396 value += static_cast<unsigned char>(theBytes[2]);
397 value <<= 8;
398 value += static_cast<unsigned char>(theBytes[1]);
399 value <<= 8;
400 value += static_cast<unsigned char>(theBytes[0]);
401 ALOGI("Section %s value is %u [0x%x]", name, value, value);
402 return value;
403 }
404}
405
406static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
407 int ret;
408 vector<Elf64_Shdr> shTable;
409
410 ret = readSectionHeadersAll(elfFile, shTable);
411 if (ret) return ret;
412
413 for (int i = 0; i < (int)shTable.size(); i++) {
414 if ((int)shTable[i].sh_type != type) continue;
415
416 vector<char> dataTmp;
417 dataTmp.resize(shTable[i].sh_size);
418
419 elfFile.seekg(shTable[i].sh_offset);
420 if (elfFile.fail()) return -1;
421
422 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
423
424 data = dataTmp;
425 return 0;
426 }
427 return -2;
428}
429
430static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
431 return (a.st_value < b.st_value);
432}
433
434static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
435 int ret, numElems;
436 Elf64_Sym* buf;
437 vector<char> secData;
438
439 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
440 if (ret) return ret;
441
442 buf = (Elf64_Sym*)secData.data();
443 numElems = (secData.size() / sizeof(Elf64_Sym));
444 data.assign(buf, buf + numElems);
445
446 if (sort) std::sort(data.begin(), data.end(), symCompare);
447 return 0;
448}
449
450static enum bpf_prog_type getSectionType(string& name) {
451 for (auto& snt : sectionNameTypes)
452 if (StartsWith(name, snt.name)) return snt.type;
453
454 return BPF_PROG_TYPE_UNSPEC;
455}
456
457static enum bpf_attach_type getExpectedAttachType(string& name) {
458 for (auto& snt : sectionNameTypes)
459 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
460 return BPF_ATTACH_TYPE_UNSPEC;
461}
462
463/*
464static string getSectionName(enum bpf_prog_type type)
465{
466 for (auto& snt : sectionNameTypes)
467 if (snt.type == type)
468 return string(snt.name);
469
470 return "UNKNOWN SECTION NAME " + std::to_string(type);
471}
472*/
473
474static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
475 size_t sizeOfBpfProgDef) {
476 vector<char> pdData;
477 int ret = readSectionByName("progs", elfFile, pdData);
478 if (ret) return ret;
479
480 if (pdData.size() % sizeOfBpfProgDef) {
481 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
482 pdData.size(), sizeOfBpfProgDef);
483 return -1;
484 };
485
486 int progCount = pdData.size() / sizeOfBpfProgDef;
487 pd.resize(progCount);
488 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
489
490 const char* dataPtr = pdData.data();
491 for (auto& p : pd) {
492 // First we zero initialize
493 memset(&p, 0, sizeof(p));
494 // Then we set non-zero defaults
495 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
496 // Then we copy over the structure prefix from the ELF file.
497 memcpy(&p, dataPtr, trimmedSize);
498 // Move to next struct in the ELF file
499 dataPtr += sizeOfBpfProgDef;
500 }
501 return 0;
502}
503
504static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
505 optional<unsigned> symbolType = std::nullopt) {
506 int ret;
507 string name;
508 vector<Elf64_Sym> symtab;
509 vector<Elf64_Shdr> shTable;
510
511 ret = readSymTab(elfFile, 1 /* sort */, symtab);
512 if (ret) return ret;
513
514 /* Get index of section */
515 ret = readSectionHeadersAll(elfFile, shTable);
516 if (ret) return ret;
517
518 int sec_idx = -1;
519 for (int i = 0; i < (int)shTable.size(); i++) {
520 ret = getSymName(elfFile, shTable[i].sh_name, name);
521 if (ret) return ret;
522
523 if (!name.compare(sectionName)) {
524 sec_idx = i;
525 break;
526 }
527 }
528
529 /* No section found with matching name*/
530 if (sec_idx == -1) {
531 ALOGW("No %s section could be found in elf object", sectionName.c_str());
532 return -1;
533 }
534
535 for (int i = 0; i < (int)symtab.size(); i++) {
536 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
537
538 if (symtab[i].st_shndx == sec_idx) {
539 string s;
540 ret = getSymName(elfFile, symtab[i].st_name, s);
541 if (ret) return ret;
542 names.push_back(s);
543 }
544 }
545
546 return 0;
547}
548
549/* Read a section by its index - for ex to get sec hdr strtab blob */
550static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef) {
551 vector<Elf64_Shdr> shTable;
552 int entries, ret = 0;
553
554 ret = readSectionHeadersAll(elfFile, shTable);
555 if (ret) return ret;
556 entries = shTable.size();
557
558 vector<struct bpf_prog_def> pd;
559 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
560 if (ret) return ret;
561 vector<string> progDefNames;
562 ret = getSectionSymNames(elfFile, "progs", progDefNames);
563 if (!pd.empty() && ret) return ret;
564
565 for (int i = 0; i < entries; i++) {
566 string name;
567 codeSection cs_temp;
568 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
569
570 ret = getSymName(elfFile, shTable[i].sh_name, name);
571 if (ret) return ret;
572
573 enum bpf_prog_type ptype = getSectionType(name);
574
575 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
576
577 // This must be done before '/' is replaced with '_'.
578 cs_temp.expected_attach_type = getExpectedAttachType(name);
579
580 string oldName = name;
581
582 // convert all slashes to underscores
583 std::replace(name.begin(), name.end(), '/', '_');
584
585 cs_temp.type = ptype;
586 cs_temp.name = name;
587
588 ret = readSectionByIdx(elfFile, i, cs_temp.data);
589 if (ret) return ret;
590 ALOGV("Loaded code section %d (%s)", i, name.c_str());
591
592 vector<string> csSymNames;
593 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
594 if (ret || !csSymNames.size()) return ret;
595 for (size_t i = 0; i < progDefNames.size(); ++i) {
596 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
597 cs_temp.prog_def = pd[i];
598 break;
599 }
600 }
601
602 /* Check for rel section */
603 if (cs_temp.data.size() > 0 && i < entries) {
604 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
605 if (ret) return ret;
606
607 if (name == (".rel" + oldName)) {
608 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
609 if (ret) return ret;
610 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
611 }
612 }
613
614 if (cs_temp.data.size() > 0) {
615 cs.push_back(std::move(cs_temp));
616 ALOGV("Adding section %d to cs list", i);
617 }
618 }
619 return 0;
620}
621
622static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
623 vector<Elf64_Sym> symtab;
624 int ret = 0;
625
626 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
627 if (ret) return ret;
628
629 if (index >= (int)symtab.size()) return -1;
630
631 return getSymName(elfFile, symtab[index].st_name, name);
632}
633
634static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
635 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
636 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
637 // so on 4.9-T kernels just pretend the map matches our expectations.
638 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
639 // This is because the primary failure mode we're trying to detect here
640 // is either a source code misconfiguration (which is likely kernel independent)
641 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
642 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
643
644 // Assuming fd is a valid Bpf Map file descriptor then
645 // all the following should always succeed on a 4.14+ kernel.
646 // If they somehow do fail, they'll return -1 (and set errno),
647 // which should then cause (among others) a key_size mismatch.
648 int fd_type = bpfGetFdMapType(fd);
649 int fd_key_size = bpfGetFdKeySize(fd);
650 int fd_value_size = bpfGetFdValueSize(fd);
651 int fd_max_entries = bpfGetFdMaxEntries(fd);
652 int fd_map_flags = bpfGetFdMapFlags(fd);
653
654 // DEVMAPs are readonly from the bpf program side's point of view, as such
655 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
656 int desired_map_flags = (int)mapDef.map_flags;
657 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
658 desired_map_flags |= BPF_F_RDONLY_PROG;
659
660 // The .h file enforces that this is a power of two, and page size will
661 // also always be a power of two, so this logic is actually enough to
662 // force it to be a multiple of the page size, as required by the kernel.
663 unsigned int desired_max_entries = mapDef.max_entries;
664 if (type == BPF_MAP_TYPE_RINGBUF) {
665 if (desired_max_entries < page_size) desired_max_entries = page_size;
666 }
667
668 // The following checks should *never* trigger, if one of them somehow does,
669 // it probably means a bpf .o file has been changed/replaced at runtime
670 // and bpfloader was manually rerun (normally it should only run *once*
671 // early during the boot process).
672 // Another possibility is that something is misconfigured in the code:
673 // most likely a shared map is declared twice differently.
674 // But such a change should never be checked into the source tree...
675 if ((fd_type == type) &&
676 (fd_key_size == (int)mapDef.key_size) &&
677 (fd_value_size == (int)mapDef.value_size) &&
678 (fd_max_entries == (int)desired_max_entries) &&
679 (fd_map_flags == desired_map_flags)) {
680 return true;
681 }
682
683 ALOGE("bpf map name %s mismatch: desired/found: "
684 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
685 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
686 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
687 return false;
688}
689
690static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
691 const char* prefix, const size_t sizeOfBpfMapDef,
692 const unsigned int bpfloader_ver) {
693 int ret;
694 vector<char> mdData;
695 vector<struct bpf_map_def> md;
696 vector<string> mapNames;
697 string objName = pathToObjName(string(elfPath));
698
699 ret = readSectionByName("maps", elfFile, mdData);
700 if (ret == -2) return 0; // no maps to read
701 if (ret) return ret;
702
703 if (mdData.size() % sizeOfBpfMapDef) {
704 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
705 mdData.size(), sizeOfBpfMapDef);
706 return -1;
707 };
708
709 int mapCount = mdData.size() / sizeOfBpfMapDef;
710 md.resize(mapCount);
711 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
712
713 const char* dataPtr = mdData.data();
714 for (auto& m : md) {
715 // First we zero initialize
716 memset(&m, 0, sizeof(m));
717 // Then we set non-zero defaults
718 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
719 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
720 // Then we copy over the structure prefix from the ELF file.
721 memcpy(&m, dataPtr, trimmedSize);
722 // Move to next struct in the ELF file
723 dataPtr += sizeOfBpfMapDef;
724 }
725
726 ret = getSectionSymNames(elfFile, "maps", mapNames);
727 if (ret) return ret;
728
729 unsigned kvers = kernelVersion();
730
731 for (int i = 0; i < (int)mapNames.size(); i++) {
732 if (md[i].zero != 0) abort();
733
734 if (bpfloader_ver < md[i].bpfloader_min_ver) {
735 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
736 md[i].bpfloader_min_ver);
737 mapFds.push_back(unique_fd());
738 continue;
739 }
740
741 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
742 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
743 md[i].bpfloader_max_ver);
744 mapFds.push_back(unique_fd());
745 continue;
746 }
747
748 if (kvers < md[i].min_kver) {
749 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
750 mapNames[i].c_str(), kvers, md[i].min_kver);
751 mapFds.push_back(unique_fd());
752 continue;
753 }
754
755 if (kvers >= md[i].max_kver) {
756 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
757 mapNames[i].c_str(), kvers, md[i].max_kver);
758 mapFds.push_back(unique_fd());
759 continue;
760 }
761
762 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
763 (md[i].ignore_on_userdebug && isUserdebug())) {
764 ALOGI("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
765 getBuildType().c_str());
766 mapFds.push_back(unique_fd());
767 continue;
768 }
769
770 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
771 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
772 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
773 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
774 (isRiscV() && md[i].ignore_on_riscv64)) {
775 ALOGI("skipping map %s which is ignored on %s", mapNames[i].c_str(),
776 describeArch());
777 mapFds.push_back(unique_fd());
778 continue;
779 }
780
781 enum bpf_map_type type = md[i].type;
782 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
783 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
784 // of be approximated: ARRAY has the same userspace api, though it is not usable
785 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
786 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
787 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
788 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
789 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
790 type = BPF_MAP_TYPE_ARRAY;
791 }
792 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
793 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
794 // of be approximated: HASH has the same userspace visible api.
795 // However it cannot be used by ebpf programs in the same way.
796 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
797 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
798 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
799 // programs as being 5.4+...
800 type = BPF_MAP_TYPE_HASH;
801 }
802
803 // The .h file enforces that this is a power of two, and page size will
804 // also always be a power of two, so this logic is actually enough to
805 // force it to be a multiple of the page size, as required by the kernel.
806 unsigned int max_entries = md[i].max_entries;
807 if (type == BPF_MAP_TYPE_RINGBUF) {
808 if (max_entries < page_size) max_entries = page_size;
809 }
810
811 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
812 if (specified(selinux_context)) {
813 ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
814 md[i].selinux_context, static_cast<int>(selinux_context),
815 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
816 }
817
818 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
819 if (unrecognized(pin_subdir)) return -ENOTDIR;
820 if (specified(pin_subdir)) {
821 ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
822 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
823 }
824
825 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
826 // except that maps shared across .o's have empty <objName>
827 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
828 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
829 (md[i].shared ? "" : objName) + "_" + mapNames[i];
830 bool reuse = false;
831 unique_fd fd;
832 int saved_errno;
833
834 if (access(mapPinLoc.c_str(), F_OK) == 0) {
835 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
836 saved_errno = errno;
837 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
838 reuse = true;
839 } else {
840 union bpf_attr req = {
841 .map_type = type,
842 .key_size = md[i].key_size,
843 .value_size = md[i].value_size,
844 .max_entries = max_entries,
845 .map_flags = md[i].map_flags,
846 };
847 if (isAtLeastKernelVersion(4, 15, 0))
848 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
849 fd.reset(bpf(BPF_MAP_CREATE, req));
850 saved_errno = errno;
851 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
852 }
853
854 if (!fd.ok()) return -saved_errno;
855
856 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
857 // safety (since reuse code path is rare) run these checks even if we just created it.
858 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
859 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
860
861 if (!reuse) {
862 if (specified(selinux_context)) {
863 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
864 "tmp_map_" + objName + "_" + mapNames[i];
865 ret = bpfFdPin(fd, createLoc.c_str());
866 if (ret) {
867 int err = errno;
868 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
869 return -err;
870 }
871 ret = renameat2(AT_FDCWD, createLoc.c_str(),
872 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
873 if (ret) {
874 int err = errno;
875 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
876 err, strerror(err));
877 return -err;
878 }
879 } else {
880 ret = bpfFdPin(fd, mapPinLoc.c_str());
881 if (ret) {
882 int err = errno;
883 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
884 return -err;
885 }
886 }
887 ret = chmod(mapPinLoc.c_str(), md[i].mode);
888 if (ret) {
889 int err = errno;
890 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
891 strerror(err));
892 return -err;
893 }
894 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
895 if (ret) {
896 int err = errno;
897 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
898 ret, err, strerror(err));
899 return -err;
900 }
901 }
902
903 int mapId = bpfGetFdMapId(fd);
904 if (mapId == -1) {
905 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
906 } else {
907 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
908 }
909
910 mapFds.push_back(std::move(fd));
911 }
912
913 return ret;
914}
915
916/* For debugging, dump all instructions */
917static void dumpIns(char* ins, int size) {
918 for (int row = 0; row < size / 8; row++) {
919 ALOGE("%d: ", row);
920 for (int j = 0; j < 8; j++) {
921 ALOGE("%3x ", ins[(row * 8) + j]);
922 }
923 ALOGE("\n");
924 }
925}
926
927/* For debugging, dump all code sections from cs list */
928static void dumpAllCs(vector<codeSection>& cs) {
929 for (int i = 0; i < (int)cs.size(); i++) {
930 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
931 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
932 ALOGE("-----------");
933 }
934}
935
936static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
937 int insnIndex;
938 struct bpf_insn *insn, *insns;
939
940 insns = (struct bpf_insn*)(insnsPtr);
941
942 insnIndex = offset / sizeof(struct bpf_insn);
943 insn = &insns[insnIndex];
944
945 // Occasionally might be useful for relocation debugging, but pretty spammy
946 if (0) {
947 ALOGV("applying relo to instruction at byte offset: %llu, "
948 "insn offset %d, insn %llx",
949 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
950 }
951
952 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
953 ALOGE("Dumping all instructions till ins %d", insnIndex);
954 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
955 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
956 return;
957 }
958
959 insn->imm = fd;
960 insn->src_reg = BPF_PSEUDO_MAP_FD;
961}
962
963static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
964 vector<string> mapNames;
965
966 int ret = getSectionSymNames(elfFile, "maps", mapNames);
967 if (ret) return;
968
969 for (int k = 0; k != (int)cs.size(); k++) {
970 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
971 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
972
973 for (int i = 0; i < n_rel; i++) {
974 int symIndex = ELF64_R_SYM(rel[i].r_info);
975 string symName;
976
977 ret = getSymNameByIdx(elfFile, symIndex, symName);
978 if (ret) return;
979
980 /* Find the map fd and apply relo */
981 for (int j = 0; j < (int)mapNames.size(); j++) {
982 if (!mapNames[j].compare(symName)) {
983 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
984 break;
985 }
986 }
987 }
988 }
989}
990
991static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
992 const char* prefix, const unsigned int bpfloader_ver) {
993 unsigned kvers = kernelVersion();
994
995 if (!kvers) {
996 ALOGE("unable to get kernel version");
997 return -EINVAL;
998 }
999
1000 string objName = pathToObjName(string(elfPath));
1001
1002 for (int i = 0; i < (int)cs.size(); i++) {
1003 unique_fd& fd = cs[i].prog_fd;
1004 int ret;
1005 string name = cs[i].name;
1006
1007 if (!cs[i].prog_def.has_value()) {
1008 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
1009 return -EINVAL;
1010 }
1011
1012 unsigned min_kver = cs[i].prog_def->min_kver;
1013 unsigned max_kver = cs[i].prog_def->max_kver;
1014 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1015 max_kver, kvers);
1016 if (kvers < min_kver) continue;
1017 if (kvers >= max_kver) continue;
1018
1019 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1020 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1021 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1022 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
1023 // Note: make sure to only check for unrecognized *after* verifying bpfloader
1024 // version limits include this bpfloader's version.
1025
1026 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
1027 bpfMinVer, bpfMaxVer);
1028 if (bpfloader_ver < bpfMinVer) continue;
1029 if (bpfloader_ver >= bpfMaxVer) continue;
1030
1031 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1032 (cs[i].prog_def->ignore_on_user && isUser()) ||
1033 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1034 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1035 getBuildType().c_str());
1036 continue;
1037 }
1038
1039 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
1040 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
1041 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
1042 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
1043 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
1044 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
1045 continue;
1046 }
1047
1048 if (unrecognized(pin_subdir)) return -ENOTDIR;
1049
1050 if (specified(selinux_context)) {
1051 ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
1052 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
1053 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1054 }
1055
1056 if (specified(pin_subdir)) {
1057 ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
1058 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
1059 lookupPinSubdir(pin_subdir));
1060 }
1061
1062 // strip any potential $foo suffix
1063 // this can be used to provide duplicate programs
1064 // conditionally loaded based on running kernel version
1065 name = name.substr(0, name.find_last_of('$'));
1066
1067 bool reuse = false;
1068 // Format of pin location is
1069 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1070 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1071 objName + '_' + string(name);
1072 if (access(progPinLoc.c_str(), F_OK) == 0) {
1073 fd.reset(retrieveProgram(progPinLoc.c_str()));
1074 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
1075 (!fd.ok() ? std::strerror(errno) : "no error"));
1076 reuse = true;
1077 } else {
1078 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1079
1080 union bpf_attr req = {
1081 .prog_type = cs[i].type,
1082 .kern_version = kvers,
1083 .license = ptr_to_u64(license.c_str()),
1084 .insns = ptr_to_u64(cs[i].data.data()),
1085 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
1086 .log_level = 1,
1087 .log_buf = ptr_to_u64(log_buf.data()),
1088 .log_size = static_cast<__u32>(log_buf.size()),
1089 .expected_attach_type = cs[i].expected_attach_type,
1090 };
1091 if (isAtLeastKernelVersion(4, 15, 0))
1092 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1093 fd.reset(bpf(BPF_PROG_LOAD, req));
1094
1095 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
1096 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
1097
1098 if (!fd.ok()) {
1099 vector<string> lines = android::base::Split(log_buf.data(), "\n");
1100
1101 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1102 for (const auto& line : lines) ALOGW("%s", line.c_str());
1103 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1104
1105 if (cs[i].prog_def->optional) {
1106 ALOGW("failed program is marked optional - continuing...");
1107 continue;
1108 }
1109 ALOGE("non-optional program failed to load.");
1110 }
1111 }
1112
1113 if (!fd.ok()) return fd.get();
1114
1115 if (!reuse) {
1116 if (specified(selinux_context)) {
1117 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1118 "tmp_prog_" + objName + '_' + string(name);
1119 ret = bpfFdPin(fd, createLoc.c_str());
1120 if (ret) {
1121 int err = errno;
1122 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1123 return -err;
1124 }
1125 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1126 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1127 if (ret) {
1128 int err = errno;
1129 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1130 err, strerror(err));
1131 return -err;
1132 }
1133 } else {
1134 ret = bpfFdPin(fd, progPinLoc.c_str());
1135 if (ret) {
1136 int err = errno;
1137 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1138 return -err;
1139 }
1140 }
1141 if (chmod(progPinLoc.c_str(), 0440)) {
1142 int err = errno;
1143 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1144 return -err;
1145 }
1146 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1147 (gid_t)cs[i].prog_def->gid)) {
1148 int err = errno;
1149 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1150 cs[i].prog_def->gid, err, strerror(err));
1151 return -err;
1152 }
1153 }
1154
1155 int progId = bpfGetFdProgId(fd);
1156 if (progId == -1) {
1157 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
1158 } else {
1159 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
1160 }
1161 }
1162
1163 return 0;
1164}
1165
1166int loadProg(const char* const elfPath, bool* const isCritical, const unsigned int bpfloader_ver,
1167 const Location& location) {
1168 vector<char> license;
1169 vector<char> critical;
1170 vector<codeSection> cs;
1171 vector<unique_fd> mapFds;
1172 int ret;
1173
1174 if (!isCritical) return -1;
1175 *isCritical = false;
1176
1177 ifstream elfFile(elfPath, ios::in | ios::binary);
1178 if (!elfFile.is_open()) return -1;
1179
1180 ret = readSectionByName("critical", elfFile, critical);
1181 *isCritical = !ret;
1182
1183 ret = readSectionByName("license", elfFile, license);
1184 if (ret) {
1185 ALOGE("Couldn't find license in %s", elfPath);
1186 return ret;
1187 } else {
1188 ALOGD("Loading %s%s ELF object %s with license %s",
1189 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
1190 elfPath, (char*)license.data());
1191 }
1192
1193 // the following default values are for bpfloader V0.0 format which does not include them
1194 unsigned int bpfLoaderMinVer =
1195 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1196 unsigned int bpfLoaderMaxVer =
1197 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
1198 unsigned int bpfLoaderMinRequiredVer =
1199 readSectionUint("bpfloader_min_required_ver", elfFile, 0);
1200 size_t sizeOfBpfMapDef =
1201 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1202 size_t sizeOfBpfProgDef =
1203 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1204
1205 // inclusive lower bound check
1206 if (bpfloader_ver < bpfLoaderMinVer) {
1207 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
1208 bpfloader_ver, elfPath, bpfLoaderMinVer);
1209 return 0;
1210 }
1211
1212 // exclusive upper bound check
1213 if (bpfloader_ver >= bpfLoaderMaxVer) {
1214 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
1215 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1216 return 0;
1217 }
1218
1219 if (bpfloader_ver < bpfLoaderMinRequiredVer) {
1220 ALOGI("BpfLoader version 0x%05x failing due to ELF object %s with required min ver 0x%05x",
1221 bpfloader_ver, elfPath, bpfLoaderMinRequiredVer);
1222 return -1;
1223 }
1224
1225 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
1226 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1227
1228 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
1229 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
1230 DEFAULT_SIZEOF_BPF_MAP_DEF);
1231 return -1;
1232 }
1233
1234 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
1235 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
1236 DEFAULT_SIZEOF_BPF_PROG_DEF);
1237 return -1;
1238 }
1239
1240 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef);
1241 if (ret) {
1242 ALOGE("Couldn't read all code sections in %s", elfPath);
1243 return ret;
1244 }
1245
1246 /* Just for future debugging */
1247 if (0) dumpAllCs(cs);
1248
1249 ret = createMaps(elfPath, elfFile, mapFds, location.prefix, sizeOfBpfMapDef, bpfloader_ver);
1250 if (ret) {
1251 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1252 return ret;
1253 }
1254
1255 for (int i = 0; i < (int)mapFds.size(); i++)
1256 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1257
1258 applyMapRelo(elfFile, mapFds, cs);
1259
1260 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix, bpfloader_ver);
1261 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1262
1263 return ret;
1264}
1265
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001266static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001267 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001268 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001269 if (errno == ENOENT) return false;
1270 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1271 abort(); // can only hit this if permissions (likely selinux) are screwed up
1272}
1273
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001274
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001275const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001276 // S+ Tethering mainline module (network_stack): tether offload
1277 {
1278 .dir = "/apex/com.android.tethering/etc/bpf/",
1279 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001280 },
1281 // T+ Tethering mainline module (shared with netd & system server)
1282 // netutils_wrapper (for iptables xt_bpf) has access to programs
1283 {
1284 .dir = "/apex/com.android.tethering/etc/bpf/netd_shared/",
1285 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001286 },
1287 // T+ Tethering mainline module (shared with netd & system server)
1288 // netutils_wrapper has no access, netd has read only access
1289 {
1290 .dir = "/apex/com.android.tethering/etc/bpf/netd_readonly/",
1291 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001292 },
1293 // T+ Tethering mainline module (shared with system server)
1294 {
1295 .dir = "/apex/com.android.tethering/etc/bpf/net_shared/",
1296 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001297 },
1298 // T+ Tethering mainline module (not shared, just network_stack)
1299 {
1300 .dir = "/apex/com.android.tethering/etc/bpf/net_private/",
1301 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001302 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001303};
1304
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001305static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001306 int retVal = 0;
1307 DIR* dir;
1308 struct dirent* ent;
1309
1310 if ((dir = opendir(location.dir)) != NULL) {
1311 while ((ent = readdir(dir)) != NULL) {
1312 string s = ent->d_name;
1313 if (!EndsWith(s, ".o")) continue;
1314
1315 string progPath(location.dir);
1316 progPath += s;
1317
1318 bool critical;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001319 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001320 if (ret) {
1321 if (critical) retVal = ret;
1322 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1323 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001324 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001325 }
1326 }
1327 closedir(dir);
1328 }
1329 return retVal;
1330}
1331
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001332static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001333 if (*prefix) {
1334 mode_t prevUmask = umask(0);
1335
1336 string s = "/sys/fs/bpf/";
1337 s += prefix;
1338
1339 errno = 0;
1340 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1341 if (ret && errno != EEXIST) {
1342 const int err = errno;
1343 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1344 return -err;
1345 }
1346
1347 umask(prevUmask);
1348 }
1349 return 0;
1350}
1351
1352// Technically 'value' doesn't need to be newline terminated, but it's best
1353// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1354// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001355static int writeProcSysFile(const char *filename, const char *value) {
1356 base::unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001357 if (fd < 0) {
1358 const int err = errno;
1359 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1360 return -err;
1361 }
1362 int len = strlen(value);
1363 int v = write(fd, value, len);
1364 if (v < 0) {
1365 const int err = errno;
1366 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1367 return -err;
1368 }
1369 if (v != len) {
1370 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1371 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1372 return -EINVAL;
1373 }
1374 return 0;
1375}
1376
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001377#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001378const char * const platformBpfLoader = "/system/bin/bpfloader";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001379
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001380static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001381 char * found_blockdev = NULL;
1382 FILE * f = NULL;
1383 char buf[4096];
1384
1385 f = fopen("/proc/mounts", "re");
1386 if (!f) return 1;
1387
1388 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1389 while (fgets(buf, sizeof(buf), f)) {
1390 char * blockdev = buf;
1391 char * space = strchr(blockdev, ' ');
1392 if (!space) continue;
1393 *space = '\0';
1394 char * mntpath = space + 1;
1395 space = strchr(mntpath, ' ');
1396 if (!space) continue;
1397 *space = '\0';
1398 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1399 found_blockdev = strdup(blockdev);
1400 break;
1401 }
1402 fclose(f);
1403 f = NULL;
1404
1405 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001406 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001407
1408 f = fopen("/proc/mounts", "re");
1409 if (!f) { free(found_blockdev); return 3; }
1410
1411 while (fgets(buf, sizeof(buf), f)) {
1412 char * blockdev = buf;
1413 char * space = strchr(blockdev, ' ');
1414 if (!space) continue;
1415 *space = '\0';
1416 char * mntpath = space + 1;
1417 space = strchr(mntpath, ' ');
1418 if (!space) continue;
1419 *space = '\0';
1420 if (strcmp(blockdev, found_blockdev)) continue;
1421 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1422 char * at = strchr(mntpath, '@');
1423 if (!at) continue;
1424 char * ver = at + 1;
1425 ALOGI("Tethering APEX version %s", ver);
1426 }
1427 fclose(f);
1428 free(found_blockdev);
1429 return 0;
1430}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001431
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001432static bool hasGSM() {
1433 static string ph = base::GetProperty("gsm.current.phone-type", "");
1434 static bool gsm = (ph != "");
1435 static bool logged = false;
1436 if (!logged) {
1437 logged = true;
1438 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1439 }
1440 return gsm;
1441}
1442
1443static bool isTV() {
1444 if (hasGSM()) return false; // TVs don't do GSM
1445
1446 static string key = base::GetProperty("ro.oem.key1", "");
1447 static bool tv = StartsWith(key, "ATV00");
1448 static bool logged = false;
1449 if (!logged) {
1450 logged = true;
1451 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1452 }
1453 return tv;
1454}
1455
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001456static bool isWear() {
1457 static string wearSdkStr = base::GetProperty("ro.cw_build.wear_sdk.version", "");
1458 static int wearSdkInt = base::GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1459 static string buildChars = base::GetProperty("ro.build.characteristics", "");
1460 static vector<string> v = base::Tokenize(buildChars, ",");
1461 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1462 static bool wear = (wearSdkInt > 0) || watch;
1463 static bool logged = false;
1464 if (!logged) {
1465 logged = true;
1466 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1467 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1468 }
1469 return wear;
1470}
1471
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001472static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001473 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001474
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001475 // Any released device will have codename REL instead of a 'real' codename.
1476 // For safety: default to 'REL' so we default to unreleased=false on failure.
1477 const bool unreleased = (base::GetProperty("ro.build.version.codename", "REL") != "REL");
1478
1479 // goog/main device_api_level is bumped *way* before aosp/main api level
1480 // (the latter only gets bumped during the push of goog/main to aosp/main)
1481 //
1482 // Since we develop in AOSP, we want it to behave as if it was bumped too.
1483 //
1484 // Note that AOSP doesn't really have a good api level (for example during
1485 // early V dev cycle, it would have *all* of T, some but not all of U, and some V).
1486 // One could argue that for our purposes AOSP api level should be infinite or 10000.
1487 //
1488 // This could also cause api to be increased in goog/main or other branches,
1489 // but I can't imagine a case where this would be a problem: the problem
1490 // is rather a too low api level, rather than some ill defined high value.
1491 // For example as I write this aosp is 34/U, and goog is 35/V,
1492 // we want to treat both goog & aosp as 35/V, but it's harmless if we
1493 // treat goog as 36 because that value isn't yet defined to mean anything,
1494 // and we thus never compare against it.
1495 //
1496 // Also note that 'android_get_device_api_level()' is what the
1497 // //system/core/init/apex_init_util.cpp
1498 // apex init .XXrc parsing code uses for XX filtering.
1499 //
1500 // That code has a hack to bump <35 to 35 (to force aosp/main to parse .35rc),
1501 // but could (should?) perhaps be adjusted to match this.
1502 const int effective_api_level = android_get_device_api_level() + (int)unreleased;
1503 const bool isAtLeastT = (effective_api_level >= __ANDROID_API_T__);
1504 const bool isAtLeastU = (effective_api_level >= __ANDROID_API_U__);
1505 const bool isAtLeastV = (effective_api_level >= __ANDROID_API_V__);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001506
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001507 // last in U QPR2 beta1
1508 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1509 // first in U QPR2 beta~2
1510 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1511
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001512 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001513 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
1514 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1515 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1516 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1517 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001518
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001519 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) uid:%d rc:%d%d",
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001520 bpfloader_ver, argv[0], android_get_device_api_level(), effective_api_level,
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001521 kernelVersion(), describeArch(), getuid(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001522 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001523
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001524 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1525 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1526 return 1;
1527 }
1528
1529 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1530 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1531 return 1;
1532 }
1533
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001534 logTetheringApexVersion();
1535
Maciej Żenczykowski11141da2024-03-15 18:21:33 -07001536 if (!isAtLeastT) {
1537 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001538 return 1;
1539 }
1540
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001541 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001542 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001543 ALOGE("Android T requires kernel 4.9.");
1544 return 1;
1545 }
1546
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001547 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001548 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001549 ALOGE("Android U requires kernel 4.14.");
1550 return 1;
1551 }
1552
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001553 // V bumps the kernel requirement up to 4.19
1554 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001555 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001556 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001557 return 1;
1558 }
1559
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001560 // Technically already required by U, but only enforce on V+
1561 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1562 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1563 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1564 if (!isTV()) return 1;
1565 }
1566
1567 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1568 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001569 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001570 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001571 }
1572
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001573 if (isAtLeastV) {
1574 bool bad = false;
1575
1576 if (!isLtsKernel()) {
1577 ALOGW("Android V only supports LTS kernels.");
1578 bad = true;
1579 }
1580
1581#define REQUIRE(maj, min, sub) \
1582 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
1583 ALOGW("Android V requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
1584 bad = true; \
1585 }
1586
1587 REQUIRE(4, 19, 236)
1588 REQUIRE(5, 4, 186)
1589 REQUIRE(5, 10, 199)
1590 REQUIRE(5, 15, 136)
1591 REQUIRE(6, 1, 57)
1592 REQUIRE(6, 6, 0)
1593
1594#undef REQUIRE
1595
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001596 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001597 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1598 }
1599 }
1600
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001601 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001602 /* Android 14/U should only launch on 64-bit kernels
1603 * T launches on 5.10/5.15
1604 * U launches on 5.15/6.1
1605 * So >=5.16 implies isKernel64Bit()
1606 *
1607 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1608 *
1609 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1610 * we also require 64-bit userspace.
1611 *
1612 * There are various known issues with 32-bit userspace talking to various
1613 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1614 * Some of these have userspace or kernel workarounds/hacks.
1615 * Some of them don't...
1616 * We're going to be removing the hacks.
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001617 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1618 * Note: this check/enforcement only applies to *system* userspace code,
1619 * it does not affect unprivileged apps, the 32-on-64 compatibility
1620 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001621 *
1622 * Additionally the 32-bit kernel jit support is poor,
1623 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
1624 */
1625 ALOGE("64-bit userspace required on 6.2+ kernels.");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001626 // Stuff won't work reliably, but exempt TVs & Arm Wear devices
1627 if (!isTV() && !(isWear() && isArm())) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001628 }
1629
1630 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001631 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001632 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001633 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001634 return 1;
1635 }
1636
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001637 if (runningAsRoot) {
1638 // Note: writing this proc file requires being root (always the case on V+)
1639
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001640 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1641 // but we need 0 (enabled)
1642 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1643 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1644 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001645 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001646 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001647
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001648 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001649 // Note: writing these proc files requires CAP_NET_ADMIN
1650 // and sepolicy which is only present on U+,
1651 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1652 // trigger (ie. by init itself) instead.
1653
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001654 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1655 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1656 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1657 // kernel does not have CONFIG_BPF_JIT=y)
1658 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1659 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1660 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001661
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001662 // Enable JIT kallsyms export for privileged users only
1663 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1664 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1665 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1666 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001667
1668 // Create all the pin subdirectories
1669 // (this must be done first to allow selinux_context and pin_subdir functionality,
1670 // which could otherwise fail with ENOENT during object pinning or renaming,
1671 // due to ordering issues)
1672 for (const auto& location : locations) {
1673 if (createSysFsBpfSubDir(location.prefix)) return 1;
1674 }
1675
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001676 // Note: there's no actual src dir for fs_bpf_loader .o's,
1677 // so it is not listed in 'locations[].prefix'.
1678 // This is because this is primarily meant for triggering genfscon rules,
1679 // and as such this will likely always be the case.
1680 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1681 if (createSysFsBpfSubDir("loader")) return 1;
1682
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001683 // Load all ELF objects, create programs and maps, and pin them
1684 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001685 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001686 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1687 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1688 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1689 "problems or startup script race.");
1690 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1691 sleep(20);
1692 return 2;
1693 }
1694 }
1695
1696 int key = 1;
1697 int value = 123;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001698 base::unique_fd map(
1699 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1700 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001701 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1702 return 1;
1703 }
1704
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001705 // leave a flag that we're done
1706 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001707
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001708 // platform bpfloader will only succeed when run as root
1709 if (!runningAsRoot) {
1710 // unreachable on U QPR3+ which always runs netbpfload as root
1711
1712 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1713 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001714 }
1715
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001716 // unreachable before U QPR3
1717 ALOGI("done, transferring control to platform bpfloader.");
1718
1719 // platform BpfLoader *needs* to run as root
1720 const char * args[] = { platformBpfLoader, NULL, };
1721 execve(args[0], (char**)args, envp);
1722 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1723 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001724}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001725
1726} // namespace bpf
1727} // namespace android
1728
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001729int main(int argc, char** argv, char * const envp[]) {
1730 android::base::InitLogging(argv, &android::base::KernelLogger);
1731
1732 if (argc == 2 && !strcmp(argv[1], "done")) {
1733 // we're being re-exec'ed from platform bpfloader to 'finalize' things
1734 if (!android::base::SetProperty("bpf.progs_loaded", "1")) {
1735 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1736 return 125;
1737 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001738 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001739 return 0;
1740 }
1741
1742 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001743}