blob: 9fd7dff0cd86141655f3c1d45f8719f4e4d9c67f [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>
Maciej Żenczykowski83f29772020-01-27 03:11:51 -080027#include <sys/stat.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070028#include <sys/utsname.h>
29#include <unistd.h>
30
Maciej Żenczykowski41661a12021-10-22 21:20:57 -070031// This is BpfLoader v0.6
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080032#define BPFLOADER_VERSION_MAJOR 0u
Maciej Żenczykowski41661a12021-10-22 21:20:57 -070033#define BPFLOADER_VERSION_MINOR 6u
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080034#define BPFLOADER_VERSION ((BPFLOADER_VERSION_MAJOR << 16) | BPFLOADER_VERSION_MINOR)
35
Maciej Żenczykowski730a3862020-01-27 01:10:48 -080036#include "../progs/include/bpf_map_def.h"
Maciej Żenczykowski07375e22020-02-19 14:23:59 -080037#include "bpf/BpfUtils.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070038#include "include/libbpf_android.h"
39
40#include <cstdlib>
41#include <fstream>
42#include <iostream>
Connor O'Brien3278a162020-02-13 21:45:22 -080043#include <optional>
Joel Fernandesd76a2002018-10-16 13:19:58 -070044#include <string>
Christopher Ferrisc151c672019-02-01 15:31:26 -080045#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070046
47#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070048#include <android-base/unique_fd.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070049
50#define BPF_FS_PATH "/sys/fs/bpf/"
51
52// Size of the BPF log buffer for verifier logging
Stephane Leeeb61b732021-10-21 17:03:11 -070053#define BPF_LOAD_LOG_SZ 0xfffff
Joel Fernandesd76a2002018-10-16 13:19:58 -070054
55using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070056using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070057using std::ifstream;
58using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080059using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080060using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070061using std::vector;
62
63namespace android {
64namespace bpf {
65
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -080066static string pathToFilename(const string& path, bool noext = false) {
67 vector<string> spath = android::base::Split(path, "/");
68 string ret = spath.back();
69
70 if (noext) {
71 size_t lastindex = ret.find_last_of('.');
72 return ret.substr(0, lastindex);
73 }
74 return ret;
75}
76
Joel Fernandesd76a2002018-10-16 13:19:58 -070077typedef struct {
78 const char* name;
79 enum bpf_prog_type type;
80} sectionType;
81
82/*
83 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070084 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -070085 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070086 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -070087 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070088 *
89 * However, be aware that you should not be directly using the SECTION() macro.
90 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -070091 */
92sectionType sectionNameTypes[] = {
Maciej Żenczykowskiaa462222021-01-07 14:24:45 -080093 {"kprobe", BPF_PROG_TYPE_KPROBE},
94 {"tracepoint", BPF_PROG_TYPE_TRACEPOINT},
95 {"skfilter", BPF_PROG_TYPE_SOCKET_FILTER},
96 {"cgroupskb", BPF_PROG_TYPE_CGROUP_SKB},
97 {"schedcls", BPF_PROG_TYPE_SCHED_CLS},
Patrick Rohrb28bf2a2021-10-13 08:26:50 +020098 {"schedact", BPF_PROG_TYPE_SCHED_ACT},
Maciej Żenczykowskiaa462222021-01-07 14:24:45 -080099 {"cgroupsock", BPF_PROG_TYPE_CGROUP_SOCK},
100 {"xdp", BPF_PROG_TYPE_XDP},
Tyler Wear25c02852021-10-26 15:38:48 -0700101 {"cgroupsockaddr", BPF_PROG_TYPE_CGROUP_SOCK_ADDR},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700102
Maciej Żenczykowskiaa462222021-01-07 14:24:45 -0800103 /* End of table */
104 {"END", BPF_PROG_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700105};
106
107typedef struct {
108 enum bpf_prog_type type;
109 string name;
110 vector<char> data;
111 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800112 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700113
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700114 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700115} codeSection;
116
Joel Fernandesd76a2002018-10-16 13:19:58 -0700117static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
118 elfFile.seekg(0);
119 if (elfFile.fail()) return -1;
120
121 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
122
123 return 0;
124}
125
126/* Reads all section header tables into an Shdr array */
127static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
128 Elf64_Ehdr eh;
129 int ret = 0;
130
131 ret = readElfHeader(elfFile, &eh);
132 if (ret) return ret;
133
134 elfFile.seekg(eh.e_shoff);
135 if (elfFile.fail()) return -1;
136
137 /* Read shdr table entries */
138 shTable.resize(eh.e_shnum);
139
140 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
141
142 return 0;
143}
144
145/* Read a section by its index - for ex to get sec hdr strtab blob */
146static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
147 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800148 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700149 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700150
151 elfFile.seekg(shTable[id].sh_offset);
152 if (elfFile.fail()) return -1;
153
154 sec.resize(shTable[id].sh_size);
155 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
156
157 return 0;
158}
159
160/* Read whole section header string table */
161static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
162 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800163 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700164 if (ret) return ret;
165
166 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
167 if (ret) return ret;
168
169 return 0;
170}
171
172/* Get name from offset in strtab */
173static int getSymName(ifstream& elfFile, int nameOff, string& name) {
174 int ret;
175 vector<char> secStrTab;
176
177 ret = readSectionHeaderStrtab(elfFile, secStrTab);
178 if (ret) return ret;
179
180 if (nameOff >= (int)secStrTab.size()) return -1;
181
182 name = string((char*)secStrTab.data() + nameOff);
183 return 0;
184}
185
186/* Reads a full section by name - example to get the GPL license */
187static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
188 vector<char> secStrTab;
189 vector<Elf64_Shdr> shTable;
190 int ret;
191
192 ret = readSectionHeadersAll(elfFile, shTable);
193 if (ret) return ret;
194
195 ret = readSectionHeaderStrtab(elfFile, secStrTab);
196 if (ret) return ret;
197
198 for (int i = 0; i < (int)shTable.size(); i++) {
199 char* secname = secStrTab.data() + shTable[i].sh_name;
200 if (!secname) continue;
201
202 if (!strcmp(secname, name)) {
203 vector<char> dataTmp;
204 dataTmp.resize(shTable[i].sh_size);
205
206 elfFile.seekg(shTable[i].sh_offset);
207 if (elfFile.fail()) return -1;
208
209 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
210
211 data = dataTmp;
212 return 0;
213 }
214 }
215 return -2;
216}
217
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700218unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800219 vector<char> theBytes;
220 int ret = readSectionByName(name, elfFile, theBytes);
221 if (ret) {
222 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).\n", name, defVal, defVal);
223 return defVal;
224 } else if (theBytes.size() < sizeof(unsigned int)) {
225 ALOGE("Section %s too short (defaulting to %u [0x%x]).\n", name, defVal, defVal);
226 return defVal;
227 } else {
228 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
229 unsigned int value = static_cast<unsigned char>(theBytes[3]);
230 value <<= 8;
231 value += static_cast<unsigned char>(theBytes[2]);
232 value <<= 8;
233 value += static_cast<unsigned char>(theBytes[1]);
234 value <<= 8;
235 value += static_cast<unsigned char>(theBytes[0]);
236 ALOGI("Section %s value is %u [0x%x]\n", name, value, value);
237 return value;
238 }
239}
240
Joel Fernandesd76a2002018-10-16 13:19:58 -0700241static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
242 int ret;
243 vector<Elf64_Shdr> shTable;
244
245 ret = readSectionHeadersAll(elfFile, shTable);
246 if (ret) return ret;
247
248 for (int i = 0; i < (int)shTable.size(); i++) {
249 if ((int)shTable[i].sh_type != type) continue;
250
251 vector<char> dataTmp;
252 dataTmp.resize(shTable[i].sh_size);
253
254 elfFile.seekg(shTable[i].sh_offset);
255 if (elfFile.fail()) return -1;
256
257 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
258
259 data = dataTmp;
260 return 0;
261 }
262 return -2;
263}
264
265static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
266 return (a.st_value < b.st_value);
267}
268
269static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
270 int ret, numElems;
271 Elf64_Sym* buf;
272 vector<char> secData;
273
274 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
275 if (ret) return ret;
276
277 buf = (Elf64_Sym*)secData.data();
278 numElems = (secData.size() / sizeof(Elf64_Sym));
279 data.assign(buf, buf + numElems);
280
281 if (sort) std::sort(data.begin(), data.end(), symCompare);
282 return 0;
283}
284
285static enum bpf_prog_type getSectionType(string& name) {
286 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++)
287 if (StartsWith(name, sectionNameTypes[i].name)) return sectionNameTypes[i].type;
288
289 return BPF_PROG_TYPE_UNSPEC;
290}
291
292/* If ever needed
293static string getSectionName(enum bpf_prog_type type)
294{
295 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++)
296 if (sectionNameTypes[i].type == type)
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800297 return string(sectionNameTypes[i].name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700298
299 return NULL;
300}
301*/
302
303static bool isRelSection(codeSection& cs, string& name) {
304 for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++) {
305 sectionType st = sectionNameTypes[i];
306
307 if (st.type != cs.type) continue;
308
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800309 if (StartsWith(name, string(".rel") + st.name + "/"))
Joel Fernandesd76a2002018-10-16 13:19:58 -0700310 return true;
311 else
312 return false;
313 }
314 return false;
315}
316
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800317static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
318 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800319 vector<char> pdData;
320 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800321 // Older file formats do not require a 'progs' section at all.
322 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800323 if (ret == -2) return 0;
324 if (ret) return ret;
325
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800326 if (pdData.size() % sizeOfBpfProgDef) {
327 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0\n",
328 pdData.size(), sizeOfBpfProgDef);
329 return -1;
330 };
331
332 int progCount = pdData.size() / sizeOfBpfProgDef;
333 pd.resize(progCount);
334 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
335
336 const char* dataPtr = pdData.data();
337 for (auto& p : pd) {
338 // First we zero initialize
339 memset(&p, 0, sizeof(p));
340 // Then we set non-zero defaults
341 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
342 // Then we copy over the structure prefix from the ELF file.
343 memcpy(&p, dataPtr, trimmedSize);
344 // Move to next struct in the ELF file
345 dataPtr += sizeOfBpfProgDef;
346 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800347 return 0;
348}
349
350static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names) {
351 int ret;
352 string name;
353 vector<Elf64_Sym> symtab;
354 vector<Elf64_Shdr> shTable;
355
356 ret = readSymTab(elfFile, 1 /* sort */, symtab);
357 if (ret) return ret;
358
359 /* Get index of section */
360 ret = readSectionHeadersAll(elfFile, shTable);
361 if (ret) return ret;
362
363 int sec_idx = -1;
364 for (int i = 0; i < (int)shTable.size(); i++) {
365 ret = getSymName(elfFile, shTable[i].sh_name, name);
366 if (ret) return ret;
367
368 if (!name.compare(sectionName)) {
369 sec_idx = i;
370 break;
371 }
372 }
373
374 /* No section found with matching name*/
375 if (sec_idx == -1) {
Maciej Żenczykowski21f34cb2020-07-20 18:44:33 -0700376 ALOGW("No %s section could be found in elf object\n", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800377 return -1;
378 }
379
380 for (int i = 0; i < (int)symtab.size(); i++) {
381 if (symtab[i].st_shndx == sec_idx) {
382 string s;
383 ret = getSymName(elfFile, symtab[i].st_name, s);
384 if (ret) return ret;
385 names.push_back(s);
386 }
387 }
388
389 return 0;
390}
391
Joel Fernandesd76a2002018-10-16 13:19:58 -0700392/* Read a section by its index - for ex to get sec hdr strtab blob */
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800393static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700394 vector<Elf64_Shdr> shTable;
395 int entries, ret = 0;
396
397 ret = readSectionHeadersAll(elfFile, shTable);
398 if (ret) return ret;
399 entries = shTable.size();
400
Connor O'Brien3278a162020-02-13 21:45:22 -0800401 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800402 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800403 if (ret) return ret;
404 vector<string> progDefNames;
405 ret = getSectionSymNames(elfFile, "progs", progDefNames);
406 if (!pd.empty() && ret) return ret;
407
Joel Fernandesd76a2002018-10-16 13:19:58 -0700408 for (int i = 0; i < entries; i++) {
409 string name;
410 codeSection cs_temp;
411 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
412
413 ret = getSymName(elfFile, shTable[i].sh_name, name);
414 if (ret) return ret;
415
416 enum bpf_prog_type ptype = getSectionType(name);
417 if (ptype != BPF_PROG_TYPE_UNSPEC) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800418 string oldName = name;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800419
420 // convert all slashes to underscores
421 std::replace(name.begin(), name.end(), '/', '_');
422
Joel Fernandesd76a2002018-10-16 13:19:58 -0700423 cs_temp.type = ptype;
424 cs_temp.name = name;
425
426 ret = readSectionByIdx(elfFile, i, cs_temp.data);
427 if (ret) return ret;
428 ALOGD("Loaded code section %d (%s)\n", i, name.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800429
430 vector<string> csSymNames;
431 ret = getSectionSymNames(elfFile, oldName, csSymNames);
432 if (ret || !csSymNames.size()) return ret;
433 for (size_t i = 0; i < progDefNames.size(); ++i) {
434 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
435 cs_temp.prog_def = pd[i];
436 break;
437 }
438 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700439 }
440
441 /* Check for rel section */
442 if (cs_temp.data.size() > 0 && i < entries) {
443 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
444 if (ret) return ret;
445
446 if (isRelSection(cs_temp, name)) {
447 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
448 if (ret) return ret;
449 ALOGD("Loaded relo section %d (%s)\n", i, name.c_str());
450 }
451 }
452
453 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700454 cs.push_back(std::move(cs_temp));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700455 ALOGD("Adding section %d to cs list\n", i);
456 }
457 }
458 return 0;
459}
460
461static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
462 vector<Elf64_Sym> symtab;
463 int ret = 0;
464
465 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
466 if (ret) return ret;
467
468 if (index >= (int)symtab.size()) return -1;
469
470 return getSymName(elfFile, symtab[index].st_name, name);
471}
472
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800473static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800474 const char* prefix, size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700475 int ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700476 vector<char> mdData;
477 vector<struct bpf_map_def> md;
478 vector<string> mapNames;
479 string fname = pathToFilename(string(elfPath), true);
480
481 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800482 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700483 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800484
485 if (mdData.size() % sizeOfBpfMapDef) {
486 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0\n",
487 mdData.size(), sizeOfBpfMapDef);
488 return -1;
489 };
490
491 int mapCount = mdData.size() / sizeOfBpfMapDef;
492 md.resize(mapCount);
493 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
494
495 const char* dataPtr = mdData.data();
496 for (auto& m : md) {
497 // First we zero initialize
498 memset(&m, 0, sizeof(m));
499 // Then we set non-zero defaults
500 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700501 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800502 // Then we copy over the structure prefix from the ELF file.
503 memcpy(&m, dataPtr, trimmedSize);
504 // Move to next struct in the ELF file
505 dataPtr += sizeOfBpfMapDef;
506 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700507
Connor O'Brien3278a162020-02-13 21:45:22 -0800508 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700509 if (ret) return ret;
510
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700511 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700512
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700513 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800514 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
515 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x\n", mapNames[i].c_str(),
516 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700517 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800518 continue;
519 }
520
521 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
522 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x\n", mapNames[i].c_str(),
523 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700524 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800525 continue;
526 }
527
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700528 if (kvers < md[i].min_kver) {
529 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x\n",
530 mapNames[i].c_str(), kvers, md[i].min_kver);
531 mapFds.push_back(unique_fd());
532 continue;
533 }
534
535 if (kvers >= md[i].max_kver) {
536 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x\n",
537 mapNames[i].c_str(), kvers, md[i].max_kver);
538 mapFds.push_back(unique_fd());
539 continue;
540 }
541
542 // Format of pin location is /sys/fs/bpf/<prefix>map_<filename>_<mapname>
543 string mapPinLoc =
544 string(BPF_FS_PATH) + prefix + "map_" + fname + "_" + string(mapNames[i]);
545 bool reuse = false;
546 unique_fd fd;
547 int saved_errno;
548
Joel Fernandesd76a2002018-10-16 13:19:58 -0700549 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700550 fd.reset(bpf_obj_get(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800551 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700552 ALOGD("bpf_create_map reusing map %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700553 reuse = true;
554 } else {
Maciej Żenczykowskicb358de2021-03-04 07:27:38 -0800555 enum bpf_map_type type = md[i].type;
556 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
557 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
558 // of be approximated: ARRAY has the same userspace api, though it is not usable
559 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
560 // helper doesn't exist on 4.9 anyway (so the bpf program would fail to load,
561 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
562 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
563 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
564 type = BPF_MAP_TYPE_ARRAY;
565 }
566 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
567 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
568 // of be approximated: HASH has the same userspace visible api.
569 // However it cannot be used by ebpf programs in the same way.
570 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
571 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
572 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
573 // programs as being 5.4+...
574 type = BPF_MAP_TYPE_HASH;
575 }
576 fd.reset(bpf_create_map(type, mapNames[i].c_str(), md[i].key_size, md[i].value_size,
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700577 md[i].max_entries, md[i].map_flags));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800578 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700579 ALOGD("bpf_create_map name %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700580 }
581
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800582 if (fd < 0) return -saved_errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700583
584 if (!reuse) {
585 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800586 if (ret) return -errno;
587 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
588 if (ret) return -errno;
589 ret = chmod(mapPinLoc.c_str(), md[i].mode);
590 if (ret) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700591 }
592
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700593 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700594 }
595
596 return ret;
597}
598
599/* For debugging, dump all instructions */
600static void dumpIns(char* ins, int size) {
601 for (int row = 0; row < size / 8; row++) {
602 ALOGE("%d: ", row);
603 for (int j = 0; j < 8; j++) {
604 ALOGE("%3x ", ins[(row * 8) + j]);
605 }
606 ALOGE("\n");
607 }
608}
609
610/* For debugging, dump all code sections from cs list */
611static void dumpAllCs(vector<codeSection>& cs) {
612 for (int i = 0; i < (int)cs.size(); i++) {
613 ALOGE("Dumping cs %d, name %s\n", int(i), cs[i].name.c_str());
614 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
615 ALOGE("-----------\n");
616 }
617}
618
619static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
620 int insnIndex;
621 struct bpf_insn *insn, *insns;
622
623 insns = (struct bpf_insn*)(insnsPtr);
624
625 insnIndex = offset / sizeof(struct bpf_insn);
626 insn = &insns[insnIndex];
627
628 ALOGD(
629 "applying relo to instruction at byte offset: %d, \
630 insn offset %d , insn %lx\n",
631 (int)offset, (int)insnIndex, *(unsigned long*)insn);
632
633 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
634 ALOGE("Dumping all instructions till ins %d\n", insnIndex);
635 ALOGE("invalid relo for insn %d: code 0x%x\n", insnIndex, insn->code);
636 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
637 return;
638 }
639
640 insn->imm = fd;
641 insn->src_reg = BPF_PSEUDO_MAP_FD;
642}
643
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700644static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700645 vector<string> mapNames;
646
Connor O'Brien3278a162020-02-13 21:45:22 -0800647 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700648 if (ret) return;
649
650 for (int k = 0; k != (int)cs.size(); k++) {
651 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
652 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
653
654 for (int i = 0; i < n_rel; i++) {
655 int symIndex = ELF64_R_SYM(rel[i].r_info);
656 string symName;
657
658 ret = getSymNameByIdx(elfFile, symIndex, symName);
659 if (ret) return;
660
661 /* Find the map fd and apply relo */
662 for (int j = 0; j < (int)mapNames.size(); j++) {
663 if (!mapNames[j].compare(symName)) {
664 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
665 break;
666 }
667 }
668 }
669 }
670}
671
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800672static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
673 const char* prefix) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800674 unsigned kvers = kernelVersion();
675 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700676
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800677 if (!kvers) return -1;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700678
679 string fname = pathToFilename(string(elfPath), true);
680
681 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700682 string name = cs[i].name;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800683 unsigned bpfMinVer = DEFAULT_BPFLOADER_MIN_VER; // v0.0
684 unsigned bpfMaxVer = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Joel Fernandesd76a2002018-10-16 13:19:58 -0700685
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800686 if (cs[i].prog_def.has_value()) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700687 unsigned min_kver = cs[i].prog_def->min_kver;
688 unsigned max_kver = cs[i].prog_def->max_kver;
689 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)\n", i, name.c_str(), min_kver,
690 max_kver, kvers);
691 if (kvers < min_kver) continue;
692 if (kvers >= max_kver) continue;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800693
694 bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
695 bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800696 }
697
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800698 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)\n", i, name.c_str(),
699 bpfMinVer, bpfMaxVer);
700 if (BPFLOADER_VERSION < bpfMinVer) continue;
701 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
702
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700703 // strip any potential $foo suffix
704 // this can be used to provide duplicate programs
705 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700706 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700707
708 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700709 // Format of pin location is
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800710 // /sys/fs/bpf/<prefix>prog_<filename>_<mapname>
711 string progPinLoc = BPF_FS_PATH;
712 progPinLoc += prefix;
713 progPinLoc += "prog_";
Maciej Żenczykowski6c7871b2020-04-23 12:46:00 -0700714 progPinLoc += fname;
715 progPinLoc += '_';
716 progPinLoc += name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700717 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700718 fd = retrieveProgram(progPinLoc.c_str());
719 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)\n", progPinLoc.c_str(), fd,
720 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700721 reuse = true;
722 } else {
723 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
724
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700725 fd = bpf_prog_load(cs[i].type, name.c_str(), (struct bpf_insn*)cs[i].data.data(),
726 cs[i].data.size(), license.c_str(), kvers, 0, log_buf.data(),
727 log_buf.size());
Steven Moreland804bca02019-12-12 17:21:23 -0800728 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)\n", elfPath,
729 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700730
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800731 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800732 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800733
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700734 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
735 for (const auto& line : lines) ALOGW("%s", line.c_str());
736 ALOGW("bpf_prog_load - END log_buf contents.");
737
738 if (cs[i].prog_def->optional) {
739 ALOGW("failed program is marked optional - continuing...");
740 continue;
741 }
742 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800743 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700744 }
745
746 if (fd < 0) return fd;
747 if (fd == 0) return -EINVAL;
748
749 if (!reuse) {
750 ret = bpf_obj_pin(fd, progPinLoc.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800751 if (ret) return -errno;
752 if (cs[i].prog_def.has_value()) {
753 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
754 (gid_t)cs[i].prog_def->gid)) {
755 return -errno;
756 }
757 }
758 if (chmod(progPinLoc.c_str(), 0440)) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700759 }
760
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700761 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700762 }
763
764 return 0;
765}
766
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800767int loadProg(const char* elfPath, bool* isCritical, const char* prefix) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700768 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700769 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700770 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700771 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700772 int ret;
773
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700774 if (!isCritical) return -1;
775 *isCritical = false;
776
Joel Fernandesd76a2002018-10-16 13:19:58 -0700777 ifstream elfFile(elfPath, ios::in | ios::binary);
778 if (!elfFile.is_open()) return -1;
779
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700780 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700781 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700782
Joel Fernandesd76a2002018-10-16 13:19:58 -0700783 ret = readSectionByName("license", elfFile, license);
784 if (ret) {
785 ALOGE("Couldn't find license in %s\n", elfPath);
786 return ret;
787 } else {
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700788 ALOGD("Loading %s%s ELF object %s with license %s\n",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700789 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700790 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700791 }
792
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800793 // the following default values are for bpfloader V0.0 format which does not include them
794 unsigned int bpfLoaderMinVer =
795 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
796 unsigned int bpfLoaderMaxVer =
797 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
798 size_t sizeOfBpfMapDef =
799 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
800 size_t sizeOfBpfProgDef =
801 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
802
803 // inclusive lower bound check
804 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
805 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x\n",
806 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
807 return 0;
808 }
809
810 // exclusive upper bound check
811 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
812 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x\n",
813 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
814 return 0;
815 }
816
817 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)\n",
818 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
819
820 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
821 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)\n", sizeOfBpfMapDef,
822 DEFAULT_SIZEOF_BPF_MAP_DEF);
823 return -1;
824 }
825
826 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
827 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)\n", sizeOfBpfProgDef,
828 DEFAULT_SIZEOF_BPF_PROG_DEF);
829 return -1;
830 }
831
832 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700833 if (ret) {
834 ALOGE("Couldn't read all code sections in %s\n", elfPath);
835 return ret;
836 }
837
838 /* Just for future debugging */
839 if (0) dumpAllCs(cs);
840
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800841 ret = createMaps(elfPath, elfFile, mapFds, prefix, sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700842 if (ret) {
843 ALOGE("Failed to create maps: (ret=%d) in %s\n", ret, elfPath);
844 return ret;
845 }
846
847 for (int i = 0; i < (int)mapFds.size(); i++)
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700848 ALOGD("map_fd found at %d is %d in %s\n", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700849
850 applyMapRelo(elfFile, mapFds, cs);
851
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800852 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700853 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d\n", ret);
854
855 return ret;
856}
857
Joel Fernandesd76a2002018-10-16 13:19:58 -0700858} // namespace bpf
859} // namespace android