blob: 93dffb67323d86d5e839c4d06f6c411de786b759 [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>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070020#include <dirent.h>
21#include <elf.h>
22#include <errno.h>
23#include <error.h>
24#include <fcntl.h>
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070025#include <fstream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070026#include <inttypes.h>
27#include <iostream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070028#include <linux/unistd.h>
29#include <log/log.h>
30#include <net/if.h>
31#include <optional>
32#include <stdint.h>
33#include <stdio.h>
34#include <stdlib.h>
35#include <string.h>
36#include <string>
37#include <sys/mman.h>
38#include <sys/socket.h>
39#include <sys/stat.h>
40#include <sys/types.h>
41#include <sys/utsname.h>
42#include <sys/wait.h>
43#include <sysexits.h>
44#include <unistd.h>
45#include <unordered_map>
46#include <vector>
47
48#include <android-base/cmsg.h>
49#include <android-base/file.h>
50#include <android-base/logging.h>
51#include <android-base/macros.h>
52#include <android-base/properties.h>
53#include <android-base/stringprintf.h>
54#include <android-base/strings.h>
55#include <android-base/unique_fd.h>
56#include <android/api-level.h>
57
58#include "BpfSyscallWrappers.h"
59#include "bpf/BpfUtils.h"
Maciej Żenczykowskid6028352024-08-19 15:20:04 -070060#include "bpf_map_def.h"
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070061
62using android::base::EndsWith;
63using android::base::StartsWith;
64using android::base::unique_fd;
65using std::ifstream;
66using std::ios;
67using std::optional;
68using std::string;
69using std::vector;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070070
71namespace android {
72namespace bpf {
73
74// Bpf programs may specify per-program & per-map selinux_context and pin_subdir.
75//
76// The BpfLoader needs to convert these bpf.o specified strings into an enum
77// for internal use (to check that valid values were specified for the specific
78// location of the bpf.o file).
79//
80// It also needs to map selinux_context's into pin_subdir's.
81// This is because of how selinux_context is actually implemented via pin+rename.
82//
83// Thus 'domain' enumerates all selinux_context's/pin_subdir's that the BpfLoader
84// is aware of. Thus there currently needs to be a 1:1 mapping between the two.
85//
86enum class domain : int {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070087 unspecified = 0, // means just use the default for that specific pin location
88 tethering, // (S+) fs_bpf_tethering /sys/fs/bpf/tethering
89 net_private, // (T+) fs_bpf_net_private /sys/fs/bpf/net_private
90 net_shared, // (T+) fs_bpf_net_shared /sys/fs/bpf/net_shared
91 netd_readonly, // (T+) fs_bpf_netd_readonly /sys/fs/bpf/netd_readonly
92 netd_shared, // (T+) fs_bpf_netd_shared /sys/fs/bpf/netd_shared
93};
94
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070095static constexpr domain AllDomains[] = {
96 domain::unspecified,
97 domain::tethering,
98 domain::net_private,
99 domain::net_shared,
100 domain::netd_readonly,
101 domain::netd_shared,
102};
103
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700104static constexpr bool specified(domain d) {
105 return d != domain::unspecified;
106}
107
108struct Location {
109 const char* const dir = "";
110 const char* const prefix = "";
111};
112
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700113// Returns the build type string (from ro.build.type).
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700114const std::string& getBuildType() {
115 static std::string t = android::base::GetProperty("ro.build.type", "unknown");
116 return t;
117}
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700118
119// The following functions classify the 3 Android build types.
120inline bool isEng() {
121 return getBuildType() == "eng";
122}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700123
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700124inline bool isUser() {
125 return getBuildType() == "user";
126}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700127
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700128inline bool isUserdebug() {
129 return getBuildType() == "userdebug";
130}
131
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700132#define BPF_FS_PATH "/sys/fs/bpf/"
133
134// Size of the BPF log buffer for verifier logging
135#define BPF_LOAD_LOG_SZ 0xfffff
136
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700137static unsigned int page_size = static_cast<unsigned int>(getpagesize());
138
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700139constexpr const char* lookupSelinuxContext(const domain d) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700140 switch (d) {
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700141 case domain::unspecified: return "";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700142 case domain::tethering: return "fs_bpf_tethering";
143 case domain::net_private: return "fs_bpf_net_private";
144 case domain::net_shared: return "fs_bpf_net_shared";
145 case domain::netd_readonly: return "fs_bpf_netd_readonly";
146 case domain::netd_shared: return "fs_bpf_netd_shared";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700147 }
148}
149
150domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
151 for (domain d : AllDomains) {
152 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
153 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
154 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
155 }
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700156 ALOGE("unrecognized selinux_context '%-32s'", s);
157 // Note: we *can* just abort() here as we only load bpf .o files shipped
158 // in the same mainline module / apex as NetBpfLoad itself.
159 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700160}
161
162constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
163 switch (d) {
164 case domain::unspecified: return unspecified;
165 case domain::tethering: return "tethering/";
166 case domain::net_private: return "net_private/";
167 case domain::net_shared: return "net_shared/";
168 case domain::netd_readonly: return "netd_readonly/";
169 case domain::netd_shared: return "netd_shared/";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700170 }
171};
172
173domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
174 for (domain d : AllDomains) {
175 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
176 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
177 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
178 }
179 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700180 // Note: we *can* just abort() here as we only load bpf .o files shipped
181 // in the same mainline module / apex as NetBpfLoad itself.
182 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700183}
184
185static string pathToObjName(const string& path) {
186 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
187 string filename = android::base::Split(path, "/").back();
188 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
189 string name = filename.substr(0, filename.find_last_of('.'));
190 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
191 // this can be used to provide duplicate programs (mux based on the bpfloader version)
192 return name.substr(0, name.find_last_of('@'));
193}
194
195typedef struct {
196 const char* name;
197 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000198 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700199} sectionType;
200
201/*
202 * Map section name prefixes to program types, the section name will be:
203 * SECTION(<prefix>/<name-of-program>)
204 * For example:
205 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
206 * is the name of the program, and tracepoint is the type.
207 *
208 * However, be aware that you should not be directly using the SECTION() macro.
209 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
210 *
211 * Programs shipped inside the tethering apex should be limited to networking stuff,
212 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
213 * since they are less stable abi/api and may conflict with platform uses of bpf.
214 */
215sectionType sectionNameTypes[] = {
216 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
217 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000218 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
219 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700220 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
221 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
222 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
223 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
224 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
225 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
226 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700227 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
228 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
229 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
230 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000231 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
232 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700233 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
234 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
235 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000236 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700237 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
238 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000239 {"xdp/", BPF_PROG_TYPE_XDP},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700240};
241
242typedef struct {
243 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000244 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700245 string name;
246 vector<char> data;
247 vector<char> rel_data;
248 optional<struct bpf_prog_def> prog_def;
249
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000250 unique_fd prog_fd; // fd after loading
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700251} codeSection;
252
253static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
254 elfFile.seekg(0);
255 if (elfFile.fail()) return -1;
256
257 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
258
259 return 0;
260}
261
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000262// Reads all section header tables into an Shdr array
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700263static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
264 Elf64_Ehdr eh;
265 int ret = 0;
266
267 ret = readElfHeader(elfFile, &eh);
268 if (ret) return ret;
269
270 elfFile.seekg(eh.e_shoff);
271 if (elfFile.fail()) return -1;
272
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000273 // Read shdr table entries
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700274 shTable.resize(eh.e_shnum);
275
276 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
277
278 return 0;
279}
280
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000281// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700282static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
283 vector<Elf64_Shdr> shTable;
284 int ret = readSectionHeadersAll(elfFile, shTable);
285 if (ret) return ret;
286
287 elfFile.seekg(shTable[id].sh_offset);
288 if (elfFile.fail()) return -1;
289
290 sec.resize(shTable[id].sh_size);
291 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
292
293 return 0;
294}
295
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000296// Read whole section header string table
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700297static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
298 Elf64_Ehdr eh;
299 int ret = readElfHeader(elfFile, &eh);
300 if (ret) return ret;
301
302 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
303 if (ret) return ret;
304
305 return 0;
306}
307
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000308// Get name from offset in strtab
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700309static int getSymName(ifstream& elfFile, int nameOff, string& name) {
310 int ret;
311 vector<char> secStrTab;
312
313 ret = readSectionHeaderStrtab(elfFile, secStrTab);
314 if (ret) return ret;
315
316 if (nameOff >= (int)secStrTab.size()) return -1;
317
318 name = string((char*)secStrTab.data() + nameOff);
319 return 0;
320}
321
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000322// Reads a full section by name - example to get the GPL license
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700323static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
324 vector<char> secStrTab;
325 vector<Elf64_Shdr> shTable;
326 int ret;
327
328 ret = readSectionHeadersAll(elfFile, shTable);
329 if (ret) return ret;
330
331 ret = readSectionHeaderStrtab(elfFile, secStrTab);
332 if (ret) return ret;
333
334 for (int i = 0; i < (int)shTable.size(); i++) {
335 char* secname = secStrTab.data() + shTable[i].sh_name;
336 if (!secname) continue;
337
338 if (!strcmp(secname, name)) {
339 vector<char> dataTmp;
340 dataTmp.resize(shTable[i].sh_size);
341
342 elfFile.seekg(shTable[i].sh_offset);
343 if (elfFile.fail()) return -1;
344
345 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
346
347 data = dataTmp;
348 return 0;
349 }
350 }
351 return -2;
352}
353
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700354unsigned int readSectionUint(const char* name, ifstream& elfFile) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700355 vector<char> theBytes;
356 int ret = readSectionByName(name, elfFile, theBytes);
357 if (ret) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700358 ALOGE("Couldn't find section %s.", name);
359 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700360 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700361 ALOGE("Section %s is too short.", name);
362 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700363 } else {
364 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
365 unsigned int value = static_cast<unsigned char>(theBytes[3]);
366 value <<= 8;
367 value += static_cast<unsigned char>(theBytes[2]);
368 value <<= 8;
369 value += static_cast<unsigned char>(theBytes[1]);
370 value <<= 8;
371 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000372 ALOGD("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700373 return value;
374 }
375}
376
377static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
378 int ret;
379 vector<Elf64_Shdr> shTable;
380
381 ret = readSectionHeadersAll(elfFile, shTable);
382 if (ret) return ret;
383
384 for (int i = 0; i < (int)shTable.size(); i++) {
385 if ((int)shTable[i].sh_type != type) continue;
386
387 vector<char> dataTmp;
388 dataTmp.resize(shTable[i].sh_size);
389
390 elfFile.seekg(shTable[i].sh_offset);
391 if (elfFile.fail()) return -1;
392
393 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
394
395 data = dataTmp;
396 return 0;
397 }
398 return -2;
399}
400
401static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
402 return (a.st_value < b.st_value);
403}
404
405static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
406 int ret, numElems;
407 Elf64_Sym* buf;
408 vector<char> secData;
409
410 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
411 if (ret) return ret;
412
413 buf = (Elf64_Sym*)secData.data();
414 numElems = (secData.size() / sizeof(Elf64_Sym));
415 data.assign(buf, buf + numElems);
416
417 if (sort) std::sort(data.begin(), data.end(), symCompare);
418 return 0;
419}
420
421static enum bpf_prog_type getSectionType(string& name) {
422 for (auto& snt : sectionNameTypes)
423 if (StartsWith(name, snt.name)) return snt.type;
424
425 return BPF_PROG_TYPE_UNSPEC;
426}
427
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700428static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700429 vector<char> pdData;
430 int ret = readSectionByName("progs", elfFile, pdData);
431 if (ret) return ret;
432
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700433 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700434 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700435 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700436 return -1;
437 };
438
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700439 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700440
441 const char* dataPtr = pdData.data();
442 for (auto& p : pd) {
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700443 // Copy the structure from the ELF file and move to the next one.
444 memcpy(&p, dataPtr, sizeof(struct bpf_prog_def));
445 dataPtr += sizeof(struct bpf_prog_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700446 }
447 return 0;
448}
449
450static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
451 optional<unsigned> symbolType = std::nullopt) {
452 int ret;
453 string name;
454 vector<Elf64_Sym> symtab;
455 vector<Elf64_Shdr> shTable;
456
457 ret = readSymTab(elfFile, 1 /* sort */, symtab);
458 if (ret) return ret;
459
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000460 // Get index of section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700461 ret = readSectionHeadersAll(elfFile, shTable);
462 if (ret) return ret;
463
464 int sec_idx = -1;
465 for (int i = 0; i < (int)shTable.size(); i++) {
466 ret = getSymName(elfFile, shTable[i].sh_name, name);
467 if (ret) return ret;
468
469 if (!name.compare(sectionName)) {
470 sec_idx = i;
471 break;
472 }
473 }
474
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000475 // No section found with matching name
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700476 if (sec_idx == -1) {
477 ALOGW("No %s section could be found in elf object", sectionName.c_str());
478 return -1;
479 }
480
481 for (int i = 0; i < (int)symtab.size(); i++) {
482 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
483
484 if (symtab[i].st_shndx == sec_idx) {
485 string s;
486 ret = getSymName(elfFile, symtab[i].st_name, s);
487 if (ret) return ret;
488 names.push_back(s);
489 }
490 }
491
492 return 0;
493}
494
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000495// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700496static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700497 vector<Elf64_Shdr> shTable;
498 int entries, ret = 0;
499
500 ret = readSectionHeadersAll(elfFile, shTable);
501 if (ret) return ret;
502 entries = shTable.size();
503
504 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700505 ret = readProgDefs(elfFile, pd);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700506 if (ret) return ret;
507 vector<string> progDefNames;
508 ret = getSectionSymNames(elfFile, "progs", progDefNames);
509 if (!pd.empty() && ret) return ret;
510
511 for (int i = 0; i < entries; i++) {
512 string name;
513 codeSection cs_temp;
514 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
515
516 ret = getSymName(elfFile, shTable[i].sh_name, name);
517 if (ret) return ret;
518
519 enum bpf_prog_type ptype = getSectionType(name);
520
521 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
522
523 // This must be done before '/' is replaced with '_'.
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000524 for (auto& snt : sectionNameTypes)
525 if (StartsWith(name, snt.name)) cs_temp.attach_type = snt.attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700526
527 string oldName = name;
528
529 // convert all slashes to underscores
530 std::replace(name.begin(), name.end(), '/', '_');
531
532 cs_temp.type = ptype;
533 cs_temp.name = name;
534
535 ret = readSectionByIdx(elfFile, i, cs_temp.data);
536 if (ret) return ret;
537 ALOGV("Loaded code section %d (%s)", i, name.c_str());
538
539 vector<string> csSymNames;
540 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
541 if (ret || !csSymNames.size()) return ret;
542 for (size_t i = 0; i < progDefNames.size(); ++i) {
543 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
544 cs_temp.prog_def = pd[i];
545 break;
546 }
547 }
548
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000549 // Check for rel section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700550 if (cs_temp.data.size() > 0 && i < entries) {
551 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
552 if (ret) return ret;
553
554 if (name == (".rel" + oldName)) {
555 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
556 if (ret) return ret;
557 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
558 }
559 }
560
561 if (cs_temp.data.size() > 0) {
562 cs.push_back(std::move(cs_temp));
563 ALOGV("Adding section %d to cs list", i);
564 }
565 }
566 return 0;
567}
568
569static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
570 vector<Elf64_Sym> symtab;
571 int ret = 0;
572
573 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
574 if (ret) return ret;
575
576 if (index >= (int)symtab.size()) return -1;
577
578 return getSymName(elfFile, symtab[index].st_name, name);
579}
580
581static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
582 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
583 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
584 // so on 4.9-T kernels just pretend the map matches our expectations.
585 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
586 // This is because the primary failure mode we're trying to detect here
587 // is either a source code misconfiguration (which is likely kernel independent)
588 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
589 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
590
591 // Assuming fd is a valid Bpf Map file descriptor then
592 // all the following should always succeed on a 4.14+ kernel.
593 // If they somehow do fail, they'll return -1 (and set errno),
594 // which should then cause (among others) a key_size mismatch.
595 int fd_type = bpfGetFdMapType(fd);
596 int fd_key_size = bpfGetFdKeySize(fd);
597 int fd_value_size = bpfGetFdValueSize(fd);
598 int fd_max_entries = bpfGetFdMaxEntries(fd);
599 int fd_map_flags = bpfGetFdMapFlags(fd);
600
601 // DEVMAPs are readonly from the bpf program side's point of view, as such
602 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
603 int desired_map_flags = (int)mapDef.map_flags;
604 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
605 desired_map_flags |= BPF_F_RDONLY_PROG;
606
Maciej Żenczykowskidcb2e742024-08-29 10:40:35 -0700607 if (type == BPF_MAP_TYPE_LPM_TRIE)
608 desired_map_flags |= BPF_F_NO_PREALLOC;
609
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700610 // 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,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700641 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700642 int ret;
643 vector<char> mdData;
644 vector<struct bpf_map_def> md;
645 vector<string> mapNames;
646 string objName = pathToObjName(string(elfPath));
647
648 ret = readSectionByName("maps", elfFile, mdData);
649 if (ret == -2) return 0; // no maps to read
650 if (ret) return ret;
651
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700652 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700653 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700654 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700655 return -1;
656 };
657
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700658 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700659
660 const char* dataPtr = mdData.data();
661 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700662 // Copy the structure from the ELF file and move to the next one.
663 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
664 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700665 }
666
667 ret = getSectionSymNames(elfFile, "maps", mapNames);
668 if (ret) return ret;
669
670 unsigned kvers = kernelVersion();
671
672 for (int i = 0; i < (int)mapNames.size(); i++) {
673 if (md[i].zero != 0) abort();
674
675 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000676 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700677 md[i].bpfloader_min_ver);
678 mapFds.push_back(unique_fd());
679 continue;
680 }
681
682 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000683 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700684 md[i].bpfloader_max_ver);
685 mapFds.push_back(unique_fd());
686 continue;
687 }
688
689 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000690 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700691 mapNames[i].c_str(), kvers, md[i].min_kver);
692 mapFds.push_back(unique_fd());
693 continue;
694 }
695
696 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000697 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700698 mapNames[i].c_str(), kvers, md[i].max_kver);
699 mapFds.push_back(unique_fd());
700 continue;
701 }
702
703 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
704 (md[i].ignore_on_userdebug && isUserdebug())) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000705 ALOGD("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700706 getBuildType().c_str());
707 mapFds.push_back(unique_fd());
708 continue;
709 }
710
711 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
712 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
713 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
714 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
715 (isRiscV() && md[i].ignore_on_riscv64)) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000716 ALOGD("skipping map %s which is ignored on %s", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700717 describeArch());
718 mapFds.push_back(unique_fd());
719 continue;
720 }
721
722 enum bpf_map_type type = md[i].type;
723 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
724 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
725 // of be approximated: ARRAY has the same userspace api, though it is not usable
726 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
727 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
728 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
729 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
730 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
731 type = BPF_MAP_TYPE_ARRAY;
732 }
733 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
734 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
735 // of be approximated: HASH has the same userspace visible api.
736 // However it cannot be used by ebpf programs in the same way.
737 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
738 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
739 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
740 // programs as being 5.4+...
741 type = BPF_MAP_TYPE_HASH;
742 }
743
744 // The .h file enforces that this is a power of two, and page size will
745 // also always be a power of two, so this logic is actually enough to
746 // force it to be a multiple of the page size, as required by the kernel.
747 unsigned int max_entries = md[i].max_entries;
748 if (type == BPF_MAP_TYPE_RINGBUF) {
749 if (max_entries < page_size) max_entries = page_size;
750 }
751
752 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
753 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000754 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700755 md[i].selinux_context, static_cast<int>(selinux_context),
756 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
757 }
758
759 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700760 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000761 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700762 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
763 }
764
765 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
766 // except that maps shared across .o's have empty <objName>
767 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
768 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
769 (md[i].shared ? "" : objName) + "_" + mapNames[i];
770 bool reuse = false;
771 unique_fd fd;
772 int saved_errno;
773
774 if (access(mapPinLoc.c_str(), F_OK) == 0) {
775 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
776 saved_errno = errno;
777 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
778 reuse = true;
779 } else {
780 union bpf_attr req = {
781 .map_type = type,
782 .key_size = md[i].key_size,
783 .value_size = md[i].value_size,
784 .max_entries = max_entries,
Maciej Żenczykowskidcb2e742024-08-29 10:40:35 -0700785 .map_flags = md[i].map_flags | (type == BPF_MAP_TYPE_LPM_TRIE ? BPF_F_NO_PREALLOC : 0),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700786 };
787 if (isAtLeastKernelVersion(4, 15, 0))
788 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
789 fd.reset(bpf(BPF_MAP_CREATE, req));
790 saved_errno = errno;
791 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
792 }
793
794 if (!fd.ok()) return -saved_errno;
795
796 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
797 // safety (since reuse code path is rare) run these checks even if we just created it.
798 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
799 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
800
801 if (!reuse) {
802 if (specified(selinux_context)) {
803 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
804 "tmp_map_" + objName + "_" + mapNames[i];
805 ret = bpfFdPin(fd, createLoc.c_str());
806 if (ret) {
807 int err = errno;
808 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
809 return -err;
810 }
811 ret = renameat2(AT_FDCWD, createLoc.c_str(),
812 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
813 if (ret) {
814 int err = errno;
815 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
816 err, strerror(err));
817 return -err;
818 }
819 } else {
820 ret = bpfFdPin(fd, mapPinLoc.c_str());
821 if (ret) {
822 int err = errno;
823 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
824 return -err;
825 }
826 }
827 ret = chmod(mapPinLoc.c_str(), md[i].mode);
828 if (ret) {
829 int err = errno;
830 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
831 strerror(err));
832 return -err;
833 }
834 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
835 if (ret) {
836 int err = errno;
837 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
838 ret, err, strerror(err));
839 return -err;
840 }
841 }
842
843 int mapId = bpfGetFdMapId(fd);
844 if (mapId == -1) {
Maciej Żenczykowski508c8f72024-08-28 15:07:33 -0700845 if (isAtLeastKernelVersion(4, 14, 0))
846 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700847 } else {
848 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
849 }
850
851 mapFds.push_back(std::move(fd));
852 }
853
854 return ret;
855}
856
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700857static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
858 int insnIndex;
859 struct bpf_insn *insn, *insns;
860
861 insns = (struct bpf_insn*)(insnsPtr);
862
863 insnIndex = offset / sizeof(struct bpf_insn);
864 insn = &insns[insnIndex];
865
866 // Occasionally might be useful for relocation debugging, but pretty spammy
867 if (0) {
868 ALOGV("applying relo to instruction at byte offset: %llu, "
869 "insn offset %d, insn %llx",
870 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
871 }
872
873 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700874 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700875 return;
876 }
877
878 insn->imm = fd;
879 insn->src_reg = BPF_PSEUDO_MAP_FD;
880}
881
882static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
883 vector<string> mapNames;
884
885 int ret = getSectionSymNames(elfFile, "maps", mapNames);
886 if (ret) return;
887
888 for (int k = 0; k != (int)cs.size(); k++) {
889 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
890 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
891
892 for (int i = 0; i < n_rel; i++) {
893 int symIndex = ELF64_R_SYM(rel[i].r_info);
894 string symName;
895
896 ret = getSymNameByIdx(elfFile, symIndex, symName);
897 if (ret) return;
898
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000899 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700900 for (int j = 0; j < (int)mapNames.size(); j++) {
901 if (!mapNames[j].compare(symName)) {
902 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
903 break;
904 }
905 }
906 }
907 }
908}
909
910static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
911 const char* prefix, const unsigned int bpfloader_ver) {
912 unsigned kvers = kernelVersion();
913
914 if (!kvers) {
915 ALOGE("unable to get kernel version");
916 return -EINVAL;
917 }
918
919 string objName = pathToObjName(string(elfPath));
920
921 for (int i = 0; i < (int)cs.size(); i++) {
922 unique_fd& fd = cs[i].prog_fd;
923 int ret;
924 string name = cs[i].name;
925
926 if (!cs[i].prog_def.has_value()) {
927 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
928 return -EINVAL;
929 }
930
931 unsigned min_kver = cs[i].prog_def->min_kver;
932 unsigned max_kver = cs[i].prog_def->max_kver;
933 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
934 max_kver, kvers);
935 if (kvers < min_kver) continue;
936 if (kvers >= max_kver) continue;
937
938 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
939 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
940 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
941 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700942
943 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
944 bpfMinVer, bpfMaxVer);
945 if (bpfloader_ver < bpfMinVer) continue;
946 if (bpfloader_ver >= bpfMaxVer) continue;
947
948 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
949 (cs[i].prog_def->ignore_on_user && isUser()) ||
950 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
951 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
952 getBuildType().c_str());
953 continue;
954 }
955
956 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
957 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
958 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
959 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
960 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
961 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
962 continue;
963 }
964
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700965 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000966 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700967 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
968 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
969 }
970
971 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000972 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700973 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
974 lookupPinSubdir(pin_subdir));
975 }
976
977 // strip any potential $foo suffix
978 // this can be used to provide duplicate programs
979 // conditionally loaded based on running kernel version
980 name = name.substr(0, name.find_last_of('$'));
981
982 bool reuse = false;
983 // Format of pin location is
984 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
985 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
986 objName + '_' + string(name);
987 if (access(progPinLoc.c_str(), F_OK) == 0) {
988 fd.reset(retrieveProgram(progPinLoc.c_str()));
989 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
990 (!fd.ok() ? std::strerror(errno) : "no error"));
991 reuse = true;
992 } else {
993 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
994
995 union bpf_attr req = {
996 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700997 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -0700998 .insns = ptr_to_u64(cs[i].data.data()),
999 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001000 .log_level = 1,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001001 .log_size = static_cast<__u32>(log_buf.size()),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001002 .log_buf = ptr_to_u64(log_buf.data()),
1003 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001004 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001005 };
1006 if (isAtLeastKernelVersion(4, 15, 0))
1007 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1008 fd.reset(bpf(BPF_PROG_LOAD, req));
1009
1010 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
1011 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
1012
1013 if (!fd.ok()) {
1014 vector<string> lines = android::base::Split(log_buf.data(), "\n");
1015
1016 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1017 for (const auto& line : lines) ALOGW("%s", line.c_str());
1018 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1019
1020 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001021 ALOGW("failed program %s is marked optional - continuing...",
1022 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001023 continue;
1024 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001025 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001026 }
1027 }
1028
1029 if (!fd.ok()) return fd.get();
1030
1031 if (!reuse) {
1032 if (specified(selinux_context)) {
1033 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1034 "tmp_prog_" + objName + '_' + string(name);
1035 ret = bpfFdPin(fd, createLoc.c_str());
1036 if (ret) {
1037 int err = errno;
1038 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1039 return -err;
1040 }
1041 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1042 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1043 if (ret) {
1044 int err = errno;
1045 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1046 err, strerror(err));
1047 return -err;
1048 }
1049 } else {
1050 ret = bpfFdPin(fd, progPinLoc.c_str());
1051 if (ret) {
1052 int err = errno;
1053 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1054 return -err;
1055 }
1056 }
1057 if (chmod(progPinLoc.c_str(), 0440)) {
1058 int err = errno;
1059 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1060 return -err;
1061 }
1062 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1063 (gid_t)cs[i].prog_def->gid)) {
1064 int err = errno;
1065 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1066 cs[i].prog_def->gid, err, strerror(err));
1067 return -err;
1068 }
1069 }
1070
1071 int progId = bpfGetFdProgId(fd);
1072 if (progId == -1) {
1073 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
1074 } else {
1075 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
1076 }
1077 }
1078
1079 return 0;
1080}
1081
1082int loadProg(const char* const elfPath, bool* const isCritical, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001083 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001084 vector<char> license;
1085 vector<char> critical;
1086 vector<codeSection> cs;
1087 vector<unique_fd> mapFds;
1088 int ret;
1089
1090 if (!isCritical) return -1;
1091 *isCritical = false;
1092
1093 ifstream elfFile(elfPath, ios::in | ios::binary);
1094 if (!elfFile.is_open()) return -1;
1095
1096 ret = readSectionByName("critical", elfFile, critical);
1097 *isCritical = !ret;
1098
1099 ret = readSectionByName("license", elfFile, license);
1100 if (ret) {
1101 ALOGE("Couldn't find license in %s", elfPath);
1102 return ret;
1103 } else {
1104 ALOGD("Loading %s%s ELF object %s with license %s",
1105 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
1106 elfPath, (char*)license.data());
1107 }
1108
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001109 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1110 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001111
1112 // inclusive lower bound check
1113 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001114 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001115 bpfloader_ver, elfPath, bpfLoaderMinVer);
1116 return 0;
1117 }
1118
1119 // exclusive upper bound check
1120 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001121 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001122 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1123 return 0;
1124 }
1125
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001126 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001127 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1128
Maciej Żenczykowskie666d852024-08-15 15:03:38 -07001129 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001130 if (ret) {
1131 ALOGE("Couldn't read all code sections in %s", elfPath);
1132 return ret;
1133 }
1134
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001135 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001136 if (ret) {
1137 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1138 return ret;
1139 }
1140
1141 for (int i = 0; i < (int)mapFds.size(); i++)
1142 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1143
1144 applyMapRelo(elfFile, mapFds, cs);
1145
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001146 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001147 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1148
1149 return ret;
1150}
1151
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001152static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001153 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001154 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001155 if (errno == ENOENT) return false;
1156 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1157 abort(); // can only hit this if permissions (likely selinux) are screwed up
1158}
1159
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001160#define APEXROOT "/apex/com.android.tethering"
1161#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001162
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001163const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001164 // S+ Tethering mainline module (network_stack): tether offload
1165 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001166 .dir = BPFROOT "/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001167 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001168 },
1169 // T+ Tethering mainline module (shared with netd & system server)
1170 // netutils_wrapper (for iptables xt_bpf) has access to programs
1171 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001172 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001173 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001174 },
1175 // T+ Tethering mainline module (shared with netd & system server)
1176 // netutils_wrapper has no access, netd has read only access
1177 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001178 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001179 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001180 },
1181 // T+ Tethering mainline module (shared with system server)
1182 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001183 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001184 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001185 },
1186 // T+ Tethering mainline module (not shared, just network_stack)
1187 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001188 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001189 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001190 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001191};
1192
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001193static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001194 int retVal = 0;
1195 DIR* dir;
1196 struct dirent* ent;
1197
1198 if ((dir = opendir(location.dir)) != NULL) {
1199 while ((ent = readdir(dir)) != NULL) {
1200 string s = ent->d_name;
1201 if (!EndsWith(s, ".o")) continue;
1202
1203 string progPath(location.dir);
1204 progPath += s;
1205
1206 bool critical;
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001207 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001208 if (ret) {
1209 if (critical) retVal = ret;
1210 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1211 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001212 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001213 }
1214 }
1215 closedir(dir);
1216 }
1217 return retVal;
1218}
1219
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001220static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001221 if (*prefix) {
1222 mode_t prevUmask = umask(0);
1223
1224 string s = "/sys/fs/bpf/";
1225 s += prefix;
1226
1227 errno = 0;
1228 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1229 if (ret && errno != EEXIST) {
1230 const int err = errno;
1231 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1232 return -err;
1233 }
1234
1235 umask(prevUmask);
1236 }
1237 return 0;
1238}
1239
1240// Technically 'value' doesn't need to be newline terminated, but it's best
1241// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1242// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001243static int writeProcSysFile(const char *filename, const char *value) {
1244 base::unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001245 if (fd < 0) {
1246 const int err = errno;
1247 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1248 return -err;
1249 }
1250 int len = strlen(value);
1251 int v = write(fd, value, len);
1252 if (v < 0) {
1253 const int err = errno;
1254 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1255 return -err;
1256 }
1257 if (v != len) {
1258 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1259 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1260 return -EINVAL;
1261 }
1262 return 0;
1263}
1264
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001265#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001266const char * const platformBpfLoader = "/system/bin/bpfloader";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001267
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001268static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001269 char * found_blockdev = NULL;
1270 FILE * f = NULL;
1271 char buf[4096];
1272
1273 f = fopen("/proc/mounts", "re");
1274 if (!f) return 1;
1275
1276 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1277 while (fgets(buf, sizeof(buf), f)) {
1278 char * blockdev = buf;
1279 char * space = strchr(blockdev, ' ');
1280 if (!space) continue;
1281 *space = '\0';
1282 char * mntpath = space + 1;
1283 space = strchr(mntpath, ' ');
1284 if (!space) continue;
1285 *space = '\0';
1286 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1287 found_blockdev = strdup(blockdev);
1288 break;
1289 }
1290 fclose(f);
1291 f = NULL;
1292
1293 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001294 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001295
1296 f = fopen("/proc/mounts", "re");
1297 if (!f) { free(found_blockdev); return 3; }
1298
1299 while (fgets(buf, sizeof(buf), f)) {
1300 char * blockdev = buf;
1301 char * space = strchr(blockdev, ' ');
1302 if (!space) continue;
1303 *space = '\0';
1304 char * mntpath = space + 1;
1305 space = strchr(mntpath, ' ');
1306 if (!space) continue;
1307 *space = '\0';
1308 if (strcmp(blockdev, found_blockdev)) continue;
1309 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1310 char * at = strchr(mntpath, '@');
1311 if (!at) continue;
1312 char * ver = at + 1;
1313 ALOGI("Tethering APEX version %s", ver);
1314 }
1315 fclose(f);
1316 free(found_blockdev);
1317 return 0;
1318}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001319
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001320static bool hasGSM() {
1321 static string ph = base::GetProperty("gsm.current.phone-type", "");
1322 static bool gsm = (ph != "");
1323 static bool logged = false;
1324 if (!logged) {
1325 logged = true;
1326 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1327 }
1328 return gsm;
1329}
1330
1331static bool isTV() {
1332 if (hasGSM()) return false; // TVs don't do GSM
1333
1334 static string key = base::GetProperty("ro.oem.key1", "");
1335 static bool tv = StartsWith(key, "ATV00");
1336 static bool logged = false;
1337 if (!logged) {
1338 logged = true;
1339 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1340 }
1341 return tv;
1342}
1343
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001344static bool isWear() {
1345 static string wearSdkStr = base::GetProperty("ro.cw_build.wear_sdk.version", "");
1346 static int wearSdkInt = base::GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1347 static string buildChars = base::GetProperty("ro.build.characteristics", "");
1348 static vector<string> v = base::Tokenize(buildChars, ",");
1349 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1350 static bool wear = (wearSdkInt > 0) || watch;
1351 static bool logged = false;
1352 if (!logged) {
1353 logged = true;
1354 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1355 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1356 }
1357 return wear;
1358}
1359
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001360static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001361 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001362
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001363 // Any released device will have codename REL instead of a 'real' codename.
1364 // For safety: default to 'REL' so we default to unreleased=false on failure.
1365 const bool unreleased = (base::GetProperty("ro.build.version.codename", "REL") != "REL");
1366
1367 // goog/main device_api_level is bumped *way* before aosp/main api level
1368 // (the latter only gets bumped during the push of goog/main to aosp/main)
1369 //
1370 // Since we develop in AOSP, we want it to behave as if it was bumped too.
1371 //
1372 // Note that AOSP doesn't really have a good api level (for example during
1373 // early V dev cycle, it would have *all* of T, some but not all of U, and some V).
1374 // One could argue that for our purposes AOSP api level should be infinite or 10000.
1375 //
1376 // This could also cause api to be increased in goog/main or other branches,
1377 // but I can't imagine a case where this would be a problem: the problem
1378 // is rather a too low api level, rather than some ill defined high value.
1379 // For example as I write this aosp is 34/U, and goog is 35/V,
1380 // we want to treat both goog & aosp as 35/V, but it's harmless if we
1381 // treat goog as 36 because that value isn't yet defined to mean anything,
1382 // and we thus never compare against it.
1383 //
1384 // Also note that 'android_get_device_api_level()' is what the
1385 // //system/core/init/apex_init_util.cpp
1386 // apex init .XXrc parsing code uses for XX filtering.
1387 //
1388 // That code has a hack to bump <35 to 35 (to force aosp/main to parse .35rc),
1389 // but could (should?) perhaps be adjusted to match this.
1390 const int effective_api_level = android_get_device_api_level() + (int)unreleased;
1391 const bool isAtLeastT = (effective_api_level >= __ANDROID_API_T__);
1392 const bool isAtLeastU = (effective_api_level >= __ANDROID_API_U__);
1393 const bool isAtLeastV = (effective_api_level >= __ANDROID_API_V__);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001394
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001395 // last in U QPR2 beta1
1396 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1397 // first in U QPR2 beta~2
1398 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1399
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001400 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001401 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
1402 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1403 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1404 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1405 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001406
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001407 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) uid:%d rc:%d%d",
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001408 bpfloader_ver, argv[0], android_get_device_api_level(), effective_api_level,
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001409 kernelVersion(), describeArch(), getuid(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001410 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001411
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001412 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1413 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1414 return 1;
1415 }
1416
1417 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1418 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1419 return 1;
1420 }
1421
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001422 logTetheringApexVersion();
1423
Maciej Żenczykowski11141da2024-03-15 18:21:33 -07001424 if (!isAtLeastT) {
1425 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001426 return 1;
1427 }
1428
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001429 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001430 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001431 ALOGE("Android T requires kernel 4.9.");
1432 return 1;
1433 }
1434
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001435 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001436 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001437 ALOGE("Android U requires kernel 4.14.");
1438 return 1;
1439 }
1440
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001441 // V bumps the kernel requirement up to 4.19
1442 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001443 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001444 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001445 return 1;
1446 }
1447
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001448 // Technically already required by U, but only enforce on V+
1449 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1450 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1451 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1452 if (!isTV()) return 1;
1453 }
1454
1455 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1456 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001457 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001458 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001459 }
1460
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001461 if (isAtLeastV) {
1462 bool bad = false;
1463
1464 if (!isLtsKernel()) {
1465 ALOGW("Android V only supports LTS kernels.");
1466 bad = true;
1467 }
1468
1469#define REQUIRE(maj, min, sub) \
1470 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
1471 ALOGW("Android V requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
1472 bad = true; \
1473 }
1474
1475 REQUIRE(4, 19, 236)
1476 REQUIRE(5, 4, 186)
1477 REQUIRE(5, 10, 199)
1478 REQUIRE(5, 15, 136)
1479 REQUIRE(6, 1, 57)
1480 REQUIRE(6, 6, 0)
1481
1482#undef REQUIRE
1483
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001484 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001485 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1486 }
1487 }
1488
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001489 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001490 /* Android 14/U should only launch on 64-bit kernels
1491 * T launches on 5.10/5.15
1492 * U launches on 5.15/6.1
1493 * So >=5.16 implies isKernel64Bit()
1494 *
1495 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1496 *
1497 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1498 * we also require 64-bit userspace.
1499 *
1500 * There are various known issues with 32-bit userspace talking to various
1501 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1502 * Some of these have userspace or kernel workarounds/hacks.
1503 * Some of them don't...
1504 * We're going to be removing the hacks.
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001505 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1506 * Note: this check/enforcement only applies to *system* userspace code,
1507 * it does not affect unprivileged apps, the 32-on-64 compatibility
1508 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001509 *
1510 * Additionally the 32-bit kernel jit support is poor,
1511 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
1512 */
1513 ALOGE("64-bit userspace required on 6.2+ kernels.");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001514 // Stuff won't work reliably, but exempt TVs & Arm Wear devices
1515 if (!isTV() && !(isWear() && isArm())) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001516 }
1517
1518 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001519 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001520 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001521 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001522 return 1;
1523 }
1524
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001525 if (runningAsRoot) {
1526 // Note: writing this proc file requires being root (always the case on V+)
1527
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001528 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1529 // but we need 0 (enabled)
1530 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1531 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1532 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001533 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001534 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001535
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001536 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001537 // Note: writing these proc files requires CAP_NET_ADMIN
1538 // and sepolicy which is only present on U+,
1539 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1540 // trigger (ie. by init itself) instead.
1541
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001542 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1543 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1544 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1545 // kernel does not have CONFIG_BPF_JIT=y)
1546 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1547 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1548 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001549
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001550 // Enable JIT kallsyms export for privileged users only
1551 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1552 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1553 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1554 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001555
1556 // Create all the pin subdirectories
1557 // (this must be done first to allow selinux_context and pin_subdir functionality,
1558 // which could otherwise fail with ENOENT during object pinning or renaming,
1559 // due to ordering issues)
1560 for (const auto& location : locations) {
1561 if (createSysFsBpfSubDir(location.prefix)) return 1;
1562 }
1563
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001564 // Note: there's no actual src dir for fs_bpf_loader .o's,
1565 // so it is not listed in 'locations[].prefix'.
1566 // This is because this is primarily meant for triggering genfscon rules,
1567 // and as such this will likely always be the case.
1568 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1569 if (createSysFsBpfSubDir("loader")) return 1;
1570
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001571 // Load all ELF objects, create programs and maps, and pin them
1572 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001573 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001574 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1575 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1576 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1577 "problems or startup script race.");
1578 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1579 sleep(20);
1580 return 2;
1581 }
1582 }
1583
1584 int key = 1;
1585 int value = 123;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001586 base::unique_fd map(
1587 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1588 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001589 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1590 return 1;
1591 }
1592
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001593 // leave a flag that we're done
1594 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001595
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001596 // platform bpfloader will only succeed when run as root
1597 if (!runningAsRoot) {
1598 // unreachable on U QPR3+ which always runs netbpfload as root
1599
1600 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1601 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001602 }
1603
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001604 // unreachable before U QPR3
1605 ALOGI("done, transferring control to platform bpfloader.");
1606
1607 // platform BpfLoader *needs* to run as root
1608 const char * args[] = { platformBpfLoader, NULL, };
1609 execve(args[0], (char**)args, envp);
1610 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1611 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001612}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001613
1614} // namespace bpf
1615} // namespace android
1616
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001617int main(int argc, char** argv, char * const envp[]) {
1618 android::base::InitLogging(argv, &android::base::KernelLogger);
1619
1620 if (argc == 2 && !strcmp(argv[1], "done")) {
1621 // we're being re-exec'ed from platform bpfloader to 'finalize' things
1622 if (!android::base::SetProperty("bpf.progs_loaded", "1")) {
1623 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1624 return 125;
1625 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001626 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001627 return 0;
1628 }
1629
1630 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001631}