blob: 8686ccc47995bfe2b0ffd84821bf5b2336d4e2f9 [file] [log] [blame]
Joel Fernandesd76a2002018-10-16 13:19:58 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "LibBpfLoader"
18
19#include <errno.h>
Maciej Żenczykowskie15229f2023-04-17 07:16:33 +000020#include <fcntl.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070021#include <linux/bpf.h>
22#include <linux/elf.h>
23#include <log/log.h>
24#include <stdint.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080028#include <sysexits.h>
Maciej Żenczykowski83f29772020-01-27 03:11:51 -080029#include <sys/stat.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070030#include <sys/utsname.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080031#include <sys/wait.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070032#include <unistd.h>
33
Maciej Żenczykowski300c51f2022-12-14 04:18:02 -080034#include "BpfSyscallWrappers.h"
Maciej Żenczykowski07375e22020-02-19 14:23:59 -080035#include "bpf/BpfUtils.h"
Ken Chend5689472021-12-20 18:07:21 +080036#include "bpf/bpf_map_def.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070037#include "include/libbpf_android.h"
38
39#include <cstdlib>
40#include <fstream>
41#include <iostream>
Connor O'Brien3278a162020-02-13 21:45:22 -080042#include <optional>
Joel Fernandesd76a2002018-10-16 13:19:58 -070043#include <string>
Connor O'Brien35425e52022-01-18 21:41:16 -080044#include <unordered_map>
Christopher Ferrisc151c672019-02-01 15:31:26 -080045#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070046
Connor O'Brien35425e52022-01-18 21:41:16 -080047#include <android-base/cmsg.h>
48#include <android-base/file.h>
Elliott Hughes3b0811b2023-10-09 22:20:04 +000049#include <android-base/properties.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070050#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070051#include <android-base/unique_fd.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070052
53#define BPF_FS_PATH "/sys/fs/bpf/"
54
55// Size of the BPF log buffer for verifier logging
Stephane Leeeb61b732021-10-21 17:03:11 -070056#define BPF_LOAD_LOG_SZ 0xfffff
Joel Fernandesd76a2002018-10-16 13:19:58 -070057
Tyler Wear4e2f4602022-02-03 09:46:01 -080058// Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
59#define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
60
Joel Fernandesd76a2002018-10-16 13:19:58 -070061using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070062using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070063using std::ifstream;
64using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080065using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080066using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070067using std::vector;
68
69namespace android {
70namespace bpf {
71
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +000072static unsigned int page_size = static_cast<unsigned int>(getpagesize());
73
Maciej Żenczykowski41817132022-06-03 08:41:04 -070074constexpr const char* lookupSelinuxContext(const domain d, const char* const unspecified = "") {
75 switch (d) {
76 case domain::unspecified: return unspecified;
77 case domain::platform: return "fs_bpf";
Maciej Żenczykowski41817132022-06-03 08:41:04 -070078 case domain::vendor: return "fs_bpf_vendor";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +000079 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski41817132022-06-03 08:41:04 -070080 default: return "(unrecognized)";
81 }
82}
83
84domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
85 for (domain d : AllDomains) {
86 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
87 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
88 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
89 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -070090 ALOGW("ignoring unrecognized selinux_context '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -070091 // We should return 'unrecognized' here, however: returning unspecified will
92 // result in the system simply using the default context, which in turn
93 // will allow future expansion by adding more restrictive selinux types.
94 // Older bpfloader will simply ignore that, and use the less restrictive default.
95 // This does mean you CANNOT later add a *less* restrictive type than the default.
96 //
97 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
98 return domain::unspecified;
99}
100
101constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
102 switch (d) {
103 case domain::unspecified: return unspecified;
104 case domain::platform: return "/";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700105 case domain::vendor: return "vendor/";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +0000106 case domain::loader: return "loader/";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700107 default: return "(unrecognized)";
108 }
109};
110
111domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
112 for (domain d : AllDomains) {
113 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
114 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
115 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
116 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700117 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700118 // pin_subdir affects the object's full pathname,
119 // and thus using the default would change the location and thus our code's ability to find it,
120 // hence this seems worth treating as a true error condition.
121 //
122 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
123 // However, our callers will treat this as an error, and stop loading the specific .o,
124 // which will fail bpfloader if the .o is marked critical.
125 return domain::unrecognized;
126}
127
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700128static string pathToObjName(const string& path) {
129 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
130 string filename = android::base::Split(path, "/").back();
131 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
132 string name = filename.substr(0, filename.find_last_of('.'));
133 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
134 // this can be used to provide duplicate programs (mux based on the bpfloader version)
135 return name.substr(0, name.find_last_of('@'));
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800136}
137
Joel Fernandesd76a2002018-10-16 13:19:58 -0700138typedef struct {
139 const char* name;
140 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800141 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700142} sectionType;
143
144/*
145 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700146 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -0700147 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700148 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -0700149 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700150 *
151 * However, be aware that you should not be directly using the SECTION() macro.
152 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -0700153 */
154sectionType sectionNameTypes[] = {
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000155 {"kprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
156 {"kretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000157 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000158 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000159 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
160 {"uprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
161 {"uretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700162};
163
164typedef struct {
165 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800166 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700167 string name;
168 vector<char> data;
169 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800170 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700171
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700172 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700173} codeSection;
174
Joel Fernandesd76a2002018-10-16 13:19:58 -0700175static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
176 elfFile.seekg(0);
177 if (elfFile.fail()) return -1;
178
179 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
180
181 return 0;
182}
183
184/* Reads all section header tables into an Shdr array */
185static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
186 Elf64_Ehdr eh;
187 int ret = 0;
188
189 ret = readElfHeader(elfFile, &eh);
190 if (ret) return ret;
191
192 elfFile.seekg(eh.e_shoff);
193 if (elfFile.fail()) return -1;
194
195 /* Read shdr table entries */
196 shTable.resize(eh.e_shnum);
197
198 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
199
200 return 0;
201}
202
203/* Read a section by its index - for ex to get sec hdr strtab blob */
204static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
205 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800206 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700207 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700208
209 elfFile.seekg(shTable[id].sh_offset);
210 if (elfFile.fail()) return -1;
211
212 sec.resize(shTable[id].sh_size);
213 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
214
215 return 0;
216}
217
218/* Read whole section header string table */
219static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
220 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800221 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700222 if (ret) return ret;
223
224 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
225 if (ret) return ret;
226
227 return 0;
228}
229
230/* Get name from offset in strtab */
231static int getSymName(ifstream& elfFile, int nameOff, string& name) {
232 int ret;
233 vector<char> secStrTab;
234
235 ret = readSectionHeaderStrtab(elfFile, secStrTab);
236 if (ret) return ret;
237
238 if (nameOff >= (int)secStrTab.size()) return -1;
239
240 name = string((char*)secStrTab.data() + nameOff);
241 return 0;
242}
243
244/* Reads a full section by name - example to get the GPL license */
245static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
246 vector<char> secStrTab;
247 vector<Elf64_Shdr> shTable;
248 int ret;
249
250 ret = readSectionHeadersAll(elfFile, shTable);
251 if (ret) return ret;
252
253 ret = readSectionHeaderStrtab(elfFile, secStrTab);
254 if (ret) return ret;
255
256 for (int i = 0; i < (int)shTable.size(); i++) {
257 char* secname = secStrTab.data() + shTable[i].sh_name;
258 if (!secname) continue;
259
260 if (!strcmp(secname, name)) {
261 vector<char> dataTmp;
262 dataTmp.resize(shTable[i].sh_size);
263
264 elfFile.seekg(shTable[i].sh_offset);
265 if (elfFile.fail()) return -1;
266
267 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
268
269 data = dataTmp;
270 return 0;
271 }
272 }
273 return -2;
274}
275
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700276unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800277 vector<char> theBytes;
278 int ret = readSectionByName(name, elfFile, theBytes);
279 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700280 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800281 return defVal;
282 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700283 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800284 return defVal;
285 } else {
286 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
287 unsigned int value = static_cast<unsigned char>(theBytes[3]);
288 value <<= 8;
289 value += static_cast<unsigned char>(theBytes[2]);
290 value <<= 8;
291 value += static_cast<unsigned char>(theBytes[1]);
292 value <<= 8;
293 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700294 ALOGI("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800295 return value;
296 }
297}
298
Joel Fernandesd76a2002018-10-16 13:19:58 -0700299static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
300 int ret;
301 vector<Elf64_Shdr> shTable;
302
303 ret = readSectionHeadersAll(elfFile, shTable);
304 if (ret) return ret;
305
306 for (int i = 0; i < (int)shTable.size(); i++) {
307 if ((int)shTable[i].sh_type != type) continue;
308
309 vector<char> dataTmp;
310 dataTmp.resize(shTable[i].sh_size);
311
312 elfFile.seekg(shTable[i].sh_offset);
313 if (elfFile.fail()) return -1;
314
315 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
316
317 data = dataTmp;
318 return 0;
319 }
320 return -2;
321}
322
323static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
324 return (a.st_value < b.st_value);
325}
326
327static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
328 int ret, numElems;
329 Elf64_Sym* buf;
330 vector<char> secData;
331
332 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
333 if (ret) return ret;
334
335 buf = (Elf64_Sym*)secData.data();
336 numElems = (secData.size() / sizeof(Elf64_Sym));
337 data.assign(buf, buf + numElems);
338
339 if (sort) std::sort(data.begin(), data.end(), symCompare);
340 return 0;
341}
342
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700343static enum bpf_prog_type getFuseProgType() {
344 int result = BPF_PROG_TYPE_UNSPEC;
345 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
346 return static_cast<bpf_prog_type>(result);
347}
348
Joel Fernandesd76a2002018-10-16 13:19:58 -0700349static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800350 for (auto& snt : sectionNameTypes)
351 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700352
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000353 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700354 if (StartsWith(name, "fuse/")) return getFuseProgType();
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000355
Joel Fernandesd76a2002018-10-16 13:19:58 -0700356 return BPF_PROG_TYPE_UNSPEC;
357}
358
Tyler Wear4e2f4602022-02-03 09:46:01 -0800359static enum bpf_attach_type getExpectedAttachType(string& name) {
360 for (auto& snt : sectionNameTypes)
361 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
362 return BPF_ATTACH_TYPE_UNSPEC;
363}
364
Joel Fernandesd76a2002018-10-16 13:19:58 -0700365static string getSectionName(enum bpf_prog_type type)
366{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800367 for (auto& snt : sectionNameTypes)
368 if (snt.type == type)
369 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700370
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800371 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700372}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700373
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800374static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
375 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800376 vector<char> pdData;
377 int ret = readSectionByName("progs", elfFile, pdData);
Connor O'Brien3278a162020-02-13 21:45:22 -0800378 if (ret) return ret;
379
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800380 if (pdData.size() % sizeOfBpfProgDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700381 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800382 pdData.size(), sizeOfBpfProgDef);
383 return -1;
384 };
385
386 int progCount = pdData.size() / sizeOfBpfProgDef;
387 pd.resize(progCount);
388 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
389
390 const char* dataPtr = pdData.data();
391 for (auto& p : pd) {
392 // First we zero initialize
393 memset(&p, 0, sizeof(p));
394 // Then we set non-zero defaults
395 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
396 // Then we copy over the structure prefix from the ELF file.
397 memcpy(&p, dataPtr, trimmedSize);
398 // Move to next struct in the ELF file
399 dataPtr += sizeOfBpfProgDef;
400 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800401 return 0;
402}
403
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800404static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
405 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800406 int ret;
407 string name;
408 vector<Elf64_Sym> symtab;
409 vector<Elf64_Shdr> shTable;
410
411 ret = readSymTab(elfFile, 1 /* sort */, symtab);
412 if (ret) return ret;
413
414 /* Get index of section */
415 ret = readSectionHeadersAll(elfFile, shTable);
416 if (ret) return ret;
417
418 int sec_idx = -1;
419 for (int i = 0; i < (int)shTable.size(); i++) {
420 ret = getSymName(elfFile, shTable[i].sh_name, name);
421 if (ret) return ret;
422
423 if (!name.compare(sectionName)) {
424 sec_idx = i;
425 break;
426 }
427 }
428
429 /* No section found with matching name*/
430 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700431 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800432 return -1;
433 }
434
435 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800436 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
437
Connor O'Brien3278a162020-02-13 21:45:22 -0800438 if (symtab[i].st_shndx == sec_idx) {
439 string s;
440 ret = getSymName(elfFile, symtab[i].st_name, s);
441 if (ret) return ret;
442 names.push_back(s);
443 }
444 }
445
446 return 0;
447}
448
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800449static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
450 if (allowed == nullptr) return true;
451
452 for (size_t i = 0; i < numAllowed; i++) {
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700453 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
454 if (type == getFuseProgType()) return true;
455 } else if (type == allowed[i])
456 return true;
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800457 }
458
459 return false;
460}
461
Joel Fernandesd76a2002018-10-16 13:19:58 -0700462/* Read a section by its index - for ex to get sec hdr strtab blob */
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800463static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef,
464 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700465 vector<Elf64_Shdr> shTable;
466 int entries, ret = 0;
467
468 ret = readSectionHeadersAll(elfFile, shTable);
469 if (ret) return ret;
470 entries = shTable.size();
471
Connor O'Brien3278a162020-02-13 21:45:22 -0800472 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800473 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800474 if (ret) return ret;
475 vector<string> progDefNames;
476 ret = getSectionSymNames(elfFile, "progs", progDefNames);
477 if (!pd.empty() && ret) return ret;
478
Joel Fernandesd76a2002018-10-16 13:19:58 -0700479 for (int i = 0; i < entries; i++) {
480 string name;
481 codeSection cs_temp;
482 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
483
484 ret = getSymName(elfFile, shTable[i].sh_name, name);
485 if (ret) return ret;
486
487 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800488
Tyler Wear4e2f4602022-02-03 09:46:01 -0800489 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800490
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800491 if (!IsAllowed(ptype, allowed, numAllowed)) {
492 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
493 return -1;
494 }
495
Tyler Wear4e2f4602022-02-03 09:46:01 -0800496 // This must be done before '/' is replaced with '_'.
497 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800498
Tyler Wear4e2f4602022-02-03 09:46:01 -0800499 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700500
Tyler Wear4e2f4602022-02-03 09:46:01 -0800501 // convert all slashes to underscores
502 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800503
Tyler Wear4e2f4602022-02-03 09:46:01 -0800504 cs_temp.type = ptype;
505 cs_temp.name = name;
506
507 ret = readSectionByIdx(elfFile, i, cs_temp.data);
508 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700509 ALOGD("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800510
511 vector<string> csSymNames;
512 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
513 if (ret || !csSymNames.size()) return ret;
514 for (size_t i = 0; i < progDefNames.size(); ++i) {
515 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
516 cs_temp.prog_def = pd[i];
517 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800518 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700519 }
520
521 /* Check for rel section */
522 if (cs_temp.data.size() > 0 && i < entries) {
523 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
524 if (ret) return ret;
525
Tyler Wear4e2f4602022-02-03 09:46:01 -0800526 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700527 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
528 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700529 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700530 }
531 }
532
533 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700534 cs.push_back(std::move(cs_temp));
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700535 ALOGD("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700536 }
537 }
538 return 0;
539}
540
541static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
542 vector<Elf64_Sym> symtab;
543 int ret = 0;
544
545 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
546 if (ret) return ret;
547
548 if (index >= (int)symtab.size()) return -1;
549
550 return getSymName(elfFile, symtab[index].st_name, name);
551}
552
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700553static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
554 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700555 // Assuming fd is a valid Bpf Map file descriptor then
556 // all the following should always succeed on a 4.14+ kernel.
557 // If they somehow do fail, they'll return -1 (and set errno),
558 // which should then cause (among others) a key_size mismatch.
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700559 int fd_type = bpfGetFdMapType(fd);
560 int fd_key_size = bpfGetFdKeySize(fd);
561 int fd_value_size = bpfGetFdValueSize(fd);
562 int fd_max_entries = bpfGetFdMaxEntries(fd);
563 int fd_map_flags = bpfGetFdMapFlags(fd);
564
565 // DEVMAPs are readonly from the bpf program side's point of view, as such
566 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
567 int desired_map_flags = (int)mapDef.map_flags;
568 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
569 desired_map_flags |= BPF_F_RDONLY_PROG;
570
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000571 // The .h file enforces that this is a power of two, and page size will
572 // also always be a power of two, so this logic is actually enough to
573 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000574 unsigned int desired_max_entries = mapDef.max_entries;
575 if (type == BPF_MAP_TYPE_RINGBUF) {
576 if (desired_max_entries < page_size) desired_max_entries = page_size;
577 }
578
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700579 // The following checks should *never* trigger, if one of them somehow does,
580 // it probably means a bpf .o file has been changed/replaced at runtime
581 // and bpfloader was manually rerun (normally it should only run *once*
582 // early during the boot process).
583 // Another possibility is that something is misconfigured in the code:
584 // most likely a shared map is declared twice differently.
585 // But such a change should never be checked into the source tree...
586 if ((fd_type == type) &&
587 (fd_key_size == (int)mapDef.key_size) &&
588 (fd_value_size == (int)mapDef.value_size) &&
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000589 (fd_max_entries == (int)desired_max_entries) &&
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700590 (fd_map_flags == desired_map_flags)) {
591 return true;
592 }
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700593
594 ALOGE("bpf map name %s mismatch: desired/found: "
595 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
596 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
597 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
598 return false;
599}
600
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800601static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700602 const char* prefix, const unsigned long long allowedDomainBitmask,
603 const size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700604 int ret;
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700605 vector<char> mdData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700606 vector<struct bpf_map_def> md;
607 vector<string> mapNames;
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700608 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700609
610 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800611 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700612 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800613
614 if (mdData.size() % sizeOfBpfMapDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700615 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800616 mdData.size(), sizeOfBpfMapDef);
617 return -1;
618 };
619
620 int mapCount = mdData.size() / sizeOfBpfMapDef;
621 md.resize(mapCount);
622 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
623
624 const char* dataPtr = mdData.data();
625 for (auto& m : md) {
626 // First we zero initialize
627 memset(&m, 0, sizeof(m));
628 // Then we set non-zero defaults
629 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700630 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800631 // Then we copy over the structure prefix from the ELF file.
632 memcpy(&m, dataPtr, trimmedSize);
633 // Move to next struct in the ELF file
634 dataPtr += sizeOfBpfMapDef;
635 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700636
Connor O'Brien3278a162020-02-13 21:45:22 -0800637 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700638 if (ret) return ret;
639
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700640 unsigned kvers = kernelVersion();
641
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700642 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +0000643 if (md[i].zero != 0) abort();
644
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700645 if (kvers < md[i].min_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700646 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700647 mapNames[i].c_str(), kvers, md[i].min_kver);
648 mapFds.push_back(unique_fd());
649 continue;
650 }
651
652 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700653 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700654 mapNames[i].c_str(), kvers, md[i].max_kver);
655 mapFds.push_back(unique_fd());
656 continue;
657 }
658
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700659 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700660 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
661 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
662 // of be approximated: HASH has the same userspace visible api.
663 // However it cannot be used by ebpf programs in the same way.
664 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
665 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
666 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
667 // programs as being 5.4+...
668 type = BPF_MAP_TYPE_HASH;
669 }
670
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000671 // The .h file enforces that this is a power of two, and page size will
672 // also always be a power of two, so this logic is actually enough to
673 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000674 unsigned int max_entries = md[i].max_entries;
675 if (type == BPF_MAP_TYPE_RINGBUF) {
676 if (max_entries < page_size) max_entries = page_size;
677 }
678
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700679 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
680 if (specified(selinux_context)) {
681 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
682 ALOGE("map %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
683 mapNames[i].c_str(), selinux_context, allowedDomainBitmask);
684 return -EINVAL;
685 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700686 ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700687 md[i].selinux_context, selinux_context, lookupSelinuxContext(selinux_context),
688 lookupPinSubdir(selinux_context));
689 }
690
691 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
692 if (unrecognized(pin_subdir)) return -ENOTDIR;
693 if (specified(pin_subdir)) {
694 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
695 ALOGE("map %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)",
696 mapNames[i].c_str(), pin_subdir, allowedDomainBitmask);
697 return -EINVAL;
698 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700699 ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700700 pin_subdir, lookupPinSubdir(pin_subdir));
701 }
702
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700703 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
704 // except that maps shared across .o's have empty <objName>
705 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700706 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700707 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700708 bool reuse = false;
709 unique_fd fd;
710 int saved_errno;
711
Joel Fernandesd76a2002018-10-16 13:19:58 -0700712 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskieb199dd2022-07-01 03:21:40 -0700713 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800714 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700715 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700716 reuse = true;
717 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700718 union bpf_attr req = {
719 .map_type = type,
720 .key_size = md[i].key_size,
721 .value_size = md[i].value_size,
722 .max_entries = max_entries,
723 .map_flags = md[i].map_flags,
Connor O'Brien35425e52022-01-18 21:41:16 -0800724 };
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700725 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
726 fd.reset(bpf(BPF_MAP_CREATE, req));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800727 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700728 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700729 }
730
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700731 if (!fd.ok()) return -saved_errno;
732
733 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
734 // safety (since reuse code path is rare) run these checks even if we just created it.
735 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
736 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700737
738 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700739 if (specified(selinux_context)) {
740 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700741 "tmp_map_" + objName + "_" + mapNames[i];
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700742 ret = bpfFdPin(fd, createLoc.c_str());
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700743 if (ret) {
744 int err = errno;
745 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
746 return -err;
747 }
Maciej Żenczykowskie15229f2023-04-17 07:16:33 +0000748 ret = renameat2(AT_FDCWD, createLoc.c_str(),
749 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700750 if (ret) {
751 int err = errno;
752 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
753 err, strerror(err));
754 return -err;
755 }
756 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700757 ret = bpfFdPin(fd, mapPinLoc.c_str());
Maciej Żenczykowskid8259aa2022-06-27 10:02:20 -0700758 if (ret) {
759 int err = errno;
760 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
761 return -err;
762 }
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700763 }
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800764 ret = chmod(mapPinLoc.c_str(), md[i].mode);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700765 if (ret) {
766 int err = errno;
767 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
768 strerror(err));
769 return -err;
770 }
Maciej Żenczykowski5e4aabf2022-06-27 01:15:53 -0700771 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
772 if (ret) {
773 int err = errno;
774 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
775 ret, err, strerror(err));
776 return -err;
777 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700778 }
779
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700780 int mapId = bpfGetFdMapId(fd);
781 if (mapId == -1) {
782 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700783 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700784 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700785 }
786
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700787 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700788 }
789
790 return ret;
791}
792
793/* For debugging, dump all instructions */
794static void dumpIns(char* ins, int size) {
795 for (int row = 0; row < size / 8; row++) {
796 ALOGE("%d: ", row);
797 for (int j = 0; j < 8; j++) {
798 ALOGE("%3x ", ins[(row * 8) + j]);
799 }
800 ALOGE("\n");
801 }
802}
803
804/* For debugging, dump all code sections from cs list */
805static void dumpAllCs(vector<codeSection>& cs) {
806 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700807 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700808 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700809 ALOGE("-----------");
Joel Fernandesd76a2002018-10-16 13:19:58 -0700810 }
811}
812
813static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
814 int insnIndex;
815 struct bpf_insn *insn, *insns;
816
817 insns = (struct bpf_insn*)(insnsPtr);
818
819 insnIndex = offset / sizeof(struct bpf_insn);
820 insn = &insns[insnIndex];
821
Maciej Żenczykowski509b1b92023-03-07 01:11:20 +0000822 // Occasionally might be useful for relocation debugging, but pretty spammy
823 if (0) {
824 ALOGD("applying relo to instruction at byte offset: %llu, "
825 "insn offset %d, insn %llx",
826 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
827 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700828
829 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700830 ALOGE("Dumping all instructions till ins %d", insnIndex);
831 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700832 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
833 return;
834 }
835
836 insn->imm = fd;
837 insn->src_reg = BPF_PSEUDO_MAP_FD;
838}
839
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700840static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700841 vector<string> mapNames;
842
Connor O'Brien3278a162020-02-13 21:45:22 -0800843 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700844 if (ret) return;
845
846 for (int k = 0; k != (int)cs.size(); k++) {
847 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
848 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
849
850 for (int i = 0; i < n_rel; i++) {
851 int symIndex = ELF64_R_SYM(rel[i].r_info);
852 string symName;
853
854 ret = getSymNameByIdx(elfFile, symIndex, symName);
855 if (ret) return;
856
857 /* Find the map fd and apply relo */
858 for (int j = 0; j < (int)mapNames.size(); j++) {
859 if (!mapNames[j].compare(symName)) {
860 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
861 break;
862 }
863 }
864 }
865 }
866}
867
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800868static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700869 const char* prefix, const unsigned long long allowedDomainBitmask) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800870 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700871
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000872 if (!kvers) {
873 ALOGE("unable to get kernel version");
874 return -EINVAL;
875 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700876
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700877 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700878
879 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700880 unique_fd& fd = cs[i].prog_fd;
881 int ret;
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700882 string name = cs[i].name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700883
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000884 if (!cs[i].prog_def.has_value()) {
885 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
886 return -EINVAL;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800887 }
888
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000889 unsigned min_kver = cs[i].prog_def->min_kver;
890 unsigned max_kver = cs[i].prog_def->max_kver;
891 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
892 max_kver, kvers);
893 if (kvers < min_kver) continue;
894 if (kvers >= max_kver) continue;
895
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000896 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
897 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000898
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700899 if (unrecognized(pin_subdir)) return -ENOTDIR;
900
901 if (specified(selinux_context)) {
902 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
903 ALOGE("prog %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
904 name.c_str(), selinux_context, allowedDomainBitmask);
905 return -EINVAL;
906 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700907 ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700908 cs[i].prog_def->selinux_context, selinux_context,
909 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
910 }
911
912 if (specified(pin_subdir)) {
913 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
914 ALOGE("prog %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)", name.c_str(),
915 pin_subdir, allowedDomainBitmask);
916 return -EINVAL;
917 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700918 ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700919 cs[i].prog_def->pin_subdir, pin_subdir, lookupPinSubdir(pin_subdir));
920 }
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800921
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700922 // strip any potential $foo suffix
923 // this can be used to provide duplicate programs
924 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700925 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700926
927 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700928 // Format of pin location is
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700929 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700930 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700931 objName + '_' + string(name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700932 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700933 fd.reset(retrieveProgram(progPinLoc.c_str()));
934 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
935 (!fd.ok() ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700936 reuse = true;
937 } else {
938 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
939
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700940 union bpf_attr req = {
941 .prog_type = cs[i].type,
942 .kern_version = kvers,
943 .license = ptr_to_u64(license.c_str()),
944 .insns = ptr_to_u64(cs[i].data.data()),
945 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
946 .log_level = 1,
947 .log_buf = ptr_to_u64(log_buf.data()),
948 .log_size = static_cast<__u32>(log_buf.size()),
949 .expected_attach_type = cs[i].expected_attach_type,
Tyler Wear4e2f4602022-02-03 09:46:01 -0800950 };
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700951 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
952 fd.reset(bpf(BPF_PROG_LOAD, req));
Tyler Wear4e2f4602022-02-03 09:46:01 -0800953
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700954 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
955 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
Tyler Wear4e2f4602022-02-03 09:46:01 -0800956
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700957 if (!fd.ok()) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800958 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800959
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700960 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700961 for (const auto& line : lines) ALOGW("%s", line.c_str());
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700962 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700963
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000964 if (cs[i].prog_def->optional) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700965 ALOGW("failed program is marked optional - continuing...");
966 continue;
967 }
968 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800969 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700970 }
971
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700972 if (!fd.ok()) return fd.get();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700973
974 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700975 if (specified(selinux_context)) {
976 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700977 "tmp_prog_" + objName + '_' + string(name);
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700978 ret = bpfFdPin(fd, createLoc.c_str());
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700979 if (ret) {
980 int err = errno;
981 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
982 return -err;
983 }
Maciej Żenczykowskie15229f2023-04-17 07:16:33 +0000984 ret = renameat2(AT_FDCWD, createLoc.c_str(),
985 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700986 if (ret) {
987 int err = errno;
988 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
989 err, strerror(err));
990 return -err;
991 }
992 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700993 ret = bpfFdPin(fd, progPinLoc.c_str());
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700994 if (ret) {
995 int err = errno;
996 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
997 return -err;
998 }
999 }
1000 if (chmod(progPinLoc.c_str(), 0440)) {
1001 int err = errno;
1002 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1003 return -err;
1004 }
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001005 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1006 (gid_t)cs[i].prog_def->gid)) {
1007 int err = errno;
1008 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1009 cs[i].prog_def->gid, err, strerror(err));
1010 return -err;
Connor O'Brien3278a162020-02-13 21:45:22 -08001011 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001012 }
1013
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001014 int progId = bpfGetFdProgId(fd);
1015 if (progId == -1) {
1016 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001017 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -07001018 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001019 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001020 }
1021
1022 return 0;
1023}
1024
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001025int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
Joel Fernandesd76a2002018-10-16 13:19:58 -07001026 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001027 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001028 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001029 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001030 int ret;
1031
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001032 if (!isCritical) return -1;
1033 *isCritical = false;
1034
Joel Fernandesd76a2002018-10-16 13:19:58 -07001035 ifstream elfFile(elfPath, ios::in | ios::binary);
1036 if (!elfFile.is_open()) return -1;
1037
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001038 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001039 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001040
Joel Fernandesd76a2002018-10-16 13:19:58 -07001041 ret = readSectionByName("license", elfFile, license);
1042 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001043 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001044 return ret;
1045 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001046 ALOGD("Loading %s%s ELF object %s with license %s",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001047 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001048 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -07001049 }
1050
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001051 // the following default values are for bpfloader V0.0 format which does not include them
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001052 size_t sizeOfBpfMapDef =
1053 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1054 size_t sizeOfBpfProgDef =
1055 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1056
Maciej Żenczykowskia5646cb2024-03-08 08:07:46 +00001057 ALOGI("Platform BpfLoader processing ELF object %s", elfPath);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001058
1059 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001060 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001061 DEFAULT_SIZEOF_BPF_MAP_DEF);
1062 return -1;
1063 }
1064
1065 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001066 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001067 DEFAULT_SIZEOF_BPF_PROG_DEF);
1068 return -1;
1069 }
1070
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001071 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, location.allowedProgTypes,
1072 location.allowedProgTypesLength);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001073 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001074 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001075 return ret;
1076 }
1077
1078 /* Just for future debugging */
1079 if (0) dumpAllCs(cs);
1080
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001081 ret = createMaps(elfPath, elfFile, mapFds, location.prefix, location.allowedDomainBitmask,
1082 sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001083 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001084 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001085 return ret;
1086 }
1087
1088 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001089 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001090
1091 applyMapRelo(elfFile, mapFds, cs);
1092
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001093 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix,
1094 location.allowedDomainBitmask);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001095 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001096
1097 return ret;
1098}
1099
Joel Fernandesd76a2002018-10-16 13:19:58 -07001100} // namespace bpf
1101} // namespace android