blob: da70e5a43d297f3c072e7eb87d1f8c4738a81838 [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
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000253 unique_fd prog_fd; // fd after loading
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700254} 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
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000265// Reads all section header tables into an Shdr array
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700266static 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
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000276 // Read shdr table entries
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700277 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
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000284// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700285static 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
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000299// Read whole section header string table
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700300static 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
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000311// Get name from offset in strtab
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700312static 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
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000325// Reads a full section by name - example to get the GPL license
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700326static 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 -0700431static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
432 size_t sizeOfBpfProgDef) {
433 vector<char> pdData;
434 int ret = readSectionByName("progs", elfFile, pdData);
435 if (ret) return ret;
436
437 if (pdData.size() % sizeOfBpfProgDef) {
438 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
439 pdData.size(), sizeOfBpfProgDef);
440 return -1;
441 };
442
443 int progCount = pdData.size() / sizeOfBpfProgDef;
444 pd.resize(progCount);
445 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
446
447 const char* dataPtr = pdData.data();
448 for (auto& p : pd) {
449 // First we zero initialize
450 memset(&p, 0, sizeof(p));
451 // Then we set non-zero defaults
452 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
453 // Then we copy over the structure prefix from the ELF file.
454 memcpy(&p, dataPtr, trimmedSize);
455 // Move to next struct in the ELF file
456 dataPtr += sizeOfBpfProgDef;
457 }
458 return 0;
459}
460
461static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
462 optional<unsigned> symbolType = std::nullopt) {
463 int ret;
464 string name;
465 vector<Elf64_Sym> symtab;
466 vector<Elf64_Shdr> shTable;
467
468 ret = readSymTab(elfFile, 1 /* sort */, symtab);
469 if (ret) return ret;
470
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000471 // Get index of section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700472 ret = readSectionHeadersAll(elfFile, shTable);
473 if (ret) return ret;
474
475 int sec_idx = -1;
476 for (int i = 0; i < (int)shTable.size(); i++) {
477 ret = getSymName(elfFile, shTable[i].sh_name, name);
478 if (ret) return ret;
479
480 if (!name.compare(sectionName)) {
481 sec_idx = i;
482 break;
483 }
484 }
485
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000486 // No section found with matching name
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700487 if (sec_idx == -1) {
488 ALOGW("No %s section could be found in elf object", sectionName.c_str());
489 return -1;
490 }
491
492 for (int i = 0; i < (int)symtab.size(); i++) {
493 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
494
495 if (symtab[i].st_shndx == sec_idx) {
496 string s;
497 ret = getSymName(elfFile, symtab[i].st_name, s);
498 if (ret) return ret;
499 names.push_back(s);
500 }
501 }
502
503 return 0;
504}
505
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000506// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700507static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef) {
508 vector<Elf64_Shdr> shTable;
509 int entries, ret = 0;
510
511 ret = readSectionHeadersAll(elfFile, shTable);
512 if (ret) return ret;
513 entries = shTable.size();
514
515 vector<struct bpf_prog_def> pd;
516 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
517 if (ret) return ret;
518 vector<string> progDefNames;
519 ret = getSectionSymNames(elfFile, "progs", progDefNames);
520 if (!pd.empty() && ret) return ret;
521
522 for (int i = 0; i < entries; i++) {
523 string name;
524 codeSection cs_temp;
525 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
526
527 ret = getSymName(elfFile, shTable[i].sh_name, name);
528 if (ret) return ret;
529
530 enum bpf_prog_type ptype = getSectionType(name);
531
532 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
533
534 // This must be done before '/' is replaced with '_'.
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000535 for (auto& snt : sectionNameTypes)
536 if (StartsWith(name, snt.name)) cs_temp.attach_type = snt.attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700537
538 string oldName = name;
539
540 // convert all slashes to underscores
541 std::replace(name.begin(), name.end(), '/', '_');
542
543 cs_temp.type = ptype;
544 cs_temp.name = name;
545
546 ret = readSectionByIdx(elfFile, i, cs_temp.data);
547 if (ret) return ret;
548 ALOGV("Loaded code section %d (%s)", i, name.c_str());
549
550 vector<string> csSymNames;
551 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
552 if (ret || !csSymNames.size()) return ret;
553 for (size_t i = 0; i < progDefNames.size(); ++i) {
554 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
555 cs_temp.prog_def = pd[i];
556 break;
557 }
558 }
559
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000560 // Check for rel section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700561 if (cs_temp.data.size() > 0 && i < entries) {
562 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
563 if (ret) return ret;
564
565 if (name == (".rel" + oldName)) {
566 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
567 if (ret) return ret;
568 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
569 }
570 }
571
572 if (cs_temp.data.size() > 0) {
573 cs.push_back(std::move(cs_temp));
574 ALOGV("Adding section %d to cs list", i);
575 }
576 }
577 return 0;
578}
579
580static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
581 vector<Elf64_Sym> symtab;
582 int ret = 0;
583
584 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
585 if (ret) return ret;
586
587 if (index >= (int)symtab.size()) return -1;
588
589 return getSymName(elfFile, symtab[index].st_name, name);
590}
591
592static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
593 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
594 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
595 // so on 4.9-T kernels just pretend the map matches our expectations.
596 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
597 // This is because the primary failure mode we're trying to detect here
598 // is either a source code misconfiguration (which is likely kernel independent)
599 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
600 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
601
602 // Assuming fd is a valid Bpf Map file descriptor then
603 // all the following should always succeed on a 4.14+ kernel.
604 // If they somehow do fail, they'll return -1 (and set errno),
605 // which should then cause (among others) a key_size mismatch.
606 int fd_type = bpfGetFdMapType(fd);
607 int fd_key_size = bpfGetFdKeySize(fd);
608 int fd_value_size = bpfGetFdValueSize(fd);
609 int fd_max_entries = bpfGetFdMaxEntries(fd);
610 int fd_map_flags = bpfGetFdMapFlags(fd);
611
612 // DEVMAPs are readonly from the bpf program side's point of view, as such
613 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
614 int desired_map_flags = (int)mapDef.map_flags;
615 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
616 desired_map_flags |= BPF_F_RDONLY_PROG;
617
618 // The .h file enforces that this is a power of two, and page size will
619 // also always be a power of two, so this logic is actually enough to
620 // force it to be a multiple of the page size, as required by the kernel.
621 unsigned int desired_max_entries = mapDef.max_entries;
622 if (type == BPF_MAP_TYPE_RINGBUF) {
623 if (desired_max_entries < page_size) desired_max_entries = page_size;
624 }
625
626 // The following checks should *never* trigger, if one of them somehow does,
627 // it probably means a bpf .o file has been changed/replaced at runtime
628 // and bpfloader was manually rerun (normally it should only run *once*
629 // early during the boot process).
630 // Another possibility is that something is misconfigured in the code:
631 // most likely a shared map is declared twice differently.
632 // But such a change should never be checked into the source tree...
633 if ((fd_type == type) &&
634 (fd_key_size == (int)mapDef.key_size) &&
635 (fd_value_size == (int)mapDef.value_size) &&
636 (fd_max_entries == (int)desired_max_entries) &&
637 (fd_map_flags == desired_map_flags)) {
638 return true;
639 }
640
641 ALOGE("bpf map name %s mismatch: desired/found: "
642 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
643 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
644 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
645 return false;
646}
647
648static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
649 const char* prefix, const size_t sizeOfBpfMapDef,
650 const unsigned int bpfloader_ver) {
651 int ret;
652 vector<char> mdData;
653 vector<struct bpf_map_def> md;
654 vector<string> mapNames;
655 string objName = pathToObjName(string(elfPath));
656
657 ret = readSectionByName("maps", elfFile, mdData);
658 if (ret == -2) return 0; // no maps to read
659 if (ret) return ret;
660
661 if (mdData.size() % sizeOfBpfMapDef) {
662 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
663 mdData.size(), sizeOfBpfMapDef);
664 return -1;
665 };
666
667 int mapCount = mdData.size() / sizeOfBpfMapDef;
668 md.resize(mapCount);
669 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
670
671 const char* dataPtr = mdData.data();
672 for (auto& m : md) {
673 // First we zero initialize
674 memset(&m, 0, sizeof(m));
675 // Then we set non-zero defaults
676 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
677 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
678 // Then we copy over the structure prefix from the ELF file.
679 memcpy(&m, dataPtr, trimmedSize);
680 // Move to next struct in the ELF file
681 dataPtr += sizeOfBpfMapDef;
682 }
683
684 ret = getSectionSymNames(elfFile, "maps", mapNames);
685 if (ret) return ret;
686
687 unsigned kvers = kernelVersion();
688
689 for (int i = 0; i < (int)mapNames.size(); i++) {
690 if (md[i].zero != 0) abort();
691
692 if (bpfloader_ver < md[i].bpfloader_min_ver) {
693 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
694 md[i].bpfloader_min_ver);
695 mapFds.push_back(unique_fd());
696 continue;
697 }
698
699 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
700 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
701 md[i].bpfloader_max_ver);
702 mapFds.push_back(unique_fd());
703 continue;
704 }
705
706 if (kvers < md[i].min_kver) {
707 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
708 mapNames[i].c_str(), kvers, md[i].min_kver);
709 mapFds.push_back(unique_fd());
710 continue;
711 }
712
713 if (kvers >= md[i].max_kver) {
714 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
715 mapNames[i].c_str(), kvers, md[i].max_kver);
716 mapFds.push_back(unique_fd());
717 continue;
718 }
719
720 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
721 (md[i].ignore_on_userdebug && isUserdebug())) {
722 ALOGI("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
723 getBuildType().c_str());
724 mapFds.push_back(unique_fd());
725 continue;
726 }
727
728 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
729 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
730 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
731 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
732 (isRiscV() && md[i].ignore_on_riscv64)) {
733 ALOGI("skipping map %s which is ignored on %s", mapNames[i].c_str(),
734 describeArch());
735 mapFds.push_back(unique_fd());
736 continue;
737 }
738
739 enum bpf_map_type type = md[i].type;
740 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
741 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
742 // of be approximated: ARRAY has the same userspace api, though it is not usable
743 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
744 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
745 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
746 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
747 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
748 type = BPF_MAP_TYPE_ARRAY;
749 }
750 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
751 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
752 // of be approximated: HASH has the same userspace visible api.
753 // However it cannot be used by ebpf programs in the same way.
754 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
755 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
756 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
757 // programs as being 5.4+...
758 type = BPF_MAP_TYPE_HASH;
759 }
760
761 // The .h file enforces that this is a power of two, and page size will
762 // also always be a power of two, so this logic is actually enough to
763 // force it to be a multiple of the page size, as required by the kernel.
764 unsigned int max_entries = md[i].max_entries;
765 if (type == BPF_MAP_TYPE_RINGBUF) {
766 if (max_entries < page_size) max_entries = page_size;
767 }
768
769 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
770 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000771 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700772 md[i].selinux_context, static_cast<int>(selinux_context),
773 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
774 }
775
776 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700777 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000778 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700779 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
780 }
781
782 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
783 // except that maps shared across .o's have empty <objName>
784 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
785 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
786 (md[i].shared ? "" : objName) + "_" + mapNames[i];
787 bool reuse = false;
788 unique_fd fd;
789 int saved_errno;
790
791 if (access(mapPinLoc.c_str(), F_OK) == 0) {
792 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
793 saved_errno = errno;
794 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
795 reuse = true;
796 } else {
797 union bpf_attr req = {
798 .map_type = type,
799 .key_size = md[i].key_size,
800 .value_size = md[i].value_size,
801 .max_entries = max_entries,
802 .map_flags = md[i].map_flags,
803 };
804 if (isAtLeastKernelVersion(4, 15, 0))
805 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
806 fd.reset(bpf(BPF_MAP_CREATE, req));
807 saved_errno = errno;
808 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
809 }
810
811 if (!fd.ok()) return -saved_errno;
812
813 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
814 // safety (since reuse code path is rare) run these checks even if we just created it.
815 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
816 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
817
818 if (!reuse) {
819 if (specified(selinux_context)) {
820 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
821 "tmp_map_" + objName + "_" + mapNames[i];
822 ret = bpfFdPin(fd, createLoc.c_str());
823 if (ret) {
824 int err = errno;
825 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
826 return -err;
827 }
828 ret = renameat2(AT_FDCWD, createLoc.c_str(),
829 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
830 if (ret) {
831 int err = errno;
832 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
833 err, strerror(err));
834 return -err;
835 }
836 } else {
837 ret = bpfFdPin(fd, mapPinLoc.c_str());
838 if (ret) {
839 int err = errno;
840 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
841 return -err;
842 }
843 }
844 ret = chmod(mapPinLoc.c_str(), md[i].mode);
845 if (ret) {
846 int err = errno;
847 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
848 strerror(err));
849 return -err;
850 }
851 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
852 if (ret) {
853 int err = errno;
854 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
855 ret, err, strerror(err));
856 return -err;
857 }
858 }
859
860 int mapId = bpfGetFdMapId(fd);
861 if (mapId == -1) {
862 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
863 } else {
864 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
865 }
866
867 mapFds.push_back(std::move(fd));
868 }
869
870 return ret;
871}
872
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700873static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
874 int insnIndex;
875 struct bpf_insn *insn, *insns;
876
877 insns = (struct bpf_insn*)(insnsPtr);
878
879 insnIndex = offset / sizeof(struct bpf_insn);
880 insn = &insns[insnIndex];
881
882 // Occasionally might be useful for relocation debugging, but pretty spammy
883 if (0) {
884 ALOGV("applying relo to instruction at byte offset: %llu, "
885 "insn offset %d, insn %llx",
886 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
887 }
888
889 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700890 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700891 return;
892 }
893
894 insn->imm = fd;
895 insn->src_reg = BPF_PSEUDO_MAP_FD;
896}
897
898static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
899 vector<string> mapNames;
900
901 int ret = getSectionSymNames(elfFile, "maps", mapNames);
902 if (ret) return;
903
904 for (int k = 0; k != (int)cs.size(); k++) {
905 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
906 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
907
908 for (int i = 0; i < n_rel; i++) {
909 int symIndex = ELF64_R_SYM(rel[i].r_info);
910 string symName;
911
912 ret = getSymNameByIdx(elfFile, symIndex, symName);
913 if (ret) return;
914
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000915 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700916 for (int j = 0; j < (int)mapNames.size(); j++) {
917 if (!mapNames[j].compare(symName)) {
918 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
919 break;
920 }
921 }
922 }
923 }
924}
925
926static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
927 const char* prefix, const unsigned int bpfloader_ver) {
928 unsigned kvers = kernelVersion();
929
930 if (!kvers) {
931 ALOGE("unable to get kernel version");
932 return -EINVAL;
933 }
934
935 string objName = pathToObjName(string(elfPath));
936
937 for (int i = 0; i < (int)cs.size(); i++) {
938 unique_fd& fd = cs[i].prog_fd;
939 int ret;
940 string name = cs[i].name;
941
942 if (!cs[i].prog_def.has_value()) {
943 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
944 return -EINVAL;
945 }
946
947 unsigned min_kver = cs[i].prog_def->min_kver;
948 unsigned max_kver = cs[i].prog_def->max_kver;
949 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
950 max_kver, kvers);
951 if (kvers < min_kver) continue;
952 if (kvers >= max_kver) continue;
953
954 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
955 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
956 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
957 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700958
959 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
960 bpfMinVer, bpfMaxVer);
961 if (bpfloader_ver < bpfMinVer) continue;
962 if (bpfloader_ver >= bpfMaxVer) continue;
963
964 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
965 (cs[i].prog_def->ignore_on_user && isUser()) ||
966 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
967 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
968 getBuildType().c_str());
969 continue;
970 }
971
972 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
973 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
974 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
975 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
976 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
977 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
978 continue;
979 }
980
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700981 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000982 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700983 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
984 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
985 }
986
987 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000988 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700989 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
990 lookupPinSubdir(pin_subdir));
991 }
992
993 // strip any potential $foo suffix
994 // this can be used to provide duplicate programs
995 // conditionally loaded based on running kernel version
996 name = name.substr(0, name.find_last_of('$'));
997
998 bool reuse = false;
999 // Format of pin location is
1000 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1001 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1002 objName + '_' + string(name);
1003 if (access(progPinLoc.c_str(), F_OK) == 0) {
1004 fd.reset(retrieveProgram(progPinLoc.c_str()));
1005 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
1006 (!fd.ok() ? std::strerror(errno) : "no error"));
1007 reuse = true;
1008 } else {
1009 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1010
1011 union bpf_attr req = {
1012 .prog_type = cs[i].type,
1013 .kern_version = kvers,
1014 .license = ptr_to_u64(license.c_str()),
1015 .insns = ptr_to_u64(cs[i].data.data()),
1016 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
1017 .log_level = 1,
1018 .log_buf = ptr_to_u64(log_buf.data()),
1019 .log_size = static_cast<__u32>(log_buf.size()),
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001020 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001021 };
1022 if (isAtLeastKernelVersion(4, 15, 0))
1023 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1024 fd.reset(bpf(BPF_PROG_LOAD, req));
1025
1026 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
1027 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
1028
1029 if (!fd.ok()) {
1030 vector<string> lines = android::base::Split(log_buf.data(), "\n");
1031
1032 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1033 for (const auto& line : lines) ALOGW("%s", line.c_str());
1034 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1035
1036 if (cs[i].prog_def->optional) {
1037 ALOGW("failed program is marked optional - continuing...");
1038 continue;
1039 }
1040 ALOGE("non-optional program failed to load.");
1041 }
1042 }
1043
1044 if (!fd.ok()) return fd.get();
1045
1046 if (!reuse) {
1047 if (specified(selinux_context)) {
1048 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1049 "tmp_prog_" + objName + '_' + string(name);
1050 ret = bpfFdPin(fd, createLoc.c_str());
1051 if (ret) {
1052 int err = errno;
1053 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1054 return -err;
1055 }
1056 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1057 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1058 if (ret) {
1059 int err = errno;
1060 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1061 err, strerror(err));
1062 return -err;
1063 }
1064 } else {
1065 ret = bpfFdPin(fd, progPinLoc.c_str());
1066 if (ret) {
1067 int err = errno;
1068 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1069 return -err;
1070 }
1071 }
1072 if (chmod(progPinLoc.c_str(), 0440)) {
1073 int err = errno;
1074 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1075 return -err;
1076 }
1077 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1078 (gid_t)cs[i].prog_def->gid)) {
1079 int err = errno;
1080 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1081 cs[i].prog_def->gid, err, strerror(err));
1082 return -err;
1083 }
1084 }
1085
1086 int progId = bpfGetFdProgId(fd);
1087 if (progId == -1) {
1088 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
1089 } else {
1090 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
1091 }
1092 }
1093
1094 return 0;
1095}
1096
1097int loadProg(const char* const elfPath, bool* const isCritical, const unsigned int bpfloader_ver,
1098 const Location& location) {
1099 vector<char> license;
1100 vector<char> critical;
1101 vector<codeSection> cs;
1102 vector<unique_fd> mapFds;
1103 int ret;
1104
1105 if (!isCritical) return -1;
1106 *isCritical = false;
1107
1108 ifstream elfFile(elfPath, ios::in | ios::binary);
1109 if (!elfFile.is_open()) return -1;
1110
1111 ret = readSectionByName("critical", elfFile, critical);
1112 *isCritical = !ret;
1113
1114 ret = readSectionByName("license", elfFile, license);
1115 if (ret) {
1116 ALOGE("Couldn't find license in %s", elfPath);
1117 return ret;
1118 } else {
1119 ALOGD("Loading %s%s ELF object %s with license %s",
1120 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
1121 elfPath, (char*)license.data());
1122 }
1123
1124 // the following default values are for bpfloader V0.0 format which does not include them
1125 unsigned int bpfLoaderMinVer =
1126 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1127 unsigned int bpfLoaderMaxVer =
1128 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001129 size_t sizeOfBpfMapDef =
1130 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1131 size_t sizeOfBpfProgDef =
1132 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1133
1134 // inclusive lower bound check
1135 if (bpfloader_ver < bpfLoaderMinVer) {
1136 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
1137 bpfloader_ver, elfPath, bpfLoaderMinVer);
1138 return 0;
1139 }
1140
1141 // exclusive upper bound check
1142 if (bpfloader_ver >= bpfLoaderMaxVer) {
1143 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
1144 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1145 return 0;
1146 }
1147
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001148 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
1149 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1150
1151 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
1152 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
1153 DEFAULT_SIZEOF_BPF_MAP_DEF);
1154 return -1;
1155 }
1156
1157 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
1158 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
1159 DEFAULT_SIZEOF_BPF_PROG_DEF);
1160 return -1;
1161 }
1162
1163 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef);
1164 if (ret) {
1165 ALOGE("Couldn't read all code sections in %s", elfPath);
1166 return ret;
1167 }
1168
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001169 ret = createMaps(elfPath, elfFile, mapFds, location.prefix, sizeOfBpfMapDef, bpfloader_ver);
1170 if (ret) {
1171 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1172 return ret;
1173 }
1174
1175 for (int i = 0; i < (int)mapFds.size(); i++)
1176 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1177
1178 applyMapRelo(elfFile, mapFds, cs);
1179
1180 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix, bpfloader_ver);
1181 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1182
1183 return ret;
1184}
1185
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001186static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001187 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001188 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001189 if (errno == ENOENT) return false;
1190 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1191 abort(); // can only hit this if permissions (likely selinux) are screwed up
1192}
1193
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001194
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001195const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001196 // S+ Tethering mainline module (network_stack): tether offload
1197 {
1198 .dir = "/apex/com.android.tethering/etc/bpf/",
1199 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001200 },
1201 // T+ Tethering mainline module (shared with netd & system server)
1202 // netutils_wrapper (for iptables xt_bpf) has access to programs
1203 {
1204 .dir = "/apex/com.android.tethering/etc/bpf/netd_shared/",
1205 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001206 },
1207 // T+ Tethering mainline module (shared with netd & system server)
1208 // netutils_wrapper has no access, netd has read only access
1209 {
1210 .dir = "/apex/com.android.tethering/etc/bpf/netd_readonly/",
1211 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001212 },
1213 // T+ Tethering mainline module (shared with system server)
1214 {
1215 .dir = "/apex/com.android.tethering/etc/bpf/net_shared/",
1216 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001217 },
1218 // T+ Tethering mainline module (not shared, just network_stack)
1219 {
1220 .dir = "/apex/com.android.tethering/etc/bpf/net_private/",
1221 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001222 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001223};
1224
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001225static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001226 int retVal = 0;
1227 DIR* dir;
1228 struct dirent* ent;
1229
1230 if ((dir = opendir(location.dir)) != NULL) {
1231 while ((ent = readdir(dir)) != NULL) {
1232 string s = ent->d_name;
1233 if (!EndsWith(s, ".o")) continue;
1234
1235 string progPath(location.dir);
1236 progPath += s;
1237
1238 bool critical;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001239 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001240 if (ret) {
1241 if (critical) retVal = ret;
1242 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1243 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001244 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001245 }
1246 }
1247 closedir(dir);
1248 }
1249 return retVal;
1250}
1251
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001252static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001253 if (*prefix) {
1254 mode_t prevUmask = umask(0);
1255
1256 string s = "/sys/fs/bpf/";
1257 s += prefix;
1258
1259 errno = 0;
1260 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1261 if (ret && errno != EEXIST) {
1262 const int err = errno;
1263 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1264 return -err;
1265 }
1266
1267 umask(prevUmask);
1268 }
1269 return 0;
1270}
1271
1272// Technically 'value' doesn't need to be newline terminated, but it's best
1273// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1274// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001275static int writeProcSysFile(const char *filename, const char *value) {
1276 base::unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001277 if (fd < 0) {
1278 const int err = errno;
1279 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1280 return -err;
1281 }
1282 int len = strlen(value);
1283 int v = write(fd, value, len);
1284 if (v < 0) {
1285 const int err = errno;
1286 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1287 return -err;
1288 }
1289 if (v != len) {
1290 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1291 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1292 return -EINVAL;
1293 }
1294 return 0;
1295}
1296
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001297#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001298const char * const platformBpfLoader = "/system/bin/bpfloader";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001299
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001300static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001301 char * found_blockdev = NULL;
1302 FILE * f = NULL;
1303 char buf[4096];
1304
1305 f = fopen("/proc/mounts", "re");
1306 if (!f) return 1;
1307
1308 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1309 while (fgets(buf, sizeof(buf), f)) {
1310 char * blockdev = buf;
1311 char * space = strchr(blockdev, ' ');
1312 if (!space) continue;
1313 *space = '\0';
1314 char * mntpath = space + 1;
1315 space = strchr(mntpath, ' ');
1316 if (!space) continue;
1317 *space = '\0';
1318 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1319 found_blockdev = strdup(blockdev);
1320 break;
1321 }
1322 fclose(f);
1323 f = NULL;
1324
1325 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001326 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001327
1328 f = fopen("/proc/mounts", "re");
1329 if (!f) { free(found_blockdev); return 3; }
1330
1331 while (fgets(buf, sizeof(buf), f)) {
1332 char * blockdev = buf;
1333 char * space = strchr(blockdev, ' ');
1334 if (!space) continue;
1335 *space = '\0';
1336 char * mntpath = space + 1;
1337 space = strchr(mntpath, ' ');
1338 if (!space) continue;
1339 *space = '\0';
1340 if (strcmp(blockdev, found_blockdev)) continue;
1341 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1342 char * at = strchr(mntpath, '@');
1343 if (!at) continue;
1344 char * ver = at + 1;
1345 ALOGI("Tethering APEX version %s", ver);
1346 }
1347 fclose(f);
1348 free(found_blockdev);
1349 return 0;
1350}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001351
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001352static bool hasGSM() {
1353 static string ph = base::GetProperty("gsm.current.phone-type", "");
1354 static bool gsm = (ph != "");
1355 static bool logged = false;
1356 if (!logged) {
1357 logged = true;
1358 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1359 }
1360 return gsm;
1361}
1362
1363static bool isTV() {
1364 if (hasGSM()) return false; // TVs don't do GSM
1365
1366 static string key = base::GetProperty("ro.oem.key1", "");
1367 static bool tv = StartsWith(key, "ATV00");
1368 static bool logged = false;
1369 if (!logged) {
1370 logged = true;
1371 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1372 }
1373 return tv;
1374}
1375
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001376static bool isWear() {
1377 static string wearSdkStr = base::GetProperty("ro.cw_build.wear_sdk.version", "");
1378 static int wearSdkInt = base::GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1379 static string buildChars = base::GetProperty("ro.build.characteristics", "");
1380 static vector<string> v = base::Tokenize(buildChars, ",");
1381 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1382 static bool wear = (wearSdkInt > 0) || watch;
1383 static bool logged = false;
1384 if (!logged) {
1385 logged = true;
1386 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1387 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1388 }
1389 return wear;
1390}
1391
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001392static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001393 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001394
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001395 // Any released device will have codename REL instead of a 'real' codename.
1396 // For safety: default to 'REL' so we default to unreleased=false on failure.
1397 const bool unreleased = (base::GetProperty("ro.build.version.codename", "REL") != "REL");
1398
1399 // goog/main device_api_level is bumped *way* before aosp/main api level
1400 // (the latter only gets bumped during the push of goog/main to aosp/main)
1401 //
1402 // Since we develop in AOSP, we want it to behave as if it was bumped too.
1403 //
1404 // Note that AOSP doesn't really have a good api level (for example during
1405 // early V dev cycle, it would have *all* of T, some but not all of U, and some V).
1406 // One could argue that for our purposes AOSP api level should be infinite or 10000.
1407 //
1408 // This could also cause api to be increased in goog/main or other branches,
1409 // but I can't imagine a case where this would be a problem: the problem
1410 // is rather a too low api level, rather than some ill defined high value.
1411 // For example as I write this aosp is 34/U, and goog is 35/V,
1412 // we want to treat both goog & aosp as 35/V, but it's harmless if we
1413 // treat goog as 36 because that value isn't yet defined to mean anything,
1414 // and we thus never compare against it.
1415 //
1416 // Also note that 'android_get_device_api_level()' is what the
1417 // //system/core/init/apex_init_util.cpp
1418 // apex init .XXrc parsing code uses for XX filtering.
1419 //
1420 // That code has a hack to bump <35 to 35 (to force aosp/main to parse .35rc),
1421 // but could (should?) perhaps be adjusted to match this.
1422 const int effective_api_level = android_get_device_api_level() + (int)unreleased;
1423 const bool isAtLeastT = (effective_api_level >= __ANDROID_API_T__);
1424 const bool isAtLeastU = (effective_api_level >= __ANDROID_API_U__);
1425 const bool isAtLeastV = (effective_api_level >= __ANDROID_API_V__);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001426
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001427 // last in U QPR2 beta1
1428 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1429 // first in U QPR2 beta~2
1430 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1431
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001432 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001433 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
1434 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1435 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1436 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1437 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001438
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001439 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) uid:%d rc:%d%d",
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001440 bpfloader_ver, argv[0], android_get_device_api_level(), effective_api_level,
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001441 kernelVersion(), describeArch(), getuid(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001442 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001443
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001444 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1445 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1446 return 1;
1447 }
1448
1449 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1450 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1451 return 1;
1452 }
1453
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001454 logTetheringApexVersion();
1455
Maciej Żenczykowski11141da2024-03-15 18:21:33 -07001456 if (!isAtLeastT) {
1457 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001458 return 1;
1459 }
1460
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001461 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001462 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001463 ALOGE("Android T requires kernel 4.9.");
1464 return 1;
1465 }
1466
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001467 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001468 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001469 ALOGE("Android U requires kernel 4.14.");
1470 return 1;
1471 }
1472
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001473 // V bumps the kernel requirement up to 4.19
1474 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001475 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001476 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001477 return 1;
1478 }
1479
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001480 // Technically already required by U, but only enforce on V+
1481 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1482 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1483 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1484 if (!isTV()) return 1;
1485 }
1486
1487 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1488 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001489 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001490 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001491 }
1492
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001493 if (isAtLeastV) {
1494 bool bad = false;
1495
1496 if (!isLtsKernel()) {
1497 ALOGW("Android V only supports LTS kernels.");
1498 bad = true;
1499 }
1500
1501#define REQUIRE(maj, min, sub) \
1502 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
1503 ALOGW("Android V requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
1504 bad = true; \
1505 }
1506
1507 REQUIRE(4, 19, 236)
1508 REQUIRE(5, 4, 186)
1509 REQUIRE(5, 10, 199)
1510 REQUIRE(5, 15, 136)
1511 REQUIRE(6, 1, 57)
1512 REQUIRE(6, 6, 0)
1513
1514#undef REQUIRE
1515
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001516 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001517 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1518 }
1519 }
1520
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001521 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001522 /* Android 14/U should only launch on 64-bit kernels
1523 * T launches on 5.10/5.15
1524 * U launches on 5.15/6.1
1525 * So >=5.16 implies isKernel64Bit()
1526 *
1527 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1528 *
1529 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1530 * we also require 64-bit userspace.
1531 *
1532 * There are various known issues with 32-bit userspace talking to various
1533 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1534 * Some of these have userspace or kernel workarounds/hacks.
1535 * Some of them don't...
1536 * We're going to be removing the hacks.
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001537 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1538 * Note: this check/enforcement only applies to *system* userspace code,
1539 * it does not affect unprivileged apps, the 32-on-64 compatibility
1540 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001541 *
1542 * Additionally the 32-bit kernel jit support is poor,
1543 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
1544 */
1545 ALOGE("64-bit userspace required on 6.2+ kernels.");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001546 // Stuff won't work reliably, but exempt TVs & Arm Wear devices
1547 if (!isTV() && !(isWear() && isArm())) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001548 }
1549
1550 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001551 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001552 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001553 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001554 return 1;
1555 }
1556
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001557 if (runningAsRoot) {
1558 // Note: writing this proc file requires being root (always the case on V+)
1559
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001560 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1561 // but we need 0 (enabled)
1562 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1563 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1564 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001565 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001566 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001567
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001568 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001569 // Note: writing these proc files requires CAP_NET_ADMIN
1570 // and sepolicy which is only present on U+,
1571 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1572 // trigger (ie. by init itself) instead.
1573
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001574 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1575 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1576 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1577 // kernel does not have CONFIG_BPF_JIT=y)
1578 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1579 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1580 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001581
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001582 // Enable JIT kallsyms export for privileged users only
1583 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1584 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1585 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1586 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001587
1588 // Create all the pin subdirectories
1589 // (this must be done first to allow selinux_context and pin_subdir functionality,
1590 // which could otherwise fail with ENOENT during object pinning or renaming,
1591 // due to ordering issues)
1592 for (const auto& location : locations) {
1593 if (createSysFsBpfSubDir(location.prefix)) return 1;
1594 }
1595
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001596 // Note: there's no actual src dir for fs_bpf_loader .o's,
1597 // so it is not listed in 'locations[].prefix'.
1598 // This is because this is primarily meant for triggering genfscon rules,
1599 // and as such this will likely always be the case.
1600 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1601 if (createSysFsBpfSubDir("loader")) return 1;
1602
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001603 // Load all ELF objects, create programs and maps, and pin them
1604 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001605 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001606 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1607 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1608 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1609 "problems or startup script race.");
1610 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1611 sleep(20);
1612 return 2;
1613 }
1614 }
1615
1616 int key = 1;
1617 int value = 123;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001618 base::unique_fd map(
1619 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1620 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001621 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1622 return 1;
1623 }
1624
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001625 // leave a flag that we're done
1626 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001627
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001628 // platform bpfloader will only succeed when run as root
1629 if (!runningAsRoot) {
1630 // unreachable on U QPR3+ which always runs netbpfload as root
1631
1632 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1633 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001634 }
1635
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001636 // unreachable before U QPR3
1637 ALOGI("done, transferring control to platform bpfloader.");
1638
1639 // platform BpfLoader *needs* to run as root
1640 const char * args[] = { platformBpfLoader, NULL, };
1641 execve(args[0], (char**)args, envp);
1642 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1643 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001644}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001645
1646} // namespace bpf
1647} // namespace android
1648
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001649int main(int argc, char** argv, char * const envp[]) {
1650 android::base::InitLogging(argv, &android::base::KernelLogger);
1651
1652 if (argc == 2 && !strcmp(argv[1], "done")) {
1653 // we're being re-exec'ed from platform bpfloader to 'finalize' things
1654 if (!android::base::SetProperty("bpf.progs_loaded", "1")) {
1655 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1656 return 125;
1657 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001658 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001659 return 0;
1660 }
1661
1662 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001663}