blob: 229dd9337415dc070da584af1a2c3393e9af253f [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>
Maciej Żenczykowskie15229f2023-04-17 07:16:33 +000020#include <fcntl.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070021#include <linux/bpf.h>
22#include <linux/elf.h>
23#include <log/log.h>
24#include <stdint.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080028#include <sysexits.h>
Maciej Żenczykowski83f29772020-01-27 03:11:51 -080029#include <sys/stat.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070030#include <sys/utsname.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080031#include <sys/wait.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070032#include <unistd.h>
33
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -070034// This is BpfLoader v0.41
Maciej Żenczykowski05825662023-01-20 13:00:24 +000035// WARNING: If you ever hit cherrypick conflicts here you're doing it wrong:
36// You are NOT allowed to cherrypick bpfloader related patches out of order.
37// (indeed: cherrypicking is probably a bad idea and you should merge instead)
38// Mainline supports ONLY the published versions of the bpfloader for each Android release.
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080039#define BPFLOADER_VERSION_MAJOR 0u
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -070040#define BPFLOADER_VERSION_MINOR 41u
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080041#define BPFLOADER_VERSION ((BPFLOADER_VERSION_MAJOR << 16) | BPFLOADER_VERSION_MINOR)
42
Maciej Żenczykowski300c51f2022-12-14 04:18:02 -080043#include "BpfSyscallWrappers.h"
Maciej Żenczykowski07375e22020-02-19 14:23:59 -080044#include "bpf/BpfUtils.h"
Ken Chend5689472021-12-20 18:07:21 +080045#include "bpf/bpf_map_def.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070046#include "include/libbpf_android.h"
47
Maciej Żenczykowskib3dcc142022-07-24 22:42:33 +000048#if BPFLOADER_VERSION < COMPILE_FOR_BPFLOADER_VERSION
49#error "BPFLOADER_VERSION is less than COMPILE_FOR_BPFLOADER_VERSION"
50#endif
51
Joel Fernandesd76a2002018-10-16 13:19:58 -070052#include <cstdlib>
53#include <fstream>
54#include <iostream>
Connor O'Brien3278a162020-02-13 21:45:22 -080055#include <optional>
Joel Fernandesd76a2002018-10-16 13:19:58 -070056#include <string>
Connor O'Brien35425e52022-01-18 21:41:16 -080057#include <unordered_map>
Christopher Ferrisc151c672019-02-01 15:31:26 -080058#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070059
Connor O'Brien35425e52022-01-18 21:41:16 -080060#include <android-base/cmsg.h>
61#include <android-base/file.h>
Elliott Hughes3b0811b2023-10-09 22:20:04 +000062#include <android-base/properties.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070063#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070064#include <android-base/unique_fd.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070065
66#define BPF_FS_PATH "/sys/fs/bpf/"
67
68// Size of the BPF log buffer for verifier logging
Stephane Leeeb61b732021-10-21 17:03:11 -070069#define BPF_LOAD_LOG_SZ 0xfffff
Joel Fernandesd76a2002018-10-16 13:19:58 -070070
Tyler Wear4e2f4602022-02-03 09:46:01 -080071// Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
72#define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
73
Joel Fernandesd76a2002018-10-16 13:19:58 -070074using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070075using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070076using std::ifstream;
77using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080078using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080079using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070080using std::vector;
81
82namespace android {
83namespace bpf {
84
Ryan Zukliece89f502022-12-15 16:14:32 -080085const std::string& getBuildType() {
Elliott Hughes3b0811b2023-10-09 22:20:04 +000086 static std::string t = android::base::GetProperty("ro.build.type", "unknown");
Ryan Zukliece89f502022-12-15 16:14:32 -080087 return t;
88}
89
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +000090static unsigned int page_size = static_cast<unsigned int>(getpagesize());
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";
Maciej Żenczykowski41817132022-06-03 08:41:04 -070096 case domain::vendor: return "fs_bpf_vendor";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +000097 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski41817132022-06-03 08:41:04 -070098 default: return "(unrecognized)";
99 }
100}
101
102domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
103 for (domain d : AllDomains) {
104 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
105 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
106 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
107 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700108 ALOGW("ignoring unrecognized selinux_context '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700109 // We should return 'unrecognized' here, however: returning unspecified will
110 // result in the system simply using the default context, which in turn
111 // will allow future expansion by adding more restrictive selinux types.
112 // Older bpfloader will simply ignore that, and use the less restrictive default.
113 // This does mean you CANNOT later add a *less* restrictive type than the default.
114 //
115 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
116 return domain::unspecified;
117}
118
119constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
120 switch (d) {
121 case domain::unspecified: return unspecified;
122 case domain::platform: return "/";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700123 case domain::vendor: return "vendor/";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +0000124 case domain::loader: return "loader/";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700125 default: return "(unrecognized)";
126 }
127};
128
129domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
130 for (domain d : AllDomains) {
131 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
132 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
133 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
134 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700135 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700136 // pin_subdir affects the object's full pathname,
137 // and thus using the default would change the location and thus our code's ability to find it,
138 // hence this seems worth treating as a true error condition.
139 //
140 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
141 // However, our callers will treat this as an error, and stop loading the specific .o,
142 // which will fail bpfloader if the .o is marked critical.
143 return domain::unrecognized;
144}
145
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700146static string pathToObjName(const string& path) {
147 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
148 string filename = android::base::Split(path, "/").back();
149 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
150 string name = filename.substr(0, filename.find_last_of('.'));
151 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
152 // this can be used to provide duplicate programs (mux based on the bpfloader version)
153 return name.substr(0, name.find_last_of('@'));
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800154}
155
Joel Fernandesd76a2002018-10-16 13:19:58 -0700156typedef struct {
157 const char* name;
158 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800159 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700160} sectionType;
161
162/*
163 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700164 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -0700165 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700166 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -0700167 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700168 *
169 * However, be aware that you should not be directly using the SECTION() macro.
170 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -0700171 */
172sectionType sectionNameTypes[] = {
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000173 {"kprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
174 {"kretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000175 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000176 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000177 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
178 {"uprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
179 {"uretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700180};
181
182typedef struct {
183 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800184 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700185 string name;
186 vector<char> data;
187 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800188 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700189
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700190 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700191} codeSection;
192
Joel Fernandesd76a2002018-10-16 13:19:58 -0700193static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
194 elfFile.seekg(0);
195 if (elfFile.fail()) return -1;
196
197 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
198
199 return 0;
200}
201
202/* Reads all section header tables into an Shdr array */
203static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
204 Elf64_Ehdr eh;
205 int ret = 0;
206
207 ret = readElfHeader(elfFile, &eh);
208 if (ret) return ret;
209
210 elfFile.seekg(eh.e_shoff);
211 if (elfFile.fail()) return -1;
212
213 /* Read shdr table entries */
214 shTable.resize(eh.e_shnum);
215
216 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
217
218 return 0;
219}
220
221/* Read a section by its index - for ex to get sec hdr strtab blob */
222static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
223 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800224 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700225 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700226
227 elfFile.seekg(shTable[id].sh_offset);
228 if (elfFile.fail()) return -1;
229
230 sec.resize(shTable[id].sh_size);
231 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
232
233 return 0;
234}
235
236/* Read whole section header string table */
237static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
238 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800239 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700240 if (ret) return ret;
241
242 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
243 if (ret) return ret;
244
245 return 0;
246}
247
248/* Get name from offset in strtab */
249static int getSymName(ifstream& elfFile, int nameOff, string& name) {
250 int ret;
251 vector<char> secStrTab;
252
253 ret = readSectionHeaderStrtab(elfFile, secStrTab);
254 if (ret) return ret;
255
256 if (nameOff >= (int)secStrTab.size()) return -1;
257
258 name = string((char*)secStrTab.data() + nameOff);
259 return 0;
260}
261
262/* Reads a full section by name - example to get the GPL license */
263static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
264 vector<char> secStrTab;
265 vector<Elf64_Shdr> shTable;
266 int ret;
267
268 ret = readSectionHeadersAll(elfFile, shTable);
269 if (ret) return ret;
270
271 ret = readSectionHeaderStrtab(elfFile, secStrTab);
272 if (ret) return ret;
273
274 for (int i = 0; i < (int)shTable.size(); i++) {
275 char* secname = secStrTab.data() + shTable[i].sh_name;
276 if (!secname) continue;
277
278 if (!strcmp(secname, name)) {
279 vector<char> dataTmp;
280 dataTmp.resize(shTable[i].sh_size);
281
282 elfFile.seekg(shTable[i].sh_offset);
283 if (elfFile.fail()) return -1;
284
285 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
286
287 data = dataTmp;
288 return 0;
289 }
290 }
291 return -2;
292}
293
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700294unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800295 vector<char> theBytes;
296 int ret = readSectionByName(name, elfFile, theBytes);
297 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700298 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800299 return defVal;
300 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700301 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800302 return defVal;
303 } else {
304 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
305 unsigned int value = static_cast<unsigned char>(theBytes[3]);
306 value <<= 8;
307 value += static_cast<unsigned char>(theBytes[2]);
308 value <<= 8;
309 value += static_cast<unsigned char>(theBytes[1]);
310 value <<= 8;
311 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700312 ALOGI("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800313 return value;
314 }
315}
316
Joel Fernandesd76a2002018-10-16 13:19:58 -0700317static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
318 int ret;
319 vector<Elf64_Shdr> shTable;
320
321 ret = readSectionHeadersAll(elfFile, shTable);
322 if (ret) return ret;
323
324 for (int i = 0; i < (int)shTable.size(); i++) {
325 if ((int)shTable[i].sh_type != type) continue;
326
327 vector<char> dataTmp;
328 dataTmp.resize(shTable[i].sh_size);
329
330 elfFile.seekg(shTable[i].sh_offset);
331 if (elfFile.fail()) return -1;
332
333 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
334
335 data = dataTmp;
336 return 0;
337 }
338 return -2;
339}
340
341static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
342 return (a.st_value < b.st_value);
343}
344
345static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
346 int ret, numElems;
347 Elf64_Sym* buf;
348 vector<char> secData;
349
350 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
351 if (ret) return ret;
352
353 buf = (Elf64_Sym*)secData.data();
354 numElems = (secData.size() / sizeof(Elf64_Sym));
355 data.assign(buf, buf + numElems);
356
357 if (sort) std::sort(data.begin(), data.end(), symCompare);
358 return 0;
359}
360
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700361static enum bpf_prog_type getFuseProgType() {
362 int result = BPF_PROG_TYPE_UNSPEC;
363 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
364 return static_cast<bpf_prog_type>(result);
365}
366
Joel Fernandesd76a2002018-10-16 13:19:58 -0700367static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800368 for (auto& snt : sectionNameTypes)
369 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700370
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000371 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700372 if (StartsWith(name, "fuse/")) return getFuseProgType();
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000373
Joel Fernandesd76a2002018-10-16 13:19:58 -0700374 return BPF_PROG_TYPE_UNSPEC;
375}
376
Tyler Wear4e2f4602022-02-03 09:46:01 -0800377static enum bpf_attach_type getExpectedAttachType(string& name) {
378 for (auto& snt : sectionNameTypes)
379 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
380 return BPF_ATTACH_TYPE_UNSPEC;
381}
382
Joel Fernandesd76a2002018-10-16 13:19:58 -0700383static string getSectionName(enum bpf_prog_type type)
384{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800385 for (auto& snt : sectionNameTypes)
386 if (snt.type == type)
387 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700388
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800389 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700390}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700391
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800392static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
393 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800394 vector<char> pdData;
395 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800396 // Older file formats do not require a 'progs' section at all.
397 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800398 if (ret == -2) return 0;
399 if (ret) return ret;
400
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800401 if (pdData.size() % sizeOfBpfProgDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700402 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800403 pdData.size(), sizeOfBpfProgDef);
404 return -1;
405 };
406
407 int progCount = pdData.size() / sizeOfBpfProgDef;
408 pd.resize(progCount);
409 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
410
411 const char* dataPtr = pdData.data();
412 for (auto& p : pd) {
413 // First we zero initialize
414 memset(&p, 0, sizeof(p));
415 // Then we set non-zero defaults
416 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
417 // Then we copy over the structure prefix from the ELF file.
418 memcpy(&p, dataPtr, trimmedSize);
419 // Move to next struct in the ELF file
420 dataPtr += sizeOfBpfProgDef;
421 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800422 return 0;
423}
424
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800425static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
426 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800427 int ret;
428 string name;
429 vector<Elf64_Sym> symtab;
430 vector<Elf64_Shdr> shTable;
431
432 ret = readSymTab(elfFile, 1 /* sort */, symtab);
433 if (ret) return ret;
434
435 /* Get index of section */
436 ret = readSectionHeadersAll(elfFile, shTable);
437 if (ret) return ret;
438
439 int sec_idx = -1;
440 for (int i = 0; i < (int)shTable.size(); i++) {
441 ret = getSymName(elfFile, shTable[i].sh_name, name);
442 if (ret) return ret;
443
444 if (!name.compare(sectionName)) {
445 sec_idx = i;
446 break;
447 }
448 }
449
450 /* No section found with matching name*/
451 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700452 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800453 return -1;
454 }
455
456 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800457 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
458
Connor O'Brien3278a162020-02-13 21:45:22 -0800459 if (symtab[i].st_shndx == sec_idx) {
460 string s;
461 ret = getSymName(elfFile, symtab[i].st_name, s);
462 if (ret) return ret;
463 names.push_back(s);
464 }
465 }
466
467 return 0;
468}
469
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800470static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
471 if (allowed == nullptr) return true;
472
473 for (size_t i = 0; i < numAllowed; i++) {
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700474 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
475 if (type == getFuseProgType()) return true;
476 } else if (type == allowed[i])
477 return true;
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800478 }
479
480 return false;
481}
482
Joel Fernandesd76a2002018-10-16 13:19:58 -0700483/* Read a section by its index - for ex to get sec hdr strtab blob */
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800484static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef,
485 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700486 vector<Elf64_Shdr> shTable;
487 int entries, ret = 0;
488
489 ret = readSectionHeadersAll(elfFile, shTable);
490 if (ret) return ret;
491 entries = shTable.size();
492
Connor O'Brien3278a162020-02-13 21:45:22 -0800493 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800494 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800495 if (ret) return ret;
496 vector<string> progDefNames;
497 ret = getSectionSymNames(elfFile, "progs", progDefNames);
498 if (!pd.empty() && ret) return ret;
499
Joel Fernandesd76a2002018-10-16 13:19:58 -0700500 for (int i = 0; i < entries; i++) {
501 string name;
502 codeSection cs_temp;
503 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
504
505 ret = getSymName(elfFile, shTable[i].sh_name, name);
506 if (ret) return ret;
507
508 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800509
Tyler Wear4e2f4602022-02-03 09:46:01 -0800510 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800511
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800512 if (!IsAllowed(ptype, allowed, numAllowed)) {
513 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
514 return -1;
515 }
516
Tyler Wear4e2f4602022-02-03 09:46:01 -0800517 // This must be done before '/' is replaced with '_'.
518 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800519
Tyler Wear4e2f4602022-02-03 09:46:01 -0800520 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700521
Tyler Wear4e2f4602022-02-03 09:46:01 -0800522 // convert all slashes to underscores
523 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800524
Tyler Wear4e2f4602022-02-03 09:46:01 -0800525 cs_temp.type = ptype;
526 cs_temp.name = name;
527
528 ret = readSectionByIdx(elfFile, i, cs_temp.data);
529 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700530 ALOGD("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800531
532 vector<string> csSymNames;
533 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
534 if (ret || !csSymNames.size()) return ret;
535 for (size_t i = 0; i < progDefNames.size(); ++i) {
536 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
537 cs_temp.prog_def = pd[i];
538 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800539 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700540 }
541
542 /* Check for rel section */
543 if (cs_temp.data.size() > 0 && i < entries) {
544 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
545 if (ret) return ret;
546
Tyler Wear4e2f4602022-02-03 09:46:01 -0800547 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700548 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
549 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700550 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700551 }
552 }
553
554 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700555 cs.push_back(std::move(cs_temp));
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700556 ALOGD("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700557 }
558 }
559 return 0;
560}
561
562static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
563 vector<Elf64_Sym> symtab;
564 int ret = 0;
565
566 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
567 if (ret) return ret;
568
569 if (index >= (int)symtab.size()) return -1;
570
571 return getSymName(elfFile, symtab[index].st_name, name);
572}
573
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700574static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
575 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700576 // Assuming fd is a valid Bpf Map file descriptor then
577 // all the following should always succeed on a 4.14+ kernel.
578 // If they somehow do fail, they'll return -1 (and set errno),
579 // which should then cause (among others) a key_size mismatch.
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700580 int fd_type = bpfGetFdMapType(fd);
581 int fd_key_size = bpfGetFdKeySize(fd);
582 int fd_value_size = bpfGetFdValueSize(fd);
583 int fd_max_entries = bpfGetFdMaxEntries(fd);
584 int fd_map_flags = bpfGetFdMapFlags(fd);
585
586 // DEVMAPs are readonly from the bpf program side's point of view, as such
587 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
588 int desired_map_flags = (int)mapDef.map_flags;
589 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
590 desired_map_flags |= BPF_F_RDONLY_PROG;
591
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000592 // The .h file enforces that this is a power of two, and page size will
593 // also always be a power of two, so this logic is actually enough to
594 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000595 unsigned int desired_max_entries = mapDef.max_entries;
596 if (type == BPF_MAP_TYPE_RINGBUF) {
597 if (desired_max_entries < page_size) desired_max_entries = page_size;
598 }
599
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700600 // The following checks should *never* trigger, if one of them somehow does,
601 // it probably means a bpf .o file has been changed/replaced at runtime
602 // and bpfloader was manually rerun (normally it should only run *once*
603 // early during the boot process).
604 // Another possibility is that something is misconfigured in the code:
605 // most likely a shared map is declared twice differently.
606 // But such a change should never be checked into the source tree...
607 if ((fd_type == type) &&
608 (fd_key_size == (int)mapDef.key_size) &&
609 (fd_value_size == (int)mapDef.value_size) &&
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000610 (fd_max_entries == (int)desired_max_entries) &&
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700611 (fd_map_flags == desired_map_flags)) {
612 return true;
613 }
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700614
615 ALOGE("bpf map name %s mismatch: desired/found: "
616 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
617 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
618 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
619 return false;
620}
621
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800622static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700623 const char* prefix, const unsigned long long allowedDomainBitmask,
624 const size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700625 int ret;
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700626 vector<char> mdData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700627 vector<struct bpf_map_def> md;
628 vector<string> mapNames;
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700629 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700630
631 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800632 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700633 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800634
635 if (mdData.size() % sizeOfBpfMapDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700636 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800637 mdData.size(), sizeOfBpfMapDef);
638 return -1;
639 };
640
641 int mapCount = mdData.size() / sizeOfBpfMapDef;
642 md.resize(mapCount);
643 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
644
645 const char* dataPtr = mdData.data();
646 for (auto& m : md) {
647 // First we zero initialize
648 memset(&m, 0, sizeof(m));
649 // Then we set non-zero defaults
650 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700651 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800652 // Then we copy over the structure prefix from the ELF file.
653 memcpy(&m, dataPtr, trimmedSize);
654 // Move to next struct in the ELF file
655 dataPtr += sizeOfBpfMapDef;
656 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700657
Connor O'Brien3278a162020-02-13 21:45:22 -0800658 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700659 if (ret) return ret;
660
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700661 unsigned kvers = kernelVersion();
662
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700663 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +0000664 if (md[i].zero != 0) abort();
665
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800666 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700667 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800668 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700669 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800670 continue;
671 }
672
673 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700674 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800675 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700676 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800677 continue;
678 }
679
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700680 if (kvers < md[i].min_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700681 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700682 mapNames[i].c_str(), kvers, md[i].min_kver);
683 mapFds.push_back(unique_fd());
684 continue;
685 }
686
687 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700688 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700689 mapNames[i].c_str(), kvers, md[i].max_kver);
690 mapFds.push_back(unique_fd());
691 continue;
692 }
693
Ryan Zukliece89f502022-12-15 16:14:32 -0800694 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
695 (md[i].ignore_on_userdebug && isUserdebug())) {
696 ALOGI("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
697 getBuildType().c_str());
698 mapFds.push_back(unique_fd());
699 continue;
700 }
701
Maciej Żenczykowski8d2e7d92023-05-19 21:06:00 +0000702 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
703 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
704 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
705 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
706 (isRiscV() && md[i].ignore_on_riscv64)) {
707 ALOGI("skipping map %s which is ignored on %s", mapNames[i].c_str(),
708 describeArch());
709 mapFds.push_back(unique_fd());
710 continue;
711 }
712
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700713 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700714 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
715 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
716 // of be approximated: HASH has the same userspace visible api.
717 // However it cannot be used by ebpf programs in the same way.
718 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
719 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
720 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
721 // programs as being 5.4+...
722 type = BPF_MAP_TYPE_HASH;
723 }
724
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000725 // The .h file enforces that this is a power of two, and page size will
726 // also always be a power of two, so this logic is actually enough to
727 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000728 unsigned int max_entries = md[i].max_entries;
729 if (type == BPF_MAP_TYPE_RINGBUF) {
730 if (max_entries < page_size) max_entries = page_size;
731 }
732
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700733 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
734 if (specified(selinux_context)) {
735 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
736 ALOGE("map %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
737 mapNames[i].c_str(), selinux_context, allowedDomainBitmask);
738 return -EINVAL;
739 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700740 ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700741 md[i].selinux_context, selinux_context, lookupSelinuxContext(selinux_context),
742 lookupPinSubdir(selinux_context));
743 }
744
745 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
746 if (unrecognized(pin_subdir)) return -ENOTDIR;
747 if (specified(pin_subdir)) {
748 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
749 ALOGE("map %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)",
750 mapNames[i].c_str(), pin_subdir, allowedDomainBitmask);
751 return -EINVAL;
752 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700753 ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700754 pin_subdir, lookupPinSubdir(pin_subdir));
755 }
756
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700757 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
758 // except that maps shared across .o's have empty <objName>
759 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700760 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700761 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700762 bool reuse = false;
763 unique_fd fd;
764 int saved_errno;
765
Joel Fernandesd76a2002018-10-16 13:19:58 -0700766 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskieb199dd2022-07-01 03:21:40 -0700767 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800768 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700769 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700770 reuse = true;
771 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700772 union bpf_attr req = {
773 .map_type = type,
774 .key_size = md[i].key_size,
775 .value_size = md[i].value_size,
776 .max_entries = max_entries,
777 .map_flags = md[i].map_flags,
Connor O'Brien35425e52022-01-18 21:41:16 -0800778 };
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700779 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
780 fd.reset(bpf(BPF_MAP_CREATE, req));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800781 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700782 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700783 }
784
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700785 if (!fd.ok()) return -saved_errno;
786
787 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
788 // safety (since reuse code path is rare) run these checks even if we just created it.
789 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
790 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700791
792 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700793 if (specified(selinux_context)) {
794 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700795 "tmp_map_" + objName + "_" + mapNames[i];
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700796 ret = bpfFdPin(fd, createLoc.c_str());
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700797 if (ret) {
798 int err = errno;
799 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
800 return -err;
801 }
Maciej Żenczykowskie15229f2023-04-17 07:16:33 +0000802 ret = renameat2(AT_FDCWD, createLoc.c_str(),
803 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700804 if (ret) {
805 int err = errno;
806 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
807 err, strerror(err));
808 return -err;
809 }
810 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700811 ret = bpfFdPin(fd, mapPinLoc.c_str());
Maciej Żenczykowskid8259aa2022-06-27 10:02:20 -0700812 if (ret) {
813 int err = errno;
814 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
815 return -err;
816 }
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700817 }
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800818 ret = chmod(mapPinLoc.c_str(), md[i].mode);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700819 if (ret) {
820 int err = errno;
821 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
822 strerror(err));
823 return -err;
824 }
Maciej Żenczykowski5e4aabf2022-06-27 01:15:53 -0700825 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
826 if (ret) {
827 int err = errno;
828 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
829 ret, err, strerror(err));
830 return -err;
831 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700832 }
833
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700834 int mapId = bpfGetFdMapId(fd);
835 if (mapId == -1) {
836 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700837 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700838 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700839 }
840
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700841 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700842 }
843
844 return ret;
845}
846
847/* For debugging, dump all instructions */
848static void dumpIns(char* ins, int size) {
849 for (int row = 0; row < size / 8; row++) {
850 ALOGE("%d: ", row);
851 for (int j = 0; j < 8; j++) {
852 ALOGE("%3x ", ins[(row * 8) + j]);
853 }
854 ALOGE("\n");
855 }
856}
857
858/* For debugging, dump all code sections from cs list */
859static void dumpAllCs(vector<codeSection>& cs) {
860 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700861 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700862 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700863 ALOGE("-----------");
Joel Fernandesd76a2002018-10-16 13:19:58 -0700864 }
865}
866
867static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
868 int insnIndex;
869 struct bpf_insn *insn, *insns;
870
871 insns = (struct bpf_insn*)(insnsPtr);
872
873 insnIndex = offset / sizeof(struct bpf_insn);
874 insn = &insns[insnIndex];
875
Maciej Żenczykowski509b1b92023-03-07 01:11:20 +0000876 // Occasionally might be useful for relocation debugging, but pretty spammy
877 if (0) {
878 ALOGD("applying relo to instruction at byte offset: %llu, "
879 "insn offset %d, insn %llx",
880 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
881 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700882
883 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700884 ALOGE("Dumping all instructions till ins %d", insnIndex);
885 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700886 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
887 return;
888 }
889
890 insn->imm = fd;
891 insn->src_reg = BPF_PSEUDO_MAP_FD;
892}
893
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700894static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700895 vector<string> mapNames;
896
Connor O'Brien3278a162020-02-13 21:45:22 -0800897 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700898 if (ret) return;
899
900 for (int k = 0; k != (int)cs.size(); k++) {
901 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
902 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
903
904 for (int i = 0; i < n_rel; i++) {
905 int symIndex = ELF64_R_SYM(rel[i].r_info);
906 string symName;
907
908 ret = getSymNameByIdx(elfFile, symIndex, symName);
909 if (ret) return;
910
911 /* Find the map fd and apply relo */
912 for (int j = 0; j < (int)mapNames.size(); j++) {
913 if (!mapNames[j].compare(symName)) {
914 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
915 break;
916 }
917 }
918 }
919 }
920}
921
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800922static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700923 const char* prefix, const unsigned long long allowedDomainBitmask) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800924 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700925
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000926 if (!kvers) {
927 ALOGE("unable to get kernel version");
928 return -EINVAL;
929 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700930
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700931 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700932
933 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700934 unique_fd& fd = cs[i].prog_fd;
935 int ret;
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700936 string name = cs[i].name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700937
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000938 if (!cs[i].prog_def.has_value()) {
939 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
940 return -EINVAL;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800941 }
942
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000943 unsigned min_kver = cs[i].prog_def->min_kver;
944 unsigned max_kver = cs[i].prog_def->max_kver;
945 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
946 max_kver, kvers);
947 if (kvers < min_kver) continue;
948 if (kvers >= max_kver) continue;
949
950 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
951 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
952 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
953 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
954 // Note: make sure to only check for unrecognized *after* verifying bpfloader
955 // version limits include this bpfloader's version.
956
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700957 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800958 bpfMinVer, bpfMaxVer);
959 if (BPFLOADER_VERSION < bpfMinVer) continue;
960 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
Ryan Zukliece89f502022-12-15 16:14:32 -0800961
962 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
963 (cs[i].prog_def->ignore_on_user && isUser()) ||
964 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
965 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
966 getBuildType().c_str());
Ryan Zuklie0fb433a2023-01-05 14:22:15 -0800967 continue;
Ryan Zukliece89f502022-12-15 16:14:32 -0800968 }
969
Maciej Żenczykowski8d2e7d92023-05-19 21:06:00 +0000970 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
971 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
972 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
973 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
974 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
975 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
976 continue;
977 }
978
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700979 if (unrecognized(pin_subdir)) return -ENOTDIR;
980
981 if (specified(selinux_context)) {
982 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
983 ALOGE("prog %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
984 name.c_str(), selinux_context, allowedDomainBitmask);
985 return -EINVAL;
986 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700987 ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700988 cs[i].prog_def->selinux_context, selinux_context,
989 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
990 }
991
992 if (specified(pin_subdir)) {
993 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
994 ALOGE("prog %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)", name.c_str(),
995 pin_subdir, allowedDomainBitmask);
996 return -EINVAL;
997 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700998 ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700999 cs[i].prog_def->pin_subdir, pin_subdir, lookupPinSubdir(pin_subdir));
1000 }
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001001
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001002 // strip any potential $foo suffix
1003 // this can be used to provide duplicate programs
1004 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -07001005 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001006
1007 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001008 // Format of pin location is
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001009 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001010 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001011 objName + '_' + string(name);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001012 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001013 fd.reset(retrieveProgram(progPinLoc.c_str()));
1014 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
1015 (!fd.ok() ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001016 reuse = true;
1017 } else {
1018 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1019
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001020 union bpf_attr req = {
1021 .prog_type = cs[i].type,
1022 .kern_version = kvers,
1023 .license = ptr_to_u64(license.c_str()),
1024 .insns = ptr_to_u64(cs[i].data.data()),
1025 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
1026 .log_level = 1,
1027 .log_buf = ptr_to_u64(log_buf.data()),
1028 .log_size = static_cast<__u32>(log_buf.size()),
1029 .expected_attach_type = cs[i].expected_attach_type,
Tyler Wear4e2f4602022-02-03 09:46:01 -08001030 };
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001031 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1032 fd.reset(bpf(BPF_PROG_LOAD, req));
Tyler Wear4e2f4602022-02-03 09:46:01 -08001033
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001034 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
1035 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
Tyler Wear4e2f4602022-02-03 09:46:01 -08001036
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001037 if (!fd.ok()) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -08001038 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001039
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001040 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001041 for (const auto& line : lines) ALOGW("%s", line.c_str());
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001042 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001043
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001044 if (cs[i].prog_def->optional) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001045 ALOGW("failed program is marked optional - continuing...");
1046 continue;
1047 }
1048 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001049 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001050 }
1051
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001052 if (!fd.ok()) return fd.get();
Joel Fernandesd76a2002018-10-16 13:19:58 -07001053
1054 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001055 if (specified(selinux_context)) {
1056 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001057 "tmp_prog_" + objName + '_' + string(name);
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001058 ret = bpfFdPin(fd, createLoc.c_str());
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001059 if (ret) {
1060 int err = errno;
1061 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1062 return -err;
1063 }
Maciej Żenczykowskie15229f2023-04-17 07:16:33 +00001064 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1065 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001066 if (ret) {
1067 int err = errno;
1068 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1069 err, strerror(err));
1070 return -err;
1071 }
1072 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001073 ret = bpfFdPin(fd, progPinLoc.c_str());
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001074 if (ret) {
1075 int err = errno;
1076 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1077 return -err;
1078 }
1079 }
1080 if (chmod(progPinLoc.c_str(), 0440)) {
1081 int err = errno;
1082 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1083 return -err;
1084 }
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001085 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1086 (gid_t)cs[i].prog_def->gid)) {
1087 int err = errno;
1088 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1089 cs[i].prog_def->gid, err, strerror(err));
1090 return -err;
Connor O'Brien3278a162020-02-13 21:45:22 -08001091 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001092 }
1093
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001094 int progId = bpfGetFdProgId(fd);
1095 if (progId == -1) {
1096 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001097 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001098 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001099 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001100 }
1101
1102 return 0;
1103}
1104
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001105int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
Joel Fernandesd76a2002018-10-16 13:19:58 -07001106 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001107 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001108 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001109 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001110 int ret;
1111
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001112 if (!isCritical) return -1;
1113 *isCritical = false;
1114
Joel Fernandesd76a2002018-10-16 13:19:58 -07001115 ifstream elfFile(elfPath, ios::in | ios::binary);
1116 if (!elfFile.is_open()) return -1;
1117
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001118 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001119 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001120
Joel Fernandesd76a2002018-10-16 13:19:58 -07001121 ret = readSectionByName("license", elfFile, license);
1122 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001123 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001124 return ret;
1125 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001126 ALOGD("Loading %s%s ELF object %s with license %s",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001127 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001128 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -07001129 }
1130
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001131 // the following default values are for bpfloader V0.0 format which does not include them
1132 unsigned int bpfLoaderMinVer =
1133 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1134 unsigned int bpfLoaderMaxVer =
1135 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001136 unsigned int bpfLoaderMinRequiredVer =
1137 readSectionUint("bpfloader_min_required_ver", elfFile, 0);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001138 size_t sizeOfBpfMapDef =
1139 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1140 size_t sizeOfBpfProgDef =
1141 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1142
1143 // inclusive lower bound check
1144 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001145 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001146 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
1147 return 0;
1148 }
1149
1150 // exclusive upper bound check
1151 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001152 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001153 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
1154 return 0;
1155 }
1156
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001157 if (BPFLOADER_VERSION < bpfLoaderMinRequiredVer) {
1158 ALOGI("BpfLoader version 0x%05x failing due to ELF object %s with required min ver 0x%05x",
1159 BPFLOADER_VERSION, elfPath, bpfLoaderMinRequiredVer);
1160 return -1;
1161 }
1162
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001163 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001164 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1165
1166 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001167 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001168 DEFAULT_SIZEOF_BPF_MAP_DEF);
1169 return -1;
1170 }
1171
1172 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001173 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001174 DEFAULT_SIZEOF_BPF_PROG_DEF);
1175 return -1;
1176 }
1177
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001178 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, location.allowedProgTypes,
1179 location.allowedProgTypesLength);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001180 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001181 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001182 return ret;
1183 }
1184
1185 /* Just for future debugging */
1186 if (0) dumpAllCs(cs);
1187
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001188 ret = createMaps(elfPath, elfFile, mapFds, location.prefix, location.allowedDomainBitmask,
1189 sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001190 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001191 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001192 return ret;
1193 }
1194
1195 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001196 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001197
1198 applyMapRelo(elfFile, mapFds, cs);
1199
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001200 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix,
1201 location.allowedDomainBitmask);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001202 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001203
1204 return ret;
1205}
1206
Joel Fernandesd76a2002018-10-16 13:19:58 -07001207} // namespace bpf
1208} // namespace android