blob: 64ebe0c5772331e965563cb97af894ad52160b85 [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>
Motomu Utsumib3d3c2a2025-03-18 15:06:34 +090020#include <bpf/btf.h>
Motomu Utsumia7693582025-02-05 17:40:08 +090021#include <bpf/libbpf.h>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070022#include <dirent.h>
23#include <elf.h>
24#include <errno.h>
25#include <error.h>
26#include <fcntl.h>
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070027#include <fstream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070028#include <inttypes.h>
29#include <iostream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070030#include <linux/unistd.h>
31#include <log/log.h>
32#include <net/if.h>
33#include <optional>
34#include <stdint.h>
35#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
38#include <string>
39#include <sys/mman.h>
40#include <sys/socket.h>
41#include <sys/stat.h>
42#include <sys/types.h>
43#include <sys/utsname.h>
44#include <sys/wait.h>
45#include <sysexits.h>
46#include <unistd.h>
47#include <unordered_map>
48#include <vector>
49
50#include <android-base/cmsg.h>
51#include <android-base/file.h>
52#include <android-base/logging.h>
53#include <android-base/macros.h>
54#include <android-base/properties.h>
55#include <android-base/stringprintf.h>
56#include <android-base/strings.h>
57#include <android-base/unique_fd.h>
58#include <android/api-level.h>
59
60#include "BpfSyscallWrappers.h"
61#include "bpf/BpfUtils.h"
Maciej Żenczykowskid6028352024-08-19 15:20:04 -070062#include "bpf_map_def.h"
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070063
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +000064// The following matches bpf_helpers.h, which is only for inclusion in bpf code
Maciej Żenczykowski8c097782025-03-04 13:11:56 -080065#define BPFLOADER_MAINLINE_S_VERSION 42u
Maciej Żenczykowski199fd352025-02-13 15:17:08 -080066#define BPFLOADER_MAINLINE_25Q2_VERSION 47u
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +000067
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070068using android::base::EndsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070069using android::base::GetIntProperty;
70using android::base::GetProperty;
71using android::base::InitLogging;
72using android::base::KernelLogger;
73using android::base::SetProperty;
74using android::base::Split;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070075using android::base::StartsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070076using android::base::Tokenize;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070077using android::base::unique_fd;
78using std::ifstream;
79using std::ios;
80using std::optional;
81using std::string;
82using std::vector;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070083
84namespace android {
85namespace bpf {
86
87// Bpf programs may specify per-program & per-map selinux_context and pin_subdir.
88//
89// The BpfLoader needs to convert these bpf.o specified strings into an enum
90// for internal use (to check that valid values were specified for the specific
91// location of the bpf.o file).
92//
93// It also needs to map selinux_context's into pin_subdir's.
94// This is because of how selinux_context is actually implemented via pin+rename.
95//
96// Thus 'domain' enumerates all selinux_context's/pin_subdir's that the BpfLoader
97// is aware of. Thus there currently needs to be a 1:1 mapping between the two.
98//
99enum class domain : int {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700100 unspecified = 0, // means just use the default for that specific pin location
101 tethering, // (S+) fs_bpf_tethering /sys/fs/bpf/tethering
102 net_private, // (T+) fs_bpf_net_private /sys/fs/bpf/net_private
103 net_shared, // (T+) fs_bpf_net_shared /sys/fs/bpf/net_shared
104 netd_readonly, // (T+) fs_bpf_netd_readonly /sys/fs/bpf/netd_readonly
105 netd_shared, // (T+) fs_bpf_netd_shared /sys/fs/bpf/netd_shared
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700106 loader, // (U+) fs_bpf_loader /sys/fs/bpf/loader
107 // on T due to lack of sepolicy/genfscon rules it behaves simply as 'fs_bpf'
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700108};
109
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700110static constexpr domain AllDomains[] = {
111 domain::unspecified,
112 domain::tethering,
113 domain::net_private,
114 domain::net_shared,
115 domain::netd_readonly,
116 domain::netd_shared,
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700117 domain::loader,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700118};
119
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700120static constexpr bool specified(domain d) {
121 return d != domain::unspecified;
122}
123
124struct Location {
125 const char* const dir = "";
126 const char* const prefix = "";
Maciej Żenczykowski0b477492025-03-04 22:12:42 -0800127 const bool t_plus = true;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700128};
129
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700130// Returns the build type string (from ro.build.type).
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700131const std::string& getBuildType() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700132 static std::string t = GetProperty("ro.build.type", "unknown");
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700133 return t;
134}
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700135
136// The following functions classify the 3 Android build types.
137inline bool isEng() {
138 return getBuildType() == "eng";
139}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700140
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700141inline bool isUser() {
142 return getBuildType() == "user";
143}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700144
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700145inline bool isUserdebug() {
146 return getBuildType() == "userdebug";
147}
148
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700149#define BPF_FS_PATH "/sys/fs/bpf/"
150
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700151static unsigned int page_size = static_cast<unsigned int>(getpagesize());
152
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700153constexpr const char* lookupSelinuxContext(const domain d) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700154 switch (d) {
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700155 case domain::unspecified: return "";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700156 case domain::tethering: return "fs_bpf_tethering";
157 case domain::net_private: return "fs_bpf_net_private";
158 case domain::net_shared: return "fs_bpf_net_shared";
159 case domain::netd_readonly: return "fs_bpf_netd_readonly";
160 case domain::netd_shared: return "fs_bpf_netd_shared";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700161 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700162 }
163}
164
165domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
166 for (domain d : AllDomains) {
167 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
168 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
169 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
170 }
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700171 ALOGE("unrecognized selinux_context '%-32s'", s);
172 // Note: we *can* just abort() here as we only load bpf .o files shipped
173 // in the same mainline module / apex as NetBpfLoad itself.
174 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700175}
176
177constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
178 switch (d) {
179 case domain::unspecified: return unspecified;
180 case domain::tethering: return "tethering/";
181 case domain::net_private: return "net_private/";
182 case domain::net_shared: return "net_shared/";
183 case domain::netd_readonly: return "netd_readonly/";
184 case domain::netd_shared: return "netd_shared/";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700185 case domain::loader: return "loader/";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700186 }
187};
188
189domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
190 for (domain d : AllDomains) {
191 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
192 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
193 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
194 }
195 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700196 // Note: we *can* just abort() here as we only load bpf .o files shipped
197 // in the same mainline module / apex as NetBpfLoad itself.
198 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700199}
200
201static string pathToObjName(const string& path) {
202 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700203 string filename = Split(path, "/").back();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700204 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
205 string name = filename.substr(0, filename.find_last_of('.'));
206 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
207 // this can be used to provide duplicate programs (mux based on the bpfloader version)
208 return name.substr(0, name.find_last_of('@'));
209}
210
211typedef struct {
212 const char* name;
213 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000214 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700215} sectionType;
216
217/*
218 * Map section name prefixes to program types, the section name will be:
219 * SECTION(<prefix>/<name-of-program>)
220 * For example:
221 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
222 * is the name of the program, and tracepoint is the type.
223 *
224 * However, be aware that you should not be directly using the SECTION() macro.
Maciej Żenczykowski3a085152024-09-18 23:45:52 +0000225 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE macros.
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700226 *
227 * Programs shipped inside the tethering apex should be limited to networking stuff,
228 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
229 * since they are less stable abi/api and may conflict with platform uses of bpf.
230 */
231sectionType sectionNameTypes[] = {
232 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
233 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000234 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
235 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700236 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
237 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
238 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
239 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
240 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
241 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
242 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700243 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
244 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
245 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
246 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000247 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
248 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700249 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
250 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
251 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000252 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700253 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
254 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000255 {"xdp/", BPF_PROG_TYPE_XDP},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700256};
257
258typedef struct {
259 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000260 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700261 string name;
262 vector<char> data;
263 vector<char> rel_data;
264 optional<struct bpf_prog_def> prog_def;
265
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000266 unique_fd prog_fd; // fd after loading
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700267} codeSection;
268
269static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
270 elfFile.seekg(0);
271 if (elfFile.fail()) return -1;
272
273 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
274
275 return 0;
276}
277
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000278// Reads all section header tables into an Shdr array
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700279static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
280 Elf64_Ehdr eh;
281 int ret = 0;
282
283 ret = readElfHeader(elfFile, &eh);
284 if (ret) return ret;
285
286 elfFile.seekg(eh.e_shoff);
287 if (elfFile.fail()) return -1;
288
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000289 // Read shdr table entries
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700290 shTable.resize(eh.e_shnum);
291
292 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
293
294 return 0;
295}
296
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000297// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700298static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
299 vector<Elf64_Shdr> shTable;
300 int ret = readSectionHeadersAll(elfFile, shTable);
301 if (ret) return ret;
302
303 elfFile.seekg(shTable[id].sh_offset);
304 if (elfFile.fail()) return -1;
305
306 sec.resize(shTable[id].sh_size);
307 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
308
309 return 0;
310}
311
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000312// Read whole section header string table
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700313static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
314 Elf64_Ehdr eh;
315 int ret = readElfHeader(elfFile, &eh);
316 if (ret) return ret;
317
318 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
319 if (ret) return ret;
320
321 return 0;
322}
323
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000324// Get name from offset in strtab
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700325static int getSymName(ifstream& elfFile, int nameOff, string& name) {
326 int ret;
327 vector<char> secStrTab;
328
329 ret = readSectionHeaderStrtab(elfFile, secStrTab);
330 if (ret) return ret;
331
332 if (nameOff >= (int)secStrTab.size()) return -1;
333
334 name = string((char*)secStrTab.data() + nameOff);
335 return 0;
336}
337
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000338// Reads a full section by name - example to get the GPL license
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700339static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
340 vector<char> secStrTab;
341 vector<Elf64_Shdr> shTable;
342 int ret;
343
344 ret = readSectionHeadersAll(elfFile, shTable);
345 if (ret) return ret;
346
347 ret = readSectionHeaderStrtab(elfFile, secStrTab);
348 if (ret) return ret;
349
350 for (int i = 0; i < (int)shTable.size(); i++) {
351 char* secname = secStrTab.data() + shTable[i].sh_name;
352 if (!secname) continue;
353
354 if (!strcmp(secname, name)) {
355 vector<char> dataTmp;
356 dataTmp.resize(shTable[i].sh_size);
357
358 elfFile.seekg(shTable[i].sh_offset);
359 if (elfFile.fail()) return -1;
360
361 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
362
363 data = dataTmp;
364 return 0;
365 }
366 }
367 return -2;
368}
369
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700370unsigned int readSectionUint(const char* name, ifstream& elfFile) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700371 vector<char> theBytes;
372 int ret = readSectionByName(name, elfFile, theBytes);
373 if (ret) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700374 ALOGE("Couldn't find section %s.", name);
375 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700376 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700377 ALOGE("Section %s is too short.", name);
378 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700379 } else {
380 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
381 unsigned int value = static_cast<unsigned char>(theBytes[3]);
382 value <<= 8;
383 value += static_cast<unsigned char>(theBytes[2]);
384 value <<= 8;
385 value += static_cast<unsigned char>(theBytes[1]);
386 value <<= 8;
387 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000388 ALOGD("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700389 return value;
390 }
391}
392
393static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
394 int ret;
395 vector<Elf64_Shdr> shTable;
396
397 ret = readSectionHeadersAll(elfFile, shTable);
398 if (ret) return ret;
399
400 for (int i = 0; i < (int)shTable.size(); i++) {
401 if ((int)shTable[i].sh_type != type) continue;
402
403 vector<char> dataTmp;
404 dataTmp.resize(shTable[i].sh_size);
405
406 elfFile.seekg(shTable[i].sh_offset);
407 if (elfFile.fail()) return -1;
408
409 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
410
411 data = dataTmp;
412 return 0;
413 }
414 return -2;
415}
416
417static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
418 return (a.st_value < b.st_value);
419}
420
421static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
422 int ret, numElems;
423 Elf64_Sym* buf;
424 vector<char> secData;
425
426 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
427 if (ret) return ret;
428
429 buf = (Elf64_Sym*)secData.data();
430 numElems = (secData.size() / sizeof(Elf64_Sym));
431 data.assign(buf, buf + numElems);
432
433 if (sort) std::sort(data.begin(), data.end(), symCompare);
434 return 0;
435}
436
437static enum bpf_prog_type getSectionType(string& name) {
438 for (auto& snt : sectionNameTypes)
439 if (StartsWith(name, snt.name)) return snt.type;
440
441 return BPF_PROG_TYPE_UNSPEC;
442}
443
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700444static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700445 vector<char> pdData;
446 int ret = readSectionByName("progs", elfFile, pdData);
447 if (ret) return ret;
448
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700449 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700450 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700451 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700452 return -1;
453 };
454
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700455 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700456
457 const char* dataPtr = pdData.data();
458 for (auto& p : pd) {
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700459 // Copy the structure from the ELF file and move to the next one.
460 memcpy(&p, dataPtr, sizeof(struct bpf_prog_def));
461 dataPtr += sizeof(struct bpf_prog_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700462 }
463 return 0;
464}
465
466static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
467 optional<unsigned> symbolType = std::nullopt) {
468 int ret;
469 string name;
470 vector<Elf64_Sym> symtab;
471 vector<Elf64_Shdr> shTable;
472
473 ret = readSymTab(elfFile, 1 /* sort */, symtab);
474 if (ret) return ret;
475
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000476 // Get index of section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700477 ret = readSectionHeadersAll(elfFile, shTable);
478 if (ret) return ret;
479
480 int sec_idx = -1;
481 for (int i = 0; i < (int)shTable.size(); i++) {
482 ret = getSymName(elfFile, shTable[i].sh_name, name);
483 if (ret) return ret;
484
485 if (!name.compare(sectionName)) {
486 sec_idx = i;
487 break;
488 }
489 }
490
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000491 // No section found with matching name
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700492 if (sec_idx == -1) {
493 ALOGW("No %s section could be found in elf object", sectionName.c_str());
494 return -1;
495 }
496
497 for (int i = 0; i < (int)symtab.size(); i++) {
498 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
499
500 if (symtab[i].st_shndx == sec_idx) {
501 string s;
502 ret = getSymName(elfFile, symtab[i].st_name, s);
503 if (ret) return ret;
504 names.push_back(s);
505 }
506 }
507
508 return 0;
509}
510
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000511// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700512static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700513 vector<Elf64_Shdr> shTable;
514 int entries, ret = 0;
515
516 ret = readSectionHeadersAll(elfFile, shTable);
517 if (ret) return ret;
518 entries = shTable.size();
519
520 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700521 ret = readProgDefs(elfFile, pd);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700522 if (ret) return ret;
523 vector<string> progDefNames;
524 ret = getSectionSymNames(elfFile, "progs", progDefNames);
525 if (!pd.empty() && ret) return ret;
526
527 for (int i = 0; i < entries; i++) {
528 string name;
529 codeSection cs_temp;
530 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
531
532 ret = getSymName(elfFile, shTable[i].sh_name, name);
533 if (ret) return ret;
534
535 enum bpf_prog_type ptype = getSectionType(name);
536
537 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
538
539 // This must be done before '/' is replaced with '_'.
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000540 for (auto& snt : sectionNameTypes)
541 if (StartsWith(name, snt.name)) cs_temp.attach_type = snt.attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700542
543 string oldName = name;
544
545 // convert all slashes to underscores
546 std::replace(name.begin(), name.end(), '/', '_');
547
548 cs_temp.type = ptype;
549 cs_temp.name = name;
550
551 ret = readSectionByIdx(elfFile, i, cs_temp.data);
552 if (ret) return ret;
553 ALOGV("Loaded code section %d (%s)", i, name.c_str());
554
555 vector<string> csSymNames;
556 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
557 if (ret || !csSymNames.size()) return ret;
558 for (size_t i = 0; i < progDefNames.size(); ++i) {
559 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
560 cs_temp.prog_def = pd[i];
561 break;
562 }
563 }
564
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000565 // Check for rel section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700566 if (cs_temp.data.size() > 0 && i < entries) {
567 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
568 if (ret) return ret;
569
570 if (name == (".rel" + oldName)) {
571 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
572 if (ret) return ret;
573 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
574 }
575 }
576
577 if (cs_temp.data.size() > 0) {
578 cs.push_back(std::move(cs_temp));
579 ALOGV("Adding section %d to cs list", i);
580 }
581 }
582 return 0;
583}
584
585static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
586 vector<Elf64_Sym> symtab;
587 int ret = 0;
588
589 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
590 if (ret) return ret;
591
592 if (index >= (int)symtab.size()) return -1;
593
594 return getSymName(elfFile, symtab[index].st_name, name);
595}
596
597static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
598 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
599 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
600 // so on 4.9-T kernels just pretend the map matches our expectations.
601 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
602 // This is because the primary failure mode we're trying to detect here
603 // is either a source code misconfiguration (which is likely kernel independent)
604 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
605 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
606
607 // Assuming fd is a valid Bpf Map file descriptor then
608 // all the following should always succeed on a 4.14+ kernel.
609 // If they somehow do fail, they'll return -1 (and set errno),
610 // which should then cause (among others) a key_size mismatch.
611 int fd_type = bpfGetFdMapType(fd);
612 int fd_key_size = bpfGetFdKeySize(fd);
613 int fd_value_size = bpfGetFdValueSize(fd);
614 int fd_max_entries = bpfGetFdMaxEntries(fd);
615 int fd_map_flags = bpfGetFdMapFlags(fd);
616
617 // DEVMAPs are readonly from the bpf program side's point of view, as such
618 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
619 int desired_map_flags = (int)mapDef.map_flags;
620 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
621 desired_map_flags |= BPF_F_RDONLY_PROG;
622
623 // The .h file enforces that this is a power of two, and page size will
624 // also always be a power of two, so this logic is actually enough to
625 // force it to be a multiple of the page size, as required by the kernel.
626 unsigned int desired_max_entries = mapDef.max_entries;
627 if (type == BPF_MAP_TYPE_RINGBUF) {
628 if (desired_max_entries < page_size) desired_max_entries = page_size;
629 }
630
631 // The following checks should *never* trigger, if one of them somehow does,
632 // it probably means a bpf .o file has been changed/replaced at runtime
633 // and bpfloader was manually rerun (normally it should only run *once*
634 // early during the boot process).
635 // Another possibility is that something is misconfigured in the code:
636 // most likely a shared map is declared twice differently.
637 // But such a change should never be checked into the source tree...
638 if ((fd_type == type) &&
639 (fd_key_size == (int)mapDef.key_size) &&
640 (fd_value_size == (int)mapDef.value_size) &&
641 (fd_max_entries == (int)desired_max_entries) &&
642 (fd_map_flags == desired_map_flags)) {
643 return true;
644 }
645
646 ALOGE("bpf map name %s mismatch: desired/found: "
647 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
648 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
649 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
650 return false;
651}
652
Motomu Utsumib3d3c2a2025-03-18 15:06:34 +0900653static int setBtfDatasecSize(ifstream &elfFile, struct btf *btf,
654 struct btf_type *bt) {
655 const char *name = btf__name_by_offset(btf, bt->name_off);
656 if (!name) {
657 ALOGE("Couldn't resolve section name, errno: %d", errno);
658 return -errno;
659 }
660
661 vector<char> data;
662 int ret = readSectionByName(name, elfFile, data);
663 if (ret) {
664 ALOGE("Couldn't read section %s, ret: %d", name, ret);
665 return ret;
666 }
667 bt->size = data.size();
668 return 0;
669}
670
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700671static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700672 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700673 int ret;
674 vector<char> mdData;
675 vector<struct bpf_map_def> md;
676 vector<string> mapNames;
677 string objName = pathToObjName(string(elfPath));
678
679 ret = readSectionByName("maps", elfFile, mdData);
680 if (ret == -2) return 0; // no maps to read
681 if (ret) return ret;
682
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700683 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700684 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700685 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700686 return -1;
687 };
688
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700689 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700690
691 const char* dataPtr = mdData.data();
692 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700693 // Copy the structure from the ELF file and move to the next one.
694 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
695 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700696 }
697
698 ret = getSectionSymNames(elfFile, "maps", mapNames);
699 if (ret) return ret;
700
701 unsigned kvers = kernelVersion();
702
703 for (int i = 0; i < (int)mapNames.size(); i++) {
704 if (md[i].zero != 0) abort();
705
706 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000707 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700708 md[i].bpfloader_min_ver);
709 mapFds.push_back(unique_fd());
710 continue;
711 }
712
713 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000714 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700715 md[i].bpfloader_max_ver);
716 mapFds.push_back(unique_fd());
717 continue;
718 }
719
720 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000721 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700722 mapNames[i].c_str(), kvers, md[i].min_kver);
723 mapFds.push_back(unique_fd());
724 continue;
725 }
726
727 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000728 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700729 mapNames[i].c_str(), kvers, md[i].max_kver);
730 mapFds.push_back(unique_fd());
731 continue;
732 }
733
734 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
735 (md[i].ignore_on_userdebug && isUserdebug())) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000736 ALOGD("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700737 getBuildType().c_str());
738 mapFds.push_back(unique_fd());
739 continue;
740 }
741
742 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
743 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
744 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
745 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
746 (isRiscV() && md[i].ignore_on_riscv64)) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000747 ALOGD("skipping map %s which is ignored on %s", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700748 describeArch());
749 mapFds.push_back(unique_fd());
750 continue;
751 }
752
753 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski87019832025-02-03 22:04:26 -0800754 if (type == BPF_MAP_TYPE_LPM_TRIE && !isAtLeastKernelVersion(4, 14, 0)) {
755 // On Linux Kernels older than 4.14 this map type doesn't exist - autoskip.
756 ALOGD("skipping LPM_TRIE map %s - requires kver 4.14+", mapNames[i].c_str());
757 mapFds.push_back(unique_fd());
758 continue;
759 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700760 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
761 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
762 // of be approximated: ARRAY has the same userspace api, though it is not usable
763 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
764 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
765 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
766 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
767 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
768 type = BPF_MAP_TYPE_ARRAY;
769 }
770 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
771 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
772 // of be approximated: HASH has the same userspace visible api.
773 // However it cannot be used by ebpf programs in the same way.
774 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
775 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
776 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
777 // programs as being 5.4+...
778 type = BPF_MAP_TYPE_HASH;
779 }
780
781 // The .h file enforces that this is a power of two, and page size will
782 // also always be a power of two, so this logic is actually enough to
783 // force it to be a multiple of the page size, as required by the kernel.
784 unsigned int max_entries = md[i].max_entries;
785 if (type == BPF_MAP_TYPE_RINGBUF) {
786 if (max_entries < page_size) max_entries = page_size;
787 }
788
789 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
790 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000791 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700792 md[i].selinux_context, static_cast<int>(selinux_context),
793 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
794 }
795
796 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700797 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000798 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700799 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
800 }
801
802 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
803 // except that maps shared across .o's have empty <objName>
804 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
805 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
806 (md[i].shared ? "" : objName) + "_" + mapNames[i];
807 bool reuse = false;
808 unique_fd fd;
809 int saved_errno;
810
811 if (access(mapPinLoc.c_str(), F_OK) == 0) {
812 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
813 saved_errno = errno;
814 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
815 reuse = true;
816 } else {
817 union bpf_attr req = {
818 .map_type = type,
819 .key_size = md[i].key_size,
820 .value_size = md[i].value_size,
821 .max_entries = max_entries,
Maciej Żenczykowskic1a9f4a2025-01-20 12:09:13 -0800822 .map_flags = md[i].map_flags,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700823 };
824 if (isAtLeastKernelVersion(4, 15, 0))
825 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
826 fd.reset(bpf(BPF_MAP_CREATE, req));
827 saved_errno = errno;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -0700828 if (fd.ok()) {
829 ALOGD("bpf_create_map[%s] -> %d", mapNames[i].c_str(), fd.get());
830 } else {
831 ALOGE("bpf_create_map[%s] -> %d errno:%d", mapNames[i].c_str(), fd.get(), saved_errno);
832 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700833 }
834
835 if (!fd.ok()) return -saved_errno;
836
837 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
838 // safety (since reuse code path is rare) run these checks even if we just created it.
839 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
840 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
841
842 if (!reuse) {
843 if (specified(selinux_context)) {
844 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
845 "tmp_map_" + objName + "_" + mapNames[i];
846 ret = bpfFdPin(fd, createLoc.c_str());
847 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800848 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700849 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
850 return -err;
851 }
852 ret = renameat2(AT_FDCWD, createLoc.c_str(),
853 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
854 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800855 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700856 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
857 err, strerror(err));
858 return -err;
859 }
860 } else {
861 ret = bpfFdPin(fd, mapPinLoc.c_str());
862 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800863 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700864 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
865 return -err;
866 }
867 }
868 ret = chmod(mapPinLoc.c_str(), md[i].mode);
869 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800870 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700871 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
872 strerror(err));
873 return -err;
874 }
875 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
876 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800877 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700878 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
879 ret, err, strerror(err));
880 return -err;
881 }
882 }
883
Maciej Żenczykowskia003ace2025-02-13 16:08:18 -0800884 if (isAtLeastKernelVersion(4, 14, 0)) {
885 int mapId = bpfGetFdMapId(fd);
886 if (mapId == -1) {
887 const int err = errno;
888 ALOGE("bpfGetFdMapId failed, errno: %d", err);
889 return -err;
890 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700891 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
892 }
893
894 mapFds.push_back(std::move(fd));
895 }
896
897 return ret;
898}
899
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700900static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
901 int insnIndex;
902 struct bpf_insn *insn, *insns;
903
904 insns = (struct bpf_insn*)(insnsPtr);
905
906 insnIndex = offset / sizeof(struct bpf_insn);
907 insn = &insns[insnIndex];
908
909 // Occasionally might be useful for relocation debugging, but pretty spammy
910 if (0) {
911 ALOGV("applying relo to instruction at byte offset: %llu, "
912 "insn offset %d, insn %llx",
913 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
914 }
915
916 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700917 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700918 return;
919 }
920
921 insn->imm = fd;
922 insn->src_reg = BPF_PSEUDO_MAP_FD;
923}
924
925static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
926 vector<string> mapNames;
927
928 int ret = getSectionSymNames(elfFile, "maps", mapNames);
929 if (ret) return;
930
931 for (int k = 0; k != (int)cs.size(); k++) {
932 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
933 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
934
935 for (int i = 0; i < n_rel; i++) {
936 int symIndex = ELF64_R_SYM(rel[i].r_info);
937 string symName;
938
939 ret = getSymNameByIdx(elfFile, symIndex, symName);
940 if (ret) return;
941
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000942 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700943 for (int j = 0; j < (int)mapNames.size(); j++) {
944 if (!mapNames[j].compare(symName)) {
945 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
946 break;
947 }
948 }
949 }
950 }
951}
952
953static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
954 const char* prefix, const unsigned int bpfloader_ver) {
955 unsigned kvers = kernelVersion();
956
957 if (!kvers) {
958 ALOGE("unable to get kernel version");
959 return -EINVAL;
960 }
961
962 string objName = pathToObjName(string(elfPath));
963
964 for (int i = 0; i < (int)cs.size(); i++) {
965 unique_fd& fd = cs[i].prog_fd;
966 int ret;
967 string name = cs[i].name;
968
969 if (!cs[i].prog_def.has_value()) {
970 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
971 return -EINVAL;
972 }
973
974 unsigned min_kver = cs[i].prog_def->min_kver;
975 unsigned max_kver = cs[i].prog_def->max_kver;
976 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
977 max_kver, kvers);
978 if (kvers < min_kver) continue;
979 if (kvers >= max_kver) continue;
980
981 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
982 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
983 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
984 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700985
986 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
987 bpfMinVer, bpfMaxVer);
988 if (bpfloader_ver < bpfMinVer) continue;
989 if (bpfloader_ver >= bpfMaxVer) continue;
990
991 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
992 (cs[i].prog_def->ignore_on_user && isUser()) ||
993 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
994 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
995 getBuildType().c_str());
996 continue;
997 }
998
999 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
1000 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
1001 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
1002 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
1003 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
1004 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
1005 continue;
1006 }
1007
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001008 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001009 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001010 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
1011 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1012 }
1013
1014 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001015 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001016 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
1017 lookupPinSubdir(pin_subdir));
1018 }
1019
1020 // strip any potential $foo suffix
1021 // this can be used to provide duplicate programs
1022 // conditionally loaded based on running kernel version
1023 name = name.substr(0, name.find_last_of('$'));
1024
1025 bool reuse = false;
1026 // Format of pin location is
1027 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1028 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1029 objName + '_' + string(name);
1030 if (access(progPinLoc.c_str(), F_OK) == 0) {
1031 fd.reset(retrieveProgram(progPinLoc.c_str()));
1032 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001033 !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001034 reuse = true;
1035 } else {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001036 static char log_buf[1 << 20]; // 1 MiB logging buffer
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001037
1038 union bpf_attr req = {
1039 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001040 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001041 .insns = ptr_to_u64(cs[i].data.data()),
1042 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001043 .log_level = 1,
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001044 .log_size = sizeof(log_buf),
1045 .log_buf = ptr_to_u64(log_buf),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001046 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001047 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001048 };
1049 if (isAtLeastKernelVersion(4, 15, 0))
1050 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1051 fd.reset(bpf(BPF_PROG_LOAD, req));
1052
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001053 // Kernel should have NULL terminated the log buffer, but force it anyway for safety
1054 log_buf[sizeof(log_buf) - 1] = 0;
1055
1056 // Strip out final newline if present
1057 int log_chars = strlen(log_buf);
1058 if (log_chars && log_buf[log_chars - 1] == '\n') log_buf[--log_chars] = 0;
1059
1060 bool log_oneline = !strchr(log_buf, '\n');
1061
1062 ALOGD("BPF_PROG_LOAD call for %s (%s) returned '%s' fd: %d (%s)", elfPath,
1063 cs[i].name.c_str(), log_oneline ? log_buf : "{multiline}",
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001064 fd.get(), !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001065
1066 if (!fd.ok()) {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001067 // kernel NULL terminates log_buf, so this checks for non-empty string
1068 if (log_buf[0]) {
1069 vector<string> lines = Split(log_buf, "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001070
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001071 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1072 for (const auto& line : lines) ALOGW("%s", line.c_str());
1073 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1074 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001075
1076 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001077 ALOGW("failed program %s is marked optional - continuing...",
1078 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001079 continue;
1080 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001081 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001082 }
1083 }
1084
1085 if (!fd.ok()) return fd.get();
1086
1087 if (!reuse) {
1088 if (specified(selinux_context)) {
1089 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1090 "tmp_prog_" + objName + '_' + string(name);
1091 ret = bpfFdPin(fd, createLoc.c_str());
1092 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001093 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001094 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1095 return -err;
1096 }
1097 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1098 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1099 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001100 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001101 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1102 err, strerror(err));
1103 return -err;
1104 }
1105 } else {
1106 ret = bpfFdPin(fd, progPinLoc.c_str());
1107 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001108 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001109 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1110 return -err;
1111 }
1112 }
1113 if (chmod(progPinLoc.c_str(), 0440)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001114 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001115 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1116 return -err;
1117 }
1118 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1119 (gid_t)cs[i].prog_def->gid)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001120 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001121 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1122 cs[i].prog_def->gid, err, strerror(err));
1123 return -err;
1124 }
1125 }
1126
Maciej Żenczykowski97debeb2025-02-14 11:15:36 -08001127 if (isAtLeastKernelVersion(4, 14, 0)) {
1128 int progId = bpfGetFdProgId(fd);
1129 if (progId == -1) {
1130 const int err = errno;
1131 ALOGE("bpfGetFdProgId failed, errno: %d", err);
1132 return -err;
1133 }
Maciej Żenczykowski199fd352025-02-13 15:17:08 -08001134
1135 int jitLen = bpfGetFdJitProgLen(fd);
1136 if (jitLen == -1) {
1137 const int err = errno;
1138 ALOGE("bpfGetFdJitProgLen failed, ret: %d", err);
1139 return -err;
1140 }
1141
1142 int xlatLen = bpfGetFdXlatProgLen(fd);
1143 if (xlatLen == -1) {
1144 const int err = errno;
1145 ALOGE("bpfGetFdXlatProgLen failed, ret: %d", err);
1146 return -err;
1147 }
1148 ALOGI("prog %s id %d len jit:%d xlat:%d", progPinLoc.c_str(), progId, jitLen, xlatLen);
1149
1150 if (!jitLen && bpfloader_ver >= BPFLOADER_MAINLINE_25Q2_VERSION) {
1151 ALOGE("Kernel eBPF JIT failure for %s", progPinLoc.c_str());
1152 return -ENOTSUP;
1153 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001154 }
1155 }
1156
1157 return 0;
1158}
1159
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001160int loadProg(const char* const elfPath, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001161 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001162 vector<char> license;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001163 vector<codeSection> cs;
1164 vector<unique_fd> mapFds;
1165 int ret;
1166
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001167 ifstream elfFile(elfPath, ios::in | ios::binary);
1168 if (!elfFile.is_open()) return -1;
1169
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001170 ret = readSectionByName("license", elfFile, license);
1171 if (ret) {
1172 ALOGE("Couldn't find license in %s", elfPath);
1173 return ret;
1174 } else {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001175 ALOGD("Loading ELF object %s with license %s",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001176 elfPath, (char*)license.data());
1177 }
1178
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001179 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1180 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001181
1182 // inclusive lower bound check
1183 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001184 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001185 bpfloader_ver, elfPath, bpfLoaderMinVer);
1186 return 0;
1187 }
1188
1189 // exclusive upper bound check
1190 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001191 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001192 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1193 return 0;
1194 }
1195
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001196 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001197 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1198
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001199 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001200 if (ret) {
1201 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1202 return ret;
1203 }
1204
1205 for (int i = 0; i < (int)mapFds.size(); i++)
1206 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1207
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001208 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001209 // BPF .o's with no programs are only supported by mainline netbpfload,
1210 // make sure .o's targeting non-mainline (ie. S) bpfloader don't show up.
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001211 if (ret == -ENOENT && bpfLoaderMinVer >= BPFLOADER_MAINLINE_S_VERSION)
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001212 return 0;
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001213 if (ret) {
1214 ALOGE("Couldn't read all code sections in %s", elfPath);
1215 return ret;
1216 }
1217
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001218 applyMapRelo(elfFile, mapFds, cs);
1219
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001220 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001221 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1222
1223 return ret;
1224}
1225
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001226static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001227 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001228 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001229 if (errno == ENOENT) return false;
1230 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1231 abort(); // can only hit this if permissions (likely selinux) are screwed up
1232}
1233
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001234#define APEXROOT "/apex/com.android.tethering"
1235#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001236
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001237const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001238 // S+ Tethering mainline module (network_stack): tether offload
1239 {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001240 .dir = BPFROOT "/tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001241 .prefix = "tethering/",
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001242 .t_plus = false,
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001243 },
1244 // T+ Tethering mainline module (shared with netd & system server)
1245 // netutils_wrapper (for iptables xt_bpf) has access to programs
1246 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001247 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001248 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001249 },
1250 // T+ Tethering mainline module (shared with netd & system server)
1251 // netutils_wrapper has no access, netd has read only access
1252 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001253 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001254 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001255 },
1256 // T+ Tethering mainline module (shared with system server)
1257 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001258 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001259 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001260 },
1261 // T+ Tethering mainline module (not shared, just network_stack)
1262 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001263 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001264 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001265 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001266};
1267
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001268static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001269 int retVal = 0;
1270 DIR* dir;
1271 struct dirent* ent;
1272
1273 if ((dir = opendir(location.dir)) != NULL) {
1274 while ((ent = readdir(dir)) != NULL) {
1275 string s = ent->d_name;
1276 if (!EndsWith(s, ".o")) continue;
1277
1278 string progPath(location.dir);
1279 progPath += s;
1280
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001281 int ret = loadProg(progPath.c_str(), bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001282 if (ret) {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001283 retVal = ret;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001284 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1285 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001286 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001287 }
1288 }
1289 closedir(dir);
1290 }
1291 return retVal;
1292}
1293
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001294static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001295 if (*prefix) {
1296 mode_t prevUmask = umask(0);
1297
1298 string s = "/sys/fs/bpf/";
1299 s += prefix;
1300
1301 errno = 0;
1302 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1303 if (ret && errno != EEXIST) {
1304 const int err = errno;
1305 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1306 return -err;
1307 }
1308
1309 umask(prevUmask);
1310 }
1311 return 0;
1312}
1313
1314// Technically 'value' doesn't need to be newline terminated, but it's best
1315// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1316// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001317static int writeProcSysFile(const char *filename, const char *value) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001318 unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001319 if (fd < 0) {
1320 const int err = errno;
1321 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1322 return -err;
1323 }
1324 int len = strlen(value);
1325 int v = write(fd, value, len);
1326 if (v < 0) {
1327 const int err = errno;
1328 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1329 return -err;
1330 }
1331 if (v != len) {
1332 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1333 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1334 return -EINVAL;
1335 }
1336 return 0;
1337}
1338
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001339#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001340const char * const platformBpfLoader = "/system/bin/bpfloader";
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001341const char *const uprobestatsBpfLoader =
1342 "/apex/com.android.uprobestats/bin/uprobestatsbpfload";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001343
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001344static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001345 char * found_blockdev = NULL;
1346 FILE * f = NULL;
1347 char buf[4096];
1348
1349 f = fopen("/proc/mounts", "re");
1350 if (!f) return 1;
1351
1352 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1353 while (fgets(buf, sizeof(buf), f)) {
1354 char * blockdev = buf;
1355 char * space = strchr(blockdev, ' ');
1356 if (!space) continue;
1357 *space = '\0';
1358 char * mntpath = space + 1;
1359 space = strchr(mntpath, ' ');
1360 if (!space) continue;
1361 *space = '\0';
1362 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1363 found_blockdev = strdup(blockdev);
1364 break;
1365 }
1366 fclose(f);
1367 f = NULL;
1368
1369 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001370 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001371
1372 f = fopen("/proc/mounts", "re");
1373 if (!f) { free(found_blockdev); return 3; }
1374
1375 while (fgets(buf, sizeof(buf), f)) {
1376 char * blockdev = buf;
1377 char * space = strchr(blockdev, ' ');
1378 if (!space) continue;
1379 *space = '\0';
1380 char * mntpath = space + 1;
1381 space = strchr(mntpath, ' ');
1382 if (!space) continue;
1383 *space = '\0';
1384 if (strcmp(blockdev, found_blockdev)) continue;
1385 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1386 char * at = strchr(mntpath, '@');
1387 if (!at) continue;
1388 char * ver = at + 1;
1389 ALOGI("Tethering APEX version %s", ver);
1390 }
1391 fclose(f);
1392 free(found_blockdev);
1393 return 0;
1394}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001395
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001396static bool hasGSM() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001397 static string ph = GetProperty("gsm.current.phone-type", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001398 static bool gsm = (ph != "");
1399 static bool logged = false;
1400 if (!logged) {
1401 logged = true;
1402 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1403 }
1404 return gsm;
1405}
1406
1407static bool isTV() {
1408 if (hasGSM()) return false; // TVs don't do GSM
1409
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001410 static string key = GetProperty("ro.oem.key1", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001411 static bool tv = StartsWith(key, "ATV00");
1412 static bool logged = false;
1413 if (!logged) {
1414 logged = true;
1415 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1416 }
1417 return tv;
1418}
1419
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001420static bool isWear() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001421 static string wearSdkStr = GetProperty("ro.cw_build.wear_sdk.version", "");
1422 static int wearSdkInt = GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1423 static string buildChars = GetProperty("ro.build.characteristics", "");
1424 static vector<string> v = Tokenize(buildChars, ",");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001425 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1426 static bool wear = (wearSdkInt > 0) || watch;
1427 static bool logged = false;
1428 if (!logged) {
1429 logged = true;
1430 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1431 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1432 }
1433 return wear;
1434}
1435
Motomu Utsumi712088d2025-03-18 14:52:02 +09001436static int libbpfPrint(enum libbpf_print_level lvl, const char *const formatStr,
1437 va_list argList) {
1438 int32_t prio;
1439 switch (lvl) {
1440 case LIBBPF_WARN:
1441 prio = ANDROID_LOG_WARN;
1442 break;
1443 case LIBBPF_INFO:
1444 prio = ANDROID_LOG_INFO;
1445 break;
1446 case LIBBPF_DEBUG:
1447 prio = ANDROID_LOG_DEBUG;
1448 break;
1449 }
1450 char *s = strdup(formatStr ?: "(no format string)");
1451 int len = strlen(s);
1452 if (len && s[len - 1] == '\n')
1453 s[len - 1] = 0;
1454 LOG_PRI_VA(prio, LOG_TAG, s, argList);
1455 free(s);
1456 return 0;
1457}
1458
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001459static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001460 if (!isAtLeastS) {
1461 ALOGE("Impossible - not reachable on Android <S.");
1462 // for safety, we don't fail, this is a just-in-case workaround
1463 // for any possible busted 'optimized' start everything vendor init hacks on R
1464 return 0;
1465 }
Motomu Utsumi712088d2025-03-18 14:52:02 +09001466 libbpf_set_print(libbpfPrint);
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001467
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001468 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001469
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001470 const int first_api_level = GetIntProperty("ro.board.first_api_level", api_level);
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001471
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001472 // last in U QPR2 beta1
1473 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1474 // first in U QPR2 beta~2
1475 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1476
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001477 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001478 unsigned int bpfloader_ver = BPFLOADER_MAINLINE_S_VERSION; // [42u]
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001479 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1480 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1481 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1482 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001483 if (isAtLeast25Q2) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_25Q2_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001484
Motomu Utsumia7693582025-02-05 17:40:08 +09001485 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) libbpf: v%u.%u "
1486 "uid:%d rc:%d%d",
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001487 bpfloader_ver, argv[0], android_get_device_api_level(), api_level,
Motomu Utsumia7693582025-02-05 17:40:08 +09001488 kernelVersion(), describeArch(), libbpf_major_version(),
1489 libbpf_minor_version(), getuid(), has_platform_bpfloader_rc,
1490 has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001491
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001492 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1493 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1494 return 1;
1495 }
1496
1497 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1498 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1499 return 1;
1500 }
1501
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001502 logTetheringApexVersion();
1503
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001504 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001505 if (!isAtLeastKernelVersion(4, 9, 0)) {
1506 ALOGE("Android S & T require kernel 4.9.");
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001507 return 1;
1508 }
1509
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001510 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001511 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001512 ALOGE("Android U requires kernel 4.14.");
1513 return 1;
1514 }
1515
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001516 // V bumps the kernel requirement up to 4.19
1517 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001518 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001519 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001520 return 1;
1521 }
1522
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001523 // 25Q2 bumps the kernel requirement up to 5.4
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001524 // see also: //system/netd/tests/kernel_test.cpp TestKernel54
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001525 if (isAtLeast25Q2 && !isAtLeastKernelVersion(5, 4, 0)) {
1526 ALOGE("Android 25Q2 requires kernel 5.4.");
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001527 return 1;
1528 }
1529
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001530 // Technically already required by U, but only enforce on V+
1531 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1532 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1533 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1534 if (!isTV()) return 1;
1535 }
1536
Maciej Żenczykowski127715a2025-02-10 21:52:01 -08001537 if (isKernel32Bit() && isAtLeast25Q2) {
1538 ALOGE("Android 25Q2 requires 64 bit kernel.");
1539 return 1;
1540 }
1541
Maciej Żenczykowski9b6a9942024-09-03 16:08:35 -07001542 // 6.6 is highest version supported by Android V, so this is effectively W+ (sdk=36+)
1543 if (isKernel32Bit() && isAtLeastKernelVersion(6, 7, 0)) {
1544 ALOGE("Android platform with 32 bit kernel version >= 6.7.0 is unsupported");
1545 return 1;
1546 }
1547
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001548 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1549 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001550 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001551 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001552 }
1553
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001554 if (isAtLeastV) {
1555 bool bad = false;
1556
1557 if (!isLtsKernel()) {
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001558 ALOGW("Android V+ only supports LTS kernels.");
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001559 bad = true;
1560 }
1561
1562#define REQUIRE(maj, min, sub) \
1563 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001564 ALOGW("Android V+ requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001565 bad = true; \
1566 }
1567
1568 REQUIRE(4, 19, 236)
1569 REQUIRE(5, 4, 186)
1570 REQUIRE(5, 10, 199)
1571 REQUIRE(5, 15, 136)
1572 REQUIRE(6, 1, 57)
1573 REQUIRE(6, 6, 0)
Maciej Żenczykowski06f38e32024-12-11 07:12:59 -08001574 REQUIRE(6, 12, 0)
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001575
1576#undef REQUIRE
1577
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001578 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001579 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1580 }
1581 }
1582
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001583 /* Android 14/U should only launch on 64-bit kernels
1584 * T launches on 5.10/5.15
1585 * U launches on 5.15/6.1
1586 * So >=5.16 implies isKernel64Bit()
1587 *
1588 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1589 *
1590 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1591 * we also require 64-bit userspace.
1592 *
1593 * There are various known issues with 32-bit userspace talking to various
1594 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1595 * Some of these have userspace or kernel workarounds/hacks.
1596 * Some of them don't...
1597 * We're going to be removing the hacks.
1598 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1599 * Note: this check/enforcement only applies to *system* userspace code,
1600 * it does not affect unprivileged apps, the 32-on-64 compatibility
1601 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1602 *
1603 * Additionally the 32-bit kernel jit support is poor,
1604 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001605 * Note, however, that TV and Wear devices will continue to support 32-bit userspace
1606 * on ARM64.
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001607 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001608 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001609 // Stuff won't work reliably, but...
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001610 if (isArm() && (isTV() || isWear())) {
1611 // exempt Arm TV or Wear devices (arm32 ABI is far less problematic than x86-32)
1612 ALOGW("[Arm TV/Wear] 32-bit userspace unsupported on 6.2+ kernels.");
Maciej Żenczykowski73238632025-02-24 14:50:09 -08001613 } else if (first_api_level <= 33 /*T*/ && isArm()) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001614 // also exempt Arm devices upgrading with major kernel rev from T-
1615 // might possibly be better for them to run with a newer kernel...
1616 ALOGW("[Arm KernelUpRev] 32-bit userspace unsupported on 6.2+ kernels.");
1617 } else if (isArm()) {
1618 ALOGE("[Arm] 64-bit userspace required on 6.2+ kernels (%d).", first_api_level);
1619 return 1;
1620 } else { // x86 since RiscV cannot be 32-bit
1621 ALOGE("[x86] 64-bit userspace required on 6.2+ kernels.");
1622 return 1;
1623 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001624 }
1625
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001626 // On handheld, 6.6 is highest version supported by Android V (sdk=35), so this is for sdk=36+
1627 if (!isArm() && isUserspace32bit() && isAtLeastKernelVersion(6, 7, 0)) {
Maciej Żenczykowski21b4a052024-09-03 15:46:48 -07001628 ALOGE("64-bit userspace required on 6.7+ kernels.");
1629 return 1;
1630 }
1631
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001632 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001633 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001634 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001635 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001636 return 1;
1637 }
1638
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001639 if (runningAsRoot) {
1640 // Note: writing this proc file requires being root (always the case on V+)
1641
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001642 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1643 // but we need 0 (enabled)
1644 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1645 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1646 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001647 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001648 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001649
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001650 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001651 // Note: writing these proc files requires CAP_NET_ADMIN
1652 // and sepolicy which is only present on U+,
1653 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1654 // trigger (ie. by init itself) instead.
1655
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001656 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1657 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1658 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1659 // kernel does not have CONFIG_BPF_JIT=y)
1660 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1661 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1662 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001663
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001664 // Enable JIT kallsyms export for privileged users only
1665 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1666 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1667 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1668 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001669
1670 // Create all the pin subdirectories
1671 // (this must be done first to allow selinux_context and pin_subdir functionality,
1672 // which could otherwise fail with ENOENT during object pinning or renaming,
1673 // due to ordering issues)
1674 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001675 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001676 if (createSysFsBpfSubDir(location.prefix)) return 1;
1677 }
1678
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001679 if (isAtLeastT) {
1680 // Note: there's no actual src dir for fs_bpf_loader .o's,
1681 // so it is not listed in 'locations[].prefix'.
1682 // This is because this is primarily meant for triggering genfscon rules,
1683 // and as such this will likely always be the case.
1684 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1685 if (createSysFsBpfSubDir("loader")) return 1;
1686 }
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001687
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001688 // Load all ELF objects, create programs and maps, and pin them
1689 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001690 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001691 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001692 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1693 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1694 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1695 "problems or startup script race.");
1696 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1697 sleep(20);
1698 return 2;
1699 }
1700 }
1701
1702 int key = 1;
1703 int value = 123;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001704 unique_fd map(
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001705 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1706 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001707 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1708 return 1;
1709 }
1710
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001711 // on S we haven't created this subdir yet, but we need it for 'mainline_done' flag below
1712 if (!isAtLeastT && createSysFsBpfSubDir("netd_shared")) return 1;
1713
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001714 // leave a flag that we're done
1715 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001716
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001717 // platform bpfloader will only succeed when run as root
1718 if (!runningAsRoot) {
1719 // unreachable on U QPR3+ which always runs netbpfload as root
1720
1721 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1722 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001723 }
1724
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001725 // unreachable before U QPR3
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001726 if (exists(uprobestatsBpfLoader)) {
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001727 ALOGI("done, transferring control to uprobestatsbpfload.");
1728 const char *args[] = {
1729 uprobestatsBpfLoader,
1730 NULL,
1731 };
1732 execve(args[0], (char **)args, envp);
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001733 ALOGI("unable to execute uprobestatsbpfload, transferring control to "
1734 "platform bpfloader.");
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001735 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001736
1737 // platform BpfLoader *needs* to run as root
1738 const char * args[] = { platformBpfLoader, NULL, };
1739 execve(args[0], (char**)args, envp);
1740 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1741 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001742}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001743
1744} // namespace bpf
1745} // namespace android
1746
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001747int main(int argc, char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001748 if (android::bpf::isAtLeastT) {
1749 InitLogging(argv, &KernelLogger);
1750 } else {
1751 // S lacks the sepolicy to make non-root uid KernelLogger viable
1752 InitLogging(argv);
1753 }
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001754
1755 if (argc == 2 && !strcmp(argv[1], "done")) {
1756 // we're being re-exec'ed from platform bpfloader to 'finalize' things
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001757 if (!SetProperty("bpf.progs_loaded", "1")) {
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001758 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1759 return 125;
1760 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001761 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001762 return 0;
1763 }
1764
1765 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001766}