• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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 "LibBpfLoader"
18 
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <linux/bpf.h>
22 #include <linux/elf.h>
23 #include <log/log.h>
24 #include <stdint.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sysexits.h>
29 #include <sys/stat.h>
30 #include <sys/utsname.h>
31 #include <sys/wait.h>
32 #include <unistd.h>
33 
34 // This is BpfLoader v0.38
35 // WARNING: If you ever hit cherrypick conflicts here you're doing it wrong:
36 // You are NOT allowed to cherrypick bpfloader related patches out of order.
37 // (indeed: cherrypicking is probably a bad idea and you should merge instead)
38 // Mainline supports ONLY the published versions of the bpfloader for each Android release.
39 #define BPFLOADER_VERSION_MAJOR 0u
40 #define BPFLOADER_VERSION_MINOR 38u
41 #define BPFLOADER_VERSION ((BPFLOADER_VERSION_MAJOR << 16) | BPFLOADER_VERSION_MINOR)
42 
43 #include "BpfSyscallWrappers.h"
44 #include "bpf/BpfUtils.h"
45 #include "bpf/bpf_map_def.h"
46 #include "include/libbpf_android.h"
47 
48 #if BPFLOADER_VERSION < COMPILE_FOR_BPFLOADER_VERSION
49 #error "BPFLOADER_VERSION is less than COMPILE_FOR_BPFLOADER_VERSION"
50 #endif
51 
52 #include <bpf/bpf.h>
53 
54 #include <cstdlib>
55 #include <fstream>
56 #include <iostream>
57 #include <optional>
58 #include <string>
59 #include <unordered_map>
60 #include <vector>
61 
62 #include <android-base/cmsg.h>
63 #include <android-base/file.h>
64 #include <android-base/strings.h>
65 #include <android-base/unique_fd.h>
66 #include <cutils/properties.h>
67 
68 #define BPF_FS_PATH "/sys/fs/bpf/"
69 
70 // Size of the BPF log buffer for verifier logging
71 #define BPF_LOAD_LOG_SZ 0xfffff
72 
73 // Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
74 #define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
75 
76 using android::base::StartsWith;
77 using android::base::unique_fd;
78 using std::ifstream;
79 using std::ios;
80 using std::optional;
81 using std::string;
82 using std::vector;
83 
getBuildTypeInternal()84 static std::string getBuildTypeInternal() {
85     char value[PROPERTY_VALUE_MAX] = {};
86     (void)property_get("ro.build.type", value, "unknown");  // ignore length
87     return value;
88 }
89 
90 namespace android {
91 namespace bpf {
92 
getBuildType()93 const std::string& getBuildType() {
94     static std::string t = getBuildTypeInternal();
95     return t;
96 }
97 
lookupSelinuxContext(const domain d,const char * const unspecified="")98 constexpr const char* lookupSelinuxContext(const domain d, const char* const unspecified = "") {
99     switch (d) {
100         case domain::unspecified:   return unspecified;
101         case domain::platform:      return "fs_bpf";
102         case domain::tethering:     return "fs_bpf_tethering";
103         case domain::net_private:   return "fs_bpf_net_private";
104         case domain::net_shared:    return "fs_bpf_net_shared";
105         case domain::netd_readonly: return "fs_bpf_netd_readonly";
106         case domain::netd_shared:   return "fs_bpf_netd_shared";
107         case domain::vendor:        return "fs_bpf_vendor";
108         case domain::loader:        return "fs_bpf_loader";
109         default:                    return "(unrecognized)";
110     }
111 }
112 
getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE])113 domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
114     for (domain d : AllDomains) {
115         // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
116         if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
117         if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
118     }
119     ALOGW("ignoring unrecognized selinux_context '%-32s'", s);
120     // We should return 'unrecognized' here, however: returning unspecified will
121     // result in the system simply using the default context, which in turn
122     // will allow future expansion by adding more restrictive selinux types.
123     // Older bpfloader will simply ignore that, and use the less restrictive default.
124     // This does mean you CANNOT later add a *less* restrictive type than the default.
125     //
126     // Note: we cannot just abort() here as this might be a mainline module shipped optional update
127     return domain::unspecified;
128 }
129 
lookupPinSubdir(const domain d,const char * const unspecified="")130 constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
131     switch (d) {
132         case domain::unspecified:   return unspecified;
133         case domain::platform:      return "/";
134         case domain::tethering:     return "tethering/";
135         case domain::net_private:   return "net_private/";
136         case domain::net_shared:    return "net_shared/";
137         case domain::netd_readonly: return "netd_readonly/";
138         case domain::netd_shared:   return "netd_shared/";
139         case domain::vendor:        return "vendor/";
140         case domain::loader:        return "loader/";
141         default:                    return "(unrecognized)";
142     }
143 };
144 
getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE])145 domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
146     for (domain d : AllDomains) {
147         // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
148         if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
149         if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
150     }
151     ALOGE("unrecognized pin_subdir '%-32s'", s);
152     // pin_subdir affects the object's full pathname,
153     // and thus using the default would change the location and thus our code's ability to find it,
154     // hence this seems worth treating as a true error condition.
155     //
156     // Note: we cannot just abort() here as this might be a mainline module shipped optional update
157     // However, our callers will treat this as an error, and stop loading the specific .o,
158     // which will fail bpfloader if the .o is marked critical.
159     return domain::unrecognized;
160 }
161 
pathToObjName(const string & path)162 static string pathToObjName(const string& path) {
163     // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
164     string filename = android::base::Split(path, "/").back();
165     // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
166     string name = filename.substr(0, filename.find_last_of('.'));
167     // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
168     // this can be used to provide duplicate programs (mux based on the bpfloader version)
169     return name.substr(0, name.find_last_of('@'));
170 }
171 
172 typedef struct {
173     const char* name;
174     enum bpf_prog_type type;
175     enum bpf_attach_type expected_attach_type;
176 } sectionType;
177 
178 /*
179  * Map section name prefixes to program types, the section name will be:
180  *   SECTION(<prefix>/<name-of-program>)
181  * For example:
182  *   SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
183  * is the name of the program, and tracepoint is the type.
184  *
185  * However, be aware that you should not be directly using the SECTION() macro.
186  * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
187  */
188 sectionType sectionNameTypes[] = {
189         {"bind4/",         BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
190         {"bind6/",         BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
191         {"cgroupskb/",     BPF_PROG_TYPE_CGROUP_SKB,       BPF_ATTACH_TYPE_UNSPEC},
192         {"cgroupsock/",    BPF_PROG_TYPE_CGROUP_SOCK,      BPF_ATTACH_TYPE_UNSPEC},
193         {"connect4/",      BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
194         {"connect6/",      BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
195         {"egress/",        BPF_PROG_TYPE_CGROUP_SKB,       BPF_CGROUP_INET_EGRESS},
196         {"getsockopt/",    BPF_PROG_TYPE_CGROUP_SOCKOPT,   BPF_CGROUP_GETSOCKOPT},
197         {"ingress/",       BPF_PROG_TYPE_CGROUP_SKB,       BPF_CGROUP_INET_INGRESS},
198         {"kprobe/",        BPF_PROG_TYPE_KPROBE,           BPF_ATTACH_TYPE_UNSPEC},
199         {"kretprobe/",     BPF_PROG_TYPE_KPROBE,           BPF_ATTACH_TYPE_UNSPEC},
200         {"lwt_in/",        BPF_PROG_TYPE_LWT_IN,           BPF_ATTACH_TYPE_UNSPEC},
201         {"lwt_out/",       BPF_PROG_TYPE_LWT_OUT,          BPF_ATTACH_TYPE_UNSPEC},
202         {"lwt_seg6local/", BPF_PROG_TYPE_LWT_SEG6LOCAL,    BPF_ATTACH_TYPE_UNSPEC},
203         {"lwt_xmit/",      BPF_PROG_TYPE_LWT_XMIT,         BPF_ATTACH_TYPE_UNSPEC},
204         {"perf_event/",    BPF_PROG_TYPE_PERF_EVENT,       BPF_ATTACH_TYPE_UNSPEC},
205         {"postbind4/",     BPF_PROG_TYPE_CGROUP_SOCK,      BPF_CGROUP_INET4_POST_BIND},
206         {"postbind6/",     BPF_PROG_TYPE_CGROUP_SOCK,      BPF_CGROUP_INET6_POST_BIND},
207         {"recvmsg4/",      BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
208         {"recvmsg6/",      BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
209         {"schedact/",      BPF_PROG_TYPE_SCHED_ACT,        BPF_ATTACH_TYPE_UNSPEC},
210         {"schedcls/",      BPF_PROG_TYPE_SCHED_CLS,        BPF_ATTACH_TYPE_UNSPEC},
211         {"sendmsg4/",      BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
212         {"sendmsg6/",      BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
213         {"setsockopt/",    BPF_PROG_TYPE_CGROUP_SOCKOPT,   BPF_CGROUP_SETSOCKOPT},
214         {"skfilter/",      BPF_PROG_TYPE_SOCKET_FILTER,    BPF_ATTACH_TYPE_UNSPEC},
215         {"sockops/",       BPF_PROG_TYPE_SOCK_OPS,         BPF_CGROUP_SOCK_OPS},
216         {"sysctl",         BPF_PROG_TYPE_CGROUP_SYSCTL,    BPF_CGROUP_SYSCTL},
217         {"tracepoint/",    BPF_PROG_TYPE_TRACEPOINT,       BPF_ATTACH_TYPE_UNSPEC},
218         {"uprobe/",        BPF_PROG_TYPE_KPROBE,           BPF_ATTACH_TYPE_UNSPEC},
219         {"uretprobe/",     BPF_PROG_TYPE_KPROBE,           BPF_ATTACH_TYPE_UNSPEC},
220         {"xdp/",           BPF_PROG_TYPE_XDP,              BPF_ATTACH_TYPE_UNSPEC},
221 };
222 
223 typedef struct {
224     enum bpf_prog_type type;
225     enum bpf_attach_type expected_attach_type;
226     string name;
227     vector<char> data;
228     vector<char> rel_data;
229     optional<struct bpf_prog_def> prog_def;
230 
231     unique_fd prog_fd; /* fd after loading */
232 } codeSection;
233 
readElfHeader(ifstream & elfFile,Elf64_Ehdr * eh)234 static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
235     elfFile.seekg(0);
236     if (elfFile.fail()) return -1;
237 
238     if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
239 
240     return 0;
241 }
242 
243 /* Reads all section header tables into an Shdr array */
readSectionHeadersAll(ifstream & elfFile,vector<Elf64_Shdr> & shTable)244 static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
245     Elf64_Ehdr eh;
246     int ret = 0;
247 
248     ret = readElfHeader(elfFile, &eh);
249     if (ret) return ret;
250 
251     elfFile.seekg(eh.e_shoff);
252     if (elfFile.fail()) return -1;
253 
254     /* Read shdr table entries */
255     shTable.resize(eh.e_shnum);
256 
257     if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
258 
259     return 0;
260 }
261 
262 /* Read a section by its index - for ex to get sec hdr strtab blob */
readSectionByIdx(ifstream & elfFile,int id,vector<char> & sec)263 static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
264     vector<Elf64_Shdr> shTable;
265     int ret = readSectionHeadersAll(elfFile, shTable);
266     if (ret) return ret;
267 
268     elfFile.seekg(shTable[id].sh_offset);
269     if (elfFile.fail()) return -1;
270 
271     sec.resize(shTable[id].sh_size);
272     if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
273 
274     return 0;
275 }
276 
277 /* Read whole section header string table */
readSectionHeaderStrtab(ifstream & elfFile,vector<char> & strtab)278 static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
279     Elf64_Ehdr eh;
280     int ret = readElfHeader(elfFile, &eh);
281     if (ret) return ret;
282 
283     ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
284     if (ret) return ret;
285 
286     return 0;
287 }
288 
289 /* Get name from offset in strtab */
getSymName(ifstream & elfFile,int nameOff,string & name)290 static int getSymName(ifstream& elfFile, int nameOff, string& name) {
291     int ret;
292     vector<char> secStrTab;
293 
294     ret = readSectionHeaderStrtab(elfFile, secStrTab);
295     if (ret) return ret;
296 
297     if (nameOff >= (int)secStrTab.size()) return -1;
298 
299     name = string((char*)secStrTab.data() + nameOff);
300     return 0;
301 }
302 
303 /* Reads a full section by name - example to get the GPL license */
readSectionByName(const char * name,ifstream & elfFile,vector<char> & data)304 static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
305     vector<char> secStrTab;
306     vector<Elf64_Shdr> shTable;
307     int ret;
308 
309     ret = readSectionHeadersAll(elfFile, shTable);
310     if (ret) return ret;
311 
312     ret = readSectionHeaderStrtab(elfFile, secStrTab);
313     if (ret) return ret;
314 
315     for (int i = 0; i < (int)shTable.size(); i++) {
316         char* secname = secStrTab.data() + shTable[i].sh_name;
317         if (!secname) continue;
318 
319         if (!strcmp(secname, name)) {
320             vector<char> dataTmp;
321             dataTmp.resize(shTable[i].sh_size);
322 
323             elfFile.seekg(shTable[i].sh_offset);
324             if (elfFile.fail()) return -1;
325 
326             if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
327 
328             data = dataTmp;
329             return 0;
330         }
331     }
332     return -2;
333 }
334 
readSectionUint(const char * name,ifstream & elfFile,unsigned int defVal)335 unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
336     vector<char> theBytes;
337     int ret = readSectionByName(name, elfFile, theBytes);
338     if (ret) {
339         ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
340         return defVal;
341     } else if (theBytes.size() < sizeof(unsigned int)) {
342         ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
343         return defVal;
344     } else {
345         // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
346         unsigned int value = static_cast<unsigned char>(theBytes[3]);
347         value <<= 8;
348         value += static_cast<unsigned char>(theBytes[2]);
349         value <<= 8;
350         value += static_cast<unsigned char>(theBytes[1]);
351         value <<= 8;
352         value += static_cast<unsigned char>(theBytes[0]);
353         ALOGI("Section %s value is %u [0x%x]", name, value, value);
354         return value;
355     }
356 }
357 
readSectionByType(ifstream & elfFile,int type,vector<char> & data)358 static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
359     int ret;
360     vector<Elf64_Shdr> shTable;
361 
362     ret = readSectionHeadersAll(elfFile, shTable);
363     if (ret) return ret;
364 
365     for (int i = 0; i < (int)shTable.size(); i++) {
366         if ((int)shTable[i].sh_type != type) continue;
367 
368         vector<char> dataTmp;
369         dataTmp.resize(shTable[i].sh_size);
370 
371         elfFile.seekg(shTable[i].sh_offset);
372         if (elfFile.fail()) return -1;
373 
374         if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
375 
376         data = dataTmp;
377         return 0;
378     }
379     return -2;
380 }
381 
symCompare(Elf64_Sym a,Elf64_Sym b)382 static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
383     return (a.st_value < b.st_value);
384 }
385 
readSymTab(ifstream & elfFile,int sort,vector<Elf64_Sym> & data)386 static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
387     int ret, numElems;
388     Elf64_Sym* buf;
389     vector<char> secData;
390 
391     ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
392     if (ret) return ret;
393 
394     buf = (Elf64_Sym*)secData.data();
395     numElems = (secData.size() / sizeof(Elf64_Sym));
396     data.assign(buf, buf + numElems);
397 
398     if (sort) std::sort(data.begin(), data.end(), symCompare);
399     return 0;
400 }
401 
getFuseProgType()402 static enum bpf_prog_type getFuseProgType() {
403     int result = BPF_PROG_TYPE_UNSPEC;
404     ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
405     return static_cast<bpf_prog_type>(result);
406 }
407 
getSectionType(string & name)408 static enum bpf_prog_type getSectionType(string& name) {
409     for (auto& snt : sectionNameTypes)
410         if (StartsWith(name, snt.name)) return snt.type;
411 
412     // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
413     if (StartsWith(name, "fuse/")) return getFuseProgType();
414 
415     return BPF_PROG_TYPE_UNSPEC;
416 }
417 
getExpectedAttachType(string & name)418 static enum bpf_attach_type getExpectedAttachType(string& name) {
419     for (auto& snt : sectionNameTypes)
420         if (StartsWith(name, snt.name)) return snt.expected_attach_type;
421     return BPF_ATTACH_TYPE_UNSPEC;
422 }
423 
getSectionName(enum bpf_prog_type type)424 static string getSectionName(enum bpf_prog_type type)
425 {
426     for (auto& snt : sectionNameTypes)
427         if (snt.type == type)
428             return string(snt.name);
429 
430     return "UNKNOWN SECTION NAME " + std::to_string(type);
431 }
432 
readProgDefs(ifstream & elfFile,vector<struct bpf_prog_def> & pd,size_t sizeOfBpfProgDef)433 static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
434                         size_t sizeOfBpfProgDef) {
435     vector<char> pdData;
436     int ret = readSectionByName("progs", elfFile, pdData);
437     // Older file formats do not require a 'progs' section at all.
438     // (We should probably figure out whether this is behaviour which is safe to remove now.)
439     if (ret == -2) return 0;
440     if (ret) return ret;
441 
442     if (pdData.size() % sizeOfBpfProgDef) {
443         ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
444               pdData.size(), sizeOfBpfProgDef);
445         return -1;
446     };
447 
448     int progCount = pdData.size() / sizeOfBpfProgDef;
449     pd.resize(progCount);
450     size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
451 
452     const char* dataPtr = pdData.data();
453     for (auto& p : pd) {
454         // First we zero initialize
455         memset(&p, 0, sizeof(p));
456         // Then we set non-zero defaults
457         p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER;  // v1.0
458         // Then we copy over the structure prefix from the ELF file.
459         memcpy(&p, dataPtr, trimmedSize);
460         // Move to next struct in the ELF file
461         dataPtr += sizeOfBpfProgDef;
462     }
463     return 0;
464 }
465 
getSectionSymNames(ifstream & elfFile,const string & sectionName,vector<string> & names,optional<unsigned> symbolType=std::nullopt)466 static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
467                               optional<unsigned> symbolType = std::nullopt) {
468     int ret;
469     string name;
470     vector<Elf64_Sym> symtab;
471     vector<Elf64_Shdr> shTable;
472 
473     ret = readSymTab(elfFile, 1 /* sort */, symtab);
474     if (ret) return ret;
475 
476     /* Get index of section */
477     ret = readSectionHeadersAll(elfFile, shTable);
478     if (ret) return ret;
479 
480     int sec_idx = -1;
481     for (int i = 0; i < (int)shTable.size(); i++) {
482         ret = getSymName(elfFile, shTable[i].sh_name, name);
483         if (ret) return ret;
484 
485         if (!name.compare(sectionName)) {
486             sec_idx = i;
487             break;
488         }
489     }
490 
491     /* No section found with matching name*/
492     if (sec_idx == -1) {
493         ALOGW("No %s section could be found in elf object", sectionName.c_str());
494         return -1;
495     }
496 
497     for (int i = 0; i < (int)symtab.size(); i++) {
498         if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
499 
500         if (symtab[i].st_shndx == sec_idx) {
501             string s;
502             ret = getSymName(elfFile, symtab[i].st_name, s);
503             if (ret) return ret;
504             names.push_back(s);
505         }
506     }
507 
508     return 0;
509 }
510 
IsAllowed(bpf_prog_type type,const bpf_prog_type * allowed,size_t numAllowed)511 static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
512     if (allowed == nullptr) return true;
513 
514     for (size_t i = 0; i < numAllowed; i++) {
515         if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
516             if (type == getFuseProgType()) return true;
517         } else if (type == allowed[i])
518             return true;
519     }
520 
521     return false;
522 }
523 
524 /* Read a section by its index - for ex to get sec hdr strtab blob */
readCodeSections(ifstream & elfFile,vector<codeSection> & cs,size_t sizeOfBpfProgDef,const bpf_prog_type * allowed,size_t numAllowed)525 static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef,
526                             const bpf_prog_type* allowed, size_t numAllowed) {
527     vector<Elf64_Shdr> shTable;
528     int entries, ret = 0;
529 
530     ret = readSectionHeadersAll(elfFile, shTable);
531     if (ret) return ret;
532     entries = shTable.size();
533 
534     vector<struct bpf_prog_def> pd;
535     ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
536     if (ret) return ret;
537     vector<string> progDefNames;
538     ret = getSectionSymNames(elfFile, "progs", progDefNames);
539     if (!pd.empty() && ret) return ret;
540 
541     for (int i = 0; i < entries; i++) {
542         string name;
543         codeSection cs_temp;
544         cs_temp.type = BPF_PROG_TYPE_UNSPEC;
545 
546         ret = getSymName(elfFile, shTable[i].sh_name, name);
547         if (ret) return ret;
548 
549         enum bpf_prog_type ptype = getSectionType(name);
550 
551         if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
552 
553         if (!IsAllowed(ptype, allowed, numAllowed)) {
554             ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
555             return -1;
556         }
557 
558         // This must be done before '/' is replaced with '_'.
559         cs_temp.expected_attach_type = getExpectedAttachType(name);
560 
561         string oldName = name;
562 
563         // convert all slashes to underscores
564         std::replace(name.begin(), name.end(), '/', '_');
565 
566         cs_temp.type = ptype;
567         cs_temp.name = name;
568 
569         ret = readSectionByIdx(elfFile, i, cs_temp.data);
570         if (ret) return ret;
571         ALOGD("Loaded code section %d (%s)", i, name.c_str());
572 
573         vector<string> csSymNames;
574         ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
575         if (ret || !csSymNames.size()) return ret;
576         for (size_t i = 0; i < progDefNames.size(); ++i) {
577             if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
578                 cs_temp.prog_def = pd[i];
579                 break;
580             }
581         }
582 
583         /* Check for rel section */
584         if (cs_temp.data.size() > 0 && i < entries) {
585             ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
586             if (ret) return ret;
587 
588             if (name == (".rel" + oldName)) {
589                 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
590                 if (ret) return ret;
591                 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
592             }
593         }
594 
595         if (cs_temp.data.size() > 0) {
596             cs.push_back(std::move(cs_temp));
597             ALOGD("Adding section %d to cs list", i);
598         }
599     }
600     return 0;
601 }
602 
getSymNameByIdx(ifstream & elfFile,int index,string & name)603 static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
604     vector<Elf64_Sym> symtab;
605     int ret = 0;
606 
607     ret = readSymTab(elfFile, 0 /* !sort */, symtab);
608     if (ret) return ret;
609 
610     if (index >= (int)symtab.size()) return -1;
611 
612     return getSymName(elfFile, symtab[index].st_name, name);
613 }
614 
waitpidTimeout(pid_t pid,int timeoutMs)615 static bool waitpidTimeout(pid_t pid, int timeoutMs) {
616     // Add SIGCHLD to the signal set.
617     sigset_t child_mask, original_mask;
618     sigemptyset(&child_mask);
619     sigaddset(&child_mask, SIGCHLD);
620     if (sigprocmask(SIG_BLOCK, &child_mask, &original_mask) == -1) return false;
621 
622     // Wait for a SIGCHLD notification.
623     errno = 0;
624     timespec ts = {0, timeoutMs * 1000000};
625     int wait_result = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, nullptr, &ts));
626 
627     // Restore the original signal set.
628     sigprocmask(SIG_SETMASK, &original_mask, nullptr);
629 
630     if (wait_result == -1) return false;
631 
632     int status;
633     return TEMP_FAILURE_RETRY(waitpid(pid, &status, WNOHANG)) == pid;
634 }
635 
getMapBtfInfo(const char * elfPath,std::unordered_map<string,std::pair<uint32_t,uint32_t>> & btfTypeIds)636 static std::optional<unique_fd> getMapBtfInfo(const char* elfPath,
637                          std::unordered_map<string, std::pair<uint32_t, uint32_t>> &btfTypeIds) {
638     unique_fd bpfloaderSocket, btfloaderSocket;
639     if (!android::base::Socketpair(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0, &bpfloaderSocket,
640                                    &btfloaderSocket)) {
641         return {};
642     }
643 
644     unique_fd pipeRead, pipeWrite;
645     if (!android::base::Pipe(&pipeRead, &pipeWrite, O_NONBLOCK)) {
646         return {};
647     }
648 
649     pid_t pid = fork();
650     if (pid < 0) return {};
651     if (!pid) {
652         bpfloaderSocket.reset();
653         pipeRead.reset();
654         auto socketFdStr = std::to_string(btfloaderSocket.release());
655         auto pipeFdStr = std::to_string(pipeWrite.release());
656 
657         if (execl("/system/bin/btfloader", "/system/bin/btfloader", socketFdStr.c_str(),
658                   pipeFdStr.c_str(), elfPath, NULL) == -1) {
659             ALOGW("exec btfloader failed with errno %d (%s)", errno, strerror(errno));
660             exit(EX_UNAVAILABLE);
661         }
662     }
663     btfloaderSocket.reset();
664     pipeWrite.reset();
665     if (!waitpidTimeout(pid, 100)) {
666         kill(pid, SIGKILL);
667         return {};
668     }
669 
670     unique_fd btfFd;
671     if (android::base::ReceiveFileDescriptors(bpfloaderSocket, nullptr, 0, &btfFd)) return {};
672 
673     std::string btfTypeIdStr;
674     if (!android::base::ReadFdToString(pipeRead, &btfTypeIdStr)) return {};
675     if (!btfFd.ok()) return {};
676 
677     const auto mapTypeIdLines = android::base::Split(btfTypeIdStr, "\n");
678     for (const auto &line : mapTypeIdLines) {
679         const auto vec = android::base::Split(line, " ");
680         // Splitting on newline will give us one empty line
681         if (vec.size() != 3) continue;
682         const int kTid = atoi(vec[1].c_str());
683         const int vTid = atoi(vec[2].c_str());
684         if (!kTid || !vTid) return {};
685         btfTypeIds[vec[0]] = std::make_pair(kTid, vTid);
686     }
687     return btfFd;
688 }
689 
mapMatchesExpectations(const unique_fd & fd,const string & mapName,const struct bpf_map_def & mapDef,const enum bpf_map_type type)690 static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
691                                    const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
692     // Assuming fd is a valid Bpf Map file descriptor then
693     // all the following should always succeed on a 4.14+ kernel.
694     // If they somehow do fail, they'll return -1 (and set errno),
695     // which should then cause (among others) a key_size mismatch.
696     int fd_type = bpfGetFdMapType(fd);
697     int fd_key_size = bpfGetFdKeySize(fd);
698     int fd_value_size = bpfGetFdValueSize(fd);
699     int fd_max_entries = bpfGetFdMaxEntries(fd);
700     int fd_map_flags = bpfGetFdMapFlags(fd);
701 
702     // DEVMAPs are readonly from the bpf program side's point of view, as such
703     // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
704     int desired_map_flags = (int)mapDef.map_flags;
705     if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
706         desired_map_flags |= BPF_F_RDONLY_PROG;
707 
708     // The following checks should *never* trigger, if one of them somehow does,
709     // it probably means a bpf .o file has been changed/replaced at runtime
710     // and bpfloader was manually rerun (normally it should only run *once*
711     // early during the boot process).
712     // Another possibility is that something is misconfigured in the code:
713     // most likely a shared map is declared twice differently.
714     // But such a change should never be checked into the source tree...
715     if ((fd_type == type) &&
716         (fd_key_size == (int)mapDef.key_size) &&
717         (fd_value_size == (int)mapDef.value_size) &&
718         (fd_max_entries == (int)mapDef.max_entries) &&
719         (fd_map_flags == desired_map_flags)) {
720         return true;
721     }
722 
723     ALOGE("bpf map name %s mismatch: desired/found: "
724           "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
725           mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
726           fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
727     return false;
728 }
729 
createMaps(const char * elfPath,ifstream & elfFile,vector<unique_fd> & mapFds,const char * prefix,const unsigned long long allowedDomainBitmask,const size_t sizeOfBpfMapDef)730 static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
731                       const char* prefix, const unsigned long long allowedDomainBitmask,
732                       const size_t sizeOfBpfMapDef) {
733     int ret;
734     vector<char> mdData, btfData;
735     vector<struct bpf_map_def> md;
736     vector<string> mapNames;
737     std::unordered_map<string, std::pair<uint32_t, uint32_t>> btfTypeIdMap;
738     string objName = pathToObjName(string(elfPath));
739 
740     ret = readSectionByName("maps", elfFile, mdData);
741     if (ret == -2) return 0;  // no maps to read
742     if (ret) return ret;
743 
744     if (mdData.size() % sizeOfBpfMapDef) {
745         ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
746               mdData.size(), sizeOfBpfMapDef);
747         return -1;
748     };
749 
750     int mapCount = mdData.size() / sizeOfBpfMapDef;
751     md.resize(mapCount);
752     size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
753 
754     const char* dataPtr = mdData.data();
755     for (auto& m : md) {
756         // First we zero initialize
757         memset(&m, 0, sizeof(m));
758         // Then we set non-zero defaults
759         m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER;  // v1.0
760         m.max_kver = 0xFFFFFFFFu;                         // matches KVER_INF from bpf_helpers.h
761         // Then we copy over the structure prefix from the ELF file.
762         memcpy(&m, dataPtr, trimmedSize);
763         // Move to next struct in the ELF file
764         dataPtr += sizeOfBpfMapDef;
765     }
766 
767     ret = getSectionSymNames(elfFile, "maps", mapNames);
768     if (ret) return ret;
769 
770     unsigned btfMinBpfLoaderVer = readSectionUint("btf_min_bpfloader_ver", elfFile, 0);
771     unsigned btfMinKernelVer = readSectionUint("btf_min_kernel_ver", elfFile, 0);
772     unsigned kvers = kernelVersion();
773 
774     std::optional<unique_fd> btfFd;
775     if ((BPFLOADER_VERSION >= btfMinBpfLoaderVer) && (kvers >= btfMinKernelVer) &&
776         (!readSectionByName(".BTF", elfFile, btfData))) {
777         btfFd = getMapBtfInfo(elfPath, btfTypeIdMap);
778     }
779 
780     for (int i = 0; i < (int)mapNames.size(); i++) {
781         if (md[i].zero != 0) abort();
782 
783         if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
784             ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
785                   md[i].bpfloader_min_ver);
786             mapFds.push_back(unique_fd());
787             continue;
788         }
789 
790         if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
791             ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
792                   md[i].bpfloader_max_ver);
793             mapFds.push_back(unique_fd());
794             continue;
795         }
796 
797         if (kvers < md[i].min_kver) {
798             ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
799                   mapNames[i].c_str(), kvers, md[i].min_kver);
800             mapFds.push_back(unique_fd());
801             continue;
802         }
803 
804         if (kvers >= md[i].max_kver) {
805             ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
806                   mapNames[i].c_str(), kvers, md[i].max_kver);
807             mapFds.push_back(unique_fd());
808             continue;
809         }
810 
811         if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
812             (md[i].ignore_on_userdebug && isUserdebug())) {
813             ALOGI("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
814                   getBuildType().c_str());
815             mapFds.push_back(unique_fd());
816             continue;
817         }
818 
819         if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
820             (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
821             (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
822             (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
823             (isRiscV() && md[i].ignore_on_riscv64)) {
824             ALOGI("skipping map %s which is ignored on %s", mapNames[i].c_str(),
825                   describeArch());
826             mapFds.push_back(unique_fd());
827             continue;
828         }
829 
830         enum bpf_map_type type = md[i].type;
831         if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
832             // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
833             // of be approximated: HASH has the same userspace visible api.
834             // However it cannot be used by ebpf programs in the same way.
835             // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
836             // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
837             // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
838             // programs as being 5.4+...
839             type = BPF_MAP_TYPE_HASH;
840         }
841 
842         domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
843         if (specified(selinux_context)) {
844             if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
845                 ALOGE("map %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
846                       mapNames[i].c_str(), selinux_context, allowedDomainBitmask);
847                 return -EINVAL;
848             }
849             ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
850                   md[i].selinux_context, selinux_context, lookupSelinuxContext(selinux_context),
851                   lookupPinSubdir(selinux_context));
852         }
853 
854         domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
855         if (unrecognized(pin_subdir)) return -ENOTDIR;
856         if (specified(pin_subdir)) {
857             if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
858                 ALOGE("map %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)",
859                       mapNames[i].c_str(), pin_subdir, allowedDomainBitmask);
860                 return -EINVAL;
861             }
862             ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
863                   pin_subdir, lookupPinSubdir(pin_subdir));
864         }
865 
866         // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
867         // except that maps shared across .o's have empty <objName>
868         // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
869         string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
870                            (md[i].shared ? "" : objName) + "_" + mapNames[i];
871         bool reuse = false;
872         unique_fd fd;
873         int saved_errno;
874 
875         if (access(mapPinLoc.c_str(), F_OK) == 0) {
876             fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
877             saved_errno = errno;
878             ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
879             reuse = true;
880         } else {
881             struct bpf_create_map_attr attr = {
882                 .name = mapNames[i].c_str(),
883                 .map_type = type,
884                 .map_flags = md[i].map_flags,
885                 .key_size = md[i].key_size,
886                 .value_size = md[i].value_size,
887                 .max_entries = md[i].max_entries,
888             };
889             if (btfFd.has_value() && btfTypeIdMap.find(mapNames[i]) != btfTypeIdMap.end()) {
890                 attr.btf_fd = btfFd->get();
891                 attr.btf_key_type_id = btfTypeIdMap.at(mapNames[i]).first;
892                 attr.btf_value_type_id = btfTypeIdMap.at(mapNames[i]).second;
893             }
894             fd.reset(bcc_create_map_xattr(&attr, true));
895             saved_errno = errno;
896             ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
897         }
898 
899         if (!fd.ok()) return -saved_errno;
900 
901         // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
902         // safety (since reuse code path is rare) run these checks even if we just created it.
903         // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
904         if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
905 
906         if (!reuse) {
907             if (specified(selinux_context)) {
908                 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
909                                    "tmp_map_" + objName + "_" + mapNames[i];
910                 ret = bpf_obj_pin(fd, createLoc.c_str());
911                 if (ret) {
912                     int err = errno;
913                     ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
914                     return -err;
915                 }
916                 ret = renameat2(AT_FDCWD, createLoc.c_str(),
917                                 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
918                 if (ret) {
919                     int err = errno;
920                     ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
921                           err, strerror(err));
922                     return -err;
923                 }
924             } else {
925                 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
926                 if (ret) {
927                     int err = errno;
928                     ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
929                     return -err;
930                 }
931             }
932             ret = chmod(mapPinLoc.c_str(), md[i].mode);
933             if (ret) {
934                 int err = errno;
935                 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
936                       strerror(err));
937                 return -err;
938             }
939             ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
940             if (ret) {
941                 int err = errno;
942                 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
943                       ret, err, strerror(err));
944                 return -err;
945             }
946         }
947 
948         struct bpf_map_info map_info = {};
949         __u32 map_info_len = sizeof(map_info);
950         int rv = bpf_obj_get_info_by_fd(fd, &map_info, &map_info_len);
951         if (rv) {
952             ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
953         } else {
954             ALOGI("map %s id %d", mapPinLoc.c_str(), map_info.id);
955         }
956 
957         mapFds.push_back(std::move(fd));
958     }
959 
960     return ret;
961 }
962 
963 /* For debugging, dump all instructions */
dumpIns(char * ins,int size)964 static void dumpIns(char* ins, int size) {
965     for (int row = 0; row < size / 8; row++) {
966         ALOGE("%d: ", row);
967         for (int j = 0; j < 8; j++) {
968             ALOGE("%3x ", ins[(row * 8) + j]);
969         }
970         ALOGE("\n");
971     }
972 }
973 
974 /* For debugging, dump all code sections from cs list */
dumpAllCs(vector<codeSection> & cs)975 static void dumpAllCs(vector<codeSection>& cs) {
976     for (int i = 0; i < (int)cs.size(); i++) {
977         ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
978         dumpIns((char*)cs[i].data.data(), cs[i].data.size());
979         ALOGE("-----------");
980     }
981 }
982 
applyRelo(void * insnsPtr,Elf64_Addr offset,int fd)983 static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
984     int insnIndex;
985     struct bpf_insn *insn, *insns;
986 
987     insns = (struct bpf_insn*)(insnsPtr);
988 
989     insnIndex = offset / sizeof(struct bpf_insn);
990     insn = &insns[insnIndex];
991 
992     // Occasionally might be useful for relocation debugging, but pretty spammy
993     if (0) {
994         ALOGD("applying relo to instruction at byte offset: %llu, "
995               "insn offset %d, insn %llx",
996               (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
997     }
998 
999     if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
1000         ALOGE("Dumping all instructions till ins %d", insnIndex);
1001         ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
1002         dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
1003         return;
1004     }
1005 
1006     insn->imm = fd;
1007     insn->src_reg = BPF_PSEUDO_MAP_FD;
1008 }
1009 
applyMapRelo(ifstream & elfFile,vector<unique_fd> & mapFds,vector<codeSection> & cs)1010 static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
1011     vector<string> mapNames;
1012 
1013     int ret = getSectionSymNames(elfFile, "maps", mapNames);
1014     if (ret) return;
1015 
1016     for (int k = 0; k != (int)cs.size(); k++) {
1017         Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
1018         int n_rel = cs[k].rel_data.size() / sizeof(*rel);
1019 
1020         for (int i = 0; i < n_rel; i++) {
1021             int symIndex = ELF64_R_SYM(rel[i].r_info);
1022             string symName;
1023 
1024             ret = getSymNameByIdx(elfFile, symIndex, symName);
1025             if (ret) return;
1026 
1027             /* Find the map fd and apply relo */
1028             for (int j = 0; j < (int)mapNames.size(); j++) {
1029                 if (!mapNames[j].compare(symName)) {
1030                     applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
1031                     break;
1032                 }
1033             }
1034         }
1035     }
1036 }
1037 
loadCodeSections(const char * elfPath,vector<codeSection> & cs,const string & license,const char * prefix,const unsigned long long allowedDomainBitmask)1038 static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
1039                             const char* prefix, const unsigned long long allowedDomainBitmask) {
1040     unsigned kvers = kernelVersion();
1041     int ret, fd;
1042 
1043     if (!kvers) {
1044         ALOGE("unable to get kernel version");
1045         return -EINVAL;
1046     }
1047 
1048     string objName = pathToObjName(string(elfPath));
1049 
1050     for (int i = 0; i < (int)cs.size(); i++) {
1051         string name = cs[i].name;
1052 
1053         if (!cs[i].prog_def.has_value()) {
1054             ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
1055             return -EINVAL;
1056         }
1057 
1058         unsigned min_kver = cs[i].prog_def->min_kver;
1059         unsigned max_kver = cs[i].prog_def->max_kver;
1060         ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1061              max_kver, kvers);
1062         if (kvers < min_kver) continue;
1063         if (kvers >= max_kver) continue;
1064 
1065         unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1066         unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1067         domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1068         domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
1069         // Note: make sure to only check for unrecognized *after* verifying bpfloader
1070         // version limits include this bpfloader's version.
1071 
1072         ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
1073               bpfMinVer, bpfMaxVer);
1074         if (BPFLOADER_VERSION < bpfMinVer) continue;
1075         if (BPFLOADER_VERSION >= bpfMaxVer) continue;
1076 
1077         if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1078             (cs[i].prog_def->ignore_on_user && isUser()) ||
1079             (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1080             ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1081                   getBuildType().c_str());
1082             continue;
1083         }
1084 
1085         if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
1086             (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
1087             (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
1088             (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
1089             (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
1090             ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
1091             continue;
1092         }
1093 
1094         if (unrecognized(pin_subdir)) return -ENOTDIR;
1095 
1096         if (specified(selinux_context)) {
1097             if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
1098                 ALOGE("prog %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
1099                       name.c_str(), selinux_context, allowedDomainBitmask);
1100                 return -EINVAL;
1101             }
1102             ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
1103                   cs[i].prog_def->selinux_context, selinux_context,
1104                   lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1105         }
1106 
1107         if (specified(pin_subdir)) {
1108             if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
1109                 ALOGE("prog %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)", name.c_str(),
1110                       pin_subdir, allowedDomainBitmask);
1111                 return -EINVAL;
1112             }
1113             ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
1114                   cs[i].prog_def->pin_subdir, pin_subdir, lookupPinSubdir(pin_subdir));
1115         }
1116 
1117         // strip any potential $foo suffix
1118         // this can be used to provide duplicate programs
1119         // conditionally loaded based on running kernel version
1120         name = name.substr(0, name.find_last_of('$'));
1121 
1122         bool reuse = false;
1123         // Format of pin location is
1124         // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
1125         string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
1126                             objName + '_' + string(name);
1127         if (access(progPinLoc.c_str(), F_OK) == 0) {
1128             fd = retrieveProgram(progPinLoc.c_str());
1129             ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd,
1130                   (fd < 0 ? std::strerror(errno) : "no error"));
1131             reuse = true;
1132         } else {
1133             vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1134 
1135             struct bpf_load_program_attr attr = {
1136                 .prog_type = cs[i].type,
1137                 .name = name.c_str(),
1138                 .insns = (struct bpf_insn*)cs[i].data.data(),
1139                 .license = license.c_str(),
1140                 .log_level = 0,
1141                 .expected_attach_type = cs[i].expected_attach_type,
1142             };
1143 
1144             fd = bcc_prog_load_xattr(&attr, cs[i].data.size(), log_buf.data(), log_buf.size(),
1145                     true);
1146 
1147             ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)", elfPath,
1148                   cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
1149 
1150             if (fd < 0) {
1151                 vector<string> lines = android::base::Split(log_buf.data(), "\n");
1152 
1153                 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
1154                 for (const auto& line : lines) ALOGW("%s", line.c_str());
1155                 ALOGW("bpf_prog_load - END log_buf contents.");
1156 
1157                 if (cs[i].prog_def->optional) {
1158                     ALOGW("failed program is marked optional - continuing...");
1159                     continue;
1160                 }
1161                 ALOGE("non-optional program failed to load.");
1162             }
1163         }
1164 
1165         if (fd < 0) return fd;
1166         if (fd == 0) return -EINVAL;
1167 
1168         if (!reuse) {
1169             if (specified(selinux_context)) {
1170                 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
1171                                    "tmp_prog_" + objName + '_' + string(name);
1172                 ret = bpf_obj_pin(fd, createLoc.c_str());
1173                 if (ret) {
1174                     int err = errno;
1175                     ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1176                     return -err;
1177                 }
1178                 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1179                                 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
1180                 if (ret) {
1181                     int err = errno;
1182                     ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1183                           err, strerror(err));
1184                     return -err;
1185                 }
1186             } else {
1187                 ret = bpf_obj_pin(fd, progPinLoc.c_str());
1188                 if (ret) {
1189                     int err = errno;
1190                     ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1191                     return -err;
1192                 }
1193             }
1194             if (chmod(progPinLoc.c_str(), 0440)) {
1195                 int err = errno;
1196                 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1197                 return -err;
1198             }
1199             if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1200                       (gid_t)cs[i].prog_def->gid)) {
1201                 int err = errno;
1202                 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1203                       cs[i].prog_def->gid, err, strerror(err));
1204                 return -err;
1205             }
1206         }
1207 
1208         struct bpf_prog_info prog_info = {};
1209         __u32 prog_info_len = sizeof(prog_info);
1210         int rv = bpf_obj_get_info_by_fd(fd, &prog_info, &prog_info_len);
1211         if (rv) {
1212             ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
1213         } else {
1214             ALOGI("prog %s id %d", progPinLoc.c_str(), prog_info.id);
1215         }
1216 
1217         cs[i].prog_fd.reset(fd);
1218     }
1219 
1220     return 0;
1221 }
1222 
loadProg(const char * elfPath,bool * isCritical,const Location & location)1223 int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
1224     vector<char> license;
1225     vector<char> critical;
1226     vector<codeSection> cs;
1227     vector<unique_fd> mapFds;
1228     int ret;
1229 
1230     if (!isCritical) return -1;
1231     *isCritical = false;
1232 
1233     ifstream elfFile(elfPath, ios::in | ios::binary);
1234     if (!elfFile.is_open()) return -1;
1235 
1236     ret = readSectionByName("critical", elfFile, critical);
1237     *isCritical = !ret;
1238 
1239     ret = readSectionByName("license", elfFile, license);
1240     if (ret) {
1241         ALOGE("Couldn't find license in %s", elfPath);
1242         return ret;
1243     } else {
1244         ALOGD("Loading %s%s ELF object %s with license %s",
1245               *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
1246               elfPath, (char*)license.data());
1247     }
1248 
1249     // the following default values are for bpfloader V0.0 format which does not include them
1250     unsigned int bpfLoaderMinVer =
1251             readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1252     unsigned int bpfLoaderMaxVer =
1253             readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
1254     unsigned int bpfLoaderMinRequiredVer =
1255             readSectionUint("bpfloader_min_required_ver", elfFile, 0);
1256     size_t sizeOfBpfMapDef =
1257             readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1258     size_t sizeOfBpfProgDef =
1259             readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1260 
1261     // inclusive lower bound check
1262     if (BPFLOADER_VERSION < bpfLoaderMinVer) {
1263         ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
1264               BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
1265         return 0;
1266     }
1267 
1268     // exclusive upper bound check
1269     if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
1270         ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
1271               BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
1272         return 0;
1273     }
1274 
1275     if (BPFLOADER_VERSION < bpfLoaderMinRequiredVer) {
1276         ALOGI("BpfLoader version 0x%05x failing due to ELF object %s with required min ver 0x%05x",
1277               BPFLOADER_VERSION, elfPath, bpfLoaderMinRequiredVer);
1278         return -1;
1279     }
1280 
1281     ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
1282           BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1283 
1284     if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
1285         ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
1286               DEFAULT_SIZEOF_BPF_MAP_DEF);
1287         return -1;
1288     }
1289 
1290     if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
1291         ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
1292               DEFAULT_SIZEOF_BPF_PROG_DEF);
1293         return -1;
1294     }
1295 
1296     ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, location.allowedProgTypes,
1297                            location.allowedProgTypesLength);
1298     if (ret) {
1299         ALOGE("Couldn't read all code sections in %s", elfPath);
1300         return ret;
1301     }
1302 
1303     /* Just for future debugging */
1304     if (0) dumpAllCs(cs);
1305 
1306     ret = createMaps(elfPath, elfFile, mapFds, location.prefix, location.allowedDomainBitmask,
1307                      sizeOfBpfMapDef);
1308     if (ret) {
1309         ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
1310         return ret;
1311     }
1312 
1313     for (int i = 0; i < (int)mapFds.size(); i++)
1314         ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
1315 
1316     applyMapRelo(elfFile, mapFds, cs);
1317 
1318     ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix,
1319                            location.allowedDomainBitmask);
1320     if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
1321 
1322     return ret;
1323 }
1324 
1325 }  // namespace bpf
1326 }  // namespace android
1327