blob: 83f6a8884e806783293529f149ce358bfd84a332 [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 Żenczykowski8a117a32023-06-16 08:18:49 +000034// This is BpfLoader v0.40
Maciej Żenczykowski05825662023-01-20 13:00:24 +000035// WARNING: If you ever hit cherrypick conflicts here you're doing it wrong:
36// You are NOT allowed to cherrypick bpfloader related patches out of order.
37// (indeed: cherrypicking is probably a bad idea and you should merge instead)
38// Mainline supports ONLY the published versions of the bpfloader for each Android release.
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080039#define BPFLOADER_VERSION_MAJOR 0u
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +000040#define BPFLOADER_VERSION_MINOR 40u
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -080041#define BPFLOADER_VERSION ((BPFLOADER_VERSION_MAJOR << 16) | BPFLOADER_VERSION_MINOR)
42
Maciej Żenczykowski300c51f2022-12-14 04:18:02 -080043#include "BpfSyscallWrappers.h"
Maciej Żenczykowski07375e22020-02-19 14:23:59 -080044#include "bpf/BpfUtils.h"
Ken Chend5689472021-12-20 18:07:21 +080045#include "bpf/bpf_map_def.h"
Joel Fernandesd76a2002018-10-16 13:19:58 -070046#include "include/libbpf_android.h"
47
Maciej Żenczykowskib3dcc142022-07-24 22:42:33 +000048#if BPFLOADER_VERSION < COMPILE_FOR_BPFLOADER_VERSION
49#error "BPFLOADER_VERSION is less than COMPILE_FOR_BPFLOADER_VERSION"
50#endif
51
Connor O'Brien35425e52022-01-18 21:41:16 -080052#include <bpf/bpf.h>
53
Joel Fernandesd76a2002018-10-16 13:19:58 -070054#include <cstdlib>
55#include <fstream>
56#include <iostream>
Connor O'Brien3278a162020-02-13 21:45:22 -080057#include <optional>
Joel Fernandesd76a2002018-10-16 13:19:58 -070058#include <string>
Connor O'Brien35425e52022-01-18 21:41:16 -080059#include <unordered_map>
Christopher Ferrisc151c672019-02-01 15:31:26 -080060#include <vector>
Joel Fernandesd76a2002018-10-16 13:19:58 -070061
Connor O'Brien35425e52022-01-18 21:41:16 -080062#include <android-base/cmsg.h>
63#include <android-base/file.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070064#include <android-base/strings.h>
Connor O'Brien8d49fc72019-10-24 18:23:49 -070065#include <android-base/unique_fd.h>
Ryan Zukliece89f502022-12-15 16:14:32 -080066#include <cutils/properties.h>
Joel Fernandesd76a2002018-10-16 13:19:58 -070067
68#define BPF_FS_PATH "/sys/fs/bpf/"
69
70// Size of the BPF log buffer for verifier logging
Stephane Leeeb61b732021-10-21 17:03:11 -070071#define BPF_LOAD_LOG_SZ 0xfffff
Joel Fernandesd76a2002018-10-16 13:19:58 -070072
Tyler Wear4e2f4602022-02-03 09:46:01 -080073// Unspecified attach type is 0 which is BPF_CGROUP_INET_INGRESS.
74#define BPF_ATTACH_TYPE_UNSPEC BPF_CGROUP_INET_INGRESS
75
Joel Fernandesd76a2002018-10-16 13:19:58 -070076using android::base::StartsWith;
Connor O'Brien8d49fc72019-10-24 18:23:49 -070077using android::base::unique_fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -070078using std::ifstream;
79using std::ios;
Connor O'Brien3278a162020-02-13 21:45:22 -080080using std::optional;
Christopher Ferrisc151c672019-02-01 15:31:26 -080081using std::string;
Joel Fernandesd76a2002018-10-16 13:19:58 -070082using std::vector;
83
Ryan Zukliece89f502022-12-15 16:14:32 -080084static std::string getBuildTypeInternal() {
85 char value[PROPERTY_VALUE_MAX] = {};
86 (void)property_get("ro.build.type", value, "unknown"); // ignore length
87 return value;
88}
89
Joel Fernandesd76a2002018-10-16 13:19:58 -070090namespace android {
91namespace bpf {
92
Ryan Zukliece89f502022-12-15 16:14:32 -080093const std::string& getBuildType() {
94 static std::string t = getBuildTypeInternal();
95 return t;
96}
97
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +000098static unsigned int page_size = static_cast<unsigned int>(getpagesize());
99
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700100constexpr const char* lookupSelinuxContext(const domain d, const char* const unspecified = "") {
101 switch (d) {
102 case domain::unspecified: return unspecified;
103 case domain::platform: return "fs_bpf";
104 case domain::tethering: return "fs_bpf_tethering";
105 case domain::net_private: return "fs_bpf_net_private";
106 case domain::net_shared: return "fs_bpf_net_shared";
107 case domain::netd_readonly: return "fs_bpf_netd_readonly";
108 case domain::netd_shared: return "fs_bpf_netd_shared";
109 case domain::vendor: return "fs_bpf_vendor";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +0000110 case domain::loader: return "fs_bpf_loader";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700111 default: return "(unrecognized)";
112 }
113}
114
115domain getDomainFromSelinuxContext(const char s[BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE]) {
116 for (domain d : AllDomains) {
117 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
118 if (strlen(lookupSelinuxContext(d)) >= BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE) abort();
119 if (!strncmp(s, lookupSelinuxContext(d), BPF_SELINUX_CONTEXT_CHAR_ARRAY_SIZE)) return d;
120 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700121 ALOGW("ignoring unrecognized selinux_context '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700122 // We should return 'unrecognized' here, however: returning unspecified will
123 // result in the system simply using the default context, which in turn
124 // will allow future expansion by adding more restrictive selinux types.
125 // Older bpfloader will simply ignore that, and use the less restrictive default.
126 // This does mean you CANNOT later add a *less* restrictive type than the default.
127 //
128 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
129 return domain::unspecified;
130}
131
132constexpr const char* lookupPinSubdir(const domain d, const char* const unspecified = "") {
133 switch (d) {
134 case domain::unspecified: return unspecified;
135 case domain::platform: return "/";
136 case domain::tethering: return "tethering/";
137 case domain::net_private: return "net_private/";
138 case domain::net_shared: return "net_shared/";
139 case domain::netd_readonly: return "netd_readonly/";
140 case domain::netd_shared: return "netd_shared/";
141 case domain::vendor: return "vendor/";
Maciej Żenczykowski9a2093d2022-12-02 13:46:53 +0000142 case domain::loader: return "loader/";
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700143 default: return "(unrecognized)";
144 }
145};
146
147domain getDomainFromPinSubdir(const char s[BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE]) {
148 for (domain d : AllDomains) {
149 // Not sure how to enforce this at compile time, so abort() bpfloader at boot instead
150 if (strlen(lookupPinSubdir(d)) >= BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE) abort();
151 if (!strncmp(s, lookupPinSubdir(d), BPF_PIN_SUBDIR_CHAR_ARRAY_SIZE)) return d;
152 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700153 ALOGE("unrecognized pin_subdir '%-32s'", s);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700154 // pin_subdir affects the object's full pathname,
155 // and thus using the default would change the location and thus our code's ability to find it,
156 // hence this seems worth treating as a true error condition.
157 //
158 // Note: we cannot just abort() here as this might be a mainline module shipped optional update
159 // However, our callers will treat this as an error, and stop loading the specific .o,
160 // which will fail bpfloader if the .o is marked critical.
161 return domain::unrecognized;
162}
163
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700164static string pathToObjName(const string& path) {
165 // extract everything after the final slash, ie. this is the filename 'foo@1.o' or 'bar.o'
166 string filename = android::base::Split(path, "/").back();
167 // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
168 string name = filename.substr(0, filename.find_last_of('.'));
169 // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
170 // this can be used to provide duplicate programs (mux based on the bpfloader version)
171 return name.substr(0, name.find_last_of('@'));
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800172}
173
Joel Fernandesd76a2002018-10-16 13:19:58 -0700174typedef struct {
175 const char* name;
176 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800177 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700178} sectionType;
179
180/*
181 * Map section name prefixes to program types, the section name will be:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700182 * SECTION(<prefix>/<name-of-program>)
Joel Fernandesd76a2002018-10-16 13:19:58 -0700183 * For example:
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700184 * SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
Joel Fernandesd76a2002018-10-16 13:19:58 -0700185 * is the name of the program, and tracepoint is the type.
Maciej Żenczykowski3adb1d52021-10-22 19:27:10 -0700186 *
187 * However, be aware that you should not be directly using the SECTION() macro.
188 * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
Joel Fernandesd76a2002018-10-16 13:19:58 -0700189 */
190sectionType sectionNameTypes[] = {
Maciej Żenczykowskie245fa92023-04-05 01:16:05 +0000191 {"bind4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND},
192 {"bind6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND},
193 {"cgroupskb/", BPF_PROG_TYPE_CGROUP_SKB, BPF_ATTACH_TYPE_UNSPEC},
194 {"cgroupsock/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_ATTACH_TYPE_UNSPEC},
195 {"connect4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT},
196 {"connect6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT},
197 {"egress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_EGRESS},
198 {"getsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT},
199 {"ingress/", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS},
200 {"kprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
201 {"kretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
202 {"lwt_in/", BPF_PROG_TYPE_LWT_IN, BPF_ATTACH_TYPE_UNSPEC},
203 {"lwt_out/", BPF_PROG_TYPE_LWT_OUT, BPF_ATTACH_TYPE_UNSPEC},
204 {"lwt_seg6local/", BPF_PROG_TYPE_LWT_SEG6LOCAL, BPF_ATTACH_TYPE_UNSPEC},
205 {"lwt_xmit/", BPF_PROG_TYPE_LWT_XMIT, BPF_ATTACH_TYPE_UNSPEC},
206 {"perf_event/", BPF_PROG_TYPE_PERF_EVENT, BPF_ATTACH_TYPE_UNSPEC},
207 {"postbind4/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND},
208 {"postbind6/", BPF_PROG_TYPE_CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND},
209 {"recvmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG},
210 {"recvmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG},
211 {"schedact/", BPF_PROG_TYPE_SCHED_ACT, BPF_ATTACH_TYPE_UNSPEC},
212 {"schedcls/", BPF_PROG_TYPE_SCHED_CLS, BPF_ATTACH_TYPE_UNSPEC},
213 {"sendmsg4/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG},
214 {"sendmsg6/", BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG},
215 {"setsockopt/", BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT},
216 {"skfilter/", BPF_PROG_TYPE_SOCKET_FILTER, BPF_ATTACH_TYPE_UNSPEC},
217 {"sockops/", BPF_PROG_TYPE_SOCK_OPS, BPF_CGROUP_SOCK_OPS},
218 {"sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_CGROUP_SYSCTL},
219 {"tracepoint/", BPF_PROG_TYPE_TRACEPOINT, BPF_ATTACH_TYPE_UNSPEC},
220 {"uprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
221 {"uretprobe/", BPF_PROG_TYPE_KPROBE, BPF_ATTACH_TYPE_UNSPEC},
222 {"xdp/", BPF_PROG_TYPE_XDP, BPF_ATTACH_TYPE_UNSPEC},
Joel Fernandesd76a2002018-10-16 13:19:58 -0700223};
224
225typedef struct {
226 enum bpf_prog_type type;
Tyler Wear4e2f4602022-02-03 09:46:01 -0800227 enum bpf_attach_type expected_attach_type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700228 string name;
229 vector<char> data;
230 vector<char> rel_data;
Connor O'Brien3278a162020-02-13 21:45:22 -0800231 optional<struct bpf_prog_def> prog_def;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700232
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700233 unique_fd prog_fd; /* fd after loading */
Joel Fernandesd76a2002018-10-16 13:19:58 -0700234} codeSection;
235
Joel Fernandesd76a2002018-10-16 13:19:58 -0700236static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
237 elfFile.seekg(0);
238 if (elfFile.fail()) return -1;
239
240 if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
241
242 return 0;
243}
244
245/* Reads all section header tables into an Shdr array */
246static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
247 Elf64_Ehdr eh;
248 int ret = 0;
249
250 ret = readElfHeader(elfFile, &eh);
251 if (ret) return ret;
252
253 elfFile.seekg(eh.e_shoff);
254 if (elfFile.fail()) return -1;
255
256 /* Read shdr table entries */
257 shTable.resize(eh.e_shnum);
258
259 if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
260
261 return 0;
262}
263
264/* Read a section by its index - for ex to get sec hdr strtab blob */
265static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
266 vector<Elf64_Shdr> shTable;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800267 int ret = readSectionHeadersAll(elfFile, shTable);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700268 if (ret) return ret;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700269
270 elfFile.seekg(shTable[id].sh_offset);
271 if (elfFile.fail()) return -1;
272
273 sec.resize(shTable[id].sh_size);
274 if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
275
276 return 0;
277}
278
279/* Read whole section header string table */
280static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
281 Elf64_Ehdr eh;
Maciej Żenczykowskid56ec052021-01-15 00:27:04 -0800282 int ret = readElfHeader(elfFile, &eh);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700283 if (ret) return ret;
284
285 ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
286 if (ret) return ret;
287
288 return 0;
289}
290
291/* Get name from offset in strtab */
292static int getSymName(ifstream& elfFile, int nameOff, string& name) {
293 int ret;
294 vector<char> secStrTab;
295
296 ret = readSectionHeaderStrtab(elfFile, secStrTab);
297 if (ret) return ret;
298
299 if (nameOff >= (int)secStrTab.size()) return -1;
300
301 name = string((char*)secStrTab.data() + nameOff);
302 return 0;
303}
304
305/* Reads a full section by name - example to get the GPL license */
306static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
307 vector<char> secStrTab;
308 vector<Elf64_Shdr> shTable;
309 int ret;
310
311 ret = readSectionHeadersAll(elfFile, shTable);
312 if (ret) return ret;
313
314 ret = readSectionHeaderStrtab(elfFile, secStrTab);
315 if (ret) return ret;
316
317 for (int i = 0; i < (int)shTable.size(); i++) {
318 char* secname = secStrTab.data() + shTable[i].sh_name;
319 if (!secname) continue;
320
321 if (!strcmp(secname, name)) {
322 vector<char> dataTmp;
323 dataTmp.resize(shTable[i].sh_size);
324
325 elfFile.seekg(shTable[i].sh_offset);
326 if (elfFile.fail()) return -1;
327
328 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
329
330 data = dataTmp;
331 return 0;
332 }
333 }
334 return -2;
335}
336
Maciej Żenczykowski7ed94ef2021-07-06 01:47:15 -0700337unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800338 vector<char> theBytes;
339 int ret = readSectionByName(name, elfFile, theBytes);
340 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700341 ALOGD("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800342 return defVal;
343 } else if (theBytes.size() < sizeof(unsigned int)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700344 ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800345 return defVal;
346 } else {
347 // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
348 unsigned int value = static_cast<unsigned char>(theBytes[3]);
349 value <<= 8;
350 value += static_cast<unsigned char>(theBytes[2]);
351 value <<= 8;
352 value += static_cast<unsigned char>(theBytes[1]);
353 value <<= 8;
354 value += static_cast<unsigned char>(theBytes[0]);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700355 ALOGI("Section %s value is %u [0x%x]", name, value, value);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800356 return value;
357 }
358}
359
Joel Fernandesd76a2002018-10-16 13:19:58 -0700360static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
361 int ret;
362 vector<Elf64_Shdr> shTable;
363
364 ret = readSectionHeadersAll(elfFile, shTable);
365 if (ret) return ret;
366
367 for (int i = 0; i < (int)shTable.size(); i++) {
368 if ((int)shTable[i].sh_type != type) continue;
369
370 vector<char> dataTmp;
371 dataTmp.resize(shTable[i].sh_size);
372
373 elfFile.seekg(shTable[i].sh_offset);
374 if (elfFile.fail()) return -1;
375
376 if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
377
378 data = dataTmp;
379 return 0;
380 }
381 return -2;
382}
383
384static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
385 return (a.st_value < b.st_value);
386}
387
388static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
389 int ret, numElems;
390 Elf64_Sym* buf;
391 vector<char> secData;
392
393 ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
394 if (ret) return ret;
395
396 buf = (Elf64_Sym*)secData.data();
397 numElems = (secData.size() / sizeof(Elf64_Sym));
398 data.assign(buf, buf + numElems);
399
400 if (sort) std::sort(data.begin(), data.end(), symCompare);
401 return 0;
402}
403
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700404static enum bpf_prog_type getFuseProgType() {
405 int result = BPF_PROG_TYPE_UNSPEC;
406 ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
407 return static_cast<bpf_prog_type>(result);
408}
409
Joel Fernandesd76a2002018-10-16 13:19:58 -0700410static enum bpf_prog_type getSectionType(string& name) {
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800411 for (auto& snt : sectionNameTypes)
412 if (StartsWith(name, snt.name)) return snt.type;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700413
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000414 // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700415 if (StartsWith(name, "fuse/")) return getFuseProgType();
Paul Lawrence9548f9f2021-11-09 16:32:43 +0000416
Joel Fernandesd76a2002018-10-16 13:19:58 -0700417 return BPF_PROG_TYPE_UNSPEC;
418}
419
Tyler Wear4e2f4602022-02-03 09:46:01 -0800420static enum bpf_attach_type getExpectedAttachType(string& name) {
421 for (auto& snt : sectionNameTypes)
422 if (StartsWith(name, snt.name)) return snt.expected_attach_type;
423 return BPF_ATTACH_TYPE_UNSPEC;
424}
425
Joel Fernandesd76a2002018-10-16 13:19:58 -0700426static string getSectionName(enum bpf_prog_type type)
427{
Maciej Żenczykowski2b203132021-11-18 15:13:36 -0800428 for (auto& snt : sectionNameTypes)
429 if (snt.type == type)
430 return string(snt.name);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700431
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800432 return "UNKNOWN SECTION NAME " + std::to_string(type);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700433}
Joel Fernandesd76a2002018-10-16 13:19:58 -0700434
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800435static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd,
436 size_t sizeOfBpfProgDef) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800437 vector<char> pdData;
438 int ret = readSectionByName("progs", elfFile, pdData);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800439 // Older file formats do not require a 'progs' section at all.
440 // (We should probably figure out whether this is behaviour which is safe to remove now.)
Connor O'Brien3278a162020-02-13 21:45:22 -0800441 if (ret == -2) return 0;
442 if (ret) return ret;
443
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800444 if (pdData.size() % sizeOfBpfProgDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700445 ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800446 pdData.size(), sizeOfBpfProgDef);
447 return -1;
448 };
449
450 int progCount = pdData.size() / sizeOfBpfProgDef;
451 pd.resize(progCount);
452 size_t trimmedSize = std::min(sizeOfBpfProgDef, sizeof(struct bpf_prog_def));
453
454 const char* dataPtr = pdData.data();
455 for (auto& p : pd) {
456 // First we zero initialize
457 memset(&p, 0, sizeof(p));
458 // Then we set non-zero defaults
459 p.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
460 // Then we copy over the structure prefix from the ELF file.
461 memcpy(&p, dataPtr, trimmedSize);
462 // Move to next struct in the ELF file
463 dataPtr += sizeOfBpfProgDef;
464 }
Connor O'Brien3278a162020-02-13 21:45:22 -0800465 return 0;
466}
467
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800468static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
469 optional<unsigned> symbolType = std::nullopt) {
Connor O'Brien3278a162020-02-13 21:45:22 -0800470 int ret;
471 string name;
472 vector<Elf64_Sym> symtab;
473 vector<Elf64_Shdr> shTable;
474
475 ret = readSymTab(elfFile, 1 /* sort */, symtab);
476 if (ret) return ret;
477
478 /* Get index of section */
479 ret = readSectionHeadersAll(elfFile, shTable);
480 if (ret) return ret;
481
482 int sec_idx = -1;
483 for (int i = 0; i < (int)shTable.size(); i++) {
484 ret = getSymName(elfFile, shTable[i].sh_name, name);
485 if (ret) return ret;
486
487 if (!name.compare(sectionName)) {
488 sec_idx = i;
489 break;
490 }
491 }
492
493 /* No section found with matching name*/
494 if (sec_idx == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700495 ALOGW("No %s section could be found in elf object", sectionName.c_str());
Connor O'Brien3278a162020-02-13 21:45:22 -0800496 return -1;
497 }
498
499 for (int i = 0; i < (int)symtab.size(); i++) {
Connor O'Brien0ea4c6b2022-01-14 00:18:11 -0800500 if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
501
Connor O'Brien3278a162020-02-13 21:45:22 -0800502 if (symtab[i].st_shndx == sec_idx) {
503 string s;
504 ret = getSymName(elfFile, symtab[i].st_name, s);
505 if (ret) return ret;
506 names.push_back(s);
507 }
508 }
509
510 return 0;
511}
512
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800513static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
514 if (allowed == nullptr) return true;
515
516 for (size_t i = 0; i < numAllowed; i++) {
Paul Lawrence7fb8b542022-07-19 16:13:49 -0700517 if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
518 if (type == getFuseProgType()) return true;
519 } else if (type == allowed[i])
520 return true;
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800521 }
522
523 return false;
524}
525
Joel Fernandesd76a2002018-10-16 13:19:58 -0700526/* Read a section by its index - for ex to get sec hdr strtab blob */
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800527static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs, size_t sizeOfBpfProgDef,
528 const bpf_prog_type* allowed, size_t numAllowed) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700529 vector<Elf64_Shdr> shTable;
530 int entries, ret = 0;
531
532 ret = readSectionHeadersAll(elfFile, shTable);
533 if (ret) return ret;
534 entries = shTable.size();
535
Connor O'Brien3278a162020-02-13 21:45:22 -0800536 vector<struct bpf_prog_def> pd;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800537 ret = readProgDefs(elfFile, pd, sizeOfBpfProgDef);
Connor O'Brien3278a162020-02-13 21:45:22 -0800538 if (ret) return ret;
539 vector<string> progDefNames;
540 ret = getSectionSymNames(elfFile, "progs", progDefNames);
541 if (!pd.empty() && ret) return ret;
542
Joel Fernandesd76a2002018-10-16 13:19:58 -0700543 for (int i = 0; i < entries; i++) {
544 string name;
545 codeSection cs_temp;
546 cs_temp.type = BPF_PROG_TYPE_UNSPEC;
547
548 ret = getSymName(elfFile, shTable[i].sh_name, name);
549 if (ret) return ret;
550
551 enum bpf_prog_type ptype = getSectionType(name);
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800552
Tyler Wear4e2f4602022-02-03 09:46:01 -0800553 if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800554
Steven Moreland0f10f3f2019-12-12 14:22:34 -0800555 if (!IsAllowed(ptype, allowed, numAllowed)) {
556 ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
557 return -1;
558 }
559
Tyler Wear4e2f4602022-02-03 09:46:01 -0800560 // This must be done before '/' is replaced with '_'.
561 cs_temp.expected_attach_type = getExpectedAttachType(name);
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -0800562
Tyler Wear4e2f4602022-02-03 09:46:01 -0800563 string oldName = name;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700564
Tyler Wear4e2f4602022-02-03 09:46:01 -0800565 // convert all slashes to underscores
566 std::replace(name.begin(), name.end(), '/', '_');
Connor O'Brien3278a162020-02-13 21:45:22 -0800567
Tyler Wear4e2f4602022-02-03 09:46:01 -0800568 cs_temp.type = ptype;
569 cs_temp.name = name;
570
571 ret = readSectionByIdx(elfFile, i, cs_temp.data);
572 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700573 ALOGD("Loaded code section %d (%s)", i, name.c_str());
Tyler Wear4e2f4602022-02-03 09:46:01 -0800574
575 vector<string> csSymNames;
576 ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
577 if (ret || !csSymNames.size()) return ret;
578 for (size_t i = 0; i < progDefNames.size(); ++i) {
579 if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
580 cs_temp.prog_def = pd[i];
581 break;
Connor O'Brien3278a162020-02-13 21:45:22 -0800582 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700583 }
584
585 /* Check for rel section */
586 if (cs_temp.data.size() > 0 && i < entries) {
587 ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
588 if (ret) return ret;
589
Tyler Wear4e2f4602022-02-03 09:46:01 -0800590 if (name == (".rel" + oldName)) {
Joel Fernandesd76a2002018-10-16 13:19:58 -0700591 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
592 if (ret) return ret;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700593 ALOGD("Loaded relo section %d (%s)", i, name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700594 }
595 }
596
597 if (cs_temp.data.size() > 0) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700598 cs.push_back(std::move(cs_temp));
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700599 ALOGD("Adding section %d to cs list", i);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700600 }
601 }
602 return 0;
603}
604
605static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
606 vector<Elf64_Sym> symtab;
607 int ret = 0;
608
609 ret = readSymTab(elfFile, 0 /* !sort */, symtab);
610 if (ret) return ret;
611
612 if (index >= (int)symtab.size()) return -1;
613
614 return getSymName(elfFile, symtab[index].st_name, name);
615}
616
Connor O'Brien35425e52022-01-18 21:41:16 -0800617static bool waitpidTimeout(pid_t pid, int timeoutMs) {
618 // Add SIGCHLD to the signal set.
619 sigset_t child_mask, original_mask;
620 sigemptyset(&child_mask);
621 sigaddset(&child_mask, SIGCHLD);
622 if (sigprocmask(SIG_BLOCK, &child_mask, &original_mask) == -1) return false;
623
624 // Wait for a SIGCHLD notification.
625 errno = 0;
626 timespec ts = {0, timeoutMs * 1000000};
627 int wait_result = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, nullptr, &ts));
628
629 // Restore the original signal set.
630 sigprocmask(SIG_SETMASK, &original_mask, nullptr);
631
632 if (wait_result == -1) return false;
633
634 int status;
635 return TEMP_FAILURE_RETRY(waitpid(pid, &status, WNOHANG)) == pid;
636}
637
638static std::optional<unique_fd> getMapBtfInfo(const char* elfPath,
639 std::unordered_map<string, std::pair<uint32_t, uint32_t>> &btfTypeIds) {
640 unique_fd bpfloaderSocket, btfloaderSocket;
641 if (!android::base::Socketpair(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0, &bpfloaderSocket,
642 &btfloaderSocket)) {
643 return {};
644 }
645
646 unique_fd pipeRead, pipeWrite;
647 if (!android::base::Pipe(&pipeRead, &pipeWrite, O_NONBLOCK)) {
648 return {};
649 }
650
651 pid_t pid = fork();
652 if (pid < 0) return {};
653 if (!pid) {
654 bpfloaderSocket.reset();
655 pipeRead.reset();
656 auto socketFdStr = std::to_string(btfloaderSocket.release());
657 auto pipeFdStr = std::to_string(pipeWrite.release());
658
659 if (execl("/system/bin/btfloader", "/system/bin/btfloader", socketFdStr.c_str(),
660 pipeFdStr.c_str(), elfPath, NULL) == -1) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700661 ALOGW("exec btfloader failed with errno %d (%s)", errno, strerror(errno));
Connor O'Brien35425e52022-01-18 21:41:16 -0800662 exit(EX_UNAVAILABLE);
663 }
664 }
665 btfloaderSocket.reset();
666 pipeWrite.reset();
667 if (!waitpidTimeout(pid, 100)) {
668 kill(pid, SIGKILL);
669 return {};
670 }
671
672 unique_fd btfFd;
673 if (android::base::ReceiveFileDescriptors(bpfloaderSocket, nullptr, 0, &btfFd)) return {};
674
675 std::string btfTypeIdStr;
676 if (!android::base::ReadFdToString(pipeRead, &btfTypeIdStr)) return {};
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700677 if (!btfFd.ok()) return {};
Connor O'Brien35425e52022-01-18 21:41:16 -0800678
679 const auto mapTypeIdLines = android::base::Split(btfTypeIdStr, "\n");
680 for (const auto &line : mapTypeIdLines) {
681 const auto vec = android::base::Split(line, " ");
682 // Splitting on newline will give us one empty line
683 if (vec.size() != 3) continue;
684 const int kTid = atoi(vec[1].c_str());
685 const int vTid = atoi(vec[2].c_str());
686 if (!kTid || !vTid) return {};
687 btfTypeIds[vec[0]] = std::make_pair(kTid, vTid);
688 }
689 return btfFd;
690}
691
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700692static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
693 const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700694 // Assuming fd is a valid Bpf Map file descriptor then
695 // all the following should always succeed on a 4.14+ kernel.
696 // If they somehow do fail, they'll return -1 (and set errno),
697 // which should then cause (among others) a key_size mismatch.
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700698 int fd_type = bpfGetFdMapType(fd);
699 int fd_key_size = bpfGetFdKeySize(fd);
700 int fd_value_size = bpfGetFdValueSize(fd);
701 int fd_max_entries = bpfGetFdMaxEntries(fd);
702 int fd_map_flags = bpfGetFdMapFlags(fd);
703
704 // DEVMAPs are readonly from the bpf program side's point of view, as such
705 // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
706 int desired_map_flags = (int)mapDef.map_flags;
707 if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
708 desired_map_flags |= BPF_F_RDONLY_PROG;
709
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000710 // The .h file enforces that this is a power of two, and page size will
711 // also always be a power of two, so this logic is actually enough to
712 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000713 unsigned int desired_max_entries = mapDef.max_entries;
714 if (type == BPF_MAP_TYPE_RINGBUF) {
715 if (desired_max_entries < page_size) desired_max_entries = page_size;
716 }
717
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700718 // The following checks should *never* trigger, if one of them somehow does,
719 // it probably means a bpf .o file has been changed/replaced at runtime
720 // and bpfloader was manually rerun (normally it should only run *once*
721 // early during the boot process).
722 // Another possibility is that something is misconfigured in the code:
723 // most likely a shared map is declared twice differently.
724 // But such a change should never be checked into the source tree...
725 if ((fd_type == type) &&
726 (fd_key_size == (int)mapDef.key_size) &&
727 (fd_value_size == (int)mapDef.value_size) &&
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000728 (fd_max_entries == (int)desired_max_entries) &&
Maciej Żenczykowski1a7fff32022-06-20 18:16:24 -0700729 (fd_map_flags == desired_map_flags)) {
730 return true;
731 }
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700732
733 ALOGE("bpf map name %s mismatch: desired/found: "
734 "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
735 mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
736 fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
737 return false;
738}
739
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -0800740static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700741 const char* prefix, const unsigned long long allowedDomainBitmask,
742 const size_t sizeOfBpfMapDef) {
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700743 int ret;
Connor O'Brien35425e52022-01-18 21:41:16 -0800744 vector<char> mdData, btfData;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700745 vector<struct bpf_map_def> md;
746 vector<string> mapNames;
Connor O'Brien35425e52022-01-18 21:41:16 -0800747 std::unordered_map<string, std::pair<uint32_t, uint32_t>> btfTypeIdMap;
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700748 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700749
750 ret = readSectionByName("maps", elfFile, mdData);
Steven Morelandc0905b42019-12-12 14:21:20 -0800751 if (ret == -2) return 0; // no maps to read
Joel Fernandesd76a2002018-10-16 13:19:58 -0700752 if (ret) return ret;
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800753
754 if (mdData.size() % sizeOfBpfMapDef) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700755 ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800756 mdData.size(), sizeOfBpfMapDef);
757 return -1;
758 };
759
760 int mapCount = mdData.size() / sizeOfBpfMapDef;
761 md.resize(mapCount);
762 size_t trimmedSize = std::min(sizeOfBpfMapDef, sizeof(struct bpf_map_def));
763
764 const char* dataPtr = mdData.data();
765 for (auto& m : md) {
766 // First we zero initialize
767 memset(&m, 0, sizeof(m));
768 // Then we set non-zero defaults
769 m.bpfloader_max_ver = DEFAULT_BPFLOADER_MAX_VER; // v1.0
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700770 m.max_kver = 0xFFFFFFFFu; // matches KVER_INF from bpf_helpers.h
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800771 // Then we copy over the structure prefix from the ELF file.
772 memcpy(&m, dataPtr, trimmedSize);
773 // Move to next struct in the ELF file
774 dataPtr += sizeOfBpfMapDef;
775 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700776
Connor O'Brien3278a162020-02-13 21:45:22 -0800777 ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -0700778 if (ret) return ret;
779
Maciej Żenczykowski411e3f02023-06-09 04:06:01 +0000780 // BpfLoader before v0.39 unconditionally check only 'btf_min_bpfloader_ver'
781 unsigned btfMinBpfLoaderVer = readSectionUint(
782 isUser() ? "btf_user_min_bpfloader_ver" : "btf_min_bpfloader_ver", elfFile, 0);
783
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700784 unsigned btfMinKernelVer = readSectionUint("btf_min_kernel_ver", elfFile, 0);
785 unsigned kvers = kernelVersion();
786
Connor O'Brien35425e52022-01-18 21:41:16 -0800787 std::optional<unique_fd> btfFd;
Maciej Żenczykowskibbab8182022-06-22 22:51:07 -0700788 if ((BPFLOADER_VERSION >= btfMinBpfLoaderVer) && (kvers >= btfMinKernelVer) &&
789 (!readSectionByName(".BTF", elfFile, btfData))) {
Connor O'Brien35425e52022-01-18 21:41:16 -0800790 btfFd = getMapBtfInfo(elfPath, btfTypeIdMap);
791 }
792
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700793 for (int i = 0; i < (int)mapNames.size(); i++) {
Maciej Żenczykowski2a5d0162022-07-21 13:27:24 +0000794 if (md[i].zero != 0) abort();
795
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800796 if (BPFLOADER_VERSION < md[i].bpfloader_min_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700797 ALOGI("skipping map %s which requires bpfloader min ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800798 md[i].bpfloader_min_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700799 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800800 continue;
801 }
802
803 if (BPFLOADER_VERSION >= md[i].bpfloader_max_ver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700804 ALOGI("skipping map %s which requires bpfloader max ver 0x%05x", mapNames[i].c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800805 md[i].bpfloader_max_ver);
Maciej Żenczykowskia21256d2021-07-02 00:40:55 -0700806 mapFds.push_back(unique_fd());
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -0800807 continue;
808 }
809
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700810 if (kvers < md[i].min_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700811 ALOGI("skipping map %s which requires kernel version 0x%x >= 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700812 mapNames[i].c_str(), kvers, md[i].min_kver);
813 mapFds.push_back(unique_fd());
814 continue;
815 }
816
817 if (kvers >= md[i].max_kver) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700818 ALOGI("skipping map %s which requires kernel version 0x%x < 0x%x",
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700819 mapNames[i].c_str(), kvers, md[i].max_kver);
820 mapFds.push_back(unique_fd());
821 continue;
822 }
823
Ryan Zukliece89f502022-12-15 16:14:32 -0800824 if ((md[i].ignore_on_eng && isEng()) || (md[i].ignore_on_user && isUser()) ||
825 (md[i].ignore_on_userdebug && isUserdebug())) {
826 ALOGI("skipping map %s which is ignored on %s builds", mapNames[i].c_str(),
827 getBuildType().c_str());
828 mapFds.push_back(unique_fd());
829 continue;
830 }
831
Maciej Żenczykowski8d2e7d92023-05-19 21:06:00 +0000832 if ((isArm() && isKernel32Bit() && md[i].ignore_on_arm32) ||
833 (isArm() && isKernel64Bit() && md[i].ignore_on_aarch64) ||
834 (isX86() && isKernel32Bit() && md[i].ignore_on_x86_32) ||
835 (isX86() && isKernel64Bit() && md[i].ignore_on_x86_64) ||
836 (isRiscV() && md[i].ignore_on_riscv64)) {
837 ALOGI("skipping map %s which is ignored on %s", mapNames[i].c_str(),
838 describeArch());
839 mapFds.push_back(unique_fd());
840 continue;
841 }
842
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700843 enum bpf_map_type type = md[i].type;
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700844 if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
845 // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
846 // of be approximated: HASH has the same userspace visible api.
847 // However it cannot be used by ebpf programs in the same way.
848 // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
849 // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
850 // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
851 // programs as being 5.4+...
852 type = BPF_MAP_TYPE_HASH;
853 }
854
Maciej Żenczykowski28f01bb2023-06-20 19:40:22 +0000855 // The .h file enforces that this is a power of two, and page size will
856 // also always be a power of two, so this logic is actually enough to
857 // force it to be a multiple of the page size, as required by the kernel.
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000858 unsigned int max_entries = md[i].max_entries;
859 if (type == BPF_MAP_TYPE_RINGBUF) {
860 if (max_entries < page_size) max_entries = page_size;
861 }
862
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700863 domain selinux_context = getDomainFromSelinuxContext(md[i].selinux_context);
864 if (specified(selinux_context)) {
865 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
866 ALOGE("map %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
867 mapNames[i].c_str(), selinux_context, allowedDomainBitmask);
868 return -EINVAL;
869 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700870 ALOGI("map %s selinux_context [%-32s] -> %d -> '%s' (%s)", mapNames[i].c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700871 md[i].selinux_context, selinux_context, lookupSelinuxContext(selinux_context),
872 lookupPinSubdir(selinux_context));
873 }
874
875 domain pin_subdir = getDomainFromPinSubdir(md[i].pin_subdir);
876 if (unrecognized(pin_subdir)) return -ENOTDIR;
877 if (specified(pin_subdir)) {
878 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
879 ALOGE("map %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)",
880 mapNames[i].c_str(), pin_subdir, allowedDomainBitmask);
881 return -EINVAL;
882 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -0700883 ALOGI("map %s pin_subdir [%-32s] -> %d -> '%s'", mapNames[i].c_str(), md[i].pin_subdir,
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700884 pin_subdir, lookupPinSubdir(pin_subdir));
885 }
886
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700887 // Format of pin location is /sys/fs/bpf/<pin_subdir|prefix>map_<objName>_<mapName>
888 // except that maps shared across .o's have empty <objName>
889 // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700890 string mapPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "map_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700891 (md[i].shared ? "" : objName) + "_" + mapNames[i];
Maciej Żenczykowski36c53ba2021-07-05 15:20:34 -0700892 bool reuse = false;
893 unique_fd fd;
894 int saved_errno;
895
Joel Fernandesd76a2002018-10-16 13:19:58 -0700896 if (access(mapPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskieb199dd2022-07-01 03:21:40 -0700897 fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800898 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700899 ALOGD("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700900 reuse = true;
901 } else {
Connor O'Brien35425e52022-01-18 21:41:16 -0800902 struct bpf_create_map_attr attr = {
903 .name = mapNames[i].c_str(),
904 .map_type = type,
905 .map_flags = md[i].map_flags,
906 .key_size = md[i].key_size,
907 .value_size = md[i].value_size,
Maciej Żenczykowski8a117a32023-06-16 08:18:49 +0000908 .max_entries = max_entries,
Connor O'Brien35425e52022-01-18 21:41:16 -0800909 };
910 if (btfFd.has_value() && btfTypeIdMap.find(mapNames[i]) != btfTypeIdMap.end()) {
911 attr.btf_fd = btfFd->get();
912 attr.btf_key_type_id = btfTypeIdMap.at(mapNames[i]).first;
913 attr.btf_value_type_id = btfTypeIdMap.at(mapNames[i]).second;
914 }
915 fd.reset(bcc_create_map_xattr(&attr, true));
Maciej Żenczykowski2c372132021-03-01 23:09:54 -0800916 saved_errno = errno;
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700917 ALOGD("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700918 }
919
Maciej Żenczykowski12bb5202022-06-16 15:50:58 -0700920 if (!fd.ok()) return -saved_errno;
921
922 // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
923 // safety (since reuse code path is rare) run these checks even if we just created it.
924 // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
925 if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
Joel Fernandesd76a2002018-10-16 13:19:58 -0700926
927 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700928 if (specified(selinux_context)) {
929 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -0700930 "tmp_map_" + objName + "_" + mapNames[i];
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700931 ret = bpf_obj_pin(fd, createLoc.c_str());
932 if (ret) {
933 int err = errno;
934 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
935 return -err;
936 }
Maciej Żenczykowskie15229f2023-04-17 07:16:33 +0000937 ret = renameat2(AT_FDCWD, createLoc.c_str(),
938 AT_FDCWD, mapPinLoc.c_str(), RENAME_NOREPLACE);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700939 if (ret) {
940 int err = errno;
941 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), mapPinLoc.c_str(), ret,
942 err, strerror(err));
943 return -err;
944 }
945 } else {
946 ret = bpf_obj_pin(fd, mapPinLoc.c_str());
Maciej Żenczykowskid8259aa2022-06-27 10:02:20 -0700947 if (ret) {
948 int err = errno;
949 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
950 return -err;
951 }
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700952 }
Maciej Żenczykowski83f29772020-01-27 03:11:51 -0800953 ret = chmod(mapPinLoc.c_str(), md[i].mode);
Maciej Żenczykowski41817132022-06-03 08:41:04 -0700954 if (ret) {
955 int err = errno;
956 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
957 strerror(err));
958 return -err;
959 }
Maciej Żenczykowski5e4aabf2022-06-27 01:15:53 -0700960 ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
961 if (ret) {
962 int err = errno;
963 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
964 ret, err, strerror(err));
965 return -err;
966 }
Joel Fernandesd76a2002018-10-16 13:19:58 -0700967 }
968
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700969 struct bpf_map_info map_info = {};
970 __u32 map_info_len = sizeof(map_info);
971 int rv = bpf_obj_get_info_by_fd(fd, &map_info, &map_info_len);
972 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700973 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700974 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700975 ALOGI("map %s id %d", mapPinLoc.c_str(), map_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -0700976 }
977
Connor O'Brien8d49fc72019-10-24 18:23:49 -0700978 mapFds.push_back(std::move(fd));
Joel Fernandesd76a2002018-10-16 13:19:58 -0700979 }
980
981 return ret;
982}
983
984/* For debugging, dump all instructions */
985static void dumpIns(char* ins, int size) {
986 for (int row = 0; row < size / 8; row++) {
987 ALOGE("%d: ", row);
988 for (int j = 0; j < 8; j++) {
989 ALOGE("%3x ", ins[(row * 8) + j]);
990 }
991 ALOGE("\n");
992 }
993}
994
995/* For debugging, dump all code sections from cs list */
996static void dumpAllCs(vector<codeSection>& cs) {
997 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -0700998 ALOGE("Dumping cs %d, name %s", int(i), cs[i].name.c_str());
Joel Fernandesd76a2002018-10-16 13:19:58 -0700999 dumpIns((char*)cs[i].data.data(), cs[i].data.size());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001000 ALOGE("-----------");
Joel Fernandesd76a2002018-10-16 13:19:58 -07001001 }
1002}
1003
1004static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
1005 int insnIndex;
1006 struct bpf_insn *insn, *insns;
1007
1008 insns = (struct bpf_insn*)(insnsPtr);
1009
1010 insnIndex = offset / sizeof(struct bpf_insn);
1011 insn = &insns[insnIndex];
1012
Maciej Żenczykowski509b1b92023-03-07 01:11:20 +00001013 // Occasionally might be useful for relocation debugging, but pretty spammy
1014 if (0) {
1015 ALOGD("applying relo to instruction at byte offset: %llu, "
1016 "insn offset %d, insn %llx",
1017 (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
1018 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001019
1020 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001021 ALOGE("Dumping all instructions till ins %d", insnIndex);
1022 ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001023 dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
1024 return;
1025 }
1026
1027 insn->imm = fd;
1028 insn->src_reg = BPF_PSEUDO_MAP_FD;
1029}
1030
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001031static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
Joel Fernandesd76a2002018-10-16 13:19:58 -07001032 vector<string> mapNames;
1033
Connor O'Brien3278a162020-02-13 21:45:22 -08001034 int ret = getSectionSymNames(elfFile, "maps", mapNames);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001035 if (ret) return;
1036
1037 for (int k = 0; k != (int)cs.size(); k++) {
1038 Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
1039 int n_rel = cs[k].rel_data.size() / sizeof(*rel);
1040
1041 for (int i = 0; i < n_rel; i++) {
1042 int symIndex = ELF64_R_SYM(rel[i].r_info);
1043 string symName;
1044
1045 ret = getSymNameByIdx(elfFile, symIndex, symName);
1046 if (ret) return;
1047
1048 /* Find the map fd and apply relo */
1049 for (int j = 0; j < (int)mapNames.size(); j++) {
1050 if (!mapNames[j].compare(symName)) {
1051 applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
1052 break;
1053 }
1054 }
1055 }
1056 }
1057}
1058
Maciej Żenczykowskid8a45782021-01-14 23:36:32 -08001059static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001060 const char* prefix, const unsigned long long allowedDomainBitmask) {
Maciej Żenczykowski07375e22020-02-19 14:23:59 -08001061 unsigned kvers = kernelVersion();
1062 int ret, fd;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001063
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001064 if (!kvers) {
1065 ALOGE("unable to get kernel version");
1066 return -EINVAL;
1067 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001068
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001069 string objName = pathToObjName(string(elfPath));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001070
1071 for (int i = 0; i < (int)cs.size(); i++) {
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001072 string name = cs[i].name;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001073
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001074 if (!cs[i].prog_def.has_value()) {
1075 ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
1076 return -EINVAL;
Maciej Żenczykowski07375e22020-02-19 14:23:59 -08001077 }
1078
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001079 unsigned min_kver = cs[i].prog_def->min_kver;
1080 unsigned max_kver = cs[i].prog_def->max_kver;
1081 ALOGD("cs[%d].name:%s min_kver:%x .max_kver:%x (kvers:%x)", i, name.c_str(), min_kver,
1082 max_kver, kvers);
1083 if (kvers < min_kver) continue;
1084 if (kvers >= max_kver) continue;
1085
1086 unsigned bpfMinVer = cs[i].prog_def->bpfloader_min_ver;
1087 unsigned bpfMaxVer = cs[i].prog_def->bpfloader_max_ver;
1088 domain selinux_context = getDomainFromSelinuxContext(cs[i].prog_def->selinux_context);
1089 domain pin_subdir = getDomainFromPinSubdir(cs[i].prog_def->pin_subdir);
1090 // Note: make sure to only check for unrecognized *after* verifying bpfloader
1091 // version limits include this bpfloader's version.
1092
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001093 ALOGD("cs[%d].name:%s requires bpfloader version [0x%05x,0x%05x)", i, name.c_str(),
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001094 bpfMinVer, bpfMaxVer);
1095 if (BPFLOADER_VERSION < bpfMinVer) continue;
1096 if (BPFLOADER_VERSION >= bpfMaxVer) continue;
Ryan Zukliece89f502022-12-15 16:14:32 -08001097
1098 if ((cs[i].prog_def->ignore_on_eng && isEng()) ||
1099 (cs[i].prog_def->ignore_on_user && isUser()) ||
1100 (cs[i].prog_def->ignore_on_userdebug && isUserdebug())) {
1101 ALOGD("cs[%d].name:%s is ignored on %s builds", i, name.c_str(),
1102 getBuildType().c_str());
Ryan Zuklie0fb433a2023-01-05 14:22:15 -08001103 continue;
Ryan Zukliece89f502022-12-15 16:14:32 -08001104 }
1105
Maciej Żenczykowski8d2e7d92023-05-19 21:06:00 +00001106 if ((isArm() && isKernel32Bit() && cs[i].prog_def->ignore_on_arm32) ||
1107 (isArm() && isKernel64Bit() && cs[i].prog_def->ignore_on_aarch64) ||
1108 (isX86() && isKernel32Bit() && cs[i].prog_def->ignore_on_x86_32) ||
1109 (isX86() && isKernel64Bit() && cs[i].prog_def->ignore_on_x86_64) ||
1110 (isRiscV() && cs[i].prog_def->ignore_on_riscv64)) {
1111 ALOGD("cs[%d].name:%s is ignored on %s", i, name.c_str(), describeArch());
1112 continue;
1113 }
1114
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001115 if (unrecognized(pin_subdir)) return -ENOTDIR;
1116
1117 if (specified(selinux_context)) {
1118 if (!inDomainBitmask(selinux_context, allowedDomainBitmask)) {
1119 ALOGE("prog %s has invalid selinux_context of %d (allowed bitmask 0x%llx)",
1120 name.c_str(), selinux_context, allowedDomainBitmask);
1121 return -EINVAL;
1122 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001123 ALOGI("prog %s selinux_context [%-32s] -> %d -> '%s' (%s)", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001124 cs[i].prog_def->selinux_context, selinux_context,
1125 lookupSelinuxContext(selinux_context), lookupPinSubdir(selinux_context));
1126 }
1127
1128 if (specified(pin_subdir)) {
1129 if (!inDomainBitmask(pin_subdir, allowedDomainBitmask)) {
1130 ALOGE("prog %s has invalid pin_subdir of %d (allowed bitmask 0x%llx)", name.c_str(),
1131 pin_subdir, allowedDomainBitmask);
1132 return -EINVAL;
1133 }
Maciej Żenczykowski99668462022-07-02 16:58:01 -07001134 ALOGI("prog %s pin_subdir [%-32s] -> %d -> '%s'", name.c_str(),
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001135 cs[i].prog_def->pin_subdir, pin_subdir, lookupPinSubdir(pin_subdir));
1136 }
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001137
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001138 // strip any potential $foo suffix
1139 // this can be used to provide duplicate programs
1140 // conditionally loaded based on running kernel version
Maciej Żenczykowski428843d2020-04-23 12:43:44 -07001141 name = name.substr(0, name.find_last_of('$'));
Maciej Żenczykowski681f6042020-04-21 15:34:18 -07001142
1143 bool reuse = false;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001144 // Format of pin location is
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001145 // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001146 string progPinLoc = string(BPF_FS_PATH) + lookupPinSubdir(pin_subdir, prefix) + "prog_" +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001147 objName + '_' + string(name);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001148 if (access(progPinLoc.c_str(), F_OK) == 0) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001149 fd = retrieveProgram(progPinLoc.c_str());
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001150 ALOGD("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd,
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001151 (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001152 reuse = true;
1153 } else {
1154 vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
1155
Tyler Wear4e2f4602022-02-03 09:46:01 -08001156 struct bpf_load_program_attr attr = {
1157 .prog_type = cs[i].type,
1158 .name = name.c_str(),
1159 .insns = (struct bpf_insn*)cs[i].data.data(),
1160 .license = license.c_str(),
1161 .log_level = 0,
1162 .expected_attach_type = cs[i].expected_attach_type,
1163 };
1164
1165 fd = bcc_prog_load_xattr(&attr, cs[i].data.size(), log_buf.data(), log_buf.size(),
1166 true);
1167
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001168 ALOGD("bpf_prog_load lib call for %s (%s) returned fd: %d (%s)", elfPath,
Steven Moreland804bca02019-12-12 17:21:23 -08001169 cs[i].name.c_str(), fd, (fd < 0 ? std::strerror(errno) : "no error"));
Joel Fernandesd76a2002018-10-16 13:19:58 -07001170
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001171 if (fd < 0) {
Maciej Żenczykowskif7c0d992021-01-21 16:01:04 -08001172 vector<string> lines = android::base::Split(log_buf.data(), "\n");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001173
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001174 ALOGW("bpf_prog_load - BEGIN log_buf contents:");
1175 for (const auto& line : lines) ALOGW("%s", line.c_str());
1176 ALOGW("bpf_prog_load - END log_buf contents.");
1177
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001178 if (cs[i].prog_def->optional) {
Maciej Żenczykowskiaa295c82020-06-16 17:02:48 -07001179 ALOGW("failed program is marked optional - continuing...");
1180 continue;
1181 }
1182 ALOGE("non-optional program failed to load.");
Maciej Żenczykowski524deef2020-02-11 11:12:37 -08001183 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001184 }
1185
1186 if (fd < 0) return fd;
1187 if (fd == 0) return -EINVAL;
1188
1189 if (!reuse) {
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001190 if (specified(selinux_context)) {
1191 string createLoc = string(BPF_FS_PATH) + lookupPinSubdir(selinux_context) +
Maciej Żenczykowski21869ef2022-07-07 06:01:57 -07001192 "tmp_prog_" + objName + '_' + string(name);
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001193 ret = bpf_obj_pin(fd, createLoc.c_str());
1194 if (ret) {
1195 int err = errno;
1196 ALOGE("create %s -> %d [%d:%s]", createLoc.c_str(), ret, err, strerror(err));
1197 return -err;
1198 }
Maciej Żenczykowskie15229f2023-04-17 07:16:33 +00001199 ret = renameat2(AT_FDCWD, createLoc.c_str(),
1200 AT_FDCWD, progPinLoc.c_str(), RENAME_NOREPLACE);
Maciej Żenczykowski41817132022-06-03 08:41:04 -07001201 if (ret) {
1202 int err = errno;
1203 ALOGE("rename %s %s -> %d [%d:%s]", createLoc.c_str(), progPinLoc.c_str(), ret,
1204 err, strerror(err));
1205 return -err;
1206 }
1207 } else {
1208 ret = bpf_obj_pin(fd, progPinLoc.c_str());
1209 if (ret) {
1210 int err = errno;
1211 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
1212 return -err;
1213 }
1214 }
1215 if (chmod(progPinLoc.c_str(), 0440)) {
1216 int err = errno;
1217 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
1218 return -err;
1219 }
Maciej Żenczykowski5c791652022-08-03 23:49:08 +00001220 if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
1221 (gid_t)cs[i].prog_def->gid)) {
1222 int err = errno;
1223 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
1224 cs[i].prog_def->gid, err, strerror(err));
1225 return -err;
Connor O'Brien3278a162020-02-13 21:45:22 -08001226 }
Joel Fernandesd76a2002018-10-16 13:19:58 -07001227 }
1228
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001229 struct bpf_prog_info prog_info = {};
1230 __u32 prog_info_len = sizeof(prog_info);
1231 int rv = bpf_obj_get_info_by_fd(fd, &prog_info, &prog_info_len);
1232 if (rv) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001233 ALOGE("bpf_obj_get_info_by_fd failed, ret: %d [%d]", rv, errno);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001234 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001235 ALOGI("prog %s id %d", progPinLoc.c_str(), prog_info.id);
Maciej Żenczykowski57412c22022-05-20 16:44:06 -07001236 }
1237
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001238 cs[i].prog_fd.reset(fd);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001239 }
1240
1241 return 0;
1242}
1243
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001244int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
Joel Fernandesd76a2002018-10-16 13:19:58 -07001245 vector<char> license;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001246 vector<char> critical;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001247 vector<codeSection> cs;
Connor O'Brien8d49fc72019-10-24 18:23:49 -07001248 vector<unique_fd> mapFds;
Joel Fernandesd76a2002018-10-16 13:19:58 -07001249 int ret;
1250
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001251 if (!isCritical) return -1;
1252 *isCritical = false;
1253
Joel Fernandesd76a2002018-10-16 13:19:58 -07001254 ifstream elfFile(elfPath, ios::in | ios::binary);
1255 if (!elfFile.is_open()) return -1;
1256
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001257 ret = readSectionByName("critical", elfFile, critical);
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001258 *isCritical = !ret;
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001259
Joel Fernandesd76a2002018-10-16 13:19:58 -07001260 ret = readSectionByName("license", elfFile, license);
1261 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001262 ALOGE("Couldn't find license in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001263 return ret;
1264 } else {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001265 ALOGD("Loading %s%s ELF object %s with license %s",
Maciej Żenczykowski89515d92020-06-14 19:27:33 -07001266 *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
Maciej Żenczykowski4ba8c1c2020-06-10 15:49:31 -07001267 elfPath, (char*)license.data());
Joel Fernandesd76a2002018-10-16 13:19:58 -07001268 }
1269
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001270 // the following default values are for bpfloader V0.0 format which does not include them
1271 unsigned int bpfLoaderMinVer =
1272 readSectionUint("bpfloader_min_ver", elfFile, DEFAULT_BPFLOADER_MIN_VER);
1273 unsigned int bpfLoaderMaxVer =
1274 readSectionUint("bpfloader_max_ver", elfFile, DEFAULT_BPFLOADER_MAX_VER);
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001275 unsigned int bpfLoaderMinRequiredVer =
1276 readSectionUint("bpfloader_min_required_ver", elfFile, 0);
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001277 size_t sizeOfBpfMapDef =
1278 readSectionUint("size_of_bpf_map_def", elfFile, DEFAULT_SIZEOF_BPF_MAP_DEF);
1279 size_t sizeOfBpfProgDef =
1280 readSectionUint("size_of_bpf_prog_def", elfFile, DEFAULT_SIZEOF_BPF_PROG_DEF);
1281
1282 // inclusive lower bound check
1283 if (BPFLOADER_VERSION < bpfLoaderMinVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001284 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with min ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001285 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer);
1286 return 0;
1287 }
1288
1289 // exclusive upper bound check
1290 if (BPFLOADER_VERSION >= bpfLoaderMaxVer) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001291 ALOGI("BpfLoader version 0x%05x ignoring ELF object %s with max ver 0x%05x",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001292 BPFLOADER_VERSION, elfPath, bpfLoaderMaxVer);
1293 return 0;
1294 }
1295
Maciej Żenczykowskib57290a2022-07-02 15:47:07 -07001296 if (BPFLOADER_VERSION < bpfLoaderMinRequiredVer) {
1297 ALOGI("BpfLoader version 0x%05x failing due to ELF object %s with required min ver 0x%05x",
1298 BPFLOADER_VERSION, elfPath, bpfLoaderMinRequiredVer);
1299 return -1;
1300 }
1301
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001302 ALOGI("BpfLoader version 0x%05x processing ELF object %s with ver [0x%05x,0x%05x)",
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001303 BPFLOADER_VERSION, elfPath, bpfLoaderMinVer, bpfLoaderMaxVer);
1304
1305 if (sizeOfBpfMapDef < DEFAULT_SIZEOF_BPF_MAP_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001306 ALOGE("sizeof(bpf_map_def) of %zu is too small (< %d)", sizeOfBpfMapDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001307 DEFAULT_SIZEOF_BPF_MAP_DEF);
1308 return -1;
1309 }
1310
1311 if (sizeOfBpfProgDef < DEFAULT_SIZEOF_BPF_PROG_DEF) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001312 ALOGE("sizeof(bpf_prog_def) of %zu is too small (< %d)", sizeOfBpfProgDef,
Maciej Żenczykowski9217eee2021-03-03 05:28:52 -08001313 DEFAULT_SIZEOF_BPF_PROG_DEF);
1314 return -1;
1315 }
1316
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001317 ret = readCodeSections(elfFile, cs, sizeOfBpfProgDef, location.allowedProgTypes,
1318 location.allowedProgTypesLength);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001319 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001320 ALOGE("Couldn't read all code sections in %s", elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001321 return ret;
1322 }
1323
1324 /* Just for future debugging */
1325 if (0) dumpAllCs(cs);
1326
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001327 ret = createMaps(elfPath, elfFile, mapFds, location.prefix, location.allowedDomainBitmask,
1328 sizeOfBpfMapDef);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001329 if (ret) {
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001330 ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001331 return ret;
1332 }
1333
1334 for (int i = 0; i < (int)mapFds.size(); i++)
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001335 ALOGD("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001336
1337 applyMapRelo(elfFile, mapFds, cs);
1338
Connor O'Brien6c0ce9f2022-12-01 20:08:17 -08001339 ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix,
1340 location.allowedDomainBitmask);
Maciej Żenczykowskie626a952022-06-17 02:35:36 -07001341 if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
Joel Fernandesd76a2002018-10-16 13:19:58 -07001342
1343 return ret;
1344}
1345
Joel Fernandesd76a2002018-10-16 13:19:58 -07001346} // namespace bpf
1347} // namespace android