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