blob: 6ec74586a2582829e4234ec4464487183b492e24 [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
Maciej Żenczykowskie2f2b822024-05-01 05:16:51 -070017#define LOG_TAG "BpfLoader"
Joel Fernandesd76a2002018-10-16 13:19:58 -070018
19#include <errno.h>
Maciej Żenczykowskie15229f2023-04-17 07:16:33 +000020#include <fcntl.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070021#include <linux/bpf.h>
22#include <linux/elf.h>
23#include <log/log.h>
24#include <stdint.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080028#include <sysexits.h>
Maciej Żenczykowski83f29772020-01-27 03:11:51 -080029#include <sys/stat.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070030#include <sys/utsname.h>
Connor O'Brien35425e52022-01-18 21:41:16 -080031#include <sys/wait.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070032#include <unistd.h>
33
Maciej Żenczykowski300c51f2022-12-14 04:18:02 -080034#include "BpfSyscallWrappers.h"
Maciej Żenczykowski07375e22020-02-19 14:23:59 -080035#include "bpf/BpfUtils.h"
Ken Chend5689472021-12-20 18:07:21 +080036#include "bpf/bpf_map_def.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070037#include "include/libbpf_android.h"
38
39#include <cstdlib>
40#include <fstream>
41#include <iostream>
Connor O'Brien3278a162020-02-13 21:45:22 -080042#include <optional>
Joel Fernandesd76a2002018-10-16 13:19:58 -070043#include <string>
Connor O'Brien35425e52022-01-18 21:41:16 -080044#include <unordered_map>
Christopher Ferrisc151c672019-02-01 15:31:26 -080045#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070046
Connor O'Brien35425e52022-01-18 21:41:16 -080047#include <android-base/cmsg.h>
48#include <android-base/file.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070049#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070050#include <android-base/unique_fd.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070051
52#define BPF_FS_PATH "/sys/fs/bpf/"
53
54// Size of the BPF log buffer for verifier logging
Stephane Leeeb61b732021-10-21 17:03:11 -070055#define BPF_LOAD_LOG_SZ 0xfffff
Joel Fernandesd76a2002018-10-16 13:19:58 -070056
Tyler Wear4e2f4602022-02-03 09:46:01 -080057// Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
58#define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
59
Joel Fernandesd76a2002018-10-16 13:19:58 -070060using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070061using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070062using std::ifstream;
63using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080064using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080065using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070066using std::vector;
67
68namespace android {
69namespace bpf {
70
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +000071static unsigned int page_size = static_cast<unsigned int>(getpagesize());
72
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -070073static string pathToObjName(const string& path) {
74 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
75 string filename = android::base::Split(path, "/").back();
76 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
77 string name = filename.substr(0, filename.find_last_of('.'));
78 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
79 // this can be used to provide duplicate programs (mux based on the bpfloader version)
80 return name.substr(0, name.find_last_of('@'));
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -080081}
82
Joel Fernandesd76a2002018-10-16 13:19:58 -070083typedef struct {
84 const char* name;
85 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -080086 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -070087} sectionType;
88
89/*
90 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070091 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -070092 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070093 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -070094 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070095 *
96 * However, be aware that you should not be directly using the SECTION() macro.
97 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -070098 */
99sectionType sectionNameTypes[] = {
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000100 {"kprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
101 {"kretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000102 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000103 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000104 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
105 {"uprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
106 {"uretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700107};
108
109typedef struct {
110 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800111 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700112 string name;
113 vector<char> data;
114 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800115 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700116
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700117 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700118} codeSection;
119
Joel Fernandesd76a2002018-10-16 13:19:58 -0700120static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
121 elfFile.seekg(0);
122 if (elfFile.fail()) return -1;
123
124 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
125
126 return 0;
127}
128
129/* Reads all section header tables into an Shdr array */
130static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
131 Elf64_Ehdr eh;
132 int ret = 0;
133
134 ret = readElfHeader(elfFile, &eh);
135 if (ret) return ret;
136
137 elfFile.seekg(eh.e_shoff);
138 if (elfFile.fail()) return -1;
139
140 /* Read shdr table entries */
141 shTable.resize(eh.e_shnum);
142
143 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
144
145 return 0;
146}
147
148/* Read a section by its index - for ex to get sec hdr strtab blob */
149static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
150 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800151 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700152 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700153
154 elfFile.seekg(shTable[id].sh_offset);
155 if (elfFile.fail()) return -1;
156
157 sec.resize(shTable[id].sh_size);
158 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
159
160 return 0;
161}
162
163/* Read whole section header string table */
164static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
165 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800166 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700167 if (ret) return ret;
168
169 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
170 if (ret) return ret;
171
172 return 0;
173}
174
175/* Get name from offset in strtab */
176static int getSymName(ifstream& elfFile, int nameOff, string& name) {
177 int ret;
178 vector<char> secStrTab;
179
180 ret = readSectionHeaderStrtab(elfFile, secStrTab);
181 if (ret) return ret;
182
183 if (nameOff >= (int)secStrTab.size()) return -1;
184
185 name = string((char*)secStrTab.data() + nameOff);
186 return 0;
187}
188
189/* Reads a full section by name - example to get the GPL license */
190static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
191 vector<char> secStrTab;
192 vector<Elf64_Shdr> shTable;
193 int ret;
194
195 ret = readSectionHeadersAll(elfFile, shTable);
196 if (ret) return ret;
197
198 ret = readSectionHeaderStrtab(elfFile, secStrTab);
199 if (ret) return ret;
200
201 for (int i = 0; i < (int)shTable.size(); i++) {
202 char* secname = secStrTab.data() + shTable[i].sh_name;
203 if (!secname) continue;
204
205 if (!strcmp(secname, name)) {
206 vector<char> dataTmp;
207 dataTmp.resize(shTable[i].sh_size);
208
209 elfFile.seekg(shTable[i].sh_offset);
210 if (elfFile.fail()) return -1;
211
212 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
213
214 data = dataTmp;
215 return 0;
216 }
217 }
218 return -2;
219}
220
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700221unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800222 vector<char> theBytes;
223 int ret = readSectionByName(name, elfFile, theBytes);
224 if (ret) {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700225 ALOGV("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800226 return defVal;
227 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700228 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800229 return defVal;
230 } else {
231 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
232 unsigned int value = static_cast<unsigned char>(theBytes[3]);
233 value <<= 8;
234 value += static_cast<unsigned char>(theBytes[2]);
235 value <<= 8;
236 value += static_cast<unsigned char>(theBytes[1]);
237 value <<= 8;
238 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700239 ALOGV("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800240 return value;
241 }
242}
243
Joel Fernandesd76a2002018-10-16 13:19:58 -0700244static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
245 int ret;
246 vector<Elf64_Shdr> shTable;
247
248 ret = readSectionHeadersAll(elfFile, shTable);
249 if (ret) return ret;
250
251 for (int i = 0; i < (int)shTable.size(); i++) {
252 if ((int)shTable[i].sh_type != type) continue;
253
254 vector<char> dataTmp;
255 dataTmp.resize(shTable[i].sh_size);
256
257 elfFile.seekg(shTable[i].sh_offset);
258 if (elfFile.fail()) return -1;
259
260 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
261
262 data = dataTmp;
263 return 0;
264 }
265 return -2;
266}
267
268static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
269 return (a.st_value < b.st_value);
270}
271
272static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
273 int ret, numElems;
274 Elf64_Sym* buf;
275 vector<char> secData;
276
277 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
278 if (ret) return ret;
279
280 buf = (Elf64_Sym*)secData.data();
281 numElems = (secData.size() / sizeof(Elf64_Sym));
282 data.assign(buf, buf + numElems);
283
284 if (sort) std::sort(data.begin(), data.end(), symCompare);
285 return 0;
286}
287
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700288static enum bpf_prog_type getFuseProgType() {
289 int result = BPF_PROG_TYPE_UNSPEC;
290 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
291 return static_cast<bpf_prog_type>(result);
292}
293
Joel Fernandesd76a2002018-10-16 13:19:58 -0700294static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800295 for (auto& snt : sectionNameTypes)
296 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700297
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000298 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700299 if (StartsWith(name, "fuse/")) return getFuseProgType();
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000300
Joel Fernandesd76a2002018-10-16 13:19:58 -0700301 return BPF_PROG_TYPE_UNSPEC;
302}
303
Tyler Wear4e2f4602022-02-03 09:46:01 -0800304static enum bpf_attach_type getExpectedAttachType(string& name) {
305 for (auto& snt : sectionNameTypes)
306 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
307 return BPF_ATTACH_TYPE_UNSPEC;
308}
309
Joel Fernandesd76a2002018-10-16 13:19:58 -0700310static string getSectionName(enum bpf_prog_type type)
311{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800312 for (auto& snt : sectionNameTypes)
313 if (snt.type == type)
314 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700315
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800316 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700317}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700318
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700319static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800320 vector<char> pdData;
321 int ret = readSectionByName("progs", elfFile, pdData);
Connor O'Brien3278a162020-02-13 21:45:22 -0800322 if (ret) return ret;
323
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700324 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700325 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700326 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800327 return -1;
328 };
329
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700330 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
331 memcpy(pd.data(), pdData.data(), pdData.size());
Connor O'Brien3278a162020-02-13 21:45:22 -0800332 return 0;
333}
334
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800335static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
336 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800337 int ret;
338 string name;
339 vector<Elf64_Sym> symtab;
340 vector<Elf64_Shdr> shTable;
341
342 ret = readSymTab(elfFile, 1 /* sort */, symtab);
343 if (ret) return ret;
344
345 /* Get index of section */
346 ret = readSectionHeadersAll(elfFile, shTable);
347 if (ret) return ret;
348
349 int sec_idx = -1;
350 for (int i = 0; i < (int)shTable.size(); i++) {
351 ret = getSymName(elfFile, shTable[i].sh_name, name);
352 if (ret) return ret;
353
354 if (!name.compare(sectionName)) {
355 sec_idx = i;
356 break;
357 }
358 }
359
360 /* No section found with matching name*/
361 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700362 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800363 return -1;
364 }
365
366 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800367 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
368
Connor O'Brien3278a162020-02-13 21:45:22 -0800369 if (symtab[i].st_shndx == sec_idx) {
370 string s;
371 ret = getSymName(elfFile, symtab[i].st_name, s);
372 if (ret) return ret;
373 names.push_back(s);
374 }
375 }
376
377 return 0;
378}
379
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800380static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
381 if (allowed == nullptr) return true;
382
383 for (size_t i = 0; i < numAllowed; i++) {
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700384 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
385 if (type == getFuseProgType()) return true;
386 } else if (type == allowed[i])
387 return true;
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800388 }
389
390 return false;
391}
392
Joel Fernandesd76a2002018-10-16 13:19:58 -0700393/* Read a section by its index - for ex to get sec hdr strtab blob */
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700394static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs,
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800395 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700396 vector<Elf64_Shdr> shTable;
397 int entries, ret = 0;
398
399 ret = readSectionHeadersAll(elfFile, shTable);
400 if (ret) return ret;
401 entries = shTable.size();
402
Connor O'Brien3278a162020-02-13 21:45:22 -0800403 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700404 ret = readProgDefs(elfFile, pd);
Connor O'Brien3278a162020-02-13 21:45:22 -0800405 if (ret) return ret;
406 vector<string> progDefNames;
407 ret = getSectionSymNames(elfFile, "progs", progDefNames);
408 if (!pd.empty() && ret) return ret;
409
Joel Fernandesd76a2002018-10-16 13:19:58 -0700410 for (int i = 0; i < entries; i++) {
411 string name;
412 codeSection cs_temp;
413 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
414
415 ret = getSymName(elfFile, shTable[i].sh_name, name);
416 if (ret) return ret;
417
418 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800419
Tyler Wear4e2f4602022-02-03 09:46:01 -0800420 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800421
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800422 if (!IsAllowed(ptype, allowed, numAllowed)) {
423 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
424 return -1;
425 }
426
Tyler Wear4e2f4602022-02-03 09:46:01 -0800427 // This must be done before '/' is replaced with '_'.
428 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800429
Tyler Wear4e2f4602022-02-03 09:46:01 -0800430 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700431
Tyler Wear4e2f4602022-02-03 09:46:01 -0800432 // convert all slashes to underscores
433 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800434
Tyler Wear4e2f4602022-02-03 09:46:01 -0800435 cs_temp.type = ptype;
436 cs_temp.name = name;
437
438 ret = readSectionByIdx(elfFile, i, cs_temp.data);
439 if (ret) return ret;
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700440 ALOGV("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800441
442 vector<string> csSymNames;
443 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
444 if (ret || !csSymNames.size()) return ret;
445 for (size_t i = 0; i < progDefNames.size(); ++i) {
446 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
447 cs_temp.prog_def = pd[i];
448 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800449 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700450 }
451
452 /* Check for rel section */
453 if (cs_temp.data.size() > 0 && i < entries) {
454 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
455 if (ret) return ret;
456
Tyler Wear4e2f4602022-02-03 09:46:01 -0800457 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700458 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
459 if (ret) return ret;
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700460 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700461 }
462 }
463
464 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700465 cs.push_back(std::move(cs_temp));
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700466 ALOGV("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700467 }
468 }
469 return 0;
470}
471
472static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
473 vector<Elf64_Sym> symtab;
474 int ret = 0;
475
476 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
477 if (ret) return ret;
478
479 if (index >= (int)symtab.size()) return -1;
480
481 return getSymName(elfFile, symtab[index].st_name, name);
482}
483
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700484static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
485 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700486 // Assuming fd is a valid Bpf Map file descriptor then
487 // all the following should always succeed on a 4.14+ kernel.
488 // If they somehow do fail, they'll return -1 (and set errno),
489 // which should then cause (among others) a key_size mismatch.
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700490 int fd_type = bpfGetFdMapType(fd);
491 int fd_key_size = bpfGetFdKeySize(fd);
492 int fd_value_size = bpfGetFdValueSize(fd);
493 int fd_max_entries = bpfGetFdMaxEntries(fd);
494 int fd_map_flags = bpfGetFdMapFlags(fd);
495
496 // DEVMAPs are readonly from the bpf program side's point of view, as such
497 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
498 int desired_map_flags = (int)mapDef.map_flags;
499 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
500 desired_map_flags |= BPF_F_RDONLY_PROG;
501
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000502 // The .h file enforces that this is a power of two, and page size will
503 // also always be a power of two, so this logic is actually enough to
504 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000505 unsigned int desired_max_entries = mapDef.max_entries;
506 if (type == BPF_MAP_TYPE_RINGBUF) {
507 if (desired_max_entries < page_size) desired_max_entries = page_size;
508 }
509
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700510 // The following checks should *never* trigger, if one of them somehow does,
511 // it probably means a bpf .o file has been changed/replaced at runtime
512 // and bpfloader was manually rerun (normally it should only run *once*
513 // early during the boot process).
514 // Another possibility is that something is misconfigured in the code:
515 // most likely a shared map is declared twice differently.
516 // But such a change should never be checked into the source tree...
517 if ((fd_type == type) &&
518 (fd_key_size == (int)mapDef.key_size) &&
519 (fd_value_size == (int)mapDef.value_size) &&
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000520 (fd_max_entries == (int)desired_max_entries) &&
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700521 (fd_map_flags == desired_map_flags)) {
522 return true;
523 }
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700524
525 ALOGE("bpf map name %s mismatch: desired/found: "
526 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
527 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
528 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
529 return false;
530}
531
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800532static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700533 const char* prefix) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700534 int ret;
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700535 vector<char> mdData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700536 vector<struct bpf_map_def> md;
537 vector<string> mapNames;
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700538 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700539
540 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800541 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700542 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800543
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700544 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700545 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700546 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800547 return -1;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800548 }
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700549 md.resize(mdData.size() / sizeof(struct bpf_map_def));
550 memcpy(md.data(), mdData.data(), mdData.size());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700551
Connor O'Brien3278a162020-02-13 21:45:22 -0800552 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700553 if (ret) return ret;
554
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700555 unsigned kvers = kernelVersion();
556
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700557 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +0000558 if (md[i].zero != 0) abort();
559
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700560 if (kvers < md[i].min_kver) {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700561 ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700562 mapNames[i].c_str(), kvers, md[i].min_kver);
563 mapFds.push_back(unique_fd());
564 continue;
565 }
566
567 if (kvers >= md[i].max_kver) {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700568 ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700569 mapNames[i].c_str(), kvers, md[i].max_kver);
570 mapFds.push_back(unique_fd());
571 continue;
572 }
573
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700574 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700575 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
576 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
577 // of be approximated: HASH has the same userspace visible api.
578 // However it cannot be used by ebpf programs in the same way.
579 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
580 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
581 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
582 // programs as being 5.4+...
583 type = BPF_MAP_TYPE_HASH;
584 }
585
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000586 // The .h file enforces that this is a power of two, and page size will
587 // also always be a power of two, so this logic is actually enough to
588 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000589 unsigned int max_entries = md[i].max_entries;
590 if (type == BPF_MAP_TYPE_RINGBUF) {
591 if (max_entries < page_size) max_entries = page_size;
592 }
593
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700594 // Format of pin location is /sys/fs/bpf/<prefix>map_<objName>_<mapName>
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700595 // except that maps shared across .o's have empty <objName>
596 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700597 string mapPinLoc = string(BPF_FS_PATH) + prefix + "map_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700598 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700599 bool reuse = false;
600 unique_fd fd;
601 int saved_errno;
602
Joel Fernandesd76a2002018-10-16 13:19:58 -0700603 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskieb199dd2022-07-01 03:21:40 -0700604 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800605 saved_errno = errno;
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700606 ALOGV("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700607 reuse = true;
608 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700609 union bpf_attr req = {
610 .map_type = type,
611 .key_size = md[i].key_size,
612 .value_size = md[i].value_size,
613 .max_entries = max_entries,
614 .map_flags = md[i].map_flags,
Connor O'Brien35425e52022-01-18 21:41:16 -0800615 };
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700616 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
617 fd.reset(bpf(BPF_MAP_CREATE, req));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800618 saved_errno = errno;
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700619 ALOGV("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700620 }
621
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700622 if (!fd.ok()) return -saved_errno;
623
624 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
625 // safety (since reuse code path is rare) run these checks even if we just created it.
626 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
627 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700628
629 if (!reuse) {
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700630 ret = bpfFdPin(fd, mapPinLoc.c_str());
631 if (ret) {
632 int err = errno;
633 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
634 return -err;
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700635 }
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800636 ret = chmod(mapPinLoc.c_str(), md[i].mode);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700637 if (ret) {
638 int err = errno;
639 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
640 strerror(err));
641 return -err;
642 }
Maciej Żenczykowski5e4aabf2022-06-27 01:15:53 -0700643 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
644 if (ret) {
645 int err = errno;
646 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
647 ret, err, strerror(err));
648 return -err;
649 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700650 }
651
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700652 int mapId = bpfGetFdMapId(fd);
653 if (mapId == -1) {
654 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700655 } else {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700656 ALOGD("map %s id %d", mapPinLoc.c_str(), mapId);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700657 }
658
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700659 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700660 }
661
662 return ret;
663}
664
Joel Fernandesd76a2002018-10-16 13:19:58 -0700665static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
666 int insnIndex;
667 struct bpf_insn *insn, *insns;
668
669 insns = (struct bpf_insn*)(insnsPtr);
670
671 insnIndex = offset / sizeof(struct bpf_insn);
672 insn = &insns[insnIndex];
673
Maciej Żenczykowski509b1b92023-03-07 01:11:20 +0000674 // Occasionally might be useful for relocation debugging, but pretty spammy
675 if (0) {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700676 ALOGV("applying relo to instruction at byte offset: %llu, "
Maciej Żenczykowski509b1b92023-03-07 01:11:20 +0000677 "insn offset %d, insn %llx",
678 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
679 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700680
681 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700682 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700683 return;
684 }
685
686 insn->imm = fd;
687 insn->src_reg = BPF_PSEUDO_MAP_FD;
688}
689
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700690static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700691 vector<string> mapNames;
692
Connor O'Brien3278a162020-02-13 21:45:22 -0800693 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700694 if (ret) return;
695
696 for (int k = 0; k != (int)cs.size(); k++) {
697 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
698 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
699
700 for (int i = 0; i < n_rel; i++) {
701 int symIndex = ELF64_R_SYM(rel[i].r_info);
702 string symName;
703
704 ret = getSymNameByIdx(elfFile, symIndex, symName);
705 if (ret) return;
706
707 /* Find the map fd and apply relo */
708 for (int j = 0; j < (int)mapNames.size(); j++) {
709 if (!mapNames[j].compare(symName)) {
710 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
711 break;
712 }
713 }
714 }
715 }
716}
717
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800718static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700719 const char* prefix) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800720 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700721
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000722 if (!kvers) {
723 ALOGE("unable to get kernel version");
724 return -EINVAL;
725 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700726
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700727 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700728
729 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700730 unique_fd& fd = cs[i].prog_fd;
731 int ret;
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700732 string name = cs[i].name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700733
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000734 if (!cs[i].prog_def.has_value()) {
735 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
736 return -EINVAL;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800737 }
738
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000739 unsigned min_kver = cs[i].prog_def->min_kver;
740 unsigned max_kver = cs[i].prog_def->max_kver;
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700741 if (kvers < min_kver || kvers >= max_kver) {
742 ALOGD("skipping program cs[%d].name:%s min_kver:%x max_kver:%x (kvers:%x)",
743 i, name.c_str(), min_kver, max_kver, kvers);
744 continue;
745 }
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000746
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700747 // strip any potential $foo suffix
748 // this can be used to provide duplicate programs
749 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -0700750 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700751
752 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700753 // Format of pin location is
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700754 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700755 string progPinLoc = string(BPF_FS_PATH) + prefix + "prog_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700756 objName + '_' + string(name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700757 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700758 fd.reset(retrieveProgram(progPinLoc.c_str()));
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700759 ALOGV("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700760 (!fd.ok() ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700761 reuse = true;
762 } else {
763 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
764
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700765 union bpf_attr req = {
766 .prog_type = cs[i].type,
767 .kern_version = kvers,
768 .license = ptr_to_u64(license.c_str()),
769 .insns = ptr_to_u64(cs[i].data.data()),
770 .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
771 .log_level = 1,
772 .log_buf = ptr_to_u64(log_buf.data()),
773 .log_size = static_cast<__u32>(log_buf.size()),
774 .expected_attach_type = cs[i].expected_attach_type,
Tyler Wear4e2f4602022-02-03 09:46:01 -0800775 };
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700776 strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
777 fd.reset(bpf(BPF_PROG_LOAD, req));
Tyler Wear4e2f4602022-02-03 09:46:01 -0800778
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700779 if (!fd.ok()) {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700780 ALOGW("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
781 cs[i].name.c_str(), fd.get(), std::strerror(errno));
782
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800783 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800784
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700785 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700786 for (const auto& line : lines) ALOGW("%s", line.c_str());
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700787 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700788
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000789 if (cs[i].prog_def->optional) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -0700790 ALOGW("failed program is marked optional - continuing...");
791 continue;
792 }
793 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -0800794 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700795 }
796
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700797 if (!fd.ok()) return fd.get();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700798
799 if (!reuse) {
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700800 ret = bpfFdPin(fd, progPinLoc.c_str());
801 if (ret) {
802 int err = errno;
803 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
804 return -err;
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700805 }
806 if (chmod(progPinLoc.c_str(), 0440)) {
807 int err = errno;
808 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
809 return -err;
810 }
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000811 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
812 (gid_t)cs[i].prog_def->gid)) {
813 int err = errno;
814 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
815 cs[i].prog_def->gid, err, strerror(err));
816 return -err;
Connor O'Brien3278a162020-02-13 21:45:22 -0800817 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700818 }
819
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700820 int progId = bpfGetFdProgId(fd);
821 if (progId == -1) {
822 ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700823 } else {
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700824 ALOGD("prog %s id %d", progPinLoc.c_str(), progId);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700825 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700826 }
827
828 return 0;
829}
830
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -0800831int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700832 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700833 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700834 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700835 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700836 int ret;
837
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700838 if (!isCritical) return -1;
839 *isCritical = false;
840
Joel Fernandesd76a2002018-10-16 13:19:58 -0700841 ifstream elfFile(elfPath, ios::in | ios::binary);
842 if (!elfFile.is_open()) return -1;
843
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700844 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700845 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700846
Joel Fernandesd76a2002018-10-16 13:19:58 -0700847 ret = readSectionByName("license", elfFile, license);
848 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700849 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700850 return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700851 }
852
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700853 ALOGI("Platform BpfLoader loading %s%s ELF object %s with license %s",
854 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
855 elfPath, (char*)license.data());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800856
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700857 ret = readCodeSections(elfFile, cs, location.allowedProgTypes, location.allowedProgTypesLength);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700858 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700859 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700860 return ret;
861 }
862
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700863 ret = createMaps(elfPath, elfFile, mapFds, location.prefix);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700864 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700865 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700866 return ret;
867 }
868
869 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowski0eb98a22024-04-30 22:35:08 -0700870 ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700871
872 applyMapRelo(elfFile, mapFds, cs);
873
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700874 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700875 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700876
877 return ret;
878}
879
Joel Fernandesd76a2002018-10-16 13:19:58 -0700880} // namespace bpf
881} // namespace android