gen.c 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340
  1. // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
  2. /* Copyright (C) 2019 Facebook */
  3. #ifndef _GNU_SOURCE
  4. #define _GNU_SOURCE
  5. #endif
  6. #include <ctype.h>
  7. #include <errno.h>
  8. #include <fcntl.h>
  9. #include <linux/err.h>
  10. #include <stdbool.h>
  11. #include <stdio.h>
  12. #include <string.h>
  13. #include <unistd.h>
  14. #include <bpf/bpf.h>
  15. #include <bpf/libbpf.h>
  16. #include <bpf/libbpf_internal.h>
  17. #include <sys/types.h>
  18. #include <sys/stat.h>
  19. #include <sys/mman.h>
  20. #include <bpf/btf.h>
  21. #include "json_writer.h"
  22. #include "main.h"
  23. #define MAX_OBJ_NAME_LEN 64
  24. static void sanitize_identifier(char *name)
  25. {
  26. int i;
  27. for (i = 0; name[i]; i++)
  28. if (!isalnum(name[i]) && name[i] != '_')
  29. name[i] = '_';
  30. }
  31. static bool str_has_prefix(const char *str, const char *prefix)
  32. {
  33. return strncmp(str, prefix, strlen(prefix)) == 0;
  34. }
  35. static bool str_has_suffix(const char *str, const char *suffix)
  36. {
  37. size_t i, n1 = strlen(str), n2 = strlen(suffix);
  38. if (n1 < n2)
  39. return false;
  40. for (i = 0; i < n2; i++) {
  41. if (str[n1 - i - 1] != suffix[n2 - i - 1])
  42. return false;
  43. }
  44. return true;
  45. }
  46. static void get_obj_name(char *name, const char *file)
  47. {
  48. /* Using basename() GNU version which doesn't modify arg. */
  49. strncpy(name, basename(file), MAX_OBJ_NAME_LEN - 1);
  50. name[MAX_OBJ_NAME_LEN - 1] = '\0';
  51. if (str_has_suffix(name, ".o"))
  52. name[strlen(name) - 2] = '\0';
  53. sanitize_identifier(name);
  54. }
  55. static void get_header_guard(char *guard, const char *obj_name, const char *suffix)
  56. {
  57. int i;
  58. sprintf(guard, "__%s_%s__", obj_name, suffix);
  59. for (i = 0; guard[i]; i++)
  60. guard[i] = toupper(guard[i]);
  61. }
  62. static bool get_map_ident(const struct bpf_map *map, char *buf, size_t buf_sz)
  63. {
  64. static const char *sfxs[] = { ".data", ".rodata", ".bss", ".kconfig" };
  65. const char *name = bpf_map__name(map);
  66. int i, n;
  67. if (!bpf_map__is_internal(map)) {
  68. snprintf(buf, buf_sz, "%s", name);
  69. return true;
  70. }
  71. for (i = 0, n = ARRAY_SIZE(sfxs); i < n; i++) {
  72. const char *sfx = sfxs[i], *p;
  73. p = strstr(name, sfx);
  74. if (p) {
  75. snprintf(buf, buf_sz, "%s", p + 1);
  76. sanitize_identifier(buf);
  77. return true;
  78. }
  79. }
  80. return false;
  81. }
  82. static bool get_datasec_ident(const char *sec_name, char *buf, size_t buf_sz)
  83. {
  84. static const char *pfxs[] = { ".data", ".rodata", ".bss", ".kconfig" };
  85. int i, n;
  86. for (i = 0, n = ARRAY_SIZE(pfxs); i < n; i++) {
  87. const char *pfx = pfxs[i];
  88. if (str_has_prefix(sec_name, pfx)) {
  89. snprintf(buf, buf_sz, "%s", sec_name + 1);
  90. sanitize_identifier(buf);
  91. return true;
  92. }
  93. }
  94. return false;
  95. }
  96. static void codegen_btf_dump_printf(void *ctx, const char *fmt, va_list args)
  97. {
  98. vprintf(fmt, args);
  99. }
  100. static int codegen_datasec_def(struct bpf_object *obj,
  101. struct btf *btf,
  102. struct btf_dump *d,
  103. const struct btf_type *sec,
  104. const char *obj_name)
  105. {
  106. const char *sec_name = btf__name_by_offset(btf, sec->name_off);
  107. const struct btf_var_secinfo *sec_var = btf_var_secinfos(sec);
  108. int i, err, off = 0, pad_cnt = 0, vlen = btf_vlen(sec);
  109. char var_ident[256], sec_ident[256];
  110. bool strip_mods = false;
  111. if (!get_datasec_ident(sec_name, sec_ident, sizeof(sec_ident)))
  112. return 0;
  113. if (strcmp(sec_name, ".kconfig") != 0)
  114. strip_mods = true;
  115. printf(" struct %s__%s {\n", obj_name, sec_ident);
  116. for (i = 0; i < vlen; i++, sec_var++) {
  117. const struct btf_type *var = btf__type_by_id(btf, sec_var->type);
  118. const char *var_name = btf__name_by_offset(btf, var->name_off);
  119. DECLARE_LIBBPF_OPTS(btf_dump_emit_type_decl_opts, opts,
  120. .field_name = var_ident,
  121. .indent_level = 2,
  122. .strip_mods = strip_mods,
  123. );
  124. int need_off = sec_var->offset, align_off, align;
  125. __u32 var_type_id = var->type;
  126. /* static variables are not exposed through BPF skeleton */
  127. if (btf_var(var)->linkage == BTF_VAR_STATIC)
  128. continue;
  129. if (off > need_off) {
  130. p_err("Something is wrong for %s's variable #%d: need offset %d, already at %d.\n",
  131. sec_name, i, need_off, off);
  132. return -EINVAL;
  133. }
  134. align = btf__align_of(btf, var->type);
  135. if (align <= 0) {
  136. p_err("Failed to determine alignment of variable '%s': %d",
  137. var_name, align);
  138. return -EINVAL;
  139. }
  140. /* Assume 32-bit architectures when generating data section
  141. * struct memory layout. Given bpftool can't know which target
  142. * host architecture it's emitting skeleton for, we need to be
  143. * conservative and assume 32-bit one to ensure enough padding
  144. * bytes are generated for pointer and long types. This will
  145. * still work correctly for 64-bit architectures, because in
  146. * the worst case we'll generate unnecessary padding field,
  147. * which on 64-bit architectures is not strictly necessary and
  148. * would be handled by natural 8-byte alignment. But it still
  149. * will be a correct memory layout, based on recorded offsets
  150. * in BTF.
  151. */
  152. if (align > 4)
  153. align = 4;
  154. align_off = (off + align - 1) / align * align;
  155. if (align_off != need_off) {
  156. printf("\t\tchar __pad%d[%d];\n",
  157. pad_cnt, need_off - off);
  158. pad_cnt++;
  159. }
  160. /* sanitize variable name, e.g., for static vars inside
  161. * a function, it's name is '<function name>.<variable name>',
  162. * which we'll turn into a '<function name>_<variable name>'
  163. */
  164. var_ident[0] = '\0';
  165. strncat(var_ident, var_name, sizeof(var_ident) - 1);
  166. sanitize_identifier(var_ident);
  167. printf("\t\t");
  168. err = btf_dump__emit_type_decl(d, var_type_id, &opts);
  169. if (err)
  170. return err;
  171. printf(";\n");
  172. off = sec_var->offset + sec_var->size;
  173. }
  174. printf(" } *%s;\n", sec_ident);
  175. return 0;
  176. }
  177. static const struct btf_type *find_type_for_map(struct btf *btf, const char *map_ident)
  178. {
  179. int n = btf__type_cnt(btf), i;
  180. char sec_ident[256];
  181. for (i = 1; i < n; i++) {
  182. const struct btf_type *t = btf__type_by_id(btf, i);
  183. const char *name;
  184. if (!btf_is_datasec(t))
  185. continue;
  186. name = btf__str_by_offset(btf, t->name_off);
  187. if (!get_datasec_ident(name, sec_ident, sizeof(sec_ident)))
  188. continue;
  189. if (strcmp(sec_ident, map_ident) == 0)
  190. return t;
  191. }
  192. return NULL;
  193. }
  194. static bool is_internal_mmapable_map(const struct bpf_map *map, char *buf, size_t sz)
  195. {
  196. if (!bpf_map__is_internal(map) || !(bpf_map__map_flags(map) & BPF_F_MMAPABLE))
  197. return false;
  198. if (!get_map_ident(map, buf, sz))
  199. return false;
  200. return true;
  201. }
  202. static int codegen_datasecs(struct bpf_object *obj, const char *obj_name)
  203. {
  204. struct btf *btf = bpf_object__btf(obj);
  205. struct btf_dump *d;
  206. struct bpf_map *map;
  207. const struct btf_type *sec;
  208. char map_ident[256];
  209. int err = 0;
  210. d = btf_dump__new(btf, codegen_btf_dump_printf, NULL, NULL);
  211. err = libbpf_get_error(d);
  212. if (err)
  213. return err;
  214. bpf_object__for_each_map(map, obj) {
  215. /* only generate definitions for memory-mapped internal maps */
  216. if (!is_internal_mmapable_map(map, map_ident, sizeof(map_ident)))
  217. continue;
  218. sec = find_type_for_map(btf, map_ident);
  219. /* In some cases (e.g., sections like .rodata.cst16 containing
  220. * compiler allocated string constants only) there will be
  221. * special internal maps with no corresponding DATASEC BTF
  222. * type. In such case, generate empty structs for each such
  223. * map. It will still be memory-mapped and its contents
  224. * accessible from user-space through BPF skeleton.
  225. */
  226. if (!sec) {
  227. printf(" struct %s__%s {\n", obj_name, map_ident);
  228. printf(" } *%s;\n", map_ident);
  229. } else {
  230. err = codegen_datasec_def(obj, btf, d, sec, obj_name);
  231. if (err)
  232. goto out;
  233. }
  234. }
  235. out:
  236. btf_dump__free(d);
  237. return err;
  238. }
  239. static bool btf_is_ptr_to_func_proto(const struct btf *btf,
  240. const struct btf_type *v)
  241. {
  242. return btf_is_ptr(v) && btf_is_func_proto(btf__type_by_id(btf, v->type));
  243. }
  244. static int codegen_subskel_datasecs(struct bpf_object *obj, const char *obj_name)
  245. {
  246. struct btf *btf = bpf_object__btf(obj);
  247. struct btf_dump *d;
  248. struct bpf_map *map;
  249. const struct btf_type *sec, *var;
  250. const struct btf_var_secinfo *sec_var;
  251. int i, err = 0, vlen;
  252. char map_ident[256], sec_ident[256];
  253. bool strip_mods = false, needs_typeof = false;
  254. const char *sec_name, *var_name;
  255. __u32 var_type_id;
  256. d = btf_dump__new(btf, codegen_btf_dump_printf, NULL, NULL);
  257. if (!d)
  258. return -errno;
  259. bpf_object__for_each_map(map, obj) {
  260. /* only generate definitions for memory-mapped internal maps */
  261. if (!is_internal_mmapable_map(map, map_ident, sizeof(map_ident)))
  262. continue;
  263. sec = find_type_for_map(btf, map_ident);
  264. if (!sec)
  265. continue;
  266. sec_name = btf__name_by_offset(btf, sec->name_off);
  267. if (!get_datasec_ident(sec_name, sec_ident, sizeof(sec_ident)))
  268. continue;
  269. strip_mods = strcmp(sec_name, ".kconfig") != 0;
  270. printf(" struct %s__%s {\n", obj_name, sec_ident);
  271. sec_var = btf_var_secinfos(sec);
  272. vlen = btf_vlen(sec);
  273. for (i = 0; i < vlen; i++, sec_var++) {
  274. DECLARE_LIBBPF_OPTS(btf_dump_emit_type_decl_opts, opts,
  275. .indent_level = 2,
  276. .strip_mods = strip_mods,
  277. /* we'll print the name separately */
  278. .field_name = "",
  279. );
  280. var = btf__type_by_id(btf, sec_var->type);
  281. var_name = btf__name_by_offset(btf, var->name_off);
  282. var_type_id = var->type;
  283. /* static variables are not exposed through BPF skeleton */
  284. if (btf_var(var)->linkage == BTF_VAR_STATIC)
  285. continue;
  286. /* The datasec member has KIND_VAR but we want the
  287. * underlying type of the variable (e.g. KIND_INT).
  288. */
  289. var = skip_mods_and_typedefs(btf, var->type, NULL);
  290. printf("\t\t");
  291. /* Func and array members require special handling.
  292. * Instead of producing `typename *var`, they produce
  293. * `typeof(typename) *var`. This allows us to keep a
  294. * similar syntax where the identifier is just prefixed
  295. * by *, allowing us to ignore C declaration minutiae.
  296. */
  297. needs_typeof = btf_is_array(var) || btf_is_ptr_to_func_proto(btf, var);
  298. if (needs_typeof)
  299. printf("typeof(");
  300. err = btf_dump__emit_type_decl(d, var_type_id, &opts);
  301. if (err)
  302. goto out;
  303. if (needs_typeof)
  304. printf(")");
  305. printf(" *%s;\n", var_name);
  306. }
  307. printf(" } %s;\n", sec_ident);
  308. }
  309. out:
  310. btf_dump__free(d);
  311. return err;
  312. }
  313. static void codegen(const char *template, ...)
  314. {
  315. const char *src, *end;
  316. int skip_tabs = 0, n;
  317. char *s, *dst;
  318. va_list args;
  319. char c;
  320. n = strlen(template);
  321. s = malloc(n + 1);
  322. if (!s)
  323. exit(-1);
  324. src = template;
  325. dst = s;
  326. /* find out "baseline" indentation to skip */
  327. while ((c = *src++)) {
  328. if (c == '\t') {
  329. skip_tabs++;
  330. } else if (c == '\n') {
  331. break;
  332. } else {
  333. p_err("unrecognized character at pos %td in template '%s': '%c'",
  334. src - template - 1, template, c);
  335. free(s);
  336. exit(-1);
  337. }
  338. }
  339. while (*src) {
  340. /* skip baseline indentation tabs */
  341. for (n = skip_tabs; n > 0; n--, src++) {
  342. if (*src != '\t') {
  343. p_err("not enough tabs at pos %td in template '%s'",
  344. src - template - 1, template);
  345. free(s);
  346. exit(-1);
  347. }
  348. }
  349. /* trim trailing whitespace */
  350. end = strchrnul(src, '\n');
  351. for (n = end - src; n > 0 && isspace(src[n - 1]); n--)
  352. ;
  353. memcpy(dst, src, n);
  354. dst += n;
  355. if (*end)
  356. *dst++ = '\n';
  357. src = *end ? end + 1 : end;
  358. }
  359. *dst++ = '\0';
  360. /* print out using adjusted template */
  361. va_start(args, template);
  362. n = vprintf(s, args);
  363. va_end(args);
  364. free(s);
  365. }
  366. static void print_hex(const char *data, int data_sz)
  367. {
  368. int i, len;
  369. for (i = 0, len = 0; i < data_sz; i++) {
  370. int w = data[i] ? 4 : 2;
  371. len += w;
  372. if (len > 78) {
  373. printf("\\\n");
  374. len = w;
  375. }
  376. if (!data[i])
  377. printf("\\0");
  378. else
  379. printf("\\x%02x", (unsigned char)data[i]);
  380. }
  381. }
  382. static size_t bpf_map_mmap_sz(const struct bpf_map *map)
  383. {
  384. long page_sz = sysconf(_SC_PAGE_SIZE);
  385. size_t map_sz;
  386. map_sz = (size_t)roundup(bpf_map__value_size(map), 8) * bpf_map__max_entries(map);
  387. map_sz = roundup(map_sz, page_sz);
  388. return map_sz;
  389. }
  390. /* Emit type size asserts for all top-level fields in memory-mapped internal maps. */
  391. static void codegen_asserts(struct bpf_object *obj, const char *obj_name)
  392. {
  393. struct btf *btf = bpf_object__btf(obj);
  394. struct bpf_map *map;
  395. struct btf_var_secinfo *sec_var;
  396. int i, vlen;
  397. const struct btf_type *sec;
  398. char map_ident[256], var_ident[256];
  399. if (!btf)
  400. return;
  401. codegen("\
  402. \n\
  403. __attribute__((unused)) static void \n\
  404. %1$s__assert(struct %1$s *s __attribute__((unused))) \n\
  405. { \n\
  406. #ifdef __cplusplus \n\
  407. #define _Static_assert static_assert \n\
  408. #endif \n\
  409. ", obj_name);
  410. bpf_object__for_each_map(map, obj) {
  411. if (!is_internal_mmapable_map(map, map_ident, sizeof(map_ident)))
  412. continue;
  413. sec = find_type_for_map(btf, map_ident);
  414. if (!sec) {
  415. /* best effort, couldn't find the type for this map */
  416. continue;
  417. }
  418. sec_var = btf_var_secinfos(sec);
  419. vlen = btf_vlen(sec);
  420. for (i = 0; i < vlen; i++, sec_var++) {
  421. const struct btf_type *var = btf__type_by_id(btf, sec_var->type);
  422. const char *var_name = btf__name_by_offset(btf, var->name_off);
  423. long var_size;
  424. /* static variables are not exposed through BPF skeleton */
  425. if (btf_var(var)->linkage == BTF_VAR_STATIC)
  426. continue;
  427. var_size = btf__resolve_size(btf, var->type);
  428. if (var_size < 0)
  429. continue;
  430. var_ident[0] = '\0';
  431. strncat(var_ident, var_name, sizeof(var_ident) - 1);
  432. sanitize_identifier(var_ident);
  433. printf("\t_Static_assert(sizeof(s->%s->%s) == %ld, \"unexpected size of '%s'\");\n",
  434. map_ident, var_ident, var_size, var_ident);
  435. }
  436. }
  437. codegen("\
  438. \n\
  439. #ifdef __cplusplus \n\
  440. #undef _Static_assert \n\
  441. #endif \n\
  442. } \n\
  443. ");
  444. }
  445. static void codegen_attach_detach(struct bpf_object *obj, const char *obj_name)
  446. {
  447. struct bpf_program *prog;
  448. bpf_object__for_each_program(prog, obj) {
  449. const char *tp_name;
  450. codegen("\
  451. \n\
  452. \n\
  453. static inline int \n\
  454. %1$s__%2$s__attach(struct %1$s *skel) \n\
  455. { \n\
  456. int prog_fd = skel->progs.%2$s.prog_fd; \n\
  457. ", obj_name, bpf_program__name(prog));
  458. switch (bpf_program__type(prog)) {
  459. case BPF_PROG_TYPE_RAW_TRACEPOINT:
  460. tp_name = strchr(bpf_program__section_name(prog), '/') + 1;
  461. printf("\tint fd = skel_raw_tracepoint_open(\"%s\", prog_fd);\n", tp_name);
  462. break;
  463. case BPF_PROG_TYPE_TRACING:
  464. case BPF_PROG_TYPE_LSM:
  465. if (bpf_program__expected_attach_type(prog) == BPF_TRACE_ITER)
  466. printf("\tint fd = skel_link_create(prog_fd, 0, BPF_TRACE_ITER);\n");
  467. else
  468. printf("\tint fd = skel_raw_tracepoint_open(NULL, prog_fd);\n");
  469. break;
  470. default:
  471. printf("\tint fd = ((void)prog_fd, 0); /* auto-attach not supported */\n");
  472. break;
  473. }
  474. codegen("\
  475. \n\
  476. \n\
  477. if (fd > 0) \n\
  478. skel->links.%1$s_fd = fd; \n\
  479. return fd; \n\
  480. } \n\
  481. ", bpf_program__name(prog));
  482. }
  483. codegen("\
  484. \n\
  485. \n\
  486. static inline int \n\
  487. %1$s__attach(struct %1$s *skel) \n\
  488. { \n\
  489. int ret = 0; \n\
  490. \n\
  491. ", obj_name);
  492. bpf_object__for_each_program(prog, obj) {
  493. codegen("\
  494. \n\
  495. ret = ret < 0 ? ret : %1$s__%2$s__attach(skel); \n\
  496. ", obj_name, bpf_program__name(prog));
  497. }
  498. codegen("\
  499. \n\
  500. return ret < 0 ? ret : 0; \n\
  501. } \n\
  502. \n\
  503. static inline void \n\
  504. %1$s__detach(struct %1$s *skel) \n\
  505. { \n\
  506. ", obj_name);
  507. bpf_object__for_each_program(prog, obj) {
  508. codegen("\
  509. \n\
  510. skel_closenz(skel->links.%1$s_fd); \n\
  511. ", bpf_program__name(prog));
  512. }
  513. codegen("\
  514. \n\
  515. } \n\
  516. ");
  517. }
  518. static void codegen_destroy(struct bpf_object *obj, const char *obj_name)
  519. {
  520. struct bpf_program *prog;
  521. struct bpf_map *map;
  522. char ident[256];
  523. codegen("\
  524. \n\
  525. static void \n\
  526. %1$s__destroy(struct %1$s *skel) \n\
  527. { \n\
  528. if (!skel) \n\
  529. return; \n\
  530. %1$s__detach(skel); \n\
  531. ",
  532. obj_name);
  533. bpf_object__for_each_program(prog, obj) {
  534. codegen("\
  535. \n\
  536. skel_closenz(skel->progs.%1$s.prog_fd); \n\
  537. ", bpf_program__name(prog));
  538. }
  539. bpf_object__for_each_map(map, obj) {
  540. if (!get_map_ident(map, ident, sizeof(ident)))
  541. continue;
  542. if (bpf_map__is_internal(map) &&
  543. (bpf_map__map_flags(map) & BPF_F_MMAPABLE))
  544. printf("\tskel_free_map_data(skel->%1$s, skel->maps.%1$s.initial_value, %2$zd);\n",
  545. ident, bpf_map_mmap_sz(map));
  546. codegen("\
  547. \n\
  548. skel_closenz(skel->maps.%1$s.map_fd); \n\
  549. ", ident);
  550. }
  551. codegen("\
  552. \n\
  553. skel_free(skel); \n\
  554. } \n\
  555. ",
  556. obj_name);
  557. }
  558. static int gen_trace(struct bpf_object *obj, const char *obj_name, const char *header_guard)
  559. {
  560. DECLARE_LIBBPF_OPTS(gen_loader_opts, opts);
  561. struct bpf_map *map;
  562. char ident[256];
  563. int err = 0;
  564. err = bpf_object__gen_loader(obj, &opts);
  565. if (err)
  566. return err;
  567. err = bpf_object__load(obj);
  568. if (err) {
  569. p_err("failed to load object file");
  570. goto out;
  571. }
  572. /* If there was no error during load then gen_loader_opts
  573. * are populated with the loader program.
  574. */
  575. /* finish generating 'struct skel' */
  576. codegen("\
  577. \n\
  578. }; \n\
  579. ", obj_name);
  580. codegen_attach_detach(obj, obj_name);
  581. codegen_destroy(obj, obj_name);
  582. codegen("\
  583. \n\
  584. static inline struct %1$s * \n\
  585. %1$s__open(void) \n\
  586. { \n\
  587. struct %1$s *skel; \n\
  588. \n\
  589. skel = skel_alloc(sizeof(*skel)); \n\
  590. if (!skel) \n\
  591. goto cleanup; \n\
  592. skel->ctx.sz = (void *)&skel->links - (void *)skel; \n\
  593. ",
  594. obj_name, opts.data_sz);
  595. bpf_object__for_each_map(map, obj) {
  596. const void *mmap_data = NULL;
  597. size_t mmap_size = 0;
  598. if (!is_internal_mmapable_map(map, ident, sizeof(ident)))
  599. continue;
  600. codegen("\
  601. \n\
  602. skel->%1$s = skel_prep_map_data((void *)\"\\ \n\
  603. ", ident);
  604. mmap_data = bpf_map__initial_value(map, &mmap_size);
  605. print_hex(mmap_data, mmap_size);
  606. codegen("\
  607. \n\
  608. \", %1$zd, %2$zd); \n\
  609. if (!skel->%3$s) \n\
  610. goto cleanup; \n\
  611. skel->maps.%3$s.initial_value = (__u64) (long) skel->%3$s;\n\
  612. ", bpf_map_mmap_sz(map), mmap_size, ident);
  613. }
  614. codegen("\
  615. \n\
  616. return skel; \n\
  617. cleanup: \n\
  618. %1$s__destroy(skel); \n\
  619. return NULL; \n\
  620. } \n\
  621. \n\
  622. static inline int \n\
  623. %1$s__load(struct %1$s *skel) \n\
  624. { \n\
  625. struct bpf_load_and_run_opts opts = {}; \n\
  626. int err; \n\
  627. \n\
  628. opts.ctx = (struct bpf_loader_ctx *)skel; \n\
  629. opts.data_sz = %2$d; \n\
  630. opts.data = (void *)\"\\ \n\
  631. ",
  632. obj_name, opts.data_sz);
  633. print_hex(opts.data, opts.data_sz);
  634. codegen("\
  635. \n\
  636. \"; \n\
  637. ");
  638. codegen("\
  639. \n\
  640. opts.insns_sz = %d; \n\
  641. opts.insns = (void *)\"\\ \n\
  642. ",
  643. opts.insns_sz);
  644. print_hex(opts.insns, opts.insns_sz);
  645. codegen("\
  646. \n\
  647. \"; \n\
  648. err = bpf_load_and_run(&opts); \n\
  649. if (err < 0) \n\
  650. return err; \n\
  651. ", obj_name);
  652. bpf_object__for_each_map(map, obj) {
  653. const char *mmap_flags;
  654. if (!is_internal_mmapable_map(map, ident, sizeof(ident)))
  655. continue;
  656. if (bpf_map__map_flags(map) & BPF_F_RDONLY_PROG)
  657. mmap_flags = "PROT_READ";
  658. else
  659. mmap_flags = "PROT_READ | PROT_WRITE";
  660. codegen("\
  661. \n\
  662. skel->%1$s = skel_finalize_map_data(&skel->maps.%1$s.initial_value, \n\
  663. %2$zd, %3$s, skel->maps.%1$s.map_fd);\n\
  664. if (!skel->%1$s) \n\
  665. return -ENOMEM; \n\
  666. ",
  667. ident, bpf_map_mmap_sz(map), mmap_flags);
  668. }
  669. codegen("\
  670. \n\
  671. return 0; \n\
  672. } \n\
  673. \n\
  674. static inline struct %1$s * \n\
  675. %1$s__open_and_load(void) \n\
  676. { \n\
  677. struct %1$s *skel; \n\
  678. \n\
  679. skel = %1$s__open(); \n\
  680. if (!skel) \n\
  681. return NULL; \n\
  682. if (%1$s__load(skel)) { \n\
  683. %1$s__destroy(skel); \n\
  684. return NULL; \n\
  685. } \n\
  686. return skel; \n\
  687. } \n\
  688. \n\
  689. ", obj_name);
  690. codegen_asserts(obj, obj_name);
  691. codegen("\
  692. \n\
  693. \n\
  694. #endif /* %s */ \n\
  695. ",
  696. header_guard);
  697. err = 0;
  698. out:
  699. return err;
  700. }
  701. static void
  702. codegen_maps_skeleton(struct bpf_object *obj, size_t map_cnt, bool mmaped)
  703. {
  704. struct bpf_map *map;
  705. char ident[256];
  706. size_t i;
  707. if (!map_cnt)
  708. return;
  709. codegen("\
  710. \n\
  711. \n\
  712. /* maps */ \n\
  713. s->map_cnt = %zu; \n\
  714. s->map_skel_sz = sizeof(*s->maps); \n\
  715. s->maps = (struct bpf_map_skeleton *)calloc(s->map_cnt, s->map_skel_sz);\n\
  716. if (!s->maps) { \n\
  717. err = -ENOMEM; \n\
  718. goto err; \n\
  719. } \n\
  720. ",
  721. map_cnt
  722. );
  723. i = 0;
  724. bpf_object__for_each_map(map, obj) {
  725. if (!get_map_ident(map, ident, sizeof(ident)))
  726. continue;
  727. codegen("\
  728. \n\
  729. \n\
  730. s->maps[%zu].name = \"%s\"; \n\
  731. s->maps[%zu].map = &obj->maps.%s; \n\
  732. ",
  733. i, bpf_map__name(map), i, ident);
  734. /* memory-mapped internal maps */
  735. if (mmaped && is_internal_mmapable_map(map, ident, sizeof(ident))) {
  736. printf("\ts->maps[%zu].mmaped = (void **)&obj->%s;\n",
  737. i, ident);
  738. }
  739. i++;
  740. }
  741. }
  742. static void
  743. codegen_progs_skeleton(struct bpf_object *obj, size_t prog_cnt, bool populate_links)
  744. {
  745. struct bpf_program *prog;
  746. int i;
  747. if (!prog_cnt)
  748. return;
  749. codegen("\
  750. \n\
  751. \n\
  752. /* programs */ \n\
  753. s->prog_cnt = %zu; \n\
  754. s->prog_skel_sz = sizeof(*s->progs); \n\
  755. s->progs = (struct bpf_prog_skeleton *)calloc(s->prog_cnt, s->prog_skel_sz);\n\
  756. if (!s->progs) { \n\
  757. err = -ENOMEM; \n\
  758. goto err; \n\
  759. } \n\
  760. ",
  761. prog_cnt
  762. );
  763. i = 0;
  764. bpf_object__for_each_program(prog, obj) {
  765. codegen("\
  766. \n\
  767. \n\
  768. s->progs[%1$zu].name = \"%2$s\"; \n\
  769. s->progs[%1$zu].prog = &obj->progs.%2$s;\n\
  770. ",
  771. i, bpf_program__name(prog));
  772. if (populate_links) {
  773. codegen("\
  774. \n\
  775. s->progs[%1$zu].link = &obj->links.%2$s;\n\
  776. ",
  777. i, bpf_program__name(prog));
  778. }
  779. i++;
  780. }
  781. }
  782. static int do_skeleton(int argc, char **argv)
  783. {
  784. char header_guard[MAX_OBJ_NAME_LEN + sizeof("__SKEL_H__")];
  785. size_t map_cnt = 0, prog_cnt = 0, file_sz, mmap_sz;
  786. DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts);
  787. char obj_name[MAX_OBJ_NAME_LEN] = "", *obj_data;
  788. struct bpf_object *obj = NULL;
  789. const char *file;
  790. char ident[256];
  791. struct bpf_program *prog;
  792. int fd, err = -1;
  793. struct bpf_map *map;
  794. struct btf *btf;
  795. struct stat st;
  796. if (!REQ_ARGS(1)) {
  797. usage();
  798. return -1;
  799. }
  800. file = GET_ARG();
  801. while (argc) {
  802. if (!REQ_ARGS(2))
  803. return -1;
  804. if (is_prefix(*argv, "name")) {
  805. NEXT_ARG();
  806. if (obj_name[0] != '\0') {
  807. p_err("object name already specified");
  808. return -1;
  809. }
  810. strncpy(obj_name, *argv, MAX_OBJ_NAME_LEN - 1);
  811. obj_name[MAX_OBJ_NAME_LEN - 1] = '\0';
  812. } else {
  813. p_err("unknown arg %s", *argv);
  814. return -1;
  815. }
  816. NEXT_ARG();
  817. }
  818. if (argc) {
  819. p_err("extra unknown arguments");
  820. return -1;
  821. }
  822. if (stat(file, &st)) {
  823. p_err("failed to stat() %s: %s", file, strerror(errno));
  824. return -1;
  825. }
  826. file_sz = st.st_size;
  827. mmap_sz = roundup(file_sz, sysconf(_SC_PAGE_SIZE));
  828. fd = open(file, O_RDONLY);
  829. if (fd < 0) {
  830. p_err("failed to open() %s: %s", file, strerror(errno));
  831. return -1;
  832. }
  833. obj_data = mmap(NULL, mmap_sz, PROT_READ, MAP_PRIVATE, fd, 0);
  834. if (obj_data == MAP_FAILED) {
  835. obj_data = NULL;
  836. p_err("failed to mmap() %s: %s", file, strerror(errno));
  837. goto out;
  838. }
  839. if (obj_name[0] == '\0')
  840. get_obj_name(obj_name, file);
  841. opts.object_name = obj_name;
  842. if (verifier_logs)
  843. /* log_level1 + log_level2 + stats, but not stable UAPI */
  844. opts.kernel_log_level = 1 + 2 + 4;
  845. obj = bpf_object__open_mem(obj_data, file_sz, &opts);
  846. err = libbpf_get_error(obj);
  847. if (err) {
  848. char err_buf[256];
  849. libbpf_strerror(err, err_buf, sizeof(err_buf));
  850. p_err("failed to open BPF object file: %s", err_buf);
  851. obj = NULL;
  852. goto out;
  853. }
  854. bpf_object__for_each_map(map, obj) {
  855. if (!get_map_ident(map, ident, sizeof(ident))) {
  856. p_err("ignoring unrecognized internal map '%s'...",
  857. bpf_map__name(map));
  858. continue;
  859. }
  860. map_cnt++;
  861. }
  862. bpf_object__for_each_program(prog, obj) {
  863. prog_cnt++;
  864. }
  865. get_header_guard(header_guard, obj_name, "SKEL_H");
  866. if (use_loader) {
  867. codegen("\
  868. \n\
  869. /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ \n\
  870. /* THIS FILE IS AUTOGENERATED BY BPFTOOL! */ \n\
  871. #ifndef %2$s \n\
  872. #define %2$s \n\
  873. \n\
  874. #include <bpf/skel_internal.h> \n\
  875. \n\
  876. struct %1$s { \n\
  877. struct bpf_loader_ctx ctx; \n\
  878. ",
  879. obj_name, header_guard
  880. );
  881. } else {
  882. codegen("\
  883. \n\
  884. /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ \n\
  885. \n\
  886. /* THIS FILE IS AUTOGENERATED BY BPFTOOL! */ \n\
  887. #ifndef %2$s \n\
  888. #define %2$s \n\
  889. \n\
  890. #include <errno.h> \n\
  891. #include <stdlib.h> \n\
  892. #include <bpf/libbpf.h> \n\
  893. \n\
  894. struct %1$s { \n\
  895. struct bpf_object_skeleton *skeleton; \n\
  896. struct bpf_object *obj; \n\
  897. ",
  898. obj_name, header_guard
  899. );
  900. }
  901. if (map_cnt) {
  902. printf("\tstruct {\n");
  903. bpf_object__for_each_map(map, obj) {
  904. if (!get_map_ident(map, ident, sizeof(ident)))
  905. continue;
  906. if (use_loader)
  907. printf("\t\tstruct bpf_map_desc %s;\n", ident);
  908. else
  909. printf("\t\tstruct bpf_map *%s;\n", ident);
  910. }
  911. printf("\t} maps;\n");
  912. }
  913. if (prog_cnt) {
  914. printf("\tstruct {\n");
  915. bpf_object__for_each_program(prog, obj) {
  916. if (use_loader)
  917. printf("\t\tstruct bpf_prog_desc %s;\n",
  918. bpf_program__name(prog));
  919. else
  920. printf("\t\tstruct bpf_program *%s;\n",
  921. bpf_program__name(prog));
  922. }
  923. printf("\t} progs;\n");
  924. printf("\tstruct {\n");
  925. bpf_object__for_each_program(prog, obj) {
  926. if (use_loader)
  927. printf("\t\tint %s_fd;\n",
  928. bpf_program__name(prog));
  929. else
  930. printf("\t\tstruct bpf_link *%s;\n",
  931. bpf_program__name(prog));
  932. }
  933. printf("\t} links;\n");
  934. }
  935. btf = bpf_object__btf(obj);
  936. if (btf) {
  937. err = codegen_datasecs(obj, obj_name);
  938. if (err)
  939. goto out;
  940. }
  941. if (use_loader) {
  942. err = gen_trace(obj, obj_name, header_guard);
  943. goto out;
  944. }
  945. codegen("\
  946. \n\
  947. \n\
  948. #ifdef __cplusplus \n\
  949. static inline struct %1$s *open(const struct bpf_object_open_opts *opts = nullptr);\n\
  950. static inline struct %1$s *open_and_load(); \n\
  951. static inline int load(struct %1$s *skel); \n\
  952. static inline int attach(struct %1$s *skel); \n\
  953. static inline void detach(struct %1$s *skel); \n\
  954. static inline void destroy(struct %1$s *skel); \n\
  955. static inline const void *elf_bytes(size_t *sz); \n\
  956. #endif /* __cplusplus */ \n\
  957. }; \n\
  958. \n\
  959. static void \n\
  960. %1$s__destroy(struct %1$s *obj) \n\
  961. { \n\
  962. if (!obj) \n\
  963. return; \n\
  964. if (obj->skeleton) \n\
  965. bpf_object__destroy_skeleton(obj->skeleton);\n\
  966. free(obj); \n\
  967. } \n\
  968. \n\
  969. static inline int \n\
  970. %1$s__create_skeleton(struct %1$s *obj); \n\
  971. \n\
  972. static inline struct %1$s * \n\
  973. %1$s__open_opts(const struct bpf_object_open_opts *opts) \n\
  974. { \n\
  975. struct %1$s *obj; \n\
  976. int err; \n\
  977. \n\
  978. obj = (struct %1$s *)calloc(1, sizeof(*obj)); \n\
  979. if (!obj) { \n\
  980. errno = ENOMEM; \n\
  981. return NULL; \n\
  982. } \n\
  983. \n\
  984. err = %1$s__create_skeleton(obj); \n\
  985. if (err) \n\
  986. goto err_out; \n\
  987. \n\
  988. err = bpf_object__open_skeleton(obj->skeleton, opts);\n\
  989. if (err) \n\
  990. goto err_out; \n\
  991. \n\
  992. return obj; \n\
  993. err_out: \n\
  994. %1$s__destroy(obj); \n\
  995. errno = -err; \n\
  996. return NULL; \n\
  997. } \n\
  998. \n\
  999. static inline struct %1$s * \n\
  1000. %1$s__open(void) \n\
  1001. { \n\
  1002. return %1$s__open_opts(NULL); \n\
  1003. } \n\
  1004. \n\
  1005. static inline int \n\
  1006. %1$s__load(struct %1$s *obj) \n\
  1007. { \n\
  1008. return bpf_object__load_skeleton(obj->skeleton); \n\
  1009. } \n\
  1010. \n\
  1011. static inline struct %1$s * \n\
  1012. %1$s__open_and_load(void) \n\
  1013. { \n\
  1014. struct %1$s *obj; \n\
  1015. int err; \n\
  1016. \n\
  1017. obj = %1$s__open(); \n\
  1018. if (!obj) \n\
  1019. return NULL; \n\
  1020. err = %1$s__load(obj); \n\
  1021. if (err) { \n\
  1022. %1$s__destroy(obj); \n\
  1023. errno = -err; \n\
  1024. return NULL; \n\
  1025. } \n\
  1026. return obj; \n\
  1027. } \n\
  1028. \n\
  1029. static inline int \n\
  1030. %1$s__attach(struct %1$s *obj) \n\
  1031. { \n\
  1032. return bpf_object__attach_skeleton(obj->skeleton); \n\
  1033. } \n\
  1034. \n\
  1035. static inline void \n\
  1036. %1$s__detach(struct %1$s *obj) \n\
  1037. { \n\
  1038. bpf_object__detach_skeleton(obj->skeleton); \n\
  1039. } \n\
  1040. ",
  1041. obj_name
  1042. );
  1043. codegen("\
  1044. \n\
  1045. \n\
  1046. static inline const void *%1$s__elf_bytes(size_t *sz); \n\
  1047. \n\
  1048. static inline int \n\
  1049. %1$s__create_skeleton(struct %1$s *obj) \n\
  1050. { \n\
  1051. struct bpf_object_skeleton *s; \n\
  1052. int err; \n\
  1053. \n\
  1054. s = (struct bpf_object_skeleton *)calloc(1, sizeof(*s));\n\
  1055. if (!s) { \n\
  1056. err = -ENOMEM; \n\
  1057. goto err; \n\
  1058. } \n\
  1059. \n\
  1060. s->sz = sizeof(*s); \n\
  1061. s->name = \"%1$s\"; \n\
  1062. s->obj = &obj->obj; \n\
  1063. ",
  1064. obj_name
  1065. );
  1066. codegen_maps_skeleton(obj, map_cnt, true /*mmaped*/);
  1067. codegen_progs_skeleton(obj, prog_cnt, true /*populate_links*/);
  1068. codegen("\
  1069. \n\
  1070. \n\
  1071. s->data = (void *)%2$s__elf_bytes(&s->data_sz); \n\
  1072. \n\
  1073. obj->skeleton = s; \n\
  1074. return 0; \n\
  1075. err: \n\
  1076. bpf_object__destroy_skeleton(s); \n\
  1077. return err; \n\
  1078. } \n\
  1079. \n\
  1080. static inline const void *%2$s__elf_bytes(size_t *sz) \n\
  1081. { \n\
  1082. *sz = %1$d; \n\
  1083. return (const void *)\"\\ \n\
  1084. "
  1085. , file_sz, obj_name);
  1086. /* embed contents of BPF object file */
  1087. print_hex(obj_data, file_sz);
  1088. codegen("\
  1089. \n\
  1090. \"; \n\
  1091. } \n\
  1092. \n\
  1093. #ifdef __cplusplus \n\
  1094. struct %1$s *%1$s::open(const struct bpf_object_open_opts *opts) { return %1$s__open_opts(opts); }\n\
  1095. struct %1$s *%1$s::open_and_load() { return %1$s__open_and_load(); } \n\
  1096. int %1$s::load(struct %1$s *skel) { return %1$s__load(skel); } \n\
  1097. int %1$s::attach(struct %1$s *skel) { return %1$s__attach(skel); } \n\
  1098. void %1$s::detach(struct %1$s *skel) { %1$s__detach(skel); } \n\
  1099. void %1$s::destroy(struct %1$s *skel) { %1$s__destroy(skel); } \n\
  1100. const void *%1$s::elf_bytes(size_t *sz) { return %1$s__elf_bytes(sz); } \n\
  1101. #endif /* __cplusplus */ \n\
  1102. \n\
  1103. ",
  1104. obj_name);
  1105. codegen_asserts(obj, obj_name);
  1106. codegen("\
  1107. \n\
  1108. \n\
  1109. #endif /* %1$s */ \n\
  1110. ",
  1111. header_guard);
  1112. err = 0;
  1113. out:
  1114. bpf_object__close(obj);
  1115. if (obj_data)
  1116. munmap(obj_data, mmap_sz);
  1117. close(fd);
  1118. return err;
  1119. }
  1120. /* Subskeletons are like skeletons, except they don't own the bpf_object,
  1121. * associated maps, links, etc. Instead, they know about the existence of
  1122. * variables, maps, programs and are able to find their locations
  1123. * _at runtime_ from an already loaded bpf_object.
  1124. *
  1125. * This allows for library-like BPF objects to have userspace counterparts
  1126. * with access to their own items without having to know anything about the
  1127. * final BPF object that the library was linked into.
  1128. */
  1129. static int do_subskeleton(int argc, char **argv)
  1130. {
  1131. char header_guard[MAX_OBJ_NAME_LEN + sizeof("__SUBSKEL_H__")];
  1132. size_t i, len, file_sz, map_cnt = 0, prog_cnt = 0, mmap_sz, var_cnt = 0, var_idx = 0;
  1133. DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts);
  1134. char obj_name[MAX_OBJ_NAME_LEN] = "", *obj_data;
  1135. struct bpf_object *obj = NULL;
  1136. const char *file, *var_name;
  1137. char ident[256];
  1138. int fd, err = -1, map_type_id;
  1139. const struct bpf_map *map;
  1140. struct bpf_program *prog;
  1141. struct btf *btf;
  1142. const struct btf_type *map_type, *var_type;
  1143. const struct btf_var_secinfo *var;
  1144. struct stat st;
  1145. if (!REQ_ARGS(1)) {
  1146. usage();
  1147. return -1;
  1148. }
  1149. file = GET_ARG();
  1150. while (argc) {
  1151. if (!REQ_ARGS(2))
  1152. return -1;
  1153. if (is_prefix(*argv, "name")) {
  1154. NEXT_ARG();
  1155. if (obj_name[0] != '\0') {
  1156. p_err("object name already specified");
  1157. return -1;
  1158. }
  1159. strncpy(obj_name, *argv, MAX_OBJ_NAME_LEN - 1);
  1160. obj_name[MAX_OBJ_NAME_LEN - 1] = '\0';
  1161. } else {
  1162. p_err("unknown arg %s", *argv);
  1163. return -1;
  1164. }
  1165. NEXT_ARG();
  1166. }
  1167. if (argc) {
  1168. p_err("extra unknown arguments");
  1169. return -1;
  1170. }
  1171. if (use_loader) {
  1172. p_err("cannot use loader for subskeletons");
  1173. return -1;
  1174. }
  1175. if (stat(file, &st)) {
  1176. p_err("failed to stat() %s: %s", file, strerror(errno));
  1177. return -1;
  1178. }
  1179. file_sz = st.st_size;
  1180. mmap_sz = roundup(file_sz, sysconf(_SC_PAGE_SIZE));
  1181. fd = open(file, O_RDONLY);
  1182. if (fd < 0) {
  1183. p_err("failed to open() %s: %s", file, strerror(errno));
  1184. return -1;
  1185. }
  1186. obj_data = mmap(NULL, mmap_sz, PROT_READ, MAP_PRIVATE, fd, 0);
  1187. if (obj_data == MAP_FAILED) {
  1188. obj_data = NULL;
  1189. p_err("failed to mmap() %s: %s", file, strerror(errno));
  1190. goto out;
  1191. }
  1192. if (obj_name[0] == '\0')
  1193. get_obj_name(obj_name, file);
  1194. /* The empty object name allows us to use bpf_map__name and produce
  1195. * ELF section names out of it. (".data" instead of "obj.data")
  1196. */
  1197. opts.object_name = "";
  1198. obj = bpf_object__open_mem(obj_data, file_sz, &opts);
  1199. if (!obj) {
  1200. char err_buf[256];
  1201. libbpf_strerror(errno, err_buf, sizeof(err_buf));
  1202. p_err("failed to open BPF object file: %s", err_buf);
  1203. obj = NULL;
  1204. goto out;
  1205. }
  1206. btf = bpf_object__btf(obj);
  1207. if (!btf) {
  1208. err = -1;
  1209. p_err("need btf type information for %s", obj_name);
  1210. goto out;
  1211. }
  1212. bpf_object__for_each_program(prog, obj) {
  1213. prog_cnt++;
  1214. }
  1215. /* First, count how many variables we have to find.
  1216. * We need this in advance so the subskel can allocate the right
  1217. * amount of storage.
  1218. */
  1219. bpf_object__for_each_map(map, obj) {
  1220. if (!get_map_ident(map, ident, sizeof(ident)))
  1221. continue;
  1222. /* Also count all maps that have a name */
  1223. map_cnt++;
  1224. if (!is_internal_mmapable_map(map, ident, sizeof(ident)))
  1225. continue;
  1226. map_type_id = bpf_map__btf_value_type_id(map);
  1227. if (map_type_id <= 0) {
  1228. err = map_type_id;
  1229. goto out;
  1230. }
  1231. map_type = btf__type_by_id(btf, map_type_id);
  1232. var = btf_var_secinfos(map_type);
  1233. len = btf_vlen(map_type);
  1234. for (i = 0; i < len; i++, var++) {
  1235. var_type = btf__type_by_id(btf, var->type);
  1236. if (btf_var(var_type)->linkage == BTF_VAR_STATIC)
  1237. continue;
  1238. var_cnt++;
  1239. }
  1240. }
  1241. get_header_guard(header_guard, obj_name, "SUBSKEL_H");
  1242. codegen("\
  1243. \n\
  1244. /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ \n\
  1245. \n\
  1246. /* THIS FILE IS AUTOGENERATED! */ \n\
  1247. #ifndef %2$s \n\
  1248. #define %2$s \n\
  1249. \n\
  1250. #include <errno.h> \n\
  1251. #include <stdlib.h> \n\
  1252. #include <bpf/libbpf.h> \n\
  1253. \n\
  1254. struct %1$s { \n\
  1255. struct bpf_object *obj; \n\
  1256. struct bpf_object_subskeleton *subskel; \n\
  1257. ", obj_name, header_guard);
  1258. if (map_cnt) {
  1259. printf("\tstruct {\n");
  1260. bpf_object__for_each_map(map, obj) {
  1261. if (!get_map_ident(map, ident, sizeof(ident)))
  1262. continue;
  1263. printf("\t\tstruct bpf_map *%s;\n", ident);
  1264. }
  1265. printf("\t} maps;\n");
  1266. }
  1267. if (prog_cnt) {
  1268. printf("\tstruct {\n");
  1269. bpf_object__for_each_program(prog, obj) {
  1270. printf("\t\tstruct bpf_program *%s;\n",
  1271. bpf_program__name(prog));
  1272. }
  1273. printf("\t} progs;\n");
  1274. }
  1275. err = codegen_subskel_datasecs(obj, obj_name);
  1276. if (err)
  1277. goto out;
  1278. /* emit code that will allocate enough storage for all symbols */
  1279. codegen("\
  1280. \n\
  1281. \n\
  1282. #ifdef __cplusplus \n\
  1283. static inline struct %1$s *open(const struct bpf_object *src);\n\
  1284. static inline void destroy(struct %1$s *skel); \n\
  1285. #endif /* __cplusplus */ \n\
  1286. }; \n\
  1287. \n\
  1288. static inline void \n\
  1289. %1$s__destroy(struct %1$s *skel) \n\
  1290. { \n\
  1291. if (!skel) \n\
  1292. return; \n\
  1293. if (skel->subskel) \n\
  1294. bpf_object__destroy_subskeleton(skel->subskel);\n\
  1295. free(skel); \n\
  1296. } \n\
  1297. \n\
  1298. static inline struct %1$s * \n\
  1299. %1$s__open(const struct bpf_object *src) \n\
  1300. { \n\
  1301. struct %1$s *obj; \n\
  1302. struct bpf_object_subskeleton *s; \n\
  1303. int err; \n\
  1304. \n\
  1305. obj = (struct %1$s *)calloc(1, sizeof(*obj)); \n\
  1306. if (!obj) { \n\
  1307. err = -ENOMEM; \n\
  1308. goto err; \n\
  1309. } \n\
  1310. s = (struct bpf_object_subskeleton *)calloc(1, sizeof(*s));\n\
  1311. if (!s) { \n\
  1312. err = -ENOMEM; \n\
  1313. goto err; \n\
  1314. } \n\
  1315. s->sz = sizeof(*s); \n\
  1316. s->obj = src; \n\
  1317. s->var_skel_sz = sizeof(*s->vars); \n\
  1318. obj->subskel = s; \n\
  1319. \n\
  1320. /* vars */ \n\
  1321. s->var_cnt = %2$d; \n\
  1322. s->vars = (struct bpf_var_skeleton *)calloc(%2$d, sizeof(*s->vars));\n\
  1323. if (!s->vars) { \n\
  1324. err = -ENOMEM; \n\
  1325. goto err; \n\
  1326. } \n\
  1327. ",
  1328. obj_name, var_cnt
  1329. );
  1330. /* walk through each symbol and emit the runtime representation */
  1331. bpf_object__for_each_map(map, obj) {
  1332. if (!is_internal_mmapable_map(map, ident, sizeof(ident)))
  1333. continue;
  1334. map_type_id = bpf_map__btf_value_type_id(map);
  1335. if (map_type_id <= 0)
  1336. /* skip over internal maps with no type*/
  1337. continue;
  1338. map_type = btf__type_by_id(btf, map_type_id);
  1339. var = btf_var_secinfos(map_type);
  1340. len = btf_vlen(map_type);
  1341. for (i = 0; i < len; i++, var++) {
  1342. var_type = btf__type_by_id(btf, var->type);
  1343. var_name = btf__name_by_offset(btf, var_type->name_off);
  1344. if (btf_var(var_type)->linkage == BTF_VAR_STATIC)
  1345. continue;
  1346. /* Note that we use the dot prefix in .data as the
  1347. * field access operator i.e. maps%s becomes maps.data
  1348. */
  1349. codegen("\
  1350. \n\
  1351. \n\
  1352. s->vars[%3$d].name = \"%1$s\"; \n\
  1353. s->vars[%3$d].map = &obj->maps.%2$s; \n\
  1354. s->vars[%3$d].addr = (void **) &obj->%2$s.%1$s;\n\
  1355. ", var_name, ident, var_idx);
  1356. var_idx++;
  1357. }
  1358. }
  1359. codegen_maps_skeleton(obj, map_cnt, false /*mmaped*/);
  1360. codegen_progs_skeleton(obj, prog_cnt, false /*links*/);
  1361. codegen("\
  1362. \n\
  1363. \n\
  1364. err = bpf_object__open_subskeleton(s); \n\
  1365. if (err) \n\
  1366. goto err; \n\
  1367. \n\
  1368. return obj; \n\
  1369. err: \n\
  1370. %1$s__destroy(obj); \n\
  1371. errno = -err; \n\
  1372. return NULL; \n\
  1373. } \n\
  1374. \n\
  1375. #ifdef __cplusplus \n\
  1376. struct %1$s *%1$s::open(const struct bpf_object *src) { return %1$s__open(src); }\n\
  1377. void %1$s::destroy(struct %1$s *skel) { %1$s__destroy(skel); }\n\
  1378. #endif /* __cplusplus */ \n\
  1379. \n\
  1380. #endif /* %2$s */ \n\
  1381. ",
  1382. obj_name, header_guard);
  1383. err = 0;
  1384. out:
  1385. bpf_object__close(obj);
  1386. if (obj_data)
  1387. munmap(obj_data, mmap_sz);
  1388. close(fd);
  1389. return err;
  1390. }
  1391. static int do_object(int argc, char **argv)
  1392. {
  1393. struct bpf_linker *linker;
  1394. const char *output_file, *file;
  1395. int err = 0;
  1396. if (!REQ_ARGS(2)) {
  1397. usage();
  1398. return -1;
  1399. }
  1400. output_file = GET_ARG();
  1401. linker = bpf_linker__new(output_file, NULL);
  1402. if (!linker) {
  1403. p_err("failed to create BPF linker instance");
  1404. return -1;
  1405. }
  1406. while (argc) {
  1407. file = GET_ARG();
  1408. err = bpf_linker__add_file(linker, file, NULL);
  1409. if (err) {
  1410. p_err("failed to link '%s': %s (%d)", file, strerror(errno), errno);
  1411. goto out;
  1412. }
  1413. }
  1414. err = bpf_linker__finalize(linker);
  1415. if (err) {
  1416. p_err("failed to finalize ELF file: %s (%d)", strerror(errno), errno);
  1417. goto out;
  1418. }
  1419. err = 0;
  1420. out:
  1421. bpf_linker__free(linker);
  1422. return err;
  1423. }
  1424. static int do_help(int argc, char **argv)
  1425. {
  1426. if (json_output) {
  1427. jsonw_null(json_wtr);
  1428. return 0;
  1429. }
  1430. fprintf(stderr,
  1431. "Usage: %1$s %2$s object OUTPUT_FILE INPUT_FILE [INPUT_FILE...]\n"
  1432. " %1$s %2$s skeleton FILE [name OBJECT_NAME]\n"
  1433. " %1$s %2$s subskeleton FILE [name OBJECT_NAME]\n"
  1434. " %1$s %2$s min_core_btf INPUT OUTPUT OBJECT [OBJECT...]\n"
  1435. " %1$s %2$s help\n"
  1436. "\n"
  1437. " " HELP_SPEC_OPTIONS " |\n"
  1438. " {-L|--use-loader} }\n"
  1439. "",
  1440. bin_name, "gen");
  1441. return 0;
  1442. }
  1443. static int btf_save_raw(const struct btf *btf, const char *path)
  1444. {
  1445. const void *data;
  1446. FILE *f = NULL;
  1447. __u32 data_sz;
  1448. int err = 0;
  1449. data = btf__raw_data(btf, &data_sz);
  1450. if (!data)
  1451. return -ENOMEM;
  1452. f = fopen(path, "wb");
  1453. if (!f)
  1454. return -errno;
  1455. if (fwrite(data, 1, data_sz, f) != data_sz)
  1456. err = -errno;
  1457. fclose(f);
  1458. return err;
  1459. }
  1460. struct btfgen_info {
  1461. struct btf *src_btf;
  1462. struct btf *marked_btf; /* btf structure used to mark used types */
  1463. };
  1464. static size_t btfgen_hash_fn(const void *key, void *ctx)
  1465. {
  1466. return (size_t)key;
  1467. }
  1468. static bool btfgen_equal_fn(const void *k1, const void *k2, void *ctx)
  1469. {
  1470. return k1 == k2;
  1471. }
  1472. static void *u32_as_hash_key(__u32 x)
  1473. {
  1474. return (void *)(uintptr_t)x;
  1475. }
  1476. static void btfgen_free_info(struct btfgen_info *info)
  1477. {
  1478. if (!info)
  1479. return;
  1480. btf__free(info->src_btf);
  1481. btf__free(info->marked_btf);
  1482. free(info);
  1483. }
  1484. static struct btfgen_info *
  1485. btfgen_new_info(const char *targ_btf_path)
  1486. {
  1487. struct btfgen_info *info;
  1488. int err;
  1489. info = calloc(1, sizeof(*info));
  1490. if (!info)
  1491. return NULL;
  1492. info->src_btf = btf__parse(targ_btf_path, NULL);
  1493. if (!info->src_btf) {
  1494. err = -errno;
  1495. p_err("failed parsing '%s' BTF file: %s", targ_btf_path, strerror(errno));
  1496. goto err_out;
  1497. }
  1498. info->marked_btf = btf__parse(targ_btf_path, NULL);
  1499. if (!info->marked_btf) {
  1500. err = -errno;
  1501. p_err("failed parsing '%s' BTF file: %s", targ_btf_path, strerror(errno));
  1502. goto err_out;
  1503. }
  1504. return info;
  1505. err_out:
  1506. btfgen_free_info(info);
  1507. errno = -err;
  1508. return NULL;
  1509. }
  1510. #define MARKED UINT32_MAX
  1511. static void btfgen_mark_member(struct btfgen_info *info, int type_id, int idx)
  1512. {
  1513. const struct btf_type *t = btf__type_by_id(info->marked_btf, type_id);
  1514. struct btf_member *m = btf_members(t) + idx;
  1515. m->name_off = MARKED;
  1516. }
  1517. static int
  1518. btfgen_mark_type(struct btfgen_info *info, unsigned int type_id, bool follow_pointers)
  1519. {
  1520. const struct btf_type *btf_type = btf__type_by_id(info->src_btf, type_id);
  1521. struct btf_type *cloned_type;
  1522. struct btf_param *param;
  1523. struct btf_array *array;
  1524. int err, i;
  1525. if (type_id == 0)
  1526. return 0;
  1527. /* mark type on cloned BTF as used */
  1528. cloned_type = (struct btf_type *) btf__type_by_id(info->marked_btf, type_id);
  1529. cloned_type->name_off = MARKED;
  1530. /* recursively mark other types needed by it */
  1531. switch (btf_kind(btf_type)) {
  1532. case BTF_KIND_UNKN:
  1533. case BTF_KIND_INT:
  1534. case BTF_KIND_FLOAT:
  1535. case BTF_KIND_ENUM:
  1536. case BTF_KIND_ENUM64:
  1537. case BTF_KIND_STRUCT:
  1538. case BTF_KIND_UNION:
  1539. break;
  1540. case BTF_KIND_PTR:
  1541. if (follow_pointers) {
  1542. err = btfgen_mark_type(info, btf_type->type, follow_pointers);
  1543. if (err)
  1544. return err;
  1545. }
  1546. break;
  1547. case BTF_KIND_CONST:
  1548. case BTF_KIND_RESTRICT:
  1549. case BTF_KIND_VOLATILE:
  1550. case BTF_KIND_TYPEDEF:
  1551. err = btfgen_mark_type(info, btf_type->type, follow_pointers);
  1552. if (err)
  1553. return err;
  1554. break;
  1555. case BTF_KIND_ARRAY:
  1556. array = btf_array(btf_type);
  1557. /* mark array type */
  1558. err = btfgen_mark_type(info, array->type, follow_pointers);
  1559. /* mark array's index type */
  1560. err = err ? : btfgen_mark_type(info, array->index_type, follow_pointers);
  1561. if (err)
  1562. return err;
  1563. break;
  1564. case BTF_KIND_FUNC_PROTO:
  1565. /* mark ret type */
  1566. err = btfgen_mark_type(info, btf_type->type, follow_pointers);
  1567. if (err)
  1568. return err;
  1569. /* mark parameters types */
  1570. param = btf_params(btf_type);
  1571. for (i = 0; i < btf_vlen(btf_type); i++) {
  1572. err = btfgen_mark_type(info, param->type, follow_pointers);
  1573. if (err)
  1574. return err;
  1575. param++;
  1576. }
  1577. break;
  1578. /* tells if some other type needs to be handled */
  1579. default:
  1580. p_err("unsupported kind: %s (%d)", btf_kind_str(btf_type), type_id);
  1581. return -EINVAL;
  1582. }
  1583. return 0;
  1584. }
  1585. static int btfgen_record_field_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
  1586. {
  1587. struct btf *btf = info->src_btf;
  1588. const struct btf_type *btf_type;
  1589. struct btf_member *btf_member;
  1590. struct btf_array *array;
  1591. unsigned int type_id = targ_spec->root_type_id;
  1592. int idx, err;
  1593. /* mark root type */
  1594. btf_type = btf__type_by_id(btf, type_id);
  1595. err = btfgen_mark_type(info, type_id, false);
  1596. if (err)
  1597. return err;
  1598. /* mark types for complex types (arrays, unions, structures) */
  1599. for (int i = 1; i < targ_spec->raw_len; i++) {
  1600. /* skip typedefs and mods */
  1601. while (btf_is_mod(btf_type) || btf_is_typedef(btf_type)) {
  1602. type_id = btf_type->type;
  1603. btf_type = btf__type_by_id(btf, type_id);
  1604. }
  1605. switch (btf_kind(btf_type)) {
  1606. case BTF_KIND_STRUCT:
  1607. case BTF_KIND_UNION:
  1608. idx = targ_spec->raw_spec[i];
  1609. btf_member = btf_members(btf_type) + idx;
  1610. /* mark member */
  1611. btfgen_mark_member(info, type_id, idx);
  1612. /* mark member's type */
  1613. type_id = btf_member->type;
  1614. btf_type = btf__type_by_id(btf, type_id);
  1615. err = btfgen_mark_type(info, type_id, false);
  1616. if (err)
  1617. return err;
  1618. break;
  1619. case BTF_KIND_ARRAY:
  1620. array = btf_array(btf_type);
  1621. type_id = array->type;
  1622. btf_type = btf__type_by_id(btf, type_id);
  1623. break;
  1624. default:
  1625. p_err("unsupported kind: %s (%d)",
  1626. btf_kind_str(btf_type), btf_type->type);
  1627. return -EINVAL;
  1628. }
  1629. }
  1630. return 0;
  1631. }
  1632. /* Mark types, members, and member types. Compared to btfgen_record_field_relo,
  1633. * this function does not rely on the target spec for inferring members, but
  1634. * uses the associated BTF.
  1635. *
  1636. * The `behind_ptr` argument is used to stop marking of composite types reached
  1637. * through a pointer. This way, we can keep BTF size in check while providing
  1638. * reasonable match semantics.
  1639. */
  1640. static int btfgen_mark_type_match(struct btfgen_info *info, __u32 type_id, bool behind_ptr)
  1641. {
  1642. const struct btf_type *btf_type;
  1643. struct btf *btf = info->src_btf;
  1644. struct btf_type *cloned_type;
  1645. int i, err;
  1646. if (type_id == 0)
  1647. return 0;
  1648. btf_type = btf__type_by_id(btf, type_id);
  1649. /* mark type on cloned BTF as used */
  1650. cloned_type = (struct btf_type *)btf__type_by_id(info->marked_btf, type_id);
  1651. cloned_type->name_off = MARKED;
  1652. switch (btf_kind(btf_type)) {
  1653. case BTF_KIND_UNKN:
  1654. case BTF_KIND_INT:
  1655. case BTF_KIND_FLOAT:
  1656. case BTF_KIND_ENUM:
  1657. case BTF_KIND_ENUM64:
  1658. break;
  1659. case BTF_KIND_STRUCT:
  1660. case BTF_KIND_UNION: {
  1661. struct btf_member *m = btf_members(btf_type);
  1662. __u16 vlen = btf_vlen(btf_type);
  1663. if (behind_ptr)
  1664. break;
  1665. for (i = 0; i < vlen; i++, m++) {
  1666. /* mark member */
  1667. btfgen_mark_member(info, type_id, i);
  1668. /* mark member's type */
  1669. err = btfgen_mark_type_match(info, m->type, false);
  1670. if (err)
  1671. return err;
  1672. }
  1673. break;
  1674. }
  1675. case BTF_KIND_CONST:
  1676. case BTF_KIND_FWD:
  1677. case BTF_KIND_RESTRICT:
  1678. case BTF_KIND_TYPEDEF:
  1679. case BTF_KIND_VOLATILE:
  1680. return btfgen_mark_type_match(info, btf_type->type, behind_ptr);
  1681. case BTF_KIND_PTR:
  1682. return btfgen_mark_type_match(info, btf_type->type, true);
  1683. case BTF_KIND_ARRAY: {
  1684. struct btf_array *array;
  1685. array = btf_array(btf_type);
  1686. /* mark array type */
  1687. err = btfgen_mark_type_match(info, array->type, false);
  1688. /* mark array's index type */
  1689. err = err ? : btfgen_mark_type_match(info, array->index_type, false);
  1690. if (err)
  1691. return err;
  1692. break;
  1693. }
  1694. case BTF_KIND_FUNC_PROTO: {
  1695. __u16 vlen = btf_vlen(btf_type);
  1696. struct btf_param *param;
  1697. /* mark ret type */
  1698. err = btfgen_mark_type_match(info, btf_type->type, false);
  1699. if (err)
  1700. return err;
  1701. /* mark parameters types */
  1702. param = btf_params(btf_type);
  1703. for (i = 0; i < vlen; i++) {
  1704. err = btfgen_mark_type_match(info, param->type, false);
  1705. if (err)
  1706. return err;
  1707. param++;
  1708. }
  1709. break;
  1710. }
  1711. /* tells if some other type needs to be handled */
  1712. default:
  1713. p_err("unsupported kind: %s (%d)", btf_kind_str(btf_type), type_id);
  1714. return -EINVAL;
  1715. }
  1716. return 0;
  1717. }
  1718. /* Mark types, members, and member types. Compared to btfgen_record_field_relo,
  1719. * this function does not rely on the target spec for inferring members, but
  1720. * uses the associated BTF.
  1721. */
  1722. static int btfgen_record_type_match_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
  1723. {
  1724. return btfgen_mark_type_match(info, targ_spec->root_type_id, false);
  1725. }
  1726. static int btfgen_record_type_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
  1727. {
  1728. return btfgen_mark_type(info, targ_spec->root_type_id, true);
  1729. }
  1730. static int btfgen_record_enumval_relo(struct btfgen_info *info, struct bpf_core_spec *targ_spec)
  1731. {
  1732. return btfgen_mark_type(info, targ_spec->root_type_id, false);
  1733. }
  1734. static int btfgen_record_reloc(struct btfgen_info *info, struct bpf_core_spec *res)
  1735. {
  1736. switch (res->relo_kind) {
  1737. case BPF_CORE_FIELD_BYTE_OFFSET:
  1738. case BPF_CORE_FIELD_BYTE_SIZE:
  1739. case BPF_CORE_FIELD_EXISTS:
  1740. case BPF_CORE_FIELD_SIGNED:
  1741. case BPF_CORE_FIELD_LSHIFT_U64:
  1742. case BPF_CORE_FIELD_RSHIFT_U64:
  1743. return btfgen_record_field_relo(info, res);
  1744. case BPF_CORE_TYPE_ID_LOCAL: /* BPF_CORE_TYPE_ID_LOCAL doesn't require kernel BTF */
  1745. return 0;
  1746. case BPF_CORE_TYPE_ID_TARGET:
  1747. case BPF_CORE_TYPE_EXISTS:
  1748. case BPF_CORE_TYPE_SIZE:
  1749. return btfgen_record_type_relo(info, res);
  1750. case BPF_CORE_TYPE_MATCHES:
  1751. return btfgen_record_type_match_relo(info, res);
  1752. case BPF_CORE_ENUMVAL_EXISTS:
  1753. case BPF_CORE_ENUMVAL_VALUE:
  1754. return btfgen_record_enumval_relo(info, res);
  1755. default:
  1756. return -EINVAL;
  1757. }
  1758. }
  1759. static struct bpf_core_cand_list *
  1760. btfgen_find_cands(const struct btf *local_btf, const struct btf *targ_btf, __u32 local_id)
  1761. {
  1762. const struct btf_type *local_type;
  1763. struct bpf_core_cand_list *cands = NULL;
  1764. struct bpf_core_cand local_cand = {};
  1765. size_t local_essent_len;
  1766. const char *local_name;
  1767. int err;
  1768. local_cand.btf = local_btf;
  1769. local_cand.id = local_id;
  1770. local_type = btf__type_by_id(local_btf, local_id);
  1771. if (!local_type) {
  1772. err = -EINVAL;
  1773. goto err_out;
  1774. }
  1775. local_name = btf__name_by_offset(local_btf, local_type->name_off);
  1776. if (!local_name) {
  1777. err = -EINVAL;
  1778. goto err_out;
  1779. }
  1780. local_essent_len = bpf_core_essential_name_len(local_name);
  1781. cands = calloc(1, sizeof(*cands));
  1782. if (!cands)
  1783. return NULL;
  1784. err = bpf_core_add_cands(&local_cand, local_essent_len, targ_btf, "vmlinux", 1, cands);
  1785. if (err)
  1786. goto err_out;
  1787. return cands;
  1788. err_out:
  1789. bpf_core_free_cands(cands);
  1790. errno = -err;
  1791. return NULL;
  1792. }
  1793. /* Record relocation information for a single BPF object */
  1794. static int btfgen_record_obj(struct btfgen_info *info, const char *obj_path)
  1795. {
  1796. const struct btf_ext_info_sec *sec;
  1797. const struct bpf_core_relo *relo;
  1798. const struct btf_ext_info *seg;
  1799. struct hashmap_entry *entry;
  1800. struct hashmap *cand_cache = NULL;
  1801. struct btf_ext *btf_ext = NULL;
  1802. unsigned int relo_idx;
  1803. struct btf *btf = NULL;
  1804. size_t i;
  1805. int err;
  1806. btf = btf__parse(obj_path, &btf_ext);
  1807. if (!btf) {
  1808. err = -errno;
  1809. p_err("failed to parse BPF object '%s': %s", obj_path, strerror(errno));
  1810. return err;
  1811. }
  1812. if (!btf_ext) {
  1813. p_err("failed to parse BPF object '%s': section %s not found",
  1814. obj_path, BTF_EXT_ELF_SEC);
  1815. err = -EINVAL;
  1816. goto out;
  1817. }
  1818. if (btf_ext->core_relo_info.len == 0) {
  1819. err = 0;
  1820. goto out;
  1821. }
  1822. cand_cache = hashmap__new(btfgen_hash_fn, btfgen_equal_fn, NULL);
  1823. if (IS_ERR(cand_cache)) {
  1824. err = PTR_ERR(cand_cache);
  1825. goto out;
  1826. }
  1827. seg = &btf_ext->core_relo_info;
  1828. for_each_btf_ext_sec(seg, sec) {
  1829. for_each_btf_ext_rec(seg, sec, relo_idx, relo) {
  1830. struct bpf_core_spec specs_scratch[3] = {};
  1831. struct bpf_core_relo_res targ_res = {};
  1832. struct bpf_core_cand_list *cands = NULL;
  1833. const void *type_key = u32_as_hash_key(relo->type_id);
  1834. const char *sec_name = btf__name_by_offset(btf, sec->sec_name_off);
  1835. if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
  1836. !hashmap__find(cand_cache, type_key, (void **)&cands)) {
  1837. cands = btfgen_find_cands(btf, info->src_btf, relo->type_id);
  1838. if (!cands) {
  1839. err = -errno;
  1840. goto out;
  1841. }
  1842. err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
  1843. if (err)
  1844. goto out;
  1845. }
  1846. err = bpf_core_calc_relo_insn(sec_name, relo, relo_idx, btf, cands,
  1847. specs_scratch, &targ_res);
  1848. if (err)
  1849. goto out;
  1850. /* specs_scratch[2] is the target spec */
  1851. err = btfgen_record_reloc(info, &specs_scratch[2]);
  1852. if (err)
  1853. goto out;
  1854. }
  1855. }
  1856. out:
  1857. btf__free(btf);
  1858. btf_ext__free(btf_ext);
  1859. if (!IS_ERR_OR_NULL(cand_cache)) {
  1860. hashmap__for_each_entry(cand_cache, entry, i) {
  1861. bpf_core_free_cands(entry->value);
  1862. }
  1863. hashmap__free(cand_cache);
  1864. }
  1865. return err;
  1866. }
  1867. static int btfgen_remap_id(__u32 *type_id, void *ctx)
  1868. {
  1869. unsigned int *ids = ctx;
  1870. *type_id = ids[*type_id];
  1871. return 0;
  1872. }
  1873. /* Generate BTF from relocation information previously recorded */
  1874. static struct btf *btfgen_get_btf(struct btfgen_info *info)
  1875. {
  1876. struct btf *btf_new = NULL;
  1877. unsigned int *ids = NULL;
  1878. unsigned int i, n = btf__type_cnt(info->marked_btf);
  1879. int err = 0;
  1880. btf_new = btf__new_empty();
  1881. if (!btf_new) {
  1882. err = -errno;
  1883. goto err_out;
  1884. }
  1885. ids = calloc(n, sizeof(*ids));
  1886. if (!ids) {
  1887. err = -errno;
  1888. goto err_out;
  1889. }
  1890. /* first pass: add all marked types to btf_new and add their new ids to the ids map */
  1891. for (i = 1; i < n; i++) {
  1892. const struct btf_type *cloned_type, *type;
  1893. const char *name;
  1894. int new_id;
  1895. cloned_type = btf__type_by_id(info->marked_btf, i);
  1896. if (cloned_type->name_off != MARKED)
  1897. continue;
  1898. type = btf__type_by_id(info->src_btf, i);
  1899. /* add members for struct and union */
  1900. if (btf_is_composite(type)) {
  1901. struct btf_member *cloned_m, *m;
  1902. unsigned short vlen;
  1903. int idx_src;
  1904. name = btf__str_by_offset(info->src_btf, type->name_off);
  1905. if (btf_is_struct(type))
  1906. err = btf__add_struct(btf_new, name, type->size);
  1907. else
  1908. err = btf__add_union(btf_new, name, type->size);
  1909. if (err < 0)
  1910. goto err_out;
  1911. new_id = err;
  1912. cloned_m = btf_members(cloned_type);
  1913. m = btf_members(type);
  1914. vlen = btf_vlen(cloned_type);
  1915. for (idx_src = 0; idx_src < vlen; idx_src++, cloned_m++, m++) {
  1916. /* add only members that are marked as used */
  1917. if (cloned_m->name_off != MARKED)
  1918. continue;
  1919. name = btf__str_by_offset(info->src_btf, m->name_off);
  1920. err = btf__add_field(btf_new, name, m->type,
  1921. btf_member_bit_offset(cloned_type, idx_src),
  1922. btf_member_bitfield_size(cloned_type, idx_src));
  1923. if (err < 0)
  1924. goto err_out;
  1925. }
  1926. } else {
  1927. err = btf__add_type(btf_new, info->src_btf, type);
  1928. if (err < 0)
  1929. goto err_out;
  1930. new_id = err;
  1931. }
  1932. /* add ID mapping */
  1933. ids[i] = new_id;
  1934. }
  1935. /* second pass: fix up type ids */
  1936. for (i = 1; i < btf__type_cnt(btf_new); i++) {
  1937. struct btf_type *btf_type = (struct btf_type *) btf__type_by_id(btf_new, i);
  1938. err = btf_type_visit_type_ids(btf_type, btfgen_remap_id, ids);
  1939. if (err)
  1940. goto err_out;
  1941. }
  1942. free(ids);
  1943. return btf_new;
  1944. err_out:
  1945. btf__free(btf_new);
  1946. free(ids);
  1947. errno = -err;
  1948. return NULL;
  1949. }
  1950. /* Create minimized BTF file for a set of BPF objects.
  1951. *
  1952. * The BTFGen algorithm is divided in two main parts: (1) collect the
  1953. * BTF types that are involved in relocations and (2) generate the BTF
  1954. * object using the collected types.
  1955. *
  1956. * In order to collect the types involved in the relocations, we parse
  1957. * the BTF and BTF.ext sections of the BPF objects and use
  1958. * bpf_core_calc_relo_insn() to get the target specification, this
  1959. * indicates how the types and fields are used in a relocation.
  1960. *
  1961. * Types are recorded in different ways according to the kind of the
  1962. * relocation. For field-based relocations only the members that are
  1963. * actually used are saved in order to reduce the size of the generated
  1964. * BTF file. For type-based relocations empty struct / unions are
  1965. * generated and for enum-based relocations the whole type is saved.
  1966. *
  1967. * The second part of the algorithm generates the BTF object. It creates
  1968. * an empty BTF object and fills it with the types recorded in the
  1969. * previous step. This function takes care of only adding the structure
  1970. * and union members that were marked as used and it also fixes up the
  1971. * type IDs on the generated BTF object.
  1972. */
  1973. static int minimize_btf(const char *src_btf, const char *dst_btf, const char *objspaths[])
  1974. {
  1975. struct btfgen_info *info;
  1976. struct btf *btf_new = NULL;
  1977. int err, i;
  1978. info = btfgen_new_info(src_btf);
  1979. if (!info) {
  1980. err = -errno;
  1981. p_err("failed to allocate info structure: %s", strerror(errno));
  1982. goto out;
  1983. }
  1984. for (i = 0; objspaths[i] != NULL; i++) {
  1985. err = btfgen_record_obj(info, objspaths[i]);
  1986. if (err) {
  1987. p_err("error recording relocations for %s: %s", objspaths[i],
  1988. strerror(errno));
  1989. goto out;
  1990. }
  1991. }
  1992. btf_new = btfgen_get_btf(info);
  1993. if (!btf_new) {
  1994. err = -errno;
  1995. p_err("error generating BTF: %s", strerror(errno));
  1996. goto out;
  1997. }
  1998. err = btf_save_raw(btf_new, dst_btf);
  1999. if (err) {
  2000. p_err("error saving btf file: %s", strerror(errno));
  2001. goto out;
  2002. }
  2003. out:
  2004. btf__free(btf_new);
  2005. btfgen_free_info(info);
  2006. return err;
  2007. }
  2008. static int do_min_core_btf(int argc, char **argv)
  2009. {
  2010. const char *input, *output, **objs;
  2011. int i, err;
  2012. if (!REQ_ARGS(3)) {
  2013. usage();
  2014. return -1;
  2015. }
  2016. input = GET_ARG();
  2017. output = GET_ARG();
  2018. objs = (const char **) calloc(argc + 1, sizeof(*objs));
  2019. if (!objs) {
  2020. p_err("failed to allocate array for object names");
  2021. return -ENOMEM;
  2022. }
  2023. i = 0;
  2024. while (argc)
  2025. objs[i++] = GET_ARG();
  2026. err = minimize_btf(input, output, objs);
  2027. free(objs);
  2028. return err;
  2029. }
  2030. static const struct cmd cmds[] = {
  2031. { "object", do_object },
  2032. { "skeleton", do_skeleton },
  2033. { "subskeleton", do_subskeleton },
  2034. { "min_core_btf", do_min_core_btf},
  2035. { "help", do_help },
  2036. { 0 }
  2037. };
  2038. int do_gen(int argc, char **argv)
  2039. {
  2040. return cmd_select(cmds, argc, argv, do_help);
  2041. }