blob: 77b865af3dfe0c965a2bf560aba496db0ae40d3b [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 Żenczykowski2b203132021-11-18 15:13:36 -080031// This is BpfLoader v0.7
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080032#define BPFLOADER_VERSION_MAJOR 0u
Maciej Żenczykowski2b203132021-11-18 15:13:36 -080033#define BPFLOADER_VERSION_MINOR 7u
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 Żenczykowski2b203132021-11-18 15:13:36 -080093 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB},
94 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK},
95 {"cgroupsockaddr/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR},
96 {"kprobe/", BPF_PROG_TYPE_KPROBE},
97 {"schedact/", BPF_PROG_TYPE_SCHED_ACT},
98 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS},
99 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER},
100 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT},
101 {"xdp/", BPF_PROG_TYPE_XDP},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700102};
103
104typedef struct {
105 enum bpf_prog_type type;
106 string name;
107 vector<char> data;
108 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800109 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700110
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700111 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700112} codeSection;
113
Joel Fernandesd76a2002018-10-16 13:19:58 -0700114static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
115 elfFile.seekg(0);
116 if (elfFile.fail()) return -1;
117
118 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
119
120 return 0;
121}
122
123/* Reads all section header tables into an Shdr array */
124static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
125 Elf64_Ehdr eh;
126 int ret = 0;
127
128 ret = readElfHeader(elfFile, &eh);
129 if (ret) return ret;
130
131 elfFile.seekg(eh.e_shoff);
132 if (elfFile.fail()) return -1;
133
134 /* Read shdr table entries */
135 shTable.resize(eh.e_shnum);
136
137 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
138
139 return 0;
140}
141
142/* Read a section by its index - for ex to get sec hdr strtab blob */
143static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
144 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800145 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700146 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700147
148 elfFile.seekg(shTable[id].sh_offset);
149 if (elfFile.fail()) return -1;
150
151 sec.resize(shTable[id].sh_size);
152 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
153
154 return 0;
155}
156
157/* Read whole section header string table */
158static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
159 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800160 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700161 if (ret) return ret;
162
163 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
164 if (ret) return ret;
165
166 return 0;
167}
168
169/* Get name from offset in strtab */
170static int getSymName(ifstream& elfFile, int nameOff, string& name) {
171 int ret;
172 vector<char> secStrTab;
173
174 ret = readSectionHeaderStrtab(elfFile, secStrTab);
175 if (ret) return ret;
176
177 if (nameOff >= (int)secStrTab.size()) return -1;
178
179 name = string((char*)secStrTab.data() + nameOff);
180 return 0;
181}
182
183/* Reads a full section by name - example to get the GPL license */
184static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
185 vector<char> secStrTab;
186 vector<Elf64_Shdr> shTable;
187 int ret;
188
189 ret = readSectionHeadersAll(elfFile, shTable);
190 if (ret) return ret;
191
192 ret = readSectionHeaderStrtab(elfFile, secStrTab);
193 if (ret) return ret;
194
195 for (int i = 0; i < (int)shTable.size(); i++) {
196 char* secname = secStrTab.data() + shTable[i].sh_name;
197 if (!secname) continue;
198
199 if (!strcmp(secname, name)) {
200 vector<char> dataTmp;
201 dataTmp.resize(shTable[i].sh_size);
202
203 elfFile.seekg(shTable[i].sh_offset);
204 if (elfFile.fail()) return -1;
205
206 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
207
208 data = dataTmp;
209 return 0;
210 }
211 }
212 return -2;
213}
214
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700215unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800216 vector<char> theBytes;
217 int ret = readSectionByName(name, elfFile, theBytes);
218 if (ret) {
219 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).\n", name, defVal, defVal);
220 return defVal;
221 } else if (theBytes.size() < sizeof(unsigned int)) {
222 ALOGE("Section %s too short (defaulting to %u [0x%x]).\n", name, defVal, defVal);
223 return defVal;
224 } else {
225 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
226 unsigned int value = static_cast<unsigned char>(theBytes[3]);
227 value <<= 8;
228 value += static_cast<unsigned char>(theBytes[2]);
229 value <<= 8;
230 value += static_cast<unsigned char>(theBytes[1]);
231 value <<= 8;
232 value += static_cast<unsigned char>(theBytes[0]);
233 ALOGI("Section %s value is %u [0x%x]\n", name, value, value);
234 return value;
235 }
236}
237
Joel Fernandesd76a2002018-10-16 13:19:58 -0700238static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
239 int ret;
240 vector<Elf64_Shdr> shTable;
241
242 ret = readSectionHeadersAll(elfFile, shTable);
243 if (ret) return ret;
244
245 for (int i = 0; i < (int)shTable.size(); i++) {
246 if ((int)shTable[i].sh_type != type) continue;
247
248 vector<char> dataTmp;
249 dataTmp.resize(shTable[i].sh_size);
250
251 elfFile.seekg(shTable[i].sh_offset);
252 if (elfFile.fail()) return -1;
253
254 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
255
256 data = dataTmp;
257 return 0;
258 }
259 return -2;
260}
261
262static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
263 return (a.st_value < b.st_value);
264}
265
266static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
267 int ret, numElems;
268 Elf64_Sym* buf;
269 vector<char> secData;
270
271 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
272 if (ret) return ret;
273
274 buf = (Elf64_Sym*)secData.data();
275 numElems = (secData.size() / sizeof(Elf64_Sym));
276 data.assign(buf, buf + numElems);
277
278 if (sort) std::sort(data.begin(), data.end(), symCompare);
279 return 0;
280}
281
282static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800283 for (auto& snt : sectionNameTypes)
284 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700285
286 return BPF_PROG_TYPE_UNSPEC;
287}
288
289/* If ever needed
290static string getSectionName(enum bpf_prog_type type)
291{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800292 for (auto& snt : sectionNameTypes)
293 if (snt.type == type)
294 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700295
296 return NULL;
297}
298*/
299
300static bool isRelSection(codeSection& cs, string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800301 for (auto& snt : sectionNameTypes) {
302 if (snt.type != cs.type) continue;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700303
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800304 if (StartsWith(name, string(".rel") + snt.name))
Joel Fernandesd76a2002018-10-16 13:19:58 -0700305 return true;
306 else
307 return false;
308 }
309 return false;
310}
311
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800312static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
313 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800314 vector<char> pdData;
315 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800316 // Older file formats do not require a 'progs' section at all.
317 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800318 if (ret == -2) return 0;
319 if (ret) return ret;
320
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800321 if (pdData.size() % sizeOfBpfProgDef) {
322 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0\n",
323 pdData.size(), sizeOfBpfProgDef);
324 return -1;
325 };
326
327 int progCount = pdData.size() / sizeOfBpfProgDef;
328 pd.resize(progCount);
329 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
330
331 const char* dataPtr = pdData.data();
332 for (auto& p : pd) {
333 // First we zero initialize
334 memset(&p, 0, sizeof(p));
335 // Then we set non-zero defaults
336 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
337 // Then we copy over the structure prefix from the ELF file.
338 memcpy(&p, dataPtr, trimmedSize);
339 // Move to next struct in the ELF file
340 dataPtr += sizeOfBpfProgDef;
341 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800342 return 0;
343}
344
345static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names) {
346 int ret;
347 string name;
348 vector<Elf64_Sym> symtab;
349 vector<Elf64_Shdr> shTable;
350
351 ret = readSymTab(elfFile, 1 /* sort */, symtab);
352 if (ret) return ret;
353
354 /* Get index of section */
355 ret = readSectionHeadersAll(elfFile, shTable);
356 if (ret) return ret;
357
358 int sec_idx = -1;
359 for (int i = 0; i < (int)shTable.size(); i++) {
360 ret = getSymName(elfFile, shTable[i].sh_name, name);
361 if (ret) return ret;
362
363 if (!name.compare(sectionName)) {
364 sec_idx = i;
365 break;
366 }
367 }
368
369 /* No section found with matching name*/
370 if (sec_idx == -1) {
Maciej Żenczykowski21f34cb2020-07-20 18:44:33 -0700371 ALOGW("No %s section could be found in elf object\n", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800372 return -1;
373 }
374
375 for (int i = 0; i < (int)symtab.size(); i++) {
376 if (symtab[i].st_shndx == sec_idx) {
377 string s;
378 ret = getSymName(elfFile, symtab[i].st_name, s);
379 if (ret) return ret;
380 names.push_back(s);
381 }
382 }
383
384 return 0;
385}
386
Joel Fernandesd76a2002018-10-16 13:19:58 -0700387/* Read a section by its index - for ex to get sec hdr strtab blob */
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800388static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700389 vector<Elf64_Shdr> shTable;
390 int entries, ret = 0;
391
392 ret = readSectionHeadersAll(elfFile, shTable);
393 if (ret) return ret;
394 entries = shTable.size();
395
Connor O'Brien3278a162020-02-13 21:45:22 -0800396 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800397 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800398 if (ret) return ret;
399 vector<string> progDefNames;
400 ret = getSectionSymNames(elfFile, "progs", progDefNames);
401 if (!pd.empty() && ret) return ret;
402
Joel Fernandesd76a2002018-10-16 13:19:58 -0700403 for (int i = 0; i < entries; i++) {
404 string name;
405 codeSection cs_temp;
406 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
407
408 ret = getSymName(elfFile, shTable[i].sh_name, name);
409 if (ret) return ret;
410
411 enum bpf_prog_type ptype = getSectionType(name);
412 if (ptype != BPF_PROG_TYPE_UNSPEC) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800413 string oldName = name;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800414
415 // convert all slashes to underscores
416 std::replace(name.begin(), name.end(), '/', '_');
417
Joel Fernandesd76a2002018-10-16 13:19:58 -0700418 cs_temp.type = ptype;
419 cs_temp.name = name;
420
421 ret = readSectionByIdx(elfFile, i, cs_temp.data);
422 if (ret) return ret;
423 ALOGD("Loaded code section %d (%s)\n", i, name.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800424
425 vector<string> csSymNames;
426 ret = getSectionSymNames(elfFile, oldName, csSymNames);
427 if (ret || !csSymNames.size()) return ret;
428 for (size_t i = 0; i < progDefNames.size(); ++i) {
429 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
430 cs_temp.prog_def = pd[i];
431 break;
432 }
433 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700434 }
435
436 /* Check for rel section */
437 if (cs_temp.data.size() > 0 && i < entries) {
438 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
439 if (ret) return ret;
440
441 if (isRelSection(cs_temp, name)) {
442 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
443 if (ret) return ret;
444 ALOGD("Loaded relo section %d (%s)\n", i, name.c_str());
445 }
446 }
447
448 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700449 cs.push_back(std::move(cs_temp));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700450 ALOGD("Adding section %d to cs list\n", i);
451 }
452 }
453 return 0;
454}
455
456static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
457 vector<Elf64_Sym> symtab;
458 int ret = 0;
459
460 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
461 if (ret) return ret;
462
463 if (index >= (int)symtab.size()) return -1;
464
465 return getSymName(elfFile, symtab[index].st_name, name);
466}
467
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800468static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800469 const char* prefix, size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700470 int ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700471 vector<char> mdData;
472 vector<struct bpf_map_def> md;
473 vector<string> mapNames;
474 string fname = pathToFilename(string(elfPath), true);
475
476 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800477 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700478 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800479
480 if (mdData.size() % sizeOfBpfMapDef) {
481 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0\n",
482 mdData.size(), sizeOfBpfMapDef);
483 return -1;
484 };
485
486 int mapCount = mdData.size() / sizeOfBpfMapDef;
487 md.resize(mapCount);
488 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
489
490 const char* dataPtr = mdData.data();
491 for (auto& m : md) {
492 // First we zero initialize
493 memset(&m, 0, sizeof(m));
494 // Then we set non-zero defaults
495 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700496 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800497 // Then we copy over the structure prefix from the ELF file.
498 memcpy(&m, dataPtr, trimmedSize);
499 // Move to next struct in the ELF file
500 dataPtr += sizeOfBpfMapDef;
501 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700502
Connor O'Brien3278a162020-02-13 21:45:22 -0800503 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700504 if (ret) return ret;
505
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700506 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700507
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700508 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800509 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
510 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x\n", mapNames[i].c_str(),
511 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700512 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800513 continue;
514 }
515
516 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
517 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x\n", mapNames[i].c_str(),
518 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700519 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800520 continue;
521 }
522
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700523 if (kvers < md[i].min_kver) {
524 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x\n",
525 mapNames[i].c_str(), kvers, md[i].min_kver);
526 mapFds.push_back(unique_fd());
527 continue;
528 }
529
530 if (kvers >= md[i].max_kver) {
531 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x\n",
532 mapNames[i].c_str(), kvers, md[i].max_kver);
533 mapFds.push_back(unique_fd());
534 continue;
535 }
536
537 // Format of pin location is /sys/fs/bpf/<prefix>map_<filename>_<mapname>
538 string mapPinLoc =
539 string(BPF_FS_PATH) + prefix + "map_" + fname + "_" + string(mapNames[i]);
540 bool reuse = false;
541 unique_fd fd;
542 int saved_errno;
543
Joel Fernandesd76a2002018-10-16 13:19:58 -0700544 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700545 fd.reset(bpf_obj_get(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800546 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700547 ALOGD("bpf_create_map reusing map %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700548 reuse = true;
549 } else {
Maciej Żenczykowskicb358de2021-03-04 07:27:38 -0800550 enum bpf_map_type type = md[i].type;
551 if (type == BPF_MAP_TYPE_DEVMAP && !isAtLeastKernelVersion(4, 14, 0)) {
552 // On Linux Kernels older than 4.14 this map type doesn't exist, but it can kind
553 // of be approximated: ARRAY has the same userspace api, though it is not usable
554 // by the same ebpf programs. However, that's okay because the bpf_redirect_map()
555 // helper doesn't exist on 4.9 anyway (so the bpf program would fail to load,
556 // and thus needs to be tagged as 4.14+ either way), so there's nothing useful you
557 // could do with a DEVMAP anyway (that isn't already provided by an ARRAY)...
558 // Hence using an ARRAY instead of a DEVMAP simply makes life easier for userspace.
559 type = BPF_MAP_TYPE_ARRAY;
560 }
561 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
562 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
563 // of be approximated: HASH has the same userspace visible api.
564 // However it cannot be used by ebpf programs in the same way.
565 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
566 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
567 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
568 // programs as being 5.4+...
569 type = BPF_MAP_TYPE_HASH;
570 }
571 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 -0700572 md[i].max_entries, md[i].map_flags));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800573 saved_errno = errno;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700574 ALOGD("bpf_create_map name %s, ret: %d\n", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700575 }
576
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800577 if (fd < 0) return -saved_errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700578
579 if (!reuse) {
580 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800581 if (ret) return -errno;
582 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
583 if (ret) return -errno;
584 ret = chmod(mapPinLoc.c_str(), md[i].mode);
585 if (ret) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700586 }
587
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700588 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700589 }
590
591 return ret;
592}
593
594/* For debugging, dump all instructions */
595static void dumpIns(char* ins, int size) {
596 for (int row = 0; row < size / 8; row++) {
597 ALOGE("%d: ", row);
598 for (int j = 0; j < 8; j++) {
599 ALOGE("%3x ", ins[(row * 8) + j]);
600 }
601 ALOGE("\n");
602 }
603}
604
605/* For debugging, dump all code sections from cs list */
606static void dumpAllCs(vector<codeSection>& cs) {
607 for (int i = 0; i < (int)cs.size(); i++) {
608 ALOGE("Dumping cs %d, name %s\n", int(i), cs[i].name.c_str());
609 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
610 ALOGE("-----------\n");
611 }
612}
613
614static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
615 int insnIndex;
616 struct bpf_insn *insn, *insns;
617
618 insns = (struct bpf_insn*)(insnsPtr);
619
620 insnIndex = offset / sizeof(struct bpf_insn);
621 insn = &insns[insnIndex];
622
623 ALOGD(
624 "applying relo to instruction at byte offset: %d, \
625 insn offset %d , insn %lx\n",
626 (int)offset, (int)insnIndex, *(unsigned long*)insn);
627
628 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
629 ALOGE("Dumping all instructions till ins %d\n", insnIndex);
630 ALOGE("invalid relo for insn %d: code 0x%x\n", insnIndex, insn->code);
631 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
632 return;
633 }
634
635 insn->imm = fd;
636 insn->src_reg = BPF_PSEUDO_MAP_FD;
637}
638
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700639static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700640 vector<string> mapNames;
641
Connor O'Brien3278a162020-02-13 21:45:22 -0800642 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700643 if (ret) return;
644
645 for (int k = 0; k != (int)cs.size(); k++) {
646 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
647 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
648
649 for (int i = 0; i < n_rel; i++) {
650 int symIndex = ELF64_R_SYM(rel[i].r_info);
651 string symName;
652
653 ret = getSymNameByIdx(elfFile, symIndex, symName);
654 if (ret) return;
655
656 /* Find the map fd and apply relo */
657 for (int j = 0; j < (int)mapNames.size(); j++) {
658 if (!mapNames[j].compare(symName)) {
659 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
660 break;
661 }
662 }
663 }
664 }
665}
666
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800667static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
668 const char* prefix) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800669 unsigned kvers = kernelVersion();
670 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700671
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800672 if (!kvers) return -1;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700673
674 string fname = pathToFilename(string(elfPath), true);
675
676 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700677 string name = cs[i].name;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800678 unsigned bpfMinVer = DEFAULT_BPFLOADER_MIN_VER; // v0.0
679 unsigned bpfMaxVer = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Joel Fernandesd76a2002018-10-16 13:19:58 -0700680
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800681 if (cs[i].prog_def.has_value()) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700682 unsigned min_kver = cs[i].prog_def->min_kver;
683 unsigned max_kver = cs[i].prog_def->max_kver;
684 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)\n", i, name.c_str(), min_kver,
685 max_kver, kvers);
686 if (kvers < min_kver) continue;
687 if (kvers >= max_kver) continue;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800688
689 bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
690 bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800691 }
692
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800693 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)\n", i, name.c_str(),
694 bpfMinVer, bpfMaxVer);
695 if (BPFLOADER_VERSION < bpfMinVer) continue;
696 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
697
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700698 // strip any potential $foo suffix
699 // this can be used to provide duplicate programs
700 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700701 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700702
703 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700704 // Format of pin location is
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800705 // /sys/fs/bpf/<prefix>prog_<filename>_<mapname>
706 string progPinLoc = BPF_FS_PATH;
707 progPinLoc += prefix;
708 progPinLoc += "prog_";
Maciej Żenczykowski6c7871b2020-04-23 12:46:00 -0700709 progPinLoc += fname;
710 progPinLoc += '_';
711 progPinLoc += name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700712 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700713 fd = retrieveProgram(progPinLoc.c_str());
714 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)\n", progPinLoc.c_str(), fd,
715 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700716 reuse = true;
717 } else {
718 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
719
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700720 fd = bpf_prog_load(cs[i].type, name.c_str(), (struct bpf_insn*)cs[i].data.data(),
721 cs[i].data.size(), license.c_str(), kvers, 0, log_buf.data(),
722 log_buf.size());
Steven Moreland804bca02019-12-12 17:21:23 -0800723 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)\n", elfPath,
724 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700725
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800726 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800727 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800728
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700729 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
730 for (const auto& line : lines) ALOGW("%s", line.c_str());
731 ALOGW("bpf_prog_load - END log_buf contents.");
732
733 if (cs[i].prog_def->optional) {
734 ALOGW("failed program is marked optional - continuing...");
735 continue;
736 }
737 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800738 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700739 }
740
741 if (fd < 0) return fd;
742 if (fd == 0) return -EINVAL;
743
744 if (!reuse) {
745 ret = bpf_obj_pin(fd, progPinLoc.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800746 if (ret) return -errno;
747 if (cs[i].prog_def.has_value()) {
748 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
749 (gid_t)cs[i].prog_def->gid)) {
750 return -errno;
751 }
752 }
753 if (chmod(progPinLoc.c_str(), 0440)) return -errno;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700754 }
755
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700756 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700757 }
758
759 return 0;
760}
761
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800762int loadProg(const char* elfPath, bool* isCritical, const char* prefix) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700763 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700764 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700765 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700766 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700767 int ret;
768
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700769 if (!isCritical) return -1;
770 *isCritical = false;
771
Joel Fernandesd76a2002018-10-16 13:19:58 -0700772 ifstream elfFile(elfPath, ios::in | ios::binary);
773 if (!elfFile.is_open()) return -1;
774
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700775 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700776 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700777
Joel Fernandesd76a2002018-10-16 13:19:58 -0700778 ret = readSectionByName("license", elfFile, license);
779 if (ret) {
780 ALOGE("Couldn't find license in %s\n", elfPath);
781 return ret;
782 } else {
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700783 ALOGD("Loading %s%s ELF object %s with license %s\n",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700784 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700785 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700786 }
787
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800788 // the following default values are for bpfloader V0.0 format which does not include them
789 unsigned int bpfLoaderMinVer =
790 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
791 unsigned int bpfLoaderMaxVer =
792 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
793 size_t sizeOfBpfMapDef =
794 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
795 size_t sizeOfBpfProgDef =
796 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
797
798 // inclusive lower bound check
799 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
800 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x\n",
801 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
802 return 0;
803 }
804
805 // exclusive upper bound check
806 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
807 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x\n",
808 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
809 return 0;
810 }
811
812 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)\n",
813 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
814
815 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
816 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)\n", sizeOfBpfMapDef,
817 DEFAULT_SIZEOF_BPF_MAP_DEF);
818 return -1;
819 }
820
821 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
822 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)\n", sizeOfBpfProgDef,
823 DEFAULT_SIZEOF_BPF_PROG_DEF);
824 return -1;
825 }
826
827 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700828 if (ret) {
829 ALOGE("Couldn't read all code sections in %s\n", elfPath);
830 return ret;
831 }
832
833 /* Just for future debugging */
834 if (0) dumpAllCs(cs);
835
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800836 ret = createMaps(elfPath, elfFile, mapFds, prefix, sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700837 if (ret) {
838 ALOGE("Failed to create maps: (ret=%d) in %s\n", ret, elfPath);
839 return ret;
840 }
841
842 for (int i = 0; i < (int)mapFds.size(); i++)
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700843 ALOGD("map_fd found at %d is %d in %s\n", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700844
845 applyMapRelo(elfFile, mapFds, cs);
846
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800847 ret = loadCodeSections(elfPath, cs, string(license.data()), prefix);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700848 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d\n", ret);
849
850 return ret;
851}
852
Joel Fernandesd76a2002018-10-16 13:19:58 -0700853} // namespace bpf
854} // namespace android