main.c 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  1. // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
  2. /*
  3. * resolve_btfids scans ELF object for .BTF_ids section and resolves
  4. * its symbols with BTF ID values.
  5. *
  6. * Each symbol points to 4 bytes data and is expected to have
  7. * following name syntax:
  8. *
  9. * __BTF_ID__<type>__<symbol>[__<id>]
  10. *
  11. * type is:
  12. *
  13. * func - lookup BTF_KIND_FUNC symbol with <symbol> name
  14. * and store its ID into the data:
  15. *
  16. * __BTF_ID__func__vfs_close__1:
  17. * .zero 4
  18. *
  19. * struct - lookup BTF_KIND_STRUCT symbol with <symbol> name
  20. * and store its ID into the data:
  21. *
  22. * __BTF_ID__struct__sk_buff__1:
  23. * .zero 4
  24. *
  25. * union - lookup BTF_KIND_UNION symbol with <symbol> name
  26. * and store its ID into the data:
  27. *
  28. * __BTF_ID__union__thread_union__1:
  29. * .zero 4
  30. *
  31. * typedef - lookup BTF_KIND_TYPEDEF symbol with <symbol> name
  32. * and store its ID into the data:
  33. *
  34. * __BTF_ID__typedef__pid_t__1:
  35. * .zero 4
  36. *
  37. * set - store symbol size into first 4 bytes and sort following
  38. * ID list
  39. *
  40. * __BTF_ID__set__list:
  41. * .zero 4
  42. * list:
  43. * __BTF_ID__func__vfs_getattr__3:
  44. * .zero 4
  45. * __BTF_ID__func__vfs_fallocate__4:
  46. * .zero 4
  47. *
  48. * set8 - store symbol size into first 4 bytes and sort following
  49. * ID list
  50. *
  51. * __BTF_ID__set8__list:
  52. * .zero 8
  53. * list:
  54. * __BTF_ID__func__vfs_getattr__3:
  55. * .zero 4
  56. * .word (1 << 0) | (1 << 2)
  57. * __BTF_ID__func__vfs_fallocate__5:
  58. * .zero 4
  59. * .word (1 << 3) | (1 << 1) | (1 << 2)
  60. */
  61. #define _GNU_SOURCE
  62. #include <stdio.h>
  63. #include <string.h>
  64. #include <unistd.h>
  65. #include <stdlib.h>
  66. #include <libelf.h>
  67. #include <gelf.h>
  68. #include <sys/stat.h>
  69. #include <fcntl.h>
  70. #include <errno.h>
  71. #include <linux/btf_ids.h>
  72. #include <linux/kallsyms.h>
  73. #include <linux/rbtree.h>
  74. #include <linux/zalloc.h>
  75. #include <linux/err.h>
  76. #include <linux/limits.h>
  77. #include <bpf/btf.h>
  78. #include <bpf/libbpf.h>
  79. #include <subcmd/parse-options.h>
  80. #define BTF_IDS_SECTION ".BTF_ids"
  81. #define BTF_ID_PREFIX "__BTF_ID__"
  82. #define BTF_STRUCT "struct"
  83. #define BTF_UNION "union"
  84. #define BTF_TYPEDEF "typedef"
  85. #define BTF_FUNC "func"
  86. #define BTF_SET "set"
  87. #define BTF_SET8 "set8"
  88. #define ADDR_CNT 100
  89. #if __BYTE_ORDER == __LITTLE_ENDIAN
  90. # define ELFDATANATIVE ELFDATA2LSB
  91. #elif __BYTE_ORDER == __BIG_ENDIAN
  92. # define ELFDATANATIVE ELFDATA2MSB
  93. #else
  94. # error "Unknown machine endianness!"
  95. #endif
  96. enum btf_id_kind {
  97. BTF_ID_KIND_NONE,
  98. BTF_ID_KIND_SYM,
  99. BTF_ID_KIND_SET,
  100. BTF_ID_KIND_SET8
  101. };
  102. struct btf_id {
  103. struct rb_node rb_node;
  104. char *name;
  105. union {
  106. int id;
  107. int cnt;
  108. };
  109. enum btf_id_kind kind;
  110. int addr_cnt;
  111. Elf64_Addr addr[ADDR_CNT];
  112. };
  113. struct object {
  114. const char *path;
  115. const char *btf_path;
  116. const char *base_btf_path;
  117. struct btf *btf;
  118. struct btf *base_btf;
  119. bool distill_base;
  120. struct {
  121. int fd;
  122. Elf *elf;
  123. Elf_Data *symbols;
  124. Elf_Data *idlist;
  125. int symbols_shndx;
  126. int idlist_shndx;
  127. size_t strtabidx;
  128. unsigned long idlist_addr;
  129. int encoding;
  130. } efile;
  131. struct rb_root sets;
  132. struct rb_root structs;
  133. struct rb_root unions;
  134. struct rb_root typedefs;
  135. struct rb_root funcs;
  136. int nr_funcs;
  137. int nr_structs;
  138. int nr_unions;
  139. int nr_typedefs;
  140. };
  141. #define KF_IMPLICIT_ARGS (1 << 16)
  142. #define KF_IMPL_SUFFIX "_impl"
  143. struct kfunc {
  144. const char *name;
  145. u32 btf_id;
  146. u32 flags;
  147. };
  148. struct btf2btf_context {
  149. struct btf *btf;
  150. u32 *decl_tags;
  151. u32 nr_decl_tags;
  152. u32 max_decl_tags;
  153. struct kfunc *kfuncs;
  154. u32 nr_kfuncs;
  155. u32 max_kfuncs;
  156. };
  157. static int verbose;
  158. static int warnings;
  159. static int eprintf(int level, int var, const char *fmt, ...)
  160. {
  161. va_list args;
  162. int ret = 0;
  163. if (var >= level) {
  164. va_start(args, fmt);
  165. ret = vfprintf(stderr, fmt, args);
  166. va_end(args);
  167. }
  168. return ret;
  169. }
  170. #ifndef pr_fmt
  171. #define pr_fmt(fmt) fmt
  172. #endif
  173. #define pr_debug(fmt, ...) \
  174. eprintf(1, verbose, pr_fmt(fmt), ##__VA_ARGS__)
  175. #define pr_debugN(n, fmt, ...) \
  176. eprintf(n, verbose, pr_fmt(fmt), ##__VA_ARGS__)
  177. #define pr_debug2(fmt, ...) pr_debugN(2, pr_fmt(fmt), ##__VA_ARGS__)
  178. #define pr_err(fmt, ...) \
  179. eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__)
  180. #define pr_info(fmt, ...) \
  181. eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__)
  182. static bool is_btf_id(const char *name)
  183. {
  184. return name && !strncmp(name, BTF_ID_PREFIX, sizeof(BTF_ID_PREFIX) - 1);
  185. }
  186. static struct btf_id *btf_id__find(struct rb_root *root, const char *name)
  187. {
  188. struct rb_node *p = root->rb_node;
  189. struct btf_id *id;
  190. int cmp;
  191. while (p) {
  192. id = rb_entry(p, struct btf_id, rb_node);
  193. cmp = strcmp(id->name, name);
  194. if (cmp < 0)
  195. p = p->rb_left;
  196. else if (cmp > 0)
  197. p = p->rb_right;
  198. else
  199. return id;
  200. }
  201. return NULL;
  202. }
  203. static struct btf_id *__btf_id__add(struct rb_root *root,
  204. const char *name,
  205. enum btf_id_kind kind,
  206. bool unique)
  207. {
  208. struct rb_node **p = &root->rb_node;
  209. struct rb_node *parent = NULL;
  210. struct btf_id *id;
  211. int cmp;
  212. while (*p != NULL) {
  213. parent = *p;
  214. id = rb_entry(parent, struct btf_id, rb_node);
  215. cmp = strcmp(id->name, name);
  216. if (cmp < 0)
  217. p = &(*p)->rb_left;
  218. else if (cmp > 0)
  219. p = &(*p)->rb_right;
  220. else
  221. return unique ? NULL : id;
  222. }
  223. id = zalloc(sizeof(*id));
  224. if (id) {
  225. pr_debug("adding symbol %s\n", name);
  226. id->name = strdup(name);
  227. if (!id->name) {
  228. free(id);
  229. return NULL;
  230. }
  231. id->kind = kind;
  232. rb_link_node(&id->rb_node, parent, p);
  233. rb_insert_color(&id->rb_node, root);
  234. }
  235. return id;
  236. }
  237. static inline struct btf_id *btf_id__add(struct rb_root *root,
  238. const char *name,
  239. enum btf_id_kind kind)
  240. {
  241. return __btf_id__add(root, name, kind, false);
  242. }
  243. static inline struct btf_id *btf_id__add_unique(struct rb_root *root,
  244. const char *name,
  245. enum btf_id_kind kind)
  246. {
  247. return __btf_id__add(root, name, kind, true);
  248. }
  249. static int get_id(const char *prefix_end, char *buf, size_t buf_sz)
  250. {
  251. /*
  252. * __BTF_ID__func__vfs_truncate__0
  253. * prefix_end = ^
  254. * pos = ^
  255. */
  256. int len = strlen(prefix_end);
  257. int pos = sizeof("__") - 1;
  258. char *p;
  259. if (pos >= len)
  260. return -1;
  261. if (len - pos >= buf_sz)
  262. return -1;
  263. strcpy(buf, prefix_end + pos);
  264. /*
  265. * __BTF_ID__func__vfs_truncate__0
  266. * buf = ^
  267. *
  268. * cut the unique id part
  269. */
  270. p = strrchr(buf, '_');
  271. p--;
  272. if (*p != '_')
  273. return -1;
  274. *p = '\0';
  275. return 0;
  276. }
  277. static struct btf_id *add_set(struct object *obj, char *name, enum btf_id_kind kind)
  278. {
  279. int len = strlen(name);
  280. int prefixlen;
  281. char *id;
  282. /*
  283. * __BTF_ID__set__name
  284. * name = ^
  285. * id = ^
  286. */
  287. switch (kind) {
  288. case BTF_ID_KIND_SET:
  289. prefixlen = sizeof(BTF_SET "__") - 1;
  290. break;
  291. case BTF_ID_KIND_SET8:
  292. prefixlen = sizeof(BTF_SET8 "__") - 1;
  293. break;
  294. default:
  295. pr_err("Unexpected kind %d passed to %s() for symbol %s\n", kind, __func__, name);
  296. return NULL;
  297. }
  298. id = name + prefixlen;
  299. if (id >= name + len) {
  300. pr_err("FAILED to parse set name: %s\n", name);
  301. return NULL;
  302. }
  303. return btf_id__add_unique(&obj->sets, id, kind);
  304. }
  305. static struct btf_id *add_symbol(struct rb_root *root, char *name, size_t size)
  306. {
  307. char id[KSYM_NAME_LEN];
  308. if (get_id(name + size, id, sizeof(id))) {
  309. pr_err("FAILED to parse symbol name: %s\n", name);
  310. return NULL;
  311. }
  312. return btf_id__add(root, id, BTF_ID_KIND_SYM);
  313. }
  314. static void btf_id__free_all(struct rb_root *root)
  315. {
  316. struct rb_node *next;
  317. struct btf_id *id;
  318. next = rb_first(root);
  319. while (next) {
  320. id = rb_entry(next, struct btf_id, rb_node);
  321. next = rb_next(&id->rb_node);
  322. rb_erase(&id->rb_node, root);
  323. free(id->name);
  324. free(id);
  325. }
  326. }
  327. static void bswap_32_data(void *data, u32 nr_bytes)
  328. {
  329. u32 cnt, i;
  330. u32 *ptr;
  331. cnt = nr_bytes / sizeof(u32);
  332. ptr = data;
  333. for (i = 0; i < cnt; i++)
  334. ptr[i] = bswap_32(ptr[i]);
  335. }
  336. static int elf_collect(struct object *obj)
  337. {
  338. Elf_Scn *scn = NULL;
  339. size_t shdrstrndx;
  340. GElf_Ehdr ehdr;
  341. int idx = 0;
  342. Elf *elf;
  343. int fd;
  344. fd = open(obj->path, O_RDWR, 0666);
  345. if (fd == -1) {
  346. pr_err("FAILED cannot open %s: %s\n",
  347. obj->path, strerror(errno));
  348. return -1;
  349. }
  350. elf_version(EV_CURRENT);
  351. elf = elf_begin(fd, ELF_C_READ_MMAP_PRIVATE, NULL);
  352. if (!elf) {
  353. close(fd);
  354. pr_err("FAILED cannot create ELF descriptor: %s\n",
  355. elf_errmsg(-1));
  356. return -1;
  357. }
  358. obj->efile.fd = fd;
  359. obj->efile.elf = elf;
  360. elf_flagelf(elf, ELF_C_SET, ELF_F_LAYOUT);
  361. if (elf_getshdrstrndx(elf, &shdrstrndx) != 0) {
  362. pr_err("FAILED cannot get shdr str ndx\n");
  363. return -1;
  364. }
  365. if (gelf_getehdr(obj->efile.elf, &ehdr) == NULL) {
  366. pr_err("FAILED cannot get ELF header: %s\n",
  367. elf_errmsg(-1));
  368. return -1;
  369. }
  370. obj->efile.encoding = ehdr.e_ident[EI_DATA];
  371. /*
  372. * Scan all the elf sections and look for save data
  373. * from .BTF_ids section and symbols.
  374. */
  375. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  376. Elf_Data *data;
  377. GElf_Shdr sh;
  378. char *name;
  379. idx++;
  380. if (gelf_getshdr(scn, &sh) != &sh) {
  381. pr_err("FAILED get section(%d) header\n", idx);
  382. return -1;
  383. }
  384. name = elf_strptr(elf, shdrstrndx, sh.sh_name);
  385. if (!name) {
  386. pr_err("FAILED get section(%d) name\n", idx);
  387. return -1;
  388. }
  389. data = elf_getdata(scn, 0);
  390. if (!data) {
  391. pr_err("FAILED to get section(%d) data from %s\n",
  392. idx, name);
  393. return -1;
  394. }
  395. pr_debug2("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
  396. idx, name, (unsigned long) data->d_size,
  397. (int) sh.sh_link, (unsigned long) sh.sh_flags,
  398. (int) sh.sh_type);
  399. if (sh.sh_type == SHT_SYMTAB) {
  400. obj->efile.symbols = data;
  401. obj->efile.symbols_shndx = idx;
  402. obj->efile.strtabidx = sh.sh_link;
  403. } else if (!strcmp(name, BTF_IDS_SECTION)) {
  404. /*
  405. * If target endianness differs from host, we need to bswap32
  406. * the .BTF_ids section data on load, because .BTF_ids has
  407. * Elf_Type = ELF_T_BYTE, and so libelf returns data buffer in
  408. * the target endianness. We repeat this on dump.
  409. */
  410. if (obj->efile.encoding != ELFDATANATIVE) {
  411. pr_debug("bswap_32 .BTF_ids data from target to host endianness\n");
  412. bswap_32_data(data->d_buf, data->d_size);
  413. }
  414. obj->efile.idlist = data;
  415. obj->efile.idlist_shndx = idx;
  416. obj->efile.idlist_addr = sh.sh_addr;
  417. }
  418. }
  419. return 0;
  420. }
  421. static int symbols_collect(struct object *obj)
  422. {
  423. Elf_Scn *scn = NULL;
  424. int n, i;
  425. GElf_Shdr sh;
  426. char *name;
  427. scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
  428. if (!scn)
  429. return -1;
  430. if (gelf_getshdr(scn, &sh) != &sh)
  431. return -1;
  432. n = sh.sh_size / sh.sh_entsize;
  433. /*
  434. * Scan symbols and look for the ones starting with
  435. * __BTF_ID__* over .BTF_ids section.
  436. */
  437. for (i = 0; i < n; i++) {
  438. char *prefix;
  439. struct btf_id *id;
  440. GElf_Sym sym;
  441. if (!gelf_getsym(obj->efile.symbols, i, &sym))
  442. return -1;
  443. if (sym.st_shndx != obj->efile.idlist_shndx)
  444. continue;
  445. name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
  446. sym.st_name);
  447. if (!is_btf_id(name))
  448. continue;
  449. /*
  450. * __BTF_ID__TYPE__vfs_truncate__0
  451. * prefix = ^
  452. */
  453. prefix = name + sizeof(BTF_ID_PREFIX) - 1;
  454. /* struct */
  455. if (!strncmp(prefix, BTF_STRUCT, sizeof(BTF_STRUCT) - 1)) {
  456. obj->nr_structs++;
  457. id = add_symbol(&obj->structs, prefix, sizeof(BTF_STRUCT) - 1);
  458. /* union */
  459. } else if (!strncmp(prefix, BTF_UNION, sizeof(BTF_UNION) - 1)) {
  460. obj->nr_unions++;
  461. id = add_symbol(&obj->unions, prefix, sizeof(BTF_UNION) - 1);
  462. /* typedef */
  463. } else if (!strncmp(prefix, BTF_TYPEDEF, sizeof(BTF_TYPEDEF) - 1)) {
  464. obj->nr_typedefs++;
  465. id = add_symbol(&obj->typedefs, prefix, sizeof(BTF_TYPEDEF) - 1);
  466. /* func */
  467. } else if (!strncmp(prefix, BTF_FUNC, sizeof(BTF_FUNC) - 1)) {
  468. obj->nr_funcs++;
  469. id = add_symbol(&obj->funcs, prefix, sizeof(BTF_FUNC) - 1);
  470. /* set8 */
  471. } else if (!strncmp(prefix, BTF_SET8, sizeof(BTF_SET8) - 1)) {
  472. id = add_set(obj, prefix, BTF_ID_KIND_SET8);
  473. /*
  474. * SET8 objects store list's count, which is encoded
  475. * in symbol's size, together with 'cnt' field hence
  476. * that - 1.
  477. */
  478. if (id)
  479. id->cnt = sym.st_size / sizeof(uint64_t) - 1;
  480. /* set */
  481. } else if (!strncmp(prefix, BTF_SET, sizeof(BTF_SET) - 1)) {
  482. id = add_set(obj, prefix, BTF_ID_KIND_SET);
  483. /*
  484. * SET objects store list's count, which is encoded
  485. * in symbol's size, together with 'cnt' field hence
  486. * that - 1.
  487. */
  488. if (id)
  489. id->cnt = sym.st_size / sizeof(int) - 1;
  490. } else {
  491. pr_err("FAILED unsupported prefix %s\n", prefix);
  492. return -1;
  493. }
  494. if (!id)
  495. return -EINVAL;
  496. if (id->addr_cnt >= ADDR_CNT) {
  497. pr_err("FAILED symbol %s crossed the number of allowed lists\n",
  498. id->name);
  499. return -1;
  500. }
  501. id->addr[id->addr_cnt++] = sym.st_value;
  502. }
  503. return 0;
  504. }
  505. static int load_btf(struct object *obj)
  506. {
  507. struct btf *base_btf = NULL, *btf = NULL;
  508. int err;
  509. if (obj->base_btf_path) {
  510. base_btf = btf__parse(obj->base_btf_path, NULL);
  511. err = libbpf_get_error(base_btf);
  512. if (err) {
  513. pr_err("FAILED: load base BTF from %s: %s\n",
  514. obj->base_btf_path, strerror(-err));
  515. goto out_err;
  516. }
  517. }
  518. btf = btf__parse_split(obj->btf_path ?: obj->path, base_btf);
  519. err = libbpf_get_error(btf);
  520. if (err) {
  521. pr_err("FAILED: load BTF from %s: %s\n",
  522. obj->btf_path ?: obj->path, strerror(-err));
  523. goto out_err;
  524. }
  525. obj->base_btf = base_btf;
  526. obj->btf = btf;
  527. return 0;
  528. out_err:
  529. btf__free(base_btf);
  530. btf__free(btf);
  531. obj->base_btf = NULL;
  532. obj->btf = NULL;
  533. return err;
  534. }
  535. static int symbols_resolve(struct object *obj)
  536. {
  537. int nr_typedefs = obj->nr_typedefs;
  538. int nr_structs = obj->nr_structs;
  539. int nr_unions = obj->nr_unions;
  540. int nr_funcs = obj->nr_funcs;
  541. struct btf *btf = obj->btf;
  542. int err, type_id;
  543. __u32 nr_types;
  544. err = -1;
  545. nr_types = btf__type_cnt(btf);
  546. /*
  547. * Iterate all the BTF types and search for collected symbol IDs.
  548. */
  549. for (type_id = 1; type_id < nr_types; type_id++) {
  550. const struct btf_type *type;
  551. struct rb_root *root;
  552. struct btf_id *id;
  553. const char *str;
  554. int *nr;
  555. type = btf__type_by_id(btf, type_id);
  556. if (!type) {
  557. pr_err("FAILED: malformed BTF, can't resolve type for ID %d\n",
  558. type_id);
  559. goto out;
  560. }
  561. if (btf_is_func(type) && nr_funcs) {
  562. nr = &nr_funcs;
  563. root = &obj->funcs;
  564. } else if (btf_is_struct(type) && nr_structs) {
  565. nr = &nr_structs;
  566. root = &obj->structs;
  567. } else if (btf_is_union(type) && nr_unions) {
  568. nr = &nr_unions;
  569. root = &obj->unions;
  570. } else if (btf_is_typedef(type) && nr_typedefs) {
  571. nr = &nr_typedefs;
  572. root = &obj->typedefs;
  573. } else
  574. continue;
  575. str = btf__name_by_offset(btf, type->name_off);
  576. if (!str) {
  577. pr_err("FAILED: malformed BTF, can't resolve name for ID %d\n",
  578. type_id);
  579. goto out;
  580. }
  581. id = btf_id__find(root, str);
  582. if (id) {
  583. if (id->id) {
  584. pr_info("WARN: multiple IDs found for '%s': %d, %d - using %d\n",
  585. str, id->id, type_id, id->id);
  586. warnings++;
  587. } else {
  588. id->id = type_id;
  589. (*nr)--;
  590. }
  591. }
  592. }
  593. err = 0;
  594. out:
  595. return err;
  596. }
  597. static int id_patch(struct object *obj, struct btf_id *id)
  598. {
  599. Elf_Data *data = obj->efile.idlist;
  600. int *ptr = data->d_buf;
  601. int i;
  602. /* For set, set8, id->id may be 0 */
  603. if (!id->id && id->kind != BTF_ID_KIND_SET && id->kind != BTF_ID_KIND_SET8) {
  604. pr_err("WARN: resolve_btfids: unresolved symbol %s\n", id->name);
  605. warnings++;
  606. }
  607. for (i = 0; i < id->addr_cnt; i++) {
  608. unsigned long addr = id->addr[i];
  609. unsigned long idx = addr - obj->efile.idlist_addr;
  610. pr_debug("patching addr %5lu: ID %7d [%s]\n",
  611. idx, id->id, id->name);
  612. if (idx >= data->d_size) {
  613. pr_err("FAILED patching index %lu out of bounds %lu\n",
  614. idx, data->d_size);
  615. return -1;
  616. }
  617. idx = idx / sizeof(int);
  618. ptr[idx] = id->id;
  619. }
  620. return 0;
  621. }
  622. static int __symbols_patch(struct object *obj, struct rb_root *root)
  623. {
  624. struct rb_node *next;
  625. struct btf_id *id;
  626. next = rb_first(root);
  627. while (next) {
  628. id = rb_entry(next, struct btf_id, rb_node);
  629. if (id_patch(obj, id))
  630. return -1;
  631. next = rb_next(next);
  632. }
  633. return 0;
  634. }
  635. static int cmp_id(const void *pa, const void *pb)
  636. {
  637. const int *a = pa, *b = pb;
  638. return *a - *b;
  639. }
  640. static int sets_patch(struct object *obj)
  641. {
  642. Elf_Data *data = obj->efile.idlist;
  643. struct rb_node *next;
  644. int cnt;
  645. next = rb_first(&obj->sets);
  646. while (next) {
  647. struct btf_id_set8 *set8 = NULL;
  648. struct btf_id_set *set = NULL;
  649. unsigned long addr, off;
  650. struct btf_id *id;
  651. id = rb_entry(next, struct btf_id, rb_node);
  652. addr = id->addr[0];
  653. off = addr - obj->efile.idlist_addr;
  654. /* sets are unique */
  655. if (id->addr_cnt != 1) {
  656. pr_err("FAILED malformed data for set '%s'\n",
  657. id->name);
  658. return -1;
  659. }
  660. switch (id->kind) {
  661. case BTF_ID_KIND_SET:
  662. set = data->d_buf + off;
  663. cnt = set->cnt;
  664. qsort(set->ids, set->cnt, sizeof(set->ids[0]), cmp_id);
  665. break;
  666. case BTF_ID_KIND_SET8:
  667. set8 = data->d_buf + off;
  668. cnt = set8->cnt;
  669. /*
  670. * Make sure id is at the beginning of the pairs
  671. * struct, otherwise the below qsort would not work.
  672. */
  673. BUILD_BUG_ON((u32 *)set8->pairs != &set8->pairs[0].id);
  674. qsort(set8->pairs, set8->cnt, sizeof(set8->pairs[0]), cmp_id);
  675. break;
  676. default:
  677. pr_err("Unexpected btf_id_kind %d for set '%s'\n", id->kind, id->name);
  678. return -1;
  679. }
  680. pr_debug("sorting addr %5lu: cnt %6d [%s]\n", off, cnt, id->name);
  681. next = rb_next(next);
  682. }
  683. return 0;
  684. }
  685. static int symbols_patch(struct object *obj)
  686. {
  687. if (__symbols_patch(obj, &obj->structs) ||
  688. __symbols_patch(obj, &obj->unions) ||
  689. __symbols_patch(obj, &obj->typedefs) ||
  690. __symbols_patch(obj, &obj->funcs) ||
  691. __symbols_patch(obj, &obj->sets))
  692. return -1;
  693. if (sets_patch(obj))
  694. return -1;
  695. return 0;
  696. }
  697. static int dump_raw_data(const char *out_path, const void *data, u32 size)
  698. {
  699. size_t written;
  700. FILE *file;
  701. file = fopen(out_path, "wb");
  702. if (!file) {
  703. pr_err("Couldn't open %s for writing\n", out_path);
  704. return -1;
  705. }
  706. written = fwrite(data, 1, size, file);
  707. if (written != size) {
  708. pr_err("Failed to write data to %s\n", out_path);
  709. fclose(file);
  710. unlink(out_path);
  711. return -1;
  712. }
  713. fclose(file);
  714. pr_debug("Dumped %lu bytes of data to %s\n", size, out_path);
  715. return 0;
  716. }
  717. static int dump_raw_btf_ids(struct object *obj, const char *out_path)
  718. {
  719. Elf_Data *data = obj->efile.idlist;
  720. int err;
  721. if (!data || !data->d_buf) {
  722. pr_debug("%s has no BTF_ids data to dump\n", obj->path);
  723. return 0;
  724. }
  725. /*
  726. * If target endianness differs from host, we need to bswap32 the
  727. * .BTF_ids section data before dumping so that the output is in
  728. * target endianness.
  729. */
  730. if (obj->efile.encoding != ELFDATANATIVE) {
  731. pr_debug("bswap_32 .BTF_ids data from host to target endianness\n");
  732. bswap_32_data(data->d_buf, data->d_size);
  733. }
  734. err = dump_raw_data(out_path, data->d_buf, data->d_size);
  735. if (err)
  736. return -1;
  737. return 0;
  738. }
  739. static int dump_raw_btf(struct btf *btf, const char *out_path)
  740. {
  741. const void *raw_btf_data;
  742. u32 raw_btf_size;
  743. int err;
  744. raw_btf_data = btf__raw_data(btf, &raw_btf_size);
  745. if (!raw_btf_data) {
  746. pr_err("btf__raw_data() failed\n");
  747. return -1;
  748. }
  749. err = dump_raw_data(out_path, raw_btf_data, raw_btf_size);
  750. if (err)
  751. return -1;
  752. return 0;
  753. }
  754. static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf, s32 type_id)
  755. {
  756. const struct btf_type *t = btf__type_by_id(btf, type_id);
  757. while (btf_is_mod(t))
  758. t = btf__type_by_id(btf, t->type);
  759. return t;
  760. }
  761. static int push_decl_tag_id(struct btf2btf_context *ctx, u32 decl_tag_id)
  762. {
  763. u32 *arr = ctx->decl_tags;
  764. u32 cap = ctx->max_decl_tags;
  765. if (ctx->nr_decl_tags + 1 > cap) {
  766. cap = max(cap + 256, cap * 2);
  767. arr = realloc(arr, sizeof(u32) * cap);
  768. if (!arr)
  769. return -ENOMEM;
  770. ctx->max_decl_tags = cap;
  771. ctx->decl_tags = arr;
  772. }
  773. ctx->decl_tags[ctx->nr_decl_tags++] = decl_tag_id;
  774. return 0;
  775. }
  776. static int push_kfunc(struct btf2btf_context *ctx, struct kfunc *kfunc)
  777. {
  778. struct kfunc *arr = ctx->kfuncs;
  779. u32 cap = ctx->max_kfuncs;
  780. if (ctx->nr_kfuncs + 1 > cap) {
  781. cap = max(cap + 256, cap * 2);
  782. arr = realloc(arr, sizeof(struct kfunc) * cap);
  783. if (!arr)
  784. return -ENOMEM;
  785. ctx->max_kfuncs = cap;
  786. ctx->kfuncs = arr;
  787. }
  788. ctx->kfuncs[ctx->nr_kfuncs++] = *kfunc;
  789. return 0;
  790. }
  791. static int collect_decl_tags(struct btf2btf_context *ctx)
  792. {
  793. const u32 type_cnt = btf__type_cnt(ctx->btf);
  794. struct btf *btf = ctx->btf;
  795. const struct btf_type *t;
  796. int err;
  797. for (u32 id = 1; id < type_cnt; id++) {
  798. t = btf__type_by_id(btf, id);
  799. if (!btf_is_decl_tag(t))
  800. continue;
  801. err = push_decl_tag_id(ctx, id);
  802. if (err)
  803. return err;
  804. }
  805. return 0;
  806. }
  807. /*
  808. * To find the kfunc flags having its struct btf_id (with ELF addresses)
  809. * we need to find the address that is in range of a set8.
  810. * If a set8 is found, then the flags are located at addr + 4 bytes.
  811. * Return 0 (no flags!) if not found.
  812. */
  813. static u32 find_kfunc_flags(struct object *obj, struct btf_id *kfunc_id)
  814. {
  815. const u32 *elf_data_ptr = obj->efile.idlist->d_buf;
  816. u64 set_lower_addr, set_upper_addr, addr;
  817. struct btf_id *set_id;
  818. struct rb_node *next;
  819. u32 flags;
  820. u64 idx;
  821. for (next = rb_first(&obj->sets); next; next = rb_next(next)) {
  822. set_id = rb_entry(next, struct btf_id, rb_node);
  823. if (set_id->kind != BTF_ID_KIND_SET8 || set_id->addr_cnt != 1)
  824. continue;
  825. set_lower_addr = set_id->addr[0];
  826. set_upper_addr = set_lower_addr + set_id->cnt * sizeof(u64);
  827. for (u32 i = 0; i < kfunc_id->addr_cnt; i++) {
  828. addr = kfunc_id->addr[i];
  829. /*
  830. * Lower bound is exclusive to skip the 8-byte header of the set.
  831. * Upper bound is inclusive to capture the last entry at offset 8*cnt.
  832. */
  833. if (set_lower_addr < addr && addr <= set_upper_addr) {
  834. pr_debug("found kfunc %s in BTF_ID_FLAGS %s\n",
  835. kfunc_id->name, set_id->name);
  836. idx = addr - obj->efile.idlist_addr;
  837. idx = idx / sizeof(u32) + 1;
  838. flags = elf_data_ptr[idx];
  839. return flags;
  840. }
  841. }
  842. }
  843. return 0;
  844. }
  845. static int collect_kfuncs(struct object *obj, struct btf2btf_context *ctx)
  846. {
  847. const char *tag_name, *func_name;
  848. struct btf *btf = ctx->btf;
  849. const struct btf_type *t;
  850. u32 flags, func_id;
  851. struct kfunc kfunc;
  852. struct btf_id *id;
  853. int err;
  854. if (ctx->nr_decl_tags == 0)
  855. return 0;
  856. for (u32 i = 0; i < ctx->nr_decl_tags; i++) {
  857. t = btf__type_by_id(btf, ctx->decl_tags[i]);
  858. if (btf_kflag(t) || btf_decl_tag(t)->component_idx != -1)
  859. continue;
  860. tag_name = btf__name_by_offset(btf, t->name_off);
  861. if (strcmp(tag_name, "bpf_kfunc") != 0)
  862. continue;
  863. func_id = t->type;
  864. t = btf__type_by_id(btf, func_id);
  865. if (!btf_is_func(t))
  866. continue;
  867. func_name = btf__name_by_offset(btf, t->name_off);
  868. if (!func_name)
  869. continue;
  870. id = btf_id__find(&obj->funcs, func_name);
  871. if (!id || id->kind != BTF_ID_KIND_SYM)
  872. continue;
  873. flags = find_kfunc_flags(obj, id);
  874. kfunc.name = id->name;
  875. kfunc.btf_id = func_id;
  876. kfunc.flags = flags;
  877. err = push_kfunc(ctx, &kfunc);
  878. if (err)
  879. return err;
  880. }
  881. return 0;
  882. }
  883. static int build_btf2btf_context(struct object *obj, struct btf2btf_context *ctx)
  884. {
  885. int err;
  886. ctx->btf = obj->btf;
  887. err = collect_decl_tags(ctx);
  888. if (err) {
  889. pr_err("ERROR: resolve_btfids: failed to collect decl tags from BTF\n");
  890. return err;
  891. }
  892. err = collect_kfuncs(obj, ctx);
  893. if (err) {
  894. pr_err("ERROR: resolve_btfids: failed to collect kfuncs from BTF\n");
  895. return err;
  896. }
  897. return 0;
  898. }
  899. /* Implicit BPF kfunc arguments can only be of particular types */
  900. static bool is_kf_implicit_arg(const struct btf *btf, const struct btf_param *p)
  901. {
  902. static const char *const kf_implicit_arg_types[] = {
  903. "bpf_prog_aux",
  904. };
  905. const struct btf_type *t;
  906. const char *name;
  907. t = btf_type_skip_qualifiers(btf, p->type);
  908. if (!btf_is_ptr(t))
  909. return false;
  910. t = btf_type_skip_qualifiers(btf, t->type);
  911. if (!btf_is_struct(t))
  912. return false;
  913. name = btf__name_by_offset(btf, t->name_off);
  914. if (!name)
  915. return false;
  916. for (int i = 0; i < ARRAY_SIZE(kf_implicit_arg_types); i++)
  917. if (strcmp(name, kf_implicit_arg_types[i]) == 0)
  918. return true;
  919. return false;
  920. }
  921. /*
  922. * For a kfunc with KF_IMPLICIT_ARGS we do the following:
  923. * 1. Add a new function with _impl suffix in the name, with the prototype
  924. * of the original kfunc.
  925. * 2. Add all decl tags except "bpf_kfunc" for the _impl func.
  926. * 3. Add a new function prototype with modified list of arguments:
  927. * omitting implicit args.
  928. * 4. Change the prototype of the original kfunc to the new one.
  929. *
  930. * This way we transform the BTF associated with the kfunc from
  931. * __bpf_kfunc bpf_foo(int arg1, void *implicit_arg);
  932. * into
  933. * bpf_foo_impl(int arg1, void *implicit_arg);
  934. * __bpf_kfunc bpf_foo(int arg1);
  935. *
  936. * If a kfunc with KF_IMPLICIT_ARGS already has an _impl counterpart
  937. * in BTF, then it's a legacy case: an _impl function is declared in the
  938. * source code. In this case, we can skip adding an _impl function, but we
  939. * still have to add a func prototype that omits implicit args.
  940. */
  941. static int process_kfunc_with_implicit_args(struct btf2btf_context *ctx, struct kfunc *kfunc)
  942. {
  943. s32 idx, new_proto_id, new_func_id, proto_id;
  944. const char *param_name, *tag_name;
  945. const struct btf_param *params;
  946. enum btf_func_linkage linkage;
  947. char tmp_name[KSYM_NAME_LEN];
  948. struct btf *btf = ctx->btf;
  949. int err, len, nr_params;
  950. struct btf_type *t;
  951. t = (struct btf_type *)btf__type_by_id(btf, kfunc->btf_id);
  952. if (!t || !btf_is_func(t)) {
  953. pr_err("ERROR: resolve_btfids: btf id %d is not a function\n", kfunc->btf_id);
  954. return -EINVAL;
  955. }
  956. linkage = btf_vlen(t);
  957. proto_id = t->type;
  958. t = (struct btf_type *)btf__type_by_id(btf, proto_id);
  959. if (!t || !btf_is_func_proto(t)) {
  960. pr_err("ERROR: resolve_btfids: btf id %d is not a function prototype\n", proto_id);
  961. return -EINVAL;
  962. }
  963. len = snprintf(tmp_name, sizeof(tmp_name), "%s%s", kfunc->name, KF_IMPL_SUFFIX);
  964. if (len < 0 || len >= sizeof(tmp_name)) {
  965. pr_err("ERROR: function name is too long: %s%s\n", kfunc->name, KF_IMPL_SUFFIX);
  966. return -E2BIG;
  967. }
  968. if (btf__find_by_name_kind(btf, tmp_name, BTF_KIND_FUNC) > 0) {
  969. pr_debug("resolve_btfids: function %s already exists in BTF\n", tmp_name);
  970. goto add_new_proto;
  971. }
  972. /* Add a new function with _impl suffix and original prototype */
  973. new_func_id = btf__add_func(btf, tmp_name, linkage, proto_id);
  974. if (new_func_id < 0) {
  975. pr_err("ERROR: resolve_btfids: failed to add func %s to BTF\n", tmp_name);
  976. return new_func_id;
  977. }
  978. /* Copy all decl tags except "bpf_kfunc" from the original kfunc to the new one */
  979. for (int i = 0; i < ctx->nr_decl_tags; i++) {
  980. t = (struct btf_type *)btf__type_by_id(btf, ctx->decl_tags[i]);
  981. if (t->type != kfunc->btf_id)
  982. continue;
  983. tag_name = btf__name_by_offset(btf, t->name_off);
  984. if (strcmp(tag_name, "bpf_kfunc") == 0)
  985. continue;
  986. idx = btf_decl_tag(t)->component_idx;
  987. if (btf_kflag(t))
  988. err = btf__add_decl_attr(btf, tag_name, new_func_id, idx);
  989. else
  990. err = btf__add_decl_tag(btf, tag_name, new_func_id, idx);
  991. if (err < 0) {
  992. pr_err("ERROR: resolve_btfids: failed to add decl tag %s for %s\n",
  993. tag_name, tmp_name);
  994. return -EINVAL;
  995. }
  996. }
  997. add_new_proto:
  998. t = (struct btf_type *)btf__type_by_id(btf, proto_id);
  999. new_proto_id = btf__add_func_proto(btf, t->type);
  1000. if (new_proto_id < 0) {
  1001. pr_err("ERROR: resolve_btfids: failed to add func proto for %s\n", kfunc->name);
  1002. return new_proto_id;
  1003. }
  1004. /* Add non-implicit args to the new prototype */
  1005. t = (struct btf_type *)btf__type_by_id(btf, proto_id);
  1006. nr_params = btf_vlen(t);
  1007. for (int i = 0; i < nr_params; i++) {
  1008. params = btf_params(t);
  1009. if (is_kf_implicit_arg(btf, &params[i]))
  1010. break;
  1011. param_name = btf__name_by_offset(btf, params[i].name_off);
  1012. err = btf__add_func_param(btf, param_name, params[i].type);
  1013. if (err < 0) {
  1014. pr_err("ERROR: resolve_btfids: failed to add param %s for %s\n",
  1015. param_name, kfunc->name);
  1016. return err;
  1017. }
  1018. t = (struct btf_type *)btf__type_by_id(btf, proto_id);
  1019. }
  1020. /* Finally change the prototype of the original kfunc to the new one */
  1021. t = (struct btf_type *)btf__type_by_id(btf, kfunc->btf_id);
  1022. t->type = new_proto_id;
  1023. pr_debug("resolve_btfids: updated BTF for kfunc with implicit args %s\n", kfunc->name);
  1024. return 0;
  1025. }
  1026. static int btf2btf(struct object *obj)
  1027. {
  1028. struct btf2btf_context ctx = {};
  1029. int err;
  1030. err = build_btf2btf_context(obj, &ctx);
  1031. if (err)
  1032. goto out;
  1033. for (u32 i = 0; i < ctx.nr_kfuncs; i++) {
  1034. struct kfunc *kfunc = &ctx.kfuncs[i];
  1035. if (!(kfunc->flags & KF_IMPLICIT_ARGS))
  1036. continue;
  1037. err = process_kfunc_with_implicit_args(&ctx, kfunc);
  1038. if (err)
  1039. goto out;
  1040. }
  1041. err = 0;
  1042. out:
  1043. free(ctx.decl_tags);
  1044. free(ctx.kfuncs);
  1045. return err;
  1046. }
  1047. /*
  1048. * Sort types by name in ascending order resulting in all
  1049. * anonymous types being placed before named types.
  1050. */
  1051. static int cmp_type_names(const void *a, const void *b, void *priv)
  1052. {
  1053. struct btf *btf = (struct btf *)priv;
  1054. const struct btf_type *ta = btf__type_by_id(btf, *(__u32 *)a);
  1055. const struct btf_type *tb = btf__type_by_id(btf, *(__u32 *)b);
  1056. const char *na, *nb;
  1057. int r;
  1058. na = btf__str_by_offset(btf, ta->name_off);
  1059. nb = btf__str_by_offset(btf, tb->name_off);
  1060. r = strcmp(na, nb);
  1061. if (r != 0)
  1062. return r;
  1063. /* preserve original relative order of anonymous or same-named types */
  1064. return *(__u32 *)a < *(__u32 *)b ? -1 : 1;
  1065. }
  1066. static int sort_btf_by_name(struct btf *btf)
  1067. {
  1068. __u32 *permute_ids = NULL, *id_map = NULL;
  1069. int nr_types, i, err = 0;
  1070. __u32 start_id = 0, id;
  1071. if (btf__base_btf(btf))
  1072. start_id = btf__type_cnt(btf__base_btf(btf));
  1073. nr_types = btf__type_cnt(btf) - start_id;
  1074. permute_ids = calloc(nr_types, sizeof(*permute_ids));
  1075. if (!permute_ids) {
  1076. err = -ENOMEM;
  1077. goto out;
  1078. }
  1079. id_map = calloc(nr_types, sizeof(*id_map));
  1080. if (!id_map) {
  1081. err = -ENOMEM;
  1082. goto out;
  1083. }
  1084. for (i = 0, id = start_id; i < nr_types; i++, id++)
  1085. permute_ids[i] = id;
  1086. qsort_r(permute_ids, nr_types, sizeof(*permute_ids), cmp_type_names,
  1087. btf);
  1088. for (i = 0; i < nr_types; i++) {
  1089. id = permute_ids[i] - start_id;
  1090. id_map[id] = i + start_id;
  1091. }
  1092. err = btf__permute(btf, id_map, nr_types, NULL);
  1093. if (err)
  1094. pr_err("FAILED: btf permute: %s\n", strerror(-err));
  1095. out:
  1096. free(permute_ids);
  1097. free(id_map);
  1098. return err;
  1099. }
  1100. static int finalize_btf(struct object *obj)
  1101. {
  1102. struct btf *base_btf = obj->base_btf, *btf = obj->btf;
  1103. int err;
  1104. if (obj->base_btf && obj->distill_base) {
  1105. err = btf__distill_base(obj->btf, &base_btf, &btf);
  1106. if (err) {
  1107. pr_err("FAILED to distill base BTF: %s\n", strerror(errno));
  1108. goto out_err;
  1109. }
  1110. btf__free(obj->base_btf);
  1111. btf__free(obj->btf);
  1112. obj->base_btf = base_btf;
  1113. obj->btf = btf;
  1114. }
  1115. err = sort_btf_by_name(obj->btf);
  1116. if (err) {
  1117. pr_err("FAILED to sort BTF: %s\n", strerror(errno));
  1118. goto out_err;
  1119. }
  1120. return 0;
  1121. out_err:
  1122. btf__free(base_btf);
  1123. btf__free(btf);
  1124. obj->base_btf = NULL;
  1125. obj->btf = NULL;
  1126. return err;
  1127. }
  1128. static inline int make_out_path(char *buf, u32 buf_sz, const char *in_path, const char *suffix)
  1129. {
  1130. int len = snprintf(buf, buf_sz, "%s%s", in_path, suffix);
  1131. if (len < 0 || len >= buf_sz) {
  1132. pr_err("Output path is too long: %s%s\n", in_path, suffix);
  1133. return -E2BIG;
  1134. }
  1135. return 0;
  1136. }
  1137. /*
  1138. * Patch the .BTF_ids section of an ELF file with data from provided file.
  1139. * Equivalent to: objcopy --update-section .BTF_ids=<btfids> <elf>
  1140. *
  1141. * 1. Find .BTF_ids section in the ELF
  1142. * 2. Verify that blob file size matches section size
  1143. * 3. Update section data buffer with blob data
  1144. * 4. Write the ELF file
  1145. */
  1146. static int patch_btfids(const char *btfids_path, const char *elf_path)
  1147. {
  1148. Elf_Scn *scn = NULL;
  1149. FILE *btfids_file;
  1150. size_t shdrstrndx;
  1151. int fd, err = -1;
  1152. Elf_Data *data;
  1153. struct stat st;
  1154. GElf_Shdr sh;
  1155. char *name;
  1156. Elf *elf;
  1157. elf_version(EV_CURRENT);
  1158. fd = open(elf_path, O_RDWR, 0666);
  1159. if (fd < 0) {
  1160. pr_err("FAILED to open %s: %s\n", elf_path, strerror(errno));
  1161. return -1;
  1162. }
  1163. elf = elf_begin(fd, ELF_C_RDWR_MMAP, NULL);
  1164. if (!elf) {
  1165. close(fd);
  1166. pr_err("FAILED cannot create ELF descriptor: %s\n", elf_errmsg(-1));
  1167. return -1;
  1168. }
  1169. elf_flagelf(elf, ELF_C_SET, ELF_F_LAYOUT);
  1170. if (elf_getshdrstrndx(elf, &shdrstrndx) != 0) {
  1171. pr_err("FAILED cannot get shdr str ndx\n");
  1172. goto out;
  1173. }
  1174. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  1175. if (gelf_getshdr(scn, &sh) != &sh) {
  1176. pr_err("FAILED to get section header\n");
  1177. goto out;
  1178. }
  1179. name = elf_strptr(elf, shdrstrndx, sh.sh_name);
  1180. if (!name)
  1181. continue;
  1182. if (strcmp(name, BTF_IDS_SECTION) == 0)
  1183. break;
  1184. }
  1185. if (!scn) {
  1186. pr_err("FAILED: section %s not found in %s\n", BTF_IDS_SECTION, elf_path);
  1187. goto out;
  1188. }
  1189. data = elf_getdata(scn, NULL);
  1190. if (!data) {
  1191. pr_err("FAILED to get %s section data from %s\n", BTF_IDS_SECTION, elf_path);
  1192. goto out;
  1193. }
  1194. if (stat(btfids_path, &st) < 0) {
  1195. pr_err("FAILED to stat %s: %s\n", btfids_path, strerror(errno));
  1196. goto out;
  1197. }
  1198. if ((size_t)st.st_size != data->d_size) {
  1199. pr_err("FAILED: size mismatch - %s section in %s is %zu bytes, %s is %zu bytes\n",
  1200. BTF_IDS_SECTION, elf_path, data->d_size, btfids_path, (size_t)st.st_size);
  1201. goto out;
  1202. }
  1203. btfids_file = fopen(btfids_path, "rb");
  1204. if (!btfids_file) {
  1205. pr_err("FAILED to open %s: %s\n", btfids_path, strerror(errno));
  1206. goto out;
  1207. }
  1208. pr_debug("Copying data from %s to %s section of %s (%zu bytes)\n",
  1209. btfids_path, BTF_IDS_SECTION, elf_path, data->d_size);
  1210. if (fread(data->d_buf, data->d_size, 1, btfids_file) != 1) {
  1211. pr_err("FAILED to read %s\n", btfids_path);
  1212. fclose(btfids_file);
  1213. goto out;
  1214. }
  1215. fclose(btfids_file);
  1216. elf_flagdata(data, ELF_C_SET, ELF_F_DIRTY);
  1217. if (elf_update(elf, ELF_C_WRITE) < 0) {
  1218. pr_err("FAILED to update ELF file %s\n", elf_path);
  1219. goto out;
  1220. }
  1221. err = 0;
  1222. out:
  1223. elf_end(elf);
  1224. close(fd);
  1225. return err;
  1226. }
  1227. static const char * const resolve_btfids_usage[] = {
  1228. "resolve_btfids [<options>] <ELF object>",
  1229. "resolve_btfids --patch_btfids <.BTF_ids file> <ELF object>",
  1230. NULL
  1231. };
  1232. int main(int argc, const char **argv)
  1233. {
  1234. struct object obj = {
  1235. .efile = {
  1236. .idlist_shndx = -1,
  1237. .symbols_shndx = -1,
  1238. },
  1239. .structs = RB_ROOT,
  1240. .unions = RB_ROOT,
  1241. .typedefs = RB_ROOT,
  1242. .funcs = RB_ROOT,
  1243. .sets = RB_ROOT,
  1244. };
  1245. const char *btfids_path = NULL;
  1246. bool fatal_warnings = false;
  1247. bool resolve_btfids = true;
  1248. char out_path[PATH_MAX];
  1249. struct option btfid_options[] = {
  1250. OPT_INCR('v', "verbose", &verbose,
  1251. "be more verbose (show errors, etc)"),
  1252. OPT_STRING(0, "btf", &obj.btf_path, "file",
  1253. "path to a file with input BTF data"),
  1254. OPT_STRING('b', "btf_base", &obj.base_btf_path, "file",
  1255. "path of file providing base BTF"),
  1256. OPT_BOOLEAN(0, "fatal_warnings", &fatal_warnings,
  1257. "turn warnings into errors"),
  1258. OPT_BOOLEAN(0, "distill_base", &obj.distill_base,
  1259. "distill --btf_base and emit .BTF.base section data"),
  1260. OPT_STRING(0, "patch_btfids", &btfids_path, "file",
  1261. "path to .BTF_ids section data blob to patch into ELF file"),
  1262. OPT_END()
  1263. };
  1264. int err = -1;
  1265. argc = parse_options(argc, argv, btfid_options, resolve_btfids_usage,
  1266. PARSE_OPT_STOP_AT_NON_OPTION);
  1267. if (argc != 1)
  1268. usage_with_options(resolve_btfids_usage, btfid_options);
  1269. obj.path = argv[0];
  1270. if (btfids_path)
  1271. return patch_btfids(btfids_path, obj.path);
  1272. if (elf_collect(&obj))
  1273. goto out;
  1274. /*
  1275. * We did not find .BTF_ids section or symbols section,
  1276. * nothing to do..
  1277. */
  1278. if (obj.efile.idlist_shndx == -1 ||
  1279. obj.efile.symbols_shndx == -1) {
  1280. pr_debug("Cannot find .BTF_ids or symbols sections, skip symbols resolution\n");
  1281. resolve_btfids = false;
  1282. }
  1283. if (resolve_btfids)
  1284. if (symbols_collect(&obj))
  1285. goto out;
  1286. if (load_btf(&obj))
  1287. goto out;
  1288. if (btf2btf(&obj))
  1289. goto out;
  1290. if (finalize_btf(&obj))
  1291. goto out;
  1292. if (!resolve_btfids)
  1293. goto dump_btf;
  1294. if (symbols_resolve(&obj))
  1295. goto out;
  1296. if (symbols_patch(&obj))
  1297. goto out;
  1298. err = make_out_path(out_path, sizeof(out_path), obj.path, BTF_IDS_SECTION);
  1299. err = err ?: dump_raw_btf_ids(&obj, out_path);
  1300. if (err)
  1301. goto out;
  1302. dump_btf:
  1303. err = make_out_path(out_path, sizeof(out_path), obj.path, BTF_ELF_SEC);
  1304. err = err ?: dump_raw_btf(obj.btf, out_path);
  1305. if (err)
  1306. goto out;
  1307. if (obj.base_btf && obj.distill_base) {
  1308. err = make_out_path(out_path, sizeof(out_path), obj.path, BTF_BASE_ELF_SEC);
  1309. err = err ?: dump_raw_btf(obj.base_btf, out_path);
  1310. if (err)
  1311. goto out;
  1312. }
  1313. if (!(fatal_warnings && warnings))
  1314. err = 0;
  1315. out:
  1316. btf__free(obj.base_btf);
  1317. btf__free(obj.btf);
  1318. btf_id__free_all(&obj.structs);
  1319. btf_id__free_all(&obj.unions);
  1320. btf_id__free_all(&obj.typedefs);
  1321. btf_id__free_all(&obj.funcs);
  1322. btf_id__free_all(&obj.sets);
  1323. if (obj.efile.elf) {
  1324. elf_end(obj.efile.elf);
  1325. close(obj.efile.fd);
  1326. }
  1327. return err;
  1328. }