blob: 305c60ed03c82be6fbd36c5005fc6893dc70df78 [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 Żenczykowskic82f5662024-03-10 14:37:24 -0700374static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800375 vector<char> pdData;
376 int ret = readSectionByName("progs", elfFile, pdData);
Connor O'Brien3278a162020-02-13 21:45:22 -0800377 if (ret) return ret;
378
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700379 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700380 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700381 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800382 return -1;
383 };
384
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700385 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
386 memcpy(pd.data(), pdData.data(), pdData.size());
Connor O'Brien3278a162020-02-13 21:45:22 -0800387 return 0;
388}
389
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800390static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
391 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800392 int ret;
393 string name;
394 vector<Elf64_Sym> symtab;
395 vector<Elf64_Shdr> shTable;
396
397 ret = readSymTab(elfFile, 1 /* sort */, symtab);
398 if (ret) return ret;
399
400 /* Get index of section */
401 ret = readSectionHeadersAll(elfFile, shTable);
402 if (ret) return ret;
403
404 int sec_idx = -1;
405 for (int i = 0; i < (int)shTable.size(); i++) {
406 ret = getSymName(elfFile, shTable[i].sh_name, name);
407 if (ret) return ret;
408
409 if (!name.compare(sectionName)) {
410 sec_idx = i;
411 break;
412 }
413 }
414
415 /* No section found with matching name*/
416 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700417 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800418 return -1;
419 }
420
421 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800422 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
423
Connor O'Brien3278a162020-02-13 21:45:22 -0800424 if (symtab[i].st_shndx == sec_idx) {
425 string s;
426 ret = getSymName(elfFile, symtab[i].st_name, s);
427 if (ret) return ret;
428 names.push_back(s);
429 }
430 }
431
432 return 0;
433}
434
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800435static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
436 if (allowed == nullptr) return true;
437
438 for (size_t i = 0; i < numAllowed; i++) {
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700439 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
440 if (type == getFuseProgType()) return true;
441 } else if (type == allowed[i])
442 return true;
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800443 }
444
445 return false;
446}
447
Joel Fernandesd76a2002018-10-16 13:19:58 -0700448/* Read a section by its index - for ex to get sec hdr strtab blob */
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700449static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs,
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800450 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700451 vector<Elf64_Shdr> shTable;
452 int entries, ret = 0;
453
454 ret = readSectionHeadersAll(elfFile, shTable);
455 if (ret) return ret;
456 entries = shTable.size();
457
Connor O'Brien3278a162020-02-13 21:45:22 -0800458 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700459 ret = readProgDefs(elfFile, pd);
Connor O'Brien3278a162020-02-13 21:45:22 -0800460 if (ret) return ret;
461 vector<string> progDefNames;
462 ret = getSectionSymNames(elfFile, "progs", progDefNames);
463 if (!pd.empty() && ret) return ret;
464
Joel Fernandesd76a2002018-10-16 13:19:58 -0700465 for (int i = 0; i < entries; i++) {
466 string name;
467 codeSection cs_temp;
468 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
469
470 ret = getSymName(elfFile, shTable[i].sh_name, name);
471 if (ret) return ret;
472
473 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800474
Tyler Wear4e2f4602022-02-03 09:46:01 -0800475 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800476
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800477 if (!IsAllowed(ptype, allowed, numAllowed)) {
478 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
479 return -1;
480 }
481
Tyler Wear4e2f4602022-02-03 09:46:01 -0800482 // This must be done before '/' is replaced with '_'.
483 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800484
Tyler Wear4e2f4602022-02-03 09:46:01 -0800485 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700486
Tyler Wear4e2f4602022-02-03 09:46:01 -0800487 // convert all slashes to underscores
488 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800489
Tyler Wear4e2f4602022-02-03 09:46:01 -0800490 cs_temp.type = ptype;
491 cs_temp.name = name;
492
493 ret = readSectionByIdx(elfFile, i, cs_temp.data);
494 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700495 ALOGD("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800496
497 vector<string> csSymNames;
498 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
499 if (ret || !csSymNames.size()) return ret;
500 for (size_t i = 0; i < progDefNames.size(); ++i) {
501 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
502 cs_temp.prog_def = pd[i];
503 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800504 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700505 }
506
507 /* Check for rel section */
508 if (cs_temp.data.size() > 0 && i < entries) {
509 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
510 if (ret) return ret;
511
Tyler Wear4e2f4602022-02-03 09:46:01 -0800512 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700513 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
514 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700515 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700516 }
517 }
518
519 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700520 cs.push_back(std::move(cs_temp));
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700521 ALOGD("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700522 }
523 }
524 return 0;
525}
526
527static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
528 vector<Elf64_Sym> symtab;
529 int ret = 0;
530
531 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
532 if (ret) return ret;
533
534 if (index >= (int)symtab.size()) return -1;
535
536 return getSymName(elfFile, symtab[index].st_name, name);
537}
538
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700539static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
540 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700541 // Assuming fd is a valid Bpf Map file descriptor then
542 // all the following should always succeed on a 4.14+ kernel.
543 // If they somehow do fail, they'll return -1 (and set errno),
544 // which should then cause (among others) a key_size mismatch.
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700545 int fd_type = bpfGetFdMapType(fd);
546 int fd_key_size = bpfGetFdKeySize(fd);
547 int fd_value_size = bpfGetFdValueSize(fd);
548 int fd_max_entries = bpfGetFdMaxEntries(fd);
549 int fd_map_flags = bpfGetFdMapFlags(fd);
550
551 // DEVMAPs are readonly from the bpf program side's point of view, as such
552 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
553 int desired_map_flags = (int)mapDef.map_flags;
554 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
555 desired_map_flags |= BPF_F_RDONLY_PROG;
556
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000557 // The .h file enforces that this is a power of two, and page size will
558 // also always be a power of two, so this logic is actually enough to
559 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000560 unsigned int desired_max_entries = mapDef.max_entries;
561 if (type == BPF_MAP_TYPE_RINGBUF) {
562 if (desired_max_entries < page_size) desired_max_entries = page_size;
563 }
564
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700565 // The following checks should *never* trigger, if one of them somehow does,
566 // it probably means a bpf .o file has been changed/replaced at runtime
567 // and bpfloader was manually rerun (normally it should only run *once*
568 // early during the boot process).
569 // Another possibility is that something is misconfigured in the code:
570 // most likely a shared map is declared twice differently.
571 // But such a change should never be checked into the source tree...
572 if ((fd_type == type) &&
573 (fd_key_size == (int)mapDef.key_size) &&
574 (fd_value_size == (int)mapDef.value_size) &&
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000575 (fd_max_entries == (int)desired_max_entries) &&
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700576 (fd_map_flags == desired_map_flags)) {
577 return true;
578 }
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700579
580 ALOGE("bpf map name %s mismatch: desired/found: "
581 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
582 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
583 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
584 return false;
585}
586
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800587static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700588 const char* prefix, const unsigned long long allowedDomainBitmask) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700589 int ret;
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700590 vector<char> mdData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700591 vector<struct bpf_map_def> md;
592 vector<string> mapNames;
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700593 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700594
595 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800596 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700597 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800598
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700599 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700600 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700601 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800602 return -1;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800603 }
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700604 md.resize(mdData.size() / sizeof(struct bpf_map_def));
605 memcpy(md.data(), mdData.data(), mdData.size());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700606
Connor O'Brien3278a162020-02-13 21:45:22 -0800607 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700608 if (ret) return ret;
609
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700610 unsigned kvers = kernelVersion();
611
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700612 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +0000613 if (md[i].zero != 0) abort();
614
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700615 if (kvers < md[i].min_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700616 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700617 mapNames[i].c_str(), kvers, md[i].min_kver);
618 mapFds.push_back(unique_fd());
619 continue;
620 }
621
622 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700623 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700624 mapNames[i].c_str(), kvers, md[i].max_kver);
625 mapFds.push_back(unique_fd());
626 continue;
627 }
628
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700629 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700630 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
631 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
632 // of be approximated: HASH has the same userspace visible api.
633 // However it cannot be used by ebpf programs in the same way.
634 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
635 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
636 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
637 // programs as being 5.4+...
638 type = BPF_MAP_TYPE_HASH;
639 }
640
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000641 // The .h file enforces that this is a power of two, and page size will
642 // also always be a power of two, so this logic is actually enough to
643 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000644 unsigned int max_entries = md[i].max_entries;
645 if (type == BPF_MAP_TYPE_RINGBUF) {
646 if (max_entries < page_size) max_entries = page_size;
647 }
648
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700649 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
650 if (specified(selinux_context)) {
651 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
652 ALOGE("map %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
653 mapNames[i].c_str(), selinux_context, allowedDomainBitmask);
654 return -EINVAL;
655 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700656 ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700657 md[i].selinux_context, selinux_context, lookupSelinuxContext(selinux_context),
658 lookupPinSubdir(selinux_context));
659 }
660
661 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
662 if (unrecognized(pin_subdir)) return -ENOTDIR;
663 if (specified(pin_subdir)) {
664 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
665 ALOGE("map %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)",
666 mapNames[i].c_str(), pin_subdir, allowedDomainBitmask);
667 return -EINVAL;
668 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700669 ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700670 pin_subdir, lookupPinSubdir(pin_subdir));
671 }
672
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700673 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
674 // except that maps shared across .o's have empty <objName>
675 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700676 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700677 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700678 bool reuse = false;
679 unique_fd fd;
680 int saved_errno;
681
Joel Fernandesd76a2002018-10-16 13:19:58 -0700682 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskieb199dd2022-07-01 03:21:40 -0700683 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800684 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700685 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700686 reuse = true;
687 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700688 union bpf_attr req = {
689 .map_type = type,
690 .key_size = md[i].key_size,
691 .value_size = md[i].value_size,
692 .max_entries = max_entries,
693 .map_flags = md[i].map_flags,
Connor O'Brien35425e52022-01-18 21:41:16 -0800694 };
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700695 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
696 fd.reset(bpf(BPF_MAP_CREATE, req));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800697 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700698 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700699 }
700
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700701 if (!fd.ok()) return -saved_errno;
702
703 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
704 // safety (since reuse code path is rare) run these checks even if we just created it.
705 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
706 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700707
708 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700709 if (specified(selinux_context)) {
710 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700711 "tmp_map_" + objName + "_" + mapNames[i];
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700712 ret = bpfFdPin(fd, createLoc.c_str());
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700713 if (ret) {
714 int err = errno;
715 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
716 return -err;
717 }
Maciej Żenczykowskie15229f2023-04-17 07:16:33 +0000718 ret = renameat2(AT_FDCWD, createLoc.c_str(),
719 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700720 if (ret) {
721 int err = errno;
722 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
723 err, strerror(err));
724 return -err;
725 }
726 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700727 ret = bpfFdPin(fd, mapPinLoc.c_str());
Maciej Żenczykowskid8259aa2022-06-27 10:02:20 -0700728 if (ret) {
729 int err = errno;
730 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
731 return -err;
732 }
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700733 }
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800734 ret = chmod(mapPinLoc.c_str(), md[i].mode);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700735 if (ret) {
736 int err = errno;
737 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
738 strerror(err));
739 return -err;
740 }
Maciej Żenczykowski5e4aabf2022-06-27 01:15:53 -0700741 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
742 if (ret) {
743 int err = errno;
744 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
745 ret, err, strerror(err));
746 return -err;
747 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700748 }
749
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700750 int mapId = bpfGetFdMapId(fd);
751 if (mapId == -1) {
752 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700753 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700754 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700755 }
756
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700757 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700758 }
759
760 return ret;
761}
762
763/* For debugging, dump all instructions */
764static void dumpIns(char* ins, int size) {
765 for (int row = 0; row < size / 8; row++) {
766 ALOGE("%d: ", row);
767 for (int j = 0; j < 8; j++) {
768 ALOGE("%3x ", ins[(row * 8) + j]);
769 }
770 ALOGE("\n");
771 }
772}
773
774/* For debugging, dump all code sections from cs list */
775static void dumpAllCs(vector<codeSection>& cs) {
776 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700777 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700778 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700779 ALOGE("-----------");
Joel Fernandesd76a2002018-10-16 13:19:58 -0700780 }
781}
782
783static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
784 int insnIndex;
785 struct bpf_insn *insn, *insns;
786
787 insns = (struct bpf_insn*)(insnsPtr);
788
789 insnIndex = offset / sizeof(struct bpf_insn);
790 insn = &insns[insnIndex];
791
Maciej Żenczykowski509b1b92023-03-07 01:11:20 +0000792 // Occasionally might be useful for relocation debugging, but pretty spammy
793 if (0) {
794 ALOGD("applying relo to instruction at byte offset: %llu, "
795 "insn offset %d, insn %llx",
796 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
797 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700798
799 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700800 ALOGE("Dumping all instructions till ins %d", insnIndex);
801 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700802 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
803 return;
804 }
805
806 insn->imm = fd;
807 insn->src_reg = BPF_PSEUDO_MAP_FD;
808}
809
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700810static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700811 vector<string> mapNames;
812
Connor O'Brien3278a162020-02-13 21:45:22 -0800813 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700814 if (ret) return;
815
816 for (int k = 0; k != (int)cs.size(); k++) {
817 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
818 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
819
820 for (int i = 0; i < n_rel; i++) {
821 int symIndex = ELF64_R_SYM(rel[i].r_info);
822 string symName;
823
824 ret = getSymNameByIdx(elfFile, symIndex, symName);
825 if (ret) return;
826
827 /* Find the map fd and apply relo */
828 for (int j = 0; j < (int)mapNames.size(); j++) {
829 if (!mapNames[j].compare(symName)) {
830 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
831 break;
832 }
833 }
834 }
835 }
836}
837
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800838static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700839 const char* prefix, const unsigned long long allowedDomainBitmask) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800840 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700841
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000842 if (!kvers) {
843 ALOGE("unable to get kernel version");
844 return -EINVAL;
845 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700846
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700847 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700848
849 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700850 unique_fd& fd = cs[i].prog_fd;
851 int ret;
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700852 string name = cs[i].name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700853
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000854 if (!cs[i].prog_def.has_value()) {
855 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
856 return -EINVAL;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800857 }
858
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000859 unsigned min_kver = cs[i].prog_def->min_kver;
860 unsigned max_kver = cs[i].prog_def->max_kver;
861 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
862 max_kver, kvers);
863 if (kvers < min_kver) continue;
864 if (kvers >= max_kver) continue;
865
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000866 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
867 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000868
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700869 if (unrecognized(pin_subdir)) return -ENOTDIR;
870
871 if (specified(selinux_context)) {
872 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
873 ALOGE("prog %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
874 name.c_str(), selinux_context, allowedDomainBitmask);
875 return -EINVAL;
876 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700877 ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700878 cs[i].prog_def->selinux_context, selinux_context,
879 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
880 }
881
882 if (specified(pin_subdir)) {
883 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
884 ALOGE("prog %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)", name.c_str(),
885 pin_subdir, allowedDomainBitmask);
886 return -EINVAL;
887 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700888 ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700889 cs[i].prog_def->pin_subdir, pin_subdir, lookupPinSubdir(pin_subdir));
890 }
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800891
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700892 // strip any potential $foo suffix
893 // this can be used to provide duplicate programs
894 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700895 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700896
897 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700898 // Format of pin location is
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700899 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700900 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700901 objName + '_' + string(name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700902 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700903 fd.reset(retrieveProgram(progPinLoc.c_str()));
904 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
905 (!fd.ok() ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700906 reuse = true;
907 } else {
908 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
909
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700910 union bpf_attr req = {
911 .prog_type = cs[i].type,
912 .kern_version = kvers,
913 .license = ptr_to_u64(license.c_str()),
914 .insns = ptr_to_u64(cs[i].data.data()),
915 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
916 .log_level = 1,
917 .log_buf = ptr_to_u64(log_buf.data()),
918 .log_size = static_cast<__u32>(log_buf.size()),
919 .expected_attach_type = cs[i].expected_attach_type,
Tyler Wear4e2f4602022-02-03 09:46:01 -0800920 };
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700921 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
922 fd.reset(bpf(BPF_PROG_LOAD, req));
Tyler Wear4e2f4602022-02-03 09:46:01 -0800923
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700924 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
925 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
Tyler Wear4e2f4602022-02-03 09:46:01 -0800926
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700927 if (!fd.ok()) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800928 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800929
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700930 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700931 for (const auto& line : lines) ALOGW("%s", line.c_str());
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700932 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700933
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000934 if (cs[i].prog_def->optional) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700935 ALOGW("failed program is marked optional - continuing...");
936 continue;
937 }
938 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800939 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700940 }
941
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700942 if (!fd.ok()) return fd.get();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700943
944 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700945 if (specified(selinux_context)) {
946 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700947 "tmp_prog_" + objName + '_' + string(name);
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700948 ret = bpfFdPin(fd, createLoc.c_str());
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700949 if (ret) {
950 int err = errno;
951 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
952 return -err;
953 }
Maciej Żenczykowskie15229f2023-04-17 07:16:33 +0000954 ret = renameat2(AT_FDCWD, createLoc.c_str(),
955 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700956 if (ret) {
957 int err = errno;
958 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
959 err, strerror(err));
960 return -err;
961 }
962 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700963 ret = bpfFdPin(fd, progPinLoc.c_str());
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700964 if (ret) {
965 int err = errno;
966 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
967 return -err;
968 }
969 }
970 if (chmod(progPinLoc.c_str(), 0440)) {
971 int err = errno;
972 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
973 return -err;
974 }
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000975 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
976 (gid_t)cs[i].prog_def->gid)) {
977 int err = errno;
978 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
979 cs[i].prog_def->gid, err, strerror(err));
980 return -err;
Connor O'Brien3278a162020-02-13 21:45:22 -0800981 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700982 }
983
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700984 int progId = bpfGetFdProgId(fd);
985 if (progId == -1) {
986 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700987 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700988 ALOGI("prog %s id %d", progPinLoc.c_str(), progId);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700989 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700990 }
991
992 return 0;
993}
994
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -0800995int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700996 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700997 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700998 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700999 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001000 int ret;
1001
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001002 if (!isCritical) return -1;
1003 *isCritical = false;
1004
Joel Fernandesd76a2002018-10-16 13:19:58 -07001005 ifstream elfFile(elfPath, ios::in | ios::binary);
1006 if (!elfFile.is_open()) return -1;
1007
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001008 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001009 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001010
Joel Fernandesd76a2002018-10-16 13:19:58 -07001011 ret = readSectionByName("license", elfFile, license);
1012 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001013 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001014 return ret;
1015 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001016 ALOGD("Loading %s%s ELF object %s with license %s",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001017 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001018 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -07001019 }
1020
Maciej Żenczykowskia5646cb2024-03-08 08:07:46 +00001021 ALOGI("Platform BpfLoader processing ELF object %s", elfPath);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001022
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -07001023 ret = readCodeSections(elfFile, cs, location.allowedProgTypes, location.allowedProgTypesLength);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001024 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001025 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001026 return ret;
1027 }
1028
1029 /* Just for future debugging */
1030 if (0) dumpAllCs(cs);
1031
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -07001032 ret = createMaps(elfPath, elfFile, mapFds, location.prefix, location.allowedDomainBitmask);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001033 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001034 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001035 return ret;
1036 }
1037
1038 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001039 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001040
1041 applyMapRelo(elfFile, mapFds, cs);
1042
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001043 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix,
1044 location.allowedDomainBitmask);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001045 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001046
1047 return ret;
1048}
1049
Joel Fernandesd76a2002018-10-16 13:19:58 -07001050} // namespace bpf
1051} // namespace android