libbpf.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317
  1. // SPDX-License-Identifier: LGPL-2.1
  2. /*
  3. * Common eBPF ELF object loading operations.
  4. *
  5. * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
  6. * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
  7. * Copyright (C) 2015 Huawei Inc.
  8. * Copyright (C) 2017 Nicira, Inc.
  9. *
  10. * This program is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation;
  13. * version 2.1 of the License (not later!)
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public
  21. * License along with this program; if not, see <http://www.gnu.org/licenses>
  22. */
  23. #include <stdlib.h>
  24. #include <stdio.h>
  25. #include <stdarg.h>
  26. #include <libgen.h>
  27. #include <inttypes.h>
  28. #include <string.h>
  29. #include <unistd.h>
  30. #include <fcntl.h>
  31. #include <errno.h>
  32. #include <perf-sys.h>
  33. #include <asm/unistd.h>
  34. #include <linux/err.h>
  35. #include <linux/kernel.h>
  36. #include <linux/bpf.h>
  37. #include <linux/list.h>
  38. #include <linux/limits.h>
  39. #include <sys/stat.h>
  40. #include <sys/types.h>
  41. #include <sys/vfs.h>
  42. #include <libelf.h>
  43. #include <gelf.h>
  44. #include "libbpf.h"
  45. #include "bpf.h"
  46. #include "btf.h"
  47. #ifndef EM_BPF
  48. #define EM_BPF 247
  49. #endif
  50. #ifndef BPF_FS_MAGIC
  51. #define BPF_FS_MAGIC 0xcafe4a11
  52. #endif
  53. #define __printf(a, b) __attribute__((format(printf, a, b)))
  54. __printf(1, 2)
  55. static int __base_pr(const char *format, ...)
  56. {
  57. va_list args;
  58. int err;
  59. va_start(args, format);
  60. err = vfprintf(stderr, format, args);
  61. va_end(args);
  62. return err;
  63. }
  64. static __printf(1, 2) libbpf_print_fn_t __pr_warning = __base_pr;
  65. static __printf(1, 2) libbpf_print_fn_t __pr_info = __base_pr;
  66. static __printf(1, 2) libbpf_print_fn_t __pr_debug;
  67. #define __pr(func, fmt, ...) \
  68. do { \
  69. if ((func)) \
  70. (func)("libbpf: " fmt, ##__VA_ARGS__); \
  71. } while (0)
  72. #define pr_warning(fmt, ...) __pr(__pr_warning, fmt, ##__VA_ARGS__)
  73. #define pr_info(fmt, ...) __pr(__pr_info, fmt, ##__VA_ARGS__)
  74. #define pr_debug(fmt, ...) __pr(__pr_debug, fmt, ##__VA_ARGS__)
  75. void libbpf_set_print(libbpf_print_fn_t warn,
  76. libbpf_print_fn_t info,
  77. libbpf_print_fn_t debug)
  78. {
  79. __pr_warning = warn;
  80. __pr_info = info;
  81. __pr_debug = debug;
  82. }
  83. #define STRERR_BUFSIZE 128
  84. #define ERRNO_OFFSET(e) ((e) - __LIBBPF_ERRNO__START)
  85. #define ERRCODE_OFFSET(c) ERRNO_OFFSET(LIBBPF_ERRNO__##c)
  86. #define NR_ERRNO (__LIBBPF_ERRNO__END - __LIBBPF_ERRNO__START)
  87. static const char *libbpf_strerror_table[NR_ERRNO] = {
  88. [ERRCODE_OFFSET(LIBELF)] = "Something wrong in libelf",
  89. [ERRCODE_OFFSET(FORMAT)] = "BPF object format invalid",
  90. [ERRCODE_OFFSET(KVERSION)] = "'version' section incorrect or lost",
  91. [ERRCODE_OFFSET(ENDIAN)] = "Endian mismatch",
  92. [ERRCODE_OFFSET(INTERNAL)] = "Internal error in libbpf",
  93. [ERRCODE_OFFSET(RELOC)] = "Relocation failed",
  94. [ERRCODE_OFFSET(VERIFY)] = "Kernel verifier blocks program loading",
  95. [ERRCODE_OFFSET(PROG2BIG)] = "Program too big",
  96. [ERRCODE_OFFSET(KVER)] = "Incorrect kernel version",
  97. [ERRCODE_OFFSET(PROGTYPE)] = "Kernel doesn't support this program type",
  98. [ERRCODE_OFFSET(WRNGPID)] = "Wrong pid in netlink message",
  99. [ERRCODE_OFFSET(INVSEQ)] = "Invalid netlink sequence",
  100. };
  101. int libbpf_strerror(int err, char *buf, size_t size)
  102. {
  103. if (!buf || !size)
  104. return -1;
  105. err = err > 0 ? err : -err;
  106. if (err < __LIBBPF_ERRNO__START) {
  107. int ret;
  108. ret = strerror_r(err, buf, size);
  109. buf[size - 1] = '\0';
  110. return ret;
  111. }
  112. if (err < __LIBBPF_ERRNO__END) {
  113. const char *msg;
  114. msg = libbpf_strerror_table[ERRNO_OFFSET(err)];
  115. snprintf(buf, size, "%s", msg);
  116. buf[size - 1] = '\0';
  117. return 0;
  118. }
  119. snprintf(buf, size, "Unknown libbpf error %d", err);
  120. buf[size - 1] = '\0';
  121. return -1;
  122. }
  123. #define CHECK_ERR(action, err, out) do { \
  124. err = action; \
  125. if (err) \
  126. goto out; \
  127. } while(0)
  128. /* Copied from tools/perf/util/util.h */
  129. #ifndef zfree
  130. # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
  131. #endif
  132. #ifndef zclose
  133. # define zclose(fd) ({ \
  134. int ___err = 0; \
  135. if ((fd) >= 0) \
  136. ___err = close((fd)); \
  137. fd = -1; \
  138. ___err; })
  139. #endif
  140. #ifdef HAVE_LIBELF_MMAP_SUPPORT
  141. # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
  142. #else
  143. # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
  144. #endif
  145. /*
  146. * bpf_prog should be a better name but it has been used in
  147. * linux/filter.h.
  148. */
  149. struct bpf_program {
  150. /* Index in elf obj file, for relocation use. */
  151. int idx;
  152. char *name;
  153. int prog_ifindex;
  154. char *section_name;
  155. struct bpf_insn *insns;
  156. size_t insns_cnt, main_prog_cnt;
  157. enum bpf_prog_type type;
  158. struct reloc_desc {
  159. enum {
  160. RELO_LD64,
  161. RELO_CALL,
  162. } type;
  163. int insn_idx;
  164. union {
  165. int map_idx;
  166. int text_off;
  167. };
  168. } *reloc_desc;
  169. int nr_reloc;
  170. struct {
  171. int nr;
  172. int *fds;
  173. } instances;
  174. bpf_program_prep_t preprocessor;
  175. struct bpf_object *obj;
  176. void *priv;
  177. bpf_program_clear_priv_t clear_priv;
  178. enum bpf_attach_type expected_attach_type;
  179. };
  180. struct bpf_map {
  181. int fd;
  182. char *name;
  183. size_t offset;
  184. int map_ifindex;
  185. struct bpf_map_def def;
  186. uint32_t btf_key_id;
  187. uint32_t btf_value_id;
  188. void *priv;
  189. bpf_map_clear_priv_t clear_priv;
  190. };
  191. static LIST_HEAD(bpf_objects_list);
  192. struct bpf_object {
  193. char license[64];
  194. u32 kern_version;
  195. struct bpf_program *programs;
  196. size_t nr_programs;
  197. struct bpf_map *maps;
  198. size_t nr_maps;
  199. bool loaded;
  200. /*
  201. * Information when doing elf related work. Only valid if fd
  202. * is valid.
  203. */
  204. struct {
  205. int fd;
  206. void *obj_buf;
  207. size_t obj_buf_sz;
  208. Elf *elf;
  209. GElf_Ehdr ehdr;
  210. Elf_Data *symbols;
  211. size_t strtabidx;
  212. struct {
  213. GElf_Shdr shdr;
  214. Elf_Data *data;
  215. } *reloc;
  216. int nr_reloc;
  217. int maps_shndx;
  218. int text_shndx;
  219. } efile;
  220. /*
  221. * All loaded bpf_object is linked in a list, which is
  222. * hidden to caller. bpf_objects__<func> handlers deal with
  223. * all objects.
  224. */
  225. struct list_head list;
  226. struct btf *btf;
  227. void *priv;
  228. bpf_object_clear_priv_t clear_priv;
  229. char path[];
  230. };
  231. #define obj_elf_valid(o) ((o)->efile.elf)
  232. static void bpf_program__unload(struct bpf_program *prog)
  233. {
  234. int i;
  235. if (!prog)
  236. return;
  237. /*
  238. * If the object is opened but the program was never loaded,
  239. * it is possible that prog->instances.nr == -1.
  240. */
  241. if (prog->instances.nr > 0) {
  242. for (i = 0; i < prog->instances.nr; i++)
  243. zclose(prog->instances.fds[i]);
  244. } else if (prog->instances.nr != -1) {
  245. pr_warning("Internal error: instances.nr is %d\n",
  246. prog->instances.nr);
  247. }
  248. prog->instances.nr = -1;
  249. zfree(&prog->instances.fds);
  250. }
  251. static void bpf_program__exit(struct bpf_program *prog)
  252. {
  253. if (!prog)
  254. return;
  255. if (prog->clear_priv)
  256. prog->clear_priv(prog, prog->priv);
  257. prog->priv = NULL;
  258. prog->clear_priv = NULL;
  259. bpf_program__unload(prog);
  260. zfree(&prog->name);
  261. zfree(&prog->section_name);
  262. zfree(&prog->insns);
  263. zfree(&prog->reloc_desc);
  264. prog->nr_reloc = 0;
  265. prog->insns_cnt = 0;
  266. prog->idx = -1;
  267. }
  268. static int
  269. bpf_program__init(void *data, size_t size, char *section_name, int idx,
  270. struct bpf_program *prog)
  271. {
  272. if (size < sizeof(struct bpf_insn)) {
  273. pr_warning("corrupted section '%s'\n", section_name);
  274. return -EINVAL;
  275. }
  276. bzero(prog, sizeof(*prog));
  277. prog->section_name = strdup(section_name);
  278. if (!prog->section_name) {
  279. pr_warning("failed to alloc name for prog under section(%d) %s\n",
  280. idx, section_name);
  281. goto errout;
  282. }
  283. prog->insns = malloc(size);
  284. if (!prog->insns) {
  285. pr_warning("failed to alloc insns for prog under section %s\n",
  286. section_name);
  287. goto errout;
  288. }
  289. prog->insns_cnt = size / sizeof(struct bpf_insn);
  290. memcpy(prog->insns, data,
  291. prog->insns_cnt * sizeof(struct bpf_insn));
  292. prog->idx = idx;
  293. prog->instances.fds = NULL;
  294. prog->instances.nr = -1;
  295. prog->type = BPF_PROG_TYPE_KPROBE;
  296. return 0;
  297. errout:
  298. bpf_program__exit(prog);
  299. return -ENOMEM;
  300. }
  301. static int
  302. bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
  303. char *section_name, int idx)
  304. {
  305. struct bpf_program prog, *progs;
  306. int nr_progs, err;
  307. err = bpf_program__init(data, size, section_name, idx, &prog);
  308. if (err)
  309. return err;
  310. progs = obj->programs;
  311. nr_progs = obj->nr_programs;
  312. progs = realloc(progs, sizeof(progs[0]) * (nr_progs + 1));
  313. if (!progs) {
  314. /*
  315. * In this case the original obj->programs
  316. * is still valid, so don't need special treat for
  317. * bpf_close_object().
  318. */
  319. pr_warning("failed to alloc a new program under section '%s'\n",
  320. section_name);
  321. bpf_program__exit(&prog);
  322. return -ENOMEM;
  323. }
  324. pr_debug("found program %s\n", prog.section_name);
  325. obj->programs = progs;
  326. obj->nr_programs = nr_progs + 1;
  327. prog.obj = obj;
  328. progs[nr_progs] = prog;
  329. return 0;
  330. }
  331. static int
  332. bpf_object__init_prog_names(struct bpf_object *obj)
  333. {
  334. Elf_Data *symbols = obj->efile.symbols;
  335. struct bpf_program *prog;
  336. size_t pi, si;
  337. for (pi = 0; pi < obj->nr_programs; pi++) {
  338. const char *name = NULL;
  339. prog = &obj->programs[pi];
  340. if (prog->idx == obj->efile.text_shndx) {
  341. name = ".text";
  342. goto skip_search;
  343. }
  344. for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
  345. si++) {
  346. GElf_Sym sym;
  347. if (!gelf_getsym(symbols, si, &sym))
  348. continue;
  349. if (sym.st_shndx != prog->idx)
  350. continue;
  351. if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
  352. continue;
  353. name = elf_strptr(obj->efile.elf,
  354. obj->efile.strtabidx,
  355. sym.st_name);
  356. if (!name) {
  357. pr_warning("failed to get sym name string for prog %s\n",
  358. prog->section_name);
  359. return -LIBBPF_ERRNO__LIBELF;
  360. }
  361. }
  362. if (!name) {
  363. pr_warning("failed to find sym for prog %s\n",
  364. prog->section_name);
  365. return -EINVAL;
  366. }
  367. skip_search:
  368. prog->name = strdup(name);
  369. if (!prog->name) {
  370. pr_warning("failed to allocate memory for prog sym %s\n",
  371. name);
  372. return -ENOMEM;
  373. }
  374. }
  375. return 0;
  376. }
  377. static struct bpf_object *bpf_object__new(const char *path,
  378. void *obj_buf,
  379. size_t obj_buf_sz)
  380. {
  381. struct bpf_object *obj;
  382. obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
  383. if (!obj) {
  384. pr_warning("alloc memory failed for %s\n", path);
  385. return ERR_PTR(-ENOMEM);
  386. }
  387. strcpy(obj->path, path);
  388. obj->efile.fd = -1;
  389. /*
  390. * Caller of this function should also calls
  391. * bpf_object__elf_finish() after data collection to return
  392. * obj_buf to user. If not, we should duplicate the buffer to
  393. * avoid user freeing them before elf finish.
  394. */
  395. obj->efile.obj_buf = obj_buf;
  396. obj->efile.obj_buf_sz = obj_buf_sz;
  397. obj->efile.maps_shndx = -1;
  398. obj->loaded = false;
  399. INIT_LIST_HEAD(&obj->list);
  400. list_add(&obj->list, &bpf_objects_list);
  401. return obj;
  402. }
  403. static void bpf_object__elf_finish(struct bpf_object *obj)
  404. {
  405. if (!obj_elf_valid(obj))
  406. return;
  407. if (obj->efile.elf) {
  408. elf_end(obj->efile.elf);
  409. obj->efile.elf = NULL;
  410. }
  411. obj->efile.symbols = NULL;
  412. zfree(&obj->efile.reloc);
  413. obj->efile.nr_reloc = 0;
  414. zclose(obj->efile.fd);
  415. obj->efile.obj_buf = NULL;
  416. obj->efile.obj_buf_sz = 0;
  417. }
  418. static int bpf_object__elf_init(struct bpf_object *obj)
  419. {
  420. int err = 0;
  421. GElf_Ehdr *ep;
  422. if (obj_elf_valid(obj)) {
  423. pr_warning("elf init: internal error\n");
  424. return -LIBBPF_ERRNO__LIBELF;
  425. }
  426. if (obj->efile.obj_buf_sz > 0) {
  427. /*
  428. * obj_buf should have been validated by
  429. * bpf_object__open_buffer().
  430. */
  431. obj->efile.elf = elf_memory(obj->efile.obj_buf,
  432. obj->efile.obj_buf_sz);
  433. } else {
  434. obj->efile.fd = open(obj->path, O_RDONLY);
  435. if (obj->efile.fd < 0) {
  436. pr_warning("failed to open %s: %s\n", obj->path,
  437. strerror(errno));
  438. return -errno;
  439. }
  440. obj->efile.elf = elf_begin(obj->efile.fd,
  441. LIBBPF_ELF_C_READ_MMAP,
  442. NULL);
  443. }
  444. if (!obj->efile.elf) {
  445. pr_warning("failed to open %s as ELF file\n",
  446. obj->path);
  447. err = -LIBBPF_ERRNO__LIBELF;
  448. goto errout;
  449. }
  450. if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
  451. pr_warning("failed to get EHDR from %s\n",
  452. obj->path);
  453. err = -LIBBPF_ERRNO__FORMAT;
  454. goto errout;
  455. }
  456. ep = &obj->efile.ehdr;
  457. /* Old LLVM set e_machine to EM_NONE */
  458. if ((ep->e_type != ET_REL) || (ep->e_machine && (ep->e_machine != EM_BPF))) {
  459. pr_warning("%s is not an eBPF object file\n",
  460. obj->path);
  461. err = -LIBBPF_ERRNO__FORMAT;
  462. goto errout;
  463. }
  464. return 0;
  465. errout:
  466. bpf_object__elf_finish(obj);
  467. return err;
  468. }
  469. static int
  470. bpf_object__check_endianness(struct bpf_object *obj)
  471. {
  472. static unsigned int const endian = 1;
  473. switch (obj->efile.ehdr.e_ident[EI_DATA]) {
  474. case ELFDATA2LSB:
  475. /* We are big endian, BPF obj is little endian. */
  476. if (*(unsigned char const *)&endian != 1)
  477. goto mismatch;
  478. break;
  479. case ELFDATA2MSB:
  480. /* We are little endian, BPF obj is big endian. */
  481. if (*(unsigned char const *)&endian != 0)
  482. goto mismatch;
  483. break;
  484. default:
  485. return -LIBBPF_ERRNO__ENDIAN;
  486. }
  487. return 0;
  488. mismatch:
  489. pr_warning("Error: endianness mismatch.\n");
  490. return -LIBBPF_ERRNO__ENDIAN;
  491. }
  492. static int
  493. bpf_object__init_license(struct bpf_object *obj,
  494. void *data, size_t size)
  495. {
  496. memcpy(obj->license, data,
  497. min(size, sizeof(obj->license) - 1));
  498. pr_debug("license of %s is %s\n", obj->path, obj->license);
  499. return 0;
  500. }
  501. static int
  502. bpf_object__init_kversion(struct bpf_object *obj,
  503. void *data, size_t size)
  504. {
  505. u32 kver;
  506. if (size != sizeof(kver)) {
  507. pr_warning("invalid kver section in %s\n", obj->path);
  508. return -LIBBPF_ERRNO__FORMAT;
  509. }
  510. memcpy(&kver, data, sizeof(kver));
  511. obj->kern_version = kver;
  512. pr_debug("kernel version of %s is %x\n", obj->path,
  513. obj->kern_version);
  514. return 0;
  515. }
  516. static int compare_bpf_map(const void *_a, const void *_b)
  517. {
  518. const struct bpf_map *a = _a;
  519. const struct bpf_map *b = _b;
  520. return a->offset - b->offset;
  521. }
  522. static int
  523. bpf_object__init_maps(struct bpf_object *obj)
  524. {
  525. int i, map_idx, map_def_sz, nr_maps = 0;
  526. Elf_Scn *scn;
  527. Elf_Data *data;
  528. Elf_Data *symbols = obj->efile.symbols;
  529. if (obj->efile.maps_shndx < 0)
  530. return -EINVAL;
  531. if (!symbols)
  532. return -EINVAL;
  533. scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
  534. if (scn)
  535. data = elf_getdata(scn, NULL);
  536. if (!scn || !data) {
  537. pr_warning("failed to get Elf_Data from map section %d\n",
  538. obj->efile.maps_shndx);
  539. return -EINVAL;
  540. }
  541. /*
  542. * Count number of maps. Each map has a name.
  543. * Array of maps is not supported: only the first element is
  544. * considered.
  545. *
  546. * TODO: Detect array of map and report error.
  547. */
  548. for (i = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
  549. GElf_Sym sym;
  550. if (!gelf_getsym(symbols, i, &sym))
  551. continue;
  552. if (sym.st_shndx != obj->efile.maps_shndx)
  553. continue;
  554. nr_maps++;
  555. }
  556. /* Alloc obj->maps and fill nr_maps. */
  557. pr_debug("maps in %s: %d maps in %zd bytes\n", obj->path,
  558. nr_maps, data->d_size);
  559. if (!nr_maps)
  560. return 0;
  561. /* Assume equally sized map definitions */
  562. map_def_sz = data->d_size / nr_maps;
  563. if (!data->d_size || (data->d_size % nr_maps) != 0) {
  564. pr_warning("unable to determine map definition size "
  565. "section %s, %d maps in %zd bytes\n",
  566. obj->path, nr_maps, data->d_size);
  567. return -EINVAL;
  568. }
  569. obj->maps = calloc(nr_maps, sizeof(obj->maps[0]));
  570. if (!obj->maps) {
  571. pr_warning("alloc maps for object failed\n");
  572. return -ENOMEM;
  573. }
  574. obj->nr_maps = nr_maps;
  575. /*
  576. * fill all fd with -1 so won't close incorrect
  577. * fd (fd=0 is stdin) when failure (zclose won't close
  578. * negative fd)).
  579. */
  580. for (i = 0; i < nr_maps; i++)
  581. obj->maps[i].fd = -1;
  582. /*
  583. * Fill obj->maps using data in "maps" section.
  584. */
  585. for (i = 0, map_idx = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
  586. GElf_Sym sym;
  587. const char *map_name;
  588. struct bpf_map_def *def;
  589. if (!gelf_getsym(symbols, i, &sym))
  590. continue;
  591. if (sym.st_shndx != obj->efile.maps_shndx)
  592. continue;
  593. map_name = elf_strptr(obj->efile.elf,
  594. obj->efile.strtabidx,
  595. sym.st_name);
  596. obj->maps[map_idx].offset = sym.st_value;
  597. if (sym.st_value + map_def_sz > data->d_size) {
  598. pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
  599. obj->path, map_name);
  600. return -EINVAL;
  601. }
  602. obj->maps[map_idx].name = strdup(map_name);
  603. if (!obj->maps[map_idx].name) {
  604. pr_warning("failed to alloc map name\n");
  605. return -ENOMEM;
  606. }
  607. pr_debug("map %d is \"%s\"\n", map_idx,
  608. obj->maps[map_idx].name);
  609. def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
  610. /*
  611. * If the definition of the map in the object file fits in
  612. * bpf_map_def, copy it. Any extra fields in our version
  613. * of bpf_map_def will default to zero as a result of the
  614. * calloc above.
  615. */
  616. if (map_def_sz <= sizeof(struct bpf_map_def)) {
  617. memcpy(&obj->maps[map_idx].def, def, map_def_sz);
  618. } else {
  619. /*
  620. * Here the map structure being read is bigger than what
  621. * we expect, truncate if the excess bits are all zero.
  622. * If they are not zero, reject this map as
  623. * incompatible.
  624. */
  625. char *b;
  626. for (b = ((char *)def) + sizeof(struct bpf_map_def);
  627. b < ((char *)def) + map_def_sz; b++) {
  628. if (*b != 0) {
  629. pr_warning("maps section in %s: \"%s\" "
  630. "has unrecognized, non-zero "
  631. "options\n",
  632. obj->path, map_name);
  633. return -EINVAL;
  634. }
  635. }
  636. memcpy(&obj->maps[map_idx].def, def,
  637. sizeof(struct bpf_map_def));
  638. }
  639. map_idx++;
  640. }
  641. qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]), compare_bpf_map);
  642. return 0;
  643. }
  644. static bool section_have_execinstr(struct bpf_object *obj, int idx)
  645. {
  646. Elf_Scn *scn;
  647. GElf_Shdr sh;
  648. scn = elf_getscn(obj->efile.elf, idx);
  649. if (!scn)
  650. return false;
  651. if (gelf_getshdr(scn, &sh) != &sh)
  652. return false;
  653. if (sh.sh_flags & SHF_EXECINSTR)
  654. return true;
  655. return false;
  656. }
  657. static int bpf_object__elf_collect(struct bpf_object *obj)
  658. {
  659. Elf *elf = obj->efile.elf;
  660. GElf_Ehdr *ep = &obj->efile.ehdr;
  661. Elf_Scn *scn = NULL;
  662. int idx = 0, err = 0;
  663. /* Elf is corrupted/truncated, avoid calling elf_strptr. */
  664. if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
  665. pr_warning("failed to get e_shstrndx from %s\n",
  666. obj->path);
  667. return -LIBBPF_ERRNO__FORMAT;
  668. }
  669. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  670. char *name;
  671. GElf_Shdr sh;
  672. Elf_Data *data;
  673. idx++;
  674. if (gelf_getshdr(scn, &sh) != &sh) {
  675. pr_warning("failed to get section(%d) header from %s\n",
  676. idx, obj->path);
  677. err = -LIBBPF_ERRNO__FORMAT;
  678. goto out;
  679. }
  680. name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
  681. if (!name) {
  682. pr_warning("failed to get section(%d) name from %s\n",
  683. idx, obj->path);
  684. err = -LIBBPF_ERRNO__FORMAT;
  685. goto out;
  686. }
  687. data = elf_getdata(scn, 0);
  688. if (!data) {
  689. pr_warning("failed to get section(%d) data from %s(%s)\n",
  690. idx, name, obj->path);
  691. err = -LIBBPF_ERRNO__FORMAT;
  692. goto out;
  693. }
  694. pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
  695. idx, name, (unsigned long)data->d_size,
  696. (int)sh.sh_link, (unsigned long)sh.sh_flags,
  697. (int)sh.sh_type);
  698. if (strcmp(name, "license") == 0)
  699. err = bpf_object__init_license(obj,
  700. data->d_buf,
  701. data->d_size);
  702. else if (strcmp(name, "version") == 0)
  703. err = bpf_object__init_kversion(obj,
  704. data->d_buf,
  705. data->d_size);
  706. else if (strcmp(name, "maps") == 0)
  707. obj->efile.maps_shndx = idx;
  708. else if (strcmp(name, BTF_ELF_SEC) == 0) {
  709. obj->btf = btf__new(data->d_buf, data->d_size,
  710. __pr_debug);
  711. if (IS_ERR(obj->btf)) {
  712. pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
  713. BTF_ELF_SEC, PTR_ERR(obj->btf));
  714. obj->btf = NULL;
  715. }
  716. } else if (sh.sh_type == SHT_SYMTAB) {
  717. if (obj->efile.symbols) {
  718. pr_warning("bpf: multiple SYMTAB in %s\n",
  719. obj->path);
  720. err = -LIBBPF_ERRNO__FORMAT;
  721. } else {
  722. obj->efile.symbols = data;
  723. obj->efile.strtabidx = sh.sh_link;
  724. }
  725. } else if ((sh.sh_type == SHT_PROGBITS) &&
  726. (sh.sh_flags & SHF_EXECINSTR) &&
  727. (data->d_size > 0)) {
  728. if (strcmp(name, ".text") == 0)
  729. obj->efile.text_shndx = idx;
  730. err = bpf_object__add_program(obj, data->d_buf,
  731. data->d_size, name, idx);
  732. if (err) {
  733. char errmsg[STRERR_BUFSIZE];
  734. strerror_r(-err, errmsg, sizeof(errmsg));
  735. pr_warning("failed to alloc program %s (%s): %s",
  736. name, obj->path, errmsg);
  737. }
  738. } else if (sh.sh_type == SHT_REL) {
  739. void *reloc = obj->efile.reloc;
  740. int nr_reloc = obj->efile.nr_reloc + 1;
  741. int sec = sh.sh_info; /* points to other section */
  742. /* Only do relo for section with exec instructions */
  743. if (!section_have_execinstr(obj, sec)) {
  744. pr_debug("skip relo %s(%d) for section(%d)\n",
  745. name, idx, sec);
  746. continue;
  747. }
  748. reloc = realloc(reloc,
  749. sizeof(*obj->efile.reloc) * nr_reloc);
  750. if (!reloc) {
  751. pr_warning("realloc failed\n");
  752. err = -ENOMEM;
  753. } else {
  754. int n = nr_reloc - 1;
  755. obj->efile.reloc = reloc;
  756. obj->efile.nr_reloc = nr_reloc;
  757. obj->efile.reloc[n].shdr = sh;
  758. obj->efile.reloc[n].data = data;
  759. }
  760. } else {
  761. pr_debug("skip section(%d) %s\n", idx, name);
  762. }
  763. if (err)
  764. goto out;
  765. }
  766. if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
  767. pr_warning("Corrupted ELF file: index of strtab invalid\n");
  768. return LIBBPF_ERRNO__FORMAT;
  769. }
  770. if (obj->efile.maps_shndx >= 0) {
  771. err = bpf_object__init_maps(obj);
  772. if (err)
  773. goto out;
  774. }
  775. err = bpf_object__init_prog_names(obj);
  776. out:
  777. return err;
  778. }
  779. static struct bpf_program *
  780. bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
  781. {
  782. struct bpf_program *prog;
  783. size_t i;
  784. for (i = 0; i < obj->nr_programs; i++) {
  785. prog = &obj->programs[i];
  786. if (prog->idx == idx)
  787. return prog;
  788. }
  789. return NULL;
  790. }
  791. static int
  792. bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
  793. Elf_Data *data, struct bpf_object *obj)
  794. {
  795. Elf_Data *symbols = obj->efile.symbols;
  796. int text_shndx = obj->efile.text_shndx;
  797. int maps_shndx = obj->efile.maps_shndx;
  798. struct bpf_map *maps = obj->maps;
  799. size_t nr_maps = obj->nr_maps;
  800. int i, nrels;
  801. pr_debug("collecting relocating info for: '%s'\n",
  802. prog->section_name);
  803. nrels = shdr->sh_size / shdr->sh_entsize;
  804. prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
  805. if (!prog->reloc_desc) {
  806. pr_warning("failed to alloc memory in relocation\n");
  807. return -ENOMEM;
  808. }
  809. prog->nr_reloc = nrels;
  810. for (i = 0; i < nrels; i++) {
  811. GElf_Sym sym;
  812. GElf_Rel rel;
  813. unsigned int insn_idx;
  814. struct bpf_insn *insns = prog->insns;
  815. size_t map_idx;
  816. if (!gelf_getrel(data, i, &rel)) {
  817. pr_warning("relocation: failed to get %d reloc\n", i);
  818. return -LIBBPF_ERRNO__FORMAT;
  819. }
  820. if (!gelf_getsym(symbols,
  821. GELF_R_SYM(rel.r_info),
  822. &sym)) {
  823. pr_warning("relocation: symbol %"PRIx64" not found\n",
  824. GELF_R_SYM(rel.r_info));
  825. return -LIBBPF_ERRNO__FORMAT;
  826. }
  827. pr_debug("relo for %lld value %lld name %d\n",
  828. (long long) (rel.r_info >> 32),
  829. (long long) sym.st_value, sym.st_name);
  830. if (sym.st_shndx != maps_shndx && sym.st_shndx != text_shndx) {
  831. pr_warning("Program '%s' contains non-map related relo data pointing to section %u\n",
  832. prog->section_name, sym.st_shndx);
  833. return -LIBBPF_ERRNO__RELOC;
  834. }
  835. insn_idx = rel.r_offset / sizeof(struct bpf_insn);
  836. pr_debug("relocation: insn_idx=%u\n", insn_idx);
  837. if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
  838. if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
  839. pr_warning("incorrect bpf_call opcode\n");
  840. return -LIBBPF_ERRNO__RELOC;
  841. }
  842. prog->reloc_desc[i].type = RELO_CALL;
  843. prog->reloc_desc[i].insn_idx = insn_idx;
  844. prog->reloc_desc[i].text_off = sym.st_value;
  845. continue;
  846. }
  847. if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
  848. pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
  849. insn_idx, insns[insn_idx].code);
  850. return -LIBBPF_ERRNO__RELOC;
  851. }
  852. /* TODO: 'maps' is sorted. We can use bsearch to make it faster. */
  853. for (map_idx = 0; map_idx < nr_maps; map_idx++) {
  854. if (maps[map_idx].offset == sym.st_value) {
  855. pr_debug("relocation: find map %zd (%s) for insn %u\n",
  856. map_idx, maps[map_idx].name, insn_idx);
  857. break;
  858. }
  859. }
  860. if (map_idx >= nr_maps) {
  861. pr_warning("bpf relocation: map_idx %d large than %d\n",
  862. (int)map_idx, (int)nr_maps - 1);
  863. return -LIBBPF_ERRNO__RELOC;
  864. }
  865. prog->reloc_desc[i].type = RELO_LD64;
  866. prog->reloc_desc[i].insn_idx = insn_idx;
  867. prog->reloc_desc[i].map_idx = map_idx;
  868. }
  869. return 0;
  870. }
  871. static int bpf_map_find_btf_info(struct bpf_map *map, const struct btf *btf)
  872. {
  873. struct bpf_map_def *def = &map->def;
  874. const size_t max_name = 256;
  875. int64_t key_size, value_size;
  876. int32_t key_id, value_id;
  877. char name[max_name];
  878. /* Find key type by name from BTF */
  879. if (snprintf(name, max_name, "%s_key", map->name) == max_name) {
  880. pr_warning("map:%s length of BTF key_type:%s_key is too long\n",
  881. map->name, map->name);
  882. return -EINVAL;
  883. }
  884. key_id = btf__find_by_name(btf, name);
  885. if (key_id < 0) {
  886. pr_debug("map:%s key_type:%s cannot be found in BTF\n",
  887. map->name, name);
  888. return key_id;
  889. }
  890. key_size = btf__resolve_size(btf, key_id);
  891. if (key_size < 0) {
  892. pr_warning("map:%s key_type:%s cannot get the BTF type_size\n",
  893. map->name, name);
  894. return key_size;
  895. }
  896. if (def->key_size != key_size) {
  897. pr_warning("map:%s key_type:%s has BTF type_size:%ld != key_size:%u\n",
  898. map->name, name, key_size, def->key_size);
  899. return -EINVAL;
  900. }
  901. /* Find value type from BTF */
  902. if (snprintf(name, max_name, "%s_value", map->name) == max_name) {
  903. pr_warning("map:%s length of BTF value_type:%s_value is too long\n",
  904. map->name, map->name);
  905. return -EINVAL;
  906. }
  907. value_id = btf__find_by_name(btf, name);
  908. if (value_id < 0) {
  909. pr_debug("map:%s value_type:%s cannot be found in BTF\n",
  910. map->name, name);
  911. return value_id;
  912. }
  913. value_size = btf__resolve_size(btf, value_id);
  914. if (value_size < 0) {
  915. pr_warning("map:%s value_type:%s cannot get the BTF type_size\n",
  916. map->name, name);
  917. return value_size;
  918. }
  919. if (def->value_size != value_size) {
  920. pr_warning("map:%s value_type:%s has BTF type_size:%ld != value_size:%u\n",
  921. map->name, name, value_size, def->value_size);
  922. return -EINVAL;
  923. }
  924. map->btf_key_id = key_id;
  925. map->btf_value_id = value_id;
  926. return 0;
  927. }
  928. static int
  929. bpf_object__create_maps(struct bpf_object *obj)
  930. {
  931. struct bpf_create_map_attr create_attr = {};
  932. unsigned int i;
  933. int err;
  934. for (i = 0; i < obj->nr_maps; i++) {
  935. struct bpf_map *map = &obj->maps[i];
  936. struct bpf_map_def *def = &map->def;
  937. int *pfd = &map->fd;
  938. create_attr.name = map->name;
  939. create_attr.map_ifindex = map->map_ifindex;
  940. create_attr.map_type = def->type;
  941. create_attr.map_flags = def->map_flags;
  942. create_attr.key_size = def->key_size;
  943. create_attr.value_size = def->value_size;
  944. create_attr.max_entries = def->max_entries;
  945. create_attr.btf_fd = 0;
  946. create_attr.btf_key_id = 0;
  947. create_attr.btf_value_id = 0;
  948. if (obj->btf && !bpf_map_find_btf_info(map, obj->btf)) {
  949. create_attr.btf_fd = btf__fd(obj->btf);
  950. create_attr.btf_key_id = map->btf_key_id;
  951. create_attr.btf_value_id = map->btf_value_id;
  952. }
  953. *pfd = bpf_create_map_xattr(&create_attr);
  954. if (*pfd < 0 && create_attr.btf_key_id) {
  955. pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
  956. map->name, strerror(errno), errno);
  957. create_attr.btf_fd = 0;
  958. create_attr.btf_key_id = 0;
  959. create_attr.btf_value_id = 0;
  960. map->btf_key_id = 0;
  961. map->btf_value_id = 0;
  962. *pfd = bpf_create_map_xattr(&create_attr);
  963. }
  964. if (*pfd < 0) {
  965. size_t j;
  966. err = *pfd;
  967. pr_warning("failed to create map (name: '%s'): %s\n",
  968. map->name,
  969. strerror(errno));
  970. for (j = 0; j < i; j++)
  971. zclose(obj->maps[j].fd);
  972. return err;
  973. }
  974. pr_debug("create map %s: fd=%d\n", map->name, *pfd);
  975. }
  976. return 0;
  977. }
  978. static int
  979. bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
  980. struct reloc_desc *relo)
  981. {
  982. struct bpf_insn *insn, *new_insn;
  983. struct bpf_program *text;
  984. size_t new_cnt;
  985. if (relo->type != RELO_CALL)
  986. return -LIBBPF_ERRNO__RELOC;
  987. if (prog->idx == obj->efile.text_shndx) {
  988. pr_warning("relo in .text insn %d into off %d\n",
  989. relo->insn_idx, relo->text_off);
  990. return -LIBBPF_ERRNO__RELOC;
  991. }
  992. if (prog->main_prog_cnt == 0) {
  993. text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
  994. if (!text) {
  995. pr_warning("no .text section found yet relo into text exist\n");
  996. return -LIBBPF_ERRNO__RELOC;
  997. }
  998. new_cnt = prog->insns_cnt + text->insns_cnt;
  999. new_insn = realloc(prog->insns, new_cnt * sizeof(*insn));
  1000. if (!new_insn) {
  1001. pr_warning("oom in prog realloc\n");
  1002. return -ENOMEM;
  1003. }
  1004. memcpy(new_insn + prog->insns_cnt, text->insns,
  1005. text->insns_cnt * sizeof(*insn));
  1006. prog->insns = new_insn;
  1007. prog->main_prog_cnt = prog->insns_cnt;
  1008. prog->insns_cnt = new_cnt;
  1009. pr_debug("added %zd insn from %s to prog %s\n",
  1010. text->insns_cnt, text->section_name,
  1011. prog->section_name);
  1012. }
  1013. insn = &prog->insns[relo->insn_idx];
  1014. insn->imm += prog->main_prog_cnt - relo->insn_idx;
  1015. return 0;
  1016. }
  1017. static int
  1018. bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
  1019. {
  1020. int i, err;
  1021. if (!prog || !prog->reloc_desc)
  1022. return 0;
  1023. for (i = 0; i < prog->nr_reloc; i++) {
  1024. if (prog->reloc_desc[i].type == RELO_LD64) {
  1025. struct bpf_insn *insns = prog->insns;
  1026. int insn_idx, map_idx;
  1027. insn_idx = prog->reloc_desc[i].insn_idx;
  1028. map_idx = prog->reloc_desc[i].map_idx;
  1029. if (insn_idx >= (int)prog->insns_cnt) {
  1030. pr_warning("relocation out of range: '%s'\n",
  1031. prog->section_name);
  1032. return -LIBBPF_ERRNO__RELOC;
  1033. }
  1034. insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
  1035. insns[insn_idx].imm = obj->maps[map_idx].fd;
  1036. } else {
  1037. err = bpf_program__reloc_text(prog, obj,
  1038. &prog->reloc_desc[i]);
  1039. if (err)
  1040. return err;
  1041. }
  1042. }
  1043. zfree(&prog->reloc_desc);
  1044. prog->nr_reloc = 0;
  1045. return 0;
  1046. }
  1047. static int
  1048. bpf_object__relocate(struct bpf_object *obj)
  1049. {
  1050. struct bpf_program *prog;
  1051. size_t i;
  1052. int err;
  1053. for (i = 0; i < obj->nr_programs; i++) {
  1054. prog = &obj->programs[i];
  1055. err = bpf_program__relocate(prog, obj);
  1056. if (err) {
  1057. pr_warning("failed to relocate '%s'\n",
  1058. prog->section_name);
  1059. return err;
  1060. }
  1061. }
  1062. return 0;
  1063. }
  1064. static int bpf_object__collect_reloc(struct bpf_object *obj)
  1065. {
  1066. int i, err;
  1067. if (!obj_elf_valid(obj)) {
  1068. pr_warning("Internal error: elf object is closed\n");
  1069. return -LIBBPF_ERRNO__INTERNAL;
  1070. }
  1071. for (i = 0; i < obj->efile.nr_reloc; i++) {
  1072. GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
  1073. Elf_Data *data = obj->efile.reloc[i].data;
  1074. int idx = shdr->sh_info;
  1075. struct bpf_program *prog;
  1076. if (shdr->sh_type != SHT_REL) {
  1077. pr_warning("internal error at %d\n", __LINE__);
  1078. return -LIBBPF_ERRNO__INTERNAL;
  1079. }
  1080. prog = bpf_object__find_prog_by_idx(obj, idx);
  1081. if (!prog) {
  1082. pr_warning("relocation failed: no section(%d)\n", idx);
  1083. return -LIBBPF_ERRNO__RELOC;
  1084. }
  1085. err = bpf_program__collect_reloc(prog,
  1086. shdr, data,
  1087. obj);
  1088. if (err)
  1089. return err;
  1090. }
  1091. return 0;
  1092. }
  1093. static int
  1094. load_program(enum bpf_prog_type type, enum bpf_attach_type expected_attach_type,
  1095. const char *name, struct bpf_insn *insns, int insns_cnt,
  1096. char *license, u32 kern_version, int *pfd, int prog_ifindex)
  1097. {
  1098. struct bpf_load_program_attr load_attr;
  1099. char *log_buf;
  1100. int ret;
  1101. memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
  1102. load_attr.prog_type = type;
  1103. load_attr.expected_attach_type = expected_attach_type;
  1104. load_attr.name = name;
  1105. load_attr.insns = insns;
  1106. load_attr.insns_cnt = insns_cnt;
  1107. load_attr.license = license;
  1108. load_attr.kern_version = kern_version;
  1109. load_attr.prog_ifindex = prog_ifindex;
  1110. if (!load_attr.insns || !load_attr.insns_cnt)
  1111. return -EINVAL;
  1112. log_buf = malloc(BPF_LOG_BUF_SIZE);
  1113. if (!log_buf)
  1114. pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
  1115. ret = bpf_load_program_xattr(&load_attr, log_buf, BPF_LOG_BUF_SIZE);
  1116. if (ret >= 0) {
  1117. *pfd = ret;
  1118. ret = 0;
  1119. goto out;
  1120. }
  1121. ret = -LIBBPF_ERRNO__LOAD;
  1122. pr_warning("load bpf program failed: %s\n", strerror(errno));
  1123. if (log_buf && log_buf[0] != '\0') {
  1124. ret = -LIBBPF_ERRNO__VERIFY;
  1125. pr_warning("-- BEGIN DUMP LOG ---\n");
  1126. pr_warning("\n%s\n", log_buf);
  1127. pr_warning("-- END LOG --\n");
  1128. } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
  1129. pr_warning("Program too large (%zu insns), at most %d insns\n",
  1130. load_attr.insns_cnt, BPF_MAXINSNS);
  1131. ret = -LIBBPF_ERRNO__PROG2BIG;
  1132. } else {
  1133. /* Wrong program type? */
  1134. if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
  1135. int fd;
  1136. load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
  1137. load_attr.expected_attach_type = 0;
  1138. fd = bpf_load_program_xattr(&load_attr, NULL, 0);
  1139. if (fd >= 0) {
  1140. close(fd);
  1141. ret = -LIBBPF_ERRNO__PROGTYPE;
  1142. goto out;
  1143. }
  1144. }
  1145. if (log_buf)
  1146. ret = -LIBBPF_ERRNO__KVER;
  1147. }
  1148. out:
  1149. free(log_buf);
  1150. return ret;
  1151. }
  1152. static int
  1153. bpf_program__load(struct bpf_program *prog,
  1154. char *license, u32 kern_version)
  1155. {
  1156. int err = 0, fd, i;
  1157. if (prog->instances.nr < 0 || !prog->instances.fds) {
  1158. if (prog->preprocessor) {
  1159. pr_warning("Internal error: can't load program '%s'\n",
  1160. prog->section_name);
  1161. return -LIBBPF_ERRNO__INTERNAL;
  1162. }
  1163. prog->instances.fds = malloc(sizeof(int));
  1164. if (!prog->instances.fds) {
  1165. pr_warning("Not enough memory for BPF fds\n");
  1166. return -ENOMEM;
  1167. }
  1168. prog->instances.nr = 1;
  1169. prog->instances.fds[0] = -1;
  1170. }
  1171. if (!prog->preprocessor) {
  1172. if (prog->instances.nr != 1) {
  1173. pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
  1174. prog->section_name, prog->instances.nr);
  1175. }
  1176. err = load_program(prog->type, prog->expected_attach_type,
  1177. prog->name, prog->insns, prog->insns_cnt,
  1178. license, kern_version, &fd,
  1179. prog->prog_ifindex);
  1180. if (!err)
  1181. prog->instances.fds[0] = fd;
  1182. goto out;
  1183. }
  1184. for (i = 0; i < prog->instances.nr; i++) {
  1185. struct bpf_prog_prep_result result;
  1186. bpf_program_prep_t preprocessor = prog->preprocessor;
  1187. bzero(&result, sizeof(result));
  1188. err = preprocessor(prog, i, prog->insns,
  1189. prog->insns_cnt, &result);
  1190. if (err) {
  1191. pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
  1192. i, prog->section_name);
  1193. goto out;
  1194. }
  1195. if (!result.new_insn_ptr || !result.new_insn_cnt) {
  1196. pr_debug("Skip loading the %dth instance of program '%s'\n",
  1197. i, prog->section_name);
  1198. prog->instances.fds[i] = -1;
  1199. if (result.pfd)
  1200. *result.pfd = -1;
  1201. continue;
  1202. }
  1203. err = load_program(prog->type, prog->expected_attach_type,
  1204. prog->name, result.new_insn_ptr,
  1205. result.new_insn_cnt,
  1206. license, kern_version, &fd,
  1207. prog->prog_ifindex);
  1208. if (err) {
  1209. pr_warning("Loading the %dth instance of program '%s' failed\n",
  1210. i, prog->section_name);
  1211. goto out;
  1212. }
  1213. if (result.pfd)
  1214. *result.pfd = fd;
  1215. prog->instances.fds[i] = fd;
  1216. }
  1217. out:
  1218. if (err)
  1219. pr_warning("failed to load program '%s'\n",
  1220. prog->section_name);
  1221. zfree(&prog->insns);
  1222. prog->insns_cnt = 0;
  1223. return err;
  1224. }
  1225. static int
  1226. bpf_object__load_progs(struct bpf_object *obj)
  1227. {
  1228. size_t i;
  1229. int err;
  1230. for (i = 0; i < obj->nr_programs; i++) {
  1231. if (obj->programs[i].idx == obj->efile.text_shndx)
  1232. continue;
  1233. err = bpf_program__load(&obj->programs[i],
  1234. obj->license,
  1235. obj->kern_version);
  1236. if (err)
  1237. return err;
  1238. }
  1239. return 0;
  1240. }
  1241. static bool bpf_prog_type__needs_kver(enum bpf_prog_type type)
  1242. {
  1243. switch (type) {
  1244. case BPF_PROG_TYPE_SOCKET_FILTER:
  1245. case BPF_PROG_TYPE_SCHED_CLS:
  1246. case BPF_PROG_TYPE_SCHED_ACT:
  1247. case BPF_PROG_TYPE_XDP:
  1248. case BPF_PROG_TYPE_CGROUP_SKB:
  1249. case BPF_PROG_TYPE_CGROUP_SOCK:
  1250. case BPF_PROG_TYPE_LWT_IN:
  1251. case BPF_PROG_TYPE_LWT_OUT:
  1252. case BPF_PROG_TYPE_LWT_XMIT:
  1253. case BPF_PROG_TYPE_SOCK_OPS:
  1254. case BPF_PROG_TYPE_SK_SKB:
  1255. case BPF_PROG_TYPE_CGROUP_DEVICE:
  1256. case BPF_PROG_TYPE_SK_MSG:
  1257. case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
  1258. return false;
  1259. case BPF_PROG_TYPE_UNSPEC:
  1260. case BPF_PROG_TYPE_KPROBE:
  1261. case BPF_PROG_TYPE_TRACEPOINT:
  1262. case BPF_PROG_TYPE_PERF_EVENT:
  1263. case BPF_PROG_TYPE_RAW_TRACEPOINT:
  1264. default:
  1265. return true;
  1266. }
  1267. }
  1268. static int bpf_object__validate(struct bpf_object *obj, bool needs_kver)
  1269. {
  1270. if (needs_kver && obj->kern_version == 0) {
  1271. pr_warning("%s doesn't provide kernel version\n",
  1272. obj->path);
  1273. return -LIBBPF_ERRNO__KVERSION;
  1274. }
  1275. return 0;
  1276. }
  1277. static struct bpf_object *
  1278. __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz,
  1279. bool needs_kver)
  1280. {
  1281. struct bpf_object *obj;
  1282. int err;
  1283. if (elf_version(EV_CURRENT) == EV_NONE) {
  1284. pr_warning("failed to init libelf for %s\n", path);
  1285. return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
  1286. }
  1287. obj = bpf_object__new(path, obj_buf, obj_buf_sz);
  1288. if (IS_ERR(obj))
  1289. return obj;
  1290. CHECK_ERR(bpf_object__elf_init(obj), err, out);
  1291. CHECK_ERR(bpf_object__check_endianness(obj), err, out);
  1292. CHECK_ERR(bpf_object__elf_collect(obj), err, out);
  1293. CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
  1294. CHECK_ERR(bpf_object__validate(obj, needs_kver), err, out);
  1295. bpf_object__elf_finish(obj);
  1296. return obj;
  1297. out:
  1298. bpf_object__close(obj);
  1299. return ERR_PTR(err);
  1300. }
  1301. struct bpf_object *bpf_object__open(const char *path)
  1302. {
  1303. /* param validation */
  1304. if (!path)
  1305. return NULL;
  1306. pr_debug("loading %s\n", path);
  1307. return __bpf_object__open(path, NULL, 0, true);
  1308. }
  1309. struct bpf_object *bpf_object__open_buffer(void *obj_buf,
  1310. size_t obj_buf_sz,
  1311. const char *name)
  1312. {
  1313. char tmp_name[64];
  1314. /* param validation */
  1315. if (!obj_buf || obj_buf_sz <= 0)
  1316. return NULL;
  1317. if (!name) {
  1318. snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
  1319. (unsigned long)obj_buf,
  1320. (unsigned long)obj_buf_sz);
  1321. tmp_name[sizeof(tmp_name) - 1] = '\0';
  1322. name = tmp_name;
  1323. }
  1324. pr_debug("loading object '%s' from buffer\n",
  1325. name);
  1326. return __bpf_object__open(name, obj_buf, obj_buf_sz, true);
  1327. }
  1328. int bpf_object__unload(struct bpf_object *obj)
  1329. {
  1330. size_t i;
  1331. if (!obj)
  1332. return -EINVAL;
  1333. for (i = 0; i < obj->nr_maps; i++)
  1334. zclose(obj->maps[i].fd);
  1335. for (i = 0; i < obj->nr_programs; i++)
  1336. bpf_program__unload(&obj->programs[i]);
  1337. return 0;
  1338. }
  1339. int bpf_object__load(struct bpf_object *obj)
  1340. {
  1341. int err;
  1342. if (!obj)
  1343. return -EINVAL;
  1344. if (obj->loaded) {
  1345. pr_warning("object should not be loaded twice\n");
  1346. return -EINVAL;
  1347. }
  1348. obj->loaded = true;
  1349. CHECK_ERR(bpf_object__create_maps(obj), err, out);
  1350. CHECK_ERR(bpf_object__relocate(obj), err, out);
  1351. CHECK_ERR(bpf_object__load_progs(obj), err, out);
  1352. return 0;
  1353. out:
  1354. bpf_object__unload(obj);
  1355. pr_warning("failed to load object '%s'\n", obj->path);
  1356. return err;
  1357. }
  1358. static int check_path(const char *path)
  1359. {
  1360. struct statfs st_fs;
  1361. char *dname, *dir;
  1362. int err = 0;
  1363. if (path == NULL)
  1364. return -EINVAL;
  1365. dname = strdup(path);
  1366. if (dname == NULL)
  1367. return -ENOMEM;
  1368. dir = dirname(dname);
  1369. if (statfs(dir, &st_fs)) {
  1370. pr_warning("failed to statfs %s: %s\n", dir, strerror(errno));
  1371. err = -errno;
  1372. }
  1373. free(dname);
  1374. if (!err && st_fs.f_type != BPF_FS_MAGIC) {
  1375. pr_warning("specified path %s is not on BPF FS\n", path);
  1376. err = -EINVAL;
  1377. }
  1378. return err;
  1379. }
  1380. int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
  1381. int instance)
  1382. {
  1383. int err;
  1384. err = check_path(path);
  1385. if (err)
  1386. return err;
  1387. if (prog == NULL) {
  1388. pr_warning("invalid program pointer\n");
  1389. return -EINVAL;
  1390. }
  1391. if (instance < 0 || instance >= prog->instances.nr) {
  1392. pr_warning("invalid prog instance %d of prog %s (max %d)\n",
  1393. instance, prog->section_name, prog->instances.nr);
  1394. return -EINVAL;
  1395. }
  1396. if (bpf_obj_pin(prog->instances.fds[instance], path)) {
  1397. pr_warning("failed to pin program: %s\n", strerror(errno));
  1398. return -errno;
  1399. }
  1400. pr_debug("pinned program '%s'\n", path);
  1401. return 0;
  1402. }
  1403. static int make_dir(const char *path)
  1404. {
  1405. int err = 0;
  1406. if (mkdir(path, 0700) && errno != EEXIST)
  1407. err = -errno;
  1408. if (err)
  1409. pr_warning("failed to mkdir %s: %s\n", path, strerror(-err));
  1410. return err;
  1411. }
  1412. int bpf_program__pin(struct bpf_program *prog, const char *path)
  1413. {
  1414. int i, err;
  1415. err = check_path(path);
  1416. if (err)
  1417. return err;
  1418. if (prog == NULL) {
  1419. pr_warning("invalid program pointer\n");
  1420. return -EINVAL;
  1421. }
  1422. if (prog->instances.nr <= 0) {
  1423. pr_warning("no instances of prog %s to pin\n",
  1424. prog->section_name);
  1425. return -EINVAL;
  1426. }
  1427. err = make_dir(path);
  1428. if (err)
  1429. return err;
  1430. for (i = 0; i < prog->instances.nr; i++) {
  1431. char buf[PATH_MAX];
  1432. int len;
  1433. len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
  1434. if (len < 0)
  1435. return -EINVAL;
  1436. else if (len >= PATH_MAX)
  1437. return -ENAMETOOLONG;
  1438. err = bpf_program__pin_instance(prog, buf, i);
  1439. if (err)
  1440. return err;
  1441. }
  1442. return 0;
  1443. }
  1444. int bpf_map__pin(struct bpf_map *map, const char *path)
  1445. {
  1446. int err;
  1447. err = check_path(path);
  1448. if (err)
  1449. return err;
  1450. if (map == NULL) {
  1451. pr_warning("invalid map pointer\n");
  1452. return -EINVAL;
  1453. }
  1454. if (bpf_obj_pin(map->fd, path)) {
  1455. pr_warning("failed to pin map: %s\n", strerror(errno));
  1456. return -errno;
  1457. }
  1458. pr_debug("pinned map '%s'\n", path);
  1459. return 0;
  1460. }
  1461. int bpf_object__pin(struct bpf_object *obj, const char *path)
  1462. {
  1463. struct bpf_program *prog;
  1464. struct bpf_map *map;
  1465. int err;
  1466. if (!obj)
  1467. return -ENOENT;
  1468. if (!obj->loaded) {
  1469. pr_warning("object not yet loaded; load it first\n");
  1470. return -ENOENT;
  1471. }
  1472. err = make_dir(path);
  1473. if (err)
  1474. return err;
  1475. bpf_map__for_each(map, obj) {
  1476. char buf[PATH_MAX];
  1477. int len;
  1478. len = snprintf(buf, PATH_MAX, "%s/%s", path,
  1479. bpf_map__name(map));
  1480. if (len < 0)
  1481. return -EINVAL;
  1482. else if (len >= PATH_MAX)
  1483. return -ENAMETOOLONG;
  1484. err = bpf_map__pin(map, buf);
  1485. if (err)
  1486. return err;
  1487. }
  1488. bpf_object__for_each_program(prog, obj) {
  1489. char buf[PATH_MAX];
  1490. int len;
  1491. len = snprintf(buf, PATH_MAX, "%s/%s", path,
  1492. prog->section_name);
  1493. if (len < 0)
  1494. return -EINVAL;
  1495. else if (len >= PATH_MAX)
  1496. return -ENAMETOOLONG;
  1497. err = bpf_program__pin(prog, buf);
  1498. if (err)
  1499. return err;
  1500. }
  1501. return 0;
  1502. }
  1503. void bpf_object__close(struct bpf_object *obj)
  1504. {
  1505. size_t i;
  1506. if (!obj)
  1507. return;
  1508. if (obj->clear_priv)
  1509. obj->clear_priv(obj, obj->priv);
  1510. bpf_object__elf_finish(obj);
  1511. bpf_object__unload(obj);
  1512. btf__free(obj->btf);
  1513. for (i = 0; i < obj->nr_maps; i++) {
  1514. zfree(&obj->maps[i].name);
  1515. if (obj->maps[i].clear_priv)
  1516. obj->maps[i].clear_priv(&obj->maps[i],
  1517. obj->maps[i].priv);
  1518. obj->maps[i].priv = NULL;
  1519. obj->maps[i].clear_priv = NULL;
  1520. }
  1521. zfree(&obj->maps);
  1522. obj->nr_maps = 0;
  1523. if (obj->programs && obj->nr_programs) {
  1524. for (i = 0; i < obj->nr_programs; i++)
  1525. bpf_program__exit(&obj->programs[i]);
  1526. }
  1527. zfree(&obj->programs);
  1528. list_del(&obj->list);
  1529. free(obj);
  1530. }
  1531. struct bpf_object *
  1532. bpf_object__next(struct bpf_object *prev)
  1533. {
  1534. struct bpf_object *next;
  1535. if (!prev)
  1536. next = list_first_entry(&bpf_objects_list,
  1537. struct bpf_object,
  1538. list);
  1539. else
  1540. next = list_next_entry(prev, list);
  1541. /* Empty list is noticed here so don't need checking on entry. */
  1542. if (&next->list == &bpf_objects_list)
  1543. return NULL;
  1544. return next;
  1545. }
  1546. const char *bpf_object__name(struct bpf_object *obj)
  1547. {
  1548. return obj ? obj->path : ERR_PTR(-EINVAL);
  1549. }
  1550. unsigned int bpf_object__kversion(struct bpf_object *obj)
  1551. {
  1552. return obj ? obj->kern_version : 0;
  1553. }
  1554. int bpf_object__btf_fd(const struct bpf_object *obj)
  1555. {
  1556. return obj->btf ? btf__fd(obj->btf) : -1;
  1557. }
  1558. int bpf_object__set_priv(struct bpf_object *obj, void *priv,
  1559. bpf_object_clear_priv_t clear_priv)
  1560. {
  1561. if (obj->priv && obj->clear_priv)
  1562. obj->clear_priv(obj, obj->priv);
  1563. obj->priv = priv;
  1564. obj->clear_priv = clear_priv;
  1565. return 0;
  1566. }
  1567. void *bpf_object__priv(struct bpf_object *obj)
  1568. {
  1569. return obj ? obj->priv : ERR_PTR(-EINVAL);
  1570. }
  1571. struct bpf_program *
  1572. bpf_program__next(struct bpf_program *prev, struct bpf_object *obj)
  1573. {
  1574. size_t idx;
  1575. if (!obj->programs)
  1576. return NULL;
  1577. /* First handler */
  1578. if (prev == NULL)
  1579. return &obj->programs[0];
  1580. if (prev->obj != obj) {
  1581. pr_warning("error: program handler doesn't match object\n");
  1582. return NULL;
  1583. }
  1584. idx = (prev - obj->programs) + 1;
  1585. if (idx >= obj->nr_programs)
  1586. return NULL;
  1587. return &obj->programs[idx];
  1588. }
  1589. int bpf_program__set_priv(struct bpf_program *prog, void *priv,
  1590. bpf_program_clear_priv_t clear_priv)
  1591. {
  1592. if (prog->priv && prog->clear_priv)
  1593. prog->clear_priv(prog, prog->priv);
  1594. prog->priv = priv;
  1595. prog->clear_priv = clear_priv;
  1596. return 0;
  1597. }
  1598. void *bpf_program__priv(struct bpf_program *prog)
  1599. {
  1600. return prog ? prog->priv : ERR_PTR(-EINVAL);
  1601. }
  1602. const char *bpf_program__title(struct bpf_program *prog, bool needs_copy)
  1603. {
  1604. const char *title;
  1605. title = prog->section_name;
  1606. if (needs_copy) {
  1607. title = strdup(title);
  1608. if (!title) {
  1609. pr_warning("failed to strdup program title\n");
  1610. return ERR_PTR(-ENOMEM);
  1611. }
  1612. }
  1613. return title;
  1614. }
  1615. int bpf_program__fd(struct bpf_program *prog)
  1616. {
  1617. return bpf_program__nth_fd(prog, 0);
  1618. }
  1619. int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
  1620. bpf_program_prep_t prep)
  1621. {
  1622. int *instances_fds;
  1623. if (nr_instances <= 0 || !prep)
  1624. return -EINVAL;
  1625. if (prog->instances.nr > 0 || prog->instances.fds) {
  1626. pr_warning("Can't set pre-processor after loading\n");
  1627. return -EINVAL;
  1628. }
  1629. instances_fds = malloc(sizeof(int) * nr_instances);
  1630. if (!instances_fds) {
  1631. pr_warning("alloc memory failed for fds\n");
  1632. return -ENOMEM;
  1633. }
  1634. /* fill all fd with -1 */
  1635. memset(instances_fds, -1, sizeof(int) * nr_instances);
  1636. prog->instances.nr = nr_instances;
  1637. prog->instances.fds = instances_fds;
  1638. prog->preprocessor = prep;
  1639. return 0;
  1640. }
  1641. int bpf_program__nth_fd(struct bpf_program *prog, int n)
  1642. {
  1643. int fd;
  1644. if (n >= prog->instances.nr || n < 0) {
  1645. pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
  1646. n, prog->section_name, prog->instances.nr);
  1647. return -EINVAL;
  1648. }
  1649. fd = prog->instances.fds[n];
  1650. if (fd < 0) {
  1651. pr_warning("%dth instance of program '%s' is invalid\n",
  1652. n, prog->section_name);
  1653. return -ENOENT;
  1654. }
  1655. return fd;
  1656. }
  1657. void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
  1658. {
  1659. prog->type = type;
  1660. }
  1661. static bool bpf_program__is_type(struct bpf_program *prog,
  1662. enum bpf_prog_type type)
  1663. {
  1664. return prog ? (prog->type == type) : false;
  1665. }
  1666. #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
  1667. int bpf_program__set_##NAME(struct bpf_program *prog) \
  1668. { \
  1669. if (!prog) \
  1670. return -EINVAL; \
  1671. bpf_program__set_type(prog, TYPE); \
  1672. return 0; \
  1673. } \
  1674. \
  1675. bool bpf_program__is_##NAME(struct bpf_program *prog) \
  1676. { \
  1677. return bpf_program__is_type(prog, TYPE); \
  1678. } \
  1679. BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
  1680. BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
  1681. BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
  1682. BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
  1683. BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
  1684. BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
  1685. BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
  1686. BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
  1687. void bpf_program__set_expected_attach_type(struct bpf_program *prog,
  1688. enum bpf_attach_type type)
  1689. {
  1690. prog->expected_attach_type = type;
  1691. }
  1692. #define BPF_PROG_SEC_FULL(string, ptype, atype) \
  1693. { string, sizeof(string) - 1, ptype, atype }
  1694. #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_FULL(string, ptype, 0)
  1695. #define BPF_S_PROG_SEC(string, ptype) \
  1696. BPF_PROG_SEC_FULL(string, BPF_PROG_TYPE_CGROUP_SOCK, ptype)
  1697. #define BPF_SA_PROG_SEC(string, ptype) \
  1698. BPF_PROG_SEC_FULL(string, BPF_PROG_TYPE_CGROUP_SOCK_ADDR, ptype)
  1699. static const struct {
  1700. const char *sec;
  1701. size_t len;
  1702. enum bpf_prog_type prog_type;
  1703. enum bpf_attach_type expected_attach_type;
  1704. } section_names[] = {
  1705. BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
  1706. BPF_PROG_SEC("kprobe/", BPF_PROG_TYPE_KPROBE),
  1707. BPF_PROG_SEC("kretprobe/", BPF_PROG_TYPE_KPROBE),
  1708. BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
  1709. BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
  1710. BPF_PROG_SEC("tracepoint/", BPF_PROG_TYPE_TRACEPOINT),
  1711. BPF_PROG_SEC("raw_tracepoint/", BPF_PROG_TYPE_RAW_TRACEPOINT),
  1712. BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
  1713. BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
  1714. BPF_PROG_SEC("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
  1715. BPF_PROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK),
  1716. BPF_PROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE),
  1717. BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
  1718. BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
  1719. BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
  1720. BPF_PROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS),
  1721. BPF_PROG_SEC("sk_skb", BPF_PROG_TYPE_SK_SKB),
  1722. BPF_PROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG),
  1723. BPF_SA_PROG_SEC("cgroup/bind4", BPF_CGROUP_INET4_BIND),
  1724. BPF_SA_PROG_SEC("cgroup/bind6", BPF_CGROUP_INET6_BIND),
  1725. BPF_SA_PROG_SEC("cgroup/connect4", BPF_CGROUP_INET4_CONNECT),
  1726. BPF_SA_PROG_SEC("cgroup/connect6", BPF_CGROUP_INET6_CONNECT),
  1727. BPF_S_PROG_SEC("cgroup/post_bind4", BPF_CGROUP_INET4_POST_BIND),
  1728. BPF_S_PROG_SEC("cgroup/post_bind6", BPF_CGROUP_INET6_POST_BIND),
  1729. };
  1730. #undef BPF_PROG_SEC
  1731. #undef BPF_PROG_SEC_FULL
  1732. #undef BPF_S_PROG_SEC
  1733. #undef BPF_SA_PROG_SEC
  1734. static int bpf_program__identify_section(struct bpf_program *prog)
  1735. {
  1736. int i;
  1737. if (!prog->section_name)
  1738. goto err;
  1739. for (i = 0; i < ARRAY_SIZE(section_names); i++)
  1740. if (strncmp(prog->section_name, section_names[i].sec,
  1741. section_names[i].len) == 0)
  1742. return i;
  1743. err:
  1744. pr_warning("failed to guess program type based on section name %s\n",
  1745. prog->section_name);
  1746. return -1;
  1747. }
  1748. int bpf_map__fd(struct bpf_map *map)
  1749. {
  1750. return map ? map->fd : -EINVAL;
  1751. }
  1752. const struct bpf_map_def *bpf_map__def(struct bpf_map *map)
  1753. {
  1754. return map ? &map->def : ERR_PTR(-EINVAL);
  1755. }
  1756. const char *bpf_map__name(struct bpf_map *map)
  1757. {
  1758. return map ? map->name : NULL;
  1759. }
  1760. uint32_t bpf_map__btf_key_id(const struct bpf_map *map)
  1761. {
  1762. return map ? map->btf_key_id : 0;
  1763. }
  1764. uint32_t bpf_map__btf_value_id(const struct bpf_map *map)
  1765. {
  1766. return map ? map->btf_value_id : 0;
  1767. }
  1768. int bpf_map__set_priv(struct bpf_map *map, void *priv,
  1769. bpf_map_clear_priv_t clear_priv)
  1770. {
  1771. if (!map)
  1772. return -EINVAL;
  1773. if (map->priv) {
  1774. if (map->clear_priv)
  1775. map->clear_priv(map, map->priv);
  1776. }
  1777. map->priv = priv;
  1778. map->clear_priv = clear_priv;
  1779. return 0;
  1780. }
  1781. void *bpf_map__priv(struct bpf_map *map)
  1782. {
  1783. return map ? map->priv : ERR_PTR(-EINVAL);
  1784. }
  1785. struct bpf_map *
  1786. bpf_map__next(struct bpf_map *prev, struct bpf_object *obj)
  1787. {
  1788. size_t idx;
  1789. struct bpf_map *s, *e;
  1790. if (!obj || !obj->maps)
  1791. return NULL;
  1792. s = obj->maps;
  1793. e = obj->maps + obj->nr_maps;
  1794. if (prev == NULL)
  1795. return s;
  1796. if ((prev < s) || (prev >= e)) {
  1797. pr_warning("error in %s: map handler doesn't belong to object\n",
  1798. __func__);
  1799. return NULL;
  1800. }
  1801. idx = (prev - obj->maps) + 1;
  1802. if (idx >= obj->nr_maps)
  1803. return NULL;
  1804. return &obj->maps[idx];
  1805. }
  1806. struct bpf_map *
  1807. bpf_object__find_map_by_name(struct bpf_object *obj, const char *name)
  1808. {
  1809. struct bpf_map *pos;
  1810. bpf_map__for_each(pos, obj) {
  1811. if (pos->name && !strcmp(pos->name, name))
  1812. return pos;
  1813. }
  1814. return NULL;
  1815. }
  1816. struct bpf_map *
  1817. bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
  1818. {
  1819. int i;
  1820. for (i = 0; i < obj->nr_maps; i++) {
  1821. if (obj->maps[i].offset == offset)
  1822. return &obj->maps[i];
  1823. }
  1824. return ERR_PTR(-ENOENT);
  1825. }
  1826. long libbpf_get_error(const void *ptr)
  1827. {
  1828. if (IS_ERR(ptr))
  1829. return PTR_ERR(ptr);
  1830. return 0;
  1831. }
  1832. int bpf_prog_load(const char *file, enum bpf_prog_type type,
  1833. struct bpf_object **pobj, int *prog_fd)
  1834. {
  1835. struct bpf_prog_load_attr attr;
  1836. memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
  1837. attr.file = file;
  1838. attr.prog_type = type;
  1839. attr.expected_attach_type = 0;
  1840. return bpf_prog_load_xattr(&attr, pobj, prog_fd);
  1841. }
  1842. int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
  1843. struct bpf_object **pobj, int *prog_fd)
  1844. {
  1845. struct bpf_program *prog, *first_prog = NULL;
  1846. enum bpf_attach_type expected_attach_type;
  1847. enum bpf_prog_type prog_type;
  1848. struct bpf_object *obj;
  1849. struct bpf_map *map;
  1850. int section_idx;
  1851. int err;
  1852. if (!attr)
  1853. return -EINVAL;
  1854. if (!attr->file)
  1855. return -EINVAL;
  1856. obj = __bpf_object__open(attr->file, NULL, 0,
  1857. bpf_prog_type__needs_kver(attr->prog_type));
  1858. if (IS_ERR(obj))
  1859. return -ENOENT;
  1860. bpf_object__for_each_program(prog, obj) {
  1861. /*
  1862. * If type is not specified, try to guess it based on
  1863. * section name.
  1864. */
  1865. prog_type = attr->prog_type;
  1866. prog->prog_ifindex = attr->ifindex;
  1867. expected_attach_type = attr->expected_attach_type;
  1868. if (prog_type == BPF_PROG_TYPE_UNSPEC) {
  1869. section_idx = bpf_program__identify_section(prog);
  1870. if (section_idx < 0) {
  1871. bpf_object__close(obj);
  1872. return -EINVAL;
  1873. }
  1874. prog_type = section_names[section_idx].prog_type;
  1875. expected_attach_type =
  1876. section_names[section_idx].expected_attach_type;
  1877. }
  1878. bpf_program__set_type(prog, prog_type);
  1879. bpf_program__set_expected_attach_type(prog,
  1880. expected_attach_type);
  1881. if (prog->idx != obj->efile.text_shndx && !first_prog)
  1882. first_prog = prog;
  1883. }
  1884. bpf_map__for_each(map, obj) {
  1885. map->map_ifindex = attr->ifindex;
  1886. }
  1887. if (!first_prog) {
  1888. pr_warning("object file doesn't contain bpf program\n");
  1889. bpf_object__close(obj);
  1890. return -ENOENT;
  1891. }
  1892. err = bpf_object__load(obj);
  1893. if (err) {
  1894. bpf_object__close(obj);
  1895. return -EINVAL;
  1896. }
  1897. *pobj = obj;
  1898. *prog_fd = bpf_program__fd(first_prog);
  1899. return 0;
  1900. }
  1901. enum bpf_perf_event_ret
  1902. bpf_perf_event_read_simple(void *mem, unsigned long size,
  1903. unsigned long page_size, void **buf, size_t *buf_len,
  1904. bpf_perf_event_print_t fn, void *priv)
  1905. {
  1906. volatile struct perf_event_mmap_page *header = mem;
  1907. __u64 data_tail = header->data_tail;
  1908. __u64 data_head = header->data_head;
  1909. void *base, *begin, *end;
  1910. int ret;
  1911. asm volatile("" ::: "memory"); /* in real code it should be smp_rmb() */
  1912. if (data_head == data_tail)
  1913. return LIBBPF_PERF_EVENT_CONT;
  1914. base = ((char *)header) + page_size;
  1915. begin = base + data_tail % size;
  1916. end = base + data_head % size;
  1917. while (begin != end) {
  1918. struct perf_event_header *ehdr;
  1919. ehdr = begin;
  1920. if (begin + ehdr->size > base + size) {
  1921. long len = base + size - begin;
  1922. if (*buf_len < ehdr->size) {
  1923. free(*buf);
  1924. *buf = malloc(ehdr->size);
  1925. if (!*buf) {
  1926. ret = LIBBPF_PERF_EVENT_ERROR;
  1927. break;
  1928. }
  1929. *buf_len = ehdr->size;
  1930. }
  1931. memcpy(*buf, begin, len);
  1932. memcpy(*buf + len, base, ehdr->size - len);
  1933. ehdr = (void *)*buf;
  1934. begin = base + ehdr->size - len;
  1935. } else if (begin + ehdr->size == base + size) {
  1936. begin = base;
  1937. } else {
  1938. begin += ehdr->size;
  1939. }
  1940. ret = fn(ehdr, priv);
  1941. if (ret != LIBBPF_PERF_EVENT_CONT)
  1942. break;
  1943. data_tail += ehdr->size;
  1944. }
  1945. __sync_synchronize(); /* smp_mb() */
  1946. header->data_tail = data_tail;
  1947. return ret;
  1948. }