blob: 4a2684dae9a2a7180a4b2f70969efa0f454fb9e4 [file] [log] [blame]
Joel Fernandesd76a2002018-10-16 13:19:58 -07001/*
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 <linux/bpf.h>
21#include <linux/elf.h>
22#include <log/log.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080027#include <sysexits.h>
Maciej Żenczykowski83f29772020-01-27 03:11:51 -080028#include <sys/stat.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070029#include <sys/utsname.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080030#include <sys/wait.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070031#include <unistd.h>
32
Ryan Zukliece89f502022-12-15 16:14:32 -080033// This is BpfLoader v0.32
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080034#define BPFLOADER_VERSION_MAJOR 0u
Ryan Zukliece89f502022-12-15 16:14:32 -080035#define BPFLOADER_VERSION_MINOR 32u
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080036#define BPFLOADER_VERSION ((BPFLOADER_VERSION_MAJOR << 16) | BPFLOADER_VERSION_MINOR)
37
Maciej Żenczykowski300c51f2022-12-14 04:18:02 -080038#include "BpfSyscallWrappers.h"
Maciej Żenczykowski07375e22020-02-19 14:23:59 -080039#include "bpf/BpfUtils.h"
Ken Chend5689472021-12-20 18:07:21 +080040#include "bpf/bpf_map_def.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070041#include "include/libbpf_android.h"
42
Maciej Żenczykowskib3dcc142022-07-24 22:42:33 +000043#if BPFLOADER_VERSION < COMPILE_FOR_BPFLOADER_VERSION
44#error "BPFLOADER_VERSION is less than COMPILE_FOR_BPFLOADER_VERSION"
45#endif
46
Connor O'Brien35425e52022-01-18 21:41:16 -080047#include <bpf/bpf.h>
48
Joel Fernandesd76a2002018-10-16 13:19:58 -070049#include <cstdlib>
50#include <fstream>
51#include <iostream>
Connor O'Brien3278a162020-02-13 21:45:22 -080052#include <optional>
Joel Fernandesd76a2002018-10-16 13:19:58 -070053#include <string>
Connor O'Brien35425e52022-01-18 21:41:16 -080054#include <unordered_map>
Christopher Ferrisc151c672019-02-01 15:31:26 -080055#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070056
Connor O'Brien35425e52022-01-18 21:41:16 -080057#include <android-base/cmsg.h>
58#include <android-base/file.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070059#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070060#include <android-base/unique_fd.h>
Ryan Zukliece89f502022-12-15 16:14:32 -080061#include <cutils/properties.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070062
63#define BPF_FS_PATH "/sys/fs/bpf/"
64
65// Size of the BPF log buffer for verifier logging
Stephane Leeeb61b732021-10-21 17:03:11 -070066#define BPF_LOAD_LOG_SZ 0xfffff
Joel Fernandesd76a2002018-10-16 13:19:58 -070067
Tyler Wear4e2f4602022-02-03 09:46:01 -080068// Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
69#define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
70
Joel Fernandesd76a2002018-10-16 13:19:58 -070071using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070072using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070073using std::ifstream;
74using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080075using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080076using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070077using std::vector;
78
Ryan Zukliece89f502022-12-15 16:14:32 -080079static std::string getBuildTypeInternal() {
80 char value[PROPERTY_VALUE_MAX] = {};
81 (void)property_get("ro.build.type", value, "unknown"); // ignore length
82 return value;
83}
84
Joel Fernandesd76a2002018-10-16 13:19:58 -070085namespace android {
86namespace bpf {
87
Ryan Zukliece89f502022-12-15 16:14:32 -080088const std::string& getBuildType() {
89 static std::string t = getBuildTypeInternal();
90 return t;
91}
92
Maciej Żenczykowski41817132022-06-03 08:41:04 -070093constexpr const char* lookupSelinuxContext(const domain d, const char* const unspecified = "") {
94 switch (d) {
95 case domain::unspecified: return unspecified;
96 case domain::platform: return "fs_bpf";
97 case domain::tethering: return "fs_bpf_tethering";
98 case domain::net_private: return "fs_bpf_net_private";
99 case domain::net_shared: return "fs_bpf_net_shared";
100 case domain::netd_readonly: return "fs_bpf_netd_readonly";
101 case domain::netd_shared: return "fs_bpf_netd_shared";
102 case domain::vendor: return "fs_bpf_vendor";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +0000103 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700104 default: return "(unrecognized)";
105 }
106}
107
108domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
109 for (domain d : AllDomains) {
110 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
111 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
112 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
113 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700114 ALOGW("ignoring unrecognized selinux_context '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700115 // We should return 'unrecognized' here, however: returning unspecified will
116 // result in the system simply using the default context, which in turn
117 // will allow future expansion by adding more restrictive selinux types.
118 // Older bpfloader will simply ignore that, and use the less restrictive default.
119 // This does mean you CANNOT later add a *less* restrictive type than the default.
120 //
121 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
122 return domain::unspecified;
123}
124
125constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
126 switch (d) {
127 case domain::unspecified: return unspecified;
128 case domain::platform: return "/";
129 case domain::tethering: return "tethering/";
130 case domain::net_private: return "net_private/";
131 case domain::net_shared: return "net_shared/";
132 case domain::netd_readonly: return "netd_readonly/";
133 case domain::netd_shared: return "netd_shared/";
134 case domain::vendor: return "vendor/";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +0000135 case domain::loader: return "loader/";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700136 default: return "(unrecognized)";
137 }
138};
139
140domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
141 for (domain d : AllDomains) {
142 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
143 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
144 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
145 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700146 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700147 // pin_subdir affects the object's full pathname,
148 // and thus using the default would change the location and thus our code's ability to find it,
149 // hence this seems worth treating as a true error condition.
150 //
151 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
152 // However, our callers will treat this as an error, and stop loading the specific .o,
153 // which will fail bpfloader if the .o is marked critical.
154 return domain::unrecognized;
155}
156
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700157static string pathToObjName(const string& path) {
158 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
159 string filename = android::base::Split(path, "/").back();
160 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
161 string name = filename.substr(0, filename.find_last_of('.'));
162 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
163 // this can be used to provide duplicate programs (mux based on the bpfloader version)
164 return name.substr(0, name.find_last_of('@'));
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800165}
166
Joel Fernandesd76a2002018-10-16 13:19:58 -0700167typedef struct {
168 const char* name;
169 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800170 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700171} sectionType;
172
173/*
174 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700175 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -0700176 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700177 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -0700178 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700179 *
180 * However, be aware that you should not be directly using the SECTION() macro.
181 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -0700182 */
183sectionType sectionNameTypes[] = {
Tyler Wear4e2f4602022-02-03 09:46:01 -0800184 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
185 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
186 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB, BPF_ATTACH_TYPE_UNSPEC},
187 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_ATTACH_TYPE_UNSPEC},
188 {"kprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie092e0b2022-05-24 13:14:32 +0000189 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT, BPF_ATTACH_TYPE_UNSPEC},
Tyler Wear4e2f4602022-02-03 09:46:01 -0800190 {"schedact/", BPF_PROG_TYPE_SCHED_ACT, BPF_ATTACH_TYPE_UNSPEC},
191 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS, BPF_ATTACH_TYPE_UNSPEC},
192 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
193 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
194 {"xdp/", BPF_PROG_TYPE_XDP, BPF_ATTACH_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700195};
196
197typedef struct {
198 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800199 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700200 string name;
201 vector<char> data;
202 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800203 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700204
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700205 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700206} codeSection;
207
Joel Fernandesd76a2002018-10-16 13:19:58 -0700208static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
209 elfFile.seekg(0);
210 if (elfFile.fail()) return -1;
211
212 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
213
214 return 0;
215}
216
217/* Reads all section header tables into an Shdr array */
218static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
219 Elf64_Ehdr eh;
220 int ret = 0;
221
222 ret = readElfHeader(elfFile, &eh);
223 if (ret) return ret;
224
225 elfFile.seekg(eh.e_shoff);
226 if (elfFile.fail()) return -1;
227
228 /* Read shdr table entries */
229 shTable.resize(eh.e_shnum);
230
231 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
232
233 return 0;
234}
235
236/* Read a section by its index - for ex to get sec hdr strtab blob */
237static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
238 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800239 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700240 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700241
242 elfFile.seekg(shTable[id].sh_offset);
243 if (elfFile.fail()) return -1;
244
245 sec.resize(shTable[id].sh_size);
246 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
247
248 return 0;
249}
250
251/* Read whole section header string table */
252static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
253 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800254 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700255 if (ret) return ret;
256
257 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
258 if (ret) return ret;
259
260 return 0;
261}
262
263/* Get name from offset in strtab */
264static int getSymName(ifstream& elfFile, int nameOff, string& name) {
265 int ret;
266 vector<char> secStrTab;
267
268 ret = readSectionHeaderStrtab(elfFile, secStrTab);
269 if (ret) return ret;
270
271 if (nameOff >= (int)secStrTab.size()) return -1;
272
273 name = string((char*)secStrTab.data() + nameOff);
274 return 0;
275}
276
277/* Reads a full section by name - example to get the GPL license */
278static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
279 vector<char> secStrTab;
280 vector<Elf64_Shdr> shTable;
281 int ret;
282
283 ret = readSectionHeadersAll(elfFile, shTable);
284 if (ret) return ret;
285
286 ret = readSectionHeaderStrtab(elfFile, secStrTab);
287 if (ret) return ret;
288
289 for (int i = 0; i < (int)shTable.size(); i++) {
290 char* secname = secStrTab.data() + shTable[i].sh_name;
291 if (!secname) continue;
292
293 if (!strcmp(secname, name)) {
294 vector<char> dataTmp;
295 dataTmp.resize(shTable[i].sh_size);
296
297 elfFile.seekg(shTable[i].sh_offset);
298 if (elfFile.fail()) return -1;
299
300 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
301
302 data = dataTmp;
303 return 0;
304 }
305 }
306 return -2;
307}
308
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700309unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800310 vector<char> theBytes;
311 int ret = readSectionByName(name, elfFile, theBytes);
312 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700313 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800314 return defVal;
315 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700316 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800317 return defVal;
318 } else {
319 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
320 unsigned int value = static_cast<unsigned char>(theBytes[3]);
321 value <<= 8;
322 value += static_cast<unsigned char>(theBytes[2]);
323 value <<= 8;
324 value += static_cast<unsigned char>(theBytes[1]);
325 value <<= 8;
326 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700327 ALOGI("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800328 return value;
329 }
330}
331
Joel Fernandesd76a2002018-10-16 13:19:58 -0700332static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
333 int ret;
334 vector<Elf64_Shdr> shTable;
335
336 ret = readSectionHeadersAll(elfFile, shTable);
337 if (ret) return ret;
338
339 for (int i = 0; i < (int)shTable.size(); i++) {
340 if ((int)shTable[i].sh_type != type) continue;
341
342 vector<char> dataTmp;
343 dataTmp.resize(shTable[i].sh_size);
344
345 elfFile.seekg(shTable[i].sh_offset);
346 if (elfFile.fail()) return -1;
347
348 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
349
350 data = dataTmp;
351 return 0;
352 }
353 return -2;
354}
355
356static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
357 return (a.st_value < b.st_value);
358}
359
360static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
361 int ret, numElems;
362 Elf64_Sym* buf;
363 vector<char> secData;
364
365 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
366 if (ret) return ret;
367
368 buf = (Elf64_Sym*)secData.data();
369 numElems = (secData.size() / sizeof(Elf64_Sym));
370 data.assign(buf, buf + numElems);
371
372 if (sort) std::sort(data.begin(), data.end(), symCompare);
373 return 0;
374}
375
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700376static enum bpf_prog_type getFuseProgType() {
377 int result = BPF_PROG_TYPE_UNSPEC;
378 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
379 return static_cast<bpf_prog_type>(result);
380}
381
Joel Fernandesd76a2002018-10-16 13:19:58 -0700382static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800383 for (auto& snt : sectionNameTypes)
384 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700385
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000386 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700387 if (StartsWith(name, "fuse/")) return getFuseProgType();
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000388
Joel Fernandesd76a2002018-10-16 13:19:58 -0700389 return BPF_PROG_TYPE_UNSPEC;
390}
391
Tyler Wear4e2f4602022-02-03 09:46:01 -0800392static enum bpf_attach_type getExpectedAttachType(string& name) {
393 for (auto& snt : sectionNameTypes)
394 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
395 return BPF_ATTACH_TYPE_UNSPEC;
396}
397
Joel Fernandesd76a2002018-10-16 13:19:58 -0700398static string getSectionName(enum bpf_prog_type type)
399{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800400 for (auto& snt : sectionNameTypes)
401 if (snt.type == type)
402 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700403
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800404 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700405}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700406
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800407static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
408 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800409 vector<char> pdData;
410 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800411 // Older file formats do not require a 'progs' section at all.
412 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800413 if (ret == -2) return 0;
414 if (ret) return ret;
415
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800416 if (pdData.size() % sizeOfBpfProgDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700417 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800418 pdData.size(), sizeOfBpfProgDef);
419 return -1;
420 };
421
422 int progCount = pdData.size() / sizeOfBpfProgDef;
423 pd.resize(progCount);
424 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
425
426 const char* dataPtr = pdData.data();
427 for (auto& p : pd) {
428 // First we zero initialize
429 memset(&p, 0, sizeof(p));
430 // Then we set non-zero defaults
431 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
432 // Then we copy over the structure prefix from the ELF file.
433 memcpy(&p, dataPtr, trimmedSize);
434 // Move to next struct in the ELF file
435 dataPtr += sizeOfBpfProgDef;
436 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800437 return 0;
438}
439
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800440static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
441 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800442 int ret;
443 string name;
444 vector<Elf64_Sym> symtab;
445 vector<Elf64_Shdr> shTable;
446
447 ret = readSymTab(elfFile, 1 /* sort */, symtab);
448 if (ret) return ret;
449
450 /* Get index of section */
451 ret = readSectionHeadersAll(elfFile, shTable);
452 if (ret) return ret;
453
454 int sec_idx = -1;
455 for (int i = 0; i < (int)shTable.size(); i++) {
456 ret = getSymName(elfFile, shTable[i].sh_name, name);
457 if (ret) return ret;
458
459 if (!name.compare(sectionName)) {
460 sec_idx = i;
461 break;
462 }
463 }
464
465 /* No section found with matching name*/
466 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700467 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800468 return -1;
469 }
470
471 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800472 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
473
Connor O'Brien3278a162020-02-13 21:45:22 -0800474 if (symtab[i].st_shndx == sec_idx) {
475 string s;
476 ret = getSymName(elfFile, symtab[i].st_name, s);
477 if (ret) return ret;
478 names.push_back(s);
479 }
480 }
481
482 return 0;
483}
484
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800485static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
486 if (allowed == nullptr) return true;
487
488 for (size_t i = 0; i < numAllowed; i++) {
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700489 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
490 if (type == getFuseProgType()) return true;
491 } else if (type == allowed[i])
492 return true;
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800493 }
494
495 return false;
496}
497
Joel Fernandesd76a2002018-10-16 13:19:58 -0700498/* Read a section by its index - for ex to get sec hdr strtab blob */
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800499static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef,
500 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700501 vector<Elf64_Shdr> shTable;
502 int entries, ret = 0;
503
504 ret = readSectionHeadersAll(elfFile, shTable);
505 if (ret) return ret;
506 entries = shTable.size();
507
Connor O'Brien3278a162020-02-13 21:45:22 -0800508 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800509 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800510 if (ret) return ret;
511 vector<string> progDefNames;
512 ret = getSectionSymNames(elfFile, "progs", progDefNames);
513 if (!pd.empty() && ret) return ret;
514
Joel Fernandesd76a2002018-10-16 13:19:58 -0700515 for (int i = 0; i < entries; i++) {
516 string name;
517 codeSection cs_temp;
518 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
519
520 ret = getSymName(elfFile, shTable[i].sh_name, name);
521 if (ret) return ret;
522
523 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800524
Tyler Wear4e2f4602022-02-03 09:46:01 -0800525 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800526
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800527 if (!IsAllowed(ptype, allowed, numAllowed)) {
528 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
529 return -1;
530 }
531
Tyler Wear4e2f4602022-02-03 09:46:01 -0800532 // This must be done before '/' is replaced with '_'.
533 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800534
Tyler Wear4e2f4602022-02-03 09:46:01 -0800535 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700536
Tyler Wear4e2f4602022-02-03 09:46:01 -0800537 // convert all slashes to underscores
538 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800539
Tyler Wear4e2f4602022-02-03 09:46:01 -0800540 cs_temp.type = ptype;
541 cs_temp.name = name;
542
543 ret = readSectionByIdx(elfFile, i, cs_temp.data);
544 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700545 ALOGD("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800546
547 vector<string> csSymNames;
548 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
549 if (ret || !csSymNames.size()) return ret;
550 for (size_t i = 0; i < progDefNames.size(); ++i) {
551 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
552 cs_temp.prog_def = pd[i];
553 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800554 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700555 }
556
557 /* Check for rel section */
558 if (cs_temp.data.size() > 0 && i < entries) {
559 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
560 if (ret) return ret;
561
Tyler Wear4e2f4602022-02-03 09:46:01 -0800562 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700563 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
564 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700565 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700566 }
567 }
568
569 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700570 cs.push_back(std::move(cs_temp));
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700571 ALOGD("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700572 }
573 }
574 return 0;
575}
576
577static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
578 vector<Elf64_Sym> symtab;
579 int ret = 0;
580
581 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
582 if (ret) return ret;
583
584 if (index >= (int)symtab.size()) return -1;
585
586 return getSymName(elfFile, symtab[index].st_name, name);
587}
588
Connor O'Brien35425e52022-01-18 21:41:16 -0800589static bool waitpidTimeout(pid_t pid, int timeoutMs) {
590 // Add SIGCHLD to the signal set.
591 sigset_t child_mask, original_mask;
592 sigemptyset(&child_mask);
593 sigaddset(&child_mask, SIGCHLD);
594 if (sigprocmask(SIG_BLOCK, &child_mask, &original_mask) == -1) return false;
595
596 // Wait for a SIGCHLD notification.
597 errno = 0;
598 timespec ts = {0, timeoutMs * 1000000};
599 int wait_result = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, nullptr, &ts));
600
601 // Restore the original signal set.
602 sigprocmask(SIG_SETMASK, &original_mask, nullptr);
603
604 if (wait_result == -1) return false;
605
606 int status;
607 return TEMP_FAILURE_RETRY(waitpid(pid, &status, WNOHANG)) == pid;
608}
609
610static std::optional<unique_fd> getMapBtfInfo(const char* elfPath,
611 std::unordered_map<string, std::pair<uint32_t, uint32_t>> &btfTypeIds) {
612 unique_fd bpfloaderSocket, btfloaderSocket;
613 if (!android::base::Socketpair(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0, &bpfloaderSocket,
614 &btfloaderSocket)) {
615 return {};
616 }
617
618 unique_fd pipeRead, pipeWrite;
619 if (!android::base::Pipe(&pipeRead, &pipeWrite, O_NONBLOCK)) {
620 return {};
621 }
622
623 pid_t pid = fork();
624 if (pid < 0) return {};
625 if (!pid) {
626 bpfloaderSocket.reset();
627 pipeRead.reset();
628 auto socketFdStr = std::to_string(btfloaderSocket.release());
629 auto pipeFdStr = std::to_string(pipeWrite.release());
630
631 if (execl("/system/bin/btfloader", "/system/bin/btfloader", socketFdStr.c_str(),
632 pipeFdStr.c_str(), elfPath, NULL) == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700633 ALOGW("exec btfloader failed with errno %d (%s)", errno, strerror(errno));
Connor O'Brien35425e52022-01-18 21:41:16 -0800634 exit(EX_UNAVAILABLE);
635 }
636 }
637 btfloaderSocket.reset();
638 pipeWrite.reset();
639 if (!waitpidTimeout(pid, 100)) {
640 kill(pid, SIGKILL);
641 return {};
642 }
643
644 unique_fd btfFd;
645 if (android::base::ReceiveFileDescriptors(bpfloaderSocket, nullptr, 0, &btfFd)) return {};
646
647 std::string btfTypeIdStr;
648 if (!android::base::ReadFdToString(pipeRead, &btfTypeIdStr)) return {};
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700649 if (!btfFd.ok()) return {};
Connor O'Brien35425e52022-01-18 21:41:16 -0800650
651 const auto mapTypeIdLines = android::base::Split(btfTypeIdStr, "\n");
652 for (const auto &line : mapTypeIdLines) {
653 const auto vec = android::base::Split(line, " ");
654 // Splitting on newline will give us one empty line
655 if (vec.size() != 3) continue;
656 const int kTid = atoi(vec[1].c_str());
657 const int vTid = atoi(vec[2].c_str());
658 if (!kTid || !vTid) return {};
659 btfTypeIds[vec[0]] = std::make_pair(kTid, vTid);
660 }
661 return btfFd;
662}
663
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700664static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
665 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700666 // Assuming fd is a valid Bpf Map file descriptor then
667 // all the following should always succeed on a 4.14+ kernel.
668 // If they somehow do fail, they'll return -1 (and set errno),
669 // which should then cause (among others) a key_size mismatch.
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700670 int fd_type = bpfGetFdMapType(fd);
671 int fd_key_size = bpfGetFdKeySize(fd);
672 int fd_value_size = bpfGetFdValueSize(fd);
673 int fd_max_entries = bpfGetFdMaxEntries(fd);
674 int fd_map_flags = bpfGetFdMapFlags(fd);
675
676 // DEVMAPs are readonly from the bpf program side's point of view, as such
677 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
678 int desired_map_flags = (int)mapDef.map_flags;
679 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
680 desired_map_flags |= BPF_F_RDONLY_PROG;
681
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700682 // The following checks should *never* trigger, if one of them somehow does,
683 // it probably means a bpf .o file has been changed/replaced at runtime
684 // and bpfloader was manually rerun (normally it should only run *once*
685 // early during the boot process).
686 // Another possibility is that something is misconfigured in the code:
687 // most likely a shared map is declared twice differently.
688 // But such a change should never be checked into the source tree...
689 if ((fd_type == type) &&
690 (fd_key_size == (int)mapDef.key_size) &&
691 (fd_value_size == (int)mapDef.value_size) &&
692 (fd_max_entries == (int)mapDef.max_entries) &&
693 (fd_map_flags == desired_map_flags)) {
694 return true;
695 }
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700696
697 ALOGE("bpf map name %s mismatch: desired/found: "
698 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
699 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
700 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
701 return false;
702}
703
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800704static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700705 const char* prefix, const unsigned long long allowedDomainBitmask,
706 const size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700707 int ret;
Connor O'Brien35425e52022-01-18 21:41:16 -0800708 vector<char> mdData, btfData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700709 vector<struct bpf_map_def> md;
710 vector<string> mapNames;
Connor O'Brien35425e52022-01-18 21:41:16 -0800711 std::unordered_map<string, std::pair<uint32_t, uint32_t>> btfTypeIdMap;
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700712 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700713
714 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800715 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700716 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800717
718 if (mdData.size() % sizeOfBpfMapDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700719 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800720 mdData.size(), sizeOfBpfMapDef);
721 return -1;
722 };
723
724 int mapCount = mdData.size() / sizeOfBpfMapDef;
725 md.resize(mapCount);
726 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
727
728 const char* dataPtr = mdData.data();
729 for (auto& m : md) {
730 // First we zero initialize
731 memset(&m, 0, sizeof(m));
732 // Then we set non-zero defaults
733 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700734 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800735 // Then we copy over the structure prefix from the ELF file.
736 memcpy(&m, dataPtr, trimmedSize);
737 // Move to next struct in the ELF file
738 dataPtr += sizeOfBpfMapDef;
739 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700740
Connor O'Brien3278a162020-02-13 21:45:22 -0800741 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700742 if (ret) return ret;
743
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700744 unsigned btfMinBpfLoaderVer = readSectionUint("btf_min_bpfloader_ver", elfFile, 0);
745 unsigned btfMinKernelVer = readSectionUint("btf_min_kernel_ver", elfFile, 0);
746 unsigned kvers = kernelVersion();
747
Connor O'Brien35425e52022-01-18 21:41:16 -0800748 std::optional<unique_fd> btfFd;
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700749 if ((BPFLOADER_VERSION >= btfMinBpfLoaderVer) && (kvers >= btfMinKernelVer) &&
750 (!readSectionByName(".BTF", elfFile, btfData))) {
Connor O'Brien35425e52022-01-18 21:41:16 -0800751 btfFd = getMapBtfInfo(elfPath, btfTypeIdMap);
752 }
753
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700754 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +0000755 if (md[i].zero != 0) abort();
756
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800757 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700758 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800759 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700760 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800761 continue;
762 }
763
764 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700765 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800766 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700767 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800768 continue;
769 }
770
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700771 if (kvers < md[i].min_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700772 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700773 mapNames[i].c_str(), kvers, md[i].min_kver);
774 mapFds.push_back(unique_fd());
775 continue;
776 }
777
778 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700779 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700780 mapNames[i].c_str(), kvers, md[i].max_kver);
781 mapFds.push_back(unique_fd());
782 continue;
783 }
784
Ryan Zukliece89f502022-12-15 16:14:32 -0800785 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
786 (md[i].ignore_on_userdebug && isUserdebug())) {
787 ALOGI("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
788 getBuildType().c_str());
789 mapFds.push_back(unique_fd());
790 continue;
791 }
792
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700793 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700794 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
795 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
796 // of be approximated: HASH has the same userspace visible api.
797 // However it cannot be used by ebpf programs in the same way.
798 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
799 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
800 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
801 // programs as being 5.4+...
802 type = BPF_MAP_TYPE_HASH;
803 }
804
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700805 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
806 if (specified(selinux_context)) {
807 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
808 ALOGE("map %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
809 mapNames[i].c_str(), selinux_context, allowedDomainBitmask);
810 return -EINVAL;
811 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700812 ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700813 md[i].selinux_context, selinux_context, lookupSelinuxContext(selinux_context),
814 lookupPinSubdir(selinux_context));
815 }
816
817 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
818 if (unrecognized(pin_subdir)) return -ENOTDIR;
819 if (specified(pin_subdir)) {
820 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
821 ALOGE("map %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)",
822 mapNames[i].c_str(), pin_subdir, allowedDomainBitmask);
823 return -EINVAL;
824 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700825 ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700826 pin_subdir, lookupPinSubdir(pin_subdir));
827 }
828
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700829 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
830 // except that maps shared across .o's have empty <objName>
831 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700832 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700833 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700834 bool reuse = false;
835 unique_fd fd;
836 int saved_errno;
837
Joel Fernandesd76a2002018-10-16 13:19:58 -0700838 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskieb199dd2022-07-01 03:21:40 -0700839 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800840 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700841 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700842 reuse = true;
843 } else {
Connor O'Brien35425e52022-01-18 21:41:16 -0800844 struct bpf_create_map_attr attr = {
845 .name = mapNames[i].c_str(),
846 .map_type = type,
847 .map_flags = md[i].map_flags,
848 .key_size = md[i].key_size,
849 .value_size = md[i].value_size,
850 .max_entries = md[i].max_entries,
851 };
852 if (btfFd.has_value() && btfTypeIdMap.find(mapNames[i]) != btfTypeIdMap.end()) {
853 attr.btf_fd = btfFd->get();
854 attr.btf_key_type_id = btfTypeIdMap.at(mapNames[i]).first;
855 attr.btf_value_type_id = btfTypeIdMap.at(mapNames[i]).second;
856 }
857 fd.reset(bcc_create_map_xattr(&attr, true));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800858 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700859 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700860 }
861
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700862 if (!fd.ok()) return -saved_errno;
863
864 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
865 // safety (since reuse code path is rare) run these checks even if we just created it.
866 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
867 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700868
869 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700870 if (specified(selinux_context)) {
871 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700872 "tmp_map_" + objName + "_" + mapNames[i];
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700873 ret = bpf_obj_pin(fd, createLoc.c_str());
874 if (ret) {
875 int err = errno;
876 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
877 return -err;
878 }
879 ret = rename(createLoc.c_str(), mapPinLoc.c_str());
880 if (ret) {
881 int err = errno;
882 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
883 err, strerror(err));
884 return -err;
885 }
886 } else {
887 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowskid8259aa2022-06-27 10:02:20 -0700888 if (ret) {
889 int err = errno;
890 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
891 return -err;
892 }
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700893 }
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800894 ret = chmod(mapPinLoc.c_str(), md[i].mode);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700895 if (ret) {
896 int err = errno;
897 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
898 strerror(err));
899 return -err;
900 }
Maciej Żenczykowski5e4aabf2022-06-27 01:15:53 -0700901 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
902 if (ret) {
903 int err = errno;
904 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
905 ret, err, strerror(err));
906 return -err;
907 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700908 }
909
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700910 struct bpf_map_info map_info = {};
911 __u32 map_info_len = sizeof(map_info);
912 int rv = bpf_obj_get_info_by_fd(fd, &map_info, &map_info_len);
913 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700914 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700915 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700916 ALOGI("map %s id %d", mapPinLoc.c_str(), map_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700917 }
918
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700919 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700920 }
921
922 return ret;
923}
924
925/* For debugging, dump all instructions */
926static void dumpIns(char* ins, int size) {
927 for (int row = 0; row < size / 8; row++) {
928 ALOGE("%d: ", row);
929 for (int j = 0; j < 8; j++) {
930 ALOGE("%3x ", ins[(row * 8) + j]);
931 }
932 ALOGE("\n");
933 }
934}
935
936/* For debugging, dump all code sections from cs list */
937static void dumpAllCs(vector<codeSection>& cs) {
938 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700939 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700940 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700941 ALOGE("-----------");
Joel Fernandesd76a2002018-10-16 13:19:58 -0700942 }
943}
944
945static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
946 int insnIndex;
947 struct bpf_insn *insn, *insns;
948
949 insns = (struct bpf_insn*)(insnsPtr);
950
951 insnIndex = offset / sizeof(struct bpf_insn);
952 insn = &insns[insnIndex];
953
Ken Chene1b518c2022-07-06 20:50:36 +0800954 ALOGD("applying relo to instruction at byte offset: %llu, "
955 "insn offset %d, insn %llx",
956 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700957
958 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700959 ALOGE("Dumping all instructions till ins %d", insnIndex);
960 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700961 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
962 return;
963 }
964
965 insn->imm = fd;
966 insn->src_reg = BPF_PSEUDO_MAP_FD;
967}
968
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700969static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700970 vector<string> mapNames;
971
Connor O'Brien3278a162020-02-13 21:45:22 -0800972 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700973 if (ret) return;
974
975 for (int k = 0; k != (int)cs.size(); k++) {
976 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
977 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
978
979 for (int i = 0; i < n_rel; i++) {
980 int symIndex = ELF64_R_SYM(rel[i].r_info);
981 string symName;
982
983 ret = getSymNameByIdx(elfFile, symIndex, symName);
984 if (ret) return;
985
986 /* Find the map fd and apply relo */
987 for (int j = 0; j < (int)mapNames.size(); j++) {
988 if (!mapNames[j].compare(symName)) {
989 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
990 break;
991 }
992 }
993 }
994 }
995}
996
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800997static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700998 const char* prefix, const unsigned long long allowedDomainBitmask) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800999 unsigned kvers = kernelVersion();
1000 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001001
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001002 if (!kvers) {
1003 ALOGE("unable to get kernel version");
1004 return -EINVAL;
1005 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001006
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001007 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001008
1009 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001010 string name = cs[i].name;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001011
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001012 if (!cs[i].prog_def.has_value()) {
1013 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
1014 return -EINVAL;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -08001015 }
1016
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001017 unsigned min_kver = cs[i].prog_def->min_kver;
1018 unsigned max_kver = cs[i].prog_def->max_kver;
1019 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1020 max_kver, kvers);
1021 if (kvers < min_kver) continue;
1022 if (kvers >= max_kver) continue;
1023
1024 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1025 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1026 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1027 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
1028 // Note: make sure to only check for unrecognized *after* verifying bpfloader
1029 // version limits include this bpfloader's version.
1030
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001031 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001032 bpfMinVer, bpfMaxVer);
1033 if (BPFLOADER_VERSION < bpfMinVer) continue;
1034 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
Ryan Zukliece89f502022-12-15 16:14:32 -08001035
1036 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1037 (cs[i].prog_def->ignore_on_user && isUser()) ||
1038 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1039 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1040 getBuildType().c_str());
1041 }
1042
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001043 if (unrecognized(pin_subdir)) return -ENOTDIR;
1044
1045 if (specified(selinux_context)) {
1046 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
1047 ALOGE("prog %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
1048 name.c_str(), selinux_context, allowedDomainBitmask);
1049 return -EINVAL;
1050 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001051 ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001052 cs[i].prog_def->selinux_context, selinux_context,
1053 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1054 }
1055
1056 if (specified(pin_subdir)) {
1057 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
1058 ALOGE("prog %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)", name.c_str(),
1059 pin_subdir, allowedDomainBitmask);
1060 return -EINVAL;
1061 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001062 ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001063 cs[i].prog_def->pin_subdir, pin_subdir, lookupPinSubdir(pin_subdir));
1064 }
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001065
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001066 // strip any potential $foo suffix
1067 // this can be used to provide duplicate programs
1068 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -07001069 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001070
1071 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001072 // Format of pin location is
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001073 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001074 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001075 objName + '_' + string(name);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001076 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001077 fd = retrieveProgram(progPinLoc.c_str());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001078 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd,
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001079 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001080 reuse = true;
1081 } else {
1082 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1083
Tyler Wear4e2f4602022-02-03 09:46:01 -08001084 struct bpf_load_program_attr attr = {
1085 .prog_type = cs[i].type,
1086 .name = name.c_str(),
1087 .insns = (struct bpf_insn*)cs[i].data.data(),
1088 .license = license.c_str(),
1089 .log_level = 0,
1090 .expected_attach_type = cs[i].expected_attach_type,
1091 };
1092
1093 fd = bcc_prog_load_xattr(&attr, cs[i].data.size(), log_buf.data(), log_buf.size(),
1094 true);
1095
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001096 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)", elfPath,
Steven Moreland804bca02019-12-12 17:21:23 -08001097 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001098
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001099 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -08001100 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001101
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001102 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
1103 for (const auto& line : lines) ALOGW("%s", line.c_str());
1104 ALOGW("bpf_prog_load - END log_buf contents.");
1105
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001106 if (cs[i].prog_def->optional) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001107 ALOGW("failed program is marked optional - continuing...");
1108 continue;
1109 }
1110 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001111 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001112 }
1113
1114 if (fd < 0) return fd;
1115 if (fd == 0) return -EINVAL;
1116
1117 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001118 if (specified(selinux_context)) {
1119 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001120 "tmp_prog_" + objName + '_' + string(name);
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001121 ret = bpf_obj_pin(fd, createLoc.c_str());
1122 if (ret) {
1123 int err = errno;
1124 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1125 return -err;
1126 }
1127 ret = rename(createLoc.c_str(), progPinLoc.c_str());
1128 if (ret) {
1129 int err = errno;
1130 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1131 err, strerror(err));
1132 return -err;
1133 }
1134 } else {
1135 ret = bpf_obj_pin(fd, progPinLoc.c_str());
1136 if (ret) {
1137 int err = errno;
1138 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1139 return -err;
1140 }
1141 }
1142 if (chmod(progPinLoc.c_str(), 0440)) {
1143 int err = errno;
1144 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1145 return -err;
1146 }
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001147 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1148 (gid_t)cs[i].prog_def->gid)) {
1149 int err = errno;
1150 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1151 cs[i].prog_def->gid, err, strerror(err));
1152 return -err;
Connor O'Brien3278a162020-02-13 21:45:22 -08001153 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001154 }
1155
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001156 struct bpf_prog_info prog_info = {};
1157 __u32 prog_info_len = sizeof(prog_info);
1158 int rv = bpf_obj_get_info_by_fd(fd, &prog_info, &prog_info_len);
1159 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001160 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001161 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001162 ALOGI("prog %s id %d", progPinLoc.c_str(), prog_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001163 }
1164
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001165 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001166 }
1167
1168 return 0;
1169}
1170
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001171int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
Joel Fernandesd76a2002018-10-16 13:19:58 -07001172 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001173 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001174 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001175 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001176 int ret;
1177
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001178 if (!isCritical) return -1;
1179 *isCritical = false;
1180
Joel Fernandesd76a2002018-10-16 13:19:58 -07001181 ifstream elfFile(elfPath, ios::in | ios::binary);
1182 if (!elfFile.is_open()) return -1;
1183
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001184 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001185 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001186
Joel Fernandesd76a2002018-10-16 13:19:58 -07001187 ret = readSectionByName("license", elfFile, license);
1188 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001189 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001190 return ret;
1191 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001192 ALOGD("Loading %s%s ELF object %s with license %s",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001193 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001194 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -07001195 }
1196
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001197 // the following default values are for bpfloader V0.0 format which does not include them
1198 unsigned int bpfLoaderMinVer =
1199 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1200 unsigned int bpfLoaderMaxVer =
1201 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001202 unsigned int bpfLoaderMinRequiredVer =
1203 readSectionUint("bpfloader_min_required_ver", elfFile, 0);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001204 size_t sizeOfBpfMapDef =
1205 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1206 size_t sizeOfBpfProgDef =
1207 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1208
1209 // inclusive lower bound check
1210 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001211 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001212 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
1213 return 0;
1214 }
1215
1216 // exclusive upper bound check
1217 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001218 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001219 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
1220 return 0;
1221 }
1222
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001223 if (BPFLOADER_VERSION < bpfLoaderMinRequiredVer) {
1224 ALOGI("BpfLoader version 0x%05x failing due to ELF object %s with required min ver 0x%05x",
1225 BPFLOADER_VERSION, elfPath, bpfLoaderMinRequiredVer);
1226 return -1;
1227 }
1228
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001229 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001230 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1231
1232 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001233 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001234 DEFAULT_SIZEOF_BPF_MAP_DEF);
1235 return -1;
1236 }
1237
1238 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001239 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001240 DEFAULT_SIZEOF_BPF_PROG_DEF);
1241 return -1;
1242 }
1243
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001244 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, location.allowedProgTypes,
1245 location.allowedProgTypesLength);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001246 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001247 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001248 return ret;
1249 }
1250
1251 /* Just for future debugging */
1252 if (0) dumpAllCs(cs);
1253
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001254 ret = createMaps(elfPath, elfFile, mapFds, location.prefix, location.allowedDomainBitmask,
1255 sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001256 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001257 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001258 return ret;
1259 }
1260
1261 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001262 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001263
1264 applyMapRelo(elfFile, mapFds, cs);
1265
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001266 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix,
1267 location.allowedDomainBitmask);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001268 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001269
1270 return ret;
1271}
1272
Joel Fernandesd76a2002018-10-16 13:19:58 -07001273} // namespace bpf
1274} // namespace android