blob: fd223a221c84e76b61c907163249a78d7780318b [file] [log] [blame]
Joel Fernandesd76a2002018-10-16 13:19:58 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "LibBpfLoader"
18
19#include <errno.h>
20#include <linux/bpf.h>
21#include <linux/elf.h>
22#include <log/log.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080027#include <sysexits.h>
Maciej Żenczykowski83f29772020-01-27 03:11:51 -080028#include <sys/stat.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070029#include <sys/utsname.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080030#include <sys/wait.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070031#include <unistd.h>
32
Tyler Wear4e2f4602022-02-03 09:46:01 -080033// This is BpfLoader v0.10
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080034#define BPFLOADER_VERSION_MAJOR 0u
Tyler Wear4e2f4602022-02-03 09:46:01 -080035#define BPFLOADER_VERSION_MINOR 10u
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080036#define BPFLOADER_VERSION ((BPFLOADER_VERSION_MAJOR << 16) | BPFLOADER_VERSION_MINOR)
37
Maciej Żenczykowski07375e22020-02-19 14:23:59 -080038#include "bpf/BpfUtils.h"
Ken Chend5689472021-12-20 18:07:21 +080039#include "bpf/bpf_map_def.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070040#include "include/libbpf_android.h"
41
Connor O'Brien35425e52022-01-18 21:41:16 -080042#include <bpf/bpf.h>
43
Joel Fernandesd76a2002018-10-16 13:19:58 -070044#include <cstdlib>
45#include <fstream>
46#include <iostream>
Connor O'Brien3278a162020-02-13 21:45:22 -080047#include <optional>
Joel Fernandesd76a2002018-10-16 13:19:58 -070048#include <string>
Connor O'Brien35425e52022-01-18 21:41:16 -080049#include <unordered_map>
Christopher Ferrisc151c672019-02-01 15:31:26 -080050#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070051
Connor O'Brien35425e52022-01-18 21:41:16 -080052#include <android-base/cmsg.h>
53#include <android-base/file.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070054#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070055#include <android-base/unique_fd.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070056
57#define BPF_FS_PATH "/sys/fs/bpf/"
58
59// Size of the BPF log buffer for verifier logging
Stephane Leeeb61b732021-10-21 17:03:11 -070060#define BPF_LOAD_LOG_SZ 0xfffff
Joel Fernandesd76a2002018-10-16 13:19:58 -070061
Tyler Wear4e2f4602022-02-03 09:46:01 -080062// Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
63#define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
64
Joel Fernandesd76a2002018-10-16 13:19:58 -070065using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070066using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070067using std::ifstream;
68using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080069using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080070using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070071using std::vector;
72
73namespace android {
74namespace bpf {
75
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -080076static string pathToFilename(const string& path, bool noext = false) {
77 vector<string> spath = android::base::Split(path, "/");
78 string ret = spath.back();
79
80 if (noext) {
81 size_t lastindex = ret.find_last_of('.');
82 return ret.substr(0, lastindex);
83 }
84 return ret;
85}
86
Joel Fernandesd76a2002018-10-16 13:19:58 -070087typedef struct {
88 const char* name;
89 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -080090 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -070091} sectionType;
92
93/*
94 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070095 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -070096 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070097 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -070098 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070099 *
100 * However, be aware that you should not be directly using the SECTION() macro.
101 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -0700102 */
103sectionType sectionNameTypes[] = {
Tyler Wear4e2f4602022-02-03 09:46:01 -0800104 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
105 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
106 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB, BPF_ATTACH_TYPE_UNSPEC},
107 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_ATTACH_TYPE_UNSPEC},
108 {"kprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
109 {"schedact/", BPF_PROG_TYPE_SCHED_ACT, BPF_ATTACH_TYPE_UNSPEC},
110 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS, BPF_ATTACH_TYPE_UNSPEC},
111 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
112 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
113 {"xdp/", BPF_PROG_TYPE_XDP, BPF_ATTACH_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700114};
115
116typedef struct {
117 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800118 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700119 string name;
120 vector<char> data;
121 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800122 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700123
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700124 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700125} codeSection;
126
Joel Fernandesd76a2002018-10-16 13:19:58 -0700127static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
128 elfFile.seekg(0);
129 if (elfFile.fail()) return -1;
130
131 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
132
133 return 0;
134}
135
136/* Reads all section header tables into an Shdr array */
137static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
138 Elf64_Ehdr eh;
139 int ret = 0;
140
141 ret = readElfHeader(elfFile, &eh);
142 if (ret) return ret;
143
144 elfFile.seekg(eh.e_shoff);
145 if (elfFile.fail()) return -1;
146
147 /* Read shdr table entries */
148 shTable.resize(eh.e_shnum);
149
150 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
151
152 return 0;
153}
154
155/* Read a section by its index - for ex to get sec hdr strtab blob */
156static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
157 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800158 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700159 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700160
161 elfFile.seekg(shTable[id].sh_offset);
162 if (elfFile.fail()) return -1;
163
164 sec.resize(shTable[id].sh_size);
165 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
166
167 return 0;
168}
169
170/* Read whole section header string table */
171static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
172 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800173 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700174 if (ret) return ret;
175
176 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
177 if (ret) return ret;
178
179 return 0;
180}
181
182/* Get name from offset in strtab */
183static int getSymName(ifstream& elfFile, int nameOff, string& name) {
184 int ret;
185 vector<char> secStrTab;
186
187 ret = readSectionHeaderStrtab(elfFile, secStrTab);
188 if (ret) return ret;
189
190 if (nameOff >= (int)secStrTab.size()) return -1;
191
192 name = string((char*)secStrTab.data() + nameOff);
193 return 0;
194}
195
196/* Reads a full section by name - example to get the GPL license */
197static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
198 vector<char> secStrTab;
199 vector<Elf64_Shdr> shTable;
200 int ret;
201
202 ret = readSectionHeadersAll(elfFile, shTable);
203 if (ret) return ret;
204
205 ret = readSectionHeaderStrtab(elfFile, secStrTab);
206 if (ret) return ret;
207
208 for (int i = 0; i < (int)shTable.size(); i++) {
209 char* secname = secStrTab.data() + shTable[i].sh_name;
210 if (!secname) continue;
211
212 if (!strcmp(secname, name)) {
213 vector<char> dataTmp;
214 dataTmp.resize(shTable[i].sh_size);
215
216 elfFile.seekg(shTable[i].sh_offset);
217 if (elfFile.fail()) return -1;
218
219 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
220
221 data = dataTmp;
222 return 0;
223 }
224 }
225 return -2;
226}
227
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700228unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800229 vector<char> theBytes;
230 int ret = readSectionByName(name, elfFile, theBytes);
231 if (ret) {
232 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).\n", name, defVal, defVal);
233 return defVal;
234 } else if (theBytes.size() < sizeof(unsigned int)) {
235 ALOGE("Section %s too short (defaulting to %u [0x%x]).\n", name, defVal, defVal);
236 return defVal;
237 } else {
238 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
239 unsigned int value = static_cast<unsigned char>(theBytes[3]);
240 value <<= 8;
241 value += static_cast<unsigned char>(theBytes[2]);
242 value <<= 8;
243 value += static_cast<unsigned char>(theBytes[1]);
244 value <<= 8;
245 value += static_cast<unsigned char>(theBytes[0]);
246 ALOGI("Section %s value is %u [0x%x]\n", name, value, value);
247 return value;
248 }
249}
250
Joel Fernandesd76a2002018-10-16 13:19:58 -0700251static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
252 int ret;
253 vector<Elf64_Shdr> shTable;
254
255 ret = readSectionHeadersAll(elfFile, shTable);
256 if (ret) return ret;
257
258 for (int i = 0; i < (int)shTable.size(); i++) {
259 if ((int)shTable[i].sh_type != type) continue;
260
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 return -2;
273}
274
275static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
276 return (a.st_value < b.st_value);
277}
278
279static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
280 int ret, numElems;
281 Elf64_Sym* buf;
282 vector<char> secData;
283
284 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
285 if (ret) return ret;
286
287 buf = (Elf64_Sym*)secData.data();
288 numElems = (secData.size() / sizeof(Elf64_Sym));
289 data.assign(buf, buf + numElems);
290
291 if (sort) std::sort(data.begin(), data.end(), symCompare);
292 return 0;
293}
294
295static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800296 for (auto& snt : sectionNameTypes)
297 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700298
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000299 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
300 if (StartsWith(name, "fuse/")) {
301 int result = BPF_PROG_TYPE_UNSPEC;
302 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
303 return static_cast<bpf_prog_type>(result);
304 }
305
Joel Fernandesd76a2002018-10-16 13:19:58 -0700306 return BPF_PROG_TYPE_UNSPEC;
307}
308
Tyler Wear4e2f4602022-02-03 09:46:01 -0800309static enum bpf_attach_type getExpectedAttachType(string& name) {
310 for (auto& snt : sectionNameTypes)
311 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
312 return BPF_ATTACH_TYPE_UNSPEC;
313}
314
Joel Fernandesd76a2002018-10-16 13:19:58 -0700315/* If ever needed
316static string getSectionName(enum bpf_prog_type type)
317{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800318 for (auto& snt : sectionNameTypes)
319 if (snt.type == type)
320 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700321
322 return NULL;
323}
324*/
325
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800326static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
327 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800328 vector<char> pdData;
329 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800330 // Older file formats do not require a 'progs' section at all.
331 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800332 if (ret == -2) return 0;
333 if (ret) return ret;
334
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800335 if (pdData.size() % sizeOfBpfProgDef) {
336 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0\n",
337 pdData.size(), sizeOfBpfProgDef);
338 return -1;
339 };
340
341 int progCount = pdData.size() / sizeOfBpfProgDef;
342 pd.resize(progCount);
343 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
344
345 const char* dataPtr = pdData.data();
346 for (auto& p : pd) {
347 // First we zero initialize
348 memset(&p, 0, sizeof(p));
349 // Then we set non-zero defaults
350 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
351 // Then we copy over the structure prefix from the ELF file.
352 memcpy(&p, dataPtr, trimmedSize);
353 // Move to next struct in the ELF file
354 dataPtr += sizeOfBpfProgDef;
355 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800356 return 0;
357}
358
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800359static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
360 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800361 int ret;
362 string name;
363 vector<Elf64_Sym> symtab;
364 vector<Elf64_Shdr> shTable;
365
366 ret = readSymTab(elfFile, 1 /* sort */, symtab);
367 if (ret) return ret;
368
369 /* Get index of section */
370 ret = readSectionHeadersAll(elfFile, shTable);
371 if (ret) return ret;
372
373 int sec_idx = -1;
374 for (int i = 0; i < (int)shTable.size(); i++) {
375 ret = getSymName(elfFile, shTable[i].sh_name, name);
376 if (ret) return ret;
377
378 if (!name.compare(sectionName)) {
379 sec_idx = i;
380 break;
381 }
382 }
383
384 /* No section found with matching name*/
385 if (sec_idx == -1) {
Maciej Żenczykowski21f34cb2020-07-20 18:44:33 -0700386 ALOGW("No %s section could be found in elf object\n", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800387 return -1;
388 }
389
390 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800391 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
392
Connor O'Brien3278a162020-02-13 21:45:22 -0800393 if (symtab[i].st_shndx == sec_idx) {
394 string s;
395 ret = getSymName(elfFile, symtab[i].st_name, s);
396 if (ret) return ret;
397 names.push_back(s);
398 }
399 }
400
401 return 0;
402}
403
Joel Fernandesd76a2002018-10-16 13:19:58 -0700404/* Read a section by its index - for ex to get sec hdr strtab blob */
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800405static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700406 vector<Elf64_Shdr> shTable;
407 int entries, ret = 0;
408
409 ret = readSectionHeadersAll(elfFile, shTable);
410 if (ret) return ret;
411 entries = shTable.size();
412
Connor O'Brien3278a162020-02-13 21:45:22 -0800413 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800414 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800415 if (ret) return ret;
416 vector<string> progDefNames;
417 ret = getSectionSymNames(elfFile, "progs", progDefNames);
418 if (!pd.empty() && ret) return ret;
419
Joel Fernandesd76a2002018-10-16 13:19:58 -0700420 for (int i = 0; i < entries; i++) {
421 string name;
422 codeSection cs_temp;
423 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
424
425 ret = getSymName(elfFile, shTable[i].sh_name, name);
426 if (ret) return ret;
427
428 enum bpf_prog_type ptype = getSectionType(name);
Tyler Wear4e2f4602022-02-03 09:46:01 -0800429 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800430
Tyler Wear4e2f4602022-02-03 09:46:01 -0800431 // This must be done before '/' is replaced with '_'.
432 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800433
Tyler Wear4e2f4602022-02-03 09:46:01 -0800434 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700435
Tyler Wear4e2f4602022-02-03 09:46:01 -0800436 // convert all slashes to underscores
437 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800438
Tyler Wear4e2f4602022-02-03 09:46:01 -0800439 cs_temp.type = ptype;
440 cs_temp.name = name;
441
442 ret = readSectionByIdx(elfFile, i, cs_temp.data);
443 if (ret) return ret;
444 ALOGD("Loaded code section %d (%s)\n", i, name.c_str());
445
446 vector<string> csSymNames;
447 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
448 if (ret || !csSymNames.size()) return ret;
449 for (size_t i = 0; i < progDefNames.size(); ++i) {
450 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
451 cs_temp.prog_def = pd[i];
452 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800453 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700454 }
455
456 /* Check for rel section */
457 if (cs_temp.data.size() > 0 && i < entries) {
458 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
459 if (ret) return ret;
460
Tyler Wear4e2f4602022-02-03 09:46:01 -0800461 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700462 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
463 if (ret) return ret;
464 ALOGD("Loaded relo section %d (%s)\n", i, name.c_str());
465 }
466 }
467
468 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700469 cs.push_back(std::move(cs_temp));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700470 ALOGD("Adding section %d to cs list\n", i);
471 }
472 }
473 return 0;
474}
475
476static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
477 vector<Elf64_Sym> symtab;
478 int ret = 0;
479
480 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
481 if (ret) return ret;
482
483 if (index >= (int)symtab.size()) return -1;
484
485 return getSymName(elfFile, symtab[index].st_name, name);
486}
487
Connor O'Brien35425e52022-01-18 21:41:16 -0800488static bool waitpidTimeout(pid_t pid, int timeoutMs) {
489 // Add SIGCHLD to the signal set.
490 sigset_t child_mask, original_mask;
491 sigemptyset(&child_mask);
492 sigaddset(&child_mask, SIGCHLD);
493 if (sigprocmask(SIG_BLOCK, &child_mask, &original_mask) == -1) return false;
494
495 // Wait for a SIGCHLD notification.
496 errno = 0;
497 timespec ts = {0, timeoutMs * 1000000};
498 int wait_result = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, nullptr, &ts));
499
500 // Restore the original signal set.
501 sigprocmask(SIG_SETMASK, &original_mask, nullptr);
502
503 if (wait_result == -1) return false;
504
505 int status;
506 return TEMP_FAILURE_RETRY(waitpid(pid, &status, WNOHANG)) == pid;
507}
508
509static std::optional<unique_fd> getMapBtfInfo(const char* elfPath,
510 std::unordered_map<string, std::pair<uint32_t, uint32_t>> &btfTypeIds) {
511 unique_fd bpfloaderSocket, btfloaderSocket;
512 if (!android::base::Socketpair(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0, &bpfloaderSocket,
513 &btfloaderSocket)) {
514 return {};
515 }
516
517 unique_fd pipeRead, pipeWrite;
518 if (!android::base::Pipe(&pipeRead, &pipeWrite, O_NONBLOCK)) {
519 return {};
520 }
521
522 pid_t pid = fork();
523 if (pid < 0) return {};
524 if (!pid) {
525 bpfloaderSocket.reset();
526 pipeRead.reset();
527 auto socketFdStr = std::to_string(btfloaderSocket.release());
528 auto pipeFdStr = std::to_string(pipeWrite.release());
529
530 if (execl("/system/bin/btfloader", "/system/bin/btfloader", socketFdStr.c_str(),
531 pipeFdStr.c_str(), elfPath, NULL) == -1) {
532 ALOGW("exec btfloader failed with errno %d (%s)\n", errno, strerror(errno));
533 exit(EX_UNAVAILABLE);
534 }
535 }
536 btfloaderSocket.reset();
537 pipeWrite.reset();
538 if (!waitpidTimeout(pid, 100)) {
539 kill(pid, SIGKILL);
540 return {};
541 }
542
543 unique_fd btfFd;
544 if (android::base::ReceiveFileDescriptors(bpfloaderSocket, nullptr, 0, &btfFd)) return {};
545
546 std::string btfTypeIdStr;
547 if (!android::base::ReadFdToString(pipeRead, &btfTypeIdStr)) return {};
548 if (btfFd.get() < 0) return {};
549
550 const auto mapTypeIdLines = android::base::Split(btfTypeIdStr, "\n");
551 for (const auto &line : mapTypeIdLines) {
552 const auto vec = android::base::Split(line, " ");
553 // Splitting on newline will give us one empty line
554 if (vec.size() != 3) continue;
555 const int kTid = atoi(vec[1].c_str());
556 const int vTid = atoi(vec[2].c_str());
557 if (!kTid || !vTid) return {};
558 btfTypeIds[vec[0]] = std::make_pair(kTid, vTid);
559 }
560 return btfFd;
561}
562
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800563static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800564 const char* prefix, size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700565 int ret;
Connor O'Brien35425e52022-01-18 21:41:16 -0800566 vector<char> mdData, btfData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700567 vector<struct bpf_map_def> md;
568 vector<string> mapNames;
Connor O'Brien35425e52022-01-18 21:41:16 -0800569 std::unordered_map<string, std::pair<uint32_t, uint32_t>> btfTypeIdMap;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700570 string fname = pathToFilename(string(elfPath), true);
571
572 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800573 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700574 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800575
576 if (mdData.size() % sizeOfBpfMapDef) {
577 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0\n",
578 mdData.size(), sizeOfBpfMapDef);
579 return -1;
580 };
581
582 int mapCount = mdData.size() / sizeOfBpfMapDef;
583 md.resize(mapCount);
584 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
585
586 const char* dataPtr = mdData.data();
587 for (auto& m : md) {
588 // First we zero initialize
589 memset(&m, 0, sizeof(m));
590 // Then we set non-zero defaults
591 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700592 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800593 // Then we copy over the structure prefix from the ELF file.
594 memcpy(&m, dataPtr, trimmedSize);
595 // Move to next struct in the ELF file
596 dataPtr += sizeOfBpfMapDef;
597 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700598
Connor O'Brien3278a162020-02-13 21:45:22 -0800599 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700600 if (ret) return ret;
601
Connor O'Brien35425e52022-01-18 21:41:16 -0800602 std::optional<unique_fd> btfFd;
603 if (!readSectionByName(".BTF", elfFile, btfData)) {
604 btfFd = getMapBtfInfo(elfPath, btfTypeIdMap);
605 }
606
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700607 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700608
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700609 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800610 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
611 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x\n", mapNames[i].c_str(),
612 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700613 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800614 continue;
615 }
616
617 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
618 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x\n", mapNames[i].c_str(),
619 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700620 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800621 continue;
622 }
623
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700624 if (kvers < md[i].min_kver) {
625 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x\n",
626 mapNames[i].c_str(), kvers, md[i].min_kver);
627 mapFds.push_back(unique_fd());
628 continue;
629 }
630
631 if (kvers >= md[i].max_kver) {
632 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x\n",
633 mapNames[i].c_str(), kvers, md[i].max_kver);
634 mapFds.push_back(unique_fd());
635 continue;
636 }
637
638 // Format of pin location is /sys/fs/bpf/<prefix>map_<filename>_<mapname>
639 string mapPinLoc =
640 string(BPF_FS_PATH) + prefix + "map_" + fname + "_" + string(mapNames[i]);
641 bool reuse = false;
642 unique_fd fd;
643 int saved_errno;
644
Joel Fernandesd76a2002018-10-16 13:19:58 -0700645 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700646 fd.reset(bpf_obj_get(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800647 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700648 ALOGD("bpf_create_map reusing map %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700649 reuse = true;
650 } else {
Maciej Żenczykowskicb358de2021-03-04 07:27:38 -0800651 enum bpf_map_type type = md[i].type;
652 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
653 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
654 // of be approximated: ARRAY has the same userspace api, though it is not usable
655 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
656 // helper doesn't exist on 4.9 anyway (so the bpf program would fail to load,
657 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
658 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
659 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
660 type = BPF_MAP_TYPE_ARRAY;
661 }
662 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
663 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
664 // of be approximated: HASH has the same userspace visible api.
665 // However it cannot be used by ebpf programs in the same way.
666 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
667 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
668 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
669 // programs as being 5.4+...
670 type = BPF_MAP_TYPE_HASH;
671 }
Connor O'Brien35425e52022-01-18 21:41:16 -0800672 struct bpf_create_map_attr attr = {
673 .name = mapNames[i].c_str(),
674 .map_type = type,
675 .map_flags = md[i].map_flags,
676 .key_size = md[i].key_size,
677 .value_size = md[i].value_size,
678 .max_entries = md[i].max_entries,
679 };
680 if (btfFd.has_value() && btfTypeIdMap.find(mapNames[i]) != btfTypeIdMap.end()) {
681 attr.btf_fd = btfFd->get();
682 attr.btf_key_type_id = btfTypeIdMap.at(mapNames[i]).first;
683 attr.btf_value_type_id = btfTypeIdMap.at(mapNames[i]).second;
684 }
685 fd.reset(bcc_create_map_xattr(&attr, true));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800686 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700687 ALOGD("bpf_create_map name %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700688 }
689
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800690 if (fd < 0) return -saved_errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700691
692 if (!reuse) {
693 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800694 if (ret) return -errno;
695 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
696 if (ret) return -errno;
697 ret = chmod(mapPinLoc.c_str(), md[i].mode);
698 if (ret) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700699 }
700
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700701 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700702 }
703
704 return ret;
705}
706
707/* For debugging, dump all instructions */
708static void dumpIns(char* ins, int size) {
709 for (int row = 0; row < size / 8; row++) {
710 ALOGE("%d: ", row);
711 for (int j = 0; j < 8; j++) {
712 ALOGE("%3x ", ins[(row * 8) + j]);
713 }
714 ALOGE("\n");
715 }
716}
717
718/* For debugging, dump all code sections from cs list */
719static void dumpAllCs(vector<codeSection>& cs) {
720 for (int i = 0; i < (int)cs.size(); i++) {
721 ALOGE("Dumping cs %d, name %s\n", int(i), cs[i].name.c_str());
722 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
723 ALOGE("-----------\n");
724 }
725}
726
727static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
728 int insnIndex;
729 struct bpf_insn *insn, *insns;
730
731 insns = (struct bpf_insn*)(insnsPtr);
732
733 insnIndex = offset / sizeof(struct bpf_insn);
734 insn = &insns[insnIndex];
735
736 ALOGD(
737 "applying relo to instruction at byte offset: %d, \
738 insn offset %d , insn %lx\n",
739 (int)offset, (int)insnIndex, *(unsigned long*)insn);
740
741 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
742 ALOGE("Dumping all instructions till ins %d\n", insnIndex);
743 ALOGE("invalid relo for insn %d: code 0x%x\n", insnIndex, insn->code);
744 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
745 return;
746 }
747
748 insn->imm = fd;
749 insn->src_reg = BPF_PSEUDO_MAP_FD;
750}
751
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700752static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700753 vector<string> mapNames;
754
Connor O'Brien3278a162020-02-13 21:45:22 -0800755 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700756 if (ret) return;
757
758 for (int k = 0; k != (int)cs.size(); k++) {
759 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
760 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
761
762 for (int i = 0; i < n_rel; i++) {
763 int symIndex = ELF64_R_SYM(rel[i].r_info);
764 string symName;
765
766 ret = getSymNameByIdx(elfFile, symIndex, symName);
767 if (ret) return;
768
769 /* Find the map fd and apply relo */
770 for (int j = 0; j < (int)mapNames.size(); j++) {
771 if (!mapNames[j].compare(symName)) {
772 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
773 break;
774 }
775 }
776 }
777 }
778}
779
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800780static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
781 const char* prefix) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800782 unsigned kvers = kernelVersion();
783 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700784
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800785 if (!kvers) return -1;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700786
787 string fname = pathToFilename(string(elfPath), true);
788
789 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700790 string name = cs[i].name;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800791 unsigned bpfMinVer = DEFAULT_BPFLOADER_MIN_VER; // v0.0
792 unsigned bpfMaxVer = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Joel Fernandesd76a2002018-10-16 13:19:58 -0700793
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800794 if (cs[i].prog_def.has_value()) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700795 unsigned min_kver = cs[i].prog_def->min_kver;
796 unsigned max_kver = cs[i].prog_def->max_kver;
797 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)\n", i, name.c_str(), min_kver,
798 max_kver, kvers);
799 if (kvers < min_kver) continue;
800 if (kvers >= max_kver) continue;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800801
802 bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
803 bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800804 }
805
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800806 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)\n", i, name.c_str(),
807 bpfMinVer, bpfMaxVer);
808 if (BPFLOADER_VERSION < bpfMinVer) continue;
809 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
810
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700811 // strip any potential $foo suffix
812 // this can be used to provide duplicate programs
813 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700814 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700815
816 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700817 // Format of pin location is
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800818 // /sys/fs/bpf/<prefix>prog_<filename>_<mapname>
819 string progPinLoc = BPF_FS_PATH;
820 progPinLoc += prefix;
821 progPinLoc += "prog_";
Maciej Żenczykowski6c7871b2020-04-23 12:46:00 -0700822 progPinLoc += fname;
823 progPinLoc += '_';
824 progPinLoc += name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700825 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700826 fd = retrieveProgram(progPinLoc.c_str());
827 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)\n", progPinLoc.c_str(), fd,
828 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700829 reuse = true;
830 } else {
831 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
832
Tyler Wear4e2f4602022-02-03 09:46:01 -0800833 struct bpf_load_program_attr attr = {
834 .prog_type = cs[i].type,
835 .name = name.c_str(),
836 .insns = (struct bpf_insn*)cs[i].data.data(),
837 .license = license.c_str(),
838 .log_level = 0,
839 .expected_attach_type = cs[i].expected_attach_type,
840 };
841
842 fd = bcc_prog_load_xattr(&attr, cs[i].data.size(), log_buf.data(), log_buf.size(),
843 true);
844
Steven Moreland804bca02019-12-12 17:21:23 -0800845 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)\n", elfPath,
846 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700847
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800848 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800849 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800850
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700851 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
852 for (const auto& line : lines) ALOGW("%s", line.c_str());
853 ALOGW("bpf_prog_load - END log_buf contents.");
854
855 if (cs[i].prog_def->optional) {
856 ALOGW("failed program is marked optional - continuing...");
857 continue;
858 }
859 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800860 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700861 }
862
863 if (fd < 0) return fd;
864 if (fd == 0) return -EINVAL;
865
866 if (!reuse) {
867 ret = bpf_obj_pin(fd, progPinLoc.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800868 if (ret) return -errno;
869 if (cs[i].prog_def.has_value()) {
870 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
871 (gid_t)cs[i].prog_def->gid)) {
872 return -errno;
873 }
874 }
875 if (chmod(progPinLoc.c_str(), 0440)) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700876 }
877
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700878 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700879 }
880
881 return 0;
882}
883
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800884int loadProg(const char* elfPath, bool* isCritical, const char* prefix) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700885 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700886 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700887 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700888 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700889 int ret;
890
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700891 if (!isCritical) return -1;
892 *isCritical = false;
893
Joel Fernandesd76a2002018-10-16 13:19:58 -0700894 ifstream elfFile(elfPath, ios::in | ios::binary);
895 if (!elfFile.is_open()) return -1;
896
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700897 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700898 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700899
Joel Fernandesd76a2002018-10-16 13:19:58 -0700900 ret = readSectionByName("license", elfFile, license);
901 if (ret) {
902 ALOGE("Couldn't find license in %s\n", elfPath);
903 return ret;
904 } else {
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700905 ALOGD("Loading %s%s ELF object %s with license %s\n",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700906 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700907 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700908 }
909
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800910 // the following default values are for bpfloader V0.0 format which does not include them
911 unsigned int bpfLoaderMinVer =
912 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
913 unsigned int bpfLoaderMaxVer =
914 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
915 size_t sizeOfBpfMapDef =
916 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
917 size_t sizeOfBpfProgDef =
918 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
919
920 // inclusive lower bound check
921 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
922 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x\n",
923 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
924 return 0;
925 }
926
927 // exclusive upper bound check
928 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
929 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x\n",
930 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
931 return 0;
932 }
933
934 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)\n",
935 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
936
937 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
938 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)\n", sizeOfBpfMapDef,
939 DEFAULT_SIZEOF_BPF_MAP_DEF);
940 return -1;
941 }
942
943 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
944 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)\n", sizeOfBpfProgDef,
945 DEFAULT_SIZEOF_BPF_PROG_DEF);
946 return -1;
947 }
948
949 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700950 if (ret) {
951 ALOGE("Couldn't read all code sections in %s\n", elfPath);
952 return ret;
953 }
954
955 /* Just for future debugging */
956 if (0) dumpAllCs(cs);
957
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800958 ret = createMaps(elfPath, elfFile, mapFds, prefix, sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700959 if (ret) {
960 ALOGE("Failed to create maps: (ret=%d) in %s\n", ret, elfPath);
961 return ret;
962 }
963
964 for (int i = 0; i < (int)mapFds.size(); i++)
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700965 ALOGD("map_fd found at %d is %d in %s\n", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700966
967 applyMapRelo(elfFile, mapFds, cs);
968
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800969 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700970 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d\n", ret);
971
972 return ret;
973}
974
Joel Fernandesd76a2002018-10-16 13:19:58 -0700975} // namespace bpf
976} // namespace android