blob: f8691fd06ba717d2e6b5549cf441a8ac838e6723 [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 Utsumia7693582025-02-05 17:40:08 +090020#include <bpf/libbpf.h>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070021#include <dirent.h>
22#include <elf.h>
23#include <errno.h>
24#include <error.h>
25#include <fcntl.h>
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070026#include <fstream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070027#include <inttypes.h>
28#include <iostream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070029#include <linux/unistd.h>
30#include <log/log.h>
31#include <net/if.h>
32#include <optional>
33#include <stdint.h>
34#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
37#include <string>
38#include <sys/mman.h>
39#include <sys/socket.h>
40#include <sys/stat.h>
41#include <sys/types.h>
42#include <sys/utsname.h>
43#include <sys/wait.h>
44#include <sysexits.h>
45#include <unistd.h>
46#include <unordered_map>
47#include <vector>
48
49#include <android-base/cmsg.h>
50#include <android-base/file.h>
51#include <android-base/logging.h>
52#include <android-base/macros.h>
53#include <android-base/properties.h>
54#include <android-base/stringprintf.h>
55#include <android-base/strings.h>
56#include <android-base/unique_fd.h>
57#include <android/api-level.h>
58
59#include "BpfSyscallWrappers.h"
60#include "bpf/BpfUtils.h"
Maciej Żenczykowskid6028352024-08-19 15:20:04 -070061#include "bpf_map_def.h"
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070062
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +000063// The following matches bpf_helpers.h, which is only for inclusion in bpf code
Maciej Żenczykowski8c097782025-03-04 13:11:56 -080064#define BPFLOADER_MAINLINE_S_VERSION 42u
Maciej Żenczykowski199fd352025-02-13 15:17:08 -080065#define BPFLOADER_MAINLINE_25Q2_VERSION 47u
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +000066
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070067using android::base::EndsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070068using android::base::GetIntProperty;
69using android::base::GetProperty;
70using android::base::InitLogging;
71using android::base::KernelLogger;
72using android::base::SetProperty;
73using android::base::Split;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070074using android::base::StartsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070075using android::base::Tokenize;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070076using android::base::unique_fd;
77using std::ifstream;
78using std::ios;
79using std::optional;
80using std::string;
81using std::vector;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070082
83namespace android {
84namespace bpf {
85
86// Bpf programs may specify per-program & per-map selinux_context and pin_subdir.
87//
88// The BpfLoader needs to convert these bpf.o specified strings into an enum
89// for internal use (to check that valid values were specified for the specific
90// location of the bpf.o file).
91//
92// It also needs to map selinux_context's into pin_subdir's.
93// This is because of how selinux_context is actually implemented via pin+rename.
94//
95// Thus 'domain' enumerates all selinux_context's/pin_subdir's that the BpfLoader
96// is aware of. Thus there currently needs to be a 1:1 mapping between the two.
97//
98enum class domain : int {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070099 unspecified = 0, // means just use the default for that specific pin location
100 tethering, // (S+) fs_bpf_tethering /sys/fs/bpf/tethering
101 net_private, // (T+) fs_bpf_net_private /sys/fs/bpf/net_private
102 net_shared, // (T+) fs_bpf_net_shared /sys/fs/bpf/net_shared
103 netd_readonly, // (T+) fs_bpf_netd_readonly /sys/fs/bpf/netd_readonly
104 netd_shared, // (T+) fs_bpf_netd_shared /sys/fs/bpf/netd_shared
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700105 loader, // (U+) fs_bpf_loader /sys/fs/bpf/loader
106 // on T due to lack of sepolicy/genfscon rules it behaves simply as 'fs_bpf'
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700107};
108
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700109static constexpr domain AllDomains[] = {
110 domain::unspecified,
111 domain::tethering,
112 domain::net_private,
113 domain::net_shared,
114 domain::netd_readonly,
115 domain::netd_shared,
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700116 domain::loader,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700117};
118
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700119static constexpr bool specified(domain d) {
120 return d != domain::unspecified;
121}
122
123struct Location {
124 const char* const dir = "";
125 const char* const prefix = "";
Maciej Żenczykowski0b477492025-03-04 22:12:42 -0800126 const bool t_plus = true;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700127};
128
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700129// Returns the build type string (from ro.build.type).
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700130const std::string& getBuildType() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700131 static std::string t = GetProperty("ro.build.type", "unknown");
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700132 return t;
133}
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700134
135// The following functions classify the 3 Android build types.
136inline bool isEng() {
137 return getBuildType() == "eng";
138}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700139
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700140inline bool isUser() {
141 return getBuildType() == "user";
142}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700143
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700144inline bool isUserdebug() {
145 return getBuildType() == "userdebug";
146}
147
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700148#define BPF_FS_PATH "/sys/fs/bpf/"
149
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700150static unsigned int page_size = static_cast<unsigned int>(getpagesize());
151
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700152constexpr const char* lookupSelinuxContext(const domain d) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700153 switch (d) {
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700154 case domain::unspecified: return "";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700155 case domain::tethering: return "fs_bpf_tethering";
156 case domain::net_private: return "fs_bpf_net_private";
157 case domain::net_shared: return "fs_bpf_net_shared";
158 case domain::netd_readonly: return "fs_bpf_netd_readonly";
159 case domain::netd_shared: return "fs_bpf_netd_shared";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700160 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700161 }
162}
163
164domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
165 for (domain d : AllDomains) {
166 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
167 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
168 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
169 }
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700170 ALOGE("unrecognized selinux_context '%-32s'", s);
171 // Note: we *can* just abort() here as we only load bpf .o files shipped
172 // in the same mainline module / apex as NetBpfLoad itself.
173 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700174}
175
176constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
177 switch (d) {
178 case domain::unspecified: return unspecified;
179 case domain::tethering: return "tethering/";
180 case domain::net_private: return "net_private/";
181 case domain::net_shared: return "net_shared/";
182 case domain::netd_readonly: return "netd_readonly/";
183 case domain::netd_shared: return "netd_shared/";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700184 case domain::loader: return "loader/";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700185 }
186};
187
188domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
189 for (domain d : AllDomains) {
190 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
191 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
192 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
193 }
194 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700195 // Note: we *can* just abort() here as we only load bpf .o files shipped
196 // in the same mainline module / apex as NetBpfLoad itself.
197 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700198}
199
200static string pathToObjName(const string& path) {
201 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700202 string filename = Split(path, "/").back();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700203 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
204 string name = filename.substr(0, filename.find_last_of('.'));
205 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
206 // this can be used to provide duplicate programs (mux based on the bpfloader version)
207 return name.substr(0, name.find_last_of('@'));
208}
209
210typedef struct {
211 const char* name;
212 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000213 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700214} sectionType;
215
216/*
217 * Map section name prefixes to program types, the section name will be:
218 * SECTION(<prefix>/<name-of-program>)
219 * For example:
220 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
221 * is the name of the program, and tracepoint is the type.
222 *
223 * However, be aware that you should not be directly using the SECTION() macro.
Maciej Żenczykowski3a085152024-09-18 23:45:52 +0000224 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE macros.
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700225 *
226 * Programs shipped inside the tethering apex should be limited to networking stuff,
227 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
228 * since they are less stable abi/api and may conflict with platform uses of bpf.
229 */
230sectionType sectionNameTypes[] = {
231 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
232 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000233 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
234 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700235 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
236 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
237 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
238 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
239 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
240 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
241 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700242 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
243 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
244 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
245 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000246 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
247 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700248 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
249 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
250 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000251 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700252 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
253 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000254 {"xdp/", BPF_PROG_TYPE_XDP},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700255};
256
257typedef struct {
258 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000259 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700260 string name;
261 vector<char> data;
262 vector<char> rel_data;
263 optional<struct bpf_prog_def> prog_def;
264
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000265 unique_fd prog_fd; // fd after loading
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700266} codeSection;
267
268static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
269 elfFile.seekg(0);
270 if (elfFile.fail()) return -1;
271
272 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
273
274 return 0;
275}
276
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000277// Reads all section header tables into an Shdr array
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700278static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
279 Elf64_Ehdr eh;
280 int ret = 0;
281
282 ret = readElfHeader(elfFile, &eh);
283 if (ret) return ret;
284
285 elfFile.seekg(eh.e_shoff);
286 if (elfFile.fail()) return -1;
287
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000288 // Read shdr table entries
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700289 shTable.resize(eh.e_shnum);
290
291 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
292
293 return 0;
294}
295
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000296// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700297static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
298 vector<Elf64_Shdr> shTable;
299 int ret = readSectionHeadersAll(elfFile, shTable);
300 if (ret) return ret;
301
302 elfFile.seekg(shTable[id].sh_offset);
303 if (elfFile.fail()) return -1;
304
305 sec.resize(shTable[id].sh_size);
306 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
307
308 return 0;
309}
310
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000311// Read whole section header string table
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700312static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
313 Elf64_Ehdr eh;
314 int ret = readElfHeader(elfFile, &eh);
315 if (ret) return ret;
316
317 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
318 if (ret) return ret;
319
320 return 0;
321}
322
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000323// Get name from offset in strtab
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700324static int getSymName(ifstream& elfFile, int nameOff, string& name) {
325 int ret;
326 vector<char> secStrTab;
327
328 ret = readSectionHeaderStrtab(elfFile, secStrTab);
329 if (ret) return ret;
330
331 if (nameOff >= (int)secStrTab.size()) return -1;
332
333 name = string((char*)secStrTab.data() + nameOff);
334 return 0;
335}
336
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000337// Reads a full section by name - example to get the GPL license
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700338static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
339 vector<char> secStrTab;
340 vector<Elf64_Shdr> shTable;
341 int ret;
342
343 ret = readSectionHeadersAll(elfFile, shTable);
344 if (ret) return ret;
345
346 ret = readSectionHeaderStrtab(elfFile, secStrTab);
347 if (ret) return ret;
348
349 for (int i = 0; i < (int)shTable.size(); i++) {
350 char* secname = secStrTab.data() + shTable[i].sh_name;
351 if (!secname) continue;
352
353 if (!strcmp(secname, name)) {
354 vector<char> dataTmp;
355 dataTmp.resize(shTable[i].sh_size);
356
357 elfFile.seekg(shTable[i].sh_offset);
358 if (elfFile.fail()) return -1;
359
360 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
361
362 data = dataTmp;
363 return 0;
364 }
365 }
366 return -2;
367}
368
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700369unsigned int readSectionUint(const char* name, ifstream& elfFile) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700370 vector<char> theBytes;
371 int ret = readSectionByName(name, elfFile, theBytes);
372 if (ret) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700373 ALOGE("Couldn't find section %s.", name);
374 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700375 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700376 ALOGE("Section %s is too short.", name);
377 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700378 } else {
379 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
380 unsigned int value = static_cast<unsigned char>(theBytes[3]);
381 value <<= 8;
382 value += static_cast<unsigned char>(theBytes[2]);
383 value <<= 8;
384 value += static_cast<unsigned char>(theBytes[1]);
385 value <<= 8;
386 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000387 ALOGD("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700388 return value;
389 }
390}
391
392static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
393 int ret;
394 vector<Elf64_Shdr> shTable;
395
396 ret = readSectionHeadersAll(elfFile, shTable);
397 if (ret) return ret;
398
399 for (int i = 0; i < (int)shTable.size(); i++) {
400 if ((int)shTable[i].sh_type != type) continue;
401
402 vector<char> dataTmp;
403 dataTmp.resize(shTable[i].sh_size);
404
405 elfFile.seekg(shTable[i].sh_offset);
406 if (elfFile.fail()) return -1;
407
408 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
409
410 data = dataTmp;
411 return 0;
412 }
413 return -2;
414}
415
416static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
417 return (a.st_value < b.st_value);
418}
419
420static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
421 int ret, numElems;
422 Elf64_Sym* buf;
423 vector<char> secData;
424
425 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
426 if (ret) return ret;
427
428 buf = (Elf64_Sym*)secData.data();
429 numElems = (secData.size() / sizeof(Elf64_Sym));
430 data.assign(buf, buf + numElems);
431
432 if (sort) std::sort(data.begin(), data.end(), symCompare);
433 return 0;
434}
435
436static enum bpf_prog_type getSectionType(string& name) {
437 for (auto& snt : sectionNameTypes)
438 if (StartsWith(name, snt.name)) return snt.type;
439
440 return BPF_PROG_TYPE_UNSPEC;
441}
442
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700443static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700444 vector<char> pdData;
445 int ret = readSectionByName("progs", elfFile, pdData);
446 if (ret) return ret;
447
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700448 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700449 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700450 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700451 return -1;
452 };
453
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700454 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700455
456 const char* dataPtr = pdData.data();
457 for (auto& p : pd) {
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700458 // Copy the structure from the ELF file and move to the next one.
459 memcpy(&p, dataPtr, sizeof(struct bpf_prog_def));
460 dataPtr += sizeof(struct bpf_prog_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700461 }
462 return 0;
463}
464
465static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
466 optional<unsigned> symbolType = std::nullopt) {
467 int ret;
468 string name;
469 vector<Elf64_Sym> symtab;
470 vector<Elf64_Shdr> shTable;
471
472 ret = readSymTab(elfFile, 1 /* sort */, symtab);
473 if (ret) return ret;
474
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000475 // Get index of section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700476 ret = readSectionHeadersAll(elfFile, shTable);
477 if (ret) return ret;
478
479 int sec_idx = -1;
480 for (int i = 0; i < (int)shTable.size(); i++) {
481 ret = getSymName(elfFile, shTable[i].sh_name, name);
482 if (ret) return ret;
483
484 if (!name.compare(sectionName)) {
485 sec_idx = i;
486 break;
487 }
488 }
489
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000490 // No section found with matching name
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700491 if (sec_idx == -1) {
492 ALOGW("No %s section could be found in elf object", sectionName.c_str());
493 return -1;
494 }
495
496 for (int i = 0; i < (int)symtab.size(); i++) {
497 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
498
499 if (symtab[i].st_shndx == sec_idx) {
500 string s;
501 ret = getSymName(elfFile, symtab[i].st_name, s);
502 if (ret) return ret;
503 names.push_back(s);
504 }
505 }
506
507 return 0;
508}
509
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000510// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700511static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700512 vector<Elf64_Shdr> shTable;
513 int entries, ret = 0;
514
515 ret = readSectionHeadersAll(elfFile, shTable);
516 if (ret) return ret;
517 entries = shTable.size();
518
519 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700520 ret = readProgDefs(elfFile, pd);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700521 if (ret) return ret;
522 vector<string> progDefNames;
523 ret = getSectionSymNames(elfFile, "progs", progDefNames);
524 if (!pd.empty() && ret) return ret;
525
526 for (int i = 0; i < entries; i++) {
527 string name;
528 codeSection cs_temp;
529 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
530
531 ret = getSymName(elfFile, shTable[i].sh_name, name);
532 if (ret) return ret;
533
534 enum bpf_prog_type ptype = getSectionType(name);
535
536 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
537
538 // This must be done before '/' is replaced with '_'.
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000539 for (auto& snt : sectionNameTypes)
540 if (StartsWith(name, snt.name)) cs_temp.attach_type = snt.attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700541
542 string oldName = name;
543
544 // convert all slashes to underscores
545 std::replace(name.begin(), name.end(), '/', '_');
546
547 cs_temp.type = ptype;
548 cs_temp.name = name;
549
550 ret = readSectionByIdx(elfFile, i, cs_temp.data);
551 if (ret) return ret;
552 ALOGV("Loaded code section %d (%s)", i, name.c_str());
553
554 vector<string> csSymNames;
555 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
556 if (ret || !csSymNames.size()) return ret;
557 for (size_t i = 0; i < progDefNames.size(); ++i) {
558 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
559 cs_temp.prog_def = pd[i];
560 break;
561 }
562 }
563
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000564 // Check for rel section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700565 if (cs_temp.data.size() > 0 && i < entries) {
566 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
567 if (ret) return ret;
568
569 if (name == (".rel" + oldName)) {
570 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
571 if (ret) return ret;
572 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
573 }
574 }
575
576 if (cs_temp.data.size() > 0) {
577 cs.push_back(std::move(cs_temp));
578 ALOGV("Adding section %d to cs list", i);
579 }
580 }
581 return 0;
582}
583
584static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
585 vector<Elf64_Sym> symtab;
586 int ret = 0;
587
588 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
589 if (ret) return ret;
590
591 if (index >= (int)symtab.size()) return -1;
592
593 return getSymName(elfFile, symtab[index].st_name, name);
594}
595
596static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
597 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
598 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
599 // so on 4.9-T kernels just pretend the map matches our expectations.
600 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
601 // This is because the primary failure mode we're trying to detect here
602 // is either a source code misconfiguration (which is likely kernel independent)
603 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
604 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
605
606 // Assuming fd is a valid Bpf Map file descriptor then
607 // all the following should always succeed on a 4.14+ kernel.
608 // If they somehow do fail, they'll return -1 (and set errno),
609 // which should then cause (among others) a key_size mismatch.
610 int fd_type = bpfGetFdMapType(fd);
611 int fd_key_size = bpfGetFdKeySize(fd);
612 int fd_value_size = bpfGetFdValueSize(fd);
613 int fd_max_entries = bpfGetFdMaxEntries(fd);
614 int fd_map_flags = bpfGetFdMapFlags(fd);
615
616 // DEVMAPs are readonly from the bpf program side's point of view, as such
617 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
618 int desired_map_flags = (int)mapDef.map_flags;
619 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
620 desired_map_flags |= BPF_F_RDONLY_PROG;
621
622 // The .h file enforces that this is a power of two, and page size will
623 // also always be a power of two, so this logic is actually enough to
624 // force it to be a multiple of the page size, as required by the kernel.
625 unsigned int desired_max_entries = mapDef.max_entries;
626 if (type == BPF_MAP_TYPE_RINGBUF) {
627 if (desired_max_entries < page_size) desired_max_entries = page_size;
628 }
629
630 // The following checks should *never* trigger, if one of them somehow does,
631 // it probably means a bpf .o file has been changed/replaced at runtime
632 // and bpfloader was manually rerun (normally it should only run *once*
633 // early during the boot process).
634 // Another possibility is that something is misconfigured in the code:
635 // most likely a shared map is declared twice differently.
636 // But such a change should never be checked into the source tree...
637 if ((fd_type == type) &&
638 (fd_key_size == (int)mapDef.key_size) &&
639 (fd_value_size == (int)mapDef.value_size) &&
640 (fd_max_entries == (int)desired_max_entries) &&
641 (fd_map_flags == desired_map_flags)) {
642 return true;
643 }
644
645 ALOGE("bpf map name %s mismatch: desired/found: "
646 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
647 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
648 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
649 return false;
650}
651
652static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700653 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700654 int ret;
655 vector<char> mdData;
656 vector<struct bpf_map_def> md;
657 vector<string> mapNames;
658 string objName = pathToObjName(string(elfPath));
659
660 ret = readSectionByName("maps", elfFile, mdData);
661 if (ret == -2) return 0; // no maps to read
662 if (ret) return ret;
663
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700664 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700665 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700666 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700667 return -1;
668 };
669
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700670 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700671
672 const char* dataPtr = mdData.data();
673 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700674 // Copy the structure from the ELF file and move to the next one.
675 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
676 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700677 }
678
679 ret = getSectionSymNames(elfFile, "maps", mapNames);
680 if (ret) return ret;
681
682 unsigned kvers = kernelVersion();
683
684 for (int i = 0; i < (int)mapNames.size(); i++) {
685 if (md[i].zero != 0) abort();
686
687 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000688 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700689 md[i].bpfloader_min_ver);
690 mapFds.push_back(unique_fd());
691 continue;
692 }
693
694 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000695 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700696 md[i].bpfloader_max_ver);
697 mapFds.push_back(unique_fd());
698 continue;
699 }
700
701 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000702 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700703 mapNames[i].c_str(), kvers, md[i].min_kver);
704 mapFds.push_back(unique_fd());
705 continue;
706 }
707
708 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000709 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700710 mapNames[i].c_str(), kvers, md[i].max_kver);
711 mapFds.push_back(unique_fd());
712 continue;
713 }
714
715 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
716 (md[i].ignore_on_userdebug && isUserdebug())) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000717 ALOGD("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700718 getBuildType().c_str());
719 mapFds.push_back(unique_fd());
720 continue;
721 }
722
723 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
724 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
725 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
726 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
727 (isRiscV() && md[i].ignore_on_riscv64)) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000728 ALOGD("skipping map %s which is ignored on %s", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700729 describeArch());
730 mapFds.push_back(unique_fd());
731 continue;
732 }
733
734 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski87019832025-02-03 22:04:26 -0800735 if (type == BPF_MAP_TYPE_LPM_TRIE && !isAtLeastKernelVersion(4, 14, 0)) {
736 // On Linux Kernels older than 4.14 this map type doesn't exist - autoskip.
737 ALOGD("skipping LPM_TRIE map %s - requires kver 4.14+", mapNames[i].c_str());
738 mapFds.push_back(unique_fd());
739 continue;
740 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700741 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
742 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
743 // of be approximated: ARRAY has the same userspace api, though it is not usable
744 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
745 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
746 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
747 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
748 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
749 type = BPF_MAP_TYPE_ARRAY;
750 }
751 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
752 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
753 // of be approximated: HASH has the same userspace visible api.
754 // However it cannot be used by ebpf programs in the same way.
755 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
756 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
757 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
758 // programs as being 5.4+...
759 type = BPF_MAP_TYPE_HASH;
760 }
761
762 // The .h file enforces that this is a power of two, and page size will
763 // also always be a power of two, so this logic is actually enough to
764 // force it to be a multiple of the page size, as required by the kernel.
765 unsigned int max_entries = md[i].max_entries;
766 if (type == BPF_MAP_TYPE_RINGBUF) {
767 if (max_entries < page_size) max_entries = page_size;
768 }
769
770 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
771 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000772 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700773 md[i].selinux_context, static_cast<int>(selinux_context),
774 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
775 }
776
777 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700778 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000779 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700780 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
781 }
782
783 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
784 // except that maps shared across .o's have empty <objName>
785 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
786 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
787 (md[i].shared ? "" : objName) + "_" + mapNames[i];
788 bool reuse = false;
789 unique_fd fd;
790 int saved_errno;
791
792 if (access(mapPinLoc.c_str(), F_OK) == 0) {
793 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
794 saved_errno = errno;
795 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
796 reuse = true;
797 } else {
798 union bpf_attr req = {
799 .map_type = type,
800 .key_size = md[i].key_size,
801 .value_size = md[i].value_size,
802 .max_entries = max_entries,
Maciej Żenczykowskic1a9f4a2025-01-20 12:09:13 -0800803 .map_flags = md[i].map_flags,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700804 };
805 if (isAtLeastKernelVersion(4, 15, 0))
806 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
807 fd.reset(bpf(BPF_MAP_CREATE, req));
808 saved_errno = errno;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -0700809 if (fd.ok()) {
810 ALOGD("bpf_create_map[%s] -> %d", mapNames[i].c_str(), fd.get());
811 } else {
812 ALOGE("bpf_create_map[%s] -> %d errno:%d", mapNames[i].c_str(), fd.get(), saved_errno);
813 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700814 }
815
816 if (!fd.ok()) return -saved_errno;
817
818 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
819 // safety (since reuse code path is rare) run these checks even if we just created it.
820 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
821 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
822
823 if (!reuse) {
824 if (specified(selinux_context)) {
825 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
826 "tmp_map_" + objName + "_" + mapNames[i];
827 ret = bpfFdPin(fd, createLoc.c_str());
828 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800829 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700830 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
831 return -err;
832 }
833 ret = renameat2(AT_FDCWD, createLoc.c_str(),
834 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
835 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800836 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700837 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
838 err, strerror(err));
839 return -err;
840 }
841 } else {
842 ret = bpfFdPin(fd, mapPinLoc.c_str());
843 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800844 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700845 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
846 return -err;
847 }
848 }
849 ret = chmod(mapPinLoc.c_str(), md[i].mode);
850 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800851 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700852 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
853 strerror(err));
854 return -err;
855 }
856 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
857 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -0800858 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700859 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
860 ret, err, strerror(err));
861 return -err;
862 }
863 }
864
Maciej Żenczykowskia003ace2025-02-13 16:08:18 -0800865 if (isAtLeastKernelVersion(4, 14, 0)) {
866 int mapId = bpfGetFdMapId(fd);
867 if (mapId == -1) {
868 const int err = errno;
869 ALOGE("bpfGetFdMapId failed, errno: %d", err);
870 return -err;
871 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700872 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
873 }
874
875 mapFds.push_back(std::move(fd));
876 }
877
878 return ret;
879}
880
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700881static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
882 int insnIndex;
883 struct bpf_insn *insn, *insns;
884
885 insns = (struct bpf_insn*)(insnsPtr);
886
887 insnIndex = offset / sizeof(struct bpf_insn);
888 insn = &insns[insnIndex];
889
890 // Occasionally might be useful for relocation debugging, but pretty spammy
891 if (0) {
892 ALOGV("applying relo to instruction at byte offset: %llu, "
893 "insn offset %d, insn %llx",
894 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
895 }
896
897 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700898 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700899 return;
900 }
901
902 insn->imm = fd;
903 insn->src_reg = BPF_PSEUDO_MAP_FD;
904}
905
906static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
907 vector<string> mapNames;
908
909 int ret = getSectionSymNames(elfFile, "maps", mapNames);
910 if (ret) return;
911
912 for (int k = 0; k != (int)cs.size(); k++) {
913 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
914 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
915
916 for (int i = 0; i < n_rel; i++) {
917 int symIndex = ELF64_R_SYM(rel[i].r_info);
918 string symName;
919
920 ret = getSymNameByIdx(elfFile, symIndex, symName);
921 if (ret) return;
922
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000923 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700924 for (int j = 0; j < (int)mapNames.size(); j++) {
925 if (!mapNames[j].compare(symName)) {
926 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
927 break;
928 }
929 }
930 }
931 }
932}
933
934static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
935 const char* prefix, const unsigned int bpfloader_ver) {
936 unsigned kvers = kernelVersion();
937
938 if (!kvers) {
939 ALOGE("unable to get kernel version");
940 return -EINVAL;
941 }
942
943 string objName = pathToObjName(string(elfPath));
944
945 for (int i = 0; i < (int)cs.size(); i++) {
946 unique_fd& fd = cs[i].prog_fd;
947 int ret;
948 string name = cs[i].name;
949
950 if (!cs[i].prog_def.has_value()) {
951 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
952 return -EINVAL;
953 }
954
955 unsigned min_kver = cs[i].prog_def->min_kver;
956 unsigned max_kver = cs[i].prog_def->max_kver;
957 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
958 max_kver, kvers);
959 if (kvers < min_kver) continue;
960 if (kvers >= max_kver) continue;
961
962 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
963 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
964 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
965 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700966
967 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
968 bpfMinVer, bpfMaxVer);
969 if (bpfloader_ver < bpfMinVer) continue;
970 if (bpfloader_ver >= bpfMaxVer) continue;
971
972 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
973 (cs[i].prog_def->ignore_on_user && isUser()) ||
974 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
975 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
976 getBuildType().c_str());
977 continue;
978 }
979
980 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
981 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
982 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
983 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
984 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
985 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
986 continue;
987 }
988
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700989 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000990 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700991 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
992 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
993 }
994
995 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000996 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700997 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
998 lookupPinSubdir(pin_subdir));
999 }
1000
1001 // strip any potential $foo suffix
1002 // this can be used to provide duplicate programs
1003 // conditionally loaded based on running kernel version
1004 name = name.substr(0, name.find_last_of('$'));
1005
1006 bool reuse = false;
1007 // Format of pin location is
1008 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1009 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1010 objName + '_' + string(name);
1011 if (access(progPinLoc.c_str(), F_OK) == 0) {
1012 fd.reset(retrieveProgram(progPinLoc.c_str()));
1013 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001014 !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001015 reuse = true;
1016 } else {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001017 static char log_buf[1 << 20]; // 1 MiB logging buffer
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001018
1019 union bpf_attr req = {
1020 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001021 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001022 .insns = ptr_to_u64(cs[i].data.data()),
1023 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001024 .log_level = 1,
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001025 .log_size = sizeof(log_buf),
1026 .log_buf = ptr_to_u64(log_buf),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001027 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001028 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001029 };
1030 if (isAtLeastKernelVersion(4, 15, 0))
1031 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1032 fd.reset(bpf(BPF_PROG_LOAD, req));
1033
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001034 // Kernel should have NULL terminated the log buffer, but force it anyway for safety
1035 log_buf[sizeof(log_buf) - 1] = 0;
1036
1037 // Strip out final newline if present
1038 int log_chars = strlen(log_buf);
1039 if (log_chars && log_buf[log_chars - 1] == '\n') log_buf[--log_chars] = 0;
1040
1041 bool log_oneline = !strchr(log_buf, '\n');
1042
1043 ALOGD("BPF_PROG_LOAD call for %s (%s) returned '%s' fd: %d (%s)", elfPath,
1044 cs[i].name.c_str(), log_oneline ? log_buf : "{multiline}",
Maciej Żenczykowski37ba9392025-02-13 16:00:26 -08001045 fd.get(), !fd.ok() ? std::strerror(errno) : "ok");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001046
1047 if (!fd.ok()) {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001048 // kernel NULL terminates log_buf, so this checks for non-empty string
1049 if (log_buf[0]) {
1050 vector<string> lines = Split(log_buf, "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001051
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001052 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1053 for (const auto& line : lines) ALOGW("%s", line.c_str());
1054 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1055 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001056
1057 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001058 ALOGW("failed program %s is marked optional - continuing...",
1059 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001060 continue;
1061 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001062 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001063 }
1064 }
1065
1066 if (!fd.ok()) return fd.get();
1067
1068 if (!reuse) {
1069 if (specified(selinux_context)) {
1070 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1071 "tmp_prog_" + objName + '_' + string(name);
1072 ret = bpfFdPin(fd, createLoc.c_str());
1073 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001074 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001075 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1076 return -err;
1077 }
1078 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1079 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1080 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001081 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001082 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1083 err, strerror(err));
1084 return -err;
1085 }
1086 } else {
1087 ret = bpfFdPin(fd, progPinLoc.c_str());
1088 if (ret) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001089 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001090 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1091 return -err;
1092 }
1093 }
1094 if (chmod(progPinLoc.c_str(), 0440)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001095 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001096 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1097 return -err;
1098 }
1099 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1100 (gid_t)cs[i].prog_def->gid)) {
Maciej Żenczykowski000f20d2025-02-13 16:04:21 -08001101 const int err = errno;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001102 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1103 cs[i].prog_def->gid, err, strerror(err));
1104 return -err;
1105 }
1106 }
1107
Maciej Żenczykowski97debeb2025-02-14 11:15:36 -08001108 if (isAtLeastKernelVersion(4, 14, 0)) {
1109 int progId = bpfGetFdProgId(fd);
1110 if (progId == -1) {
1111 const int err = errno;
1112 ALOGE("bpfGetFdProgId failed, errno: %d", err);
1113 return -err;
1114 }
Maciej Żenczykowski199fd352025-02-13 15:17:08 -08001115
1116 int jitLen = bpfGetFdJitProgLen(fd);
1117 if (jitLen == -1) {
1118 const int err = errno;
1119 ALOGE("bpfGetFdJitProgLen failed, ret: %d", err);
1120 return -err;
1121 }
1122
1123 int xlatLen = bpfGetFdXlatProgLen(fd);
1124 if (xlatLen == -1) {
1125 const int err = errno;
1126 ALOGE("bpfGetFdXlatProgLen failed, ret: %d", err);
1127 return -err;
1128 }
1129 ALOGI("prog %s id %d len jit:%d xlat:%d", progPinLoc.c_str(), progId, jitLen, xlatLen);
1130
1131 if (!jitLen && bpfloader_ver >= BPFLOADER_MAINLINE_25Q2_VERSION) {
1132 ALOGE("Kernel eBPF JIT failure for %s", progPinLoc.c_str());
1133 return -ENOTSUP;
1134 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001135 }
1136 }
1137
1138 return 0;
1139}
1140
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001141int loadProg(const char* const elfPath, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001142 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001143 vector<char> license;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001144 vector<codeSection> cs;
1145 vector<unique_fd> mapFds;
1146 int ret;
1147
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001148 ifstream elfFile(elfPath, ios::in | ios::binary);
1149 if (!elfFile.is_open()) return -1;
1150
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001151 ret = readSectionByName("license", elfFile, license);
1152 if (ret) {
1153 ALOGE("Couldn't find license in %s", elfPath);
1154 return ret;
1155 } else {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001156 ALOGD("Loading ELF object %s with license %s",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001157 elfPath, (char*)license.data());
1158 }
1159
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001160 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1161 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001162
1163 // inclusive lower bound check
1164 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001165 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001166 bpfloader_ver, elfPath, bpfLoaderMinVer);
1167 return 0;
1168 }
1169
1170 // exclusive upper bound check
1171 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001172 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001173 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1174 return 0;
1175 }
1176
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001177 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001178 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1179
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001180 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001181 if (ret) {
1182 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1183 return ret;
1184 }
1185
1186 for (int i = 0; i < (int)mapFds.size(); i++)
1187 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1188
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001189 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001190 // BPF .o's with no programs are only supported by mainline netbpfload,
1191 // make sure .o's targeting non-mainline (ie. S) bpfloader don't show up.
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001192 if (ret == -ENOENT && bpfLoaderMinVer >= BPFLOADER_MAINLINE_S_VERSION)
Maciej Żenczykowski2d52f8c2024-09-25 22:14:04 +00001193 return 0;
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001194 if (ret) {
1195 ALOGE("Couldn't read all code sections in %s", elfPath);
1196 return ret;
1197 }
1198
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001199 applyMapRelo(elfFile, mapFds, cs);
1200
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001201 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001202 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1203
1204 return ret;
1205}
1206
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001207static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001208 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001209 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001210 if (errno == ENOENT) return false;
1211 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1212 abort(); // can only hit this if permissions (likely selinux) are screwed up
1213}
1214
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001215#define APEXROOT "/apex/com.android.tethering"
1216#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001217
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001218const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001219 // S+ Tethering mainline module (network_stack): tether offload
1220 {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001221 .dir = BPFROOT "/tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001222 .prefix = "tethering/",
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001223 .t_plus = false,
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001224 },
1225 // T+ Tethering mainline module (shared with netd & system server)
1226 // netutils_wrapper (for iptables xt_bpf) has access to programs
1227 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001228 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001229 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001230 },
1231 // T+ Tethering mainline module (shared with netd & system server)
1232 // netutils_wrapper has no access, netd has read only access
1233 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001234 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001235 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001236 },
1237 // T+ Tethering mainline module (shared with system server)
1238 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001239 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001240 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001241 },
1242 // T+ Tethering mainline module (not shared, just network_stack)
1243 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001244 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001245 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001246 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001247};
1248
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001249static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001250 int retVal = 0;
1251 DIR* dir;
1252 struct dirent* ent;
1253
1254 if ((dir = opendir(location.dir)) != NULL) {
1255 while ((ent = readdir(dir)) != NULL) {
1256 string s = ent->d_name;
1257 if (!EndsWith(s, ".o")) continue;
1258
1259 string progPath(location.dir);
1260 progPath += s;
1261
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001262 int ret = loadProg(progPath.c_str(), bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001263 if (ret) {
Maciej Żenczykowski3a085152024-09-18 23:45:52 +00001264 retVal = ret;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001265 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1266 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001267 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001268 }
1269 }
1270 closedir(dir);
1271 }
1272 return retVal;
1273}
1274
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001275static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001276 if (*prefix) {
1277 mode_t prevUmask = umask(0);
1278
1279 string s = "/sys/fs/bpf/";
1280 s += prefix;
1281
1282 errno = 0;
1283 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1284 if (ret && errno != EEXIST) {
1285 const int err = errno;
1286 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1287 return -err;
1288 }
1289
1290 umask(prevUmask);
1291 }
1292 return 0;
1293}
1294
1295// Technically 'value' doesn't need to be newline terminated, but it's best
1296// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1297// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001298static int writeProcSysFile(const char *filename, const char *value) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001299 unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001300 if (fd < 0) {
1301 const int err = errno;
1302 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1303 return -err;
1304 }
1305 int len = strlen(value);
1306 int v = write(fd, value, len);
1307 if (v < 0) {
1308 const int err = errno;
1309 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1310 return -err;
1311 }
1312 if (v != len) {
1313 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1314 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1315 return -EINVAL;
1316 }
1317 return 0;
1318}
1319
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001320#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001321const char * const platformBpfLoader = "/system/bin/bpfloader";
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001322const char *const uprobestatsBpfLoader =
1323 "/apex/com.android.uprobestats/bin/uprobestatsbpfload";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001324
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001325static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001326 char * found_blockdev = NULL;
1327 FILE * f = NULL;
1328 char buf[4096];
1329
1330 f = fopen("/proc/mounts", "re");
1331 if (!f) return 1;
1332
1333 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1334 while (fgets(buf, sizeof(buf), f)) {
1335 char * blockdev = buf;
1336 char * space = strchr(blockdev, ' ');
1337 if (!space) continue;
1338 *space = '\0';
1339 char * mntpath = space + 1;
1340 space = strchr(mntpath, ' ');
1341 if (!space) continue;
1342 *space = '\0';
1343 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1344 found_blockdev = strdup(blockdev);
1345 break;
1346 }
1347 fclose(f);
1348 f = NULL;
1349
1350 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001351 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001352
1353 f = fopen("/proc/mounts", "re");
1354 if (!f) { free(found_blockdev); return 3; }
1355
1356 while (fgets(buf, sizeof(buf), f)) {
1357 char * blockdev = buf;
1358 char * space = strchr(blockdev, ' ');
1359 if (!space) continue;
1360 *space = '\0';
1361 char * mntpath = space + 1;
1362 space = strchr(mntpath, ' ');
1363 if (!space) continue;
1364 *space = '\0';
1365 if (strcmp(blockdev, found_blockdev)) continue;
1366 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1367 char * at = strchr(mntpath, '@');
1368 if (!at) continue;
1369 char * ver = at + 1;
1370 ALOGI("Tethering APEX version %s", ver);
1371 }
1372 fclose(f);
1373 free(found_blockdev);
1374 return 0;
1375}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001376
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001377static bool hasGSM() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001378 static string ph = GetProperty("gsm.current.phone-type", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001379 static bool gsm = (ph != "");
1380 static bool logged = false;
1381 if (!logged) {
1382 logged = true;
1383 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1384 }
1385 return gsm;
1386}
1387
1388static bool isTV() {
1389 if (hasGSM()) return false; // TVs don't do GSM
1390
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001391 static string key = GetProperty("ro.oem.key1", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001392 static bool tv = StartsWith(key, "ATV00");
1393 static bool logged = false;
1394 if (!logged) {
1395 logged = true;
1396 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1397 }
1398 return tv;
1399}
1400
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001401static bool isWear() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001402 static string wearSdkStr = GetProperty("ro.cw_build.wear_sdk.version", "");
1403 static int wearSdkInt = GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1404 static string buildChars = GetProperty("ro.build.characteristics", "");
1405 static vector<string> v = Tokenize(buildChars, ",");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001406 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1407 static bool wear = (wearSdkInt > 0) || watch;
1408 static bool logged = false;
1409 if (!logged) {
1410 logged = true;
1411 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1412 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1413 }
1414 return wear;
1415}
1416
Motomu Utsumi712088d2025-03-18 14:52:02 +09001417static int libbpfPrint(enum libbpf_print_level lvl, const char *const formatStr,
1418 va_list argList) {
1419 int32_t prio;
1420 switch (lvl) {
1421 case LIBBPF_WARN:
1422 prio = ANDROID_LOG_WARN;
1423 break;
1424 case LIBBPF_INFO:
1425 prio = ANDROID_LOG_INFO;
1426 break;
1427 case LIBBPF_DEBUG:
1428 prio = ANDROID_LOG_DEBUG;
1429 break;
1430 }
1431 char *s = strdup(formatStr ?: "(no format string)");
1432 int len = strlen(s);
1433 if (len && s[len - 1] == '\n')
1434 s[len - 1] = 0;
1435 LOG_PRI_VA(prio, LOG_TAG, s, argList);
1436 free(s);
1437 return 0;
1438}
1439
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001440static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001441 if (!isAtLeastS) {
1442 ALOGE("Impossible - not reachable on Android <S.");
1443 // for safety, we don't fail, this is a just-in-case workaround
1444 // for any possible busted 'optimized' start everything vendor init hacks on R
1445 return 0;
1446 }
Motomu Utsumi712088d2025-03-18 14:52:02 +09001447 libbpf_set_print(libbpfPrint);
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001448
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001449 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001450
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001451 const int first_api_level = GetIntProperty("ro.board.first_api_level", api_level);
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001452
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001453 // last in U QPR2 beta1
1454 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1455 // first in U QPR2 beta~2
1456 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1457
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001458 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski8c097782025-03-04 13:11:56 -08001459 unsigned int bpfloader_ver = BPFLOADER_MAINLINE_S_VERSION; // [42u]
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001460 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1461 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1462 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1463 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001464 if (isAtLeast25Q2) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_25Q2_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001465
Motomu Utsumia7693582025-02-05 17:40:08 +09001466 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) libbpf: v%u.%u "
1467 "uid:%d rc:%d%d",
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001468 bpfloader_ver, argv[0], android_get_device_api_level(), api_level,
Motomu Utsumia7693582025-02-05 17:40:08 +09001469 kernelVersion(), describeArch(), libbpf_major_version(),
1470 libbpf_minor_version(), getuid(), has_platform_bpfloader_rc,
1471 has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001472
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001473 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1474 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1475 return 1;
1476 }
1477
1478 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1479 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1480 return 1;
1481 }
1482
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001483 logTetheringApexVersion();
1484
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001485 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001486 if (!isAtLeastKernelVersion(4, 9, 0)) {
1487 ALOGE("Android S & T require kernel 4.9.");
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001488 return 1;
1489 }
1490
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001491 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001492 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001493 ALOGE("Android U requires kernel 4.14.");
1494 return 1;
1495 }
1496
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001497 // V bumps the kernel requirement up to 4.19
1498 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001499 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001500 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001501 return 1;
1502 }
1503
Maciej Żenczykowskidb9171f2025-01-14 16:22:46 -08001504 // 25Q2 bumps the kernel requirement up to 5.4
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001505 // see also: //system/netd/tests/kernel_test.cpp TestKernel54
Maciej Żenczykowski98975122025-01-14 14:57:24 -08001506 if (isAtLeast25Q2 && !isAtLeastKernelVersion(5, 4, 0)) {
1507 ALOGE("Android 25Q2 requires kernel 5.4.");
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001508 return 1;
1509 }
1510
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001511 // Technically already required by U, but only enforce on V+
1512 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1513 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1514 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1515 if (!isTV()) return 1;
1516 }
1517
Maciej Żenczykowski127715a2025-02-10 21:52:01 -08001518 if (isKernel32Bit() && isAtLeast25Q2) {
1519 ALOGE("Android 25Q2 requires 64 bit kernel.");
1520 return 1;
1521 }
1522
Maciej Żenczykowski9b6a9942024-09-03 16:08:35 -07001523 // 6.6 is highest version supported by Android V, so this is effectively W+ (sdk=36+)
1524 if (isKernel32Bit() && isAtLeastKernelVersion(6, 7, 0)) {
1525 ALOGE("Android platform with 32 bit kernel version >= 6.7.0 is unsupported");
1526 return 1;
1527 }
1528
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001529 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1530 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001531 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001532 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001533 }
1534
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001535 if (isAtLeastV) {
1536 bool bad = false;
1537
1538 if (!isLtsKernel()) {
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001539 ALOGW("Android V+ only supports LTS kernels.");
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001540 bad = true;
1541 }
1542
1543#define REQUIRE(maj, min, sub) \
1544 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
Maciej Żenczykowski76f66b62024-09-27 02:46:00 +00001545 ALOGW("Android V+ requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001546 bad = true; \
1547 }
1548
1549 REQUIRE(4, 19, 236)
1550 REQUIRE(5, 4, 186)
1551 REQUIRE(5, 10, 199)
1552 REQUIRE(5, 15, 136)
1553 REQUIRE(6, 1, 57)
1554 REQUIRE(6, 6, 0)
Maciej Żenczykowski06f38e32024-12-11 07:12:59 -08001555 REQUIRE(6, 12, 0)
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001556
1557#undef REQUIRE
1558
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001559 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001560 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1561 }
1562 }
1563
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001564 /* Android 14/U should only launch on 64-bit kernels
1565 * T launches on 5.10/5.15
1566 * U launches on 5.15/6.1
1567 * So >=5.16 implies isKernel64Bit()
1568 *
1569 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1570 *
1571 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1572 * we also require 64-bit userspace.
1573 *
1574 * There are various known issues with 32-bit userspace talking to various
1575 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1576 * Some of these have userspace or kernel workarounds/hacks.
1577 * Some of them don't...
1578 * We're going to be removing the hacks.
1579 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1580 * Note: this check/enforcement only applies to *system* userspace code,
1581 * it does not affect unprivileged apps, the 32-on-64 compatibility
1582 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1583 *
1584 * Additionally the 32-bit kernel jit support is poor,
1585 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001586 * Note, however, that TV and Wear devices will continue to support 32-bit userspace
1587 * on ARM64.
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001588 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001589 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001590 // Stuff won't work reliably, but...
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001591 if (isArm() && (isTV() || isWear())) {
1592 // exempt Arm TV or Wear devices (arm32 ABI is far less problematic than x86-32)
1593 ALOGW("[Arm TV/Wear] 32-bit userspace unsupported on 6.2+ kernels.");
Maciej Żenczykowski73238632025-02-24 14:50:09 -08001594 } else if (first_api_level <= 33 /*T*/ && isArm()) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001595 // also exempt Arm devices upgrading with major kernel rev from T-
1596 // might possibly be better for them to run with a newer kernel...
1597 ALOGW("[Arm KernelUpRev] 32-bit userspace unsupported on 6.2+ kernels.");
1598 } else if (isArm()) {
1599 ALOGE("[Arm] 64-bit userspace required on 6.2+ kernels (%d).", first_api_level);
1600 return 1;
1601 } else { // x86 since RiscV cannot be 32-bit
1602 ALOGE("[x86] 64-bit userspace required on 6.2+ kernels.");
1603 return 1;
1604 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001605 }
1606
Lorenzo Colittid95c0c62024-12-04 15:16:15 +09001607 // On handheld, 6.6 is highest version supported by Android V (sdk=35), so this is for sdk=36+
1608 if (!isArm() && isUserspace32bit() && isAtLeastKernelVersion(6, 7, 0)) {
Maciej Żenczykowski21b4a052024-09-03 15:46:48 -07001609 ALOGE("64-bit userspace required on 6.7+ kernels.");
1610 return 1;
1611 }
1612
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001613 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001614 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001615 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001616 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001617 return 1;
1618 }
1619
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001620 if (runningAsRoot) {
1621 // Note: writing this proc file requires being root (always the case on V+)
1622
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001623 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1624 // but we need 0 (enabled)
1625 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1626 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1627 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001628 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001629 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001630
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001631 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001632 // Note: writing these proc files requires CAP_NET_ADMIN
1633 // and sepolicy which is only present on U+,
1634 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1635 // trigger (ie. by init itself) instead.
1636
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001637 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1638 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1639 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1640 // kernel does not have CONFIG_BPF_JIT=y)
1641 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1642 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1643 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001644
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001645 // Enable JIT kallsyms export for privileged users only
1646 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1647 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1648 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1649 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001650
1651 // Create all the pin subdirectories
1652 // (this must be done first to allow selinux_context and pin_subdir functionality,
1653 // which could otherwise fail with ENOENT during object pinning or renaming,
1654 // due to ordering issues)
1655 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001656 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001657 if (createSysFsBpfSubDir(location.prefix)) return 1;
1658 }
1659
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001660 if (isAtLeastT) {
1661 // Note: there's no actual src dir for fs_bpf_loader .o's,
1662 // so it is not listed in 'locations[].prefix'.
1663 // This is because this is primarily meant for triggering genfscon rules,
1664 // and as such this will likely always be the case.
1665 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1666 if (createSysFsBpfSubDir("loader")) return 1;
1667 }
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001668
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001669 // Load all ELF objects, create programs and maps, and pin them
1670 for (const auto& location : locations) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001671 if (location.t_plus && !isAtLeastT) continue;
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001672 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001673 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1674 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1675 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1676 "problems or startup script race.");
1677 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1678 sleep(20);
1679 return 2;
1680 }
1681 }
1682
1683 int key = 1;
1684 int value = 123;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001685 unique_fd map(
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001686 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1687 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001688 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1689 return 1;
1690 }
1691
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001692 // on S we haven't created this subdir yet, but we need it for 'mainline_done' flag below
1693 if (!isAtLeastT && createSysFsBpfSubDir("netd_shared")) return 1;
1694
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001695 // leave a flag that we're done
1696 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001697
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001698 // platform bpfloader will only succeed when run as root
1699 if (!runningAsRoot) {
1700 // unreachable on U QPR3+ which always runs netbpfload as root
1701
1702 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1703 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001704 }
1705
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001706 // unreachable before U QPR3
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001707 if (exists(uprobestatsBpfLoader)) {
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001708 ALOGI("done, transferring control to uprobestatsbpfload.");
1709 const char *args[] = {
1710 uprobestatsBpfLoader,
1711 NULL,
1712 };
1713 execve(args[0], (char **)args, envp);
Yu-Ting Tsengcb19e1b2024-12-10 14:55:04 -08001714 ALOGI("unable to execute uprobestatsbpfload, transferring control to "
1715 "platform bpfloader.");
Yu-Ting Tseng9b15fa02024-10-28 11:16:35 -07001716 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001717
1718 // platform BpfLoader *needs* to run as root
1719 const char * args[] = { platformBpfLoader, NULL, };
1720 execve(args[0], (char**)args, envp);
1721 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1722 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001723}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001724
1725} // namespace bpf
1726} // namespace android
1727
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001728int main(int argc, char** argv, char * const envp[]) {
Maciej Żenczykowski0b477492025-03-04 22:12:42 -08001729 if (android::bpf::isAtLeastT) {
1730 InitLogging(argv, &KernelLogger);
1731 } else {
1732 // S lacks the sepolicy to make non-root uid KernelLogger viable
1733 InitLogging(argv);
1734 }
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001735
1736 if (argc == 2 && !strcmp(argv[1], "done")) {
1737 // we're being re-exec'ed from platform bpfloader to 'finalize' things
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001738 if (!SetProperty("bpf.progs_loaded", "1")) {
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001739 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1740 return 125;
1741 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001742 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001743 return 0;
1744 }
1745
1746 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001747}