blob: 4767dfafbade97931c1a42b4bb680ebb9ddca977 [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
144// Size of the BPF log buffer for verifier logging
145#define BPF_LOAD_LOG_SZ 0xfffff
146
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700147static unsigned int page_size = static_cast<unsigned int>(getpagesize());
148
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700149constexpr const char* lookupSelinuxContext(const domain d) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700150 switch (d) {
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700151 case domain::unspecified: return "";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700152 case domain::tethering: return "fs_bpf_tethering";
153 case domain::net_private: return "fs_bpf_net_private";
154 case domain::net_shared: return "fs_bpf_net_shared";
155 case domain::netd_readonly: return "fs_bpf_netd_readonly";
156 case domain::netd_shared: return "fs_bpf_netd_shared";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700157 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700158 }
159}
160
161domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
162 for (domain d : AllDomains) {
163 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
164 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
165 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
166 }
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700167 ALOGE("unrecognized selinux_context '%-32s'", s);
168 // Note: we *can* just abort() here as we only load bpf .o files shipped
169 // in the same mainline module / apex as NetBpfLoad itself.
170 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700171}
172
173constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
174 switch (d) {
175 case domain::unspecified: return unspecified;
176 case domain::tethering: return "tethering/";
177 case domain::net_private: return "net_private/";
178 case domain::net_shared: return "net_shared/";
179 case domain::netd_readonly: return "netd_readonly/";
180 case domain::netd_shared: return "netd_shared/";
Maciej Żenczykowski1ec8d7d2024-09-04 16:44:04 -0700181 case domain::loader: return "loader/";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700182 }
183};
184
185domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
186 for (domain d : AllDomains) {
187 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
188 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
189 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
190 }
191 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700192 // Note: we *can* just abort() here as we only load bpf .o files shipped
193 // in the same mainline module / apex as NetBpfLoad itself.
194 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700195}
196
197static string pathToObjName(const string& path) {
198 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700199 string filename = Split(path, "/").back();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700200 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
201 string name = filename.substr(0, filename.find_last_of('.'));
202 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
203 // this can be used to provide duplicate programs (mux based on the bpfloader version)
204 return name.substr(0, name.find_last_of('@'));
205}
206
207typedef struct {
208 const char* name;
209 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000210 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700211} sectionType;
212
213/*
214 * Map section name prefixes to program types, the section name will be:
215 * SECTION(<prefix>/<name-of-program>)
216 * For example:
217 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
218 * is the name of the program, and tracepoint is the type.
219 *
220 * However, be aware that you should not be directly using the SECTION() macro.
221 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
222 *
223 * Programs shipped inside the tethering apex should be limited to networking stuff,
224 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
225 * since they are less stable abi/api and may conflict with platform uses of bpf.
226 */
227sectionType sectionNameTypes[] = {
228 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
229 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000230 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
231 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700232 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
233 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
234 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
235 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
236 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
237 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
238 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700239 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
240 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
241 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
242 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000243 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
244 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700245 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
246 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
247 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000248 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700249 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
250 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000251 {"xdp/", BPF_PROG_TYPE_XDP},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700252};
253
254typedef struct {
255 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000256 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700257 string name;
258 vector<char> data;
259 vector<char> rel_data;
260 optional<struct bpf_prog_def> prog_def;
261
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000262 unique_fd prog_fd; // fd after loading
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700263} codeSection;
264
265static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
266 elfFile.seekg(0);
267 if (elfFile.fail()) return -1;
268
269 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
270
271 return 0;
272}
273
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000274// Reads all section header tables into an Shdr array
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700275static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
276 Elf64_Ehdr eh;
277 int ret = 0;
278
279 ret = readElfHeader(elfFile, &eh);
280 if (ret) return ret;
281
282 elfFile.seekg(eh.e_shoff);
283 if (elfFile.fail()) return -1;
284
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000285 // Read shdr table entries
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700286 shTable.resize(eh.e_shnum);
287
288 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
289
290 return 0;
291}
292
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000293// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700294static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
295 vector<Elf64_Shdr> shTable;
296 int ret = readSectionHeadersAll(elfFile, shTable);
297 if (ret) return ret;
298
299 elfFile.seekg(shTable[id].sh_offset);
300 if (elfFile.fail()) return -1;
301
302 sec.resize(shTable[id].sh_size);
303 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
304
305 return 0;
306}
307
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000308// Read whole section header string table
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700309static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
310 Elf64_Ehdr eh;
311 int ret = readElfHeader(elfFile, &eh);
312 if (ret) return ret;
313
314 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
315 if (ret) return ret;
316
317 return 0;
318}
319
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000320// Get name from offset in strtab
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700321static int getSymName(ifstream& elfFile, int nameOff, string& name) {
322 int ret;
323 vector<char> secStrTab;
324
325 ret = readSectionHeaderStrtab(elfFile, secStrTab);
326 if (ret) return ret;
327
328 if (nameOff >= (int)secStrTab.size()) return -1;
329
330 name = string((char*)secStrTab.data() + nameOff);
331 return 0;
332}
333
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000334// Reads a full section by name - example to get the GPL license
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700335static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
336 vector<char> secStrTab;
337 vector<Elf64_Shdr> shTable;
338 int ret;
339
340 ret = readSectionHeadersAll(elfFile, shTable);
341 if (ret) return ret;
342
343 ret = readSectionHeaderStrtab(elfFile, secStrTab);
344 if (ret) return ret;
345
346 for (int i = 0; i < (int)shTable.size(); i++) {
347 char* secname = secStrTab.data() + shTable[i].sh_name;
348 if (!secname) continue;
349
350 if (!strcmp(secname, name)) {
351 vector<char> dataTmp;
352 dataTmp.resize(shTable[i].sh_size);
353
354 elfFile.seekg(shTable[i].sh_offset);
355 if (elfFile.fail()) return -1;
356
357 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
358
359 data = dataTmp;
360 return 0;
361 }
362 }
363 return -2;
364}
365
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700366unsigned int readSectionUint(const char* name, ifstream& elfFile) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700367 vector<char> theBytes;
368 int ret = readSectionByName(name, elfFile, theBytes);
369 if (ret) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700370 ALOGE("Couldn't find section %s.", name);
371 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700372 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700373 ALOGE("Section %s is too short.", name);
374 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700375 } else {
376 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
377 unsigned int value = static_cast<unsigned char>(theBytes[3]);
378 value <<= 8;
379 value += static_cast<unsigned char>(theBytes[2]);
380 value <<= 8;
381 value += static_cast<unsigned char>(theBytes[1]);
382 value <<= 8;
383 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000384 ALOGD("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700385 return value;
386 }
387}
388
389static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
390 int ret;
391 vector<Elf64_Shdr> shTable;
392
393 ret = readSectionHeadersAll(elfFile, shTable);
394 if (ret) return ret;
395
396 for (int i = 0; i < (int)shTable.size(); i++) {
397 if ((int)shTable[i].sh_type != type) continue;
398
399 vector<char> dataTmp;
400 dataTmp.resize(shTable[i].sh_size);
401
402 elfFile.seekg(shTable[i].sh_offset);
403 if (elfFile.fail()) return -1;
404
405 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
406
407 data = dataTmp;
408 return 0;
409 }
410 return -2;
411}
412
413static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
414 return (a.st_value < b.st_value);
415}
416
417static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
418 int ret, numElems;
419 Elf64_Sym* buf;
420 vector<char> secData;
421
422 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
423 if (ret) return ret;
424
425 buf = (Elf64_Sym*)secData.data();
426 numElems = (secData.size() / sizeof(Elf64_Sym));
427 data.assign(buf, buf + numElems);
428
429 if (sort) std::sort(data.begin(), data.end(), symCompare);
430 return 0;
431}
432
433static enum bpf_prog_type getSectionType(string& name) {
434 for (auto& snt : sectionNameTypes)
435 if (StartsWith(name, snt.name)) return snt.type;
436
437 return BPF_PROG_TYPE_UNSPEC;
438}
439
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700440static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700441 vector<char> pdData;
442 int ret = readSectionByName("progs", elfFile, pdData);
443 if (ret) return ret;
444
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700445 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700446 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700447 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700448 return -1;
449 };
450
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700451 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700452
453 const char* dataPtr = pdData.data();
454 for (auto& p : pd) {
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700455 // Copy the structure from the ELF file and move to the next one.
456 memcpy(&p, dataPtr, sizeof(struct bpf_prog_def));
457 dataPtr += sizeof(struct bpf_prog_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700458 }
459 return 0;
460}
461
462static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
463 optional<unsigned> symbolType = std::nullopt) {
464 int ret;
465 string name;
466 vector<Elf64_Sym> symtab;
467 vector<Elf64_Shdr> shTable;
468
469 ret = readSymTab(elfFile, 1 /* sort */, symtab);
470 if (ret) return ret;
471
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000472 // Get index of section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700473 ret = readSectionHeadersAll(elfFile, shTable);
474 if (ret) return ret;
475
476 int sec_idx = -1;
477 for (int i = 0; i < (int)shTable.size(); i++) {
478 ret = getSymName(elfFile, shTable[i].sh_name, name);
479 if (ret) return ret;
480
481 if (!name.compare(sectionName)) {
482 sec_idx = i;
483 break;
484 }
485 }
486
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000487 // No section found with matching name
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700488 if (sec_idx == -1) {
489 ALOGW("No %s section could be found in elf object", sectionName.c_str());
490 return -1;
491 }
492
493 for (int i = 0; i < (int)symtab.size(); i++) {
494 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
495
496 if (symtab[i].st_shndx == sec_idx) {
497 string s;
498 ret = getSymName(elfFile, symtab[i].st_name, s);
499 if (ret) return ret;
500 names.push_back(s);
501 }
502 }
503
504 return 0;
505}
506
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000507// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700508static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700509 vector<Elf64_Shdr> shTable;
510 int entries, ret = 0;
511
512 ret = readSectionHeadersAll(elfFile, shTable);
513 if (ret) return ret;
514 entries = shTable.size();
515
516 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700517 ret = readProgDefs(elfFile, pd);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700518 if (ret) return ret;
519 vector<string> progDefNames;
520 ret = getSectionSymNames(elfFile, "progs", progDefNames);
521 if (!pd.empty() && ret) return ret;
522
523 for (int i = 0; i < entries; i++) {
524 string name;
525 codeSection cs_temp;
526 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
527
528 ret = getSymName(elfFile, shTable[i].sh_name, name);
529 if (ret) return ret;
530
531 enum bpf_prog_type ptype = getSectionType(name);
532
533 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
534
535 // This must be done before '/' is replaced with '_'.
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000536 for (auto& snt : sectionNameTypes)
537 if (StartsWith(name, snt.name)) cs_temp.attach_type = snt.attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700538
539 string oldName = name;
540
541 // convert all slashes to underscores
542 std::replace(name.begin(), name.end(), '/', '_');
543
544 cs_temp.type = ptype;
545 cs_temp.name = name;
546
547 ret = readSectionByIdx(elfFile, i, cs_temp.data);
548 if (ret) return ret;
549 ALOGV("Loaded code section %d (%s)", i, name.c_str());
550
551 vector<string> csSymNames;
552 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
553 if (ret || !csSymNames.size()) return ret;
554 for (size_t i = 0; i < progDefNames.size(); ++i) {
555 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
556 cs_temp.prog_def = pd[i];
557 break;
558 }
559 }
560
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000561 // Check for rel section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700562 if (cs_temp.data.size() > 0 && i < entries) {
563 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
564 if (ret) return ret;
565
566 if (name == (".rel" + oldName)) {
567 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
568 if (ret) return ret;
569 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
570 }
571 }
572
573 if (cs_temp.data.size() > 0) {
574 cs.push_back(std::move(cs_temp));
575 ALOGV("Adding section %d to cs list", i);
576 }
577 }
578 return 0;
579}
580
581static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
582 vector<Elf64_Sym> symtab;
583 int ret = 0;
584
585 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
586 if (ret) return ret;
587
588 if (index >= (int)symtab.size()) return -1;
589
590 return getSymName(elfFile, symtab[index].st_name, name);
591}
592
593static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
594 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
595 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
596 // so on 4.9-T kernels just pretend the map matches our expectations.
597 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
598 // This is because the primary failure mode we're trying to detect here
599 // is either a source code misconfiguration (which is likely kernel independent)
600 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
601 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
602
603 // Assuming fd is a valid Bpf Map file descriptor then
604 // all the following should always succeed on a 4.14+ kernel.
605 // If they somehow do fail, they'll return -1 (and set errno),
606 // which should then cause (among others) a key_size mismatch.
607 int fd_type = bpfGetFdMapType(fd);
608 int fd_key_size = bpfGetFdKeySize(fd);
609 int fd_value_size = bpfGetFdValueSize(fd);
610 int fd_max_entries = bpfGetFdMaxEntries(fd);
611 int fd_map_flags = bpfGetFdMapFlags(fd);
612
613 // DEVMAPs are readonly from the bpf program side's point of view, as such
614 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
615 int desired_map_flags = (int)mapDef.map_flags;
616 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
617 desired_map_flags |= BPF_F_RDONLY_PROG;
618
Maciej Żenczykowskidcb2e742024-08-29 10:40:35 -0700619 if (type == BPF_MAP_TYPE_LPM_TRIE)
620 desired_map_flags |= BPF_F_NO_PREALLOC;
621
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700622 // 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;
735 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
736 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
737 // of be approximated: ARRAY has the same userspace api, though it is not usable
738 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
739 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
740 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
741 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
742 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
743 type = BPF_MAP_TYPE_ARRAY;
744 }
745 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
746 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
747 // of be approximated: HASH has the same userspace visible api.
748 // However it cannot be used by ebpf programs in the same way.
749 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
750 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
751 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
752 // programs as being 5.4+...
753 type = BPF_MAP_TYPE_HASH;
754 }
755
756 // The .h file enforces that this is a power of two, and page size will
757 // also always be a power of two, so this logic is actually enough to
758 // force it to be a multiple of the page size, as required by the kernel.
759 unsigned int max_entries = md[i].max_entries;
760 if (type == BPF_MAP_TYPE_RINGBUF) {
761 if (max_entries < page_size) max_entries = page_size;
762 }
763
764 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
765 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000766 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700767 md[i].selinux_context, static_cast<int>(selinux_context),
768 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
769 }
770
771 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700772 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000773 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700774 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
775 }
776
777 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
778 // except that maps shared across .o's have empty <objName>
779 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
780 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
781 (md[i].shared ? "" : objName) + "_" + mapNames[i];
782 bool reuse = false;
783 unique_fd fd;
784 int saved_errno;
785
786 if (access(mapPinLoc.c_str(), F_OK) == 0) {
787 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
788 saved_errno = errno;
789 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
790 reuse = true;
791 } else {
792 union bpf_attr req = {
793 .map_type = type,
794 .key_size = md[i].key_size,
795 .value_size = md[i].value_size,
796 .max_entries = max_entries,
Maciej Żenczykowskidcb2e742024-08-29 10:40:35 -0700797 .map_flags = md[i].map_flags | (type == BPF_MAP_TYPE_LPM_TRIE ? BPF_F_NO_PREALLOC : 0),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700798 };
799 if (isAtLeastKernelVersion(4, 15, 0))
800 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
801 fd.reset(bpf(BPF_MAP_CREATE, req));
802 saved_errno = errno;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -0700803 if (fd.ok()) {
804 ALOGD("bpf_create_map[%s] -> %d", mapNames[i].c_str(), fd.get());
805 } else {
806 ALOGE("bpf_create_map[%s] -> %d errno:%d", mapNames[i].c_str(), fd.get(), saved_errno);
807 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700808 }
809
810 if (!fd.ok()) return -saved_errno;
811
812 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
813 // safety (since reuse code path is rare) run these checks even if we just created it.
814 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
815 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
816
817 if (!reuse) {
818 if (specified(selinux_context)) {
819 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
820 "tmp_map_" + objName + "_" + mapNames[i];
821 ret = bpfFdPin(fd, createLoc.c_str());
822 if (ret) {
823 int err = errno;
824 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
825 return -err;
826 }
827 ret = renameat2(AT_FDCWD, createLoc.c_str(),
828 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
829 if (ret) {
830 int err = errno;
831 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
832 err, strerror(err));
833 return -err;
834 }
835 } else {
836 ret = bpfFdPin(fd, mapPinLoc.c_str());
837 if (ret) {
838 int err = errno;
839 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
840 return -err;
841 }
842 }
843 ret = chmod(mapPinLoc.c_str(), md[i].mode);
844 if (ret) {
845 int err = errno;
846 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
847 strerror(err));
848 return -err;
849 }
850 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
851 if (ret) {
852 int err = errno;
853 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
854 ret, err, strerror(err));
855 return -err;
856 }
857 }
858
859 int mapId = bpfGetFdMapId(fd);
860 if (mapId == -1) {
Maciej Żenczykowski508c8f72024-08-28 15:07:33 -0700861 if (isAtLeastKernelVersion(4, 14, 0))
862 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700863 } else {
864 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
865 }
866
867 mapFds.push_back(std::move(fd));
868 }
869
870 return ret;
871}
872
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700873static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
874 int insnIndex;
875 struct bpf_insn *insn, *insns;
876
877 insns = (struct bpf_insn*)(insnsPtr);
878
879 insnIndex = offset / sizeof(struct bpf_insn);
880 insn = &insns[insnIndex];
881
882 // Occasionally might be useful for relocation debugging, but pretty spammy
883 if (0) {
884 ALOGV("applying relo to instruction at byte offset: %llu, "
885 "insn offset %d, insn %llx",
886 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
887 }
888
889 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700890 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700891 return;
892 }
893
894 insn->imm = fd;
895 insn->src_reg = BPF_PSEUDO_MAP_FD;
896}
897
898static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
899 vector<string> mapNames;
900
901 int ret = getSectionSymNames(elfFile, "maps", mapNames);
902 if (ret) return;
903
904 for (int k = 0; k != (int)cs.size(); k++) {
905 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
906 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
907
908 for (int i = 0; i < n_rel; i++) {
909 int symIndex = ELF64_R_SYM(rel[i].r_info);
910 string symName;
911
912 ret = getSymNameByIdx(elfFile, symIndex, symName);
913 if (ret) return;
914
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000915 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700916 for (int j = 0; j < (int)mapNames.size(); j++) {
917 if (!mapNames[j].compare(symName)) {
918 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
919 break;
920 }
921 }
922 }
923 }
924}
925
926static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
927 const char* prefix, const unsigned int bpfloader_ver) {
928 unsigned kvers = kernelVersion();
929
930 if (!kvers) {
931 ALOGE("unable to get kernel version");
932 return -EINVAL;
933 }
934
935 string objName = pathToObjName(string(elfPath));
936
937 for (int i = 0; i < (int)cs.size(); i++) {
938 unique_fd& fd = cs[i].prog_fd;
939 int ret;
940 string name = cs[i].name;
941
942 if (!cs[i].prog_def.has_value()) {
943 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
944 return -EINVAL;
945 }
946
947 unsigned min_kver = cs[i].prog_def->min_kver;
948 unsigned max_kver = cs[i].prog_def->max_kver;
949 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
950 max_kver, kvers);
951 if (kvers < min_kver) continue;
952 if (kvers >= max_kver) continue;
953
954 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
955 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
956 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
957 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700958
959 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
960 bpfMinVer, bpfMaxVer);
961 if (bpfloader_ver < bpfMinVer) continue;
962 if (bpfloader_ver >= bpfMaxVer) continue;
963
964 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
965 (cs[i].prog_def->ignore_on_user && isUser()) ||
966 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
967 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
968 getBuildType().c_str());
969 continue;
970 }
971
972 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
973 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
974 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
975 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
976 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
977 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
978 continue;
979 }
980
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700981 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000982 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700983 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
984 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
985 }
986
987 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000988 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700989 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
990 lookupPinSubdir(pin_subdir));
991 }
992
993 // strip any potential $foo suffix
994 // this can be used to provide duplicate programs
995 // conditionally loaded based on running kernel version
996 name = name.substr(0, name.find_last_of('$'));
997
998 bool reuse = false;
999 // Format of pin location is
1000 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1001 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1002 objName + '_' + string(name);
1003 if (access(progPinLoc.c_str(), F_OK) == 0) {
1004 fd.reset(retrieveProgram(progPinLoc.c_str()));
1005 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
1006 (!fd.ok() ? std::strerror(errno) : "no error"));
1007 reuse = true;
1008 } else {
1009 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1010
1011 union bpf_attr req = {
1012 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001013 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001014 .insns = ptr_to_u64(cs[i].data.data()),
1015 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001016 .log_level = 1,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001017 .log_size = static_cast<__u32>(log_buf.size()),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001018 .log_buf = ptr_to_u64(log_buf.data()),
1019 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001020 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001021 };
1022 if (isAtLeastKernelVersion(4, 15, 0))
1023 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1024 fd.reset(bpf(BPF_PROG_LOAD, req));
1025
1026 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
1027 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
1028
1029 if (!fd.ok()) {
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001030 if (log_buf.size()) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001031 vector<string> lines = Split(log_buf.data(), "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001032
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001033 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1034 for (const auto& line : lines) ALOGW("%s", line.c_str());
1035 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1036 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001037
1038 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001039 ALOGW("failed program %s is marked optional - continuing...",
1040 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001041 continue;
1042 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001043 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001044 }
1045 }
1046
1047 if (!fd.ok()) return fd.get();
1048
1049 if (!reuse) {
1050 if (specified(selinux_context)) {
1051 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1052 "tmp_prog_" + objName + '_' + string(name);
1053 ret = bpfFdPin(fd, createLoc.c_str());
1054 if (ret) {
1055 int err = errno;
1056 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1057 return -err;
1058 }
1059 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1060 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1061 if (ret) {
1062 int err = errno;
1063 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1064 err, strerror(err));
1065 return -err;
1066 }
1067 } else {
1068 ret = bpfFdPin(fd, progPinLoc.c_str());
1069 if (ret) {
1070 int err = errno;
1071 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1072 return -err;
1073 }
1074 }
1075 if (chmod(progPinLoc.c_str(), 0440)) {
1076 int err = errno;
1077 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1078 return -err;
1079 }
1080 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1081 (gid_t)cs[i].prog_def->gid)) {
1082 int err = errno;
1083 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1084 cs[i].prog_def->gid, err, strerror(err));
1085 return -err;
1086 }
1087 }
1088
1089 int progId = bpfGetFdProgId(fd);
1090 if (progId == -1) {
1091 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
1092 } else {
1093 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
1094 }
1095 }
1096
1097 return 0;
1098}
1099
1100int loadProg(const char* const elfPath, bool* const isCritical, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001101 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001102 vector<char> license;
1103 vector<char> critical;
1104 vector<codeSection> cs;
1105 vector<unique_fd> mapFds;
1106 int ret;
1107
1108 if (!isCritical) return -1;
1109 *isCritical = false;
1110
1111 ifstream elfFile(elfPath, ios::in | ios::binary);
1112 if (!elfFile.is_open()) return -1;
1113
1114 ret = readSectionByName("critical", elfFile, critical);
1115 *isCritical = !ret;
1116
1117 ret = readSectionByName("license", elfFile, license);
1118 if (ret) {
1119 ALOGE("Couldn't find license in %s", elfPath);
1120 return ret;
1121 } else {
1122 ALOGD("Loading %s%s ELF object %s with license %s",
1123 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
1124 elfPath, (char*)license.data());
1125 }
1126
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001127 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1128 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001129
1130 // inclusive lower bound check
1131 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001132 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001133 bpfloader_ver, elfPath, bpfLoaderMinVer);
1134 return 0;
1135 }
1136
1137 // exclusive upper bound check
1138 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001139 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001140 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1141 return 0;
1142 }
1143
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001144 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001145 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1146
Maciej Żenczykowskie666d852024-08-15 15:03:38 -07001147 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001148 if (ret) {
1149 ALOGE("Couldn't read all code sections in %s", elfPath);
1150 return ret;
1151 }
1152
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001153 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001154 if (ret) {
1155 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1156 return ret;
1157 }
1158
1159 for (int i = 0; i < (int)mapFds.size(); i++)
1160 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1161
1162 applyMapRelo(elfFile, mapFds, cs);
1163
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001164 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001165 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1166
1167 return ret;
1168}
1169
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001170static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001171 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001172 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001173 if (errno == ENOENT) return false;
1174 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1175 abort(); // can only hit this if permissions (likely selinux) are screwed up
1176}
1177
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001178#define APEXROOT "/apex/com.android.tethering"
1179#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001180
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001181const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001182 // S+ Tethering mainline module (network_stack): tether offload
1183 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001184 .dir = BPFROOT "/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001185 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001186 },
1187 // T+ Tethering mainline module (shared with netd & system server)
1188 // netutils_wrapper (for iptables xt_bpf) has access to programs
1189 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001190 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001191 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001192 },
1193 // T+ Tethering mainline module (shared with netd & system server)
1194 // netutils_wrapper has no access, netd has read only access
1195 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001196 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001197 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001198 },
1199 // T+ Tethering mainline module (shared with system server)
1200 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001201 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001202 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001203 },
1204 // T+ Tethering mainline module (not shared, just network_stack)
1205 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001206 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001207 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001208 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001209};
1210
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001211static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001212 int retVal = 0;
1213 DIR* dir;
1214 struct dirent* ent;
1215
1216 if ((dir = opendir(location.dir)) != NULL) {
1217 while ((ent = readdir(dir)) != NULL) {
1218 string s = ent->d_name;
1219 if (!EndsWith(s, ".o")) continue;
1220
1221 string progPath(location.dir);
1222 progPath += s;
1223
1224 bool critical;
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001225 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001226 if (ret) {
1227 if (critical) retVal = ret;
1228 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1229 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001230 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001231 }
1232 }
1233 closedir(dir);
1234 }
1235 return retVal;
1236}
1237
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001238static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001239 if (*prefix) {
1240 mode_t prevUmask = umask(0);
1241
1242 string s = "/sys/fs/bpf/";
1243 s += prefix;
1244
1245 errno = 0;
1246 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1247 if (ret && errno != EEXIST) {
1248 const int err = errno;
1249 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1250 return -err;
1251 }
1252
1253 umask(prevUmask);
1254 }
1255 return 0;
1256}
1257
1258// Technically 'value' doesn't need to be newline terminated, but it's best
1259// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1260// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001261static int writeProcSysFile(const char *filename, const char *value) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001262 unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001263 if (fd < 0) {
1264 const int err = errno;
1265 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1266 return -err;
1267 }
1268 int len = strlen(value);
1269 int v = write(fd, value, len);
1270 if (v < 0) {
1271 const int err = errno;
1272 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1273 return -err;
1274 }
1275 if (v != len) {
1276 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1277 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1278 return -EINVAL;
1279 }
1280 return 0;
1281}
1282
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001283#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001284const char * const platformBpfLoader = "/system/bin/bpfloader";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001285
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001286static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001287 char * found_blockdev = NULL;
1288 FILE * f = NULL;
1289 char buf[4096];
1290
1291 f = fopen("/proc/mounts", "re");
1292 if (!f) return 1;
1293
1294 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1295 while (fgets(buf, sizeof(buf), f)) {
1296 char * blockdev = buf;
1297 char * space = strchr(blockdev, ' ');
1298 if (!space) continue;
1299 *space = '\0';
1300 char * mntpath = space + 1;
1301 space = strchr(mntpath, ' ');
1302 if (!space) continue;
1303 *space = '\0';
1304 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1305 found_blockdev = strdup(blockdev);
1306 break;
1307 }
1308 fclose(f);
1309 f = NULL;
1310
1311 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001312 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001313
1314 f = fopen("/proc/mounts", "re");
1315 if (!f) { free(found_blockdev); return 3; }
1316
1317 while (fgets(buf, sizeof(buf), f)) {
1318 char * blockdev = buf;
1319 char * space = strchr(blockdev, ' ');
1320 if (!space) continue;
1321 *space = '\0';
1322 char * mntpath = space + 1;
1323 space = strchr(mntpath, ' ');
1324 if (!space) continue;
1325 *space = '\0';
1326 if (strcmp(blockdev, found_blockdev)) continue;
1327 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1328 char * at = strchr(mntpath, '@');
1329 if (!at) continue;
1330 char * ver = at + 1;
1331 ALOGI("Tethering APEX version %s", ver);
1332 }
1333 fclose(f);
1334 free(found_blockdev);
1335 return 0;
1336}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001337
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001338static bool hasGSM() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001339 static string ph = GetProperty("gsm.current.phone-type", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001340 static bool gsm = (ph != "");
1341 static bool logged = false;
1342 if (!logged) {
1343 logged = true;
1344 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1345 }
1346 return gsm;
1347}
1348
1349static bool isTV() {
1350 if (hasGSM()) return false; // TVs don't do GSM
1351
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001352 static string key = GetProperty("ro.oem.key1", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001353 static bool tv = StartsWith(key, "ATV00");
1354 static bool logged = false;
1355 if (!logged) {
1356 logged = true;
1357 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1358 }
1359 return tv;
1360}
1361
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001362static bool isWear() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001363 static string wearSdkStr = GetProperty("ro.cw_build.wear_sdk.version", "");
1364 static int wearSdkInt = GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1365 static string buildChars = GetProperty("ro.build.characteristics", "");
1366 static vector<string> v = Tokenize(buildChars, ",");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001367 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1368 static bool wear = (wearSdkInt > 0) || watch;
1369 static bool logged = false;
1370 if (!logged) {
1371 logged = true;
1372 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1373 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1374 }
1375 return wear;
1376}
1377
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001378static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001379 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001380
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001381 // Any released device will have codename REL instead of a 'real' codename.
1382 // For safety: default to 'REL' so we default to unreleased=false on failure.
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001383 const bool unreleased = (GetProperty("ro.build.version.codename", "REL") != "REL");
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001384
1385 // goog/main device_api_level is bumped *way* before aosp/main api level
1386 // (the latter only gets bumped during the push of goog/main to aosp/main)
1387 //
1388 // Since we develop in AOSP, we want it to behave as if it was bumped too.
1389 //
1390 // Note that AOSP doesn't really have a good api level (for example during
1391 // early V dev cycle, it would have *all* of T, some but not all of U, and some V).
1392 // One could argue that for our purposes AOSP api level should be infinite or 10000.
1393 //
1394 // This could also cause api to be increased in goog/main or other branches,
1395 // but I can't imagine a case where this would be a problem: the problem
1396 // is rather a too low api level, rather than some ill defined high value.
1397 // For example as I write this aosp is 34/U, and goog is 35/V,
1398 // we want to treat both goog & aosp as 35/V, but it's harmless if we
1399 // treat goog as 36 because that value isn't yet defined to mean anything,
1400 // and we thus never compare against it.
1401 //
1402 // Also note that 'android_get_device_api_level()' is what the
1403 // //system/core/init/apex_init_util.cpp
1404 // apex init .XXrc parsing code uses for XX filtering.
1405 //
1406 // That code has a hack to bump <35 to 35 (to force aosp/main to parse .35rc),
1407 // but could (should?) perhaps be adjusted to match this.
1408 const int effective_api_level = android_get_device_api_level() + (int)unreleased;
1409 const bool isAtLeastT = (effective_api_level >= __ANDROID_API_T__);
1410 const bool isAtLeastU = (effective_api_level >= __ANDROID_API_U__);
1411 const bool isAtLeastV = (effective_api_level >= __ANDROID_API_V__);
Maciej Żenczykowskide7374d2024-09-03 15:56:44 -07001412 const bool isAtLeastW = (effective_api_level > __ANDROID_API_V__); // TODO: switch to W
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001413
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001414 const int first_api_level = GetIntProperty("ro.board.first_api_level", effective_api_level);
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001415
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001416 // last in U QPR2 beta1
1417 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1418 // first in U QPR2 beta~2
1419 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1420
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001421 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001422 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
1423 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1424 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1425 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1426 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowskide7374d2024-09-03 15:56:44 -07001427 if (isAtLeastW) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_W_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001428
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001429 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) uid:%d rc:%d%d",
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001430 bpfloader_ver, argv[0], android_get_device_api_level(), effective_api_level,
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001431 kernelVersion(), describeArch(), getuid(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001432 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001433
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001434 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1435 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1436 return 1;
1437 }
1438
1439 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1440 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1441 return 1;
1442 }
1443
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001444 logTetheringApexVersion();
1445
Maciej Żenczykowski11141da2024-03-15 18:21:33 -07001446 if (!isAtLeastT) {
1447 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001448 return 1;
1449 }
1450
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001451 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001452 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001453 ALOGE("Android T requires kernel 4.9.");
1454 return 1;
1455 }
1456
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001457 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001458 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001459 ALOGE("Android U requires kernel 4.14.");
1460 return 1;
1461 }
1462
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001463 // V bumps the kernel requirement up to 4.19
1464 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001465 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001466 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001467 return 1;
1468 }
1469
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001470 // Technically already required by U, but only enforce on V+
1471 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1472 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1473 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1474 if (!isTV()) return 1;
1475 }
1476
Maciej Żenczykowski9b6a9942024-09-03 16:08:35 -07001477 // 6.6 is highest version supported by Android V, so this is effectively W+ (sdk=36+)
1478 if (isKernel32Bit() && isAtLeastKernelVersion(6, 7, 0)) {
1479 ALOGE("Android platform with 32 bit kernel version >= 6.7.0 is unsupported");
1480 return 1;
1481 }
1482
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001483 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1484 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001485 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001486 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001487 }
1488
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001489 if (isAtLeastV) {
1490 bool bad = false;
1491
1492 if (!isLtsKernel()) {
1493 ALOGW("Android V only supports LTS kernels.");
1494 bad = true;
1495 }
1496
1497#define REQUIRE(maj, min, sub) \
1498 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
1499 ALOGW("Android V requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
1500 bad = true; \
1501 }
1502
1503 REQUIRE(4, 19, 236)
1504 REQUIRE(5, 4, 186)
1505 REQUIRE(5, 10, 199)
1506 REQUIRE(5, 15, 136)
1507 REQUIRE(6, 1, 57)
1508 REQUIRE(6, 6, 0)
1509
1510#undef REQUIRE
1511
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001512 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001513 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1514 }
1515 }
1516
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001517 /* Android 14/U should only launch on 64-bit kernels
1518 * T launches on 5.10/5.15
1519 * U launches on 5.15/6.1
1520 * So >=5.16 implies isKernel64Bit()
1521 *
1522 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1523 *
1524 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1525 * we also require 64-bit userspace.
1526 *
1527 * There are various known issues with 32-bit userspace talking to various
1528 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1529 * Some of these have userspace or kernel workarounds/hacks.
1530 * Some of them don't...
1531 * We're going to be removing the hacks.
1532 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1533 * Note: this check/enforcement only applies to *system* userspace code,
1534 * it does not affect unprivileged apps, the 32-on-64 compatibility
1535 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1536 *
1537 * Additionally the 32-bit kernel jit support is poor,
1538 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
1539 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001540 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001541 // Stuff won't work reliably, but...
1542 if (isTV()) {
1543 // exempt TVs... they don't really need functional advanced networking
1544 ALOGW("[TV] 32-bit userspace unsupported on 6.2+ kernels.");
1545 } else if (isWear() && isArm()) {
1546 // exempt Arm Wear devices (arm32 ABI is far less problematic than x86-32)
1547 ALOGW("[Arm Wear] 32-bit userspace unsupported on 6.2+ kernels.");
1548 } else if (first_api_level <= __ANDROID_API_T__ && isArm()) {
1549 // also exempt Arm devices upgrading with major kernel rev from T-
1550 // might possibly be better for them to run with a newer kernel...
1551 ALOGW("[Arm KernelUpRev] 32-bit userspace unsupported on 6.2+ kernels.");
1552 } else if (isArm()) {
1553 ALOGE("[Arm] 64-bit userspace required on 6.2+ kernels (%d).", first_api_level);
1554 return 1;
1555 } else { // x86 since RiscV cannot be 32-bit
1556 ALOGE("[x86] 64-bit userspace required on 6.2+ kernels.");
1557 return 1;
1558 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001559 }
1560
Maciej Żenczykowski21b4a052024-09-03 15:46:48 -07001561 // Note: 6.6 is highest version supported by Android V (sdk=35), so this is for sdk=36+
1562 if (isUserspace32bit() && isAtLeastKernelVersion(6, 7, 0)) {
1563 ALOGE("64-bit userspace required on 6.7+ kernels.");
1564 return 1;
1565 }
1566
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001567 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001568 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001569 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001570 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001571 return 1;
1572 }
1573
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001574 if (runningAsRoot) {
1575 // Note: writing this proc file requires being root (always the case on V+)
1576
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001577 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1578 // but we need 0 (enabled)
1579 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1580 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1581 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001582 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001583 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001584
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001585 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001586 // Note: writing these proc files requires CAP_NET_ADMIN
1587 // and sepolicy which is only present on U+,
1588 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1589 // trigger (ie. by init itself) instead.
1590
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001591 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1592 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1593 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1594 // kernel does not have CONFIG_BPF_JIT=y)
1595 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1596 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1597 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001598
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001599 // Enable JIT kallsyms export for privileged users only
1600 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1601 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1602 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1603 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001604
1605 // Create all the pin subdirectories
1606 // (this must be done first to allow selinux_context and pin_subdir functionality,
1607 // which could otherwise fail with ENOENT during object pinning or renaming,
1608 // due to ordering issues)
1609 for (const auto& location : locations) {
1610 if (createSysFsBpfSubDir(location.prefix)) return 1;
1611 }
1612
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001613 // Note: there's no actual src dir for fs_bpf_loader .o's,
1614 // so it is not listed in 'locations[].prefix'.
1615 // This is because this is primarily meant for triggering genfscon rules,
1616 // and as such this will likely always be the case.
1617 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1618 if (createSysFsBpfSubDir("loader")) return 1;
1619
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001620 // Load all ELF objects, create programs and maps, and pin them
1621 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001622 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001623 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1624 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1625 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1626 "problems or startup script race.");
1627 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1628 sleep(20);
1629 return 2;
1630 }
1631 }
1632
1633 int key = 1;
1634 int value = 123;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001635 unique_fd map(
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001636 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1637 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001638 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1639 return 1;
1640 }
1641
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001642 // leave a flag that we're done
1643 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001644
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001645 // platform bpfloader will only succeed when run as root
1646 if (!runningAsRoot) {
1647 // unreachable on U QPR3+ which always runs netbpfload as root
1648
1649 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1650 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001651 }
1652
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001653 // unreachable before U QPR3
1654 ALOGI("done, transferring control to platform bpfloader.");
1655
1656 // platform BpfLoader *needs* to run as root
1657 const char * args[] = { platformBpfLoader, NULL, };
1658 execve(args[0], (char**)args, envp);
1659 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1660 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001661}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001662
1663} // namespace bpf
1664} // namespace android
1665
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001666int main(int argc, char** argv, char * const envp[]) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001667 InitLogging(argv, &KernelLogger);
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001668
1669 if (argc == 2 && !strcmp(argv[1], "done")) {
1670 // we're being re-exec'ed from platform bpfloader to 'finalize' things
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001671 if (!SetProperty("bpf.progs_loaded", "1")) {
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001672 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1673 return 125;
1674 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001675 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001676 return 0;
1677 }
1678
1679 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001680}