libbpf.c 53 KB

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