blob: 37a764afca2cc92e70d6d9e71ccc3190038f0fa9 [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 Żenczykowskie092e0b2022-05-24 13:14:32 +000033// This is BpfLoader v0.15
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080034#define BPFLOADER_VERSION_MAJOR 0u
Maciej Żenczykowskie092e0b2022-05-24 13:14:32 +000035#define BPFLOADER_VERSION_MINOR 15u
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},
Maciej Żenczykowskie092e0b2022-05-24 13:14:32 +0000109 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT, BPF_ATTACH_TYPE_UNSPEC},
Tyler Wear4e2f4602022-02-03 09:46:01 -0800110 {"schedact/", BPF_PROG_TYPE_SCHED_ACT, BPF_ATTACH_TYPE_UNSPEC},
111 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS, BPF_ATTACH_TYPE_UNSPEC},
112 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
113 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
114 {"xdp/", BPF_PROG_TYPE_XDP, BPF_ATTACH_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700115};
116
117typedef struct {
118 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800119 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700120 string name;
121 vector<char> data;
122 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800123 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700124
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700125 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700126} codeSection;
127
Joel Fernandesd76a2002018-10-16 13:19:58 -0700128static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
129 elfFile.seekg(0);
130 if (elfFile.fail()) return -1;
131
132 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
133
134 return 0;
135}
136
137/* Reads all section header tables into an Shdr array */
138static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
139 Elf64_Ehdr eh;
140 int ret = 0;
141
142 ret = readElfHeader(elfFile, &eh);
143 if (ret) return ret;
144
145 elfFile.seekg(eh.e_shoff);
146 if (elfFile.fail()) return -1;
147
148 /* Read shdr table entries */
149 shTable.resize(eh.e_shnum);
150
151 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
152
153 return 0;
154}
155
156/* Read a section by its index - for ex to get sec hdr strtab blob */
157static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
158 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800159 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700160 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700161
162 elfFile.seekg(shTable[id].sh_offset);
163 if (elfFile.fail()) return -1;
164
165 sec.resize(shTable[id].sh_size);
166 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
167
168 return 0;
169}
170
171/* Read whole section header string table */
172static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
173 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800174 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700175 if (ret) return ret;
176
177 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
178 if (ret) return ret;
179
180 return 0;
181}
182
183/* Get name from offset in strtab */
184static int getSymName(ifstream& elfFile, int nameOff, string& name) {
185 int ret;
186 vector<char> secStrTab;
187
188 ret = readSectionHeaderStrtab(elfFile, secStrTab);
189 if (ret) return ret;
190
191 if (nameOff >= (int)secStrTab.size()) return -1;
192
193 name = string((char*)secStrTab.data() + nameOff);
194 return 0;
195}
196
197/* Reads a full section by name - example to get the GPL license */
198static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
199 vector<char> secStrTab;
200 vector<Elf64_Shdr> shTable;
201 int ret;
202
203 ret = readSectionHeadersAll(elfFile, shTable);
204 if (ret) return ret;
205
206 ret = readSectionHeaderStrtab(elfFile, secStrTab);
207 if (ret) return ret;
208
209 for (int i = 0; i < (int)shTable.size(); i++) {
210 char* secname = secStrTab.data() + shTable[i].sh_name;
211 if (!secname) continue;
212
213 if (!strcmp(secname, name)) {
214 vector<char> dataTmp;
215 dataTmp.resize(shTable[i].sh_size);
216
217 elfFile.seekg(shTable[i].sh_offset);
218 if (elfFile.fail()) return -1;
219
220 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
221
222 data = dataTmp;
223 return 0;
224 }
225 }
226 return -2;
227}
228
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700229unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800230 vector<char> theBytes;
231 int ret = readSectionByName(name, elfFile, theBytes);
232 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700233 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800234 return defVal;
235 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700236 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800237 return defVal;
238 } else {
239 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
240 unsigned int value = static_cast<unsigned char>(theBytes[3]);
241 value <<= 8;
242 value += static_cast<unsigned char>(theBytes[2]);
243 value <<= 8;
244 value += static_cast<unsigned char>(theBytes[1]);
245 value <<= 8;
246 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700247 ALOGI("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800248 return value;
249 }
250}
251
Joel Fernandesd76a2002018-10-16 13:19:58 -0700252static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
253 int ret;
254 vector<Elf64_Shdr> shTable;
255
256 ret = readSectionHeadersAll(elfFile, shTable);
257 if (ret) return ret;
258
259 for (int i = 0; i < (int)shTable.size(); i++) {
260 if ((int)shTable[i].sh_type != type) continue;
261
262 vector<char> dataTmp;
263 dataTmp.resize(shTable[i].sh_size);
264
265 elfFile.seekg(shTable[i].sh_offset);
266 if (elfFile.fail()) return -1;
267
268 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
269
270 data = dataTmp;
271 return 0;
272 }
273 return -2;
274}
275
276static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
277 return (a.st_value < b.st_value);
278}
279
280static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
281 int ret, numElems;
282 Elf64_Sym* buf;
283 vector<char> secData;
284
285 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
286 if (ret) return ret;
287
288 buf = (Elf64_Sym*)secData.data();
289 numElems = (secData.size() / sizeof(Elf64_Sym));
290 data.assign(buf, buf + numElems);
291
292 if (sort) std::sort(data.begin(), data.end(), symCompare);
293 return 0;
294}
295
296static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800297 for (auto& snt : sectionNameTypes)
298 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700299
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000300 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
301 if (StartsWith(name, "fuse/")) {
302 int result = BPF_PROG_TYPE_UNSPEC;
303 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
304 return static_cast<bpf_prog_type>(result);
305 }
306
Joel Fernandesd76a2002018-10-16 13:19:58 -0700307 return BPF_PROG_TYPE_UNSPEC;
308}
309
Tyler Wear4e2f4602022-02-03 09:46:01 -0800310static enum bpf_attach_type getExpectedAttachType(string& name) {
311 for (auto& snt : sectionNameTypes)
312 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
313 return BPF_ATTACH_TYPE_UNSPEC;
314}
315
Joel Fernandesd76a2002018-10-16 13:19:58 -0700316static 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
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800322 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700323}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700324
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800325static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
326 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800327 vector<char> pdData;
328 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800329 // Older file formats do not require a 'progs' section at all.
330 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800331 if (ret == -2) return 0;
332 if (ret) return ret;
333
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800334 if (pdData.size() % sizeOfBpfProgDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700335 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800336 pdData.size(), sizeOfBpfProgDef);
337 return -1;
338 };
339
340 int progCount = pdData.size() / sizeOfBpfProgDef;
341 pd.resize(progCount);
342 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
343
344 const char* dataPtr = pdData.data();
345 for (auto& p : pd) {
346 // First we zero initialize
347 memset(&p, 0, sizeof(p));
348 // Then we set non-zero defaults
349 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
350 // Then we copy over the structure prefix from the ELF file.
351 memcpy(&p, dataPtr, trimmedSize);
352 // Move to next struct in the ELF file
353 dataPtr += sizeOfBpfProgDef;
354 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800355 return 0;
356}
357
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800358static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
359 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800360 int ret;
361 string name;
362 vector<Elf64_Sym> symtab;
363 vector<Elf64_Shdr> shTable;
364
365 ret = readSymTab(elfFile, 1 /* sort */, symtab);
366 if (ret) return ret;
367
368 /* Get index of section */
369 ret = readSectionHeadersAll(elfFile, shTable);
370 if (ret) return ret;
371
372 int sec_idx = -1;
373 for (int i = 0; i < (int)shTable.size(); i++) {
374 ret = getSymName(elfFile, shTable[i].sh_name, name);
375 if (ret) return ret;
376
377 if (!name.compare(sectionName)) {
378 sec_idx = i;
379 break;
380 }
381 }
382
383 /* No section found with matching name*/
384 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700385 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800386 return -1;
387 }
388
389 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800390 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
391
Connor O'Brien3278a162020-02-13 21:45:22 -0800392 if (symtab[i].st_shndx == sec_idx) {
393 string s;
394 ret = getSymName(elfFile, symtab[i].st_name, s);
395 if (ret) return ret;
396 names.push_back(s);
397 }
398 }
399
400 return 0;
401}
402
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800403static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
404 if (allowed == nullptr) return true;
405
406 for (size_t i = 0; i < numAllowed; i++) {
407 if (type == allowed[i]) return true;
408 }
409
410 return false;
411}
412
Joel Fernandesd76a2002018-10-16 13:19:58 -0700413/* Read a section by its index - for ex to get sec hdr strtab blob */
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800414static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef,
415 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700416 vector<Elf64_Shdr> shTable;
417 int entries, ret = 0;
418
419 ret = readSectionHeadersAll(elfFile, shTable);
420 if (ret) return ret;
421 entries = shTable.size();
422
Connor O'Brien3278a162020-02-13 21:45:22 -0800423 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800424 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800425 if (ret) return ret;
426 vector<string> progDefNames;
427 ret = getSectionSymNames(elfFile, "progs", progDefNames);
428 if (!pd.empty() && ret) return ret;
429
Joel Fernandesd76a2002018-10-16 13:19:58 -0700430 for (int i = 0; i < entries; i++) {
431 string name;
432 codeSection cs_temp;
433 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
434
435 ret = getSymName(elfFile, shTable[i].sh_name, name);
436 if (ret) return ret;
437
438 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800439
Tyler Wear4e2f4602022-02-03 09:46:01 -0800440 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800441
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800442 if (!IsAllowed(ptype, allowed, numAllowed)) {
443 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
444 return -1;
445 }
446
Tyler Wear4e2f4602022-02-03 09:46:01 -0800447 // This must be done before '/' is replaced with '_'.
448 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800449
Tyler Wear4e2f4602022-02-03 09:46:01 -0800450 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700451
Tyler Wear4e2f4602022-02-03 09:46:01 -0800452 // convert all slashes to underscores
453 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800454
Tyler Wear4e2f4602022-02-03 09:46:01 -0800455 cs_temp.type = ptype;
456 cs_temp.name = name;
457
458 ret = readSectionByIdx(elfFile, i, cs_temp.data);
459 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700460 ALOGD("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800461
462 vector<string> csSymNames;
463 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
464 if (ret || !csSymNames.size()) return ret;
465 for (size_t i = 0; i < progDefNames.size(); ++i) {
466 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
467 cs_temp.prog_def = pd[i];
468 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800469 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700470 }
471
472 /* Check for rel section */
473 if (cs_temp.data.size() > 0 && i < entries) {
474 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
475 if (ret) return ret;
476
Tyler Wear4e2f4602022-02-03 09:46:01 -0800477 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700478 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
479 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700480 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700481 }
482 }
483
484 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700485 cs.push_back(std::move(cs_temp));
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700486 ALOGD("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700487 }
488 }
489 return 0;
490}
491
492static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
493 vector<Elf64_Sym> symtab;
494 int ret = 0;
495
496 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
497 if (ret) return ret;
498
499 if (index >= (int)symtab.size()) return -1;
500
501 return getSymName(elfFile, symtab[index].st_name, name);
502}
503
Connor O'Brien35425e52022-01-18 21:41:16 -0800504static bool waitpidTimeout(pid_t pid, int timeoutMs) {
505 // Add SIGCHLD to the signal set.
506 sigset_t child_mask, original_mask;
507 sigemptyset(&child_mask);
508 sigaddset(&child_mask, SIGCHLD);
509 if (sigprocmask(SIG_BLOCK, &child_mask, &original_mask) == -1) return false;
510
511 // Wait for a SIGCHLD notification.
512 errno = 0;
513 timespec ts = {0, timeoutMs * 1000000};
514 int wait_result = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, nullptr, &ts));
515
516 // Restore the original signal set.
517 sigprocmask(SIG_SETMASK, &original_mask, nullptr);
518
519 if (wait_result == -1) return false;
520
521 int status;
522 return TEMP_FAILURE_RETRY(waitpid(pid, &status, WNOHANG)) == pid;
523}
524
525static std::optional<unique_fd> getMapBtfInfo(const char* elfPath,
526 std::unordered_map<string, std::pair<uint32_t, uint32_t>> &btfTypeIds) {
527 unique_fd bpfloaderSocket, btfloaderSocket;
528 if (!android::base::Socketpair(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0, &bpfloaderSocket,
529 &btfloaderSocket)) {
530 return {};
531 }
532
533 unique_fd pipeRead, pipeWrite;
534 if (!android::base::Pipe(&pipeRead, &pipeWrite, O_NONBLOCK)) {
535 return {};
536 }
537
538 pid_t pid = fork();
539 if (pid < 0) return {};
540 if (!pid) {
541 bpfloaderSocket.reset();
542 pipeRead.reset();
543 auto socketFdStr = std::to_string(btfloaderSocket.release());
544 auto pipeFdStr = std::to_string(pipeWrite.release());
545
546 if (execl("/system/bin/btfloader", "/system/bin/btfloader", socketFdStr.c_str(),
547 pipeFdStr.c_str(), elfPath, NULL) == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700548 ALOGW("exec btfloader failed with errno %d (%s)", errno, strerror(errno));
Connor O'Brien35425e52022-01-18 21:41:16 -0800549 exit(EX_UNAVAILABLE);
550 }
551 }
552 btfloaderSocket.reset();
553 pipeWrite.reset();
554 if (!waitpidTimeout(pid, 100)) {
555 kill(pid, SIGKILL);
556 return {};
557 }
558
559 unique_fd btfFd;
560 if (android::base::ReceiveFileDescriptors(bpfloaderSocket, nullptr, 0, &btfFd)) return {};
561
562 std::string btfTypeIdStr;
563 if (!android::base::ReadFdToString(pipeRead, &btfTypeIdStr)) return {};
564 if (btfFd.get() < 0) return {};
565
566 const auto mapTypeIdLines = android::base::Split(btfTypeIdStr, "\n");
567 for (const auto &line : mapTypeIdLines) {
568 const auto vec = android::base::Split(line, " ");
569 // Splitting on newline will give us one empty line
570 if (vec.size() != 3) continue;
571 const int kTid = atoi(vec[1].c_str());
572 const int vTid = atoi(vec[2].c_str());
573 if (!kTid || !vTid) return {};
574 btfTypeIds[vec[0]] = std::make_pair(kTid, vTid);
575 }
576 return btfFd;
577}
578
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800579static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800580 const char* prefix, size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700581 int ret;
Connor O'Brien35425e52022-01-18 21:41:16 -0800582 vector<char> mdData, btfData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700583 vector<struct bpf_map_def> md;
584 vector<string> mapNames;
Connor O'Brien35425e52022-01-18 21:41:16 -0800585 std::unordered_map<string, std::pair<uint32_t, uint32_t>> btfTypeIdMap;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700586 string fname = pathToFilename(string(elfPath), true);
587
588 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800589 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700590 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800591
592 if (mdData.size() % sizeOfBpfMapDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700593 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800594 mdData.size(), sizeOfBpfMapDef);
595 return -1;
596 };
597
598 int mapCount = mdData.size() / sizeOfBpfMapDef;
599 md.resize(mapCount);
600 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
601
602 const char* dataPtr = mdData.data();
603 for (auto& m : md) {
604 // First we zero initialize
605 memset(&m, 0, sizeof(m));
606 // Then we set non-zero defaults
607 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700608 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800609 // Then we copy over the structure prefix from the ELF file.
610 memcpy(&m, dataPtr, trimmedSize);
611 // Move to next struct in the ELF file
612 dataPtr += sizeOfBpfMapDef;
613 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700614
Connor O'Brien3278a162020-02-13 21:45:22 -0800615 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700616 if (ret) return ret;
617
Connor O'Brien35425e52022-01-18 21:41:16 -0800618 std::optional<unique_fd> btfFd;
619 if (!readSectionByName(".BTF", elfFile, btfData)) {
620 btfFd = getMapBtfInfo(elfPath, btfTypeIdMap);
621 }
622
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700623 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700624
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700625 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800626 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700627 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800628 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700629 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800630 continue;
631 }
632
633 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700634 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800635 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700636 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800637 continue;
638 }
639
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700640 if (kvers < md[i].min_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700641 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700642 mapNames[i].c_str(), kvers, md[i].min_kver);
643 mapFds.push_back(unique_fd());
644 continue;
645 }
646
647 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700648 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700649 mapNames[i].c_str(), kvers, md[i].max_kver);
650 mapFds.push_back(unique_fd());
651 continue;
652 }
653
654 // Format of pin location is /sys/fs/bpf/<prefix>map_<filename>_<mapname>
655 string mapPinLoc =
656 string(BPF_FS_PATH) + prefix + "map_" + fname + "_" + string(mapNames[i]);
657 bool reuse = false;
658 unique_fd fd;
659 int saved_errno;
660
Joel Fernandesd76a2002018-10-16 13:19:58 -0700661 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700662 fd.reset(bpf_obj_get(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800663 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700664 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700665 reuse = true;
666 } else {
Maciej Żenczykowskicb358de2021-03-04 07:27:38 -0800667 enum bpf_map_type type = md[i].type;
668 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
669 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
670 // of be approximated: ARRAY has the same userspace api, though it is not usable
671 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
672 // helper doesn't exist on 4.9 anyway (so the bpf program would fail to load,
673 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
674 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
675 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
676 type = BPF_MAP_TYPE_ARRAY;
677 }
678 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
679 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
680 // of be approximated: HASH has the same userspace visible api.
681 // However it cannot be used by ebpf programs in the same way.
682 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
683 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
684 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
685 // programs as being 5.4+...
686 type = BPF_MAP_TYPE_HASH;
687 }
Connor O'Brien35425e52022-01-18 21:41:16 -0800688 struct bpf_create_map_attr attr = {
689 .name = mapNames[i].c_str(),
690 .map_type = type,
691 .map_flags = md[i].map_flags,
692 .key_size = md[i].key_size,
693 .value_size = md[i].value_size,
694 .max_entries = md[i].max_entries,
695 };
696 if (btfFd.has_value() && btfTypeIdMap.find(mapNames[i]) != btfTypeIdMap.end()) {
697 attr.btf_fd = btfFd->get();
698 attr.btf_key_type_id = btfTypeIdMap.at(mapNames[i]).first;
699 attr.btf_value_type_id = btfTypeIdMap.at(mapNames[i]).second;
700 }
701 fd.reset(bcc_create_map_xattr(&attr, true));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800702 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700703 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700704 }
705
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800706 if (fd < 0) return -saved_errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700707
708 if (!reuse) {
709 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800710 if (ret) return -errno;
711 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
712 if (ret) return -errno;
713 ret = chmod(mapPinLoc.c_str(), md[i].mode);
714 if (ret) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700715 }
716
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700717 struct bpf_map_info map_info = {};
718 __u32 map_info_len = sizeof(map_info);
719 int rv = bpf_obj_get_info_by_fd(fd, &map_info, &map_info_len);
720 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700721 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700722 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700723 ALOGI("map %s id %d", mapPinLoc.c_str(), map_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700724 }
725
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700726 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700727 }
728
729 return ret;
730}
731
732/* For debugging, dump all instructions */
733static void dumpIns(char* ins, int size) {
734 for (int row = 0; row < size / 8; row++) {
735 ALOGE("%d: ", row);
736 for (int j = 0; j < 8; j++) {
737 ALOGE("%3x ", ins[(row * 8) + j]);
738 }
739 ALOGE("\n");
740 }
741}
742
743/* For debugging, dump all code sections from cs list */
744static void dumpAllCs(vector<codeSection>& cs) {
745 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700746 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700747 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700748 ALOGE("-----------");
Joel Fernandesd76a2002018-10-16 13:19:58 -0700749 }
750}
751
752static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
753 int insnIndex;
754 struct bpf_insn *insn, *insns;
755
756 insns = (struct bpf_insn*)(insnsPtr);
757
758 insnIndex = offset / sizeof(struct bpf_insn);
759 insn = &insns[insnIndex];
760
761 ALOGD(
762 "applying relo to instruction at byte offset: %d, \
763 insn offset %d , insn %lx\n",
764 (int)offset, (int)insnIndex, *(unsigned long*)insn);
765
766 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700767 ALOGE("Dumping all instructions till ins %d", insnIndex);
768 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700769 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
770 return;
771 }
772
773 insn->imm = fd;
774 insn->src_reg = BPF_PSEUDO_MAP_FD;
775}
776
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700777static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700778 vector<string> mapNames;
779
Connor O'Brien3278a162020-02-13 21:45:22 -0800780 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700781 if (ret) return;
782
783 for (int k = 0; k != (int)cs.size(); k++) {
784 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
785 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
786
787 for (int i = 0; i < n_rel; i++) {
788 int symIndex = ELF64_R_SYM(rel[i].r_info);
789 string symName;
790
791 ret = getSymNameByIdx(elfFile, symIndex, symName);
792 if (ret) return;
793
794 /* Find the map fd and apply relo */
795 for (int j = 0; j < (int)mapNames.size(); j++) {
796 if (!mapNames[j].compare(symName)) {
797 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
798 break;
799 }
800 }
801 }
802 }
803}
804
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800805static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
806 const char* prefix) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800807 unsigned kvers = kernelVersion();
808 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700809
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800810 if (!kvers) return -1;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700811
812 string fname = pathToFilename(string(elfPath), true);
813
814 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700815 string name = cs[i].name;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800816 unsigned bpfMinVer = DEFAULT_BPFLOADER_MIN_VER; // v0.0
817 unsigned bpfMaxVer = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Joel Fernandesd76a2002018-10-16 13:19:58 -0700818
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800819 if (cs[i].prog_def.has_value()) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700820 unsigned min_kver = cs[i].prog_def->min_kver;
821 unsigned max_kver = cs[i].prog_def->max_kver;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700822 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700823 max_kver, kvers);
824 if (kvers < min_kver) continue;
825 if (kvers >= max_kver) continue;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800826
827 bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
828 bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800829 }
830
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700831 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800832 bpfMinVer, bpfMaxVer);
833 if (BPFLOADER_VERSION < bpfMinVer) continue;
834 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
835
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700836 // strip any potential $foo suffix
837 // this can be used to provide duplicate programs
838 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700839 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700840
841 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700842 // Format of pin location is
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800843 // /sys/fs/bpf/<prefix>prog_<filename>_<mapname>
844 string progPinLoc = BPF_FS_PATH;
845 progPinLoc += prefix;
846 progPinLoc += "prog_";
Maciej Żenczykowski6c7871b2020-04-23 12:46:00 -0700847 progPinLoc += fname;
848 progPinLoc += '_';
849 progPinLoc += name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700850 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700851 fd = retrieveProgram(progPinLoc.c_str());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700852 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd,
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700853 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700854 reuse = true;
855 } else {
856 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
857
Tyler Wear4e2f4602022-02-03 09:46:01 -0800858 struct bpf_load_program_attr attr = {
859 .prog_type = cs[i].type,
860 .name = name.c_str(),
861 .insns = (struct bpf_insn*)cs[i].data.data(),
862 .license = license.c_str(),
863 .log_level = 0,
864 .expected_attach_type = cs[i].expected_attach_type,
865 };
866
867 fd = bcc_prog_load_xattr(&attr, cs[i].data.size(), log_buf.data(), log_buf.size(),
868 true);
869
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700870 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)", elfPath,
Steven Moreland804bca02019-12-12 17:21:23 -0800871 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700872
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800873 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800874 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800875
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700876 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
877 for (const auto& line : lines) ALOGW("%s", line.c_str());
878 ALOGW("bpf_prog_load - END log_buf contents.");
879
880 if (cs[i].prog_def->optional) {
881 ALOGW("failed program is marked optional - continuing...");
882 continue;
883 }
884 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800885 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700886 }
887
888 if (fd < 0) return fd;
889 if (fd == 0) return -EINVAL;
890
891 if (!reuse) {
892 ret = bpf_obj_pin(fd, progPinLoc.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800893 if (ret) return -errno;
Stephane Lee16c93602022-03-08 17:27:09 -0800894 if (chmod(progPinLoc.c_str(), 0440)) return -errno;
Connor O'Brien3278a162020-02-13 21:45:22 -0800895 if (cs[i].prog_def.has_value()) {
896 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
897 (gid_t)cs[i].prog_def->gid)) {
898 return -errno;
899 }
900 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700901 }
902
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700903 struct bpf_prog_info prog_info = {};
904 __u32 prog_info_len = sizeof(prog_info);
905 int rv = bpf_obj_get_info_by_fd(fd, &prog_info, &prog_info_len);
906 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700907 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700908 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700909 ALOGI("prog %s id %d", progPinLoc.c_str(), prog_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700910 }
911
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700912 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700913 }
914
915 return 0;
916}
917
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800918int loadProg(const char* elfPath, bool* isCritical, const char* prefix,
919 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700920 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700921 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700922 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700923 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700924 int ret;
925
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700926 if (!isCritical) return -1;
927 *isCritical = false;
928
Joel Fernandesd76a2002018-10-16 13:19:58 -0700929 ifstream elfFile(elfPath, ios::in | ios::binary);
930 if (!elfFile.is_open()) return -1;
931
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700932 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700933 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700934
Joel Fernandesd76a2002018-10-16 13:19:58 -0700935 ret = readSectionByName("license", elfFile, license);
936 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700937 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700938 return ret;
939 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700940 ALOGD("Loading %s%s ELF object %s with license %s",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700941 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700942 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700943 }
944
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800945 // the following default values are for bpfloader V0.0 format which does not include them
946 unsigned int bpfLoaderMinVer =
947 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
948 unsigned int bpfLoaderMaxVer =
949 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
950 size_t sizeOfBpfMapDef =
951 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
952 size_t sizeOfBpfProgDef =
953 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
954
955 // inclusive lower bound check
956 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700957 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800958 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
959 return 0;
960 }
961
962 // exclusive upper bound check
963 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700964 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800965 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
966 return 0;
967 }
968
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700969 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800970 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
971
972 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700973 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800974 DEFAULT_SIZEOF_BPF_MAP_DEF);
975 return -1;
976 }
977
978 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700979 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800980 DEFAULT_SIZEOF_BPF_PROG_DEF);
981 return -1;
982 }
983
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800984 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, allowed, numAllowed);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700985 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700986 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700987 return ret;
988 }
989
990 /* Just for future debugging */
991 if (0) dumpAllCs(cs);
992
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800993 ret = createMaps(elfPath, elfFile, mapFds, prefix, sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700994 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700995 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700996 return ret;
997 }
998
999 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001000 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001001
1002 applyMapRelo(elfFile, mapFds, cs);
1003
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -08001004 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001005 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001006
1007 return ret;
1008}
1009
Joel Fernandesd76a2002018-10-16 13:19:58 -07001010} // namespace bpf
1011} // namespace android