blob: d817614523c5258e96a0b411b357a7f0b1069cc1 [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>
Joel Fernandesd76a2002018-10-16 13:19:58 -070062#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070063#include <android-base/unique_fd.h>
Ryan Zukliece89f502022-12-15 16:14:32 -080064#include <cutils/properties.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
Ryan Zukliece89f502022-12-15 16:14:32 -080082static std::string getBuildTypeInternal() {
83 char value[PROPERTY_VALUE_MAX] = {};
84 (void)property_get("ro.build.type", value, "unknown"); // ignore length
85 return value;
86}
87
Joel Fernandesd76a2002018-10-16 13:19:58 -070088namespace android {
89namespace bpf {
90
Ryan Zukliece89f502022-12-15 16:14:32 -080091const std::string& getBuildType() {
92 static std::string t = getBuildTypeInternal();
93 return t;
94}
95
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +000096static unsigned int page_size = static_cast<unsigned int>(getpagesize());
97
Maciej Żenczykowski41817132022-06-03 08:41:04 -070098constexpr const char* lookupSelinuxContext(const domain d, const char* const unspecified = "") {
99 switch (d) {
100 case domain::unspecified: return unspecified;
101 case domain::platform: return "fs_bpf";
102 case domain::tethering: return "fs_bpf_tethering";
103 case domain::net_private: return "fs_bpf_net_private";
104 case domain::net_shared: return "fs_bpf_net_shared";
105 case domain::netd_readonly: return "fs_bpf_netd_readonly";
106 case domain::netd_shared: return "fs_bpf_netd_shared";
107 case domain::vendor: return "fs_bpf_vendor";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +0000108 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700109 default: return "(unrecognized)";
110 }
111}
112
113domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
114 for (domain d : AllDomains) {
115 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
116 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
117 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
118 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700119 ALOGW("ignoring unrecognized selinux_context '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700120 // We should return 'unrecognized' here, however: returning unspecified will
121 // result in the system simply using the default context, which in turn
122 // will allow future expansion by adding more restrictive selinux types.
123 // Older bpfloader will simply ignore that, and use the less restrictive default.
124 // This does mean you CANNOT later add a *less* restrictive type than the default.
125 //
126 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
127 return domain::unspecified;
128}
129
130constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
131 switch (d) {
132 case domain::unspecified: return unspecified;
133 case domain::platform: return "/";
134 case domain::tethering: return "tethering/";
135 case domain::net_private: return "net_private/";
136 case domain::net_shared: return "net_shared/";
137 case domain::netd_readonly: return "netd_readonly/";
138 case domain::netd_shared: return "netd_shared/";
139 case domain::vendor: return "vendor/";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +0000140 case domain::loader: return "loader/";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700141 default: return "(unrecognized)";
142 }
143};
144
145domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
146 for (domain d : AllDomains) {
147 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
148 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
149 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
150 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700151 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700152 // pin_subdir affects the object's full pathname,
153 // and thus using the default would change the location and thus our code's ability to find it,
154 // hence this seems worth treating as a true error condition.
155 //
156 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
157 // However, our callers will treat this as an error, and stop loading the specific .o,
158 // which will fail bpfloader if the .o is marked critical.
159 return domain::unrecognized;
160}
161
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700162static string pathToObjName(const string& path) {
163 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
164 string filename = android::base::Split(path, "/").back();
165 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
166 string name = filename.substr(0, filename.find_last_of('.'));
167 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
168 // this can be used to provide duplicate programs (mux based on the bpfloader version)
169 return name.substr(0, name.find_last_of('@'));
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800170}
171
Joel Fernandesd76a2002018-10-16 13:19:58 -0700172typedef struct {
173 const char* name;
174 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800175 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700176} sectionType;
177
178/*
179 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700180 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -0700181 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700182 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -0700183 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700184 *
185 * However, be aware that you should not be directly using the SECTION() macro.
186 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -0700187 */
188sectionType sectionNameTypes[] = {
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000189 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
190 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
191 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB, BPF_ATTACH_TYPE_UNSPEC},
192 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_ATTACH_TYPE_UNSPEC},
193 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
194 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
195 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
196 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
197 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
198 {"kprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
199 {"kretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
200 {"lwt_in/", BPF_PROG_TYPE_LWT_IN, BPF_ATTACH_TYPE_UNSPEC},
201 {"lwt_out/", BPF_PROG_TYPE_LWT_OUT, BPF_ATTACH_TYPE_UNSPEC},
202 {"lwt_seg6local/", BPF_PROG_TYPE_LWT_SEG6LOCAL, BPF_ATTACH_TYPE_UNSPEC},
203 {"lwt_xmit/", BPF_PROG_TYPE_LWT_XMIT, BPF_ATTACH_TYPE_UNSPEC},
204 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT, BPF_ATTACH_TYPE_UNSPEC},
205 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
206 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
207 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
208 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
209 {"schedact/", BPF_PROG_TYPE_SCHED_ACT, BPF_ATTACH_TYPE_UNSPEC},
210 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS, BPF_ATTACH_TYPE_UNSPEC},
211 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
212 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
213 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
214 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
215 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
216 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
217 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
218 {"uprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
219 {"uretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
220 {"xdp/", BPF_PROG_TYPE_XDP, BPF_ATTACH_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700221};
222
223typedef struct {
224 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800225 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700226 string name;
227 vector<char> data;
228 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800229 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700230
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700231 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700232} codeSection;
233
Joel Fernandesd76a2002018-10-16 13:19:58 -0700234static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
235 elfFile.seekg(0);
236 if (elfFile.fail()) return -1;
237
238 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
239
240 return 0;
241}
242
243/* Reads all section header tables into an Shdr array */
244static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
245 Elf64_Ehdr eh;
246 int ret = 0;
247
248 ret = readElfHeader(elfFile, &eh);
249 if (ret) return ret;
250
251 elfFile.seekg(eh.e_shoff);
252 if (elfFile.fail()) return -1;
253
254 /* Read shdr table entries */
255 shTable.resize(eh.e_shnum);
256
257 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
258
259 return 0;
260}
261
262/* Read a section by its index - for ex to get sec hdr strtab blob */
263static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
264 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800265 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700266 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700267
268 elfFile.seekg(shTable[id].sh_offset);
269 if (elfFile.fail()) return -1;
270
271 sec.resize(shTable[id].sh_size);
272 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
273
274 return 0;
275}
276
277/* Read whole section header string table */
278static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
279 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800280 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700281 if (ret) return ret;
282
283 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
284 if (ret) return ret;
285
286 return 0;
287}
288
289/* Get name from offset in strtab */
290static int getSymName(ifstream& elfFile, int nameOff, string& name) {
291 int ret;
292 vector<char> secStrTab;
293
294 ret = readSectionHeaderStrtab(elfFile, secStrTab);
295 if (ret) return ret;
296
297 if (nameOff >= (int)secStrTab.size()) return -1;
298
299 name = string((char*)secStrTab.data() + nameOff);
300 return 0;
301}
302
303/* Reads a full section by name - example to get the GPL license */
304static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
305 vector<char> secStrTab;
306 vector<Elf64_Shdr> shTable;
307 int ret;
308
309 ret = readSectionHeadersAll(elfFile, shTable);
310 if (ret) return ret;
311
312 ret = readSectionHeaderStrtab(elfFile, secStrTab);
313 if (ret) return ret;
314
315 for (int i = 0; i < (int)shTable.size(); i++) {
316 char* secname = secStrTab.data() + shTable[i].sh_name;
317 if (!secname) continue;
318
319 if (!strcmp(secname, name)) {
320 vector<char> dataTmp;
321 dataTmp.resize(shTable[i].sh_size);
322
323 elfFile.seekg(shTable[i].sh_offset);
324 if (elfFile.fail()) return -1;
325
326 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
327
328 data = dataTmp;
329 return 0;
330 }
331 }
332 return -2;
333}
334
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700335unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800336 vector<char> theBytes;
337 int ret = readSectionByName(name, elfFile, theBytes);
338 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700339 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800340 return defVal;
341 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700342 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800343 return defVal;
344 } else {
345 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
346 unsigned int value = static_cast<unsigned char>(theBytes[3]);
347 value <<= 8;
348 value += static_cast<unsigned char>(theBytes[2]);
349 value <<= 8;
350 value += static_cast<unsigned char>(theBytes[1]);
351 value <<= 8;
352 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700353 ALOGI("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800354 return value;
355 }
356}
357
Joel Fernandesd76a2002018-10-16 13:19:58 -0700358static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
359 int ret;
360 vector<Elf64_Shdr> shTable;
361
362 ret = readSectionHeadersAll(elfFile, shTable);
363 if (ret) return ret;
364
365 for (int i = 0; i < (int)shTable.size(); i++) {
366 if ((int)shTable[i].sh_type != type) continue;
367
368 vector<char> dataTmp;
369 dataTmp.resize(shTable[i].sh_size);
370
371 elfFile.seekg(shTable[i].sh_offset);
372 if (elfFile.fail()) return -1;
373
374 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
375
376 data = dataTmp;
377 return 0;
378 }
379 return -2;
380}
381
382static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
383 return (a.st_value < b.st_value);
384}
385
386static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
387 int ret, numElems;
388 Elf64_Sym* buf;
389 vector<char> secData;
390
391 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
392 if (ret) return ret;
393
394 buf = (Elf64_Sym*)secData.data();
395 numElems = (secData.size() / sizeof(Elf64_Sym));
396 data.assign(buf, buf + numElems);
397
398 if (sort) std::sort(data.begin(), data.end(), symCompare);
399 return 0;
400}
401
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700402static enum bpf_prog_type getFuseProgType() {
403 int result = BPF_PROG_TYPE_UNSPEC;
404 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
405 return static_cast<bpf_prog_type>(result);
406}
407
Joel Fernandesd76a2002018-10-16 13:19:58 -0700408static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800409 for (auto& snt : sectionNameTypes)
410 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700411
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000412 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700413 if (StartsWith(name, "fuse/")) return getFuseProgType();
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000414
Joel Fernandesd76a2002018-10-16 13:19:58 -0700415 return BPF_PROG_TYPE_UNSPEC;
416}
417
Tyler Wear4e2f4602022-02-03 09:46:01 -0800418static enum bpf_attach_type getExpectedAttachType(string& name) {
419 for (auto& snt : sectionNameTypes)
420 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
421 return BPF_ATTACH_TYPE_UNSPEC;
422}
423
Joel Fernandesd76a2002018-10-16 13:19:58 -0700424static string getSectionName(enum bpf_prog_type type)
425{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800426 for (auto& snt : sectionNameTypes)
427 if (snt.type == type)
428 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700429
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800430 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700431}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700432
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800433static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
434 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800435 vector<char> pdData;
436 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800437 // Older file formats do not require a 'progs' section at all.
438 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800439 if (ret == -2) return 0;
440 if (ret) return ret;
441
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800442 if (pdData.size() % sizeOfBpfProgDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700443 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800444 pdData.size(), sizeOfBpfProgDef);
445 return -1;
446 };
447
448 int progCount = pdData.size() / sizeOfBpfProgDef;
449 pd.resize(progCount);
450 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
451
452 const char* dataPtr = pdData.data();
453 for (auto& p : pd) {
454 // First we zero initialize
455 memset(&p, 0, sizeof(p));
456 // Then we set non-zero defaults
457 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
458 // Then we copy over the structure prefix from the ELF file.
459 memcpy(&p, dataPtr, trimmedSize);
460 // Move to next struct in the ELF file
461 dataPtr += sizeOfBpfProgDef;
462 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800463 return 0;
464}
465
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800466static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
467 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800468 int ret;
469 string name;
470 vector<Elf64_Sym> symtab;
471 vector<Elf64_Shdr> shTable;
472
473 ret = readSymTab(elfFile, 1 /* sort */, symtab);
474 if (ret) return ret;
475
476 /* Get index of section */
477 ret = readSectionHeadersAll(elfFile, shTable);
478 if (ret) return ret;
479
480 int sec_idx = -1;
481 for (int i = 0; i < (int)shTable.size(); i++) {
482 ret = getSymName(elfFile, shTable[i].sh_name, name);
483 if (ret) return ret;
484
485 if (!name.compare(sectionName)) {
486 sec_idx = i;
487 break;
488 }
489 }
490
491 /* No section found with matching name*/
492 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700493 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800494 return -1;
495 }
496
497 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800498 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
499
Connor O'Brien3278a162020-02-13 21:45:22 -0800500 if (symtab[i].st_shndx == sec_idx) {
501 string s;
502 ret = getSymName(elfFile, symtab[i].st_name, s);
503 if (ret) return ret;
504 names.push_back(s);
505 }
506 }
507
508 return 0;
509}
510
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800511static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
512 if (allowed == nullptr) return true;
513
514 for (size_t i = 0; i < numAllowed; i++) {
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700515 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
516 if (type == getFuseProgType()) return true;
517 } else if (type == allowed[i])
518 return true;
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800519 }
520
521 return false;
522}
523
Joel Fernandesd76a2002018-10-16 13:19:58 -0700524/* Read a section by its index - for ex to get sec hdr strtab blob */
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800525static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef,
526 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700527 vector<Elf64_Shdr> shTable;
528 int entries, ret = 0;
529
530 ret = readSectionHeadersAll(elfFile, shTable);
531 if (ret) return ret;
532 entries = shTable.size();
533
Connor O'Brien3278a162020-02-13 21:45:22 -0800534 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800535 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800536 if (ret) return ret;
537 vector<string> progDefNames;
538 ret = getSectionSymNames(elfFile, "progs", progDefNames);
539 if (!pd.empty() && ret) return ret;
540
Joel Fernandesd76a2002018-10-16 13:19:58 -0700541 for (int i = 0; i < entries; i++) {
542 string name;
543 codeSection cs_temp;
544 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
545
546 ret = getSymName(elfFile, shTable[i].sh_name, name);
547 if (ret) return ret;
548
549 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800550
Tyler Wear4e2f4602022-02-03 09:46:01 -0800551 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800552
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800553 if (!IsAllowed(ptype, allowed, numAllowed)) {
554 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
555 return -1;
556 }
557
Tyler Wear4e2f4602022-02-03 09:46:01 -0800558 // This must be done before '/' is replaced with '_'.
559 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800560
Tyler Wear4e2f4602022-02-03 09:46:01 -0800561 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700562
Tyler Wear4e2f4602022-02-03 09:46:01 -0800563 // convert all slashes to underscores
564 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800565
Tyler Wear4e2f4602022-02-03 09:46:01 -0800566 cs_temp.type = ptype;
567 cs_temp.name = name;
568
569 ret = readSectionByIdx(elfFile, i, cs_temp.data);
570 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700571 ALOGD("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800572
573 vector<string> csSymNames;
574 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
575 if (ret || !csSymNames.size()) return ret;
576 for (size_t i = 0; i < progDefNames.size(); ++i) {
577 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
578 cs_temp.prog_def = pd[i];
579 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800580 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700581 }
582
583 /* Check for rel section */
584 if (cs_temp.data.size() > 0 && i < entries) {
585 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
586 if (ret) return ret;
587
Tyler Wear4e2f4602022-02-03 09:46:01 -0800588 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700589 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
590 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700591 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700592 }
593 }
594
595 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700596 cs.push_back(std::move(cs_temp));
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700597 ALOGD("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700598 }
599 }
600 return 0;
601}
602
603static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
604 vector<Elf64_Sym> symtab;
605 int ret = 0;
606
607 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
608 if (ret) return ret;
609
610 if (index >= (int)symtab.size()) return -1;
611
612 return getSymName(elfFile, symtab[index].st_name, name);
613}
614
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700615static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
616 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700617 // Assuming fd is a valid Bpf Map file descriptor then
618 // all the following should always succeed on a 4.14+ kernel.
619 // If they somehow do fail, they'll return -1 (and set errno),
620 // which should then cause (among others) a key_size mismatch.
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700621 int fd_type = bpfGetFdMapType(fd);
622 int fd_key_size = bpfGetFdKeySize(fd);
623 int fd_value_size = bpfGetFdValueSize(fd);
624 int fd_max_entries = bpfGetFdMaxEntries(fd);
625 int fd_map_flags = bpfGetFdMapFlags(fd);
626
627 // DEVMAPs are readonly from the bpf program side's point of view, as such
628 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
629 int desired_map_flags = (int)mapDef.map_flags;
630 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
631 desired_map_flags |= BPF_F_RDONLY_PROG;
632
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000633 // The .h file enforces that this is a power of two, and page size will
634 // also always be a power of two, so this logic is actually enough to
635 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000636 unsigned int desired_max_entries = mapDef.max_entries;
637 if (type == BPF_MAP_TYPE_RINGBUF) {
638 if (desired_max_entries < page_size) desired_max_entries = page_size;
639 }
640
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700641 // The following checks should *never* trigger, if one of them somehow does,
642 // it probably means a bpf .o file has been changed/replaced at runtime
643 // and bpfloader was manually rerun (normally it should only run *once*
644 // early during the boot process).
645 // Another possibility is that something is misconfigured in the code:
646 // most likely a shared map is declared twice differently.
647 // But such a change should never be checked into the source tree...
648 if ((fd_type == type) &&
649 (fd_key_size == (int)mapDef.key_size) &&
650 (fd_value_size == (int)mapDef.value_size) &&
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000651 (fd_max_entries == (int)desired_max_entries) &&
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700652 (fd_map_flags == desired_map_flags)) {
653 return true;
654 }
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700655
656 ALOGE("bpf map name %s mismatch: desired/found: "
657 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
658 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
659 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
660 return false;
661}
662
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800663static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700664 const char* prefix, const unsigned long long allowedDomainBitmask,
665 const size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700666 int ret;
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700667 vector<char> mdData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700668 vector<struct bpf_map_def> md;
669 vector<string> mapNames;
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700670 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700671
672 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800673 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700674 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800675
676 if (mdData.size() % sizeOfBpfMapDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700677 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800678 mdData.size(), sizeOfBpfMapDef);
679 return -1;
680 };
681
682 int mapCount = mdData.size() / sizeOfBpfMapDef;
683 md.resize(mapCount);
684 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
685
686 const char* dataPtr = mdData.data();
687 for (auto& m : md) {
688 // First we zero initialize
689 memset(&m, 0, sizeof(m));
690 // Then we set non-zero defaults
691 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700692 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800693 // Then we copy over the structure prefix from the ELF file.
694 memcpy(&m, dataPtr, trimmedSize);
695 // Move to next struct in the ELF file
696 dataPtr += sizeOfBpfMapDef;
697 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700698
Connor O'Brien3278a162020-02-13 21:45:22 -0800699 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700700 if (ret) return ret;
701
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700702 unsigned kvers = kernelVersion();
703
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700704 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +0000705 if (md[i].zero != 0) abort();
706
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800707 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700708 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800709 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700710 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800711 continue;
712 }
713
714 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700715 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800716 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700717 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800718 continue;
719 }
720
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700721 if (kvers < md[i].min_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700722 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700723 mapNames[i].c_str(), kvers, md[i].min_kver);
724 mapFds.push_back(unique_fd());
725 continue;
726 }
727
728 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700729 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700730 mapNames[i].c_str(), kvers, md[i].max_kver);
731 mapFds.push_back(unique_fd());
732 continue;
733 }
734
Ryan Zukliece89f502022-12-15 16:14:32 -0800735 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
736 (md[i].ignore_on_userdebug && isUserdebug())) {
737 ALOGI("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
738 getBuildType().c_str());
739 mapFds.push_back(unique_fd());
740 continue;
741 }
742
Maciej Żenczykowski8d2e7d92023-05-19 21:06:00 +0000743 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
744 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
745 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
746 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
747 (isRiscV() && md[i].ignore_on_riscv64)) {
748 ALOGI("skipping map %s which is ignored on %s", mapNames[i].c_str(),
749 describeArch());
750 mapFds.push_back(unique_fd());
751 continue;
752 }
753
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700754 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700755 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
756 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
757 // of be approximated: HASH has the same userspace visible api.
758 // However it cannot be used by ebpf programs in the same way.
759 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
760 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
761 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
762 // programs as being 5.4+...
763 type = BPF_MAP_TYPE_HASH;
764 }
765
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000766 // The .h file enforces that this is a power of two, and page size will
767 // also always be a power of two, so this logic is actually enough to
768 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000769 unsigned int max_entries = md[i].max_entries;
770 if (type == BPF_MAP_TYPE_RINGBUF) {
771 if (max_entries < page_size) max_entries = page_size;
772 }
773
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700774 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
775 if (specified(selinux_context)) {
776 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
777 ALOGE("map %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
778 mapNames[i].c_str(), selinux_context, allowedDomainBitmask);
779 return -EINVAL;
780 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700781 ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700782 md[i].selinux_context, selinux_context, lookupSelinuxContext(selinux_context),
783 lookupPinSubdir(selinux_context));
784 }
785
786 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
787 if (unrecognized(pin_subdir)) return -ENOTDIR;
788 if (specified(pin_subdir)) {
789 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
790 ALOGE("map %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)",
791 mapNames[i].c_str(), pin_subdir, allowedDomainBitmask);
792 return -EINVAL;
793 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700794 ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700795 pin_subdir, lookupPinSubdir(pin_subdir));
796 }
797
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700798 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
799 // except that maps shared across .o's have empty <objName>
800 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700801 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700802 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700803 bool reuse = false;
804 unique_fd fd;
805 int saved_errno;
806
Joel Fernandesd76a2002018-10-16 13:19:58 -0700807 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskieb199dd2022-07-01 03:21:40 -0700808 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800809 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700810 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700811 reuse = true;
812 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700813 union bpf_attr req = {
814 .map_type = type,
815 .key_size = md[i].key_size,
816 .value_size = md[i].value_size,
817 .max_entries = max_entries,
818 .map_flags = md[i].map_flags,
Connor O'Brien35425e52022-01-18 21:41:16 -0800819 };
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700820 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
821 fd.reset(bpf(BPF_MAP_CREATE, req));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800822 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700823 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700824 }
825
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700826 if (!fd.ok()) return -saved_errno;
827
828 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
829 // safety (since reuse code path is rare) run these checks even if we just created it.
830 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
831 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700832
833 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700834 if (specified(selinux_context)) {
835 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700836 "tmp_map_" + objName + "_" + mapNames[i];
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700837 ret = bpfFdPin(fd, createLoc.c_str());
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700838 if (ret) {
839 int err = errno;
840 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
841 return -err;
842 }
Maciej Żenczykowskie15229f2023-04-17 07:16:33 +0000843 ret = renameat2(AT_FDCWD, createLoc.c_str(),
844 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700845 if (ret) {
846 int err = errno;
847 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
848 err, strerror(err));
849 return -err;
850 }
851 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700852 ret = bpfFdPin(fd, mapPinLoc.c_str());
Maciej Żenczykowskid8259aa2022-06-27 10:02:20 -0700853 if (ret) {
854 int err = errno;
855 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
856 return -err;
857 }
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700858 }
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800859 ret = chmod(mapPinLoc.c_str(), md[i].mode);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700860 if (ret) {
861 int err = errno;
862 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
863 strerror(err));
864 return -err;
865 }
Maciej Żenczykowski5e4aabf2022-06-27 01:15:53 -0700866 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
867 if (ret) {
868 int err = errno;
869 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
870 ret, err, strerror(err));
871 return -err;
872 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700873 }
874
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700875 int mapId = bpfGetFdMapId(fd);
876 if (mapId == -1) {
877 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700878 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700879 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700880 }
881
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700882 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700883 }
884
885 return ret;
886}
887
888/* For debugging, dump all instructions */
889static void dumpIns(char* ins, int size) {
890 for (int row = 0; row < size / 8; row++) {
891 ALOGE("%d: ", row);
892 for (int j = 0; j < 8; j++) {
893 ALOGE("%3x ", ins[(row * 8) + j]);
894 }
895 ALOGE("\n");
896 }
897}
898
899/* For debugging, dump all code sections from cs list */
900static void dumpAllCs(vector<codeSection>& cs) {
901 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700902 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700903 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700904 ALOGE("-----------");
Joel Fernandesd76a2002018-10-16 13:19:58 -0700905 }
906}
907
908static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
909 int insnIndex;
910 struct bpf_insn *insn, *insns;
911
912 insns = (struct bpf_insn*)(insnsPtr);
913
914 insnIndex = offset / sizeof(struct bpf_insn);
915 insn = &insns[insnIndex];
916
Maciej Żenczykowski509b1b92023-03-07 01:11:20 +0000917 // Occasionally might be useful for relocation debugging, but pretty spammy
918 if (0) {
919 ALOGD("applying relo to instruction at byte offset: %llu, "
920 "insn offset %d, insn %llx",
921 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
922 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700923
924 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700925 ALOGE("Dumping all instructions till ins %d", insnIndex);
926 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700927 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
928 return;
929 }
930
931 insn->imm = fd;
932 insn->src_reg = BPF_PSEUDO_MAP_FD;
933}
934
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700935static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700936 vector<string> mapNames;
937
Connor O'Brien3278a162020-02-13 21:45:22 -0800938 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700939 if (ret) return;
940
941 for (int k = 0; k != (int)cs.size(); k++) {
942 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
943 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
944
945 for (int i = 0; i < n_rel; i++) {
946 int symIndex = ELF64_R_SYM(rel[i].r_info);
947 string symName;
948
949 ret = getSymNameByIdx(elfFile, symIndex, symName);
950 if (ret) return;
951
952 /* Find the map fd and apply relo */
953 for (int j = 0; j < (int)mapNames.size(); j++) {
954 if (!mapNames[j].compare(symName)) {
955 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
956 break;
957 }
958 }
959 }
960 }
961}
962
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800963static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700964 const char* prefix, const unsigned long long allowedDomainBitmask) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800965 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700966
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000967 if (!kvers) {
968 ALOGE("unable to get kernel version");
969 return -EINVAL;
970 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700971
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700972 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700973
974 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700975 unique_fd& fd = cs[i].prog_fd;
976 int ret;
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700977 string name = cs[i].name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700978
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000979 if (!cs[i].prog_def.has_value()) {
980 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
981 return -EINVAL;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800982 }
983
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000984 unsigned min_kver = cs[i].prog_def->min_kver;
985 unsigned max_kver = cs[i].prog_def->max_kver;
986 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
987 max_kver, kvers);
988 if (kvers < min_kver) continue;
989 if (kvers >= max_kver) continue;
990
991 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
992 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
993 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
994 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
995 // Note: make sure to only check for unrecognized *after* verifying bpfloader
996 // version limits include this bpfloader's version.
997
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700998 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800999 bpfMinVer, bpfMaxVer);
1000 if (BPFLOADER_VERSION < bpfMinVer) continue;
1001 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
Ryan Zukliece89f502022-12-15 16:14:32 -08001002
1003 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1004 (cs[i].prog_def->ignore_on_user && isUser()) ||
1005 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1006 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1007 getBuildType().c_str());
Ryan Zuklie0fb433a2023-01-05 14:22:15 -08001008 continue;
Ryan Zukliece89f502022-12-15 16:14:32 -08001009 }
1010
Maciej Żenczykowski8d2e7d92023-05-19 21:06:00 +00001011 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
1012 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
1013 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
1014 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
1015 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
1016 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
1017 continue;
1018 }
1019
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001020 if (unrecognized(pin_subdir)) return -ENOTDIR;
1021
1022 if (specified(selinux_context)) {
1023 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
1024 ALOGE("prog %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
1025 name.c_str(), selinux_context, allowedDomainBitmask);
1026 return -EINVAL;
1027 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001028 ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001029 cs[i].prog_def->selinux_context, selinux_context,
1030 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1031 }
1032
1033 if (specified(pin_subdir)) {
1034 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
1035 ALOGE("prog %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)", name.c_str(),
1036 pin_subdir, allowedDomainBitmask);
1037 return -EINVAL;
1038 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001039 ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001040 cs[i].prog_def->pin_subdir, pin_subdir, lookupPinSubdir(pin_subdir));
1041 }
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001042
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001043 // strip any potential $foo suffix
1044 // this can be used to provide duplicate programs
1045 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -07001046 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001047
1048 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001049 // Format of pin location is
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001050 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001051 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001052 objName + '_' + string(name);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001053 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001054 fd.reset(retrieveProgram(progPinLoc.c_str()));
1055 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
1056 (!fd.ok() ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001057 reuse = true;
1058 } else {
1059 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1060
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001061 union bpf_attr req = {
1062 .prog_type = cs[i].type,
1063 .kern_version = kvers,
1064 .license = ptr_to_u64(license.c_str()),
1065 .insns = ptr_to_u64(cs[i].data.data()),
1066 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
1067 .log_level = 1,
1068 .log_buf = ptr_to_u64(log_buf.data()),
1069 .log_size = static_cast<__u32>(log_buf.size()),
1070 .expected_attach_type = cs[i].expected_attach_type,
Tyler Wear4e2f4602022-02-03 09:46:01 -08001071 };
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001072 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
1073 fd.reset(bpf(BPF_PROG_LOAD, req));
Tyler Wear4e2f4602022-02-03 09:46:01 -08001074
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001075 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
1076 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
Tyler Wear4e2f4602022-02-03 09:46:01 -08001077
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001078 if (!fd.ok()) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -08001079 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001080
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001081 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001082 for (const auto& line : lines) ALOGW("%s", line.c_str());
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001083 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001084
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001085 if (cs[i].prog_def->optional) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001086 ALOGW("failed program is marked optional - continuing...");
1087 continue;
1088 }
1089 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001090 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001091 }
1092
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001093 if (!fd.ok()) return fd.get();
Joel Fernandesd76a2002018-10-16 13:19:58 -07001094
1095 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001096 if (specified(selinux_context)) {
1097 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001098 "tmp_prog_" + objName + '_' + string(name);
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001099 ret = bpfFdPin(fd, createLoc.c_str());
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001100 if (ret) {
1101 int err = errno;
1102 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1103 return -err;
1104 }
Maciej Żenczykowskie15229f2023-04-17 07:16:33 +00001105 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1106 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001107 if (ret) {
1108 int err = errno;
1109 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1110 err, strerror(err));
1111 return -err;
1112 }
1113 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001114 ret = bpfFdPin(fd, progPinLoc.c_str());
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001115 if (ret) {
1116 int err = errno;
1117 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1118 return -err;
1119 }
1120 }
1121 if (chmod(progPinLoc.c_str(), 0440)) {
1122 int err = errno;
1123 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1124 return -err;
1125 }
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001126 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1127 (gid_t)cs[i].prog_def->gid)) {
1128 int err = errno;
1129 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1130 cs[i].prog_def->gid, err, strerror(err));
1131 return -err;
Connor O'Brien3278a162020-02-13 21:45:22 -08001132 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001133 }
1134
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001135 int progId = bpfGetFdProgId(fd);
1136 if (progId == -1) {
1137 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001138 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001139 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001140 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001141 }
1142
1143 return 0;
1144}
1145
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001146int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
Joel Fernandesd76a2002018-10-16 13:19:58 -07001147 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001148 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001149 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001150 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001151 int ret;
1152
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001153 if (!isCritical) return -1;
1154 *isCritical = false;
1155
Joel Fernandesd76a2002018-10-16 13:19:58 -07001156 ifstream elfFile(elfPath, ios::in | ios::binary);
1157 if (!elfFile.is_open()) return -1;
1158
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001159 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001160 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001161
Joel Fernandesd76a2002018-10-16 13:19:58 -07001162 ret = readSectionByName("license", elfFile, license);
1163 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001164 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001165 return ret;
1166 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001167 ALOGD("Loading %s%s ELF object %s with license %s",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001168 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001169 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -07001170 }
1171
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001172 // the following default values are for bpfloader V0.0 format which does not include them
1173 unsigned int bpfLoaderMinVer =
1174 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1175 unsigned int bpfLoaderMaxVer =
1176 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001177 unsigned int bpfLoaderMinRequiredVer =
1178 readSectionUint("bpfloader_min_required_ver", elfFile, 0);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001179 size_t sizeOfBpfMapDef =
1180 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1181 size_t sizeOfBpfProgDef =
1182 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1183
1184 // inclusive lower bound check
1185 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001186 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001187 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
1188 return 0;
1189 }
1190
1191 // exclusive upper bound check
1192 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001193 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001194 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
1195 return 0;
1196 }
1197
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001198 if (BPFLOADER_VERSION < bpfLoaderMinRequiredVer) {
1199 ALOGI("BpfLoader version 0x%05x failing due to ELF object %s with required min ver 0x%05x",
1200 BPFLOADER_VERSION, elfPath, bpfLoaderMinRequiredVer);
1201 return -1;
1202 }
1203
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001204 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001205 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1206
1207 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001208 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001209 DEFAULT_SIZEOF_BPF_MAP_DEF);
1210 return -1;
1211 }
1212
1213 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001214 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001215 DEFAULT_SIZEOF_BPF_PROG_DEF);
1216 return -1;
1217 }
1218
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001219 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, location.allowedProgTypes,
1220 location.allowedProgTypesLength);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001221 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001222 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001223 return ret;
1224 }
1225
1226 /* Just for future debugging */
1227 if (0) dumpAllCs(cs);
1228
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001229 ret = createMaps(elfPath, elfFile, mapFds, location.prefix, location.allowedDomainBitmask,
1230 sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001231 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001232 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001233 return ret;
1234 }
1235
1236 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001237 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001238
1239 applyMapRelo(elfFile, mapFds, cs);
1240
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001241 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix,
1242 location.allowedDomainBitmask);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001243 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001244
1245 return ret;
1246}
1247
Joel Fernandesd76a2002018-10-16 13:19:58 -07001248} // namespace bpf
1249} // namespace android