blob: 2a2c3b0b632c81842744b1849cfd7f946e6d78f1 [file] [log] [blame]
Joel Fernandesd76a2002018-10-16 13:19:58 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "LibBpfLoader"
18
19#include <errno.h>
20#include <linux/bpf.h>
21#include <linux/elf.h>
22#include <log/log.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080027#include <sysexits.h>
Maciej Żenczykowski83f29772020-01-27 03:11:51 -080028#include <sys/stat.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070029#include <sys/utsname.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080030#include <sys/wait.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070031#include <unistd.h>
32
Maciej Żenczykowskic3c4f482023-03-29 03:25:19 +000033// This is BpfLoader v0.36
Maciej Żenczykowski05825662023-01-20 13:00:24 +000034// WARNING: If you ever hit cherrypick conflicts here you're doing it wrong:
35// You are NOT allowed to cherrypick bpfloader related patches out of order.
36// (indeed: cherrypicking is probably a bad idea and you should merge instead)
37// Mainline supports ONLY the published versions of the bpfloader for each Android release.
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080038#define BPFLOADER_VERSION_MAJOR 0u
Maciej Żenczykowskic3c4f482023-03-29 03:25:19 +000039#define BPFLOADER_VERSION_MINOR 36u
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080040#define BPFLOADER_VERSION ((BPFLOADER_VERSION_MAJOR << 16) | BPFLOADER_VERSION_MINOR)
41
Maciej Żenczykowski300c51f2022-12-14 04:18:02 -080042#include "BpfSyscallWrappers.h"
Maciej Żenczykowski07375e22020-02-19 14:23:59 -080043#include "bpf/BpfUtils.h"
Ken Chend5689472021-12-20 18:07:21 +080044#include "bpf/bpf_map_def.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070045#include "include/libbpf_android.h"
46
Maciej Żenczykowskib3dcc142022-07-24 22:42:33 +000047#if BPFLOADER_VERSION < COMPILE_FOR_BPFLOADER_VERSION
48#error "BPFLOADER_VERSION is less than COMPILE_FOR_BPFLOADER_VERSION"
49#endif
50
Connor O'Brien35425e52022-01-18 21:41:16 -080051#include <bpf/bpf.h>
52
Joel Fernandesd76a2002018-10-16 13:19:58 -070053#include <cstdlib>
54#include <fstream>
55#include <iostream>
Connor O'Brien3278a162020-02-13 21:45:22 -080056#include <optional>
Joel Fernandesd76a2002018-10-16 13:19:58 -070057#include <string>
Connor O'Brien35425e52022-01-18 21:41:16 -080058#include <unordered_map>
Christopher Ferrisc151c672019-02-01 15:31:26 -080059#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070060
Connor O'Brien35425e52022-01-18 21:41:16 -080061#include <android-base/cmsg.h>
62#include <android-base/file.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>
Ryan Zukliece89f502022-12-15 16:14:32 -080065#include <cutils/properties.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070066
67#define BPF_FS_PATH "/sys/fs/bpf/"
68
69// Size of the BPF log buffer for verifier logging
Stephane Leeeb61b732021-10-21 17:03:11 -070070#define BPF_LOAD_LOG_SZ 0xfffff
Joel Fernandesd76a2002018-10-16 13:19:58 -070071
Tyler Wear4e2f4602022-02-03 09:46:01 -080072// Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
73#define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
74
Joel Fernandesd76a2002018-10-16 13:19:58 -070075using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070076using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070077using std::ifstream;
78using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080079using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080080using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070081using std::vector;
82
Ryan Zukliece89f502022-12-15 16:14:32 -080083static std::string getBuildTypeInternal() {
84 char value[PROPERTY_VALUE_MAX] = {};
85 (void)property_get("ro.build.type", value, "unknown"); // ignore length
86 return value;
87}
88
Joel Fernandesd76a2002018-10-16 13:19:58 -070089namespace android {
90namespace bpf {
91
Ryan Zukliece89f502022-12-15 16:14:32 -080092const std::string& getBuildType() {
93 static std::string t = getBuildTypeInternal();
94 return t;
95}
96
Maciej Żenczykowski41817132022-06-03 08:41:04 -070097constexpr const char* lookupSelinuxContext(const domain d, const char* const unspecified = "") {
98 switch (d) {
99 case domain::unspecified: return unspecified;
100 case domain::platform: return "fs_bpf";
101 case domain::tethering: return "fs_bpf_tethering";
102 case domain::net_private: return "fs_bpf_net_private";
103 case domain::net_shared: return "fs_bpf_net_shared";
104 case domain::netd_readonly: return "fs_bpf_netd_readonly";
105 case domain::netd_shared: return "fs_bpf_netd_shared";
106 case domain::vendor: return "fs_bpf_vendor";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +0000107 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700108 default: return "(unrecognized)";
109 }
110}
111
112domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
113 for (domain d : AllDomains) {
114 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
115 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
116 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
117 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700118 ALOGW("ignoring unrecognized selinux_context '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700119 // We should return 'unrecognized' here, however: returning unspecified will
120 // result in the system simply using the default context, which in turn
121 // will allow future expansion by adding more restrictive selinux types.
122 // Older bpfloader will simply ignore that, and use the less restrictive default.
123 // This does mean you CANNOT later add a *less* restrictive type than the default.
124 //
125 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
126 return domain::unspecified;
127}
128
129constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
130 switch (d) {
131 case domain::unspecified: return unspecified;
132 case domain::platform: return "/";
133 case domain::tethering: return "tethering/";
134 case domain::net_private: return "net_private/";
135 case domain::net_shared: return "net_shared/";
136 case domain::netd_readonly: return "netd_readonly/";
137 case domain::netd_shared: return "netd_shared/";
138 case domain::vendor: return "vendor/";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +0000139 case domain::loader: return "loader/";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700140 default: return "(unrecognized)";
141 }
142};
143
144domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
145 for (domain d : AllDomains) {
146 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
147 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
148 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
149 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700150 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700151 // pin_subdir affects the object's full pathname,
152 // and thus using the default would change the location and thus our code's ability to find it,
153 // hence this seems worth treating as a true error condition.
154 //
155 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
156 // However, our callers will treat this as an error, and stop loading the specific .o,
157 // which will fail bpfloader if the .o is marked critical.
158 return domain::unrecognized;
159}
160
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700161static string pathToObjName(const string& path) {
162 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
163 string filename = android::base::Split(path, "/").back();
164 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
165 string name = filename.substr(0, filename.find_last_of('.'));
166 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
167 // this can be used to provide duplicate programs (mux based on the bpfloader version)
168 return name.substr(0, name.find_last_of('@'));
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800169}
170
Joel Fernandesd76a2002018-10-16 13:19:58 -0700171typedef struct {
172 const char* name;
173 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800174 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700175} sectionType;
176
177/*
178 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700179 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -0700180 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700181 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -0700182 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700183 *
184 * However, be aware that you should not be directly using the SECTION() macro.
185 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -0700186 */
187sectionType sectionNameTypes[] = {
Maciej Żenczykowskic3c4f482023-03-29 03:25:19 +0000188 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
189 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
190 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB, BPF_ATTACH_TYPE_UNSPEC},
191 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_ATTACH_TYPE_UNSPEC},
192 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
193 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
194 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
195 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
196 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
197 {"kprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
198 {"kretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
199 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT, BPF_ATTACH_TYPE_UNSPEC},
200 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
201 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
202 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
203 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
204 {"schedact/", BPF_PROG_TYPE_SCHED_ACT, BPF_ATTACH_TYPE_UNSPEC},
205 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS, BPF_ATTACH_TYPE_UNSPEC},
206 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
207 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
208 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
209 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
210 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
211 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
212 {"uprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
213 {"uretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
214 {"xdp/", BPF_PROG_TYPE_XDP, BPF_ATTACH_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700215};
216
217typedef struct {
218 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800219 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700220 string name;
221 vector<char> data;
222 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800223 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700224
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700225 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700226} codeSection;
227
Joel Fernandesd76a2002018-10-16 13:19:58 -0700228static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
229 elfFile.seekg(0);
230 if (elfFile.fail()) return -1;
231
232 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
233
234 return 0;
235}
236
237/* Reads all section header tables into an Shdr array */
238static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
239 Elf64_Ehdr eh;
240 int ret = 0;
241
242 ret = readElfHeader(elfFile, &eh);
243 if (ret) return ret;
244
245 elfFile.seekg(eh.e_shoff);
246 if (elfFile.fail()) return -1;
247
248 /* Read shdr table entries */
249 shTable.resize(eh.e_shnum);
250
251 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
252
253 return 0;
254}
255
256/* Read a section by its index - for ex to get sec hdr strtab blob */
257static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
258 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800259 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700260 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700261
262 elfFile.seekg(shTable[id].sh_offset);
263 if (elfFile.fail()) return -1;
264
265 sec.resize(shTable[id].sh_size);
266 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
267
268 return 0;
269}
270
271/* Read whole section header string table */
272static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
273 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800274 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700275 if (ret) return ret;
276
277 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
278 if (ret) return ret;
279
280 return 0;
281}
282
283/* Get name from offset in strtab */
284static int getSymName(ifstream& elfFile, int nameOff, string& name) {
285 int ret;
286 vector<char> secStrTab;
287
288 ret = readSectionHeaderStrtab(elfFile, secStrTab);
289 if (ret) return ret;
290
291 if (nameOff >= (int)secStrTab.size()) return -1;
292
293 name = string((char*)secStrTab.data() + nameOff);
294 return 0;
295}
296
297/* Reads a full section by name - example to get the GPL license */
298static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
299 vector<char> secStrTab;
300 vector<Elf64_Shdr> shTable;
301 int ret;
302
303 ret = readSectionHeadersAll(elfFile, shTable);
304 if (ret) return ret;
305
306 ret = readSectionHeaderStrtab(elfFile, secStrTab);
307 if (ret) return ret;
308
309 for (int i = 0; i < (int)shTable.size(); i++) {
310 char* secname = secStrTab.data() + shTable[i].sh_name;
311 if (!secname) continue;
312
313 if (!strcmp(secname, name)) {
314 vector<char> dataTmp;
315 dataTmp.resize(shTable[i].sh_size);
316
317 elfFile.seekg(shTable[i].sh_offset);
318 if (elfFile.fail()) return -1;
319
320 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
321
322 data = dataTmp;
323 return 0;
324 }
325 }
326 return -2;
327}
328
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700329unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800330 vector<char> theBytes;
331 int ret = readSectionByName(name, elfFile, theBytes);
332 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700333 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800334 return defVal;
335 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700336 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800337 return defVal;
338 } else {
339 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
340 unsigned int value = static_cast<unsigned char>(theBytes[3]);
341 value <<= 8;
342 value += static_cast<unsigned char>(theBytes[2]);
343 value <<= 8;
344 value += static_cast<unsigned char>(theBytes[1]);
345 value <<= 8;
346 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700347 ALOGI("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800348 return value;
349 }
350}
351
Joel Fernandesd76a2002018-10-16 13:19:58 -0700352static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
353 int ret;
354 vector<Elf64_Shdr> shTable;
355
356 ret = readSectionHeadersAll(elfFile, shTable);
357 if (ret) return ret;
358
359 for (int i = 0; i < (int)shTable.size(); i++) {
360 if ((int)shTable[i].sh_type != type) continue;
361
362 vector<char> dataTmp;
363 dataTmp.resize(shTable[i].sh_size);
364
365 elfFile.seekg(shTable[i].sh_offset);
366 if (elfFile.fail()) return -1;
367
368 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
369
370 data = dataTmp;
371 return 0;
372 }
373 return -2;
374}
375
376static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
377 return (a.st_value < b.st_value);
378}
379
380static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
381 int ret, numElems;
382 Elf64_Sym* buf;
383 vector<char> secData;
384
385 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
386 if (ret) return ret;
387
388 buf = (Elf64_Sym*)secData.data();
389 numElems = (secData.size() / sizeof(Elf64_Sym));
390 data.assign(buf, buf + numElems);
391
392 if (sort) std::sort(data.begin(), data.end(), symCompare);
393 return 0;
394}
395
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700396static enum bpf_prog_type getFuseProgType() {
397 int result = BPF_PROG_TYPE_UNSPEC;
398 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
399 return static_cast<bpf_prog_type>(result);
400}
401
Joel Fernandesd76a2002018-10-16 13:19:58 -0700402static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800403 for (auto& snt : sectionNameTypes)
404 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700405
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000406 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700407 if (StartsWith(name, "fuse/")) return getFuseProgType();
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000408
Joel Fernandesd76a2002018-10-16 13:19:58 -0700409 return BPF_PROG_TYPE_UNSPEC;
410}
411
Tyler Wear4e2f4602022-02-03 09:46:01 -0800412static enum bpf_attach_type getExpectedAttachType(string& name) {
413 for (auto& snt : sectionNameTypes)
414 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
415 return BPF_ATTACH_TYPE_UNSPEC;
416}
417
Joel Fernandesd76a2002018-10-16 13:19:58 -0700418static string getSectionName(enum bpf_prog_type type)
419{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800420 for (auto& snt : sectionNameTypes)
421 if (snt.type == type)
422 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700423
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800424 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700425}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700426
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800427static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
428 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800429 vector<char> pdData;
430 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800431 // Older file formats do not require a 'progs' section at all.
432 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800433 if (ret == -2) return 0;
434 if (ret) return ret;
435
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800436 if (pdData.size() % sizeOfBpfProgDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700437 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800438 pdData.size(), sizeOfBpfProgDef);
439 return -1;
440 };
441
442 int progCount = pdData.size() / sizeOfBpfProgDef;
443 pd.resize(progCount);
444 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
445
446 const char* dataPtr = pdData.data();
447 for (auto& p : pd) {
448 // First we zero initialize
449 memset(&p, 0, sizeof(p));
450 // Then we set non-zero defaults
451 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
452 // Then we copy over the structure prefix from the ELF file.
453 memcpy(&p, dataPtr, trimmedSize);
454 // Move to next struct in the ELF file
455 dataPtr += sizeOfBpfProgDef;
456 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800457 return 0;
458}
459
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800460static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
461 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800462 int ret;
463 string name;
464 vector<Elf64_Sym> symtab;
465 vector<Elf64_Shdr> shTable;
466
467 ret = readSymTab(elfFile, 1 /* sort */, symtab);
468 if (ret) return ret;
469
470 /* Get index of section */
471 ret = readSectionHeadersAll(elfFile, shTable);
472 if (ret) return ret;
473
474 int sec_idx = -1;
475 for (int i = 0; i < (int)shTable.size(); i++) {
476 ret = getSymName(elfFile, shTable[i].sh_name, name);
477 if (ret) return ret;
478
479 if (!name.compare(sectionName)) {
480 sec_idx = i;
481 break;
482 }
483 }
484
485 /* No section found with matching name*/
486 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700487 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800488 return -1;
489 }
490
491 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800492 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
493
Connor O'Brien3278a162020-02-13 21:45:22 -0800494 if (symtab[i].st_shndx == sec_idx) {
495 string s;
496 ret = getSymName(elfFile, symtab[i].st_name, s);
497 if (ret) return ret;
498 names.push_back(s);
499 }
500 }
501
502 return 0;
503}
504
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800505static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
506 if (allowed == nullptr) return true;
507
508 for (size_t i = 0; i < numAllowed; i++) {
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700509 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
510 if (type == getFuseProgType()) return true;
511 } else if (type == allowed[i])
512 return true;
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800513 }
514
515 return false;
516}
517
Joel Fernandesd76a2002018-10-16 13:19:58 -0700518/* Read a section by its index - for ex to get sec hdr strtab blob */
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800519static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef,
520 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700521 vector<Elf64_Shdr> shTable;
522 int entries, ret = 0;
523
524 ret = readSectionHeadersAll(elfFile, shTable);
525 if (ret) return ret;
526 entries = shTable.size();
527
Connor O'Brien3278a162020-02-13 21:45:22 -0800528 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800529 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800530 if (ret) return ret;
531 vector<string> progDefNames;
532 ret = getSectionSymNames(elfFile, "progs", progDefNames);
533 if (!pd.empty() && ret) return ret;
534
Joel Fernandesd76a2002018-10-16 13:19:58 -0700535 for (int i = 0; i < entries; i++) {
536 string name;
537 codeSection cs_temp;
538 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
539
540 ret = getSymName(elfFile, shTable[i].sh_name, name);
541 if (ret) return ret;
542
543 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800544
Tyler Wear4e2f4602022-02-03 09:46:01 -0800545 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800546
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800547 if (!IsAllowed(ptype, allowed, numAllowed)) {
548 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
549 return -1;
550 }
551
Tyler Wear4e2f4602022-02-03 09:46:01 -0800552 // This must be done before '/' is replaced with '_'.
553 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800554
Tyler Wear4e2f4602022-02-03 09:46:01 -0800555 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700556
Tyler Wear4e2f4602022-02-03 09:46:01 -0800557 // convert all slashes to underscores
558 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800559
Tyler Wear4e2f4602022-02-03 09:46:01 -0800560 cs_temp.type = ptype;
561 cs_temp.name = name;
562
563 ret = readSectionByIdx(elfFile, i, cs_temp.data);
564 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700565 ALOGD("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800566
567 vector<string> csSymNames;
568 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
569 if (ret || !csSymNames.size()) return ret;
570 for (size_t i = 0; i < progDefNames.size(); ++i) {
571 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
572 cs_temp.prog_def = pd[i];
573 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800574 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700575 }
576
577 /* Check for rel section */
578 if (cs_temp.data.size() > 0 && i < entries) {
579 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
580 if (ret) return ret;
581
Tyler Wear4e2f4602022-02-03 09:46:01 -0800582 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700583 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
584 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700585 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700586 }
587 }
588
589 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700590 cs.push_back(std::move(cs_temp));
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700591 ALOGD("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700592 }
593 }
594 return 0;
595}
596
597static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
598 vector<Elf64_Sym> symtab;
599 int ret = 0;
600
601 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
602 if (ret) return ret;
603
604 if (index >= (int)symtab.size()) return -1;
605
606 return getSymName(elfFile, symtab[index].st_name, name);
607}
608
Connor O'Brien35425e52022-01-18 21:41:16 -0800609static bool waitpidTimeout(pid_t pid, int timeoutMs) {
610 // Add SIGCHLD to the signal set.
611 sigset_t child_mask, original_mask;
612 sigemptyset(&child_mask);
613 sigaddset(&child_mask, SIGCHLD);
614 if (sigprocmask(SIG_BLOCK, &child_mask, &original_mask) == -1) return false;
615
616 // Wait for a SIGCHLD notification.
617 errno = 0;
618 timespec ts = {0, timeoutMs * 1000000};
619 int wait_result = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, nullptr, &ts));
620
621 // Restore the original signal set.
622 sigprocmask(SIG_SETMASK, &original_mask, nullptr);
623
624 if (wait_result == -1) return false;
625
626 int status;
627 return TEMP_FAILURE_RETRY(waitpid(pid, &status, WNOHANG)) == pid;
628}
629
630static std::optional<unique_fd> getMapBtfInfo(const char* elfPath,
631 std::unordered_map<string, std::pair<uint32_t, uint32_t>> &btfTypeIds) {
632 unique_fd bpfloaderSocket, btfloaderSocket;
633 if (!android::base::Socketpair(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0, &bpfloaderSocket,
634 &btfloaderSocket)) {
635 return {};
636 }
637
638 unique_fd pipeRead, pipeWrite;
639 if (!android::base::Pipe(&pipeRead, &pipeWrite, O_NONBLOCK)) {
640 return {};
641 }
642
643 pid_t pid = fork();
644 if (pid < 0) return {};
645 if (!pid) {
646 bpfloaderSocket.reset();
647 pipeRead.reset();
648 auto socketFdStr = std::to_string(btfloaderSocket.release());
649 auto pipeFdStr = std::to_string(pipeWrite.release());
650
651 if (execl("/system/bin/btfloader", "/system/bin/btfloader", socketFdStr.c_str(),
652 pipeFdStr.c_str(), elfPath, NULL) == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700653 ALOGW("exec btfloader failed with errno %d (%s)", errno, strerror(errno));
Connor O'Brien35425e52022-01-18 21:41:16 -0800654 exit(EX_UNAVAILABLE);
655 }
656 }
657 btfloaderSocket.reset();
658 pipeWrite.reset();
659 if (!waitpidTimeout(pid, 100)) {
660 kill(pid, SIGKILL);
661 return {};
662 }
663
664 unique_fd btfFd;
665 if (android::base::ReceiveFileDescriptors(bpfloaderSocket, nullptr, 0, &btfFd)) return {};
666
667 std::string btfTypeIdStr;
668 if (!android::base::ReadFdToString(pipeRead, &btfTypeIdStr)) return {};
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700669 if (!btfFd.ok()) return {};
Connor O'Brien35425e52022-01-18 21:41:16 -0800670
671 const auto mapTypeIdLines = android::base::Split(btfTypeIdStr, "\n");
672 for (const auto &line : mapTypeIdLines) {
673 const auto vec = android::base::Split(line, " ");
674 // Splitting on newline will give us one empty line
675 if (vec.size() != 3) continue;
676 const int kTid = atoi(vec[1].c_str());
677 const int vTid = atoi(vec[2].c_str());
678 if (!kTid || !vTid) return {};
679 btfTypeIds[vec[0]] = std::make_pair(kTid, vTid);
680 }
681 return btfFd;
682}
683
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700684static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
685 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700686 // Assuming fd is a valid Bpf Map file descriptor then
687 // all the following should always succeed on a 4.14+ kernel.
688 // If they somehow do fail, they'll return -1 (and set errno),
689 // which should then cause (among others) a key_size mismatch.
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700690 int fd_type = bpfGetFdMapType(fd);
691 int fd_key_size = bpfGetFdKeySize(fd);
692 int fd_value_size = bpfGetFdValueSize(fd);
693 int fd_max_entries = bpfGetFdMaxEntries(fd);
694 int fd_map_flags = bpfGetFdMapFlags(fd);
695
696 // DEVMAPs are readonly from the bpf program side's point of view, as such
697 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
698 int desired_map_flags = (int)mapDef.map_flags;
699 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
700 desired_map_flags |= BPF_F_RDONLY_PROG;
701
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700702 // The following checks should *never* trigger, if one of them somehow does,
703 // it probably means a bpf .o file has been changed/replaced at runtime
704 // and bpfloader was manually rerun (normally it should only run *once*
705 // early during the boot process).
706 // Another possibility is that something is misconfigured in the code:
707 // most likely a shared map is declared twice differently.
708 // But such a change should never be checked into the source tree...
709 if ((fd_type == type) &&
710 (fd_key_size == (int)mapDef.key_size) &&
711 (fd_value_size == (int)mapDef.value_size) &&
712 (fd_max_entries == (int)mapDef.max_entries) &&
713 (fd_map_flags == desired_map_flags)) {
714 return true;
715 }
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700716
717 ALOGE("bpf map name %s mismatch: desired/found: "
718 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
719 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
720 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
721 return false;
722}
723
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800724static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700725 const char* prefix, const unsigned long long allowedDomainBitmask,
726 const size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700727 int ret;
Connor O'Brien35425e52022-01-18 21:41:16 -0800728 vector<char> mdData, btfData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700729 vector<struct bpf_map_def> md;
730 vector<string> mapNames;
Connor O'Brien35425e52022-01-18 21:41:16 -0800731 std::unordered_map<string, std::pair<uint32_t, uint32_t>> btfTypeIdMap;
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700732 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700733
734 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800735 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700736 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800737
738 if (mdData.size() % sizeOfBpfMapDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700739 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800740 mdData.size(), sizeOfBpfMapDef);
741 return -1;
742 };
743
744 int mapCount = mdData.size() / sizeOfBpfMapDef;
745 md.resize(mapCount);
746 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
747
748 const char* dataPtr = mdData.data();
749 for (auto& m : md) {
750 // First we zero initialize
751 memset(&m, 0, sizeof(m));
752 // Then we set non-zero defaults
753 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700754 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800755 // Then we copy over the structure prefix from the ELF file.
756 memcpy(&m, dataPtr, trimmedSize);
757 // Move to next struct in the ELF file
758 dataPtr += sizeOfBpfMapDef;
759 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700760
Connor O'Brien3278a162020-02-13 21:45:22 -0800761 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700762 if (ret) return ret;
763
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700764 unsigned btfMinBpfLoaderVer = readSectionUint("btf_min_bpfloader_ver", elfFile, 0);
765 unsigned btfMinKernelVer = readSectionUint("btf_min_kernel_ver", elfFile, 0);
766 unsigned kvers = kernelVersion();
767
Connor O'Brien35425e52022-01-18 21:41:16 -0800768 std::optional<unique_fd> btfFd;
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700769 if ((BPFLOADER_VERSION >= btfMinBpfLoaderVer) && (kvers >= btfMinKernelVer) &&
770 (!readSectionByName(".BTF", elfFile, btfData))) {
Connor O'Brien35425e52022-01-18 21:41:16 -0800771 btfFd = getMapBtfInfo(elfPath, btfTypeIdMap);
772 }
773
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700774 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +0000775 if (md[i].zero != 0) abort();
776
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800777 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700778 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800779 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700780 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800781 continue;
782 }
783
784 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700785 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800786 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700787 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800788 continue;
789 }
790
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700791 if (kvers < md[i].min_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700792 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700793 mapNames[i].c_str(), kvers, md[i].min_kver);
794 mapFds.push_back(unique_fd());
795 continue;
796 }
797
798 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700799 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700800 mapNames[i].c_str(), kvers, md[i].max_kver);
801 mapFds.push_back(unique_fd());
802 continue;
803 }
804
Ryan Zukliece89f502022-12-15 16:14:32 -0800805 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
806 (md[i].ignore_on_userdebug && isUserdebug())) {
807 ALOGI("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
808 getBuildType().c_str());
809 mapFds.push_back(unique_fd());
810 continue;
811 }
812
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700813 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700814 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
815 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
816 // of be approximated: HASH has the same userspace visible api.
817 // However it cannot be used by ebpf programs in the same way.
818 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
819 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
820 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
821 // programs as being 5.4+...
822 type = BPF_MAP_TYPE_HASH;
823 }
824
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700825 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
826 if (specified(selinux_context)) {
827 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
828 ALOGE("map %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
829 mapNames[i].c_str(), selinux_context, allowedDomainBitmask);
830 return -EINVAL;
831 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700832 ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700833 md[i].selinux_context, selinux_context, lookupSelinuxContext(selinux_context),
834 lookupPinSubdir(selinux_context));
835 }
836
837 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
838 if (unrecognized(pin_subdir)) return -ENOTDIR;
839 if (specified(pin_subdir)) {
840 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
841 ALOGE("map %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)",
842 mapNames[i].c_str(), pin_subdir, allowedDomainBitmask);
843 return -EINVAL;
844 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700845 ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700846 pin_subdir, lookupPinSubdir(pin_subdir));
847 }
848
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700849 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
850 // except that maps shared across .o's have empty <objName>
851 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700852 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700853 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700854 bool reuse = false;
855 unique_fd fd;
856 int saved_errno;
857
Joel Fernandesd76a2002018-10-16 13:19:58 -0700858 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskieb199dd2022-07-01 03:21:40 -0700859 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800860 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700861 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700862 reuse = true;
863 } else {
Connor O'Brien35425e52022-01-18 21:41:16 -0800864 struct bpf_create_map_attr attr = {
865 .name = mapNames[i].c_str(),
866 .map_type = type,
867 .map_flags = md[i].map_flags,
868 .key_size = md[i].key_size,
869 .value_size = md[i].value_size,
870 .max_entries = md[i].max_entries,
871 };
872 if (btfFd.has_value() && btfTypeIdMap.find(mapNames[i]) != btfTypeIdMap.end()) {
873 attr.btf_fd = btfFd->get();
874 attr.btf_key_type_id = btfTypeIdMap.at(mapNames[i]).first;
875 attr.btf_value_type_id = btfTypeIdMap.at(mapNames[i]).second;
876 }
877 fd.reset(bcc_create_map_xattr(&attr, true));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800878 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700879 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700880 }
881
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700882 if (!fd.ok()) return -saved_errno;
883
884 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
885 // safety (since reuse code path is rare) run these checks even if we just created it.
886 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
887 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700888
889 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700890 if (specified(selinux_context)) {
891 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700892 "tmp_map_" + objName + "_" + mapNames[i];
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700893 ret = bpf_obj_pin(fd, createLoc.c_str());
894 if (ret) {
895 int err = errno;
896 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
897 return -err;
898 }
899 ret = rename(createLoc.c_str(), mapPinLoc.c_str());
900 if (ret) {
901 int err = errno;
902 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
903 err, strerror(err));
904 return -err;
905 }
906 } else {
907 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowskid8259aa2022-06-27 10:02:20 -0700908 if (ret) {
909 int err = errno;
910 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
911 return -err;
912 }
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700913 }
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800914 ret = chmod(mapPinLoc.c_str(), md[i].mode);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700915 if (ret) {
916 int err = errno;
917 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
918 strerror(err));
919 return -err;
920 }
Maciej Żenczykowski5e4aabf2022-06-27 01:15:53 -0700921 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
922 if (ret) {
923 int err = errno;
924 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
925 ret, err, strerror(err));
926 return -err;
927 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700928 }
929
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700930 struct bpf_map_info map_info = {};
931 __u32 map_info_len = sizeof(map_info);
932 int rv = bpf_obj_get_info_by_fd(fd, &map_info, &map_info_len);
933 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700934 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700935 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700936 ALOGI("map %s id %d", mapPinLoc.c_str(), map_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700937 }
938
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700939 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700940 }
941
942 return ret;
943}
944
945/* For debugging, dump all instructions */
946static void dumpIns(char* ins, int size) {
947 for (int row = 0; row < size / 8; row++) {
948 ALOGE("%d: ", row);
949 for (int j = 0; j < 8; j++) {
950 ALOGE("%3x ", ins[(row * 8) + j]);
951 }
952 ALOGE("\n");
953 }
954}
955
956/* For debugging, dump all code sections from cs list */
957static void dumpAllCs(vector<codeSection>& cs) {
958 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700959 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700960 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700961 ALOGE("-----------");
Joel Fernandesd76a2002018-10-16 13:19:58 -0700962 }
963}
964
965static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
966 int insnIndex;
967 struct bpf_insn *insn, *insns;
968
969 insns = (struct bpf_insn*)(insnsPtr);
970
971 insnIndex = offset / sizeof(struct bpf_insn);
972 insn = &insns[insnIndex];
973
Maciej Żenczykowski509b1b92023-03-07 01:11:20 +0000974 // Occasionally might be useful for relocation debugging, but pretty spammy
975 if (0) {
976 ALOGD("applying relo to instruction at byte offset: %llu, "
977 "insn offset %d, insn %llx",
978 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
979 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700980
981 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700982 ALOGE("Dumping all instructions till ins %d", insnIndex);
983 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700984 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
985 return;
986 }
987
988 insn->imm = fd;
989 insn->src_reg = BPF_PSEUDO_MAP_FD;
990}
991
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700992static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700993 vector<string> mapNames;
994
Connor O'Brien3278a162020-02-13 21:45:22 -0800995 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700996 if (ret) return;
997
998 for (int k = 0; k != (int)cs.size(); k++) {
999 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
1000 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
1001
1002 for (int i = 0; i < n_rel; i++) {
1003 int symIndex = ELF64_R_SYM(rel[i].r_info);
1004 string symName;
1005
1006 ret = getSymNameByIdx(elfFile, symIndex, symName);
1007 if (ret) return;
1008
1009 /* Find the map fd and apply relo */
1010 for (int j = 0; j < (int)mapNames.size(); j++) {
1011 if (!mapNames[j].compare(symName)) {
1012 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
1013 break;
1014 }
1015 }
1016 }
1017 }
1018}
1019
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -08001020static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001021 const char* prefix, const unsigned long long allowedDomainBitmask) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -08001022 unsigned kvers = kernelVersion();
1023 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001024
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001025 if (!kvers) {
1026 ALOGE("unable to get kernel version");
1027 return -EINVAL;
1028 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001029
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001030 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001031
1032 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001033 string name = cs[i].name;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001034
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001035 if (!cs[i].prog_def.has_value()) {
1036 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
1037 return -EINVAL;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -08001038 }
1039
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001040 unsigned min_kver = cs[i].prog_def->min_kver;
1041 unsigned max_kver = cs[i].prog_def->max_kver;
1042 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1043 max_kver, kvers);
1044 if (kvers < min_kver) continue;
1045 if (kvers >= max_kver) continue;
1046
1047 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1048 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1049 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1050 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
1051 // Note: make sure to only check for unrecognized *after* verifying bpfloader
1052 // version limits include this bpfloader's version.
1053
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001054 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001055 bpfMinVer, bpfMaxVer);
1056 if (BPFLOADER_VERSION < bpfMinVer) continue;
1057 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
Ryan Zukliece89f502022-12-15 16:14:32 -08001058
1059 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1060 (cs[i].prog_def->ignore_on_user && isUser()) ||
1061 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1062 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1063 getBuildType().c_str());
Ryan Zuklie0fb433a2023-01-05 14:22:15 -08001064 continue;
Ryan Zukliece89f502022-12-15 16:14:32 -08001065 }
1066
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001067 if (unrecognized(pin_subdir)) return -ENOTDIR;
1068
1069 if (specified(selinux_context)) {
1070 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
1071 ALOGE("prog %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
1072 name.c_str(), selinux_context, allowedDomainBitmask);
1073 return -EINVAL;
1074 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001075 ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001076 cs[i].prog_def->selinux_context, selinux_context,
1077 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1078 }
1079
1080 if (specified(pin_subdir)) {
1081 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
1082 ALOGE("prog %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)", name.c_str(),
1083 pin_subdir, allowedDomainBitmask);
1084 return -EINVAL;
1085 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001086 ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001087 cs[i].prog_def->pin_subdir, pin_subdir, lookupPinSubdir(pin_subdir));
1088 }
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001089
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001090 // strip any potential $foo suffix
1091 // this can be used to provide duplicate programs
1092 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -07001093 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001094
1095 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001096 // Format of pin location is
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001097 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001098 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001099 objName + '_' + string(name);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001100 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001101 fd = retrieveProgram(progPinLoc.c_str());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001102 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd,
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001103 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001104 reuse = true;
1105 } else {
1106 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1107
Tyler Wear4e2f4602022-02-03 09:46:01 -08001108 struct bpf_load_program_attr attr = {
1109 .prog_type = cs[i].type,
1110 .name = name.c_str(),
1111 .insns = (struct bpf_insn*)cs[i].data.data(),
1112 .license = license.c_str(),
1113 .log_level = 0,
1114 .expected_attach_type = cs[i].expected_attach_type,
1115 };
1116
1117 fd = bcc_prog_load_xattr(&attr, cs[i].data.size(), log_buf.data(), log_buf.size(),
1118 true);
1119
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001120 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)", elfPath,
Steven Moreland804bca02019-12-12 17:21:23 -08001121 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001122
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001123 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -08001124 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001125
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001126 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
1127 for (const auto& line : lines) ALOGW("%s", line.c_str());
1128 ALOGW("bpf_prog_load - END log_buf contents.");
1129
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001130 if (cs[i].prog_def->optional) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001131 ALOGW("failed program is marked optional - continuing...");
1132 continue;
1133 }
1134 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001135 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001136 }
1137
1138 if (fd < 0) return fd;
1139 if (fd == 0) return -EINVAL;
1140
1141 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001142 if (specified(selinux_context)) {
1143 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001144 "tmp_prog_" + objName + '_' + string(name);
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001145 ret = bpf_obj_pin(fd, createLoc.c_str());
1146 if (ret) {
1147 int err = errno;
1148 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1149 return -err;
1150 }
1151 ret = rename(createLoc.c_str(), progPinLoc.c_str());
1152 if (ret) {
1153 int err = errno;
1154 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1155 err, strerror(err));
1156 return -err;
1157 }
1158 } else {
1159 ret = bpf_obj_pin(fd, progPinLoc.c_str());
1160 if (ret) {
1161 int err = errno;
1162 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1163 return -err;
1164 }
1165 }
1166 if (chmod(progPinLoc.c_str(), 0440)) {
1167 int err = errno;
1168 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1169 return -err;
1170 }
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001171 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1172 (gid_t)cs[i].prog_def->gid)) {
1173 int err = errno;
1174 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1175 cs[i].prog_def->gid, err, strerror(err));
1176 return -err;
Connor O'Brien3278a162020-02-13 21:45:22 -08001177 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001178 }
1179
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001180 struct bpf_prog_info prog_info = {};
1181 __u32 prog_info_len = sizeof(prog_info);
1182 int rv = bpf_obj_get_info_by_fd(fd, &prog_info, &prog_info_len);
1183 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001184 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001185 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001186 ALOGI("prog %s id %d", progPinLoc.c_str(), prog_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001187 }
1188
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001189 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001190 }
1191
1192 return 0;
1193}
1194
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001195int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
Joel Fernandesd76a2002018-10-16 13:19:58 -07001196 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001197 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001198 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001199 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001200 int ret;
1201
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001202 if (!isCritical) return -1;
1203 *isCritical = false;
1204
Joel Fernandesd76a2002018-10-16 13:19:58 -07001205 ifstream elfFile(elfPath, ios::in | ios::binary);
1206 if (!elfFile.is_open()) return -1;
1207
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001208 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001209 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001210
Joel Fernandesd76a2002018-10-16 13:19:58 -07001211 ret = readSectionByName("license", elfFile, license);
1212 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001213 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001214 return ret;
1215 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001216 ALOGD("Loading %s%s ELF object %s with license %s",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001217 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001218 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -07001219 }
1220
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001221 // the following default values are for bpfloader V0.0 format which does not include them
1222 unsigned int bpfLoaderMinVer =
1223 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1224 unsigned int bpfLoaderMaxVer =
1225 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001226 unsigned int bpfLoaderMinRequiredVer =
1227 readSectionUint("bpfloader_min_required_ver", elfFile, 0);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001228 size_t sizeOfBpfMapDef =
1229 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1230 size_t sizeOfBpfProgDef =
1231 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1232
1233 // inclusive lower bound check
1234 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001235 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001236 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
1237 return 0;
1238 }
1239
1240 // exclusive upper bound check
1241 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001242 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001243 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
1244 return 0;
1245 }
1246
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001247 if (BPFLOADER_VERSION < bpfLoaderMinRequiredVer) {
1248 ALOGI("BpfLoader version 0x%05x failing due to ELF object %s with required min ver 0x%05x",
1249 BPFLOADER_VERSION, elfPath, bpfLoaderMinRequiredVer);
1250 return -1;
1251 }
1252
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001253 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001254 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1255
1256 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001257 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001258 DEFAULT_SIZEOF_BPF_MAP_DEF);
1259 return -1;
1260 }
1261
1262 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001263 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001264 DEFAULT_SIZEOF_BPF_PROG_DEF);
1265 return -1;
1266 }
1267
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001268 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, location.allowedProgTypes,
1269 location.allowedProgTypesLength);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001270 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001271 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001272 return ret;
1273 }
1274
1275 /* Just for future debugging */
1276 if (0) dumpAllCs(cs);
1277
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001278 ret = createMaps(elfPath, elfFile, mapFds, location.prefix, location.allowedDomainBitmask,
1279 sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001280 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001281 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001282 return ret;
1283 }
1284
1285 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001286 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001287
1288 applyMapRelo(elfFile, mapFds, cs);
1289
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001290 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix,
1291 location.allowedDomainBitmask);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001292 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001293
1294 return ret;
1295}
1296
Joel Fernandesd76a2002018-10-16 13:19:58 -07001297} // namespace bpf
1298} // namespace android