blob: 8b539aa7c99677ebee1a680d0f52a2d171cdff90 [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>
20#include <cstdlib>
21#include <dirent.h>
22#include <elf.h>
23#include <errno.h>
24#include <error.h>
25#include <fcntl.h>
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070026#include <fstream>
Maciej Żenczykowski49140b92024-08-07 15:06:07 -070027#include <inttypes.h>
28#include <iostream>
29#include <linux/bpf.h>
30#include <linux/elf.h>
31#include <linux/unistd.h>
32#include <log/log.h>
33#include <net/if.h>
34#include <optional>
35#include <stdint.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <string>
40#include <sys/mman.h>
41#include <sys/socket.h>
42#include <sys/stat.h>
43#include <sys/types.h>
44#include <sys/utsname.h>
45#include <sys/wait.h>
46#include <sysexits.h>
47#include <unistd.h>
48#include <unordered_map>
49#include <vector>
50
51#include <android-base/cmsg.h>
52#include <android-base/file.h>
53#include <android-base/logging.h>
54#include <android-base/macros.h>
55#include <android-base/properties.h>
56#include <android-base/stringprintf.h>
57#include <android-base/strings.h>
58#include <android-base/unique_fd.h>
59#include <android/api-level.h>
60
61#include "BpfSyscallWrappers.h"
62#include "bpf/BpfUtils.h"
63#include "bpf/bpf_map_def.h"
64
65using android::base::EndsWith;
66using android::base::StartsWith;
67using android::base::unique_fd;
68using std::ifstream;
69using std::ios;
70using std::optional;
71using std::string;
72using std::vector;
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070073
74namespace android {
75namespace bpf {
76
77// Bpf programs may specify per-program & per-map selinux_context and pin_subdir.
78//
79// The BpfLoader needs to convert these bpf.o specified strings into an enum
80// for internal use (to check that valid values were specified for the specific
81// location of the bpf.o file).
82//
83// It also needs to map selinux_context's into pin_subdir's.
84// This is because of how selinux_context is actually implemented via pin+rename.
85//
86// Thus 'domain' enumerates all selinux_context's/pin_subdir's that the BpfLoader
87// is aware of. Thus there currently needs to be a 1:1 mapping between the two.
88//
89enum class domain : int {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070090 unspecified = 0, // means just use the default for that specific pin location
91 tethering, // (S+) fs_bpf_tethering /sys/fs/bpf/tethering
92 net_private, // (T+) fs_bpf_net_private /sys/fs/bpf/net_private
93 net_shared, // (T+) fs_bpf_net_shared /sys/fs/bpf/net_shared
94 netd_readonly, // (T+) fs_bpf_netd_readonly /sys/fs/bpf/netd_readonly
95 netd_shared, // (T+) fs_bpf_netd_shared /sys/fs/bpf/netd_shared
96};
97
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -070098static constexpr domain AllDomains[] = {
99 domain::unspecified,
100 domain::tethering,
101 domain::net_private,
102 domain::net_shared,
103 domain::netd_readonly,
104 domain::netd_shared,
105};
106
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700107static constexpr bool specified(domain d) {
108 return d != domain::unspecified;
109}
110
111struct Location {
112 const char* const dir = "";
113 const char* const prefix = "";
114};
115
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700116// Returns the build type string (from ro.build.type).
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700117const std::string& getBuildType() {
118 static std::string t = android::base::GetProperty("ro.build.type", "unknown");
119 return t;
120}
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700121
122// The following functions classify the 3 Android build types.
123inline bool isEng() {
124 return getBuildType() == "eng";
125}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700126
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700127inline bool isUser() {
128 return getBuildType() == "user";
129}
Maciej Żenczykowski49140b92024-08-07 15:06:07 -0700130
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700131inline bool isUserdebug() {
132 return getBuildType() == "userdebug";
133}
134
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700135#define BPF_FS_PATH "/sys/fs/bpf/"
136
137// Size of the BPF log buffer for verifier logging
138#define BPF_LOAD_LOG_SZ 0xfffff
139
140// Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
141#define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
142
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700143static unsigned int page_size = static_cast<unsigned int>(getpagesize());
144
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700145constexpr const char* lookupSelinuxContext(const domain d) {
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700146 switch (d) {
Maciej Żenczykowskid9fa1c02024-08-07 15:46:11 -0700147 case domain::unspecified: return "";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700148 case domain::tethering: return "fs_bpf_tethering";
149 case domain::net_private: return "fs_bpf_net_private";
150 case domain::net_shared: return "fs_bpf_net_shared";
151 case domain::netd_readonly: return "fs_bpf_netd_readonly";
152 case domain::netd_shared: return "fs_bpf_netd_shared";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700153 }
154}
155
156domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
157 for (domain d : AllDomains) {
158 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
159 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
160 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
161 }
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700162 ALOGE("unrecognized selinux_context '%-32s'", s);
163 // Note: we *can* just abort() here as we only load bpf .o files shipped
164 // in the same mainline module / apex as NetBpfLoad itself.
165 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700166}
167
168constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
169 switch (d) {
170 case domain::unspecified: return unspecified;
171 case domain::tethering: return "tethering/";
172 case domain::net_private: return "net_private/";
173 case domain::net_shared: return "net_shared/";
174 case domain::netd_readonly: return "netd_readonly/";
175 case domain::netd_shared: return "netd_shared/";
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700176 }
177};
178
179domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
180 for (domain d : AllDomains) {
181 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
182 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
183 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
184 }
185 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski6641f2f2024-08-07 15:34:24 -0700186 // Note: we *can* just abort() here as we only load bpf .o files shipped
187 // in the same mainline module / apex as NetBpfLoad itself.
188 abort();
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700189}
190
191static string pathToObjName(const string& path) {
192 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
193 string filename = android::base::Split(path, "/").back();
194 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
195 string name = filename.substr(0, filename.find_last_of('.'));
196 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
197 // this can be used to provide duplicate programs (mux based on the bpfloader version)
198 return name.substr(0, name.find_last_of('@'));
199}
200
201typedef struct {
202 const char* name;
203 enum bpf_prog_type type;
204 enum bpf_attach_type expected_attach_type;
205} sectionType;
206
207/*
208 * Map section name prefixes to program types, the section name will be:
209 * SECTION(<prefix>/<name-of-program>)
210 * For example:
211 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
212 * is the name of the program, and tracepoint is the type.
213 *
214 * However, be aware that you should not be directly using the SECTION() macro.
215 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
216 *
217 * Programs shipped inside the tethering apex should be limited to networking stuff,
218 * as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
219 * since they are less stable abi/api and may conflict with platform uses of bpf.
220 */
221sectionType sectionNameTypes[] = {
222 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
223 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
224 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB, BPF_ATTACH_TYPE_UNSPEC},
225 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_ATTACH_TYPE_UNSPEC},
226 {"cgroupsockcreate/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE},
227 {"cgroupsockrelease/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE},
228 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
229 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
230 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
231 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
232 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
233 {"lwt_in/", BPF_PROG_TYPE_LWT_IN, BPF_ATTACH_TYPE_UNSPEC},
234 {"lwt_out/", BPF_PROG_TYPE_LWT_OUT, BPF_ATTACH_TYPE_UNSPEC},
235 {"lwt_seg6local/", BPF_PROG_TYPE_LWT_SEG6LOCAL, BPF_ATTACH_TYPE_UNSPEC},
236 {"lwt_xmit/", BPF_PROG_TYPE_LWT_XMIT, BPF_ATTACH_TYPE_UNSPEC},
237 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
238 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
239 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
240 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
241 {"schedact/", BPF_PROG_TYPE_SCHED_ACT, BPF_ATTACH_TYPE_UNSPEC},
242 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS, BPF_ATTACH_TYPE_UNSPEC},
243 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
244 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
245 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
246 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
247 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
248 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
249 {"xdp/", BPF_PROG_TYPE_XDP, BPF_ATTACH_TYPE_UNSPEC},
250};
251
252typedef struct {
253 enum bpf_prog_type type;
254 enum bpf_attach_type expected_attach_type;
255 string name;
256 vector<char> data;
257 vector<char> rel_data;
258 optional<struct bpf_prog_def> prog_def;
259
260 unique_fd prog_fd; /* fd after loading */
261} codeSection;
262
263static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
264 elfFile.seekg(0);
265 if (elfFile.fail()) return -1;
266
267 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
268
269 return 0;
270}
271
272/* Reads all section header tables into an Shdr array */
273static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
274 Elf64_Ehdr eh;
275 int ret = 0;
276
277 ret = readElfHeader(elfFile, &eh);
278 if (ret) return ret;
279
280 elfFile.seekg(eh.e_shoff);
281 if (elfFile.fail()) return -1;
282
283 /* Read shdr table entries */
284 shTable.resize(eh.e_shnum);
285
286 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
287
288 return 0;
289}
290
291/* Read a section by its index - for ex to get sec hdr strtab blob */
292static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
293 vector<Elf64_Shdr> shTable;
294 int ret = readSectionHeadersAll(elfFile, shTable);
295 if (ret) return ret;
296
297 elfFile.seekg(shTable[id].sh_offset);
298 if (elfFile.fail()) return -1;
299
300 sec.resize(shTable[id].sh_size);
301 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
302
303 return 0;
304}
305
306/* Read whole section header string table */
307static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
308 Elf64_Ehdr eh;
309 int ret = readElfHeader(elfFile, &eh);
310 if (ret) return ret;
311
312 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
313 if (ret) return ret;
314
315 return 0;
316}
317
318/* Get name from offset in strtab */
319static int getSymName(ifstream& elfFile, int nameOff, string& name) {
320 int ret;
321 vector<char> secStrTab;
322
323 ret = readSectionHeaderStrtab(elfFile, secStrTab);
324 if (ret) return ret;
325
326 if (nameOff >= (int)secStrTab.size()) return -1;
327
328 name = string((char*)secStrTab.data() + nameOff);
329 return 0;
330}
331
332/* Reads a full section by name - example to get the GPL license */
333static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
334 vector<char> secStrTab;
335 vector<Elf64_Shdr> shTable;
336 int ret;
337
338 ret = readSectionHeadersAll(elfFile, shTable);
339 if (ret) return ret;
340
341 ret = readSectionHeaderStrtab(elfFile, secStrTab);
342 if (ret) return ret;
343
344 for (int i = 0; i < (int)shTable.size(); i++) {
345 char* secname = secStrTab.data() + shTable[i].sh_name;
346 if (!secname) continue;
347
348 if (!strcmp(secname, name)) {
349 vector<char> dataTmp;
350 dataTmp.resize(shTable[i].sh_size);
351
352 elfFile.seekg(shTable[i].sh_offset);
353 if (elfFile.fail()) return -1;
354
355 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
356
357 data = dataTmp;
358 return 0;
359 }
360 }
361 return -2;
362}
363
364unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
365 vector<char> theBytes;
366 int ret = readSectionByName(name, elfFile, theBytes);
367 if (ret) {
368 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
369 return defVal;
370 } else if (theBytes.size() < sizeof(unsigned int)) {
371 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
372 return defVal;
373 } else {
374 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
375 unsigned int value = static_cast<unsigned char>(theBytes[3]);
376 value <<= 8;
377 value += static_cast<unsigned char>(theBytes[2]);
378 value <<= 8;
379 value += static_cast<unsigned char>(theBytes[1]);
380 value <<= 8;
381 value += static_cast<unsigned char>(theBytes[0]);
382 ALOGI("Section %s value is %u [0x%x]", name, value, value);
383 return value;
384 }
385}
386
387static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
388 int ret;
389 vector<Elf64_Shdr> shTable;
390
391 ret = readSectionHeadersAll(elfFile, shTable);
392 if (ret) return ret;
393
394 for (int i = 0; i < (int)shTable.size(); i++) {
395 if ((int)shTable[i].sh_type != type) continue;
396
397 vector<char> dataTmp;
398 dataTmp.resize(shTable[i].sh_size);
399
400 elfFile.seekg(shTable[i].sh_offset);
401 if (elfFile.fail()) return -1;
402
403 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
404
405 data = dataTmp;
406 return 0;
407 }
408 return -2;
409}
410
411static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
412 return (a.st_value < b.st_value);
413}
414
415static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
416 int ret, numElems;
417 Elf64_Sym* buf;
418 vector<char> secData;
419
420 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
421 if (ret) return ret;
422
423 buf = (Elf64_Sym*)secData.data();
424 numElems = (secData.size() / sizeof(Elf64_Sym));
425 data.assign(buf, buf + numElems);
426
427 if (sort) std::sort(data.begin(), data.end(), symCompare);
428 return 0;
429}
430
431static enum bpf_prog_type getSectionType(string& name) {
432 for (auto& snt : sectionNameTypes)
433 if (StartsWith(name, snt.name)) return snt.type;
434
435 return BPF_PROG_TYPE_UNSPEC;
436}
437
438static enum bpf_attach_type getExpectedAttachType(string& name) {
439 for (auto& snt : sectionNameTypes)
440 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
441 return BPF_ATTACH_TYPE_UNSPEC;
442}
443
444/*
445static string getSectionName(enum bpf_prog_type type)
446{
447 for (auto& snt : sectionNameTypes)
448 if (snt.type == type)
449 return string(snt.name);
450
451 return "UNKNOWN SECTION NAME " + std::to_string(type);
452}
453*/
454
455static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
456 size_t sizeOfBpfProgDef) {
457 vector<char> pdData;
458 int ret = readSectionByName("progs", elfFile, pdData);
459 if (ret) return ret;
460
461 if (pdData.size() % sizeOfBpfProgDef) {
462 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
463 pdData.size(), sizeOfBpfProgDef);
464 return -1;
465 };
466
467 int progCount = pdData.size() / sizeOfBpfProgDef;
468 pd.resize(progCount);
469 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
470
471 const char* dataPtr = pdData.data();
472 for (auto& p : pd) {
473 // First we zero initialize
474 memset(&p, 0, sizeof(p));
475 // Then we set non-zero defaults
476 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
477 // Then we copy over the structure prefix from the ELF file.
478 memcpy(&p, dataPtr, trimmedSize);
479 // Move to next struct in the ELF file
480 dataPtr += sizeOfBpfProgDef;
481 }
482 return 0;
483}
484
485static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
486 optional<unsigned> symbolType = std::nullopt) {
487 int ret;
488 string name;
489 vector<Elf64_Sym> symtab;
490 vector<Elf64_Shdr> shTable;
491
492 ret = readSymTab(elfFile, 1 /* sort */, symtab);
493 if (ret) return ret;
494
495 /* Get index of section */
496 ret = readSectionHeadersAll(elfFile, shTable);
497 if (ret) return ret;
498
499 int sec_idx = -1;
500 for (int i = 0; i < (int)shTable.size(); i++) {
501 ret = getSymName(elfFile, shTable[i].sh_name, name);
502 if (ret) return ret;
503
504 if (!name.compare(sectionName)) {
505 sec_idx = i;
506 break;
507 }
508 }
509
510 /* No section found with matching name*/
511 if (sec_idx == -1) {
512 ALOGW("No %s section could be found in elf object", sectionName.c_str());
513 return -1;
514 }
515
516 for (int i = 0; i < (int)symtab.size(); i++) {
517 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
518
519 if (symtab[i].st_shndx == sec_idx) {
520 string s;
521 ret = getSymName(elfFile, symtab[i].st_name, s);
522 if (ret) return ret;
523 names.push_back(s);
524 }
525 }
526
527 return 0;
528}
529
530/* Read a section by its index - for ex to get sec hdr strtab blob */
531static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef) {
532 vector<Elf64_Shdr> shTable;
533 int entries, ret = 0;
534
535 ret = readSectionHeadersAll(elfFile, shTable);
536 if (ret) return ret;
537 entries = shTable.size();
538
539 vector<struct bpf_prog_def> pd;
540 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
541 if (ret) return ret;
542 vector<string> progDefNames;
543 ret = getSectionSymNames(elfFile, "progs", progDefNames);
544 if (!pd.empty() && ret) return ret;
545
546 for (int i = 0; i < entries; i++) {
547 string name;
548 codeSection cs_temp;
549 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
550
551 ret = getSymName(elfFile, shTable[i].sh_name, name);
552 if (ret) return ret;
553
554 enum bpf_prog_type ptype = getSectionType(name);
555
556 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
557
558 // This must be done before '/' is replaced with '_'.
559 cs_temp.expected_attach_type = getExpectedAttachType(name);
560
561 string oldName = name;
562
563 // convert all slashes to underscores
564 std::replace(name.begin(), name.end(), '/', '_');
565
566 cs_temp.type = ptype;
567 cs_temp.name = name;
568
569 ret = readSectionByIdx(elfFile, i, cs_temp.data);
570 if (ret) return ret;
571 ALOGV("Loaded code section %d (%s)", i, name.c_str());
572
573 vector<string> csSymNames;
574 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
575 if (ret || !csSymNames.size()) return ret;
576 for (size_t i = 0; i < progDefNames.size(); ++i) {
577 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
578 cs_temp.prog_def = pd[i];
579 break;
580 }
581 }
582
583 /* Check for rel section */
584 if (cs_temp.data.size() > 0 && i < entries) {
585 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
586 if (ret) return ret;
587
588 if (name == (".rel" + oldName)) {
589 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
590 if (ret) return ret;
591 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
592 }
593 }
594
595 if (cs_temp.data.size() > 0) {
596 cs.push_back(std::move(cs_temp));
597 ALOGV("Adding section %d to cs list", i);
598 }
599 }
600 return 0;
601}
602
603static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
604 vector<Elf64_Sym> symtab;
605 int ret = 0;
606
607 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
608 if (ret) return ret;
609
610 if (index >= (int)symtab.size()) return -1;
611
612 return getSymName(elfFile, symtab[index].st_name, name);
613}
614
615static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
616 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
617 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
618 // so on 4.9-T kernels just pretend the map matches our expectations.
619 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
620 // This is because the primary failure mode we're trying to detect here
621 // is either a source code misconfiguration (which is likely kernel independent)
622 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
623 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
624
625 // Assuming fd is a valid Bpf Map file descriptor then
626 // all the following should always succeed on a 4.14+ kernel.
627 // If they somehow do fail, they'll return -1 (and set errno),
628 // which should then cause (among others) a key_size mismatch.
629 int fd_type = bpfGetFdMapType(fd);
630 int fd_key_size = bpfGetFdKeySize(fd);
631 int fd_value_size = bpfGetFdValueSize(fd);
632 int fd_max_entries = bpfGetFdMaxEntries(fd);
633 int fd_map_flags = bpfGetFdMapFlags(fd);
634
635 // DEVMAPs are readonly from the bpf program side's point of view, as such
636 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
637 int desired_map_flags = (int)mapDef.map_flags;
638 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
639 desired_map_flags |= BPF_F_RDONLY_PROG;
640
641 // The .h file enforces that this is a power of two, and page size will
642 // also always be a power of two, so this logic is actually enough to
643 // force it to be a multiple of the page size, as required by the kernel.
644 unsigned int desired_max_entries = mapDef.max_entries;
645 if (type == BPF_MAP_TYPE_RINGBUF) {
646 if (desired_max_entries < page_size) desired_max_entries = page_size;
647 }
648
649 // The following checks should *never* trigger, if one of them somehow does,
650 // it probably means a bpf .o file has been changed/replaced at runtime
651 // and bpfloader was manually rerun (normally it should only run *once*
652 // early during the boot process).
653 // Another possibility is that something is misconfigured in the code:
654 // most likely a shared map is declared twice differently.
655 // But such a change should never be checked into the source tree...
656 if ((fd_type == type) &&
657 (fd_key_size == (int)mapDef.key_size) &&
658 (fd_value_size == (int)mapDef.value_size) &&
659 (fd_max_entries == (int)desired_max_entries) &&
660 (fd_map_flags == desired_map_flags)) {
661 return true;
662 }
663
664 ALOGE("bpf map name %s mismatch: desired/found: "
665 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
666 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
667 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
668 return false;
669}
670
671static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
672 const char* prefix, const size_t sizeOfBpfMapDef,
673 const unsigned int bpfloader_ver) {
674 int ret;
675 vector<char> mdData;
676 vector<struct bpf_map_def> md;
677 vector<string> mapNames;
678 string objName = pathToObjName(string(elfPath));
679
680 ret = readSectionByName("maps", elfFile, mdData);
681 if (ret == -2) return 0; // no maps to read
682 if (ret) return ret;
683
684 if (mdData.size() % sizeOfBpfMapDef) {
685 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
686 mdData.size(), sizeOfBpfMapDef);
687 return -1;
688 };
689
690 int mapCount = mdData.size() / sizeOfBpfMapDef;
691 md.resize(mapCount);
692 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
693
694 const char* dataPtr = mdData.data();
695 for (auto& m : md) {
696 // First we zero initialize
697 memset(&m, 0, sizeof(m));
698 // Then we set non-zero defaults
699 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
700 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
701 // Then we copy over the structure prefix from the ELF file.
702 memcpy(&m, dataPtr, trimmedSize);
703 // Move to next struct in the ELF file
704 dataPtr += sizeOfBpfMapDef;
705 }
706
707 ret = getSectionSymNames(elfFile, "maps", mapNames);
708 if (ret) return ret;
709
710 unsigned kvers = kernelVersion();
711
712 for (int i = 0; i < (int)mapNames.size(); i++) {
713 if (md[i].zero != 0) abort();
714
715 if (bpfloader_ver < md[i].bpfloader_min_ver) {
716 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
717 md[i].bpfloader_min_ver);
718 mapFds.push_back(unique_fd());
719 continue;
720 }
721
722 if (bpfloader_ver >= md[i].bpfloader_max_ver) {
723 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
724 md[i].bpfloader_max_ver);
725 mapFds.push_back(unique_fd());
726 continue;
727 }
728
729 if (kvers < md[i].min_kver) {
730 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
731 mapNames[i].c_str(), kvers, md[i].min_kver);
732 mapFds.push_back(unique_fd());
733 continue;
734 }
735
736 if (kvers >= md[i].max_kver) {
737 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
738 mapNames[i].c_str(), kvers, md[i].max_kver);
739 mapFds.push_back(unique_fd());
740 continue;
741 }
742
743 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
744 (md[i].ignore_on_userdebug && isUserdebug())) {
745 ALOGI("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
746 getBuildType().c_str());
747 mapFds.push_back(unique_fd());
748 continue;
749 }
750
751 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
752 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
753 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
754 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
755 (isRiscV() && md[i].ignore_on_riscv64)) {
756 ALOGI("skipping map %s which is ignored on %s", mapNames[i].c_str(),
757 describeArch());
758 mapFds.push_back(unique_fd());
759 continue;
760 }
761
762 enum bpf_map_type type = md[i].type;
763 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
764 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
765 // of be approximated: ARRAY has the same userspace api, though it is not usable
766 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
767 // helper doesn't exist on 4.9-T anyway (so the bpf program would fail to load,
768 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
769 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
770 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
771 type = BPF_MAP_TYPE_ARRAY;
772 }
773 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
774 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
775 // of be approximated: HASH has the same userspace visible api.
776 // However it cannot be used by ebpf programs in the same way.
777 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
778 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
779 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
780 // programs as being 5.4+...
781 type = BPF_MAP_TYPE_HASH;
782 }
783
784 // The .h file enforces that this is a power of two, and page size will
785 // also always be a power of two, so this logic is actually enough to
786 // force it to be a multiple of the page size, as required by the kernel.
787 unsigned int max_entries = md[i].max_entries;
788 if (type == BPF_MAP_TYPE_RINGBUF) {
789 if (max_entries < page_size) max_entries = page_size;
790 }
791
792 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
793 if (specified(selinux_context)) {
794 ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
795 md[i].selinux_context, static_cast<int>(selinux_context),
796 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
797 }
798
799 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -0700800 if (specified(pin_subdir)) {
801 ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
802 static_cast<int>(pin_subdir), lookupPinSubdir(pin_subdir));
803 }
804
805 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
806 // except that maps shared across .o's have empty <objName>
807 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
808 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
809 (md[i].shared ? "" : objName) + "_" + mapNames[i];
810 bool reuse = false;
811 unique_fd fd;
812 int saved_errno;
813
814 if (access(mapPinLoc.c_str(), F_OK) == 0) {
815 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
816 saved_errno = errno;
817 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
818 reuse = true;
819 } else {
820 union bpf_attr req = {
821 .map_type = type,
822 .key_size = md[i].key_size,
823 .value_size = md[i].value_size,
824 .max_entries = max_entries,
825 .map_flags = md[i].map_flags,
826 };
827 if (isAtLeastKernelVersion(4, 15, 0))
828 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
829 fd.reset(bpf(BPF_MAP_CREATE, req));
830 saved_errno = errno;
831 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
832 }
833
834 if (!fd.ok()) return -saved_errno;
835
836 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
837 // safety (since reuse code path is rare) run these checks even if we just created it.
838 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
839 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
840
841 if (!reuse) {
842 if (specified(selinux_context)) {
843 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
844 "tmp_map_" + objName + "_" + mapNames[i];
845 ret = bpfFdPin(fd, createLoc.c_str());
846 if (ret) {
847 int err = errno;
848 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
849 return -err;
850 }
851 ret = renameat2(AT_FDCWD, createLoc.c_str(),
852 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
853 if (ret) {
854 int err = errno;
855 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
856 err, strerror(err));
857 return -err;
858 }
859 } else {
860 ret = bpfFdPin(fd, mapPinLoc.c_str());
861 if (ret) {
862 int err = errno;
863 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
864 return -err;
865 }
866 }
867 ret = chmod(mapPinLoc.c_str(), md[i].mode);
868 if (ret) {
869 int err = errno;
870 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
871 strerror(err));
872 return -err;
873 }
874 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
875 if (ret) {
876 int err = errno;
877 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
878 ret, err, strerror(err));
879 return -err;
880 }
881 }
882
883 int mapId = bpfGetFdMapId(fd);
884 if (mapId == -1) {
885 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
886 } else {
887 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
888 }
889
890 mapFds.push_back(std::move(fd));
891 }
892
893 return ret;
894}
895
896/* For debugging, dump all instructions */
897static void dumpIns(char* ins, int size) {
898 for (int row = 0; row < size / 8; row++) {
899 ALOGE("%d: ", row);
900 for (int j = 0; j < 8; j++) {
901 ALOGE("%3x ", ins[(row * 8) + j]);
902 }
903 ALOGE("\n");
904 }
905}
906
907/* For debugging, dump all code sections from cs list */
908static void dumpAllCs(vector<codeSection>& cs) {
909 for (int i = 0; i < (int)cs.size(); i++) {
910 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
911 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
912 ALOGE("-----------");
913 }
914}
915
916static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
917 int insnIndex;
918 struct bpf_insn *insn, *insns;
919
920 insns = (struct bpf_insn*)(insnsPtr);
921
922 insnIndex = offset / sizeof(struct bpf_insn);
923 insn = &insns[insnIndex];
924
925 // Occasionally might be useful for relocation debugging, but pretty spammy
926 if (0) {
927 ALOGV("applying relo to instruction at byte offset: %llu, "
928 "insn offset %d, insn %llx",
929 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
930 }
931
932 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
933 ALOGE("Dumping all instructions till ins %d", insnIndex);
934 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
935 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
936 return;
937 }
938
939 insn->imm = fd;
940 insn->src_reg = BPF_PSEUDO_MAP_FD;
941}
942
943static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
944 vector<string> mapNames;
945
946 int ret = getSectionSymNames(elfFile, "maps", mapNames);
947 if (ret) return;
948
949 for (int k = 0; k != (int)cs.size(); k++) {
950 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
951 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
952
953 for (int i = 0; i < n_rel; i++) {
954 int symIndex = ELF64_R_SYM(rel[i].r_info);
955 string symName;
956
957 ret = getSymNameByIdx(elfFile, symIndex, symName);
958 if (ret) return;
959
960 /* Find the map fd and apply relo */
961 for (int j = 0; j < (int)mapNames.size(); j++) {
962 if (!mapNames[j].compare(symName)) {
963 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
964 break;
965 }
966 }
967 }
968 }
969}
970
971static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
972 const char* prefix, const unsigned int bpfloader_ver) {
973 unsigned kvers = kernelVersion();
974
975 if (!kvers) {
976 ALOGE("unable to get kernel version");
977 return -EINVAL;
978 }
979
980 string objName = pathToObjName(string(elfPath));
981
982 for (int i = 0; i < (int)cs.size(); i++) {
983 unique_fd& fd = cs[i].prog_fd;
984 int ret;
985 string name = cs[i].name;
986
987 if (!cs[i].prog_def.has_value()) {
988 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
989 return -EINVAL;
990 }
991
992 unsigned min_kver = cs[i].prog_def->min_kver;
993 unsigned max_kver = cs[i].prog_def->max_kver;
994 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
995 max_kver, kvers);
996 if (kvers < min_kver) continue;
997 if (kvers >= max_kver) continue;
998
999 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1000 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1001 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1002 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001003
1004 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
1005 bpfMinVer, bpfMaxVer);
1006 if (bpfloader_ver < bpfMinVer) continue;
1007 if (bpfloader_ver >= bpfMaxVer) continue;
1008
1009 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1010 (cs[i].prog_def->ignore_on_user && isUser()) ||
1011 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1012 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1013 getBuildType().c_str());
1014 continue;
1015 }
1016
1017 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
1018 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
1019 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
1020 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
1021 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
1022 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
1023 continue;
1024 }
1025
Maciej Żenczykowski6e1b4252024-08-07 15:03:44 -07001026 if (specified(selinux_context)) {
1027 ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
1028 cs[i].prog_def->selinux_context, static_cast<int>(selinux_context),
1029 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1030 }
1031
1032 if (specified(pin_subdir)) {
1033 ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
1034 cs[i].prog_def->pin_subdir, static_cast<int>(pin_subdir),
1035 lookupPinSubdir(pin_subdir));
1036 }
1037
1038 // strip any potential $foo suffix
1039 // this can be used to provide duplicate programs
1040 // conditionally loaded based on running kernel version
1041 name = name.substr(0, name.find_last_of('$'));
1042
1043 bool reuse = false;
1044 // Format of pin location is
1045 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1046 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1047 objName + '_' + string(name);
1048 if (access(progPinLoc.c_str(), F_OK) == 0) {
1049 fd.reset(retrieveProgram(progPinLoc.c_str()));
1050 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
1051 (!fd.ok() ? std::strerror(errno) : "no error"));
1052 reuse = true;
1053 } else {
1054 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1055
1056 union bpf_attr req = {
1057 .prog_type = cs[i].type,
1058 .kern_version = kvers,
1059 .license = ptr_to_u64(license.c_str()),
1060 .insns = ptr_to_u64(cs[i].data.data()),
1061 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
1062 .log_level = 1,
1063 .log_buf = ptr_to_u64(log_buf.data()),
1064 .log_size = static_cast<__u32>(log_buf.size()),
1065 .expected_attach_type = cs[i].expected_attach_type,
1066 };
1067 if (isAtLeastKernelVersion(4, 15, 0))
1068 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1069 fd.reset(bpf(BPF_PROG_LOAD, req));
1070
1071 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
1072 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
1073
1074 if (!fd.ok()) {
1075 vector<string> lines = android::base::Split(log_buf.data(), "\n");
1076
1077 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
1078 for (const auto& line : lines) ALOGW("%s", line.c_str());
1079 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
1080
1081 if (cs[i].prog_def->optional) {
1082 ALOGW("failed program is marked optional - continuing...");
1083 continue;
1084 }
1085 ALOGE("non-optional program failed to load.");
1086 }
1087 }
1088
1089 if (!fd.ok()) return fd.get();
1090
1091 if (!reuse) {
1092 if (specified(selinux_context)) {
1093 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1094 "tmp_prog_" + objName + '_' + string(name);
1095 ret = bpfFdPin(fd, createLoc.c_str());
1096 if (ret) {
1097 int err = errno;
1098 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1099 return -err;
1100 }
1101 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1102 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1103 if (ret) {
1104 int err = errno;
1105 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1106 err, strerror(err));
1107 return -err;
1108 }
1109 } else {
1110 ret = bpfFdPin(fd, progPinLoc.c_str());
1111 if (ret) {
1112 int err = errno;
1113 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1114 return -err;
1115 }
1116 }
1117 if (chmod(progPinLoc.c_str(), 0440)) {
1118 int err = errno;
1119 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1120 return -err;
1121 }
1122 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1123 (gid_t)cs[i].prog_def->gid)) {
1124 int err = errno;
1125 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1126 cs[i].prog_def->gid, err, strerror(err));
1127 return -err;
1128 }
1129 }
1130
1131 int progId = bpfGetFdProgId(fd);
1132 if (progId == -1) {
1133 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
1134 } else {
1135 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
1136 }
1137 }
1138
1139 return 0;
1140}
1141
1142int loadProg(const char* const elfPath, bool* const isCritical, const unsigned int bpfloader_ver,
1143 const Location& location) {
1144 vector<char> license;
1145 vector<char> critical;
1146 vector<codeSection> cs;
1147 vector<unique_fd> mapFds;
1148 int ret;
1149
1150 if (!isCritical) return -1;
1151 *isCritical = false;
1152
1153 ifstream elfFile(elfPath, ios::in | ios::binary);
1154 if (!elfFile.is_open()) return -1;
1155
1156 ret = readSectionByName("critical", elfFile, critical);
1157 *isCritical = !ret;
1158
1159 ret = readSectionByName("license", elfFile, license);
1160 if (ret) {
1161 ALOGE("Couldn't find license in %s", elfPath);
1162 return ret;
1163 } else {
1164 ALOGD("Loading %s%s ELF object %s with license %s",
1165 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
1166 elfPath, (char*)license.data());
1167 }
1168
1169 // the following default values are for bpfloader V0.0 format which does not include them
1170 unsigned int bpfLoaderMinVer =
1171 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1172 unsigned int bpfLoaderMaxVer =
1173 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
1174 unsigned int bpfLoaderMinRequiredVer =
1175 readSectionUint("bpfloader_min_required_ver", elfFile, 0);
1176 size_t sizeOfBpfMapDef =
1177 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1178 size_t sizeOfBpfProgDef =
1179 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1180
1181 // inclusive lower bound check
1182 if (bpfloader_ver < bpfLoaderMinVer) {
1183 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
1184 bpfloader_ver, elfPath, bpfLoaderMinVer);
1185 return 0;
1186 }
1187
1188 // exclusive upper bound check
1189 if (bpfloader_ver >= bpfLoaderMaxVer) {
1190 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
1191 bpfloader_ver, elfPath, bpfLoaderMaxVer);
1192 return 0;
1193 }
1194
1195 if (bpfloader_ver < bpfLoaderMinRequiredVer) {
1196 ALOGI("BpfLoader version 0x%05x failing due to ELF object %s with required min ver 0x%05x",
1197 bpfloader_ver, elfPath, bpfLoaderMinRequiredVer);
1198 return -1;
1199 }
1200
1201 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
1202 bpfloader_ver, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1203
1204 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
1205 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
1206 DEFAULT_SIZEOF_BPF_MAP_DEF);
1207 return -1;
1208 }
1209
1210 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
1211 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
1212 DEFAULT_SIZEOF_BPF_PROG_DEF);
1213 return -1;
1214 }
1215
1216 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef);
1217 if (ret) {
1218 ALOGE("Couldn't read all code sections in %s", elfPath);
1219 return ret;
1220 }
1221
1222 /* Just for future debugging */
1223 if (0) dumpAllCs(cs);
1224
1225 ret = createMaps(elfPath, elfFile, mapFds, location.prefix, sizeOfBpfMapDef, bpfloader_ver);
1226 if (ret) {
1227 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1228 return ret;
1229 }
1230
1231 for (int i = 0; i < (int)mapFds.size(); i++)
1232 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1233
1234 applyMapRelo(elfFile, mapFds, cs);
1235
1236 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix, bpfloader_ver);
1237 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1238
1239 return ret;
1240}
1241
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001242static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001243 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +00001244 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001245 if (errno == ENOENT) return false;
1246 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
1247 abort(); // can only hit this if permissions (likely selinux) are screwed up
1248}
1249
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001250
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001251const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001252 // S+ Tethering mainline module (network_stack): tether offload
1253 {
1254 .dir = "/apex/com.android.tethering/etc/bpf/",
1255 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001256 },
1257 // T+ Tethering mainline module (shared with netd & system server)
1258 // netutils_wrapper (for iptables xt_bpf) has access to programs
1259 {
1260 .dir = "/apex/com.android.tethering/etc/bpf/netd_shared/",
1261 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001262 },
1263 // T+ Tethering mainline module (shared with netd & system server)
1264 // netutils_wrapper has no access, netd has read only access
1265 {
1266 .dir = "/apex/com.android.tethering/etc/bpf/netd_readonly/",
1267 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001268 },
1269 // T+ Tethering mainline module (shared with system server)
1270 {
1271 .dir = "/apex/com.android.tethering/etc/bpf/net_shared/",
1272 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001273 },
1274 // T+ Tethering mainline module (not shared, just network_stack)
1275 {
1276 .dir = "/apex/com.android.tethering/etc/bpf/net_private/",
1277 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001278 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001279};
1280
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001281static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001282 int retVal = 0;
1283 DIR* dir;
1284 struct dirent* ent;
1285
1286 if ((dir = opendir(location.dir)) != NULL) {
1287 while ((ent = readdir(dir)) != NULL) {
1288 string s = ent->d_name;
1289 if (!EndsWith(s, ".o")) continue;
1290
1291 string progPath(location.dir);
1292 progPath += s;
1293
1294 bool critical;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001295 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001296 if (ret) {
1297 if (critical) retVal = ret;
1298 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
1299 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001300 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001301 }
1302 }
1303 closedir(dir);
1304 }
1305 return retVal;
1306}
1307
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001308static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001309 if (*prefix) {
1310 mode_t prevUmask = umask(0);
1311
1312 string s = "/sys/fs/bpf/";
1313 s += prefix;
1314
1315 errno = 0;
1316 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
1317 if (ret && errno != EEXIST) {
1318 const int err = errno;
1319 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
1320 return -err;
1321 }
1322
1323 umask(prevUmask);
1324 }
1325 return 0;
1326}
1327
1328// Technically 'value' doesn't need to be newline terminated, but it's best
1329// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
1330// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001331static int writeProcSysFile(const char *filename, const char *value) {
1332 base::unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001333 if (fd < 0) {
1334 const int err = errno;
1335 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
1336 return -err;
1337 }
1338 int len = strlen(value);
1339 int v = write(fd, value, len);
1340 if (v < 0) {
1341 const int err = errno;
1342 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
1343 return -err;
1344 }
1345 if (v != len) {
1346 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
1347 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
1348 return -EINVAL;
1349 }
1350 return 0;
1351}
1352
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001353#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001354const char * const platformBpfLoader = "/system/bin/bpfloader";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001355
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001356static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001357 char * found_blockdev = NULL;
1358 FILE * f = NULL;
1359 char buf[4096];
1360
1361 f = fopen("/proc/mounts", "re");
1362 if (!f) return 1;
1363
1364 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
1365 while (fgets(buf, sizeof(buf), f)) {
1366 char * blockdev = buf;
1367 char * space = strchr(blockdev, ' ');
1368 if (!space) continue;
1369 *space = '\0';
1370 char * mntpath = space + 1;
1371 space = strchr(mntpath, ' ');
1372 if (!space) continue;
1373 *space = '\0';
1374 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
1375 found_blockdev = strdup(blockdev);
1376 break;
1377 }
1378 fclose(f);
1379 f = NULL;
1380
1381 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +00001382 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001383
1384 f = fopen("/proc/mounts", "re");
1385 if (!f) { free(found_blockdev); return 3; }
1386
1387 while (fgets(buf, sizeof(buf), f)) {
1388 char * blockdev = buf;
1389 char * space = strchr(blockdev, ' ');
1390 if (!space) continue;
1391 *space = '\0';
1392 char * mntpath = space + 1;
1393 space = strchr(mntpath, ' ');
1394 if (!space) continue;
1395 *space = '\0';
1396 if (strcmp(blockdev, found_blockdev)) continue;
1397 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
1398 char * at = strchr(mntpath, '@');
1399 if (!at) continue;
1400 char * ver = at + 1;
1401 ALOGI("Tethering APEX version %s", ver);
1402 }
1403 fclose(f);
1404 free(found_blockdev);
1405 return 0;
1406}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +00001407
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001408static bool hasGSM() {
1409 static string ph = base::GetProperty("gsm.current.phone-type", "");
1410 static bool gsm = (ph != "");
1411 static bool logged = false;
1412 if (!logged) {
1413 logged = true;
1414 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
1415 }
1416 return gsm;
1417}
1418
1419static bool isTV() {
1420 if (hasGSM()) return false; // TVs don't do GSM
1421
1422 static string key = base::GetProperty("ro.oem.key1", "");
1423 static bool tv = StartsWith(key, "ATV00");
1424 static bool logged = false;
1425 if (!logged) {
1426 logged = true;
1427 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
1428 }
1429 return tv;
1430}
1431
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001432static bool isWear() {
1433 static string wearSdkStr = base::GetProperty("ro.cw_build.wear_sdk.version", "");
1434 static int wearSdkInt = base::GetIntProperty("ro.cw_build.wear_sdk.version", 0);
1435 static string buildChars = base::GetProperty("ro.build.characteristics", "");
1436 static vector<string> v = base::Tokenize(buildChars, ",");
1437 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
1438 static bool wear = (wearSdkInt > 0) || watch;
1439 static bool logged = false;
1440 if (!logged) {
1441 logged = true;
1442 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
1443 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
1444 }
1445 return wear;
1446}
1447
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001448static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001449 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001450
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001451 // Any released device will have codename REL instead of a 'real' codename.
1452 // For safety: default to 'REL' so we default to unreleased=false on failure.
1453 const bool unreleased = (base::GetProperty("ro.build.version.codename", "REL") != "REL");
1454
1455 // goog/main device_api_level is bumped *way* before aosp/main api level
1456 // (the latter only gets bumped during the push of goog/main to aosp/main)
1457 //
1458 // Since we develop in AOSP, we want it to behave as if it was bumped too.
1459 //
1460 // Note that AOSP doesn't really have a good api level (for example during
1461 // early V dev cycle, it would have *all* of T, some but not all of U, and some V).
1462 // One could argue that for our purposes AOSP api level should be infinite or 10000.
1463 //
1464 // This could also cause api to be increased in goog/main or other branches,
1465 // but I can't imagine a case where this would be a problem: the problem
1466 // is rather a too low api level, rather than some ill defined high value.
1467 // For example as I write this aosp is 34/U, and goog is 35/V,
1468 // we want to treat both goog & aosp as 35/V, but it's harmless if we
1469 // treat goog as 36 because that value isn't yet defined to mean anything,
1470 // and we thus never compare against it.
1471 //
1472 // Also note that 'android_get_device_api_level()' is what the
1473 // //system/core/init/apex_init_util.cpp
1474 // apex init .XXrc parsing code uses for XX filtering.
1475 //
1476 // That code has a hack to bump <35 to 35 (to force aosp/main to parse .35rc),
1477 // but could (should?) perhaps be adjusted to match this.
1478 const int effective_api_level = android_get_device_api_level() + (int)unreleased;
1479 const bool isAtLeastT = (effective_api_level >= __ANDROID_API_T__);
1480 const bool isAtLeastU = (effective_api_level >= __ANDROID_API_U__);
1481 const bool isAtLeastV = (effective_api_level >= __ANDROID_API_V__);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001482
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001483 // last in U QPR2 beta1
1484 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
1485 // first in U QPR2 beta~2
1486 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
1487
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001488 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -07001489 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
1490 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
1491 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
1492 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
1493 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -07001494
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001495 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) uid:%d rc:%d%d",
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -07001496 bpfloader_ver, argv[0], android_get_device_api_level(), effective_api_level,
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -07001497 kernelVersion(), describeArch(), getuid(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001498 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001499
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001500 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
1501 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
1502 return 1;
1503 }
1504
1505 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
1506 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
1507 return 1;
1508 }
1509
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -08001510 logTetheringApexVersion();
1511
Maciej Żenczykowski11141da2024-03-15 18:21:33 -07001512 if (!isAtLeastT) {
1513 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +00001514 return 1;
1515 }
1516
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001517 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001518 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001519 ALOGE("Android T requires kernel 4.9.");
1520 return 1;
1521 }
1522
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001523 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001524 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001525 ALOGE("Android U requires kernel 4.14.");
1526 return 1;
1527 }
1528
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001529 // V bumps the kernel requirement up to 4.19
1530 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001531 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -07001532 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001533 return 1;
1534 }
1535
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001536 // Technically already required by U, but only enforce on V+
1537 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
1538 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
1539 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
1540 if (!isTV()) return 1;
1541 }
1542
1543 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
1544 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001545 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -07001546 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +00001547 }
1548
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001549 if (isAtLeastV) {
1550 bool bad = false;
1551
1552 if (!isLtsKernel()) {
1553 ALOGW("Android V only supports LTS kernels.");
1554 bad = true;
1555 }
1556
1557#define REQUIRE(maj, min, sub) \
1558 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
1559 ALOGW("Android V requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
1560 bad = true; \
1561 }
1562
1563 REQUIRE(4, 19, 236)
1564 REQUIRE(5, 4, 186)
1565 REQUIRE(5, 10, 199)
1566 REQUIRE(5, 15, 136)
1567 REQUIRE(6, 1, 57)
1568 REQUIRE(6, 6, 0)
1569
1570#undef REQUIRE
1571
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +00001572 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -07001573 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
1574 }
1575 }
1576
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001577 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001578 /* Android 14/U should only launch on 64-bit kernels
1579 * T launches on 5.10/5.15
1580 * U launches on 5.15/6.1
1581 * So >=5.16 implies isKernel64Bit()
1582 *
1583 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
1584 *
1585 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
1586 * we also require 64-bit userspace.
1587 *
1588 * There are various known issues with 32-bit userspace talking to various
1589 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
1590 * Some of these have userspace or kernel workarounds/hacks.
1591 * Some of them don't...
1592 * We're going to be removing the hacks.
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +00001593 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
1594 * Note: this check/enforcement only applies to *system* userspace code,
1595 * it does not affect unprivileged apps, the 32-on-64 compatibility
1596 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001597 *
1598 * Additionally the 32-bit kernel jit support is poor,
1599 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
1600 */
1601 ALOGE("64-bit userspace required on 6.2+ kernels.");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +00001602 // Stuff won't work reliably, but exempt TVs & Arm Wear devices
1603 if (!isTV() && !(isWear() && isArm())) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001604 }
1605
1606 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001607 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001608 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001609 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001610 return 1;
1611 }
1612
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001613 if (runningAsRoot) {
1614 // Note: writing this proc file requires being root (always the case on V+)
1615
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001616 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
1617 // but we need 0 (enabled)
1618 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
1619 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
1620 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001621 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001622 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001623
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001624 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -07001625 // Note: writing these proc files requires CAP_NET_ADMIN
1626 // and sepolicy which is only present on U+,
1627 // on Android T and earlier versions they're written from the 'load_bpf_programs'
1628 // trigger (ie. by init itself) instead.
1629
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001630 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
1631 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
1632 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1633 // kernel does not have CONFIG_BPF_JIT=y)
1634 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
1635 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
1636 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001637
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -07001638 // Enable JIT kallsyms export for privileged users only
1639 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
1640 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
1641 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
1642 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001643
1644 // Create all the pin subdirectories
1645 // (this must be done first to allow selinux_context and pin_subdir functionality,
1646 // which could otherwise fail with ENOENT during object pinning or renaming,
1647 // due to ordering issues)
1648 for (const auto& location : locations) {
1649 if (createSysFsBpfSubDir(location.prefix)) return 1;
1650 }
1651
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +00001652 // Note: there's no actual src dir for fs_bpf_loader .o's,
1653 // so it is not listed in 'locations[].prefix'.
1654 // This is because this is primarily meant for triggering genfscon rules,
1655 // and as such this will likely always be the case.
1656 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
1657 if (createSysFsBpfSubDir("loader")) return 1;
1658
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001659 // Load all ELF objects, create programs and maps, and pin them
1660 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -07001661 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001662 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1663 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1664 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1665 "problems or startup script race.");
1666 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1667 sleep(20);
1668 return 2;
1669 }
1670 }
1671
1672 int key = 1;
1673 int value = 123;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001674 base::unique_fd map(
1675 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
1676 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001677 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
1678 return 1;
1679 }
1680
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001681 // leave a flag that we're done
1682 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -07001683
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001684 // platform bpfloader will only succeed when run as root
1685 if (!runningAsRoot) {
1686 // unreachable on U QPR3+ which always runs netbpfload as root
1687
1688 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
1689 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -07001690 }
1691
Maciej Żenczykowski15f97312024-06-13 14:11:28 -07001692 // unreachable before U QPR3
1693 ALOGI("done, transferring control to platform bpfloader.");
1694
1695 // platform BpfLoader *needs* to run as root
1696 const char * args[] = { platformBpfLoader, NULL, };
1697 execve(args[0], (char**)args, envp);
1698 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
1699 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001700}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001701
1702} // namespace bpf
1703} // namespace android
1704
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001705int main(int argc, char** argv, char * const envp[]) {
1706 android::base::InitLogging(argv, &android::base::KernelLogger);
1707
1708 if (argc == 2 && !strcmp(argv[1], "done")) {
1709 // we're being re-exec'ed from platform bpfloader to 'finalize' things
1710 if (!android::base::SetProperty("bpf.progs_loaded", "1")) {
1711 ALOGE("Failed to set bpf.progs_loaded property to 1.");
1712 return 125;
1713 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -07001714 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -07001715 return 0;
1716 }
1717
1718 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -07001719}