Loader.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. /*
  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. #define LOG_TAG "LibBpfLoader"
  17. #include <errno.h>
  18. #include <linux/bpf.h>
  19. #include <linux/elf.h>
  20. #include <log/log.h>
  21. #include <stdint.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <sys/utsname.h>
  26. #include <unistd.h>
  27. #include "LoaderUtils.h"
  28. #include "include/libbpf_android.h"
  29. #include <cstdlib>
  30. #include <fstream>
  31. #include <iostream>
  32. #include <string>
  33. #include <vector>
  34. #include <android-base/strings.h>
  35. #define BPF_FS_PATH "/sys/fs/bpf/"
  36. // Size of the BPF log buffer for verifier logging
  37. #define BPF_LOAD_LOG_SZ 0x1ffff
  38. using android::base::StartsWith;
  39. using std::ifstream;
  40. using std::ios;
  41. using std::string;
  42. using std::vector;
  43. namespace android {
  44. namespace bpf {
  45. typedef struct {
  46. const char* name;
  47. enum bpf_prog_type type;
  48. } sectionType;
  49. /*
  50. * Map section name prefixes to program types, the section name will be:
  51. * SEC(<prefix>/<name-of-program>)
  52. * For example:
  53. * SEC("tracepoint/sched_switch_func") where sched_switch_funcs
  54. * is the name of the program, and tracepoint is the type.
  55. */
  56. sectionType sectionNameTypes[] = {
  57. {"kprobe", BPF_PROG_TYPE_KPROBE},
  58. {"tracepoint", BPF_PROG_TYPE_TRACEPOINT},
  59. {"skfilter", BPF_PROG_TYPE_SOCKET_FILTER},
  60. {"cgroupskb", BPF_PROG_TYPE_CGROUP_SKB},
  61. {"schedcls", BPF_PROG_TYPE_SCHED_CLS},
  62. {"cgroupsock", BPF_PROG_TYPE_CGROUP_SOCK},
  63. /* End of table */
  64. {"END", BPF_PROG_TYPE_UNSPEC},
  65. };
  66. typedef struct {
  67. enum bpf_prog_type type;
  68. string name;
  69. vector<char> data;
  70. vector<char> rel_data;
  71. int prog_fd; /* fd after loading */
  72. } codeSection;
  73. /* Common with the eBPF C program */
  74. struct bpf_map_def {
  75. enum bpf_map_type type;
  76. unsigned int key_size;
  77. unsigned int value_size;
  78. unsigned int max_entries;
  79. unsigned int map_flags;
  80. unsigned int inner_map_idx;
  81. unsigned int numa_node;
  82. };
  83. static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
  84. elfFile.seekg(0);
  85. if (elfFile.fail()) return -1;
  86. if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
  87. return 0;
  88. }
  89. /* Reads all section header tables into an Shdr array */
  90. static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
  91. Elf64_Ehdr eh;
  92. int ret = 0;
  93. ret = readElfHeader(elfFile, &eh);
  94. if (ret) return ret;
  95. elfFile.seekg(eh.e_shoff);
  96. if (elfFile.fail()) return -1;
  97. /* Read shdr table entries */
  98. shTable.resize(eh.e_shnum);
  99. if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
  100. return 0;
  101. }
  102. /* Read a section by its index - for ex to get sec hdr strtab blob */
  103. static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
  104. vector<Elf64_Shdr> shTable;
  105. int entries, ret = 0;
  106. ret = readSectionHeadersAll(elfFile, shTable);
  107. if (ret) return ret;
  108. entries = shTable.size();
  109. elfFile.seekg(shTable[id].sh_offset);
  110. if (elfFile.fail()) return -1;
  111. sec.resize(shTable[id].sh_size);
  112. if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
  113. return 0;
  114. }
  115. /* Read whole section header string table */
  116. static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
  117. Elf64_Ehdr eh;
  118. int ret = 0;
  119. ret = readElfHeader(elfFile, &eh);
  120. if (ret) return ret;
  121. ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
  122. if (ret) return ret;
  123. return 0;
  124. }
  125. /* Get name from offset in strtab */
  126. static int getSymName(ifstream& elfFile, int nameOff, string& name) {
  127. int ret;
  128. vector<char> secStrTab;
  129. ret = readSectionHeaderStrtab(elfFile, secStrTab);
  130. if (ret) return ret;
  131. if (nameOff >= (int)secStrTab.size()) return -1;
  132. name = string((char*)secStrTab.data() + nameOff);
  133. return 0;
  134. }
  135. /* Reads a full section by name - example to get the GPL license */
  136. static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
  137. vector<char> secStrTab;
  138. vector<Elf64_Shdr> shTable;
  139. int ret;
  140. ret = readSectionHeadersAll(elfFile, shTable);
  141. if (ret) return ret;
  142. ret = readSectionHeaderStrtab(elfFile, secStrTab);
  143. if (ret) return ret;
  144. for (int i = 0; i < (int)shTable.size(); i++) {
  145. char* secname = secStrTab.data() + shTable[i].sh_name;
  146. if (!secname) continue;
  147. if (!strcmp(secname, name)) {
  148. vector<char> dataTmp;
  149. dataTmp.resize(shTable[i].sh_size);
  150. elfFile.seekg(shTable[i].sh_offset);
  151. if (elfFile.fail()) return -1;
  152. if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
  153. data = dataTmp;
  154. return 0;
  155. }
  156. }
  157. return -2;
  158. }
  159. static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
  160. int ret;
  161. vector<Elf64_Shdr> shTable;
  162. ret = readSectionHeadersAll(elfFile, shTable);
  163. if (ret) return ret;
  164. for (int i = 0; i < (int)shTable.size(); i++) {
  165. if ((int)shTable[i].sh_type != type) continue;
  166. vector<char> dataTmp;
  167. dataTmp.resize(shTable[i].sh_size);
  168. elfFile.seekg(shTable[i].sh_offset);
  169. if (elfFile.fail()) return -1;
  170. if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
  171. data = dataTmp;
  172. return 0;
  173. }
  174. return -2;
  175. }
  176. static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
  177. return (a.st_value < b.st_value);
  178. }
  179. static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
  180. int ret, numElems;
  181. Elf64_Sym* buf;
  182. vector<char> secData;
  183. ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
  184. if (ret) return ret;
  185. buf = (Elf64_Sym*)secData.data();
  186. numElems = (secData.size() / sizeof(Elf64_Sym));
  187. data.assign(buf, buf + numElems);
  188. if (sort) std::sort(data.begin(), data.end(), symCompare);
  189. return 0;
  190. }
  191. static enum bpf_prog_type getSectionType(string& name) {
  192. for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++)
  193. if (StartsWith(name, sectionNameTypes[i].name)) return sectionNameTypes[i].type;
  194. return BPF_PROG_TYPE_UNSPEC;
  195. }
  196. /* If ever needed
  197. static string getSectionName(enum bpf_prog_type type)
  198. {
  199. for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++)
  200. if (sectionNameTypes[i].type == type)
  201. return std::string(sectionNameTypes[i].name);
  202. return NULL;
  203. }
  204. */
  205. static bool isRelSection(codeSection& cs, string& name) {
  206. for (int i = 0; sectionNameTypes[i].type != BPF_PROG_TYPE_UNSPEC; i++) {
  207. sectionType st = sectionNameTypes[i];
  208. if (st.type != cs.type) continue;
  209. if (StartsWith(name, std::string(".rel") + st.name + "/"))
  210. return true;
  211. else
  212. return false;
  213. }
  214. return false;
  215. }
  216. /* Read a section by its index - for ex to get sec hdr strtab blob */
  217. static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs) {
  218. vector<Elf64_Shdr> shTable;
  219. int entries, ret = 0;
  220. ret = readSectionHeadersAll(elfFile, shTable);
  221. if (ret) return ret;
  222. entries = shTable.size();
  223. for (int i = 0; i < entries; i++) {
  224. string name;
  225. codeSection cs_temp;
  226. cs_temp.type = BPF_PROG_TYPE_UNSPEC;
  227. ret = getSymName(elfFile, shTable[i].sh_name, name);
  228. if (ret) return ret;
  229. enum bpf_prog_type ptype = getSectionType(name);
  230. if (ptype != BPF_PROG_TYPE_UNSPEC) {
  231. deslash(name);
  232. cs_temp.type = ptype;
  233. cs_temp.name = name;
  234. ret = readSectionByIdx(elfFile, i, cs_temp.data);
  235. if (ret) return ret;
  236. ALOGD("Loaded code section %d (%s)\n", i, name.c_str());
  237. }
  238. /* Check for rel section */
  239. if (cs_temp.data.size() > 0 && i < entries) {
  240. ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
  241. if (ret) return ret;
  242. if (isRelSection(cs_temp, name)) {
  243. ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
  244. if (ret) return ret;
  245. ALOGD("Loaded relo section %d (%s)\n", i, name.c_str());
  246. }
  247. }
  248. if (cs_temp.data.size() > 0) {
  249. cs.push_back(cs_temp);
  250. ALOGD("Adding section %d to cs list\n", i);
  251. }
  252. }
  253. return 0;
  254. }
  255. static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
  256. vector<Elf64_Sym> symtab;
  257. int ret = 0;
  258. ret = readSymTab(elfFile, 0 /* !sort */, symtab);
  259. if (ret) return ret;
  260. if (index >= (int)symtab.size()) return -1;
  261. return getSymName(elfFile, symtab[index].st_name, name);
  262. }
  263. static int getMapNames(ifstream& elfFile, vector<string>& names) {
  264. int ret;
  265. string mapName;
  266. vector<Elf64_Sym> symtab;
  267. vector<Elf64_Shdr> shTable;
  268. ret = readSymTab(elfFile, 1 /* sort */, symtab);
  269. if (ret) return ret;
  270. /* Get index of maps section */
  271. ret = readSectionHeadersAll(elfFile, shTable);
  272. if (ret) return ret;
  273. int maps_idx = -1;
  274. for (int i = 0; i < (int)shTable.size(); i++) {
  275. ret = getSymName(elfFile, shTable[i].sh_name, mapName);
  276. if (ret) return ret;
  277. if (!mapName.compare("maps")) {
  278. maps_idx = i;
  279. break;
  280. }
  281. }
  282. /* No maps found */
  283. if (maps_idx == -1) {
  284. ALOGE("No maps could be found in elf object\n");
  285. return -1;
  286. }
  287. for (int i = 0; i < (int)symtab.size(); i++) {
  288. if (symtab[i].st_shndx == maps_idx) {
  289. string s;
  290. ret = getSymName(elfFile, symtab[i].st_name, s);
  291. if (ret) return ret;
  292. names.push_back(s);
  293. }
  294. }
  295. return 0;
  296. }
  297. static int createMaps(const char* elfPath, ifstream& elfFile, vector<int>& mapFds) {
  298. int ret, fd;
  299. vector<char> mdData;
  300. vector<struct bpf_map_def> md;
  301. vector<string> mapNames;
  302. string fname = pathToFilename(string(elfPath), true);
  303. ret = readSectionByName("maps", elfFile, mdData);
  304. if (ret) return ret;
  305. md.resize(mdData.size() / sizeof(struct bpf_map_def));
  306. memcpy(md.data(), mdData.data(), mdData.size());
  307. ret = getMapNames(elfFile, mapNames);
  308. if (ret) return ret;
  309. mapFds.resize(mapNames.size());
  310. for (int i = 0; i < (int)mapNames.size(); i++) {
  311. // Format of pin location is /sys/fs/bpf/map_<filename>_<mapname>
  312. string mapPinLoc;
  313. bool reuse = false;
  314. mapPinLoc = string(BPF_FS_PATH) + "map_" + fname + "_" + string(mapNames[i]);
  315. if (access(mapPinLoc.c_str(), F_OK) == 0) {
  316. fd = bpf_obj_get(mapPinLoc.c_str());
  317. ALOGD("bpf_create_map reusing map %s, ret: %d\n", mapNames[i].c_str(), fd);
  318. reuse = true;
  319. } else {
  320. fd = bpf_create_map(md[i].type, mapNames[i].c_str(), md[i].key_size, md[i].value_size,
  321. md[i].max_entries, md[i].map_flags);
  322. ALOGD("bpf_create_map name %s, ret: %d\n", mapNames[i].c_str(), fd);
  323. }
  324. if (fd < 0) return fd;
  325. if (fd == 0) return -EINVAL;
  326. if (!reuse) {
  327. ret = bpf_obj_pin(fd, mapPinLoc.c_str());
  328. if (ret < 0) return ret;
  329. }
  330. mapFds[i] = fd;
  331. }
  332. return ret;
  333. }
  334. /* For debugging, dump all instructions */
  335. static void dumpIns(char* ins, int size) {
  336. for (int row = 0; row < size / 8; row++) {
  337. ALOGE("%d: ", row);
  338. for (int j = 0; j < 8; j++) {
  339. ALOGE("%3x ", ins[(row * 8) + j]);
  340. }
  341. ALOGE("\n");
  342. }
  343. }
  344. /* For debugging, dump all code sections from cs list */
  345. static void dumpAllCs(vector<codeSection>& cs) {
  346. for (int i = 0; i < (int)cs.size(); i++) {
  347. ALOGE("Dumping cs %d, name %s\n", int(i), cs[i].name.c_str());
  348. dumpIns((char*)cs[i].data.data(), cs[i].data.size());
  349. ALOGE("-----------\n");
  350. }
  351. }
  352. static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
  353. int insnIndex;
  354. struct bpf_insn *insn, *insns;
  355. insns = (struct bpf_insn*)(insnsPtr);
  356. insnIndex = offset / sizeof(struct bpf_insn);
  357. insn = &insns[insnIndex];
  358. ALOGD(
  359. "applying relo to instruction at byte offset: %d, \
  360. insn offset %d , insn %lx\n",
  361. (int)offset, (int)insnIndex, *(unsigned long*)insn);
  362. if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
  363. ALOGE("Dumping all instructions till ins %d\n", insnIndex);
  364. ALOGE("invalid relo for insn %d: code 0x%x\n", insnIndex, insn->code);
  365. dumpIns((char*)insnsPtr, (insnIndex + 3) * 8);
  366. return;
  367. }
  368. insn->imm = fd;
  369. insn->src_reg = BPF_PSEUDO_MAP_FD;
  370. }
  371. static void applyMapRelo(ifstream& elfFile, vector<int> mapFds, vector<codeSection>& cs) {
  372. vector<string> mapNames;
  373. int ret = getMapNames(elfFile, mapNames);
  374. if (ret) return;
  375. for (int k = 0; k != (int)cs.size(); k++) {
  376. Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
  377. int n_rel = cs[k].rel_data.size() / sizeof(*rel);
  378. for (int i = 0; i < n_rel; i++) {
  379. int symIndex = ELF64_R_SYM(rel[i].r_info);
  380. string symName;
  381. ret = getSymNameByIdx(elfFile, symIndex, symName);
  382. if (ret) return;
  383. /* Find the map fd and apply relo */
  384. for (int j = 0; j < (int)mapNames.size(); j++) {
  385. if (!mapNames[j].compare(symName)) {
  386. applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
  387. break;
  388. }
  389. }
  390. }
  391. }
  392. }
  393. static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license) {
  394. int ret, fd, kvers;
  395. if ((kvers = getMachineKvers()) < 0) return -1;
  396. string fname = pathToFilename(string(elfPath), true);
  397. for (int i = 0; i < (int)cs.size(); i++) {
  398. string progPinLoc;
  399. bool reuse = false;
  400. // Format of pin location is
  401. // /sys/fs/bpf/prog_<filename>_<mapname>
  402. progPinLoc = string(BPF_FS_PATH) + "prog_" + fname + "_" + cs[i].name;
  403. if (access(progPinLoc.c_str(), F_OK) == 0) {
  404. fd = bpf_obj_get(progPinLoc.c_str());
  405. ALOGD("New bpf prog load reusing prog %s, ret: %d\n", cs[i].name.c_str(), fd);
  406. reuse = true;
  407. } else {
  408. vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
  409. fd = bpf_prog_load(cs[i].type, cs[i].name.c_str(), (struct bpf_insn*)cs[i].data.data(),
  410. cs[i].data.size(), license.c_str(), kvers, 0,
  411. log_buf.data(), log_buf.size());
  412. ALOGD("New bpf core prog_load for %s (%s) returned: %d\n", elfPath, cs[i].name.c_str(),
  413. fd);
  414. if (fd <= 0)
  415. ALOGE("bpf_prog_load: log_buf contents: %s\n", (char *)log_buf.data());
  416. }
  417. if (fd < 0) return fd;
  418. if (fd == 0) return -EINVAL;
  419. if (!reuse) {
  420. ret = bpf_obj_pin(fd, progPinLoc.c_str());
  421. if (ret < 0) return ret;
  422. }
  423. cs[i].prog_fd = fd;
  424. }
  425. return 0;
  426. }
  427. int loadProg(const char* elfPath) {
  428. vector<char> license;
  429. vector<codeSection> cs;
  430. vector<int> mapFds;
  431. int ret;
  432. ifstream elfFile(elfPath, ios::in | ios::binary);
  433. if (!elfFile.is_open()) return -1;
  434. ret = readSectionByName("license", elfFile, license);
  435. if (ret) {
  436. ALOGE("Couldn't find license in %s\n", elfPath);
  437. return ret;
  438. } else {
  439. ALOGD("Loading ELF object %s with license %s\n", elfPath, (char*)license.data());
  440. }
  441. ret = readCodeSections(elfFile, cs);
  442. if (ret) {
  443. ALOGE("Couldn't read all code sections in %s\n", elfPath);
  444. return ret;
  445. }
  446. /* Just for future debugging */
  447. if (0) dumpAllCs(cs);
  448. ret = createMaps(elfPath, elfFile, mapFds);
  449. if (ret) {
  450. ALOGE("Failed to create maps: (ret=%d) in %s\n", ret, elfPath);
  451. return ret;
  452. }
  453. for (int i = 0; i < (int)mapFds.size(); i++)
  454. ALOGD("map_fd found at %d is %d in %s\n", i, mapFds[i], elfPath);
  455. applyMapRelo(elfFile, mapFds, cs);
  456. ret = loadCodeSections(elfPath, cs, string(license.data()));
  457. if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d\n", ret);
  458. return ret;
  459. }
  460. } // namespace bpf
  461. } // namespace android