blob: 5f2bc70dc4da76b5c3a954bfa31b9d90af3d19d6 [file] [log] [blame]
Joel Fernandesd76a2002018-10-16 13:19:58 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "LibBpfLoader"
18
19#include <errno.h>
20#include <linux/bpf.h>
21#include <linux/elf.h>
22#include <log/log.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080027#include <sysexits.h>
Maciej Żenczykowski83f29772020-01-27 03:11:51 -080028#include <sys/stat.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070029#include <sys/utsname.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080030#include <sys/wait.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070031#include <unistd.h>
32
Maciej Żenczykowski57412c22022-05-20 16:44:06 -070033// This is BpfLoader v0.14
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080034#define BPFLOADER_VERSION_MAJOR 0u
Maciej Żenczykowski57412c22022-05-20 16:44:06 -070035#define BPFLOADER_VERSION_MINOR 14u
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 -0700315static string getSectionName(enum bpf_prog_type type)
316{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800317 for (auto& snt : sectionNameTypes)
318 if (snt.type == type)
319 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700320
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800321 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700322}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700323
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800324static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
325 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800326 vector<char> pdData;
327 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800328 // Older file formats do not require a 'progs' section at all.
329 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800330 if (ret == -2) return 0;
331 if (ret) return ret;
332
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800333 if (pdData.size() % sizeOfBpfProgDef) {
334 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0\n",
335 pdData.size(), sizeOfBpfProgDef);
336 return -1;
337 };
338
339 int progCount = pdData.size() / sizeOfBpfProgDef;
340 pd.resize(progCount);
341 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
342
343 const char* dataPtr = pdData.data();
344 for (auto& p : pd) {
345 // First we zero initialize
346 memset(&p, 0, sizeof(p));
347 // Then we set non-zero defaults
348 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
349 // Then we copy over the structure prefix from the ELF file.
350 memcpy(&p, dataPtr, trimmedSize);
351 // Move to next struct in the ELF file
352 dataPtr += sizeOfBpfProgDef;
353 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800354 return 0;
355}
356
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800357static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
358 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800359 int ret;
360 string name;
361 vector<Elf64_Sym> symtab;
362 vector<Elf64_Shdr> shTable;
363
364 ret = readSymTab(elfFile, 1 /* sort */, symtab);
365 if (ret) return ret;
366
367 /* Get index of section */
368 ret = readSectionHeadersAll(elfFile, shTable);
369 if (ret) return ret;
370
371 int sec_idx = -1;
372 for (int i = 0; i < (int)shTable.size(); i++) {
373 ret = getSymName(elfFile, shTable[i].sh_name, name);
374 if (ret) return ret;
375
376 if (!name.compare(sectionName)) {
377 sec_idx = i;
378 break;
379 }
380 }
381
382 /* No section found with matching name*/
383 if (sec_idx == -1) {
Maciej Żenczykowski21f34cb2020-07-20 18:44:33 -0700384 ALOGW("No %s section could be found in elf object\n", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800385 return -1;
386 }
387
388 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800389 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
390
Connor O'Brien3278a162020-02-13 21:45:22 -0800391 if (symtab[i].st_shndx == sec_idx) {
392 string s;
393 ret = getSymName(elfFile, symtab[i].st_name, s);
394 if (ret) return ret;
395 names.push_back(s);
396 }
397 }
398
399 return 0;
400}
401
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800402static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
403 if (allowed == nullptr) return true;
404
405 for (size_t i = 0; i < numAllowed; i++) {
406 if (type == allowed[i]) return true;
407 }
408
409 return false;
410}
411
Joel Fernandesd76a2002018-10-16 13:19:58 -0700412/* Read a section by its index - for ex to get sec hdr strtab blob */
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800413static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef,
414 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700415 vector<Elf64_Shdr> shTable;
416 int entries, ret = 0;
417
418 ret = readSectionHeadersAll(elfFile, shTable);
419 if (ret) return ret;
420 entries = shTable.size();
421
Connor O'Brien3278a162020-02-13 21:45:22 -0800422 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800423 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800424 if (ret) return ret;
425 vector<string> progDefNames;
426 ret = getSectionSymNames(elfFile, "progs", progDefNames);
427 if (!pd.empty() && ret) return ret;
428
Joel Fernandesd76a2002018-10-16 13:19:58 -0700429 for (int i = 0; i < entries; i++) {
430 string name;
431 codeSection cs_temp;
432 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
433
434 ret = getSymName(elfFile, shTable[i].sh_name, name);
435 if (ret) return ret;
436
437 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800438
Tyler Wear4e2f4602022-02-03 09:46:01 -0800439 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800440
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800441 if (!IsAllowed(ptype, allowed, numAllowed)) {
442 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
443 return -1;
444 }
445
Tyler Wear4e2f4602022-02-03 09:46:01 -0800446 // This must be done before '/' is replaced with '_'.
447 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800448
Tyler Wear4e2f4602022-02-03 09:46:01 -0800449 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700450
Tyler Wear4e2f4602022-02-03 09:46:01 -0800451 // convert all slashes to underscores
452 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800453
Tyler Wear4e2f4602022-02-03 09:46:01 -0800454 cs_temp.type = ptype;
455 cs_temp.name = name;
456
457 ret = readSectionByIdx(elfFile, i, cs_temp.data);
458 if (ret) return ret;
459 ALOGD("Loaded code section %d (%s)\n", i, name.c_str());
460
461 vector<string> csSymNames;
462 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
463 if (ret || !csSymNames.size()) return ret;
464 for (size_t i = 0; i < progDefNames.size(); ++i) {
465 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
466 cs_temp.prog_def = pd[i];
467 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800468 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700469 }
470
471 /* Check for rel section */
472 if (cs_temp.data.size() > 0 && i < entries) {
473 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
474 if (ret) return ret;
475
Tyler Wear4e2f4602022-02-03 09:46:01 -0800476 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700477 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
478 if (ret) return ret;
479 ALOGD("Loaded relo section %d (%s)\n", i, name.c_str());
480 }
481 }
482
483 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700484 cs.push_back(std::move(cs_temp));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700485 ALOGD("Adding section %d to cs list\n", i);
486 }
487 }
488 return 0;
489}
490
491static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
492 vector<Elf64_Sym> symtab;
493 int ret = 0;
494
495 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
496 if (ret) return ret;
497
498 if (index >= (int)symtab.size()) return -1;
499
500 return getSymName(elfFile, symtab[index].st_name, name);
501}
502
Connor O'Brien35425e52022-01-18 21:41:16 -0800503static bool waitpidTimeout(pid_t pid, int timeoutMs) {
504 // Add SIGCHLD to the signal set.
505 sigset_t child_mask, original_mask;
506 sigemptyset(&child_mask);
507 sigaddset(&child_mask, SIGCHLD);
508 if (sigprocmask(SIG_BLOCK, &child_mask, &original_mask) == -1) return false;
509
510 // Wait for a SIGCHLD notification.
511 errno = 0;
512 timespec ts = {0, timeoutMs * 1000000};
513 int wait_result = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, nullptr, &ts));
514
515 // Restore the original signal set.
516 sigprocmask(SIG_SETMASK, &original_mask, nullptr);
517
518 if (wait_result == -1) return false;
519
520 int status;
521 return TEMP_FAILURE_RETRY(waitpid(pid, &status, WNOHANG)) == pid;
522}
523
524static std::optional<unique_fd> getMapBtfInfo(const char* elfPath,
525 std::unordered_map<string, std::pair<uint32_t, uint32_t>> &btfTypeIds) {
526 unique_fd bpfloaderSocket, btfloaderSocket;
527 if (!android::base::Socketpair(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0, &bpfloaderSocket,
528 &btfloaderSocket)) {
529 return {};
530 }
531
532 unique_fd pipeRead, pipeWrite;
533 if (!android::base::Pipe(&pipeRead, &pipeWrite, O_NONBLOCK)) {
534 return {};
535 }
536
537 pid_t pid = fork();
538 if (pid < 0) return {};
539 if (!pid) {
540 bpfloaderSocket.reset();
541 pipeRead.reset();
542 auto socketFdStr = std::to_string(btfloaderSocket.release());
543 auto pipeFdStr = std::to_string(pipeWrite.release());
544
545 if (execl("/system/bin/btfloader", "/system/bin/btfloader", socketFdStr.c_str(),
546 pipeFdStr.c_str(), elfPath, NULL) == -1) {
547 ALOGW("exec btfloader failed with errno %d (%s)\n", errno, strerror(errno));
548 exit(EX_UNAVAILABLE);
549 }
550 }
551 btfloaderSocket.reset();
552 pipeWrite.reset();
553 if (!waitpidTimeout(pid, 100)) {
554 kill(pid, SIGKILL);
555 return {};
556 }
557
558 unique_fd btfFd;
559 if (android::base::ReceiveFileDescriptors(bpfloaderSocket, nullptr, 0, &btfFd)) return {};
560
561 std::string btfTypeIdStr;
562 if (!android::base::ReadFdToString(pipeRead, &btfTypeIdStr)) return {};
563 if (btfFd.get() < 0) return {};
564
565 const auto mapTypeIdLines = android::base::Split(btfTypeIdStr, "\n");
566 for (const auto &line : mapTypeIdLines) {
567 const auto vec = android::base::Split(line, " ");
568 // Splitting on newline will give us one empty line
569 if (vec.size() != 3) continue;
570 const int kTid = atoi(vec[1].c_str());
571 const int vTid = atoi(vec[2].c_str());
572 if (!kTid || !vTid) return {};
573 btfTypeIds[vec[0]] = std::make_pair(kTid, vTid);
574 }
575 return btfFd;
576}
577
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800578static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800579 const char* prefix, size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700580 int ret;
Connor O'Brien35425e52022-01-18 21:41:16 -0800581 vector<char> mdData, btfData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700582 vector<struct bpf_map_def> md;
583 vector<string> mapNames;
Connor O'Brien35425e52022-01-18 21:41:16 -0800584 std::unordered_map<string, std::pair<uint32_t, uint32_t>> btfTypeIdMap;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700585 string fname = pathToFilename(string(elfPath), true);
586
587 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800588 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700589 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800590
591 if (mdData.size() % sizeOfBpfMapDef) {
592 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0\n",
593 mdData.size(), sizeOfBpfMapDef);
594 return -1;
595 };
596
597 int mapCount = mdData.size() / sizeOfBpfMapDef;
598 md.resize(mapCount);
599 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
600
601 const char* dataPtr = mdData.data();
602 for (auto& m : md) {
603 // First we zero initialize
604 memset(&m, 0, sizeof(m));
605 // Then we set non-zero defaults
606 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700607 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800608 // Then we copy over the structure prefix from the ELF file.
609 memcpy(&m, dataPtr, trimmedSize);
610 // Move to next struct in the ELF file
611 dataPtr += sizeOfBpfMapDef;
612 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700613
Connor O'Brien3278a162020-02-13 21:45:22 -0800614 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700615 if (ret) return ret;
616
Connor O'Brien35425e52022-01-18 21:41:16 -0800617 std::optional<unique_fd> btfFd;
618 if (!readSectionByName(".BTF", elfFile, btfData)) {
619 btfFd = getMapBtfInfo(elfPath, btfTypeIdMap);
620 }
621
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700622 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700623
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700624 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800625 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
626 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x\n", mapNames[i].c_str(),
627 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700628 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800629 continue;
630 }
631
632 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
633 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x\n", mapNames[i].c_str(),
634 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700635 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800636 continue;
637 }
638
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700639 if (kvers < md[i].min_kver) {
640 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x\n",
641 mapNames[i].c_str(), kvers, md[i].min_kver);
642 mapFds.push_back(unique_fd());
643 continue;
644 }
645
646 if (kvers >= md[i].max_kver) {
647 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x\n",
648 mapNames[i].c_str(), kvers, md[i].max_kver);
649 mapFds.push_back(unique_fd());
650 continue;
651 }
652
653 // Format of pin location is /sys/fs/bpf/<prefix>map_<filename>_<mapname>
654 string mapPinLoc =
655 string(BPF_FS_PATH) + prefix + "map_" + fname + "_" + string(mapNames[i]);
656 bool reuse = false;
657 unique_fd fd;
658 int saved_errno;
659
Joel Fernandesd76a2002018-10-16 13:19:58 -0700660 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700661 fd.reset(bpf_obj_get(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800662 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700663 ALOGD("bpf_create_map reusing map %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700664 reuse = true;
665 } else {
Maciej Żenczykowskicb358de2021-03-04 07:27:38 -0800666 enum bpf_map_type type = md[i].type;
667 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
668 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
669 // of be approximated: ARRAY has the same userspace api, though it is not usable
670 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
671 // helper doesn't exist on 4.9 anyway (so the bpf program would fail to load,
672 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
673 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
674 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
675 type = BPF_MAP_TYPE_ARRAY;
676 }
677 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
678 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
679 // of be approximated: HASH has the same userspace visible api.
680 // However it cannot be used by ebpf programs in the same way.
681 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
682 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
683 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
684 // programs as being 5.4+...
685 type = BPF_MAP_TYPE_HASH;
686 }
Connor O'Brien35425e52022-01-18 21:41:16 -0800687 struct bpf_create_map_attr attr = {
688 .name = mapNames[i].c_str(),
689 .map_type = type,
690 .map_flags = md[i].map_flags,
691 .key_size = md[i].key_size,
692 .value_size = md[i].value_size,
693 .max_entries = md[i].max_entries,
694 };
695 if (btfFd.has_value() && btfTypeIdMap.find(mapNames[i]) != btfTypeIdMap.end()) {
696 attr.btf_fd = btfFd->get();
697 attr.btf_key_type_id = btfTypeIdMap.at(mapNames[i]).first;
698 attr.btf_value_type_id = btfTypeIdMap.at(mapNames[i]).second;
699 }
700 fd.reset(bcc_create_map_xattr(&attr, true));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800701 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700702 ALOGD("bpf_create_map name %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700703 }
704
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800705 if (fd < 0) return -saved_errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700706
707 if (!reuse) {
708 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800709 if (ret) return -errno;
710 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
711 if (ret) return -errno;
712 ret = chmod(mapPinLoc.c_str(), md[i].mode);
713 if (ret) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700714 }
715
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700716 struct bpf_map_info map_info = {};
717 __u32 map_info_len = sizeof(map_info);
718 int rv = bpf_obj_get_info_by_fd(fd, &map_info, &map_info_len);
719 if (rv) {
720 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]\n", rv, errno);
721 } else {
722 ALOGI("map %s id %d\n", mapPinLoc.c_str(), map_info.id);
723 }
724
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700725 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700726 }
727
728 return ret;
729}
730
731/* For debugging, dump all instructions */
732static void dumpIns(char* ins, int size) {
733 for (int row = 0; row < size / 8; row++) {
734 ALOGE("%d: ", row);
735 for (int j = 0; j < 8; j++) {
736 ALOGE("%3x ", ins[(row * 8) + j]);
737 }
738 ALOGE("\n");
739 }
740}
741
742/* For debugging, dump all code sections from cs list */
743static void dumpAllCs(vector<codeSection>& cs) {
744 for (int i = 0; i < (int)cs.size(); i++) {
745 ALOGE("Dumping cs %d, name %s\n", int(i), cs[i].name.c_str());
746 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
747 ALOGE("-----------\n");
748 }
749}
750
751static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
752 int insnIndex;
753 struct bpf_insn *insn, *insns;
754
755 insns = (struct bpf_insn*)(insnsPtr);
756
757 insnIndex = offset / sizeof(struct bpf_insn);
758 insn = &insns[insnIndex];
759
760 ALOGD(
761 "applying relo to instruction at byte offset: %d, \
762 insn offset %d , insn %lx\n",
763 (int)offset, (int)insnIndex, *(unsigned long*)insn);
764
765 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
766 ALOGE("Dumping all instructions till ins %d\n", insnIndex);
767 ALOGE("invalid relo for insn %d: code 0x%x\n", insnIndex, insn->code);
768 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
769 return;
770 }
771
772 insn->imm = fd;
773 insn->src_reg = BPF_PSEUDO_MAP_FD;
774}
775
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700776static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700777 vector<string> mapNames;
778
Connor O'Brien3278a162020-02-13 21:45:22 -0800779 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700780 if (ret) return;
781
782 for (int k = 0; k != (int)cs.size(); k++) {
783 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
784 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
785
786 for (int i = 0; i < n_rel; i++) {
787 int symIndex = ELF64_R_SYM(rel[i].r_info);
788 string symName;
789
790 ret = getSymNameByIdx(elfFile, symIndex, symName);
791 if (ret) return;
792
793 /* Find the map fd and apply relo */
794 for (int j = 0; j < (int)mapNames.size(); j++) {
795 if (!mapNames[j].compare(symName)) {
796 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
797 break;
798 }
799 }
800 }
801 }
802}
803
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800804static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
805 const char* prefix) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800806 unsigned kvers = kernelVersion();
807 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700808
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800809 if (!kvers) return -1;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700810
811 string fname = pathToFilename(string(elfPath), true);
812
813 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700814 string name = cs[i].name;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800815 unsigned bpfMinVer = DEFAULT_BPFLOADER_MIN_VER; // v0.0
816 unsigned bpfMaxVer = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Joel Fernandesd76a2002018-10-16 13:19:58 -0700817
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800818 if (cs[i].prog_def.has_value()) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700819 unsigned min_kver = cs[i].prog_def->min_kver;
820 unsigned max_kver = cs[i].prog_def->max_kver;
821 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)\n", i, name.c_str(), min_kver,
822 max_kver, kvers);
823 if (kvers < min_kver) continue;
824 if (kvers >= max_kver) continue;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800825
826 bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
827 bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800828 }
829
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800830 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)\n", i, name.c_str(),
831 bpfMinVer, bpfMaxVer);
832 if (BPFLOADER_VERSION < bpfMinVer) continue;
833 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
834
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700835 // strip any potential $foo suffix
836 // this can be used to provide duplicate programs
837 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700838 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700839
840 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700841 // Format of pin location is
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800842 // /sys/fs/bpf/<prefix>prog_<filename>_<mapname>
843 string progPinLoc = BPF_FS_PATH;
844 progPinLoc += prefix;
845 progPinLoc += "prog_";
Maciej Żenczykowski6c7871b2020-04-23 12:46:00 -0700846 progPinLoc += fname;
847 progPinLoc += '_';
848 progPinLoc += name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700849 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700850 fd = retrieveProgram(progPinLoc.c_str());
851 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)\n", progPinLoc.c_str(), fd,
852 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700853 reuse = true;
854 } else {
855 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
856
Tyler Wear4e2f4602022-02-03 09:46:01 -0800857 struct bpf_load_program_attr attr = {
858 .prog_type = cs[i].type,
859 .name = name.c_str(),
860 .insns = (struct bpf_insn*)cs[i].data.data(),
861 .license = license.c_str(),
862 .log_level = 0,
863 .expected_attach_type = cs[i].expected_attach_type,
864 };
865
866 fd = bcc_prog_load_xattr(&attr, cs[i].data.size(), log_buf.data(), log_buf.size(),
867 true);
868
Steven Moreland804bca02019-12-12 17:21:23 -0800869 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)\n", elfPath,
870 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700871
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800872 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800873 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800874
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700875 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
876 for (const auto& line : lines) ALOGW("%s", line.c_str());
877 ALOGW("bpf_prog_load - END log_buf contents.");
878
879 if (cs[i].prog_def->optional) {
880 ALOGW("failed program is marked optional - continuing...");
881 continue;
882 }
883 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800884 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700885 }
886
887 if (fd < 0) return fd;
888 if (fd == 0) return -EINVAL;
889
890 if (!reuse) {
891 ret = bpf_obj_pin(fd, progPinLoc.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800892 if (ret) return -errno;
Stephane Lee16c93602022-03-08 17:27:09 -0800893 if (chmod(progPinLoc.c_str(), 0440)) return -errno;
Connor O'Brien3278a162020-02-13 21:45:22 -0800894 if (cs[i].prog_def.has_value()) {
895 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
896 (gid_t)cs[i].prog_def->gid)) {
897 return -errno;
898 }
899 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700900 }
901
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700902 struct bpf_prog_info prog_info = {};
903 __u32 prog_info_len = sizeof(prog_info);
904 int rv = bpf_obj_get_info_by_fd(fd, &prog_info, &prog_info_len);
905 if (rv) {
906 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]\n", rv, errno);
907 } else {
908 ALOGI("prog %s id %d\n", progPinLoc.c_str(), prog_info.id);
909 }
910
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700911 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700912 }
913
914 return 0;
915}
916
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800917int loadProg(const char* elfPath, bool* isCritical, const char* prefix,
918 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700919 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700920 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700921 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700922 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700923 int ret;
924
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700925 if (!isCritical) return -1;
926 *isCritical = false;
927
Joel Fernandesd76a2002018-10-16 13:19:58 -0700928 ifstream elfFile(elfPath, ios::in | ios::binary);
929 if (!elfFile.is_open()) return -1;
930
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700931 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700932 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700933
Joel Fernandesd76a2002018-10-16 13:19:58 -0700934 ret = readSectionByName("license", elfFile, license);
935 if (ret) {
936 ALOGE("Couldn't find license in %s\n", elfPath);
937 return ret;
938 } else {
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700939 ALOGD("Loading %s%s ELF object %s with license %s\n",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700940 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700941 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700942 }
943
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800944 // the following default values are for bpfloader V0.0 format which does not include them
945 unsigned int bpfLoaderMinVer =
946 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
947 unsigned int bpfLoaderMaxVer =
948 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
949 size_t sizeOfBpfMapDef =
950 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
951 size_t sizeOfBpfProgDef =
952 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
953
954 // inclusive lower bound check
955 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
956 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x\n",
957 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
958 return 0;
959 }
960
961 // exclusive upper bound check
962 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
963 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x\n",
964 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
965 return 0;
966 }
967
968 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)\n",
969 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
970
971 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
972 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)\n", sizeOfBpfMapDef,
973 DEFAULT_SIZEOF_BPF_MAP_DEF);
974 return -1;
975 }
976
977 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
978 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)\n", sizeOfBpfProgDef,
979 DEFAULT_SIZEOF_BPF_PROG_DEF);
980 return -1;
981 }
982
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800983 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, allowed, numAllowed);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700984 if (ret) {
985 ALOGE("Couldn't read all code sections in %s\n", elfPath);
986 return ret;
987 }
988
989 /* Just for future debugging */
990 if (0) dumpAllCs(cs);
991
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800992 ret = createMaps(elfPath, elfFile, mapFds, prefix, sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700993 if (ret) {
994 ALOGE("Failed to create maps: (ret=%d) in %s\n", ret, elfPath);
995 return ret;
996 }
997
998 for (int i = 0; i < (int)mapFds.size(); i++)
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700999 ALOGD("map_fd found at %d is %d in %s\n", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001000
1001 applyMapRelo(elfFile, mapFds, cs);
1002
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -08001003 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001004 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d\n", ret);
1005
1006 return ret;
1007}
1008
Joel Fernandesd76a2002018-10-16 13:19:58 -07001009} // namespace bpf
1010} // namespace android