elf.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #endif
  5. #include <libelf.h>
  6. #include <gelf.h>
  7. #include <fcntl.h>
  8. #include <linux/kernel.h>
  9. #include "libbpf_internal.h"
  10. /* A SHT_GNU_versym section holds 16-bit words. This bit is set if
  11. * the symbol is hidden and can only be seen when referenced using an
  12. * explicit version number. This is a GNU extension.
  13. */
  14. #define VERSYM_HIDDEN 0x8000
  15. /* This is the mask for the rest of the data in a word read from a
  16. * SHT_GNU_versym section.
  17. */
  18. #define VERSYM_VERSION 0x7fff
  19. int elf_open(const char *binary_path, struct elf_fd *elf_fd)
  20. {
  21. int fd, ret;
  22. Elf *elf;
  23. elf_fd->elf = NULL;
  24. elf_fd->fd = -1;
  25. if (elf_version(EV_CURRENT) == EV_NONE) {
  26. pr_warn("elf: failed to init libelf for %s\n", binary_path);
  27. return -LIBBPF_ERRNO__LIBELF;
  28. }
  29. fd = open(binary_path, O_RDONLY | O_CLOEXEC);
  30. if (fd < 0) {
  31. ret = -errno;
  32. pr_warn("elf: failed to open %s: %s\n", binary_path, errstr(ret));
  33. return ret;
  34. }
  35. elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
  36. if (!elf) {
  37. pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
  38. close(fd);
  39. return -LIBBPF_ERRNO__FORMAT;
  40. }
  41. elf_fd->fd = fd;
  42. elf_fd->elf = elf;
  43. return 0;
  44. }
  45. void elf_close(struct elf_fd *elf_fd)
  46. {
  47. if (!elf_fd)
  48. return;
  49. elf_end(elf_fd->elf);
  50. close(elf_fd->fd);
  51. }
  52. /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
  53. static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
  54. {
  55. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  56. GElf_Shdr sh;
  57. if (!gelf_getshdr(scn, &sh))
  58. continue;
  59. if (sh.sh_type == sh_type)
  60. return scn;
  61. }
  62. return NULL;
  63. }
  64. struct elf_sym {
  65. const char *name;
  66. GElf_Sym sym;
  67. GElf_Shdr sh;
  68. int ver;
  69. bool hidden;
  70. };
  71. struct elf_sym_iter {
  72. Elf *elf;
  73. Elf_Data *syms;
  74. Elf_Data *versyms;
  75. Elf_Data *verdefs;
  76. size_t nr_syms;
  77. size_t strtabidx;
  78. size_t verdef_strtabidx;
  79. size_t next_sym_idx;
  80. struct elf_sym sym;
  81. int st_type;
  82. };
  83. static int elf_sym_iter_new(struct elf_sym_iter *iter,
  84. Elf *elf, const char *binary_path,
  85. int sh_type, int st_type)
  86. {
  87. Elf_Scn *scn = NULL;
  88. GElf_Ehdr ehdr;
  89. GElf_Shdr sh;
  90. memset(iter, 0, sizeof(*iter));
  91. if (!gelf_getehdr(elf, &ehdr)) {
  92. pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
  93. return -EINVAL;
  94. }
  95. scn = elf_find_next_scn_by_type(elf, sh_type, NULL);
  96. if (!scn) {
  97. pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
  98. binary_path);
  99. return -ENOENT;
  100. }
  101. if (!gelf_getshdr(scn, &sh))
  102. return -EINVAL;
  103. iter->strtabidx = sh.sh_link;
  104. iter->syms = elf_getdata(scn, 0);
  105. if (!iter->syms) {
  106. pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
  107. binary_path, elf_errmsg(-1));
  108. return -EINVAL;
  109. }
  110. iter->nr_syms = iter->syms->d_size / sh.sh_entsize;
  111. iter->elf = elf;
  112. iter->st_type = st_type;
  113. /* Version symbol table is meaningful to dynsym only */
  114. if (sh_type != SHT_DYNSYM)
  115. return 0;
  116. scn = elf_find_next_scn_by_type(elf, SHT_GNU_versym, NULL);
  117. if (!scn)
  118. return 0;
  119. iter->versyms = elf_getdata(scn, 0);
  120. scn = elf_find_next_scn_by_type(elf, SHT_GNU_verdef, NULL);
  121. if (!scn)
  122. return 0;
  123. iter->verdefs = elf_getdata(scn, 0);
  124. if (!iter->verdefs || !gelf_getshdr(scn, &sh)) {
  125. pr_warn("elf: failed to get verdef ELF section in '%s'\n", binary_path);
  126. return -EINVAL;
  127. }
  128. iter->verdef_strtabidx = sh.sh_link;
  129. return 0;
  130. }
  131. static struct elf_sym *elf_sym_iter_next(struct elf_sym_iter *iter)
  132. {
  133. struct elf_sym *ret = &iter->sym;
  134. GElf_Sym *sym = &ret->sym;
  135. const char *name = NULL;
  136. GElf_Versym versym;
  137. Elf_Scn *sym_scn;
  138. size_t idx;
  139. for (idx = iter->next_sym_idx; idx < iter->nr_syms; idx++) {
  140. if (!gelf_getsym(iter->syms, idx, sym))
  141. continue;
  142. if (GELF_ST_TYPE(sym->st_info) != iter->st_type)
  143. continue;
  144. name = elf_strptr(iter->elf, iter->strtabidx, sym->st_name);
  145. if (!name)
  146. continue;
  147. sym_scn = elf_getscn(iter->elf, sym->st_shndx);
  148. if (!sym_scn)
  149. continue;
  150. if (!gelf_getshdr(sym_scn, &ret->sh))
  151. continue;
  152. iter->next_sym_idx = idx + 1;
  153. ret->name = name;
  154. ret->ver = 0;
  155. ret->hidden = false;
  156. if (iter->versyms) {
  157. if (!gelf_getversym(iter->versyms, idx, &versym))
  158. continue;
  159. ret->ver = versym & VERSYM_VERSION;
  160. ret->hidden = versym & VERSYM_HIDDEN;
  161. }
  162. return ret;
  163. }
  164. return NULL;
  165. }
  166. static const char *elf_get_vername(struct elf_sym_iter *iter, int ver)
  167. {
  168. GElf_Verdaux verdaux;
  169. GElf_Verdef verdef;
  170. int offset;
  171. if (!iter->verdefs)
  172. return NULL;
  173. offset = 0;
  174. while (gelf_getverdef(iter->verdefs, offset, &verdef)) {
  175. if (verdef.vd_ndx != ver) {
  176. if (!verdef.vd_next)
  177. break;
  178. offset += verdef.vd_next;
  179. continue;
  180. }
  181. if (!gelf_getverdaux(iter->verdefs, offset + verdef.vd_aux, &verdaux))
  182. break;
  183. return elf_strptr(iter->elf, iter->verdef_strtabidx, verdaux.vda_name);
  184. }
  185. return NULL;
  186. }
  187. static bool symbol_match(struct elf_sym_iter *iter, int sh_type, struct elf_sym *sym,
  188. const char *name, size_t name_len, const char *lib_ver)
  189. {
  190. const char *ver_name;
  191. /* Symbols are in forms of func, func@LIB_VER or func@@LIB_VER
  192. * make sure the func part matches the user specified name
  193. */
  194. if (strncmp(sym->name, name, name_len) != 0)
  195. return false;
  196. /* ...but we don't want a search for "foo" to match 'foo2" also, so any
  197. * additional characters in sname should be of the form "@@LIB".
  198. */
  199. if (sym->name[name_len] != '\0' && sym->name[name_len] != '@')
  200. return false;
  201. /* If user does not specify symbol version, then we got a match */
  202. if (!lib_ver)
  203. return true;
  204. /* If user specifies symbol version, for dynamic symbols,
  205. * get version name from ELF verdef section for comparison.
  206. */
  207. if (sh_type == SHT_DYNSYM) {
  208. ver_name = elf_get_vername(iter, sym->ver);
  209. if (!ver_name)
  210. return false;
  211. return strcmp(ver_name, lib_ver) == 0;
  212. }
  213. /* For normal symbols, it is already in form of func@LIB_VER */
  214. return strcmp(sym->name, name) == 0;
  215. }
  216. /* Transform symbol's virtual address (absolute for binaries and relative
  217. * for shared libs) into file offset, which is what kernel is expecting
  218. * for uprobe/uretprobe attachment.
  219. * See Documentation/trace/uprobetracer.rst for more details. This is done
  220. * by looking up symbol's containing section's header and using iter's virtual
  221. * address (sh_addr) and corresponding file offset (sh_offset) to transform
  222. * sym.st_value (virtual address) into desired final file offset.
  223. */
  224. static unsigned long elf_sym_offset(struct elf_sym *sym)
  225. {
  226. return sym->sym.st_value - sym->sh.sh_addr + sym->sh.sh_offset;
  227. }
  228. /* Find offset of function name in the provided ELF object. "binary_path" is
  229. * the path to the ELF binary represented by "elf", and only used for error
  230. * reporting matters. "name" matches symbol name or name@@LIB for library
  231. * functions.
  232. */
  233. long elf_find_func_offset(Elf *elf, const char *binary_path, const char *name)
  234. {
  235. int i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
  236. const char *at_symbol, *lib_ver;
  237. bool is_shared_lib;
  238. long ret = -ENOENT;
  239. size_t name_len;
  240. GElf_Ehdr ehdr;
  241. if (!gelf_getehdr(elf, &ehdr)) {
  242. pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
  243. ret = -LIBBPF_ERRNO__FORMAT;
  244. goto out;
  245. }
  246. /* for shared lib case, we do not need to calculate relative offset */
  247. is_shared_lib = ehdr.e_type == ET_DYN;
  248. /* Does name specify "@@LIB_VER" or "@LIB_VER" ? */
  249. at_symbol = strchr(name, '@');
  250. if (at_symbol) {
  251. name_len = at_symbol - name;
  252. /* skip second @ if it's @@LIB_VER case */
  253. if (at_symbol[1] == '@')
  254. at_symbol++;
  255. lib_ver = at_symbol + 1;
  256. } else {
  257. name_len = strlen(name);
  258. lib_ver = NULL;
  259. }
  260. /* Search SHT_DYNSYM, SHT_SYMTAB for symbol. This search order is used because if
  261. * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
  262. * linked binary may not have SHT_DYMSYM, so absence of a section should not be
  263. * reported as a warning/error.
  264. */
  265. for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
  266. struct elf_sym_iter iter;
  267. struct elf_sym *sym;
  268. int last_bind = -1;
  269. int cur_bind;
  270. ret = elf_sym_iter_new(&iter, elf, binary_path, sh_types[i], STT_FUNC);
  271. if (ret == -ENOENT)
  272. continue;
  273. if (ret)
  274. goto out;
  275. while ((sym = elf_sym_iter_next(&iter))) {
  276. if (!symbol_match(&iter, sh_types[i], sym, name, name_len, lib_ver))
  277. continue;
  278. cur_bind = GELF_ST_BIND(sym->sym.st_info);
  279. if (ret > 0) {
  280. /* handle multiple matches */
  281. if (elf_sym_offset(sym) == ret) {
  282. /* same offset, no problem */
  283. continue;
  284. } else if (last_bind != STB_WEAK && cur_bind != STB_WEAK) {
  285. /* Only accept one non-weak bind. */
  286. pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
  287. sym->name, name, binary_path);
  288. ret = -LIBBPF_ERRNO__FORMAT;
  289. goto out;
  290. } else if (cur_bind == STB_WEAK) {
  291. /* already have a non-weak bind, and
  292. * this is a weak bind, so ignore.
  293. */
  294. continue;
  295. }
  296. }
  297. ret = elf_sym_offset(sym);
  298. last_bind = cur_bind;
  299. }
  300. if (ret > 0)
  301. break;
  302. }
  303. if (ret > 0) {
  304. pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
  305. ret);
  306. } else {
  307. if (ret == 0) {
  308. pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
  309. is_shared_lib ? "should not be 0 in a shared library" :
  310. "try using shared library path instead");
  311. ret = -ENOENT;
  312. } else {
  313. pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
  314. }
  315. }
  316. out:
  317. return ret;
  318. }
  319. /* Find offset of function name in ELF object specified by path. "name" matches
  320. * symbol name or name@@LIB for library functions.
  321. */
  322. long elf_find_func_offset_from_file(const char *binary_path, const char *name)
  323. {
  324. struct elf_fd elf_fd;
  325. long ret = -ENOENT;
  326. ret = elf_open(binary_path, &elf_fd);
  327. if (ret)
  328. return ret;
  329. ret = elf_find_func_offset(elf_fd.elf, binary_path, name);
  330. elf_close(&elf_fd);
  331. return ret;
  332. }
  333. struct symbol {
  334. const char *name;
  335. int bind;
  336. int idx;
  337. };
  338. static int symbol_cmp(const void *a, const void *b)
  339. {
  340. const struct symbol *sym_a = a;
  341. const struct symbol *sym_b = b;
  342. return strcmp(sym_a->name, sym_b->name);
  343. }
  344. /*
  345. * Return offsets in @poffsets for symbols specified in @syms array argument.
  346. * On success returns 0 and offsets are returned in allocated array with @cnt
  347. * size, that needs to be released by the caller.
  348. */
  349. int elf_resolve_syms_offsets(const char *binary_path, int cnt,
  350. const char **syms, unsigned long **poffsets,
  351. int st_type)
  352. {
  353. int sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
  354. int err = 0, i, cnt_done = 0;
  355. unsigned long *offsets;
  356. struct symbol *symbols;
  357. struct elf_fd elf_fd;
  358. err = elf_open(binary_path, &elf_fd);
  359. if (err)
  360. return err;
  361. offsets = calloc(cnt, sizeof(*offsets));
  362. symbols = calloc(cnt, sizeof(*symbols));
  363. if (!offsets || !symbols) {
  364. err = -ENOMEM;
  365. goto out;
  366. }
  367. for (i = 0; i < cnt; i++) {
  368. symbols[i].name = syms[i];
  369. symbols[i].idx = i;
  370. }
  371. qsort(symbols, cnt, sizeof(*symbols), symbol_cmp);
  372. for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
  373. struct elf_sym_iter iter;
  374. struct elf_sym *sym;
  375. err = elf_sym_iter_new(&iter, elf_fd.elf, binary_path, sh_types[i], st_type);
  376. if (err == -ENOENT)
  377. continue;
  378. if (err)
  379. goto out;
  380. while ((sym = elf_sym_iter_next(&iter))) {
  381. unsigned long sym_offset = elf_sym_offset(sym);
  382. int bind = GELF_ST_BIND(sym->sym.st_info);
  383. struct symbol *found, tmp = {
  384. .name = sym->name,
  385. };
  386. unsigned long *offset;
  387. found = bsearch(&tmp, symbols, cnt, sizeof(*symbols), symbol_cmp);
  388. if (!found)
  389. continue;
  390. offset = &offsets[found->idx];
  391. if (*offset > 0) {
  392. /* same offset, no problem */
  393. if (*offset == sym_offset)
  394. continue;
  395. /* handle multiple matches */
  396. if (found->bind != STB_WEAK && bind != STB_WEAK) {
  397. /* Only accept one non-weak bind. */
  398. pr_warn("elf: ambiguous match found '%s@%lu' in '%s' previous offset %lu\n",
  399. sym->name, sym_offset, binary_path, *offset);
  400. err = -ESRCH;
  401. goto out;
  402. } else if (bind == STB_WEAK) {
  403. /* already have a non-weak bind, and
  404. * this is a weak bind, so ignore.
  405. */
  406. continue;
  407. }
  408. } else {
  409. cnt_done++;
  410. }
  411. *offset = sym_offset;
  412. found->bind = bind;
  413. }
  414. }
  415. if (cnt != cnt_done) {
  416. err = -ENOENT;
  417. goto out;
  418. }
  419. *poffsets = offsets;
  420. out:
  421. free(symbols);
  422. if (err)
  423. free(offsets);
  424. elf_close(&elf_fd);
  425. return err;
  426. }
  427. /*
  428. * Return offsets in @poffsets for symbols specified by @pattern argument.
  429. * On success returns 0 and offsets are returned in allocated @poffsets
  430. * array with the @pctn size, that needs to be released by the caller.
  431. */
  432. int elf_resolve_pattern_offsets(const char *binary_path, const char *pattern,
  433. unsigned long **poffsets, size_t *pcnt)
  434. {
  435. int sh_types[2] = { SHT_SYMTAB, SHT_DYNSYM };
  436. unsigned long *offsets = NULL;
  437. size_t cap = 0, cnt = 0;
  438. struct elf_fd elf_fd;
  439. int err = 0, i;
  440. err = elf_open(binary_path, &elf_fd);
  441. if (err)
  442. return err;
  443. for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
  444. struct elf_sym_iter iter;
  445. struct elf_sym *sym;
  446. err = elf_sym_iter_new(&iter, elf_fd.elf, binary_path, sh_types[i], STT_FUNC);
  447. if (err == -ENOENT)
  448. continue;
  449. if (err)
  450. goto out;
  451. while ((sym = elf_sym_iter_next(&iter))) {
  452. if (!glob_match(sym->name, pattern))
  453. continue;
  454. err = libbpf_ensure_mem((void **) &offsets, &cap, sizeof(*offsets),
  455. cnt + 1);
  456. if (err)
  457. goto out;
  458. offsets[cnt++] = elf_sym_offset(sym);
  459. }
  460. /* If we found anything in the first symbol section,
  461. * do not search others to avoid duplicates.
  462. */
  463. if (cnt)
  464. break;
  465. }
  466. if (cnt) {
  467. *poffsets = offsets;
  468. *pcnt = cnt;
  469. } else {
  470. err = -ENOENT;
  471. }
  472. out:
  473. if (err)
  474. free(offsets);
  475. elf_close(&elf_fd);
  476. return err;
  477. }