blob: bdc2e8c609dc74d44dc5f1a83b411ef1e723588c [file] [log] [blame]
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001/*
Maciej Żenczykowski49140b92024-08-07 15:06:07 -07002 * Copyright (C) 2018-2024 The Android Open Source Project
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070017#define LOG_TAG "NetBpfLoad"
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070018
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070019#include <arpa/inet.h>
Motomu Utsumib3d3c2a2025-03-18 15:06:34 +090020#include <bpf/btf.h>
Motomu Utsumia7693582025-02-05 17:40:08 +090021#include <bpf/libbpf.h>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070022#include <dirent.h>
23#include <elf.h>
24#include <errno.h>
25#include <error.h>
26#include <fcntl.h>
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070027#include <fstream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070028#include <inttypes.h>
29#include <iostream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070030#include <linux/unistd.h>
31#include <log/log.h>
32#include <net/if.h>
33#include <optional>
34#include <stdint.h>
35#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
38#include <string>
39#include <sys/mman.h>
40#include <sys/socket.h>
41#include <sys/stat.h>
42#include <sys/types.h>
43#include <sys/utsname.h>
44#include <sys/wait.h>
45#include <sysexits.h>
46#include <unistd.h>
47#include <unordered_map>
48#include <vector>
49
50#include <android-base/cmsg.h>
51#include <android-base/file.h>
52#include <android-base/logging.h>
53#include <android-base/macros.h>
54#include <android-base/properties.h>
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +090055#include <android-base/scopeguard.h>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070056#include <android-base/stringprintf.h>
57#include <android-base/strings.h>
58#include <android-base/unique_fd.h>
59#include <android/api-level.h>
60
61#include "BpfSyscallWrappers.h"
62#include "bpf/BpfUtils.h"
Maciej Żenczykowskid6028352024-08-19 15:20:04 -070063#include "bpf_map_def.h"
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070064
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +000065// The following matches bpf_helpers.h, which is only for inclusion in bpf code
Maciej Żenczykowski8c097782025-03-04 13:11:56 -080066#define BPFLOADER_MAINLINE_S_VERSION 42u
Maciej Żenczykowski199fd352025-02-13 15:17:08 -080067#define BPFLOADER_MAINLINE_25Q2_VERSION 47u
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +000068
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070069using android::base::EndsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070070using android::base::GetIntProperty;
71using android::base::GetProperty;
72using android::base::InitLogging;
73using android::base::KernelLogger;
74using android::base::SetProperty;
75using android::base::Split;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070076using android::base::StartsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070077using android::base::Tokenize;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070078using android::base::unique_fd;
79using std::ifstream;
80using std::ios;
81using std::optional;
82using std::string;
83using std::vector;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070084
85namespace android {
86namespace bpf {
87
88// Bpf programs may specify per-program & per-map selinux_context and pin_subdir.
89//
90// The BpfLoader needs to convert these bpf.o specified strings into an enum
91// for internal use (to check that valid values were specified for the specific
92// location of the bpf.o file).
93//
94// It also needs to map selinux_context's into pin_subdir's.
95// This is because of how selinux_context is actually implemented via pin+rename.
96//
97// Thus 'domain' enumerates all selinux_context's/pin_subdir's that the BpfLoader
98// is aware of. Thus there currently needs to be a 1:1 mapping between the two.
99//
100enum class domain : int {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700101 unspecified = 0, // means just use the default for that specific pin location
102 tethering, // (S+) fs_bpf_tethering /sys/fs/bpf/tethering
103 net_private, // (T+) fs_bpf_net_private /sys/fs/bpf/net_private
104 net_shared, // (T+) fs_bpf_net_shared /sys/fs/bpf/net_shared
105 netd_readonly, // (T+) fs_bpf_netd_readonly /sys/fs/bpf/netd_readonly
106 netd_shared, // (T+) fs_bpf_netd_shared /sys/fs/bpf/netd_shared
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700107 loader, // (U+) fs_bpf_loader /sys/fs/bpf/loader
108 // on T due to lack of sepolicy/genfscon rules it behaves simply as 'fs_bpf'
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700109};
110
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700111static constexpr domain AllDomains[] = {
112 domain::unspecified,
113 domain::tethering,
114 domain::net_private,
115 domain::net_shared,
116 domain::netd_readonly,
117 domain::netd_shared,
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700118 domain::loader,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700119};
120
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700121static constexpr bool specified(domain d) {
122 return d != domain::unspecified;
123}
124
125struct Location {
126 const char* const dir = "";
127 const char* const prefix = "";
Maciej Żenczykowski0b477492025-03-04 22:12:42 -0800128 const bool t_plus = true;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700129};
130
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700131// Returns the build type string (from ro.build.type).
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700132const std::string& getBuildType() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700133 static std::string t = GetProperty("ro.build.type", "unknown");
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700134 return t;
135}
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700136
137// The following functions classify the 3 Android build types.
138inline bool isEng() {
139 return getBuildType() == "eng";
140}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700141
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700142inline bool isUser() {
143 return getBuildType() == "user";
144}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700145
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700146inline bool isUserdebug() {
147 return getBuildType() == "userdebug";
148}
149
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700150#define BPF_FS_PATH "/sys/fs/bpf/"
151
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700152static unsigned int page_size = static_cast<unsigned int>(getpagesize());
153
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700154constexpr const char* lookupSelinuxContext(const domain d) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700155 switch (d) {
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700156 case domain::unspecified: return "";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700157 case domain::tethering: return "fs_bpf_tethering";
158 case domain::net_private: return "fs_bpf_net_private";
159 case domain::net_shared: return "fs_bpf_net_shared";
160 case domain::netd_readonly: return "fs_bpf_netd_readonly";
161 case domain::netd_shared: return "fs_bpf_netd_shared";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700162 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700163 }
164}
165
166domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
167 for (domain d : AllDomains) {
168 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
169 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
170 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
171 }
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700172 ALOGE("unrecognized selinux_context '%-32s'", s);
173 // Note: we *can* just abort() here as we only load bpf .o files shipped
174 // in the same mainline module / apex as NetBpfLoad itself.
175 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700176}
177
178constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
179 switch (d) {
180 case domain::unspecified: return unspecified;
181 case domain::tethering: return "tethering/";
182 case domain::net_private: return "net_private/";
183 case domain::net_shared: return "net_shared/";
184 case domain::netd_readonly: return "netd_readonly/";
185 case domain::netd_shared: return "netd_shared/";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700186 case domain::loader: return "loader/";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700187 }
188};
189
190domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
191 for (domain d : AllDomains) {
192 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
193 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
194 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
195 }
196 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700197 // Note: we *can* just abort() here as we only load bpf .o files shipped
198 // in the same mainline module / apex as NetBpfLoad itself.
199 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700200}
201
202static string pathToObjName(const string& path) {
203 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700204 string filename = Split(path, "/").back();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700205 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
206 string name = filename.substr(0, filename.find_last_of('.'));
207 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
208 // this can be used to provide duplicate programs (mux based on the bpfloader version)
209 return name.substr(0, name.find_last_of('@'));
210}
211
212typedef struct {
213 const char* name;
214 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000215 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700216} sectionType;
217
218/*
219 * Map section name prefixes to program types, the section name will be:
220 * SECTION(<prefix>/<name-of-program>)
221 * For example:
222 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
223 * is the name of the program, and tracepoint is the type.
224 *
225 * However, be aware that you should not be directly using the SECTION() macro.
Maciej Żenczykowski3a085152024-09-18 23:45:52 +0000226 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE macros.
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700227 *
228 * Programs shipped inside the tethering apex should be limited to networking stuff,
229 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
230 * since they are less stable abi/api and may conflict with platform uses of bpf.
231 */
232sectionType sectionNameTypes[] = {
233 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
234 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000235 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
236 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700237 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
238 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
239 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
240 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
241 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
242 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
243 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700244 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
245 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
246 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
247 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000248 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
249 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700250 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
251 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
252 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000253 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700254 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
255 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000256 {"xdp/", BPF_PROG_TYPE_XDP},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700257};
258
259typedef struct {
260 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000261 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700262 string name;
263 vector<char> data;
264 vector<char> rel_data;
265 optional<struct bpf_prog_def> prog_def;
266
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000267 unique_fd prog_fd; // fd after loading
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700268} codeSection;
269
270static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
271 elfFile.seekg(0);
272 if (elfFile.fail()) return -1;
273
274 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
275
276 return 0;
277}
278
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000279// Reads all section header tables into an Shdr array
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700280static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
281 Elf64_Ehdr eh;
282 int ret = 0;
283
284 ret = readElfHeader(elfFile, &eh);
285 if (ret) return ret;
286
287 elfFile.seekg(eh.e_shoff);
288 if (elfFile.fail()) return -1;
289
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000290 // Read shdr table entries
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700291 shTable.resize(eh.e_shnum);
292
293 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
294
295 return 0;
296}
297
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000298// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700299static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
300 vector<Elf64_Shdr> shTable;
301 int ret = readSectionHeadersAll(elfFile, shTable);
302 if (ret) return ret;
303
304 elfFile.seekg(shTable[id].sh_offset);
305 if (elfFile.fail()) return -1;
306
307 sec.resize(shTable[id].sh_size);
308 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
309
310 return 0;
311}
312
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000313// Read whole section header string table
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700314static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
315 Elf64_Ehdr eh;
316 int ret = readElfHeader(elfFile, &eh);
317 if (ret) return ret;
318
319 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
320 if (ret) return ret;
321
322 return 0;
323}
324
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000325// Get name from offset in strtab
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700326static int getSymName(ifstream& elfFile, int nameOff, string& name) {
327 int ret;
328 vector<char> secStrTab;
329
330 ret = readSectionHeaderStrtab(elfFile, secStrTab);
331 if (ret) return ret;
332
333 if (nameOff >= (int)secStrTab.size()) return -1;
334
335 name = string((char*)secStrTab.data() + nameOff);
336 return 0;
337}
338
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000339// Reads a full section by name - example to get the GPL license
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700340static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
341 vector<char> secStrTab;
342 vector<Elf64_Shdr> shTable;
343 int ret;
344
345 ret = readSectionHeadersAll(elfFile, shTable);
346 if (ret) return ret;
347
348 ret = readSectionHeaderStrtab(elfFile, secStrTab);
349 if (ret) return ret;
350
351 for (int i = 0; i < (int)shTable.size(); i++) {
352 char* secname = secStrTab.data() + shTable[i].sh_name;
353 if (!secname) continue;
354
355 if (!strcmp(secname, name)) {
356 vector<char> dataTmp;
357 dataTmp.resize(shTable[i].sh_size);
358
359 elfFile.seekg(shTable[i].sh_offset);
360 if (elfFile.fail()) return -1;
361
362 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
363
364 data = dataTmp;
365 return 0;
366 }
367 }
368 return -2;
369}
370
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700371unsigned int readSectionUint(const char* name, ifstream& elfFile) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700372 vector<char> theBytes;
373 int ret = readSectionByName(name, elfFile, theBytes);
374 if (ret) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700375 ALOGE("Couldn't find section %s.", name);
376 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700377 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700378 ALOGE("Section %s is too short.", name);
379 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700380 } else {
381 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
382 unsigned int value = static_cast<unsigned char>(theBytes[3]);
383 value <<= 8;
384 value += static_cast<unsigned char>(theBytes[2]);
385 value <<= 8;
386 value += static_cast<unsigned char>(theBytes[1]);
387 value <<= 8;
388 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000389 ALOGD("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700390 return value;
391 }
392}
393
394static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
395 int ret;
396 vector<Elf64_Shdr> shTable;
397
398 ret = readSectionHeadersAll(elfFile, shTable);
399 if (ret) return ret;
400
401 for (int i = 0; i < (int)shTable.size(); i++) {
402 if ((int)shTable[i].sh_type != type) continue;
403
404 vector<char> dataTmp;
405 dataTmp.resize(shTable[i].sh_size);
406
407 elfFile.seekg(shTable[i].sh_offset);
408 if (elfFile.fail()) return -1;
409
410 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
411
412 data = dataTmp;
413 return 0;
414 }
415 return -2;
416}
417
418static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
419 return (a.st_value < b.st_value);
420}
421
422static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
423 int ret, numElems;
424 Elf64_Sym* buf;
425 vector<char> secData;
426
427 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
428 if (ret) return ret;
429
430 buf = (Elf64_Sym*)secData.data();
431 numElems = (secData.size() / sizeof(Elf64_Sym));
432 data.assign(buf, buf + numElems);
433
434 if (sort) std::sort(data.begin(), data.end(), symCompare);
435 return 0;
436}
437
438static enum bpf_prog_type getSectionType(string& name) {
439 for (auto& snt : sectionNameTypes)
440 if (StartsWith(name, snt.name)) return snt.type;
441
442 return BPF_PROG_TYPE_UNSPEC;
443}
444
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700445static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700446 vector<char> pdData;
447 int ret = readSectionByName("progs", elfFile, pdData);
448 if (ret) return ret;
449
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700450 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700451 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700452 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700453 return -1;
454 };
455
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700456 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700457
458 const char* dataPtr = pdData.data();
459 for (auto& p : pd) {
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700460 // Copy the structure from the ELF file and move to the next one.
461 memcpy(&p, dataPtr, sizeof(struct bpf_prog_def));
462 dataPtr += sizeof(struct bpf_prog_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700463 }
464 return 0;
465}
466
467static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
468 optional<unsigned> symbolType = std::nullopt) {
469 int ret;
470 string name;
471 vector<Elf64_Sym> symtab;
472 vector<Elf64_Shdr> shTable;
473
474 ret = readSymTab(elfFile, 1 /* sort */, symtab);
475 if (ret) return ret;
476
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000477 // Get index of section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700478 ret = readSectionHeadersAll(elfFile, shTable);
479 if (ret) return ret;
480
481 int sec_idx = -1;
482 for (int i = 0; i < (int)shTable.size(); i++) {
483 ret = getSymName(elfFile, shTable[i].sh_name, name);
484 if (ret) return ret;
485
486 if (!name.compare(sectionName)) {
487 sec_idx = i;
488 break;
489 }
490 }
491
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000492 // No section found with matching name
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700493 if (sec_idx == -1) {
494 ALOGW("No %s section could be found in elf object", sectionName.c_str());
495 return -1;
496 }
497
498 for (int i = 0; i < (int)symtab.size(); i++) {
499 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
500
501 if (symtab[i].st_shndx == sec_idx) {
502 string s;
503 ret = getSymName(elfFile, symtab[i].st_name, s);
504 if (ret) return ret;
505 names.push_back(s);
506 }
507 }
508
509 return 0;
510}
511
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000512// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700513static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700514 vector<Elf64_Shdr> shTable;
515 int entries, ret = 0;
516
517 ret = readSectionHeadersAll(elfFile, shTable);
518 if (ret) return ret;
519 entries = shTable.size();
520
521 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700522 ret = readProgDefs(elfFile, pd);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700523 if (ret) return ret;
524 vector<string> progDefNames;
525 ret = getSectionSymNames(elfFile, "progs", progDefNames);
526 if (!pd.empty() && ret) return ret;
527
528 for (int i = 0; i < entries; i++) {
529 string name;
530 codeSection cs_temp;
531 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
532
533 ret = getSymName(elfFile, shTable[i].sh_name, name);
534 if (ret) return ret;
535
536 enum bpf_prog_type ptype = getSectionType(name);
537
538 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
539
540 // This must be done before '/' is replaced with '_'.
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000541 for (auto& snt : sectionNameTypes)
542 if (StartsWith(name, snt.name)) cs_temp.attach_type = snt.attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700543
544 string oldName = name;
545
546 // convert all slashes to underscores
547 std::replace(name.begin(), name.end(), '/', '_');
548
549 cs_temp.type = ptype;
550 cs_temp.name = name;
551
552 ret = readSectionByIdx(elfFile, i, cs_temp.data);
553 if (ret) return ret;
554 ALOGV("Loaded code section %d (%s)", i, name.c_str());
555
556 vector<string> csSymNames;
557 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
558 if (ret || !csSymNames.size()) return ret;
Motomu Utsumi62b1c882025-03-21 15:13:00 +0900559 for (size_t j = 0; j < progDefNames.size(); ++j) {
560 if (!progDefNames[j].compare(csSymNames[0] + "_def")) {
561 cs_temp.prog_def = pd[j];
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700562 break;
563 }
564 }
565
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000566 // Check for rel section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700567 if (cs_temp.data.size() > 0 && i < entries) {
568 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
569 if (ret) return ret;
570
571 if (name == (".rel" + oldName)) {
572 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
573 if (ret) return ret;
574 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
575 }
576 }
577
578 if (cs_temp.data.size() > 0) {
579 cs.push_back(std::move(cs_temp));
580 ALOGV("Adding section %d to cs list", i);
581 }
582 }
583 return 0;
584}
585
586static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
587 vector<Elf64_Sym> symtab;
588 int ret = 0;
589
590 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
591 if (ret) return ret;
592
593 if (index >= (int)symtab.size()) return -1;
594
595 return getSymName(elfFile, symtab[index].st_name, name);
596}
597
598static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
599 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
600 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
601 // so on 4.9-T kernels just pretend the map matches our expectations.
602 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
603 // This is because the primary failure mode we're trying to detect here
604 // is either a source code misconfiguration (which is likely kernel independent)
605 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
606 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
607
608 // Assuming fd is a valid Bpf Map file descriptor then
609 // all the following should always succeed on a 4.14+ kernel.
610 // If they somehow do fail, they'll return -1 (and set errno),
611 // which should then cause (among others) a key_size mismatch.
612 int fd_type = bpfGetFdMapType(fd);
613 int fd_key_size = bpfGetFdKeySize(fd);
614 int fd_value_size = bpfGetFdValueSize(fd);
615 int fd_max_entries = bpfGetFdMaxEntries(fd);
616 int fd_map_flags = bpfGetFdMapFlags(fd);
617
618 // DEVMAPs are readonly from the bpf program side's point of view, as such
619 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
620 int desired_map_flags = (int)mapDef.map_flags;
621 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
622 desired_map_flags |= BPF_F_RDONLY_PROG;
623
624 // The .h file enforces that this is a power of two, and page size will
625 // also always be a power of two, so this logic is actually enough to
626 // force it to be a multiple of the page size, as required by the kernel.
627 unsigned int desired_max_entries = mapDef.max_entries;
628 if (type == BPF_MAP_TYPE_RINGBUF) {
629 if (desired_max_entries < page_size) desired_max_entries = page_size;
630 }
631
632 // The following checks should *never* trigger, if one of them somehow does,
633 // it probably means a bpf .o file has been changed/replaced at runtime
634 // and bpfloader was manually rerun (normally it should only run *once*
635 // early during the boot process).
636 // Another possibility is that something is misconfigured in the code:
637 // most likely a shared map is declared twice differently.
638 // But such a change should never be checked into the source tree...
639 if ((fd_type == type) &&
640 (fd_key_size == (int)mapDef.key_size) &&
641 (fd_value_size == (int)mapDef.value_size) &&
642 (fd_max_entries == (int)desired_max_entries) &&
643 (fd_map_flags == desired_map_flags)) {
644 return true;
645 }
646
647 ALOGE("bpf map name %s mismatch: desired/found: "
648 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
649 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
650 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
651 return false;
652}
653
Motomu Utsumib3d3c2a2025-03-18 15:06:34 +0900654static int setBtfDatasecSize(ifstream &elfFile, struct btf *btf,
655 struct btf_type *bt) {
656 const char *name = btf__name_by_offset(btf, bt->name_off);
657 if (!name) {
658 ALOGE("Couldn't resolve section name, errno: %d", errno);
659 return -errno;
660 }
661
662 vector<char> data;
663 int ret = readSectionByName(name, elfFile, data);
664 if (ret) {
665 ALOGE("Couldn't read section %s, ret: %d", name, ret);
666 return ret;
667 }
668 bt->size = data.size();
669 return 0;
670}
671
Motomu Utsumiefe33312025-03-18 15:08:15 +0900672static int getSymOffsetByName(ifstream &elfFile, const char *name, int *off) {
673 vector<Elf64_Sym> symtab;
674 int ret = readSymTab(elfFile, 1 /* sort */, symtab);
675 if (ret) return ret;
676 for (int i = 0; i < (int)symtab.size(); i++) {
677 string s;
678 ret = getSymName(elfFile, symtab[i].st_name, s);
679 if (ret) continue;
680 if (!strcmp(s.c_str(), name)) {
681 *off = symtab[i].st_value;
682 return 0;
683 }
684 }
685 return -1;
686}
687
688static int setBtfVarOffset(ifstream &elfFile, struct btf *btf,
689 struct btf_type *datasecBt) {
690 int i, vars = btf_vlen(datasecBt);
691 struct btf_var_secinfo *vsi;
692 const char *datasecName = btf__name_by_offset(btf, datasecBt->name_off);
693 if (!datasecName) {
694 ALOGE("Couldn't resolve section name, errno: %d", errno);
695 return -errno;
696 }
697
698 for (i = 0, vsi = btf_var_secinfos(datasecBt); i < vars; i++, vsi++) {
699 const struct btf_type *varBt = btf__type_by_id(btf, vsi->type);
700 if (!varBt || !btf_is_var(varBt)) {
701 ALOGE("Found non VAR kind btf_type, section: %s id: %d", datasecName,
702 vsi->type);
703 return -1;
704 }
705
706 const struct btf_var *var = btf_var(varBt);
707 if (var->linkage == BTF_VAR_STATIC) continue;
708
709 const char *varName = btf__name_by_offset(btf, varBt->name_off);
710 if (!varName) {
711 ALOGE("Failed to resolve var name, section: %s", datasecName);
712 return -1;
713 }
714
715 int off;
716 int ret = getSymOffsetByName(elfFile, varName, &off);
717 if (ret) {
718 ALOGE("No offset found in symbol table, section: %s, var: %s, ret: %d",
719 datasecName, varName, ret);
720 return ret;
721 }
722 vsi->offset = off;
723 }
724 return 0;
725}
726
Motomu Utsumi21536e52025-03-18 15:09:27 +0900727static int loadBtf(ifstream &elfFile, struct btf *btf) {
728 int ret;
729 for (unsigned int i = 1; i < btf__type_cnt(btf); ++i) {
730 struct btf_type *bt = (struct btf_type *)btf__type_by_id(btf, i);
731 if (!btf_is_datasec(bt)) continue;
732 ret = setBtfDatasecSize(elfFile, btf, bt);
733 if (ret) return ret;
734 ret = setBtfVarOffset(elfFile, btf, bt);
735 if (ret) return ret;
736 }
737
738 ret = btf__load_into_kernel(btf);
739 if (ret) {
740 if (errno != EINVAL) {
741 ALOGE("btf__load_into_kernel failed, errno: %d", errno);
742 return ret;
743 };
744 // For BTF_KIND_FUNC, newer kernels can read the BTF_INFO_VLEN bits of
745 // struct btf_type to distinguish static vs. global vs. extern
746 // functions, but older kernels enforce that only the BTF_INFO_KIND bits
747 // can be set. Retry with non-BTF_INFO_KIND bits zeroed out to handle
748 // this case.
749 for (unsigned int i = 1; i < btf__type_cnt(btf); ++i) {
750 struct btf_type *bt = (struct btf_type *)btf__type_by_id(btf, i);
751 if (btf_is_func(bt)) {
752 bt->info = (BTF_INFO_KIND(bt->info)) << 24;
753 }
754 }
755 ret = btf__load_into_kernel(btf);
756 if (ret) {
757 ALOGE("btf__load_into_kernel retry failed, errno: %d", errno);
758 return ret;
759 };
760 }
761 return 0;
762}
763
Motomu Utsumi59b20992025-03-18 15:10:19 +0900764int getKeyValueTids(const struct btf *btf, const char *mapName,
765 uint32_t expectedKeySize, uint32_t expectedValueSize,
766 uint32_t *keyTypeId, uint32_t *valueTypeId) {
767 const struct btf_type *kvBt;
768 const struct btf_member *key, *value;
769 const size_t max_name = 256;
770 char kvTypeName[max_name];
771 int64_t keySize, valueSize;
Motomu Utsumia6ffae22025-03-21 11:00:10 +0900772 int32_t kvId;
Motomu Utsumi59b20992025-03-18 15:10:19 +0900773
774 if (snprintf(kvTypeName, max_name, "____btf_map_%s", mapName) == max_name) {
775 ALOGE("____btf_map_%s is too long", mapName);
776 return -1;
777 }
778
779 kvId = btf__find_by_name(btf, kvTypeName);
780 if (kvId < 0) {
781 ALOGE("section not found, map: %s typeName: %s", mapName, kvTypeName);
782 return -1;
783 }
784
785 kvBt = btf__type_by_id(btf, kvId);
786 if (!kvBt) {
787 ALOGE("Couldn't find BTF type, map: %s id: %u", mapName, kvId);
788 return -1;
789 }
790
791 if (!btf_is_struct(kvBt) || btf_vlen(kvBt) < 2) {
792 ALOGE("Non Struct kind or invalid vlen, map: %s id: %u", mapName, kvId);
793 return -1;
794 }
795
796 key = btf_members(kvBt);
797 value = key + 1;
798
799 keySize = btf__resolve_size(btf, key->type);
800 if (keySize < 0) {
801 ALOGE("Couldn't get key size, map: %s errno: %d", mapName, errno);
802 return -1;
803 }
804
805 valueSize = btf__resolve_size(btf, value->type);
806 if (valueSize < 0) {
807 ALOGE("Couldn't get value size, map: %s errno: %d", mapName, errno);
808 return -1;
809 }
810
811 if (expectedKeySize != keySize || expectedValueSize != valueSize) {
812 ALOGE("Key value size mismatch, map: %s key size: %d expected key size: "
813 "%d value size: %d expected value size: %d",
814 mapName, (uint32_t)keySize, expectedKeySize, (uint32_t)valueSize,
815 expectedValueSize);
816 return -1;
817 }
818
819 *keyTypeId = key->type;
820 *valueTypeId = value->type;
821
822 return 0;
823}
824
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900825static bool isBtfSupported(enum bpf_map_type type) {
826 return type != BPF_MAP_TYPE_DEVMAP_HASH && type != BPF_MAP_TYPE_RINGBUF;
827}
828
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700829static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700830 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700831 int ret;
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900832 vector<char> mdData, btfData;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700833 vector<struct bpf_map_def> md;
834 vector<string> mapNames;
835 string objName = pathToObjName(string(elfPath));
836
837 ret = readSectionByName("maps", elfFile, mdData);
838 if (ret == -2) return 0; // no maps to read
839 if (ret) return ret;
840
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700841 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700842 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700843 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700844 return -1;
845 };
846
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700847 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700848
849 const char* dataPtr = mdData.data();
850 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700851 // Copy the structure from the ELF file and move to the next one.
852 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
853 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700854 }
855
856 ret = getSectionSymNames(elfFile, "maps", mapNames);
857 if (ret) return ret;
858
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900859 struct btf *btf = NULL;
860 auto scopeGuard = base::make_scope_guard([btf] { if (btf) btf__free(btf); });
Motomu Utsumi861f11c2025-03-21 15:29:00 +0900861 if (isAtLeastKernelVersion(5, 10, 0)) {
862 // Untested on Linux Kernel 5.4, but likely compatible.
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900863 // On Linux Kernels older than 4.18 BPF_BTF_LOAD command doesn't exist.
Motomu Utsumi861f11c2025-03-21 15:29:00 +0900864 // On Linux Kernels older than 5.2 BTF_KIND_VAR and BTF_KIND_DATASEC don't exist.
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900865 ret = readSectionByName(".BTF", elfFile, btfData);
866 if (ret) {
867 ALOGE("Failed to read .BTF section, ret:%d", ret);
868 return ret;
869 }
Motomu Utsumi62b1c882025-03-21 15:13:00 +0900870 btf = btf__new(btfData.data(), btfData.size());
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900871 if (btf == NULL) {
872 ALOGE("btf__new failed, errno: %d", errno);
873 return -errno;
874 }
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900875
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900876 ret = loadBtf(elfFile, btf);
877 if (ret) return ret;
878 }
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900879
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700880 unsigned kvers = kernelVersion();
881
882 for (int i = 0; i < (int)mapNames.size(); i++) {
883 if (md[i].zero != 0) abort();
884
885 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000886 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700887 md[i].bpfloader_min_ver);
888 mapFds.push_back(unique_fd());
889 continue;
890 }
891
892 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000893 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700894 md[i].bpfloader_max_ver);
895 mapFds.push_back(unique_fd());
896 continue;
897 }
898
899 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000900 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700901 mapNames[i].c_str(), kvers, md[i].min_kver);
902 mapFds.push_back(unique_fd());
903 continue;
904 }
905
906 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000907 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700908 mapNames[i].c_str(), kvers, md[i].max_kver);
909 mapFds.push_back(unique_fd());
910 continue;
911 }
912
913 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
914 (md[i].ignore_on_userdebug && isUserdebug())) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000915 ALOGD("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700916 getBuildType().c_str());
917 mapFds.push_back(unique_fd());
918 continue;
919 }
920
921 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
922 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
923 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
924 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
925 (isRiscV() && md[i].ignore_on_riscv64)) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000926 ALOGD("skipping map %s which is ignored on %s", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700927 describeArch());
928 mapFds.push_back(unique_fd());
929 continue;
930 }
931
932 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski87019832025-02-03 22:04:26 -0800933 if (type == BPF_MAP_TYPE_LPM_TRIE && !isAtLeastKernelVersion(4, 14, 0)) {
934 // On Linux Kernels older than 4.14 this map type doesn't exist - autoskip.
935 ALOGD("skipping LPM_TRIE map %s - requires kver 4.14+", mapNames[i].c_str());
936 mapFds.push_back(unique_fd());
937 continue;
938 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700939 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
940 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
941 // of be approximated: ARRAY has the same userspace api, though it is not usable
942 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
943 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
944 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
945 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
946 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
947 type = BPF_MAP_TYPE_ARRAY;
948 }
949 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
950 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
951 // of be approximated: HASH has the same userspace visible api.
952 // However it cannot be used by ebpf programs in the same way.
953 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
954 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
955 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
956 // programs as being 5.4+...
957 type = BPF_MAP_TYPE_HASH;
958 }
959
960 // The .h file enforces that this is a power of two, and page size will
961 // also always be a power of two, so this logic is actually enough to
962 // force it to be a multiple of the page size, as required by the kernel.
963 unsigned int max_entries = md[i].max_entries;
964 if (type == BPF_MAP_TYPE_RINGBUF) {
965 if (max_entries < page_size) max_entries = page_size;
966 }
967
968 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
969 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000970 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700971 md[i].selinux_context, static_cast<int>(selinux_context),
972 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
973 }
974
975 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700976 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000977 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700978 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
979 }
980
981 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
982 // except that maps shared across .o's have empty <objName>
983 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
984 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
985 (md[i].shared ? "" : objName) + "_" + mapNames[i];
986 bool reuse = false;
987 unique_fd fd;
988 int saved_errno;
989
990 if (access(mapPinLoc.c_str(), F_OK) == 0) {
991 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
992 saved_errno = errno;
993 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
994 reuse = true;
995 } else {
996 union bpf_attr req = {
997 .map_type = type,
998 .key_size = md[i].key_size,
999 .value_size = md[i].value_size,
1000 .max_entries = max_entries,
Maciej Żenczykowskic1a9f4a2025-01-20 12:09:13 -08001001 .map_flags = md[i].map_flags,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001002 };
1003 if (isAtLeastKernelVersion(4, 15, 0))
1004 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +09001005
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +09001006 bool haveBtf = btf && isBtfSupported(type);
Maciej Żenczykowski9fef9302025-03-18 20:09:34 -07001007 if (haveBtf) {
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +09001008 uint32_t kTid, vTid;
1009 ret = getKeyValueTids(btf, mapNames[i].c_str(), md[i].key_size,
1010 md[i].value_size, &kTid, &vTid);
1011 if (ret) return ret;
1012 req.btf_fd = btf__fd(btf);
1013 req.btf_key_type_id = kTid;
1014 req.btf_value_type_id = vTid;
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +09001015 }
1016
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001017 fd.reset(bpf(BPF_MAP_CREATE, req));
1018 saved_errno = errno;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -07001019 if (fd.ok()) {
Maciej Żenczykowski9fef9302025-03-18 20:09:34 -07001020 ALOGD("bpf_create_map[%s] btf:%d -> %d",
1021 mapNames[i].c_str(), haveBtf, fd.get());
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -07001022 } else {
Maciej Żenczykowski9fef9302025-03-18 20:09:34 -07001023 ALOGE("bpf_create_map[%s] btf:%d -> %d errno:%d",
1024 mapNames[i].c_str(), haveBtf, fd.get(), saved_errno);
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -07001025 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001026 }
1027
1028 if (!fd.ok()) return -saved_errno;
1029
1030 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
1031 // safety (since reuse code path is rare) run these checks even if we just created it.
1032 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
1033 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
1034
1035 if (!reuse) {
1036 if (specified(selinux_context)) {
1037 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1038 "tmp_map_" + objName + "_" + mapNames[i];
1039 ret = bpfFdPin(fd, createLoc.c_str());
1040 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001041 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001042 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1043 return -err;
1044 }
1045 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1046 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
1047 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001048 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001049 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
1050 err, strerror(err));
1051 return -err;
1052 }
1053 } else {
1054 ret = bpfFdPin(fd, mapPinLoc.c_str());
1055 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001056 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001057 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
1058 return -err;
1059 }
1060 }
1061 ret = chmod(mapPinLoc.c_str(), md[i].mode);
1062 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001063 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001064 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
1065 strerror(err));
1066 return -err;
1067 }
1068 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
1069 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001070 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001071 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
1072 ret, err, strerror(err));
1073 return -err;
1074 }
1075 }
1076
Maciej Żenczykowskia003ace2025-02-13 16:08:18 -08001077 if (isAtLeastKernelVersion(4, 14, 0)) {
1078 int mapId = bpfGetFdMapId(fd);
1079 if (mapId == -1) {
1080 const int err = errno;
1081 ALOGE("bpfGetFdMapId failed, errno: %d", err);
1082 return -err;
1083 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001084 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
1085 }
1086
1087 mapFds.push_back(std::move(fd));
1088 }
1089
1090 return ret;
1091}
1092
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001093static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
1094 int insnIndex;
1095 struct bpf_insn *insn, *insns;
1096
1097 insns = (struct bpf_insn*)(insnsPtr);
1098
1099 insnIndex = offset / sizeof(struct bpf_insn);
1100 insn = &insns[insnIndex];
1101
1102 // Occasionally might be useful for relocation debugging, but pretty spammy
1103 if (0) {
1104 ALOGV("applying relo to instruction at byte offset: %llu, "
1105 "insn offset %d, insn %llx",
1106 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
1107 }
1108
1109 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001110 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001111 return;
1112 }
1113
1114 insn->imm = fd;
1115 insn->src_reg = BPF_PSEUDO_MAP_FD;
1116}
1117
1118static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
1119 vector<string> mapNames;
1120
1121 int ret = getSectionSymNames(elfFile, "maps", mapNames);
1122 if (ret) return;
1123
1124 for (int k = 0; k != (int)cs.size(); k++) {
1125 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
1126 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
1127
1128 for (int i = 0; i < n_rel; i++) {
1129 int symIndex = ELF64_R_SYM(rel[i].r_info);
1130 string symName;
1131
1132 ret = getSymNameByIdx(elfFile, symIndex, symName);
1133 if (ret) return;
1134
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +00001135 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001136 for (int j = 0; j < (int)mapNames.size(); j++) {
1137 if (!mapNames[j].compare(symName)) {
1138 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
1139 break;
1140 }
1141 }
1142 }
1143 }
1144}
1145
1146static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
1147 const char* prefix, const unsigned int bpfloader_ver) {
1148 unsigned kvers = kernelVersion();
1149
1150 if (!kvers) {
1151 ALOGE("unable to get kernel version");
1152 return -EINVAL;
1153 }
1154
1155 string objName = pathToObjName(string(elfPath));
1156
1157 for (int i = 0; i < (int)cs.size(); i++) {
1158 unique_fd& fd = cs[i].prog_fd;
1159 int ret;
1160 string name = cs[i].name;
1161
1162 if (!cs[i].prog_def.has_value()) {
1163 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
1164 return -EINVAL;
1165 }
1166
1167 unsigned min_kver = cs[i].prog_def->min_kver;
1168 unsigned max_kver = cs[i].prog_def->max_kver;
1169 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1170 max_kver, kvers);
1171 if (kvers < min_kver) continue;
1172 if (kvers >= max_kver) continue;
1173
1174 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1175 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1176 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1177 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001178
1179 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
1180 bpfMinVer, bpfMaxVer);
1181 if (bpfloader_ver < bpfMinVer) continue;
1182 if (bpfloader_ver >= bpfMaxVer) continue;
1183
1184 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1185 (cs[i].prog_def->ignore_on_user && isUser()) ||
1186 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1187 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1188 getBuildType().c_str());
1189 continue;
1190 }
1191
1192 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
1193 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
1194 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
1195 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
1196 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
1197 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
1198 continue;
1199 }
1200
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001201 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001202 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001203 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
1204 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1205 }
1206
1207 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001208 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001209 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
1210 lookupPinSubdir(pin_subdir));
1211 }
1212
1213 // strip any potential $foo suffix
1214 // this can be used to provide duplicate programs
1215 // conditionally loaded based on running kernel version
1216 name = name.substr(0, name.find_last_of('$'));
1217
1218 bool reuse = false;
1219 // Format of pin location is
1220 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1221 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1222 objName + '_' + string(name);
1223 if (access(progPinLoc.c_str(), F_OK) == 0) {
1224 fd.reset(retrieveProgram(progPinLoc.c_str()));
1225 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001226 !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001227 reuse = true;
1228 } else {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001229 static char log_buf[1 << 20]; // 1 MiB logging buffer
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001230
1231 union bpf_attr req = {
1232 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001233 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001234 .insns = ptr_to_u64(cs[i].data.data()),
1235 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001236 .log_level = 1,
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001237 .log_size = sizeof(log_buf),
1238 .log_buf = ptr_to_u64(log_buf),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001239 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001240 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001241 };
1242 if (isAtLeastKernelVersion(4, 15, 0))
1243 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1244 fd.reset(bpf(BPF_PROG_LOAD, req));
1245
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001246 // Kernel should have NULL terminated the log buffer, but force it anyway for safety
1247 log_buf[sizeof(log_buf) - 1] = 0;
1248
1249 // Strip out final newline if present
1250 int log_chars = strlen(log_buf);
1251 if (log_chars && log_buf[log_chars - 1] == '\n') log_buf[--log_chars] = 0;
1252
1253 bool log_oneline = !strchr(log_buf, '\n');
1254
1255 ALOGD("BPF_PROG_LOAD call for %s (%s) returned '%s' fd: %d (%s)", elfPath,
1256 cs[i].name.c_str(), log_oneline ? log_buf : "{multiline}",
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001257 fd.get(), !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001258
1259 if (!fd.ok()) {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001260 // kernel NULL terminates log_buf, so this checks for non-empty string
1261 if (log_buf[0]) {
1262 vector<string> lines = Split(log_buf, "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001263
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001264 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1265 for (const auto& line : lines) ALOGW("%s", line.c_str());
1266 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1267 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001268
1269 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001270 ALOGW("failed program %s is marked optional - continuing...",
1271 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001272 continue;
1273 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001274 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001275 }
1276 }
1277
1278 if (!fd.ok()) return fd.get();
1279
1280 if (!reuse) {
1281 if (specified(selinux_context)) {
1282 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1283 "tmp_prog_" + objName + '_' + string(name);
1284 ret = bpfFdPin(fd, createLoc.c_str());
1285 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001286 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001287 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1288 return -err;
1289 }
1290 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1291 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1292 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001293 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001294 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1295 err, strerror(err));
1296 return -err;
1297 }
1298 } else {
1299 ret = bpfFdPin(fd, progPinLoc.c_str());
1300 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001301 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001302 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1303 return -err;
1304 }
1305 }
1306 if (chmod(progPinLoc.c_str(), 0440)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001307 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001308 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1309 return -err;
1310 }
1311 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1312 (gid_t)cs[i].prog_def->gid)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001313 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001314 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1315 cs[i].prog_def->gid, err, strerror(err));
1316 return -err;
1317 }
1318 }
1319
Maciej Żenczykowski97debeb2025-02-14 11:15:36 -08001320 if (isAtLeastKernelVersion(4, 14, 0)) {
1321 int progId = bpfGetFdProgId(fd);
1322 if (progId == -1) {
1323 const int err = errno;
1324 ALOGE("bpfGetFdProgId failed, errno: %d", err);
1325 return -err;
1326 }
Maciej Żenczykowski199fd352025-02-13 15:17:08 -08001327
1328 int jitLen = bpfGetFdJitProgLen(fd);
1329 if (jitLen == -1) {
1330 const int err = errno;
1331 ALOGE("bpfGetFdJitProgLen failed, ret: %d", err);
1332 return -err;
1333 }
1334
1335 int xlatLen = bpfGetFdXlatProgLen(fd);
1336 if (xlatLen == -1) {
1337 const int err = errno;
1338 ALOGE("bpfGetFdXlatProgLen failed, ret: %d", err);
1339 return -err;
1340 }
1341 ALOGI("prog %s id %d len jit:%d xlat:%d", progPinLoc.c_str(), progId, jitLen, xlatLen);
1342
1343 if (!jitLen && bpfloader_ver >= BPFLOADER_MAINLINE_25Q2_VERSION) {
1344 ALOGE("Kernel eBPF JIT failure for %s", progPinLoc.c_str());
1345 return -ENOTSUP;
1346 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001347 }
1348 }
1349
1350 return 0;
1351}
1352
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001353int loadProg(const char* const elfPath, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001354 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001355 vector<char> license;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001356 vector<codeSection> cs;
1357 vector<unique_fd> mapFds;
1358 int ret;
1359
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001360 ifstream elfFile(elfPath, ios::in | ios::binary);
1361 if (!elfFile.is_open()) return -1;
1362
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001363 ret = readSectionByName("license", elfFile, license);
1364 if (ret) {
1365 ALOGE("Couldn't find license in %s", elfPath);
1366 return ret;
1367 } else {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001368 ALOGD("Loading ELF object %s with license %s",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001369 elfPath, (char*)license.data());
1370 }
1371
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001372 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1373 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001374
1375 // inclusive lower bound check
1376 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001377 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001378 bpfloader_ver, elfPath, bpfLoaderMinVer);
1379 return 0;
1380 }
1381
1382 // exclusive upper bound check
1383 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001384 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001385 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1386 return 0;
1387 }
1388
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001389 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001390 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1391
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001392 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001393 if (ret) {
1394 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1395 return ret;
1396 }
1397
1398 for (int i = 0; i < (int)mapFds.size(); i++)
1399 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1400
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001401 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001402 // BPF .o's with no programs are only supported by mainline netbpfload,
1403 // make sure .o's targeting non-mainline (ie. S) bpfloader don't show up.
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001404 if (ret == -ENOENT && bpfLoaderMinVer >= BPFLOADER_MAINLINE_S_VERSION)
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001405 return 0;
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001406 if (ret) {
1407 ALOGE("Couldn't read all code sections in %s", elfPath);
1408 return ret;
1409 }
1410
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001411 applyMapRelo(elfFile, mapFds, cs);
1412
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001413 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001414 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1415
1416 return ret;
1417}
1418
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001419static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001420 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001421 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001422 if (errno == ENOENT) return false;
1423 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1424 abort(); // can only hit this if permissions (likely selinux) are screwed up
1425}
1426
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001427#define APEXROOT "/apex/com.android.tethering"
1428#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001429
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001430const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001431 // S+ Tethering mainline module (network_stack): tether offload
1432 {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001433 .dir = BPFROOT "/tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001434 .prefix = "tethering/",
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001435 .t_plus = false,
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001436 },
1437 // T+ Tethering mainline module (shared with netd & system server)
1438 // netutils_wrapper (for iptables xt_bpf) has access to programs
1439 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001440 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001441 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001442 },
1443 // T+ Tethering mainline module (shared with netd & system server)
1444 // netutils_wrapper has no access, netd has read only access
1445 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001446 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001447 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001448 },
1449 // T+ Tethering mainline module (shared with system server)
1450 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001451 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001452 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001453 },
1454 // T+ Tethering mainline module (not shared, just network_stack)
1455 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001456 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001457 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001458 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001459};
1460
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001461static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001462 int retVal = 0;
1463 DIR* dir;
1464 struct dirent* ent;
1465
1466 if ((dir = opendir(location.dir)) != NULL) {
1467 while ((ent = readdir(dir)) != NULL) {
1468 string s = ent->d_name;
1469 if (!EndsWith(s, ".o")) continue;
1470
1471 string progPath(location.dir);
1472 progPath += s;
1473
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001474 int ret = loadProg(progPath.c_str(), bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001475 if (ret) {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001476 retVal = ret;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001477 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1478 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001479 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001480 }
1481 }
1482 closedir(dir);
1483 }
1484 return retVal;
1485}
1486
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001487static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001488 if (*prefix) {
1489 mode_t prevUmask = umask(0);
1490
1491 string s = "/sys/fs/bpf/";
1492 s += prefix;
1493
1494 errno = 0;
1495 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1496 if (ret && errno != EEXIST) {
1497 const int err = errno;
1498 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1499 return -err;
1500 }
1501
1502 umask(prevUmask);
1503 }
1504 return 0;
1505}
1506
1507// Technically 'value' doesn't need to be newline terminated, but it's best
1508// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1509// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001510static int writeProcSysFile(const char *filename, const char *value) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001511 unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001512 if (fd < 0) {
1513 const int err = errno;
1514 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1515 return -err;
1516 }
1517 int len = strlen(value);
1518 int v = write(fd, value, len);
1519 if (v < 0) {
1520 const int err = errno;
1521 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1522 return -err;
1523 }
1524 if (v != len) {
1525 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1526 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1527 return -EINVAL;
1528 }
1529 return 0;
1530}
1531
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001532#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001533const char * const platformBpfLoader = "/system/bin/bpfloader";
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001534const char *const uprobestatsBpfLoader =
1535 "/apex/com.android.uprobestats/bin/uprobestatsbpfload";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001536
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001537static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001538 char * found_blockdev = NULL;
1539 FILE * f = NULL;
1540 char buf[4096];
1541
1542 f = fopen("/proc/mounts", "re");
1543 if (!f) return 1;
1544
1545 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1546 while (fgets(buf, sizeof(buf), f)) {
1547 char * blockdev = buf;
1548 char * space = strchr(blockdev, ' ');
1549 if (!space) continue;
1550 *space = '\0';
1551 char * mntpath = space + 1;
1552 space = strchr(mntpath, ' ');
1553 if (!space) continue;
1554 *space = '\0';
1555 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1556 found_blockdev = strdup(blockdev);
1557 break;
1558 }
1559 fclose(f);
1560 f = NULL;
1561
1562 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001563 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001564
1565 f = fopen("/proc/mounts", "re");
1566 if (!f) { free(found_blockdev); return 3; }
1567
1568 while (fgets(buf, sizeof(buf), f)) {
1569 char * blockdev = buf;
1570 char * space = strchr(blockdev, ' ');
1571 if (!space) continue;
1572 *space = '\0';
1573 char * mntpath = space + 1;
1574 space = strchr(mntpath, ' ');
1575 if (!space) continue;
1576 *space = '\0';
1577 if (strcmp(blockdev, found_blockdev)) continue;
1578 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1579 char * at = strchr(mntpath, '@');
1580 if (!at) continue;
1581 char * ver = at + 1;
1582 ALOGI("Tethering APEX version %s", ver);
1583 }
1584 fclose(f);
1585 free(found_blockdev);
1586 return 0;
1587}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001588
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001589static bool hasGSM() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001590 static string ph = GetProperty("gsm.current.phone-type", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001591 static bool gsm = (ph != "");
1592 static bool logged = false;
1593 if (!logged) {
1594 logged = true;
1595 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1596 }
1597 return gsm;
1598}
1599
1600static bool isTV() {
1601 if (hasGSM()) return false; // TVs don't do GSM
1602
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001603 static string key = GetProperty("ro.oem.key1", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001604 static bool tv = StartsWith(key, "ATV00");
1605 static bool logged = false;
1606 if (!logged) {
1607 logged = true;
1608 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1609 }
1610 return tv;
1611}
1612
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001613static bool isWear() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001614 static string wearSdkStr = GetProperty("ro.cw_build.wear_sdk.version", "");
1615 static int wearSdkInt = GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1616 static string buildChars = GetProperty("ro.build.characteristics", "");
1617 static vector<string> v = Tokenize(buildChars, ",");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001618 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1619 static bool wear = (wearSdkInt > 0) || watch;
1620 static bool logged = false;
1621 if (!logged) {
1622 logged = true;
1623 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1624 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1625 }
1626 return wear;
1627}
1628
Motomu Utsumi712088d2025-03-18 14:52:02 +09001629static int libbpfPrint(enum libbpf_print_level lvl, const char *const formatStr,
1630 va_list argList) {
1631 int32_t prio;
1632 switch (lvl) {
1633 case LIBBPF_WARN:
1634 prio = ANDROID_LOG_WARN;
1635 break;
1636 case LIBBPF_INFO:
1637 prio = ANDROID_LOG_INFO;
1638 break;
1639 case LIBBPF_DEBUG:
1640 prio = ANDROID_LOG_DEBUG;
1641 break;
1642 }
1643 char *s = strdup(formatStr ?: "(no format string)");
1644 int len = strlen(s);
1645 if (len && s[len - 1] == '\n')
1646 s[len - 1] = 0;
1647 LOG_PRI_VA(prio, LOG_TAG, s, argList);
1648 free(s);
1649 return 0;
1650}
1651
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001652static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001653 if (!isAtLeastS) {
1654 ALOGE("Impossible - not reachable on Android <S.");
1655 // for safety, we don't fail, this is a just-in-case workaround
1656 // for any possible busted 'optimized' start everything vendor init hacks on R
1657 return 0;
1658 }
Motomu Utsumi712088d2025-03-18 14:52:02 +09001659 libbpf_set_print(libbpfPrint);
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001660
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001661 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001662
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001663 const int first_api_level = GetIntProperty("ro.board.first_api_level", api_level);
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001664
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001665 // last in U QPR2 beta1
1666 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1667 // first in U QPR2 beta~2
1668 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1669
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001670 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001671 unsigned int bpfloader_ver = BPFLOADER_MAINLINE_S_VERSION; // [42u]
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001672 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1673 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1674 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1675 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001676 if (isAtLeast25Q2) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_25Q2_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001677
Motomu Utsumia7693582025-02-05 17:40:08 +09001678 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) libbpf: v%u.%u "
1679 "uid:%d rc:%d%d",
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001680 bpfloader_ver, argv[0], android_get_device_api_level(), api_level,
Motomu Utsumia7693582025-02-05 17:40:08 +09001681 kernelVersion(), describeArch(), libbpf_major_version(),
1682 libbpf_minor_version(), getuid(), has_platform_bpfloader_rc,
1683 has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001684
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001685 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1686 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1687 return 1;
1688 }
1689
1690 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1691 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1692 return 1;
1693 }
1694
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001695 logTetheringApexVersion();
1696
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001697 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001698 if (!isAtLeastKernelVersion(4, 9, 0)) {
1699 ALOGE("Android S & T require kernel 4.9.");
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001700 return 1;
1701 }
1702
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001703 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001704 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001705 ALOGE("Android U requires kernel 4.14.");
1706 return 1;
1707 }
1708
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001709 // V bumps the kernel requirement up to 4.19
1710 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001711 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001712 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001713 return 1;
1714 }
1715
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001716 // 25Q2 bumps the kernel requirement up to 5.4
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001717 // see also: //system/netd/tests/kernel_test.cpp TestKernel54
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001718 if (isAtLeast25Q2 && !isAtLeastKernelVersion(5, 4, 0)) {
1719 ALOGE("Android 25Q2 requires kernel 5.4.");
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001720 return 1;
1721 }
1722
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001723 // Technically already required by U, but only enforce on V+
1724 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1725 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1726 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1727 if (!isTV()) return 1;
1728 }
1729
Maciej Żenczykowski127715a2025-02-10 21:52:01 -08001730 if (isKernel32Bit() && isAtLeast25Q2) {
1731 ALOGE("Android 25Q2 requires 64 bit kernel.");
1732 return 1;
1733 }
1734
Maciej Żenczykowski9b6a9942024-09-03 16:08:35 -07001735 // 6.6 is highest version supported by Android V, so this is effectively W+ (sdk=36+)
1736 if (isKernel32Bit() && isAtLeastKernelVersion(6, 7, 0)) {
1737 ALOGE("Android platform with 32 bit kernel version >= 6.7.0 is unsupported");
1738 return 1;
1739 }
1740
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001741 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1742 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001743 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001744 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001745 }
1746
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001747 if (isAtLeastV) {
1748 bool bad = false;
1749
1750 if (!isLtsKernel()) {
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001751 ALOGW("Android V+ only supports LTS kernels.");
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001752 bad = true;
1753 }
1754
1755#define REQUIRE(maj, min, sub) \
1756 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001757 ALOGW("Android V+ requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001758 bad = true; \
1759 }
1760
1761 REQUIRE(4, 19, 236)
1762 REQUIRE(5, 4, 186)
1763 REQUIRE(5, 10, 199)
1764 REQUIRE(5, 15, 136)
1765 REQUIRE(6, 1, 57)
1766 REQUIRE(6, 6, 0)
Maciej Żenczykowski06f38e32024-12-11 07:12:59 -08001767 REQUIRE(6, 12, 0)
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001768
1769#undef REQUIRE
1770
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001771 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001772 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1773 }
1774 }
1775
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001776 /* Android 14/U should only launch on 64-bit kernels
1777 * T launches on 5.10/5.15
1778 * U launches on 5.15/6.1
1779 * So >=5.16 implies isKernel64Bit()
1780 *
1781 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1782 *
1783 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1784 * we also require 64-bit userspace.
1785 *
1786 * There are various known issues with 32-bit userspace talking to various
1787 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1788 * Some of these have userspace or kernel workarounds/hacks.
1789 * Some of them don't...
1790 * We're going to be removing the hacks.
1791 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1792 * Note: this check/enforcement only applies to *system* userspace code,
1793 * it does not affect unprivileged apps, the 32-on-64 compatibility
1794 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1795 *
1796 * Additionally the 32-bit kernel jit support is poor,
1797 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001798 * Note, however, that TV and Wear devices will continue to support 32-bit userspace
1799 * on ARM64.
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001800 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001801 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001802 // Stuff won't work reliably, but...
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001803 if (isArm() && (isTV() || isWear())) {
1804 // exempt Arm TV or Wear devices (arm32 ABI is far less problematic than x86-32)
1805 ALOGW("[Arm TV/Wear] 32-bit userspace unsupported on 6.2+ kernels.");
Maciej Żenczykowski73238632025-02-24 14:50:09 -08001806 } else if (first_api_level <= 33 /*T*/ && isArm()) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001807 // also exempt Arm devices upgrading with major kernel rev from T-
1808 // might possibly be better for them to run with a newer kernel...
1809 ALOGW("[Arm KernelUpRev] 32-bit userspace unsupported on 6.2+ kernels.");
1810 } else if (isArm()) {
1811 ALOGE("[Arm] 64-bit userspace required on 6.2+ kernels (%d).", first_api_level);
1812 return 1;
1813 } else { // x86 since RiscV cannot be 32-bit
1814 ALOGE("[x86] 64-bit userspace required on 6.2+ kernels.");
1815 return 1;
1816 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001817 }
1818
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001819 // On handheld, 6.6 is highest version supported by Android V (sdk=35), so this is for sdk=36+
1820 if (!isArm() && isUserspace32bit() && isAtLeastKernelVersion(6, 7, 0)) {
Maciej Żenczykowski21b4a052024-09-03 15:46:48 -07001821 ALOGE("64-bit userspace required on 6.7+ kernels.");
1822 return 1;
1823 }
1824
Maciej Żenczykowski25e26222025-03-20 23:25:39 -07001825 if (isAtLeast25Q2) {
1826 FILE * f = fopen("/system/etc/init/netbpfload.rc", "re");
1827 if (!f) {
1828 ALOGE("failure opening /system/etc/init/netbpfload.rc");
1829 return 1;
1830 }
1831 int y = -1, q = -1, a = -1, b = -1, c = -1;
1832 int v = fscanf(f, "# %d %d %d %d %d #", &y, &q, &a, &b, &c);
1833 ALOGI("detected %d of 5: %dQ%d api:%d.%d.%d", v, y, q, a, b, c);
1834 fclose(f);
1835 if (v != 5 || y != 2025 || q != 2 || a != 36 || b || c) return 1;
1836 }
1837
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001838 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001839 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001840 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001841 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001842 return 1;
1843 }
1844
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001845 if (runningAsRoot) {
1846 // Note: writing this proc file requires being root (always the case on V+)
1847
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001848 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1849 // but we need 0 (enabled)
1850 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1851 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1852 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001853 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001854 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001855
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001856 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001857 // Note: writing these proc files requires CAP_NET_ADMIN
1858 // and sepolicy which is only present on U+,
1859 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1860 // trigger (ie. by init itself) instead.
1861
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001862 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1863 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1864 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1865 // kernel does not have CONFIG_BPF_JIT=y)
1866 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1867 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1868 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001869
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001870 // Enable JIT kallsyms export for privileged users only
1871 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1872 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1873 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1874 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001875
1876 // Create all the pin subdirectories
1877 // (this must be done first to allow selinux_context and pin_subdir functionality,
1878 // which could otherwise fail with ENOENT during object pinning or renaming,
1879 // due to ordering issues)
1880 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001881 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001882 if (createSysFsBpfSubDir(location.prefix)) return 1;
1883 }
1884
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001885 if (isAtLeastT) {
1886 // Note: there's no actual src dir for fs_bpf_loader .o's,
1887 // so it is not listed in 'locations[].prefix'.
1888 // This is because this is primarily meant for triggering genfscon rules,
1889 // and as such this will likely always be the case.
1890 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1891 if (createSysFsBpfSubDir("loader")) return 1;
1892 }
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001893
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001894 // Load all ELF objects, create programs and maps, and pin them
1895 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001896 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001897 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001898 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1899 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1900 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1901 "problems or startup script race.");
1902 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1903 sleep(20);
1904 return 2;
1905 }
1906 }
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.");
1914 return 1;
1915 }
1916
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001917 // on S we haven't created this subdir yet, but we need it for 'mainline_done' flag below
1918 if (!isAtLeastT && createSysFsBpfSubDir("netd_shared")) return 1;
1919
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001920 // leave a flag that we're done
1921 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001922
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001923 // platform bpfloader will only succeed when run as root
1924 if (!runningAsRoot) {
1925 // unreachable on U QPR3+ which always runs netbpfload as root
1926
1927 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1928 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001929 }
1930
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001931 // unreachable before U QPR3
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001932 if (exists(uprobestatsBpfLoader)) {
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001933 ALOGI("done, transferring control to uprobestatsbpfload.");
1934 const char *args[] = {
1935 uprobestatsBpfLoader,
1936 NULL,
1937 };
1938 execve(args[0], (char **)args, envp);
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001939 ALOGI("unable to execute uprobestatsbpfload, transferring control to "
1940 "platform bpfloader.");
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001941 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001942
1943 // platform BpfLoader *needs* to run as root
1944 const char * args[] = { platformBpfLoader, NULL, };
1945 execve(args[0], (char**)args, envp);
1946 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1947 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001948}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001949
1950} // namespace bpf
1951} // namespace android
1952
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001953int main(int argc, char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001954 if (android::bpf::isAtLeastT) {
1955 InitLogging(argv, &KernelLogger);
1956 } else {
1957 // S lacks the sepolicy to make non-root uid KernelLogger viable
1958 InitLogging(argv);
1959 }
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001960
1961 if (argc == 2 && !strcmp(argv[1], "done")) {
1962 // we're being re-exec'ed from platform bpfloader to 'finalize' things
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001963 if (!SetProperty("bpf.progs_loaded", "1")) {
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001964 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1965 return 125;
1966 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001967 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001968 return 0;
1969 }
1970
1971 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001972}