libbpf.c 53 KB

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