blob: 69f1cb5b5895883c21845a8927b411c5d5da5a60 [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>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070020#include <dirent.h>
21#include <elf.h>
22#include <errno.h>
23#include <error.h>
24#include <fcntl.h>
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070025#include <fstream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070026#include <inttypes.h>
27#include <iostream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070028#include <linux/unistd.h>
29#include <log/log.h>
30#include <net/if.h>
31#include <optional>
32#include <stdint.h>
33#include <stdio.h>
34#include <stdlib.h>
35#include <string.h>
36#include <string>
37#include <sys/mman.h>
38#include <sys/socket.h>
39#include <sys/stat.h>
40#include <sys/types.h>
41#include <sys/utsname.h>
42#include <sys/wait.h>
43#include <sysexits.h>
44#include <unistd.h>
45#include <unordered_map>
46#include <vector>
47
48#include <android-base/cmsg.h>
49#include <android-base/file.h>
50#include <android-base/logging.h>
51#include <android-base/macros.h>
52#include <android-base/properties.h>
53#include <android-base/stringprintf.h>
54#include <android-base/strings.h>
55#include <android-base/unique_fd.h>
56#include <android/api-level.h>
57
58#include "BpfSyscallWrappers.h"
59#include "bpf/BpfUtils.h"
Maciej Żenczykowskid6028352024-08-19 15:20:04 -070060#include "bpf_map_def.h"
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070061
62using android::base::EndsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070063using android::base::GetIntProperty;
64using android::base::GetProperty;
65using android::base::InitLogging;
66using android::base::KernelLogger;
67using android::base::SetProperty;
68using android::base::Split;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070069using android::base::StartsWith;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -070070using android::base::Tokenize;
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070071using android::base::unique_fd;
72using std::ifstream;
73using std::ios;
74using std::optional;
75using std::string;
76using std::vector;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070077
78namespace android {
79namespace bpf {
80
81// Bpf programs may specify per-program & per-map selinux_context and pin_subdir.
82//
83// The BpfLoader needs to convert these bpf.o specified strings into an enum
84// for internal use (to check that valid values were specified for the specific
85// location of the bpf.o file).
86//
87// It also needs to map selinux_context's into pin_subdir's.
88// This is because of how selinux_context is actually implemented via pin+rename.
89//
90// Thus 'domain' enumerates all selinux_context's/pin_subdir's that the BpfLoader
91// is aware of. Thus there currently needs to be a 1:1 mapping between the two.
92//
93enum class domain : int {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070094 unspecified = 0, // means just use the default for that specific pin location
95 tethering, // (S+) fs_bpf_tethering /sys/fs/bpf/tethering
96 net_private, // (T+) fs_bpf_net_private /sys/fs/bpf/net_private
97 net_shared, // (T+) fs_bpf_net_shared /sys/fs/bpf/net_shared
98 netd_readonly, // (T+) fs_bpf_netd_readonly /sys/fs/bpf/netd_readonly
99 netd_shared, // (T+) fs_bpf_netd_shared /sys/fs/bpf/netd_shared
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700100 loader, // (U+) fs_bpf_loader /sys/fs/bpf/loader
101 // on T due to lack of sepolicy/genfscon rules it behaves simply as 'fs_bpf'
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700102};
103
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700104static constexpr domain AllDomains[] = {
105 domain::unspecified,
106 domain::tethering,
107 domain::net_private,
108 domain::net_shared,
109 domain::netd_readonly,
110 domain::netd_shared,
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700111 domain::loader,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700112};
113
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700114static constexpr bool specified(domain d) {
115 return d != domain::unspecified;
116}
117
118struct Location {
119 const char* const dir = "";
120 const char* const prefix = "";
121};
122
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700123// Returns the build type string (from ro.build.type).
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700124const std::string& getBuildType() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700125 static std::string t = GetProperty("ro.build.type", "unknown");
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700126 return t;
127}
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700128
129// The following functions classify the 3 Android build types.
130inline bool isEng() {
131 return getBuildType() == "eng";
132}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700133
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700134inline bool isUser() {
135 return getBuildType() == "user";
136}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700137
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700138inline bool isUserdebug() {
139 return getBuildType() == "userdebug";
140}
141
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700142#define BPF_FS_PATH "/sys/fs/bpf/"
143
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700144static unsigned int page_size = static_cast<unsigned int>(getpagesize());
145
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700146constexpr const char* lookupSelinuxContext(const domain d) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700147 switch (d) {
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700148 case domain::unspecified: return "";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700149 case domain::tethering: return "fs_bpf_tethering";
150 case domain::net_private: return "fs_bpf_net_private";
151 case domain::net_shared: return "fs_bpf_net_shared";
152 case domain::netd_readonly: return "fs_bpf_netd_readonly";
153 case domain::netd_shared: return "fs_bpf_netd_shared";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700154 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700155 }
156}
157
158domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
159 for (domain d : AllDomains) {
160 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
161 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
162 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
163 }
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700164 ALOGE("unrecognized selinux_context '%-32s'", s);
165 // Note: we *can* just abort() here as we only load bpf .o files shipped
166 // in the same mainline module / apex as NetBpfLoad itself.
167 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700168}
169
170constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
171 switch (d) {
172 case domain::unspecified: return unspecified;
173 case domain::tethering: return "tethering/";
174 case domain::net_private: return "net_private/";
175 case domain::net_shared: return "net_shared/";
176 case domain::netd_readonly: return "netd_readonly/";
177 case domain::netd_shared: return "netd_shared/";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700178 case domain::loader: return "loader/";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700179 }
180};
181
182domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
183 for (domain d : AllDomains) {
184 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
185 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
186 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
187 }
188 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700189 // Note: we *can* just abort() here as we only load bpf .o files shipped
190 // in the same mainline module / apex as NetBpfLoad itself.
191 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700192}
193
194static string pathToObjName(const string& path) {
195 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700196 string filename = Split(path, "/").back();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700197 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
198 string name = filename.substr(0, filename.find_last_of('.'));
199 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
200 // this can be used to provide duplicate programs (mux based on the bpfloader version)
201 return name.substr(0, name.find_last_of('@'));
202}
203
204typedef struct {
205 const char* name;
206 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000207 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700208} sectionType;
209
210/*
211 * Map section name prefixes to program types, the section name will be:
212 * SECTION(<prefix>/<name-of-program>)
213 * For example:
214 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
215 * is the name of the program, and tracepoint is the type.
216 *
217 * However, be aware that you should not be directly using the SECTION() macro.
218 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
219 *
220 * Programs shipped inside the tethering apex should be limited to networking stuff,
221 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
222 * since they are less stable abi/api and may conflict with platform uses of bpf.
223 */
224sectionType sectionNameTypes[] = {
225 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
226 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000227 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
228 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700229 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
230 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
231 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
232 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
233 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
234 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
235 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700236 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
237 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
238 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
239 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000240 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
241 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700242 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
243 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
244 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000245 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700246 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
247 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000248 {"xdp/", BPF_PROG_TYPE_XDP},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700249};
250
251typedef struct {
252 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000253 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700254 string name;
255 vector<char> data;
256 vector<char> rel_data;
257 optional<struct bpf_prog_def> prog_def;
258
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000259 unique_fd prog_fd; // fd after loading
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700260} codeSection;
261
262static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
263 elfFile.seekg(0);
264 if (elfFile.fail()) return -1;
265
266 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
267
268 return 0;
269}
270
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000271// Reads all section header tables into an Shdr array
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700272static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
273 Elf64_Ehdr eh;
274 int ret = 0;
275
276 ret = readElfHeader(elfFile, &eh);
277 if (ret) return ret;
278
279 elfFile.seekg(eh.e_shoff);
280 if (elfFile.fail()) return -1;
281
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000282 // Read shdr table entries
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700283 shTable.resize(eh.e_shnum);
284
285 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
286
287 return 0;
288}
289
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000290// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700291static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
292 vector<Elf64_Shdr> shTable;
293 int ret = readSectionHeadersAll(elfFile, shTable);
294 if (ret) return ret;
295
296 elfFile.seekg(shTable[id].sh_offset);
297 if (elfFile.fail()) return -1;
298
299 sec.resize(shTable[id].sh_size);
300 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
301
302 return 0;
303}
304
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000305// Read whole section header string table
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700306static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
307 Elf64_Ehdr eh;
308 int ret = readElfHeader(elfFile, &eh);
309 if (ret) return ret;
310
311 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
312 if (ret) return ret;
313
314 return 0;
315}
316
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000317// Get name from offset in strtab
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700318static int getSymName(ifstream& elfFile, int nameOff, string& name) {
319 int ret;
320 vector<char> secStrTab;
321
322 ret = readSectionHeaderStrtab(elfFile, secStrTab);
323 if (ret) return ret;
324
325 if (nameOff >= (int)secStrTab.size()) return -1;
326
327 name = string((char*)secStrTab.data() + nameOff);
328 return 0;
329}
330
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000331// Reads a full section by name - example to get the GPL license
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700332static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
333 vector<char> secStrTab;
334 vector<Elf64_Shdr> shTable;
335 int ret;
336
337 ret = readSectionHeadersAll(elfFile, shTable);
338 if (ret) return ret;
339
340 ret = readSectionHeaderStrtab(elfFile, secStrTab);
341 if (ret) return ret;
342
343 for (int i = 0; i < (int)shTable.size(); i++) {
344 char* secname = secStrTab.data() + shTable[i].sh_name;
345 if (!secname) continue;
346
347 if (!strcmp(secname, name)) {
348 vector<char> dataTmp;
349 dataTmp.resize(shTable[i].sh_size);
350
351 elfFile.seekg(shTable[i].sh_offset);
352 if (elfFile.fail()) return -1;
353
354 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
355
356 data = dataTmp;
357 return 0;
358 }
359 }
360 return -2;
361}
362
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700363unsigned int readSectionUint(const char* name, ifstream& elfFile) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700364 vector<char> theBytes;
365 int ret = readSectionByName(name, elfFile, theBytes);
366 if (ret) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700367 ALOGE("Couldn't find section %s.", name);
368 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700369 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700370 ALOGE("Section %s is too short.", name);
371 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700372 } else {
373 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
374 unsigned int value = static_cast<unsigned char>(theBytes[3]);
375 value <<= 8;
376 value += static_cast<unsigned char>(theBytes[2]);
377 value <<= 8;
378 value += static_cast<unsigned char>(theBytes[1]);
379 value <<= 8;
380 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000381 ALOGD("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700382 return value;
383 }
384}
385
386static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
387 int ret;
388 vector<Elf64_Shdr> shTable;
389
390 ret = readSectionHeadersAll(elfFile, shTable);
391 if (ret) return ret;
392
393 for (int i = 0; i < (int)shTable.size(); i++) {
394 if ((int)shTable[i].sh_type != type) continue;
395
396 vector<char> dataTmp;
397 dataTmp.resize(shTable[i].sh_size);
398
399 elfFile.seekg(shTable[i].sh_offset);
400 if (elfFile.fail()) return -1;
401
402 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
403
404 data = dataTmp;
405 return 0;
406 }
407 return -2;
408}
409
410static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
411 return (a.st_value < b.st_value);
412}
413
414static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
415 int ret, numElems;
416 Elf64_Sym* buf;
417 vector<char> secData;
418
419 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
420 if (ret) return ret;
421
422 buf = (Elf64_Sym*)secData.data();
423 numElems = (secData.size() / sizeof(Elf64_Sym));
424 data.assign(buf, buf + numElems);
425
426 if (sort) std::sort(data.begin(), data.end(), symCompare);
427 return 0;
428}
429
430static enum bpf_prog_type getSectionType(string& name) {
431 for (auto& snt : sectionNameTypes)
432 if (StartsWith(name, snt.name)) return snt.type;
433
434 return BPF_PROG_TYPE_UNSPEC;
435}
436
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700437static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700438 vector<char> pdData;
439 int ret = readSectionByName("progs", elfFile, pdData);
440 if (ret) return ret;
441
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700442 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700443 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700444 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700445 return -1;
446 };
447
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700448 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700449
450 const char* dataPtr = pdData.data();
451 for (auto& p : pd) {
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700452 // Copy the structure from the ELF file and move to the next one.
453 memcpy(&p, dataPtr, sizeof(struct bpf_prog_def));
454 dataPtr += sizeof(struct bpf_prog_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700455 }
456 return 0;
457}
458
459static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
460 optional<unsigned> symbolType = std::nullopt) {
461 int ret;
462 string name;
463 vector<Elf64_Sym> symtab;
464 vector<Elf64_Shdr> shTable;
465
466 ret = readSymTab(elfFile, 1 /* sort */, symtab);
467 if (ret) return ret;
468
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000469 // Get index of section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700470 ret = readSectionHeadersAll(elfFile, shTable);
471 if (ret) return ret;
472
473 int sec_idx = -1;
474 for (int i = 0; i < (int)shTable.size(); i++) {
475 ret = getSymName(elfFile, shTable[i].sh_name, name);
476 if (ret) return ret;
477
478 if (!name.compare(sectionName)) {
479 sec_idx = i;
480 break;
481 }
482 }
483
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000484 // No section found with matching name
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700485 if (sec_idx == -1) {
486 ALOGW("No %s section could be found in elf object", sectionName.c_str());
487 return -1;
488 }
489
490 for (int i = 0; i < (int)symtab.size(); i++) {
491 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
492
493 if (symtab[i].st_shndx == sec_idx) {
494 string s;
495 ret = getSymName(elfFile, symtab[i].st_name, s);
496 if (ret) return ret;
497 names.push_back(s);
498 }
499 }
500
501 return 0;
502}
503
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000504// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700505static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700506 vector<Elf64_Shdr> shTable;
507 int entries, ret = 0;
508
509 ret = readSectionHeadersAll(elfFile, shTable);
510 if (ret) return ret;
511 entries = shTable.size();
512
513 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700514 ret = readProgDefs(elfFile, pd);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700515 if (ret) return ret;
516 vector<string> progDefNames;
517 ret = getSectionSymNames(elfFile, "progs", progDefNames);
518 if (!pd.empty() && ret) return ret;
519
520 for (int i = 0; i < entries; i++) {
521 string name;
522 codeSection cs_temp;
523 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
524
525 ret = getSymName(elfFile, shTable[i].sh_name, name);
526 if (ret) return ret;
527
528 enum bpf_prog_type ptype = getSectionType(name);
529
530 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
531
532 // This must be done before '/' is replaced with '_'.
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000533 for (auto& snt : sectionNameTypes)
534 if (StartsWith(name, snt.name)) cs_temp.attach_type = snt.attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700535
536 string oldName = name;
537
538 // convert all slashes to underscores
539 std::replace(name.begin(), name.end(), '/', '_');
540
541 cs_temp.type = ptype;
542 cs_temp.name = name;
543
544 ret = readSectionByIdx(elfFile, i, cs_temp.data);
545 if (ret) return ret;
546 ALOGV("Loaded code section %d (%s)", i, name.c_str());
547
548 vector<string> csSymNames;
549 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
550 if (ret || !csSymNames.size()) return ret;
551 for (size_t i = 0; i < progDefNames.size(); ++i) {
552 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
553 cs_temp.prog_def = pd[i];
554 break;
555 }
556 }
557
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000558 // Check for rel section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700559 if (cs_temp.data.size() > 0 && i < entries) {
560 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
561 if (ret) return ret;
562
563 if (name == (".rel" + oldName)) {
564 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
565 if (ret) return ret;
566 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
567 }
568 }
569
570 if (cs_temp.data.size() > 0) {
571 cs.push_back(std::move(cs_temp));
572 ALOGV("Adding section %d to cs list", i);
573 }
574 }
575 return 0;
576}
577
578static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
579 vector<Elf64_Sym> symtab;
580 int ret = 0;
581
582 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
583 if (ret) return ret;
584
585 if (index >= (int)symtab.size()) return -1;
586
587 return getSymName(elfFile, symtab[index].st_name, name);
588}
589
590static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
591 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
592 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
593 // so on 4.9-T kernels just pretend the map matches our expectations.
594 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
595 // This is because the primary failure mode we're trying to detect here
596 // is either a source code misconfiguration (which is likely kernel independent)
597 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
598 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
599
600 // Assuming fd is a valid Bpf Map file descriptor then
601 // all the following should always succeed on a 4.14+ kernel.
602 // If they somehow do fail, they'll return -1 (and set errno),
603 // which should then cause (among others) a key_size mismatch.
604 int fd_type = bpfGetFdMapType(fd);
605 int fd_key_size = bpfGetFdKeySize(fd);
606 int fd_value_size = bpfGetFdValueSize(fd);
607 int fd_max_entries = bpfGetFdMaxEntries(fd);
608 int fd_map_flags = bpfGetFdMapFlags(fd);
609
610 // DEVMAPs are readonly from the bpf program side's point of view, as such
611 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
612 int desired_map_flags = (int)mapDef.map_flags;
613 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
614 desired_map_flags |= BPF_F_RDONLY_PROG;
615
Maciej Żenczykowskidcb2e742024-08-29 10:40:35 -0700616 if (type == BPF_MAP_TYPE_LPM_TRIE)
617 desired_map_flags |= BPF_F_NO_PREALLOC;
618
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700619 // The .h file enforces that this is a power of two, and page size will
620 // also always be a power of two, so this logic is actually enough to
621 // force it to be a multiple of the page size, as required by the kernel.
622 unsigned int desired_max_entries = mapDef.max_entries;
623 if (type == BPF_MAP_TYPE_RINGBUF) {
624 if (desired_max_entries < page_size) desired_max_entries = page_size;
625 }
626
627 // The following checks should *never* trigger, if one of them somehow does,
628 // it probably means a bpf .o file has been changed/replaced at runtime
629 // and bpfloader was manually rerun (normally it should only run *once*
630 // early during the boot process).
631 // Another possibility is that something is misconfigured in the code:
632 // most likely a shared map is declared twice differently.
633 // But such a change should never be checked into the source tree...
634 if ((fd_type == type) &&
635 (fd_key_size == (int)mapDef.key_size) &&
636 (fd_value_size == (int)mapDef.value_size) &&
637 (fd_max_entries == (int)desired_max_entries) &&
638 (fd_map_flags == desired_map_flags)) {
639 return true;
640 }
641
642 ALOGE("bpf map name %s mismatch: desired/found: "
643 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
644 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
645 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
646 return false;
647}
648
649static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700650 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700651 int ret;
652 vector<char> mdData;
653 vector<struct bpf_map_def> md;
654 vector<string> mapNames;
655 string objName = pathToObjName(string(elfPath));
656
657 ret = readSectionByName("maps", elfFile, mdData);
658 if (ret == -2) return 0; // no maps to read
659 if (ret) return ret;
660
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700661 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700662 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700663 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700664 return -1;
665 };
666
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700667 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700668
669 const char* dataPtr = mdData.data();
670 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700671 // Copy the structure from the ELF file and move to the next one.
672 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
673 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700674 }
675
676 ret = getSectionSymNames(elfFile, "maps", mapNames);
677 if (ret) return ret;
678
679 unsigned kvers = kernelVersion();
680
681 for (int i = 0; i < (int)mapNames.size(); i++) {
682 if (md[i].zero != 0) abort();
683
684 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000685 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700686 md[i].bpfloader_min_ver);
687 mapFds.push_back(unique_fd());
688 continue;
689 }
690
691 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000692 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700693 md[i].bpfloader_max_ver);
694 mapFds.push_back(unique_fd());
695 continue;
696 }
697
698 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000699 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700700 mapNames[i].c_str(), kvers, md[i].min_kver);
701 mapFds.push_back(unique_fd());
702 continue;
703 }
704
705 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000706 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700707 mapNames[i].c_str(), kvers, md[i].max_kver);
708 mapFds.push_back(unique_fd());
709 continue;
710 }
711
712 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
713 (md[i].ignore_on_userdebug && isUserdebug())) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000714 ALOGD("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700715 getBuildType().c_str());
716 mapFds.push_back(unique_fd());
717 continue;
718 }
719
720 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
721 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
722 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
723 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
724 (isRiscV() && md[i].ignore_on_riscv64)) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000725 ALOGD("skipping map %s which is ignored on %s", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700726 describeArch());
727 mapFds.push_back(unique_fd());
728 continue;
729 }
730
731 enum bpf_map_type type = md[i].type;
732 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
733 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
734 // of be approximated: ARRAY has the same userspace api, though it is not usable
735 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
736 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
737 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
738 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
739 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
740 type = BPF_MAP_TYPE_ARRAY;
741 }
742 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
743 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
744 // of be approximated: HASH has the same userspace visible api.
745 // However it cannot be used by ebpf programs in the same way.
746 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
747 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
748 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
749 // programs as being 5.4+...
750 type = BPF_MAP_TYPE_HASH;
751 }
752
753 // The .h file enforces that this is a power of two, and page size will
754 // also always be a power of two, so this logic is actually enough to
755 // force it to be a multiple of the page size, as required by the kernel.
756 unsigned int max_entries = md[i].max_entries;
757 if (type == BPF_MAP_TYPE_RINGBUF) {
758 if (max_entries < page_size) max_entries = page_size;
759 }
760
761 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
762 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000763 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700764 md[i].selinux_context, static_cast<int>(selinux_context),
765 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
766 }
767
768 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700769 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000770 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700771 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
772 }
773
774 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
775 // except that maps shared across .o's have empty <objName>
776 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
777 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
778 (md[i].shared ? "" : objName) + "_" + mapNames[i];
779 bool reuse = false;
780 unique_fd fd;
781 int saved_errno;
782
783 if (access(mapPinLoc.c_str(), F_OK) == 0) {
784 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
785 saved_errno = errno;
786 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
787 reuse = true;
788 } else {
789 union bpf_attr req = {
790 .map_type = type,
791 .key_size = md[i].key_size,
792 .value_size = md[i].value_size,
793 .max_entries = max_entries,
Maciej Żenczykowskidcb2e742024-08-29 10:40:35 -0700794 .map_flags = md[i].map_flags | (type == BPF_MAP_TYPE_LPM_TRIE ? BPF_F_NO_PREALLOC : 0),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700795 };
796 if (isAtLeastKernelVersion(4, 15, 0))
797 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
798 fd.reset(bpf(BPF_MAP_CREATE, req));
799 saved_errno = errno;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -0700800 if (fd.ok()) {
801 ALOGD("bpf_create_map[%s] -> %d", mapNames[i].c_str(), fd.get());
802 } else {
803 ALOGE("bpf_create_map[%s] -> %d errno:%d", mapNames[i].c_str(), fd.get(), saved_errno);
804 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700805 }
806
807 if (!fd.ok()) return -saved_errno;
808
809 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
810 // safety (since reuse code path is rare) run these checks even if we just created it.
811 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
812 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
813
814 if (!reuse) {
815 if (specified(selinux_context)) {
816 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
817 "tmp_map_" + objName + "_" + mapNames[i];
818 ret = bpfFdPin(fd, createLoc.c_str());
819 if (ret) {
820 int err = errno;
821 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
822 return -err;
823 }
824 ret = renameat2(AT_FDCWD, createLoc.c_str(),
825 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
826 if (ret) {
827 int err = errno;
828 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
829 err, strerror(err));
830 return -err;
831 }
832 } else {
833 ret = bpfFdPin(fd, mapPinLoc.c_str());
834 if (ret) {
835 int err = errno;
836 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
837 return -err;
838 }
839 }
840 ret = chmod(mapPinLoc.c_str(), md[i].mode);
841 if (ret) {
842 int err = errno;
843 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
844 strerror(err));
845 return -err;
846 }
847 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
848 if (ret) {
849 int err = errno;
850 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
851 ret, err, strerror(err));
852 return -err;
853 }
854 }
855
856 int mapId = bpfGetFdMapId(fd);
857 if (mapId == -1) {
Maciej Żenczykowski508c8f72024-08-28 15:07:33 -0700858 if (isAtLeastKernelVersion(4, 14, 0))
859 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700860 } else {
861 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
862 }
863
864 mapFds.push_back(std::move(fd));
865 }
866
867 return ret;
868}
869
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700870static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
871 int insnIndex;
872 struct bpf_insn *insn, *insns;
873
874 insns = (struct bpf_insn*)(insnsPtr);
875
876 insnIndex = offset / sizeof(struct bpf_insn);
877 insn = &insns[insnIndex];
878
879 // Occasionally might be useful for relocation debugging, but pretty spammy
880 if (0) {
881 ALOGV("applying relo to instruction at byte offset: %llu, "
882 "insn offset %d, insn %llx",
883 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
884 }
885
886 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700887 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700888 return;
889 }
890
891 insn->imm = fd;
892 insn->src_reg = BPF_PSEUDO_MAP_FD;
893}
894
895static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
896 vector<string> mapNames;
897
898 int ret = getSectionSymNames(elfFile, "maps", mapNames);
899 if (ret) return;
900
901 for (int k = 0; k != (int)cs.size(); k++) {
902 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
903 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
904
905 for (int i = 0; i < n_rel; i++) {
906 int symIndex = ELF64_R_SYM(rel[i].r_info);
907 string symName;
908
909 ret = getSymNameByIdx(elfFile, symIndex, symName);
910 if (ret) return;
911
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000912 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700913 for (int j = 0; j < (int)mapNames.size(); j++) {
914 if (!mapNames[j].compare(symName)) {
915 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
916 break;
917 }
918 }
919 }
920 }
921}
922
923static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
924 const char* prefix, const unsigned int bpfloader_ver) {
925 unsigned kvers = kernelVersion();
926
927 if (!kvers) {
928 ALOGE("unable to get kernel version");
929 return -EINVAL;
930 }
931
932 string objName = pathToObjName(string(elfPath));
933
934 for (int i = 0; i < (int)cs.size(); i++) {
935 unique_fd& fd = cs[i].prog_fd;
936 int ret;
937 string name = cs[i].name;
938
939 if (!cs[i].prog_def.has_value()) {
940 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
941 return -EINVAL;
942 }
943
944 unsigned min_kver = cs[i].prog_def->min_kver;
945 unsigned max_kver = cs[i].prog_def->max_kver;
946 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
947 max_kver, kvers);
948 if (kvers < min_kver) continue;
949 if (kvers >= max_kver) continue;
950
951 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
952 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
953 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
954 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700955
956 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
957 bpfMinVer, bpfMaxVer);
958 if (bpfloader_ver < bpfMinVer) continue;
959 if (bpfloader_ver >= bpfMaxVer) continue;
960
961 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
962 (cs[i].prog_def->ignore_on_user && isUser()) ||
963 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
964 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
965 getBuildType().c_str());
966 continue;
967 }
968
969 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
970 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
971 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
972 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
973 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
974 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
975 continue;
976 }
977
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700978 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000979 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700980 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
981 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
982 }
983
984 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000985 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700986 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
987 lookupPinSubdir(pin_subdir));
988 }
989
990 // strip any potential $foo suffix
991 // this can be used to provide duplicate programs
992 // conditionally loaded based on running kernel version
993 name = name.substr(0, name.find_last_of('$'));
994
995 bool reuse = false;
996 // Format of pin location is
997 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
998 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
999 objName + '_' + string(name);
1000 if (access(progPinLoc.c_str(), F_OK) == 0) {
1001 fd.reset(retrieveProgram(progPinLoc.c_str()));
1002 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
1003 (!fd.ok() ? std::strerror(errno) : "no error"));
1004 reuse = true;
1005 } else {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001006 static char log_buf[1 << 20]; // 1 MiB logging buffer
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001007
1008 union bpf_attr req = {
1009 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001010 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001011 .insns = ptr_to_u64(cs[i].data.data()),
1012 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001013 .log_level = 1,
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001014 .log_size = sizeof(log_buf),
1015 .log_buf = ptr_to_u64(log_buf),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001016 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001017 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001018 };
1019 if (isAtLeastKernelVersion(4, 15, 0))
1020 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1021 fd.reset(bpf(BPF_PROG_LOAD, req));
1022
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001023 // Kernel should have NULL terminated the log buffer, but force it anyway for safety
1024 log_buf[sizeof(log_buf) - 1] = 0;
1025
1026 // Strip out final newline if present
1027 int log_chars = strlen(log_buf);
1028 if (log_chars && log_buf[log_chars - 1] == '\n') log_buf[--log_chars] = 0;
1029
1030 bool log_oneline = !strchr(log_buf, '\n');
1031
1032 ALOGD("BPF_PROG_LOAD call for %s (%s) returned '%s' fd: %d (%s)", elfPath,
1033 cs[i].name.c_str(), log_oneline ? log_buf : "{multiline}",
1034 fd.get(), (!fd.ok() ? std::strerror(errno) : "ok"));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001035
1036 if (!fd.ok()) {
Maciej Żenczykowskiea1d8f62024-09-05 09:38:14 -07001037 // kernel NULL terminates log_buf, so this checks for non-empty string
1038 if (log_buf[0]) {
1039 vector<string> lines = Split(log_buf, "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001040
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001041 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1042 for (const auto& line : lines) ALOGW("%s", line.c_str());
1043 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1044 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001045
1046 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001047 ALOGW("failed program %s is marked optional - continuing...",
1048 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001049 continue;
1050 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001051 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001052 }
1053 }
1054
1055 if (!fd.ok()) return fd.get();
1056
1057 if (!reuse) {
1058 if (specified(selinux_context)) {
1059 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1060 "tmp_prog_" + objName + '_' + string(name);
1061 ret = bpfFdPin(fd, createLoc.c_str());
1062 if (ret) {
1063 int err = errno;
1064 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1065 return -err;
1066 }
1067 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1068 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1069 if (ret) {
1070 int err = errno;
1071 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1072 err, strerror(err));
1073 return -err;
1074 }
1075 } else {
1076 ret = bpfFdPin(fd, progPinLoc.c_str());
1077 if (ret) {
1078 int err = errno;
1079 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1080 return -err;
1081 }
1082 }
1083 if (chmod(progPinLoc.c_str(), 0440)) {
1084 int err = errno;
1085 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1086 return -err;
1087 }
1088 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1089 (gid_t)cs[i].prog_def->gid)) {
1090 int err = errno;
1091 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1092 cs[i].prog_def->gid, err, strerror(err));
1093 return -err;
1094 }
1095 }
1096
1097 int progId = bpfGetFdProgId(fd);
1098 if (progId == -1) {
1099 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
1100 } else {
1101 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
1102 }
1103 }
1104
1105 return 0;
1106}
1107
1108int loadProg(const char* const elfPath, bool* const isCritical, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001109 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001110 vector<char> license;
1111 vector<char> critical;
1112 vector<codeSection> cs;
1113 vector<unique_fd> mapFds;
1114 int ret;
1115
1116 if (!isCritical) return -1;
1117 *isCritical = false;
1118
1119 ifstream elfFile(elfPath, ios::in | ios::binary);
1120 if (!elfFile.is_open()) return -1;
1121
1122 ret = readSectionByName("critical", elfFile, critical);
1123 *isCritical = !ret;
1124
1125 ret = readSectionByName("license", elfFile, license);
1126 if (ret) {
1127 ALOGE("Couldn't find license in %s", elfPath);
1128 return ret;
1129 } else {
1130 ALOGD("Loading %s%s ELF object %s with license %s",
1131 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
1132 elfPath, (char*)license.data());
1133 }
1134
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001135 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1136 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001137
1138 // inclusive lower bound check
1139 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001140 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001141 bpfloader_ver, elfPath, bpfLoaderMinVer);
1142 return 0;
1143 }
1144
1145 // exclusive upper bound check
1146 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001147 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001148 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1149 return 0;
1150 }
1151
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001152 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001153 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1154
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001155 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001156 if (ret) {
1157 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1158 return ret;
1159 }
1160
1161 for (int i = 0; i < (int)mapFds.size(); i++)
1162 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1163
Maciej Żenczykowski1e487172024-09-05 09:27:35 -07001164 ret = readCodeSections(elfFile, cs);
1165 if (ret == -ENOENT) return 0; // no programs defined in this .o
1166 if (ret) {
1167 ALOGE("Couldn't read all code sections in %s", elfPath);
1168 return ret;
1169 }
1170
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001171 applyMapRelo(elfFile, mapFds, cs);
1172
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001173 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001174 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1175
1176 return ret;
1177}
1178
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001179static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001180 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001181 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001182 if (errno == ENOENT) return false;
1183 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1184 abort(); // can only hit this if permissions (likely selinux) are screwed up
1185}
1186
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001187#define APEXROOT "/apex/com.android.tethering"
1188#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001189
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001190const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001191 // S+ Tethering mainline module (network_stack): tether offload
1192 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001193 .dir = BPFROOT "/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001194 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001195 },
1196 // T+ Tethering mainline module (shared with netd & system server)
1197 // netutils_wrapper (for iptables xt_bpf) has access to programs
1198 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001199 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001200 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001201 },
1202 // T+ Tethering mainline module (shared with netd & system server)
1203 // netutils_wrapper has no access, netd has read only access
1204 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001205 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001206 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001207 },
1208 // T+ Tethering mainline module (shared with system server)
1209 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001210 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001211 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001212 },
1213 // T+ Tethering mainline module (not shared, just network_stack)
1214 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001215 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001216 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001217 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001218};
1219
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001220static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001221 int retVal = 0;
1222 DIR* dir;
1223 struct dirent* ent;
1224
1225 if ((dir = opendir(location.dir)) != NULL) {
1226 while ((ent = readdir(dir)) != NULL) {
1227 string s = ent->d_name;
1228 if (!EndsWith(s, ".o")) continue;
1229
1230 string progPath(location.dir);
1231 progPath += s;
1232
1233 bool critical;
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001234 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001235 if (ret) {
1236 if (critical) retVal = ret;
1237 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1238 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001239 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001240 }
1241 }
1242 closedir(dir);
1243 }
1244 return retVal;
1245}
1246
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001247static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001248 if (*prefix) {
1249 mode_t prevUmask = umask(0);
1250
1251 string s = "/sys/fs/bpf/";
1252 s += prefix;
1253
1254 errno = 0;
1255 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1256 if (ret && errno != EEXIST) {
1257 const int err = errno;
1258 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1259 return -err;
1260 }
1261
1262 umask(prevUmask);
1263 }
1264 return 0;
1265}
1266
1267// Technically 'value' doesn't need to be newline terminated, but it's best
1268// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1269// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001270static int writeProcSysFile(const char *filename, const char *value) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001271 unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001272 if (fd < 0) {
1273 const int err = errno;
1274 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1275 return -err;
1276 }
1277 int len = strlen(value);
1278 int v = write(fd, value, len);
1279 if (v < 0) {
1280 const int err = errno;
1281 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1282 return -err;
1283 }
1284 if (v != len) {
1285 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1286 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1287 return -EINVAL;
1288 }
1289 return 0;
1290}
1291
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001292#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001293const char * const platformBpfLoader = "/system/bin/bpfloader";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001294
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001295static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001296 char * found_blockdev = NULL;
1297 FILE * f = NULL;
1298 char buf[4096];
1299
1300 f = fopen("/proc/mounts", "re");
1301 if (!f) return 1;
1302
1303 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1304 while (fgets(buf, sizeof(buf), f)) {
1305 char * blockdev = buf;
1306 char * space = strchr(blockdev, ' ');
1307 if (!space) continue;
1308 *space = '\0';
1309 char * mntpath = space + 1;
1310 space = strchr(mntpath, ' ');
1311 if (!space) continue;
1312 *space = '\0';
1313 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1314 found_blockdev = strdup(blockdev);
1315 break;
1316 }
1317 fclose(f);
1318 f = NULL;
1319
1320 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001321 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001322
1323 f = fopen("/proc/mounts", "re");
1324 if (!f) { free(found_blockdev); return 3; }
1325
1326 while (fgets(buf, sizeof(buf), f)) {
1327 char * blockdev = buf;
1328 char * space = strchr(blockdev, ' ');
1329 if (!space) continue;
1330 *space = '\0';
1331 char * mntpath = space + 1;
1332 space = strchr(mntpath, ' ');
1333 if (!space) continue;
1334 *space = '\0';
1335 if (strcmp(blockdev, found_blockdev)) continue;
1336 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1337 char * at = strchr(mntpath, '@');
1338 if (!at) continue;
1339 char * ver = at + 1;
1340 ALOGI("Tethering APEX version %s", ver);
1341 }
1342 fclose(f);
1343 free(found_blockdev);
1344 return 0;
1345}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001346
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001347static bool hasGSM() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001348 static string ph = GetProperty("gsm.current.phone-type", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001349 static bool gsm = (ph != "");
1350 static bool logged = false;
1351 if (!logged) {
1352 logged = true;
1353 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1354 }
1355 return gsm;
1356}
1357
1358static bool isTV() {
1359 if (hasGSM()) return false; // TVs don't do GSM
1360
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001361 static string key = GetProperty("ro.oem.key1", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001362 static bool tv = StartsWith(key, "ATV00");
1363 static bool logged = false;
1364 if (!logged) {
1365 logged = true;
1366 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1367 }
1368 return tv;
1369}
1370
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001371static bool isWear() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001372 static string wearSdkStr = GetProperty("ro.cw_build.wear_sdk.version", "");
1373 static int wearSdkInt = GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1374 static string buildChars = GetProperty("ro.build.characteristics", "");
1375 static vector<string> v = Tokenize(buildChars, ",");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001376 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1377 static bool wear = (wearSdkInt > 0) || watch;
1378 static bool logged = false;
1379 if (!logged) {
1380 logged = true;
1381 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1382 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1383 }
1384 return wear;
1385}
1386
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001387static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001388 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001389
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001390 // Any released device will have codename REL instead of a 'real' codename.
1391 // For safety: default to 'REL' so we default to unreleased=false on failure.
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001392 const bool unreleased = (GetProperty("ro.build.version.codename", "REL") != "REL");
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001393
1394 // goog/main device_api_level is bumped *way* before aosp/main api level
1395 // (the latter only gets bumped during the push of goog/main to aosp/main)
1396 //
1397 // Since we develop in AOSP, we want it to behave as if it was bumped too.
1398 //
1399 // Note that AOSP doesn't really have a good api level (for example during
1400 // early V dev cycle, it would have *all* of T, some but not all of U, and some V).
1401 // One could argue that for our purposes AOSP api level should be infinite or 10000.
1402 //
1403 // This could also cause api to be increased in goog/main or other branches,
1404 // but I can't imagine a case where this would be a problem: the problem
1405 // is rather a too low api level, rather than some ill defined high value.
1406 // For example as I write this aosp is 34/U, and goog is 35/V,
1407 // we want to treat both goog & aosp as 35/V, but it's harmless if we
1408 // treat goog as 36 because that value isn't yet defined to mean anything,
1409 // and we thus never compare against it.
1410 //
1411 // Also note that 'android_get_device_api_level()' is what the
1412 // //system/core/init/apex_init_util.cpp
1413 // apex init .XXrc parsing code uses for XX filtering.
1414 //
1415 // That code has a hack to bump <35 to 35 (to force aosp/main to parse .35rc),
1416 // but could (should?) perhaps be adjusted to match this.
1417 const int effective_api_level = android_get_device_api_level() + (int)unreleased;
1418 const bool isAtLeastT = (effective_api_level >= __ANDROID_API_T__);
1419 const bool isAtLeastU = (effective_api_level >= __ANDROID_API_U__);
1420 const bool isAtLeastV = (effective_api_level >= __ANDROID_API_V__);
Maciej Żenczykowskide7374d2024-09-03 15:56:44 -07001421 const bool isAtLeastW = (effective_api_level > __ANDROID_API_V__); // TODO: switch to W
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001422
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001423 const int first_api_level = GetIntProperty("ro.board.first_api_level", effective_api_level);
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001424
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001425 // last in U QPR2 beta1
1426 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1427 // first in U QPR2 beta~2
1428 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1429
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001430 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001431 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
1432 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1433 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1434 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1435 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowskide7374d2024-09-03 15:56:44 -07001436 if (isAtLeastW) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_W_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001437
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001438 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) uid:%d rc:%d%d",
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001439 bpfloader_ver, argv[0], android_get_device_api_level(), effective_api_level,
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001440 kernelVersion(), describeArch(), getuid(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001441 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001442
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001443 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1444 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1445 return 1;
1446 }
1447
1448 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1449 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1450 return 1;
1451 }
1452
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001453 logTetheringApexVersion();
1454
Maciej Żenczykowski11141da2024-03-15 18:21:33 -07001455 if (!isAtLeastT) {
1456 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001457 return 1;
1458 }
1459
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001460 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001461 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001462 ALOGE("Android T requires kernel 4.9.");
1463 return 1;
1464 }
1465
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001466 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001467 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001468 ALOGE("Android U requires kernel 4.14.");
1469 return 1;
1470 }
1471
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001472 // V bumps the kernel requirement up to 4.19
1473 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001474 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001475 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001476 return 1;
1477 }
1478
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001479 // Technically already required by U, but only enforce on V+
1480 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1481 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1482 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1483 if (!isTV()) return 1;
1484 }
1485
Maciej Żenczykowski9b6a9942024-09-03 16:08:35 -07001486 // 6.6 is highest version supported by Android V, so this is effectively W+ (sdk=36+)
1487 if (isKernel32Bit() && isAtLeastKernelVersion(6, 7, 0)) {
1488 ALOGE("Android platform with 32 bit kernel version >= 6.7.0 is unsupported");
1489 return 1;
1490 }
1491
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001492 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1493 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001494 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001495 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001496 }
1497
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001498 if (isAtLeastV) {
1499 bool bad = false;
1500
1501 if (!isLtsKernel()) {
1502 ALOGW("Android V only supports LTS kernels.");
1503 bad = true;
1504 }
1505
1506#define REQUIRE(maj, min, sub) \
1507 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
1508 ALOGW("Android V requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
1509 bad = true; \
1510 }
1511
1512 REQUIRE(4, 19, 236)
1513 REQUIRE(5, 4, 186)
1514 REQUIRE(5, 10, 199)
1515 REQUIRE(5, 15, 136)
1516 REQUIRE(6, 1, 57)
1517 REQUIRE(6, 6, 0)
1518
1519#undef REQUIRE
1520
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001521 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001522 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1523 }
1524 }
1525
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001526 /* Android 14/U should only launch on 64-bit kernels
1527 * T launches on 5.10/5.15
1528 * U launches on 5.15/6.1
1529 * So >=5.16 implies isKernel64Bit()
1530 *
1531 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1532 *
1533 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1534 * we also require 64-bit userspace.
1535 *
1536 * There are various known issues with 32-bit userspace talking to various
1537 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1538 * Some of these have userspace or kernel workarounds/hacks.
1539 * Some of them don't...
1540 * We're going to be removing the hacks.
1541 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1542 * Note: this check/enforcement only applies to *system* userspace code,
1543 * it does not affect unprivileged apps, the 32-on-64 compatibility
1544 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1545 *
1546 * Additionally the 32-bit kernel jit support is poor,
1547 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
1548 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001549 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001550 // Stuff won't work reliably, but...
1551 if (isTV()) {
1552 // exempt TVs... they don't really need functional advanced networking
1553 ALOGW("[TV] 32-bit userspace unsupported on 6.2+ kernels.");
1554 } else if (isWear() && isArm()) {
1555 // exempt Arm Wear devices (arm32 ABI is far less problematic than x86-32)
1556 ALOGW("[Arm Wear] 32-bit userspace unsupported on 6.2+ kernels.");
1557 } else if (first_api_level <= __ANDROID_API_T__ && isArm()) {
1558 // also exempt Arm devices upgrading with major kernel rev from T-
1559 // might possibly be better for them to run with a newer kernel...
1560 ALOGW("[Arm KernelUpRev] 32-bit userspace unsupported on 6.2+ kernels.");
1561 } else if (isArm()) {
1562 ALOGE("[Arm] 64-bit userspace required on 6.2+ kernels (%d).", first_api_level);
1563 return 1;
1564 } else { // x86 since RiscV cannot be 32-bit
1565 ALOGE("[x86] 64-bit userspace required on 6.2+ kernels.");
1566 return 1;
1567 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001568 }
1569
Maciej Żenczykowski21b4a052024-09-03 15:46:48 -07001570 // Note: 6.6 is highest version supported by Android V (sdk=35), so this is for sdk=36+
1571 if (isUserspace32bit() && isAtLeastKernelVersion(6, 7, 0)) {
1572 ALOGE("64-bit userspace required on 6.7+ kernels.");
1573 return 1;
1574 }
1575
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001576 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001577 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001578 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001579 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001580 return 1;
1581 }
1582
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001583 if (runningAsRoot) {
1584 // Note: writing this proc file requires being root (always the case on V+)
1585
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001586 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1587 // but we need 0 (enabled)
1588 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1589 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1590 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001591 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001592 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001593
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001594 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001595 // Note: writing these proc files requires CAP_NET_ADMIN
1596 // and sepolicy which is only present on U+,
1597 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1598 // trigger (ie. by init itself) instead.
1599
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001600 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1601 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1602 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1603 // kernel does not have CONFIG_BPF_JIT=y)
1604 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1605 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1606 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001607
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001608 // Enable JIT kallsyms export for privileged users only
1609 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1610 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1611 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1612 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001613
1614 // Create all the pin subdirectories
1615 // (this must be done first to allow selinux_context and pin_subdir functionality,
1616 // which could otherwise fail with ENOENT during object pinning or renaming,
1617 // due to ordering issues)
1618 for (const auto& location : locations) {
1619 if (createSysFsBpfSubDir(location.prefix)) return 1;
1620 }
1621
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001622 // Note: there's no actual src dir for fs_bpf_loader .o's,
1623 // so it is not listed in 'locations[].prefix'.
1624 // This is because this is primarily meant for triggering genfscon rules,
1625 // and as such this will likely always be the case.
1626 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1627 if (createSysFsBpfSubDir("loader")) return 1;
1628
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001629 // Load all ELF objects, create programs and maps, and pin them
1630 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001631 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001632 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1633 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1634 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1635 "problems or startup script race.");
1636 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1637 sleep(20);
1638 return 2;
1639 }
1640 }
1641
1642 int key = 1;
1643 int value = 123;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001644 unique_fd map(
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001645 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1646 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001647 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1648 return 1;
1649 }
1650
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001651 // leave a flag that we're done
1652 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001653
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001654 // platform bpfloader will only succeed when run as root
1655 if (!runningAsRoot) {
1656 // unreachable on U QPR3+ which always runs netbpfload as root
1657
1658 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1659 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001660 }
1661
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001662 // unreachable before U QPR3
1663 ALOGI("done, transferring control to platform bpfloader.");
1664
1665 // platform BpfLoader *needs* to run as root
1666 const char * args[] = { platformBpfLoader, NULL, };
1667 execve(args[0], (char**)args, envp);
1668 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1669 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001670}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001671
1672} // namespace bpf
1673} // namespace android
1674
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001675int main(int argc, char** argv, char * const envp[]) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001676 InitLogging(argv, &KernelLogger);
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001677
1678 if (argc == 2 && !strcmp(argv[1], "done")) {
1679 // we're being re-exec'ed from platform bpfloader to 'finalize' things
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001680 if (!SetProperty("bpf.progs_loaded", "1")) {
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001681 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1682 return 125;
1683 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001684 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001685 return 0;
1686 }
1687
1688 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001689}