blob: c61aec34a19e7347d59cd955733c916e2e487ed5 [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
Elliott Hughescd7f3bf2025-05-22 16:37:33 -040019#include <algorithm>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070020#include <arpa/inet.h>
Motomu Utsumib3d3c2a2025-03-18 15:06:34 +090021#include <bpf/btf.h>
Motomu Utsumia7693582025-02-05 17:40:08 +090022#include <bpf/libbpf.h>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070023#include <dirent.h>
24#include <elf.h>
25#include <errno.h>
26#include <error.h>
27#include <fcntl.h>
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070028#include <fstream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070029#include <inttypes.h>
30#include <iostream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070031#include <linux/unistd.h>
32#include <log/log.h>
33#include <net/if.h>
34#include <optional>
35#include <stdint.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <string>
40#include <sys/mman.h>
41#include <sys/socket.h>
42#include <sys/stat.h>
43#include <sys/types.h>
44#include <sys/utsname.h>
45#include <sys/wait.h>
46#include <sysexits.h>
47#include <unistd.h>
48#include <unordered_map>
49#include <vector>
50
51#include <android-base/cmsg.h>
52#include <android-base/file.h>
53#include <android-base/logging.h>
54#include <android-base/macros.h>
55#include <android-base/properties.h>
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +090056#include <android-base/scopeguard.h>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070057#include <android-base/stringprintf.h>
58#include <android-base/strings.h>
59#include <android-base/unique_fd.h>
60#include <android/api-level.h>
61
62#include "BpfSyscallWrappers.h"
63#include "bpf/BpfUtils.h"
Maciej Żenczykowskid6028352024-08-19 15:20:04 -070064#include "bpf_map_def.h"
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070065
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +000066// The following matches bpf_helpers.h, which is only for inclusion in bpf code
Maciej Żenczykowski8c097782025-03-04 13:11:56 -080067#define BPFLOADER_MAINLINE_S_VERSION 42u
Maciej Żenczykowski199fd352025-02-13 15:17:08 -080068#define BPFLOADER_MAINLINE_25Q2_VERSION 47u
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +000069
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070070using android::base::EndsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070071using android::base::GetIntProperty;
72using android::base::GetProperty;
73using android::base::InitLogging;
74using android::base::KernelLogger;
75using android::base::SetProperty;
76using android::base::Split;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070077using android::base::StartsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070078using android::base::Tokenize;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070079using android::base::unique_fd;
80using std::ifstream;
81using std::ios;
82using std::optional;
83using std::string;
84using std::vector;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070085
86namespace android {
87namespace bpf {
88
89// Bpf programs may specify per-program & per-map selinux_context and pin_subdir.
90//
91// The BpfLoader needs to convert these bpf.o specified strings into an enum
92// for internal use (to check that valid values were specified for the specific
93// location of the bpf.o file).
94//
95// It also needs to map selinux_context's into pin_subdir's.
96// This is because of how selinux_context is actually implemented via pin+rename.
97//
98// Thus 'domain' enumerates all selinux_context's/pin_subdir's that the BpfLoader
99// is aware of. Thus there currently needs to be a 1:1 mapping between the two.
100//
101enum class domain : int {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700102 unspecified = 0, // means just use the default for that specific pin location
103 tethering, // (S+) fs_bpf_tethering /sys/fs/bpf/tethering
104 net_private, // (T+) fs_bpf_net_private /sys/fs/bpf/net_private
105 net_shared, // (T+) fs_bpf_net_shared /sys/fs/bpf/net_shared
106 netd_readonly, // (T+) fs_bpf_netd_readonly /sys/fs/bpf/netd_readonly
107 netd_shared, // (T+) fs_bpf_netd_shared /sys/fs/bpf/netd_shared
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700108 loader, // (U+) fs_bpf_loader /sys/fs/bpf/loader
109 // on T due to lack of sepolicy/genfscon rules it behaves simply as 'fs_bpf'
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700110};
111
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700112static constexpr domain AllDomains[] = {
113 domain::unspecified,
114 domain::tethering,
115 domain::net_private,
116 domain::net_shared,
117 domain::netd_readonly,
118 domain::netd_shared,
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700119 domain::loader,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700120};
121
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700122static constexpr bool specified(domain d) {
123 return d != domain::unspecified;
124}
125
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700126// Returns the build type string (from ro.build.type).
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700127const std::string& getBuildType() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700128 static std::string t = GetProperty("ro.build.type", "unknown");
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700129 return t;
130}
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700131
132// The following functions classify the 3 Android build types.
133inline bool isEng() {
134 return getBuildType() == "eng";
135}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700136
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700137inline bool isUser() {
138 return getBuildType() == "user";
139}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700140
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700141inline bool isUserdebug() {
142 return getBuildType() == "userdebug";
143}
144
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700145#define BPF_FS_PATH "/sys/fs/bpf/"
146
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700147static unsigned int page_size = static_cast<unsigned int>(getpagesize());
148
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700149constexpr const char* lookupSelinuxContext(const domain d) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700150 switch (d) {
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700151 case domain::unspecified: return "";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700152 case domain::tethering: return "fs_bpf_tethering";
153 case domain::net_private: return "fs_bpf_net_private";
154 case domain::net_shared: return "fs_bpf_net_shared";
155 case domain::netd_readonly: return "fs_bpf_netd_readonly";
156 case domain::netd_shared: return "fs_bpf_netd_shared";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700157 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700158 }
159}
160
161domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
162 for (domain d : AllDomains) {
163 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
164 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
165 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
166 }
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700167 ALOGE("unrecognized selinux_context '%-32s'", s);
168 // Note: we *can* just abort() here as we only load bpf .o files shipped
169 // in the same mainline module / apex as NetBpfLoad itself.
170 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700171}
172
173constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
174 switch (d) {
175 case domain::unspecified: return unspecified;
176 case domain::tethering: return "tethering/";
177 case domain::net_private: return "net_private/";
178 case domain::net_shared: return "net_shared/";
179 case domain::netd_readonly: return "netd_readonly/";
180 case domain::netd_shared: return "netd_shared/";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700181 case domain::loader: return "loader/";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700182 }
183};
184
185domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
186 for (domain d : AllDomains) {
187 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
188 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
189 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
190 }
191 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700192 // Note: we *can* just abort() here as we only load bpf .o files shipped
193 // in the same mainline module / apex as NetBpfLoad itself.
194 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700195}
196
197static string pathToObjName(const string& path) {
198 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700199 string filename = Split(path, "/").back();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700200 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
201 string name = filename.substr(0, filename.find_last_of('.'));
202 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
203 // this can be used to provide duplicate programs (mux based on the bpfloader version)
204 return name.substr(0, name.find_last_of('@'));
205}
206
207typedef struct {
208 const char* name;
209 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000210 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700211} sectionType;
212
213/*
214 * Map section name prefixes to program types, the section name will be:
215 * SECTION(<prefix>/<name-of-program>)
216 * For example:
217 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
218 * is the name of the program, and tracepoint is the type.
219 *
220 * However, be aware that you should not be directly using the SECTION() macro.
Maciej Żenczykowski3a085152024-09-18 23:45:52 +0000221 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE macros.
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700222 *
223 * Programs shipped inside the tethering apex should be limited to networking stuff,
224 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
225 * since they are less stable abi/api and may conflict with platform uses of bpf.
226 */
227sectionType sectionNameTypes[] = {
228 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
229 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000230 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
231 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700232 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
233 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
234 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
235 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
236 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
237 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
238 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700239 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
240 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
241 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
242 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000243 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
244 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700245 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
246 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
247 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000248 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700249 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
250 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000251 {"xdp/", BPF_PROG_TYPE_XDP},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700252};
253
254typedef struct {
255 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000256 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700257 string name;
258 vector<char> data;
259 vector<char> rel_data;
260 optional<struct bpf_prog_def> prog_def;
261
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000262 unique_fd prog_fd; // fd after loading
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700263} codeSection;
264
265static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
266 elfFile.seekg(0);
267 if (elfFile.fail()) return -1;
268
269 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
270
271 return 0;
272}
273
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000274// Reads all section header tables into an Shdr array
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700275static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
276 Elf64_Ehdr eh;
277 int ret = 0;
278
279 ret = readElfHeader(elfFile, &eh);
280 if (ret) return ret;
281
282 elfFile.seekg(eh.e_shoff);
283 if (elfFile.fail()) return -1;
284
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000285 // Read shdr table entries
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700286 shTable.resize(eh.e_shnum);
287
288 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
289
290 return 0;
291}
292
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000293// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700294static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
295 vector<Elf64_Shdr> shTable;
296 int ret = readSectionHeadersAll(elfFile, shTable);
297 if (ret) return ret;
298
299 elfFile.seekg(shTable[id].sh_offset);
300 if (elfFile.fail()) return -1;
301
302 sec.resize(shTable[id].sh_size);
303 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
304
305 return 0;
306}
307
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000308// Read whole section header string table
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700309static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
310 Elf64_Ehdr eh;
311 int ret = readElfHeader(elfFile, &eh);
312 if (ret) return ret;
313
314 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
315 if (ret) return ret;
316
317 return 0;
318}
319
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000320// Get name from offset in strtab
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700321static int getSymName(ifstream& elfFile, int nameOff, string& name) {
322 int ret;
323 vector<char> secStrTab;
324
325 ret = readSectionHeaderStrtab(elfFile, secStrTab);
326 if (ret) return ret;
327
328 if (nameOff >= (int)secStrTab.size()) return -1;
329
330 name = string((char*)secStrTab.data() + nameOff);
331 return 0;
332}
333
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000334// Reads a full section by name - example to get the GPL license
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700335static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
336 vector<char> secStrTab;
337 vector<Elf64_Shdr> shTable;
338 int ret;
339
340 ret = readSectionHeadersAll(elfFile, shTable);
341 if (ret) return ret;
342
343 ret = readSectionHeaderStrtab(elfFile, secStrTab);
344 if (ret) return ret;
345
346 for (int i = 0; i < (int)shTable.size(); i++) {
347 char* secname = secStrTab.data() + shTable[i].sh_name;
348 if (!secname) continue;
349
350 if (!strcmp(secname, name)) {
351 vector<char> dataTmp;
352 dataTmp.resize(shTable[i].sh_size);
353
354 elfFile.seekg(shTable[i].sh_offset);
355 if (elfFile.fail()) return -1;
356
357 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
358
359 data = dataTmp;
360 return 0;
361 }
362 }
363 return -2;
364}
365
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700366unsigned int readSectionUint(const char* name, ifstream& elfFile) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700367 vector<char> theBytes;
368 int ret = readSectionByName(name, elfFile, theBytes);
369 if (ret) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700370 ALOGE("Couldn't find section %s.", name);
371 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700372 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700373 ALOGE("Section %s is too short.", name);
374 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700375 } else {
376 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
377 unsigned int value = static_cast<unsigned char>(theBytes[3]);
378 value <<= 8;
379 value += static_cast<unsigned char>(theBytes[2]);
380 value <<= 8;
381 value += static_cast<unsigned char>(theBytes[1]);
382 value <<= 8;
383 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000384 ALOGD("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700385 return value;
386 }
387}
388
389static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
390 int ret;
391 vector<Elf64_Shdr> shTable;
392
393 ret = readSectionHeadersAll(elfFile, shTable);
394 if (ret) return ret;
395
396 for (int i = 0; i < (int)shTable.size(); i++) {
397 if ((int)shTable[i].sh_type != type) continue;
398
399 vector<char> dataTmp;
400 dataTmp.resize(shTable[i].sh_size);
401
402 elfFile.seekg(shTable[i].sh_offset);
403 if (elfFile.fail()) return -1;
404
405 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
406
407 data = dataTmp;
408 return 0;
409 }
410 return -2;
411}
412
413static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
414 return (a.st_value < b.st_value);
415}
416
417static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
418 int ret, numElems;
419 Elf64_Sym* buf;
420 vector<char> secData;
421
422 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
423 if (ret) return ret;
424
425 buf = (Elf64_Sym*)secData.data();
426 numElems = (secData.size() / sizeof(Elf64_Sym));
427 data.assign(buf, buf + numElems);
428
429 if (sort) std::sort(data.begin(), data.end(), symCompare);
430 return 0;
431}
432
433static enum bpf_prog_type getSectionType(string& name) {
434 for (auto& snt : sectionNameTypes)
435 if (StartsWith(name, snt.name)) return snt.type;
436
437 return BPF_PROG_TYPE_UNSPEC;
438}
439
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700440static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700441 vector<char> pdData;
442 int ret = readSectionByName("progs", elfFile, pdData);
443 if (ret) return ret;
444
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700445 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700446 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700447 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700448 return -1;
449 };
450
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700451 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700452
453 const char* dataPtr = pdData.data();
454 for (auto& p : pd) {
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700455 // Copy the structure from the ELF file and move to the next one.
456 memcpy(&p, dataPtr, sizeof(struct bpf_prog_def));
457 dataPtr += sizeof(struct bpf_prog_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700458 }
459 return 0;
460}
461
462static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
463 optional<unsigned> symbolType = std::nullopt) {
464 int ret;
465 string name;
466 vector<Elf64_Sym> symtab;
467 vector<Elf64_Shdr> shTable;
468
469 ret = readSymTab(elfFile, 1 /* sort */, symtab);
470 if (ret) return ret;
471
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000472 // Get index of section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700473 ret = readSectionHeadersAll(elfFile, shTable);
474 if (ret) return ret;
475
476 int sec_idx = -1;
477 for (int i = 0; i < (int)shTable.size(); i++) {
478 ret = getSymName(elfFile, shTable[i].sh_name, name);
479 if (ret) return ret;
480
481 if (!name.compare(sectionName)) {
482 sec_idx = i;
483 break;
484 }
485 }
486
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000487 // No section found with matching name
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700488 if (sec_idx == -1) {
489 ALOGW("No %s section could be found in elf object", sectionName.c_str());
490 return -1;
491 }
492
493 for (int i = 0; i < (int)symtab.size(); i++) {
494 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
495
496 if (symtab[i].st_shndx == sec_idx) {
497 string s;
498 ret = getSymName(elfFile, symtab[i].st_name, s);
499 if (ret) return ret;
500 names.push_back(s);
501 }
502 }
503
504 return 0;
505}
506
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000507// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700508static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700509 vector<Elf64_Shdr> shTable;
510 int entries, ret = 0;
511
512 ret = readSectionHeadersAll(elfFile, shTable);
513 if (ret) return ret;
514 entries = shTable.size();
515
516 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700517 ret = readProgDefs(elfFile, pd);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700518 if (ret) return ret;
519 vector<string> progDefNames;
520 ret = getSectionSymNames(elfFile, "progs", progDefNames);
521 if (!pd.empty() && ret) return ret;
522
523 for (int i = 0; i < entries; i++) {
524 string name;
525 codeSection cs_temp;
526 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
527
528 ret = getSymName(elfFile, shTable[i].sh_name, name);
529 if (ret) return ret;
530
531 enum bpf_prog_type ptype = getSectionType(name);
532
533 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
534
535 // This must be done before '/' is replaced with '_'.
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000536 for (auto& snt : sectionNameTypes)
537 if (StartsWith(name, snt.name)) cs_temp.attach_type = snt.attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700538
539 string oldName = name;
540
541 // convert all slashes to underscores
542 std::replace(name.begin(), name.end(), '/', '_');
543
544 cs_temp.type = ptype;
545 cs_temp.name = name;
546
547 ret = readSectionByIdx(elfFile, i, cs_temp.data);
548 if (ret) return ret;
549 ALOGV("Loaded code section %d (%s)", i, name.c_str());
550
551 vector<string> csSymNames;
552 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
553 if (ret || !csSymNames.size()) return ret;
Motomu Utsumi62b1c882025-03-21 15:13:00 +0900554 for (size_t j = 0; j < progDefNames.size(); ++j) {
555 if (!progDefNames[j].compare(csSymNames[0] + "_def")) {
556 cs_temp.prog_def = pd[j];
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700557 break;
558 }
559 }
560
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000561 // Check for rel section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700562 if (cs_temp.data.size() > 0 && i < entries) {
563 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
564 if (ret) return ret;
565
566 if (name == (".rel" + oldName)) {
567 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
568 if (ret) return ret;
569 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
570 }
571 }
572
573 if (cs_temp.data.size() > 0) {
574 cs.push_back(std::move(cs_temp));
575 ALOGV("Adding section %d to cs list", i);
576 }
577 }
578 return 0;
579}
580
581static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
582 vector<Elf64_Sym> symtab;
583 int ret = 0;
584
585 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
586 if (ret) return ret;
587
588 if (index >= (int)symtab.size()) return -1;
589
590 return getSymName(elfFile, symtab[index].st_name, name);
591}
592
593static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
594 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
595 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
596 // so on 4.9-T kernels just pretend the map matches our expectations.
597 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
598 // This is because the primary failure mode we're trying to detect here
599 // is either a source code misconfiguration (which is likely kernel independent)
600 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
601 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
602
603 // Assuming fd is a valid Bpf Map file descriptor then
604 // all the following should always succeed on a 4.14+ kernel.
605 // If they somehow do fail, they'll return -1 (and set errno),
606 // which should then cause (among others) a key_size mismatch.
607 int fd_type = bpfGetFdMapType(fd);
608 int fd_key_size = bpfGetFdKeySize(fd);
609 int fd_value_size = bpfGetFdValueSize(fd);
610 int fd_max_entries = bpfGetFdMaxEntries(fd);
611 int fd_map_flags = bpfGetFdMapFlags(fd);
612
613 // DEVMAPs are readonly from the bpf program side's point of view, as such
614 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
615 int desired_map_flags = (int)mapDef.map_flags;
616 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
617 desired_map_flags |= BPF_F_RDONLY_PROG;
618
619 // The .h file enforces that this is a power of two, and page size will
620 // also always be a power of two, so this logic is actually enough to
621 // force it to be a multiple of the page size, as required by the kernel.
622 unsigned int desired_max_entries = mapDef.max_entries;
623 if (type == BPF_MAP_TYPE_RINGBUF) {
624 if (desired_max_entries < page_size) desired_max_entries = page_size;
625 }
626
627 // The following checks should *never* trigger, if one of them somehow does,
628 // it probably means a bpf .o file has been changed/replaced at runtime
629 // and bpfloader was manually rerun (normally it should only run *once*
630 // early during the boot process).
631 // Another possibility is that something is misconfigured in the code:
632 // most likely a shared map is declared twice differently.
633 // But such a change should never be checked into the source tree...
634 if ((fd_type == type) &&
635 (fd_key_size == (int)mapDef.key_size) &&
636 (fd_value_size == (int)mapDef.value_size) &&
637 (fd_max_entries == (int)desired_max_entries) &&
638 (fd_map_flags == desired_map_flags)) {
639 return true;
640 }
641
Maciej Żenczykowski4b3937b2025-05-29 01:24:47 -0700642 ALOGE("bpf map name %s mismatch: desired/found (errno: %d): "
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700643 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
Maciej Żenczykowski4b3937b2025-05-29 01:24:47 -0700644 mapName.c_str(), errno, type, fd_type, mapDef.key_size, fd_key_size,
645 mapDef.value_size, fd_value_size, mapDef.max_entries, fd_max_entries,
646 desired_map_flags, fd_map_flags);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700647 return false;
648}
649
Motomu Utsumib3d3c2a2025-03-18 15:06:34 +0900650static int setBtfDatasecSize(ifstream &elfFile, struct btf *btf,
651 struct btf_type *bt) {
652 const char *name = btf__name_by_offset(btf, bt->name_off);
653 if (!name) {
654 ALOGE("Couldn't resolve section name, errno: %d", errno);
655 return -errno;
656 }
657
658 vector<char> data;
659 int ret = readSectionByName(name, elfFile, data);
660 if (ret) {
661 ALOGE("Couldn't read section %s, ret: %d", name, ret);
662 return ret;
663 }
664 bt->size = data.size();
665 return 0;
666}
667
Motomu Utsumiefe33312025-03-18 15:08:15 +0900668static int getSymOffsetByName(ifstream &elfFile, const char *name, int *off) {
669 vector<Elf64_Sym> symtab;
670 int ret = readSymTab(elfFile, 1 /* sort */, symtab);
671 if (ret) return ret;
672 for (int i = 0; i < (int)symtab.size(); i++) {
673 string s;
674 ret = getSymName(elfFile, symtab[i].st_name, s);
675 if (ret) continue;
676 if (!strcmp(s.c_str(), name)) {
677 *off = symtab[i].st_value;
678 return 0;
679 }
680 }
681 return -1;
682}
683
684static int setBtfVarOffset(ifstream &elfFile, struct btf *btf,
685 struct btf_type *datasecBt) {
686 int i, vars = btf_vlen(datasecBt);
687 struct btf_var_secinfo *vsi;
688 const char *datasecName = btf__name_by_offset(btf, datasecBt->name_off);
689 if (!datasecName) {
690 ALOGE("Couldn't resolve section name, errno: %d", errno);
691 return -errno;
692 }
693
694 for (i = 0, vsi = btf_var_secinfos(datasecBt); i < vars; i++, vsi++) {
695 const struct btf_type *varBt = btf__type_by_id(btf, vsi->type);
696 if (!varBt || !btf_is_var(varBt)) {
697 ALOGE("Found non VAR kind btf_type, section: %s id: %d", datasecName,
698 vsi->type);
699 return -1;
700 }
701
702 const struct btf_var *var = btf_var(varBt);
703 if (var->linkage == BTF_VAR_STATIC) continue;
704
705 const char *varName = btf__name_by_offset(btf, varBt->name_off);
706 if (!varName) {
707 ALOGE("Failed to resolve var name, section: %s", datasecName);
708 return -1;
709 }
710
711 int off;
712 int ret = getSymOffsetByName(elfFile, varName, &off);
713 if (ret) {
714 ALOGE("No offset found in symbol table, section: %s, var: %s, ret: %d",
715 datasecName, varName, ret);
716 return ret;
717 }
718 vsi->offset = off;
719 }
720 return 0;
721}
722
Motomu Utsumi21536e52025-03-18 15:09:27 +0900723static int loadBtf(ifstream &elfFile, struct btf *btf) {
724 int ret;
725 for (unsigned int i = 1; i < btf__type_cnt(btf); ++i) {
726 struct btf_type *bt = (struct btf_type *)btf__type_by_id(btf, i);
727 if (!btf_is_datasec(bt)) continue;
728 ret = setBtfDatasecSize(elfFile, btf, bt);
729 if (ret) return ret;
730 ret = setBtfVarOffset(elfFile, btf, bt);
731 if (ret) return ret;
732 }
733
734 ret = btf__load_into_kernel(btf);
735 if (ret) {
736 if (errno != EINVAL) {
737 ALOGE("btf__load_into_kernel failed, errno: %d", errno);
738 return ret;
739 };
740 // For BTF_KIND_FUNC, newer kernels can read the BTF_INFO_VLEN bits of
741 // struct btf_type to distinguish static vs. global vs. extern
742 // functions, but older kernels enforce that only the BTF_INFO_KIND bits
743 // can be set. Retry with non-BTF_INFO_KIND bits zeroed out to handle
744 // this case.
745 for (unsigned int i = 1; i < btf__type_cnt(btf); ++i) {
746 struct btf_type *bt = (struct btf_type *)btf__type_by_id(btf, i);
747 if (btf_is_func(bt)) {
748 bt->info = (BTF_INFO_KIND(bt->info)) << 24;
749 }
750 }
751 ret = btf__load_into_kernel(btf);
752 if (ret) {
753 ALOGE("btf__load_into_kernel retry failed, errno: %d", errno);
754 return ret;
755 };
756 }
757 return 0;
758}
759
Motomu Utsumi59b20992025-03-18 15:10:19 +0900760int getKeyValueTids(const struct btf *btf, const char *mapName,
761 uint32_t expectedKeySize, uint32_t expectedValueSize,
762 uint32_t *keyTypeId, uint32_t *valueTypeId) {
763 const struct btf_type *kvBt;
764 const struct btf_member *key, *value;
765 const size_t max_name = 256;
766 char kvTypeName[max_name];
767 int64_t keySize, valueSize;
Motomu Utsumia6ffae22025-03-21 11:00:10 +0900768 int32_t kvId;
Motomu Utsumi59b20992025-03-18 15:10:19 +0900769
770 if (snprintf(kvTypeName, max_name, "____btf_map_%s", mapName) == max_name) {
771 ALOGE("____btf_map_%s is too long", mapName);
772 return -1;
773 }
774
775 kvId = btf__find_by_name(btf, kvTypeName);
776 if (kvId < 0) {
777 ALOGE("section not found, map: %s typeName: %s", mapName, kvTypeName);
778 return -1;
779 }
780
781 kvBt = btf__type_by_id(btf, kvId);
782 if (!kvBt) {
783 ALOGE("Couldn't find BTF type, map: %s id: %u", mapName, kvId);
784 return -1;
785 }
786
787 if (!btf_is_struct(kvBt) || btf_vlen(kvBt) < 2) {
788 ALOGE("Non Struct kind or invalid vlen, map: %s id: %u", mapName, kvId);
789 return -1;
790 }
791
792 key = btf_members(kvBt);
793 value = key + 1;
794
795 keySize = btf__resolve_size(btf, key->type);
796 if (keySize < 0) {
797 ALOGE("Couldn't get key size, map: %s errno: %d", mapName, errno);
798 return -1;
799 }
800
801 valueSize = btf__resolve_size(btf, value->type);
802 if (valueSize < 0) {
803 ALOGE("Couldn't get value size, map: %s errno: %d", mapName, errno);
804 return -1;
805 }
806
807 if (expectedKeySize != keySize || expectedValueSize != valueSize) {
808 ALOGE("Key value size mismatch, map: %s key size: %d expected key size: "
809 "%d value size: %d expected value size: %d",
810 mapName, (uint32_t)keySize, expectedKeySize, (uint32_t)valueSize,
811 expectedValueSize);
812 return -1;
813 }
814
815 *keyTypeId = key->type;
816 *valueTypeId = value->type;
817
818 return 0;
819}
820
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900821static bool isBtfSupported(enum bpf_map_type type) {
822 return type != BPF_MAP_TYPE_DEVMAP_HASH && type != BPF_MAP_TYPE_RINGBUF;
823}
824
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700825static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700826 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700827 int ret;
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900828 vector<char> mdData, btfData;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700829 vector<struct bpf_map_def> md;
830 vector<string> mapNames;
831 string objName = pathToObjName(string(elfPath));
832
833 ret = readSectionByName("maps", elfFile, mdData);
834 if (ret == -2) return 0; // no maps to read
835 if (ret) return ret;
836
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700837 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700838 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700839 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700840 return -1;
841 };
842
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700843 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700844
845 const char* dataPtr = mdData.data();
846 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700847 // Copy the structure from the ELF file and move to the next one.
848 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
849 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700850 }
851
852 ret = getSectionSymNames(elfFile, "maps", mapNames);
853 if (ret) return ret;
854
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900855 struct btf *btf = NULL;
Patrick Rohr03b97432025-04-17 08:37:01 -0700856 auto btfGuard = base::make_scope_guard([&btf] { if (btf) btf__free(btf); });
Motomu Utsumi861f11c2025-03-21 15:29:00 +0900857 if (isAtLeastKernelVersion(5, 10, 0)) {
858 // Untested on Linux Kernel 5.4, but likely compatible.
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900859 // On Linux Kernels older than 4.18 BPF_BTF_LOAD command doesn't exist.
Motomu Utsumi861f11c2025-03-21 15:29:00 +0900860 // On Linux Kernels older than 5.2 BTF_KIND_VAR and BTF_KIND_DATASEC don't exist.
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900861 ret = readSectionByName(".BTF", elfFile, btfData);
862 if (ret) {
863 ALOGE("Failed to read .BTF section, ret:%d", ret);
864 return ret;
865 }
Motomu Utsumi62b1c882025-03-21 15:13:00 +0900866 btf = btf__new(btfData.data(), btfData.size());
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900867 if (btf == NULL) {
868 ALOGE("btf__new failed, errno: %d", errno);
869 return -errno;
870 }
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900871
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900872 ret = loadBtf(elfFile, btf);
873 if (ret) return ret;
874 }
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900875
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700876 unsigned kvers = kernelVersion();
877
878 for (int i = 0; i < (int)mapNames.size(); i++) {
879 if (md[i].zero != 0) abort();
880
881 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000882 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700883 md[i].bpfloader_min_ver);
884 mapFds.push_back(unique_fd());
885 continue;
886 }
887
888 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000889 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700890 md[i].bpfloader_max_ver);
891 mapFds.push_back(unique_fd());
892 continue;
893 }
894
895 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000896 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700897 mapNames[i].c_str(), kvers, md[i].min_kver);
898 mapFds.push_back(unique_fd());
899 continue;
900 }
901
902 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000903 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700904 mapNames[i].c_str(), kvers, md[i].max_kver);
905 mapFds.push_back(unique_fd());
906 continue;
907 }
908
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700909 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski87019832025-02-03 22:04:26 -0800910 if (type == BPF_MAP_TYPE_LPM_TRIE && !isAtLeastKernelVersion(4, 14, 0)) {
911 // On Linux Kernels older than 4.14 this map type doesn't exist - autoskip.
912 ALOGD("skipping LPM_TRIE map %s - requires kver 4.14+", mapNames[i].c_str());
913 mapFds.push_back(unique_fd());
914 continue;
915 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700916 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
917 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
918 // of be approximated: ARRAY has the same userspace api, though it is not usable
919 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
920 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
921 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
922 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
923 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
924 type = BPF_MAP_TYPE_ARRAY;
925 }
926 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
927 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
928 // of be approximated: HASH has the same userspace visible api.
929 // However it cannot be used by ebpf programs in the same way.
930 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
931 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
932 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
933 // programs as being 5.4+...
934 type = BPF_MAP_TYPE_HASH;
935 }
936
937 // The .h file enforces that this is a power of two, and page size will
938 // also always be a power of two, so this logic is actually enough to
939 // force it to be a multiple of the page size, as required by the kernel.
940 unsigned int max_entries = md[i].max_entries;
941 if (type == BPF_MAP_TYPE_RINGBUF) {
942 if (max_entries < page_size) max_entries = page_size;
943 }
944
945 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
946 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000947 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700948 md[i].selinux_context, static_cast<int>(selinux_context),
949 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
950 }
951
952 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700953 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000954 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700955 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
Maciej Żenczykowski10979ef2025-05-20 06:38:16 -0700956 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700957 }
958
959 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
960 // except that maps shared across .o's have empty <objName>
961 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
962 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
963 (md[i].shared ? "" : objName) + "_" + mapNames[i];
964 bool reuse = false;
965 unique_fd fd;
966 int saved_errno;
967
968 if (access(mapPinLoc.c_str(), F_OK) == 0) {
969 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
970 saved_errno = errno;
971 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
972 reuse = true;
Maciej Żenczykowskib71cd4f2025-05-20 06:41:01 -0700973 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700974 } else {
975 union bpf_attr req = {
976 .map_type = type,
977 .key_size = md[i].key_size,
978 .value_size = md[i].value_size,
979 .max_entries = max_entries,
Maciej Żenczykowskic1a9f4a2025-01-20 12:09:13 -0800980 .map_flags = md[i].map_flags,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700981 };
982 if (isAtLeastKernelVersion(4, 15, 0))
983 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900984
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900985 bool haveBtf = btf && isBtfSupported(type);
Maciej Żenczykowski9fef9302025-03-18 20:09:34 -0700986 if (haveBtf) {
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900987 uint32_t kTid, vTid;
988 ret = getKeyValueTids(btf, mapNames[i].c_str(), md[i].key_size,
989 md[i].value_size, &kTid, &vTid);
990 if (ret) return ret;
991 req.btf_fd = btf__fd(btf);
992 req.btf_key_type_id = kTid;
993 req.btf_value_type_id = vTid;
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900994 }
995
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700996 fd.reset(bpf(BPF_MAP_CREATE, req));
997 saved_errno = errno;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -0700998 if (fd.ok()) {
Maciej Żenczykowski9fef9302025-03-18 20:09:34 -0700999 ALOGD("bpf_create_map[%s] btf:%d -> %d",
1000 mapNames[i].c_str(), haveBtf, fd.get());
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -07001001 } else {
Maciej Żenczykowski9fef9302025-03-18 20:09:34 -07001002 ALOGE("bpf_create_map[%s] btf:%d -> %d errno:%d",
1003 mapNames[i].c_str(), haveBtf, fd.get(), saved_errno);
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -07001004 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001005 }
1006
1007 if (!fd.ok()) return -saved_errno;
1008
1009 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
1010 // safety (since reuse code path is rare) run these checks even if we just created it.
1011 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
1012 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
1013
1014 if (!reuse) {
1015 if (specified(selinux_context)) {
1016 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1017 "tmp_map_" + objName + "_" + mapNames[i];
1018 ret = bpfFdPin(fd, createLoc.c_str());
1019 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001020 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001021 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1022 return -err;
1023 }
1024 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1025 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
1026 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001027 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001028 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
1029 err, strerror(err));
1030 return -err;
1031 }
1032 } else {
1033 ret = bpfFdPin(fd, mapPinLoc.c_str());
1034 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001035 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001036 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
1037 return -err;
1038 }
1039 }
1040 ret = chmod(mapPinLoc.c_str(), md[i].mode);
1041 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001042 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001043 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
1044 strerror(err));
1045 return -err;
1046 }
1047 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
1048 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001049 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001050 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
1051 ret, err, strerror(err));
1052 return -err;
1053 }
1054 }
1055
Maciej Żenczykowskia003ace2025-02-13 16:08:18 -08001056 if (isAtLeastKernelVersion(4, 14, 0)) {
1057 int mapId = bpfGetFdMapId(fd);
1058 if (mapId == -1) {
1059 const int err = errno;
1060 ALOGE("bpfGetFdMapId failed, errno: %d", err);
1061 return -err;
1062 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001063 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
1064 }
1065
1066 mapFds.push_back(std::move(fd));
1067 }
1068
1069 return ret;
1070}
1071
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001072static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
1073 int insnIndex;
1074 struct bpf_insn *insn, *insns;
1075
1076 insns = (struct bpf_insn*)(insnsPtr);
1077
1078 insnIndex = offset / sizeof(struct bpf_insn);
1079 insn = &insns[insnIndex];
1080
1081 // Occasionally might be useful for relocation debugging, but pretty spammy
1082 if (0) {
1083 ALOGV("applying relo to instruction at byte offset: %llu, "
1084 "insn offset %d, insn %llx",
1085 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
1086 }
1087
1088 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001089 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001090 return;
1091 }
1092
1093 insn->imm = fd;
1094 insn->src_reg = BPF_PSEUDO_MAP_FD;
1095}
1096
1097static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
1098 vector<string> mapNames;
1099
1100 int ret = getSectionSymNames(elfFile, "maps", mapNames);
1101 if (ret) return;
1102
1103 for (int k = 0; k != (int)cs.size(); k++) {
1104 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
1105 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
1106
1107 for (int i = 0; i < n_rel; i++) {
1108 int symIndex = ELF64_R_SYM(rel[i].r_info);
1109 string symName;
1110
1111 ret = getSymNameByIdx(elfFile, symIndex, symName);
1112 if (ret) return;
1113
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +00001114 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001115 for (int j = 0; j < (int)mapNames.size(); j++) {
1116 if (!mapNames[j].compare(symName)) {
1117 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
1118 break;
1119 }
1120 }
1121 }
1122 }
1123}
1124
1125static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
1126 const char* prefix, const unsigned int bpfloader_ver) {
1127 unsigned kvers = kernelVersion();
1128
1129 if (!kvers) {
1130 ALOGE("unable to get kernel version");
1131 return -EINVAL;
1132 }
1133
1134 string objName = pathToObjName(string(elfPath));
1135
1136 for (int i = 0; i < (int)cs.size(); i++) {
1137 unique_fd& fd = cs[i].prog_fd;
1138 int ret;
1139 string name = cs[i].name;
1140
1141 if (!cs[i].prog_def.has_value()) {
1142 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
1143 return -EINVAL;
1144 }
1145
1146 unsigned min_kver = cs[i].prog_def->min_kver;
1147 unsigned max_kver = cs[i].prog_def->max_kver;
1148 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1149 max_kver, kvers);
1150 if (kvers < min_kver) continue;
1151 if (kvers >= max_kver) continue;
1152
1153 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1154 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1155 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1156 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001157
1158 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
1159 bpfMinVer, bpfMaxVer);
1160 if (bpfloader_ver < bpfMinVer) continue;
1161 if (bpfloader_ver >= bpfMaxVer) continue;
1162
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001163 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001164 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001165 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
1166 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1167 }
1168
1169 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001170 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001171 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
1172 lookupPinSubdir(pin_subdir));
Maciej Żenczykowski10979ef2025-05-20 06:38:16 -07001173 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001174 }
1175
1176 // strip any potential $foo suffix
1177 // this can be used to provide duplicate programs
1178 // conditionally loaded based on running kernel version
1179 name = name.substr(0, name.find_last_of('$'));
1180
1181 bool reuse = false;
1182 // Format of pin location is
1183 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1184 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1185 objName + '_' + string(name);
1186 if (access(progPinLoc.c_str(), F_OK) == 0) {
1187 fd.reset(retrieveProgram(progPinLoc.c_str()));
1188 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001189 !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001190 reuse = true;
1191 } else {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001192 static char log_buf[1 << 20]; // 1 MiB logging buffer
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001193
1194 union bpf_attr req = {
1195 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001196 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001197 .insns = ptr_to_u64(cs[i].data.data()),
1198 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001199 .log_level = 1,
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001200 .log_size = sizeof(log_buf),
1201 .log_buf = ptr_to_u64(log_buf),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001202 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001203 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001204 };
1205 if (isAtLeastKernelVersion(4, 15, 0))
1206 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1207 fd.reset(bpf(BPF_PROG_LOAD, req));
1208
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001209 // Kernel should have NULL terminated the log buffer, but force it anyway for safety
1210 log_buf[sizeof(log_buf) - 1] = 0;
1211
1212 // Strip out final newline if present
1213 int log_chars = strlen(log_buf);
1214 if (log_chars && log_buf[log_chars - 1] == '\n') log_buf[--log_chars] = 0;
1215
1216 bool log_oneline = !strchr(log_buf, '\n');
1217
1218 ALOGD("BPF_PROG_LOAD call for %s (%s) returned '%s' fd: %d (%s)", elfPath,
1219 cs[i].name.c_str(), log_oneline ? log_buf : "{multiline}",
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001220 fd.get(), !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001221
1222 if (!fd.ok()) {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001223 // kernel NULL terminates log_buf, so this checks for non-empty string
1224 if (log_buf[0]) {
1225 vector<string> lines = Split(log_buf, "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001226
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001227 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1228 for (const auto& line : lines) ALOGW("%s", line.c_str());
1229 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1230 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001231
1232 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001233 ALOGW("failed program %s is marked optional - continuing...",
1234 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001235 continue;
1236 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001237 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001238 }
1239 }
1240
1241 if (!fd.ok()) return fd.get();
1242
1243 if (!reuse) {
1244 if (specified(selinux_context)) {
1245 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1246 "tmp_prog_" + objName + '_' + string(name);
1247 ret = bpfFdPin(fd, createLoc.c_str());
1248 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001249 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001250 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1251 return -err;
1252 }
1253 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1254 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1255 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001256 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001257 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1258 err, strerror(err));
1259 return -err;
1260 }
1261 } else {
1262 ret = bpfFdPin(fd, progPinLoc.c_str());
1263 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001264 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001265 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1266 return -err;
1267 }
1268 }
1269 if (chmod(progPinLoc.c_str(), 0440)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001270 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001271 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1272 return -err;
1273 }
1274 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1275 (gid_t)cs[i].prog_def->gid)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001276 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001277 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1278 cs[i].prog_def->gid, err, strerror(err));
1279 return -err;
1280 }
1281 }
1282
Maciej Żenczykowski97debeb2025-02-14 11:15:36 -08001283 if (isAtLeastKernelVersion(4, 14, 0)) {
1284 int progId = bpfGetFdProgId(fd);
1285 if (progId == -1) {
1286 const int err = errno;
1287 ALOGE("bpfGetFdProgId failed, errno: %d", err);
1288 return -err;
1289 }
Maciej Żenczykowski199fd352025-02-13 15:17:08 -08001290
1291 int jitLen = bpfGetFdJitProgLen(fd);
1292 if (jitLen == -1) {
1293 const int err = errno;
1294 ALOGE("bpfGetFdJitProgLen failed, ret: %d", err);
1295 return -err;
1296 }
1297
1298 int xlatLen = bpfGetFdXlatProgLen(fd);
1299 if (xlatLen == -1) {
1300 const int err = errno;
1301 ALOGE("bpfGetFdXlatProgLen failed, ret: %d", err);
1302 return -err;
1303 }
1304 ALOGI("prog %s id %d len jit:%d xlat:%d", progPinLoc.c_str(), progId, jitLen, xlatLen);
1305
1306 if (!jitLen && bpfloader_ver >= BPFLOADER_MAINLINE_25Q2_VERSION) {
1307 ALOGE("Kernel eBPF JIT failure for %s", progPinLoc.c_str());
1308 return -ENOTSUP;
1309 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001310 }
1311 }
1312
1313 return 0;
1314}
1315
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001316int loadProg(const char* const elfPath, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001317 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001318 vector<char> license;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001319 vector<codeSection> cs;
1320 vector<unique_fd> mapFds;
1321 int ret;
1322
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001323 ifstream elfFile(elfPath, ios::in | ios::binary);
1324 if (!elfFile.is_open()) return -1;
1325
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001326 ret = readSectionByName("license", elfFile, license);
1327 if (ret) {
1328 ALOGE("Couldn't find license in %s", elfPath);
1329 return ret;
1330 } else {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001331 ALOGD("Loading ELF object %s with license %s",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001332 elfPath, (char*)license.data());
1333 }
1334
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001335 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1336 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001337
1338 // inclusive lower bound check
1339 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001340 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001341 bpfloader_ver, elfPath, bpfLoaderMinVer);
1342 return 0;
1343 }
1344
1345 // exclusive upper bound check
1346 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001347 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001348 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1349 return 0;
1350 }
1351
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001352 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001353 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1354
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001355 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001356 if (ret) {
1357 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1358 return ret;
1359 }
1360
1361 for (int i = 0; i < (int)mapFds.size(); i++)
1362 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1363
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001364 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski66893bf2025-05-06 02:59:22 -07001365 if (ret == -ENOENT) 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"
Maciej Żenczykowski82ce2ca2025-05-14 14:49:28 -07001388#define BPFROOT APEXROOT "/etc/bpf/mainline/"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001389
Maciej Żenczykowski82ce2ca2025-05-14 14:49:28 -07001390static int loadObject(const unsigned int bpfloader_ver, const char* const prefix,
1391 const char* const fname) {
1392 string progPath = string(BPFROOT) + fname;
1393 int ret = loadProg(progPath.c_str(), bpfloader_ver, prefix);
1394 if (ret) {
1395 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1396 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001397 }
Maciej Żenczykowski82ce2ca2025-05-14 14:49:28 -07001398 ALOGD("Loaded object: %s", progPath.c_str());
1399 return 0;
1400}
1401
1402static int loadAllObjects(const unsigned int bpfloader_ver) {
1403 // S+ Tethering mainline module (network_stack): tether offload
1404 // loads under /sys/fs/bpf/tethering:
1405 if (loadObject(bpfloader_ver, "tethering/", "offload.o")) return 1;
1406 if (loadObject(bpfloader_ver, "tethering/", "test.o")) return 1;
1407 if (isAtLeastT) {
1408 // T+ Tethering mainline module loads under:
1409 // /sys/fs/bpf/net_shared: shared with netd & system server
1410 if (loadObject(bpfloader_ver, "net_shared/", "clatd.o")) return 1;
1411 if (loadObject(bpfloader_ver, "net_shared/", "dscpPolicy.o")) return 1;
1412
1413 // /sys/fs/bpf/netd_shared: shared with netd & system server
1414 // - netutils_wrapper (for iptables xt_bpf) has access to programs
1415
1416 // WARNING: Android T+ non-updatable netd depends on both of the
1417 // 'netd_shared' & 'netd' strings for xt_bpf programs it loads
1418 if (loadObject(bpfloader_ver, "netd_shared/", "netd.o")) return 1;
1419
1420 // /sys/fs/bpf/netd_readonly: shared with netd & system server
1421 // - netutils_wrapper has no access, netd has read only access
1422
1423 // /sys/fs/bpf/net_private: not shared, just network_stack
1424 }
1425 return 0;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001426}
1427
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001428static int createDir(const char* const dir) {
1429 mode_t prevUmask = umask(0);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001430
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001431 errno = 0;
1432 int ret = mkdir(dir, S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1433 if (ret && errno != EEXIST) {
1434 const int err = errno;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001435 umask(prevUmask);
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001436 ALOGE("Failed to create directory: %s, ret: %s", dir, std::strerror(err));
1437 return -err;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001438 }
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001439
1440 umask(prevUmask);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001441 return 0;
1442}
1443
1444// Technically 'value' doesn't need to be newline terminated, but it's best
1445// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1446// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001447static int writeProcSysFile(const char *filename, const char *value) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001448 unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001449 if (fd < 0) {
1450 const int err = errno;
1451 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1452 return -err;
1453 }
1454 int len = strlen(value);
1455 int v = write(fd, value, len);
1456 if (v < 0) {
1457 const int err = errno;
1458 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1459 return -err;
1460 }
1461 if (v != len) {
1462 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1463 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1464 return -EINVAL;
1465 }
1466 return 0;
1467}
1468
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001469#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001470const char * const platformBpfLoader = "/system/bin/bpfloader";
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001471const char *const uprobestatsBpfLoader =
1472 "/apex/com.android.uprobestats/bin/uprobestatsbpfload";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001473
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001474static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001475 char * found_blockdev = NULL;
1476 FILE * f = NULL;
1477 char buf[4096];
1478
1479 f = fopen("/proc/mounts", "re");
1480 if (!f) return 1;
1481
1482 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1483 while (fgets(buf, sizeof(buf), f)) {
1484 char * blockdev = buf;
1485 char * space = strchr(blockdev, ' ');
1486 if (!space) continue;
1487 *space = '\0';
1488 char * mntpath = space + 1;
1489 space = strchr(mntpath, ' ');
1490 if (!space) continue;
1491 *space = '\0';
1492 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1493 found_blockdev = strdup(blockdev);
1494 break;
1495 }
1496 fclose(f);
1497 f = NULL;
1498
1499 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001500 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001501
1502 f = fopen("/proc/mounts", "re");
1503 if (!f) { free(found_blockdev); return 3; }
1504
1505 while (fgets(buf, sizeof(buf), f)) {
1506 char * blockdev = buf;
1507 char * space = strchr(blockdev, ' ');
1508 if (!space) continue;
1509 *space = '\0';
1510 char * mntpath = space + 1;
1511 space = strchr(mntpath, ' ');
1512 if (!space) continue;
1513 *space = '\0';
1514 if (strcmp(blockdev, found_blockdev)) continue;
1515 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1516 char * at = strchr(mntpath, '@');
1517 if (!at) continue;
1518 char * ver = at + 1;
1519 ALOGI("Tethering APEX version %s", ver);
1520 }
1521 fclose(f);
1522 free(found_blockdev);
1523 return 0;
1524}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001525
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001526static bool hasGSM() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001527 static string ph = GetProperty("gsm.current.phone-type", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001528 static bool gsm = (ph != "");
1529 static bool logged = false;
1530 if (!logged) {
1531 logged = true;
1532 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1533 }
1534 return gsm;
1535}
1536
1537static bool isTV() {
1538 if (hasGSM()) return false; // TVs don't do GSM
1539
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001540 static string key = GetProperty("ro.oem.key1", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001541 static bool tv = StartsWith(key, "ATV00");
1542 static bool logged = false;
1543 if (!logged) {
1544 logged = true;
1545 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1546 }
1547 return tv;
1548}
1549
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001550static bool isWear() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001551 static string wearSdkStr = GetProperty("ro.cw_build.wear_sdk.version", "");
1552 static int wearSdkInt = GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1553 static string buildChars = GetProperty("ro.build.characteristics", "");
1554 static vector<string> v = Tokenize(buildChars, ",");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001555 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1556 static bool wear = (wearSdkInt > 0) || watch;
1557 static bool logged = false;
1558 if (!logged) {
1559 logged = true;
1560 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1561 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1562 }
1563 return wear;
1564}
1565
Motomu Utsumi712088d2025-03-18 14:52:02 +09001566static int libbpfPrint(enum libbpf_print_level lvl, const char *const formatStr,
1567 va_list argList) {
1568 int32_t prio;
1569 switch (lvl) {
1570 case LIBBPF_WARN:
1571 prio = ANDROID_LOG_WARN;
1572 break;
1573 case LIBBPF_INFO:
1574 prio = ANDROID_LOG_INFO;
1575 break;
1576 case LIBBPF_DEBUG:
1577 prio = ANDROID_LOG_DEBUG;
1578 break;
1579 }
1580 char *s = strdup(formatStr ?: "(no format string)");
1581 int len = strlen(s);
1582 if (len && s[len - 1] == '\n')
1583 s[len - 1] = 0;
1584 LOG_PRI_VA(prio, LOG_TAG, s, argList);
1585 free(s);
1586 return 0;
1587}
1588
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001589static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001590 if (!isAtLeastS) {
1591 ALOGE("Impossible - not reachable on Android <S.");
1592 // for safety, we don't fail, this is a just-in-case workaround
1593 // for any possible busted 'optimized' start everything vendor init hacks on R
1594 return 0;
1595 }
Motomu Utsumi712088d2025-03-18 14:52:02 +09001596 libbpf_set_print(libbpfPrint);
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001597
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001598 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001599
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001600 const int first_api_level = GetIntProperty("ro.board.first_api_level", api_level);
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001601
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001602 // last in U QPR2 beta1
1603 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1604 // first in U QPR2 beta~2
1605 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1606
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001607 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001608 unsigned int bpfloader_ver = BPFLOADER_MAINLINE_S_VERSION; // [42u]
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001609 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1610 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1611 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1612 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001613 if (isAtLeast25Q2) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_25Q2_VERSION
Maciej Żenczykowskic5b9f5e2025-05-06 02:35:27 -07001614 if (isAtLeast25Q3) ++bpfloader_ver; // [48] BPFLOADER_MAINLINE_25Q3_VERSION
1615 if (isAtLeast25Q4) ++bpfloader_ver; // [49] BPFLOADER_MAINLINE_25Q4_VERSION
1616 if (isAtLeast26Q1) ++bpfloader_ver; // [50] BPFLOADER_MAINLINE_26Q1_VERSION
1617 if (isAtLeast26Q2) ++bpfloader_ver; // [51] BPFLOADER_MAINLINE_26Q2_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001618
Motomu Utsumia7693582025-02-05 17:40:08 +09001619 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) libbpf: v%u.%u "
1620 "uid:%d rc:%d%d",
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001621 bpfloader_ver, argv[0], android_get_device_api_level(), api_level,
Motomu Utsumia7693582025-02-05 17:40:08 +09001622 kernelVersion(), describeArch(), libbpf_major_version(),
1623 libbpf_minor_version(), getuid(), has_platform_bpfloader_rc,
1624 has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001625
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001626 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1627 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1628 return 1;
1629 }
1630
1631 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1632 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1633 return 1;
1634 }
1635
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001636 logTetheringApexVersion();
1637
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001638 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001639 if (!isAtLeastKernelVersion(4, 9, 0)) {
1640 ALOGE("Android S & T require kernel 4.9.");
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001641 return 1;
1642 }
1643
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001644 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001645 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001646 ALOGE("Android U requires kernel 4.14.");
1647 return 1;
1648 }
1649
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001650 // V bumps the kernel requirement up to 4.19
1651 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001652 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001653 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001654 return 1;
1655 }
1656
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001657 // 25Q2 bumps the kernel requirement up to 5.4
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001658 // see also: //system/netd/tests/kernel_test.cpp TestKernel54
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001659 if (isAtLeast25Q2 && !isAtLeastKernelVersion(5, 4, 0)) {
1660 ALOGE("Android 25Q2 requires kernel 5.4.");
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001661 return 1;
1662 }
1663
Maciej Żenczykowskiec1115e2025-05-06 04:51:09 -07001664 // 25Q4 bumps the kernel requirement up to 5.10
1665 // see also: //system/netd/tests/kernel_test.cpp TestKernel510
1666 if (isAtLeast25Q4 && !isAtLeastKernelVersion(5, 10, 0)) {
1667 ALOGE("Android 25Q4 requires kernel 5.10.");
1668 return 1;
1669 }
1670
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001671 // Technically already required by U, but only enforce on V+
1672 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1673 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1674 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1675 if (!isTV()) return 1;
1676 }
1677
Maciej Żenczykowski127715a2025-02-10 21:52:01 -08001678 if (isKernel32Bit() && isAtLeast25Q2) {
1679 ALOGE("Android 25Q2 requires 64 bit kernel.");
1680 return 1;
1681 }
1682
Maciej Żenczykowski9b6a9942024-09-03 16:08:35 -07001683 // 6.6 is highest version supported by Android V, so this is effectively W+ (sdk=36+)
1684 if (isKernel32Bit() && isAtLeastKernelVersion(6, 7, 0)) {
1685 ALOGE("Android platform with 32 bit kernel version >= 6.7.0 is unsupported");
1686 return 1;
1687 }
1688
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001689 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1690 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001691 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001692 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001693 }
1694
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001695 if (isAtLeastV) {
1696 bool bad = false;
1697
1698 if (!isLtsKernel()) {
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001699 ALOGW("Android V+ only supports LTS kernels.");
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001700 bad = true;
1701 }
1702
1703#define REQUIRE(maj, min, sub) \
1704 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001705 ALOGW("Android V+ requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001706 bad = true; \
1707 }
1708
1709 REQUIRE(4, 19, 236)
1710 REQUIRE(5, 4, 186)
1711 REQUIRE(5, 10, 199)
1712 REQUIRE(5, 15, 136)
1713 REQUIRE(6, 1, 57)
1714 REQUIRE(6, 6, 0)
Maciej Żenczykowski06f38e32024-12-11 07:12:59 -08001715 REQUIRE(6, 12, 0)
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001716
1717#undef REQUIRE
1718
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001719 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001720 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1721 }
1722 }
1723
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001724 /* Android 14/U should only launch on 64-bit kernels
1725 * T launches on 5.10/5.15
1726 * U launches on 5.15/6.1
1727 * So >=5.16 implies isKernel64Bit()
1728 *
1729 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1730 *
1731 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1732 * we also require 64-bit userspace.
1733 *
1734 * There are various known issues with 32-bit userspace talking to various
1735 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1736 * Some of these have userspace or kernel workarounds/hacks.
1737 * Some of them don't...
1738 * We're going to be removing the hacks.
1739 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1740 * Note: this check/enforcement only applies to *system* userspace code,
1741 * it does not affect unprivileged apps, the 32-on-64 compatibility
1742 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1743 *
1744 * Additionally the 32-bit kernel jit support is poor,
1745 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001746 * Note, however, that TV and Wear devices will continue to support 32-bit userspace
1747 * on ARM64.
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001748 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001749 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001750 // Stuff won't work reliably, but...
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001751 if (isArm() && (isTV() || isWear())) {
1752 // exempt Arm TV or Wear devices (arm32 ABI is far less problematic than x86-32)
1753 ALOGW("[Arm TV/Wear] 32-bit userspace unsupported on 6.2+ kernels.");
Maciej Żenczykowski73238632025-02-24 14:50:09 -08001754 } else if (first_api_level <= 33 /*T*/ && isArm()) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001755 // also exempt Arm devices upgrading with major kernel rev from T-
1756 // might possibly be better for them to run with a newer kernel...
1757 ALOGW("[Arm KernelUpRev] 32-bit userspace unsupported on 6.2+ kernels.");
1758 } else if (isArm()) {
1759 ALOGE("[Arm] 64-bit userspace required on 6.2+ kernels (%d).", first_api_level);
1760 return 1;
1761 } else { // x86 since RiscV cannot be 32-bit
1762 ALOGE("[x86] 64-bit userspace required on 6.2+ kernels.");
1763 return 1;
1764 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001765 }
1766
Maciej Żenczykowski1da19452025-05-16 11:07:51 -07001767 // Linux 6.12 was an LTS released at the end of 2024 (Nov 17),
1768 // and was first supported by Android 16 / 25Q2 (released in June 2025).
1769 // The next Linux LTS should be released near the end of 2025,
1770 // and will likely be 6.18.
1771 // Since officially Android only supports LTS, 6.13+ really means 6.18+,
1772 // and won't be supported before 2026, most likely Android 17 / 26Q2.
1773 // 6.13+ (implying 26Q2+) requires 64-bit userspace.
1774 if (isUserspace32bit() && isAtLeastKernelVersion(6, 13, 0)) {
1775 // due to previous check only reachable on Arm && (<=T kernel uprev || TV || Wear)
1776 ALOGE("64-bit userspace required on 6.13+ kernels.");
1777 return 1;
1778 }
1779
Maciej Żenczykowski25e26222025-03-20 23:25:39 -07001780 if (isAtLeast25Q2) {
1781 FILE * f = fopen("/system/etc/init/netbpfload.rc", "re");
1782 if (!f) {
1783 ALOGE("failure opening /system/etc/init/netbpfload.rc");
1784 return 1;
1785 }
1786 int y = -1, q = -1, a = -1, b = -1, c = -1;
1787 int v = fscanf(f, "# %d %d %d %d %d #", &y, &q, &a, &b, &c);
1788 ALOGI("detected %d of 5: %dQ%d api:%d.%d.%d", v, y, q, a, b, c);
1789 fclose(f);
Maciej Żenczykowskicb555722025-05-01 06:12:00 -07001790 if (v != 5) return 1;
1791 if (y < 2025 || y > 2099) return 1;
1792 if (q < 1 || q > 4) return 1;
1793 if (a < 36) return 1;
1794 if (b < 0 || b > 4) return 1;
1795 if (c < 0) return 1;
Maciej Żenczykowski25e26222025-03-20 23:25:39 -07001796 }
1797
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001798 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001799 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001800 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001801 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001802 return 1;
1803 }
1804
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001805 if (runningAsRoot) {
1806 // Note: writing this proc file requires being root (always the case on V+)
1807
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001808 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1809 // but we need 0 (enabled)
1810 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1811 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1812 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001813 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001814 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001815
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001816 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001817 // Note: writing these proc files requires CAP_NET_ADMIN
1818 // and sepolicy which is only present on U+,
1819 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1820 // trigger (ie. by init itself) instead.
1821
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001822 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1823 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1824 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1825 // kernel does not have CONFIG_BPF_JIT=y)
1826 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1827 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1828 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001829
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001830 // Enable JIT kallsyms export for privileged users only
1831 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1832 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1833 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1834 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001835
Maciej Żenczykowski18523cb2025-06-07 05:59:44 -07001836 if (runningAsRoot) { // implies U QPR3+ and kernel 4.14+
1837 // There should not be any programs or maps yet
1838 errno = 0;
1839 uint32_t progId = bpfGetNextProgId(0); // expect 0 with errno == ENOENT
1840 if (progId || errno != ENOENT) {
1841 ALOGE("bpfGetNextProgId(zero) returned %u (errno %d)", progId, errno);
1842 return 1;
1843 }
1844 errno = 0;
1845 uint32_t mapId = bpfGetNextMapId(0); // expect 0 with errno == ENOENT
1846 if (mapId || errno != ENOENT) {
1847 ALOGE("bpfGetNextMapId(zero) returned %u (errno %d)", mapId, errno);
1848 return 1;
1849 }
1850 } else if (isAtLeastKernelVersion(4, 14, 0)) { // implies S through U QPR2
1851 // bpfGetNext{Prog,Map}Id require 4.14+
1852 // furthermore since we're not running as root, we're not the initial
1853 // platform bpfloader, so there may already be some maps & programs.
1854 uint32_t mapId = 0;
1855 while (true) {
1856 errno = 0;
1857 uint32_t next = bpfGetNextMapId(mapId);
1858 if (!next && errno == ENOENT) break;
1859 if (next <= mapId) {
1860 ALOGE("bpfGetNextMapId(%u) returned %u errno %d", mapId, next, errno);
1861 return 1;
1862 }
1863 mapId = next;
1864 }
1865 // mapId is now the last map id, creating a new map should change that
1866 unique_fd map(createMap(BPF_MAP_TYPE_ARRAY, sizeof(int), sizeof(int), 1, 0));
1867 errno = 0;
1868 uint32_t next = bpfGetNextMapId(mapId);
1869 if (next <= mapId) {
1870 // We should fail here on Xiaomi S 4.14.180 due to kernel uapi bug,
1871 // which causes bpfGetNextMapId to behave as bpfGetNextProgId,
1872 // and thus it should return 0 with errno == ENOENT.
1873 ALOGE("bpfGetNextMapId(final %d) returned %d errno %d", mapId, next, errno);
1874 return 1;
1875 }
1876 } else { // implies S/T with 4.9 kernel
1877 // nothing we can do.
1878 }
1879
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001880 // Create all the pin subdirectories
1881 // (this must be done first to allow selinux_context and pin_subdir functionality,
1882 // which could otherwise fail with ENOENT during object pinning or renaming,
1883 // due to ordering issues)
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001884 if (createDir("/sys/fs/bpf/tethering")) return 1;
1885 // This is technically T+ but S also needs it for the 'mainline_done' file.
1886 if (createDir("/sys/fs/bpf/netd_shared")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001887
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001888 if (isAtLeastT) {
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001889 if (createDir("/sys/fs/bpf/netd_readonly")) return 1;
1890 if (createDir("/sys/fs/bpf/net_shared")) return 1;
1891 if (createDir("/sys/fs/bpf/net_private")) return 1;
1892
1893 // This one is primarily meant for triggering genfscon rules.
1894 if (createDir("/sys/fs/bpf/loader")) return 1;
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001895 }
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001896
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001897 // Load all ELF objects, create programs and maps, and pin them
Maciej Żenczykowski82ce2ca2025-05-14 14:49:28 -07001898 if (loadAllObjects(bpfloader_ver)) {
1899 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS ===");
1900 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1901 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1902 "problems or startup script race.");
1903 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1904 sleep(20);
1905 return 2;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001906 }
1907
1908 int key = 1;
1909 int value = 123;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001910 unique_fd map(
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001911 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1912 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001913 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
Maciej Żenczykowskib3ddc8a2025-04-02 17:52:39 -07001914 if (isAtLeastT) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001915 }
1916
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001917 // leave a flag that we're done
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001918 if (createDir("/sys/fs/bpf/netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001919
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001920 // platform bpfloader will only succeed when run as root
1921 if (!runningAsRoot) {
1922 // unreachable on U QPR3+ which always runs netbpfload as root
1923
1924 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1925 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001926 }
1927
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001928 // unreachable before U QPR3
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001929 if (exists(uprobestatsBpfLoader)) {
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001930 ALOGI("done, transferring control to uprobestatsbpfload.");
1931 const char *args[] = {
1932 uprobestatsBpfLoader,
1933 NULL,
1934 };
1935 execve(args[0], (char **)args, envp);
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001936 ALOGI("unable to execute uprobestatsbpfload, transferring control to "
1937 "platform bpfloader.");
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001938 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001939
1940 // platform BpfLoader *needs* to run as root
1941 const char * args[] = { platformBpfLoader, NULL, };
1942 execve(args[0], (char**)args, envp);
1943 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1944 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001945}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001946
1947} // namespace bpf
1948} // namespace android
1949
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001950int main(int argc, char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001951 if (android::bpf::isAtLeastT) {
1952 InitLogging(argv, &KernelLogger);
1953 } else {
1954 // S lacks the sepolicy to make non-root uid KernelLogger viable
1955 InitLogging(argv);
1956 }
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001957
1958 if (argc == 2 && !strcmp(argv[1], "done")) {
1959 // we're being re-exec'ed from platform bpfloader to 'finalize' things
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001960 if (!SetProperty("bpf.progs_loaded", "1")) {
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001961 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1962 return 125;
1963 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001964 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001965 return 0;
1966 }
1967
1968 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001969}