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