blob: 5e01ef7d073266cceb507ab90ece0cbeb4cfcf3f [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
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700763static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700764 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700765 int ret;
766 vector<char> mdData;
767 vector<struct bpf_map_def> md;
768 vector<string> mapNames;
769 string objName = pathToObjName(string(elfPath));
770
771 ret = readSectionByName("maps", elfFile, mdData);
772 if (ret == -2) return 0; // no maps to read
773 if (ret) return ret;
774
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700775 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700776 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700777 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700778 return -1;
779 };
780
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700781 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700782
783 const char* dataPtr = mdData.data();
784 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700785 // Copy the structure from the ELF file and move to the next one.
786 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
787 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700788 }
789
790 ret = getSectionSymNames(elfFile, "maps", mapNames);
791 if (ret) return ret;
792
793 unsigned kvers = kernelVersion();
794
795 for (int i = 0; i < (int)mapNames.size(); i++) {
796 if (md[i].zero != 0) abort();
797
798 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000799 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700800 md[i].bpfloader_min_ver);
801 mapFds.push_back(unique_fd());
802 continue;
803 }
804
805 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000806 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700807 md[i].bpfloader_max_ver);
808 mapFds.push_back(unique_fd());
809 continue;
810 }
811
812 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000813 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700814 mapNames[i].c_str(), kvers, md[i].min_kver);
815 mapFds.push_back(unique_fd());
816 continue;
817 }
818
819 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000820 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700821 mapNames[i].c_str(), kvers, md[i].max_kver);
822 mapFds.push_back(unique_fd());
823 continue;
824 }
825
826 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
827 (md[i].ignore_on_userdebug && isUserdebug())) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000828 ALOGD("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700829 getBuildType().c_str());
830 mapFds.push_back(unique_fd());
831 continue;
832 }
833
834 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
835 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
836 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
837 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
838 (isRiscV() && md[i].ignore_on_riscv64)) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000839 ALOGD("skipping map %s which is ignored on %s", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700840 describeArch());
841 mapFds.push_back(unique_fd());
842 continue;
843 }
844
845 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski87019832025-02-03 22:04:26 -0800846 if (type == BPF_MAP_TYPE_LPM_TRIE && !isAtLeastKernelVersion(4, 14, 0)) {
847 // On Linux Kernels older than 4.14 this map type doesn't exist - autoskip.
848 ALOGD("skipping LPM_TRIE map %s - requires kver 4.14+", mapNames[i].c_str());
849 mapFds.push_back(unique_fd());
850 continue;
851 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700852 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
853 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
854 // of be approximated: ARRAY has the same userspace api, though it is not usable
855 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
856 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
857 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
858 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
859 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
860 type = BPF_MAP_TYPE_ARRAY;
861 }
862 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
863 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
864 // of be approximated: HASH has the same userspace visible api.
865 // However it cannot be used by ebpf programs in the same way.
866 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
867 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
868 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
869 // programs as being 5.4+...
870 type = BPF_MAP_TYPE_HASH;
871 }
872
873 // The .h file enforces that this is a power of two, and page size will
874 // also always be a power of two, so this logic is actually enough to
875 // force it to be a multiple of the page size, as required by the kernel.
876 unsigned int max_entries = md[i].max_entries;
877 if (type == BPF_MAP_TYPE_RINGBUF) {
878 if (max_entries < page_size) max_entries = page_size;
879 }
880
881 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
882 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000883 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700884 md[i].selinux_context, static_cast<int>(selinux_context),
885 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
886 }
887
888 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700889 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000890 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700891 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
892 }
893
894 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
895 // except that maps shared across .o's have empty <objName>
896 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
897 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
898 (md[i].shared ? "" : objName) + "_" + mapNames[i];
899 bool reuse = false;
900 unique_fd fd;
901 int saved_errno;
902
903 if (access(mapPinLoc.c_str(), F_OK) == 0) {
904 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
905 saved_errno = errno;
906 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
907 reuse = true;
908 } else {
909 union bpf_attr req = {
910 .map_type = type,
911 .key_size = md[i].key_size,
912 .value_size = md[i].value_size,
913 .max_entries = max_entries,
Maciej Żenczykowskic1a9f4a2025-01-20 12:09:13 -0800914 .map_flags = md[i].map_flags,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700915 };
916 if (isAtLeastKernelVersion(4, 15, 0))
917 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
918 fd.reset(bpf(BPF_MAP_CREATE, req));
919 saved_errno = errno;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -0700920 if (fd.ok()) {
921 ALOGD("bpf_create_map[%s] -> %d", mapNames[i].c_str(), fd.get());
922 } else {
923 ALOGE("bpf_create_map[%s] -> %d errno:%d", mapNames[i].c_str(), fd.get(), saved_errno);
924 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700925 }
926
927 if (!fd.ok()) return -saved_errno;
928
929 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
930 // safety (since reuse code path is rare) run these checks even if we just created it.
931 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
932 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
933
934 if (!reuse) {
935 if (specified(selinux_context)) {
936 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
937 "tmp_map_" + objName + "_" + mapNames[i];
938 ret = bpfFdPin(fd, createLoc.c_str());
939 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800940 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700941 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
942 return -err;
943 }
944 ret = renameat2(AT_FDCWD, createLoc.c_str(),
945 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
946 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800947 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700948 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
949 err, strerror(err));
950 return -err;
951 }
952 } else {
953 ret = bpfFdPin(fd, mapPinLoc.c_str());
954 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800955 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700956 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
957 return -err;
958 }
959 }
960 ret = chmod(mapPinLoc.c_str(), md[i].mode);
961 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800962 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700963 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
964 strerror(err));
965 return -err;
966 }
967 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
968 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800969 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700970 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
971 ret, err, strerror(err));
972 return -err;
973 }
974 }
975
Maciej Żenczykowskia003ace2025-02-13 16:08:18 -0800976 if (isAtLeastKernelVersion(4, 14, 0)) {
977 int mapId = bpfGetFdMapId(fd);
978 if (mapId == -1) {
979 const int err = errno;
980 ALOGE("bpfGetFdMapId failed, errno: %d", err);
981 return -err;
982 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700983 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
984 }
985
986 mapFds.push_back(std::move(fd));
987 }
988
989 return ret;
990}
991
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700992static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
993 int insnIndex;
994 struct bpf_insn *insn, *insns;
995
996 insns = (struct bpf_insn*)(insnsPtr);
997
998 insnIndex = offset / sizeof(struct bpf_insn);
999 insn = &insns[insnIndex];
1000
1001 // Occasionally might be useful for relocation debugging, but pretty spammy
1002 if (0) {
1003 ALOGV("applying relo to instruction at byte offset: %llu, "
1004 "insn offset %d, insn %llx",
1005 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
1006 }
1007
1008 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001009 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001010 return;
1011 }
1012
1013 insn->imm = fd;
1014 insn->src_reg = BPF_PSEUDO_MAP_FD;
1015}
1016
1017static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
1018 vector<string> mapNames;
1019
1020 int ret = getSectionSymNames(elfFile, "maps", mapNames);
1021 if (ret) return;
1022
1023 for (int k = 0; k != (int)cs.size(); k++) {
1024 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
1025 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
1026
1027 for (int i = 0; i < n_rel; i++) {
1028 int symIndex = ELF64_R_SYM(rel[i].r_info);
1029 string symName;
1030
1031 ret = getSymNameByIdx(elfFile, symIndex, symName);
1032 if (ret) return;
1033
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +00001034 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001035 for (int j = 0; j < (int)mapNames.size(); j++) {
1036 if (!mapNames[j].compare(symName)) {
1037 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
1038 break;
1039 }
1040 }
1041 }
1042 }
1043}
1044
1045static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
1046 const char* prefix, const unsigned int bpfloader_ver) {
1047 unsigned kvers = kernelVersion();
1048
1049 if (!kvers) {
1050 ALOGE("unable to get kernel version");
1051 return -EINVAL;
1052 }
1053
1054 string objName = pathToObjName(string(elfPath));
1055
1056 for (int i = 0; i < (int)cs.size(); i++) {
1057 unique_fd& fd = cs[i].prog_fd;
1058 int ret;
1059 string name = cs[i].name;
1060
1061 if (!cs[i].prog_def.has_value()) {
1062 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
1063 return -EINVAL;
1064 }
1065
1066 unsigned min_kver = cs[i].prog_def->min_kver;
1067 unsigned max_kver = cs[i].prog_def->max_kver;
1068 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1069 max_kver, kvers);
1070 if (kvers < min_kver) continue;
1071 if (kvers >= max_kver) continue;
1072
1073 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1074 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1075 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1076 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001077
1078 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
1079 bpfMinVer, bpfMaxVer);
1080 if (bpfloader_ver < bpfMinVer) continue;
1081 if (bpfloader_ver >= bpfMaxVer) continue;
1082
1083 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1084 (cs[i].prog_def->ignore_on_user && isUser()) ||
1085 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1086 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1087 getBuildType().c_str());
1088 continue;
1089 }
1090
1091 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
1092 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
1093 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
1094 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
1095 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
1096 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
1097 continue;
1098 }
1099
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001100 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001101 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001102 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
1103 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1104 }
1105
1106 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001107 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001108 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
1109 lookupPinSubdir(pin_subdir));
1110 }
1111
1112 // strip any potential $foo suffix
1113 // this can be used to provide duplicate programs
1114 // conditionally loaded based on running kernel version
1115 name = name.substr(0, name.find_last_of('$'));
1116
1117 bool reuse = false;
1118 // Format of pin location is
1119 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1120 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1121 objName + '_' + string(name);
1122 if (access(progPinLoc.c_str(), F_OK) == 0) {
1123 fd.reset(retrieveProgram(progPinLoc.c_str()));
1124 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001125 !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001126 reuse = true;
1127 } else {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001128 static char log_buf[1 << 20]; // 1 MiB logging buffer
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001129
1130 union bpf_attr req = {
1131 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001132 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001133 .insns = ptr_to_u64(cs[i].data.data()),
1134 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001135 .log_level = 1,
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001136 .log_size = sizeof(log_buf),
1137 .log_buf = ptr_to_u64(log_buf),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001138 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001139 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001140 };
1141 if (isAtLeastKernelVersion(4, 15, 0))
1142 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1143 fd.reset(bpf(BPF_PROG_LOAD, req));
1144
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001145 // Kernel should have NULL terminated the log buffer, but force it anyway for safety
1146 log_buf[sizeof(log_buf) - 1] = 0;
1147
1148 // Strip out final newline if present
1149 int log_chars = strlen(log_buf);
1150 if (log_chars && log_buf[log_chars - 1] == '\n') log_buf[--log_chars] = 0;
1151
1152 bool log_oneline = !strchr(log_buf, '\n');
1153
1154 ALOGD("BPF_PROG_LOAD call for %s (%s) returned '%s' fd: %d (%s)", elfPath,
1155 cs[i].name.c_str(), log_oneline ? log_buf : "{multiline}",
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001156 fd.get(), !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001157
1158 if (!fd.ok()) {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001159 // kernel NULL terminates log_buf, so this checks for non-empty string
1160 if (log_buf[0]) {
1161 vector<string> lines = Split(log_buf, "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001162
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001163 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1164 for (const auto& line : lines) ALOGW("%s", line.c_str());
1165 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1166 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001167
1168 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001169 ALOGW("failed program %s is marked optional - continuing...",
1170 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001171 continue;
1172 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001173 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001174 }
1175 }
1176
1177 if (!fd.ok()) return fd.get();
1178
1179 if (!reuse) {
1180 if (specified(selinux_context)) {
1181 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1182 "tmp_prog_" + objName + '_' + string(name);
1183 ret = bpfFdPin(fd, createLoc.c_str());
1184 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001185 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001186 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1187 return -err;
1188 }
1189 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1190 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1191 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001192 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001193 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1194 err, strerror(err));
1195 return -err;
1196 }
1197 } else {
1198 ret = bpfFdPin(fd, progPinLoc.c_str());
1199 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001200 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001201 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1202 return -err;
1203 }
1204 }
1205 if (chmod(progPinLoc.c_str(), 0440)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001206 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001207 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1208 return -err;
1209 }
1210 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1211 (gid_t)cs[i].prog_def->gid)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001212 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001213 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1214 cs[i].prog_def->gid, err, strerror(err));
1215 return -err;
1216 }
1217 }
1218
Maciej Żenczykowski97debeb2025-02-14 11:15:36 -08001219 if (isAtLeastKernelVersion(4, 14, 0)) {
1220 int progId = bpfGetFdProgId(fd);
1221 if (progId == -1) {
1222 const int err = errno;
1223 ALOGE("bpfGetFdProgId failed, errno: %d", err);
1224 return -err;
1225 }
Maciej Żenczykowski199fd352025-02-13 15:17:08 -08001226
1227 int jitLen = bpfGetFdJitProgLen(fd);
1228 if (jitLen == -1) {
1229 const int err = errno;
1230 ALOGE("bpfGetFdJitProgLen failed, ret: %d", err);
1231 return -err;
1232 }
1233
1234 int xlatLen = bpfGetFdXlatProgLen(fd);
1235 if (xlatLen == -1) {
1236 const int err = errno;
1237 ALOGE("bpfGetFdXlatProgLen failed, ret: %d", err);
1238 return -err;
1239 }
1240 ALOGI("prog %s id %d len jit:%d xlat:%d", progPinLoc.c_str(), progId, jitLen, xlatLen);
1241
1242 if (!jitLen && bpfloader_ver >= BPFLOADER_MAINLINE_25Q2_VERSION) {
1243 ALOGE("Kernel eBPF JIT failure for %s", progPinLoc.c_str());
1244 return -ENOTSUP;
1245 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001246 }
1247 }
1248
1249 return 0;
1250}
1251
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001252int loadProg(const char* const elfPath, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001253 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001254 vector<char> license;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001255 vector<codeSection> cs;
1256 vector<unique_fd> mapFds;
1257 int ret;
1258
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001259 ifstream elfFile(elfPath, ios::in | ios::binary);
1260 if (!elfFile.is_open()) return -1;
1261
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001262 ret = readSectionByName("license", elfFile, license);
1263 if (ret) {
1264 ALOGE("Couldn't find license in %s", elfPath);
1265 return ret;
1266 } else {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001267 ALOGD("Loading ELF object %s with license %s",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001268 elfPath, (char*)license.data());
1269 }
1270
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001271 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1272 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001273
1274 // inclusive lower bound check
1275 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001276 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001277 bpfloader_ver, elfPath, bpfLoaderMinVer);
1278 return 0;
1279 }
1280
1281 // exclusive upper bound check
1282 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001283 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001284 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1285 return 0;
1286 }
1287
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001288 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001289 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1290
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001291 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001292 if (ret) {
1293 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1294 return ret;
1295 }
1296
1297 for (int i = 0; i < (int)mapFds.size(); i++)
1298 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1299
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001300 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001301 // BPF .o's with no programs are only supported by mainline netbpfload,
1302 // make sure .o's targeting non-mainline (ie. S) bpfloader don't show up.
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001303 if (ret == -ENOENT && bpfLoaderMinVer >= BPFLOADER_MAINLINE_S_VERSION)
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001304 return 0;
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001305 if (ret) {
1306 ALOGE("Couldn't read all code sections in %s", elfPath);
1307 return ret;
1308 }
1309
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001310 applyMapRelo(elfFile, mapFds, cs);
1311
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001312 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001313 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1314
1315 return ret;
1316}
1317
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001318static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001319 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001320 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001321 if (errno == ENOENT) return false;
1322 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1323 abort(); // can only hit this if permissions (likely selinux) are screwed up
1324}
1325
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001326#define APEXROOT "/apex/com.android.tethering"
1327#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001328
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001329const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001330 // S+ Tethering mainline module (network_stack): tether offload
1331 {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001332 .dir = BPFROOT "/tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001333 .prefix = "tethering/",
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001334 .t_plus = false,
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001335 },
1336 // T+ Tethering mainline module (shared with netd & system server)
1337 // netutils_wrapper (for iptables xt_bpf) has access to programs
1338 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001339 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001340 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001341 },
1342 // T+ Tethering mainline module (shared with netd & system server)
1343 // netutils_wrapper has no access, netd has read only access
1344 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001345 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001346 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001347 },
1348 // T+ Tethering mainline module (shared with system server)
1349 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001350 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001351 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001352 },
1353 // T+ Tethering mainline module (not shared, just network_stack)
1354 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001355 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001356 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001357 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001358};
1359
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001360static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001361 int retVal = 0;
1362 DIR* dir;
1363 struct dirent* ent;
1364
1365 if ((dir = opendir(location.dir)) != NULL) {
1366 while ((ent = readdir(dir)) != NULL) {
1367 string s = ent->d_name;
1368 if (!EndsWith(s, ".o")) continue;
1369
1370 string progPath(location.dir);
1371 progPath += s;
1372
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001373 int ret = loadProg(progPath.c_str(), bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001374 if (ret) {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001375 retVal = ret;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001376 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1377 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001378 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001379 }
1380 }
1381 closedir(dir);
1382 }
1383 return retVal;
1384}
1385
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001386static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001387 if (*prefix) {
1388 mode_t prevUmask = umask(0);
1389
1390 string s = "/sys/fs/bpf/";
1391 s += prefix;
1392
1393 errno = 0;
1394 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1395 if (ret && errno != EEXIST) {
1396 const int err = errno;
1397 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1398 return -err;
1399 }
1400
1401 umask(prevUmask);
1402 }
1403 return 0;
1404}
1405
1406// Technically 'value' doesn't need to be newline terminated, but it's best
1407// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1408// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001409static int writeProcSysFile(const char *filename, const char *value) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001410 unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001411 if (fd < 0) {
1412 const int err = errno;
1413 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1414 return -err;
1415 }
1416 int len = strlen(value);
1417 int v = write(fd, value, len);
1418 if (v < 0) {
1419 const int err = errno;
1420 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1421 return -err;
1422 }
1423 if (v != len) {
1424 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1425 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1426 return -EINVAL;
1427 }
1428 return 0;
1429}
1430
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001431#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001432const char * const platformBpfLoader = "/system/bin/bpfloader";
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001433const char *const uprobestatsBpfLoader =
1434 "/apex/com.android.uprobestats/bin/uprobestatsbpfload";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001435
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001436static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001437 char * found_blockdev = NULL;
1438 FILE * f = NULL;
1439 char buf[4096];
1440
1441 f = fopen("/proc/mounts", "re");
1442 if (!f) return 1;
1443
1444 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1445 while (fgets(buf, sizeof(buf), f)) {
1446 char * blockdev = buf;
1447 char * space = strchr(blockdev, ' ');
1448 if (!space) continue;
1449 *space = '\0';
1450 char * mntpath = space + 1;
1451 space = strchr(mntpath, ' ');
1452 if (!space) continue;
1453 *space = '\0';
1454 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1455 found_blockdev = strdup(blockdev);
1456 break;
1457 }
1458 fclose(f);
1459 f = NULL;
1460
1461 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001462 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001463
1464 f = fopen("/proc/mounts", "re");
1465 if (!f) { free(found_blockdev); return 3; }
1466
1467 while (fgets(buf, sizeof(buf), f)) {
1468 char * blockdev = buf;
1469 char * space = strchr(blockdev, ' ');
1470 if (!space) continue;
1471 *space = '\0';
1472 char * mntpath = space + 1;
1473 space = strchr(mntpath, ' ');
1474 if (!space) continue;
1475 *space = '\0';
1476 if (strcmp(blockdev, found_blockdev)) continue;
1477 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1478 char * at = strchr(mntpath, '@');
1479 if (!at) continue;
1480 char * ver = at + 1;
1481 ALOGI("Tethering APEX version %s", ver);
1482 }
1483 fclose(f);
1484 free(found_blockdev);
1485 return 0;
1486}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001487
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001488static bool hasGSM() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001489 static string ph = GetProperty("gsm.current.phone-type", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001490 static bool gsm = (ph != "");
1491 static bool logged = false;
1492 if (!logged) {
1493 logged = true;
1494 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1495 }
1496 return gsm;
1497}
1498
1499static bool isTV() {
1500 if (hasGSM()) return false; // TVs don't do GSM
1501
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001502 static string key = GetProperty("ro.oem.key1", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001503 static bool tv = StartsWith(key, "ATV00");
1504 static bool logged = false;
1505 if (!logged) {
1506 logged = true;
1507 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1508 }
1509 return tv;
1510}
1511
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001512static bool isWear() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001513 static string wearSdkStr = GetProperty("ro.cw_build.wear_sdk.version", "");
1514 static int wearSdkInt = GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1515 static string buildChars = GetProperty("ro.build.characteristics", "");
1516 static vector<string> v = Tokenize(buildChars, ",");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001517 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1518 static bool wear = (wearSdkInt > 0) || watch;
1519 static bool logged = false;
1520 if (!logged) {
1521 logged = true;
1522 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1523 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1524 }
1525 return wear;
1526}
1527
Motomu Utsumi712088d2025-03-18 14:52:02 +09001528static int libbpfPrint(enum libbpf_print_level lvl, const char *const formatStr,
1529 va_list argList) {
1530 int32_t prio;
1531 switch (lvl) {
1532 case LIBBPF_WARN:
1533 prio = ANDROID_LOG_WARN;
1534 break;
1535 case LIBBPF_INFO:
1536 prio = ANDROID_LOG_INFO;
1537 break;
1538 case LIBBPF_DEBUG:
1539 prio = ANDROID_LOG_DEBUG;
1540 break;
1541 }
1542 char *s = strdup(formatStr ?: "(no format string)");
1543 int len = strlen(s);
1544 if (len && s[len - 1] == '\n')
1545 s[len - 1] = 0;
1546 LOG_PRI_VA(prio, LOG_TAG, s, argList);
1547 free(s);
1548 return 0;
1549}
1550
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001551static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001552 if (!isAtLeastS) {
1553 ALOGE("Impossible - not reachable on Android <S.");
1554 // for safety, we don't fail, this is a just-in-case workaround
1555 // for any possible busted 'optimized' start everything vendor init hacks on R
1556 return 0;
1557 }
Motomu Utsumi712088d2025-03-18 14:52:02 +09001558 libbpf_set_print(libbpfPrint);
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001559
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001560 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001561
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001562 const int first_api_level = GetIntProperty("ro.board.first_api_level", api_level);
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001563
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001564 // last in U QPR2 beta1
1565 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1566 // first in U QPR2 beta~2
1567 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1568
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001569 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001570 unsigned int bpfloader_ver = BPFLOADER_MAINLINE_S_VERSION; // [42u]
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001571 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1572 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1573 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1574 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001575 if (isAtLeast25Q2) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_25Q2_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001576
Motomu Utsumia7693582025-02-05 17:40:08 +09001577 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) libbpf: v%u.%u "
1578 "uid:%d rc:%d%d",
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001579 bpfloader_ver, argv[0], android_get_device_api_level(), api_level,
Motomu Utsumia7693582025-02-05 17:40:08 +09001580 kernelVersion(), describeArch(), libbpf_major_version(),
1581 libbpf_minor_version(), getuid(), has_platform_bpfloader_rc,
1582 has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001583
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001584 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1585 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1586 return 1;
1587 }
1588
1589 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1590 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1591 return 1;
1592 }
1593
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001594 logTetheringApexVersion();
1595
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001596 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001597 if (!isAtLeastKernelVersion(4, 9, 0)) {
1598 ALOGE("Android S & T require kernel 4.9.");
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001599 return 1;
1600 }
1601
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001602 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001603 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001604 ALOGE("Android U requires kernel 4.14.");
1605 return 1;
1606 }
1607
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001608 // V bumps the kernel requirement up to 4.19
1609 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001610 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001611 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001612 return 1;
1613 }
1614
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001615 // 25Q2 bumps the kernel requirement up to 5.4
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001616 // see also: //system/netd/tests/kernel_test.cpp TestKernel54
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001617 if (isAtLeast25Q2 && !isAtLeastKernelVersion(5, 4, 0)) {
1618 ALOGE("Android 25Q2 requires kernel 5.4.");
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001619 return 1;
1620 }
1621
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001622 // Technically already required by U, but only enforce on V+
1623 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1624 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1625 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1626 if (!isTV()) return 1;
1627 }
1628
Maciej Żenczykowski127715a2025-02-10 21:52:01 -08001629 if (isKernel32Bit() && isAtLeast25Q2) {
1630 ALOGE("Android 25Q2 requires 64 bit kernel.");
1631 return 1;
1632 }
1633
Maciej Żenczykowski9b6a9942024-09-03 16:08:35 -07001634 // 6.6 is highest version supported by Android V, so this is effectively W+ (sdk=36+)
1635 if (isKernel32Bit() && isAtLeastKernelVersion(6, 7, 0)) {
1636 ALOGE("Android platform with 32 bit kernel version >= 6.7.0 is unsupported");
1637 return 1;
1638 }
1639
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001640 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1641 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001642 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001643 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001644 }
1645
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001646 if (isAtLeastV) {
1647 bool bad = false;
1648
1649 if (!isLtsKernel()) {
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001650 ALOGW("Android V+ only supports LTS kernels.");
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001651 bad = true;
1652 }
1653
1654#define REQUIRE(maj, min, sub) \
1655 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001656 ALOGW("Android V+ requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001657 bad = true; \
1658 }
1659
1660 REQUIRE(4, 19, 236)
1661 REQUIRE(5, 4, 186)
1662 REQUIRE(5, 10, 199)
1663 REQUIRE(5, 15, 136)
1664 REQUIRE(6, 1, 57)
1665 REQUIRE(6, 6, 0)
Maciej Żenczykowski06f38e32024-12-11 07:12:59 -08001666 REQUIRE(6, 12, 0)
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001667
1668#undef REQUIRE
1669
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001670 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001671 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1672 }
1673 }
1674
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001675 /* Android 14/U should only launch on 64-bit kernels
1676 * T launches on 5.10/5.15
1677 * U launches on 5.15/6.1
1678 * So >=5.16 implies isKernel64Bit()
1679 *
1680 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1681 *
1682 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1683 * we also require 64-bit userspace.
1684 *
1685 * There are various known issues with 32-bit userspace talking to various
1686 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1687 * Some of these have userspace or kernel workarounds/hacks.
1688 * Some of them don't...
1689 * We're going to be removing the hacks.
1690 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1691 * Note: this check/enforcement only applies to *system* userspace code,
1692 * it does not affect unprivileged apps, the 32-on-64 compatibility
1693 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1694 *
1695 * Additionally the 32-bit kernel jit support is poor,
1696 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001697 * Note, however, that TV and Wear devices will continue to support 32-bit userspace
1698 * on ARM64.
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001699 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001700 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001701 // Stuff won't work reliably, but...
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001702 if (isArm() && (isTV() || isWear())) {
1703 // exempt Arm TV or Wear devices (arm32 ABI is far less problematic than x86-32)
1704 ALOGW("[Arm TV/Wear] 32-bit userspace unsupported on 6.2+ kernels.");
Maciej Żenczykowski73238632025-02-24 14:50:09 -08001705 } else if (first_api_level <= 33 /*T*/ && isArm()) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001706 // also exempt Arm devices upgrading with major kernel rev from T-
1707 // might possibly be better for them to run with a newer kernel...
1708 ALOGW("[Arm KernelUpRev] 32-bit userspace unsupported on 6.2+ kernels.");
1709 } else if (isArm()) {
1710 ALOGE("[Arm] 64-bit userspace required on 6.2+ kernels (%d).", first_api_level);
1711 return 1;
1712 } else { // x86 since RiscV cannot be 32-bit
1713 ALOGE("[x86] 64-bit userspace required on 6.2+ kernels.");
1714 return 1;
1715 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001716 }
1717
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001718 // On handheld, 6.6 is highest version supported by Android V (sdk=35), so this is for sdk=36+
1719 if (!isArm() && isUserspace32bit() && isAtLeastKernelVersion(6, 7, 0)) {
Maciej Żenczykowski21b4a052024-09-03 15:46:48 -07001720 ALOGE("64-bit userspace required on 6.7+ kernels.");
1721 return 1;
1722 }
1723
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001724 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001725 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001726 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001727 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001728 return 1;
1729 }
1730
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001731 if (runningAsRoot) {
1732 // Note: writing this proc file requires being root (always the case on V+)
1733
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001734 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1735 // but we need 0 (enabled)
1736 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1737 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1738 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001739 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001740 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001741
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001742 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001743 // Note: writing these proc files requires CAP_NET_ADMIN
1744 // and sepolicy which is only present on U+,
1745 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1746 // trigger (ie. by init itself) instead.
1747
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001748 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1749 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1750 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1751 // kernel does not have CONFIG_BPF_JIT=y)
1752 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1753 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1754 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001755
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001756 // Enable JIT kallsyms export for privileged users only
1757 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1758 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1759 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1760 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001761
1762 // Create all the pin subdirectories
1763 // (this must be done first to allow selinux_context and pin_subdir functionality,
1764 // which could otherwise fail with ENOENT during object pinning or renaming,
1765 // due to ordering issues)
1766 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001767 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001768 if (createSysFsBpfSubDir(location.prefix)) return 1;
1769 }
1770
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001771 if (isAtLeastT) {
1772 // Note: there's no actual src dir for fs_bpf_loader .o's,
1773 // so it is not listed in 'locations[].prefix'.
1774 // This is because this is primarily meant for triggering genfscon rules,
1775 // and as such this will likely always be the case.
1776 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1777 if (createSysFsBpfSubDir("loader")) return 1;
1778 }
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001779
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001780 // Load all ELF objects, create programs and maps, and pin them
1781 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001782 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001783 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001784 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1785 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1786 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1787 "problems or startup script race.");
1788 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1789 sleep(20);
1790 return 2;
1791 }
1792 }
1793
1794 int key = 1;
1795 int value = 123;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001796 unique_fd map(
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001797 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1798 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001799 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1800 return 1;
1801 }
1802
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001803 // on S we haven't created this subdir yet, but we need it for 'mainline_done' flag below
1804 if (!isAtLeastT && createSysFsBpfSubDir("netd_shared")) return 1;
1805
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001806 // leave a flag that we're done
1807 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001808
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001809 // platform bpfloader will only succeed when run as root
1810 if (!runningAsRoot) {
1811 // unreachable on U QPR3+ which always runs netbpfload as root
1812
1813 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1814 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001815 }
1816
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001817 // unreachable before U QPR3
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001818 if (exists(uprobestatsBpfLoader)) {
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001819 ALOGI("done, transferring control to uprobestatsbpfload.");
1820 const char *args[] = {
1821 uprobestatsBpfLoader,
1822 NULL,
1823 };
1824 execve(args[0], (char **)args, envp);
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001825 ALOGI("unable to execute uprobestatsbpfload, transferring control to "
1826 "platform bpfloader.");
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001827 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001828
1829 // platform BpfLoader *needs* to run as root
1830 const char * args[] = { platformBpfLoader, NULL, };
1831 execve(args[0], (char**)args, envp);
1832 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1833 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001834}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001835
1836} // namespace bpf
1837} // namespace android
1838
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001839int main(int argc, char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001840 if (android::bpf::isAtLeastT) {
1841 InitLogging(argv, &KernelLogger);
1842 } else {
1843 // S lacks the sepolicy to make non-root uid KernelLogger viable
1844 InitLogging(argv);
1845 }
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001846
1847 if (argc == 2 && !strcmp(argv[1], "done")) {
1848 // we're being re-exec'ed from platform bpfloader to 'finalize' things
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001849 if (!SetProperty("bpf.progs_loaded", "1")) {
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001850 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1851 return 125;
1852 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001853 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001854 return 0;
1855 }
1856
1857 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001858}