blob: 879f98e65d8f3e76b53bef9e964b2e7636deec99 [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
Maciej Żenczykowskif7eb2bf2025-06-10 01:56:48 -070062#define BPF_SUPPORT_CMD_FIXUP
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070063#include "BpfSyscallWrappers.h"
64#include "bpf/BpfUtils.h"
Maciej Żenczykowskid6028352024-08-19 15:20:04 -070065#include "bpf_map_def.h"
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070066
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +000067// The following matches bpf_helpers.h, which is only for inclusion in bpf code
Maciej Żenczykowski8c097782025-03-04 13:11:56 -080068#define BPFLOADER_MAINLINE_S_VERSION 42u
Maciej Żenczykowski199fd352025-02-13 15:17:08 -080069#define BPFLOADER_MAINLINE_25Q2_VERSION 47u
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +000070
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070071using android::base::EndsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070072using android::base::GetIntProperty;
73using android::base::GetProperty;
74using android::base::InitLogging;
75using android::base::KernelLogger;
76using android::base::SetProperty;
77using android::base::Split;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070078using android::base::StartsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070079using android::base::Tokenize;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070080using android::base::unique_fd;
81using std::ifstream;
82using std::ios;
83using std::optional;
84using std::string;
85using std::vector;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070086
87namespace android {
88namespace bpf {
89
90// Bpf programs may specify per-program & per-map selinux_context and pin_subdir.
91//
92// The BpfLoader needs to convert these bpf.o specified strings into an enum
93// for internal use (to check that valid values were specified for the specific
94// location of the bpf.o file).
95//
96// It also needs to map selinux_context's into pin_subdir's.
97// This is because of how selinux_context is actually implemented via pin+rename.
98//
99// Thus 'domain' enumerates all selinux_context's/pin_subdir's that the BpfLoader
100// is aware of. Thus there currently needs to be a 1:1 mapping between the two.
101//
102enum class domain : int {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700103 unspecified = 0, // means just use the default for that specific pin location
104 tethering, // (S+) fs_bpf_tethering /sys/fs/bpf/tethering
105 net_private, // (T+) fs_bpf_net_private /sys/fs/bpf/net_private
106 net_shared, // (T+) fs_bpf_net_shared /sys/fs/bpf/net_shared
107 netd_readonly, // (T+) fs_bpf_netd_readonly /sys/fs/bpf/netd_readonly
108 netd_shared, // (T+) fs_bpf_netd_shared /sys/fs/bpf/netd_shared
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700109 loader, // (U+) fs_bpf_loader /sys/fs/bpf/loader
110 // on T due to lack of sepolicy/genfscon rules it behaves simply as 'fs_bpf'
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700111};
112
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700113static constexpr domain AllDomains[] = {
114 domain::unspecified,
115 domain::tethering,
116 domain::net_private,
117 domain::net_shared,
118 domain::netd_readonly,
119 domain::netd_shared,
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700120 domain::loader,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700121};
122
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700123static constexpr bool specified(domain d) {
124 return d != domain::unspecified;
125}
126
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700127// Returns the build type string (from ro.build.type).
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700128const std::string& getBuildType() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700129 static std::string t = GetProperty("ro.build.type", "unknown");
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700130 return t;
131}
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700132
133// The following functions classify the 3 Android build types.
134inline bool isEng() {
135 return getBuildType() == "eng";
136}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700137
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700138inline bool isUser() {
139 return getBuildType() == "user";
140}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700141
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700142inline bool isUserdebug() {
143 return getBuildType() == "userdebug";
144}
145
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700146#define BPF_FS_PATH "/sys/fs/bpf/"
147
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700148static unsigned int page_size = static_cast<unsigned int>(getpagesize());
149
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700150constexpr const char* lookupSelinuxContext(const domain d) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700151 switch (d) {
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700152 case domain::unspecified: return "";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700153 case domain::tethering: return "fs_bpf_tethering";
154 case domain::net_private: return "fs_bpf_net_private";
155 case domain::net_shared: return "fs_bpf_net_shared";
156 case domain::netd_readonly: return "fs_bpf_netd_readonly";
157 case domain::netd_shared: return "fs_bpf_netd_shared";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700158 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700159 }
160}
161
162domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
163 for (domain d : AllDomains) {
164 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
165 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
166 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
167 }
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700168 ALOGE("unrecognized selinux_context '%-32s'", s);
169 // Note: we *can* just abort() here as we only load bpf .o files shipped
170 // in the same mainline module / apex as NetBpfLoad itself.
171 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700172}
173
174constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
175 switch (d) {
176 case domain::unspecified: return unspecified;
177 case domain::tethering: return "tethering/";
178 case domain::net_private: return "net_private/";
179 case domain::net_shared: return "net_shared/";
180 case domain::netd_readonly: return "netd_readonly/";
181 case domain::netd_shared: return "netd_shared/";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700182 case domain::loader: return "loader/";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700183 }
184};
185
186domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
187 for (domain d : AllDomains) {
188 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
189 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
190 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
191 }
192 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700193 // Note: we *can* just abort() here as we only load bpf .o files shipped
194 // in the same mainline module / apex as NetBpfLoad itself.
195 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700196}
197
198static string pathToObjName(const string& path) {
199 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700200 string filename = Split(path, "/").back();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700201 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
202 string name = filename.substr(0, filename.find_last_of('.'));
203 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
204 // this can be used to provide duplicate programs (mux based on the bpfloader version)
205 return name.substr(0, name.find_last_of('@'));
206}
207
208typedef struct {
209 const char* name;
210 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000211 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700212} sectionType;
213
214/*
215 * Map section name prefixes to program types, the section name will be:
216 * SECTION(<prefix>/<name-of-program>)
217 * For example:
218 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
219 * is the name of the program, and tracepoint is the type.
220 *
221 * However, be aware that you should not be directly using the SECTION() macro.
Maciej Żenczykowski3a085152024-09-18 23:45:52 +0000222 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE macros.
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700223 *
224 * Programs shipped inside the tethering apex should be limited to networking stuff,
225 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
226 * since they are less stable abi/api and may conflict with platform uses of bpf.
227 */
228sectionType sectionNameTypes[] = {
229 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
230 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000231 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
232 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700233 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
234 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
235 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
236 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
237 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
238 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
239 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700240 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
241 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
242 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
243 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000244 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
245 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700246 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
247 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
248 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000249 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700250 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
251 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000252 {"xdp/", BPF_PROG_TYPE_XDP},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700253};
254
255typedef struct {
256 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000257 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700258 string name;
259 vector<char> data;
260 vector<char> rel_data;
261 optional<struct bpf_prog_def> prog_def;
262
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000263 unique_fd prog_fd; // fd after loading
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700264} codeSection;
265
266static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
267 elfFile.seekg(0);
268 if (elfFile.fail()) return -1;
269
270 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
271
272 return 0;
273}
274
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000275// Reads all section header tables into an Shdr array
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700276static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
277 Elf64_Ehdr eh;
278 int ret = 0;
279
280 ret = readElfHeader(elfFile, &eh);
281 if (ret) return ret;
282
283 elfFile.seekg(eh.e_shoff);
284 if (elfFile.fail()) return -1;
285
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000286 // Read shdr table entries
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700287 shTable.resize(eh.e_shnum);
288
289 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
290
291 return 0;
292}
293
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000294// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700295static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
296 vector<Elf64_Shdr> shTable;
297 int ret = readSectionHeadersAll(elfFile, shTable);
298 if (ret) return ret;
299
300 elfFile.seekg(shTable[id].sh_offset);
301 if (elfFile.fail()) return -1;
302
303 sec.resize(shTable[id].sh_size);
304 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
305
306 return 0;
307}
308
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000309// Read whole section header string table
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700310static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
311 Elf64_Ehdr eh;
312 int ret = readElfHeader(elfFile, &eh);
313 if (ret) return ret;
314
315 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
316 if (ret) return ret;
317
318 return 0;
319}
320
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000321// Get name from offset in strtab
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700322static int getSymName(ifstream& elfFile, int nameOff, string& name) {
323 int ret;
324 vector<char> secStrTab;
325
326 ret = readSectionHeaderStrtab(elfFile, secStrTab);
327 if (ret) return ret;
328
329 if (nameOff >= (int)secStrTab.size()) return -1;
330
331 name = string((char*)secStrTab.data() + nameOff);
332 return 0;
333}
334
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000335// Reads a full section by name - example to get the GPL license
Motomu Utsumi99a7b732025-07-17 10:59:49 +0900336template <typename T>
337static int readSectionByName(const char* name, ifstream& elfFile, vector<T>& data) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700338 vector<char> secStrTab;
339 vector<Elf64_Shdr> shTable;
340 int ret;
341
342 ret = readSectionHeadersAll(elfFile, shTable);
343 if (ret) return ret;
344
345 ret = readSectionHeaderStrtab(elfFile, secStrTab);
346 if (ret) return ret;
347
348 for (int i = 0; i < (int)shTable.size(); i++) {
349 char* secname = secStrTab.data() + shTable[i].sh_name;
350 if (!secname) continue;
351
352 if (!strcmp(secname, name)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700353 elfFile.seekg(shTable[i].sh_offset);
354 if (elfFile.fail()) return -1;
355
Motomu Utsumi99a7b732025-07-17 10:59:49 +0900356 if (shTable[i].sh_size % sizeof(T)) return -1;
357 data.resize(shTable[i].sh_size / sizeof(T));
358 if (!elfFile.read(reinterpret_cast<char*>(data.data()), shTable[i].sh_size))
359 return -1;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700360
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700361 return 0;
362 }
363 }
364 return -2;
365}
366
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700367unsigned int readSectionUint(const char* name, ifstream& elfFile) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700368 vector<char> theBytes;
369 int ret = readSectionByName(name, elfFile, theBytes);
370 if (ret) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700371 ALOGE("Couldn't find section %s.", name);
372 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700373 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700374 ALOGE("Section %s is too short.", name);
375 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700376 } else {
377 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
378 unsigned int value = static_cast<unsigned char>(theBytes[3]);
379 value <<= 8;
380 value += static_cast<unsigned char>(theBytes[2]);
381 value <<= 8;
382 value += static_cast<unsigned char>(theBytes[1]);
383 value <<= 8;
384 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000385 ALOGD("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700386 return value;
387 }
388}
389
390static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
391 int ret;
392 vector<Elf64_Shdr> shTable;
393
394 ret = readSectionHeadersAll(elfFile, shTable);
395 if (ret) return ret;
396
397 for (int i = 0; i < (int)shTable.size(); i++) {
398 if ((int)shTable[i].sh_type != type) continue;
399
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700400 elfFile.seekg(shTable[i].sh_offset);
401 if (elfFile.fail()) return -1;
402
Motomu Utsumi1ae10a02025-07-17 10:45:19 +0900403 data.resize(shTable[i].sh_size);
404 if (!elfFile.read(data.data(), shTable[i].sh_size)) return -1;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700405
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700406 return 0;
407 }
408 return -2;
409}
410
411static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
412 return (a.st_value < b.st_value);
413}
414
415static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
416 int ret, numElems;
417 Elf64_Sym* buf;
418 vector<char> secData;
419
420 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
421 if (ret) return ret;
422
423 buf = (Elf64_Sym*)secData.data();
424 numElems = (secData.size() / sizeof(Elf64_Sym));
425 data.assign(buf, buf + numElems);
426
427 if (sort) std::sort(data.begin(), data.end(), symCompare);
428 return 0;
429}
430
431static enum bpf_prog_type getSectionType(string& name) {
432 for (auto& snt : sectionNameTypes)
433 if (StartsWith(name, snt.name)) return snt.type;
434
435 return BPF_PROG_TYPE_UNSPEC;
436}
437
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700438static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Motomu Utsumi99a7b732025-07-17 10:59:49 +0900439 return readSectionByName("progs", elfFile, pd);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700440}
441
442static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
443 optional<unsigned> symbolType = std::nullopt) {
444 int ret;
445 string name;
446 vector<Elf64_Sym> symtab;
447 vector<Elf64_Shdr> shTable;
448
449 ret = readSymTab(elfFile, 1 /* sort */, symtab);
450 if (ret) return ret;
451
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000452 // Get index of section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700453 ret = readSectionHeadersAll(elfFile, shTable);
454 if (ret) return ret;
455
456 int sec_idx = -1;
457 for (int i = 0; i < (int)shTable.size(); i++) {
458 ret = getSymName(elfFile, shTable[i].sh_name, name);
459 if (ret) return ret;
460
461 if (!name.compare(sectionName)) {
462 sec_idx = i;
463 break;
464 }
465 }
466
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000467 // No section found with matching name
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700468 if (sec_idx == -1) {
469 ALOGW("No %s section could be found in elf object", sectionName.c_str());
470 return -1;
471 }
472
473 for (int i = 0; i < (int)symtab.size(); i++) {
474 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
475
476 if (symtab[i].st_shndx == sec_idx) {
477 string s;
478 ret = getSymName(elfFile, symtab[i].st_name, s);
479 if (ret) return ret;
480 names.push_back(s);
481 }
482 }
483
484 return 0;
485}
486
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000487// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700488static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700489 vector<Elf64_Shdr> shTable;
490 int entries, ret = 0;
491
492 ret = readSectionHeadersAll(elfFile, shTable);
493 if (ret) return ret;
494 entries = shTable.size();
495
496 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700497 ret = readProgDefs(elfFile, pd);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700498 if (ret) return ret;
499 vector<string> progDefNames;
500 ret = getSectionSymNames(elfFile, "progs", progDefNames);
501 if (!pd.empty() && ret) return ret;
502
503 for (int i = 0; i < entries; i++) {
504 string name;
505 codeSection cs_temp;
506 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
507
508 ret = getSymName(elfFile, shTable[i].sh_name, name);
509 if (ret) return ret;
510
511 enum bpf_prog_type ptype = getSectionType(name);
512
513 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
514
515 // This must be done before '/' is replaced with '_'.
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000516 for (auto& snt : sectionNameTypes)
517 if (StartsWith(name, snt.name)) cs_temp.attach_type = snt.attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700518
519 string oldName = name;
520
521 // convert all slashes to underscores
522 std::replace(name.begin(), name.end(), '/', '_');
523
524 cs_temp.type = ptype;
525 cs_temp.name = name;
526
527 ret = readSectionByIdx(elfFile, i, cs_temp.data);
528 if (ret) return ret;
529 ALOGV("Loaded code section %d (%s)", i, name.c_str());
530
531 vector<string> csSymNames;
532 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
533 if (ret || !csSymNames.size()) return ret;
Motomu Utsumi62b1c882025-03-21 15:13:00 +0900534 for (size_t j = 0; j < progDefNames.size(); ++j) {
535 if (!progDefNames[j].compare(csSymNames[0] + "_def")) {
536 cs_temp.prog_def = pd[j];
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700537 break;
538 }
539 }
540
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000541 // Check for rel section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700542 if (cs_temp.data.size() > 0 && i < entries) {
543 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
544 if (ret) return ret;
545
546 if (name == (".rel" + oldName)) {
547 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
548 if (ret) return ret;
549 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
550 }
551 }
552
553 if (cs_temp.data.size() > 0) {
554 cs.push_back(std::move(cs_temp));
555 ALOGV("Adding section %d to cs list", i);
556 }
557 }
558 return 0;
559}
560
561static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
562 vector<Elf64_Sym> symtab;
563 int ret = 0;
564
565 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
566 if (ret) return ret;
567
568 if (index >= (int)symtab.size()) return -1;
569
570 return getSymName(elfFile, symtab[index].st_name, name);
571}
572
573static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
574 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
575 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
576 // so on 4.9-T kernels just pretend the map matches our expectations.
577 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
578 // This is because the primary failure mode we're trying to detect here
579 // is either a source code misconfiguration (which is likely kernel independent)
580 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
581 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
582
583 // Assuming fd is a valid Bpf Map file descriptor then
584 // all the following should always succeed on a 4.14+ kernel.
585 // If they somehow do fail, they'll return -1 (and set errno),
586 // which should then cause (among others) a key_size mismatch.
587 int fd_type = bpfGetFdMapType(fd);
588 int fd_key_size = bpfGetFdKeySize(fd);
589 int fd_value_size = bpfGetFdValueSize(fd);
590 int fd_max_entries = bpfGetFdMaxEntries(fd);
591 int fd_map_flags = bpfGetFdMapFlags(fd);
592
593 // DEVMAPs are readonly from the bpf program side's point of view, as such
594 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
595 int desired_map_flags = (int)mapDef.map_flags;
596 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
597 desired_map_flags |= BPF_F_RDONLY_PROG;
598
599 // The .h file enforces that this is a power of two, and page size will
600 // also always be a power of two, so this logic is actually enough to
601 // force it to be a multiple of the page size, as required by the kernel.
602 unsigned int desired_max_entries = mapDef.max_entries;
603 if (type == BPF_MAP_TYPE_RINGBUF) {
604 if (desired_max_entries < page_size) desired_max_entries = page_size;
605 }
606
607 // The following checks should *never* trigger, if one of them somehow does,
608 // it probably means a bpf .o file has been changed/replaced at runtime
609 // and bpfloader was manually rerun (normally it should only run *once*
610 // early during the boot process).
611 // Another possibility is that something is misconfigured in the code:
612 // most likely a shared map is declared twice differently.
613 // But such a change should never be checked into the source tree...
614 if ((fd_type == type) &&
615 (fd_key_size == (int)mapDef.key_size) &&
616 (fd_value_size == (int)mapDef.value_size) &&
617 (fd_max_entries == (int)desired_max_entries) &&
618 (fd_map_flags == desired_map_flags)) {
619 return true;
620 }
621
Maciej Żenczykowski4b3937b2025-05-29 01:24:47 -0700622 ALOGE("bpf map name %s mismatch: desired/found (errno: %d): "
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700623 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
Maciej Żenczykowski4b3937b2025-05-29 01:24:47 -0700624 mapName.c_str(), errno, type, fd_type, mapDef.key_size, fd_key_size,
625 mapDef.value_size, fd_value_size, mapDef.max_entries, fd_max_entries,
626 desired_map_flags, fd_map_flags);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700627 return false;
628}
629
Motomu Utsumib3d3c2a2025-03-18 15:06:34 +0900630static int setBtfDatasecSize(ifstream &elfFile, struct btf *btf,
631 struct btf_type *bt) {
632 const char *name = btf__name_by_offset(btf, bt->name_off);
633 if (!name) {
634 ALOGE("Couldn't resolve section name, errno: %d", errno);
635 return -errno;
636 }
637
638 vector<char> data;
639 int ret = readSectionByName(name, elfFile, data);
640 if (ret) {
641 ALOGE("Couldn't read section %s, ret: %d", name, ret);
642 return ret;
643 }
644 bt->size = data.size();
645 return 0;
646}
647
Motomu Utsumiefe33312025-03-18 15:08:15 +0900648static int getSymOffsetByName(ifstream &elfFile, const char *name, int *off) {
649 vector<Elf64_Sym> symtab;
650 int ret = readSymTab(elfFile, 1 /* sort */, symtab);
651 if (ret) return ret;
652 for (int i = 0; i < (int)symtab.size(); i++) {
653 string s;
654 ret = getSymName(elfFile, symtab[i].st_name, s);
655 if (ret) continue;
656 if (!strcmp(s.c_str(), name)) {
657 *off = symtab[i].st_value;
658 return 0;
659 }
660 }
661 return -1;
662}
663
664static int setBtfVarOffset(ifstream &elfFile, struct btf *btf,
665 struct btf_type *datasecBt) {
666 int i, vars = btf_vlen(datasecBt);
667 struct btf_var_secinfo *vsi;
668 const char *datasecName = btf__name_by_offset(btf, datasecBt->name_off);
669 if (!datasecName) {
670 ALOGE("Couldn't resolve section name, errno: %d", errno);
671 return -errno;
672 }
673
674 for (i = 0, vsi = btf_var_secinfos(datasecBt); i < vars; i++, vsi++) {
675 const struct btf_type *varBt = btf__type_by_id(btf, vsi->type);
676 if (!varBt || !btf_is_var(varBt)) {
677 ALOGE("Found non VAR kind btf_type, section: %s id: %d", datasecName,
678 vsi->type);
679 return -1;
680 }
681
682 const struct btf_var *var = btf_var(varBt);
683 if (var->linkage == BTF_VAR_STATIC) continue;
684
685 const char *varName = btf__name_by_offset(btf, varBt->name_off);
686 if (!varName) {
687 ALOGE("Failed to resolve var name, section: %s", datasecName);
688 return -1;
689 }
690
691 int off;
692 int ret = getSymOffsetByName(elfFile, varName, &off);
693 if (ret) {
694 ALOGE("No offset found in symbol table, section: %s, var: %s, ret: %d",
695 datasecName, varName, ret);
696 return ret;
697 }
698 vsi->offset = off;
699 }
700 return 0;
701}
702
Motomu Utsumi4a3b5372025-06-04 09:15:36 +0900703#define BTF_INFO_ENC(kind, kind_flag, vlen) \
704 ((!!(kind_flag) << 31) | ((kind) << 24) | ((vlen) & BTF_MAX_VLEN))
705#define BTF_INT_ENC(encoding, bits_offset, nr_bits) \
706 ((encoding) << 24 | (bits_offset) << 16 | (nr_bits))
707
708static int sanitizeBtf(struct btf *btf) {
709 for (unsigned int i = 1; i < btf__type_cnt(btf); ++i) {
710 struct btf_type *bt = (struct btf_type *)btf__type_by_id(btf, i);
711
712 // Replace BTF_KIND_VAR (5.2+) with BTF_KIND_INT (4.18+)
713 if (btf_is_var(bt)) {
714 bt->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
715 // using size = 1 is the safest choice, 4 will be too
716 // big and cause kernel BTF validation failure if
717 // original variable took less than 4 bytes
718 bt->size = 1;
719 *(int *)(bt + 1) = BTF_INT_ENC(0, 0, 8);
720 continue;
721 }
722
723 // Replace BTF_KIND_FUNC_PROTO (5.0+) with BTF_KIND_ENUM (4.18+)
724 if (btf_is_func_proto(bt)) {
725 int vlen = btf_vlen(bt);
726 bt->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
727 bt->size = sizeof(__u32); // kernel enforced
728 continue;
729 }
730
731 // Replace BTF_KIND_FUNC (5.0+) with BTF_KIND_TYPEDEF (4.18+)
732 if (btf_is_func(bt)) {
733 bt->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
734 continue;
735 }
736
737 // Replace BTF_KIND_DATASEC (5.2+) with BTF_KIND_STRUCT (4.18+)
738 if (btf_is_datasec(bt)) {
739 const struct btf_var_secinfo *v = btf_var_secinfos(bt);
740 struct btf_member *m = btf_members(bt);
741 char *name;
742
743 name = (char *)btf__name_by_offset(btf, bt->name_off);
744 while (*name) {
745 if (*name == '.' || *name == '?') *name = '_';
746 name++;
747 }
748
749 int vlen = btf_vlen(bt);
750 bt->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
751 for (int j = 0; j < vlen; j++, v++, m++) {
752 // order of field assignments is important
753 m->offset = v->offset * 8;
754 m->type = v->type;
755 // preserve variable name as member name
756 const struct btf_type *vt = btf__type_by_id(btf, v->type);
757 m->name_off = vt->name_off;
758 }
759 }
760 }
761 return 0;
762}
763
Motomu Utsumi21536e52025-03-18 15:09:27 +0900764static int loadBtf(ifstream &elfFile, struct btf *btf) {
765 int ret;
766 for (unsigned int i = 1; i < btf__type_cnt(btf); ++i) {
767 struct btf_type *bt = (struct btf_type *)btf__type_by_id(btf, i);
768 if (!btf_is_datasec(bt)) continue;
769 ret = setBtfDatasecSize(elfFile, btf, bt);
770 if (ret) return ret;
771 ret = setBtfVarOffset(elfFile, btf, bt);
772 if (ret) return ret;
773 }
774
Motomu Utsumi4a3b5372025-06-04 09:15:36 +0900775 if (!isAtLeastKernelVersion(5, 10, 0)) {
776 // Likely unnecessary on kernel 5.4 but untested.
777 sanitizeBtf(btf);
778 }
779
Motomu Utsumi21536e52025-03-18 15:09:27 +0900780 ret = btf__load_into_kernel(btf);
781 if (ret) {
782 if (errno != EINVAL) {
783 ALOGE("btf__load_into_kernel failed, errno: %d", errno);
784 return ret;
785 };
786 // For BTF_KIND_FUNC, newer kernels can read the BTF_INFO_VLEN bits of
787 // struct btf_type to distinguish static vs. global vs. extern
788 // functions, but older kernels enforce that only the BTF_INFO_KIND bits
789 // can be set. Retry with non-BTF_INFO_KIND bits zeroed out to handle
790 // this case.
791 for (unsigned int i = 1; i < btf__type_cnt(btf); ++i) {
792 struct btf_type *bt = (struct btf_type *)btf__type_by_id(btf, i);
793 if (btf_is_func(bt)) {
794 bt->info = (BTF_INFO_KIND(bt->info)) << 24;
795 }
796 }
797 ret = btf__load_into_kernel(btf);
798 if (ret) {
799 ALOGE("btf__load_into_kernel retry failed, errno: %d", errno);
800 return ret;
801 };
802 }
803 return 0;
804}
805
Motomu Utsumi59b20992025-03-18 15:10:19 +0900806int getKeyValueTids(const struct btf *btf, const char *mapName,
807 uint32_t expectedKeySize, uint32_t expectedValueSize,
808 uint32_t *keyTypeId, uint32_t *valueTypeId) {
809 const struct btf_type *kvBt;
810 const struct btf_member *key, *value;
811 const size_t max_name = 256;
812 char kvTypeName[max_name];
813 int64_t keySize, valueSize;
Motomu Utsumia6ffae22025-03-21 11:00:10 +0900814 int32_t kvId;
Motomu Utsumi59b20992025-03-18 15:10:19 +0900815
816 if (snprintf(kvTypeName, max_name, "____btf_map_%s", mapName) == max_name) {
817 ALOGE("____btf_map_%s is too long", mapName);
818 return -1;
819 }
820
821 kvId = btf__find_by_name(btf, kvTypeName);
822 if (kvId < 0) {
823 ALOGE("section not found, map: %s typeName: %s", mapName, kvTypeName);
824 return -1;
825 }
826
827 kvBt = btf__type_by_id(btf, kvId);
828 if (!kvBt) {
829 ALOGE("Couldn't find BTF type, map: %s id: %u", mapName, kvId);
830 return -1;
831 }
832
833 if (!btf_is_struct(kvBt) || btf_vlen(kvBt) < 2) {
834 ALOGE("Non Struct kind or invalid vlen, map: %s id: %u", mapName, kvId);
835 return -1;
836 }
837
838 key = btf_members(kvBt);
839 value = key + 1;
840
841 keySize = btf__resolve_size(btf, key->type);
842 if (keySize < 0) {
843 ALOGE("Couldn't get key size, map: %s errno: %d", mapName, errno);
844 return -1;
845 }
846
847 valueSize = btf__resolve_size(btf, value->type);
848 if (valueSize < 0) {
849 ALOGE("Couldn't get value size, map: %s errno: %d", mapName, errno);
850 return -1;
851 }
852
853 if (expectedKeySize != keySize || expectedValueSize != valueSize) {
854 ALOGE("Key value size mismatch, map: %s key size: %d expected key size: "
855 "%d value size: %d expected value size: %d",
856 mapName, (uint32_t)keySize, expectedKeySize, (uint32_t)valueSize,
857 expectedValueSize);
858 return -1;
859 }
860
861 *keyTypeId = key->type;
862 *valueTypeId = value->type;
863
864 return 0;
865}
866
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900867static bool isBtfSupported(enum bpf_map_type type) {
868 return type != BPF_MAP_TYPE_DEVMAP_HASH && type != BPF_MAP_TYPE_RINGBUF;
869}
870
Motomu Utsumi77b0b252025-07-15 13:36:20 +0900871static int pinMap(const unique_fd& fd, const string& mapName, const struct bpf_map_def& mapDef,
872 const string& objName, const string& mapPinLoc) {
873 int ret;
874 domain selinux_context = getDomainFromSelinuxContext(mapDef.selinux_context);
875 if (specified(selinux_context)) {
876 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapName.c_str(),
877 mapDef.selinux_context, static_cast<int>(selinux_context),
878 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
879
880 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
881 "tmp_map_" + objName + "_" + mapName;
882 ret = bpfFdPin(fd, createLoc.c_str());
883 if (ret) {
884 const int err = errno;
885 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
886 return -err;
887 }
888 ret = renameat2(AT_FDCWD, createLoc.c_str(),
889 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
890 if (ret) {
891 const int err = errno;
892 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
893 err, strerror(err));
894 return -err;
895 }
896 } else {
897 ret = bpfFdPin(fd, mapPinLoc.c_str());
898 if (ret) {
899 const int err = errno;
900 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
901 return -err;
902 }
903 }
904 ret = chmod(mapPinLoc.c_str(), mapDef.mode);
905 if (ret) {
906 const int err = errno;
907 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), mapDef.mode, ret, err,
908 strerror(err));
909 return -err;
910 }
911 ret = chown(mapPinLoc.c_str(), (uid_t)mapDef.uid, (gid_t)mapDef.gid);
912 if (ret) {
913 const int err = errno;
914 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), mapDef.uid, mapDef.gid,
915 ret, err, strerror(err));
916 return -err;
917 }
918
919 if (isAtLeastKernelVersion(4, 14, 0)) {
920 int mapId = bpfGetFdMapId(fd);
921 if (mapId == -1) {
922 const int err = errno;
923 ALOGE("bpfGetFdMapId failed, errno: %d", err);
924 return -err;
925 }
926 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
927 }
928 return 0;
929}
930
Motomu Utsumie5dcaf72025-07-01 14:44:18 +0900931static int readMapNames(ifstream& elfFile, vector<string>& mapNames) {
932 int ret = getSectionSymNames(elfFile, ".android_maps", mapNames);
933 if (ret) return ret;
934
935 const string suffix = "_def";
936 for (string& name : mapNames) {
937 if (EndsWith(name, suffix)) {
938 name.erase(name.length() - suffix.length());
939 } else {
940 ALOGE("Failed to get map names, invalid symbol in .android_maps: %s", name.c_str());
941 return 1;
942 }
943 }
944 return 0;
945}
946
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700947static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700948 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700949 int ret;
Motomu Utsumi99a7b732025-07-17 10:59:49 +0900950 vector<char> btfData;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700951 vector<struct bpf_map_def> md;
952 vector<string> mapNames;
953 string objName = pathToObjName(string(elfPath));
954
Motomu Utsumi99a7b732025-07-17 10:59:49 +0900955 ret = readSectionByName(".android_maps", elfFile, md);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700956 if (ret == -2) return 0; // no maps to read
957 if (ret) return ret;
958
Motomu Utsumie5dcaf72025-07-01 14:44:18 +0900959 ret = readMapNames(elfFile, mapNames);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700960 if (ret) return ret;
961
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900962 struct btf *btf = NULL;
Patrick Rohr03b97432025-04-17 08:37:01 -0700963 auto btfGuard = base::make_scope_guard([&btf] { if (btf) btf__free(btf); });
Motomu Utsumi4a3b5372025-06-04 09:15:36 +0900964 if (isAtLeastKernelVersion(4, 19, 0)) {
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900965 // On Linux Kernels older than 4.18 BPF_BTF_LOAD command doesn't exist.
966 ret = readSectionByName(".BTF", elfFile, btfData);
967 if (ret) {
968 ALOGE("Failed to read .BTF section, ret:%d", ret);
969 return ret;
970 }
Motomu Utsumi62b1c882025-03-21 15:13:00 +0900971 btf = btf__new(btfData.data(), btfData.size());
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900972 if (btf == NULL) {
973 ALOGE("btf__new failed, errno: %d", errno);
974 return -errno;
975 }
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900976
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +0900977 ret = loadBtf(elfFile, btf);
978 if (ret) return ret;
979 }
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900980
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700981 unsigned kvers = kernelVersion();
982
983 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700984 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000985 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700986 md[i].bpfloader_min_ver);
987 mapFds.push_back(unique_fd());
988 continue;
989 }
990
991 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000992 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700993 md[i].bpfloader_max_ver);
994 mapFds.push_back(unique_fd());
995 continue;
996 }
997
998 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000999 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001000 mapNames[i].c_str(), kvers, md[i].min_kver);
1001 mapFds.push_back(unique_fd());
1002 continue;
1003 }
1004
1005 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001006 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001007 mapNames[i].c_str(), kvers, md[i].max_kver);
1008 mapFds.push_back(unique_fd());
1009 continue;
1010 }
1011
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001012 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski87019832025-02-03 22:04:26 -08001013 if (type == BPF_MAP_TYPE_LPM_TRIE && !isAtLeastKernelVersion(4, 14, 0)) {
1014 // On Linux Kernels older than 4.14 this map type doesn't exist - autoskip.
1015 ALOGD("skipping LPM_TRIE map %s - requires kver 4.14+", mapNames[i].c_str());
1016 mapFds.push_back(unique_fd());
1017 continue;
1018 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001019 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
1020 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
1021 // of be approximated: ARRAY has the same userspace api, though it is not usable
1022 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
1023 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
1024 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
1025 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
1026 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
1027 type = BPF_MAP_TYPE_ARRAY;
1028 }
1029 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
1030 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
1031 // of be approximated: HASH has the same userspace visible api.
1032 // However it cannot be used by ebpf programs in the same way.
1033 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
1034 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
1035 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
1036 // programs as being 5.4+...
1037 type = BPF_MAP_TYPE_HASH;
1038 }
1039
1040 // The .h file enforces that this is a power of two, and page size will
1041 // also always be a power of two, so this logic is actually enough to
1042 // force it to be a multiple of the page size, as required by the kernel.
1043 unsigned int max_entries = md[i].max_entries;
1044 if (type == BPF_MAP_TYPE_RINGBUF) {
1045 if (max_entries < page_size) max_entries = page_size;
1046 }
1047
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001048 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001049 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001050 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001051 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
Maciej Żenczykowski10979ef2025-05-20 06:38:16 -07001052 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001053 }
1054
1055 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
1056 // except that maps shared across .o's have empty <objName>
1057 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
1058 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
1059 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001060 unique_fd fd;
1061 int saved_errno;
1062
1063 if (access(mapPinLoc.c_str(), F_OK) == 0) {
1064 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
1065 saved_errno = errno;
1066 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Maciej Żenczykowskib71cd4f2025-05-20 06:41:01 -07001067 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001068 } else {
1069 union bpf_attr req = {
1070 .map_type = type,
1071 .key_size = md[i].key_size,
1072 .value_size = md[i].value_size,
1073 .max_entries = max_entries,
Maciej Żenczykowskic1a9f4a2025-01-20 12:09:13 -08001074 .map_flags = md[i].map_flags,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001075 };
1076 if (isAtLeastKernelVersion(4, 15, 0))
1077 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +09001078
Motomu Utsumi6f1cecc2025-03-19 19:49:08 +09001079 bool haveBtf = btf && isBtfSupported(type);
Maciej Żenczykowski9fef9302025-03-18 20:09:34 -07001080 if (haveBtf) {
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +09001081 uint32_t kTid, vTid;
1082 ret = getKeyValueTids(btf, mapNames[i].c_str(), md[i].key_size,
1083 md[i].value_size, &kTid, &vTid);
1084 if (ret) return ret;
1085 req.btf_fd = btf__fd(btf);
1086 req.btf_key_type_id = kTid;
1087 req.btf_value_type_id = vTid;
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +09001088 }
1089
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001090 fd.reset(bpf(BPF_MAP_CREATE, req));
1091 saved_errno = errno;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -07001092 if (fd.ok()) {
Maciej Żenczykowski9fef9302025-03-18 20:09:34 -07001093 ALOGD("bpf_create_map[%s] btf:%d -> %d",
1094 mapNames[i].c_str(), haveBtf, fd.get());
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -07001095 } else {
Maciej Żenczykowski9fef9302025-03-18 20:09:34 -07001096 ALOGE("bpf_create_map[%s] btf:%d -> %d errno:%d",
1097 mapNames[i].c_str(), haveBtf, fd.get(), saved_errno);
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -07001098 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001099 }
1100
1101 if (!fd.ok()) return -saved_errno;
1102
1103 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
1104 // safety (since reuse code path is rare) run these checks even if we just created it.
1105 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
1106 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
1107
Motomu Utsumi77b0b252025-07-15 13:36:20 +09001108 ret = pinMap(fd, mapNames[i], md[i], objName, mapPinLoc);
1109 if (ret) return ret;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001110
1111 mapFds.push_back(std::move(fd));
1112 }
1113
1114 return ret;
1115}
1116
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001117static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
1118 int insnIndex;
1119 struct bpf_insn *insn, *insns;
1120
1121 insns = (struct bpf_insn*)(insnsPtr);
1122
1123 insnIndex = offset / sizeof(struct bpf_insn);
1124 insn = &insns[insnIndex];
1125
1126 // Occasionally might be useful for relocation debugging, but pretty spammy
1127 if (0) {
1128 ALOGV("applying relo to instruction at byte offset: %llu, "
1129 "insn offset %d, insn %llx",
1130 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
1131 }
1132
1133 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001134 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001135 return;
1136 }
1137
1138 insn->imm = fd;
1139 insn->src_reg = BPF_PSEUDO_MAP_FD;
1140}
1141
1142static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
1143 vector<string> mapNames;
1144
Motomu Utsumie5dcaf72025-07-01 14:44:18 +09001145 int ret = readMapNames(elfFile, mapNames);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001146 if (ret) return;
1147
1148 for (int k = 0; k != (int)cs.size(); k++) {
1149 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
1150 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
1151
1152 for (int i = 0; i < n_rel; i++) {
1153 int symIndex = ELF64_R_SYM(rel[i].r_info);
1154 string symName;
1155
1156 ret = getSymNameByIdx(elfFile, symIndex, symName);
1157 if (ret) return;
1158
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +00001159 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001160 for (int j = 0; j < (int)mapNames.size(); j++) {
1161 if (!mapNames[j].compare(symName)) {
1162 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
1163 break;
1164 }
1165 }
1166 }
1167 }
1168}
1169
Motomu Utsumi597f3af2025-07-16 14:23:46 +09001170static int pinProg(const unique_fd& fd, string& name, struct bpf_prog_def& progDef,
1171 const string& objName, string& progPinLoc) {
1172 int ret;
1173 domain selinux_context = getDomainFromSelinuxContext(progDef.selinux_context);
1174 if (specified(selinux_context)) {
1175 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
1176 progDef.selinux_context, static_cast<int>(selinux_context),
1177 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1178 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1179 "tmp_prog_" + objName + '_' + string(name);
1180 ret = bpfFdPin(fd, createLoc.c_str());
1181 if (ret) {
1182 const int err = errno;
1183 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1184 return -err;
1185 }
1186 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1187 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1188 if (ret) {
1189 const int err = errno;
1190 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1191 err, strerror(err));
1192 return -err;
1193 }
1194 } else {
1195 ret = bpfFdPin(fd, progPinLoc.c_str());
1196 if (ret) {
1197 const int err = errno;
1198 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1199 return -err;
1200 }
1201 }
1202 if (chmod(progPinLoc.c_str(), 0440)) {
1203 const int err = errno;
1204 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1205 return -err;
1206 }
1207 if (chown(progPinLoc.c_str(), (uid_t)progDef.uid,
1208 (gid_t)progDef.gid)) {
1209 const int err = errno;
1210 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), progDef.uid,
1211 progDef.gid, err, strerror(err));
1212 return -err;
1213 }
1214 return 0;
1215}
1216
Motomu Utsumi1d25bb32025-07-16 14:26:59 +09001217static int validateProg(unique_fd& fd, string& progPinLoc, const unsigned int bpfloader_ver) {
1218 if (!isAtLeastKernelVersion(4, 14, 0)) {
1219 return 0;
1220 }
1221 int progId = bpfGetFdProgId(fd);
1222 if (progId == -1) {
1223 const int err = errno;
1224 ALOGE("bpfGetFdProgId failed, errno: %d", err);
1225 return -err;
1226 }
1227
1228 int jitLen = bpfGetFdJitProgLen(fd);
1229 if (jitLen == -1) {
1230 const int err = errno;
1231 ALOGE("bpfGetFdJitProgLen failed, ret: %d", err);
1232 return -err;
1233 }
1234
1235 int xlatLen = bpfGetFdXlatProgLen(fd);
1236 if (xlatLen == -1) {
1237 const int err = errno;
1238 ALOGE("bpfGetFdXlatProgLen failed, ret: %d", err);
1239 return -err;
1240 }
1241 ALOGI("prog %s id %d len jit:%d xlat:%d", progPinLoc.c_str(), progId, jitLen, xlatLen);
1242
1243 if (!jitLen && bpfloader_ver >= BPFLOADER_MAINLINE_25Q2_VERSION) {
1244 ALOGE("Kernel eBPF JIT failure for %s", progPinLoc.c_str());
1245 return -ENOTSUP;
1246 }
1247 return 0;
1248}
1249
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001250static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
1251 const char* prefix, const unsigned int bpfloader_ver) {
1252 unsigned kvers = kernelVersion();
1253
1254 if (!kvers) {
1255 ALOGE("unable to get kernel version");
1256 return -EINVAL;
1257 }
1258
1259 string objName = pathToObjName(string(elfPath));
1260
1261 for (int i = 0; i < (int)cs.size(); i++) {
1262 unique_fd& fd = cs[i].prog_fd;
1263 int ret;
1264 string name = cs[i].name;
1265
1266 if (!cs[i].prog_def.has_value()) {
1267 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
1268 return -EINVAL;
1269 }
1270
1271 unsigned min_kver = cs[i].prog_def->min_kver;
1272 unsigned max_kver = cs[i].prog_def->max_kver;
1273 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1274 max_kver, kvers);
1275 if (kvers < min_kver) continue;
1276 if (kvers >= max_kver) continue;
1277
1278 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1279 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001280 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001281
1282 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
1283 bpfMinVer, bpfMaxVer);
1284 if (bpfloader_ver < bpfMinVer) continue;
1285 if (bpfloader_ver >= bpfMaxVer) continue;
1286
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001287 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001288 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001289 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
1290 lookupPinSubdir(pin_subdir));
Maciej Żenczykowski10979ef2025-05-20 06:38:16 -07001291 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001292 }
1293
1294 // strip any potential $foo suffix
1295 // this can be used to provide duplicate programs
1296 // conditionally loaded based on running kernel version
1297 name = name.substr(0, name.find_last_of('$'));
1298
1299 bool reuse = false;
1300 // Format of pin location is
1301 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1302 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1303 objName + '_' + string(name);
1304 if (access(progPinLoc.c_str(), F_OK) == 0) {
1305 fd.reset(retrieveProgram(progPinLoc.c_str()));
1306 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001307 !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001308 reuse = true;
1309 } else {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001310 static char log_buf[1 << 20]; // 1 MiB logging buffer
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001311
1312 union bpf_attr req = {
1313 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001314 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001315 .insns = ptr_to_u64(cs[i].data.data()),
1316 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001317 .log_level = 1,
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001318 .log_size = sizeof(log_buf),
1319 .log_buf = ptr_to_u64(log_buf),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001320 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001321 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001322 };
1323 if (isAtLeastKernelVersion(4, 15, 0))
1324 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1325 fd.reset(bpf(BPF_PROG_LOAD, req));
1326
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001327 // Kernel should have NULL terminated the log buffer, but force it anyway for safety
1328 log_buf[sizeof(log_buf) - 1] = 0;
1329
1330 // Strip out final newline if present
1331 int log_chars = strlen(log_buf);
1332 if (log_chars && log_buf[log_chars - 1] == '\n') log_buf[--log_chars] = 0;
1333
1334 bool log_oneline = !strchr(log_buf, '\n');
1335
1336 ALOGD("BPF_PROG_LOAD call for %s (%s) returned '%s' fd: %d (%s)", elfPath,
1337 cs[i].name.c_str(), log_oneline ? log_buf : "{multiline}",
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001338 fd.get(), !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001339
1340 if (!fd.ok()) {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001341 // kernel NULL terminates log_buf, so this checks for non-empty string
Maciej Żenczykowskif1259922025-07-15 14:57:23 -07001342 if (log_buf[0] && !isUser()) {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001343 vector<string> lines = Split(log_buf, "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001344
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001345 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1346 for (const auto& line : lines) ALOGW("%s", line.c_str());
1347 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1348 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001349
1350 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001351 ALOGW("failed program %s is marked optional - continuing...",
1352 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001353 continue;
1354 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001355 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001356 }
1357 }
1358
1359 if (!fd.ok()) return fd.get();
1360
1361 if (!reuse) {
Motomu Utsumi597f3af2025-07-16 14:23:46 +09001362 ret = pinProg(fd, name, cs[i].prog_def.value(), objName, progPinLoc);
1363 if (ret) return ret;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001364 }
Motomu Utsumi1d25bb32025-07-16 14:26:59 +09001365 ret = validateProg(fd, progPinLoc, bpfloader_ver);
1366 if (ret) return ret;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001367 }
1368
1369 return 0;
1370}
1371
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001372int loadProg(const char* const elfPath, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001373 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001374 vector<char> license;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001375 vector<codeSection> cs;
1376 vector<unique_fd> mapFds;
1377 int ret;
1378
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001379 ifstream elfFile(elfPath, ios::in | ios::binary);
1380 if (!elfFile.is_open()) return -1;
1381
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001382 ret = readSectionByName("license", elfFile, license);
1383 if (ret) {
1384 ALOGE("Couldn't find license in %s", elfPath);
1385 return ret;
1386 } else {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001387 ALOGD("Loading ELF object %s with license %s",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001388 elfPath, (char*)license.data());
1389 }
1390
Maciej Żenczykowskic4a1cae2025-07-15 14:23:51 -07001391 ALOGD("BpfLoader ver 0x%05x processing ELF object %s", bpfloader_ver, elfPath);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001392
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001393 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001394 if (ret) {
1395 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1396 return ret;
1397 }
1398
1399 for (int i = 0; i < (int)mapFds.size(); i++)
1400 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1401
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001402 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski66893bf2025-05-06 02:59:22 -07001403 if (ret == -ENOENT) return 0;
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001404 if (ret) {
1405 ALOGE("Couldn't read all code sections in %s", elfPath);
1406 return ret;
1407 }
1408
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001409 applyMapRelo(elfFile, mapFds, cs);
1410
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001411 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001412 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1413
1414 return ret;
1415}
1416
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001417static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001418 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001419 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001420 if (errno == ENOENT) return false;
1421 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1422 abort(); // can only hit this if permissions (likely selinux) are screwed up
1423}
1424
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001425#define APEXROOT "/apex/com.android.tethering"
Maciej Żenczykowski82ce2ca2025-05-14 14:49:28 -07001426#define BPFROOT APEXROOT "/etc/bpf/mainline/"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001427
Maciej Żenczykowski82ce2ca2025-05-14 14:49:28 -07001428static int loadObject(const unsigned int bpfloader_ver, const char* const prefix,
1429 const char* const fname) {
1430 string progPath = string(BPFROOT) + fname;
1431 int ret = loadProg(progPath.c_str(), bpfloader_ver, prefix);
1432 if (ret) {
1433 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1434 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001435 }
Maciej Żenczykowski82ce2ca2025-05-14 14:49:28 -07001436 ALOGD("Loaded object: %s", progPath.c_str());
1437 return 0;
1438}
1439
1440static int loadAllObjects(const unsigned int bpfloader_ver) {
1441 // S+ Tethering mainline module (network_stack): tether offload
1442 // loads under /sys/fs/bpf/tethering:
1443 if (loadObject(bpfloader_ver, "tethering/", "offload.o")) return 1;
1444 if (loadObject(bpfloader_ver, "tethering/", "test.o")) return 1;
1445 if (isAtLeastT) {
1446 // T+ Tethering mainline module loads under:
1447 // /sys/fs/bpf/net_shared: shared with netd & system server
1448 if (loadObject(bpfloader_ver, "net_shared/", "clatd.o")) return 1;
1449 if (loadObject(bpfloader_ver, "net_shared/", "dscpPolicy.o")) return 1;
1450
1451 // /sys/fs/bpf/netd_shared: shared with netd & system server
1452 // - netutils_wrapper (for iptables xt_bpf) has access to programs
1453
1454 // WARNING: Android T+ non-updatable netd depends on both of the
1455 // 'netd_shared' & 'netd' strings for xt_bpf programs it loads
1456 if (loadObject(bpfloader_ver, "netd_shared/", "netd.o")) return 1;
1457
1458 // /sys/fs/bpf/netd_readonly: shared with netd & system server
1459 // - netutils_wrapper has no access, netd has read only access
1460
1461 // /sys/fs/bpf/net_private: not shared, just network_stack
1462 }
1463 return 0;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001464}
1465
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001466static int createDir(const char* const dir) {
1467 mode_t prevUmask = umask(0);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001468
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001469 errno = 0;
1470 int ret = mkdir(dir, S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1471 if (ret && errno != EEXIST) {
1472 const int err = errno;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001473 umask(prevUmask);
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001474 ALOGE("Failed to create directory: %s, ret: %s", dir, std::strerror(err));
1475 return -err;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001476 }
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001477
1478 umask(prevUmask);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001479 return 0;
1480}
1481
1482// Technically 'value' doesn't need to be newline terminated, but it's best
1483// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1484// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001485static int writeProcSysFile(const char *filename, const char *value) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001486 unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001487 if (fd < 0) {
1488 const int err = errno;
1489 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1490 return -err;
1491 }
1492 int len = strlen(value);
1493 int v = write(fd, value, len);
1494 if (v < 0) {
1495 const int err = errno;
1496 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1497 return -err;
1498 }
1499 if (v != len) {
1500 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1501 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1502 return -EINVAL;
1503 }
1504 return 0;
1505}
1506
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001507#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001508const char * const platformBpfLoader = "/system/bin/bpfloader";
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001509const char *const uprobestatsBpfLoader =
1510 "/apex/com.android.uprobestats/bin/uprobestatsbpfload";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001511
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001512static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001513 char * found_blockdev = NULL;
1514 FILE * f = NULL;
1515 char buf[4096];
1516
1517 f = fopen("/proc/mounts", "re");
1518 if (!f) return 1;
1519
1520 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1521 while (fgets(buf, sizeof(buf), f)) {
1522 char * blockdev = buf;
1523 char * space = strchr(blockdev, ' ');
1524 if (!space) continue;
1525 *space = '\0';
1526 char * mntpath = space + 1;
1527 space = strchr(mntpath, ' ');
1528 if (!space) continue;
1529 *space = '\0';
1530 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1531 found_blockdev = strdup(blockdev);
1532 break;
1533 }
1534 fclose(f);
1535 f = NULL;
1536
1537 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001538 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001539
1540 f = fopen("/proc/mounts", "re");
1541 if (!f) { free(found_blockdev); return 3; }
1542
1543 while (fgets(buf, sizeof(buf), f)) {
1544 char * blockdev = buf;
1545 char * space = strchr(blockdev, ' ');
1546 if (!space) continue;
1547 *space = '\0';
1548 char * mntpath = space + 1;
1549 space = strchr(mntpath, ' ');
1550 if (!space) continue;
1551 *space = '\0';
1552 if (strcmp(blockdev, found_blockdev)) continue;
1553 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1554 char * at = strchr(mntpath, '@');
1555 if (!at) continue;
1556 char * ver = at + 1;
1557 ALOGI("Tethering APEX version %s", ver);
1558 }
1559 fclose(f);
1560 free(found_blockdev);
1561 return 0;
1562}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001563
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001564static bool hasGSM() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001565 static string ph = GetProperty("gsm.current.phone-type", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001566 static bool gsm = (ph != "");
1567 static bool logged = false;
1568 if (!logged) {
1569 logged = true;
1570 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1571 }
1572 return gsm;
1573}
1574
1575static bool isTV() {
1576 if (hasGSM()) return false; // TVs don't do GSM
1577
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001578 static string key = GetProperty("ro.oem.key1", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001579 static bool tv = StartsWith(key, "ATV00");
1580 static bool logged = false;
1581 if (!logged) {
1582 logged = true;
1583 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1584 }
1585 return tv;
1586}
1587
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001588static bool isWear() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001589 static string wearSdkStr = GetProperty("ro.cw_build.wear_sdk.version", "");
1590 static int wearSdkInt = GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1591 static string buildChars = GetProperty("ro.build.characteristics", "");
1592 static vector<string> v = Tokenize(buildChars, ",");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001593 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1594 static bool wear = (wearSdkInt > 0) || watch;
1595 static bool logged = false;
1596 if (!logged) {
1597 logged = true;
1598 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1599 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1600 }
1601 return wear;
1602}
1603
Motomu Utsumi712088d2025-03-18 14:52:02 +09001604static int libbpfPrint(enum libbpf_print_level lvl, const char *const formatStr,
1605 va_list argList) {
1606 int32_t prio;
1607 switch (lvl) {
1608 case LIBBPF_WARN:
1609 prio = ANDROID_LOG_WARN;
1610 break;
1611 case LIBBPF_INFO:
1612 prio = ANDROID_LOG_INFO;
1613 break;
1614 case LIBBPF_DEBUG:
1615 prio = ANDROID_LOG_DEBUG;
1616 break;
1617 }
1618 char *s = strdup(formatStr ?: "(no format string)");
1619 int len = strlen(s);
1620 if (len && s[len - 1] == '\n')
1621 s[len - 1] = 0;
1622 LOG_PRI_VA(prio, LOG_TAG, s, argList);
1623 free(s);
1624 return 0;
1625}
1626
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001627static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001628 if (!isAtLeastS) {
1629 ALOGE("Impossible - not reachable on Android <S.");
1630 // for safety, we don't fail, this is a just-in-case workaround
1631 // for any possible busted 'optimized' start everything vendor init hacks on R
1632 return 0;
1633 }
Motomu Utsumi712088d2025-03-18 14:52:02 +09001634 libbpf_set_print(libbpfPrint);
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001635
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001636 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001637
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001638 const int first_api_level = GetIntProperty("ro.board.first_api_level", api_level);
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001639
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001640 // last in U QPR2 beta1
1641 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1642 // first in U QPR2 beta~2
1643 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1644
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001645 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001646 unsigned int bpfloader_ver = BPFLOADER_MAINLINE_S_VERSION; // [42u]
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001647 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1648 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1649 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1650 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001651 if (isAtLeast25Q2) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_25Q2_VERSION
Maciej Żenczykowskic5b9f5e2025-05-06 02:35:27 -07001652 if (isAtLeast25Q3) ++bpfloader_ver; // [48] BPFLOADER_MAINLINE_25Q3_VERSION
1653 if (isAtLeast25Q4) ++bpfloader_ver; // [49] BPFLOADER_MAINLINE_25Q4_VERSION
1654 if (isAtLeast26Q1) ++bpfloader_ver; // [50] BPFLOADER_MAINLINE_26Q1_VERSION
1655 if (isAtLeast26Q2) ++bpfloader_ver; // [51] BPFLOADER_MAINLINE_26Q2_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001656
Motomu Utsumia7693582025-02-05 17:40:08 +09001657 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) libbpf: v%u.%u "
1658 "uid:%d rc:%d%d",
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001659 bpfloader_ver, argv[0], android_get_device_api_level(), api_level,
Motomu Utsumia7693582025-02-05 17:40:08 +09001660 kernelVersion(), describeArch(), libbpf_major_version(),
1661 libbpf_minor_version(), getuid(), has_platform_bpfloader_rc,
1662 has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001663
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001664 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1665 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1666 return 1;
1667 }
1668
1669 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1670 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1671 return 1;
1672 }
1673
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001674 logTetheringApexVersion();
1675
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001676 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001677 if (!isAtLeastKernelVersion(4, 9, 0)) {
1678 ALOGE("Android S & T require kernel 4.9.");
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001679 return 1;
1680 }
1681
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001682 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001683 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001684 ALOGE("Android U requires kernel 4.14.");
1685 return 1;
1686 }
1687
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001688 // V bumps the kernel requirement up to 4.19
1689 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001690 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001691 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001692 return 1;
1693 }
1694
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001695 // 25Q2 bumps the kernel requirement up to 5.4
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001696 // see also: //system/netd/tests/kernel_test.cpp TestKernel54
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001697 if (isAtLeast25Q2 && !isAtLeastKernelVersion(5, 4, 0)) {
1698 ALOGE("Android 25Q2 requires kernel 5.4.");
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001699 return 1;
1700 }
1701
Maciej Żenczykowskiec1115e2025-05-06 04:51:09 -07001702 // 25Q4 bumps the kernel requirement up to 5.10
1703 // see also: //system/netd/tests/kernel_test.cpp TestKernel510
1704 if (isAtLeast25Q4 && !isAtLeastKernelVersion(5, 10, 0)) {
1705 ALOGE("Android 25Q4 requires kernel 5.10.");
1706 return 1;
1707 }
1708
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001709 // Technically already required by U, but only enforce on V+
1710 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1711 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1712 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1713 if (!isTV()) return 1;
1714 }
1715
Maciej Żenczykowski127715a2025-02-10 21:52:01 -08001716 if (isKernel32Bit() && isAtLeast25Q2) {
1717 ALOGE("Android 25Q2 requires 64 bit kernel.");
1718 return 1;
1719 }
1720
Maciej Żenczykowski9b6a9942024-09-03 16:08:35 -07001721 // 6.6 is highest version supported by Android V, so this is effectively W+ (sdk=36+)
1722 if (isKernel32Bit() && isAtLeastKernelVersion(6, 7, 0)) {
1723 ALOGE("Android platform with 32 bit kernel version >= 6.7.0 is unsupported");
1724 return 1;
1725 }
1726
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001727 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1728 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001729 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001730 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001731 }
1732
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001733 if (isAtLeastV) {
1734 bool bad = false;
1735
1736 if (!isLtsKernel()) {
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001737 ALOGW("Android V+ only supports LTS kernels.");
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001738 bad = true;
1739 }
1740
1741#define REQUIRE(maj, min, sub) \
1742 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001743 ALOGW("Android V+ requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001744 bad = true; \
1745 }
1746
1747 REQUIRE(4, 19, 236)
1748 REQUIRE(5, 4, 186)
1749 REQUIRE(5, 10, 199)
1750 REQUIRE(5, 15, 136)
1751 REQUIRE(6, 1, 57)
1752 REQUIRE(6, 6, 0)
Maciej Żenczykowski06f38e32024-12-11 07:12:59 -08001753 REQUIRE(6, 12, 0)
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001754
1755#undef REQUIRE
1756
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001757 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001758 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1759 }
1760 }
1761
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001762 /* Android 14/U should only launch on 64-bit kernels
1763 * T launches on 5.10/5.15
1764 * U launches on 5.15/6.1
1765 * So >=5.16 implies isKernel64Bit()
1766 *
1767 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1768 *
1769 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1770 * we also require 64-bit userspace.
1771 *
1772 * There are various known issues with 32-bit userspace talking to various
1773 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1774 * Some of these have userspace or kernel workarounds/hacks.
1775 * Some of them don't...
1776 * We're going to be removing the hacks.
1777 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1778 * Note: this check/enforcement only applies to *system* userspace code,
1779 * it does not affect unprivileged apps, the 32-on-64 compatibility
1780 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1781 *
1782 * Additionally the 32-bit kernel jit support is poor,
1783 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001784 * Note, however, that TV and Wear devices will continue to support 32-bit userspace
1785 * on ARM64.
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001786 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001787 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001788 // Stuff won't work reliably, but...
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001789 if (isArm() && (isTV() || isWear())) {
1790 // exempt Arm TV or Wear devices (arm32 ABI is far less problematic than x86-32)
1791 ALOGW("[Arm TV/Wear] 32-bit userspace unsupported on 6.2+ kernels.");
Maciej Żenczykowski73238632025-02-24 14:50:09 -08001792 } else if (first_api_level <= 33 /*T*/ && isArm()) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001793 // also exempt Arm devices upgrading with major kernel rev from T-
1794 // might possibly be better for them to run with a newer kernel...
1795 ALOGW("[Arm KernelUpRev] 32-bit userspace unsupported on 6.2+ kernels.");
1796 } else if (isArm()) {
1797 ALOGE("[Arm] 64-bit userspace required on 6.2+ kernels (%d).", first_api_level);
1798 return 1;
1799 } else { // x86 since RiscV cannot be 32-bit
1800 ALOGE("[x86] 64-bit userspace required on 6.2+ kernels.");
1801 return 1;
1802 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001803 }
1804
Maciej Żenczykowski1da19452025-05-16 11:07:51 -07001805 // Linux 6.12 was an LTS released at the end of 2024 (Nov 17),
1806 // and was first supported by Android 16 / 25Q2 (released in June 2025).
1807 // The next Linux LTS should be released near the end of 2025,
1808 // and will likely be 6.18.
1809 // Since officially Android only supports LTS, 6.13+ really means 6.18+,
1810 // and won't be supported before 2026, most likely Android 17 / 26Q2.
1811 // 6.13+ (implying 26Q2+) requires 64-bit userspace.
1812 if (isUserspace32bit() && isAtLeastKernelVersion(6, 13, 0)) {
1813 // due to previous check only reachable on Arm && (<=T kernel uprev || TV || Wear)
1814 ALOGE("64-bit userspace required on 6.13+ kernels.");
1815 return 1;
1816 }
1817
Maciej Żenczykowski25e26222025-03-20 23:25:39 -07001818 if (isAtLeast25Q2) {
1819 FILE * f = fopen("/system/etc/init/netbpfload.rc", "re");
1820 if (!f) {
1821 ALOGE("failure opening /system/etc/init/netbpfload.rc");
1822 return 1;
1823 }
1824 int y = -1, q = -1, a = -1, b = -1, c = -1;
1825 int v = fscanf(f, "# %d %d %d %d %d #", &y, &q, &a, &b, &c);
1826 ALOGI("detected %d of 5: %dQ%d api:%d.%d.%d", v, y, q, a, b, c);
1827 fclose(f);
Maciej Żenczykowskicb555722025-05-01 06:12:00 -07001828 if (v != 5) return 1;
1829 if (y < 2025 || y > 2099) return 1;
1830 if (q < 1 || q > 4) return 1;
1831 if (a < 36) return 1;
1832 if (b < 0 || b > 4) return 1;
1833 if (c < 0) return 1;
Maciej Żenczykowski25e26222025-03-20 23:25:39 -07001834 }
1835
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001836 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001837 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001838 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001839 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001840 return 1;
1841 }
1842
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001843 if (runningAsRoot) {
1844 // Note: writing this proc file requires being root (always the case on V+)
1845
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001846 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1847 // but we need 0 (enabled)
1848 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1849 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1850 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001851 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001852 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001853
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001854 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001855 // Note: writing these proc files requires CAP_NET_ADMIN
1856 // and sepolicy which is only present on U+,
1857 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1858 // trigger (ie. by init itself) instead.
1859
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001860 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1861 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1862 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1863 // kernel does not have CONFIG_BPF_JIT=y)
1864 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1865 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1866 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001867
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001868 // Enable JIT kallsyms export for privileged users only
1869 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1870 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1871 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1872 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001873
Maciej Żenczykowski18523cb2025-06-07 05:59:44 -07001874 if (runningAsRoot) { // implies U QPR3+ and kernel 4.14+
1875 // There should not be any programs or maps yet
1876 errno = 0;
1877 uint32_t progId = bpfGetNextProgId(0); // expect 0 with errno == ENOENT
1878 if (progId || errno != ENOENT) {
1879 ALOGE("bpfGetNextProgId(zero) returned %u (errno %d)", progId, errno);
1880 return 1;
1881 }
1882 errno = 0;
1883 uint32_t mapId = bpfGetNextMapId(0); // expect 0 with errno == ENOENT
1884 if (mapId || errno != ENOENT) {
1885 ALOGE("bpfGetNextMapId(zero) returned %u (errno %d)", mapId, errno);
1886 return 1;
1887 }
1888 } else if (isAtLeastKernelVersion(4, 14, 0)) { // implies S through U QPR2
1889 // bpfGetNext{Prog,Map}Id require 4.14+
1890 // furthermore since we're not running as root, we're not the initial
1891 // platform bpfloader, so there may already be some maps & programs.
1892 uint32_t mapId = 0;
1893 while (true) {
1894 errno = 0;
1895 uint32_t next = bpfGetNextMapId(mapId);
1896 if (!next && errno == ENOENT) break;
1897 if (next <= mapId) {
1898 ALOGE("bpfGetNextMapId(%u) returned %u errno %d", mapId, next, errno);
1899 return 1;
1900 }
1901 mapId = next;
1902 }
1903 // mapId is now the last map id, creating a new map should change that
1904 unique_fd map(createMap(BPF_MAP_TYPE_ARRAY, sizeof(int), sizeof(int), 1, 0));
1905 errno = 0;
1906 uint32_t next = bpfGetNextMapId(mapId);
1907 if (next <= mapId) {
1908 // We should fail here on Xiaomi S 4.14.180 due to kernel uapi bug,
1909 // which causes bpfGetNextMapId to behave as bpfGetNextProgId,
1910 // and thus it should return 0 with errno == ENOENT.
1911 ALOGE("bpfGetNextMapId(final %d) returned %d errno %d", mapId, next, errno);
Maciej Żenczykowskif7eb2bf2025-06-10 01:56:48 -07001912 if (next || errno != ENOENT) return 1;
1913 if (isAtLeastT || isAtLeastKernelVersion(4, 20, 0)) return 1;
1914 // implies Android S with 4.14 or 4.19 kernel
1915 ALOGW("Enabling bpfCmdFixupIsNeeded.");
1916 bpfCmdFixupIsNeeded = true;
Maciej Żenczykowski18523cb2025-06-07 05:59:44 -07001917 }
1918 } else { // implies S/T with 4.9 kernel
1919 // nothing we can do.
1920 }
1921
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001922 // Create all the pin subdirectories
1923 // (this must be done first to allow selinux_context and pin_subdir functionality,
1924 // which could otherwise fail with ENOENT during object pinning or renaming,
1925 // due to ordering issues)
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001926 if (createDir("/sys/fs/bpf/tethering")) return 1;
1927 // This is technically T+ but S also needs it for the 'mainline_done' file.
1928 if (createDir("/sys/fs/bpf/netd_shared")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001929
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001930 if (isAtLeastT) {
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001931 if (createDir("/sys/fs/bpf/netd_readonly")) return 1;
1932 if (createDir("/sys/fs/bpf/net_shared")) return 1;
1933 if (createDir("/sys/fs/bpf/net_private")) return 1;
1934
1935 // This one is primarily meant for triggering genfscon rules.
1936 if (createDir("/sys/fs/bpf/loader")) return 1;
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001937 }
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001938
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001939 // Load all ELF objects, create programs and maps, and pin them
Maciej Żenczykowski82ce2ca2025-05-14 14:49:28 -07001940 if (loadAllObjects(bpfloader_ver)) {
1941 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS ===");
1942 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1943 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1944 "problems or startup script race.");
1945 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1946 sleep(20);
1947 return 2;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001948 }
1949
Maciej Żenczykowski83d5ad12025-06-17 00:48:44 -07001950 {
1951 // Create a trivial bpf map: a two element array [int->int]
1952 unique_fd map(createMap(BPF_MAP_TYPE_ARRAY, sizeof(int), sizeof(int), 2, 0));
1953
1954 int zero = 0;
1955 int kernel_bugs = bpfCmdFixupIsNeeded;
1956 if (writeToMapEntry(map, &zero, &kernel_bugs, BPF_ANY)) {
1957 ALOGE("Failure to write into index 0 of kernel bugs array.");
1958 return 1;
1959 }
1960
1961 int one = 1;
1962 int value = 123;
1963 if (writeToMapEntry(map, &one, &value, BPF_ANY)) {
1964 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1965 if (isAtLeastT) return 1;
1966 }
1967
1968 int ret = bpfFdPin(map, "/sys/fs/bpf/tethering/map_kernel_bugs");
1969 if (ret) {
1970 const int err = errno;
1971 ALOGE("pin -> %d [%d:%s]", ret, err, strerror(err));
1972 return -err;
1973 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001974 }
1975
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001976 // leave a flag that we're done
Maciej Żenczykowski57de4bf2025-05-12 17:52:04 -07001977 if (createDir("/sys/fs/bpf/netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001978
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001979 // platform bpfloader will only succeed when run as root
1980 if (!runningAsRoot) {
1981 // unreachable on U QPR3+ which always runs netbpfload as root
1982
1983 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1984 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001985 }
1986
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001987 // unreachable before U QPR3
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001988 if (exists(uprobestatsBpfLoader)) {
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001989 ALOGI("done, transferring control to uprobestatsbpfload.");
1990 const char *args[] = {
1991 uprobestatsBpfLoader,
1992 NULL,
1993 };
1994 execve(args[0], (char **)args, envp);
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001995 ALOGI("unable to execute uprobestatsbpfload, transferring control to "
1996 "platform bpfloader.");
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001997 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001998
1999 // platform BpfLoader *needs* to run as root
2000 const char * args[] = { platformBpfLoader, NULL, };
2001 execve(args[0], (char**)args, envp);
2002 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
2003 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07002004}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07002005
2006} // namespace bpf
2007} // namespace android
2008
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07002009int main(int argc, char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08002010 if (android::bpf::isAtLeastT) {
2011 InitLogging(argv, &KernelLogger);
2012 } else {
2013 // S lacks the sepolicy to make non-root uid KernelLogger viable
2014 InitLogging(argv);
2015 }
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07002016
2017 if (argc == 2 && !strcmp(argv[1], "done")) {
2018 // we're being re-exec'ed from platform bpfloader to 'finalize' things
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07002019 if (!SetProperty("bpf.progs_loaded", "1")) {
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07002020 ALOGE("Failed to set bpf.progs_loaded property to 1.");
2021 return 125;
2022 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07002023 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07002024 return 0;
2025 }
2026
2027 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07002028}