blob: 2d0e4c682f3118b84242317b2b21b6bccc1676c7 [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
Motomu Utsumiefe33312025-03-18 15:08:15 +0900671static int getSymOffsetByName(ifstream &elfFile, const char *name, int *off) {
672 vector<Elf64_Sym> symtab;
673 int ret = readSymTab(elfFile, 1 /* sort */, symtab);
674 if (ret) return ret;
675 for (int i = 0; i < (int)symtab.size(); i++) {
676 string s;
677 ret = getSymName(elfFile, symtab[i].st_name, s);
678 if (ret) continue;
679 if (!strcmp(s.c_str(), name)) {
680 *off = symtab[i].st_value;
681 return 0;
682 }
683 }
684 return -1;
685}
686
687static int setBtfVarOffset(ifstream &elfFile, struct btf *btf,
688 struct btf_type *datasecBt) {
689 int i, vars = btf_vlen(datasecBt);
690 struct btf_var_secinfo *vsi;
691 const char *datasecName = btf__name_by_offset(btf, datasecBt->name_off);
692 if (!datasecName) {
693 ALOGE("Couldn't resolve section name, errno: %d", errno);
694 return -errno;
695 }
696
697 for (i = 0, vsi = btf_var_secinfos(datasecBt); i < vars; i++, vsi++) {
698 const struct btf_type *varBt = btf__type_by_id(btf, vsi->type);
699 if (!varBt || !btf_is_var(varBt)) {
700 ALOGE("Found non VAR kind btf_type, section: %s id: %d", datasecName,
701 vsi->type);
702 return -1;
703 }
704
705 const struct btf_var *var = btf_var(varBt);
706 if (var->linkage == BTF_VAR_STATIC) continue;
707
708 const char *varName = btf__name_by_offset(btf, varBt->name_off);
709 if (!varName) {
710 ALOGE("Failed to resolve var name, section: %s", datasecName);
711 return -1;
712 }
713
714 int off;
715 int ret = getSymOffsetByName(elfFile, varName, &off);
716 if (ret) {
717 ALOGE("No offset found in symbol table, section: %s, var: %s, ret: %d",
718 datasecName, varName, ret);
719 return ret;
720 }
721 vsi->offset = off;
722 }
723 return 0;
724}
725
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700726static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700727 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700728 int ret;
729 vector<char> mdData;
730 vector<struct bpf_map_def> md;
731 vector<string> mapNames;
732 string objName = pathToObjName(string(elfPath));
733
734 ret = readSectionByName("maps", elfFile, mdData);
735 if (ret == -2) return 0; // no maps to read
736 if (ret) return ret;
737
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700738 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700739 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700740 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700741 return -1;
742 };
743
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700744 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700745
746 const char* dataPtr = mdData.data();
747 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700748 // Copy the structure from the ELF file and move to the next one.
749 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
750 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700751 }
752
753 ret = getSectionSymNames(elfFile, "maps", mapNames);
754 if (ret) return ret;
755
756 unsigned kvers = kernelVersion();
757
758 for (int i = 0; i < (int)mapNames.size(); i++) {
759 if (md[i].zero != 0) abort();
760
761 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000762 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700763 md[i].bpfloader_min_ver);
764 mapFds.push_back(unique_fd());
765 continue;
766 }
767
768 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000769 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700770 md[i].bpfloader_max_ver);
771 mapFds.push_back(unique_fd());
772 continue;
773 }
774
775 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000776 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700777 mapNames[i].c_str(), kvers, md[i].min_kver);
778 mapFds.push_back(unique_fd());
779 continue;
780 }
781
782 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000783 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700784 mapNames[i].c_str(), kvers, md[i].max_kver);
785 mapFds.push_back(unique_fd());
786 continue;
787 }
788
789 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
790 (md[i].ignore_on_userdebug && isUserdebug())) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000791 ALOGD("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700792 getBuildType().c_str());
793 mapFds.push_back(unique_fd());
794 continue;
795 }
796
797 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
798 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
799 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
800 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
801 (isRiscV() && md[i].ignore_on_riscv64)) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000802 ALOGD("skipping map %s which is ignored on %s", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700803 describeArch());
804 mapFds.push_back(unique_fd());
805 continue;
806 }
807
808 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski87019832025-02-03 22:04:26 -0800809 if (type == BPF_MAP_TYPE_LPM_TRIE && !isAtLeastKernelVersion(4, 14, 0)) {
810 // On Linux Kernels older than 4.14 this map type doesn't exist - autoskip.
811 ALOGD("skipping LPM_TRIE map %s - requires kver 4.14+", mapNames[i].c_str());
812 mapFds.push_back(unique_fd());
813 continue;
814 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700815 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
816 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
817 // of be approximated: ARRAY has the same userspace api, though it is not usable
818 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
819 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
820 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
821 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
822 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
823 type = BPF_MAP_TYPE_ARRAY;
824 }
825 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
826 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
827 // of be approximated: HASH has the same userspace visible api.
828 // However it cannot be used by ebpf programs in the same way.
829 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
830 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
831 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
832 // programs as being 5.4+...
833 type = BPF_MAP_TYPE_HASH;
834 }
835
836 // The .h file enforces that this is a power of two, and page size will
837 // also always be a power of two, so this logic is actually enough to
838 // force it to be a multiple of the page size, as required by the kernel.
839 unsigned int max_entries = md[i].max_entries;
840 if (type == BPF_MAP_TYPE_RINGBUF) {
841 if (max_entries < page_size) max_entries = page_size;
842 }
843
844 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
845 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000846 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700847 md[i].selinux_context, static_cast<int>(selinux_context),
848 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
849 }
850
851 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700852 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000853 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700854 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
855 }
856
857 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
858 // except that maps shared across .o's have empty <objName>
859 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
860 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
861 (md[i].shared ? "" : objName) + "_" + mapNames[i];
862 bool reuse = false;
863 unique_fd fd;
864 int saved_errno;
865
866 if (access(mapPinLoc.c_str(), F_OK) == 0) {
867 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
868 saved_errno = errno;
869 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
870 reuse = true;
871 } else {
872 union bpf_attr req = {
873 .map_type = type,
874 .key_size = md[i].key_size,
875 .value_size = md[i].value_size,
876 .max_entries = max_entries,
Maciej Żenczykowskic1a9f4a2025-01-20 12:09:13 -0800877 .map_flags = md[i].map_flags,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700878 };
879 if (isAtLeastKernelVersion(4, 15, 0))
880 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
881 fd.reset(bpf(BPF_MAP_CREATE, req));
882 saved_errno = errno;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -0700883 if (fd.ok()) {
884 ALOGD("bpf_create_map[%s] -> %d", mapNames[i].c_str(), fd.get());
885 } else {
886 ALOGE("bpf_create_map[%s] -> %d errno:%d", mapNames[i].c_str(), fd.get(), saved_errno);
887 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700888 }
889
890 if (!fd.ok()) return -saved_errno;
891
892 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
893 // safety (since reuse code path is rare) run these checks even if we just created it.
894 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
895 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
896
897 if (!reuse) {
898 if (specified(selinux_context)) {
899 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
900 "tmp_map_" + objName + "_" + mapNames[i];
901 ret = bpfFdPin(fd, createLoc.c_str());
902 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800903 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700904 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
905 return -err;
906 }
907 ret = renameat2(AT_FDCWD, createLoc.c_str(),
908 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
909 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800910 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700911 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
912 err, strerror(err));
913 return -err;
914 }
915 } else {
916 ret = bpfFdPin(fd, mapPinLoc.c_str());
917 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800918 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700919 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
920 return -err;
921 }
922 }
923 ret = chmod(mapPinLoc.c_str(), md[i].mode);
924 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800925 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700926 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
927 strerror(err));
928 return -err;
929 }
930 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
931 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800932 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700933 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
934 ret, err, strerror(err));
935 return -err;
936 }
937 }
938
Maciej Żenczykowskia003ace2025-02-13 16:08:18 -0800939 if (isAtLeastKernelVersion(4, 14, 0)) {
940 int mapId = bpfGetFdMapId(fd);
941 if (mapId == -1) {
942 const int err = errno;
943 ALOGE("bpfGetFdMapId failed, errno: %d", err);
944 return -err;
945 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700946 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
947 }
948
949 mapFds.push_back(std::move(fd));
950 }
951
952 return ret;
953}
954
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700955static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
956 int insnIndex;
957 struct bpf_insn *insn, *insns;
958
959 insns = (struct bpf_insn*)(insnsPtr);
960
961 insnIndex = offset / sizeof(struct bpf_insn);
962 insn = &insns[insnIndex];
963
964 // Occasionally might be useful for relocation debugging, but pretty spammy
965 if (0) {
966 ALOGV("applying relo to instruction at byte offset: %llu, "
967 "insn offset %d, insn %llx",
968 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
969 }
970
971 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700972 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700973 return;
974 }
975
976 insn->imm = fd;
977 insn->src_reg = BPF_PSEUDO_MAP_FD;
978}
979
980static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
981 vector<string> mapNames;
982
983 int ret = getSectionSymNames(elfFile, "maps", mapNames);
984 if (ret) return;
985
986 for (int k = 0; k != (int)cs.size(); k++) {
987 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
988 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
989
990 for (int i = 0; i < n_rel; i++) {
991 int symIndex = ELF64_R_SYM(rel[i].r_info);
992 string symName;
993
994 ret = getSymNameByIdx(elfFile, symIndex, symName);
995 if (ret) return;
996
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000997 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700998 for (int j = 0; j < (int)mapNames.size(); j++) {
999 if (!mapNames[j].compare(symName)) {
1000 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
1001 break;
1002 }
1003 }
1004 }
1005 }
1006}
1007
1008static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
1009 const char* prefix, const unsigned int bpfloader_ver) {
1010 unsigned kvers = kernelVersion();
1011
1012 if (!kvers) {
1013 ALOGE("unable to get kernel version");
1014 return -EINVAL;
1015 }
1016
1017 string objName = pathToObjName(string(elfPath));
1018
1019 for (int i = 0; i < (int)cs.size(); i++) {
1020 unique_fd& fd = cs[i].prog_fd;
1021 int ret;
1022 string name = cs[i].name;
1023
1024 if (!cs[i].prog_def.has_value()) {
1025 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
1026 return -EINVAL;
1027 }
1028
1029 unsigned min_kver = cs[i].prog_def->min_kver;
1030 unsigned max_kver = cs[i].prog_def->max_kver;
1031 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1032 max_kver, kvers);
1033 if (kvers < min_kver) continue;
1034 if (kvers >= max_kver) continue;
1035
1036 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1037 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1038 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1039 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001040
1041 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
1042 bpfMinVer, bpfMaxVer);
1043 if (bpfloader_ver < bpfMinVer) continue;
1044 if (bpfloader_ver >= bpfMaxVer) continue;
1045
1046 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1047 (cs[i].prog_def->ignore_on_user && isUser()) ||
1048 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1049 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1050 getBuildType().c_str());
1051 continue;
1052 }
1053
1054 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
1055 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
1056 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
1057 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
1058 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
1059 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
1060 continue;
1061 }
1062
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001063 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001064 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001065 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
1066 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1067 }
1068
1069 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001070 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001071 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
1072 lookupPinSubdir(pin_subdir));
1073 }
1074
1075 // strip any potential $foo suffix
1076 // this can be used to provide duplicate programs
1077 // conditionally loaded based on running kernel version
1078 name = name.substr(0, name.find_last_of('$'));
1079
1080 bool reuse = false;
1081 // Format of pin location is
1082 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1083 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1084 objName + '_' + string(name);
1085 if (access(progPinLoc.c_str(), F_OK) == 0) {
1086 fd.reset(retrieveProgram(progPinLoc.c_str()));
1087 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001088 !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001089 reuse = true;
1090 } else {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001091 static char log_buf[1 << 20]; // 1 MiB logging buffer
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001092
1093 union bpf_attr req = {
1094 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001095 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001096 .insns = ptr_to_u64(cs[i].data.data()),
1097 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001098 .log_level = 1,
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001099 .log_size = sizeof(log_buf),
1100 .log_buf = ptr_to_u64(log_buf),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001101 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001102 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001103 };
1104 if (isAtLeastKernelVersion(4, 15, 0))
1105 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1106 fd.reset(bpf(BPF_PROG_LOAD, req));
1107
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001108 // Kernel should have NULL terminated the log buffer, but force it anyway for safety
1109 log_buf[sizeof(log_buf) - 1] = 0;
1110
1111 // Strip out final newline if present
1112 int log_chars = strlen(log_buf);
1113 if (log_chars && log_buf[log_chars - 1] == '\n') log_buf[--log_chars] = 0;
1114
1115 bool log_oneline = !strchr(log_buf, '\n');
1116
1117 ALOGD("BPF_PROG_LOAD call for %s (%s) returned '%s' fd: %d (%s)", elfPath,
1118 cs[i].name.c_str(), log_oneline ? log_buf : "{multiline}",
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001119 fd.get(), !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001120
1121 if (!fd.ok()) {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001122 // kernel NULL terminates log_buf, so this checks for non-empty string
1123 if (log_buf[0]) {
1124 vector<string> lines = Split(log_buf, "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001125
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001126 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1127 for (const auto& line : lines) ALOGW("%s", line.c_str());
1128 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1129 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001130
1131 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001132 ALOGW("failed program %s is marked optional - continuing...",
1133 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001134 continue;
1135 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001136 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001137 }
1138 }
1139
1140 if (!fd.ok()) return fd.get();
1141
1142 if (!reuse) {
1143 if (specified(selinux_context)) {
1144 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1145 "tmp_prog_" + objName + '_' + string(name);
1146 ret = bpfFdPin(fd, createLoc.c_str());
1147 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001148 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001149 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1150 return -err;
1151 }
1152 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1153 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1154 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001155 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001156 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1157 err, strerror(err));
1158 return -err;
1159 }
1160 } else {
1161 ret = bpfFdPin(fd, progPinLoc.c_str());
1162 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001163 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001164 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1165 return -err;
1166 }
1167 }
1168 if (chmod(progPinLoc.c_str(), 0440)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001169 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001170 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1171 return -err;
1172 }
1173 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1174 (gid_t)cs[i].prog_def->gid)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001175 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001176 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1177 cs[i].prog_def->gid, err, strerror(err));
1178 return -err;
1179 }
1180 }
1181
Maciej Żenczykowski97debeb2025-02-14 11:15:36 -08001182 if (isAtLeastKernelVersion(4, 14, 0)) {
1183 int progId = bpfGetFdProgId(fd);
1184 if (progId == -1) {
1185 const int err = errno;
1186 ALOGE("bpfGetFdProgId failed, errno: %d", err);
1187 return -err;
1188 }
Maciej Żenczykowski199fd352025-02-13 15:17:08 -08001189
1190 int jitLen = bpfGetFdJitProgLen(fd);
1191 if (jitLen == -1) {
1192 const int err = errno;
1193 ALOGE("bpfGetFdJitProgLen failed, ret: %d", err);
1194 return -err;
1195 }
1196
1197 int xlatLen = bpfGetFdXlatProgLen(fd);
1198 if (xlatLen == -1) {
1199 const int err = errno;
1200 ALOGE("bpfGetFdXlatProgLen failed, ret: %d", err);
1201 return -err;
1202 }
1203 ALOGI("prog %s id %d len jit:%d xlat:%d", progPinLoc.c_str(), progId, jitLen, xlatLen);
1204
1205 if (!jitLen && bpfloader_ver >= BPFLOADER_MAINLINE_25Q2_VERSION) {
1206 ALOGE("Kernel eBPF JIT failure for %s", progPinLoc.c_str());
1207 return -ENOTSUP;
1208 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001209 }
1210 }
1211
1212 return 0;
1213}
1214
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001215int loadProg(const char* const elfPath, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001216 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001217 vector<char> license;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001218 vector<codeSection> cs;
1219 vector<unique_fd> mapFds;
1220 int ret;
1221
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001222 ifstream elfFile(elfPath, ios::in | ios::binary);
1223 if (!elfFile.is_open()) return -1;
1224
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001225 ret = readSectionByName("license", elfFile, license);
1226 if (ret) {
1227 ALOGE("Couldn't find license in %s", elfPath);
1228 return ret;
1229 } else {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001230 ALOGD("Loading ELF object %s with license %s",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001231 elfPath, (char*)license.data());
1232 }
1233
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001234 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1235 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001236
1237 // inclusive lower bound check
1238 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001239 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001240 bpfloader_ver, elfPath, bpfLoaderMinVer);
1241 return 0;
1242 }
1243
1244 // exclusive upper bound check
1245 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001246 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001247 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1248 return 0;
1249 }
1250
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001251 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001252 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1253
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001254 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001255 if (ret) {
1256 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1257 return ret;
1258 }
1259
1260 for (int i = 0; i < (int)mapFds.size(); i++)
1261 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1262
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001263 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001264 // BPF .o's with no programs are only supported by mainline netbpfload,
1265 // make sure .o's targeting non-mainline (ie. S) bpfloader don't show up.
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001266 if (ret == -ENOENT && bpfLoaderMinVer >= BPFLOADER_MAINLINE_S_VERSION)
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001267 return 0;
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001268 if (ret) {
1269 ALOGE("Couldn't read all code sections in %s", elfPath);
1270 return ret;
1271 }
1272
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001273 applyMapRelo(elfFile, mapFds, cs);
1274
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001275 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001276 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1277
1278 return ret;
1279}
1280
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001281static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001282 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001283 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001284 if (errno == ENOENT) return false;
1285 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1286 abort(); // can only hit this if permissions (likely selinux) are screwed up
1287}
1288
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001289#define APEXROOT "/apex/com.android.tethering"
1290#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001291
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001292const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001293 // S+ Tethering mainline module (network_stack): tether offload
1294 {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001295 .dir = BPFROOT "/tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001296 .prefix = "tethering/",
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001297 .t_plus = false,
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001298 },
1299 // T+ Tethering mainline module (shared with netd & system server)
1300 // netutils_wrapper (for iptables xt_bpf) has access to programs
1301 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001302 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001303 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001304 },
1305 // T+ Tethering mainline module (shared with netd & system server)
1306 // netutils_wrapper has no access, netd has read only access
1307 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001308 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001309 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001310 },
1311 // T+ Tethering mainline module (shared with system server)
1312 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001313 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001314 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001315 },
1316 // T+ Tethering mainline module (not shared, just network_stack)
1317 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001318 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001319 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001320 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001321};
1322
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001323static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001324 int retVal = 0;
1325 DIR* dir;
1326 struct dirent* ent;
1327
1328 if ((dir = opendir(location.dir)) != NULL) {
1329 while ((ent = readdir(dir)) != NULL) {
1330 string s = ent->d_name;
1331 if (!EndsWith(s, ".o")) continue;
1332
1333 string progPath(location.dir);
1334 progPath += s;
1335
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001336 int ret = loadProg(progPath.c_str(), bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001337 if (ret) {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001338 retVal = ret;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001339 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1340 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001341 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001342 }
1343 }
1344 closedir(dir);
1345 }
1346 return retVal;
1347}
1348
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001349static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001350 if (*prefix) {
1351 mode_t prevUmask = umask(0);
1352
1353 string s = "/sys/fs/bpf/";
1354 s += prefix;
1355
1356 errno = 0;
1357 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1358 if (ret && errno != EEXIST) {
1359 const int err = errno;
1360 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1361 return -err;
1362 }
1363
1364 umask(prevUmask);
1365 }
1366 return 0;
1367}
1368
1369// Technically 'value' doesn't need to be newline terminated, but it's best
1370// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1371// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001372static int writeProcSysFile(const char *filename, const char *value) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001373 unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001374 if (fd < 0) {
1375 const int err = errno;
1376 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1377 return -err;
1378 }
1379 int len = strlen(value);
1380 int v = write(fd, value, len);
1381 if (v < 0) {
1382 const int err = errno;
1383 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1384 return -err;
1385 }
1386 if (v != len) {
1387 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1388 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1389 return -EINVAL;
1390 }
1391 return 0;
1392}
1393
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001394#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001395const char * const platformBpfLoader = "/system/bin/bpfloader";
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001396const char *const uprobestatsBpfLoader =
1397 "/apex/com.android.uprobestats/bin/uprobestatsbpfload";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001398
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001399static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001400 char * found_blockdev = NULL;
1401 FILE * f = NULL;
1402 char buf[4096];
1403
1404 f = fopen("/proc/mounts", "re");
1405 if (!f) return 1;
1406
1407 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1408 while (fgets(buf, sizeof(buf), f)) {
1409 char * blockdev = buf;
1410 char * space = strchr(blockdev, ' ');
1411 if (!space) continue;
1412 *space = '\0';
1413 char * mntpath = space + 1;
1414 space = strchr(mntpath, ' ');
1415 if (!space) continue;
1416 *space = '\0';
1417 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1418 found_blockdev = strdup(blockdev);
1419 break;
1420 }
1421 fclose(f);
1422 f = NULL;
1423
1424 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001425 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001426
1427 f = fopen("/proc/mounts", "re");
1428 if (!f) { free(found_blockdev); return 3; }
1429
1430 while (fgets(buf, sizeof(buf), f)) {
1431 char * blockdev = buf;
1432 char * space = strchr(blockdev, ' ');
1433 if (!space) continue;
1434 *space = '\0';
1435 char * mntpath = space + 1;
1436 space = strchr(mntpath, ' ');
1437 if (!space) continue;
1438 *space = '\0';
1439 if (strcmp(blockdev, found_blockdev)) continue;
1440 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1441 char * at = strchr(mntpath, '@');
1442 if (!at) continue;
1443 char * ver = at + 1;
1444 ALOGI("Tethering APEX version %s", ver);
1445 }
1446 fclose(f);
1447 free(found_blockdev);
1448 return 0;
1449}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001450
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001451static bool hasGSM() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001452 static string ph = GetProperty("gsm.current.phone-type", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001453 static bool gsm = (ph != "");
1454 static bool logged = false;
1455 if (!logged) {
1456 logged = true;
1457 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1458 }
1459 return gsm;
1460}
1461
1462static bool isTV() {
1463 if (hasGSM()) return false; // TVs don't do GSM
1464
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001465 static string key = GetProperty("ro.oem.key1", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001466 static bool tv = StartsWith(key, "ATV00");
1467 static bool logged = false;
1468 if (!logged) {
1469 logged = true;
1470 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1471 }
1472 return tv;
1473}
1474
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001475static bool isWear() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001476 static string wearSdkStr = GetProperty("ro.cw_build.wear_sdk.version", "");
1477 static int wearSdkInt = GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1478 static string buildChars = GetProperty("ro.build.characteristics", "");
1479 static vector<string> v = Tokenize(buildChars, ",");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001480 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1481 static bool wear = (wearSdkInt > 0) || watch;
1482 static bool logged = false;
1483 if (!logged) {
1484 logged = true;
1485 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1486 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1487 }
1488 return wear;
1489}
1490
Motomu Utsumi712088d2025-03-18 14:52:02 +09001491static int libbpfPrint(enum libbpf_print_level lvl, const char *const formatStr,
1492 va_list argList) {
1493 int32_t prio;
1494 switch (lvl) {
1495 case LIBBPF_WARN:
1496 prio = ANDROID_LOG_WARN;
1497 break;
1498 case LIBBPF_INFO:
1499 prio = ANDROID_LOG_INFO;
1500 break;
1501 case LIBBPF_DEBUG:
1502 prio = ANDROID_LOG_DEBUG;
1503 break;
1504 }
1505 char *s = strdup(formatStr ?: "(no format string)");
1506 int len = strlen(s);
1507 if (len && s[len - 1] == '\n')
1508 s[len - 1] = 0;
1509 LOG_PRI_VA(prio, LOG_TAG, s, argList);
1510 free(s);
1511 return 0;
1512}
1513
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001514static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001515 if (!isAtLeastS) {
1516 ALOGE("Impossible - not reachable on Android <S.");
1517 // for safety, we don't fail, this is a just-in-case workaround
1518 // for any possible busted 'optimized' start everything vendor init hacks on R
1519 return 0;
1520 }
Motomu Utsumi712088d2025-03-18 14:52:02 +09001521 libbpf_set_print(libbpfPrint);
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001522
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001523 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001524
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001525 const int first_api_level = GetIntProperty("ro.board.first_api_level", api_level);
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001526
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001527 // last in U QPR2 beta1
1528 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1529 // first in U QPR2 beta~2
1530 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1531
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001532 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001533 unsigned int bpfloader_ver = BPFLOADER_MAINLINE_S_VERSION; // [42u]
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001534 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1535 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1536 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1537 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001538 if (isAtLeast25Q2) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_25Q2_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001539
Motomu Utsumia7693582025-02-05 17:40:08 +09001540 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) libbpf: v%u.%u "
1541 "uid:%d rc:%d%d",
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001542 bpfloader_ver, argv[0], android_get_device_api_level(), api_level,
Motomu Utsumia7693582025-02-05 17:40:08 +09001543 kernelVersion(), describeArch(), libbpf_major_version(),
1544 libbpf_minor_version(), getuid(), has_platform_bpfloader_rc,
1545 has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001546
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001547 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1548 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1549 return 1;
1550 }
1551
1552 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1553 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1554 return 1;
1555 }
1556
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001557 logTetheringApexVersion();
1558
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001559 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001560 if (!isAtLeastKernelVersion(4, 9, 0)) {
1561 ALOGE("Android S & T require kernel 4.9.");
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001562 return 1;
1563 }
1564
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001565 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001566 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001567 ALOGE("Android U requires kernel 4.14.");
1568 return 1;
1569 }
1570
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001571 // V bumps the kernel requirement up to 4.19
1572 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001573 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001574 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001575 return 1;
1576 }
1577
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001578 // 25Q2 bumps the kernel requirement up to 5.4
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001579 // see also: //system/netd/tests/kernel_test.cpp TestKernel54
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001580 if (isAtLeast25Q2 && !isAtLeastKernelVersion(5, 4, 0)) {
1581 ALOGE("Android 25Q2 requires kernel 5.4.");
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001582 return 1;
1583 }
1584
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001585 // Technically already required by U, but only enforce on V+
1586 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1587 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1588 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1589 if (!isTV()) return 1;
1590 }
1591
Maciej Żenczykowski127715a2025-02-10 21:52:01 -08001592 if (isKernel32Bit() && isAtLeast25Q2) {
1593 ALOGE("Android 25Q2 requires 64 bit kernel.");
1594 return 1;
1595 }
1596
Maciej Żenczykowski9b6a9942024-09-03 16:08:35 -07001597 // 6.6 is highest version supported by Android V, so this is effectively W+ (sdk=36+)
1598 if (isKernel32Bit() && isAtLeastKernelVersion(6, 7, 0)) {
1599 ALOGE("Android platform with 32 bit kernel version >= 6.7.0 is unsupported");
1600 return 1;
1601 }
1602
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001603 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1604 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001605 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001606 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001607 }
1608
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001609 if (isAtLeastV) {
1610 bool bad = false;
1611
1612 if (!isLtsKernel()) {
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001613 ALOGW("Android V+ only supports LTS kernels.");
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001614 bad = true;
1615 }
1616
1617#define REQUIRE(maj, min, sub) \
1618 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001619 ALOGW("Android V+ requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001620 bad = true; \
1621 }
1622
1623 REQUIRE(4, 19, 236)
1624 REQUIRE(5, 4, 186)
1625 REQUIRE(5, 10, 199)
1626 REQUIRE(5, 15, 136)
1627 REQUIRE(6, 1, 57)
1628 REQUIRE(6, 6, 0)
Maciej Żenczykowski06f38e32024-12-11 07:12:59 -08001629 REQUIRE(6, 12, 0)
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001630
1631#undef REQUIRE
1632
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001633 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001634 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1635 }
1636 }
1637
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001638 /* Android 14/U should only launch on 64-bit kernels
1639 * T launches on 5.10/5.15
1640 * U launches on 5.15/6.1
1641 * So >=5.16 implies isKernel64Bit()
1642 *
1643 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1644 *
1645 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1646 * we also require 64-bit userspace.
1647 *
1648 * There are various known issues with 32-bit userspace talking to various
1649 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1650 * Some of these have userspace or kernel workarounds/hacks.
1651 * Some of them don't...
1652 * We're going to be removing the hacks.
1653 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1654 * Note: this check/enforcement only applies to *system* userspace code,
1655 * it does not affect unprivileged apps, the 32-on-64 compatibility
1656 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1657 *
1658 * Additionally the 32-bit kernel jit support is poor,
1659 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001660 * Note, however, that TV and Wear devices will continue to support 32-bit userspace
1661 * on ARM64.
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001662 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001663 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001664 // Stuff won't work reliably, but...
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001665 if (isArm() && (isTV() || isWear())) {
1666 // exempt Arm TV or Wear devices (arm32 ABI is far less problematic than x86-32)
1667 ALOGW("[Arm TV/Wear] 32-bit userspace unsupported on 6.2+ kernels.");
Maciej Żenczykowski73238632025-02-24 14:50:09 -08001668 } else if (first_api_level <= 33 /*T*/ && isArm()) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001669 // also exempt Arm devices upgrading with major kernel rev from T-
1670 // might possibly be better for them to run with a newer kernel...
1671 ALOGW("[Arm KernelUpRev] 32-bit userspace unsupported on 6.2+ kernels.");
1672 } else if (isArm()) {
1673 ALOGE("[Arm] 64-bit userspace required on 6.2+ kernels (%d).", first_api_level);
1674 return 1;
1675 } else { // x86 since RiscV cannot be 32-bit
1676 ALOGE("[x86] 64-bit userspace required on 6.2+ kernels.");
1677 return 1;
1678 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001679 }
1680
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001681 // On handheld, 6.6 is highest version supported by Android V (sdk=35), so this is for sdk=36+
1682 if (!isArm() && isUserspace32bit() && isAtLeastKernelVersion(6, 7, 0)) {
Maciej Żenczykowski21b4a052024-09-03 15:46:48 -07001683 ALOGE("64-bit userspace required on 6.7+ kernels.");
1684 return 1;
1685 }
1686
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001687 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001688 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001689 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001690 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001691 return 1;
1692 }
1693
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001694 if (runningAsRoot) {
1695 // Note: writing this proc file requires being root (always the case on V+)
1696
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001697 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1698 // but we need 0 (enabled)
1699 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1700 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1701 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001702 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001703 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001704
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001705 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001706 // Note: writing these proc files requires CAP_NET_ADMIN
1707 // and sepolicy which is only present on U+,
1708 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1709 // trigger (ie. by init itself) instead.
1710
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001711 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1712 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1713 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1714 // kernel does not have CONFIG_BPF_JIT=y)
1715 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1716 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1717 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001718
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001719 // Enable JIT kallsyms export for privileged users only
1720 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1721 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1722 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1723 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001724
1725 // Create all the pin subdirectories
1726 // (this must be done first to allow selinux_context and pin_subdir functionality,
1727 // which could otherwise fail with ENOENT during object pinning or renaming,
1728 // due to ordering issues)
1729 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001730 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001731 if (createSysFsBpfSubDir(location.prefix)) return 1;
1732 }
1733
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001734 if (isAtLeastT) {
1735 // Note: there's no actual src dir for fs_bpf_loader .o's,
1736 // so it is not listed in 'locations[].prefix'.
1737 // This is because this is primarily meant for triggering genfscon rules,
1738 // and as such this will likely always be the case.
1739 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1740 if (createSysFsBpfSubDir("loader")) return 1;
1741 }
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001742
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001743 // Load all ELF objects, create programs and maps, and pin them
1744 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001745 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001746 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001747 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1748 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1749 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1750 "problems or startup script race.");
1751 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1752 sleep(20);
1753 return 2;
1754 }
1755 }
1756
1757 int key = 1;
1758 int value = 123;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001759 unique_fd map(
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001760 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1761 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001762 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1763 return 1;
1764 }
1765
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001766 // on S we haven't created this subdir yet, but we need it for 'mainline_done' flag below
1767 if (!isAtLeastT && createSysFsBpfSubDir("netd_shared")) return 1;
1768
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001769 // leave a flag that we're done
1770 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001771
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001772 // platform bpfloader will only succeed when run as root
1773 if (!runningAsRoot) {
1774 // unreachable on U QPR3+ which always runs netbpfload as root
1775
1776 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1777 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001778 }
1779
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001780 // unreachable before U QPR3
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001781 if (exists(uprobestatsBpfLoader)) {
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001782 ALOGI("done, transferring control to uprobestatsbpfload.");
1783 const char *args[] = {
1784 uprobestatsBpfLoader,
1785 NULL,
1786 };
1787 execve(args[0], (char **)args, envp);
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001788 ALOGI("unable to execute uprobestatsbpfload, transferring control to "
1789 "platform bpfloader.");
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001790 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001791
1792 // platform BpfLoader *needs* to run as root
1793 const char * args[] = { platformBpfLoader, NULL, };
1794 execve(args[0], (char**)args, envp);
1795 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1796 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001797}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001798
1799} // namespace bpf
1800} // namespace android
1801
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001802int main(int argc, char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001803 if (android::bpf::isAtLeastT) {
1804 InitLogging(argv, &KernelLogger);
1805 } else {
1806 // S lacks the sepolicy to make non-root uid KernelLogger viable
1807 InitLogging(argv);
1808 }
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001809
1810 if (argc == 2 && !strcmp(argv[1], "done")) {
1811 // we're being re-exec'ed from platform bpfloader to 'finalize' things
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001812 if (!SetProperty("bpf.progs_loaded", "1")) {
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001813 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1814 return 125;
1815 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001816 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001817 return 0;
1818 }
1819
1820 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001821}