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