blob: 1e088a6f6590c0cee79a7dbbdd2daf97013859d6 [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
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +000062// The following matches bpf_helpers.h, which is only for inclusion in bpf code
63#define BPFLOADER_MAINLINE_VERSION 42u
64
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070065using android::base::EndsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070066using android::base::GetIntProperty;
67using android::base::GetProperty;
68using android::base::InitLogging;
69using android::base::KernelLogger;
70using android::base::SetProperty;
71using android::base::Split;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070072using android::base::StartsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070073using android::base::Tokenize;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070074using android::base::unique_fd;
75using std::ifstream;
76using std::ios;
77using std::optional;
78using std::string;
79using std::vector;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070080
81namespace android {
82namespace bpf {
83
84// Bpf programs may specify per-program & per-map selinux_context and pin_subdir.
85//
86// The BpfLoader needs to convert these bpf.o specified strings into an enum
87// for internal use (to check that valid values were specified for the specific
88// location of the bpf.o file).
89//
90// It also needs to map selinux_context's into pin_subdir's.
91// This is because of how selinux_context is actually implemented via pin+rename.
92//
93// Thus 'domain' enumerates all selinux_context's/pin_subdir's that the BpfLoader
94// is aware of. Thus there currently needs to be a 1:1 mapping between the two.
95//
96enum class domain : int {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070097 unspecified = 0, // means just use the default for that specific pin location
98 tethering, // (S+) fs_bpf_tethering /sys/fs/bpf/tethering
99 net_private, // (T+) fs_bpf_net_private /sys/fs/bpf/net_private
100 net_shared, // (T+) fs_bpf_net_shared /sys/fs/bpf/net_shared
101 netd_readonly, // (T+) fs_bpf_netd_readonly /sys/fs/bpf/netd_readonly
102 netd_shared, // (T+) fs_bpf_netd_shared /sys/fs/bpf/netd_shared
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700103 loader, // (U+) fs_bpf_loader /sys/fs/bpf/loader
104 // on T due to lack of sepolicy/genfscon rules it behaves simply as 'fs_bpf'
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700105};
106
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700107static constexpr domain AllDomains[] = {
108 domain::unspecified,
109 domain::tethering,
110 domain::net_private,
111 domain::net_shared,
112 domain::netd_readonly,
113 domain::netd_shared,
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700114 domain::loader,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700115};
116
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700117static constexpr bool specified(domain d) {
118 return d != domain::unspecified;
119}
120
121struct Location {
122 const char* const dir = "";
123 const char* const prefix = "";
124};
125
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700126// Returns the build type string (from ro.build.type).
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700127const std::string& getBuildType() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700128 static std::string t = GetProperty("ro.build.type", "unknown");
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700129 return t;
130}
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700131
132// The following functions classify the 3 Android build types.
133inline bool isEng() {
134 return getBuildType() == "eng";
135}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700136
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700137inline bool isUser() {
138 return getBuildType() == "user";
139}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700140
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700141inline bool isUserdebug() {
142 return getBuildType() == "userdebug";
143}
144
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700145#define BPF_FS_PATH "/sys/fs/bpf/"
146
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700147static unsigned int page_size = static_cast<unsigned int>(getpagesize());
148
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700149constexpr const char* lookupSelinuxContext(const domain d) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700150 switch (d) {
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700151 case domain::unspecified: return "";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700152 case domain::tethering: return "fs_bpf_tethering";
153 case domain::net_private: return "fs_bpf_net_private";
154 case domain::net_shared: return "fs_bpf_net_shared";
155 case domain::netd_readonly: return "fs_bpf_netd_readonly";
156 case domain::netd_shared: return "fs_bpf_netd_shared";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700157 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700158 }
159}
160
161domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
162 for (domain d : AllDomains) {
163 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
164 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
165 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
166 }
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700167 ALOGE("unrecognized selinux_context '%-32s'", s);
168 // Note: we *can* just abort() here as we only load bpf .o files shipped
169 // in the same mainline module / apex as NetBpfLoad itself.
170 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700171}
172
173constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
174 switch (d) {
175 case domain::unspecified: return unspecified;
176 case domain::tethering: return "tethering/";
177 case domain::net_private: return "net_private/";
178 case domain::net_shared: return "net_shared/";
179 case domain::netd_readonly: return "netd_readonly/";
180 case domain::netd_shared: return "netd_shared/";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700181 case domain::loader: return "loader/";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700182 }
183};
184
185domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
186 for (domain d : AllDomains) {
187 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
188 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
189 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
190 }
191 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700192 // Note: we *can* just abort() here as we only load bpf .o files shipped
193 // in the same mainline module / apex as NetBpfLoad itself.
194 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700195}
196
197static string pathToObjName(const string& path) {
198 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700199 string filename = Split(path, "/").back();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700200 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
201 string name = filename.substr(0, filename.find_last_of('.'));
202 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
203 // this can be used to provide duplicate programs (mux based on the bpfloader version)
204 return name.substr(0, name.find_last_of('@'));
205}
206
207typedef struct {
208 const char* name;
209 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000210 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700211} sectionType;
212
213/*
214 * Map section name prefixes to program types, the section name will be:
215 * SECTION(<prefix>/<name-of-program>)
216 * For example:
217 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
218 * is the name of the program, and tracepoint is the type.
219 *
220 * However, be aware that you should not be directly using the SECTION() macro.
Maciej Żenczykowski3a085152024-09-18 23:45:52 +0000221 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE macros.
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700222 *
223 * Programs shipped inside the tethering apex should be limited to networking stuff,
224 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
225 * since they are less stable abi/api and may conflict with platform uses of bpf.
226 */
227sectionType sectionNameTypes[] = {
228 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
229 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000230 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
231 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700232 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
233 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
234 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
235 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
236 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
237 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
238 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700239 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
240 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
241 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
242 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000243 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
244 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700245 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
246 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
247 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000248 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700249 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
250 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000251 {"xdp/", BPF_PROG_TYPE_XDP},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700252};
253
254typedef struct {
255 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000256 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700257 string name;
258 vector<char> data;
259 vector<char> rel_data;
260 optional<struct bpf_prog_def> prog_def;
261
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000262 unique_fd prog_fd; // fd after loading
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700263} codeSection;
264
265static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
266 elfFile.seekg(0);
267 if (elfFile.fail()) return -1;
268
269 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
270
271 return 0;
272}
273
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000274// Reads all section header tables into an Shdr array
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700275static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
276 Elf64_Ehdr eh;
277 int ret = 0;
278
279 ret = readElfHeader(elfFile, &eh);
280 if (ret) return ret;
281
282 elfFile.seekg(eh.e_shoff);
283 if (elfFile.fail()) return -1;
284
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000285 // Read shdr table entries
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700286 shTable.resize(eh.e_shnum);
287
288 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
289
290 return 0;
291}
292
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000293// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700294static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
295 vector<Elf64_Shdr> shTable;
296 int ret = readSectionHeadersAll(elfFile, shTable);
297 if (ret) return ret;
298
299 elfFile.seekg(shTable[id].sh_offset);
300 if (elfFile.fail()) return -1;
301
302 sec.resize(shTable[id].sh_size);
303 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
304
305 return 0;
306}
307
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000308// Read whole section header string table
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700309static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
310 Elf64_Ehdr eh;
311 int ret = readElfHeader(elfFile, &eh);
312 if (ret) return ret;
313
314 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
315 if (ret) return ret;
316
317 return 0;
318}
319
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000320// Get name from offset in strtab
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700321static int getSymName(ifstream& elfFile, int nameOff, string& name) {
322 int ret;
323 vector<char> secStrTab;
324
325 ret = readSectionHeaderStrtab(elfFile, secStrTab);
326 if (ret) return ret;
327
328 if (nameOff >= (int)secStrTab.size()) return -1;
329
330 name = string((char*)secStrTab.data() + nameOff);
331 return 0;
332}
333
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000334// Reads a full section by name - example to get the GPL license
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700335static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
336 vector<char> secStrTab;
337 vector<Elf64_Shdr> shTable;
338 int ret;
339
340 ret = readSectionHeadersAll(elfFile, shTable);
341 if (ret) return ret;
342
343 ret = readSectionHeaderStrtab(elfFile, secStrTab);
344 if (ret) return ret;
345
346 for (int i = 0; i < (int)shTable.size(); i++) {
347 char* secname = secStrTab.data() + shTable[i].sh_name;
348 if (!secname) continue;
349
350 if (!strcmp(secname, name)) {
351 vector<char> dataTmp;
352 dataTmp.resize(shTable[i].sh_size);
353
354 elfFile.seekg(shTable[i].sh_offset);
355 if (elfFile.fail()) return -1;
356
357 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
358
359 data = dataTmp;
360 return 0;
361 }
362 }
363 return -2;
364}
365
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700366unsigned int readSectionUint(const char* name, ifstream& elfFile) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700367 vector<char> theBytes;
368 int ret = readSectionByName(name, elfFile, theBytes);
369 if (ret) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700370 ALOGE("Couldn't find section %s.", name);
371 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700372 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700373 ALOGE("Section %s is too short.", name);
374 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700375 } else {
376 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
377 unsigned int value = static_cast<unsigned char>(theBytes[3]);
378 value <<= 8;
379 value += static_cast<unsigned char>(theBytes[2]);
380 value <<= 8;
381 value += static_cast<unsigned char>(theBytes[1]);
382 value <<= 8;
383 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000384 ALOGD("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700385 return value;
386 }
387}
388
389static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
390 int ret;
391 vector<Elf64_Shdr> shTable;
392
393 ret = readSectionHeadersAll(elfFile, shTable);
394 if (ret) return ret;
395
396 for (int i = 0; i < (int)shTable.size(); i++) {
397 if ((int)shTable[i].sh_type != type) continue;
398
399 vector<char> dataTmp;
400 dataTmp.resize(shTable[i].sh_size);
401
402 elfFile.seekg(shTable[i].sh_offset);
403 if (elfFile.fail()) return -1;
404
405 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
406
407 data = dataTmp;
408 return 0;
409 }
410 return -2;
411}
412
413static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
414 return (a.st_value < b.st_value);
415}
416
417static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
418 int ret, numElems;
419 Elf64_Sym* buf;
420 vector<char> secData;
421
422 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
423 if (ret) return ret;
424
425 buf = (Elf64_Sym*)secData.data();
426 numElems = (secData.size() / sizeof(Elf64_Sym));
427 data.assign(buf, buf + numElems);
428
429 if (sort) std::sort(data.begin(), data.end(), symCompare);
430 return 0;
431}
432
433static enum bpf_prog_type getSectionType(string& name) {
434 for (auto& snt : sectionNameTypes)
435 if (StartsWith(name, snt.name)) return snt.type;
436
437 return BPF_PROG_TYPE_UNSPEC;
438}
439
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700440static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700441 vector<char> pdData;
442 int ret = readSectionByName("progs", elfFile, pdData);
443 if (ret) return ret;
444
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700445 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700446 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700447 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700448 return -1;
449 };
450
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700451 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700452
453 const char* dataPtr = pdData.data();
454 for (auto& p : pd) {
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700455 // Copy the structure from the ELF file and move to the next one.
456 memcpy(&p, dataPtr, sizeof(struct bpf_prog_def));
457 dataPtr += sizeof(struct bpf_prog_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700458 }
459 return 0;
460}
461
462static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
463 optional<unsigned> symbolType = std::nullopt) {
464 int ret;
465 string name;
466 vector<Elf64_Sym> symtab;
467 vector<Elf64_Shdr> shTable;
468
469 ret = readSymTab(elfFile, 1 /* sort */, symtab);
470 if (ret) return ret;
471
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000472 // Get index of section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700473 ret = readSectionHeadersAll(elfFile, shTable);
474 if (ret) return ret;
475
476 int sec_idx = -1;
477 for (int i = 0; i < (int)shTable.size(); i++) {
478 ret = getSymName(elfFile, shTable[i].sh_name, name);
479 if (ret) return ret;
480
481 if (!name.compare(sectionName)) {
482 sec_idx = i;
483 break;
484 }
485 }
486
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000487 // No section found with matching name
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700488 if (sec_idx == -1) {
489 ALOGW("No %s section could be found in elf object", sectionName.c_str());
490 return -1;
491 }
492
493 for (int i = 0; i < (int)symtab.size(); i++) {
494 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
495
496 if (symtab[i].st_shndx == sec_idx) {
497 string s;
498 ret = getSymName(elfFile, symtab[i].st_name, s);
499 if (ret) return ret;
500 names.push_back(s);
501 }
502 }
503
504 return 0;
505}
506
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000507// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700508static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700509 vector<Elf64_Shdr> shTable;
510 int entries, ret = 0;
511
512 ret = readSectionHeadersAll(elfFile, shTable);
513 if (ret) return ret;
514 entries = shTable.size();
515
516 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700517 ret = readProgDefs(elfFile, pd);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700518 if (ret) return ret;
519 vector<string> progDefNames;
520 ret = getSectionSymNames(elfFile, "progs", progDefNames);
521 if (!pd.empty() && ret) return ret;
522
523 for (int i = 0; i < entries; i++) {
524 string name;
525 codeSection cs_temp;
526 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
527
528 ret = getSymName(elfFile, shTable[i].sh_name, name);
529 if (ret) return ret;
530
531 enum bpf_prog_type ptype = getSectionType(name);
532
533 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
534
535 // This must be done before '/' is replaced with '_'.
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000536 for (auto& snt : sectionNameTypes)
537 if (StartsWith(name, snt.name)) cs_temp.attach_type = snt.attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700538
539 string oldName = name;
540
541 // convert all slashes to underscores
542 std::replace(name.begin(), name.end(), '/', '_');
543
544 cs_temp.type = ptype;
545 cs_temp.name = name;
546
547 ret = readSectionByIdx(elfFile, i, cs_temp.data);
548 if (ret) return ret;
549 ALOGV("Loaded code section %d (%s)", i, name.c_str());
550
551 vector<string> csSymNames;
552 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
553 if (ret || !csSymNames.size()) return ret;
554 for (size_t i = 0; i < progDefNames.size(); ++i) {
555 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
556 cs_temp.prog_def = pd[i];
557 break;
558 }
559 }
560
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000561 // Check for rel section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700562 if (cs_temp.data.size() > 0 && i < entries) {
563 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
564 if (ret) return ret;
565
566 if (name == (".rel" + oldName)) {
567 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
568 if (ret) return ret;
569 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
570 }
571 }
572
573 if (cs_temp.data.size() > 0) {
574 cs.push_back(std::move(cs_temp));
575 ALOGV("Adding section %d to cs list", i);
576 }
577 }
578 return 0;
579}
580
581static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
582 vector<Elf64_Sym> symtab;
583 int ret = 0;
584
585 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
586 if (ret) return ret;
587
588 if (index >= (int)symtab.size()) return -1;
589
590 return getSymName(elfFile, symtab[index].st_name, name);
591}
592
593static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
594 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
595 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
596 // so on 4.9-T kernels just pretend the map matches our expectations.
597 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
598 // This is because the primary failure mode we're trying to detect here
599 // is either a source code misconfiguration (which is likely kernel independent)
600 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
601 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
602
603 // Assuming fd is a valid Bpf Map file descriptor then
604 // all the following should always succeed on a 4.14+ kernel.
605 // If they somehow do fail, they'll return -1 (and set errno),
606 // which should then cause (among others) a key_size mismatch.
607 int fd_type = bpfGetFdMapType(fd);
608 int fd_key_size = bpfGetFdKeySize(fd);
609 int fd_value_size = bpfGetFdValueSize(fd);
610 int fd_max_entries = bpfGetFdMaxEntries(fd);
611 int fd_map_flags = bpfGetFdMapFlags(fd);
612
613 // DEVMAPs are readonly from the bpf program side's point of view, as such
614 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
615 int desired_map_flags = (int)mapDef.map_flags;
616 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
617 desired_map_flags |= BPF_F_RDONLY_PROG;
618
619 // The .h file enforces that this is a power of two, and page size will
620 // also always be a power of two, so this logic is actually enough to
621 // force it to be a multiple of the page size, as required by the kernel.
622 unsigned int desired_max_entries = mapDef.max_entries;
623 if (type == BPF_MAP_TYPE_RINGBUF) {
624 if (desired_max_entries < page_size) desired_max_entries = page_size;
625 }
626
627 // The following checks should *never* trigger, if one of them somehow does,
628 // it probably means a bpf .o file has been changed/replaced at runtime
629 // and bpfloader was manually rerun (normally it should only run *once*
630 // early during the boot process).
631 // Another possibility is that something is misconfigured in the code:
632 // most likely a shared map is declared twice differently.
633 // But such a change should never be checked into the source tree...
634 if ((fd_type == type) &&
635 (fd_key_size == (int)mapDef.key_size) &&
636 (fd_value_size == (int)mapDef.value_size) &&
637 (fd_max_entries == (int)desired_max_entries) &&
638 (fd_map_flags == desired_map_flags)) {
639 return true;
640 }
641
642 ALOGE("bpf map name %s mismatch: desired/found: "
643 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
644 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
645 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
646 return false;
647}
648
649static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700650 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700651 int ret;
652 vector<char> mdData;
653 vector<struct bpf_map_def> md;
654 vector<string> mapNames;
655 string objName = pathToObjName(string(elfPath));
656
657 ret = readSectionByName("maps", elfFile, mdData);
658 if (ret == -2) return 0; // no maps to read
659 if (ret) return ret;
660
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700661 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700662 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700663 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700664 return -1;
665 };
666
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700667 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700668
669 const char* dataPtr = mdData.data();
670 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700671 // Copy the structure from the ELF file and move to the next one.
672 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
673 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700674 }
675
676 ret = getSectionSymNames(elfFile, "maps", mapNames);
677 if (ret) return ret;
678
679 unsigned kvers = kernelVersion();
680
681 for (int i = 0; i < (int)mapNames.size(); i++) {
682 if (md[i].zero != 0) abort();
683
684 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000685 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700686 md[i].bpfloader_min_ver);
687 mapFds.push_back(unique_fd());
688 continue;
689 }
690
691 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000692 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700693 md[i].bpfloader_max_ver);
694 mapFds.push_back(unique_fd());
695 continue;
696 }
697
698 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000699 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700700 mapNames[i].c_str(), kvers, md[i].min_kver);
701 mapFds.push_back(unique_fd());
702 continue;
703 }
704
705 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000706 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700707 mapNames[i].c_str(), kvers, md[i].max_kver);
708 mapFds.push_back(unique_fd());
709 continue;
710 }
711
712 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
713 (md[i].ignore_on_userdebug && isUserdebug())) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000714 ALOGD("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700715 getBuildType().c_str());
716 mapFds.push_back(unique_fd());
717 continue;
718 }
719
720 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
721 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
722 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
723 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
724 (isRiscV() && md[i].ignore_on_riscv64)) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000725 ALOGD("skipping map %s which is ignored on %s", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700726 describeArch());
727 mapFds.push_back(unique_fd());
728 continue;
729 }
730
731 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski87019832025-02-03 22:04:26 -0800732 if (type == BPF_MAP_TYPE_LPM_TRIE && !isAtLeastKernelVersion(4, 14, 0)) {
733 // On Linux Kernels older than 4.14 this map type doesn't exist - autoskip.
734 ALOGD("skipping LPM_TRIE map %s - requires kver 4.14+", mapNames[i].c_str());
735 mapFds.push_back(unique_fd());
736 continue;
737 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700738 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
739 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
740 // of be approximated: ARRAY has the same userspace api, though it is not usable
741 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
742 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
743 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
744 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
745 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
746 type = BPF_MAP_TYPE_ARRAY;
747 }
748 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
749 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
750 // of be approximated: HASH has the same userspace visible api.
751 // However it cannot be used by ebpf programs in the same way.
752 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
753 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
754 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
755 // programs as being 5.4+...
756 type = BPF_MAP_TYPE_HASH;
757 }
758
759 // The .h file enforces that this is a power of two, and page size will
760 // also always be a power of two, so this logic is actually enough to
761 // force it to be a multiple of the page size, as required by the kernel.
762 unsigned int max_entries = md[i].max_entries;
763 if (type == BPF_MAP_TYPE_RINGBUF) {
764 if (max_entries < page_size) max_entries = page_size;
765 }
766
767 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
768 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000769 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700770 md[i].selinux_context, static_cast<int>(selinux_context),
771 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
772 }
773
774 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700775 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000776 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700777 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
778 }
779
780 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
781 // except that maps shared across .o's have empty <objName>
782 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
783 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
784 (md[i].shared ? "" : objName) + "_" + mapNames[i];
785 bool reuse = false;
786 unique_fd fd;
787 int saved_errno;
788
789 if (access(mapPinLoc.c_str(), F_OK) == 0) {
790 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
791 saved_errno = errno;
792 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
793 reuse = true;
794 } else {
795 union bpf_attr req = {
796 .map_type = type,
797 .key_size = md[i].key_size,
798 .value_size = md[i].value_size,
799 .max_entries = max_entries,
Maciej Żenczykowskic1a9f4a2025-01-20 12:09:13 -0800800 .map_flags = md[i].map_flags,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700801 };
802 if (isAtLeastKernelVersion(4, 15, 0))
803 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
804 fd.reset(bpf(BPF_MAP_CREATE, req));
805 saved_errno = errno;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -0700806 if (fd.ok()) {
807 ALOGD("bpf_create_map[%s] -> %d", mapNames[i].c_str(), fd.get());
808 } else {
809 ALOGE("bpf_create_map[%s] -> %d errno:%d", mapNames[i].c_str(), fd.get(), saved_errno);
810 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700811 }
812
813 if (!fd.ok()) return -saved_errno;
814
815 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
816 // safety (since reuse code path is rare) run these checks even if we just created it.
817 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
818 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
819
820 if (!reuse) {
821 if (specified(selinux_context)) {
822 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
823 "tmp_map_" + objName + "_" + mapNames[i];
824 ret = bpfFdPin(fd, createLoc.c_str());
825 if (ret) {
826 int err = errno;
827 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
828 return -err;
829 }
830 ret = renameat2(AT_FDCWD, createLoc.c_str(),
831 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
832 if (ret) {
833 int err = errno;
834 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
835 err, strerror(err));
836 return -err;
837 }
838 } else {
839 ret = bpfFdPin(fd, mapPinLoc.c_str());
840 if (ret) {
841 int err = errno;
842 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
843 return -err;
844 }
845 }
846 ret = chmod(mapPinLoc.c_str(), md[i].mode);
847 if (ret) {
848 int err = errno;
849 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
850 strerror(err));
851 return -err;
852 }
853 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
854 if (ret) {
855 int err = errno;
856 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
857 ret, err, strerror(err));
858 return -err;
859 }
860 }
861
862 int mapId = bpfGetFdMapId(fd);
863 if (mapId == -1) {
Maciej Żenczykowski508c8f72024-08-28 15:07:33 -0700864 if (isAtLeastKernelVersion(4, 14, 0))
865 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700866 } else {
867 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
868 }
869
870 mapFds.push_back(std::move(fd));
871 }
872
873 return ret;
874}
875
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700876static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
877 int insnIndex;
878 struct bpf_insn *insn, *insns;
879
880 insns = (struct bpf_insn*)(insnsPtr);
881
882 insnIndex = offset / sizeof(struct bpf_insn);
883 insn = &insns[insnIndex];
884
885 // Occasionally might be useful for relocation debugging, but pretty spammy
886 if (0) {
887 ALOGV("applying relo to instruction at byte offset: %llu, "
888 "insn offset %d, insn %llx",
889 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
890 }
891
892 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700893 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700894 return;
895 }
896
897 insn->imm = fd;
898 insn->src_reg = BPF_PSEUDO_MAP_FD;
899}
900
901static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
902 vector<string> mapNames;
903
904 int ret = getSectionSymNames(elfFile, "maps", mapNames);
905 if (ret) return;
906
907 for (int k = 0; k != (int)cs.size(); k++) {
908 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
909 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
910
911 for (int i = 0; i < n_rel; i++) {
912 int symIndex = ELF64_R_SYM(rel[i].r_info);
913 string symName;
914
915 ret = getSymNameByIdx(elfFile, symIndex, symName);
916 if (ret) return;
917
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000918 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700919 for (int j = 0; j < (int)mapNames.size(); j++) {
920 if (!mapNames[j].compare(symName)) {
921 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
922 break;
923 }
924 }
925 }
926 }
927}
928
929static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
930 const char* prefix, const unsigned int bpfloader_ver) {
931 unsigned kvers = kernelVersion();
932
933 if (!kvers) {
934 ALOGE("unable to get kernel version");
935 return -EINVAL;
936 }
937
938 string objName = pathToObjName(string(elfPath));
939
940 for (int i = 0; i < (int)cs.size(); i++) {
941 unique_fd& fd = cs[i].prog_fd;
942 int ret;
943 string name = cs[i].name;
944
945 if (!cs[i].prog_def.has_value()) {
946 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
947 return -EINVAL;
948 }
949
950 unsigned min_kver = cs[i].prog_def->min_kver;
951 unsigned max_kver = cs[i].prog_def->max_kver;
952 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
953 max_kver, kvers);
954 if (kvers < min_kver) continue;
955 if (kvers >= max_kver) continue;
956
957 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
958 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
959 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
960 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700961
962 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
963 bpfMinVer, bpfMaxVer);
964 if (bpfloader_ver < bpfMinVer) continue;
965 if (bpfloader_ver >= bpfMaxVer) continue;
966
967 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
968 (cs[i].prog_def->ignore_on_user && isUser()) ||
969 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
970 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
971 getBuildType().c_str());
972 continue;
973 }
974
975 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
976 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
977 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
978 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
979 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
980 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
981 continue;
982 }
983
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700984 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000985 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700986 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
987 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
988 }
989
990 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000991 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700992 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
993 lookupPinSubdir(pin_subdir));
994 }
995
996 // strip any potential $foo suffix
997 // this can be used to provide duplicate programs
998 // conditionally loaded based on running kernel version
999 name = name.substr(0, name.find_last_of('$'));
1000
1001 bool reuse = false;
1002 // Format of pin location is
1003 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1004 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1005 objName + '_' + string(name);
1006 if (access(progPinLoc.c_str(), F_OK) == 0) {
1007 fd.reset(retrieveProgram(progPinLoc.c_str()));
1008 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
1009 (!fd.ok() ? std::strerror(errno) : "no error"));
1010 reuse = true;
1011 } else {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001012 static char log_buf[1 << 20]; // 1 MiB logging buffer
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001013
1014 union bpf_attr req = {
1015 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001016 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001017 .insns = ptr_to_u64(cs[i].data.data()),
1018 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001019 .log_level = 1,
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001020 .log_size = sizeof(log_buf),
1021 .log_buf = ptr_to_u64(log_buf),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001022 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001023 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001024 };
1025 if (isAtLeastKernelVersion(4, 15, 0))
1026 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1027 fd.reset(bpf(BPF_PROG_LOAD, req));
1028
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001029 // Kernel should have NULL terminated the log buffer, but force it anyway for safety
1030 log_buf[sizeof(log_buf) - 1] = 0;
1031
1032 // Strip out final newline if present
1033 int log_chars = strlen(log_buf);
1034 if (log_chars && log_buf[log_chars - 1] == '\n') log_buf[--log_chars] = 0;
1035
1036 bool log_oneline = !strchr(log_buf, '\n');
1037
1038 ALOGD("BPF_PROG_LOAD call for %s (%s) returned '%s' fd: %d (%s)", elfPath,
1039 cs[i].name.c_str(), log_oneline ? log_buf : "{multiline}",
1040 fd.get(), (!fd.ok() ? std::strerror(errno) : "ok"));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001041
1042 if (!fd.ok()) {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001043 // kernel NULL terminates log_buf, so this checks for non-empty string
1044 if (log_buf[0]) {
1045 vector<string> lines = Split(log_buf, "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001046
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001047 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1048 for (const auto& line : lines) ALOGW("%s", line.c_str());
1049 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1050 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001051
1052 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001053 ALOGW("failed program %s is marked optional - continuing...",
1054 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001055 continue;
1056 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001057 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001058 }
1059 }
1060
1061 if (!fd.ok()) return fd.get();
1062
1063 if (!reuse) {
1064 if (specified(selinux_context)) {
1065 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1066 "tmp_prog_" + objName + '_' + string(name);
1067 ret = bpfFdPin(fd, createLoc.c_str());
1068 if (ret) {
1069 int err = errno;
1070 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1071 return -err;
1072 }
1073 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1074 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1075 if (ret) {
1076 int err = errno;
1077 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1078 err, strerror(err));
1079 return -err;
1080 }
1081 } else {
1082 ret = bpfFdPin(fd, progPinLoc.c_str());
1083 if (ret) {
1084 int err = errno;
1085 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1086 return -err;
1087 }
1088 }
1089 if (chmod(progPinLoc.c_str(), 0440)) {
1090 int err = errno;
1091 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1092 return -err;
1093 }
1094 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1095 (gid_t)cs[i].prog_def->gid)) {
1096 int err = errno;
1097 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1098 cs[i].prog_def->gid, err, strerror(err));
1099 return -err;
1100 }
1101 }
1102
1103 int progId = bpfGetFdProgId(fd);
1104 if (progId == -1) {
1105 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
1106 } else {
1107 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
1108 }
1109 }
1110
1111 return 0;
1112}
1113
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001114int loadProg(const char* const elfPath, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001115 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001116 vector<char> license;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001117 vector<codeSection> cs;
1118 vector<unique_fd> mapFds;
1119 int ret;
1120
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001121 ifstream elfFile(elfPath, ios::in | ios::binary);
1122 if (!elfFile.is_open()) return -1;
1123
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001124 ret = readSectionByName("license", elfFile, license);
1125 if (ret) {
1126 ALOGE("Couldn't find license in %s", elfPath);
1127 return ret;
1128 } else {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001129 ALOGD("Loading ELF object %s with license %s",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001130 elfPath, (char*)license.data());
1131 }
1132
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001133 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1134 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001135
1136 // inclusive lower bound check
1137 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001138 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001139 bpfloader_ver, elfPath, bpfLoaderMinVer);
1140 return 0;
1141 }
1142
1143 // exclusive upper bound check
1144 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001145 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001146 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1147 return 0;
1148 }
1149
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001150 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001151 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1152
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001153 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001154 if (ret) {
1155 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1156 return ret;
1157 }
1158
1159 for (int i = 0; i < (int)mapFds.size(); i++)
1160 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1161
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001162 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001163 // BPF .o's with no programs are only supported by mainline netbpfload,
1164 // make sure .o's targeting non-mainline (ie. S) bpfloader don't show up.
1165 if (ret == -ENOENT && bpfLoaderMinVer >= BPFLOADER_MAINLINE_VERSION)
1166 return 0;
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001167 if (ret) {
1168 ALOGE("Couldn't read all code sections in %s", elfPath);
1169 return ret;
1170 }
1171
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001172 applyMapRelo(elfFile, mapFds, cs);
1173
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001174 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001175 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1176
1177 return ret;
1178}
1179
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001180static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001181 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001182 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001183 if (errno == ENOENT) return false;
1184 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1185 abort(); // can only hit this if permissions (likely selinux) are screwed up
1186}
1187
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001188#define APEXROOT "/apex/com.android.tethering"
1189#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001190
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001191const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001192 // S+ Tethering mainline module (network_stack): tether offload
1193 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001194 .dir = BPFROOT "/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001195 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001196 },
1197 // T+ Tethering mainline module (shared with netd & system server)
1198 // netutils_wrapper (for iptables xt_bpf) has access to programs
1199 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001200 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001201 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001202 },
1203 // T+ Tethering mainline module (shared with netd & system server)
1204 // netutils_wrapper has no access, netd has read only access
1205 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001206 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001207 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001208 },
1209 // T+ Tethering mainline module (shared with system server)
1210 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001211 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001212 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001213 },
1214 // T+ Tethering mainline module (not shared, just network_stack)
1215 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001216 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001217 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001218 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001219};
1220
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001221static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001222 int retVal = 0;
1223 DIR* dir;
1224 struct dirent* ent;
1225
1226 if ((dir = opendir(location.dir)) != NULL) {
1227 while ((ent = readdir(dir)) != NULL) {
1228 string s = ent->d_name;
1229 if (!EndsWith(s, ".o")) continue;
1230
1231 string progPath(location.dir);
1232 progPath += s;
1233
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001234 int ret = loadProg(progPath.c_str(), bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001235 if (ret) {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001236 retVal = ret;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001237 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1238 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001239 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001240 }
1241 }
1242 closedir(dir);
1243 }
1244 return retVal;
1245}
1246
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001247static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001248 if (*prefix) {
1249 mode_t prevUmask = umask(0);
1250
1251 string s = "/sys/fs/bpf/";
1252 s += prefix;
1253
1254 errno = 0;
1255 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1256 if (ret && errno != EEXIST) {
1257 const int err = errno;
1258 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1259 return -err;
1260 }
1261
1262 umask(prevUmask);
1263 }
1264 return 0;
1265}
1266
1267// Technically 'value' doesn't need to be newline terminated, but it's best
1268// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1269// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001270static int writeProcSysFile(const char *filename, const char *value) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001271 unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001272 if (fd < 0) {
1273 const int err = errno;
1274 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1275 return -err;
1276 }
1277 int len = strlen(value);
1278 int v = write(fd, value, len);
1279 if (v < 0) {
1280 const int err = errno;
1281 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1282 return -err;
1283 }
1284 if (v != len) {
1285 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1286 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1287 return -EINVAL;
1288 }
1289 return 0;
1290}
1291
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001292#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001293const char * const platformBpfLoader = "/system/bin/bpfloader";
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001294const char *const uprobestatsBpfLoader =
1295 "/apex/com.android.uprobestats/bin/uprobestatsbpfload";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001296
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001297static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001298 char * found_blockdev = NULL;
1299 FILE * f = NULL;
1300 char buf[4096];
1301
1302 f = fopen("/proc/mounts", "re");
1303 if (!f) return 1;
1304
1305 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1306 while (fgets(buf, sizeof(buf), f)) {
1307 char * blockdev = buf;
1308 char * space = strchr(blockdev, ' ');
1309 if (!space) continue;
1310 *space = '\0';
1311 char * mntpath = space + 1;
1312 space = strchr(mntpath, ' ');
1313 if (!space) continue;
1314 *space = '\0';
1315 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1316 found_blockdev = strdup(blockdev);
1317 break;
1318 }
1319 fclose(f);
1320 f = NULL;
1321
1322 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001323 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001324
1325 f = fopen("/proc/mounts", "re");
1326 if (!f) { free(found_blockdev); return 3; }
1327
1328 while (fgets(buf, sizeof(buf), f)) {
1329 char * blockdev = buf;
1330 char * space = strchr(blockdev, ' ');
1331 if (!space) continue;
1332 *space = '\0';
1333 char * mntpath = space + 1;
1334 space = strchr(mntpath, ' ');
1335 if (!space) continue;
1336 *space = '\0';
1337 if (strcmp(blockdev, found_blockdev)) continue;
1338 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1339 char * at = strchr(mntpath, '@');
1340 if (!at) continue;
1341 char * ver = at + 1;
1342 ALOGI("Tethering APEX version %s", ver);
1343 }
1344 fclose(f);
1345 free(found_blockdev);
1346 return 0;
1347}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001348
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001349static bool hasGSM() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001350 static string ph = GetProperty("gsm.current.phone-type", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001351 static bool gsm = (ph != "");
1352 static bool logged = false;
1353 if (!logged) {
1354 logged = true;
1355 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1356 }
1357 return gsm;
1358}
1359
1360static bool isTV() {
1361 if (hasGSM()) return false; // TVs don't do GSM
1362
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001363 static string key = GetProperty("ro.oem.key1", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001364 static bool tv = StartsWith(key, "ATV00");
1365 static bool logged = false;
1366 if (!logged) {
1367 logged = true;
1368 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1369 }
1370 return tv;
1371}
1372
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001373static bool isWear() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001374 static string wearSdkStr = GetProperty("ro.cw_build.wear_sdk.version", "");
1375 static int wearSdkInt = GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1376 static string buildChars = GetProperty("ro.build.characteristics", "");
1377 static vector<string> v = Tokenize(buildChars, ",");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001378 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1379 static bool wear = (wearSdkInt > 0) || watch;
1380 static bool logged = false;
1381 if (!logged) {
1382 logged = true;
1383 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1384 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1385 }
1386 return wear;
1387}
1388
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001389static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001390 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001391
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001392 // Any released device will have codename REL instead of a 'real' codename.
1393 // For safety: default to 'REL' so we default to unreleased=false on failure.
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001394 const bool unreleased = (GetProperty("ro.build.version.codename", "REL") != "REL");
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001395
1396 // goog/main device_api_level is bumped *way* before aosp/main api level
1397 // (the latter only gets bumped during the push of goog/main to aosp/main)
1398 //
1399 // Since we develop in AOSP, we want it to behave as if it was bumped too.
1400 //
1401 // Note that AOSP doesn't really have a good api level (for example during
1402 // early V dev cycle, it would have *all* of T, some but not all of U, and some V).
1403 // One could argue that for our purposes AOSP api level should be infinite or 10000.
1404 //
1405 // This could also cause api to be increased in goog/main or other branches,
1406 // but I can't imagine a case where this would be a problem: the problem
1407 // is rather a too low api level, rather than some ill defined high value.
1408 // For example as I write this aosp is 34/U, and goog is 35/V,
1409 // we want to treat both goog & aosp as 35/V, but it's harmless if we
1410 // treat goog as 36 because that value isn't yet defined to mean anything,
1411 // and we thus never compare against it.
1412 //
1413 // Also note that 'android_get_device_api_level()' is what the
1414 // //system/core/init/apex_init_util.cpp
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001415 // apex init .XXrc parsing code uses for XX filtering, and that code
1416 // (now) similarly uses __ANDROID_API_FUTURE__ for non 'REL' codenames.
1417 const int api_level = unreleased ? __ANDROID_API_FUTURE__ : android_get_device_api_level();
1418 const bool isAtLeastT = (api_level >= __ANDROID_API_T__);
1419 const bool isAtLeastU = (api_level >= __ANDROID_API_U__);
1420 const bool isAtLeastV = (api_level >= __ANDROID_API_V__);
1421 const bool isAtLeast25Q2 = (api_level > __ANDROID_API_V__); // TODO: fix >
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001422
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001423 const int first_api_level = GetIntProperty("ro.board.first_api_level", api_level);
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001424
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001425 // last in U QPR2 beta1
1426 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1427 // first in U QPR2 beta~2
1428 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1429
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001430 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001431 unsigned int bpfloader_ver = BPFLOADER_MAINLINE_VERSION; // [42u]
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001432 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1433 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1434 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1435 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001436 if (isAtLeast25Q2) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_25Q2_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001437
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001438 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) uid:%d rc:%d%d",
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001439 bpfloader_ver, argv[0], android_get_device_api_level(), api_level,
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001440 kernelVersion(), describeArch(), getuid(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001441 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001442
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001443 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1444 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1445 return 1;
1446 }
1447
1448 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1449 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1450 return 1;
1451 }
1452
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001453 logTetheringApexVersion();
1454
Maciej Żenczykowski11141da2024-03-15 18:21:33 -07001455 if (!isAtLeastT) {
1456 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001457 return 1;
1458 }
1459
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001460 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001461 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001462 ALOGE("Android T requires kernel 4.9.");
1463 return 1;
1464 }
1465
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001466 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001467 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001468 ALOGE("Android U requires kernel 4.14.");
1469 return 1;
1470 }
1471
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001472 // V bumps the kernel requirement up to 4.19
1473 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001474 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001475 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001476 return 1;
1477 }
1478
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001479 // 25Q2 bumps the kernel requirement up to 5.4
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001480 // see also: //system/netd/tests/kernel_test.cpp TestKernel54
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001481 if (isAtLeast25Q2 && !isAtLeastKernelVersion(5, 4, 0)) {
1482 ALOGE("Android 25Q2 requires kernel 5.4.");
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001483 return 1;
1484 }
1485
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001486 // Technically already required by U, but only enforce on V+
1487 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1488 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1489 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1490 if (!isTV()) return 1;
1491 }
1492
Maciej Żenczykowski127715a2025-02-10 21:52:01 -08001493 if (isKernel32Bit() && isAtLeast25Q2) {
1494 ALOGE("Android 25Q2 requires 64 bit kernel.");
1495 return 1;
1496 }
1497
Maciej Żenczykowski9b6a9942024-09-03 16:08:35 -07001498 // 6.6 is highest version supported by Android V, so this is effectively W+ (sdk=36+)
1499 if (isKernel32Bit() && isAtLeastKernelVersion(6, 7, 0)) {
1500 ALOGE("Android platform with 32 bit kernel version >= 6.7.0 is unsupported");
1501 return 1;
1502 }
1503
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001504 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1505 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001506 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001507 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001508 }
1509
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001510 if (isAtLeastV) {
1511 bool bad = false;
1512
1513 if (!isLtsKernel()) {
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001514 ALOGW("Android V+ only supports LTS kernels.");
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001515 bad = true;
1516 }
1517
1518#define REQUIRE(maj, min, sub) \
1519 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001520 ALOGW("Android V+ requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001521 bad = true; \
1522 }
1523
1524 REQUIRE(4, 19, 236)
1525 REQUIRE(5, 4, 186)
1526 REQUIRE(5, 10, 199)
1527 REQUIRE(5, 15, 136)
1528 REQUIRE(6, 1, 57)
1529 REQUIRE(6, 6, 0)
Maciej Żenczykowski06f38e32024-12-11 07:12:59 -08001530 REQUIRE(6, 12, 0)
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001531
1532#undef REQUIRE
1533
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001534 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001535 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1536 }
1537 }
1538
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001539 /* Android 14/U should only launch on 64-bit kernels
1540 * T launches on 5.10/5.15
1541 * U launches on 5.15/6.1
1542 * So >=5.16 implies isKernel64Bit()
1543 *
1544 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1545 *
1546 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1547 * we also require 64-bit userspace.
1548 *
1549 * There are various known issues with 32-bit userspace talking to various
1550 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1551 * Some of these have userspace or kernel workarounds/hacks.
1552 * Some of them don't...
1553 * We're going to be removing the hacks.
1554 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1555 * Note: this check/enforcement only applies to *system* userspace code,
1556 * it does not affect unprivileged apps, the 32-on-64 compatibility
1557 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1558 *
1559 * Additionally the 32-bit kernel jit support is poor,
1560 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001561 * Note, however, that TV and Wear devices will continue to support 32-bit userspace
1562 * on ARM64.
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001563 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001564 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001565 // Stuff won't work reliably, but...
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001566 if (isArm() && (isTV() || isWear())) {
1567 // exempt Arm TV or Wear devices (arm32 ABI is far less problematic than x86-32)
1568 ALOGW("[Arm TV/Wear] 32-bit userspace unsupported on 6.2+ kernels.");
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001569 } else if (first_api_level <= __ANDROID_API_T__ && isArm()) {
1570 // also exempt Arm devices upgrading with major kernel rev from T-
1571 // might possibly be better for them to run with a newer kernel...
1572 ALOGW("[Arm KernelUpRev] 32-bit userspace unsupported on 6.2+ kernels.");
1573 } else if (isArm()) {
1574 ALOGE("[Arm] 64-bit userspace required on 6.2+ kernels (%d).", first_api_level);
1575 return 1;
1576 } else { // x86 since RiscV cannot be 32-bit
1577 ALOGE("[x86] 64-bit userspace required on 6.2+ kernels.");
1578 return 1;
1579 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001580 }
1581
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001582 // On handheld, 6.6 is highest version supported by Android V (sdk=35), so this is for sdk=36+
1583 if (!isArm() && isUserspace32bit() && isAtLeastKernelVersion(6, 7, 0)) {
Maciej Żenczykowski21b4a052024-09-03 15:46:48 -07001584 ALOGE("64-bit userspace required on 6.7+ kernels.");
1585 return 1;
1586 }
1587
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001588 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001589 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001590 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001591 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001592 return 1;
1593 }
1594
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001595 if (runningAsRoot) {
1596 // Note: writing this proc file requires being root (always the case on V+)
1597
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001598 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1599 // but we need 0 (enabled)
1600 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1601 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1602 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001603 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001604 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001605
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001606 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001607 // Note: writing these proc files requires CAP_NET_ADMIN
1608 // and sepolicy which is only present on U+,
1609 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1610 // trigger (ie. by init itself) instead.
1611
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001612 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1613 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1614 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1615 // kernel does not have CONFIG_BPF_JIT=y)
1616 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1617 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1618 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001619
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001620 // Enable JIT kallsyms export for privileged users only
1621 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1622 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1623 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1624 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001625
1626 // Create all the pin subdirectories
1627 // (this must be done first to allow selinux_context and pin_subdir functionality,
1628 // which could otherwise fail with ENOENT during object pinning or renaming,
1629 // due to ordering issues)
1630 for (const auto& location : locations) {
1631 if (createSysFsBpfSubDir(location.prefix)) return 1;
1632 }
1633
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001634 // Note: there's no actual src dir for fs_bpf_loader .o's,
1635 // so it is not listed in 'locations[].prefix'.
1636 // This is because this is primarily meant for triggering genfscon rules,
1637 // and as such this will likely always be the case.
1638 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1639 if (createSysFsBpfSubDir("loader")) return 1;
1640
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001641 // Load all ELF objects, create programs and maps, and pin them
1642 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001643 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001644 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1645 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1646 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1647 "problems or startup script race.");
1648 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1649 sleep(20);
1650 return 2;
1651 }
1652 }
1653
1654 int key = 1;
1655 int value = 123;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001656 unique_fd map(
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001657 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1658 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001659 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1660 return 1;
1661 }
1662
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001663 // leave a flag that we're done
1664 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001665
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001666 // platform bpfloader will only succeed when run as root
1667 if (!runningAsRoot) {
1668 // unreachable on U QPR3+ which always runs netbpfload as root
1669
1670 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1671 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001672 }
1673
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001674 // unreachable before U QPR3
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001675 if (exists(uprobestatsBpfLoader)) {
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001676 ALOGI("done, transferring control to uprobestatsbpfload.");
1677 const char *args[] = {
1678 uprobestatsBpfLoader,
1679 NULL,
1680 };
1681 execve(args[0], (char **)args, envp);
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001682 ALOGI("unable to execute uprobestatsbpfload, transferring control to "
1683 "platform bpfloader.");
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001684 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001685
1686 // platform BpfLoader *needs* to run as root
1687 const char * args[] = { platformBpfLoader, NULL, };
1688 execve(args[0], (char**)args, envp);
1689 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1690 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001691}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001692
1693} // namespace bpf
1694} // namespace android
1695
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001696int main(int argc, char** argv, char * const envp[]) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001697 InitLogging(argv, &KernelLogger);
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001698
1699 if (argc == 2 && !strcmp(argv[1], "done")) {
1700 // we're being re-exec'ed from platform bpfloader to 'finalize' things
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001701 if (!SetProperty("bpf.progs_loaded", "1")) {
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001702 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1703 return 125;
1704 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001705 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001706 return 0;
1707 }
1708
1709 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001710}