blob: 07be8c687110f9dfb1b9e72fc8aaa184d8324a90 [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
607 // The .h file enforces that this is a power of two, and page size will
608 // also always be a power of two, so this logic is actually enough to
609 // force it to be a multiple of the page size, as required by the kernel.
610 unsigned int desired_max_entries = mapDef.max_entries;
611 if (type == BPF_MAP_TYPE_RINGBUF) {
612 if (desired_max_entries < page_size) desired_max_entries = page_size;
613 }
614
615 // The following checks should *never* trigger, if one of them somehow does,
616 // it probably means a bpf .o file has been changed/replaced at runtime
617 // and bpfloader was manually rerun (normally it should only run *once*
618 // early during the boot process).
619 // Another possibility is that something is misconfigured in the code:
620 // most likely a shared map is declared twice differently.
621 // But such a change should never be checked into the source tree...
622 if ((fd_type == type) &&
623 (fd_key_size == (int)mapDef.key_size) &&
624 (fd_value_size == (int)mapDef.value_size) &&
625 (fd_max_entries == (int)desired_max_entries) &&
626 (fd_map_flags == desired_map_flags)) {
627 return true;
628 }
629
630 ALOGE("bpf map name %s mismatch: desired/found: "
631 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
632 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
633 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
634 return false;
635}
636
637static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700638 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700639 int ret;
640 vector<char> mdData;
641 vector<struct bpf_map_def> md;
642 vector<string> mapNames;
643 string objName = pathToObjName(string(elfPath));
644
645 ret = readSectionByName("maps", elfFile, mdData);
646 if (ret == -2) return 0; // no maps to read
647 if (ret) return ret;
648
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700649 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700650 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700651 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700652 return -1;
653 };
654
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700655 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700656
657 const char* dataPtr = mdData.data();
658 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700659 // Copy the structure from the ELF file and move to the next one.
660 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
661 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700662 }
663
664 ret = getSectionSymNames(elfFile, "maps", mapNames);
665 if (ret) return ret;
666
667 unsigned kvers = kernelVersion();
668
669 for (int i = 0; i < (int)mapNames.size(); i++) {
670 if (md[i].zero != 0) abort();
671
672 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000673 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700674 md[i].bpfloader_min_ver);
675 mapFds.push_back(unique_fd());
676 continue;
677 }
678
679 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000680 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700681 md[i].bpfloader_max_ver);
682 mapFds.push_back(unique_fd());
683 continue;
684 }
685
686 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000687 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700688 mapNames[i].c_str(), kvers, md[i].min_kver);
689 mapFds.push_back(unique_fd());
690 continue;
691 }
692
693 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000694 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700695 mapNames[i].c_str(), kvers, md[i].max_kver);
696 mapFds.push_back(unique_fd());
697 continue;
698 }
699
700 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
701 (md[i].ignore_on_userdebug && isUserdebug())) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000702 ALOGD("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700703 getBuildType().c_str());
704 mapFds.push_back(unique_fd());
705 continue;
706 }
707
708 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
709 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
710 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
711 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
712 (isRiscV() && md[i].ignore_on_riscv64)) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000713 ALOGD("skipping map %s which is ignored on %s", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700714 describeArch());
715 mapFds.push_back(unique_fd());
716 continue;
717 }
718
719 enum bpf_map_type type = md[i].type;
720 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
721 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
722 // of be approximated: ARRAY has the same userspace api, though it is not usable
723 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
724 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
725 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
726 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
727 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
728 type = BPF_MAP_TYPE_ARRAY;
729 }
730 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
731 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
732 // of be approximated: HASH has the same userspace visible api.
733 // However it cannot be used by ebpf programs in the same way.
734 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
735 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
736 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
737 // programs as being 5.4+...
738 type = BPF_MAP_TYPE_HASH;
739 }
740
741 // The .h file enforces that this is a power of two, and page size will
742 // also always be a power of two, so this logic is actually enough to
743 // force it to be a multiple of the page size, as required by the kernel.
744 unsigned int max_entries = md[i].max_entries;
745 if (type == BPF_MAP_TYPE_RINGBUF) {
746 if (max_entries < page_size) max_entries = page_size;
747 }
748
749 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
750 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000751 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700752 md[i].selinux_context, static_cast<int>(selinux_context),
753 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
754 }
755
756 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700757 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000758 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700759 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
760 }
761
762 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
763 // except that maps shared across .o's have empty <objName>
764 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
765 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
766 (md[i].shared ? "" : objName) + "_" + mapNames[i];
767 bool reuse = false;
768 unique_fd fd;
769 int saved_errno;
770
771 if (access(mapPinLoc.c_str(), F_OK) == 0) {
772 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
773 saved_errno = errno;
774 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
775 reuse = true;
776 } else {
777 union bpf_attr req = {
778 .map_type = type,
779 .key_size = md[i].key_size,
780 .value_size = md[i].value_size,
781 .max_entries = max_entries,
782 .map_flags = md[i].map_flags,
783 };
784 if (isAtLeastKernelVersion(4, 15, 0))
785 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
786 fd.reset(bpf(BPF_MAP_CREATE, req));
787 saved_errno = errno;
788 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
789 }
790
791 if (!fd.ok()) return -saved_errno;
792
793 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
794 // safety (since reuse code path is rare) run these checks even if we just created it.
795 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
796 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
797
798 if (!reuse) {
799 if (specified(selinux_context)) {
800 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
801 "tmp_map_" + objName + "_" + mapNames[i];
802 ret = bpfFdPin(fd, createLoc.c_str());
803 if (ret) {
804 int err = errno;
805 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
806 return -err;
807 }
808 ret = renameat2(AT_FDCWD, createLoc.c_str(),
809 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
810 if (ret) {
811 int err = errno;
812 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
813 err, strerror(err));
814 return -err;
815 }
816 } else {
817 ret = bpfFdPin(fd, mapPinLoc.c_str());
818 if (ret) {
819 int err = errno;
820 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
821 return -err;
822 }
823 }
824 ret = chmod(mapPinLoc.c_str(), md[i].mode);
825 if (ret) {
826 int err = errno;
827 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
828 strerror(err));
829 return -err;
830 }
831 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
832 if (ret) {
833 int err = errno;
834 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
835 ret, err, strerror(err));
836 return -err;
837 }
838 }
839
840 int mapId = bpfGetFdMapId(fd);
841 if (mapId == -1) {
Maciej Żenczykowski508c8f72024-08-28 15:07:33 -0700842 if (isAtLeastKernelVersion(4, 14, 0))
843 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700844 } else {
845 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
846 }
847
848 mapFds.push_back(std::move(fd));
849 }
850
851 return ret;
852}
853
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700854static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
855 int insnIndex;
856 struct bpf_insn *insn, *insns;
857
858 insns = (struct bpf_insn*)(insnsPtr);
859
860 insnIndex = offset / sizeof(struct bpf_insn);
861 insn = &insns[insnIndex];
862
863 // Occasionally might be useful for relocation debugging, but pretty spammy
864 if (0) {
865 ALOGV("applying relo to instruction at byte offset: %llu, "
866 "insn offset %d, insn %llx",
867 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
868 }
869
870 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700871 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700872 return;
873 }
874
875 insn->imm = fd;
876 insn->src_reg = BPF_PSEUDO_MAP_FD;
877}
878
879static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
880 vector<string> mapNames;
881
882 int ret = getSectionSymNames(elfFile, "maps", mapNames);
883 if (ret) return;
884
885 for (int k = 0; k != (int)cs.size(); k++) {
886 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
887 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
888
889 for (int i = 0; i < n_rel; i++) {
890 int symIndex = ELF64_R_SYM(rel[i].r_info);
891 string symName;
892
893 ret = getSymNameByIdx(elfFile, symIndex, symName);
894 if (ret) return;
895
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000896 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700897 for (int j = 0; j < (int)mapNames.size(); j++) {
898 if (!mapNames[j].compare(symName)) {
899 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
900 break;
901 }
902 }
903 }
904 }
905}
906
907static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
908 const char* prefix, const unsigned int bpfloader_ver) {
909 unsigned kvers = kernelVersion();
910
911 if (!kvers) {
912 ALOGE("unable to get kernel version");
913 return -EINVAL;
914 }
915
916 string objName = pathToObjName(string(elfPath));
917
918 for (int i = 0; i < (int)cs.size(); i++) {
919 unique_fd& fd = cs[i].prog_fd;
920 int ret;
921 string name = cs[i].name;
922
923 if (!cs[i].prog_def.has_value()) {
924 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
925 return -EINVAL;
926 }
927
928 unsigned min_kver = cs[i].prog_def->min_kver;
929 unsigned max_kver = cs[i].prog_def->max_kver;
930 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
931 max_kver, kvers);
932 if (kvers < min_kver) continue;
933 if (kvers >= max_kver) continue;
934
935 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
936 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
937 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
938 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700939
940 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
941 bpfMinVer, bpfMaxVer);
942 if (bpfloader_ver < bpfMinVer) continue;
943 if (bpfloader_ver >= bpfMaxVer) continue;
944
945 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
946 (cs[i].prog_def->ignore_on_user && isUser()) ||
947 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
948 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
949 getBuildType().c_str());
950 continue;
951 }
952
953 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
954 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
955 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
956 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
957 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
958 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
959 continue;
960 }
961
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700962 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000963 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700964 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
965 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
966 }
967
968 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000969 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700970 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
971 lookupPinSubdir(pin_subdir));
972 }
973
974 // strip any potential $foo suffix
975 // this can be used to provide duplicate programs
976 // conditionally loaded based on running kernel version
977 name = name.substr(0, name.find_last_of('$'));
978
979 bool reuse = false;
980 // Format of pin location is
981 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
982 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
983 objName + '_' + string(name);
984 if (access(progPinLoc.c_str(), F_OK) == 0) {
985 fd.reset(retrieveProgram(progPinLoc.c_str()));
986 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
987 (!fd.ok() ? std::strerror(errno) : "no error"));
988 reuse = true;
989 } else {
990 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
991
992 union bpf_attr req = {
993 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700994 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -0700995 .insns = ptr_to_u64(cs[i].data.data()),
996 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700997 .log_level = 1,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700998 .log_size = static_cast<__u32>(log_buf.size()),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -0700999 .log_buf = ptr_to_u64(log_buf.data()),
1000 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001001 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001002 };
1003 if (isAtLeastKernelVersion(4, 15, 0))
1004 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1005 fd.reset(bpf(BPF_PROG_LOAD, req));
1006
1007 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
1008 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
1009
1010 if (!fd.ok()) {
1011 vector<string> lines = android::base::Split(log_buf.data(), "\n");
1012
1013 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1014 for (const auto& line : lines) ALOGW("%s", line.c_str());
1015 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1016
1017 if (cs[i].prog_def->optional) {
1018 ALOGW("failed program is marked optional - continuing...");
1019 continue;
1020 }
1021 ALOGE("non-optional program failed to load.");
1022 }
1023 }
1024
1025 if (!fd.ok()) return fd.get();
1026
1027 if (!reuse) {
1028 if (specified(selinux_context)) {
1029 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1030 "tmp_prog_" + objName + '_' + string(name);
1031 ret = bpfFdPin(fd, createLoc.c_str());
1032 if (ret) {
1033 int err = errno;
1034 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1035 return -err;
1036 }
1037 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1038 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1039 if (ret) {
1040 int err = errno;
1041 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1042 err, strerror(err));
1043 return -err;
1044 }
1045 } else {
1046 ret = bpfFdPin(fd, progPinLoc.c_str());
1047 if (ret) {
1048 int err = errno;
1049 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1050 return -err;
1051 }
1052 }
1053 if (chmod(progPinLoc.c_str(), 0440)) {
1054 int err = errno;
1055 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1056 return -err;
1057 }
1058 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1059 (gid_t)cs[i].prog_def->gid)) {
1060 int err = errno;
1061 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1062 cs[i].prog_def->gid, err, strerror(err));
1063 return -err;
1064 }
1065 }
1066
1067 int progId = bpfGetFdProgId(fd);
1068 if (progId == -1) {
1069 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
1070 } else {
1071 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
1072 }
1073 }
1074
1075 return 0;
1076}
1077
1078int loadProg(const char* const elfPath, bool* const isCritical, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001079 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001080 vector<char> license;
1081 vector<char> critical;
1082 vector<codeSection> cs;
1083 vector<unique_fd> mapFds;
1084 int ret;
1085
1086 if (!isCritical) return -1;
1087 *isCritical = false;
1088
1089 ifstream elfFile(elfPath, ios::in | ios::binary);
1090 if (!elfFile.is_open()) return -1;
1091
1092 ret = readSectionByName("critical", elfFile, critical);
1093 *isCritical = !ret;
1094
1095 ret = readSectionByName("license", elfFile, license);
1096 if (ret) {
1097 ALOGE("Couldn't find license in %s", elfPath);
1098 return ret;
1099 } else {
1100 ALOGD("Loading %s%s ELF object %s with license %s",
1101 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
1102 elfPath, (char*)license.data());
1103 }
1104
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001105 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1106 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001107
1108 // inclusive lower bound check
1109 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001110 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001111 bpfloader_ver, elfPath, bpfLoaderMinVer);
1112 return 0;
1113 }
1114
1115 // exclusive upper bound check
1116 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001117 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001118 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1119 return 0;
1120 }
1121
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001122 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001123 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1124
Maciej Żenczykowskie666d852024-08-15 15:03:38 -07001125 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001126 if (ret) {
1127 ALOGE("Couldn't read all code sections in %s", elfPath);
1128 return ret;
1129 }
1130
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001131 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001132 if (ret) {
1133 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1134 return ret;
1135 }
1136
1137 for (int i = 0; i < (int)mapFds.size(); i++)
1138 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1139
1140 applyMapRelo(elfFile, mapFds, cs);
1141
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001142 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001143 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1144
1145 return ret;
1146}
1147
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001148static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001149 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001150 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001151 if (errno == ENOENT) return false;
1152 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1153 abort(); // can only hit this if permissions (likely selinux) are screwed up
1154}
1155
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001156#define APEXROOT "/apex/com.android.tethering"
1157#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001158
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001159const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001160 // S+ Tethering mainline module (network_stack): tether offload
1161 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001162 .dir = BPFROOT "/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001163 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001164 },
1165 // T+ Tethering mainline module (shared with netd & system server)
1166 // netutils_wrapper (for iptables xt_bpf) has access to programs
1167 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001168 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001169 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001170 },
1171 // T+ Tethering mainline module (shared with netd & system server)
1172 // netutils_wrapper has no access, netd has read only access
1173 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001174 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001175 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001176 },
1177 // T+ Tethering mainline module (shared with system server)
1178 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001179 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001180 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001181 },
1182 // T+ Tethering mainline module (not shared, just network_stack)
1183 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001184 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001185 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001186 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001187};
1188
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001189static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001190 int retVal = 0;
1191 DIR* dir;
1192 struct dirent* ent;
1193
1194 if ((dir = opendir(location.dir)) != NULL) {
1195 while ((ent = readdir(dir)) != NULL) {
1196 string s = ent->d_name;
1197 if (!EndsWith(s, ".o")) continue;
1198
1199 string progPath(location.dir);
1200 progPath += s;
1201
1202 bool critical;
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001203 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001204 if (ret) {
1205 if (critical) retVal = ret;
1206 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1207 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001208 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001209 }
1210 }
1211 closedir(dir);
1212 }
1213 return retVal;
1214}
1215
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001216static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001217 if (*prefix) {
1218 mode_t prevUmask = umask(0);
1219
1220 string s = "/sys/fs/bpf/";
1221 s += prefix;
1222
1223 errno = 0;
1224 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1225 if (ret && errno != EEXIST) {
1226 const int err = errno;
1227 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1228 return -err;
1229 }
1230
1231 umask(prevUmask);
1232 }
1233 return 0;
1234}
1235
1236// Technically 'value' doesn't need to be newline terminated, but it's best
1237// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1238// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001239static int writeProcSysFile(const char *filename, const char *value) {
1240 base::unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001241 if (fd < 0) {
1242 const int err = errno;
1243 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1244 return -err;
1245 }
1246 int len = strlen(value);
1247 int v = write(fd, value, len);
1248 if (v < 0) {
1249 const int err = errno;
1250 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1251 return -err;
1252 }
1253 if (v != len) {
1254 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1255 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1256 return -EINVAL;
1257 }
1258 return 0;
1259}
1260
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001261#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001262const char * const platformBpfLoader = "/system/bin/bpfloader";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001263
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001264static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001265 char * found_blockdev = NULL;
1266 FILE * f = NULL;
1267 char buf[4096];
1268
1269 f = fopen("/proc/mounts", "re");
1270 if (!f) return 1;
1271
1272 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1273 while (fgets(buf, sizeof(buf), f)) {
1274 char * blockdev = buf;
1275 char * space = strchr(blockdev, ' ');
1276 if (!space) continue;
1277 *space = '\0';
1278 char * mntpath = space + 1;
1279 space = strchr(mntpath, ' ');
1280 if (!space) continue;
1281 *space = '\0';
1282 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1283 found_blockdev = strdup(blockdev);
1284 break;
1285 }
1286 fclose(f);
1287 f = NULL;
1288
1289 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001290 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001291
1292 f = fopen("/proc/mounts", "re");
1293 if (!f) { free(found_blockdev); return 3; }
1294
1295 while (fgets(buf, sizeof(buf), f)) {
1296 char * blockdev = buf;
1297 char * space = strchr(blockdev, ' ');
1298 if (!space) continue;
1299 *space = '\0';
1300 char * mntpath = space + 1;
1301 space = strchr(mntpath, ' ');
1302 if (!space) continue;
1303 *space = '\0';
1304 if (strcmp(blockdev, found_blockdev)) continue;
1305 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1306 char * at = strchr(mntpath, '@');
1307 if (!at) continue;
1308 char * ver = at + 1;
1309 ALOGI("Tethering APEX version %s", ver);
1310 }
1311 fclose(f);
1312 free(found_blockdev);
1313 return 0;
1314}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001315
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001316static bool hasGSM() {
1317 static string ph = base::GetProperty("gsm.current.phone-type", "");
1318 static bool gsm = (ph != "");
1319 static bool logged = false;
1320 if (!logged) {
1321 logged = true;
1322 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1323 }
1324 return gsm;
1325}
1326
1327static bool isTV() {
1328 if (hasGSM()) return false; // TVs don't do GSM
1329
1330 static string key = base::GetProperty("ro.oem.key1", "");
1331 static bool tv = StartsWith(key, "ATV00");
1332 static bool logged = false;
1333 if (!logged) {
1334 logged = true;
1335 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1336 }
1337 return tv;
1338}
1339
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001340static bool isWear() {
1341 static string wearSdkStr = base::GetProperty("ro.cw_build.wear_sdk.version", "");
1342 static int wearSdkInt = base::GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1343 static string buildChars = base::GetProperty("ro.build.characteristics", "");
1344 static vector<string> v = base::Tokenize(buildChars, ",");
1345 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1346 static bool wear = (wearSdkInt > 0) || watch;
1347 static bool logged = false;
1348 if (!logged) {
1349 logged = true;
1350 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1351 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1352 }
1353 return wear;
1354}
1355
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001356static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001357 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001358
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001359 // Any released device will have codename REL instead of a 'real' codename.
1360 // For safety: default to 'REL' so we default to unreleased=false on failure.
1361 const bool unreleased = (base::GetProperty("ro.build.version.codename", "REL") != "REL");
1362
1363 // goog/main device_api_level is bumped *way* before aosp/main api level
1364 // (the latter only gets bumped during the push of goog/main to aosp/main)
1365 //
1366 // Since we develop in AOSP, we want it to behave as if it was bumped too.
1367 //
1368 // Note that AOSP doesn't really have a good api level (for example during
1369 // early V dev cycle, it would have *all* of T, some but not all of U, and some V).
1370 // One could argue that for our purposes AOSP api level should be infinite or 10000.
1371 //
1372 // This could also cause api to be increased in goog/main or other branches,
1373 // but I can't imagine a case where this would be a problem: the problem
1374 // is rather a too low api level, rather than some ill defined high value.
1375 // For example as I write this aosp is 34/U, and goog is 35/V,
1376 // we want to treat both goog & aosp as 35/V, but it's harmless if we
1377 // treat goog as 36 because that value isn't yet defined to mean anything,
1378 // and we thus never compare against it.
1379 //
1380 // Also note that 'android_get_device_api_level()' is what the
1381 // //system/core/init/apex_init_util.cpp
1382 // apex init .XXrc parsing code uses for XX filtering.
1383 //
1384 // That code has a hack to bump <35 to 35 (to force aosp/main to parse .35rc),
1385 // but could (should?) perhaps be adjusted to match this.
1386 const int effective_api_level = android_get_device_api_level() + (int)unreleased;
1387 const bool isAtLeastT = (effective_api_level >= __ANDROID_API_T__);
1388 const bool isAtLeastU = (effective_api_level >= __ANDROID_API_U__);
1389 const bool isAtLeastV = (effective_api_level >= __ANDROID_API_V__);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001390
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001391 // last in U QPR2 beta1
1392 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1393 // first in U QPR2 beta~2
1394 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1395
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001396 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001397 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
1398 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1399 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1400 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1401 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001402
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001403 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) uid:%d rc:%d%d",
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001404 bpfloader_ver, argv[0], android_get_device_api_level(), effective_api_level,
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001405 kernelVersion(), describeArch(), getuid(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001406 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001407
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001408 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1409 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1410 return 1;
1411 }
1412
1413 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1414 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1415 return 1;
1416 }
1417
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001418 logTetheringApexVersion();
1419
Maciej Żenczykowski11141da2024-03-15 18:21:33 -07001420 if (!isAtLeastT) {
1421 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001422 return 1;
1423 }
1424
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001425 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001426 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001427 ALOGE("Android T requires kernel 4.9.");
1428 return 1;
1429 }
1430
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001431 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001432 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001433 ALOGE("Android U requires kernel 4.14.");
1434 return 1;
1435 }
1436
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001437 // V bumps the kernel requirement up to 4.19
1438 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001439 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001440 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001441 return 1;
1442 }
1443
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001444 // Technically already required by U, but only enforce on V+
1445 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1446 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1447 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1448 if (!isTV()) return 1;
1449 }
1450
1451 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1452 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001453 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001454 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001455 }
1456
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001457 if (isAtLeastV) {
1458 bool bad = false;
1459
1460 if (!isLtsKernel()) {
1461 ALOGW("Android V only supports LTS kernels.");
1462 bad = true;
1463 }
1464
1465#define REQUIRE(maj, min, sub) \
1466 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
1467 ALOGW("Android V requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
1468 bad = true; \
1469 }
1470
1471 REQUIRE(4, 19, 236)
1472 REQUIRE(5, 4, 186)
1473 REQUIRE(5, 10, 199)
1474 REQUIRE(5, 15, 136)
1475 REQUIRE(6, 1, 57)
1476 REQUIRE(6, 6, 0)
1477
1478#undef REQUIRE
1479
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001480 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001481 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1482 }
1483 }
1484
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001485 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001486 /* Android 14/U should only launch on 64-bit kernels
1487 * T launches on 5.10/5.15
1488 * U launches on 5.15/6.1
1489 * So >=5.16 implies isKernel64Bit()
1490 *
1491 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1492 *
1493 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1494 * we also require 64-bit userspace.
1495 *
1496 * There are various known issues with 32-bit userspace talking to various
1497 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1498 * Some of these have userspace or kernel workarounds/hacks.
1499 * Some of them don't...
1500 * We're going to be removing the hacks.
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001501 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1502 * Note: this check/enforcement only applies to *system* userspace code,
1503 * it does not affect unprivileged apps, the 32-on-64 compatibility
1504 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001505 *
1506 * Additionally the 32-bit kernel jit support is poor,
1507 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
1508 */
1509 ALOGE("64-bit userspace required on 6.2+ kernels.");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001510 // Stuff won't work reliably, but exempt TVs & Arm Wear devices
1511 if (!isTV() && !(isWear() && isArm())) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001512 }
1513
1514 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001515 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001516 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001517 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001518 return 1;
1519 }
1520
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001521 if (runningAsRoot) {
1522 // Note: writing this proc file requires being root (always the case on V+)
1523
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001524 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1525 // but we need 0 (enabled)
1526 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1527 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1528 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001529 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001530 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001531
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001532 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001533 // Note: writing these proc files requires CAP_NET_ADMIN
1534 // and sepolicy which is only present on U+,
1535 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1536 // trigger (ie. by init itself) instead.
1537
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001538 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1539 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1540 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1541 // kernel does not have CONFIG_BPF_JIT=y)
1542 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1543 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1544 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001545
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001546 // Enable JIT kallsyms export for privileged users only
1547 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1548 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1549 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1550 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001551
1552 // Create all the pin subdirectories
1553 // (this must be done first to allow selinux_context and pin_subdir functionality,
1554 // which could otherwise fail with ENOENT during object pinning or renaming,
1555 // due to ordering issues)
1556 for (const auto& location : locations) {
1557 if (createSysFsBpfSubDir(location.prefix)) return 1;
1558 }
1559
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001560 // Note: there's no actual src dir for fs_bpf_loader .o's,
1561 // so it is not listed in 'locations[].prefix'.
1562 // This is because this is primarily meant for triggering genfscon rules,
1563 // and as such this will likely always be the case.
1564 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1565 if (createSysFsBpfSubDir("loader")) return 1;
1566
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001567 // Load all ELF objects, create programs and maps, and pin them
1568 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001569 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001570 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1571 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1572 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1573 "problems or startup script race.");
1574 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1575 sleep(20);
1576 return 2;
1577 }
1578 }
1579
1580 int key = 1;
1581 int value = 123;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001582 base::unique_fd map(
1583 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1584 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001585 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1586 return 1;
1587 }
1588
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001589 // leave a flag that we're done
1590 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001591
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001592 // platform bpfloader will only succeed when run as root
1593 if (!runningAsRoot) {
1594 // unreachable on U QPR3+ which always runs netbpfload as root
1595
1596 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1597 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001598 }
1599
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001600 // unreachable before U QPR3
1601 ALOGI("done, transferring control to platform bpfloader.");
1602
1603 // platform BpfLoader *needs* to run as root
1604 const char * args[] = { platformBpfLoader, NULL, };
1605 execve(args[0], (char**)args, envp);
1606 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1607 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001608}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001609
1610} // namespace bpf
1611} // namespace android
1612
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001613int main(int argc, char** argv, char * const envp[]) {
1614 android::base::InitLogging(argv, &android::base::KernelLogger);
1615
1616 if (argc == 2 && !strcmp(argv[1], "done")) {
1617 // we're being re-exec'ed from platform bpfloader to 'finalize' things
1618 if (!android::base::SetProperty("bpf.progs_loaded", "1")) {
1619 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1620 return 125;
1621 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001622 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001623 return 0;
1624 }
1625
1626 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001627}