blob: be4ed1f5604d4ac004465b1b55239be08d958aaa [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
Motomu Utsumi21536e52025-03-18 15:09:27 +0900726static int loadBtf(ifstream &elfFile, struct btf *btf) {
727 int ret;
728 for (unsigned int i = 1; i < btf__type_cnt(btf); ++i) {
729 struct btf_type *bt = (struct btf_type *)btf__type_by_id(btf, i);
730 if (!btf_is_datasec(bt)) continue;
731 ret = setBtfDatasecSize(elfFile, btf, bt);
732 if (ret) return ret;
733 ret = setBtfVarOffset(elfFile, btf, bt);
734 if (ret) return ret;
735 }
736
737 ret = btf__load_into_kernel(btf);
738 if (ret) {
739 if (errno != EINVAL) {
740 ALOGE("btf__load_into_kernel failed, errno: %d", errno);
741 return ret;
742 };
743 // For BTF_KIND_FUNC, newer kernels can read the BTF_INFO_VLEN bits of
744 // struct btf_type to distinguish static vs. global vs. extern
745 // functions, but older kernels enforce that only the BTF_INFO_KIND bits
746 // can be set. Retry with non-BTF_INFO_KIND bits zeroed out to handle
747 // this case.
748 for (unsigned int i = 1; i < btf__type_cnt(btf); ++i) {
749 struct btf_type *bt = (struct btf_type *)btf__type_by_id(btf, i);
750 if (btf_is_func(bt)) {
751 bt->info = (BTF_INFO_KIND(bt->info)) << 24;
752 }
753 }
754 ret = btf__load_into_kernel(btf);
755 if (ret) {
756 ALOGE("btf__load_into_kernel retry failed, errno: %d", errno);
757 return ret;
758 };
759 }
760 return 0;
761}
762
Motomu Utsumi59b20992025-03-18 15:10:19 +0900763int getKeyValueTids(const struct btf *btf, const char *mapName,
764 uint32_t expectedKeySize, uint32_t expectedValueSize,
765 uint32_t *keyTypeId, uint32_t *valueTypeId) {
766 const struct btf_type *kvBt;
767 const struct btf_member *key, *value;
768 const size_t max_name = 256;
769 char kvTypeName[max_name];
770 int64_t keySize, valueSize;
771 uint32_t kvId;
772
773 if (snprintf(kvTypeName, max_name, "____btf_map_%s", mapName) == max_name) {
774 ALOGE("____btf_map_%s is too long", mapName);
775 return -1;
776 }
777
778 kvId = btf__find_by_name(btf, kvTypeName);
779 if (kvId < 0) {
780 ALOGE("section not found, map: %s typeName: %s", mapName, kvTypeName);
781 return -1;
782 }
783
784 kvBt = btf__type_by_id(btf, kvId);
785 if (!kvBt) {
786 ALOGE("Couldn't find BTF type, map: %s id: %u", mapName, kvId);
787 return -1;
788 }
789
790 if (!btf_is_struct(kvBt) || btf_vlen(kvBt) < 2) {
791 ALOGE("Non Struct kind or invalid vlen, map: %s id: %u", mapName, kvId);
792 return -1;
793 }
794
795 key = btf_members(kvBt);
796 value = key + 1;
797
798 keySize = btf__resolve_size(btf, key->type);
799 if (keySize < 0) {
800 ALOGE("Couldn't get key size, map: %s errno: %d", mapName, errno);
801 return -1;
802 }
803
804 valueSize = btf__resolve_size(btf, value->type);
805 if (valueSize < 0) {
806 ALOGE("Couldn't get value size, map: %s errno: %d", mapName, errno);
807 return -1;
808 }
809
810 if (expectedKeySize != keySize || expectedValueSize != valueSize) {
811 ALOGE("Key value size mismatch, map: %s key size: %d expected key size: "
812 "%d value size: %d expected value size: %d",
813 mapName, (uint32_t)keySize, expectedKeySize, (uint32_t)valueSize,
814 expectedValueSize);
815 return -1;
816 }
817
818 *keyTypeId = key->type;
819 *valueTypeId = value->type;
820
821 return 0;
822}
823
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700824static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700825 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700826 int ret;
827 vector<char> mdData;
828 vector<struct bpf_map_def> md;
829 vector<string> mapNames;
830 string objName = pathToObjName(string(elfPath));
831
832 ret = readSectionByName("maps", elfFile, mdData);
833 if (ret == -2) return 0; // no maps to read
834 if (ret) return ret;
835
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700836 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700837 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700838 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700839 return -1;
840 };
841
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700842 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700843
844 const char* dataPtr = mdData.data();
845 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700846 // Copy the structure from the ELF file and move to the next one.
847 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
848 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700849 }
850
851 ret = getSectionSymNames(elfFile, "maps", mapNames);
852 if (ret) return ret;
853
854 unsigned kvers = kernelVersion();
855
856 for (int i = 0; i < (int)mapNames.size(); i++) {
857 if (md[i].zero != 0) abort();
858
859 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000860 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700861 md[i].bpfloader_min_ver);
862 mapFds.push_back(unique_fd());
863 continue;
864 }
865
866 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000867 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700868 md[i].bpfloader_max_ver);
869 mapFds.push_back(unique_fd());
870 continue;
871 }
872
873 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000874 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700875 mapNames[i].c_str(), kvers, md[i].min_kver);
876 mapFds.push_back(unique_fd());
877 continue;
878 }
879
880 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000881 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700882 mapNames[i].c_str(), kvers, md[i].max_kver);
883 mapFds.push_back(unique_fd());
884 continue;
885 }
886
887 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
888 (md[i].ignore_on_userdebug && isUserdebug())) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000889 ALOGD("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700890 getBuildType().c_str());
891 mapFds.push_back(unique_fd());
892 continue;
893 }
894
895 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
896 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
897 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
898 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
899 (isRiscV() && md[i].ignore_on_riscv64)) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000900 ALOGD("skipping map %s which is ignored on %s", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700901 describeArch());
902 mapFds.push_back(unique_fd());
903 continue;
904 }
905
906 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski87019832025-02-03 22:04:26 -0800907 if (type == BPF_MAP_TYPE_LPM_TRIE && !isAtLeastKernelVersion(4, 14, 0)) {
908 // On Linux Kernels older than 4.14 this map type doesn't exist - autoskip.
909 ALOGD("skipping LPM_TRIE map %s - requires kver 4.14+", mapNames[i].c_str());
910 mapFds.push_back(unique_fd());
911 continue;
912 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700913 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
914 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
915 // of be approximated: ARRAY has the same userspace api, though it is not usable
916 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
917 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
918 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
919 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
920 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
921 type = BPF_MAP_TYPE_ARRAY;
922 }
923 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
924 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
925 // of be approximated: HASH has the same userspace visible api.
926 // However it cannot be used by ebpf programs in the same way.
927 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
928 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
929 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
930 // programs as being 5.4+...
931 type = BPF_MAP_TYPE_HASH;
932 }
933
934 // The .h file enforces that this is a power of two, and page size will
935 // also always be a power of two, so this logic is actually enough to
936 // force it to be a multiple of the page size, as required by the kernel.
937 unsigned int max_entries = md[i].max_entries;
938 if (type == BPF_MAP_TYPE_RINGBUF) {
939 if (max_entries < page_size) max_entries = page_size;
940 }
941
942 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
943 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000944 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700945 md[i].selinux_context, static_cast<int>(selinux_context),
946 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
947 }
948
949 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700950 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000951 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700952 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
953 }
954
955 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
956 // except that maps shared across .o's have empty <objName>
957 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
958 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
959 (md[i].shared ? "" : objName) + "_" + mapNames[i];
960 bool reuse = false;
961 unique_fd fd;
962 int saved_errno;
963
964 if (access(mapPinLoc.c_str(), F_OK) == 0) {
965 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
966 saved_errno = errno;
967 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
968 reuse = true;
969 } else {
970 union bpf_attr req = {
971 .map_type = type,
972 .key_size = md[i].key_size,
973 .value_size = md[i].value_size,
974 .max_entries = max_entries,
Maciej Żenczykowskic1a9f4a2025-01-20 12:09:13 -0800975 .map_flags = md[i].map_flags,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700976 };
977 if (isAtLeastKernelVersion(4, 15, 0))
978 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
979 fd.reset(bpf(BPF_MAP_CREATE, req));
980 saved_errno = errno;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -0700981 if (fd.ok()) {
982 ALOGD("bpf_create_map[%s] -> %d", mapNames[i].c_str(), fd.get());
983 } else {
984 ALOGE("bpf_create_map[%s] -> %d errno:%d", mapNames[i].c_str(), fd.get(), saved_errno);
985 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700986 }
987
988 if (!fd.ok()) return -saved_errno;
989
990 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
991 // safety (since reuse code path is rare) run these checks even if we just created it.
992 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
993 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
994
995 if (!reuse) {
996 if (specified(selinux_context)) {
997 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
998 "tmp_map_" + objName + "_" + mapNames[i];
999 ret = bpfFdPin(fd, createLoc.c_str());
1000 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001001 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001002 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1003 return -err;
1004 }
1005 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1006 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
1007 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001008 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001009 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
1010 err, strerror(err));
1011 return -err;
1012 }
1013 } else {
1014 ret = bpfFdPin(fd, mapPinLoc.c_str());
1015 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001016 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001017 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
1018 return -err;
1019 }
1020 }
1021 ret = chmod(mapPinLoc.c_str(), md[i].mode);
1022 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001023 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001024 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
1025 strerror(err));
1026 return -err;
1027 }
1028 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
1029 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001030 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001031 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
1032 ret, err, strerror(err));
1033 return -err;
1034 }
1035 }
1036
Maciej Żenczykowskia003ace2025-02-13 16:08:18 -08001037 if (isAtLeastKernelVersion(4, 14, 0)) {
1038 int mapId = bpfGetFdMapId(fd);
1039 if (mapId == -1) {
1040 const int err = errno;
1041 ALOGE("bpfGetFdMapId failed, errno: %d", err);
1042 return -err;
1043 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001044 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
1045 }
1046
1047 mapFds.push_back(std::move(fd));
1048 }
1049
1050 return ret;
1051}
1052
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001053static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
1054 int insnIndex;
1055 struct bpf_insn *insn, *insns;
1056
1057 insns = (struct bpf_insn*)(insnsPtr);
1058
1059 insnIndex = offset / sizeof(struct bpf_insn);
1060 insn = &insns[insnIndex];
1061
1062 // Occasionally might be useful for relocation debugging, but pretty spammy
1063 if (0) {
1064 ALOGV("applying relo to instruction at byte offset: %llu, "
1065 "insn offset %d, insn %llx",
1066 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
1067 }
1068
1069 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001070 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001071 return;
1072 }
1073
1074 insn->imm = fd;
1075 insn->src_reg = BPF_PSEUDO_MAP_FD;
1076}
1077
1078static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
1079 vector<string> mapNames;
1080
1081 int ret = getSectionSymNames(elfFile, "maps", mapNames);
1082 if (ret) return;
1083
1084 for (int k = 0; k != (int)cs.size(); k++) {
1085 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
1086 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
1087
1088 for (int i = 0; i < n_rel; i++) {
1089 int symIndex = ELF64_R_SYM(rel[i].r_info);
1090 string symName;
1091
1092 ret = getSymNameByIdx(elfFile, symIndex, symName);
1093 if (ret) return;
1094
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +00001095 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001096 for (int j = 0; j < (int)mapNames.size(); j++) {
1097 if (!mapNames[j].compare(symName)) {
1098 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
1099 break;
1100 }
1101 }
1102 }
1103 }
1104}
1105
1106static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
1107 const char* prefix, const unsigned int bpfloader_ver) {
1108 unsigned kvers = kernelVersion();
1109
1110 if (!kvers) {
1111 ALOGE("unable to get kernel version");
1112 return -EINVAL;
1113 }
1114
1115 string objName = pathToObjName(string(elfPath));
1116
1117 for (int i = 0; i < (int)cs.size(); i++) {
1118 unique_fd& fd = cs[i].prog_fd;
1119 int ret;
1120 string name = cs[i].name;
1121
1122 if (!cs[i].prog_def.has_value()) {
1123 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
1124 return -EINVAL;
1125 }
1126
1127 unsigned min_kver = cs[i].prog_def->min_kver;
1128 unsigned max_kver = cs[i].prog_def->max_kver;
1129 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1130 max_kver, kvers);
1131 if (kvers < min_kver) continue;
1132 if (kvers >= max_kver) continue;
1133
1134 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1135 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1136 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1137 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001138
1139 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
1140 bpfMinVer, bpfMaxVer);
1141 if (bpfloader_ver < bpfMinVer) continue;
1142 if (bpfloader_ver >= bpfMaxVer) continue;
1143
1144 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1145 (cs[i].prog_def->ignore_on_user && isUser()) ||
1146 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1147 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1148 getBuildType().c_str());
1149 continue;
1150 }
1151
1152 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
1153 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
1154 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
1155 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
1156 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
1157 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
1158 continue;
1159 }
1160
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001161 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001162 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001163 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
1164 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1165 }
1166
1167 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001168 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001169 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
1170 lookupPinSubdir(pin_subdir));
1171 }
1172
1173 // strip any potential $foo suffix
1174 // this can be used to provide duplicate programs
1175 // conditionally loaded based on running kernel version
1176 name = name.substr(0, name.find_last_of('$'));
1177
1178 bool reuse = false;
1179 // Format of pin location is
1180 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1181 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1182 objName + '_' + string(name);
1183 if (access(progPinLoc.c_str(), F_OK) == 0) {
1184 fd.reset(retrieveProgram(progPinLoc.c_str()));
1185 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001186 !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001187 reuse = true;
1188 } else {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001189 static char log_buf[1 << 20]; // 1 MiB logging buffer
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001190
1191 union bpf_attr req = {
1192 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001193 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001194 .insns = ptr_to_u64(cs[i].data.data()),
1195 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001196 .log_level = 1,
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001197 .log_size = sizeof(log_buf),
1198 .log_buf = ptr_to_u64(log_buf),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001199 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001200 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001201 };
1202 if (isAtLeastKernelVersion(4, 15, 0))
1203 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1204 fd.reset(bpf(BPF_PROG_LOAD, req));
1205
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001206 // Kernel should have NULL terminated the log buffer, but force it anyway for safety
1207 log_buf[sizeof(log_buf) - 1] = 0;
1208
1209 // Strip out final newline if present
1210 int log_chars = strlen(log_buf);
1211 if (log_chars && log_buf[log_chars - 1] == '\n') log_buf[--log_chars] = 0;
1212
1213 bool log_oneline = !strchr(log_buf, '\n');
1214
1215 ALOGD("BPF_PROG_LOAD call for %s (%s) returned '%s' fd: %d (%s)", elfPath,
1216 cs[i].name.c_str(), log_oneline ? log_buf : "{multiline}",
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001217 fd.get(), !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001218
1219 if (!fd.ok()) {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001220 // kernel NULL terminates log_buf, so this checks for non-empty string
1221 if (log_buf[0]) {
1222 vector<string> lines = Split(log_buf, "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001223
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001224 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1225 for (const auto& line : lines) ALOGW("%s", line.c_str());
1226 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1227 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001228
1229 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001230 ALOGW("failed program %s is marked optional - continuing...",
1231 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001232 continue;
1233 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001234 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001235 }
1236 }
1237
1238 if (!fd.ok()) return fd.get();
1239
1240 if (!reuse) {
1241 if (specified(selinux_context)) {
1242 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1243 "tmp_prog_" + objName + '_' + string(name);
1244 ret = bpfFdPin(fd, createLoc.c_str());
1245 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001246 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001247 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1248 return -err;
1249 }
1250 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1251 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1252 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001253 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001254 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1255 err, strerror(err));
1256 return -err;
1257 }
1258 } else {
1259 ret = bpfFdPin(fd, progPinLoc.c_str());
1260 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001261 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001262 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1263 return -err;
1264 }
1265 }
1266 if (chmod(progPinLoc.c_str(), 0440)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001267 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001268 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1269 return -err;
1270 }
1271 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1272 (gid_t)cs[i].prog_def->gid)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001273 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001274 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1275 cs[i].prog_def->gid, err, strerror(err));
1276 return -err;
1277 }
1278 }
1279
Maciej Żenczykowski97debeb2025-02-14 11:15:36 -08001280 if (isAtLeastKernelVersion(4, 14, 0)) {
1281 int progId = bpfGetFdProgId(fd);
1282 if (progId == -1) {
1283 const int err = errno;
1284 ALOGE("bpfGetFdProgId failed, errno: %d", err);
1285 return -err;
1286 }
Maciej Żenczykowski199fd352025-02-13 15:17:08 -08001287
1288 int jitLen = bpfGetFdJitProgLen(fd);
1289 if (jitLen == -1) {
1290 const int err = errno;
1291 ALOGE("bpfGetFdJitProgLen failed, ret: %d", err);
1292 return -err;
1293 }
1294
1295 int xlatLen = bpfGetFdXlatProgLen(fd);
1296 if (xlatLen == -1) {
1297 const int err = errno;
1298 ALOGE("bpfGetFdXlatProgLen failed, ret: %d", err);
1299 return -err;
1300 }
1301 ALOGI("prog %s id %d len jit:%d xlat:%d", progPinLoc.c_str(), progId, jitLen, xlatLen);
1302
1303 if (!jitLen && bpfloader_ver >= BPFLOADER_MAINLINE_25Q2_VERSION) {
1304 ALOGE("Kernel eBPF JIT failure for %s", progPinLoc.c_str());
1305 return -ENOTSUP;
1306 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001307 }
1308 }
1309
1310 return 0;
1311}
1312
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001313int loadProg(const char* const elfPath, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001314 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001315 vector<char> license;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001316 vector<codeSection> cs;
1317 vector<unique_fd> mapFds;
1318 int ret;
1319
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001320 ifstream elfFile(elfPath, ios::in | ios::binary);
1321 if (!elfFile.is_open()) return -1;
1322
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001323 ret = readSectionByName("license", elfFile, license);
1324 if (ret) {
1325 ALOGE("Couldn't find license in %s", elfPath);
1326 return ret;
1327 } else {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001328 ALOGD("Loading ELF object %s with license %s",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001329 elfPath, (char*)license.data());
1330 }
1331
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001332 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1333 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001334
1335 // inclusive lower bound check
1336 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001337 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001338 bpfloader_ver, elfPath, bpfLoaderMinVer);
1339 return 0;
1340 }
1341
1342 // exclusive upper bound check
1343 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001344 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001345 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1346 return 0;
1347 }
1348
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001349 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001350 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1351
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001352 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001353 if (ret) {
1354 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1355 return ret;
1356 }
1357
1358 for (int i = 0; i < (int)mapFds.size(); i++)
1359 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1360
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001361 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001362 // BPF .o's with no programs are only supported by mainline netbpfload,
1363 // make sure .o's targeting non-mainline (ie. S) bpfloader don't show up.
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001364 if (ret == -ENOENT && bpfLoaderMinVer >= BPFLOADER_MAINLINE_S_VERSION)
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001365 return 0;
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001366 if (ret) {
1367 ALOGE("Couldn't read all code sections in %s", elfPath);
1368 return ret;
1369 }
1370
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001371 applyMapRelo(elfFile, mapFds, cs);
1372
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001373 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001374 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1375
1376 return ret;
1377}
1378
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001379static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001380 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001381 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001382 if (errno == ENOENT) return false;
1383 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1384 abort(); // can only hit this if permissions (likely selinux) are screwed up
1385}
1386
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001387#define APEXROOT "/apex/com.android.tethering"
1388#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001389
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001390const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001391 // S+ Tethering mainline module (network_stack): tether offload
1392 {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001393 .dir = BPFROOT "/tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001394 .prefix = "tethering/",
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001395 .t_plus = false,
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001396 },
1397 // T+ Tethering mainline module (shared with netd & system server)
1398 // netutils_wrapper (for iptables xt_bpf) has access to programs
1399 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001400 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001401 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001402 },
1403 // T+ Tethering mainline module (shared with netd & system server)
1404 // netutils_wrapper has no access, netd has read only access
1405 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001406 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001407 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001408 },
1409 // T+ Tethering mainline module (shared with system server)
1410 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001411 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001412 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001413 },
1414 // T+ Tethering mainline module (not shared, just network_stack)
1415 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001416 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001417 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001418 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001419};
1420
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001421static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001422 int retVal = 0;
1423 DIR* dir;
1424 struct dirent* ent;
1425
1426 if ((dir = opendir(location.dir)) != NULL) {
1427 while ((ent = readdir(dir)) != NULL) {
1428 string s = ent->d_name;
1429 if (!EndsWith(s, ".o")) continue;
1430
1431 string progPath(location.dir);
1432 progPath += s;
1433
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001434 int ret = loadProg(progPath.c_str(), bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001435 if (ret) {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001436 retVal = ret;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001437 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1438 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001439 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001440 }
1441 }
1442 closedir(dir);
1443 }
1444 return retVal;
1445}
1446
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001447static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001448 if (*prefix) {
1449 mode_t prevUmask = umask(0);
1450
1451 string s = "/sys/fs/bpf/";
1452 s += prefix;
1453
1454 errno = 0;
1455 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1456 if (ret && errno != EEXIST) {
1457 const int err = errno;
1458 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1459 return -err;
1460 }
1461
1462 umask(prevUmask);
1463 }
1464 return 0;
1465}
1466
1467// Technically 'value' doesn't need to be newline terminated, but it's best
1468// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1469// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001470static int writeProcSysFile(const char *filename, const char *value) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001471 unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001472 if (fd < 0) {
1473 const int err = errno;
1474 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1475 return -err;
1476 }
1477 int len = strlen(value);
1478 int v = write(fd, value, len);
1479 if (v < 0) {
1480 const int err = errno;
1481 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1482 return -err;
1483 }
1484 if (v != len) {
1485 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1486 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1487 return -EINVAL;
1488 }
1489 return 0;
1490}
1491
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001492#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001493const char * const platformBpfLoader = "/system/bin/bpfloader";
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001494const char *const uprobestatsBpfLoader =
1495 "/apex/com.android.uprobestats/bin/uprobestatsbpfload";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001496
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001497static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001498 char * found_blockdev = NULL;
1499 FILE * f = NULL;
1500 char buf[4096];
1501
1502 f = fopen("/proc/mounts", "re");
1503 if (!f) return 1;
1504
1505 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1506 while (fgets(buf, sizeof(buf), f)) {
1507 char * blockdev = buf;
1508 char * space = strchr(blockdev, ' ');
1509 if (!space) continue;
1510 *space = '\0';
1511 char * mntpath = space + 1;
1512 space = strchr(mntpath, ' ');
1513 if (!space) continue;
1514 *space = '\0';
1515 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1516 found_blockdev = strdup(blockdev);
1517 break;
1518 }
1519 fclose(f);
1520 f = NULL;
1521
1522 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001523 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001524
1525 f = fopen("/proc/mounts", "re");
1526 if (!f) { free(found_blockdev); return 3; }
1527
1528 while (fgets(buf, sizeof(buf), f)) {
1529 char * blockdev = buf;
1530 char * space = strchr(blockdev, ' ');
1531 if (!space) continue;
1532 *space = '\0';
1533 char * mntpath = space + 1;
1534 space = strchr(mntpath, ' ');
1535 if (!space) continue;
1536 *space = '\0';
1537 if (strcmp(blockdev, found_blockdev)) continue;
1538 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1539 char * at = strchr(mntpath, '@');
1540 if (!at) continue;
1541 char * ver = at + 1;
1542 ALOGI("Tethering APEX version %s", ver);
1543 }
1544 fclose(f);
1545 free(found_blockdev);
1546 return 0;
1547}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001548
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001549static bool hasGSM() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001550 static string ph = GetProperty("gsm.current.phone-type", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001551 static bool gsm = (ph != "");
1552 static bool logged = false;
1553 if (!logged) {
1554 logged = true;
1555 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1556 }
1557 return gsm;
1558}
1559
1560static bool isTV() {
1561 if (hasGSM()) return false; // TVs don't do GSM
1562
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001563 static string key = GetProperty("ro.oem.key1", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001564 static bool tv = StartsWith(key, "ATV00");
1565 static bool logged = false;
1566 if (!logged) {
1567 logged = true;
1568 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1569 }
1570 return tv;
1571}
1572
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001573static bool isWear() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001574 static string wearSdkStr = GetProperty("ro.cw_build.wear_sdk.version", "");
1575 static int wearSdkInt = GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1576 static string buildChars = GetProperty("ro.build.characteristics", "");
1577 static vector<string> v = Tokenize(buildChars, ",");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001578 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1579 static bool wear = (wearSdkInt > 0) || watch;
1580 static bool logged = false;
1581 if (!logged) {
1582 logged = true;
1583 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1584 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1585 }
1586 return wear;
1587}
1588
Motomu Utsumi712088d2025-03-18 14:52:02 +09001589static int libbpfPrint(enum libbpf_print_level lvl, const char *const formatStr,
1590 va_list argList) {
1591 int32_t prio;
1592 switch (lvl) {
1593 case LIBBPF_WARN:
1594 prio = ANDROID_LOG_WARN;
1595 break;
1596 case LIBBPF_INFO:
1597 prio = ANDROID_LOG_INFO;
1598 break;
1599 case LIBBPF_DEBUG:
1600 prio = ANDROID_LOG_DEBUG;
1601 break;
1602 }
1603 char *s = strdup(formatStr ?: "(no format string)");
1604 int len = strlen(s);
1605 if (len && s[len - 1] == '\n')
1606 s[len - 1] = 0;
1607 LOG_PRI_VA(prio, LOG_TAG, s, argList);
1608 free(s);
1609 return 0;
1610}
1611
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001612static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001613 if (!isAtLeastS) {
1614 ALOGE("Impossible - not reachable on Android <S.");
1615 // for safety, we don't fail, this is a just-in-case workaround
1616 // for any possible busted 'optimized' start everything vendor init hacks on R
1617 return 0;
1618 }
Motomu Utsumi712088d2025-03-18 14:52:02 +09001619 libbpf_set_print(libbpfPrint);
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001620
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001621 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001622
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001623 const int first_api_level = GetIntProperty("ro.board.first_api_level", api_level);
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001624
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001625 // last in U QPR2 beta1
1626 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1627 // first in U QPR2 beta~2
1628 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1629
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001630 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001631 unsigned int bpfloader_ver = BPFLOADER_MAINLINE_S_VERSION; // [42u]
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001632 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1633 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1634 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1635 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001636 if (isAtLeast25Q2) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_25Q2_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001637
Motomu Utsumia7693582025-02-05 17:40:08 +09001638 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) libbpf: v%u.%u "
1639 "uid:%d rc:%d%d",
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001640 bpfloader_ver, argv[0], android_get_device_api_level(), api_level,
Motomu Utsumia7693582025-02-05 17:40:08 +09001641 kernelVersion(), describeArch(), libbpf_major_version(),
1642 libbpf_minor_version(), getuid(), has_platform_bpfloader_rc,
1643 has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001644
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001645 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1646 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1647 return 1;
1648 }
1649
1650 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1651 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1652 return 1;
1653 }
1654
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001655 logTetheringApexVersion();
1656
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001657 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001658 if (!isAtLeastKernelVersion(4, 9, 0)) {
1659 ALOGE("Android S & T require kernel 4.9.");
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001660 return 1;
1661 }
1662
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001663 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001664 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001665 ALOGE("Android U requires kernel 4.14.");
1666 return 1;
1667 }
1668
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001669 // V bumps the kernel requirement up to 4.19
1670 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001671 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001672 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001673 return 1;
1674 }
1675
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001676 // 25Q2 bumps the kernel requirement up to 5.4
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001677 // see also: //system/netd/tests/kernel_test.cpp TestKernel54
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001678 if (isAtLeast25Q2 && !isAtLeastKernelVersion(5, 4, 0)) {
1679 ALOGE("Android 25Q2 requires kernel 5.4.");
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001680 return 1;
1681 }
1682
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001683 // Technically already required by U, but only enforce on V+
1684 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1685 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1686 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1687 if (!isTV()) return 1;
1688 }
1689
Maciej Żenczykowski127715a2025-02-10 21:52:01 -08001690 if (isKernel32Bit() && isAtLeast25Q2) {
1691 ALOGE("Android 25Q2 requires 64 bit kernel.");
1692 return 1;
1693 }
1694
Maciej Żenczykowski9b6a9942024-09-03 16:08:35 -07001695 // 6.6 is highest version supported by Android V, so this is effectively W+ (sdk=36+)
1696 if (isKernel32Bit() && isAtLeastKernelVersion(6, 7, 0)) {
1697 ALOGE("Android platform with 32 bit kernel version >= 6.7.0 is unsupported");
1698 return 1;
1699 }
1700
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001701 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1702 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001703 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001704 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001705 }
1706
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001707 if (isAtLeastV) {
1708 bool bad = false;
1709
1710 if (!isLtsKernel()) {
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001711 ALOGW("Android V+ only supports LTS kernels.");
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001712 bad = true;
1713 }
1714
1715#define REQUIRE(maj, min, sub) \
1716 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001717 ALOGW("Android V+ requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001718 bad = true; \
1719 }
1720
1721 REQUIRE(4, 19, 236)
1722 REQUIRE(5, 4, 186)
1723 REQUIRE(5, 10, 199)
1724 REQUIRE(5, 15, 136)
1725 REQUIRE(6, 1, 57)
1726 REQUIRE(6, 6, 0)
Maciej Żenczykowski06f38e32024-12-11 07:12:59 -08001727 REQUIRE(6, 12, 0)
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001728
1729#undef REQUIRE
1730
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001731 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001732 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1733 }
1734 }
1735
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001736 /* Android 14/U should only launch on 64-bit kernels
1737 * T launches on 5.10/5.15
1738 * U launches on 5.15/6.1
1739 * So >=5.16 implies isKernel64Bit()
1740 *
1741 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1742 *
1743 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1744 * we also require 64-bit userspace.
1745 *
1746 * There are various known issues with 32-bit userspace talking to various
1747 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1748 * Some of these have userspace or kernel workarounds/hacks.
1749 * Some of them don't...
1750 * We're going to be removing the hacks.
1751 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1752 * Note: this check/enforcement only applies to *system* userspace code,
1753 * it does not affect unprivileged apps, the 32-on-64 compatibility
1754 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1755 *
1756 * Additionally the 32-bit kernel jit support is poor,
1757 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001758 * Note, however, that TV and Wear devices will continue to support 32-bit userspace
1759 * on ARM64.
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001760 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001761 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001762 // Stuff won't work reliably, but...
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001763 if (isArm() && (isTV() || isWear())) {
1764 // exempt Arm TV or Wear devices (arm32 ABI is far less problematic than x86-32)
1765 ALOGW("[Arm TV/Wear] 32-bit userspace unsupported on 6.2+ kernels.");
Maciej Żenczykowski73238632025-02-24 14:50:09 -08001766 } else if (first_api_level <= 33 /*T*/ && isArm()) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001767 // also exempt Arm devices upgrading with major kernel rev from T-
1768 // might possibly be better for them to run with a newer kernel...
1769 ALOGW("[Arm KernelUpRev] 32-bit userspace unsupported on 6.2+ kernels.");
1770 } else if (isArm()) {
1771 ALOGE("[Arm] 64-bit userspace required on 6.2+ kernels (%d).", first_api_level);
1772 return 1;
1773 } else { // x86 since RiscV cannot be 32-bit
1774 ALOGE("[x86] 64-bit userspace required on 6.2+ kernels.");
1775 return 1;
1776 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001777 }
1778
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001779 // On handheld, 6.6 is highest version supported by Android V (sdk=35), so this is for sdk=36+
1780 if (!isArm() && isUserspace32bit() && isAtLeastKernelVersion(6, 7, 0)) {
Maciej Żenczykowski21b4a052024-09-03 15:46:48 -07001781 ALOGE("64-bit userspace required on 6.7+ kernels.");
1782 return 1;
1783 }
1784
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001785 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001786 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001787 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001788 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001789 return 1;
1790 }
1791
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001792 if (runningAsRoot) {
1793 // Note: writing this proc file requires being root (always the case on V+)
1794
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001795 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1796 // but we need 0 (enabled)
1797 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1798 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1799 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001800 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001801 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001802
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001803 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001804 // Note: writing these proc files requires CAP_NET_ADMIN
1805 // and sepolicy which is only present on U+,
1806 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1807 // trigger (ie. by init itself) instead.
1808
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001809 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1810 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1811 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1812 // kernel does not have CONFIG_BPF_JIT=y)
1813 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1814 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1815 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001816
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001817 // Enable JIT kallsyms export for privileged users only
1818 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1819 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1820 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1821 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001822
1823 // Create all the pin subdirectories
1824 // (this must be done first to allow selinux_context and pin_subdir functionality,
1825 // which could otherwise fail with ENOENT during object pinning or renaming,
1826 // due to ordering issues)
1827 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001828 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001829 if (createSysFsBpfSubDir(location.prefix)) return 1;
1830 }
1831
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001832 if (isAtLeastT) {
1833 // Note: there's no actual src dir for fs_bpf_loader .o's,
1834 // so it is not listed in 'locations[].prefix'.
1835 // This is because this is primarily meant for triggering genfscon rules,
1836 // and as such this will likely always be the case.
1837 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1838 if (createSysFsBpfSubDir("loader")) return 1;
1839 }
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001840
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001841 // Load all ELF objects, create programs and maps, and pin them
1842 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001843 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001844 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001845 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1846 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1847 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1848 "problems or startup script race.");
1849 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1850 sleep(20);
1851 return 2;
1852 }
1853 }
1854
1855 int key = 1;
1856 int value = 123;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001857 unique_fd map(
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001858 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1859 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001860 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1861 return 1;
1862 }
1863
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001864 // on S we haven't created this subdir yet, but we need it for 'mainline_done' flag below
1865 if (!isAtLeastT && createSysFsBpfSubDir("netd_shared")) return 1;
1866
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001867 // leave a flag that we're done
1868 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001869
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001870 // platform bpfloader will only succeed when run as root
1871 if (!runningAsRoot) {
1872 // unreachable on U QPR3+ which always runs netbpfload as root
1873
1874 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1875 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001876 }
1877
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001878 // unreachable before U QPR3
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001879 if (exists(uprobestatsBpfLoader)) {
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001880 ALOGI("done, transferring control to uprobestatsbpfload.");
1881 const char *args[] = {
1882 uprobestatsBpfLoader,
1883 NULL,
1884 };
1885 execve(args[0], (char **)args, envp);
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001886 ALOGI("unable to execute uprobestatsbpfload, transferring control to "
1887 "platform bpfloader.");
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001888 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001889
1890 // platform BpfLoader *needs* to run as root
1891 const char * args[] = { platformBpfLoader, NULL, };
1892 execve(args[0], (char**)args, envp);
1893 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1894 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001895}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001896
1897} // namespace bpf
1898} // namespace android
1899
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001900int main(int argc, char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001901 if (android::bpf::isAtLeastT) {
1902 InitLogging(argv, &KernelLogger);
1903 } else {
1904 // S lacks the sepolicy to make non-root uid KernelLogger viable
1905 InitLogging(argv);
1906 }
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001907
1908 if (argc == 2 && !strcmp(argv[1], "done")) {
1909 // we're being re-exec'ed from platform bpfloader to 'finalize' things
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001910 if (!SetProperty("bpf.progs_loaded", "1")) {
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001911 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1912 return 125;
1913 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001914 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001915 return 0;
1916 }
1917
1918 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001919}