blob: 810cfb29a5e0037ea96b1e1c983b5be1c7a31d1d [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
Maciej Żenczykowskiebfacde2022-12-05 13:33:43 +000033// This is BpfLoader v0.31
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080034#define BPFLOADER_VERSION_MAJOR 0u
Maciej Żenczykowskiebfacde2022-12-05 13:33:43 +000035#define BPFLOADER_VERSION_MINOR 31u
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>
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
78namespace android {
79namespace bpf {
80
Maciej Żenczykowski41817132022-06-03 08:41:04 -070081constexpr const char* lookupSelinuxContext(const domain d, const char* const unspecified = "") {
82 switch (d) {
83 case domain::unspecified: return unspecified;
84 case domain::platform: return "fs_bpf";
85 case domain::tethering: return "fs_bpf_tethering";
86 case domain::net_private: return "fs_bpf_net_private";
87 case domain::net_shared: return "fs_bpf_net_shared";
88 case domain::netd_readonly: return "fs_bpf_netd_readonly";
89 case domain::netd_shared: return "fs_bpf_netd_shared";
90 case domain::vendor: return "fs_bpf_vendor";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +000091 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski41817132022-06-03 08:41:04 -070092 default: return "(unrecognized)";
93 }
94}
95
96domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
97 for (domain d : AllDomains) {
98 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
99 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
100 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
101 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700102 ALOGW("ignoring unrecognized selinux_context '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700103 // We should return 'unrecognized' here, however: returning unspecified will
104 // result in the system simply using the default context, which in turn
105 // will allow future expansion by adding more restrictive selinux types.
106 // Older bpfloader will simply ignore that, and use the less restrictive default.
107 // This does mean you CANNOT later add a *less* restrictive type than the default.
108 //
109 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
110 return domain::unspecified;
111}
112
113constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
114 switch (d) {
115 case domain::unspecified: return unspecified;
116 case domain::platform: return "/";
117 case domain::tethering: return "tethering/";
118 case domain::net_private: return "net_private/";
119 case domain::net_shared: return "net_shared/";
120 case domain::netd_readonly: return "netd_readonly/";
121 case domain::netd_shared: return "netd_shared/";
122 case domain::vendor: return "vendor/";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +0000123 case domain::loader: return "loader/";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700124 default: return "(unrecognized)";
125 }
126};
127
128domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
129 for (domain d : AllDomains) {
130 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
131 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
132 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
133 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700134 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700135 // pin_subdir affects the object's full pathname,
136 // and thus using the default would change the location and thus our code's ability to find it,
137 // hence this seems worth treating as a true error condition.
138 //
139 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
140 // However, our callers will treat this as an error, and stop loading the specific .o,
141 // which will fail bpfloader if the .o is marked critical.
142 return domain::unrecognized;
143}
144
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700145static string pathToObjName(const string& path) {
146 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
147 string filename = android::base::Split(path, "/").back();
148 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
149 string name = filename.substr(0, filename.find_last_of('.'));
150 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
151 // this can be used to provide duplicate programs (mux based on the bpfloader version)
152 return name.substr(0, name.find_last_of('@'));
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800153}
154
Joel Fernandesd76a2002018-10-16 13:19:58 -0700155typedef struct {
156 const char* name;
157 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800158 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700159} sectionType;
160
161/*
162 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700163 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -0700164 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700165 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -0700166 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700167 *
168 * However, be aware that you should not be directly using the SECTION() macro.
169 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -0700170 */
171sectionType sectionNameTypes[] = {
Tyler Wear4e2f4602022-02-03 09:46:01 -0800172 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
173 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
174 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB, BPF_ATTACH_TYPE_UNSPEC},
175 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_ATTACH_TYPE_UNSPEC},
176 {"kprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie092e0b2022-05-24 13:14:32 +0000177 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT, BPF_ATTACH_TYPE_UNSPEC},
Tyler Wear4e2f4602022-02-03 09:46:01 -0800178 {"schedact/", BPF_PROG_TYPE_SCHED_ACT, BPF_ATTACH_TYPE_UNSPEC},
179 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS, BPF_ATTACH_TYPE_UNSPEC},
180 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
181 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
182 {"xdp/", BPF_PROG_TYPE_XDP, BPF_ATTACH_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700183};
184
185typedef struct {
186 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800187 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700188 string name;
189 vector<char> data;
190 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800191 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700192
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700193 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700194} codeSection;
195
Joel Fernandesd76a2002018-10-16 13:19:58 -0700196static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
197 elfFile.seekg(0);
198 if (elfFile.fail()) return -1;
199
200 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
201
202 return 0;
203}
204
205/* Reads all section header tables into an Shdr array */
206static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
207 Elf64_Ehdr eh;
208 int ret = 0;
209
210 ret = readElfHeader(elfFile, &eh);
211 if (ret) return ret;
212
213 elfFile.seekg(eh.e_shoff);
214 if (elfFile.fail()) return -1;
215
216 /* Read shdr table entries */
217 shTable.resize(eh.e_shnum);
218
219 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
220
221 return 0;
222}
223
224/* Read a section by its index - for ex to get sec hdr strtab blob */
225static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
226 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800227 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700228 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700229
230 elfFile.seekg(shTable[id].sh_offset);
231 if (elfFile.fail()) return -1;
232
233 sec.resize(shTable[id].sh_size);
234 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
235
236 return 0;
237}
238
239/* Read whole section header string table */
240static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
241 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800242 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700243 if (ret) return ret;
244
245 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
246 if (ret) return ret;
247
248 return 0;
249}
250
251/* Get name from offset in strtab */
252static int getSymName(ifstream& elfFile, int nameOff, string& name) {
253 int ret;
254 vector<char> secStrTab;
255
256 ret = readSectionHeaderStrtab(elfFile, secStrTab);
257 if (ret) return ret;
258
259 if (nameOff >= (int)secStrTab.size()) return -1;
260
261 name = string((char*)secStrTab.data() + nameOff);
262 return 0;
263}
264
265/* Reads a full section by name - example to get the GPL license */
266static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
267 vector<char> secStrTab;
268 vector<Elf64_Shdr> shTable;
269 int ret;
270
271 ret = readSectionHeadersAll(elfFile, shTable);
272 if (ret) return ret;
273
274 ret = readSectionHeaderStrtab(elfFile, secStrTab);
275 if (ret) return ret;
276
277 for (int i = 0; i < (int)shTable.size(); i++) {
278 char* secname = secStrTab.data() + shTable[i].sh_name;
279 if (!secname) continue;
280
281 if (!strcmp(secname, name)) {
282 vector<char> dataTmp;
283 dataTmp.resize(shTable[i].sh_size);
284
285 elfFile.seekg(shTable[i].sh_offset);
286 if (elfFile.fail()) return -1;
287
288 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
289
290 data = dataTmp;
291 return 0;
292 }
293 }
294 return -2;
295}
296
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700297unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800298 vector<char> theBytes;
299 int ret = readSectionByName(name, elfFile, theBytes);
300 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700301 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800302 return defVal;
303 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700304 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800305 return defVal;
306 } else {
307 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
308 unsigned int value = static_cast<unsigned char>(theBytes[3]);
309 value <<= 8;
310 value += static_cast<unsigned char>(theBytes[2]);
311 value <<= 8;
312 value += static_cast<unsigned char>(theBytes[1]);
313 value <<= 8;
314 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700315 ALOGI("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800316 return value;
317 }
318}
319
Joel Fernandesd76a2002018-10-16 13:19:58 -0700320static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
321 int ret;
322 vector<Elf64_Shdr> shTable;
323
324 ret = readSectionHeadersAll(elfFile, shTable);
325 if (ret) return ret;
326
327 for (int i = 0; i < (int)shTable.size(); i++) {
328 if ((int)shTable[i].sh_type != type) continue;
329
330 vector<char> dataTmp;
331 dataTmp.resize(shTable[i].sh_size);
332
333 elfFile.seekg(shTable[i].sh_offset);
334 if (elfFile.fail()) return -1;
335
336 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
337
338 data = dataTmp;
339 return 0;
340 }
341 return -2;
342}
343
344static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
345 return (a.st_value < b.st_value);
346}
347
348static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
349 int ret, numElems;
350 Elf64_Sym* buf;
351 vector<char> secData;
352
353 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
354 if (ret) return ret;
355
356 buf = (Elf64_Sym*)secData.data();
357 numElems = (secData.size() / sizeof(Elf64_Sym));
358 data.assign(buf, buf + numElems);
359
360 if (sort) std::sort(data.begin(), data.end(), symCompare);
361 return 0;
362}
363
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700364static enum bpf_prog_type getFuseProgType() {
365 int result = BPF_PROG_TYPE_UNSPEC;
366 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
367 return static_cast<bpf_prog_type>(result);
368}
369
Joel Fernandesd76a2002018-10-16 13:19:58 -0700370static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800371 for (auto& snt : sectionNameTypes)
372 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700373
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000374 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700375 if (StartsWith(name, "fuse/")) return getFuseProgType();
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000376
Joel Fernandesd76a2002018-10-16 13:19:58 -0700377 return BPF_PROG_TYPE_UNSPEC;
378}
379
Tyler Wear4e2f4602022-02-03 09:46:01 -0800380static enum bpf_attach_type getExpectedAttachType(string& name) {
381 for (auto& snt : sectionNameTypes)
382 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
383 return BPF_ATTACH_TYPE_UNSPEC;
384}
385
Joel Fernandesd76a2002018-10-16 13:19:58 -0700386static string getSectionName(enum bpf_prog_type type)
387{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800388 for (auto& snt : sectionNameTypes)
389 if (snt.type == type)
390 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700391
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800392 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700393}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700394
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800395static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
396 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800397 vector<char> pdData;
398 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800399 // Older file formats do not require a 'progs' section at all.
400 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800401 if (ret == -2) return 0;
402 if (ret) return ret;
403
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800404 if (pdData.size() % sizeOfBpfProgDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700405 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800406 pdData.size(), sizeOfBpfProgDef);
407 return -1;
408 };
409
410 int progCount = pdData.size() / sizeOfBpfProgDef;
411 pd.resize(progCount);
412 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
413
414 const char* dataPtr = pdData.data();
415 for (auto& p : pd) {
416 // First we zero initialize
417 memset(&p, 0, sizeof(p));
418 // Then we set non-zero defaults
419 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
420 // Then we copy over the structure prefix from the ELF file.
421 memcpy(&p, dataPtr, trimmedSize);
422 // Move to next struct in the ELF file
423 dataPtr += sizeOfBpfProgDef;
424 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800425 return 0;
426}
427
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800428static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
429 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800430 int ret;
431 string name;
432 vector<Elf64_Sym> symtab;
433 vector<Elf64_Shdr> shTable;
434
435 ret = readSymTab(elfFile, 1 /* sort */, symtab);
436 if (ret) return ret;
437
438 /* Get index of section */
439 ret = readSectionHeadersAll(elfFile, shTable);
440 if (ret) return ret;
441
442 int sec_idx = -1;
443 for (int i = 0; i < (int)shTable.size(); i++) {
444 ret = getSymName(elfFile, shTable[i].sh_name, name);
445 if (ret) return ret;
446
447 if (!name.compare(sectionName)) {
448 sec_idx = i;
449 break;
450 }
451 }
452
453 /* No section found with matching name*/
454 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700455 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800456 return -1;
457 }
458
459 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800460 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
461
Connor O'Brien3278a162020-02-13 21:45:22 -0800462 if (symtab[i].st_shndx == sec_idx) {
463 string s;
464 ret = getSymName(elfFile, symtab[i].st_name, s);
465 if (ret) return ret;
466 names.push_back(s);
467 }
468 }
469
470 return 0;
471}
472
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800473static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
474 if (allowed == nullptr) return true;
475
476 for (size_t i = 0; i < numAllowed; i++) {
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700477 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
478 if (type == getFuseProgType()) return true;
479 } else if (type == allowed[i])
480 return true;
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800481 }
482
483 return false;
484}
485
Joel Fernandesd76a2002018-10-16 13:19:58 -0700486/* Read a section by its index - for ex to get sec hdr strtab blob */
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800487static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef,
488 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700489 vector<Elf64_Shdr> shTable;
490 int entries, ret = 0;
491
492 ret = readSectionHeadersAll(elfFile, shTable);
493 if (ret) return ret;
494 entries = shTable.size();
495
Connor O'Brien3278a162020-02-13 21:45:22 -0800496 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800497 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800498 if (ret) return ret;
499 vector<string> progDefNames;
500 ret = getSectionSymNames(elfFile, "progs", progDefNames);
501 if (!pd.empty() && ret) return ret;
502
Joel Fernandesd76a2002018-10-16 13:19:58 -0700503 for (int i = 0; i < entries; i++) {
504 string name;
505 codeSection cs_temp;
506 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
507
508 ret = getSymName(elfFile, shTable[i].sh_name, name);
509 if (ret) return ret;
510
511 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800512
Tyler Wear4e2f4602022-02-03 09:46:01 -0800513 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800514
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800515 if (!IsAllowed(ptype, allowed, numAllowed)) {
516 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
517 return -1;
518 }
519
Tyler Wear4e2f4602022-02-03 09:46:01 -0800520 // This must be done before '/' is replaced with '_'.
521 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800522
Tyler Wear4e2f4602022-02-03 09:46:01 -0800523 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700524
Tyler Wear4e2f4602022-02-03 09:46:01 -0800525 // convert all slashes to underscores
526 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800527
Tyler Wear4e2f4602022-02-03 09:46:01 -0800528 cs_temp.type = ptype;
529 cs_temp.name = name;
530
531 ret = readSectionByIdx(elfFile, i, cs_temp.data);
532 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700533 ALOGD("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800534
535 vector<string> csSymNames;
536 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
537 if (ret || !csSymNames.size()) return ret;
538 for (size_t i = 0; i < progDefNames.size(); ++i) {
539 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
540 cs_temp.prog_def = pd[i];
541 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800542 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700543 }
544
545 /* Check for rel section */
546 if (cs_temp.data.size() > 0 && i < entries) {
547 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
548 if (ret) return ret;
549
Tyler Wear4e2f4602022-02-03 09:46:01 -0800550 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700551 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
552 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700553 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700554 }
555 }
556
557 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700558 cs.push_back(std::move(cs_temp));
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700559 ALOGD("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700560 }
561 }
562 return 0;
563}
564
565static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
566 vector<Elf64_Sym> symtab;
567 int ret = 0;
568
569 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
570 if (ret) return ret;
571
572 if (index >= (int)symtab.size()) return -1;
573
574 return getSymName(elfFile, symtab[index].st_name, name);
575}
576
Connor O'Brien35425e52022-01-18 21:41:16 -0800577static bool waitpidTimeout(pid_t pid, int timeoutMs) {
578 // Add SIGCHLD to the signal set.
579 sigset_t child_mask, original_mask;
580 sigemptyset(&child_mask);
581 sigaddset(&child_mask, SIGCHLD);
582 if (sigprocmask(SIG_BLOCK, &child_mask, &original_mask) == -1) return false;
583
584 // Wait for a SIGCHLD notification.
585 errno = 0;
586 timespec ts = {0, timeoutMs * 1000000};
587 int wait_result = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, nullptr, &ts));
588
589 // Restore the original signal set.
590 sigprocmask(SIG_SETMASK, &original_mask, nullptr);
591
592 if (wait_result == -1) return false;
593
594 int status;
595 return TEMP_FAILURE_RETRY(waitpid(pid, &status, WNOHANG)) == pid;
596}
597
598static std::optional<unique_fd> getMapBtfInfo(const char* elfPath,
599 std::unordered_map<string, std::pair<uint32_t, uint32_t>> &btfTypeIds) {
600 unique_fd bpfloaderSocket, btfloaderSocket;
601 if (!android::base::Socketpair(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0, &bpfloaderSocket,
602 &btfloaderSocket)) {
603 return {};
604 }
605
606 unique_fd pipeRead, pipeWrite;
607 if (!android::base::Pipe(&pipeRead, &pipeWrite, O_NONBLOCK)) {
608 return {};
609 }
610
611 pid_t pid = fork();
612 if (pid < 0) return {};
613 if (!pid) {
614 bpfloaderSocket.reset();
615 pipeRead.reset();
616 auto socketFdStr = std::to_string(btfloaderSocket.release());
617 auto pipeFdStr = std::to_string(pipeWrite.release());
618
619 if (execl("/system/bin/btfloader", "/system/bin/btfloader", socketFdStr.c_str(),
620 pipeFdStr.c_str(), elfPath, NULL) == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700621 ALOGW("exec btfloader failed with errno %d (%s)", errno, strerror(errno));
Connor O'Brien35425e52022-01-18 21:41:16 -0800622 exit(EX_UNAVAILABLE);
623 }
624 }
625 btfloaderSocket.reset();
626 pipeWrite.reset();
627 if (!waitpidTimeout(pid, 100)) {
628 kill(pid, SIGKILL);
629 return {};
630 }
631
632 unique_fd btfFd;
633 if (android::base::ReceiveFileDescriptors(bpfloaderSocket, nullptr, 0, &btfFd)) return {};
634
635 std::string btfTypeIdStr;
636 if (!android::base::ReadFdToString(pipeRead, &btfTypeIdStr)) return {};
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700637 if (!btfFd.ok()) return {};
Connor O'Brien35425e52022-01-18 21:41:16 -0800638
639 const auto mapTypeIdLines = android::base::Split(btfTypeIdStr, "\n");
640 for (const auto &line : mapTypeIdLines) {
641 const auto vec = android::base::Split(line, " ");
642 // Splitting on newline will give us one empty line
643 if (vec.size() != 3) continue;
644 const int kTid = atoi(vec[1].c_str());
645 const int vTid = atoi(vec[2].c_str());
646 if (!kTid || !vTid) return {};
647 btfTypeIds[vec[0]] = std::make_pair(kTid, vTid);
648 }
649 return btfFd;
650}
651
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700652static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
653 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700654 // Assuming fd is a valid Bpf Map file descriptor then
655 // all the following should always succeed on a 4.14+ kernel.
656 // If they somehow do fail, they'll return -1 (and set errno),
657 // which should then cause (among others) a key_size mismatch.
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700658 int fd_type = bpfGetFdMapType(fd);
659 int fd_key_size = bpfGetFdKeySize(fd);
660 int fd_value_size = bpfGetFdValueSize(fd);
661 int fd_max_entries = bpfGetFdMaxEntries(fd);
662 int fd_map_flags = bpfGetFdMapFlags(fd);
663
664 // DEVMAPs are readonly from the bpf program side's point of view, as such
665 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
666 int desired_map_flags = (int)mapDef.map_flags;
667 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
668 desired_map_flags |= BPF_F_RDONLY_PROG;
669
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700670 // The following checks should *never* trigger, if one of them somehow does,
671 // it probably means a bpf .o file has been changed/replaced at runtime
672 // and bpfloader was manually rerun (normally it should only run *once*
673 // early during the boot process).
674 // Another possibility is that something is misconfigured in the code:
675 // most likely a shared map is declared twice differently.
676 // But such a change should never be checked into the source tree...
677 if ((fd_type == type) &&
678 (fd_key_size == (int)mapDef.key_size) &&
679 (fd_value_size == (int)mapDef.value_size) &&
680 (fd_max_entries == (int)mapDef.max_entries) &&
681 (fd_map_flags == desired_map_flags)) {
682 return true;
683 }
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700684
685 ALOGE("bpf map name %s mismatch: desired/found: "
686 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
687 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
688 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
689 return false;
690}
691
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800692static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700693 const char* prefix, const unsigned long long allowedDomainBitmask,
694 const size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700695 int ret;
Connor O'Brien35425e52022-01-18 21:41:16 -0800696 vector<char> mdData, btfData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700697 vector<struct bpf_map_def> md;
698 vector<string> mapNames;
Connor O'Brien35425e52022-01-18 21:41:16 -0800699 std::unordered_map<string, std::pair<uint32_t, uint32_t>> btfTypeIdMap;
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700700 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700701
702 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800703 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700704 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800705
706 if (mdData.size() % sizeOfBpfMapDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700707 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800708 mdData.size(), sizeOfBpfMapDef);
709 return -1;
710 };
711
712 int mapCount = mdData.size() / sizeOfBpfMapDef;
713 md.resize(mapCount);
714 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
715
716 const char* dataPtr = mdData.data();
717 for (auto& m : md) {
718 // First we zero initialize
719 memset(&m, 0, sizeof(m));
720 // Then we set non-zero defaults
721 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700722 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800723 // Then we copy over the structure prefix from the ELF file.
724 memcpy(&m, dataPtr, trimmedSize);
725 // Move to next struct in the ELF file
726 dataPtr += sizeOfBpfMapDef;
727 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700728
Connor O'Brien3278a162020-02-13 21:45:22 -0800729 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700730 if (ret) return ret;
731
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700732 unsigned btfMinBpfLoaderVer = readSectionUint("btf_min_bpfloader_ver", elfFile, 0);
733 unsigned btfMinKernelVer = readSectionUint("btf_min_kernel_ver", elfFile, 0);
734 unsigned kvers = kernelVersion();
735
Connor O'Brien35425e52022-01-18 21:41:16 -0800736 std::optional<unique_fd> btfFd;
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700737 if ((BPFLOADER_VERSION >= btfMinBpfLoaderVer) && (kvers >= btfMinKernelVer) &&
738 (!readSectionByName(".BTF", elfFile, btfData))) {
Connor O'Brien35425e52022-01-18 21:41:16 -0800739 btfFd = getMapBtfInfo(elfPath, btfTypeIdMap);
740 }
741
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700742 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +0000743 if (md[i].zero != 0) abort();
744
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800745 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700746 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800747 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700748 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800749 continue;
750 }
751
752 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700753 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800754 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700755 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800756 continue;
757 }
758
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700759 if (kvers < md[i].min_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700760 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700761 mapNames[i].c_str(), kvers, md[i].min_kver);
762 mapFds.push_back(unique_fd());
763 continue;
764 }
765
766 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700767 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700768 mapNames[i].c_str(), kvers, md[i].max_kver);
769 mapFds.push_back(unique_fd());
770 continue;
771 }
772
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700773 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700774 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
775 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
776 // of be approximated: HASH has the same userspace visible api.
777 // However it cannot be used by ebpf programs in the same way.
778 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
779 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
780 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
781 // programs as being 5.4+...
782 type = BPF_MAP_TYPE_HASH;
783 }
784
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700785 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
786 if (specified(selinux_context)) {
787 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
788 ALOGE("map %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
789 mapNames[i].c_str(), selinux_context, allowedDomainBitmask);
790 return -EINVAL;
791 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700792 ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700793 md[i].selinux_context, selinux_context, lookupSelinuxContext(selinux_context),
794 lookupPinSubdir(selinux_context));
795 }
796
797 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
798 if (unrecognized(pin_subdir)) return -ENOTDIR;
799 if (specified(pin_subdir)) {
800 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
801 ALOGE("map %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)",
802 mapNames[i].c_str(), pin_subdir, allowedDomainBitmask);
803 return -EINVAL;
804 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700805 ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700806 pin_subdir, lookupPinSubdir(pin_subdir));
807 }
808
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700809 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
810 // except that maps shared across .o's have empty <objName>
811 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700812 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700813 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700814 bool reuse = false;
815 unique_fd fd;
816 int saved_errno;
817
Joel Fernandesd76a2002018-10-16 13:19:58 -0700818 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskieb199dd2022-07-01 03:21:40 -0700819 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800820 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700821 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700822 reuse = true;
823 } else {
Connor O'Brien35425e52022-01-18 21:41:16 -0800824 struct bpf_create_map_attr attr = {
825 .name = mapNames[i].c_str(),
826 .map_type = type,
827 .map_flags = md[i].map_flags,
828 .key_size = md[i].key_size,
829 .value_size = md[i].value_size,
830 .max_entries = md[i].max_entries,
831 };
832 if (btfFd.has_value() && btfTypeIdMap.find(mapNames[i]) != btfTypeIdMap.end()) {
833 attr.btf_fd = btfFd->get();
834 attr.btf_key_type_id = btfTypeIdMap.at(mapNames[i]).first;
835 attr.btf_value_type_id = btfTypeIdMap.at(mapNames[i]).second;
836 }
837 fd.reset(bcc_create_map_xattr(&attr, true));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800838 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700839 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700840 }
841
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700842 if (!fd.ok()) return -saved_errno;
843
844 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
845 // safety (since reuse code path is rare) run these checks even if we just created it.
846 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
847 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700848
849 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700850 if (specified(selinux_context)) {
851 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700852 "tmp_map_" + objName + "_" + mapNames[i];
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700853 ret = bpf_obj_pin(fd, createLoc.c_str());
854 if (ret) {
855 int err = errno;
856 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
857 return -err;
858 }
859 ret = rename(createLoc.c_str(), mapPinLoc.c_str());
860 if (ret) {
861 int err = errno;
862 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
863 err, strerror(err));
864 return -err;
865 }
866 } else {
867 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowskid8259aa2022-06-27 10:02:20 -0700868 if (ret) {
869 int err = errno;
870 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
871 return -err;
872 }
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700873 }
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800874 ret = chmod(mapPinLoc.c_str(), md[i].mode);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700875 if (ret) {
876 int err = errno;
877 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
878 strerror(err));
879 return -err;
880 }
Maciej Żenczykowski5e4aabf2022-06-27 01:15:53 -0700881 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
882 if (ret) {
883 int err = errno;
884 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
885 ret, err, strerror(err));
886 return -err;
887 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700888 }
889
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700890 struct bpf_map_info map_info = {};
891 __u32 map_info_len = sizeof(map_info);
892 int rv = bpf_obj_get_info_by_fd(fd, &map_info, &map_info_len);
893 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700894 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700895 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700896 ALOGI("map %s id %d", mapPinLoc.c_str(), map_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700897 }
898
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700899 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700900 }
901
902 return ret;
903}
904
905/* For debugging, dump all instructions */
906static void dumpIns(char* ins, int size) {
907 for (int row = 0; row < size / 8; row++) {
908 ALOGE("%d: ", row);
909 for (int j = 0; j < 8; j++) {
910 ALOGE("%3x ", ins[(row * 8) + j]);
911 }
912 ALOGE("\n");
913 }
914}
915
916/* For debugging, dump all code sections from cs list */
917static void dumpAllCs(vector<codeSection>& cs) {
918 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700919 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700920 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700921 ALOGE("-----------");
Joel Fernandesd76a2002018-10-16 13:19:58 -0700922 }
923}
924
925static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
926 int insnIndex;
927 struct bpf_insn *insn, *insns;
928
929 insns = (struct bpf_insn*)(insnsPtr);
930
931 insnIndex = offset / sizeof(struct bpf_insn);
932 insn = &insns[insnIndex];
933
Ken Chene1b518c2022-07-06 20:50:36 +0800934 ALOGD("applying relo to instruction at byte offset: %llu, "
935 "insn offset %d, insn %llx",
936 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700937
938 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700939 ALOGE("Dumping all instructions till ins %d", insnIndex);
940 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700941 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
942 return;
943 }
944
945 insn->imm = fd;
946 insn->src_reg = BPF_PSEUDO_MAP_FD;
947}
948
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700949static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700950 vector<string> mapNames;
951
Connor O'Brien3278a162020-02-13 21:45:22 -0800952 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700953 if (ret) return;
954
955 for (int k = 0; k != (int)cs.size(); k++) {
956 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
957 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
958
959 for (int i = 0; i < n_rel; i++) {
960 int symIndex = ELF64_R_SYM(rel[i].r_info);
961 string symName;
962
963 ret = getSymNameByIdx(elfFile, symIndex, symName);
964 if (ret) return;
965
966 /* Find the map fd and apply relo */
967 for (int j = 0; j < (int)mapNames.size(); j++) {
968 if (!mapNames[j].compare(symName)) {
969 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
970 break;
971 }
972 }
973 }
974 }
975}
976
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800977static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700978 const char* prefix, const unsigned long long allowedDomainBitmask) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800979 unsigned kvers = kernelVersion();
980 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700981
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000982 if (!kvers) {
983 ALOGE("unable to get kernel version");
984 return -EINVAL;
985 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700986
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700987 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700988
989 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700990 string name = cs[i].name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700991
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000992 if (!cs[i].prog_def.has_value()) {
993 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
994 return -EINVAL;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800995 }
996
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000997 unsigned min_kver = cs[i].prog_def->min_kver;
998 unsigned max_kver = cs[i].prog_def->max_kver;
999 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1000 max_kver, kvers);
1001 if (kvers < min_kver) continue;
1002 if (kvers >= max_kver) continue;
1003
1004 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1005 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1006 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1007 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
1008 // Note: make sure to only check for unrecognized *after* verifying bpfloader
1009 // version limits include this bpfloader's version.
1010
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001011 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001012 bpfMinVer, bpfMaxVer);
1013 if (BPFLOADER_VERSION < bpfMinVer) continue;
1014 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001015 if (unrecognized(pin_subdir)) return -ENOTDIR;
1016
1017 if (specified(selinux_context)) {
1018 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
1019 ALOGE("prog %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
1020 name.c_str(), selinux_context, allowedDomainBitmask);
1021 return -EINVAL;
1022 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001023 ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001024 cs[i].prog_def->selinux_context, selinux_context,
1025 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1026 }
1027
1028 if (specified(pin_subdir)) {
1029 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
1030 ALOGE("prog %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)", name.c_str(),
1031 pin_subdir, allowedDomainBitmask);
1032 return -EINVAL;
1033 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001034 ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001035 cs[i].prog_def->pin_subdir, pin_subdir, lookupPinSubdir(pin_subdir));
1036 }
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001037
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001038 // strip any potential $foo suffix
1039 // this can be used to provide duplicate programs
1040 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -07001041 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001042
1043 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001044 // Format of pin location is
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001045 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001046 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001047 objName + '_' + string(name);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001048 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001049 fd = retrieveProgram(progPinLoc.c_str());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001050 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd,
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001051 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001052 reuse = true;
1053 } else {
1054 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1055
Tyler Wear4e2f4602022-02-03 09:46:01 -08001056 struct bpf_load_program_attr attr = {
1057 .prog_type = cs[i].type,
1058 .name = name.c_str(),
1059 .insns = (struct bpf_insn*)cs[i].data.data(),
1060 .license = license.c_str(),
1061 .log_level = 0,
1062 .expected_attach_type = cs[i].expected_attach_type,
1063 };
1064
1065 fd = bcc_prog_load_xattr(&attr, cs[i].data.size(), log_buf.data(), log_buf.size(),
1066 true);
1067
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001068 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)", elfPath,
Steven Moreland804bca02019-12-12 17:21:23 -08001069 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001070
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001071 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -08001072 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001073
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001074 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
1075 for (const auto& line : lines) ALOGW("%s", line.c_str());
1076 ALOGW("bpf_prog_load - END log_buf contents.");
1077
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001078 if (cs[i].prog_def->optional) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001079 ALOGW("failed program is marked optional - continuing...");
1080 continue;
1081 }
1082 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001083 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001084 }
1085
1086 if (fd < 0) return fd;
1087 if (fd == 0) return -EINVAL;
1088
1089 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001090 if (specified(selinux_context)) {
1091 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001092 "tmp_prog_" + objName + '_' + string(name);
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001093 ret = bpf_obj_pin(fd, createLoc.c_str());
1094 if (ret) {
1095 int err = errno;
1096 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1097 return -err;
1098 }
1099 ret = rename(createLoc.c_str(), progPinLoc.c_str());
1100 if (ret) {
1101 int err = errno;
1102 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1103 err, strerror(err));
1104 return -err;
1105 }
1106 } else {
1107 ret = bpf_obj_pin(fd, progPinLoc.c_str());
1108 if (ret) {
1109 int err = errno;
1110 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1111 return -err;
1112 }
1113 }
1114 if (chmod(progPinLoc.c_str(), 0440)) {
1115 int err = errno;
1116 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1117 return -err;
1118 }
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001119 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1120 (gid_t)cs[i].prog_def->gid)) {
1121 int err = errno;
1122 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1123 cs[i].prog_def->gid, err, strerror(err));
1124 return -err;
Connor O'Brien3278a162020-02-13 21:45:22 -08001125 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001126 }
1127
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001128 struct bpf_prog_info prog_info = {};
1129 __u32 prog_info_len = sizeof(prog_info);
1130 int rv = bpf_obj_get_info_by_fd(fd, &prog_info, &prog_info_len);
1131 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001132 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001133 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001134 ALOGI("prog %s id %d", progPinLoc.c_str(), prog_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001135 }
1136
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001137 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001138 }
1139
1140 return 0;
1141}
1142
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001143int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
Joel Fernandesd76a2002018-10-16 13:19:58 -07001144 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001145 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001146 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001147 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001148 int ret;
1149
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001150 if (!isCritical) return -1;
1151 *isCritical = false;
1152
Joel Fernandesd76a2002018-10-16 13:19:58 -07001153 ifstream elfFile(elfPath, ios::in | ios::binary);
1154 if (!elfFile.is_open()) return -1;
1155
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001156 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001157 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001158
Joel Fernandesd76a2002018-10-16 13:19:58 -07001159 ret = readSectionByName("license", elfFile, license);
1160 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001161 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001162 return ret;
1163 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001164 ALOGD("Loading %s%s ELF object %s with license %s",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001165 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001166 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -07001167 }
1168
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001169 // the following default values are for bpfloader V0.0 format which does not include them
1170 unsigned int bpfLoaderMinVer =
1171 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1172 unsigned int bpfLoaderMaxVer =
1173 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001174 unsigned int bpfLoaderMinRequiredVer =
1175 readSectionUint("bpfloader_min_required_ver", elfFile, 0);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001176 size_t sizeOfBpfMapDef =
1177 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1178 size_t sizeOfBpfProgDef =
1179 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1180
1181 // inclusive lower bound check
1182 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001183 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001184 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
1185 return 0;
1186 }
1187
1188 // exclusive upper bound check
1189 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001190 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001191 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
1192 return 0;
1193 }
1194
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001195 if (BPFLOADER_VERSION < bpfLoaderMinRequiredVer) {
1196 ALOGI("BpfLoader version 0x%05x failing due to ELF object %s with required min ver 0x%05x",
1197 BPFLOADER_VERSION, elfPath, bpfLoaderMinRequiredVer);
1198 return -1;
1199 }
1200
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001201 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001202 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1203
1204 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001205 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001206 DEFAULT_SIZEOF_BPF_MAP_DEF);
1207 return -1;
1208 }
1209
1210 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001211 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001212 DEFAULT_SIZEOF_BPF_PROG_DEF);
1213 return -1;
1214 }
1215
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001216 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, location.allowedProgTypes,
1217 location.allowedProgTypesLength);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001218 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001219 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001220 return ret;
1221 }
1222
1223 /* Just for future debugging */
1224 if (0) dumpAllCs(cs);
1225
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001226 ret = createMaps(elfPath, elfFile, mapFds, location.prefix, location.allowedDomainBitmask,
1227 sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001228 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001229 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001230 return ret;
1231 }
1232
1233 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001234 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001235
1236 applyMapRelo(elfFile, mapFds, cs);
1237
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001238 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix,
1239 location.allowedDomainBitmask);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001240 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001241
1242 return ret;
1243}
1244
Joel Fernandesd76a2002018-10-16 13:19:58 -07001245} // namespace bpf
1246} // namespace android