blob: f06d20f5f579f09ca6845d673e2a5e6cd18455f5 [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 Żenczykowski12bb5202022-06-16 15:50:58 -070033// This is BpfLoader v0.17
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080034#define BPFLOADER_VERSION_MAJOR 0u
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -070035#define BPFLOADER_VERSION_MINOR 17u
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 {};
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700564 if (!btfFd.ok()) return {};
Connor O'Brien35425e52022-01-18 21:41:16 -0800565
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 Żenczykowski12bb5202022-06-16 15:50:58 -0700579static bool mapMatchesExpectations(unique_fd& fd, string& mapName, struct bpf_map_def& mapDef,
580 enum bpf_map_type type) {
581 // bpfGetFd... family of functions require at minimum a 4.14 kernel,
582 // so on 4.9 kernels just pretend the map matches our expectations.
583 // This isn't really a problem as we only really support 4.14+ anyway...
584 // Additionally we'll get almost equivalent test coverage on newer devices/kernels.
585 // This is because the primary failure mode we're trying to detect here
586 // is either a source code misconfiguration (which is likely kernel independent)
587 // or a newly introduced kernel feature/bug (which is unlikely to get backported to 4.9).
588 if (!isAtLeastKernelVersion(4, 14, 0)) return true;
589
590 // These asserts should *never* trigger, if one of them somehow does,
591 // it probably means a bpf .o file has been changed/replaced at runtime
592 // and bpfloader was manually rerun (normally it should only run *once*
593 // early during the boot process).
594 // Another possibility is that something is misconfigured in the code:
595 // most likely a shared map is declared twice differently.
596 // But such a change should never be checked into the source tree...
597 int fd_type = bpfGetFdMapType(fd);
598 int fd_key_size = bpfGetFdKeySize(fd);
599 int fd_value_size = bpfGetFdValueSize(fd);
600 int fd_max_entries = bpfGetFdMaxEntries(fd);
601 int fd_map_flags = bpfGetFdMapFlags(fd);
602
603 // DEVMAPs are readonly from the bpf program side's point of view, as such
604 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
605 int desired_map_flags = (int)mapDef.map_flags;
606 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
607 desired_map_flags |= BPF_F_RDONLY_PROG;
608
609 // If anything doesn't match, just close the fd - it's of no use anyway.
610 if (fd_type != type) fd.reset();
611 if (fd_key_size != (int)mapDef.key_size) fd.reset();
612 if (fd_value_size != (int)mapDef.value_size) fd.reset();
613 if (fd_max_entries != (int)mapDef.max_entries) fd.reset();
614 if (fd_map_flags != desired_map_flags) fd.reset();
615
616 if (fd.ok()) return true;
617
618 ALOGE("bpf map name %s mismatch: desired/found: "
619 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
620 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
621 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
622 return false;
623}
624
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800625static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800626 const char* prefix, size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700627 int ret;
Connor O'Brien35425e52022-01-18 21:41:16 -0800628 vector<char> mdData, btfData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700629 vector<struct bpf_map_def> md;
630 vector<string> mapNames;
Connor O'Brien35425e52022-01-18 21:41:16 -0800631 std::unordered_map<string, std::pair<uint32_t, uint32_t>> btfTypeIdMap;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700632 string fname = pathToFilename(string(elfPath), true);
633
634 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800635 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700636 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800637
638 if (mdData.size() % sizeOfBpfMapDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700639 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800640 mdData.size(), sizeOfBpfMapDef);
641 return -1;
642 };
643
644 int mapCount = mdData.size() / sizeOfBpfMapDef;
645 md.resize(mapCount);
646 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
647
648 const char* dataPtr = mdData.data();
649 for (auto& m : md) {
650 // First we zero initialize
651 memset(&m, 0, sizeof(m));
652 // Then we set non-zero defaults
653 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700654 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800655 // Then we copy over the structure prefix from the ELF file.
656 memcpy(&m, dataPtr, trimmedSize);
657 // Move to next struct in the ELF file
658 dataPtr += sizeOfBpfMapDef;
659 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700660
Connor O'Brien3278a162020-02-13 21:45:22 -0800661 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700662 if (ret) return ret;
663
Connor O'Brien35425e52022-01-18 21:41:16 -0800664 std::optional<unique_fd> btfFd;
665 if (!readSectionByName(".BTF", elfFile, btfData)) {
666 btfFd = getMapBtfInfo(elfPath, btfTypeIdMap);
667 }
668
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700669 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700670
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700671 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800672 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700673 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800674 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700675 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800676 continue;
677 }
678
679 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700680 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800681 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700682 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800683 continue;
684 }
685
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700686 if (kvers < md[i].min_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700687 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700688 mapNames[i].c_str(), kvers, md[i].min_kver);
689 mapFds.push_back(unique_fd());
690 continue;
691 }
692
693 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700694 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700695 mapNames[i].c_str(), kvers, md[i].max_kver);
696 mapFds.push_back(unique_fd());
697 continue;
698 }
699
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700700 enum bpf_map_type type = md[i].type;
701 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
702 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
703 // of be approximated: ARRAY has the same userspace api, though it is not usable
704 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
705 // helper doesn't exist on 4.9 anyway (so the bpf program would fail to load,
706 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
707 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
708 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
709 type = BPF_MAP_TYPE_ARRAY;
710 }
711 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
712 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
713 // of be approximated: HASH has the same userspace visible api.
714 // However it cannot be used by ebpf programs in the same way.
715 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
716 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
717 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
718 // programs as being 5.4+...
719 type = BPF_MAP_TYPE_HASH;
720 }
721
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700722 // Format of pin location is /sys/fs/bpf/<prefix>map_<filename>_<mapname>
723 string mapPinLoc =
724 string(BPF_FS_PATH) + prefix + "map_" + fname + "_" + string(mapNames[i]);
725 bool reuse = false;
726 unique_fd fd;
727 int saved_errno;
728
Joel Fernandesd76a2002018-10-16 13:19:58 -0700729 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700730 fd.reset(bpf_obj_get(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800731 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700732 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700733 reuse = true;
734 } else {
Connor O'Brien35425e52022-01-18 21:41:16 -0800735 struct bpf_create_map_attr attr = {
736 .name = mapNames[i].c_str(),
737 .map_type = type,
738 .map_flags = md[i].map_flags,
739 .key_size = md[i].key_size,
740 .value_size = md[i].value_size,
741 .max_entries = md[i].max_entries,
742 };
743 if (btfFd.has_value() && btfTypeIdMap.find(mapNames[i]) != btfTypeIdMap.end()) {
744 attr.btf_fd = btfFd->get();
745 attr.btf_key_type_id = btfTypeIdMap.at(mapNames[i]).first;
746 attr.btf_value_type_id = btfTypeIdMap.at(mapNames[i]).second;
747 }
748 fd.reset(bcc_create_map_xattr(&attr, true));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800749 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700750 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700751 }
752
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700753 if (!fd.ok()) return -saved_errno;
754
755 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
756 // safety (since reuse code path is rare) run these checks even if we just created it.
757 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
758 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700759
760 if (!reuse) {
761 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800762 if (ret) return -errno;
763 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
764 if (ret) return -errno;
765 ret = chmod(mapPinLoc.c_str(), md[i].mode);
766 if (ret) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700767 }
768
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700769 struct bpf_map_info map_info = {};
770 __u32 map_info_len = sizeof(map_info);
771 int rv = bpf_obj_get_info_by_fd(fd, &map_info, &map_info_len);
772 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700773 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700774 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700775 ALOGI("map %s id %d", mapPinLoc.c_str(), map_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700776 }
777
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700778 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700779 }
780
781 return ret;
782}
783
784/* For debugging, dump all instructions */
785static void dumpIns(char* ins, int size) {
786 for (int row = 0; row < size / 8; row++) {
787 ALOGE("%d: ", row);
788 for (int j = 0; j < 8; j++) {
789 ALOGE("%3x ", ins[(row * 8) + j]);
790 }
791 ALOGE("\n");
792 }
793}
794
795/* For debugging, dump all code sections from cs list */
796static void dumpAllCs(vector<codeSection>& cs) {
797 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700798 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700799 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700800 ALOGE("-----------");
Joel Fernandesd76a2002018-10-16 13:19:58 -0700801 }
802}
803
804static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
805 int insnIndex;
806 struct bpf_insn *insn, *insns;
807
808 insns = (struct bpf_insn*)(insnsPtr);
809
810 insnIndex = offset / sizeof(struct bpf_insn);
811 insn = &insns[insnIndex];
812
813 ALOGD(
814 "applying relo to instruction at byte offset: %d, \
815 insn offset %d , insn %lx\n",
816 (int)offset, (int)insnIndex, *(unsigned long*)insn);
817
818 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700819 ALOGE("Dumping all instructions till ins %d", insnIndex);
820 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700821 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
822 return;
823 }
824
825 insn->imm = fd;
826 insn->src_reg = BPF_PSEUDO_MAP_FD;
827}
828
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700829static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700830 vector<string> mapNames;
831
Connor O'Brien3278a162020-02-13 21:45:22 -0800832 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700833 if (ret) return;
834
835 for (int k = 0; k != (int)cs.size(); k++) {
836 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
837 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
838
839 for (int i = 0; i < n_rel; i++) {
840 int symIndex = ELF64_R_SYM(rel[i].r_info);
841 string symName;
842
843 ret = getSymNameByIdx(elfFile, symIndex, symName);
844 if (ret) return;
845
846 /* Find the map fd and apply relo */
847 for (int j = 0; j < (int)mapNames.size(); j++) {
848 if (!mapNames[j].compare(symName)) {
849 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
850 break;
851 }
852 }
853 }
854 }
855}
856
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800857static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
858 const char* prefix) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800859 unsigned kvers = kernelVersion();
860 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700861
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800862 if (!kvers) return -1;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700863
864 string fname = pathToFilename(string(elfPath), true);
865
866 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700867 string name = cs[i].name;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800868 unsigned bpfMinVer = DEFAULT_BPFLOADER_MIN_VER; // v0.0
869 unsigned bpfMaxVer = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Joel Fernandesd76a2002018-10-16 13:19:58 -0700870
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800871 if (cs[i].prog_def.has_value()) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700872 unsigned min_kver = cs[i].prog_def->min_kver;
873 unsigned max_kver = cs[i].prog_def->max_kver;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700874 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 -0700875 max_kver, kvers);
876 if (kvers < min_kver) continue;
877 if (kvers >= max_kver) continue;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800878
879 bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
880 bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800881 }
882
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700883 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800884 bpfMinVer, bpfMaxVer);
885 if (BPFLOADER_VERSION < bpfMinVer) continue;
886 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
887
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700888 // strip any potential $foo suffix
889 // this can be used to provide duplicate programs
890 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700891 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700892
893 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700894 // Format of pin location is
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800895 // /sys/fs/bpf/<prefix>prog_<filename>_<mapname>
896 string progPinLoc = BPF_FS_PATH;
897 progPinLoc += prefix;
898 progPinLoc += "prog_";
Maciej Żenczykowski6c7871b2020-04-23 12:46:00 -0700899 progPinLoc += fname;
900 progPinLoc += '_';
901 progPinLoc += name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700902 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700903 fd = retrieveProgram(progPinLoc.c_str());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700904 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd,
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700905 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700906 reuse = true;
907 } else {
908 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
909
Tyler Wear4e2f4602022-02-03 09:46:01 -0800910 struct bpf_load_program_attr attr = {
911 .prog_type = cs[i].type,
912 .name = name.c_str(),
913 .insns = (struct bpf_insn*)cs[i].data.data(),
914 .license = license.c_str(),
915 .log_level = 0,
916 .expected_attach_type = cs[i].expected_attach_type,
917 };
918
919 fd = bcc_prog_load_xattr(&attr, cs[i].data.size(), log_buf.data(), log_buf.size(),
920 true);
921
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700922 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)", elfPath,
Steven Moreland804bca02019-12-12 17:21:23 -0800923 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700924
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800925 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800926 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800927
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700928 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
929 for (const auto& line : lines) ALOGW("%s", line.c_str());
930 ALOGW("bpf_prog_load - END log_buf contents.");
931
932 if (cs[i].prog_def->optional) {
933 ALOGW("failed program is marked optional - continuing...");
934 continue;
935 }
936 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800937 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700938 }
939
940 if (fd < 0) return fd;
941 if (fd == 0) return -EINVAL;
942
943 if (!reuse) {
944 ret = bpf_obj_pin(fd, progPinLoc.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800945 if (ret) return -errno;
Stephane Lee16c93602022-03-08 17:27:09 -0800946 if (chmod(progPinLoc.c_str(), 0440)) return -errno;
Connor O'Brien3278a162020-02-13 21:45:22 -0800947 if (cs[i].prog_def.has_value()) {
948 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
949 (gid_t)cs[i].prog_def->gid)) {
950 return -errno;
951 }
952 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700953 }
954
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700955 struct bpf_prog_info prog_info = {};
956 __u32 prog_info_len = sizeof(prog_info);
957 int rv = bpf_obj_get_info_by_fd(fd, &prog_info, &prog_info_len);
958 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700959 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700960 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700961 ALOGI("prog %s id %d", progPinLoc.c_str(), prog_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700962 }
963
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700964 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700965 }
966
967 return 0;
968}
969
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800970int loadProg(const char* elfPath, bool* isCritical, const char* prefix,
971 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700972 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700973 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700974 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700975 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700976 int ret;
977
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700978 if (!isCritical) return -1;
979 *isCritical = false;
980
Joel Fernandesd76a2002018-10-16 13:19:58 -0700981 ifstream elfFile(elfPath, ios::in | ios::binary);
982 if (!elfFile.is_open()) return -1;
983
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700984 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700985 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700986
Joel Fernandesd76a2002018-10-16 13:19:58 -0700987 ret = readSectionByName("license", elfFile, license);
988 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700989 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700990 return ret;
991 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700992 ALOGD("Loading %s%s ELF object %s with license %s",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700993 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700994 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700995 }
996
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800997 // the following default values are for bpfloader V0.0 format which does not include them
998 unsigned int bpfLoaderMinVer =
999 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1000 unsigned int bpfLoaderMaxVer =
1001 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
1002 size_t sizeOfBpfMapDef =
1003 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1004 size_t sizeOfBpfProgDef =
1005 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1006
1007 // inclusive lower bound check
1008 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001009 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001010 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
1011 return 0;
1012 }
1013
1014 // exclusive upper bound check
1015 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001016 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001017 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
1018 return 0;
1019 }
1020
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001021 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001022 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1023
1024 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001025 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001026 DEFAULT_SIZEOF_BPF_MAP_DEF);
1027 return -1;
1028 }
1029
1030 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001031 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001032 DEFAULT_SIZEOF_BPF_PROG_DEF);
1033 return -1;
1034 }
1035
Steven Moreland0f10f3f2019-12-12 14:22:34 -08001036 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, allowed, numAllowed);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001037 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001038 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001039 return ret;
1040 }
1041
1042 /* Just for future debugging */
1043 if (0) dumpAllCs(cs);
1044
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001045 ret = createMaps(elfPath, elfFile, mapFds, prefix, sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001046 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001047 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001048 return ret;
1049 }
1050
1051 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001052 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001053
1054 applyMapRelo(elfFile, mapFds, cs);
1055
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -08001056 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001057 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001058
1059 return ret;
1060}
1061
Joel Fernandesd76a2002018-10-16 13:19:58 -07001062} // namespace bpf
1063} // namespace android