blob: ba0ed4c85a6bc33020a1dcdcaa2d71ccc3cda0a6 [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 Żenczykowski2a5d0162022-07-21 13:27:24 +000033// This is BpfLoader v0.28
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080034#define BPFLOADER_VERSION_MAJOR 0u
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +000035#define BPFLOADER_VERSION_MINOR 28u
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080036#define BPFLOADER_VERSION ((BPFLOADER_VERSION_MAJOR << 16) | BPFLOADER_VERSION_MINOR)
37
Maciej Żenczykowski07375e22020-02-19 14:23:59 -080038#include "bpf/BpfUtils.h"
Ken Chend5689472021-12-20 18:07:21 +080039#include "bpf/bpf_map_def.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070040#include "include/libbpf_android.h"
41
Connor O'Brien35425e52022-01-18 21:41:16 -080042#include <bpf/bpf.h>
43
Joel Fernandesd76a2002018-10-16 13:19:58 -070044#include <cstdlib>
45#include <fstream>
46#include <iostream>
Connor O'Brien3278a162020-02-13 21:45:22 -080047#include <optional>
Joel Fernandesd76a2002018-10-16 13:19:58 -070048#include <string>
Connor O'Brien35425e52022-01-18 21:41:16 -080049#include <unordered_map>
Christopher Ferrisc151c672019-02-01 15:31:26 -080050#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070051
Connor O'Brien35425e52022-01-18 21:41:16 -080052#include <android-base/cmsg.h>
53#include <android-base/file.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070054#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070055#include <android-base/unique_fd.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070056
57#define BPF_FS_PATH "/sys/fs/bpf/"
58
59// Size of the BPF log buffer for verifier logging
Stephane Leeeb61b732021-10-21 17:03:11 -070060#define BPF_LOAD_LOG_SZ 0xfffff
Joel Fernandesd76a2002018-10-16 13:19:58 -070061
Tyler Wear4e2f4602022-02-03 09:46:01 -080062// Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
63#define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
64
Joel Fernandesd76a2002018-10-16 13:19:58 -070065using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070066using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070067using std::ifstream;
68using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080069using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080070using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070071using std::vector;
72
73namespace android {
74namespace bpf {
75
Maciej Żenczykowski41817132022-06-03 08:41:04 -070076constexpr const char* lookupSelinuxContext(const domain d, const char* const unspecified = "") {
77 switch (d) {
78 case domain::unspecified: return unspecified;
79 case domain::platform: return "fs_bpf";
80 case domain::tethering: return "fs_bpf_tethering";
81 case domain::net_private: return "fs_bpf_net_private";
82 case domain::net_shared: return "fs_bpf_net_shared";
83 case domain::netd_readonly: return "fs_bpf_netd_readonly";
84 case domain::netd_shared: return "fs_bpf_netd_shared";
85 case domain::vendor: return "fs_bpf_vendor";
86 default: return "(unrecognized)";
87 }
88}
89
90domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
91 for (domain d : AllDomains) {
92 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
93 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
94 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
95 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -070096 ALOGW("ignoring unrecognized selinux_context '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -070097 // We should return 'unrecognized' here, however: returning unspecified will
98 // result in the system simply using the default context, which in turn
99 // will allow future expansion by adding more restrictive selinux types.
100 // Older bpfloader will simply ignore that, and use the less restrictive default.
101 // This does mean you CANNOT later add a *less* restrictive type than the default.
102 //
103 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
104 return domain::unspecified;
105}
106
107constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
108 switch (d) {
109 case domain::unspecified: return unspecified;
110 case domain::platform: return "/";
111 case domain::tethering: return "tethering/";
112 case domain::net_private: return "net_private/";
113 case domain::net_shared: return "net_shared/";
114 case domain::netd_readonly: return "netd_readonly/";
115 case domain::netd_shared: return "netd_shared/";
116 case domain::vendor: return "vendor/";
117 default: return "(unrecognized)";
118 }
119};
120
121domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
122 for (domain d : AllDomains) {
123 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
124 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
125 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
126 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700127 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700128 // pin_subdir affects the object's full pathname,
129 // and thus using the default would change the location and thus our code's ability to find it,
130 // hence this seems worth treating as a true error condition.
131 //
132 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
133 // However, our callers will treat this as an error, and stop loading the specific .o,
134 // which will fail bpfloader if the .o is marked critical.
135 return domain::unrecognized;
136}
137
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700138static string pathToObjName(const string& path) {
139 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
140 string filename = android::base::Split(path, "/").back();
141 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
142 string name = filename.substr(0, filename.find_last_of('.'));
143 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
144 // this can be used to provide duplicate programs (mux based on the bpfloader version)
145 return name.substr(0, name.find_last_of('@'));
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800146}
147
Joel Fernandesd76a2002018-10-16 13:19:58 -0700148typedef struct {
149 const char* name;
150 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800151 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700152} sectionType;
153
154/*
155 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700156 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -0700157 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700158 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -0700159 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700160 *
161 * However, be aware that you should not be directly using the SECTION() macro.
162 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -0700163 */
164sectionType sectionNameTypes[] = {
Tyler Wear4e2f4602022-02-03 09:46:01 -0800165 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
166 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
167 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB, BPF_ATTACH_TYPE_UNSPEC},
168 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_ATTACH_TYPE_UNSPEC},
169 {"kprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie092e0b2022-05-24 13:14:32 +0000170 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT, BPF_ATTACH_TYPE_UNSPEC},
Tyler Wear4e2f4602022-02-03 09:46:01 -0800171 {"schedact/", BPF_PROG_TYPE_SCHED_ACT, BPF_ATTACH_TYPE_UNSPEC},
172 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS, BPF_ATTACH_TYPE_UNSPEC},
173 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
174 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
175 {"xdp/", BPF_PROG_TYPE_XDP, BPF_ATTACH_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700176};
177
178typedef struct {
179 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800180 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700181 string name;
182 vector<char> data;
183 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800184 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700185
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700186 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700187} codeSection;
188
Joel Fernandesd76a2002018-10-16 13:19:58 -0700189static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
190 elfFile.seekg(0);
191 if (elfFile.fail()) return -1;
192
193 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
194
195 return 0;
196}
197
198/* Reads all section header tables into an Shdr array */
199static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
200 Elf64_Ehdr eh;
201 int ret = 0;
202
203 ret = readElfHeader(elfFile, &eh);
204 if (ret) return ret;
205
206 elfFile.seekg(eh.e_shoff);
207 if (elfFile.fail()) return -1;
208
209 /* Read shdr table entries */
210 shTable.resize(eh.e_shnum);
211
212 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
213
214 return 0;
215}
216
217/* Read a section by its index - for ex to get sec hdr strtab blob */
218static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
219 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800220 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700221 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700222
223 elfFile.seekg(shTable[id].sh_offset);
224 if (elfFile.fail()) return -1;
225
226 sec.resize(shTable[id].sh_size);
227 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
228
229 return 0;
230}
231
232/* Read whole section header string table */
233static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
234 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800235 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700236 if (ret) return ret;
237
238 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
239 if (ret) return ret;
240
241 return 0;
242}
243
244/* Get name from offset in strtab */
245static int getSymName(ifstream& elfFile, int nameOff, string& name) {
246 int ret;
247 vector<char> secStrTab;
248
249 ret = readSectionHeaderStrtab(elfFile, secStrTab);
250 if (ret) return ret;
251
252 if (nameOff >= (int)secStrTab.size()) return -1;
253
254 name = string((char*)secStrTab.data() + nameOff);
255 return 0;
256}
257
258/* Reads a full section by name - example to get the GPL license */
259static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
260 vector<char> secStrTab;
261 vector<Elf64_Shdr> shTable;
262 int ret;
263
264 ret = readSectionHeadersAll(elfFile, shTable);
265 if (ret) return ret;
266
267 ret = readSectionHeaderStrtab(elfFile, secStrTab);
268 if (ret) return ret;
269
270 for (int i = 0; i < (int)shTable.size(); i++) {
271 char* secname = secStrTab.data() + shTable[i].sh_name;
272 if (!secname) continue;
273
274 if (!strcmp(secname, name)) {
275 vector<char> dataTmp;
276 dataTmp.resize(shTable[i].sh_size);
277
278 elfFile.seekg(shTable[i].sh_offset);
279 if (elfFile.fail()) return -1;
280
281 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
282
283 data = dataTmp;
284 return 0;
285 }
286 }
287 return -2;
288}
289
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700290unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800291 vector<char> theBytes;
292 int ret = readSectionByName(name, elfFile, theBytes);
293 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700294 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800295 return defVal;
296 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700297 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800298 return defVal;
299 } else {
300 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
301 unsigned int value = static_cast<unsigned char>(theBytes[3]);
302 value <<= 8;
303 value += static_cast<unsigned char>(theBytes[2]);
304 value <<= 8;
305 value += static_cast<unsigned char>(theBytes[1]);
306 value <<= 8;
307 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700308 ALOGI("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800309 return value;
310 }
311}
312
Joel Fernandesd76a2002018-10-16 13:19:58 -0700313static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
314 int ret;
315 vector<Elf64_Shdr> shTable;
316
317 ret = readSectionHeadersAll(elfFile, shTable);
318 if (ret) return ret;
319
320 for (int i = 0; i < (int)shTable.size(); i++) {
321 if ((int)shTable[i].sh_type != type) continue;
322
323 vector<char> dataTmp;
324 dataTmp.resize(shTable[i].sh_size);
325
326 elfFile.seekg(shTable[i].sh_offset);
327 if (elfFile.fail()) return -1;
328
329 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
330
331 data = dataTmp;
332 return 0;
333 }
334 return -2;
335}
336
337static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
338 return (a.st_value < b.st_value);
339}
340
341static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
342 int ret, numElems;
343 Elf64_Sym* buf;
344 vector<char> secData;
345
346 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
347 if (ret) return ret;
348
349 buf = (Elf64_Sym*)secData.data();
350 numElems = (secData.size() / sizeof(Elf64_Sym));
351 data.assign(buf, buf + numElems);
352
353 if (sort) std::sort(data.begin(), data.end(), symCompare);
354 return 0;
355}
356
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700357static enum bpf_prog_type getFuseProgType() {
358 int result = BPF_PROG_TYPE_UNSPEC;
359 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
360 return static_cast<bpf_prog_type>(result);
361}
362
Joel Fernandesd76a2002018-10-16 13:19:58 -0700363static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800364 for (auto& snt : sectionNameTypes)
365 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700366
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000367 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700368 if (StartsWith(name, "fuse/")) return getFuseProgType();
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000369
Joel Fernandesd76a2002018-10-16 13:19:58 -0700370 return BPF_PROG_TYPE_UNSPEC;
371}
372
Tyler Wear4e2f4602022-02-03 09:46:01 -0800373static enum bpf_attach_type getExpectedAttachType(string& name) {
374 for (auto& snt : sectionNameTypes)
375 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
376 return BPF_ATTACH_TYPE_UNSPEC;
377}
378
Joel Fernandesd76a2002018-10-16 13:19:58 -0700379static string getSectionName(enum bpf_prog_type type)
380{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800381 for (auto& snt : sectionNameTypes)
382 if (snt.type == type)
383 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700384
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800385 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700386}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700387
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800388static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
389 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800390 vector<char> pdData;
391 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800392 // Older file formats do not require a 'progs' section at all.
393 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800394 if (ret == -2) return 0;
395 if (ret) return ret;
396
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800397 if (pdData.size() % sizeOfBpfProgDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700398 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800399 pdData.size(), sizeOfBpfProgDef);
400 return -1;
401 };
402
403 int progCount = pdData.size() / sizeOfBpfProgDef;
404 pd.resize(progCount);
405 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
406
407 const char* dataPtr = pdData.data();
408 for (auto& p : pd) {
409 // First we zero initialize
410 memset(&p, 0, sizeof(p));
411 // Then we set non-zero defaults
412 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
413 // Then we copy over the structure prefix from the ELF file.
414 memcpy(&p, dataPtr, trimmedSize);
415 // Move to next struct in the ELF file
416 dataPtr += sizeOfBpfProgDef;
417 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800418 return 0;
419}
420
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800421static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
422 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800423 int ret;
424 string name;
425 vector<Elf64_Sym> symtab;
426 vector<Elf64_Shdr> shTable;
427
428 ret = readSymTab(elfFile, 1 /* sort */, symtab);
429 if (ret) return ret;
430
431 /* Get index of section */
432 ret = readSectionHeadersAll(elfFile, shTable);
433 if (ret) return ret;
434
435 int sec_idx = -1;
436 for (int i = 0; i < (int)shTable.size(); i++) {
437 ret = getSymName(elfFile, shTable[i].sh_name, name);
438 if (ret) return ret;
439
440 if (!name.compare(sectionName)) {
441 sec_idx = i;
442 break;
443 }
444 }
445
446 /* No section found with matching name*/
447 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700448 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800449 return -1;
450 }
451
452 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800453 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
454
Connor O'Brien3278a162020-02-13 21:45:22 -0800455 if (symtab[i].st_shndx == sec_idx) {
456 string s;
457 ret = getSymName(elfFile, symtab[i].st_name, s);
458 if (ret) return ret;
459 names.push_back(s);
460 }
461 }
462
463 return 0;
464}
465
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800466static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
467 if (allowed == nullptr) return true;
468
469 for (size_t i = 0; i < numAllowed; i++) {
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700470 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
471 if (type == getFuseProgType()) return true;
472 } else if (type == allowed[i])
473 return true;
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800474 }
475
476 return false;
477}
478
Joel Fernandesd76a2002018-10-16 13:19:58 -0700479/* Read a section by its index - for ex to get sec hdr strtab blob */
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800480static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef,
481 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700482 vector<Elf64_Shdr> shTable;
483 int entries, ret = 0;
484
485 ret = readSectionHeadersAll(elfFile, shTable);
486 if (ret) return ret;
487 entries = shTable.size();
488
Connor O'Brien3278a162020-02-13 21:45:22 -0800489 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800490 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800491 if (ret) return ret;
492 vector<string> progDefNames;
493 ret = getSectionSymNames(elfFile, "progs", progDefNames);
494 if (!pd.empty() && ret) return ret;
495
Joel Fernandesd76a2002018-10-16 13:19:58 -0700496 for (int i = 0; i < entries; i++) {
497 string name;
498 codeSection cs_temp;
499 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
500
501 ret = getSymName(elfFile, shTable[i].sh_name, name);
502 if (ret) return ret;
503
504 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800505
Tyler Wear4e2f4602022-02-03 09:46:01 -0800506 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800507
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800508 if (!IsAllowed(ptype, allowed, numAllowed)) {
509 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
510 return -1;
511 }
512
Tyler Wear4e2f4602022-02-03 09:46:01 -0800513 // This must be done before '/' is replaced with '_'.
514 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800515
Tyler Wear4e2f4602022-02-03 09:46:01 -0800516 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700517
Tyler Wear4e2f4602022-02-03 09:46:01 -0800518 // convert all slashes to underscores
519 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800520
Tyler Wear4e2f4602022-02-03 09:46:01 -0800521 cs_temp.type = ptype;
522 cs_temp.name = name;
523
524 ret = readSectionByIdx(elfFile, i, cs_temp.data);
525 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700526 ALOGD("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800527
528 vector<string> csSymNames;
529 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
530 if (ret || !csSymNames.size()) return ret;
531 for (size_t i = 0; i < progDefNames.size(); ++i) {
532 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
533 cs_temp.prog_def = pd[i];
534 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800535 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700536 }
537
538 /* Check for rel section */
539 if (cs_temp.data.size() > 0 && i < entries) {
540 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
541 if (ret) return ret;
542
Tyler Wear4e2f4602022-02-03 09:46:01 -0800543 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700544 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
545 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700546 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700547 }
548 }
549
550 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700551 cs.push_back(std::move(cs_temp));
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700552 ALOGD("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700553 }
554 }
555 return 0;
556}
557
558static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
559 vector<Elf64_Sym> symtab;
560 int ret = 0;
561
562 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
563 if (ret) return ret;
564
565 if (index >= (int)symtab.size()) return -1;
566
567 return getSymName(elfFile, symtab[index].st_name, name);
568}
569
Connor O'Brien35425e52022-01-18 21:41:16 -0800570static bool waitpidTimeout(pid_t pid, int timeoutMs) {
571 // Add SIGCHLD to the signal set.
572 sigset_t child_mask, original_mask;
573 sigemptyset(&child_mask);
574 sigaddset(&child_mask, SIGCHLD);
575 if (sigprocmask(SIG_BLOCK, &child_mask, &original_mask) == -1) return false;
576
577 // Wait for a SIGCHLD notification.
578 errno = 0;
579 timespec ts = {0, timeoutMs * 1000000};
580 int wait_result = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, nullptr, &ts));
581
582 // Restore the original signal set.
583 sigprocmask(SIG_SETMASK, &original_mask, nullptr);
584
585 if (wait_result == -1) return false;
586
587 int status;
588 return TEMP_FAILURE_RETRY(waitpid(pid, &status, WNOHANG)) == pid;
589}
590
591static std::optional<unique_fd> getMapBtfInfo(const char* elfPath,
592 std::unordered_map<string, std::pair<uint32_t, uint32_t>> &btfTypeIds) {
593 unique_fd bpfloaderSocket, btfloaderSocket;
594 if (!android::base::Socketpair(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0, &bpfloaderSocket,
595 &btfloaderSocket)) {
596 return {};
597 }
598
599 unique_fd pipeRead, pipeWrite;
600 if (!android::base::Pipe(&pipeRead, &pipeWrite, O_NONBLOCK)) {
601 return {};
602 }
603
604 pid_t pid = fork();
605 if (pid < 0) return {};
606 if (!pid) {
607 bpfloaderSocket.reset();
608 pipeRead.reset();
609 auto socketFdStr = std::to_string(btfloaderSocket.release());
610 auto pipeFdStr = std::to_string(pipeWrite.release());
611
612 if (execl("/system/bin/btfloader", "/system/bin/btfloader", socketFdStr.c_str(),
613 pipeFdStr.c_str(), elfPath, NULL) == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700614 ALOGW("exec btfloader failed with errno %d (%s)", errno, strerror(errno));
Connor O'Brien35425e52022-01-18 21:41:16 -0800615 exit(EX_UNAVAILABLE);
616 }
617 }
618 btfloaderSocket.reset();
619 pipeWrite.reset();
620 if (!waitpidTimeout(pid, 100)) {
621 kill(pid, SIGKILL);
622 return {};
623 }
624
625 unique_fd btfFd;
626 if (android::base::ReceiveFileDescriptors(bpfloaderSocket, nullptr, 0, &btfFd)) return {};
627
628 std::string btfTypeIdStr;
629 if (!android::base::ReadFdToString(pipeRead, &btfTypeIdStr)) return {};
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700630 if (!btfFd.ok()) return {};
Connor O'Brien35425e52022-01-18 21:41:16 -0800631
632 const auto mapTypeIdLines = android::base::Split(btfTypeIdStr, "\n");
633 for (const auto &line : mapTypeIdLines) {
634 const auto vec = android::base::Split(line, " ");
635 // Splitting on newline will give us one empty line
636 if (vec.size() != 3) continue;
637 const int kTid = atoi(vec[1].c_str());
638 const int vTid = atoi(vec[2].c_str());
639 if (!kTid || !vTid) return {};
640 btfTypeIds[vec[0]] = std::make_pair(kTid, vTid);
641 }
642 return btfFd;
643}
644
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700645static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
646 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700647 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
648 // so on 4.9 kernels just pretend the map matches our expectations.
649 // This isn't really a problem as we only really support 4.14+ anyway...
650 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
651 // This is because the primary failure mode we're trying to detect here
652 // is either a source code misconfiguration (which is likely kernel independent)
653 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
654 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
655
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700656 // Assuming fd is a valid Bpf Map file descriptor then
657 // all the following should always succeed on a 4.14+ kernel.
658 // If they somehow do fail, they'll return -1 (and set errno),
659 // which should then cause (among others) a key_size mismatch.
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700660 int fd_type = bpfGetFdMapType(fd);
661 int fd_key_size = bpfGetFdKeySize(fd);
662 int fd_value_size = bpfGetFdValueSize(fd);
663 int fd_max_entries = bpfGetFdMaxEntries(fd);
664 int fd_map_flags = bpfGetFdMapFlags(fd);
665
666 // DEVMAPs are readonly from the bpf program side's point of view, as such
667 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
668 int desired_map_flags = (int)mapDef.map_flags;
669 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
670 desired_map_flags |= BPF_F_RDONLY_PROG;
671
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700672 // The following checks should *never* trigger, if one of them somehow does,
673 // it probably means a bpf .o file has been changed/replaced at runtime
674 // and bpfloader was manually rerun (normally it should only run *once*
675 // early during the boot process).
676 // Another possibility is that something is misconfigured in the code:
677 // most likely a shared map is declared twice differently.
678 // But such a change should never be checked into the source tree...
679 if ((fd_type == type) &&
680 (fd_key_size == (int)mapDef.key_size) &&
681 (fd_value_size == (int)mapDef.value_size) &&
682 (fd_max_entries == (int)mapDef.max_entries) &&
683 (fd_map_flags == desired_map_flags)) {
684 return true;
685 }
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700686
687 ALOGE("bpf map name %s mismatch: desired/found: "
688 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
689 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
690 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
691 return false;
692}
693
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800694static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700695 const char* prefix, const unsigned long long allowedDomainBitmask,
696 const size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700697 int ret;
Connor O'Brien35425e52022-01-18 21:41:16 -0800698 vector<char> mdData, btfData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700699 vector<struct bpf_map_def> md;
700 vector<string> mapNames;
Connor O'Brien35425e52022-01-18 21:41:16 -0800701 std::unordered_map<string, std::pair<uint32_t, uint32_t>> btfTypeIdMap;
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700702 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700703
704 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800705 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700706 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800707
708 if (mdData.size() % sizeOfBpfMapDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700709 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800710 mdData.size(), sizeOfBpfMapDef);
711 return -1;
712 };
713
714 int mapCount = mdData.size() / sizeOfBpfMapDef;
715 md.resize(mapCount);
716 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
717
718 const char* dataPtr = mdData.data();
719 for (auto& m : md) {
720 // First we zero initialize
721 memset(&m, 0, sizeof(m));
722 // Then we set non-zero defaults
723 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700724 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800725 // Then we copy over the structure prefix from the ELF file.
726 memcpy(&m, dataPtr, trimmedSize);
727 // Move to next struct in the ELF file
728 dataPtr += sizeOfBpfMapDef;
729 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700730
Connor O'Brien3278a162020-02-13 21:45:22 -0800731 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700732 if (ret) return ret;
733
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700734 unsigned btfMinBpfLoaderVer = readSectionUint("btf_min_bpfloader_ver", elfFile, 0);
735 unsigned btfMinKernelVer = readSectionUint("btf_min_kernel_ver", elfFile, 0);
736 unsigned kvers = kernelVersion();
737
Connor O'Brien35425e52022-01-18 21:41:16 -0800738 std::optional<unique_fd> btfFd;
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700739 if ((BPFLOADER_VERSION >= btfMinBpfLoaderVer) && (kvers >= btfMinKernelVer) &&
740 (!readSectionByName(".BTF", elfFile, btfData))) {
Connor O'Brien35425e52022-01-18 21:41:16 -0800741 btfFd = getMapBtfInfo(elfPath, btfTypeIdMap);
742 }
743
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700744 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +0000745 if (md[i].zero != 0) abort();
746
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800747 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700748 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800749 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700750 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800751 continue;
752 }
753
754 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700755 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800756 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700757 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800758 continue;
759 }
760
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700761 if (kvers < md[i].min_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700762 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700763 mapNames[i].c_str(), kvers, md[i].min_kver);
764 mapFds.push_back(unique_fd());
765 continue;
766 }
767
768 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700769 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700770 mapNames[i].c_str(), kvers, md[i].max_kver);
771 mapFds.push_back(unique_fd());
772 continue;
773 }
774
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700775 enum bpf_map_type type = md[i].type;
776 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
777 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
778 // of be approximated: ARRAY has the same userspace api, though it is not usable
779 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
780 // helper doesn't exist on 4.9 anyway (so the bpf program would fail to load,
781 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
782 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
783 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
784 type = BPF_MAP_TYPE_ARRAY;
785 }
786 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
787 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
788 // of be approximated: HASH has the same userspace visible api.
789 // However it cannot be used by ebpf programs in the same way.
790 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
791 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
792 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
793 // programs as being 5.4+...
794 type = BPF_MAP_TYPE_HASH;
795 }
796
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700797 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
798 if (specified(selinux_context)) {
799 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
800 ALOGE("map %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
801 mapNames[i].c_str(), selinux_context, allowedDomainBitmask);
802 return -EINVAL;
803 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700804 ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700805 md[i].selinux_context, selinux_context, lookupSelinuxContext(selinux_context),
806 lookupPinSubdir(selinux_context));
807 }
808
809 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
810 if (unrecognized(pin_subdir)) return -ENOTDIR;
811 if (specified(pin_subdir)) {
812 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
813 ALOGE("map %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)",
814 mapNames[i].c_str(), pin_subdir, allowedDomainBitmask);
815 return -EINVAL;
816 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700817 ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700818 pin_subdir, lookupPinSubdir(pin_subdir));
819 }
820
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700821 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
822 // except that maps shared across .o's have empty <objName>
823 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700824 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700825 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700826 bool reuse = false;
827 unique_fd fd;
828 int saved_errno;
829
Joel Fernandesd76a2002018-10-16 13:19:58 -0700830 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskieb199dd2022-07-01 03:21:40 -0700831 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800832 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700833 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700834 reuse = true;
835 } else {
Connor O'Brien35425e52022-01-18 21:41:16 -0800836 struct bpf_create_map_attr attr = {
837 .name = mapNames[i].c_str(),
838 .map_type = type,
839 .map_flags = md[i].map_flags,
840 .key_size = md[i].key_size,
841 .value_size = md[i].value_size,
842 .max_entries = md[i].max_entries,
843 };
844 if (btfFd.has_value() && btfTypeIdMap.find(mapNames[i]) != btfTypeIdMap.end()) {
845 attr.btf_fd = btfFd->get();
846 attr.btf_key_type_id = btfTypeIdMap.at(mapNames[i]).first;
847 attr.btf_value_type_id = btfTypeIdMap.at(mapNames[i]).second;
848 }
849 fd.reset(bcc_create_map_xattr(&attr, true));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800850 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700851 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700852 }
853
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700854 if (!fd.ok()) return -saved_errno;
855
856 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
857 // safety (since reuse code path is rare) run these checks even if we just created it.
858 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
859 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700860
861 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700862 if (specified(selinux_context)) {
863 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700864 "tmp_map_" + objName + "_" + mapNames[i];
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700865 ret = bpf_obj_pin(fd, createLoc.c_str());
866 if (ret) {
867 int err = errno;
868 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
869 return -err;
870 }
871 ret = rename(createLoc.c_str(), mapPinLoc.c_str());
872 if (ret) {
873 int err = errno;
874 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
875 err, strerror(err));
876 return -err;
877 }
878 } else {
879 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowskid8259aa2022-06-27 10:02:20 -0700880 if (ret) {
881 int err = errno;
882 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
883 return -err;
884 }
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700885 }
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800886 ret = chmod(mapPinLoc.c_str(), md[i].mode);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700887 if (ret) {
888 int err = errno;
889 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
890 strerror(err));
891 return -err;
892 }
Maciej Żenczykowski5e4aabf2022-06-27 01:15:53 -0700893 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
894 if (ret) {
895 int err = errno;
896 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
897 ret, err, strerror(err));
898 return -err;
899 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700900 }
901
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700902 struct bpf_map_info map_info = {};
903 __u32 map_info_len = sizeof(map_info);
904 int rv = bpf_obj_get_info_by_fd(fd, &map_info, &map_info_len);
905 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700906 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700907 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700908 ALOGI("map %s id %d", mapPinLoc.c_str(), map_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700909 }
910
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700911 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700912 }
913
914 return ret;
915}
916
917/* For debugging, dump all instructions */
918static void dumpIns(char* ins, int size) {
919 for (int row = 0; row < size / 8; row++) {
920 ALOGE("%d: ", row);
921 for (int j = 0; j < 8; j++) {
922 ALOGE("%3x ", ins[(row * 8) + j]);
923 }
924 ALOGE("\n");
925 }
926}
927
928/* For debugging, dump all code sections from cs list */
929static void dumpAllCs(vector<codeSection>& cs) {
930 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700931 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700932 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700933 ALOGE("-----------");
Joel Fernandesd76a2002018-10-16 13:19:58 -0700934 }
935}
936
937static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
938 int insnIndex;
939 struct bpf_insn *insn, *insns;
940
941 insns = (struct bpf_insn*)(insnsPtr);
942
943 insnIndex = offset / sizeof(struct bpf_insn);
944 insn = &insns[insnIndex];
945
Ken Chene1b518c2022-07-06 20:50:36 +0800946 ALOGD("applying relo to instruction at byte offset: %llu, "
947 "insn offset %d, insn %llx",
948 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700949
950 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700951 ALOGE("Dumping all instructions till ins %d", insnIndex);
952 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700953 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
954 return;
955 }
956
957 insn->imm = fd;
958 insn->src_reg = BPF_PSEUDO_MAP_FD;
959}
960
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700961static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700962 vector<string> mapNames;
963
Connor O'Brien3278a162020-02-13 21:45:22 -0800964 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700965 if (ret) return;
966
967 for (int k = 0; k != (int)cs.size(); k++) {
968 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
969 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
970
971 for (int i = 0; i < n_rel; i++) {
972 int symIndex = ELF64_R_SYM(rel[i].r_info);
973 string symName;
974
975 ret = getSymNameByIdx(elfFile, symIndex, symName);
976 if (ret) return;
977
978 /* Find the map fd and apply relo */
979 for (int j = 0; j < (int)mapNames.size(); j++) {
980 if (!mapNames[j].compare(symName)) {
981 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
982 break;
983 }
984 }
985 }
986 }
987}
988
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800989static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700990 const char* prefix, const unsigned long long allowedDomainBitmask) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800991 unsigned kvers = kernelVersion();
992 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700993
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800994 if (!kvers) return -1;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700995
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700996 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700997
998 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700999 string name = cs[i].name;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001000 unsigned bpfMinVer = DEFAULT_BPFLOADER_MIN_VER; // v0.0
1001 unsigned bpfMaxVer = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001002 domain selinux_context = domain::unspecified;
1003 domain pin_subdir = domain::unspecified;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001004
Maciej Żenczykowski07375e22020-02-19 14:23:59 -08001005 if (cs[i].prog_def.has_value()) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001006 unsigned min_kver = cs[i].prog_def->min_kver;
1007 unsigned max_kver = cs[i].prog_def->max_kver;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001008 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001009 max_kver, kvers);
1010 if (kvers < min_kver) continue;
1011 if (kvers >= max_kver) continue;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001012
1013 bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1014 bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001015 selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1016 pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
1017 // Note: make sure to only check for unrecognized *after* verifying bpfloader
1018 // version limits include this bpfloader's version.
Maciej Żenczykowski07375e22020-02-19 14:23:59 -08001019 }
1020
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001021 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001022 bpfMinVer, bpfMaxVer);
1023 if (BPFLOADER_VERSION < bpfMinVer) continue;
1024 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001025 if (unrecognized(pin_subdir)) return -ENOTDIR;
1026
1027 if (specified(selinux_context)) {
1028 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
1029 ALOGE("prog %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
1030 name.c_str(), selinux_context, allowedDomainBitmask);
1031 return -EINVAL;
1032 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001033 ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001034 cs[i].prog_def->selinux_context, selinux_context,
1035 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1036 }
1037
1038 if (specified(pin_subdir)) {
1039 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
1040 ALOGE("prog %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)", name.c_str(),
1041 pin_subdir, allowedDomainBitmask);
1042 return -EINVAL;
1043 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001044 ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001045 cs[i].prog_def->pin_subdir, pin_subdir, lookupPinSubdir(pin_subdir));
1046 }
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001047
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001048 // strip any potential $foo suffix
1049 // this can be used to provide duplicate programs
1050 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -07001051 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001052
1053 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001054 // Format of pin location is
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001055 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001056 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001057 objName + '_' + string(name);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001058 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001059 fd = retrieveProgram(progPinLoc.c_str());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001060 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd,
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001061 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001062 reuse = true;
1063 } else {
1064 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1065
Tyler Wear4e2f4602022-02-03 09:46:01 -08001066 struct bpf_load_program_attr attr = {
1067 .prog_type = cs[i].type,
1068 .name = name.c_str(),
1069 .insns = (struct bpf_insn*)cs[i].data.data(),
1070 .license = license.c_str(),
1071 .log_level = 0,
1072 .expected_attach_type = cs[i].expected_attach_type,
1073 };
1074
1075 fd = bcc_prog_load_xattr(&attr, cs[i].data.size(), log_buf.data(), log_buf.size(),
1076 true);
1077
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001078 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)", elfPath,
Steven Moreland804bca02019-12-12 17:21:23 -08001079 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001080
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001081 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -08001082 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001083
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001084 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
1085 for (const auto& line : lines) ALOGW("%s", line.c_str());
1086 ALOGW("bpf_prog_load - END log_buf contents.");
1087
Maciej Żenczykowski6f4e6ae2022-07-13 20:51:17 +00001088 if (cs[i].prog_def.has_value() && cs[i].prog_def->optional) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001089 ALOGW("failed program is marked optional - continuing...");
1090 continue;
1091 }
1092 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001093 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001094 }
1095
1096 if (fd < 0) return fd;
1097 if (fd == 0) return -EINVAL;
1098
1099 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001100 if (specified(selinux_context)) {
1101 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001102 "tmp_prog_" + objName + '_' + string(name);
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001103 ret = bpf_obj_pin(fd, createLoc.c_str());
1104 if (ret) {
1105 int err = errno;
1106 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1107 return -err;
1108 }
1109 ret = rename(createLoc.c_str(), progPinLoc.c_str());
1110 if (ret) {
1111 int err = errno;
1112 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1113 err, strerror(err));
1114 return -err;
1115 }
1116 } else {
1117 ret = bpf_obj_pin(fd, progPinLoc.c_str());
1118 if (ret) {
1119 int err = errno;
1120 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1121 return -err;
1122 }
1123 }
1124 if (chmod(progPinLoc.c_str(), 0440)) {
1125 int err = errno;
1126 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1127 return -err;
1128 }
Connor O'Brien3278a162020-02-13 21:45:22 -08001129 if (cs[i].prog_def.has_value()) {
1130 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1131 (gid_t)cs[i].prog_def->gid)) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001132 int err = errno;
1133 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1134 cs[i].prog_def->gid, err, strerror(err));
1135 return -err;
Connor O'Brien3278a162020-02-13 21:45:22 -08001136 }
1137 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001138 }
1139
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001140 struct bpf_prog_info prog_info = {};
1141 __u32 prog_info_len = sizeof(prog_info);
1142 int rv = bpf_obj_get_info_by_fd(fd, &prog_info, &prog_info_len);
1143 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001144 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001145 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001146 ALOGI("prog %s id %d", progPinLoc.c_str(), prog_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001147 }
1148
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001149 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001150 }
1151
1152 return 0;
1153}
1154
Steven Moreland0f10f3f2019-12-12 14:22:34 -08001155int loadProg(const char* elfPath, bool* isCritical, const char* prefix,
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001156 const unsigned long long allowedDomainBitmask, const bpf_prog_type* allowed,
1157 size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -07001158 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001159 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001160 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001161 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001162 int ret;
1163
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001164 if (!isCritical) return -1;
1165 *isCritical = false;
1166
Joel Fernandesd76a2002018-10-16 13:19:58 -07001167 ifstream elfFile(elfPath, ios::in | ios::binary);
1168 if (!elfFile.is_open()) return -1;
1169
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001170 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001171 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001172
Joel Fernandesd76a2002018-10-16 13:19:58 -07001173 ret = readSectionByName("license", elfFile, license);
1174 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001175 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001176 return ret;
1177 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001178 ALOGD("Loading %s%s ELF object %s with license %s",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001179 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001180 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -07001181 }
1182
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001183 // the following default values are for bpfloader V0.0 format which does not include them
1184 unsigned int bpfLoaderMinVer =
1185 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1186 unsigned int bpfLoaderMaxVer =
1187 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001188 unsigned int bpfLoaderMinRequiredVer =
1189 readSectionUint("bpfloader_min_required_ver", elfFile, 0);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001190 size_t sizeOfBpfMapDef =
1191 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1192 size_t sizeOfBpfProgDef =
1193 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1194
1195 // inclusive lower bound check
1196 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001197 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001198 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
1199 return 0;
1200 }
1201
1202 // exclusive upper bound check
1203 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001204 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001205 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
1206 return 0;
1207 }
1208
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001209 if (BPFLOADER_VERSION < bpfLoaderMinRequiredVer) {
1210 ALOGI("BpfLoader version 0x%05x failing due to ELF object %s with required min ver 0x%05x",
1211 BPFLOADER_VERSION, elfPath, bpfLoaderMinRequiredVer);
1212 return -1;
1213 }
1214
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001215 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001216 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1217
1218 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001219 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001220 DEFAULT_SIZEOF_BPF_MAP_DEF);
1221 return -1;
1222 }
1223
1224 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001225 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001226 DEFAULT_SIZEOF_BPF_PROG_DEF);
1227 return -1;
1228 }
1229
Steven Moreland0f10f3f2019-12-12 14:22:34 -08001230 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, allowed, numAllowed);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001231 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001232 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001233 return ret;
1234 }
1235
1236 /* Just for future debugging */
1237 if (0) dumpAllCs(cs);
1238
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001239 ret = createMaps(elfPath, elfFile, mapFds, prefix, allowedDomainBitmask, sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001240 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001241 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001242 return ret;
1243 }
1244
1245 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001246 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001247
1248 applyMapRelo(elfFile, mapFds, cs);
1249
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001250 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix, allowedDomainBitmask);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001251 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001252
1253 return ret;
1254}
1255
Joel Fernandesd76a2002018-10-16 13:19:58 -07001256} // namespace bpf
1257} // namespace android