blob: 940ce191ac2ed56c0bb66dbcb26c8facbcc18e07 [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
Maciej Żenczykowskie2f2b822024-05-01 05:16:51 -070017#define LOG_TAG "BpfLoader"
Joel Fernandesd76a2002018-10-16 13:19:58 -070018
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"
Maciej Żenczykowski1b444552024-08-19 17:43:40 -070036#include "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>
Maciej Żenczykowski6d4d9d82024-08-06 15:32:00 -070049#include <android-base/logging.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
Maciej Żenczykowski6d4d9d82024-08-06 15:32:00 -070058using android::base::EndsWith;
Joel Fernandesd76a2002018-10-16 13:19:58 -070059using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070060using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070061using std::ifstream;
62using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080063using std::optional;
Maciej Żenczykowski6d4d9d82024-08-06 15:32:00 -070064using std::strerror;
Christopher Ferrisc151c672019-02-01 15:31:26 -080065using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070066using std::vector;
67
68namespace android {
69namespace bpf {
70
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +000071static unsigned int page_size = static_cast<unsigned int>(getpagesize());
72
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -070073static string pathToObjName(const string& path) {
74 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
75 string filename = android::base::Split(path, "/").back();
76 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
77 string name = filename.substr(0, filename.find_last_of('.'));
78 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
79 // this can be used to provide duplicate programs (mux based on the bpfloader version)
80 return name.substr(0, name.find_last_of('@'));
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -080081}
82
Joel Fernandesd76a2002018-10-16 13:19:58 -070083typedef struct {
84 const char* name;
85 enum bpf_prog_type type;
86} sectionType;
87
88/*
89 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070090 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -070091 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070092 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -070093 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070094 *
95 * However, be aware that you should not be directly using the SECTION() macro.
96 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -070097 */
98sectionType sectionNameTypes[] = {
Maciej Żenczykowski119ad752024-08-12 17:41:09 +000099 {"kprobe/", BPF_PROG_TYPE_KPROBE},
100 {"kretprobe/", BPF_PROG_TYPE_KPROBE},
101 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT},
102 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
103 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT},
104 {"uprobe/", BPF_PROG_TYPE_KPROBE},
105 {"uretprobe/", BPF_PROG_TYPE_KPROBE},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700106};
107
108typedef struct {
109 enum bpf_prog_type type;
110 string name;
111 vector<char> data;
112 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800113 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700114
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700115 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700116} codeSection;
117
Joel Fernandesd76a2002018-10-16 13:19:58 -0700118static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
119 elfFile.seekg(0);
120 if (elfFile.fail()) return -1;
121
122 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
123
124 return 0;
125}
126
127/* Reads all section header tables into an Shdr array */
128static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
129 Elf64_Ehdr eh;
130 int ret = 0;
131
132 ret = readElfHeader(elfFile, &eh);
133 if (ret) return ret;
134
135 elfFile.seekg(eh.e_shoff);
136 if (elfFile.fail()) return -1;
137
138 /* Read shdr table entries */
139 shTable.resize(eh.e_shnum);
140
141 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
142
143 return 0;
144}
145
146/* Read a section by its index - for ex to get sec hdr strtab blob */
147static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
148 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800149 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700150 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700151
152 elfFile.seekg(shTable[id].sh_offset);
153 if (elfFile.fail()) return -1;
154
155 sec.resize(shTable[id].sh_size);
156 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
157
158 return 0;
159}
160
161/* Read whole section header string table */
162static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
163 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800164 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700165 if (ret) return ret;
166
167 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
168 if (ret) return ret;
169
170 return 0;
171}
172
173/* Get name from offset in strtab */
174static int getSymName(ifstream& elfFile, int nameOff, string& name) {
175 int ret;
176 vector<char> secStrTab;
177
178 ret = readSectionHeaderStrtab(elfFile, secStrTab);
179 if (ret) return ret;
180
181 if (nameOff >= (int)secStrTab.size()) return -1;
182
183 name = string((char*)secStrTab.data() + nameOff);
184 return 0;
185}
186
187/* Reads a full section by name - example to get the GPL license */
188static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
189 vector<char> secStrTab;
190 vector<Elf64_Shdr> shTable;
191 int ret;
192
193 ret = readSectionHeadersAll(elfFile, shTable);
194 if (ret) return ret;
195
196 ret = readSectionHeaderStrtab(elfFile, secStrTab);
197 if (ret) return ret;
198
199 for (int i = 0; i < (int)shTable.size(); i++) {
200 char* secname = secStrTab.data() + shTable[i].sh_name;
201 if (!secname) continue;
202
203 if (!strcmp(secname, name)) {
204 vector<char> dataTmp;
205 dataTmp.resize(shTable[i].sh_size);
206
207 elfFile.seekg(shTable[i].sh_offset);
208 if (elfFile.fail()) return -1;
209
210 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
211
212 data = dataTmp;
213 return 0;
214 }
215 }
216 return -2;
217}
218
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700219unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800220 vector<char> theBytes;
221 int ret = readSectionByName(name, elfFile, theBytes);
222 if (ret) {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700223 ALOGV("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800224 return defVal;
225 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700226 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800227 return defVal;
228 } else {
229 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
230 unsigned int value = static_cast<unsigned char>(theBytes[3]);
231 value <<= 8;
232 value += static_cast<unsigned char>(theBytes[2]);
233 value <<= 8;
234 value += static_cast<unsigned char>(theBytes[1]);
235 value <<= 8;
236 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700237 ALOGV("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800238 return value;
239 }
240}
241
Joel Fernandesd76a2002018-10-16 13:19:58 -0700242static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
243 int ret;
244 vector<Elf64_Shdr> shTable;
245
246 ret = readSectionHeadersAll(elfFile, shTable);
247 if (ret) return ret;
248
249 for (int i = 0; i < (int)shTable.size(); i++) {
250 if ((int)shTable[i].sh_type != type) continue;
251
252 vector<char> dataTmp;
253 dataTmp.resize(shTable[i].sh_size);
254
255 elfFile.seekg(shTable[i].sh_offset);
256 if (elfFile.fail()) return -1;
257
258 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
259
260 data = dataTmp;
261 return 0;
262 }
263 return -2;
264}
265
266static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
267 return (a.st_value < b.st_value);
268}
269
270static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
271 int ret, numElems;
272 Elf64_Sym* buf;
273 vector<char> secData;
274
275 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
276 if (ret) return ret;
277
278 buf = (Elf64_Sym*)secData.data();
279 numElems = (secData.size() / sizeof(Elf64_Sym));
280 data.assign(buf, buf + numElems);
281
282 if (sort) std::sort(data.begin(), data.end(), symCompare);
283 return 0;
284}
285
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700286static enum bpf_prog_type getFuseProgType() {
287 int result = BPF_PROG_TYPE_UNSPEC;
288 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
289 return static_cast<bpf_prog_type>(result);
290}
291
Joel Fernandesd76a2002018-10-16 13:19:58 -0700292static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800293 for (auto& snt : sectionNameTypes)
294 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700295
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000296 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700297 if (StartsWith(name, "fuse/")) return getFuseProgType();
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000298
Joel Fernandesd76a2002018-10-16 13:19:58 -0700299 return BPF_PROG_TYPE_UNSPEC;
300}
301
Joel Fernandesd76a2002018-10-16 13:19:58 -0700302static string getSectionName(enum bpf_prog_type type)
303{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800304 for (auto& snt : sectionNameTypes)
305 if (snt.type == type)
306 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700307
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800308 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700309}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700310
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700311static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800312 vector<char> pdData;
313 int ret = readSectionByName("progs", elfFile, pdData);
Connor O'Brien3278a162020-02-13 21:45:22 -0800314 if (ret) return ret;
315
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700316 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700317 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700318 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800319 return -1;
320 };
321
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700322 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
323 memcpy(pd.data(), pdData.data(), pdData.size());
Connor O'Brien3278a162020-02-13 21:45:22 -0800324 return 0;
325}
326
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800327static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
328 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800329 int ret;
330 string name;
331 vector<Elf64_Sym> symtab;
332 vector<Elf64_Shdr> shTable;
333
334 ret = readSymTab(elfFile, 1 /* sort */, symtab);
335 if (ret) return ret;
336
337 /* Get index of section */
338 ret = readSectionHeadersAll(elfFile, shTable);
339 if (ret) return ret;
340
341 int sec_idx = -1;
342 for (int i = 0; i < (int)shTable.size(); i++) {
343 ret = getSymName(elfFile, shTable[i].sh_name, name);
344 if (ret) return ret;
345
346 if (!name.compare(sectionName)) {
347 sec_idx = i;
348 break;
349 }
350 }
351
352 /* No section found with matching name*/
353 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700354 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800355 return -1;
356 }
357
358 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800359 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
360
Connor O'Brien3278a162020-02-13 21:45:22 -0800361 if (symtab[i].st_shndx == sec_idx) {
362 string s;
363 ret = getSymName(elfFile, symtab[i].st_name, s);
364 if (ret) return ret;
365 names.push_back(s);
366 }
367 }
368
369 return 0;
370}
371
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800372static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
373 if (allowed == nullptr) return true;
374
375 for (size_t i = 0; i < numAllowed; i++) {
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700376 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
377 if (type == getFuseProgType()) return true;
378 } else if (type == allowed[i])
379 return true;
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800380 }
381
382 return false;
383}
384
Joel Fernandesd76a2002018-10-16 13:19:58 -0700385/* Read a section by its index - for ex to get sec hdr strtab blob */
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700386static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs,
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800387 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700388 vector<Elf64_Shdr> shTable;
389 int entries, ret = 0;
390
391 ret = readSectionHeadersAll(elfFile, shTable);
392 if (ret) return ret;
393 entries = shTable.size();
394
Connor O'Brien3278a162020-02-13 21:45:22 -0800395 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700396 ret = readProgDefs(elfFile, pd);
Connor O'Brien3278a162020-02-13 21:45:22 -0800397 if (ret) return ret;
398 vector<string> progDefNames;
399 ret = getSectionSymNames(elfFile, "progs", progDefNames);
400 if (!pd.empty() && ret) return ret;
401
Joel Fernandesd76a2002018-10-16 13:19:58 -0700402 for (int i = 0; i < entries; i++) {
403 string name;
404 codeSection cs_temp;
405 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
406
407 ret = getSymName(elfFile, shTable[i].sh_name, name);
408 if (ret) return ret;
409
410 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800411
Tyler Wear4e2f4602022-02-03 09:46:01 -0800412 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800413
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800414 if (!IsAllowed(ptype, allowed, numAllowed)) {
415 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
416 return -1;
417 }
418
Tyler Wear4e2f4602022-02-03 09:46:01 -0800419 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700420
Tyler Wear4e2f4602022-02-03 09:46:01 -0800421 // convert all slashes to underscores
422 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800423
Tyler Wear4e2f4602022-02-03 09:46:01 -0800424 cs_temp.type = ptype;
425 cs_temp.name = name;
426
427 ret = readSectionByIdx(elfFile, i, cs_temp.data);
428 if (ret) return ret;
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700429 ALOGV("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800430
431 vector<string> csSymNames;
432 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
433 if (ret || !csSymNames.size()) return ret;
Motomu Utsumic52a98d2025-03-21 15:08:42 +0900434 for (size_t j = 0; j < progDefNames.size(); ++j) {
435 if (!progDefNames[j].compare(csSymNames[0] + "_def")) {
436 cs_temp.prog_def = pd[j];
Tyler Wear4e2f4602022-02-03 09:46:01 -0800437 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800438 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700439 }
440
441 /* Check for rel section */
442 if (cs_temp.data.size() > 0 && i < entries) {
443 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
444 if (ret) return ret;
445
Tyler Wear4e2f4602022-02-03 09:46:01 -0800446 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700447 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
448 if (ret) return ret;
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700449 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700450 }
451 }
452
453 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700454 cs.push_back(std::move(cs_temp));
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700455 ALOGV("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700456 }
457 }
458 return 0;
459}
460
461static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
462 vector<Elf64_Sym> symtab;
463 int ret = 0;
464
465 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
466 if (ret) return ret;
467
468 if (index >= (int)symtab.size()) return -1;
469
470 return getSymName(elfFile, symtab[index].st_name, name);
471}
472
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700473static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
474 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700475 // Assuming fd is a valid Bpf Map file descriptor then
476 // all the following should always succeed on a 4.14+ kernel.
477 // If they somehow do fail, they'll return -1 (and set errno),
478 // which should then cause (among others) a key_size mismatch.
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700479 int fd_type = bpfGetFdMapType(fd);
480 int fd_key_size = bpfGetFdKeySize(fd);
481 int fd_value_size = bpfGetFdValueSize(fd);
482 int fd_max_entries = bpfGetFdMaxEntries(fd);
483 int fd_map_flags = bpfGetFdMapFlags(fd);
484
485 // DEVMAPs are readonly from the bpf program side's point of view, as such
486 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
487 int desired_map_flags = (int)mapDef.map_flags;
488 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
489 desired_map_flags |= BPF_F_RDONLY_PROG;
490
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000491 // The .h file enforces that this is a power of two, and page size will
492 // also always be a power of two, so this logic is actually enough to
493 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000494 unsigned int desired_max_entries = mapDef.max_entries;
495 if (type == BPF_MAP_TYPE_RINGBUF) {
496 if (desired_max_entries < page_size) desired_max_entries = page_size;
497 }
498
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700499 // The following checks should *never* trigger, if one of them somehow does,
500 // it probably means a bpf .o file has been changed/replaced at runtime
501 // and bpfloader was manually rerun (normally it should only run *once*
502 // early during the boot process).
503 // Another possibility is that something is misconfigured in the code:
504 // most likely a shared map is declared twice differently.
505 // But such a change should never be checked into the source tree...
506 if ((fd_type == type) &&
507 (fd_key_size == (int)mapDef.key_size) &&
508 (fd_value_size == (int)mapDef.value_size) &&
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000509 (fd_max_entries == (int)desired_max_entries) &&
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700510 (fd_map_flags == desired_map_flags)) {
511 return true;
512 }
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700513
514 ALOGE("bpf map name %s mismatch: desired/found: "
515 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
516 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
517 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
518 return false;
519}
520
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800521static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700522 const char* prefix) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700523 int ret;
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700524 vector<char> mdData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700525 vector<struct bpf_map_def> md;
526 vector<string> mapNames;
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700527 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700528
529 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800530 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700531 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800532
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700533 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700534 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700535 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800536 return -1;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800537 }
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700538 md.resize(mdData.size() / sizeof(struct bpf_map_def));
539 memcpy(md.data(), mdData.data(), mdData.size());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700540
Connor O'Brien3278a162020-02-13 21:45:22 -0800541 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700542 if (ret) return ret;
543
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700544 unsigned kvers = kernelVersion();
545
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700546 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +0000547 if (md[i].zero != 0) abort();
548
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700549 if (kvers < md[i].min_kver) {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700550 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700551 mapNames[i].c_str(), kvers, md[i].min_kver);
552 mapFds.push_back(unique_fd());
553 continue;
554 }
555
556 if (kvers >= md[i].max_kver) {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700557 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700558 mapNames[i].c_str(), kvers, md[i].max_kver);
559 mapFds.push_back(unique_fd());
560 continue;
561 }
562
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700563 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700564 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
565 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
566 // of be approximated: HASH has the same userspace visible api.
567 // However it cannot be used by ebpf programs in the same way.
568 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
569 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
570 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
571 // programs as being 5.4+...
572 type = BPF_MAP_TYPE_HASH;
573 }
574
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000575 // The .h file enforces that this is a power of two, and page size will
576 // also always be a power of two, so this logic is actually enough to
577 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000578 unsigned int max_entries = md[i].max_entries;
579 if (type == BPF_MAP_TYPE_RINGBUF) {
580 if (max_entries < page_size) max_entries = page_size;
581 }
582
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700583 // Format of pin location is /sys/fs/bpf/<prefix>map_<objName>_<mapName>
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700584 // except that maps shared across .o's have empty <objName>
585 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700586 string mapPinLoc = string(BPF_FS_PATH) + prefix + "map_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700587 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700588 bool reuse = false;
589 unique_fd fd;
590 int saved_errno;
591
Joel Fernandesd76a2002018-10-16 13:19:58 -0700592 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskieb199dd2022-07-01 03:21:40 -0700593 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800594 saved_errno = errno;
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700595 ALOGV("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700596 reuse = true;
597 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700598 union bpf_attr req = {
599 .map_type = type,
600 .key_size = md[i].key_size,
601 .value_size = md[i].value_size,
602 .max_entries = max_entries,
603 .map_flags = md[i].map_flags,
Connor O'Brien35425e52022-01-18 21:41:16 -0800604 };
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700605 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
606 fd.reset(bpf(BPF_MAP_CREATE, req));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800607 saved_errno = errno;
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700608 ALOGV("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700609 }
610
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700611 if (!fd.ok()) return -saved_errno;
612
613 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
614 // safety (since reuse code path is rare) run these checks even if we just created it.
615 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
616 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700617
618 if (!reuse) {
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700619 ret = bpfFdPin(fd, mapPinLoc.c_str());
620 if (ret) {
621 int err = errno;
622 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
623 return -err;
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700624 }
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800625 ret = chmod(mapPinLoc.c_str(), md[i].mode);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700626 if (ret) {
627 int err = errno;
628 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
629 strerror(err));
630 return -err;
631 }
Maciej Żenczykowski5e4aabf2022-06-27 01:15:53 -0700632 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
633 if (ret) {
634 int err = errno;
635 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
636 ret, err, strerror(err));
637 return -err;
638 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700639 }
640
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700641 int mapId = bpfGetFdMapId(fd);
642 if (mapId == -1) {
643 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700644 } else {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700645 ALOGD("map %s id %d", mapPinLoc.c_str(), mapId);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700646 }
647
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700648 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700649 }
650
651 return ret;
652}
653
Joel Fernandesd76a2002018-10-16 13:19:58 -0700654static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
655 int insnIndex;
656 struct bpf_insn *insn, *insns;
657
658 insns = (struct bpf_insn*)(insnsPtr);
659
660 insnIndex = offset / sizeof(struct bpf_insn);
661 insn = &insns[insnIndex];
662
Maciej Żenczykowski509b1b92023-03-07 01:11:20 +0000663 // Occasionally might be useful for relocation debugging, but pretty spammy
664 if (0) {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700665 ALOGV("applying relo to instruction at byte offset: %llu, "
Maciej Żenczykowski509b1b92023-03-07 01:11:20 +0000666 "insn offset %d, insn %llx",
667 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
668 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700669
670 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700671 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700672 return;
673 }
674
675 insn->imm = fd;
676 insn->src_reg = BPF_PSEUDO_MAP_FD;
677}
678
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700679static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700680 vector<string> mapNames;
681
Connor O'Brien3278a162020-02-13 21:45:22 -0800682 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700683 if (ret) return;
684
685 for (int k = 0; k != (int)cs.size(); k++) {
686 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
687 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
688
689 for (int i = 0; i < n_rel; i++) {
690 int symIndex = ELF64_R_SYM(rel[i].r_info);
691 string symName;
692
693 ret = getSymNameByIdx(elfFile, symIndex, symName);
694 if (ret) return;
695
696 /* Find the map fd and apply relo */
697 for (int j = 0; j < (int)mapNames.size(); j++) {
698 if (!mapNames[j].compare(symName)) {
699 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
700 break;
701 }
702 }
703 }
704 }
705}
706
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800707static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700708 const char* prefix) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800709 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700710
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000711 if (!kvers) {
712 ALOGE("unable to get kernel version");
713 return -EINVAL;
714 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700715
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700716 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700717
718 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700719 unique_fd& fd = cs[i].prog_fd;
720 int ret;
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700721 string name = cs[i].name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700722
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000723 if (!cs[i].prog_def.has_value()) {
724 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
725 return -EINVAL;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800726 }
727
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000728 unsigned min_kver = cs[i].prog_def->min_kver;
729 unsigned max_kver = cs[i].prog_def->max_kver;
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700730 if (kvers < min_kver || kvers >= max_kver) {
731 ALOGD("skipping program cs[%d].name:%s min_kver:%x max_kver:%x (kvers:%x)",
732 i, name.c_str(), min_kver, max_kver, kvers);
733 continue;
734 }
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000735
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700736 // strip any potential $foo suffix
737 // this can be used to provide duplicate programs
738 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700739 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700740
741 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700742 // Format of pin location is
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700743 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700744 string progPinLoc = string(BPF_FS_PATH) + prefix + "prog_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700745 objName + '_' + string(name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700746 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700747 fd.reset(retrieveProgram(progPinLoc.c_str()));
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700748 ALOGV("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700749 (!fd.ok() ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700750 reuse = true;
751 } else {
752 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
753
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700754 union bpf_attr req = {
755 .prog_type = cs[i].type,
756 .kern_version = kvers,
757 .license = ptr_to_u64(license.c_str()),
758 .insns = ptr_to_u64(cs[i].data.data()),
759 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
760 .log_level = 1,
761 .log_buf = ptr_to_u64(log_buf.data()),
762 .log_size = static_cast<__u32>(log_buf.size()),
Tyler Wear4e2f4602022-02-03 09:46:01 -0800763 };
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700764 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
765 fd.reset(bpf(BPF_PROG_LOAD, req));
Tyler Wear4e2f4602022-02-03 09:46:01 -0800766
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700767 if (!fd.ok()) {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700768 ALOGW("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
769 cs[i].name.c_str(), fd.get(), std::strerror(errno));
770
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800771 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800772
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700773 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700774 for (const auto& line : lines) ALOGW("%s", line.c_str());
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700775 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700776
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000777 if (cs[i].prog_def->optional) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700778 ALOGW("failed program is marked optional - continuing...");
779 continue;
780 }
781 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800782 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700783 }
784
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700785 if (!fd.ok()) return fd.get();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700786
787 if (!reuse) {
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700788 ret = bpfFdPin(fd, progPinLoc.c_str());
789 if (ret) {
790 int err = errno;
791 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
792 return -err;
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700793 }
794 if (chmod(progPinLoc.c_str(), 0440)) {
795 int err = errno;
796 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
797 return -err;
798 }
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000799 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
800 (gid_t)cs[i].prog_def->gid)) {
801 int err = errno;
802 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
803 cs[i].prog_def->gid, err, strerror(err));
804 return -err;
Connor O'Brien3278a162020-02-13 21:45:22 -0800805 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700806 }
807
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700808 int progId = bpfGetFdProgId(fd);
809 if (progId == -1) {
810 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700811 } else {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700812 ALOGD("prog %s id %d", progPinLoc.c_str(), progId);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700813 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700814 }
815
816 return 0;
817}
818
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -0800819int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700820 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700821 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700822 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700823 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700824 int ret;
825
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700826 if (!isCritical) return -1;
827 *isCritical = false;
828
Joel Fernandesd76a2002018-10-16 13:19:58 -0700829 ifstream elfFile(elfPath, ios::in | ios::binary);
830 if (!elfFile.is_open()) return -1;
831
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700832 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700833 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700834
Joel Fernandesd76a2002018-10-16 13:19:58 -0700835 ret = readSectionByName("license", elfFile, license);
836 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700837 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700838 return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700839 }
840
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700841 ALOGI("Platform BpfLoader loading %s%s ELF object %s with license %s",
842 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
843 elfPath, (char*)license.data());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800844
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700845 ret = readCodeSections(elfFile, cs, location.allowedProgTypes, location.allowedProgTypesLength);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700846 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700847 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700848 return ret;
849 }
850
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700851 ret = createMaps(elfPath, elfFile, mapFds, location.prefix);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700852 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700853 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700854 return ret;
855 }
856
857 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700858 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700859
860 applyMapRelo(elfFile, mapFds, cs);
861
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700862 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700863 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700864
865 return ret;
866}
867
Maciej Żenczykowskie0f11522024-08-06 15:25:55 -0700868// Networking-related program types are limited to the Tethering Apex
869// to prevent things from breaking due to conflicts on mainline updates
870// (exception made for socket filters, ie. xt_bpf for potential use in iptables,
871// or for attaching to sockets directly)
872constexpr bpf_prog_type kPlatformAllowedProgTypes[] = {
873 BPF_PROG_TYPE_KPROBE,
874 BPF_PROG_TYPE_PERF_EVENT,
875 BPF_PROG_TYPE_SOCKET_FILTER,
876 BPF_PROG_TYPE_TRACEPOINT,
877 BPF_PROG_TYPE_UNSPEC, // Will be replaced with fuse bpf program type
878};
879
Carlos Galo0621b1e2024-09-04 01:05:36 +0000880constexpr bpf_prog_type kMemEventsAllowedProgTypes[] = {
881 BPF_PROG_TYPE_TRACEPOINT,
882 BPF_PROG_TYPE_SOCKET_FILTER,
883};
884
Maciej Żenczykowskie0f11522024-08-06 15:25:55 -0700885// see b/162057235. For arbitrary program types, the concern is that due to the lack of
886// SELinux access controls over BPF program attachpoints, we have no way to control the
887// attachment of programs to shared resources (or to detect when a shared resource
888// has one BPF program replace another that is attached there)
889constexpr bpf_prog_type kVendorAllowedProgTypes[] = {
890 BPF_PROG_TYPE_SOCKET_FILTER,
891};
892
Maciej Żenczykowski6d4d9d82024-08-06 15:32:00 -0700893const Location locations[] = {
Maciej Żenczykowskie0f11522024-08-06 15:25:55 -0700894 // Core operating system
895 {
896 .dir = "/system/etc/bpf/",
897 .prefix = "",
898 .allowedProgTypes = kPlatformAllowedProgTypes,
899 .allowedProgTypesLength = arraysize(kPlatformAllowedProgTypes),
900 },
Carlos Galo0621b1e2024-09-04 01:05:36 +0000901 // memevents
902 {
903 .dir = "/system/etc/bpf/memevents/",
904 .prefix = "memevents/",
905 .allowedProgTypes = kMemEventsAllowedProgTypes,
906 .allowedProgTypesLength = arraysize(kMemEventsAllowedProgTypes),
907 },
Maciej Żenczykowskie0f11522024-08-06 15:25:55 -0700908 // Vendor operating system
909 {
910 .dir = "/vendor/etc/bpf/",
911 .prefix = "vendor/",
912 .allowedProgTypes = kVendorAllowedProgTypes,
913 .allowedProgTypesLength = arraysize(kVendorAllowedProgTypes),
914 },
915};
916
Maciej Żenczykowski6d4d9d82024-08-06 15:32:00 -0700917int loadAllElfObjects(const Location& location) {
Maciej Żenczykowskie0f11522024-08-06 15:25:55 -0700918 int retVal = 0;
919 DIR* dir;
920 struct dirent* ent;
921
922 if ((dir = opendir(location.dir)) != NULL) {
923 while ((ent = readdir(dir)) != NULL) {
924 string s = ent->d_name;
925 if (!EndsWith(s, ".o")) continue;
926
927 string progPath(location.dir);
928 progPath += s;
929
930 bool critical;
Maciej Żenczykowski6d4d9d82024-08-06 15:32:00 -0700931 int ret = loadProg(progPath.c_str(), &critical, location);
Maciej Żenczykowskie0f11522024-08-06 15:25:55 -0700932 if (ret) {
933 if (critical) retVal = ret;
Maciej Żenczykowski6d4d9d82024-08-06 15:32:00 -0700934 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), strerror(-ret));
Maciej Żenczykowskie0f11522024-08-06 15:25:55 -0700935 } else {
936 ALOGV("Loaded object: %s", progPath.c_str());
937 }
938 }
939 closedir(dir);
940 }
941 return retVal;
942}
943
944int createSysFsBpfSubDir(const char* const prefix) {
945 if (*prefix) {
946 mode_t prevUmask = umask(0);
947
948 string s = "/sys/fs/bpf/";
949 s += prefix;
950
951 errno = 0;
952 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
953 if (ret && errno != EEXIST) {
954 const int err = errno;
Maciej Żenczykowski6d4d9d82024-08-06 15:32:00 -0700955 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), strerror(err));
Maciej Żenczykowskie0f11522024-08-06 15:25:55 -0700956 return -err;
957 }
958
959 umask(prevUmask);
960 }
961 return 0;
962}
963
Maciej Żenczykowskidd4bd2d2024-08-07 12:27:18 -0700964} // namespace bpf
965} // namespace android
Maciej Żenczykowskie0f11522024-08-06 15:25:55 -0700966
Maciej Żenczykowskidd4bd2d2024-08-07 12:27:18 -0700967// ----- extern C stuff for rust below here -----
968
969void initLogging() {
970 // since we only ever get called from mainline NetBpfLoad
971 // (see packages/modules/Connectivity/netbpfload/NetBpfLoad.cpp around line 516)
972 // and there no arguments, so we can just pretend/assume this is the case.
973 const char* argv[] = {"/system/bin/bpfloader", NULL};
974 android::base::InitLogging(const_cast<char**>(argv), &android::base::KernelLogger);
975}
976
Maciej Żenczykowski7ff83102024-08-13 20:04:00 +0000977void createBpfFsSubDirectories() {
978 for (const auto& location : android::bpf::locations) {
979 if (android::bpf::createSysFsBpfSubDir(location.prefix)) {
980 exit(120);
981 }
982 }
983}
984
Maciej Żenczykowskidd4bd2d2024-08-07 12:27:18 -0700985void legacyBpfLoader() {
Maciej Żenczykowskie0f11522024-08-06 15:25:55 -0700986 // Load all ELF objects, create programs and maps, and pin them
Maciej Żenczykowskidd4bd2d2024-08-07 12:27:18 -0700987 for (const auto& location : android::bpf::locations) {
Maciej Żenczykowski7ff83102024-08-13 20:04:00 +0000988 if (android::bpf::loadAllElfObjects(location)) {
Maciej Żenczykowskie0f11522024-08-06 15:25:55 -0700989 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
990 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
991 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
992 "problems or startup script race.");
993 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
994 sleep(20);
Maciej Żenczykowski7ff83102024-08-13 20:04:00 +0000995 exit(121);
Maciej Żenczykowskie0f11522024-08-06 15:25:55 -0700996 }
997 }
Maciej Żenczykowskie0f11522024-08-06 15:25:55 -0700998}
Maciej Żenczykowski6d4d9d82024-08-06 15:32:00 -0700999
Maciej Żenczykowskidd4bd2d2024-08-07 12:27:18 -07001000void execNetBpfLoadDone() {
1001 const char* args[] = {"/apex/com.android.tethering/bin/netbpfload", "done", NULL};
1002 execve(args[0], (char**)args, environ);
1003 ALOGE("FATAL: execve(): %d[%s]", errno, strerror(errno));
Maciej Żenczykowski7ff83102024-08-13 20:04:00 +00001004 exit(122);
Maciej Żenczykowskidd4bd2d2024-08-07 12:27:18 -07001005}