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