blob: 3300e922a67e8745bddbdffb94f47dce8de9fb33 [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;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -0700791 if (fd.ok()) {
792 ALOGD("bpf_create_map[%s] -> %d", mapNames[i].c_str(), fd.get());
793 } else {
794 ALOGE("bpf_create_map[%s] -> %d errno:%d", mapNames[i].c_str(), fd.get(), saved_errno);
795 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700796 }
797
798 if (!fd.ok()) return -saved_errno;
799
800 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
801 // safety (since reuse code path is rare) run these checks even if we just created it.
802 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
803 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
804
805 if (!reuse) {
806 if (specified(selinux_context)) {
807 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
808 "tmp_map_" + objName + "_" + mapNames[i];
809 ret = bpfFdPin(fd, createLoc.c_str());
810 if (ret) {
811 int err = errno;
812 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
813 return -err;
814 }
815 ret = renameat2(AT_FDCWD, createLoc.c_str(),
816 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
817 if (ret) {
818 int err = errno;
819 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
820 err, strerror(err));
821 return -err;
822 }
823 } else {
824 ret = bpfFdPin(fd, mapPinLoc.c_str());
825 if (ret) {
826 int err = errno;
827 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
828 return -err;
829 }
830 }
831 ret = chmod(mapPinLoc.c_str(), md[i].mode);
832 if (ret) {
833 int err = errno;
834 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
835 strerror(err));
836 return -err;
837 }
838 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
839 if (ret) {
840 int err = errno;
841 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
842 ret, err, strerror(err));
843 return -err;
844 }
845 }
846
847 int mapId = bpfGetFdMapId(fd);
848 if (mapId == -1) {
Maciej Żenczykowski508c8f72024-08-28 15:07:33 -0700849 if (isAtLeastKernelVersion(4, 14, 0))
850 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700851 } else {
852 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
853 }
854
855 mapFds.push_back(std::move(fd));
856 }
857
858 return ret;
859}
860
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700861static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
862 int insnIndex;
863 struct bpf_insn *insn, *insns;
864
865 insns = (struct bpf_insn*)(insnsPtr);
866
867 insnIndex = offset / sizeof(struct bpf_insn);
868 insn = &insns[insnIndex];
869
870 // Occasionally might be useful for relocation debugging, but pretty spammy
871 if (0) {
872 ALOGV("applying relo to instruction at byte offset: %llu, "
873 "insn offset %d, insn %llx",
874 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
875 }
876
877 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700878 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700879 return;
880 }
881
882 insn->imm = fd;
883 insn->src_reg = BPF_PSEUDO_MAP_FD;
884}
885
886static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
887 vector<string> mapNames;
888
889 int ret = getSectionSymNames(elfFile, "maps", mapNames);
890 if (ret) return;
891
892 for (int k = 0; k != (int)cs.size(); k++) {
893 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
894 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
895
896 for (int i = 0; i < n_rel; i++) {
897 int symIndex = ELF64_R_SYM(rel[i].r_info);
898 string symName;
899
900 ret = getSymNameByIdx(elfFile, symIndex, symName);
901 if (ret) return;
902
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000903 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700904 for (int j = 0; j < (int)mapNames.size(); j++) {
905 if (!mapNames[j].compare(symName)) {
906 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
907 break;
908 }
909 }
910 }
911 }
912}
913
914static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
915 const char* prefix, const unsigned int bpfloader_ver) {
916 unsigned kvers = kernelVersion();
917
918 if (!kvers) {
919 ALOGE("unable to get kernel version");
920 return -EINVAL;
921 }
922
923 string objName = pathToObjName(string(elfPath));
924
925 for (int i = 0; i < (int)cs.size(); i++) {
926 unique_fd& fd = cs[i].prog_fd;
927 int ret;
928 string name = cs[i].name;
929
930 if (!cs[i].prog_def.has_value()) {
931 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
932 return -EINVAL;
933 }
934
935 unsigned min_kver = cs[i].prog_def->min_kver;
936 unsigned max_kver = cs[i].prog_def->max_kver;
937 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
938 max_kver, kvers);
939 if (kvers < min_kver) continue;
940 if (kvers >= max_kver) continue;
941
942 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
943 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
944 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
945 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700946
947 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
948 bpfMinVer, bpfMaxVer);
949 if (bpfloader_ver < bpfMinVer) continue;
950 if (bpfloader_ver >= bpfMaxVer) continue;
951
952 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
953 (cs[i].prog_def->ignore_on_user && isUser()) ||
954 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
955 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
956 getBuildType().c_str());
957 continue;
958 }
959
960 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
961 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
962 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
963 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
964 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
965 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
966 continue;
967 }
968
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700969 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000970 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700971 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
972 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
973 }
974
975 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000976 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700977 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
978 lookupPinSubdir(pin_subdir));
979 }
980
981 // strip any potential $foo suffix
982 // this can be used to provide duplicate programs
983 // conditionally loaded based on running kernel version
984 name = name.substr(0, name.find_last_of('$'));
985
986 bool reuse = false;
987 // Format of pin location is
988 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
989 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
990 objName + '_' + string(name);
991 if (access(progPinLoc.c_str(), F_OK) == 0) {
992 fd.reset(retrieveProgram(progPinLoc.c_str()));
993 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
994 (!fd.ok() ? std::strerror(errno) : "no error"));
995 reuse = true;
996 } else {
997 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
998
999 union bpf_attr req = {
1000 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001001 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001002 .insns = ptr_to_u64(cs[i].data.data()),
1003 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001004 .log_level = 1,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001005 .log_size = static_cast<__u32>(log_buf.size()),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001006 .log_buf = ptr_to_u64(log_buf.data()),
1007 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001008 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001009 };
1010 if (isAtLeastKernelVersion(4, 15, 0))
1011 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1012 fd.reset(bpf(BPF_PROG_LOAD, req));
1013
1014 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
1015 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
1016
1017 if (!fd.ok()) {
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001018 if (log_buf.size()) {
1019 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001020
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001021 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1022 for (const auto& line : lines) ALOGW("%s", line.c_str());
1023 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1024 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001025
1026 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001027 ALOGW("failed program %s is marked optional - continuing...",
1028 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001029 continue;
1030 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001031 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001032 }
1033 }
1034
1035 if (!fd.ok()) return fd.get();
1036
1037 if (!reuse) {
1038 if (specified(selinux_context)) {
1039 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1040 "tmp_prog_" + objName + '_' + string(name);
1041 ret = bpfFdPin(fd, createLoc.c_str());
1042 if (ret) {
1043 int err = errno;
1044 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1045 return -err;
1046 }
1047 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1048 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1049 if (ret) {
1050 int err = errno;
1051 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1052 err, strerror(err));
1053 return -err;
1054 }
1055 } else {
1056 ret = bpfFdPin(fd, progPinLoc.c_str());
1057 if (ret) {
1058 int err = errno;
1059 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1060 return -err;
1061 }
1062 }
1063 if (chmod(progPinLoc.c_str(), 0440)) {
1064 int err = errno;
1065 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1066 return -err;
1067 }
1068 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1069 (gid_t)cs[i].prog_def->gid)) {
1070 int err = errno;
1071 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1072 cs[i].prog_def->gid, err, strerror(err));
1073 return -err;
1074 }
1075 }
1076
1077 int progId = bpfGetFdProgId(fd);
1078 if (progId == -1) {
1079 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
1080 } else {
1081 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
1082 }
1083 }
1084
1085 return 0;
1086}
1087
1088int loadProg(const char* const elfPath, bool* const isCritical, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001089 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001090 vector<char> license;
1091 vector<char> critical;
1092 vector<codeSection> cs;
1093 vector<unique_fd> mapFds;
1094 int ret;
1095
1096 if (!isCritical) return -1;
1097 *isCritical = false;
1098
1099 ifstream elfFile(elfPath, ios::in | ios::binary);
1100 if (!elfFile.is_open()) return -1;
1101
1102 ret = readSectionByName("critical", elfFile, critical);
1103 *isCritical = !ret;
1104
1105 ret = readSectionByName("license", elfFile, license);
1106 if (ret) {
1107 ALOGE("Couldn't find license in %s", elfPath);
1108 return ret;
1109 } else {
1110 ALOGD("Loading %s%s ELF object %s with license %s",
1111 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
1112 elfPath, (char*)license.data());
1113 }
1114
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001115 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1116 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001117
1118 // inclusive lower bound check
1119 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001120 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001121 bpfloader_ver, elfPath, bpfLoaderMinVer);
1122 return 0;
1123 }
1124
1125 // exclusive upper bound check
1126 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001127 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001128 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1129 return 0;
1130 }
1131
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001132 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001133 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1134
Maciej Żenczykowskie666d852024-08-15 15:03:38 -07001135 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001136 if (ret) {
1137 ALOGE("Couldn't read all code sections in %s", elfPath);
1138 return ret;
1139 }
1140
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001141 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001142 if (ret) {
1143 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1144 return ret;
1145 }
1146
1147 for (int i = 0; i < (int)mapFds.size(); i++)
1148 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1149
1150 applyMapRelo(elfFile, mapFds, cs);
1151
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001152 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001153 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1154
1155 return ret;
1156}
1157
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001158static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001159 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001160 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001161 if (errno == ENOENT) return false;
1162 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1163 abort(); // can only hit this if permissions (likely selinux) are screwed up
1164}
1165
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001166#define APEXROOT "/apex/com.android.tethering"
1167#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001168
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001169const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001170 // S+ Tethering mainline module (network_stack): tether offload
1171 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001172 .dir = BPFROOT "/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001173 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001174 },
1175 // T+ Tethering mainline module (shared with netd & system server)
1176 // netutils_wrapper (for iptables xt_bpf) has access to programs
1177 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001178 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001179 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001180 },
1181 // T+ Tethering mainline module (shared with netd & system server)
1182 // netutils_wrapper has no access, netd has read only access
1183 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001184 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001185 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001186 },
1187 // T+ Tethering mainline module (shared with system server)
1188 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001189 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001190 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001191 },
1192 // T+ Tethering mainline module (not shared, just network_stack)
1193 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001194 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001195 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001196 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001197};
1198
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001199static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001200 int retVal = 0;
1201 DIR* dir;
1202 struct dirent* ent;
1203
1204 if ((dir = opendir(location.dir)) != NULL) {
1205 while ((ent = readdir(dir)) != NULL) {
1206 string s = ent->d_name;
1207 if (!EndsWith(s, ".o")) continue;
1208
1209 string progPath(location.dir);
1210 progPath += s;
1211
1212 bool critical;
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001213 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001214 if (ret) {
1215 if (critical) retVal = ret;
1216 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1217 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001218 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001219 }
1220 }
1221 closedir(dir);
1222 }
1223 return retVal;
1224}
1225
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001226static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001227 if (*prefix) {
1228 mode_t prevUmask = umask(0);
1229
1230 string s = "/sys/fs/bpf/";
1231 s += prefix;
1232
1233 errno = 0;
1234 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1235 if (ret && errno != EEXIST) {
1236 const int err = errno;
1237 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1238 return -err;
1239 }
1240
1241 umask(prevUmask);
1242 }
1243 return 0;
1244}
1245
1246// Technically 'value' doesn't need to be newline terminated, but it's best
1247// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1248// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001249static int writeProcSysFile(const char *filename, const char *value) {
1250 base::unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001251 if (fd < 0) {
1252 const int err = errno;
1253 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1254 return -err;
1255 }
1256 int len = strlen(value);
1257 int v = write(fd, value, len);
1258 if (v < 0) {
1259 const int err = errno;
1260 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1261 return -err;
1262 }
1263 if (v != len) {
1264 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1265 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1266 return -EINVAL;
1267 }
1268 return 0;
1269}
1270
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001271#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001272const char * const platformBpfLoader = "/system/bin/bpfloader";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001273
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001274static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001275 char * found_blockdev = NULL;
1276 FILE * f = NULL;
1277 char buf[4096];
1278
1279 f = fopen("/proc/mounts", "re");
1280 if (!f) return 1;
1281
1282 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1283 while (fgets(buf, sizeof(buf), f)) {
1284 char * blockdev = buf;
1285 char * space = strchr(blockdev, ' ');
1286 if (!space) continue;
1287 *space = '\0';
1288 char * mntpath = space + 1;
1289 space = strchr(mntpath, ' ');
1290 if (!space) continue;
1291 *space = '\0';
1292 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1293 found_blockdev = strdup(blockdev);
1294 break;
1295 }
1296 fclose(f);
1297 f = NULL;
1298
1299 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001300 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001301
1302 f = fopen("/proc/mounts", "re");
1303 if (!f) { free(found_blockdev); return 3; }
1304
1305 while (fgets(buf, sizeof(buf), f)) {
1306 char * blockdev = buf;
1307 char * space = strchr(blockdev, ' ');
1308 if (!space) continue;
1309 *space = '\0';
1310 char * mntpath = space + 1;
1311 space = strchr(mntpath, ' ');
1312 if (!space) continue;
1313 *space = '\0';
1314 if (strcmp(blockdev, found_blockdev)) continue;
1315 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1316 char * at = strchr(mntpath, '@');
1317 if (!at) continue;
1318 char * ver = at + 1;
1319 ALOGI("Tethering APEX version %s", ver);
1320 }
1321 fclose(f);
1322 free(found_blockdev);
1323 return 0;
1324}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001325
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001326static bool hasGSM() {
1327 static string ph = base::GetProperty("gsm.current.phone-type", "");
1328 static bool gsm = (ph != "");
1329 static bool logged = false;
1330 if (!logged) {
1331 logged = true;
1332 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1333 }
1334 return gsm;
1335}
1336
1337static bool isTV() {
1338 if (hasGSM()) return false; // TVs don't do GSM
1339
1340 static string key = base::GetProperty("ro.oem.key1", "");
1341 static bool tv = StartsWith(key, "ATV00");
1342 static bool logged = false;
1343 if (!logged) {
1344 logged = true;
1345 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1346 }
1347 return tv;
1348}
1349
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001350static bool isWear() {
1351 static string wearSdkStr = base::GetProperty("ro.cw_build.wear_sdk.version", "");
1352 static int wearSdkInt = base::GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1353 static string buildChars = base::GetProperty("ro.build.characteristics", "");
1354 static vector<string> v = base::Tokenize(buildChars, ",");
1355 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1356 static bool wear = (wearSdkInt > 0) || watch;
1357 static bool logged = false;
1358 if (!logged) {
1359 logged = true;
1360 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1361 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1362 }
1363 return wear;
1364}
1365
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001366static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001367 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001368
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001369 // Any released device will have codename REL instead of a 'real' codename.
1370 // For safety: default to 'REL' so we default to unreleased=false on failure.
1371 const bool unreleased = (base::GetProperty("ro.build.version.codename", "REL") != "REL");
1372
1373 // goog/main device_api_level is bumped *way* before aosp/main api level
1374 // (the latter only gets bumped during the push of goog/main to aosp/main)
1375 //
1376 // Since we develop in AOSP, we want it to behave as if it was bumped too.
1377 //
1378 // Note that AOSP doesn't really have a good api level (for example during
1379 // early V dev cycle, it would have *all* of T, some but not all of U, and some V).
1380 // One could argue that for our purposes AOSP api level should be infinite or 10000.
1381 //
1382 // This could also cause api to be increased in goog/main or other branches,
1383 // but I can't imagine a case where this would be a problem: the problem
1384 // is rather a too low api level, rather than some ill defined high value.
1385 // For example as I write this aosp is 34/U, and goog is 35/V,
1386 // we want to treat both goog & aosp as 35/V, but it's harmless if we
1387 // treat goog as 36 because that value isn't yet defined to mean anything,
1388 // and we thus never compare against it.
1389 //
1390 // Also note that 'android_get_device_api_level()' is what the
1391 // //system/core/init/apex_init_util.cpp
1392 // apex init .XXrc parsing code uses for XX filtering.
1393 //
1394 // That code has a hack to bump <35 to 35 (to force aosp/main to parse .35rc),
1395 // but could (should?) perhaps be adjusted to match this.
1396 const int effective_api_level = android_get_device_api_level() + (int)unreleased;
1397 const bool isAtLeastT = (effective_api_level >= __ANDROID_API_T__);
1398 const bool isAtLeastU = (effective_api_level >= __ANDROID_API_U__);
1399 const bool isAtLeastV = (effective_api_level >= __ANDROID_API_V__);
Maciej Żenczykowskide7374d2024-09-03 15:56:44 -07001400 const bool isAtLeastW = (effective_api_level > __ANDROID_API_V__); // TODO: switch to W
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001401
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001402 // last in U QPR2 beta1
1403 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1404 // first in U QPR2 beta~2
1405 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1406
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001407 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001408 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
1409 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1410 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1411 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1412 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowskide7374d2024-09-03 15:56:44 -07001413 if (isAtLeastW) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_W_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001414
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001415 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) uid:%d rc:%d%d",
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001416 bpfloader_ver, argv[0], android_get_device_api_level(), effective_api_level,
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001417 kernelVersion(), describeArch(), getuid(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001418 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001419
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001420 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1421 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1422 return 1;
1423 }
1424
1425 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1426 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1427 return 1;
1428 }
1429
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001430 logTetheringApexVersion();
1431
Maciej Żenczykowski11141da2024-03-15 18:21:33 -07001432 if (!isAtLeastT) {
1433 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001434 return 1;
1435 }
1436
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001437 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001438 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001439 ALOGE("Android T requires kernel 4.9.");
1440 return 1;
1441 }
1442
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001443 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001444 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001445 ALOGE("Android U requires kernel 4.14.");
1446 return 1;
1447 }
1448
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001449 // V bumps the kernel requirement up to 4.19
1450 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001451 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001452 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001453 return 1;
1454 }
1455
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001456 // Technically already required by U, but only enforce on V+
1457 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1458 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1459 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1460 if (!isTV()) return 1;
1461 }
1462
1463 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1464 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001465 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001466 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001467 }
1468
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001469 if (isAtLeastV) {
1470 bool bad = false;
1471
1472 if (!isLtsKernel()) {
1473 ALOGW("Android V only supports LTS kernels.");
1474 bad = true;
1475 }
1476
1477#define REQUIRE(maj, min, sub) \
1478 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
1479 ALOGW("Android V requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
1480 bad = true; \
1481 }
1482
1483 REQUIRE(4, 19, 236)
1484 REQUIRE(5, 4, 186)
1485 REQUIRE(5, 10, 199)
1486 REQUIRE(5, 15, 136)
1487 REQUIRE(6, 1, 57)
1488 REQUIRE(6, 6, 0)
1489
1490#undef REQUIRE
1491
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001492 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001493 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1494 }
1495 }
1496
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001497 /* Android 14/U should only launch on 64-bit kernels
1498 * T launches on 5.10/5.15
1499 * U launches on 5.15/6.1
1500 * So >=5.16 implies isKernel64Bit()
1501 *
1502 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1503 *
1504 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1505 * we also require 64-bit userspace.
1506 *
1507 * There are various known issues with 32-bit userspace talking to various
1508 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1509 * Some of these have userspace or kernel workarounds/hacks.
1510 * Some of them don't...
1511 * We're going to be removing the hacks.
1512 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1513 * Note: this check/enforcement only applies to *system* userspace code,
1514 * it does not affect unprivileged apps, the 32-on-64 compatibility
1515 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1516 *
1517 * Additionally the 32-bit kernel jit support is poor,
1518 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
1519 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001520 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001521 ALOGE("64-bit userspace required on 6.2+ kernels.");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001522 // Stuff won't work reliably, but exempt TVs & Arm Wear devices
1523 if (!isTV() && !(isWear() && isArm())) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001524 }
1525
1526 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001527 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001528 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001529 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001530 return 1;
1531 }
1532
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001533 if (runningAsRoot) {
1534 // Note: writing this proc file requires being root (always the case on V+)
1535
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001536 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1537 // but we need 0 (enabled)
1538 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1539 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1540 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001541 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001542 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001543
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001544 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001545 // Note: writing these proc files requires CAP_NET_ADMIN
1546 // and sepolicy which is only present on U+,
1547 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1548 // trigger (ie. by init itself) instead.
1549
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001550 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1551 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1552 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1553 // kernel does not have CONFIG_BPF_JIT=y)
1554 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1555 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1556 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001557
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001558 // Enable JIT kallsyms export for privileged users only
1559 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1560 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1561 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1562 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001563
1564 // Create all the pin subdirectories
1565 // (this must be done first to allow selinux_context and pin_subdir functionality,
1566 // which could otherwise fail with ENOENT during object pinning or renaming,
1567 // due to ordering issues)
1568 for (const auto& location : locations) {
1569 if (createSysFsBpfSubDir(location.prefix)) return 1;
1570 }
1571
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001572 // Note: there's no actual src dir for fs_bpf_loader .o's,
1573 // so it is not listed in 'locations[].prefix'.
1574 // This is because this is primarily meant for triggering genfscon rules,
1575 // and as such this will likely always be the case.
1576 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1577 if (createSysFsBpfSubDir("loader")) return 1;
1578
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001579 // Load all ELF objects, create programs and maps, and pin them
1580 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001581 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001582 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1583 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1584 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1585 "problems or startup script race.");
1586 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1587 sleep(20);
1588 return 2;
1589 }
1590 }
1591
1592 int key = 1;
1593 int value = 123;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001594 base::unique_fd map(
1595 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1596 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001597 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1598 return 1;
1599 }
1600
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001601 // leave a flag that we're done
1602 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001603
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001604 // platform bpfloader will only succeed when run as root
1605 if (!runningAsRoot) {
1606 // unreachable on U QPR3+ which always runs netbpfload as root
1607
1608 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1609 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001610 }
1611
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001612 // unreachable before U QPR3
1613 ALOGI("done, transferring control to platform bpfloader.");
1614
1615 // platform BpfLoader *needs* to run as root
1616 const char * args[] = { platformBpfLoader, NULL, };
1617 execve(args[0], (char**)args, envp);
1618 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1619 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001620}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001621
1622} // namespace bpf
1623} // namespace android
1624
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001625int main(int argc, char** argv, char * const envp[]) {
1626 android::base::InitLogging(argv, &android::base::KernelLogger);
1627
1628 if (argc == 2 && !strcmp(argv[1], "done")) {
1629 // we're being re-exec'ed from platform bpfloader to 'finalize' things
1630 if (!android::base::SetProperty("bpf.progs_loaded", "1")) {
1631 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1632 return 125;
1633 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001634 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001635 return 0;
1636 }
1637
1638 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001639}