blob: 5d4cd4258063a4f50a65241368111fc85c1d20e0 [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
100};
101
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700102static constexpr domain AllDomains[] = {
103 domain::unspecified,
104 domain::tethering,
105 domain::net_private,
106 domain::net_shared,
107 domain::netd_readonly,
108 domain::netd_shared,
109};
110
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700111static constexpr bool specified(domain d) {
112 return d != domain::unspecified;
113}
114
115struct Location {
116 const char* const dir = "";
117 const char* const prefix = "";
118};
119
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700120// Returns the build type string (from ro.build.type).
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700121const std::string& getBuildType() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700122 static std::string t = GetProperty("ro.build.type", "unknown");
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700123 return t;
124}
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700125
126// The following functions classify the 3 Android build types.
127inline bool isEng() {
128 return getBuildType() == "eng";
129}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700130
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700131inline bool isUser() {
132 return getBuildType() == "user";
133}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700134
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700135inline bool isUserdebug() {
136 return getBuildType() == "userdebug";
137}
138
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700139#define BPF_FS_PATH "/sys/fs/bpf/"
140
141// Size of the BPF log buffer for verifier logging
142#define BPF_LOAD_LOG_SZ 0xfffff
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 Żenczykowski6e1b4252024-08-07 15:03:44 -0700154 }
155}
156
157domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
158 for (domain d : AllDomains) {
159 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
160 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
161 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
162 }
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700163 ALOGE("unrecognized selinux_context '%-32s'", s);
164 // Note: we *can* just abort() here as we only load bpf .o files shipped
165 // in the same mainline module / apex as NetBpfLoad itself.
166 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700167}
168
169constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
170 switch (d) {
171 case domain::unspecified: return unspecified;
172 case domain::tethering: return "tethering/";
173 case domain::net_private: return "net_private/";
174 case domain::net_shared: return "net_shared/";
175 case domain::netd_readonly: return "netd_readonly/";
176 case domain::netd_shared: return "netd_shared/";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700177 }
178};
179
180domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
181 for (domain d : AllDomains) {
182 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
183 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
184 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
185 }
186 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700187 // Note: we *can* just abort() here as we only load bpf .o files shipped
188 // in the same mainline module / apex as NetBpfLoad itself.
189 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700190}
191
192static string pathToObjName(const string& path) {
193 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
Maciej Żenczykowski8a767282024-09-04 10:56:55 -0700194 string filename = Split(path, "/").back();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700195 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
196 string name = filename.substr(0, filename.find_last_of('.'));
197 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
198 // this can be used to provide duplicate programs (mux based on the bpfloader version)
199 return name.substr(0, name.find_last_of('@'));
200}
201
202typedef struct {
203 const char* name;
204 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000205 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700206} sectionType;
207
208/*
209 * Map section name prefixes to program types, the section name will be:
210 * SECTION(<prefix>/<name-of-program>)
211 * For example:
212 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
213 * is the name of the program, and tracepoint is the type.
214 *
215 * However, be aware that you should not be directly using the SECTION() macro.
216 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
217 *
218 * Programs shipped inside the tethering apex should be limited to networking stuff,
219 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
220 * since they are less stable abi/api and may conflict with platform uses of bpf.
221 */
222sectionType sectionNameTypes[] = {
223 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
224 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000225 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
226 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700227 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
228 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
229 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
230 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
231 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
232 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
233 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700234 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
235 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
236 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
237 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000238 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
239 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700240 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
241 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
242 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000243 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700244 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
245 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000246 {"xdp/", BPF_PROG_TYPE_XDP},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700247};
248
249typedef struct {
250 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000251 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700252 string name;
253 vector<char> data;
254 vector<char> rel_data;
255 optional<struct bpf_prog_def> prog_def;
256
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000257 unique_fd prog_fd; // fd after loading
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700258} codeSection;
259
260static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
261 elfFile.seekg(0);
262 if (elfFile.fail()) return -1;
263
264 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
265
266 return 0;
267}
268
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000269// Reads all section header tables into an Shdr array
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700270static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
271 Elf64_Ehdr eh;
272 int ret = 0;
273
274 ret = readElfHeader(elfFile, &eh);
275 if (ret) return ret;
276
277 elfFile.seekg(eh.e_shoff);
278 if (elfFile.fail()) return -1;
279
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000280 // Read shdr table entries
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700281 shTable.resize(eh.e_shnum);
282
283 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
284
285 return 0;
286}
287
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000288// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700289static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
290 vector<Elf64_Shdr> shTable;
291 int ret = readSectionHeadersAll(elfFile, shTable);
292 if (ret) return ret;
293
294 elfFile.seekg(shTable[id].sh_offset);
295 if (elfFile.fail()) return -1;
296
297 sec.resize(shTable[id].sh_size);
298 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
299
300 return 0;
301}
302
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000303// Read whole section header string table
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700304static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
305 Elf64_Ehdr eh;
306 int ret = readElfHeader(elfFile, &eh);
307 if (ret) return ret;
308
309 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
310 if (ret) return ret;
311
312 return 0;
313}
314
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000315// Get name from offset in strtab
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700316static int getSymName(ifstream& elfFile, int nameOff, string& name) {
317 int ret;
318 vector<char> secStrTab;
319
320 ret = readSectionHeaderStrtab(elfFile, secStrTab);
321 if (ret) return ret;
322
323 if (nameOff >= (int)secStrTab.size()) return -1;
324
325 name = string((char*)secStrTab.data() + nameOff);
326 return 0;
327}
328
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000329// Reads a full section by name - example to get the GPL license
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700330static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
331 vector<char> secStrTab;
332 vector<Elf64_Shdr> shTable;
333 int ret;
334
335 ret = readSectionHeadersAll(elfFile, shTable);
336 if (ret) return ret;
337
338 ret = readSectionHeaderStrtab(elfFile, secStrTab);
339 if (ret) return ret;
340
341 for (int i = 0; i < (int)shTable.size(); i++) {
342 char* secname = secStrTab.data() + shTable[i].sh_name;
343 if (!secname) continue;
344
345 if (!strcmp(secname, name)) {
346 vector<char> dataTmp;
347 dataTmp.resize(shTable[i].sh_size);
348
349 elfFile.seekg(shTable[i].sh_offset);
350 if (elfFile.fail()) return -1;
351
352 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
353
354 data = dataTmp;
355 return 0;
356 }
357 }
358 return -2;
359}
360
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700361unsigned int readSectionUint(const char* name, ifstream& elfFile) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700362 vector<char> theBytes;
363 int ret = readSectionByName(name, elfFile, theBytes);
364 if (ret) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700365 ALOGE("Couldn't find section %s.", name);
366 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700367 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700368 ALOGE("Section %s is too short.", name);
369 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700370 } else {
371 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
372 unsigned int value = static_cast<unsigned char>(theBytes[3]);
373 value <<= 8;
374 value += static_cast<unsigned char>(theBytes[2]);
375 value <<= 8;
376 value += static_cast<unsigned char>(theBytes[1]);
377 value <<= 8;
378 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000379 ALOGD("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700380 return value;
381 }
382}
383
384static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
385 int ret;
386 vector<Elf64_Shdr> shTable;
387
388 ret = readSectionHeadersAll(elfFile, shTable);
389 if (ret) return ret;
390
391 for (int i = 0; i < (int)shTable.size(); i++) {
392 if ((int)shTable[i].sh_type != type) continue;
393
394 vector<char> dataTmp;
395 dataTmp.resize(shTable[i].sh_size);
396
397 elfFile.seekg(shTable[i].sh_offset);
398 if (elfFile.fail()) return -1;
399
400 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
401
402 data = dataTmp;
403 return 0;
404 }
405 return -2;
406}
407
408static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
409 return (a.st_value < b.st_value);
410}
411
412static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
413 int ret, numElems;
414 Elf64_Sym* buf;
415 vector<char> secData;
416
417 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
418 if (ret) return ret;
419
420 buf = (Elf64_Sym*)secData.data();
421 numElems = (secData.size() / sizeof(Elf64_Sym));
422 data.assign(buf, buf + numElems);
423
424 if (sort) std::sort(data.begin(), data.end(), symCompare);
425 return 0;
426}
427
428static enum bpf_prog_type getSectionType(string& name) {
429 for (auto& snt : sectionNameTypes)
430 if (StartsWith(name, snt.name)) return snt.type;
431
432 return BPF_PROG_TYPE_UNSPEC;
433}
434
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700435static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700436 vector<char> pdData;
437 int ret = readSectionByName("progs", elfFile, pdData);
438 if (ret) return ret;
439
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700440 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700441 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700442 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700443 return -1;
444 };
445
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700446 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700447
448 const char* dataPtr = pdData.data();
449 for (auto& p : pd) {
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700450 // Copy the structure from the ELF file and move to the next one.
451 memcpy(&p, dataPtr, sizeof(struct bpf_prog_def));
452 dataPtr += sizeof(struct bpf_prog_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700453 }
454 return 0;
455}
456
457static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
458 optional<unsigned> symbolType = std::nullopt) {
459 int ret;
460 string name;
461 vector<Elf64_Sym> symtab;
462 vector<Elf64_Shdr> shTable;
463
464 ret = readSymTab(elfFile, 1 /* sort */, symtab);
465 if (ret) return ret;
466
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000467 // Get index of section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700468 ret = readSectionHeadersAll(elfFile, shTable);
469 if (ret) return ret;
470
471 int sec_idx = -1;
472 for (int i = 0; i < (int)shTable.size(); i++) {
473 ret = getSymName(elfFile, shTable[i].sh_name, name);
474 if (ret) return ret;
475
476 if (!name.compare(sectionName)) {
477 sec_idx = i;
478 break;
479 }
480 }
481
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000482 // No section found with matching name
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700483 if (sec_idx == -1) {
484 ALOGW("No %s section could be found in elf object", sectionName.c_str());
485 return -1;
486 }
487
488 for (int i = 0; i < (int)symtab.size(); i++) {
489 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
490
491 if (symtab[i].st_shndx == sec_idx) {
492 string s;
493 ret = getSymName(elfFile, symtab[i].st_name, s);
494 if (ret) return ret;
495 names.push_back(s);
496 }
497 }
498
499 return 0;
500}
501
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000502// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700503static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700504 vector<Elf64_Shdr> shTable;
505 int entries, ret = 0;
506
507 ret = readSectionHeadersAll(elfFile, shTable);
508 if (ret) return ret;
509 entries = shTable.size();
510
511 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700512 ret = readProgDefs(elfFile, pd);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700513 if (ret) return ret;
514 vector<string> progDefNames;
515 ret = getSectionSymNames(elfFile, "progs", progDefNames);
516 if (!pd.empty() && ret) return ret;
517
518 for (int i = 0; i < entries; i++) {
519 string name;
520 codeSection cs_temp;
521 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
522
523 ret = getSymName(elfFile, shTable[i].sh_name, name);
524 if (ret) return ret;
525
526 enum bpf_prog_type ptype = getSectionType(name);
527
528 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
529
530 // This must be done before '/' is replaced with '_'.
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000531 for (auto& snt : sectionNameTypes)
532 if (StartsWith(name, snt.name)) cs_temp.attach_type = snt.attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700533
534 string oldName = name;
535
536 // convert all slashes to underscores
537 std::replace(name.begin(), name.end(), '/', '_');
538
539 cs_temp.type = ptype;
540 cs_temp.name = name;
541
542 ret = readSectionByIdx(elfFile, i, cs_temp.data);
543 if (ret) return ret;
544 ALOGV("Loaded code section %d (%s)", i, name.c_str());
545
546 vector<string> csSymNames;
547 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
548 if (ret || !csSymNames.size()) return ret;
549 for (size_t i = 0; i < progDefNames.size(); ++i) {
550 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
551 cs_temp.prog_def = pd[i];
552 break;
553 }
554 }
555
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000556 // Check for rel section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700557 if (cs_temp.data.size() > 0 && i < entries) {
558 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
559 if (ret) return ret;
560
561 if (name == (".rel" + oldName)) {
562 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
563 if (ret) return ret;
564 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
565 }
566 }
567
568 if (cs_temp.data.size() > 0) {
569 cs.push_back(std::move(cs_temp));
570 ALOGV("Adding section %d to cs list", i);
571 }
572 }
573 return 0;
574}
575
576static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
577 vector<Elf64_Sym> symtab;
578 int ret = 0;
579
580 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
581 if (ret) return ret;
582
583 if (index >= (int)symtab.size()) return -1;
584
585 return getSymName(elfFile, symtab[index].st_name, name);
586}
587
588static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
589 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
590 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
591 // so on 4.9-T kernels just pretend the map matches our expectations.
592 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
593 // This is because the primary failure mode we're trying to detect here
594 // is either a source code misconfiguration (which is likely kernel independent)
595 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
596 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
597
598 // Assuming fd is a valid Bpf Map file descriptor then
599 // all the following should always succeed on a 4.14+ kernel.
600 // If they somehow do fail, they'll return -1 (and set errno),
601 // which should then cause (among others) a key_size mismatch.
602 int fd_type = bpfGetFdMapType(fd);
603 int fd_key_size = bpfGetFdKeySize(fd);
604 int fd_value_size = bpfGetFdValueSize(fd);
605 int fd_max_entries = bpfGetFdMaxEntries(fd);
606 int fd_map_flags = bpfGetFdMapFlags(fd);
607
608 // DEVMAPs are readonly from the bpf program side's point of view, as such
609 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
610 int desired_map_flags = (int)mapDef.map_flags;
611 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
612 desired_map_flags |= BPF_F_RDONLY_PROG;
613
Maciej Żenczykowskidcb2e742024-08-29 10:40:35 -0700614 if (type == BPF_MAP_TYPE_LPM_TRIE)
615 desired_map_flags |= BPF_F_NO_PREALLOC;
616
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700617 // The .h file enforces that this is a power of two, and page size will
618 // also always be a power of two, so this logic is actually enough to
619 // force it to be a multiple of the page size, as required by the kernel.
620 unsigned int desired_max_entries = mapDef.max_entries;
621 if (type == BPF_MAP_TYPE_RINGBUF) {
622 if (desired_max_entries < page_size) desired_max_entries = page_size;
623 }
624
625 // The following checks should *never* trigger, if one of them somehow does,
626 // it probably means a bpf .o file has been changed/replaced at runtime
627 // and bpfloader was manually rerun (normally it should only run *once*
628 // early during the boot process).
629 // Another possibility is that something is misconfigured in the code:
630 // most likely a shared map is declared twice differently.
631 // But such a change should never be checked into the source tree...
632 if ((fd_type == type) &&
633 (fd_key_size == (int)mapDef.key_size) &&
634 (fd_value_size == (int)mapDef.value_size) &&
635 (fd_max_entries == (int)desired_max_entries) &&
636 (fd_map_flags == desired_map_flags)) {
637 return true;
638 }
639
640 ALOGE("bpf map name %s mismatch: desired/found: "
641 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
642 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
643 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
644 return false;
645}
646
647static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700648 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700649 int ret;
650 vector<char> mdData;
651 vector<struct bpf_map_def> md;
652 vector<string> mapNames;
653 string objName = pathToObjName(string(elfPath));
654
655 ret = readSectionByName("maps", elfFile, mdData);
656 if (ret == -2) return 0; // no maps to read
657 if (ret) return ret;
658
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700659 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700660 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700661 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700662 return -1;
663 };
664
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700665 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700666
667 const char* dataPtr = mdData.data();
668 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700669 // Copy the structure from the ELF file and move to the next one.
670 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
671 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700672 }
673
674 ret = getSectionSymNames(elfFile, "maps", mapNames);
675 if (ret) return ret;
676
677 unsigned kvers = kernelVersion();
678
679 for (int i = 0; i < (int)mapNames.size(); i++) {
680 if (md[i].zero != 0) abort();
681
682 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000683 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700684 md[i].bpfloader_min_ver);
685 mapFds.push_back(unique_fd());
686 continue;
687 }
688
689 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000690 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700691 md[i].bpfloader_max_ver);
692 mapFds.push_back(unique_fd());
693 continue;
694 }
695
696 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000697 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700698 mapNames[i].c_str(), kvers, md[i].min_kver);
699 mapFds.push_back(unique_fd());
700 continue;
701 }
702
703 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000704 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700705 mapNames[i].c_str(), kvers, md[i].max_kver);
706 mapFds.push_back(unique_fd());
707 continue;
708 }
709
710 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
711 (md[i].ignore_on_userdebug && isUserdebug())) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000712 ALOGD("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700713 getBuildType().c_str());
714 mapFds.push_back(unique_fd());
715 continue;
716 }
717
718 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
719 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
720 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
721 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
722 (isRiscV() && md[i].ignore_on_riscv64)) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000723 ALOGD("skipping map %s which is ignored on %s", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700724 describeArch());
725 mapFds.push_back(unique_fd());
726 continue;
727 }
728
729 enum bpf_map_type type = md[i].type;
730 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
731 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
732 // of be approximated: ARRAY has the same userspace api, though it is not usable
733 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
734 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
735 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
736 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
737 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
738 type = BPF_MAP_TYPE_ARRAY;
739 }
740 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
741 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
742 // of be approximated: HASH has the same userspace visible api.
743 // However it cannot be used by ebpf programs in the same way.
744 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
745 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
746 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
747 // programs as being 5.4+...
748 type = BPF_MAP_TYPE_HASH;
749 }
750
751 // The .h file enforces that this is a power of two, and page size will
752 // also always be a power of two, so this logic is actually enough to
753 // force it to be a multiple of the page size, as required by the kernel.
754 unsigned int max_entries = md[i].max_entries;
755 if (type == BPF_MAP_TYPE_RINGBUF) {
756 if (max_entries < page_size) max_entries = page_size;
757 }
758
759 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
760 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000761 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700762 md[i].selinux_context, static_cast<int>(selinux_context),
763 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
764 }
765
766 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700767 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000768 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700769 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
770 }
771
772 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
773 // except that maps shared across .o's have empty <objName>
774 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
775 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
776 (md[i].shared ? "" : objName) + "_" + mapNames[i];
777 bool reuse = false;
778 unique_fd fd;
779 int saved_errno;
780
781 if (access(mapPinLoc.c_str(), F_OK) == 0) {
782 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
783 saved_errno = errno;
784 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
785 reuse = true;
786 } else {
787 union bpf_attr req = {
788 .map_type = type,
789 .key_size = md[i].key_size,
790 .value_size = md[i].value_size,
791 .max_entries = max_entries,
Maciej Żenczykowskidcb2e742024-08-29 10:40:35 -0700792 .map_flags = md[i].map_flags | (type == BPF_MAP_TYPE_LPM_TRIE ? BPF_F_NO_PREALLOC : 0),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700793 };
794 if (isAtLeastKernelVersion(4, 15, 0))
795 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
796 fd.reset(bpf(BPF_MAP_CREATE, req));
797 saved_errno = errno;
Maciej Żenczykowski8597e3a2024-08-28 15:42:01 -0700798 if (fd.ok()) {
799 ALOGD("bpf_create_map[%s] -> %d", mapNames[i].c_str(), fd.get());
800 } else {
801 ALOGE("bpf_create_map[%s] -> %d errno:%d", mapNames[i].c_str(), fd.get(), saved_errno);
802 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700803 }
804
805 if (!fd.ok()) return -saved_errno;
806
807 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
808 // safety (since reuse code path is rare) run these checks even if we just created it.
809 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
810 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
811
812 if (!reuse) {
813 if (specified(selinux_context)) {
814 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
815 "tmp_map_" + objName + "_" + mapNames[i];
816 ret = bpfFdPin(fd, createLoc.c_str());
817 if (ret) {
818 int err = errno;
819 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
820 return -err;
821 }
822 ret = renameat2(AT_FDCWD, createLoc.c_str(),
823 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
824 if (ret) {
825 int err = errno;
826 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
827 err, strerror(err));
828 return -err;
829 }
830 } else {
831 ret = bpfFdPin(fd, mapPinLoc.c_str());
832 if (ret) {
833 int err = errno;
834 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
835 return -err;
836 }
837 }
838 ret = chmod(mapPinLoc.c_str(), md[i].mode);
839 if (ret) {
840 int err = errno;
841 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
842 strerror(err));
843 return -err;
844 }
845 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
846 if (ret) {
847 int err = errno;
848 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
849 ret, err, strerror(err));
850 return -err;
851 }
852 }
853
854 int mapId = bpfGetFdMapId(fd);
855 if (mapId == -1) {
Maciej Żenczykowski508c8f72024-08-28 15:07:33 -0700856 if (isAtLeastKernelVersion(4, 14, 0))
857 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700858 } else {
859 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
860 }
861
862 mapFds.push_back(std::move(fd));
863 }
864
865 return ret;
866}
867
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700868static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
869 int insnIndex;
870 struct bpf_insn *insn, *insns;
871
872 insns = (struct bpf_insn*)(insnsPtr);
873
874 insnIndex = offset / sizeof(struct bpf_insn);
875 insn = &insns[insnIndex];
876
877 // Occasionally might be useful for relocation debugging, but pretty spammy
878 if (0) {
879 ALOGV("applying relo to instruction at byte offset: %llu, "
880 "insn offset %d, insn %llx",
881 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
882 }
883
884 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700885 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700886 return;
887 }
888
889 insn->imm = fd;
890 insn->src_reg = BPF_PSEUDO_MAP_FD;
891}
892
893static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
894 vector<string> mapNames;
895
896 int ret = getSectionSymNames(elfFile, "maps", mapNames);
897 if (ret) return;
898
899 for (int k = 0; k != (int)cs.size(); k++) {
900 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
901 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
902
903 for (int i = 0; i < n_rel; i++) {
904 int symIndex = ELF64_R_SYM(rel[i].r_info);
905 string symName;
906
907 ret = getSymNameByIdx(elfFile, symIndex, symName);
908 if (ret) return;
909
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000910 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700911 for (int j = 0; j < (int)mapNames.size(); j++) {
912 if (!mapNames[j].compare(symName)) {
913 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
914 break;
915 }
916 }
917 }
918 }
919}
920
921static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
922 const char* prefix, const unsigned int bpfloader_ver) {
923 unsigned kvers = kernelVersion();
924
925 if (!kvers) {
926 ALOGE("unable to get kernel version");
927 return -EINVAL;
928 }
929
930 string objName = pathToObjName(string(elfPath));
931
932 for (int i = 0; i < (int)cs.size(); i++) {
933 unique_fd& fd = cs[i].prog_fd;
934 int ret;
935 string name = cs[i].name;
936
937 if (!cs[i].prog_def.has_value()) {
938 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
939 return -EINVAL;
940 }
941
942 unsigned min_kver = cs[i].prog_def->min_kver;
943 unsigned max_kver = cs[i].prog_def->max_kver;
944 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
945 max_kver, kvers);
946 if (kvers < min_kver) continue;
947 if (kvers >= max_kver) continue;
948
949 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
950 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
951 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
952 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700953
954 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
955 bpfMinVer, bpfMaxVer);
956 if (bpfloader_ver < bpfMinVer) continue;
957 if (bpfloader_ver >= bpfMaxVer) continue;
958
959 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
960 (cs[i].prog_def->ignore_on_user && isUser()) ||
961 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
962 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
963 getBuildType().c_str());
964 continue;
965 }
966
967 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
968 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
969 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
970 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
971 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
972 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
973 continue;
974 }
975
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700976 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000977 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700978 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
979 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
980 }
981
982 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000983 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700984 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
985 lookupPinSubdir(pin_subdir));
986 }
987
988 // strip any potential $foo suffix
989 // this can be used to provide duplicate programs
990 // conditionally loaded based on running kernel version
991 name = name.substr(0, name.find_last_of('$'));
992
993 bool reuse = false;
994 // Format of pin location is
995 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
996 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
997 objName + '_' + string(name);
998 if (access(progPinLoc.c_str(), F_OK) == 0) {
999 fd.reset(retrieveProgram(progPinLoc.c_str()));
1000 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
1001 (!fd.ok() ? std::strerror(errno) : "no error"));
1002 reuse = true;
1003 } else {
1004 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1005
1006 union bpf_attr req = {
1007 .prog_type = cs[i].type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001008 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001009 .insns = ptr_to_u64(cs[i].data.data()),
1010 .license = ptr_to_u64(license.c_str()),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001011 .log_level = 1,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001012 .log_size = static_cast<__u32>(log_buf.size()),
Maciej Żenczykowski52be6a82024-08-26 17:18:39 -07001013 .log_buf = ptr_to_u64(log_buf.data()),
1014 .kern_version = kvers,
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001015 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001016 };
1017 if (isAtLeastKernelVersion(4, 15, 0))
1018 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1019 fd.reset(bpf(BPF_PROG_LOAD, req));
1020
1021 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
1022 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
1023
1024 if (!fd.ok()) {
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001025 if (log_buf.size()) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001026 vector<string> lines = Split(log_buf.data(), "\n");
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001027
Maciej Żenczykowski9f8b17e2024-08-29 12:07:35 -07001028 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1029 for (const auto& line : lines) ALOGW("%s", line.c_str());
1030 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1031 }
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001032
1033 if (cs[i].prog_def->optional) {
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001034 ALOGW("failed program %s is marked optional - continuing...",
1035 cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001036 continue;
1037 }
Maciej Żenczykowskibfc0b612024-08-28 17:45:25 -07001038 ALOGE("non-optional program %s failed to load.", cs[i].name.c_str());
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001039 }
1040 }
1041
1042 if (!fd.ok()) return fd.get();
1043
1044 if (!reuse) {
1045 if (specified(selinux_context)) {
1046 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1047 "tmp_prog_" + objName + '_' + string(name);
1048 ret = bpfFdPin(fd, createLoc.c_str());
1049 if (ret) {
1050 int err = errno;
1051 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1052 return -err;
1053 }
1054 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1055 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1056 if (ret) {
1057 int err = errno;
1058 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1059 err, strerror(err));
1060 return -err;
1061 }
1062 } else {
1063 ret = bpfFdPin(fd, progPinLoc.c_str());
1064 if (ret) {
1065 int err = errno;
1066 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1067 return -err;
1068 }
1069 }
1070 if (chmod(progPinLoc.c_str(), 0440)) {
1071 int err = errno;
1072 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1073 return -err;
1074 }
1075 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1076 (gid_t)cs[i].prog_def->gid)) {
1077 int err = errno;
1078 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1079 cs[i].prog_def->gid, err, strerror(err));
1080 return -err;
1081 }
1082 }
1083
1084 int progId = bpfGetFdProgId(fd);
1085 if (progId == -1) {
1086 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
1087 } else {
1088 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
1089 }
1090 }
1091
1092 return 0;
1093}
1094
1095int loadProg(const char* const elfPath, bool* const isCritical, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001096 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001097 vector<char> license;
1098 vector<char> critical;
1099 vector<codeSection> cs;
1100 vector<unique_fd> mapFds;
1101 int ret;
1102
1103 if (!isCritical) return -1;
1104 *isCritical = false;
1105
1106 ifstream elfFile(elfPath, ios::in | ios::binary);
1107 if (!elfFile.is_open()) return -1;
1108
1109 ret = readSectionByName("critical", elfFile, critical);
1110 *isCritical = !ret;
1111
1112 ret = readSectionByName("license", elfFile, license);
1113 if (ret) {
1114 ALOGE("Couldn't find license in %s", elfPath);
1115 return ret;
1116 } else {
1117 ALOGD("Loading %s%s ELF object %s with license %s",
1118 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
1119 elfPath, (char*)license.data());
1120 }
1121
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001122 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1123 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001124
1125 // inclusive lower bound check
1126 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001127 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001128 bpfloader_ver, elfPath, bpfLoaderMinVer);
1129 return 0;
1130 }
1131
1132 // exclusive upper bound check
1133 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001134 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001135 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1136 return 0;
1137 }
1138
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001139 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001140 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1141
Maciej Żenczykowskie666d852024-08-15 15:03:38 -07001142 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001143 if (ret) {
1144 ALOGE("Couldn't read all code sections in %s", elfPath);
1145 return ret;
1146 }
1147
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001148 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001149 if (ret) {
1150 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1151 return ret;
1152 }
1153
1154 for (int i = 0; i < (int)mapFds.size(); i++)
1155 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1156
1157 applyMapRelo(elfFile, mapFds, cs);
1158
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001159 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001160 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1161
1162 return ret;
1163}
1164
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001165static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001166 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001167 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001168 if (errno == ENOENT) return false;
1169 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1170 abort(); // can only hit this if permissions (likely selinux) are screwed up
1171}
1172
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001173#define APEXROOT "/apex/com.android.tethering"
1174#define BPFROOT APEXROOT "/etc/bpf"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001175
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001176const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001177 // S+ Tethering mainline module (network_stack): tether offload
1178 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001179 .dir = BPFROOT "/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001180 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001181 },
1182 // T+ Tethering mainline module (shared with netd & system server)
1183 // netutils_wrapper (for iptables xt_bpf) has access to programs
1184 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001185 .dir = BPFROOT "/netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001186 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001187 },
1188 // T+ Tethering mainline module (shared with netd & system server)
1189 // netutils_wrapper has no access, netd has read only access
1190 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001191 .dir = BPFROOT "/netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001192 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001193 },
1194 // T+ Tethering mainline module (shared with system server)
1195 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001196 .dir = BPFROOT "/net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001197 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001198 },
1199 // T+ Tethering mainline module (not shared, just network_stack)
1200 {
Maciej Żenczykowski78fa8612024-08-26 17:22:25 -07001201 .dir = BPFROOT "/net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001202 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001203 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001204};
1205
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001206static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001207 int retVal = 0;
1208 DIR* dir;
1209 struct dirent* ent;
1210
1211 if ((dir = opendir(location.dir)) != NULL) {
1212 while ((ent = readdir(dir)) != NULL) {
1213 string s = ent->d_name;
1214 if (!EndsWith(s, ".o")) continue;
1215
1216 string progPath(location.dir);
1217 progPath += s;
1218
1219 bool critical;
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001220 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001221 if (ret) {
1222 if (critical) retVal = ret;
1223 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1224 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001225 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001226 }
1227 }
1228 closedir(dir);
1229 }
1230 return retVal;
1231}
1232
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001233static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001234 if (*prefix) {
1235 mode_t prevUmask = umask(0);
1236
1237 string s = "/sys/fs/bpf/";
1238 s += prefix;
1239
1240 errno = 0;
1241 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1242 if (ret && errno != EEXIST) {
1243 const int err = errno;
1244 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1245 return -err;
1246 }
1247
1248 umask(prevUmask);
1249 }
1250 return 0;
1251}
1252
1253// Technically 'value' doesn't need to be newline terminated, but it's best
1254// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1255// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001256static int writeProcSysFile(const char *filename, const char *value) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001257 unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001258 if (fd < 0) {
1259 const int err = errno;
1260 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1261 return -err;
1262 }
1263 int len = strlen(value);
1264 int v = write(fd, value, len);
1265 if (v < 0) {
1266 const int err = errno;
1267 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1268 return -err;
1269 }
1270 if (v != len) {
1271 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1272 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1273 return -EINVAL;
1274 }
1275 return 0;
1276}
1277
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001278#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001279const char * const platformBpfLoader = "/system/bin/bpfloader";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001280
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001281static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001282 char * found_blockdev = NULL;
1283 FILE * f = NULL;
1284 char buf[4096];
1285
1286 f = fopen("/proc/mounts", "re");
1287 if (!f) return 1;
1288
1289 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1290 while (fgets(buf, sizeof(buf), f)) {
1291 char * blockdev = buf;
1292 char * space = strchr(blockdev, ' ');
1293 if (!space) continue;
1294 *space = '\0';
1295 char * mntpath = space + 1;
1296 space = strchr(mntpath, ' ');
1297 if (!space) continue;
1298 *space = '\0';
1299 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1300 found_blockdev = strdup(blockdev);
1301 break;
1302 }
1303 fclose(f);
1304 f = NULL;
1305
1306 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001307 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001308
1309 f = fopen("/proc/mounts", "re");
1310 if (!f) { free(found_blockdev); return 3; }
1311
1312 while (fgets(buf, sizeof(buf), f)) {
1313 char * blockdev = buf;
1314 char * space = strchr(blockdev, ' ');
1315 if (!space) continue;
1316 *space = '\0';
1317 char * mntpath = space + 1;
1318 space = strchr(mntpath, ' ');
1319 if (!space) continue;
1320 *space = '\0';
1321 if (strcmp(blockdev, found_blockdev)) continue;
1322 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1323 char * at = strchr(mntpath, '@');
1324 if (!at) continue;
1325 char * ver = at + 1;
1326 ALOGI("Tethering APEX version %s", ver);
1327 }
1328 fclose(f);
1329 free(found_blockdev);
1330 return 0;
1331}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001332
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001333static bool hasGSM() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001334 static string ph = GetProperty("gsm.current.phone-type", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001335 static bool gsm = (ph != "");
1336 static bool logged = false;
1337 if (!logged) {
1338 logged = true;
1339 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1340 }
1341 return gsm;
1342}
1343
1344static bool isTV() {
1345 if (hasGSM()) return false; // TVs don't do GSM
1346
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001347 static string key = GetProperty("ro.oem.key1", "");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001348 static bool tv = StartsWith(key, "ATV00");
1349 static bool logged = false;
1350 if (!logged) {
1351 logged = true;
1352 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1353 }
1354 return tv;
1355}
1356
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001357static bool isWear() {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001358 static string wearSdkStr = GetProperty("ro.cw_build.wear_sdk.version", "");
1359 static int wearSdkInt = GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1360 static string buildChars = GetProperty("ro.build.characteristics", "");
1361 static vector<string> v = Tokenize(buildChars, ",");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001362 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1363 static bool wear = (wearSdkInt > 0) || watch;
1364 static bool logged = false;
1365 if (!logged) {
1366 logged = true;
1367 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1368 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1369 }
1370 return wear;
1371}
1372
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001373static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001374 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001375
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001376 // Any released device will have codename REL instead of a 'real' codename.
1377 // For safety: default to 'REL' so we default to unreleased=false on failure.
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001378 const bool unreleased = (GetProperty("ro.build.version.codename", "REL") != "REL");
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001379
1380 // goog/main device_api_level is bumped *way* before aosp/main api level
1381 // (the latter only gets bumped during the push of goog/main to aosp/main)
1382 //
1383 // Since we develop in AOSP, we want it to behave as if it was bumped too.
1384 //
1385 // Note that AOSP doesn't really have a good api level (for example during
1386 // early V dev cycle, it would have *all* of T, some but not all of U, and some V).
1387 // One could argue that for our purposes AOSP api level should be infinite or 10000.
1388 //
1389 // This could also cause api to be increased in goog/main or other branches,
1390 // but I can't imagine a case where this would be a problem: the problem
1391 // is rather a too low api level, rather than some ill defined high value.
1392 // For example as I write this aosp is 34/U, and goog is 35/V,
1393 // we want to treat both goog & aosp as 35/V, but it's harmless if we
1394 // treat goog as 36 because that value isn't yet defined to mean anything,
1395 // and we thus never compare against it.
1396 //
1397 // Also note that 'android_get_device_api_level()' is what the
1398 // //system/core/init/apex_init_util.cpp
1399 // apex init .XXrc parsing code uses for XX filtering.
1400 //
1401 // That code has a hack to bump <35 to 35 (to force aosp/main to parse .35rc),
1402 // but could (should?) perhaps be adjusted to match this.
1403 const int effective_api_level = android_get_device_api_level() + (int)unreleased;
1404 const bool isAtLeastT = (effective_api_level >= __ANDROID_API_T__);
1405 const bool isAtLeastU = (effective_api_level >= __ANDROID_API_U__);
1406 const bool isAtLeastV = (effective_api_level >= __ANDROID_API_V__);
Maciej Żenczykowskide7374d2024-09-03 15:56:44 -07001407 const bool isAtLeastW = (effective_api_level > __ANDROID_API_V__); // TODO: switch to W
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001408
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001409 const int first_api_level = GetIntProperty("ro.board.first_api_level", effective_api_level);
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001410
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001411 // last in U QPR2 beta1
1412 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1413 // first in U QPR2 beta~2
1414 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1415
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001416 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001417 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
1418 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1419 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1420 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1421 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowskide7374d2024-09-03 15:56:44 -07001422 if (isAtLeastW) ++bpfloader_ver; // [47] BPFLOADER_MAINLINE_W_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001423
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001424 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) uid:%d rc:%d%d",
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001425 bpfloader_ver, argv[0], android_get_device_api_level(), effective_api_level,
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001426 kernelVersion(), describeArch(), getuid(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001427 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001428
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001429 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1430 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1431 return 1;
1432 }
1433
1434 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1435 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1436 return 1;
1437 }
1438
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001439 logTetheringApexVersion();
1440
Maciej Żenczykowski11141da2024-03-15 18:21:33 -07001441 if (!isAtLeastT) {
1442 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001443 return 1;
1444 }
1445
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001446 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001447 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001448 ALOGE("Android T requires kernel 4.9.");
1449 return 1;
1450 }
1451
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001452 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001453 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001454 ALOGE("Android U requires kernel 4.14.");
1455 return 1;
1456 }
1457
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001458 // V bumps the kernel requirement up to 4.19
1459 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001460 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001461 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001462 return 1;
1463 }
1464
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001465 // Technically already required by U, but only enforce on V+
1466 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1467 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1468 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1469 if (!isTV()) return 1;
1470 }
1471
Maciej Żenczykowski9b6a9942024-09-03 16:08:35 -07001472 // 6.6 is highest version supported by Android V, so this is effectively W+ (sdk=36+)
1473 if (isKernel32Bit() && isAtLeastKernelVersion(6, 7, 0)) {
1474 ALOGE("Android platform with 32 bit kernel version >= 6.7.0 is unsupported");
1475 return 1;
1476 }
1477
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001478 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1479 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001480 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001481 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001482 }
1483
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001484 if (isAtLeastV) {
1485 bool bad = false;
1486
1487 if (!isLtsKernel()) {
1488 ALOGW("Android V only supports LTS kernels.");
1489 bad = true;
1490 }
1491
1492#define REQUIRE(maj, min, sub) \
1493 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
1494 ALOGW("Android V requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
1495 bad = true; \
1496 }
1497
1498 REQUIRE(4, 19, 236)
1499 REQUIRE(5, 4, 186)
1500 REQUIRE(5, 10, 199)
1501 REQUIRE(5, 15, 136)
1502 REQUIRE(6, 1, 57)
1503 REQUIRE(6, 6, 0)
1504
1505#undef REQUIRE
1506
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001507 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001508 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1509 }
1510 }
1511
Maciej Żenczykowski726b58f2024-09-03 15:42:46 -07001512 /* Android 14/U should only launch on 64-bit kernels
1513 * T launches on 5.10/5.15
1514 * U launches on 5.15/6.1
1515 * So >=5.16 implies isKernel64Bit()
1516 *
1517 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1518 *
1519 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1520 * we also require 64-bit userspace.
1521 *
1522 * There are various known issues with 32-bit userspace talking to various
1523 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1524 * Some of these have userspace or kernel workarounds/hacks.
1525 * Some of them don't...
1526 * We're going to be removing the hacks.
1527 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1528 * Note: this check/enforcement only applies to *system* userspace code,
1529 * it does not affect unprivileged apps, the 32-on-64 compatibility
1530 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
1531 *
1532 * Additionally the 32-bit kernel jit support is poor,
1533 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
1534 */
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001535 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski1c2187a2024-09-03 16:03:45 -07001536 // Stuff won't work reliably, but...
1537 if (isTV()) {
1538 // exempt TVs... they don't really need functional advanced networking
1539 ALOGW("[TV] 32-bit userspace unsupported on 6.2+ kernels.");
1540 } else if (isWear() && isArm()) {
1541 // exempt Arm Wear devices (arm32 ABI is far less problematic than x86-32)
1542 ALOGW("[Arm Wear] 32-bit userspace unsupported on 6.2+ kernels.");
1543 } else if (first_api_level <= __ANDROID_API_T__ && isArm()) {
1544 // also exempt Arm devices upgrading with major kernel rev from T-
1545 // might possibly be better for them to run with a newer kernel...
1546 ALOGW("[Arm KernelUpRev] 32-bit userspace unsupported on 6.2+ kernels.");
1547 } else if (isArm()) {
1548 ALOGE("[Arm] 64-bit userspace required on 6.2+ kernels (%d).", first_api_level);
1549 return 1;
1550 } else { // x86 since RiscV cannot be 32-bit
1551 ALOGE("[x86] 64-bit userspace required on 6.2+ kernels.");
1552 return 1;
1553 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001554 }
1555
Maciej Żenczykowski21b4a052024-09-03 15:46:48 -07001556 // Note: 6.6 is highest version supported by Android V (sdk=35), so this is for sdk=36+
1557 if (isUserspace32bit() && isAtLeastKernelVersion(6, 7, 0)) {
1558 ALOGE("64-bit userspace required on 6.7+ kernels.");
1559 return 1;
1560 }
1561
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001562 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001563 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001564 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001565 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001566 return 1;
1567 }
1568
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001569 if (runningAsRoot) {
1570 // Note: writing this proc file requires being root (always the case on V+)
1571
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001572 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1573 // but we need 0 (enabled)
1574 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1575 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1576 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001577 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001578 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001579
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001580 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001581 // Note: writing these proc files requires CAP_NET_ADMIN
1582 // and sepolicy which is only present on U+,
1583 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1584 // trigger (ie. by init itself) instead.
1585
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001586 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1587 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1588 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1589 // kernel does not have CONFIG_BPF_JIT=y)
1590 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1591 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1592 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001593
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001594 // Enable JIT kallsyms export for privileged users only
1595 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1596 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1597 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1598 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001599
1600 // Create all the pin subdirectories
1601 // (this must be done first to allow selinux_context and pin_subdir functionality,
1602 // which could otherwise fail with ENOENT during object pinning or renaming,
1603 // due to ordering issues)
1604 for (const auto& location : locations) {
1605 if (createSysFsBpfSubDir(location.prefix)) return 1;
1606 }
1607
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001608 // Note: there's no actual src dir for fs_bpf_loader .o's,
1609 // so it is not listed in 'locations[].prefix'.
1610 // This is because this is primarily meant for triggering genfscon rules,
1611 // and as such this will likely always be the case.
1612 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1613 if (createSysFsBpfSubDir("loader")) return 1;
1614
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001615 // Load all ELF objects, create programs and maps, and pin them
1616 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001617 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001618 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1619 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1620 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1621 "problems or startup script race.");
1622 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1623 sleep(20);
1624 return 2;
1625 }
1626 }
1627
1628 int key = 1;
1629 int value = 123;
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001630 unique_fd map(
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001631 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1632 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001633 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1634 return 1;
1635 }
1636
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001637 // leave a flag that we're done
1638 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001639
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001640 // platform bpfloader will only succeed when run as root
1641 if (!runningAsRoot) {
1642 // unreachable on U QPR3+ which always runs netbpfload as root
1643
1644 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1645 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001646 }
1647
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001648 // unreachable before U QPR3
1649 ALOGI("done, transferring control to platform bpfloader.");
1650
1651 // platform BpfLoader *needs* to run as root
1652 const char * args[] = { platformBpfLoader, NULL, };
1653 execve(args[0], (char**)args, envp);
1654 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1655 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001656}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001657
1658} // namespace bpf
1659} // namespace android
1660
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001661int main(int argc, char** argv, char * const envp[]) {
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001662 InitLogging(argv, &KernelLogger);
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001663
1664 if (argc == 2 && !strcmp(argv[1], "done")) {
1665 // we're being re-exec'ed from platform bpfloader to 'finalize' things
Maciej Żenczykowski8a767282024-09-04 10:56:55 -07001666 if (!SetProperty("bpf.progs_loaded", "1")) {
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001667 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1668 return 125;
1669 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001670 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001671 return 0;
1672 }
1673
1674 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001675}