1 /* 2 * Copyright (C) 2017 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 #ifndef LOG_TAG 18 #define LOG_TAG "bpfloader" 19 #endif 20 21 #include <arpa/inet.h> 22 #include <dirent.h> 23 #include <elf.h> 24 #include <error.h> 25 #include <fcntl.h> 26 #include <inttypes.h> 27 #include <linux/bpf.h> 28 #include <linux/unistd.h> 29 #include <net/if.h> 30 #include <stdint.h> 31 #include <stdio.h> 32 #include <stdlib.h> 33 #include <string.h> 34 #include <unistd.h> 35 36 #include <sys/mman.h> 37 #include <sys/socket.h> 38 #include <sys/stat.h> 39 #include <sys/types.h> 40 41 #include <android-base/properties.h> 42 #include <android-base/stringprintf.h> 43 #include <android-base/strings.h> 44 #include <android-base/unique_fd.h> 45 #include <libbpf_android.h> 46 #include <log/log.h> 47 #include <netdutils/Misc.h> 48 #include <netdutils/Slice.h> 49 #include "bpf/BpfUtils.h" 50 51 using android::base::EndsWith; 52 using android::base::unique_fd; 53 using std::string; 54 55 #define BPF_PROG_PATH "/system/etc/bpf/" 56 57 #define CLEANANDEXIT(ret, mapPatterns) \ 58 do { \ 59 for (size_t i = 0; i < mapPatterns.size(); i++) { \ 60 if (mapPatterns[i].fd > -1) { \ 61 close(mapPatterns[i].fd); \ 62 } \ 63 } \ 64 return ret; \ 65 } while (0) 66 67 using android::bpf::BpfMapInfo; 68 using android::bpf::BpfProgInfo; 69 70 void loadAllElfObjects(void) { 71 DIR* dir; 72 struct dirent* ent; 73 74 if ((dir = opendir(BPF_PROG_PATH)) != NULL) { 75 while ((ent = readdir(dir)) != NULL) { 76 string s = ent->d_name; 77 if (!EndsWith(s, ".o")) continue; 78 79 string progPath = BPF_PROG_PATH + s; 80 81 int ret = android::bpf::loadProg(progPath.c_str()); 82 ALOGI("Attempted load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret)); 83 } 84 closedir(dir); 85 } 86 } 87 88 int main() { 89 std::string value = android::base::GetProperty("bpf.progs_loaded", ""); 90 if (value == "1") { 91 ALOGI("Property bpf.progs_loaded is set, progs already loaded.\n"); 92 return 0; 93 } 94 95 if (android::bpf::getBpfSupportLevel() != android::bpf::BpfLevel::NONE) { 96 // Load all ELF objects, create programs and maps, and pin them 97 loadAllElfObjects(); 98 } 99 100 if (android::base::SetProperty("bpf.progs_loaded", "1") == false) { 101 ALOGE("Failed to set bpf.progs_loaded property\n"); 102 return 1; 103 } 104 105 return 0; 106 } 107