blob: 746aca8abede8264a06a5f22fdefa75e6ebe7866 [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>
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>
Elliott Hughes3b0811b2023-10-09 22:20:04 +000049#include <android-base/properties.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070050#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070051#include <android-base/unique_fd.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070052
53#define BPF_FS_PATH "/sys/fs/bpf/"
54
55// Size of the BPF log buffer for verifier logging
Stephane Leeeb61b732021-10-21 17:03:11 -070056#define BPF_LOAD_LOG_SZ 0xfffff
Joel Fernandesd76a2002018-10-16 13:19:58 -070057
Tyler Wear4e2f4602022-02-03 09:46:01 -080058// Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
59#define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
60
Joel Fernandesd76a2002018-10-16 13:19:58 -070061using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070062using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070063using std::ifstream;
64using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080065using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080066using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070067using std::vector;
68
69namespace android {
70namespace bpf {
71
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +000072static unsigned int page_size = static_cast<unsigned int>(getpagesize());
73
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -070074static string pathToObjName(const string& path) {
75 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
76 string filename = android::base::Split(path, "/").back();
77 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
78 string name = filename.substr(0, filename.find_last_of('.'));
79 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
80 // this can be used to provide duplicate programs (mux based on the bpfloader version)
81 return name.substr(0, name.find_last_of('@'));
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -080082}
83
Joel Fernandesd76a2002018-10-16 13:19:58 -070084typedef struct {
85 const char* name;
86 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -080087 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -070088} sectionType;
89
90/*
91 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070092 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -070093 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070094 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -070095 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -070096 *
97 * However, be aware that you should not be directly using the SECTION() macro.
98 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -070099 */
100sectionType sectionNameTypes[] = {
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000101 {"kprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
102 {"kretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000103 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000104 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000105 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
106 {"uprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
107 {"uretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700108};
109
110typedef struct {
111 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800112 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700113 string name;
114 vector<char> data;
115 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800116 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700117
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700118 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700119} codeSection;
120
Joel Fernandesd76a2002018-10-16 13:19:58 -0700121static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
122 elfFile.seekg(0);
123 if (elfFile.fail()) return -1;
124
125 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
126
127 return 0;
128}
129
130/* Reads all section header tables into an Shdr array */
131static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
132 Elf64_Ehdr eh;
133 int ret = 0;
134
135 ret = readElfHeader(elfFile, &eh);
136 if (ret) return ret;
137
138 elfFile.seekg(eh.e_shoff);
139 if (elfFile.fail()) return -1;
140
141 /* Read shdr table entries */
142 shTable.resize(eh.e_shnum);
143
144 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
145
146 return 0;
147}
148
149/* Read a section by its index - for ex to get sec hdr strtab blob */
150static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
151 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800152 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700153 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700154
155 elfFile.seekg(shTable[id].sh_offset);
156 if (elfFile.fail()) return -1;
157
158 sec.resize(shTable[id].sh_size);
159 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
160
161 return 0;
162}
163
164/* Read whole section header string table */
165static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
166 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800167 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700168 if (ret) return ret;
169
170 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
171 if (ret) return ret;
172
173 return 0;
174}
175
176/* Get name from offset in strtab */
177static int getSymName(ifstream& elfFile, int nameOff, string& name) {
178 int ret;
179 vector<char> secStrTab;
180
181 ret = readSectionHeaderStrtab(elfFile, secStrTab);
182 if (ret) return ret;
183
184 if (nameOff >= (int)secStrTab.size()) return -1;
185
186 name = string((char*)secStrTab.data() + nameOff);
187 return 0;
188}
189
190/* Reads a full section by name - example to get the GPL license */
191static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
192 vector<char> secStrTab;
193 vector<Elf64_Shdr> shTable;
194 int ret;
195
196 ret = readSectionHeadersAll(elfFile, shTable);
197 if (ret) return ret;
198
199 ret = readSectionHeaderStrtab(elfFile, secStrTab);
200 if (ret) return ret;
201
202 for (int i = 0; i < (int)shTable.size(); i++) {
203 char* secname = secStrTab.data() + shTable[i].sh_name;
204 if (!secname) continue;
205
206 if (!strcmp(secname, name)) {
207 vector<char> dataTmp;
208 dataTmp.resize(shTable[i].sh_size);
209
210 elfFile.seekg(shTable[i].sh_offset);
211 if (elfFile.fail()) return -1;
212
213 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
214
215 data = dataTmp;
216 return 0;
217 }
218 }
219 return -2;
220}
221
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700222unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800223 vector<char> theBytes;
224 int ret = readSectionByName(name, elfFile, theBytes);
225 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700226 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800227 return defVal;
228 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700229 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800230 return defVal;
231 } else {
232 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
233 unsigned int value = static_cast<unsigned char>(theBytes[3]);
234 value <<= 8;
235 value += static_cast<unsigned char>(theBytes[2]);
236 value <<= 8;
237 value += static_cast<unsigned char>(theBytes[1]);
238 value <<= 8;
239 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700240 ALOGI("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800241 return value;
242 }
243}
244
Joel Fernandesd76a2002018-10-16 13:19:58 -0700245static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
246 int ret;
247 vector<Elf64_Shdr> shTable;
248
249 ret = readSectionHeadersAll(elfFile, shTable);
250 if (ret) return ret;
251
252 for (int i = 0; i < (int)shTable.size(); i++) {
253 if ((int)shTable[i].sh_type != type) continue;
254
255 vector<char> dataTmp;
256 dataTmp.resize(shTable[i].sh_size);
257
258 elfFile.seekg(shTable[i].sh_offset);
259 if (elfFile.fail()) return -1;
260
261 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
262
263 data = dataTmp;
264 return 0;
265 }
266 return -2;
267}
268
269static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
270 return (a.st_value < b.st_value);
271}
272
273static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
274 int ret, numElems;
275 Elf64_Sym* buf;
276 vector<char> secData;
277
278 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
279 if (ret) return ret;
280
281 buf = (Elf64_Sym*)secData.data();
282 numElems = (secData.size() / sizeof(Elf64_Sym));
283 data.assign(buf, buf + numElems);
284
285 if (sort) std::sort(data.begin(), data.end(), symCompare);
286 return 0;
287}
288
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700289static enum bpf_prog_type getFuseProgType() {
290 int result = BPF_PROG_TYPE_UNSPEC;
291 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
292 return static_cast<bpf_prog_type>(result);
293}
294
Joel Fernandesd76a2002018-10-16 13:19:58 -0700295static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800296 for (auto& snt : sectionNameTypes)
297 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700298
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000299 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700300 if (StartsWith(name, "fuse/")) return getFuseProgType();
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000301
Joel Fernandesd76a2002018-10-16 13:19:58 -0700302 return BPF_PROG_TYPE_UNSPEC;
303}
304
Tyler Wear4e2f4602022-02-03 09:46:01 -0800305static enum bpf_attach_type getExpectedAttachType(string& name) {
306 for (auto& snt : sectionNameTypes)
307 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
308 return BPF_ATTACH_TYPE_UNSPEC;
309}
310
Joel Fernandesd76a2002018-10-16 13:19:58 -0700311static string getSectionName(enum bpf_prog_type type)
312{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800313 for (auto& snt : sectionNameTypes)
314 if (snt.type == type)
315 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700316
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800317 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700318}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700319
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700320static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800321 vector<char> pdData;
322 int ret = readSectionByName("progs", elfFile, pdData);
Connor O'Brien3278a162020-02-13 21:45:22 -0800323 if (ret) return ret;
324
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700325 if (pdData.size() % sizeof(struct bpf_prog_def)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700326 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700327 pdData.size(), sizeof(struct bpf_prog_def));
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800328 return -1;
329 };
330
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700331 pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
332 memcpy(pd.data(), pdData.data(), pdData.size());
Connor O'Brien3278a162020-02-13 21:45:22 -0800333 return 0;
334}
335
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800336static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
337 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800338 int ret;
339 string name;
340 vector<Elf64_Sym> symtab;
341 vector<Elf64_Shdr> shTable;
342
343 ret = readSymTab(elfFile, 1 /* sort */, symtab);
344 if (ret) return ret;
345
346 /* Get index of section */
347 ret = readSectionHeadersAll(elfFile, shTable);
348 if (ret) return ret;
349
350 int sec_idx = -1;
351 for (int i = 0; i < (int)shTable.size(); i++) {
352 ret = getSymName(elfFile, shTable[i].sh_name, name);
353 if (ret) return ret;
354
355 if (!name.compare(sectionName)) {
356 sec_idx = i;
357 break;
358 }
359 }
360
361 /* No section found with matching name*/
362 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700363 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800364 return -1;
365 }
366
367 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800368 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
369
Connor O'Brien3278a162020-02-13 21:45:22 -0800370 if (symtab[i].st_shndx == sec_idx) {
371 string s;
372 ret = getSymName(elfFile, symtab[i].st_name, s);
373 if (ret) return ret;
374 names.push_back(s);
375 }
376 }
377
378 return 0;
379}
380
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800381static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
382 if (allowed == nullptr) return true;
383
384 for (size_t i = 0; i < numAllowed; i++) {
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700385 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
386 if (type == getFuseProgType()) return true;
387 } else if (type == allowed[i])
388 return true;
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800389 }
390
391 return false;
392}
393
Joel Fernandesd76a2002018-10-16 13:19:58 -0700394/* Read a section by its index - for ex to get sec hdr strtab blob */
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700395static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs,
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800396 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700397 vector<Elf64_Shdr> shTable;
398 int entries, ret = 0;
399
400 ret = readSectionHeadersAll(elfFile, shTable);
401 if (ret) return ret;
402 entries = shTable.size();
403
Connor O'Brien3278a162020-02-13 21:45:22 -0800404 vector<struct bpf_prog_def> pd;
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700405 ret = readProgDefs(elfFile, pd);
Connor O'Brien3278a162020-02-13 21:45:22 -0800406 if (ret) return ret;
407 vector<string> progDefNames;
408 ret = getSectionSymNames(elfFile, "progs", progDefNames);
409 if (!pd.empty() && ret) return ret;
410
Joel Fernandesd76a2002018-10-16 13:19:58 -0700411 for (int i = 0; i < entries; i++) {
412 string name;
413 codeSection cs_temp;
414 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
415
416 ret = getSymName(elfFile, shTable[i].sh_name, name);
417 if (ret) return ret;
418
419 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800420
Tyler Wear4e2f4602022-02-03 09:46:01 -0800421 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800422
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800423 if (!IsAllowed(ptype, allowed, numAllowed)) {
424 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
425 return -1;
426 }
427
Tyler Wear4e2f4602022-02-03 09:46:01 -0800428 // This must be done before '/' is replaced with '_'.
429 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800430
Tyler Wear4e2f4602022-02-03 09:46:01 -0800431 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700432
Tyler Wear4e2f4602022-02-03 09:46:01 -0800433 // convert all slashes to underscores
434 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800435
Tyler Wear4e2f4602022-02-03 09:46:01 -0800436 cs_temp.type = ptype;
437 cs_temp.name = name;
438
439 ret = readSectionByIdx(elfFile, i, cs_temp.data);
440 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700441 ALOGD("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800442
443 vector<string> csSymNames;
444 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
445 if (ret || !csSymNames.size()) return ret;
446 for (size_t i = 0; i < progDefNames.size(); ++i) {
447 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
448 cs_temp.prog_def = pd[i];
449 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800450 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700451 }
452
453 /* Check for rel section */
454 if (cs_temp.data.size() > 0 && i < entries) {
455 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
456 if (ret) return ret;
457
Tyler Wear4e2f4602022-02-03 09:46:01 -0800458 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700459 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
460 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700461 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700462 }
463 }
464
465 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700466 cs.push_back(std::move(cs_temp));
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700467 ALOGD("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700468 }
469 }
470 return 0;
471}
472
473static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
474 vector<Elf64_Sym> symtab;
475 int ret = 0;
476
477 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
478 if (ret) return ret;
479
480 if (index >= (int)symtab.size()) return -1;
481
482 return getSymName(elfFile, symtab[index].st_name, name);
483}
484
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700485static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
486 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700487 // Assuming fd is a valid Bpf Map file descriptor then
488 // all the following should always succeed on a 4.14+ kernel.
489 // If they somehow do fail, they'll return -1 (and set errno),
490 // which should then cause (among others) a key_size mismatch.
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700491 int fd_type = bpfGetFdMapType(fd);
492 int fd_key_size = bpfGetFdKeySize(fd);
493 int fd_value_size = bpfGetFdValueSize(fd);
494 int fd_max_entries = bpfGetFdMaxEntries(fd);
495 int fd_map_flags = bpfGetFdMapFlags(fd);
496
497 // DEVMAPs are readonly from the bpf program side's point of view, as such
498 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
499 int desired_map_flags = (int)mapDef.map_flags;
500 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
501 desired_map_flags |= BPF_F_RDONLY_PROG;
502
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000503 // The .h file enforces that this is a power of two, and page size will
504 // also always be a power of two, so this logic is actually enough to
505 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000506 unsigned int desired_max_entries = mapDef.max_entries;
507 if (type == BPF_MAP_TYPE_RINGBUF) {
508 if (desired_max_entries < page_size) desired_max_entries = page_size;
509 }
510
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700511 // The following checks should *never* trigger, if one of them somehow does,
512 // it probably means a bpf .o file has been changed/replaced at runtime
513 // and bpfloader was manually rerun (normally it should only run *once*
514 // early during the boot process).
515 // Another possibility is that something is misconfigured in the code:
516 // most likely a shared map is declared twice differently.
517 // But such a change should never be checked into the source tree...
518 if ((fd_type == type) &&
519 (fd_key_size == (int)mapDef.key_size) &&
520 (fd_value_size == (int)mapDef.value_size) &&
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000521 (fd_max_entries == (int)desired_max_entries) &&
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700522 (fd_map_flags == desired_map_flags)) {
523 return true;
524 }
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700525
526 ALOGE("bpf map name %s mismatch: desired/found: "
527 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
528 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
529 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
530 return false;
531}
532
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800533static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700534 const char* prefix) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700535 int ret;
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700536 vector<char> mdData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700537 vector<struct bpf_map_def> md;
538 vector<string> mapNames;
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700539 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700540
541 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800542 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700543 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800544
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700545 if (mdData.size() % sizeof(struct bpf_map_def)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700546 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700547 mdData.size(), sizeof(struct bpf_map_def));
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800548 return -1;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800549 }
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700550 md.resize(mdData.size() / sizeof(struct bpf_map_def));
551 memcpy(md.data(), mdData.data(), mdData.size());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700552
Connor O'Brien3278a162020-02-13 21:45:22 -0800553 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700554 if (ret) return ret;
555
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700556 unsigned kvers = kernelVersion();
557
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700558 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +0000559 if (md[i].zero != 0) abort();
560
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700561 if (kvers < md[i].min_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700562 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700563 mapNames[i].c_str(), kvers, md[i].min_kver);
564 mapFds.push_back(unique_fd());
565 continue;
566 }
567
568 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700569 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700570 mapNames[i].c_str(), kvers, md[i].max_kver);
571 mapFds.push_back(unique_fd());
572 continue;
573 }
574
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700575 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700576 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
577 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
578 // of be approximated: HASH has the same userspace visible api.
579 // However it cannot be used by ebpf programs in the same way.
580 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
581 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
582 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
583 // programs as being 5.4+...
584 type = BPF_MAP_TYPE_HASH;
585 }
586
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000587 // The .h file enforces that this is a power of two, and page size will
588 // also always be a power of two, so this logic is actually enough to
589 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000590 unsigned int max_entries = md[i].max_entries;
591 if (type == BPF_MAP_TYPE_RINGBUF) {
592 if (max_entries < page_size) max_entries = page_size;
593 }
594
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700595 // Format of pin location is /sys/fs/bpf/<prefix>map_<objName>_<mapName>
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700596 // except that maps shared across .o's have empty <objName>
597 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700598 string mapPinLoc = string(BPF_FS_PATH) + prefix + "map_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700599 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700600 bool reuse = false;
601 unique_fd fd;
602 int saved_errno;
603
Joel Fernandesd76a2002018-10-16 13:19:58 -0700604 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskieb199dd2022-07-01 03:21:40 -0700605 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800606 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700607 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700608 reuse = true;
609 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700610 union bpf_attr req = {
611 .map_type = type,
612 .key_size = md[i].key_size,
613 .value_size = md[i].value_size,
614 .max_entries = max_entries,
615 .map_flags = md[i].map_flags,
Connor O'Brien35425e52022-01-18 21:41:16 -0800616 };
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700617 strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
618 fd.reset(bpf(BPF_MAP_CREATE, req));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800619 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700620 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700621 }
622
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700623 if (!fd.ok()) return -saved_errno;
624
625 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
626 // safety (since reuse code path is rare) run these checks even if we just created it.
627 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
628 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700629
630 if (!reuse) {
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700631 ret = bpfFdPin(fd, mapPinLoc.c_str());
632 if (ret) {
633 int err = errno;
634 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
635 return -err;
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700636 }
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800637 ret = chmod(mapPinLoc.c_str(), md[i].mode);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700638 if (ret) {
639 int err = errno;
640 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
641 strerror(err));
642 return -err;
643 }
Maciej Żenczykowski5e4aabf2022-06-27 01:15:53 -0700644 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
645 if (ret) {
646 int err = errno;
647 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
648 ret, err, strerror(err));
649 return -err;
650 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700651 }
652
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700653 int mapId = bpfGetFdMapId(fd);
654 if (mapId == -1) {
655 ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700656 } else {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700657 ALOGI("map %s id %d", mapPinLoc.c_str(), mapId);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700658 }
659
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700660 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700661 }
662
663 return ret;
664}
665
Joel Fernandesd76a2002018-10-16 13:19:58 -0700666static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
667 int insnIndex;
668 struct bpf_insn *insn, *insns;
669
670 insns = (struct bpf_insn*)(insnsPtr);
671
672 insnIndex = offset / sizeof(struct bpf_insn);
673 insn = &insns[insnIndex];
674
Maciej Żenczykowski509b1b92023-03-07 01:11:20 +0000675 // Occasionally might be useful for relocation debugging, but pretty spammy
676 if (0) {
677 ALOGD("applying relo to instruction at byte offset: %llu, "
678 "insn offset %d, insn %llx",
679 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
680 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700681
682 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700683 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700684 return;
685 }
686
687 insn->imm = fd;
688 insn->src_reg = BPF_PSEUDO_MAP_FD;
689}
690
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700691static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700692 vector<string> mapNames;
693
Connor O'Brien3278a162020-02-13 21:45:22 -0800694 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700695 if (ret) return;
696
697 for (int k = 0; k != (int)cs.size(); k++) {
698 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
699 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
700
701 for (int i = 0; i < n_rel; i++) {
702 int symIndex = ELF64_R_SYM(rel[i].r_info);
703 string symName;
704
705 ret = getSymNameByIdx(elfFile, symIndex, symName);
706 if (ret) return;
707
708 /* Find the map fd and apply relo */
709 for (int j = 0; j < (int)mapNames.size(); j++) {
710 if (!mapNames[j].compare(symName)) {
711 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
712 break;
713 }
714 }
715 }
716 }
717}
718
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800719static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700720 const char* prefix) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800721 unsigned kvers = kernelVersion();
Joel Fernandesd76a2002018-10-16 13:19:58 -0700722
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000723 if (!kvers) {
724 ALOGE("unable to get kernel version");
725 return -EINVAL;
726 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700727
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700728 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700729
730 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700731 unique_fd& fd = cs[i].prog_fd;
732 int ret;
Maciej Żenczykowski681f6042020-04-21 15:34:18 -0700733 string name = cs[i].name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700734
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000735 if (!cs[i].prog_def.has_value()) {
736 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
737 return -EINVAL;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -0800738 }
739
Maciej Żenczykowski5c791652022-08-03 23:49:08 +0000740 unsigned min_kver = cs[i].prog_def->min_kver;
741 unsigned max_kver = cs[i].prog_def->max_kver;
742 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
743 max_kver, kvers);
744 if (kvers < min_kver) continue;
745 if (kvers >= max_kver) continue;
746
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()));
759 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
760 (!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 ALOGD("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
780 cs[i].name.c_str(), fd.get(), (!fd.ok() ? std::strerror(errno) : "no error"));
Tyler Wear4e2f4602022-02-03 09:46:01 -0800781
Maciej Żenczykowskib44e2872023-06-12 23:10:52 -0700782 if (!fd.ok()) {
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 Żenczykowskib44e2872023-06-12 23:10:52 -0700824 ALOGI("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;
851 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700852 ALOGD("Loading %s%s ELF object %s with license %s",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -0700853 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -0700854 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700855 }
856
Maciej Żenczykowskia5646cb2024-03-08 08:07:46 +0000857 ALOGI("Platform BpfLoader processing ELF object %s", elfPath);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800858
Maciej Żenczykowskic82f5662024-03-10 14:37:24 -0700859 ret = readCodeSections(elfFile, cs, location.allowedProgTypes, location.allowedProgTypesLength);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700860 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700861 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700862 return ret;
863 }
864
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700865 ret = createMaps(elfPath, elfFile, mapFds, location.prefix);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700866 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700867 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700868 return ret;
869 }
870
871 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700872 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700873
874 applyMapRelo(elfFile, mapFds, cs);
875
Maciej Żenczykowskic1647d72024-03-10 19:11:58 -0700876 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700877 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700878
879 return ret;
880}
881
Joel Fernandesd76a2002018-10-16 13:19:58 -0700882} // namespace bpf
883} // namespace android