blob: 99498bc07e488ac96da0b5d68d1816ea1030befa [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;
63using android::base::StartsWith;
64using android::base::unique_fd;
65using std::ifstream;
66using std::ios;
67using std::optional;
68using std::string;
69using std::vector;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070070
71namespace android {
72namespace bpf {
73
74// Bpf programs may specify per-program & per-map selinux_context and pin_subdir.
75//
76// The BpfLoader needs to convert these bpf.o specified strings into an enum
77// for internal use (to check that valid values were specified for the specific
78// location of the bpf.o file).
79//
80// It also needs to map selinux_context's into pin_subdir's.
81// This is because of how selinux_context is actually implemented via pin+rename.
82//
83// Thus 'domain' enumerates all selinux_context's/pin_subdir's that the BpfLoader
84// is aware of. Thus there currently needs to be a 1:1 mapping between the two.
85//
86enum class domain : int {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070087 unspecified = 0, // means just use the default for that specific pin location
88 tethering, // (S+) fs_bpf_tethering /sys/fs/bpf/tethering
89 net_private, // (T+) fs_bpf_net_private /sys/fs/bpf/net_private
90 net_shared, // (T+) fs_bpf_net_shared /sys/fs/bpf/net_shared
91 netd_readonly, // (T+) fs_bpf_netd_readonly /sys/fs/bpf/netd_readonly
92 netd_shared, // (T+) fs_bpf_netd_shared /sys/fs/bpf/netd_shared
93};
94
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070095static constexpr domain AllDomains[] = {
96 domain::unspecified,
97 domain::tethering,
98 domain::net_private,
99 domain::net_shared,
100 domain::netd_readonly,
101 domain::netd_shared,
102};
103
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700104static constexpr bool specified(domain d) {
105 return d != domain::unspecified;
106}
107
108struct Location {
109 const char* const dir = "";
110 const char* const prefix = "";
111};
112
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700113// Returns the build type string (from ro.build.type).
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700114const std::string& getBuildType() {
115 static std::string t = android::base::GetProperty("ro.build.type", "unknown");
116 return t;
117}
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700118
119// The following functions classify the 3 Android build types.
120inline bool isEng() {
121 return getBuildType() == "eng";
122}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700123
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700124inline bool isUser() {
125 return getBuildType() == "user";
126}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700127
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700128inline bool isUserdebug() {
129 return getBuildType() == "userdebug";
130}
131
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700132#define BPF_FS_PATH "/sys/fs/bpf/"
133
134// Size of the BPF log buffer for verifier logging
135#define BPF_LOAD_LOG_SZ 0xfffff
136
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700137static unsigned int page_size = static_cast<unsigned int>(getpagesize());
138
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700139constexpr const char* lookupSelinuxContext(const domain d) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700140 switch (d) {
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700141 case domain::unspecified: return "";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700142 case domain::tethering: return "fs_bpf_tethering";
143 case domain::net_private: return "fs_bpf_net_private";
144 case domain::net_shared: return "fs_bpf_net_shared";
145 case domain::netd_readonly: return "fs_bpf_netd_readonly";
146 case domain::netd_shared: return "fs_bpf_netd_shared";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700147 }
148}
149
150domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
151 for (domain d : AllDomains) {
152 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
153 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
154 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
155 }
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700156 ALOGE("unrecognized selinux_context '%-32s'", s);
157 // Note: we *can* just abort() here as we only load bpf .o files shipped
158 // in the same mainline module / apex as NetBpfLoad itself.
159 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700160}
161
162constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
163 switch (d) {
164 case domain::unspecified: return unspecified;
165 case domain::tethering: return "tethering/";
166 case domain::net_private: return "net_private/";
167 case domain::net_shared: return "net_shared/";
168 case domain::netd_readonly: return "netd_readonly/";
169 case domain::netd_shared: return "netd_shared/";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700170 }
171};
172
173domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
174 for (domain d : AllDomains) {
175 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
176 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
177 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
178 }
179 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700180 // Note: we *can* just abort() here as we only load bpf .o files shipped
181 // in the same mainline module / apex as NetBpfLoad itself.
182 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700183}
184
185static string pathToObjName(const string& path) {
186 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
187 string filename = android::base::Split(path, "/").back();
188 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
189 string name = filename.substr(0, filename.find_last_of('.'));
190 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
191 // this can be used to provide duplicate programs (mux based on the bpfloader version)
192 return name.substr(0, name.find_last_of('@'));
193}
194
195typedef struct {
196 const char* name;
197 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000198 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700199} sectionType;
200
201/*
202 * Map section name prefixes to program types, the section name will be:
203 * SECTION(<prefix>/<name-of-program>)
204 * For example:
205 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
206 * is the name of the program, and tracepoint is the type.
207 *
208 * However, be aware that you should not be directly using the SECTION() macro.
209 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
210 *
211 * Programs shipped inside the tethering apex should be limited to networking stuff,
212 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
213 * since they are less stable abi/api and may conflict with platform uses of bpf.
214 */
215sectionType sectionNameTypes[] = {
216 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
217 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000218 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
219 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700220 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
221 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
222 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
223 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
224 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
225 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
226 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700227 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
228 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
229 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
230 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000231 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
232 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700233 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
234 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
235 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000236 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700237 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
238 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000239 {"xdp/", BPF_PROG_TYPE_XDP},
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700240};
241
242typedef struct {
243 enum bpf_prog_type type;
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000244 enum bpf_attach_type attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700245 string name;
246 vector<char> data;
247 vector<char> rel_data;
248 optional<struct bpf_prog_def> prog_def;
249
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000250 unique_fd prog_fd; // fd after loading
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700251} codeSection;
252
253static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
254 elfFile.seekg(0);
255 if (elfFile.fail()) return -1;
256
257 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
258
259 return 0;
260}
261
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000262// Reads all section header tables into an Shdr array
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700263static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
264 Elf64_Ehdr eh;
265 int ret = 0;
266
267 ret = readElfHeader(elfFile, &eh);
268 if (ret) return ret;
269
270 elfFile.seekg(eh.e_shoff);
271 if (elfFile.fail()) return -1;
272
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000273 // Read shdr table entries
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700274 shTable.resize(eh.e_shnum);
275
276 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
277
278 return 0;
279}
280
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000281// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700282static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
283 vector<Elf64_Shdr> shTable;
284 int ret = readSectionHeadersAll(elfFile, shTable);
285 if (ret) return ret;
286
287 elfFile.seekg(shTable[id].sh_offset);
288 if (elfFile.fail()) return -1;
289
290 sec.resize(shTable[id].sh_size);
291 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
292
293 return 0;
294}
295
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000296// Read whole section header string table
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700297static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
298 Elf64_Ehdr eh;
299 int ret = readElfHeader(elfFile, &eh);
300 if (ret) return ret;
301
302 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
303 if (ret) return ret;
304
305 return 0;
306}
307
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000308// Get name from offset in strtab
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700309static int getSymName(ifstream& elfFile, int nameOff, string& name) {
310 int ret;
311 vector<char> secStrTab;
312
313 ret = readSectionHeaderStrtab(elfFile, secStrTab);
314 if (ret) return ret;
315
316 if (nameOff >= (int)secStrTab.size()) return -1;
317
318 name = string((char*)secStrTab.data() + nameOff);
319 return 0;
320}
321
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000322// Reads a full section by name - example to get the GPL license
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700323static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
324 vector<char> secStrTab;
325 vector<Elf64_Shdr> shTable;
326 int ret;
327
328 ret = readSectionHeadersAll(elfFile, shTable);
329 if (ret) return ret;
330
331 ret = readSectionHeaderStrtab(elfFile, secStrTab);
332 if (ret) return ret;
333
334 for (int i = 0; i < (int)shTable.size(); i++) {
335 char* secname = secStrTab.data() + shTable[i].sh_name;
336 if (!secname) continue;
337
338 if (!strcmp(secname, name)) {
339 vector<char> dataTmp;
340 dataTmp.resize(shTable[i].sh_size);
341
342 elfFile.seekg(shTable[i].sh_offset);
343 if (elfFile.fail()) return -1;
344
345 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
346
347 data = dataTmp;
348 return 0;
349 }
350 }
351 return -2;
352}
353
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700354unsigned int readSectionUint(const char* name, ifstream& elfFile) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700355 vector<char> theBytes;
356 int ret = readSectionByName(name, elfFile, theBytes);
357 if (ret) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700358 ALOGE("Couldn't find section %s.", name);
359 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700360 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowski213c9222024-08-15 15:52:43 -0700361 ALOGE("Section %s is too short.", name);
362 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700363 } else {
364 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
365 unsigned int value = static_cast<unsigned char>(theBytes[3]);
366 value <<= 8;
367 value += static_cast<unsigned char>(theBytes[2]);
368 value <<= 8;
369 value += static_cast<unsigned char>(theBytes[1]);
370 value <<= 8;
371 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000372 ALOGD("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700373 return value;
374 }
375}
376
377static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
378 int ret;
379 vector<Elf64_Shdr> shTable;
380
381 ret = readSectionHeadersAll(elfFile, shTable);
382 if (ret) return ret;
383
384 for (int i = 0; i < (int)shTable.size(); i++) {
385 if ((int)shTable[i].sh_type != type) continue;
386
387 vector<char> dataTmp;
388 dataTmp.resize(shTable[i].sh_size);
389
390 elfFile.seekg(shTable[i].sh_offset);
391 if (elfFile.fail()) return -1;
392
393 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
394
395 data = dataTmp;
396 return 0;
397 }
398 return -2;
399}
400
401static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
402 return (a.st_value < b.st_value);
403}
404
405static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
406 int ret, numElems;
407 Elf64_Sym* buf;
408 vector<char> secData;
409
410 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
411 if (ret) return ret;
412
413 buf = (Elf64_Sym*)secData.data();
414 numElems = (secData.size() / sizeof(Elf64_Sym));
415 data.assign(buf, buf + numElems);
416
417 if (sort) std::sort(data.begin(), data.end(), symCompare);
418 return 0;
419}
420
421static enum bpf_prog_type getSectionType(string& name) {
422 for (auto& snt : sectionNameTypes)
423 if (StartsWith(name, snt.name)) return snt.type;
424
425 return BPF_PROG_TYPE_UNSPEC;
426}
427
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700428static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700429 vector<char> pdData;
430 int ret = readSectionByName("progs", elfFile, pdData);
431 if (ret) return ret;
432
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700433 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700434 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700435 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700436 return -1;
437 };
438
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700439 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700440
441 const char* dataPtr = pdData.data();
442 for (auto& p : pd) {
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700443 // Copy the structure from the ELF file and move to the next one.
444 memcpy(&p, dataPtr, sizeof(struct bpf_prog_def));
445 dataPtr += sizeof(struct bpf_prog_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700446 }
447 return 0;
448}
449
450static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
451 optional<unsigned> symbolType = std::nullopt) {
452 int ret;
453 string name;
454 vector<Elf64_Sym> symtab;
455 vector<Elf64_Shdr> shTable;
456
457 ret = readSymTab(elfFile, 1 /* sort */, symtab);
458 if (ret) return ret;
459
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000460 // Get index of section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700461 ret = readSectionHeadersAll(elfFile, shTable);
462 if (ret) return ret;
463
464 int sec_idx = -1;
465 for (int i = 0; i < (int)shTable.size(); i++) {
466 ret = getSymName(elfFile, shTable[i].sh_name, name);
467 if (ret) return ret;
468
469 if (!name.compare(sectionName)) {
470 sec_idx = i;
471 break;
472 }
473 }
474
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000475 // No section found with matching name
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700476 if (sec_idx == -1) {
477 ALOGW("No %s section could be found in elf object", sectionName.c_str());
478 return -1;
479 }
480
481 for (int i = 0; i < (int)symtab.size(); i++) {
482 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
483
484 if (symtab[i].st_shndx == sec_idx) {
485 string s;
486 ret = getSymName(elfFile, symtab[i].st_name, s);
487 if (ret) return ret;
488 names.push_back(s);
489 }
490 }
491
492 return 0;
493}
494
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000495// Read a section by its index - for ex to get sec hdr strtab blob
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700496static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700497 vector<Elf64_Shdr> shTable;
498 int entries, ret = 0;
499
500 ret = readSectionHeadersAll(elfFile, shTable);
501 if (ret) return ret;
502 entries = shTable.size();
503
504 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskie666d852024-08-15 15:03:38 -0700505 ret = readProgDefs(elfFile, pd);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700506 if (ret) return ret;
507 vector<string> progDefNames;
508 ret = getSectionSymNames(elfFile, "progs", progDefNames);
509 if (!pd.empty() && ret) return ret;
510
511 for (int i = 0; i < entries; i++) {
512 string name;
513 codeSection cs_temp;
514 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
515
516 ret = getSymName(elfFile, shTable[i].sh_name, name);
517 if (ret) return ret;
518
519 enum bpf_prog_type ptype = getSectionType(name);
520
521 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
522
523 // This must be done before '/' is replaced with '_'.
Maciej Żenczykowski346831c2024-08-12 17:49:10 +0000524 for (auto& snt : sectionNameTypes)
525 if (StartsWith(name, snt.name)) cs_temp.attach_type = snt.attach_type;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700526
527 string oldName = name;
528
529 // convert all slashes to underscores
530 std::replace(name.begin(), name.end(), '/', '_');
531
532 cs_temp.type = ptype;
533 cs_temp.name = name;
534
535 ret = readSectionByIdx(elfFile, i, cs_temp.data);
536 if (ret) return ret;
537 ALOGV("Loaded code section %d (%s)", i, name.c_str());
538
539 vector<string> csSymNames;
540 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
541 if (ret || !csSymNames.size()) return ret;
542 for (size_t i = 0; i < progDefNames.size(); ++i) {
543 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
544 cs_temp.prog_def = pd[i];
545 break;
546 }
547 }
548
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000549 // Check for rel section
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700550 if (cs_temp.data.size() > 0 && i < entries) {
551 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
552 if (ret) return ret;
553
554 if (name == (".rel" + oldName)) {
555 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
556 if (ret) return ret;
557 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
558 }
559 }
560
561 if (cs_temp.data.size() > 0) {
562 cs.push_back(std::move(cs_temp));
563 ALOGV("Adding section %d to cs list", i);
564 }
565 }
566 return 0;
567}
568
569static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
570 vector<Elf64_Sym> symtab;
571 int ret = 0;
572
573 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
574 if (ret) return ret;
575
576 if (index >= (int)symtab.size()) return -1;
577
578 return getSymName(elfFile, symtab[index].st_name, name);
579}
580
581static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
582 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
583 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
584 // so on 4.9-T kernels just pretend the map matches our expectations.
585 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
586 // This is because the primary failure mode we're trying to detect here
587 // is either a source code misconfiguration (which is likely kernel independent)
588 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
589 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
590
591 // Assuming fd is a valid Bpf Map file descriptor then
592 // all the following should always succeed on a 4.14+ kernel.
593 // If they somehow do fail, they'll return -1 (and set errno),
594 // which should then cause (among others) a key_size mismatch.
595 int fd_type = bpfGetFdMapType(fd);
596 int fd_key_size = bpfGetFdKeySize(fd);
597 int fd_value_size = bpfGetFdValueSize(fd);
598 int fd_max_entries = bpfGetFdMaxEntries(fd);
599 int fd_map_flags = bpfGetFdMapFlags(fd);
600
601 // DEVMAPs are readonly from the bpf program side's point of view, as such
602 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
603 int desired_map_flags = (int)mapDef.map_flags;
604 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
605 desired_map_flags |= BPF_F_RDONLY_PROG;
606
607 // The .h file enforces that this is a power of two, and page size will
608 // also always be a power of two, so this logic is actually enough to
609 // force it to be a multiple of the page size, as required by the kernel.
610 unsigned int desired_max_entries = mapDef.max_entries;
611 if (type == BPF_MAP_TYPE_RINGBUF) {
612 if (desired_max_entries < page_size) desired_max_entries = page_size;
613 }
614
615 // The following checks should *never* trigger, if one of them somehow does,
616 // it probably means a bpf .o file has been changed/replaced at runtime
617 // and bpfloader was manually rerun (normally it should only run *once*
618 // early during the boot process).
619 // Another possibility is that something is misconfigured in the code:
620 // most likely a shared map is declared twice differently.
621 // But such a change should never be checked into the source tree...
622 if ((fd_type == type) &&
623 (fd_key_size == (int)mapDef.key_size) &&
624 (fd_value_size == (int)mapDef.value_size) &&
625 (fd_max_entries == (int)desired_max_entries) &&
626 (fd_map_flags == desired_map_flags)) {
627 return true;
628 }
629
630 ALOGE("bpf map name %s mismatch: desired/found: "
631 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
632 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
633 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
634 return false;
635}
636
637static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700638 const char* prefix, const unsigned int bpfloader_ver) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700639 int ret;
640 vector<char> mdData;
641 vector<struct bpf_map_def> md;
642 vector<string> mapNames;
643 string objName = pathToObjName(string(elfPath));
644
645 ret = readSectionByName("maps", elfFile, mdData);
646 if (ret == -2) return 0; // no maps to read
647 if (ret) return ret;
648
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700649 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700650 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700651 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700652 return -1;
653 };
654
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700655 md.resize(mdData.size() / sizeof(struct bpf_map_def));
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700656
657 const char* dataPtr = mdData.data();
658 for (auto& m : md) {
Maciej Żenczykowskiacd4aa82024-08-15 15:16:48 -0700659 // Copy the structure from the ELF file and move to the next one.
660 memcpy(&m, dataPtr, sizeof(struct bpf_map_def));
661 dataPtr += sizeof(struct bpf_map_def);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700662 }
663
664 ret = getSectionSymNames(elfFile, "maps", mapNames);
665 if (ret) return ret;
666
667 unsigned kvers = kernelVersion();
668
669 for (int i = 0; i < (int)mapNames.size(); i++) {
670 if (md[i].zero != 0) abort();
671
672 if (bpfloader_ver < md[i].bpfloader_min_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000673 ALOGD("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700674 md[i].bpfloader_min_ver);
675 mapFds.push_back(unique_fd());
676 continue;
677 }
678
679 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000680 ALOGD("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700681 md[i].bpfloader_max_ver);
682 mapFds.push_back(unique_fd());
683 continue;
684 }
685
686 if (kvers < md[i].min_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000687 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700688 mapNames[i].c_str(), kvers, md[i].min_kver);
689 mapFds.push_back(unique_fd());
690 continue;
691 }
692
693 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000694 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700695 mapNames[i].c_str(), kvers, md[i].max_kver);
696 mapFds.push_back(unique_fd());
697 continue;
698 }
699
700 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
701 (md[i].ignore_on_userdebug && isUserdebug())) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000702 ALOGD("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700703 getBuildType().c_str());
704 mapFds.push_back(unique_fd());
705 continue;
706 }
707
708 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
709 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
710 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
711 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
712 (isRiscV() && md[i].ignore_on_riscv64)) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +0000713 ALOGD("skipping map %s which is ignored on %s", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700714 describeArch());
715 mapFds.push_back(unique_fd());
716 continue;
717 }
718
719 enum bpf_map_type type = md[i].type;
720 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
721 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
722 // of be approximated: ARRAY has the same userspace api, though it is not usable
723 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
724 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
725 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
726 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
727 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
728 type = BPF_MAP_TYPE_ARRAY;
729 }
730 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
731 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
732 // of be approximated: HASH has the same userspace visible api.
733 // However it cannot be used by ebpf programs in the same way.
734 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
735 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
736 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
737 // programs as being 5.4+...
738 type = BPF_MAP_TYPE_HASH;
739 }
740
741 // The .h file enforces that this is a power of two, and page size will
742 // also always be a power of two, so this logic is actually enough to
743 // force it to be a multiple of the page size, as required by the kernel.
744 unsigned int max_entries = md[i].max_entries;
745 if (type == BPF_MAP_TYPE_RINGBUF) {
746 if (max_entries < page_size) max_entries = page_size;
747 }
748
749 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
750 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000751 ALOGV("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700752 md[i].selinux_context, static_cast<int>(selinux_context),
753 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
754 }
755
756 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700757 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000758 ALOGV("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700759 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
760 }
761
762 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
763 // except that maps shared across .o's have empty <objName>
764 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
765 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
766 (md[i].shared ? "" : objName) + "_" + mapNames[i];
767 bool reuse = false;
768 unique_fd fd;
769 int saved_errno;
770
771 if (access(mapPinLoc.c_str(), F_OK) == 0) {
772 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
773 saved_errno = errno;
774 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
775 reuse = true;
776 } else {
777 union bpf_attr req = {
778 .map_type = type,
779 .key_size = md[i].key_size,
780 .value_size = md[i].value_size,
781 .max_entries = max_entries,
782 .map_flags = md[i].map_flags,
783 };
784 if (isAtLeastKernelVersion(4, 15, 0))
785 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
786 fd.reset(bpf(BPF_MAP_CREATE, req));
787 saved_errno = errno;
788 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
789 }
790
791 if (!fd.ok()) return -saved_errno;
792
793 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
794 // safety (since reuse code path is rare) run these checks even if we just created it.
795 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
796 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
797
798 if (!reuse) {
799 if (specified(selinux_context)) {
800 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
801 "tmp_map_" + objName + "_" + mapNames[i];
802 ret = bpfFdPin(fd, createLoc.c_str());
803 if (ret) {
804 int err = errno;
805 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
806 return -err;
807 }
808 ret = renameat2(AT_FDCWD, createLoc.c_str(),
809 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
810 if (ret) {
811 int err = errno;
812 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
813 err, strerror(err));
814 return -err;
815 }
816 } else {
817 ret = bpfFdPin(fd, mapPinLoc.c_str());
818 if (ret) {
819 int err = errno;
820 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
821 return -err;
822 }
823 }
824 ret = chmod(mapPinLoc.c_str(), md[i].mode);
825 if (ret) {
826 int err = errno;
827 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
828 strerror(err));
829 return -err;
830 }
831 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
832 if (ret) {
833 int err = errno;
834 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
835 ret, err, strerror(err));
836 return -err;
837 }
838 }
839
840 int mapId = bpfGetFdMapId(fd);
841 if (mapId == -1) {
842 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
843 } else {
844 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
845 }
846
847 mapFds.push_back(std::move(fd));
848 }
849
850 return ret;
851}
852
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700853static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
854 int insnIndex;
855 struct bpf_insn *insn, *insns;
856
857 insns = (struct bpf_insn*)(insnsPtr);
858
859 insnIndex = offset / sizeof(struct bpf_insn);
860 insn = &insns[insnIndex];
861
862 // Occasionally might be useful for relocation debugging, but pretty spammy
863 if (0) {
864 ALOGV("applying relo to instruction at byte offset: %llu, "
865 "insn offset %d, insn %llx",
866 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
867 }
868
869 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700870 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700871 return;
872 }
873
874 insn->imm = fd;
875 insn->src_reg = BPF_PSEUDO_MAP_FD;
876}
877
878static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
879 vector<string> mapNames;
880
881 int ret = getSectionSymNames(elfFile, "maps", mapNames);
882 if (ret) return;
883
884 for (int k = 0; k != (int)cs.size(); k++) {
885 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
886 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
887
888 for (int i = 0; i < n_rel; i++) {
889 int symIndex = ELF64_R_SYM(rel[i].r_info);
890 string symName;
891
892 ret = getSymNameByIdx(elfFile, symIndex, symName);
893 if (ret) return;
894
Maciej Żenczykowskib4bade92024-08-14 23:06:54 +0000895 // Find the map fd and apply relo
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700896 for (int j = 0; j < (int)mapNames.size(); j++) {
897 if (!mapNames[j].compare(symName)) {
898 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
899 break;
900 }
901 }
902 }
903 }
904}
905
906static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
907 const char* prefix, const unsigned int bpfloader_ver) {
908 unsigned kvers = kernelVersion();
909
910 if (!kvers) {
911 ALOGE("unable to get kernel version");
912 return -EINVAL;
913 }
914
915 string objName = pathToObjName(string(elfPath));
916
917 for (int i = 0; i < (int)cs.size(); i++) {
918 unique_fd& fd = cs[i].prog_fd;
919 int ret;
920 string name = cs[i].name;
921
922 if (!cs[i].prog_def.has_value()) {
923 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
924 return -EINVAL;
925 }
926
927 unsigned min_kver = cs[i].prog_def->min_kver;
928 unsigned max_kver = cs[i].prog_def->max_kver;
929 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
930 max_kver, kvers);
931 if (kvers < min_kver) continue;
932 if (kvers >= max_kver) continue;
933
934 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
935 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
936 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
937 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700938
939 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
940 bpfMinVer, bpfMaxVer);
941 if (bpfloader_ver < bpfMinVer) continue;
942 if (bpfloader_ver >= bpfMaxVer) continue;
943
944 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
945 (cs[i].prog_def->ignore_on_user && isUser()) ||
946 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
947 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
948 getBuildType().c_str());
949 continue;
950 }
951
952 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
953 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
954 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
955 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
956 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
957 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
958 continue;
959 }
960
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700961 if (specified(selinux_context)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000962 ALOGV("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700963 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
964 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
965 }
966
967 if (specified(pin_subdir)) {
Maciej Żenczykowski27b535a2024-08-15 19:46:46 +0000968 ALOGV("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700969 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
970 lookupPinSubdir(pin_subdir));
971 }
972
973 // strip any potential $foo suffix
974 // this can be used to provide duplicate programs
975 // conditionally loaded based on running kernel version
976 name = name.substr(0, name.find_last_of('$'));
977
978 bool reuse = false;
979 // Format of pin location is
980 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
981 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
982 objName + '_' + string(name);
983 if (access(progPinLoc.c_str(), F_OK) == 0) {
984 fd.reset(retrieveProgram(progPinLoc.c_str()));
985 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
986 (!fd.ok() ? std::strerror(errno) : "no error"));
987 reuse = true;
988 } else {
989 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
990
991 union bpf_attr req = {
992 .prog_type = cs[i].type,
993 .kern_version = kvers,
994 .license = ptr_to_u64(license.c_str()),
995 .insns = ptr_to_u64(cs[i].data.data()),
996 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
997 .log_level = 1,
998 .log_buf = ptr_to_u64(log_buf.data()),
999 .log_size = static_cast<__u32>(log_buf.size()),
Maciej Żenczykowski346831c2024-08-12 17:49:10 +00001000 .expected_attach_type = cs[i].attach_type,
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001001 };
1002 if (isAtLeastKernelVersion(4, 15, 0))
1003 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1004 fd.reset(bpf(BPF_PROG_LOAD, req));
1005
1006 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
1007 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
1008
1009 if (!fd.ok()) {
1010 vector<string> lines = android::base::Split(log_buf.data(), "\n");
1011
1012 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1013 for (const auto& line : lines) ALOGW("%s", line.c_str());
1014 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1015
1016 if (cs[i].prog_def->optional) {
1017 ALOGW("failed program is marked optional - continuing...");
1018 continue;
1019 }
1020 ALOGE("non-optional program failed to load.");
1021 }
1022 }
1023
1024 if (!fd.ok()) return fd.get();
1025
1026 if (!reuse) {
1027 if (specified(selinux_context)) {
1028 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1029 "tmp_prog_" + objName + '_' + string(name);
1030 ret = bpfFdPin(fd, createLoc.c_str());
1031 if (ret) {
1032 int err = errno;
1033 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1034 return -err;
1035 }
1036 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1037 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1038 if (ret) {
1039 int err = errno;
1040 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1041 err, strerror(err));
1042 return -err;
1043 }
1044 } else {
1045 ret = bpfFdPin(fd, progPinLoc.c_str());
1046 if (ret) {
1047 int err = errno;
1048 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1049 return -err;
1050 }
1051 }
1052 if (chmod(progPinLoc.c_str(), 0440)) {
1053 int err = errno;
1054 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1055 return -err;
1056 }
1057 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1058 (gid_t)cs[i].prog_def->gid)) {
1059 int err = errno;
1060 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1061 cs[i].prog_def->gid, err, strerror(err));
1062 return -err;
1063 }
1064 }
1065
1066 int progId = bpfGetFdProgId(fd);
1067 if (progId == -1) {
1068 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
1069 } else {
1070 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
1071 }
1072 }
1073
1074 return 0;
1075}
1076
1077int loadProg(const char* const elfPath, bool* const isCritical, const unsigned int bpfloader_ver,
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001078 const char* const prefix) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001079 vector<char> license;
1080 vector<char> critical;
1081 vector<codeSection> cs;
1082 vector<unique_fd> mapFds;
1083 int ret;
1084
1085 if (!isCritical) return -1;
1086 *isCritical = false;
1087
1088 ifstream elfFile(elfPath, ios::in | ios::binary);
1089 if (!elfFile.is_open()) return -1;
1090
1091 ret = readSectionByName("critical", elfFile, critical);
1092 *isCritical = !ret;
1093
1094 ret = readSectionByName("license", elfFile, license);
1095 if (ret) {
1096 ALOGE("Couldn't find license in %s", elfPath);
1097 return ret;
1098 } else {
1099 ALOGD("Loading %s%s ELF object %s with license %s",
1100 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
1101 elfPath, (char*)license.data());
1102 }
1103
Maciej Żenczykowski213c9222024-08-15 15:52:43 -07001104 unsigned int bpfLoaderMinVer = readSectionUint("bpfloader_min_ver", elfFile);
1105 unsigned int bpfLoaderMaxVer = readSectionUint("bpfloader_max_ver", elfFile);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001106
1107 // inclusive lower bound check
1108 if (bpfloader_ver < bpfLoaderMinVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001109 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001110 bpfloader_ver, elfPath, bpfLoaderMinVer);
1111 return 0;
1112 }
1113
1114 // exclusive upper bound check
1115 if (bpfloader_ver >= bpfLoaderMaxVer) {
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001116 ALOGD("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001117 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1118 return 0;
1119 }
1120
Maciej Żenczykowskidbdd90f2024-08-22 23:42:58 +00001121 ALOGD("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001122 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1123
Maciej Żenczykowskie666d852024-08-15 15:03:38 -07001124 ret = readCodeSections(elfFile, cs);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001125 if (ret) {
1126 ALOGE("Couldn't read all code sections in %s", elfPath);
1127 return ret;
1128 }
1129
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001130 ret = createMaps(elfPath, elfFile, mapFds, prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001131 if (ret) {
1132 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1133 return ret;
1134 }
1135
1136 for (int i = 0; i < (int)mapFds.size(); i++)
1137 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1138
1139 applyMapRelo(elfFile, mapFds, cs);
1140
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001141 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, bpfloader_ver);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001142 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1143
1144 return ret;
1145}
1146
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001147static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001148 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001149 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001150 if (errno == ENOENT) return false;
1151 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1152 abort(); // can only hit this if permissions (likely selinux) are screwed up
1153}
1154
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001155
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001156const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001157 // S+ Tethering mainline module (network_stack): tether offload
1158 {
1159 .dir = "/apex/com.android.tethering/etc/bpf/",
1160 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001161 },
1162 // T+ Tethering mainline module (shared with netd & system server)
1163 // netutils_wrapper (for iptables xt_bpf) has access to programs
1164 {
1165 .dir = "/apex/com.android.tethering/etc/bpf/netd_shared/",
1166 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001167 },
1168 // T+ Tethering mainline module (shared with netd & system server)
1169 // netutils_wrapper has no access, netd has read only access
1170 {
1171 .dir = "/apex/com.android.tethering/etc/bpf/netd_readonly/",
1172 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001173 },
1174 // T+ Tethering mainline module (shared with system server)
1175 {
1176 .dir = "/apex/com.android.tethering/etc/bpf/net_shared/",
1177 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001178 },
1179 // T+ Tethering mainline module (not shared, just network_stack)
1180 {
1181 .dir = "/apex/com.android.tethering/etc/bpf/net_private/",
1182 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001183 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001184};
1185
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001186static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001187 int retVal = 0;
1188 DIR* dir;
1189 struct dirent* ent;
1190
1191 if ((dir = opendir(location.dir)) != NULL) {
1192 while ((ent = readdir(dir)) != NULL) {
1193 string s = ent->d_name;
1194 if (!EndsWith(s, ".o")) continue;
1195
1196 string progPath(location.dir);
1197 progPath += s;
1198
1199 bool critical;
Maciej Żenczykowski4c7f59f2024-08-15 16:24:59 -07001200 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location.prefix);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001201 if (ret) {
1202 if (critical) retVal = ret;
1203 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1204 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001205 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001206 }
1207 }
1208 closedir(dir);
1209 }
1210 return retVal;
1211}
1212
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001213static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001214 if (*prefix) {
1215 mode_t prevUmask = umask(0);
1216
1217 string s = "/sys/fs/bpf/";
1218 s += prefix;
1219
1220 errno = 0;
1221 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1222 if (ret && errno != EEXIST) {
1223 const int err = errno;
1224 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1225 return -err;
1226 }
1227
1228 umask(prevUmask);
1229 }
1230 return 0;
1231}
1232
1233// Technically 'value' doesn't need to be newline terminated, but it's best
1234// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1235// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001236static int writeProcSysFile(const char *filename, const char *value) {
1237 base::unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001238 if (fd < 0) {
1239 const int err = errno;
1240 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1241 return -err;
1242 }
1243 int len = strlen(value);
1244 int v = write(fd, value, len);
1245 if (v < 0) {
1246 const int err = errno;
1247 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1248 return -err;
1249 }
1250 if (v != len) {
1251 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1252 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1253 return -EINVAL;
1254 }
1255 return 0;
1256}
1257
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001258#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001259const char * const platformBpfLoader = "/system/bin/bpfloader";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001260
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001261static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001262 char * found_blockdev = NULL;
1263 FILE * f = NULL;
1264 char buf[4096];
1265
1266 f = fopen("/proc/mounts", "re");
1267 if (!f) return 1;
1268
1269 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1270 while (fgets(buf, sizeof(buf), f)) {
1271 char * blockdev = buf;
1272 char * space = strchr(blockdev, ' ');
1273 if (!space) continue;
1274 *space = '\0';
1275 char * mntpath = space + 1;
1276 space = strchr(mntpath, ' ');
1277 if (!space) continue;
1278 *space = '\0';
1279 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1280 found_blockdev = strdup(blockdev);
1281 break;
1282 }
1283 fclose(f);
1284 f = NULL;
1285
1286 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001287 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001288
1289 f = fopen("/proc/mounts", "re");
1290 if (!f) { free(found_blockdev); return 3; }
1291
1292 while (fgets(buf, sizeof(buf), f)) {
1293 char * blockdev = buf;
1294 char * space = strchr(blockdev, ' ');
1295 if (!space) continue;
1296 *space = '\0';
1297 char * mntpath = space + 1;
1298 space = strchr(mntpath, ' ');
1299 if (!space) continue;
1300 *space = '\0';
1301 if (strcmp(blockdev, found_blockdev)) continue;
1302 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1303 char * at = strchr(mntpath, '@');
1304 if (!at) continue;
1305 char * ver = at + 1;
1306 ALOGI("Tethering APEX version %s", ver);
1307 }
1308 fclose(f);
1309 free(found_blockdev);
1310 return 0;
1311}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001312
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001313static bool hasGSM() {
1314 static string ph = base::GetProperty("gsm.current.phone-type", "");
1315 static bool gsm = (ph != "");
1316 static bool logged = false;
1317 if (!logged) {
1318 logged = true;
1319 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1320 }
1321 return gsm;
1322}
1323
1324static bool isTV() {
1325 if (hasGSM()) return false; // TVs don't do GSM
1326
1327 static string key = base::GetProperty("ro.oem.key1", "");
1328 static bool tv = StartsWith(key, "ATV00");
1329 static bool logged = false;
1330 if (!logged) {
1331 logged = true;
1332 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1333 }
1334 return tv;
1335}
1336
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001337static bool isWear() {
1338 static string wearSdkStr = base::GetProperty("ro.cw_build.wear_sdk.version", "");
1339 static int wearSdkInt = base::GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1340 static string buildChars = base::GetProperty("ro.build.characteristics", "");
1341 static vector<string> v = base::Tokenize(buildChars, ",");
1342 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1343 static bool wear = (wearSdkInt > 0) || watch;
1344 static bool logged = false;
1345 if (!logged) {
1346 logged = true;
1347 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1348 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1349 }
1350 return wear;
1351}
1352
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001353static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001354 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001355
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001356 // Any released device will have codename REL instead of a 'real' codename.
1357 // For safety: default to 'REL' so we default to unreleased=false on failure.
1358 const bool unreleased = (base::GetProperty("ro.build.version.codename", "REL") != "REL");
1359
1360 // goog/main device_api_level is bumped *way* before aosp/main api level
1361 // (the latter only gets bumped during the push of goog/main to aosp/main)
1362 //
1363 // Since we develop in AOSP, we want it to behave as if it was bumped too.
1364 //
1365 // Note that AOSP doesn't really have a good api level (for example during
1366 // early V dev cycle, it would have *all* of T, some but not all of U, and some V).
1367 // One could argue that for our purposes AOSP api level should be infinite or 10000.
1368 //
1369 // This could also cause api to be increased in goog/main or other branches,
1370 // but I can't imagine a case where this would be a problem: the problem
1371 // is rather a too low api level, rather than some ill defined high value.
1372 // For example as I write this aosp is 34/U, and goog is 35/V,
1373 // we want to treat both goog & aosp as 35/V, but it's harmless if we
1374 // treat goog as 36 because that value isn't yet defined to mean anything,
1375 // and we thus never compare against it.
1376 //
1377 // Also note that 'android_get_device_api_level()' is what the
1378 // //system/core/init/apex_init_util.cpp
1379 // apex init .XXrc parsing code uses for XX filtering.
1380 //
1381 // That code has a hack to bump <35 to 35 (to force aosp/main to parse .35rc),
1382 // but could (should?) perhaps be adjusted to match this.
1383 const int effective_api_level = android_get_device_api_level() + (int)unreleased;
1384 const bool isAtLeastT = (effective_api_level >= __ANDROID_API_T__);
1385 const bool isAtLeastU = (effective_api_level >= __ANDROID_API_U__);
1386 const bool isAtLeastV = (effective_api_level >= __ANDROID_API_V__);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001387
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001388 // last in U QPR2 beta1
1389 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1390 // first in U QPR2 beta~2
1391 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1392
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001393 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001394 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
1395 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1396 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1397 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1398 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001399
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001400 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) uid:%d rc:%d%d",
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001401 bpfloader_ver, argv[0], android_get_device_api_level(), effective_api_level,
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001402 kernelVersion(), describeArch(), getuid(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001403 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001404
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001405 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1406 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1407 return 1;
1408 }
1409
1410 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1411 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1412 return 1;
1413 }
1414
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001415 logTetheringApexVersion();
1416
Maciej Żenczykowski11141da2024-03-15 18:21:33 -07001417 if (!isAtLeastT) {
1418 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001419 return 1;
1420 }
1421
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001422 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001423 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001424 ALOGE("Android T requires kernel 4.9.");
1425 return 1;
1426 }
1427
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001428 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001429 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001430 ALOGE("Android U requires kernel 4.14.");
1431 return 1;
1432 }
1433
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001434 // V bumps the kernel requirement up to 4.19
1435 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001436 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001437 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001438 return 1;
1439 }
1440
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001441 // Technically already required by U, but only enforce on V+
1442 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1443 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1444 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1445 if (!isTV()) return 1;
1446 }
1447
1448 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1449 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001450 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001451 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001452 }
1453
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001454 if (isAtLeastV) {
1455 bool bad = false;
1456
1457 if (!isLtsKernel()) {
1458 ALOGW("Android V only supports LTS kernels.");
1459 bad = true;
1460 }
1461
1462#define REQUIRE(maj, min, sub) \
1463 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
1464 ALOGW("Android V requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
1465 bad = true; \
1466 }
1467
1468 REQUIRE(4, 19, 236)
1469 REQUIRE(5, 4, 186)
1470 REQUIRE(5, 10, 199)
1471 REQUIRE(5, 15, 136)
1472 REQUIRE(6, 1, 57)
1473 REQUIRE(6, 6, 0)
1474
1475#undef REQUIRE
1476
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001477 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001478 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1479 }
1480 }
1481
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001482 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001483 /* Android 14/U should only launch on 64-bit kernels
1484 * T launches on 5.10/5.15
1485 * U launches on 5.15/6.1
1486 * So >=5.16 implies isKernel64Bit()
1487 *
1488 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1489 *
1490 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1491 * we also require 64-bit userspace.
1492 *
1493 * There are various known issues with 32-bit userspace talking to various
1494 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1495 * Some of these have userspace or kernel workarounds/hacks.
1496 * Some of them don't...
1497 * We're going to be removing the hacks.
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001498 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1499 * Note: this check/enforcement only applies to *system* userspace code,
1500 * it does not affect unprivileged apps, the 32-on-64 compatibility
1501 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001502 *
1503 * Additionally the 32-bit kernel jit support is poor,
1504 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
1505 */
1506 ALOGE("64-bit userspace required on 6.2+ kernels.");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001507 // Stuff won't work reliably, but exempt TVs & Arm Wear devices
1508 if (!isTV() && !(isWear() && isArm())) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001509 }
1510
1511 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001512 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001513 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001514 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001515 return 1;
1516 }
1517
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001518 if (runningAsRoot) {
1519 // Note: writing this proc file requires being root (always the case on V+)
1520
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001521 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1522 // but we need 0 (enabled)
1523 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1524 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1525 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001526 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001527 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001528
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001529 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001530 // Note: writing these proc files requires CAP_NET_ADMIN
1531 // and sepolicy which is only present on U+,
1532 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1533 // trigger (ie. by init itself) instead.
1534
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001535 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1536 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1537 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1538 // kernel does not have CONFIG_BPF_JIT=y)
1539 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1540 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1541 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001542
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001543 // Enable JIT kallsyms export for privileged users only
1544 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1545 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1546 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1547 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001548
1549 // Create all the pin subdirectories
1550 // (this must be done first to allow selinux_context and pin_subdir functionality,
1551 // which could otherwise fail with ENOENT during object pinning or renaming,
1552 // due to ordering issues)
1553 for (const auto& location : locations) {
1554 if (createSysFsBpfSubDir(location.prefix)) return 1;
1555 }
1556
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001557 // Note: there's no actual src dir for fs_bpf_loader .o's,
1558 // so it is not listed in 'locations[].prefix'.
1559 // This is because this is primarily meant for triggering genfscon rules,
1560 // and as such this will likely always be the case.
1561 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1562 if (createSysFsBpfSubDir("loader")) return 1;
1563
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001564 // Load all ELF objects, create programs and maps, and pin them
1565 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001566 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001567 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1568 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1569 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1570 "problems or startup script race.");
1571 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1572 sleep(20);
1573 return 2;
1574 }
1575 }
1576
1577 int key = 1;
1578 int value = 123;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001579 base::unique_fd map(
1580 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1581 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001582 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1583 return 1;
1584 }
1585
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001586 // leave a flag that we're done
1587 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001588
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001589 // platform bpfloader will only succeed when run as root
1590 if (!runningAsRoot) {
1591 // unreachable on U QPR3+ which always runs netbpfload as root
1592
1593 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1594 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001595 }
1596
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001597 // unreachable before U QPR3
1598 ALOGI("done, transferring control to platform bpfloader.");
1599
1600 // platform BpfLoader *needs* to run as root
1601 const char * args[] = { platformBpfLoader, NULL, };
1602 execve(args[0], (char**)args, envp);
1603 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1604 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001605}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001606
1607} // namespace bpf
1608} // namespace android
1609
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001610int main(int argc, char** argv, char * const envp[]) {
1611 android::base::InitLogging(argv, &android::base::KernelLogger);
1612
1613 if (argc == 2 && !strcmp(argv[1], "done")) {
1614 // we're being re-exec'ed from platform bpfloader to 'finalize' things
1615 if (!android::base::SetProperty("bpf.progs_loaded", "1")) {
1616 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1617 return 125;
1618 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001619 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001620 return 0;
1621 }
1622
1623 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001624}