blob: 28cb09e3e763cd7870c8dee280bdad9d5c84b04c [file] [log] [blame]
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001/*
Maciej Żenczykowski49140b92024-08-07 15:06:07 -07002 * Copyright (C) 2018-2024 The Android Open Source Project
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070017#define LOG_TAG "NetBpfLoad"
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070018
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070019#include <arpa/inet.h>
Motomu Utsumib3d3c2a2025-03-18 15:06:34 +090020#include <bpf/btf.h>
Motomu Utsumia7693582025-02-05 17:40:08 +090021#include <bpf/libbpf.h>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070022#include <dirent.h>
23#include <elf.h>
24#include <errno.h>
25#include <error.h>
26#include <fcntl.h>
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070027#include <fstream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070028#include <inttypes.h>
29#include <iostream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070030#include <linux/unistd.h>
31#include <log/log.h>
32#include <net/if.h>
33#include <optional>
34#include <stdint.h>
35#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
38#include <string>
39#include <sys/mman.h>
40#include <sys/socket.h>
41#include <sys/stat.h>
42#include <sys/types.h>
43#include <sys/utsname.h>
44#include <sys/wait.h>
45#include <sysexits.h>
46#include <unistd.h>
47#include <unordered_map>
48#include <vector>
49
50#include <android-base/cmsg.h>
51#include <android-base/file.h>
52#include <android-base/logging.h>
53#include <android-base/macros.h>
54#include <android-base/properties.h>
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +090055#include <android-base/scopeguard.h>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070056#include <android-base/stringprintf.h>
57#include <android-base/strings.h>
58#include <android-base/unique_fd.h>
59#include <android/api-level.h>
60
61#include "BpfSyscallWrappers.h"
62#include "bpf/BpfUtils.h"
Maciej Żenczykowskid6028352024-08-19 15:20:04 -070063#include "bpf_map_def.h"
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070064
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +000065// The following matches bpf_helpers.h, which is only for inclusion in bpf code
Maciej Żenczykowski8c097782025-03-04 13:11:56 -080066#define BPFLOADER_MAINLINE_S_VERSION 42u
Maciej Żenczykowski199fd352025-02-13 15:17:08 -080067#define BPFLOADER_MAINLINE_25Q2_VERSION 47u
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +000068
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070069using android::base::EndsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070070using android::base::GetIntProperty;
71using android::base::GetProperty;
72using android::base::InitLogging;
73using android::base::KernelLogger;
74using android::base::SetProperty;
75using android::base::Split;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070076using android::base::StartsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070077using android::base::Tokenize;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070078using android::base::unique_fd;
79using std::ifstream;
80using std::ios;
81using std::optional;
82using std::string;
83using std::vector;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070084
85namespace android {
86namespace bpf {
87
88// Bpf programs may specify per-program & per-map selinux_context and pin_subdir.
89//
90// The BpfLoader needs to convert these bpf.o specified strings into an enum
91// for internal use (to check that valid values were specified for the specific
92// location of the bpf.o file).
93//
94// It also needs to map selinux_context's into pin_subdir's.
95// This is because of how selinux_context is actually implemented via pin+rename.
96//
97// Thus 'domain' enumerates all selinux_context's/pin_subdir's that the BpfLoader
98// is aware of. Thus there currently needs to be a 1:1 mapping between the two.
99//
100enum class domain : int {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700101 unspecified = 0, // means just use the default for that specific pin location
102 tethering, // (S+) fs_bpf_tethering /sys/fs/bpf/tethering
103 net_private, // (T+) fs_bpf_net_private /sys/fs/bpf/net_private
104 net_shared, // (T+) fs_bpf_net_shared /sys/fs/bpf/net_shared
105 netd_readonly, // (T+) fs_bpf_netd_readonly /sys/fs/bpf/netd_readonly
106 netd_shared, // (T+) fs_bpf_netd_shared /sys/fs/bpf/netd_shared
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700107 loader, // (U+) fs_bpf_loader /sys/fs/bpf/loader
108 // on T due to lack of sepolicy/genfscon rules it behaves simply as 'fs_bpf'
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700109};
110
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700111static constexpr domain AllDomains[] = {
112 domain::unspecified,
113 domain::tethering,
114 domain::net_private,
115 domain::net_shared,
116 domain::netd_readonly,
117 domain::netd_shared,
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700118 domain::loader,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700119};
120
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700121static constexpr bool specified(domain d) {
122 return d != domain::unspecified;
123}
124
125struct Location {
126 const char* const dir = "";
127 const char* const prefix = "";
Maciej Żenczykowski0b477492025-03-04 22:12:42 -0800128 const bool t_plus = true;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700129};
130
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700131// Returns the build type string (from ro.build.type).
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700132const std::string& getBuildType() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700133 static std::string t = GetProperty("ro.build.type", "unknown");
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700134 return t;
135}
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700136
137// The following functions classify the 3 Android build types.
138inline bool isEng() {
139 return getBuildType() == "eng";
140}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700141
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700142inline bool isUser() {
143 return getBuildType() == "user";
144}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700145
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700146inline bool isUserdebug() {
147 return getBuildType() == "userdebug";
148}
149
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700150#define BPF_FS_PATH "/sys/fs/bpf/"
151
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700152static unsigned int page_size = static_cast<unsigned int>(getpagesize());
153
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700154constexpr const char* lookupSelinuxContext(const domain d) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700155 switch (d) {
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700156 case domain::unspecified: return "";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700157 case domain::tethering: return "fs_bpf_tethering";
158 case domain::net_private: return "fs_bpf_net_private";
159 case domain::net_shared: return "fs_bpf_net_shared";
160 case domain::netd_readonly: return "fs_bpf_netd_readonly";
161 case domain::netd_shared: return "fs_bpf_netd_shared";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700162 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700163 }
164}
165
166domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
167 for (domain d : AllDomains) {
168 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
169 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
170 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
171 }
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700172 ALOGE("unrecognized selinux_context '%-32s'", s);
173 // Note: we *can* just abort() here as we only load bpf .o files shipped
174 // in the same mainline module / apex as NetBpfLoad itself.
175 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700176}
177
178constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
179 switch (d) {
180 case domain::unspecified: return unspecified;
181 case domain::tethering: return "tethering/";
182 case domain::net_private: return "net_private/";
183 case domain::net_shared: return "net_shared/";
184 case domain::netd_readonly: return "netd_readonly/";
185 case domain::netd_shared: return "netd_shared/";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700186 case domain::loader: return "loader/";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700187 }
188};
189
190domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
191 for (domain d : AllDomains) {
192 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
193 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
194 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
195 }
196 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700197 // Note: we *can* just abort() here as we only load bpf .o files shipped
198 // in the same mainline module / apex as NetBpfLoad itself.
199 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700200}
201
202static string pathToObjName(const string& path) {
203 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700204 string filename = Split(path, "/").back();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700205 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
206 string name = filename.substr(0, filename.find_last_of('.'));
207 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
208 // this can be used to provide duplicate programs (mux based on the bpfloader version)
209 return name.substr(0, name.find_last_of('@'));
210}
211
212typedef struct {
213 const char* name;
214 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000215 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700216} sectionType;
217
218/*
219 * Map section name prefixes to program types, the section name will be:
220 * SECTION(<prefix>/<name-of-program>)
221 * For example:
222 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
223 * is the name of the program, and tracepoint is the type.
224 *
225 * However, be aware that you should not be directly using the SECTION() macro.
Maciej Żenczykowski3a085152024-09-18 23:45:52 +0000226 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE macros.
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700227 *
228 * Programs shipped inside the tethering apex should be limited to networking stuff,
229 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
230 * since they are less stable abi/api and may conflict with platform uses of bpf.
231 */
232sectionType sectionNameTypes[] = {
233 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
234 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000235 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
236 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700237 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
238 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
239 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
240 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
241 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
242 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
243 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700244 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
245 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
246 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
247 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000248 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
249 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700250 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
251 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
252 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000253 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700254 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
255 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000256 {"xdp/", BPF_PROG_TYPE_XDP},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700257};
258
259typedef struct {
260 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000261 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700262 string name;
263 vector<char> data;
264 vector<char> rel_data;
265 optional<struct bpf_prog_def> prog_def;
266
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000267 unique_fd prog_fd; // fd after loading
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700268} codeSection;
269
270static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
271 elfFile.seekg(0);
272 if (elfFile.fail()) return -1;
273
274 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
275
276 return 0;
277}
278
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000279// Reads all section header tables into an Shdr array
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700280static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
281 Elf64_Ehdr eh;
282 int ret = 0;
283
284 ret = readElfHeader(elfFile, &eh);
285 if (ret) return ret;
286
287 elfFile.seekg(eh.e_shoff);
288 if (elfFile.fail()) return -1;
289
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000290 // Read shdr table entries
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700291 shTable.resize(eh.e_shnum);
292
293 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
294
295 return 0;
296}
297
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000298// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700299static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
300 vector<Elf64_Shdr> shTable;
301 int ret = readSectionHeadersAll(elfFile, shTable);
302 if (ret) return ret;
303
304 elfFile.seekg(shTable[id].sh_offset);
305 if (elfFile.fail()) return -1;
306
307 sec.resize(shTable[id].sh_size);
308 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
309
310 return 0;
311}
312
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000313// Read whole section header string table
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700314static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
315 Elf64_Ehdr eh;
316 int ret = readElfHeader(elfFile, &eh);
317 if (ret) return ret;
318
319 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
320 if (ret) return ret;
321
322 return 0;
323}
324
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000325// Get name from offset in strtab
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700326static int getSymName(ifstream& elfFile, int nameOff, string& name) {
327 int ret;
328 vector<char> secStrTab;
329
330 ret = readSectionHeaderStrtab(elfFile, secStrTab);
331 if (ret) return ret;
332
333 if (nameOff >= (int)secStrTab.size()) return -1;
334
335 name = string((char*)secStrTab.data() + nameOff);
336 return 0;
337}
338
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000339// Reads a full section by name - example to get the GPL license
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700340static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
341 vector<char> secStrTab;
342 vector<Elf64_Shdr> shTable;
343 int ret;
344
345 ret = readSectionHeadersAll(elfFile, shTable);
346 if (ret) return ret;
347
348 ret = readSectionHeaderStrtab(elfFile, secStrTab);
349 if (ret) return ret;
350
351 for (int i = 0; i < (int)shTable.size(); i++) {
352 char* secname = secStrTab.data() + shTable[i].sh_name;
353 if (!secname) continue;
354
355 if (!strcmp(secname, name)) {
356 vector<char> dataTmp;
357 dataTmp.resize(shTable[i].sh_size);
358
359 elfFile.seekg(shTable[i].sh_offset);
360 if (elfFile.fail()) return -1;
361
362 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
363
364 data = dataTmp;
365 return 0;
366 }
367 }
368 return -2;
369}
370
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700371unsigned int readSectionUint(const char* name, ifstream& elfFile) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700372 vector<char> theBytes;
373 int ret = readSectionByName(name, elfFile, theBytes);
374 if (ret) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700375 ALOGE("Couldn't find section %s.", name);
376 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700377 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700378 ALOGE("Section %s is too short.", name);
379 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700380 } else {
381 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
382 unsigned int value = static_cast<unsigned char>(theBytes[3]);
383 value <<= 8;
384 value += static_cast<unsigned char>(theBytes[2]);
385 value <<= 8;
386 value += static_cast<unsigned char>(theBytes[1]);
387 value <<= 8;
388 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000389 ALOGD("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700390 return value;
391 }
392}
393
394static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
395 int ret;
396 vector<Elf64_Shdr> shTable;
397
398 ret = readSectionHeadersAll(elfFile, shTable);
399 if (ret) return ret;
400
401 for (int i = 0; i < (int)shTable.size(); i++) {
402 if ((int)shTable[i].sh_type != type) continue;
403
404 vector<char> dataTmp;
405 dataTmp.resize(shTable[i].sh_size);
406
407 elfFile.seekg(shTable[i].sh_offset);
408 if (elfFile.fail()) return -1;
409
410 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
411
412 data = dataTmp;
413 return 0;
414 }
415 return -2;
416}
417
418static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
419 return (a.st_value < b.st_value);
420}
421
422static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
423 int ret, numElems;
424 Elf64_Sym* buf;
425 vector<char> secData;
426
427 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
428 if (ret) return ret;
429
430 buf = (Elf64_Sym*)secData.data();
431 numElems = (secData.size() / sizeof(Elf64_Sym));
432 data.assign(buf, buf + numElems);
433
434 if (sort) std::sort(data.begin(), data.end(), symCompare);
435 return 0;
436}
437
438static enum bpf_prog_type getSectionType(string& name) {
439 for (auto& snt : sectionNameTypes)
440 if (StartsWith(name, snt.name)) return snt.type;
441
442 return BPF_PROG_TYPE_UNSPEC;
443}
444
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700445static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700446 vector<char> pdData;
447 int ret = readSectionByName("progs", elfFile, pdData);
448 if (ret) return ret;
449
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700450 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700451 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700452 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700453 return -1;
454 };
455
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700456 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700457
458 const char* dataPtr = pdData.data();
459 for (auto& p : pd) {
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700460 // Copy the structure from the ELF file and move to the next one.
461 memcpy(&p, dataPtr, sizeof(struct bpf_prog_def));
462 dataPtr += sizeof(struct bpf_prog_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700463 }
464 return 0;
465}
466
467static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
468 optional<unsigned> symbolType = std::nullopt) {
469 int ret;
470 string name;
471 vector<Elf64_Sym> symtab;
472 vector<Elf64_Shdr> shTable;
473
474 ret = readSymTab(elfFile, 1 /* sort */, symtab);
475 if (ret) return ret;
476
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000477 // Get index of section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700478 ret = readSectionHeadersAll(elfFile, shTable);
479 if (ret) return ret;
480
481 int sec_idx = -1;
482 for (int i = 0; i < (int)shTable.size(); i++) {
483 ret = getSymName(elfFile, shTable[i].sh_name, name);
484 if (ret) return ret;
485
486 if (!name.compare(sectionName)) {
487 sec_idx = i;
488 break;
489 }
490 }
491
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000492 // No section found with matching name
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700493 if (sec_idx == -1) {
494 ALOGW("No %s section could be found in elf object", sectionName.c_str());
495 return -1;
496 }
497
498 for (int i = 0; i < (int)symtab.size(); i++) {
499 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
500
501 if (symtab[i].st_shndx == sec_idx) {
502 string s;
503 ret = getSymName(elfFile, symtab[i].st_name, s);
504 if (ret) return ret;
505 names.push_back(s);
506 }
507 }
508
509 return 0;
510}
511
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000512// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700513static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700514 vector<Elf64_Shdr> shTable;
515 int entries, ret = 0;
516
517 ret = readSectionHeadersAll(elfFile, shTable);
518 if (ret) return ret;
519 entries = shTable.size();
520
521 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700522 ret = readProgDefs(elfFile, pd);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700523 if (ret) return ret;
524 vector<string> progDefNames;
525 ret = getSectionSymNames(elfFile, "progs", progDefNames);
526 if (!pd.empty() && ret) return ret;
527
528 for (int i = 0; i < entries; i++) {
529 string name;
530 codeSection cs_temp;
531 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
532
533 ret = getSymName(elfFile, shTable[i].sh_name, name);
534 if (ret) return ret;
535
536 enum bpf_prog_type ptype = getSectionType(name);
537
538 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
539
540 // This must be done before '/' is replaced with '_'.
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000541 for (auto& snt : sectionNameTypes)
542 if (StartsWith(name, snt.name)) cs_temp.attach_type = snt.attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700543
544 string oldName = name;
545
546 // convert all slashes to underscores
547 std::replace(name.begin(), name.end(), '/', '_');
548
549 cs_temp.type = ptype;
550 cs_temp.name = name;
551
552 ret = readSectionByIdx(elfFile, i, cs_temp.data);
553 if (ret) return ret;
554 ALOGV("Loaded code section %d (%s)", i, name.c_str());
555
556 vector<string> csSymNames;
557 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
558 if (ret || !csSymNames.size()) return ret;
559 for (size_t i = 0; i < progDefNames.size(); ++i) {
560 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
561 cs_temp.prog_def = pd[i];
562 break;
563 }
564 }
565
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000566 // Check for rel section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700567 if (cs_temp.data.size() > 0 && i < entries) {
568 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
569 if (ret) return ret;
570
571 if (name == (".rel" + oldName)) {
572 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
573 if (ret) return ret;
574 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
575 }
576 }
577
578 if (cs_temp.data.size() > 0) {
579 cs.push_back(std::move(cs_temp));
580 ALOGV("Adding section %d to cs list", i);
581 }
582 }
583 return 0;
584}
585
586static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
587 vector<Elf64_Sym> symtab;
588 int ret = 0;
589
590 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
591 if (ret) return ret;
592
593 if (index >= (int)symtab.size()) return -1;
594
595 return getSymName(elfFile, symtab[index].st_name, name);
596}
597
598static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
599 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
600 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
601 // so on 4.9-T kernels just pretend the map matches our expectations.
602 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
603 // This is because the primary failure mode we're trying to detect here
604 // is either a source code misconfiguration (which is likely kernel independent)
605 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
606 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
607
608 // Assuming fd is a valid Bpf Map file descriptor then
609 // all the following should always succeed on a 4.14+ kernel.
610 // If they somehow do fail, they'll return -1 (and set errno),
611 // which should then cause (among others) a key_size mismatch.
612 int fd_type = bpfGetFdMapType(fd);
613 int fd_key_size = bpfGetFdKeySize(fd);
614 int fd_value_size = bpfGetFdValueSize(fd);
615 int fd_max_entries = bpfGetFdMaxEntries(fd);
616 int fd_map_flags = bpfGetFdMapFlags(fd);
617
618 // DEVMAPs are readonly from the bpf program side's point of view, as such
619 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
620 int desired_map_flags = (int)mapDef.map_flags;
621 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
622 desired_map_flags |= BPF_F_RDONLY_PROG;
623
624 // The .h file enforces that this is a power of two, and page size will
625 // also always be a power of two, so this logic is actually enough to
626 // force it to be a multiple of the page size, as required by the kernel.
627 unsigned int desired_max_entries = mapDef.max_entries;
628 if (type == BPF_MAP_TYPE_RINGBUF) {
629 if (desired_max_entries < page_size) desired_max_entries = page_size;
630 }
631
632 // The following checks should *never* trigger, if one of them somehow does,
633 // it probably means a bpf .o file has been changed/replaced at runtime
634 // and bpfloader was manually rerun (normally it should only run *once*
635 // early during the boot process).
636 // Another possibility is that something is misconfigured in the code:
637 // most likely a shared map is declared twice differently.
638 // But such a change should never be checked into the source tree...
639 if ((fd_type == type) &&
640 (fd_key_size == (int)mapDef.key_size) &&
641 (fd_value_size == (int)mapDef.value_size) &&
642 (fd_max_entries == (int)desired_max_entries) &&
643 (fd_map_flags == desired_map_flags)) {
644 return true;
645 }
646
647 ALOGE("bpf map name %s mismatch: desired/found: "
648 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
649 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
650 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
651 return false;
652}
653
Motomu Utsumib3d3c2a2025-03-18 15:06:34 +0900654static int setBtfDatasecSize(ifstream &elfFile, struct btf *btf,
655 struct btf_type *bt) {
656 const char *name = btf__name_by_offset(btf, bt->name_off);
657 if (!name) {
658 ALOGE("Couldn't resolve section name, errno: %d", errno);
659 return -errno;
660 }
661
662 vector<char> data;
663 int ret = readSectionByName(name, elfFile, data);
664 if (ret) {
665 ALOGE("Couldn't read section %s, ret: %d", name, ret);
666 return ret;
667 }
668 bt->size = data.size();
669 return 0;
670}
671
Motomu Utsumiefe33312025-03-18 15:08:15 +0900672static int getSymOffsetByName(ifstream &elfFile, const char *name, int *off) {
673 vector<Elf64_Sym> symtab;
674 int ret = readSymTab(elfFile, 1 /* sort */, symtab);
675 if (ret) return ret;
676 for (int i = 0; i < (int)symtab.size(); i++) {
677 string s;
678 ret = getSymName(elfFile, symtab[i].st_name, s);
679 if (ret) continue;
680 if (!strcmp(s.c_str(), name)) {
681 *off = symtab[i].st_value;
682 return 0;
683 }
684 }
685 return -1;
686}
687
688static int setBtfVarOffset(ifstream &elfFile, struct btf *btf,
689 struct btf_type *datasecBt) {
690 int i, vars = btf_vlen(datasecBt);
691 struct btf_var_secinfo *vsi;
692 const char *datasecName = btf__name_by_offset(btf, datasecBt->name_off);
693 if (!datasecName) {
694 ALOGE("Couldn't resolve section name, errno: %d", errno);
695 return -errno;
696 }
697
698 for (i = 0, vsi = btf_var_secinfos(datasecBt); i < vars; i++, vsi++) {
699 const struct btf_type *varBt = btf__type_by_id(btf, vsi->type);
700 if (!varBt || !btf_is_var(varBt)) {
701 ALOGE("Found non VAR kind btf_type, section: %s id: %d", datasecName,
702 vsi->type);
703 return -1;
704 }
705
706 const struct btf_var *var = btf_var(varBt);
707 if (var->linkage == BTF_VAR_STATIC) continue;
708
709 const char *varName = btf__name_by_offset(btf, varBt->name_off);
710 if (!varName) {
711 ALOGE("Failed to resolve var name, section: %s", datasecName);
712 return -1;
713 }
714
715 int off;
716 int ret = getSymOffsetByName(elfFile, varName, &off);
717 if (ret) {
718 ALOGE("No offset found in symbol table, section: %s, var: %s, ret: %d",
719 datasecName, varName, ret);
720 return ret;
721 }
722 vsi->offset = off;
723 }
724 return 0;
725}
726
Motomu Utsumi21536e52025-03-18 15:09:27 +0900727static int loadBtf(ifstream &elfFile, struct btf *btf) {
728 int ret;
729 for (unsigned int i = 1; i < btf__type_cnt(btf); ++i) {
730 struct btf_type *bt = (struct btf_type *)btf__type_by_id(btf, i);
731 if (!btf_is_datasec(bt)) continue;
732 ret = setBtfDatasecSize(elfFile, btf, bt);
733 if (ret) return ret;
734 ret = setBtfVarOffset(elfFile, btf, bt);
735 if (ret) return ret;
736 }
737
738 ret = btf__load_into_kernel(btf);
739 if (ret) {
740 if (errno != EINVAL) {
741 ALOGE("btf__load_into_kernel failed, errno: %d", errno);
742 return ret;
743 };
744 // For BTF_KIND_FUNC, newer kernels can read the BTF_INFO_VLEN bits of
745 // struct btf_type to distinguish static vs. global vs. extern
746 // functions, but older kernels enforce that only the BTF_INFO_KIND bits
747 // can be set. Retry with non-BTF_INFO_KIND bits zeroed out to handle
748 // this case.
749 for (unsigned int i = 1; i < btf__type_cnt(btf); ++i) {
750 struct btf_type *bt = (struct btf_type *)btf__type_by_id(btf, i);
751 if (btf_is_func(bt)) {
752 bt->info = (BTF_INFO_KIND(bt->info)) << 24;
753 }
754 }
755 ret = btf__load_into_kernel(btf);
756 if (ret) {
757 ALOGE("btf__load_into_kernel retry failed, errno: %d", errno);
758 return ret;
759 };
760 }
761 return 0;
762}
763
Motomu Utsumi59b20992025-03-18 15:10:19 +0900764int getKeyValueTids(const struct btf *btf, const char *mapName,
765 uint32_t expectedKeySize, uint32_t expectedValueSize,
766 uint32_t *keyTypeId, uint32_t *valueTypeId) {
767 const struct btf_type *kvBt;
768 const struct btf_member *key, *value;
769 const size_t max_name = 256;
770 char kvTypeName[max_name];
771 int64_t keySize, valueSize;
772 uint32_t kvId;
773
774 if (snprintf(kvTypeName, max_name, "____btf_map_%s", mapName) == max_name) {
775 ALOGE("____btf_map_%s is too long", mapName);
776 return -1;
777 }
778
779 kvId = btf__find_by_name(btf, kvTypeName);
780 if (kvId < 0) {
781 ALOGE("section not found, map: %s typeName: %s", mapName, kvTypeName);
782 return -1;
783 }
784
785 kvBt = btf__type_by_id(btf, kvId);
786 if (!kvBt) {
787 ALOGE("Couldn't find BTF type, map: %s id: %u", mapName, kvId);
788 return -1;
789 }
790
791 if (!btf_is_struct(kvBt) || btf_vlen(kvBt) < 2) {
792 ALOGE("Non Struct kind or invalid vlen, map: %s id: %u", mapName, kvId);
793 return -1;
794 }
795
796 key = btf_members(kvBt);
797 value = key + 1;
798
799 keySize = btf__resolve_size(btf, key->type);
800 if (keySize < 0) {
801 ALOGE("Couldn't get key size, map: %s errno: %d", mapName, errno);
802 return -1;
803 }
804
805 valueSize = btf__resolve_size(btf, value->type);
806 if (valueSize < 0) {
807 ALOGE("Couldn't get value size, map: %s errno: %d", mapName, errno);
808 return -1;
809 }
810
811 if (expectedKeySize != keySize || expectedValueSize != valueSize) {
812 ALOGE("Key value size mismatch, map: %s key size: %d expected key size: "
813 "%d value size: %d expected value size: %d",
814 mapName, (uint32_t)keySize, expectedKeySize, (uint32_t)valueSize,
815 expectedValueSize);
816 return -1;
817 }
818
819 *keyTypeId = key->type;
820 *valueTypeId = value->type;
821
822 return 0;
823}
824
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900825static bool isBtfSupported(enum bpf_map_type type) {
826 return type != BPF_MAP_TYPE_DEVMAP_HASH && type != BPF_MAP_TYPE_RINGBUF;
827}
828
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700829static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700830 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700831 int ret;
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900832 vector<char> mdData, btfData;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700833 vector<struct bpf_map_def> md;
834 vector<string> mapNames;
835 string objName = pathToObjName(string(elfPath));
836
837 ret = readSectionByName("maps", elfFile, mdData);
838 if (ret == -2) return 0; // no maps to read
839 if (ret) return ret;
840
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700841 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700842 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700843 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700844 return -1;
845 };
846
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700847 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700848
849 const char* dataPtr = mdData.data();
850 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700851 // Copy the structure from the ELF file and move to the next one.
852 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
853 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700854 }
855
856 ret = getSectionSymNames(elfFile, "maps", mapNames);
857 if (ret) return ret;
858
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900859 ret = readSectionByName(".BTF", elfFile, btfData);
860 if (ret) {
861 ALOGE("Failed to read .BTF section, ret:%d", ret);
862 return ret;
863 }
864 struct btf *btf = btf__new(btfData.data(), btfData.size());
865 if (btf == NULL) {
866 ALOGE("btf__new failed, errno: %d", errno);
867 return -errno;
868 }
869 auto scopeGuard = base::make_scope_guard([btf] { btf__free(btf); });
870
871 ret = loadBtf(elfFile, btf);
872 if (ret) return ret;
873
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700874 unsigned kvers = kernelVersion();
875
876 for (int i = 0; i < (int)mapNames.size(); i++) {
877 if (md[i].zero != 0) abort();
878
879 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000880 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700881 md[i].bpfloader_min_ver);
882 mapFds.push_back(unique_fd());
883 continue;
884 }
885
886 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000887 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700888 md[i].bpfloader_max_ver);
889 mapFds.push_back(unique_fd());
890 continue;
891 }
892
893 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000894 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700895 mapNames[i].c_str(), kvers, md[i].min_kver);
896 mapFds.push_back(unique_fd());
897 continue;
898 }
899
900 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000901 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700902 mapNames[i].c_str(), kvers, md[i].max_kver);
903 mapFds.push_back(unique_fd());
904 continue;
905 }
906
907 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
908 (md[i].ignore_on_userdebug && isUserdebug())) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000909 ALOGD("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700910 getBuildType().c_str());
911 mapFds.push_back(unique_fd());
912 continue;
913 }
914
915 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
916 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
917 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
918 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
919 (isRiscV() && md[i].ignore_on_riscv64)) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000920 ALOGD("skipping map %s which is ignored on %s", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700921 describeArch());
922 mapFds.push_back(unique_fd());
923 continue;
924 }
925
926 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski87019832025-02-03 22:04:26 -0800927 if (type == BPF_MAP_TYPE_LPM_TRIE && !isAtLeastKernelVersion(4, 14, 0)) {
928 // On Linux Kernels older than 4.14 this map type doesn't exist - autoskip.
929 ALOGD("skipping LPM_TRIE map %s - requires kver 4.14+", mapNames[i].c_str());
930 mapFds.push_back(unique_fd());
931 continue;
932 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700933 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
934 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
935 // of be approximated: ARRAY has the same userspace api, though it is not usable
936 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
937 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
938 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
939 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
940 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
941 type = BPF_MAP_TYPE_ARRAY;
942 }
943 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
944 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
945 // of be approximated: HASH has the same userspace visible api.
946 // However it cannot be used by ebpf programs in the same way.
947 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
948 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
949 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
950 // programs as being 5.4+...
951 type = BPF_MAP_TYPE_HASH;
952 }
953
954 // The .h file enforces that this is a power of two, and page size will
955 // also always be a power of two, so this logic is actually enough to
956 // force it to be a multiple of the page size, as required by the kernel.
957 unsigned int max_entries = md[i].max_entries;
958 if (type == BPF_MAP_TYPE_RINGBUF) {
959 if (max_entries < page_size) max_entries = page_size;
960 }
961
962 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
963 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000964 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700965 md[i].selinux_context, static_cast<int>(selinux_context),
966 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
967 }
968
969 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700970 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000971 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700972 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
973 }
974
975 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
976 // except that maps shared across .o's have empty <objName>
977 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
978 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
979 (md[i].shared ? "" : objName) + "_" + mapNames[i];
980 bool reuse = false;
981 unique_fd fd;
982 int saved_errno;
983
984 if (access(mapPinLoc.c_str(), F_OK) == 0) {
985 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
986 saved_errno = errno;
987 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
988 reuse = true;
989 } else {
990 union bpf_attr req = {
991 .map_type = type,
992 .key_size = md[i].key_size,
993 .value_size = md[i].value_size,
994 .max_entries = max_entries,
Maciej Żenczykowskic1a9f4a2025-01-20 12:09:13 -0800995 .map_flags = md[i].map_flags,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700996 };
997 if (isAtLeastKernelVersion(4, 15, 0))
998 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +0900999
1000 if (isBtfSupported(type)) {
1001 uint32_t kTid, vTid;
1002 ret = getKeyValueTids(btf, mapNames[i].c_str(), md[i].key_size,
1003 md[i].value_size, &kTid, &vTid);
1004 if (ret) return ret;
1005 req.btf_fd = btf__fd(btf);
1006 req.btf_key_type_id = kTid;
1007 req.btf_value_type_id = vTid;
1008 ALOGI("Create map with BTF, map: %s", mapNames[i].c_str());
1009 } else {
1010 ALOGI("Create map without BTF, map: %s", mapNames[i].c_str());
1011 }
1012
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001013 fd.reset(bpf(BPF_MAP_CREATE, req));
1014 saved_errno = errno;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -07001015 if (fd.ok()) {
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +09001016 ALOGD("bpf_create_map[%s] -> %d", mapNames[i].c_str(), fd.get());
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -07001017 } else {
Motomu Utsumi1a5cc5b2025-03-18 15:25:13 +09001018 ALOGE("bpf_create_map[%s] -> %d errno:%d", mapNames[i].c_str(), fd.get(), saved_errno);
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -07001019 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001020 }
1021
1022 if (!fd.ok()) return -saved_errno;
1023
1024 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
1025 // safety (since reuse code path is rare) run these checks even if we just created it.
1026 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
1027 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
1028
1029 if (!reuse) {
1030 if (specified(selinux_context)) {
1031 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1032 "tmp_map_" + objName + "_" + mapNames[i];
1033 ret = bpfFdPin(fd, createLoc.c_str());
1034 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001035 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001036 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1037 return -err;
1038 }
1039 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1040 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
1041 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001042 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001043 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
1044 err, strerror(err));
1045 return -err;
1046 }
1047 } else {
1048 ret = bpfFdPin(fd, mapPinLoc.c_str());
1049 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001050 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001051 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
1052 return -err;
1053 }
1054 }
1055 ret = chmod(mapPinLoc.c_str(), md[i].mode);
1056 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001057 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001058 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
1059 strerror(err));
1060 return -err;
1061 }
1062 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
1063 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001064 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001065 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
1066 ret, err, strerror(err));
1067 return -err;
1068 }
1069 }
1070
Maciej Żenczykowskia003ace2025-02-13 16:08:18 -08001071 if (isAtLeastKernelVersion(4, 14, 0)) {
1072 int mapId = bpfGetFdMapId(fd);
1073 if (mapId == -1) {
1074 const int err = errno;
1075 ALOGE("bpfGetFdMapId failed, errno: %d", err);
1076 return -err;
1077 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001078 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
1079 }
1080
1081 mapFds.push_back(std::move(fd));
1082 }
1083
1084 return ret;
1085}
1086
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001087static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
1088 int insnIndex;
1089 struct bpf_insn *insn, *insns;
1090
1091 insns = (struct bpf_insn*)(insnsPtr);
1092
1093 insnIndex = offset / sizeof(struct bpf_insn);
1094 insn = &insns[insnIndex];
1095
1096 // Occasionally might be useful for relocation debugging, but pretty spammy
1097 if (0) {
1098 ALOGV("applying relo to instruction at byte offset: %llu, "
1099 "insn offset %d, insn %llx",
1100 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
1101 }
1102
1103 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001104 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001105 return;
1106 }
1107
1108 insn->imm = fd;
1109 insn->src_reg = BPF_PSEUDO_MAP_FD;
1110}
1111
1112static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
1113 vector<string> mapNames;
1114
1115 int ret = getSectionSymNames(elfFile, "maps", mapNames);
1116 if (ret) return;
1117
1118 for (int k = 0; k != (int)cs.size(); k++) {
1119 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
1120 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
1121
1122 for (int i = 0; i < n_rel; i++) {
1123 int symIndex = ELF64_R_SYM(rel[i].r_info);
1124 string symName;
1125
1126 ret = getSymNameByIdx(elfFile, symIndex, symName);
1127 if (ret) return;
1128
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +00001129 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001130 for (int j = 0; j < (int)mapNames.size(); j++) {
1131 if (!mapNames[j].compare(symName)) {
1132 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
1133 break;
1134 }
1135 }
1136 }
1137 }
1138}
1139
1140static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
1141 const char* prefix, const unsigned int bpfloader_ver) {
1142 unsigned kvers = kernelVersion();
1143
1144 if (!kvers) {
1145 ALOGE("unable to get kernel version");
1146 return -EINVAL;
1147 }
1148
1149 string objName = pathToObjName(string(elfPath));
1150
1151 for (int i = 0; i < (int)cs.size(); i++) {
1152 unique_fd& fd = cs[i].prog_fd;
1153 int ret;
1154 string name = cs[i].name;
1155
1156 if (!cs[i].prog_def.has_value()) {
1157 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
1158 return -EINVAL;
1159 }
1160
1161 unsigned min_kver = cs[i].prog_def->min_kver;
1162 unsigned max_kver = cs[i].prog_def->max_kver;
1163 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1164 max_kver, kvers);
1165 if (kvers < min_kver) continue;
1166 if (kvers >= max_kver) continue;
1167
1168 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1169 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1170 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1171 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001172
1173 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
1174 bpfMinVer, bpfMaxVer);
1175 if (bpfloader_ver < bpfMinVer) continue;
1176 if (bpfloader_ver >= bpfMaxVer) continue;
1177
1178 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1179 (cs[i].prog_def->ignore_on_user && isUser()) ||
1180 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1181 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1182 getBuildType().c_str());
1183 continue;
1184 }
1185
1186 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
1187 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
1188 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
1189 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
1190 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
1191 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
1192 continue;
1193 }
1194
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001195 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001196 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001197 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
1198 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1199 }
1200
1201 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +00001202 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001203 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
1204 lookupPinSubdir(pin_subdir));
1205 }
1206
1207 // strip any potential $foo suffix
1208 // this can be used to provide duplicate programs
1209 // conditionally loaded based on running kernel version
1210 name = name.substr(0, name.find_last_of('$'));
1211
1212 bool reuse = false;
1213 // Format of pin location is
1214 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1215 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1216 objName + '_' + string(name);
1217 if (access(progPinLoc.c_str(), F_OK) == 0) {
1218 fd.reset(retrieveProgram(progPinLoc.c_str()));
1219 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001220 !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001221 reuse = true;
1222 } else {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001223 static char log_buf[1 << 20]; // 1 MiB logging buffer
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001224
1225 union bpf_attr req = {
1226 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001227 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001228 .insns = ptr_to_u64(cs[i].data.data()),
1229 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001230 .log_level = 1,
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001231 .log_size = sizeof(log_buf),
1232 .log_buf = ptr_to_u64(log_buf),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001233 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001234 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001235 };
1236 if (isAtLeastKernelVersion(4, 15, 0))
1237 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1238 fd.reset(bpf(BPF_PROG_LOAD, req));
1239
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001240 // Kernel should have NULL terminated the log buffer, but force it anyway for safety
1241 log_buf[sizeof(log_buf) - 1] = 0;
1242
1243 // Strip out final newline if present
1244 int log_chars = strlen(log_buf);
1245 if (log_chars && log_buf[log_chars - 1] == '\n') log_buf[--log_chars] = 0;
1246
1247 bool log_oneline = !strchr(log_buf, '\n');
1248
1249 ALOGD("BPF_PROG_LOAD call for %s (%s) returned '%s' fd: %d (%s)", elfPath,
1250 cs[i].name.c_str(), log_oneline ? log_buf : "{multiline}",
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001251 fd.get(), !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001252
1253 if (!fd.ok()) {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001254 // kernel NULL terminates log_buf, so this checks for non-empty string
1255 if (log_buf[0]) {
1256 vector<string> lines = Split(log_buf, "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001257
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001258 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1259 for (const auto& line : lines) ALOGW("%s", line.c_str());
1260 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1261 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001262
1263 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001264 ALOGW("failed program %s is marked optional - continuing...",
1265 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001266 continue;
1267 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001268 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001269 }
1270 }
1271
1272 if (!fd.ok()) return fd.get();
1273
1274 if (!reuse) {
1275 if (specified(selinux_context)) {
1276 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1277 "tmp_prog_" + objName + '_' + string(name);
1278 ret = bpfFdPin(fd, createLoc.c_str());
1279 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001280 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001281 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1282 return -err;
1283 }
1284 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1285 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1286 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001287 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001288 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1289 err, strerror(err));
1290 return -err;
1291 }
1292 } else {
1293 ret = bpfFdPin(fd, progPinLoc.c_str());
1294 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001295 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001296 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1297 return -err;
1298 }
1299 }
1300 if (chmod(progPinLoc.c_str(), 0440)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001301 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001302 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1303 return -err;
1304 }
1305 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1306 (gid_t)cs[i].prog_def->gid)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001307 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001308 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1309 cs[i].prog_def->gid, err, strerror(err));
1310 return -err;
1311 }
1312 }
1313
Maciej Żenczykowski97debeb2025-02-14 11:15:36 -08001314 if (isAtLeastKernelVersion(4, 14, 0)) {
1315 int progId = bpfGetFdProgId(fd);
1316 if (progId == -1) {
1317 const int err = errno;
1318 ALOGE("bpfGetFdProgId failed, errno: %d", err);
1319 return -err;
1320 }
Maciej Żenczykowski199fd352025-02-13 15:17:08 -08001321
1322 int jitLen = bpfGetFdJitProgLen(fd);
1323 if (jitLen == -1) {
1324 const int err = errno;
1325 ALOGE("bpfGetFdJitProgLen failed, ret: %d", err);
1326 return -err;
1327 }
1328
1329 int xlatLen = bpfGetFdXlatProgLen(fd);
1330 if (xlatLen == -1) {
1331 const int err = errno;
1332 ALOGE("bpfGetFdXlatProgLen failed, ret: %d", err);
1333 return -err;
1334 }
1335 ALOGI("prog %s id %d len jit:%d xlat:%d", progPinLoc.c_str(), progId, jitLen, xlatLen);
1336
1337 if (!jitLen && bpfloader_ver >= BPFLOADER_MAINLINE_25Q2_VERSION) {
1338 ALOGE("Kernel eBPF JIT failure for %s", progPinLoc.c_str());
1339 return -ENOTSUP;
1340 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001341 }
1342 }
1343
1344 return 0;
1345}
1346
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001347int loadProg(const char* const elfPath, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001348 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001349 vector<char> license;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001350 vector<codeSection> cs;
1351 vector<unique_fd> mapFds;
1352 int ret;
1353
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001354 ifstream elfFile(elfPath, ios::in | ios::binary);
1355 if (!elfFile.is_open()) return -1;
1356
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001357 ret = readSectionByName("license", elfFile, license);
1358 if (ret) {
1359 ALOGE("Couldn't find license in %s", elfPath);
1360 return ret;
1361 } else {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001362 ALOGD("Loading ELF object %s with license %s",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001363 elfPath, (char*)license.data());
1364 }
1365
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001366 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1367 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001368
1369 // inclusive lower bound check
1370 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001371 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001372 bpfloader_ver, elfPath, bpfLoaderMinVer);
1373 return 0;
1374 }
1375
1376 // exclusive upper bound check
1377 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001378 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001379 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1380 return 0;
1381 }
1382
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001383 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001384 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1385
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001386 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001387 if (ret) {
1388 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1389 return ret;
1390 }
1391
1392 for (int i = 0; i < (int)mapFds.size(); i++)
1393 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1394
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001395 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001396 // BPF .o's with no programs are only supported by mainline netbpfload,
1397 // make sure .o's targeting non-mainline (ie. S) bpfloader don't show up.
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001398 if (ret == -ENOENT && bpfLoaderMinVer >= BPFLOADER_MAINLINE_S_VERSION)
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001399 return 0;
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001400 if (ret) {
1401 ALOGE("Couldn't read all code sections in %s", elfPath);
1402 return ret;
1403 }
1404
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001405 applyMapRelo(elfFile, mapFds, cs);
1406
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001407 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001408 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1409
1410 return ret;
1411}
1412
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001413static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001414 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001415 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001416 if (errno == ENOENT) return false;
1417 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1418 abort(); // can only hit this if permissions (likely selinux) are screwed up
1419}
1420
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001421#define APEXROOT "/apex/com.android.tethering"
1422#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001423
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001424const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001425 // S+ Tethering mainline module (network_stack): tether offload
1426 {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001427 .dir = BPFROOT "/tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001428 .prefix = "tethering/",
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001429 .t_plus = false,
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001430 },
1431 // T+ Tethering mainline module (shared with netd & system server)
1432 // netutils_wrapper (for iptables xt_bpf) has access to programs
1433 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001434 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001435 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001436 },
1437 // T+ Tethering mainline module (shared with netd & system server)
1438 // netutils_wrapper has no access, netd has read only access
1439 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001440 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001441 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001442 },
1443 // T+ Tethering mainline module (shared with system server)
1444 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001445 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001446 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001447 },
1448 // T+ Tethering mainline module (not shared, just network_stack)
1449 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001450 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001451 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001452 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001453};
1454
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001455static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001456 int retVal = 0;
1457 DIR* dir;
1458 struct dirent* ent;
1459
1460 if ((dir = opendir(location.dir)) != NULL) {
1461 while ((ent = readdir(dir)) != NULL) {
1462 string s = ent->d_name;
1463 if (!EndsWith(s, ".o")) continue;
1464
1465 string progPath(location.dir);
1466 progPath += s;
1467
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001468 int ret = loadProg(progPath.c_str(), bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001469 if (ret) {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001470 retVal = ret;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001471 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1472 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001473 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001474 }
1475 }
1476 closedir(dir);
1477 }
1478 return retVal;
1479}
1480
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001481static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001482 if (*prefix) {
1483 mode_t prevUmask = umask(0);
1484
1485 string s = "/sys/fs/bpf/";
1486 s += prefix;
1487
1488 errno = 0;
1489 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1490 if (ret && errno != EEXIST) {
1491 const int err = errno;
1492 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1493 return -err;
1494 }
1495
1496 umask(prevUmask);
1497 }
1498 return 0;
1499}
1500
1501// Technically 'value' doesn't need to be newline terminated, but it's best
1502// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1503// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001504static int writeProcSysFile(const char *filename, const char *value) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001505 unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001506 if (fd < 0) {
1507 const int err = errno;
1508 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1509 return -err;
1510 }
1511 int len = strlen(value);
1512 int v = write(fd, value, len);
1513 if (v < 0) {
1514 const int err = errno;
1515 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1516 return -err;
1517 }
1518 if (v != len) {
1519 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1520 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1521 return -EINVAL;
1522 }
1523 return 0;
1524}
1525
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001526#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001527const char * const platformBpfLoader = "/system/bin/bpfloader";
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001528const char *const uprobestatsBpfLoader =
1529 "/apex/com.android.uprobestats/bin/uprobestatsbpfload";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001530
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001531static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001532 char * found_blockdev = NULL;
1533 FILE * f = NULL;
1534 char buf[4096];
1535
1536 f = fopen("/proc/mounts", "re");
1537 if (!f) return 1;
1538
1539 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1540 while (fgets(buf, sizeof(buf), f)) {
1541 char * blockdev = buf;
1542 char * space = strchr(blockdev, ' ');
1543 if (!space) continue;
1544 *space = '\0';
1545 char * mntpath = space + 1;
1546 space = strchr(mntpath, ' ');
1547 if (!space) continue;
1548 *space = '\0';
1549 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1550 found_blockdev = strdup(blockdev);
1551 break;
1552 }
1553 fclose(f);
1554 f = NULL;
1555
1556 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001557 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001558
1559 f = fopen("/proc/mounts", "re");
1560 if (!f) { free(found_blockdev); return 3; }
1561
1562 while (fgets(buf, sizeof(buf), f)) {
1563 char * blockdev = buf;
1564 char * space = strchr(blockdev, ' ');
1565 if (!space) continue;
1566 *space = '\0';
1567 char * mntpath = space + 1;
1568 space = strchr(mntpath, ' ');
1569 if (!space) continue;
1570 *space = '\0';
1571 if (strcmp(blockdev, found_blockdev)) continue;
1572 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1573 char * at = strchr(mntpath, '@');
1574 if (!at) continue;
1575 char * ver = at + 1;
1576 ALOGI("Tethering APEX version %s", ver);
1577 }
1578 fclose(f);
1579 free(found_blockdev);
1580 return 0;
1581}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001582
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001583static bool hasGSM() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001584 static string ph = GetProperty("gsm.current.phone-type", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001585 static bool gsm = (ph != "");
1586 static bool logged = false;
1587 if (!logged) {
1588 logged = true;
1589 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1590 }
1591 return gsm;
1592}
1593
1594static bool isTV() {
1595 if (hasGSM()) return false; // TVs don't do GSM
1596
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001597 static string key = GetProperty("ro.oem.key1", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001598 static bool tv = StartsWith(key, "ATV00");
1599 static bool logged = false;
1600 if (!logged) {
1601 logged = true;
1602 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1603 }
1604 return tv;
1605}
1606
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001607static bool isWear() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001608 static string wearSdkStr = GetProperty("ro.cw_build.wear_sdk.version", "");
1609 static int wearSdkInt = GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1610 static string buildChars = GetProperty("ro.build.characteristics", "");
1611 static vector<string> v = Tokenize(buildChars, ",");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001612 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1613 static bool wear = (wearSdkInt > 0) || watch;
1614 static bool logged = false;
1615 if (!logged) {
1616 logged = true;
1617 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1618 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1619 }
1620 return wear;
1621}
1622
Motomu Utsumi712088d2025-03-18 14:52:02 +09001623static int libbpfPrint(enum libbpf_print_level lvl, const char *const formatStr,
1624 va_list argList) {
1625 int32_t prio;
1626 switch (lvl) {
1627 case LIBBPF_WARN:
1628 prio = ANDROID_LOG_WARN;
1629 break;
1630 case LIBBPF_INFO:
1631 prio = ANDROID_LOG_INFO;
1632 break;
1633 case LIBBPF_DEBUG:
1634 prio = ANDROID_LOG_DEBUG;
1635 break;
1636 }
1637 char *s = strdup(formatStr ?: "(no format string)");
1638 int len = strlen(s);
1639 if (len && s[len - 1] == '\n')
1640 s[len - 1] = 0;
1641 LOG_PRI_VA(prio, LOG_TAG, s, argList);
1642 free(s);
1643 return 0;
1644}
1645
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001646static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001647 if (!isAtLeastS) {
1648 ALOGE("Impossible - not reachable on Android <S.");
1649 // for safety, we don't fail, this is a just-in-case workaround
1650 // for any possible busted 'optimized' start everything vendor init hacks on R
1651 return 0;
1652 }
Motomu Utsumi712088d2025-03-18 14:52:02 +09001653 libbpf_set_print(libbpfPrint);
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001654
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001655 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001656
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001657 const int first_api_level = GetIntProperty("ro.board.first_api_level", api_level);
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001658
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001659 // last in U QPR2 beta1
1660 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1661 // first in U QPR2 beta~2
1662 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1663
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001664 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001665 unsigned int bpfloader_ver = BPFLOADER_MAINLINE_S_VERSION; // [42u]
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001666 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1667 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1668 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1669 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001670 if (isAtLeast25Q2) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_25Q2_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001671
Motomu Utsumia7693582025-02-05 17:40:08 +09001672 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) libbpf: v%u.%u "
1673 "uid:%d rc:%d%d",
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001674 bpfloader_ver, argv[0], android_get_device_api_level(), api_level,
Motomu Utsumia7693582025-02-05 17:40:08 +09001675 kernelVersion(), describeArch(), libbpf_major_version(),
1676 libbpf_minor_version(), getuid(), has_platform_bpfloader_rc,
1677 has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001678
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001679 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1680 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1681 return 1;
1682 }
1683
1684 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1685 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1686 return 1;
1687 }
1688
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001689 logTetheringApexVersion();
1690
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001691 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001692 if (!isAtLeastKernelVersion(4, 9, 0)) {
1693 ALOGE("Android S & T require kernel 4.9.");
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001694 return 1;
1695 }
1696
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001697 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001698 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001699 ALOGE("Android U requires kernel 4.14.");
1700 return 1;
1701 }
1702
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001703 // V bumps the kernel requirement up to 4.19
1704 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001705 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001706 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001707 return 1;
1708 }
1709
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001710 // 25Q2 bumps the kernel requirement up to 5.4
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001711 // see also: //system/netd/tests/kernel_test.cpp TestKernel54
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001712 if (isAtLeast25Q2 && !isAtLeastKernelVersion(5, 4, 0)) {
1713 ALOGE("Android 25Q2 requires kernel 5.4.");
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001714 return 1;
1715 }
1716
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001717 // Technically already required by U, but only enforce on V+
1718 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1719 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1720 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1721 if (!isTV()) return 1;
1722 }
1723
Maciej Żenczykowski127715a2025-02-10 21:52:01 -08001724 if (isKernel32Bit() && isAtLeast25Q2) {
1725 ALOGE("Android 25Q2 requires 64 bit kernel.");
1726 return 1;
1727 }
1728
Maciej Żenczykowski9b6a9942024-09-03 16:08:35 -07001729 // 6.6 is highest version supported by Android V, so this is effectively W+ (sdk=36+)
1730 if (isKernel32Bit() && isAtLeastKernelVersion(6, 7, 0)) {
1731 ALOGE("Android platform with 32 bit kernel version >= 6.7.0 is unsupported");
1732 return 1;
1733 }
1734
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001735 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1736 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001737 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001738 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001739 }
1740
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001741 if (isAtLeastV) {
1742 bool bad = false;
1743
1744 if (!isLtsKernel()) {
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001745 ALOGW("Android V+ only supports LTS kernels.");
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001746 bad = true;
1747 }
1748
1749#define REQUIRE(maj, min, sub) \
1750 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001751 ALOGW("Android V+ requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001752 bad = true; \
1753 }
1754
1755 REQUIRE(4, 19, 236)
1756 REQUIRE(5, 4, 186)
1757 REQUIRE(5, 10, 199)
1758 REQUIRE(5, 15, 136)
1759 REQUIRE(6, 1, 57)
1760 REQUIRE(6, 6, 0)
Maciej Żenczykowski06f38e32024-12-11 07:12:59 -08001761 REQUIRE(6, 12, 0)
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001762
1763#undef REQUIRE
1764
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001765 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001766 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1767 }
1768 }
1769
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001770 /* Android 14/U should only launch on 64-bit kernels
1771 * T launches on 5.10/5.15
1772 * U launches on 5.15/6.1
1773 * So >=5.16 implies isKernel64Bit()
1774 *
1775 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1776 *
1777 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1778 * we also require 64-bit userspace.
1779 *
1780 * There are various known issues with 32-bit userspace talking to various
1781 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1782 * Some of these have userspace or kernel workarounds/hacks.
1783 * Some of them don't...
1784 * We're going to be removing the hacks.
1785 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1786 * Note: this check/enforcement only applies to *system* userspace code,
1787 * it does not affect unprivileged apps, the 32-on-64 compatibility
1788 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1789 *
1790 * Additionally the 32-bit kernel jit support is poor,
1791 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001792 * Note, however, that TV and Wear devices will continue to support 32-bit userspace
1793 * on ARM64.
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001794 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001795 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001796 // Stuff won't work reliably, but...
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001797 if (isArm() && (isTV() || isWear())) {
1798 // exempt Arm TV or Wear devices (arm32 ABI is far less problematic than x86-32)
1799 ALOGW("[Arm TV/Wear] 32-bit userspace unsupported on 6.2+ kernels.");
Maciej Żenczykowski73238632025-02-24 14:50:09 -08001800 } else if (first_api_level <= 33 /*T*/ && isArm()) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001801 // also exempt Arm devices upgrading with major kernel rev from T-
1802 // might possibly be better for them to run with a newer kernel...
1803 ALOGW("[Arm KernelUpRev] 32-bit userspace unsupported on 6.2+ kernels.");
1804 } else if (isArm()) {
1805 ALOGE("[Arm] 64-bit userspace required on 6.2+ kernels (%d).", first_api_level);
1806 return 1;
1807 } else { // x86 since RiscV cannot be 32-bit
1808 ALOGE("[x86] 64-bit userspace required on 6.2+ kernels.");
1809 return 1;
1810 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001811 }
1812
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001813 // On handheld, 6.6 is highest version supported by Android V (sdk=35), so this is for sdk=36+
1814 if (!isArm() && isUserspace32bit() && isAtLeastKernelVersion(6, 7, 0)) {
Maciej Żenczykowski21b4a052024-09-03 15:46:48 -07001815 ALOGE("64-bit userspace required on 6.7+ kernels.");
1816 return 1;
1817 }
1818
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001819 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001820 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001821 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001822 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001823 return 1;
1824 }
1825
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001826 if (runningAsRoot) {
1827 // Note: writing this proc file requires being root (always the case on V+)
1828
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001829 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1830 // but we need 0 (enabled)
1831 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1832 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1833 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001834 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001835 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001836
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001837 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001838 // Note: writing these proc files requires CAP_NET_ADMIN
1839 // and sepolicy which is only present on U+,
1840 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1841 // trigger (ie. by init itself) instead.
1842
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001843 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1844 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1845 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1846 // kernel does not have CONFIG_BPF_JIT=y)
1847 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1848 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1849 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001850
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001851 // Enable JIT kallsyms export for privileged users only
1852 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1853 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1854 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1855 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001856
1857 // Create all the pin subdirectories
1858 // (this must be done first to allow selinux_context and pin_subdir functionality,
1859 // which could otherwise fail with ENOENT during object pinning or renaming,
1860 // due to ordering issues)
1861 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001862 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001863 if (createSysFsBpfSubDir(location.prefix)) return 1;
1864 }
1865
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001866 if (isAtLeastT) {
1867 // Note: there's no actual src dir for fs_bpf_loader .o's,
1868 // so it is not listed in 'locations[].prefix'.
1869 // This is because this is primarily meant for triggering genfscon rules,
1870 // and as such this will likely always be the case.
1871 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1872 if (createSysFsBpfSubDir("loader")) return 1;
1873 }
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001874
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001875 // Load all ELF objects, create programs and maps, and pin them
1876 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001877 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001878 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001879 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1880 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1881 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1882 "problems or startup script race.");
1883 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1884 sleep(20);
1885 return 2;
1886 }
1887 }
1888
1889 int key = 1;
1890 int value = 123;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001891 unique_fd map(
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001892 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1893 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001894 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1895 return 1;
1896 }
1897
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001898 // on S we haven't created this subdir yet, but we need it for 'mainline_done' flag below
1899 if (!isAtLeastT && createSysFsBpfSubDir("netd_shared")) return 1;
1900
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001901 // leave a flag that we're done
1902 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001903
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001904 // platform bpfloader will only succeed when run as root
1905 if (!runningAsRoot) {
1906 // unreachable on U QPR3+ which always runs netbpfload as root
1907
1908 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1909 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001910 }
1911
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001912 // unreachable before U QPR3
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001913 if (exists(uprobestatsBpfLoader)) {
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001914 ALOGI("done, transferring control to uprobestatsbpfload.");
1915 const char *args[] = {
1916 uprobestatsBpfLoader,
1917 NULL,
1918 };
1919 execve(args[0], (char **)args, envp);
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001920 ALOGI("unable to execute uprobestatsbpfload, transferring control to "
1921 "platform bpfloader.");
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001922 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001923
1924 // platform BpfLoader *needs* to run as root
1925 const char * args[] = { platformBpfLoader, NULL, };
1926 execve(args[0], (char**)args, envp);
1927 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1928 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001929}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001930
1931} // namespace bpf
1932} // namespace android
1933
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001934int main(int argc, char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001935 if (android::bpf::isAtLeastT) {
1936 InitLogging(argv, &KernelLogger);
1937 } else {
1938 // S lacks the sepolicy to make non-root uid KernelLogger viable
1939 InitLogging(argv);
1940 }
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001941
1942 if (argc == 2 && !strcmp(argv[1], "done")) {
1943 // we're being re-exec'ed from platform bpfloader to 'finalize' things
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001944 if (!SetProperty("bpf.progs_loaded", "1")) {
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001945 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1946 return 125;
1947 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001948 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001949 return 0;
1950 }
1951
1952 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001953}