blob: 24e5a901082a4f23b1628f58a0c1e1f63b6f0609 [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 Żenczykowski07375e22020-02-19 14:23:59 -080038#include "bpf/BpfUtils.h"
Ken Chend5689472021-12-20 18:07:21 +080039#include "bpf/bpf_map_def.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070040#include "include/libbpf_android.h"
41
Maciej Żenczykowskib3dcc142022-07-24 22:42:33 +000042#if BPFLOADER_VERSION < COMPILE_FOR_BPFLOADER_VERSION
43#error "BPFLOADER_VERSION is less than COMPILE_FOR_BPFLOADER_VERSION"
44#endif
45
Connor O'Brien35425e52022-01-18 21:41:16 -080046#include <bpf/bpf.h>
47
Joel Fernandesd76a2002018-10-16 13:19:58 -070048#include <cstdlib>
49#include <fstream>
50#include <iostream>
Connor O'Brien3278a162020-02-13 21:45:22 -080051#include <optional>
Joel Fernandesd76a2002018-10-16 13:19:58 -070052#include <string>
Connor O'Brien35425e52022-01-18 21:41:16 -080053#include <unordered_map>
Christopher Ferrisc151c672019-02-01 15:31:26 -080054#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070055
Connor O'Brien35425e52022-01-18 21:41:16 -080056#include <android-base/cmsg.h>
57#include <android-base/file.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070058#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070059#include <android-base/unique_fd.h>
Ryan Zukliece89f502022-12-15 16:14:32 -080060#include <cutils/properties.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070061
62#define BPF_FS_PATH "/sys/fs/bpf/"
63
64// Size of the BPF log buffer for verifier logging
Stephane Leeeb61b732021-10-21 17:03:11 -070065#define BPF_LOAD_LOG_SZ 0xfffff
Joel Fernandesd76a2002018-10-16 13:19:58 -070066
Tyler Wear4e2f4602022-02-03 09:46:01 -080067// Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
68#define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
69
Joel Fernandesd76a2002018-10-16 13:19:58 -070070using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070071using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070072using std::ifstream;
73using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080074using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080075using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070076using std::vector;
77
Ryan Zukliece89f502022-12-15 16:14:32 -080078static std::string getBuildTypeInternal() {
79 char value[PROPERTY_VALUE_MAX] = {};
80 (void)property_get("ro.build.type", value, "unknown"); // ignore length
81 return value;
82}
83
Joel Fernandesd76a2002018-10-16 13:19:58 -070084namespace android {
85namespace bpf {
86
Ryan Zukliece89f502022-12-15 16:14:32 -080087const std::string& getBuildType() {
88 static std::string t = getBuildTypeInternal();
89 return t;
90}
91
Maciej Żenczykowski41817132022-06-03 08:41:04 -070092constexpr const char* lookupSelinuxContext(const domain d, const char* const unspecified = "") {
93 switch (d) {
94 case domain::unspecified: return unspecified;
95 case domain::platform: return "fs_bpf";
96 case domain::tethering: return "fs_bpf_tethering";
97 case domain::net_private: return "fs_bpf_net_private";
98 case domain::net_shared: return "fs_bpf_net_shared";
99 case domain::netd_readonly: return "fs_bpf_netd_readonly";
100 case domain::netd_shared: return "fs_bpf_netd_shared";
101 case domain::vendor: return "fs_bpf_vendor";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +0000102 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700103 default: return "(unrecognized)";
104 }
105}
106
107domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
108 for (domain d : AllDomains) {
109 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
110 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
111 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
112 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700113 ALOGW("ignoring unrecognized selinux_context '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700114 // We should return 'unrecognized' here, however: returning unspecified will
115 // result in the system simply using the default context, which in turn
116 // will allow future expansion by adding more restrictive selinux types.
117 // Older bpfloader will simply ignore that, and use the less restrictive default.
118 // This does mean you CANNOT later add a *less* restrictive type than the default.
119 //
120 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
121 return domain::unspecified;
122}
123
124constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
125 switch (d) {
126 case domain::unspecified: return unspecified;
127 case domain::platform: return "/";
128 case domain::tethering: return "tethering/";
129 case domain::net_private: return "net_private/";
130 case domain::net_shared: return "net_shared/";
131 case domain::netd_readonly: return "netd_readonly/";
132 case domain::netd_shared: return "netd_shared/";
133 case domain::vendor: return "vendor/";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +0000134 case domain::loader: return "loader/";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700135 default: return "(unrecognized)";
136 }
137};
138
139domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
140 for (domain d : AllDomains) {
141 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
142 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
143 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
144 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700145 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700146 // pin_subdir affects the object's full pathname,
147 // and thus using the default would change the location and thus our code's ability to find it,
148 // hence this seems worth treating as a true error condition.
149 //
150 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
151 // However, our callers will treat this as an error, and stop loading the specific .o,
152 // which will fail bpfloader if the .o is marked critical.
153 return domain::unrecognized;
154}
155
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700156static string pathToObjName(const string& path) {
157 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
158 string filename = android::base::Split(path, "/").back();
159 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
160 string name = filename.substr(0, filename.find_last_of('.'));
161 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
162 // this can be used to provide duplicate programs (mux based on the bpfloader version)
163 return name.substr(0, name.find_last_of('@'));
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800164}
165
Joel Fernandesd76a2002018-10-16 13:19:58 -0700166typedef struct {
167 const char* name;
168 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800169 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700170} sectionType;
171
172/*
173 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700174 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -0700175 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700176 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -0700177 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700178 *
179 * However, be aware that you should not be directly using the SECTION() macro.
180 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -0700181 */
182sectionType sectionNameTypes[] = {
Tyler Wear4e2f4602022-02-03 09:46:01 -0800183 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
184 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
185 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB, BPF_ATTACH_TYPE_UNSPEC},
186 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_ATTACH_TYPE_UNSPEC},
187 {"kprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie092e0b2022-05-24 13:14:32 +0000188 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT, BPF_ATTACH_TYPE_UNSPEC},
Tyler Wear4e2f4602022-02-03 09:46:01 -0800189 {"schedact/", BPF_PROG_TYPE_SCHED_ACT, BPF_ATTACH_TYPE_UNSPEC},
190 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS, BPF_ATTACH_TYPE_UNSPEC},
191 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
192 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
193 {"xdp/", BPF_PROG_TYPE_XDP, BPF_ATTACH_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700194};
195
196typedef struct {
197 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800198 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700199 string name;
200 vector<char> data;
201 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800202 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700203
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700204 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700205} codeSection;
206
Joel Fernandesd76a2002018-10-16 13:19:58 -0700207static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
208 elfFile.seekg(0);
209 if (elfFile.fail()) return -1;
210
211 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
212
213 return 0;
214}
215
216/* Reads all section header tables into an Shdr array */
217static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
218 Elf64_Ehdr eh;
219 int ret = 0;
220
221 ret = readElfHeader(elfFile, &eh);
222 if (ret) return ret;
223
224 elfFile.seekg(eh.e_shoff);
225 if (elfFile.fail()) return -1;
226
227 /* Read shdr table entries */
228 shTable.resize(eh.e_shnum);
229
230 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
231
232 return 0;
233}
234
235/* Read a section by its index - for ex to get sec hdr strtab blob */
236static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
237 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800238 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700239 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700240
241 elfFile.seekg(shTable[id].sh_offset);
242 if (elfFile.fail()) return -1;
243
244 sec.resize(shTable[id].sh_size);
245 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
246
247 return 0;
248}
249
250/* Read whole section header string table */
251static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
252 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800253 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700254 if (ret) return ret;
255
256 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
257 if (ret) return ret;
258
259 return 0;
260}
261
262/* Get name from offset in strtab */
263static int getSymName(ifstream& elfFile, int nameOff, string& name) {
264 int ret;
265 vector<char> secStrTab;
266
267 ret = readSectionHeaderStrtab(elfFile, secStrTab);
268 if (ret) return ret;
269
270 if (nameOff >= (int)secStrTab.size()) return -1;
271
272 name = string((char*)secStrTab.data() + nameOff);
273 return 0;
274}
275
276/* Reads a full section by name - example to get the GPL license */
277static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
278 vector<char> secStrTab;
279 vector<Elf64_Shdr> shTable;
280 int ret;
281
282 ret = readSectionHeadersAll(elfFile, shTable);
283 if (ret) return ret;
284
285 ret = readSectionHeaderStrtab(elfFile, secStrTab);
286 if (ret) return ret;
287
288 for (int i = 0; i < (int)shTable.size(); i++) {
289 char* secname = secStrTab.data() + shTable[i].sh_name;
290 if (!secname) continue;
291
292 if (!strcmp(secname, name)) {
293 vector<char> dataTmp;
294 dataTmp.resize(shTable[i].sh_size);
295
296 elfFile.seekg(shTable[i].sh_offset);
297 if (elfFile.fail()) return -1;
298
299 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
300
301 data = dataTmp;
302 return 0;
303 }
304 }
305 return -2;
306}
307
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700308unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800309 vector<char> theBytes;
310 int ret = readSectionByName(name, elfFile, theBytes);
311 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700312 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800313 return defVal;
314 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700315 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800316 return defVal;
317 } else {
318 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
319 unsigned int value = static_cast<unsigned char>(theBytes[3]);
320 value <<= 8;
321 value += static_cast<unsigned char>(theBytes[2]);
322 value <<= 8;
323 value += static_cast<unsigned char>(theBytes[1]);
324 value <<= 8;
325 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700326 ALOGI("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800327 return value;
328 }
329}
330
Joel Fernandesd76a2002018-10-16 13:19:58 -0700331static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
332 int ret;
333 vector<Elf64_Shdr> shTable;
334
335 ret = readSectionHeadersAll(elfFile, shTable);
336 if (ret) return ret;
337
338 for (int i = 0; i < (int)shTable.size(); i++) {
339 if ((int)shTable[i].sh_type != type) continue;
340
341 vector<char> dataTmp;
342 dataTmp.resize(shTable[i].sh_size);
343
344 elfFile.seekg(shTable[i].sh_offset);
345 if (elfFile.fail()) return -1;
346
347 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
348
349 data = dataTmp;
350 return 0;
351 }
352 return -2;
353}
354
355static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
356 return (a.st_value < b.st_value);
357}
358
359static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
360 int ret, numElems;
361 Elf64_Sym* buf;
362 vector<char> secData;
363
364 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
365 if (ret) return ret;
366
367 buf = (Elf64_Sym*)secData.data();
368 numElems = (secData.size() / sizeof(Elf64_Sym));
369 data.assign(buf, buf + numElems);
370
371 if (sort) std::sort(data.begin(), data.end(), symCompare);
372 return 0;
373}
374
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700375static enum bpf_prog_type getFuseProgType() {
376 int result = BPF_PROG_TYPE_UNSPEC;
377 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
378 return static_cast<bpf_prog_type>(result);
379}
380
Joel Fernandesd76a2002018-10-16 13:19:58 -0700381static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800382 for (auto& snt : sectionNameTypes)
383 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700384
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000385 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700386 if (StartsWith(name, "fuse/")) return getFuseProgType();
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000387
Joel Fernandesd76a2002018-10-16 13:19:58 -0700388 return BPF_PROG_TYPE_UNSPEC;
389}
390
Tyler Wear4e2f4602022-02-03 09:46:01 -0800391static enum bpf_attach_type getExpectedAttachType(string& name) {
392 for (auto& snt : sectionNameTypes)
393 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
394 return BPF_ATTACH_TYPE_UNSPEC;
395}
396
Joel Fernandesd76a2002018-10-16 13:19:58 -0700397static string getSectionName(enum bpf_prog_type type)
398{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800399 for (auto& snt : sectionNameTypes)
400 if (snt.type == type)
401 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700402
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800403 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700404}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700405
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800406static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
407 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800408 vector<char> pdData;
409 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800410 // Older file formats do not require a 'progs' section at all.
411 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800412 if (ret == -2) return 0;
413 if (ret) return ret;
414
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800415 if (pdData.size() % sizeOfBpfProgDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700416 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800417 pdData.size(), sizeOfBpfProgDef);
418 return -1;
419 };
420
421 int progCount = pdData.size() / sizeOfBpfProgDef;
422 pd.resize(progCount);
423 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
424
425 const char* dataPtr = pdData.data();
426 for (auto& p : pd) {
427 // First we zero initialize
428 memset(&p, 0, sizeof(p));
429 // Then we set non-zero defaults
430 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
431 // Then we copy over the structure prefix from the ELF file.
432 memcpy(&p, dataPtr, trimmedSize);
433 // Move to next struct in the ELF file
434 dataPtr += sizeOfBpfProgDef;
435 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800436 return 0;
437}
438
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800439static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
440 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800441 int ret;
442 string name;
443 vector<Elf64_Sym> symtab;
444 vector<Elf64_Shdr> shTable;
445
446 ret = readSymTab(elfFile, 1 /* sort */, symtab);
447 if (ret) return ret;
448
449 /* Get index of section */
450 ret = readSectionHeadersAll(elfFile, shTable);
451 if (ret) return ret;
452
453 int sec_idx = -1;
454 for (int i = 0; i < (int)shTable.size(); i++) {
455 ret = getSymName(elfFile, shTable[i].sh_name, name);
456 if (ret) return ret;
457
458 if (!name.compare(sectionName)) {
459 sec_idx = i;
460 break;
461 }
462 }
463
464 /* No section found with matching name*/
465 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700466 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800467 return -1;
468 }
469
470 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800471 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
472
Connor O'Brien3278a162020-02-13 21:45:22 -0800473 if (symtab[i].st_shndx == sec_idx) {
474 string s;
475 ret = getSymName(elfFile, symtab[i].st_name, s);
476 if (ret) return ret;
477 names.push_back(s);
478 }
479 }
480
481 return 0;
482}
483
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800484static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
485 if (allowed == nullptr) return true;
486
487 for (size_t i = 0; i < numAllowed; i++) {
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700488 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
489 if (type == getFuseProgType()) return true;
490 } else if (type == allowed[i])
491 return true;
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800492 }
493
494 return false;
495}
496
Joel Fernandesd76a2002018-10-16 13:19:58 -0700497/* Read a section by its index - for ex to get sec hdr strtab blob */
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800498static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef,
499 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700500 vector<Elf64_Shdr> shTable;
501 int entries, ret = 0;
502
503 ret = readSectionHeadersAll(elfFile, shTable);
504 if (ret) return ret;
505 entries = shTable.size();
506
Connor O'Brien3278a162020-02-13 21:45:22 -0800507 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800508 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800509 if (ret) return ret;
510 vector<string> progDefNames;
511 ret = getSectionSymNames(elfFile, "progs", progDefNames);
512 if (!pd.empty() && ret) return ret;
513
Joel Fernandesd76a2002018-10-16 13:19:58 -0700514 for (int i = 0; i < entries; i++) {
515 string name;
516 codeSection cs_temp;
517 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
518
519 ret = getSymName(elfFile, shTable[i].sh_name, name);
520 if (ret) return ret;
521
522 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800523
Tyler Wear4e2f4602022-02-03 09:46:01 -0800524 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800525
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800526 if (!IsAllowed(ptype, allowed, numAllowed)) {
527 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
528 return -1;
529 }
530
Tyler Wear4e2f4602022-02-03 09:46:01 -0800531 // This must be done before '/' is replaced with '_'.
532 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800533
Tyler Wear4e2f4602022-02-03 09:46:01 -0800534 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700535
Tyler Wear4e2f4602022-02-03 09:46:01 -0800536 // convert all slashes to underscores
537 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800538
Tyler Wear4e2f4602022-02-03 09:46:01 -0800539 cs_temp.type = ptype;
540 cs_temp.name = name;
541
542 ret = readSectionByIdx(elfFile, i, cs_temp.data);
543 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700544 ALOGD("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800545
546 vector<string> csSymNames;
547 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
548 if (ret || !csSymNames.size()) return ret;
549 for (size_t i = 0; i < progDefNames.size(); ++i) {
550 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
551 cs_temp.prog_def = pd[i];
552 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800553 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700554 }
555
556 /* Check for rel section */
557 if (cs_temp.data.size() > 0 && i < entries) {
558 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
559 if (ret) return ret;
560
Tyler Wear4e2f4602022-02-03 09:46:01 -0800561 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700562 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
563 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700564 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700565 }
566 }
567
568 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700569 cs.push_back(std::move(cs_temp));
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700570 ALOGD("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700571 }
572 }
573 return 0;
574}
575
576static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
577 vector<Elf64_Sym> symtab;
578 int ret = 0;
579
580 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
581 if (ret) return ret;
582
583 if (index >= (int)symtab.size()) return -1;
584
585 return getSymName(elfFile, symtab[index].st_name, name);
586}
587
Connor O'Brien35425e52022-01-18 21:41:16 -0800588static bool waitpidTimeout(pid_t pid, int timeoutMs) {
589 // Add SIGCHLD to the signal set.
590 sigset_t child_mask, original_mask;
591 sigemptyset(&child_mask);
592 sigaddset(&child_mask, SIGCHLD);
593 if (sigprocmask(SIG_BLOCK, &child_mask, &original_mask) == -1) return false;
594
595 // Wait for a SIGCHLD notification.
596 errno = 0;
597 timespec ts = {0, timeoutMs * 1000000};
598 int wait_result = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, nullptr, &ts));
599
600 // Restore the original signal set.
601 sigprocmask(SIG_SETMASK, &original_mask, nullptr);
602
603 if (wait_result == -1) return false;
604
605 int status;
606 return TEMP_FAILURE_RETRY(waitpid(pid, &status, WNOHANG)) == pid;
607}
608
609static std::optional<unique_fd> getMapBtfInfo(const char* elfPath,
610 std::unordered_map<string, std::pair<uint32_t, uint32_t>> &btfTypeIds) {
611 unique_fd bpfloaderSocket, btfloaderSocket;
612 if (!android::base::Socketpair(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0, &bpfloaderSocket,
613 &btfloaderSocket)) {
614 return {};
615 }
616
617 unique_fd pipeRead, pipeWrite;
618 if (!android::base::Pipe(&pipeRead, &pipeWrite, O_NONBLOCK)) {
619 return {};
620 }
621
622 pid_t pid = fork();
623 if (pid < 0) return {};
624 if (!pid) {
625 bpfloaderSocket.reset();
626 pipeRead.reset();
627 auto socketFdStr = std::to_string(btfloaderSocket.release());
628 auto pipeFdStr = std::to_string(pipeWrite.release());
629
630 if (execl("/system/bin/btfloader", "/system/bin/btfloader", socketFdStr.c_str(),
631 pipeFdStr.c_str(), elfPath, NULL) == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700632 ALOGW("exec btfloader failed with errno %d (%s)", errno, strerror(errno));
Connor O'Brien35425e52022-01-18 21:41:16 -0800633 exit(EX_UNAVAILABLE);
634 }
635 }
636 btfloaderSocket.reset();
637 pipeWrite.reset();
638 if (!waitpidTimeout(pid, 100)) {
639 kill(pid, SIGKILL);
640 return {};
641 }
642
643 unique_fd btfFd;
644 if (android::base::ReceiveFileDescriptors(bpfloaderSocket, nullptr, 0, &btfFd)) return {};
645
646 std::string btfTypeIdStr;
647 if (!android::base::ReadFdToString(pipeRead, &btfTypeIdStr)) return {};
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700648 if (!btfFd.ok()) return {};
Connor O'Brien35425e52022-01-18 21:41:16 -0800649
650 const auto mapTypeIdLines = android::base::Split(btfTypeIdStr, "\n");
651 for (const auto &line : mapTypeIdLines) {
652 const auto vec = android::base::Split(line, " ");
653 // Splitting on newline will give us one empty line
654 if (vec.size() != 3) continue;
655 const int kTid = atoi(vec[1].c_str());
656 const int vTid = atoi(vec[2].c_str());
657 if (!kTid || !vTid) return {};
658 btfTypeIds[vec[0]] = std::make_pair(kTid, vTid);
659 }
660 return btfFd;
661}
662
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700663static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
664 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700665 // Assuming fd is a valid Bpf Map file descriptor then
666 // all the following should always succeed on a 4.14+ kernel.
667 // If they somehow do fail, they'll return -1 (and set errno),
668 // which should then cause (among others) a key_size mismatch.
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700669 int fd_type = bpfGetFdMapType(fd);
670 int fd_key_size = bpfGetFdKeySize(fd);
671 int fd_value_size = bpfGetFdValueSize(fd);
672 int fd_max_entries = bpfGetFdMaxEntries(fd);
673 int fd_map_flags = bpfGetFdMapFlags(fd);
674
675 // DEVMAPs are readonly from the bpf program side's point of view, as such
676 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
677 int desired_map_flags = (int)mapDef.map_flags;
678 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
679 desired_map_flags |= BPF_F_RDONLY_PROG;
680
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700681 // The following checks should *never* trigger, if one of them somehow does,
682 // it probably means a bpf .o file has been changed/replaced at runtime
683 // and bpfloader was manually rerun (normally it should only run *once*
684 // early during the boot process).
685 // Another possibility is that something is misconfigured in the code:
686 // most likely a shared map is declared twice differently.
687 // But such a change should never be checked into the source tree...
688 if ((fd_type == type) &&
689 (fd_key_size == (int)mapDef.key_size) &&
690 (fd_value_size == (int)mapDef.value_size) &&
691 (fd_max_entries == (int)mapDef.max_entries) &&
692 (fd_map_flags == desired_map_flags)) {
693 return true;
694 }
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700695
696 ALOGE("bpf map name %s mismatch: desired/found: "
697 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
698 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
699 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
700 return false;
701}
702
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800703static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700704 const char* prefix, const unsigned long long allowedDomainBitmask,
705 const size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700706 int ret;
Connor O'Brien35425e52022-01-18 21:41:16 -0800707 vector<char> mdData, btfData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700708 vector<struct bpf_map_def> md;
709 vector<string> mapNames;
Connor O'Brien35425e52022-01-18 21:41:16 -0800710 std::unordered_map<string, std::pair<uint32_t, uint32_t>> btfTypeIdMap;
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700711 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700712
713 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800714 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700715 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800716
717 if (mdData.size() % sizeOfBpfMapDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700718 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800719 mdData.size(), sizeOfBpfMapDef);
720 return -1;
721 };
722
723 int mapCount = mdData.size() / sizeOfBpfMapDef;
724 md.resize(mapCount);
725 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
726
727 const char* dataPtr = mdData.data();
728 for (auto& m : md) {
729 // First we zero initialize
730 memset(&m, 0, sizeof(m));
731 // Then we set non-zero defaults
732 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700733 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800734 // Then we copy over the structure prefix from the ELF file.
735 memcpy(&m, dataPtr, trimmedSize);
736 // Move to next struct in the ELF file
737 dataPtr += sizeOfBpfMapDef;
738 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700739
Connor O'Brien3278a162020-02-13 21:45:22 -0800740 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700741 if (ret) return ret;
742
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700743 unsigned btfMinBpfLoaderVer = readSectionUint("btf_min_bpfloader_ver", elfFile, 0);
744 unsigned btfMinKernelVer = readSectionUint("btf_min_kernel_ver", elfFile, 0);
745 unsigned kvers = kernelVersion();
746
Connor O'Brien35425e52022-01-18 21:41:16 -0800747 std::optional<unique_fd> btfFd;
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700748 if ((BPFLOADER_VERSION >= btfMinBpfLoaderVer) && (kvers >= btfMinKernelVer) &&
749 (!readSectionByName(".BTF", elfFile, btfData))) {
Connor O'Brien35425e52022-01-18 21:41:16 -0800750 btfFd = getMapBtfInfo(elfPath, btfTypeIdMap);
751 }
752
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700753 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +0000754 if (md[i].zero != 0) abort();
755
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800756 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700757 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800758 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700759 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800760 continue;
761 }
762
763 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700764 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800765 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700766 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800767 continue;
768 }
769
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700770 if (kvers < md[i].min_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700771 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700772 mapNames[i].c_str(), kvers, md[i].min_kver);
773 mapFds.push_back(unique_fd());
774 continue;
775 }
776
777 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700778 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700779 mapNames[i].c_str(), kvers, md[i].max_kver);
780 mapFds.push_back(unique_fd());
781 continue;
782 }
783
Ryan Zukliece89f502022-12-15 16:14:32 -0800784 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
785 (md[i].ignore_on_userdebug && isUserdebug())) {
786 ALOGI("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
787 getBuildType().c_str());
788 mapFds.push_back(unique_fd());
789 continue;
790 }
791
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700792 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700793 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
794 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
795 // of be approximated: HASH has the same userspace visible api.
796 // However it cannot be used by ebpf programs in the same way.
797 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
798 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
799 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
800 // programs as being 5.4+...
801 type = BPF_MAP_TYPE_HASH;
802 }
803
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700804 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
805 if (specified(selinux_context)) {
806 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
807 ALOGE("map %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
808 mapNames[i].c_str(), selinux_context, allowedDomainBitmask);
809 return -EINVAL;
810 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700811 ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700812 md[i].selinux_context, selinux_context, lookupSelinuxContext(selinux_context),
813 lookupPinSubdir(selinux_context));
814 }
815
816 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
817 if (unrecognized(pin_subdir)) return -ENOTDIR;
818 if (specified(pin_subdir)) {
819 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
820 ALOGE("map %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)",
821 mapNames[i].c_str(), pin_subdir, allowedDomainBitmask);
822 return -EINVAL;
823 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700824 ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700825 pin_subdir, lookupPinSubdir(pin_subdir));
826 }
827
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700828 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
829 // except that maps shared across .o's have empty <objName>
830 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700831 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700832 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700833 bool reuse = false;
834 unique_fd fd;
835 int saved_errno;
836
Joel Fernandesd76a2002018-10-16 13:19:58 -0700837 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskieb199dd2022-07-01 03:21:40 -0700838 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800839 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700840 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700841 reuse = true;
842 } else {
Connor O'Brien35425e52022-01-18 21:41:16 -0800843 struct bpf_create_map_attr attr = {
844 .name = mapNames[i].c_str(),
845 .map_type = type,
846 .map_flags = md[i].map_flags,
847 .key_size = md[i].key_size,
848 .value_size = md[i].value_size,
849 .max_entries = md[i].max_entries,
850 };
851 if (btfFd.has_value() && btfTypeIdMap.find(mapNames[i]) != btfTypeIdMap.end()) {
852 attr.btf_fd = btfFd->get();
853 attr.btf_key_type_id = btfTypeIdMap.at(mapNames[i]).first;
854 attr.btf_value_type_id = btfTypeIdMap.at(mapNames[i]).second;
855 }
856 fd.reset(bcc_create_map_xattr(&attr, true));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800857 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700858 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700859 }
860
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700861 if (!fd.ok()) return -saved_errno;
862
863 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
864 // safety (since reuse code path is rare) run these checks even if we just created it.
865 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
866 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700867
868 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700869 if (specified(selinux_context)) {
870 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700871 "tmp_map_" + objName + "_" + mapNames[i];
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700872 ret = bpf_obj_pin(fd, createLoc.c_str());
873 if (ret) {
874 int err = errno;
875 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
876 return -err;
877 }
878 ret = rename(createLoc.c_str(), mapPinLoc.c_str());
879 if (ret) {
880 int err = errno;
881 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
882 err, strerror(err));
883 return -err;
884 }
885 } else {
886 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowskid8259aa2022-06-27 10:02:20 -0700887 if (ret) {
888 int err = errno;
889 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
890 return -err;
891 }
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700892 }
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800893 ret = chmod(mapPinLoc.c_str(), md[i].mode);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700894 if (ret) {
895 int err = errno;
896 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
897 strerror(err));
898 return -err;
899 }
Maciej Żenczykowski5e4aabf2022-06-27 01:15:53 -0700900 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
901 if (ret) {
902 int err = errno;
903 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
904 ret, err, strerror(err));
905 return -err;
906 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700907 }
908
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700909 struct bpf_map_info map_info = {};
910 __u32 map_info_len = sizeof(map_info);
911 int rv = bpf_obj_get_info_by_fd(fd, &map_info, &map_info_len);
912 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700913 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700914 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700915 ALOGI("map %s id %d", mapPinLoc.c_str(), map_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700916 }
917
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700918 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700919 }
920
921 return ret;
922}
923
924/* For debugging, dump all instructions */
925static void dumpIns(char* ins, int size) {
926 for (int row = 0; row < size / 8; row++) {
927 ALOGE("%d: ", row);
928 for (int j = 0; j < 8; j++) {
929 ALOGE("%3x ", ins[(row * 8) + j]);
930 }
931 ALOGE("\n");
932 }
933}
934
935/* For debugging, dump all code sections from cs list */
936static void dumpAllCs(vector<codeSection>& cs) {
937 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700938 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700939 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700940 ALOGE("-----------");
Joel Fernandesd76a2002018-10-16 13:19:58 -0700941 }
942}
943
944static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
945 int insnIndex;
946 struct bpf_insn *insn, *insns;
947
948 insns = (struct bpf_insn*)(insnsPtr);
949
950 insnIndex = offset / sizeof(struct bpf_insn);
951 insn = &insns[insnIndex];
952
Ken Chene1b518c2022-07-06 20:50:36 +0800953 ALOGD("applying relo to instruction at byte offset: %llu, "
954 "insn offset %d, insn %llx",
955 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700956
957 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700958 ALOGE("Dumping all instructions till ins %d", insnIndex);
959 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700960 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
961 return;
962 }
963
964 insn->imm = fd;
965 insn->src_reg = BPF_PSEUDO_MAP_FD;
966}
967
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700968static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700969 vector<string> mapNames;
970
Connor O'Brien3278a162020-02-13 21:45:22 -0800971 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700972 if (ret) return;
973
974 for (int k = 0; k != (int)cs.size(); k++) {
975 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
976 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
977
978 for (int i = 0; i < n_rel; i++) {
979 int symIndex = ELF64_R_SYM(rel[i].r_info);
980 string symName;
981
982 ret = getSymNameByIdx(elfFile, symIndex, symName);
983 if (ret) return;
984
985 /* Find the map fd and apply relo */
986 for (int j = 0; j < (int)mapNames.size(); j++) {
987 if (!mapNames[j].compare(symName)) {
988 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
989 break;
990 }
991 }
992 }
993 }
994}
995
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800996static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700997 const char* prefix, const unsigned long long allowedDomainBitmask) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800998 unsigned kvers = kernelVersion();
999 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001000
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001001 if (!kvers) {
1002 ALOGE("unable to get kernel version");
1003 return -EINVAL;
1004 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001005
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001006 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001007
1008 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001009 string name = cs[i].name;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001010
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001011 if (!cs[i].prog_def.has_value()) {
1012 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
1013 return -EINVAL;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -08001014 }
1015
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001016 unsigned min_kver = cs[i].prog_def->min_kver;
1017 unsigned max_kver = cs[i].prog_def->max_kver;
1018 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1019 max_kver, kvers);
1020 if (kvers < min_kver) continue;
1021 if (kvers >= max_kver) continue;
1022
1023 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1024 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1025 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1026 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
1027 // Note: make sure to only check for unrecognized *after* verifying bpfloader
1028 // version limits include this bpfloader's version.
1029
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001030 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001031 bpfMinVer, bpfMaxVer);
1032 if (BPFLOADER_VERSION < bpfMinVer) continue;
1033 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
Ryan Zukliece89f502022-12-15 16:14:32 -08001034
1035 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1036 (cs[i].prog_def->ignore_on_user && isUser()) ||
1037 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1038 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1039 getBuildType().c_str());
1040 }
1041
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001042 if (unrecognized(pin_subdir)) return -ENOTDIR;
1043
1044 if (specified(selinux_context)) {
1045 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
1046 ALOGE("prog %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
1047 name.c_str(), selinux_context, allowedDomainBitmask);
1048 return -EINVAL;
1049 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001050 ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001051 cs[i].prog_def->selinux_context, selinux_context,
1052 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1053 }
1054
1055 if (specified(pin_subdir)) {
1056 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
1057 ALOGE("prog %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)", name.c_str(),
1058 pin_subdir, allowedDomainBitmask);
1059 return -EINVAL;
1060 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001061 ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001062 cs[i].prog_def->pin_subdir, pin_subdir, lookupPinSubdir(pin_subdir));
1063 }
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001064
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001065 // strip any potential $foo suffix
1066 // this can be used to provide duplicate programs
1067 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -07001068 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001069
1070 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001071 // Format of pin location is
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001072 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001073 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001074 objName + '_' + string(name);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001075 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001076 fd = retrieveProgram(progPinLoc.c_str());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001077 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd,
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001078 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001079 reuse = true;
1080 } else {
1081 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1082
Tyler Wear4e2f4602022-02-03 09:46:01 -08001083 struct bpf_load_program_attr attr = {
1084 .prog_type = cs[i].type,
1085 .name = name.c_str(),
1086 .insns = (struct bpf_insn*)cs[i].data.data(),
1087 .license = license.c_str(),
1088 .log_level = 0,
1089 .expected_attach_type = cs[i].expected_attach_type,
1090 };
1091
1092 fd = bcc_prog_load_xattr(&attr, cs[i].data.size(), log_buf.data(), log_buf.size(),
1093 true);
1094
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001095 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)", elfPath,
Steven Moreland804bca02019-12-12 17:21:23 -08001096 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001097
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001098 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -08001099 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001100
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001101 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
1102 for (const auto& line : lines) ALOGW("%s", line.c_str());
1103 ALOGW("bpf_prog_load - END log_buf contents.");
1104
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001105 if (cs[i].prog_def->optional) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001106 ALOGW("failed program is marked optional - continuing...");
1107 continue;
1108 }
1109 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001110 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001111 }
1112
1113 if (fd < 0) return fd;
1114 if (fd == 0) return -EINVAL;
1115
1116 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001117 if (specified(selinux_context)) {
1118 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001119 "tmp_prog_" + objName + '_' + string(name);
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001120 ret = bpf_obj_pin(fd, createLoc.c_str());
1121 if (ret) {
1122 int err = errno;
1123 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1124 return -err;
1125 }
1126 ret = rename(createLoc.c_str(), progPinLoc.c_str());
1127 if (ret) {
1128 int err = errno;
1129 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1130 err, strerror(err));
1131 return -err;
1132 }
1133 } else {
1134 ret = bpf_obj_pin(fd, progPinLoc.c_str());
1135 if (ret) {
1136 int err = errno;
1137 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1138 return -err;
1139 }
1140 }
1141 if (chmod(progPinLoc.c_str(), 0440)) {
1142 int err = errno;
1143 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1144 return -err;
1145 }
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001146 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1147 (gid_t)cs[i].prog_def->gid)) {
1148 int err = errno;
1149 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1150 cs[i].prog_def->gid, err, strerror(err));
1151 return -err;
Connor O'Brien3278a162020-02-13 21:45:22 -08001152 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001153 }
1154
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001155 struct bpf_prog_info prog_info = {};
1156 __u32 prog_info_len = sizeof(prog_info);
1157 int rv = bpf_obj_get_info_by_fd(fd, &prog_info, &prog_info_len);
1158 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001159 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001160 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001161 ALOGI("prog %s id %d", progPinLoc.c_str(), prog_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001162 }
1163
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001164 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001165 }
1166
1167 return 0;
1168}
1169
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001170int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
Joel Fernandesd76a2002018-10-16 13:19:58 -07001171 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001172 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001173 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001174 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001175 int ret;
1176
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001177 if (!isCritical) return -1;
1178 *isCritical = false;
1179
Joel Fernandesd76a2002018-10-16 13:19:58 -07001180 ifstream elfFile(elfPath, ios::in | ios::binary);
1181 if (!elfFile.is_open()) return -1;
1182
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001183 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001184 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001185
Joel Fernandesd76a2002018-10-16 13:19:58 -07001186 ret = readSectionByName("license", elfFile, license);
1187 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001188 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001189 return ret;
1190 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001191 ALOGD("Loading %s%s ELF object %s with license %s",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001192 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001193 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -07001194 }
1195
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001196 // the following default values are for bpfloader V0.0 format which does not include them
1197 unsigned int bpfLoaderMinVer =
1198 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1199 unsigned int bpfLoaderMaxVer =
1200 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001201 unsigned int bpfLoaderMinRequiredVer =
1202 readSectionUint("bpfloader_min_required_ver", elfFile, 0);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001203 size_t sizeOfBpfMapDef =
1204 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1205 size_t sizeOfBpfProgDef =
1206 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1207
1208 // inclusive lower bound check
1209 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001210 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001211 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
1212 return 0;
1213 }
1214
1215 // exclusive upper bound check
1216 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001217 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001218 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
1219 return 0;
1220 }
1221
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001222 if (BPFLOADER_VERSION < bpfLoaderMinRequiredVer) {
1223 ALOGI("BpfLoader version 0x%05x failing due to ELF object %s with required min ver 0x%05x",
1224 BPFLOADER_VERSION, elfPath, bpfLoaderMinRequiredVer);
1225 return -1;
1226 }
1227
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001228 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001229 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1230
1231 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001232 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001233 DEFAULT_SIZEOF_BPF_MAP_DEF);
1234 return -1;
1235 }
1236
1237 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001238 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001239 DEFAULT_SIZEOF_BPF_PROG_DEF);
1240 return -1;
1241 }
1242
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001243 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, location.allowedProgTypes,
1244 location.allowedProgTypesLength);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001245 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001246 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001247 return ret;
1248 }
1249
1250 /* Just for future debugging */
1251 if (0) dumpAllCs(cs);
1252
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001253 ret = createMaps(elfPath, elfFile, mapFds, location.prefix, location.allowedDomainBitmask,
1254 sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001255 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001256 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001257 return ret;
1258 }
1259
1260 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001261 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001262
1263 applyMapRelo(elfFile, mapFds, cs);
1264
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001265 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix,
1266 location.allowedDomainBitmask);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001267 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001268
1269 return ret;
1270}
1271
Joel Fernandesd76a2002018-10-16 13:19:58 -07001272} // namespace bpf
1273} // namespace android