libbpf.c 53 KB

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