btf_dump.c 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617
  1. // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
  2. /*
  3. * BTF-to-C type converter.
  4. *
  5. * Copyright (c) 2019 Facebook
  6. */
  7. #include <stdbool.h>
  8. #include <stddef.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <ctype.h>
  12. #include <endian.h>
  13. #include <errno.h>
  14. #include <limits.h>
  15. #include <linux/err.h>
  16. #include <linux/btf.h>
  17. #include <linux/kernel.h>
  18. #include "btf.h"
  19. #include "hashmap.h"
  20. #include "libbpf.h"
  21. #include "libbpf_internal.h"
  22. static const char PREFIXES[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t";
  23. static const size_t PREFIX_CNT = sizeof(PREFIXES) - 1;
  24. static const char *pfx(int lvl)
  25. {
  26. return lvl >= PREFIX_CNT ? PREFIXES : &PREFIXES[PREFIX_CNT - lvl];
  27. }
  28. enum btf_dump_type_order_state {
  29. NOT_ORDERED,
  30. ORDERING,
  31. ORDERED,
  32. };
  33. enum btf_dump_type_emit_state {
  34. NOT_EMITTED,
  35. EMITTING,
  36. EMITTED,
  37. };
  38. /* per-type auxiliary state */
  39. struct btf_dump_type_aux_state {
  40. /* topological sorting state */
  41. enum btf_dump_type_order_state order_state: 2;
  42. /* emitting state used to determine the need for forward declaration */
  43. enum btf_dump_type_emit_state emit_state: 2;
  44. /* whether forward declaration was already emitted */
  45. __u8 fwd_emitted: 1;
  46. /* whether unique non-duplicate name was already assigned */
  47. __u8 name_resolved: 1;
  48. /* whether type is referenced from any other type */
  49. __u8 referenced: 1;
  50. };
  51. /* indent string length; one indent string is added for each indent level */
  52. #define BTF_DATA_INDENT_STR_LEN 32
  53. /*
  54. * Common internal data for BTF type data dump operations.
  55. */
  56. struct btf_dump_data {
  57. const void *data_end; /* end of valid data to show */
  58. bool compact;
  59. bool skip_names;
  60. bool emit_zeroes;
  61. bool emit_strings;
  62. __u8 indent_lvl; /* base indent level */
  63. char indent_str[BTF_DATA_INDENT_STR_LEN];
  64. /* below are used during iteration */
  65. int depth;
  66. bool is_array_member;
  67. bool is_array_terminated;
  68. bool is_array_char;
  69. };
  70. struct btf_dump {
  71. const struct btf *btf;
  72. btf_dump_printf_fn_t printf_fn;
  73. void *cb_ctx;
  74. int ptr_sz;
  75. bool strip_mods;
  76. bool skip_anon_defs;
  77. int last_id;
  78. /* per-type auxiliary state */
  79. struct btf_dump_type_aux_state *type_states;
  80. size_t type_states_cap;
  81. /* per-type optional cached unique name, must be freed, if present */
  82. const char **cached_names;
  83. size_t cached_names_cap;
  84. /* topo-sorted list of dependent type definitions */
  85. __u32 *emit_queue;
  86. int emit_queue_cap;
  87. int emit_queue_cnt;
  88. /*
  89. * stack of type declarations (e.g., chain of modifiers, arrays,
  90. * funcs, etc)
  91. */
  92. __u32 *decl_stack;
  93. int decl_stack_cap;
  94. int decl_stack_cnt;
  95. /* maps struct/union/enum name to a number of name occurrences */
  96. struct hashmap *type_names;
  97. /*
  98. * maps typedef identifiers and enum value names to a number of such
  99. * name occurrences
  100. */
  101. struct hashmap *ident_names;
  102. /*
  103. * data for typed display; allocated if needed.
  104. */
  105. struct btf_dump_data *typed_dump;
  106. };
  107. static size_t str_hash_fn(long key, void *ctx)
  108. {
  109. return str_hash((void *)key);
  110. }
  111. static bool str_equal_fn(long a, long b, void *ctx)
  112. {
  113. return strcmp((void *)a, (void *)b) == 0;
  114. }
  115. static const char *btf_name_of(const struct btf_dump *d, __u32 name_off)
  116. {
  117. return btf__name_by_offset(d->btf, name_off);
  118. }
  119. static void btf_dump_printf(const struct btf_dump *d, const char *fmt, ...)
  120. {
  121. va_list args;
  122. va_start(args, fmt);
  123. d->printf_fn(d->cb_ctx, fmt, args);
  124. va_end(args);
  125. }
  126. static int btf_dump_mark_referenced(struct btf_dump *d);
  127. static int btf_dump_resize(struct btf_dump *d);
  128. struct btf_dump *btf_dump__new(const struct btf *btf,
  129. btf_dump_printf_fn_t printf_fn,
  130. void *ctx,
  131. const struct btf_dump_opts *opts)
  132. {
  133. struct btf_dump *d;
  134. int err;
  135. if (!OPTS_VALID(opts, btf_dump_opts))
  136. return libbpf_err_ptr(-EINVAL);
  137. if (!printf_fn)
  138. return libbpf_err_ptr(-EINVAL);
  139. d = calloc(1, sizeof(struct btf_dump));
  140. if (!d)
  141. return libbpf_err_ptr(-ENOMEM);
  142. d->btf = btf;
  143. d->printf_fn = printf_fn;
  144. d->cb_ctx = ctx;
  145. d->ptr_sz = btf__pointer_size(btf) ? : sizeof(void *);
  146. d->type_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
  147. if (IS_ERR(d->type_names)) {
  148. err = PTR_ERR(d->type_names);
  149. d->type_names = NULL;
  150. goto err;
  151. }
  152. d->ident_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
  153. if (IS_ERR(d->ident_names)) {
  154. err = PTR_ERR(d->ident_names);
  155. d->ident_names = NULL;
  156. goto err;
  157. }
  158. err = btf_dump_resize(d);
  159. if (err)
  160. goto err;
  161. return d;
  162. err:
  163. btf_dump__free(d);
  164. return libbpf_err_ptr(err);
  165. }
  166. static int btf_dump_resize(struct btf_dump *d)
  167. {
  168. int err, last_id = btf__type_cnt(d->btf) - 1;
  169. if (last_id <= d->last_id)
  170. return 0;
  171. if (libbpf_ensure_mem((void **)&d->type_states, &d->type_states_cap,
  172. sizeof(*d->type_states), last_id + 1))
  173. return -ENOMEM;
  174. if (libbpf_ensure_mem((void **)&d->cached_names, &d->cached_names_cap,
  175. sizeof(*d->cached_names), last_id + 1))
  176. return -ENOMEM;
  177. if (d->last_id == 0) {
  178. /* VOID is special */
  179. d->type_states[0].order_state = ORDERED;
  180. d->type_states[0].emit_state = EMITTED;
  181. }
  182. /* eagerly determine referenced types for anon enums */
  183. err = btf_dump_mark_referenced(d);
  184. if (err)
  185. return err;
  186. d->last_id = last_id;
  187. return 0;
  188. }
  189. static void btf_dump_free_names(struct hashmap *map)
  190. {
  191. size_t bkt;
  192. struct hashmap_entry *cur;
  193. if (!map)
  194. return;
  195. hashmap__for_each_entry(map, cur, bkt)
  196. free((void *)cur->pkey);
  197. hashmap__free(map);
  198. }
  199. void btf_dump__free(struct btf_dump *d)
  200. {
  201. int i;
  202. if (IS_ERR_OR_NULL(d))
  203. return;
  204. free(d->type_states);
  205. if (d->cached_names) {
  206. /* any set cached name is owned by us and should be freed */
  207. for (i = 0; i <= d->last_id; i++) {
  208. if (d->cached_names[i])
  209. free((void *)d->cached_names[i]);
  210. }
  211. }
  212. free(d->cached_names);
  213. free(d->emit_queue);
  214. free(d->decl_stack);
  215. btf_dump_free_names(d->type_names);
  216. btf_dump_free_names(d->ident_names);
  217. free(d);
  218. }
  219. static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr);
  220. static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id);
  221. /*
  222. * Dump BTF type in a compilable C syntax, including all the necessary
  223. * dependent types, necessary for compilation. If some of the dependent types
  224. * were already emitted as part of previous btf_dump__dump_type() invocation
  225. * for another type, they won't be emitted again. This API allows callers to
  226. * filter out BTF types according to user-defined criterias and emitted only
  227. * minimal subset of types, necessary to compile everything. Full struct/union
  228. * definitions will still be emitted, even if the only usage is through
  229. * pointer and could be satisfied with just a forward declaration.
  230. *
  231. * Dumping is done in two high-level passes:
  232. * 1. Topologically sort type definitions to satisfy C rules of compilation.
  233. * 2. Emit type definitions in C syntax.
  234. *
  235. * Returns 0 on success; <0, otherwise.
  236. */
  237. int btf_dump__dump_type(struct btf_dump *d, __u32 id)
  238. {
  239. int err, i;
  240. if (id >= btf__type_cnt(d->btf))
  241. return libbpf_err(-EINVAL);
  242. err = btf_dump_resize(d);
  243. if (err)
  244. return libbpf_err(err);
  245. d->emit_queue_cnt = 0;
  246. err = btf_dump_order_type(d, id, false);
  247. if (err < 0)
  248. return libbpf_err(err);
  249. for (i = 0; i < d->emit_queue_cnt; i++)
  250. btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
  251. return 0;
  252. }
  253. /*
  254. * Mark all types that are referenced from any other type. This is used to
  255. * determine top-level anonymous enums that need to be emitted as an
  256. * independent type declarations.
  257. * Anonymous enums come in two flavors: either embedded in a struct's field
  258. * definition, in which case they have to be declared inline as part of field
  259. * type declaration; or as a top-level anonymous enum, typically used for
  260. * declaring global constants. It's impossible to distinguish between two
  261. * without knowing whether given enum type was referenced from other type:
  262. * top-level anonymous enum won't be referenced by anything, while embedded
  263. * one will.
  264. */
  265. static int btf_dump_mark_referenced(struct btf_dump *d)
  266. {
  267. int i, j, n = btf__type_cnt(d->btf);
  268. const struct btf_type *t;
  269. __u16 vlen;
  270. for (i = d->last_id + 1; i < n; i++) {
  271. t = btf__type_by_id(d->btf, i);
  272. vlen = btf_vlen(t);
  273. switch (btf_kind(t)) {
  274. case BTF_KIND_INT:
  275. case BTF_KIND_ENUM:
  276. case BTF_KIND_ENUM64:
  277. case BTF_KIND_FWD:
  278. case BTF_KIND_FLOAT:
  279. break;
  280. case BTF_KIND_VOLATILE:
  281. case BTF_KIND_CONST:
  282. case BTF_KIND_RESTRICT:
  283. case BTF_KIND_PTR:
  284. case BTF_KIND_TYPEDEF:
  285. case BTF_KIND_FUNC:
  286. case BTF_KIND_VAR:
  287. case BTF_KIND_DECL_TAG:
  288. case BTF_KIND_TYPE_TAG:
  289. d->type_states[t->type].referenced = 1;
  290. break;
  291. case BTF_KIND_ARRAY: {
  292. const struct btf_array *a = btf_array(t);
  293. d->type_states[a->index_type].referenced = 1;
  294. d->type_states[a->type].referenced = 1;
  295. break;
  296. }
  297. case BTF_KIND_STRUCT:
  298. case BTF_KIND_UNION: {
  299. const struct btf_member *m = btf_members(t);
  300. for (j = 0; j < vlen; j++, m++)
  301. d->type_states[m->type].referenced = 1;
  302. break;
  303. }
  304. case BTF_KIND_FUNC_PROTO: {
  305. const struct btf_param *p = btf_params(t);
  306. for (j = 0; j < vlen; j++, p++)
  307. d->type_states[p->type].referenced = 1;
  308. break;
  309. }
  310. case BTF_KIND_DATASEC: {
  311. const struct btf_var_secinfo *v = btf_var_secinfos(t);
  312. for (j = 0; j < vlen; j++, v++)
  313. d->type_states[v->type].referenced = 1;
  314. break;
  315. }
  316. default:
  317. return -EINVAL;
  318. }
  319. }
  320. return 0;
  321. }
  322. static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
  323. {
  324. __u32 *new_queue;
  325. size_t new_cap;
  326. if (d->emit_queue_cnt >= d->emit_queue_cap) {
  327. new_cap = max(16, d->emit_queue_cap * 3 / 2);
  328. new_queue = libbpf_reallocarray(d->emit_queue, new_cap, sizeof(new_queue[0]));
  329. if (!new_queue)
  330. return -ENOMEM;
  331. d->emit_queue = new_queue;
  332. d->emit_queue_cap = new_cap;
  333. }
  334. d->emit_queue[d->emit_queue_cnt++] = id;
  335. return 0;
  336. }
  337. /*
  338. * Determine order of emitting dependent types and specified type to satisfy
  339. * C compilation rules. This is done through topological sorting with an
  340. * additional complication which comes from C rules. The main idea for C is
  341. * that if some type is "embedded" into a struct/union, it's size needs to be
  342. * known at the time of definition of containing type. E.g., for:
  343. *
  344. * struct A {};
  345. * struct B { struct A x; }
  346. *
  347. * struct A *HAS* to be defined before struct B, because it's "embedded",
  348. * i.e., it is part of struct B layout. But in the following case:
  349. *
  350. * struct A;
  351. * struct B { struct A *x; }
  352. * struct A {};
  353. *
  354. * it's enough to just have a forward declaration of struct A at the time of
  355. * struct B definition, as struct B has a pointer to struct A, so the size of
  356. * field x is known without knowing struct A size: it's sizeof(void *).
  357. *
  358. * Unfortunately, there are some trickier cases we need to handle, e.g.:
  359. *
  360. * struct A {}; // if this was forward-declaration: compilation error
  361. * struct B {
  362. * struct { // anonymous struct
  363. * struct A y;
  364. * } *x;
  365. * };
  366. *
  367. * In this case, struct B's field x is a pointer, so it's size is known
  368. * regardless of the size of (anonymous) struct it points to. But because this
  369. * struct is anonymous and thus defined inline inside struct B, *and* it
  370. * embeds struct A, compiler requires full definition of struct A to be known
  371. * before struct B can be defined. This creates a transitive dependency
  372. * between struct A and struct B. If struct A was forward-declared before
  373. * struct B definition and fully defined after struct B definition, that would
  374. * trigger compilation error.
  375. *
  376. * All this means that while we are doing topological sorting on BTF type
  377. * graph, we need to determine relationships between different types (graph
  378. * nodes):
  379. * - weak link (relationship) between X and Y, if Y *CAN* be
  380. * forward-declared at the point of X definition;
  381. * - strong link, if Y *HAS* to be fully-defined before X can be defined.
  382. *
  383. * The rule is as follows. Given a chain of BTF types from X to Y, if there is
  384. * BTF_KIND_PTR type in the chain and at least one non-anonymous type
  385. * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
  386. * Weak/strong relationship is determined recursively during DFS traversal and
  387. * is returned as a result from btf_dump_order_type().
  388. *
  389. * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
  390. * but it is not guaranteeing that no extraneous forward declarations will be
  391. * emitted.
  392. *
  393. * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
  394. * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
  395. * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
  396. * entire graph path, so depending where from one came to that BTF type, it
  397. * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
  398. * once they are processed, there is no need to do it again, so they are
  399. * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
  400. * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
  401. * in any case, once those are processed, no need to do it again, as the
  402. * result won't change.
  403. *
  404. * Returns:
  405. * - 1, if type is part of strong link (so there is strong topological
  406. * ordering requirements);
  407. * - 0, if type is part of weak link (so can be satisfied through forward
  408. * declaration);
  409. * - <0, on error (e.g., unsatisfiable type loop detected).
  410. */
  411. static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
  412. {
  413. /*
  414. * Order state is used to detect strong link cycles, but only for BTF
  415. * kinds that are or could be an independent definition (i.e.,
  416. * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
  417. * func_protos, modifiers are just means to get to these definitions.
  418. * Int/void don't need definitions, they are assumed to be always
  419. * properly defined. We also ignore datasec, var, and funcs for now.
  420. * So for all non-defining kinds, we never even set ordering state,
  421. * for defining kinds we set ORDERING and subsequently ORDERED if it
  422. * forms a strong link.
  423. */
  424. struct btf_dump_type_aux_state *tstate = &d->type_states[id];
  425. const struct btf_type *t;
  426. __u16 vlen;
  427. int err, i;
  428. /* return true, letting typedefs know that it's ok to be emitted */
  429. if (tstate->order_state == ORDERED)
  430. return 1;
  431. t = btf__type_by_id(d->btf, id);
  432. if (tstate->order_state == ORDERING) {
  433. /* type loop, but resolvable through fwd declaration */
  434. if (btf_is_composite(t) && through_ptr && t->name_off != 0)
  435. return 0;
  436. pr_warn("unsatisfiable type cycle, id:[%u]\n", id);
  437. return -ELOOP;
  438. }
  439. switch (btf_kind(t)) {
  440. case BTF_KIND_INT:
  441. case BTF_KIND_FLOAT:
  442. tstate->order_state = ORDERED;
  443. return 0;
  444. case BTF_KIND_PTR:
  445. err = btf_dump_order_type(d, t->type, true);
  446. tstate->order_state = ORDERED;
  447. return err;
  448. case BTF_KIND_ARRAY:
  449. return btf_dump_order_type(d, btf_array(t)->type, false);
  450. case BTF_KIND_STRUCT:
  451. case BTF_KIND_UNION: {
  452. const struct btf_member *m = btf_members(t);
  453. /*
  454. * struct/union is part of strong link, only if it's embedded
  455. * (so no ptr in a path) or it's anonymous (so has to be
  456. * defined inline, even if declared through ptr)
  457. */
  458. if (through_ptr && t->name_off != 0)
  459. return 0;
  460. tstate->order_state = ORDERING;
  461. vlen = btf_vlen(t);
  462. for (i = 0; i < vlen; i++, m++) {
  463. err = btf_dump_order_type(d, m->type, false);
  464. if (err < 0)
  465. return err;
  466. }
  467. if (t->name_off != 0) {
  468. err = btf_dump_add_emit_queue_id(d, id);
  469. if (err < 0)
  470. return err;
  471. }
  472. tstate->order_state = ORDERED;
  473. return 1;
  474. }
  475. case BTF_KIND_ENUM:
  476. case BTF_KIND_ENUM64:
  477. case BTF_KIND_FWD:
  478. /*
  479. * non-anonymous or non-referenced enums are top-level
  480. * declarations and should be emitted. Same logic can be
  481. * applied to FWDs, it won't hurt anyways.
  482. */
  483. if (t->name_off != 0 || !tstate->referenced) {
  484. err = btf_dump_add_emit_queue_id(d, id);
  485. if (err)
  486. return err;
  487. }
  488. tstate->order_state = ORDERED;
  489. return 1;
  490. case BTF_KIND_TYPEDEF: {
  491. int is_strong;
  492. is_strong = btf_dump_order_type(d, t->type, through_ptr);
  493. if (is_strong < 0)
  494. return is_strong;
  495. /* typedef is similar to struct/union w.r.t. fwd-decls */
  496. if (through_ptr && !is_strong)
  497. return 0;
  498. /* typedef is always a named definition */
  499. err = btf_dump_add_emit_queue_id(d, id);
  500. if (err)
  501. return err;
  502. d->type_states[id].order_state = ORDERED;
  503. return 1;
  504. }
  505. case BTF_KIND_VOLATILE:
  506. case BTF_KIND_CONST:
  507. case BTF_KIND_RESTRICT:
  508. case BTF_KIND_TYPE_TAG:
  509. return btf_dump_order_type(d, t->type, through_ptr);
  510. case BTF_KIND_FUNC_PROTO: {
  511. const struct btf_param *p = btf_params(t);
  512. bool is_strong;
  513. err = btf_dump_order_type(d, t->type, through_ptr);
  514. if (err < 0)
  515. return err;
  516. is_strong = err > 0;
  517. vlen = btf_vlen(t);
  518. for (i = 0; i < vlen; i++, p++) {
  519. err = btf_dump_order_type(d, p->type, through_ptr);
  520. if (err < 0)
  521. return err;
  522. if (err > 0)
  523. is_strong = true;
  524. }
  525. return is_strong;
  526. }
  527. case BTF_KIND_FUNC:
  528. case BTF_KIND_VAR:
  529. case BTF_KIND_DATASEC:
  530. case BTF_KIND_DECL_TAG:
  531. d->type_states[id].order_state = ORDERED;
  532. return 0;
  533. default:
  534. return -EINVAL;
  535. }
  536. }
  537. static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
  538. const struct btf_type *t);
  539. static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
  540. const struct btf_type *t);
  541. static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
  542. const struct btf_type *t, int lvl);
  543. static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
  544. const struct btf_type *t);
  545. static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
  546. const struct btf_type *t, int lvl);
  547. static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
  548. const struct btf_type *t);
  549. static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
  550. const struct btf_type *t, int lvl);
  551. /* a local view into a shared stack */
  552. struct id_stack {
  553. const __u32 *ids;
  554. int cnt;
  555. };
  556. static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
  557. const char *fname, int lvl);
  558. static void btf_dump_emit_type_chain(struct btf_dump *d,
  559. struct id_stack *decl_stack,
  560. const char *fname, int lvl);
  561. static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
  562. static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
  563. static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
  564. const char *orig_name);
  565. static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
  566. {
  567. const struct btf_type *t = btf__type_by_id(d->btf, id);
  568. /* __builtin_va_list is a compiler built-in, which causes compilation
  569. * errors, when compiling w/ different compiler, then used to compile
  570. * original code (e.g., GCC to compile kernel, Clang to use generated
  571. * C header from BTF). As it is built-in, it should be already defined
  572. * properly internally in compiler.
  573. */
  574. if (t->name_off == 0)
  575. return false;
  576. return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
  577. }
  578. /*
  579. * Emit C-syntax definitions of types from chains of BTF types.
  580. *
  581. * High-level handling of determining necessary forward declarations are handled
  582. * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
  583. * declarations/definitions in C syntax are handled by a combo of
  584. * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
  585. * corresponding btf_dump_emit_*_{def,fwd}() functions.
  586. *
  587. * We also keep track of "containing struct/union type ID" to determine when
  588. * we reference it from inside and thus can avoid emitting unnecessary forward
  589. * declaration.
  590. *
  591. * This algorithm is designed in such a way, that even if some error occurs
  592. * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
  593. * that doesn't comply to C rules completely), algorithm will try to proceed
  594. * and produce as much meaningful output as possible.
  595. */
  596. static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
  597. {
  598. struct btf_dump_type_aux_state *tstate = &d->type_states[id];
  599. bool top_level_def = cont_id == 0;
  600. const struct btf_type *t;
  601. __u16 kind;
  602. if (tstate->emit_state == EMITTED)
  603. return;
  604. t = btf__type_by_id(d->btf, id);
  605. kind = btf_kind(t);
  606. if (tstate->emit_state == EMITTING) {
  607. if (tstate->fwd_emitted)
  608. return;
  609. switch (kind) {
  610. case BTF_KIND_STRUCT:
  611. case BTF_KIND_UNION:
  612. /*
  613. * if we are referencing a struct/union that we are
  614. * part of - then no need for fwd declaration
  615. */
  616. if (id == cont_id)
  617. return;
  618. if (t->name_off == 0) {
  619. pr_warn("anonymous struct/union loop, id:[%u]\n",
  620. id);
  621. return;
  622. }
  623. btf_dump_emit_struct_fwd(d, id, t);
  624. btf_dump_printf(d, ";\n\n");
  625. tstate->fwd_emitted = 1;
  626. break;
  627. case BTF_KIND_TYPEDEF:
  628. /*
  629. * for typedef fwd_emitted means typedef definition
  630. * was emitted, but it can be used only for "weak"
  631. * references through pointer only, not for embedding
  632. */
  633. if (!btf_dump_is_blacklisted(d, id)) {
  634. btf_dump_emit_typedef_def(d, id, t, 0);
  635. btf_dump_printf(d, ";\n\n");
  636. }
  637. tstate->fwd_emitted = 1;
  638. break;
  639. default:
  640. break;
  641. }
  642. return;
  643. }
  644. switch (kind) {
  645. case BTF_KIND_INT:
  646. /* Emit type alias definitions if necessary */
  647. btf_dump_emit_missing_aliases(d, id, t);
  648. tstate->emit_state = EMITTED;
  649. break;
  650. case BTF_KIND_ENUM:
  651. case BTF_KIND_ENUM64:
  652. if (top_level_def) {
  653. btf_dump_emit_enum_def(d, id, t, 0);
  654. btf_dump_printf(d, ";\n\n");
  655. }
  656. tstate->emit_state = EMITTED;
  657. break;
  658. case BTF_KIND_PTR:
  659. case BTF_KIND_VOLATILE:
  660. case BTF_KIND_CONST:
  661. case BTF_KIND_RESTRICT:
  662. case BTF_KIND_TYPE_TAG:
  663. btf_dump_emit_type(d, t->type, cont_id);
  664. break;
  665. case BTF_KIND_ARRAY:
  666. btf_dump_emit_type(d, btf_array(t)->type, cont_id);
  667. break;
  668. case BTF_KIND_FWD:
  669. btf_dump_emit_fwd_def(d, id, t);
  670. btf_dump_printf(d, ";\n\n");
  671. tstate->emit_state = EMITTED;
  672. break;
  673. case BTF_KIND_TYPEDEF:
  674. tstate->emit_state = EMITTING;
  675. btf_dump_emit_type(d, t->type, id);
  676. /*
  677. * typedef can server as both definition and forward
  678. * declaration; at this stage someone depends on
  679. * typedef as a forward declaration (refers to it
  680. * through pointer), so unless we already did it,
  681. * emit typedef as a forward declaration
  682. */
  683. if (!tstate->fwd_emitted && !btf_dump_is_blacklisted(d, id)) {
  684. btf_dump_emit_typedef_def(d, id, t, 0);
  685. btf_dump_printf(d, ";\n\n");
  686. }
  687. tstate->emit_state = EMITTED;
  688. break;
  689. case BTF_KIND_STRUCT:
  690. case BTF_KIND_UNION:
  691. tstate->emit_state = EMITTING;
  692. /* if it's a top-level struct/union definition or struct/union
  693. * is anonymous, then in C we'll be emitting all fields and
  694. * their types (as opposed to just `struct X`), so we need to
  695. * make sure that all types, referenced from struct/union
  696. * members have necessary forward-declarations, where
  697. * applicable
  698. */
  699. if (top_level_def || t->name_off == 0) {
  700. const struct btf_member *m = btf_members(t);
  701. __u16 vlen = btf_vlen(t);
  702. int i, new_cont_id;
  703. new_cont_id = t->name_off == 0 ? cont_id : id;
  704. for (i = 0; i < vlen; i++, m++)
  705. btf_dump_emit_type(d, m->type, new_cont_id);
  706. } else if (!tstate->fwd_emitted && id != cont_id) {
  707. btf_dump_emit_struct_fwd(d, id, t);
  708. btf_dump_printf(d, ";\n\n");
  709. tstate->fwd_emitted = 1;
  710. }
  711. if (top_level_def) {
  712. btf_dump_emit_struct_def(d, id, t, 0);
  713. btf_dump_printf(d, ";\n\n");
  714. tstate->emit_state = EMITTED;
  715. } else {
  716. tstate->emit_state = NOT_EMITTED;
  717. }
  718. break;
  719. case BTF_KIND_FUNC_PROTO: {
  720. const struct btf_param *p = btf_params(t);
  721. __u16 n = btf_vlen(t);
  722. int i;
  723. btf_dump_emit_type(d, t->type, cont_id);
  724. for (i = 0; i < n; i++, p++)
  725. btf_dump_emit_type(d, p->type, cont_id);
  726. break;
  727. }
  728. default:
  729. break;
  730. }
  731. }
  732. static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
  733. const struct btf_type *t)
  734. {
  735. const struct btf_member *m;
  736. int max_align = 1, align, i, bit_sz;
  737. __u16 vlen;
  738. m = btf_members(t);
  739. vlen = btf_vlen(t);
  740. /* all non-bitfield fields have to be naturally aligned */
  741. for (i = 0; i < vlen; i++, m++) {
  742. align = btf__align_of(btf, m->type);
  743. bit_sz = btf_member_bitfield_size(t, i);
  744. if (align && bit_sz == 0 && m->offset % (8 * align) != 0)
  745. return true;
  746. max_align = max(align, max_align);
  747. }
  748. /* size of a non-packed struct has to be a multiple of its alignment */
  749. if (t->size % max_align != 0)
  750. return true;
  751. /*
  752. * if original struct was marked as packed, but its layout is
  753. * naturally aligned, we'll detect that it's not packed
  754. */
  755. return false;
  756. }
  757. static void btf_dump_emit_bit_padding(const struct btf_dump *d,
  758. int cur_off, int next_off, int next_align,
  759. bool in_bitfield, int lvl)
  760. {
  761. const struct {
  762. const char *name;
  763. int bits;
  764. } pads[] = {
  765. {"long", d->ptr_sz * 8}, {"int", 32}, {"short", 16}, {"char", 8}
  766. };
  767. int new_off = 0, pad_bits = 0, bits, i;
  768. const char *pad_type = NULL;
  769. if (cur_off >= next_off)
  770. return; /* no gap */
  771. /* For filling out padding we want to take advantage of
  772. * natural alignment rules to minimize unnecessary explicit
  773. * padding. First, we find the largest type (among long, int,
  774. * short, or char) that can be used to force naturally aligned
  775. * boundary. Once determined, we'll use such type to fill in
  776. * the remaining padding gap. In some cases we can rely on
  777. * compiler filling some gaps, but sometimes we need to force
  778. * alignment to close natural alignment with markers like
  779. * `long: 0` (this is always the case for bitfields). Note
  780. * that even if struct itself has, let's say 4-byte alignment
  781. * (i.e., it only uses up to int-aligned types), using `long:
  782. * X;` explicit padding doesn't actually change struct's
  783. * overall alignment requirements, but compiler does take into
  784. * account that type's (long, in this example) natural
  785. * alignment requirements when adding implicit padding. We use
  786. * this fact heavily and don't worry about ruining correct
  787. * struct alignment requirement.
  788. */
  789. for (i = 0; i < ARRAY_SIZE(pads); i++) {
  790. pad_bits = pads[i].bits;
  791. pad_type = pads[i].name;
  792. new_off = roundup(cur_off, pad_bits);
  793. if (new_off <= next_off)
  794. break;
  795. }
  796. if (new_off > cur_off && new_off <= next_off) {
  797. /* We need explicit `<type>: 0` aligning mark if next
  798. * field is right on alignment offset and its
  799. * alignment requirement is less strict than <type>'s
  800. * alignment (so compiler won't naturally align to the
  801. * offset we expect), or if subsequent `<type>: X`,
  802. * will actually completely fit in the remaining hole,
  803. * making compiler basically ignore `<type>: X`
  804. * completely.
  805. */
  806. if (in_bitfield ||
  807. (new_off == next_off && roundup(cur_off, next_align * 8) != new_off) ||
  808. (new_off != next_off && next_off - new_off <= new_off - cur_off))
  809. /* but for bitfields we'll emit explicit bit count */
  810. btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type,
  811. in_bitfield ? new_off - cur_off : 0);
  812. cur_off = new_off;
  813. }
  814. /* Now we know we start at naturally aligned offset for a chosen
  815. * padding type (long, int, short, or char), and so the rest is just
  816. * a straightforward filling of remaining padding gap with full
  817. * `<type>: sizeof(<type>);` markers, except for the last one, which
  818. * might need smaller than sizeof(<type>) padding.
  819. */
  820. while (cur_off != next_off) {
  821. bits = min(next_off - cur_off, pad_bits);
  822. if (bits == pad_bits) {
  823. btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
  824. cur_off += bits;
  825. continue;
  826. }
  827. /* For the remainder padding that doesn't cover entire
  828. * pad_type bit length, we pick the smallest necessary type.
  829. * This is pure aesthetics, we could have just used `long`,
  830. * but having smallest necessary one communicates better the
  831. * scale of the padding gap.
  832. */
  833. for (i = ARRAY_SIZE(pads) - 1; i >= 0; i--) {
  834. pad_type = pads[i].name;
  835. pad_bits = pads[i].bits;
  836. if (pad_bits < bits)
  837. continue;
  838. btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, bits);
  839. cur_off += bits;
  840. break;
  841. }
  842. }
  843. }
  844. static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
  845. const struct btf_type *t)
  846. {
  847. btf_dump_printf(d, "%s%s%s",
  848. btf_is_struct(t) ? "struct" : "union",
  849. t->name_off ? " " : "",
  850. btf_dump_type_name(d, id));
  851. }
  852. static void btf_dump_emit_struct_def(struct btf_dump *d,
  853. __u32 id,
  854. const struct btf_type *t,
  855. int lvl)
  856. {
  857. const struct btf_member *m = btf_members(t);
  858. bool is_struct = btf_is_struct(t);
  859. bool packed, prev_bitfield = false;
  860. int align, i, off = 0;
  861. __u16 vlen = btf_vlen(t);
  862. align = btf__align_of(d->btf, id);
  863. packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
  864. btf_dump_printf(d, "%s%s%s {",
  865. is_struct ? "struct" : "union",
  866. t->name_off ? " " : "",
  867. btf_dump_type_name(d, id));
  868. for (i = 0; i < vlen; i++, m++) {
  869. const char *fname;
  870. int m_off, m_sz, m_align;
  871. bool in_bitfield;
  872. fname = btf_name_of(d, m->name_off);
  873. m_sz = btf_member_bitfield_size(t, i);
  874. m_off = btf_member_bit_offset(t, i);
  875. m_align = packed ? 1 : btf__align_of(d->btf, m->type);
  876. in_bitfield = prev_bitfield && m_sz != 0;
  877. btf_dump_emit_bit_padding(d, off, m_off, m_align, in_bitfield, lvl + 1);
  878. btf_dump_printf(d, "\n%s", pfx(lvl + 1));
  879. btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
  880. if (m_sz) {
  881. btf_dump_printf(d, ": %d", m_sz);
  882. off = m_off + m_sz;
  883. prev_bitfield = true;
  884. } else {
  885. m_sz = max((__s64)0, btf__resolve_size(d->btf, m->type));
  886. off = m_off + m_sz * 8;
  887. prev_bitfield = false;
  888. }
  889. btf_dump_printf(d, ";");
  890. }
  891. /* pad at the end, if necessary */
  892. if (is_struct)
  893. btf_dump_emit_bit_padding(d, off, t->size * 8, align, false, lvl + 1);
  894. /*
  895. * Keep `struct empty {}` on a single line,
  896. * only print newline when there are regular or padding fields.
  897. */
  898. if (vlen || t->size) {
  899. btf_dump_printf(d, "\n");
  900. btf_dump_printf(d, "%s}", pfx(lvl));
  901. } else {
  902. btf_dump_printf(d, "}");
  903. }
  904. if (packed)
  905. btf_dump_printf(d, " __attribute__((packed))");
  906. }
  907. static const char *missing_base_types[][2] = {
  908. /*
  909. * GCC emits typedefs to its internal __PolyX_t types when compiling Arm
  910. * SIMD intrinsics. Alias them to standard base types.
  911. */
  912. { "__Poly8_t", "unsigned char" },
  913. { "__Poly16_t", "unsigned short" },
  914. { "__Poly64_t", "unsigned long long" },
  915. { "__Poly128_t", "unsigned __int128" },
  916. };
  917. static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
  918. const struct btf_type *t)
  919. {
  920. const char *name = btf_dump_type_name(d, id);
  921. int i;
  922. for (i = 0; i < ARRAY_SIZE(missing_base_types); i++) {
  923. if (strcmp(name, missing_base_types[i][0]) == 0) {
  924. btf_dump_printf(d, "typedef %s %s;\n\n",
  925. missing_base_types[i][1], name);
  926. break;
  927. }
  928. }
  929. }
  930. static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
  931. const struct btf_type *t)
  932. {
  933. btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
  934. }
  935. static void btf_dump_emit_enum32_val(struct btf_dump *d,
  936. const struct btf_type *t,
  937. int lvl, __u16 vlen)
  938. {
  939. const struct btf_enum *v = btf_enum(t);
  940. bool is_signed = btf_kflag(t);
  941. const char *fmt_str;
  942. const char *name;
  943. size_t dup_cnt;
  944. int i;
  945. for (i = 0; i < vlen; i++, v++) {
  946. name = btf_name_of(d, v->name_off);
  947. /* enumerators share namespace with typedef idents */
  948. dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
  949. if (dup_cnt > 1) {
  950. fmt_str = is_signed ? "\n%s%s___%zd = %d," : "\n%s%s___%zd = %u,";
  951. btf_dump_printf(d, fmt_str, pfx(lvl + 1), name, dup_cnt, v->val);
  952. } else {
  953. fmt_str = is_signed ? "\n%s%s = %d," : "\n%s%s = %u,";
  954. btf_dump_printf(d, fmt_str, pfx(lvl + 1), name, v->val);
  955. }
  956. }
  957. }
  958. static void btf_dump_emit_enum64_val(struct btf_dump *d,
  959. const struct btf_type *t,
  960. int lvl, __u16 vlen)
  961. {
  962. const struct btf_enum64 *v = btf_enum64(t);
  963. bool is_signed = btf_kflag(t);
  964. const char *fmt_str;
  965. const char *name;
  966. size_t dup_cnt;
  967. __u64 val;
  968. int i;
  969. for (i = 0; i < vlen; i++, v++) {
  970. name = btf_name_of(d, v->name_off);
  971. dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
  972. val = btf_enum64_value(v);
  973. if (dup_cnt > 1) {
  974. fmt_str = is_signed ? "\n%s%s___%zd = %lldLL,"
  975. : "\n%s%s___%zd = %lluULL,";
  976. btf_dump_printf(d, fmt_str,
  977. pfx(lvl + 1), name, dup_cnt,
  978. (unsigned long long)val);
  979. } else {
  980. fmt_str = is_signed ? "\n%s%s = %lldLL,"
  981. : "\n%s%s = %lluULL,";
  982. btf_dump_printf(d, fmt_str,
  983. pfx(lvl + 1), name,
  984. (unsigned long long)val);
  985. }
  986. }
  987. }
  988. static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
  989. const struct btf_type *t,
  990. int lvl)
  991. {
  992. __u16 vlen = btf_vlen(t);
  993. btf_dump_printf(d, "enum%s%s",
  994. t->name_off ? " " : "",
  995. btf_dump_type_name(d, id));
  996. if (!vlen)
  997. return;
  998. btf_dump_printf(d, " {");
  999. if (btf_is_enum(t))
  1000. btf_dump_emit_enum32_val(d, t, lvl, vlen);
  1001. else
  1002. btf_dump_emit_enum64_val(d, t, lvl, vlen);
  1003. btf_dump_printf(d, "\n%s}", pfx(lvl));
  1004. /* special case enums with special sizes */
  1005. if (t->size == 1) {
  1006. /* one-byte enums can be forced with mode(byte) attribute */
  1007. btf_dump_printf(d, " __attribute__((mode(byte)))");
  1008. } else if (t->size == 8 && d->ptr_sz == 8) {
  1009. /* enum can be 8-byte sized if one of the enumerator values
  1010. * doesn't fit in 32-bit integer, or by adding mode(word)
  1011. * attribute (but probably only on 64-bit architectures); do
  1012. * our best here to try to satisfy the contract without adding
  1013. * unnecessary attributes
  1014. */
  1015. bool needs_word_mode;
  1016. if (btf_is_enum(t)) {
  1017. /* enum can't represent 64-bit values, so we need word mode */
  1018. needs_word_mode = true;
  1019. } else {
  1020. /* enum64 needs mode(word) if none of its values has
  1021. * non-zero upper 32-bits (which means that all values
  1022. * fit in 32-bit integers and won't cause compiler to
  1023. * bump enum to be 64-bit naturally
  1024. */
  1025. int i;
  1026. needs_word_mode = true;
  1027. for (i = 0; i < vlen; i++) {
  1028. if (btf_enum64(t)[i].val_hi32 != 0) {
  1029. needs_word_mode = false;
  1030. break;
  1031. }
  1032. }
  1033. }
  1034. if (needs_word_mode)
  1035. btf_dump_printf(d, " __attribute__((mode(word)))");
  1036. }
  1037. }
  1038. static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
  1039. const struct btf_type *t)
  1040. {
  1041. const char *name = btf_dump_type_name(d, id);
  1042. if (btf_kflag(t))
  1043. btf_dump_printf(d, "union %s", name);
  1044. else
  1045. btf_dump_printf(d, "struct %s", name);
  1046. }
  1047. static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
  1048. const struct btf_type *t, int lvl)
  1049. {
  1050. const char *name = btf_dump_ident_name(d, id);
  1051. /*
  1052. * Old GCC versions are emitting invalid typedef for __gnuc_va_list
  1053. * pointing to VOID. This generates warnings from btf_dump() and
  1054. * results in uncompilable header file, so we are fixing it up here
  1055. * with valid typedef into __builtin_va_list.
  1056. */
  1057. if (t->type == 0 && strcmp(name, "__gnuc_va_list") == 0) {
  1058. btf_dump_printf(d, "typedef __builtin_va_list __gnuc_va_list");
  1059. return;
  1060. }
  1061. btf_dump_printf(d, "typedef ");
  1062. btf_dump_emit_type_decl(d, t->type, name, lvl);
  1063. }
  1064. static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
  1065. {
  1066. __u32 *new_stack;
  1067. size_t new_cap;
  1068. if (d->decl_stack_cnt >= d->decl_stack_cap) {
  1069. new_cap = max(16, d->decl_stack_cap * 3 / 2);
  1070. new_stack = libbpf_reallocarray(d->decl_stack, new_cap, sizeof(new_stack[0]));
  1071. if (!new_stack)
  1072. return -ENOMEM;
  1073. d->decl_stack = new_stack;
  1074. d->decl_stack_cap = new_cap;
  1075. }
  1076. d->decl_stack[d->decl_stack_cnt++] = id;
  1077. return 0;
  1078. }
  1079. /*
  1080. * Emit type declaration (e.g., field type declaration in a struct or argument
  1081. * declaration in function prototype) in correct C syntax.
  1082. *
  1083. * For most types it's trivial, but there are few quirky type declaration
  1084. * cases worth mentioning:
  1085. * - function prototypes (especially nesting of function prototypes);
  1086. * - arrays;
  1087. * - const/volatile/restrict for pointers vs other types.
  1088. *
  1089. * For a good discussion of *PARSING* C syntax (as a human), see
  1090. * Peter van der Linden's "Expert C Programming: Deep C Secrets",
  1091. * Ch.3 "Unscrambling Declarations in C".
  1092. *
  1093. * It won't help with BTF to C conversion much, though, as it's an opposite
  1094. * problem. So we came up with this algorithm in reverse to van der Linden's
  1095. * parsing algorithm. It goes from structured BTF representation of type
  1096. * declaration to a valid compilable C syntax.
  1097. *
  1098. * For instance, consider this C typedef:
  1099. * typedef const int * const * arr[10] arr_t;
  1100. * It will be represented in BTF with this chain of BTF types:
  1101. * [typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
  1102. *
  1103. * Notice how [const] modifier always goes before type it modifies in BTF type
  1104. * graph, but in C syntax, const/volatile/restrict modifiers are written to
  1105. * the right of pointers, but to the left of other types. There are also other
  1106. * quirks, like function pointers, arrays of them, functions returning other
  1107. * functions, etc.
  1108. *
  1109. * We handle that by pushing all the types to a stack, until we hit "terminal"
  1110. * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
  1111. * top of a stack, modifiers are handled differently. Array/function pointers
  1112. * have also wildly different syntax and how nesting of them are done. See
  1113. * code for authoritative definition.
  1114. *
  1115. * To avoid allocating new stack for each independent chain of BTF types, we
  1116. * share one bigger stack, with each chain working only on its own local view
  1117. * of a stack frame. Some care is required to "pop" stack frames after
  1118. * processing type declaration chain.
  1119. */
  1120. int btf_dump__emit_type_decl(struct btf_dump *d, __u32 id,
  1121. const struct btf_dump_emit_type_decl_opts *opts)
  1122. {
  1123. const char *fname;
  1124. int lvl, err;
  1125. if (!OPTS_VALID(opts, btf_dump_emit_type_decl_opts))
  1126. return libbpf_err(-EINVAL);
  1127. err = btf_dump_resize(d);
  1128. if (err)
  1129. return libbpf_err(err);
  1130. fname = OPTS_GET(opts, field_name, "");
  1131. lvl = OPTS_GET(opts, indent_level, 0);
  1132. d->strip_mods = OPTS_GET(opts, strip_mods, false);
  1133. btf_dump_emit_type_decl(d, id, fname, lvl);
  1134. d->strip_mods = false;
  1135. return 0;
  1136. }
  1137. static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
  1138. const char *fname, int lvl)
  1139. {
  1140. struct id_stack decl_stack;
  1141. const struct btf_type *t;
  1142. int err, stack_start;
  1143. stack_start = d->decl_stack_cnt;
  1144. for (;;) {
  1145. t = btf__type_by_id(d->btf, id);
  1146. if (d->strip_mods && btf_is_mod(t))
  1147. goto skip_mod;
  1148. err = btf_dump_push_decl_stack_id(d, id);
  1149. if (err < 0) {
  1150. /*
  1151. * if we don't have enough memory for entire type decl
  1152. * chain, restore stack, emit warning, and try to
  1153. * proceed nevertheless
  1154. */
  1155. pr_warn("not enough memory for decl stack: %s\n", errstr(err));
  1156. d->decl_stack_cnt = stack_start;
  1157. return;
  1158. }
  1159. skip_mod:
  1160. /* VOID */
  1161. if (id == 0)
  1162. break;
  1163. switch (btf_kind(t)) {
  1164. case BTF_KIND_PTR:
  1165. case BTF_KIND_VOLATILE:
  1166. case BTF_KIND_CONST:
  1167. case BTF_KIND_RESTRICT:
  1168. case BTF_KIND_FUNC_PROTO:
  1169. case BTF_KIND_TYPE_TAG:
  1170. id = t->type;
  1171. break;
  1172. case BTF_KIND_ARRAY:
  1173. id = btf_array(t)->type;
  1174. break;
  1175. case BTF_KIND_INT:
  1176. case BTF_KIND_ENUM:
  1177. case BTF_KIND_ENUM64:
  1178. case BTF_KIND_FWD:
  1179. case BTF_KIND_STRUCT:
  1180. case BTF_KIND_UNION:
  1181. case BTF_KIND_TYPEDEF:
  1182. case BTF_KIND_FLOAT:
  1183. goto done;
  1184. default:
  1185. pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
  1186. btf_kind(t), id);
  1187. goto done;
  1188. }
  1189. }
  1190. done:
  1191. /*
  1192. * We might be inside a chain of declarations (e.g., array of function
  1193. * pointers returning anonymous (so inlined) structs, having another
  1194. * array field). Each of those needs its own "stack frame" to handle
  1195. * emitting of declarations. Those stack frames are non-overlapping
  1196. * portions of shared btf_dump->decl_stack. To make it a bit nicer to
  1197. * handle this set of nested stacks, we create a view corresponding to
  1198. * our own "stack frame" and work with it as an independent stack.
  1199. * We'll need to clean up after emit_type_chain() returns, though.
  1200. */
  1201. decl_stack.ids = d->decl_stack + stack_start;
  1202. decl_stack.cnt = d->decl_stack_cnt - stack_start;
  1203. btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
  1204. /*
  1205. * emit_type_chain() guarantees that it will pop its entire decl_stack
  1206. * frame before returning. But it works with a read-only view into
  1207. * decl_stack, so it doesn't actually pop anything from the
  1208. * perspective of shared btf_dump->decl_stack, per se. We need to
  1209. * reset decl_stack state to how it was before us to avoid it growing
  1210. * all the time.
  1211. */
  1212. d->decl_stack_cnt = stack_start;
  1213. }
  1214. static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
  1215. {
  1216. const struct btf_type *t;
  1217. __u32 id;
  1218. while (decl_stack->cnt) {
  1219. id = decl_stack->ids[decl_stack->cnt - 1];
  1220. t = btf__type_by_id(d->btf, id);
  1221. switch (btf_kind(t)) {
  1222. case BTF_KIND_VOLATILE:
  1223. btf_dump_printf(d, "volatile ");
  1224. break;
  1225. case BTF_KIND_CONST:
  1226. btf_dump_printf(d, "const ");
  1227. break;
  1228. case BTF_KIND_RESTRICT:
  1229. btf_dump_printf(d, "restrict ");
  1230. break;
  1231. default:
  1232. return;
  1233. }
  1234. decl_stack->cnt--;
  1235. }
  1236. }
  1237. static void btf_dump_drop_mods(struct btf_dump *d, struct id_stack *decl_stack)
  1238. {
  1239. const struct btf_type *t;
  1240. __u32 id;
  1241. while (decl_stack->cnt) {
  1242. id = decl_stack->ids[decl_stack->cnt - 1];
  1243. t = btf__type_by_id(d->btf, id);
  1244. if (!btf_is_mod(t))
  1245. return;
  1246. decl_stack->cnt--;
  1247. }
  1248. }
  1249. static void btf_dump_emit_name(const struct btf_dump *d,
  1250. const char *name, bool last_was_ptr)
  1251. {
  1252. bool separate = name[0] && !last_was_ptr;
  1253. btf_dump_printf(d, "%s%s", separate ? " " : "", name);
  1254. }
  1255. static void btf_dump_emit_type_chain(struct btf_dump *d,
  1256. struct id_stack *decls,
  1257. const char *fname, int lvl)
  1258. {
  1259. /*
  1260. * last_was_ptr is used to determine if we need to separate pointer
  1261. * asterisk (*) from previous part of type signature with space, so
  1262. * that we get `int ***`, instead of `int * * *`. We default to true
  1263. * for cases where we have single pointer in a chain. E.g., in ptr ->
  1264. * func_proto case. func_proto will start a new emit_type_chain call
  1265. * with just ptr, which should be emitted as (*) or (*<fname>), so we
  1266. * don't want to prepend space for that last pointer.
  1267. */
  1268. bool last_was_ptr = true;
  1269. const struct btf_type *t;
  1270. const char *name;
  1271. __u16 kind;
  1272. __u32 id;
  1273. while (decls->cnt) {
  1274. id = decls->ids[--decls->cnt];
  1275. if (id == 0) {
  1276. /* VOID is a special snowflake */
  1277. btf_dump_emit_mods(d, decls);
  1278. btf_dump_printf(d, "void");
  1279. last_was_ptr = false;
  1280. continue;
  1281. }
  1282. t = btf__type_by_id(d->btf, id);
  1283. kind = btf_kind(t);
  1284. switch (kind) {
  1285. case BTF_KIND_INT:
  1286. case BTF_KIND_FLOAT:
  1287. btf_dump_emit_mods(d, decls);
  1288. name = btf_name_of(d, t->name_off);
  1289. btf_dump_printf(d, "%s", name);
  1290. break;
  1291. case BTF_KIND_STRUCT:
  1292. case BTF_KIND_UNION:
  1293. btf_dump_emit_mods(d, decls);
  1294. /* inline anonymous struct/union */
  1295. if (t->name_off == 0 && !d->skip_anon_defs)
  1296. btf_dump_emit_struct_def(d, id, t, lvl);
  1297. else
  1298. btf_dump_emit_struct_fwd(d, id, t);
  1299. break;
  1300. case BTF_KIND_ENUM:
  1301. case BTF_KIND_ENUM64:
  1302. btf_dump_emit_mods(d, decls);
  1303. /* inline anonymous enum */
  1304. if (t->name_off == 0 && !d->skip_anon_defs)
  1305. btf_dump_emit_enum_def(d, id, t, lvl);
  1306. else
  1307. btf_dump_emit_enum_fwd(d, id, t);
  1308. break;
  1309. case BTF_KIND_FWD:
  1310. btf_dump_emit_mods(d, decls);
  1311. btf_dump_emit_fwd_def(d, id, t);
  1312. break;
  1313. case BTF_KIND_TYPEDEF:
  1314. btf_dump_emit_mods(d, decls);
  1315. btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
  1316. break;
  1317. case BTF_KIND_PTR:
  1318. btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
  1319. break;
  1320. case BTF_KIND_VOLATILE:
  1321. btf_dump_printf(d, " volatile");
  1322. break;
  1323. case BTF_KIND_CONST:
  1324. btf_dump_printf(d, " const");
  1325. break;
  1326. case BTF_KIND_RESTRICT:
  1327. btf_dump_printf(d, " restrict");
  1328. break;
  1329. case BTF_KIND_TYPE_TAG:
  1330. btf_dump_emit_mods(d, decls);
  1331. name = btf_name_of(d, t->name_off);
  1332. if (btf_kflag(t))
  1333. btf_dump_printf(d, " __attribute__((%s))", name);
  1334. else
  1335. btf_dump_printf(d, " __attribute__((btf_type_tag(\"%s\")))", name);
  1336. break;
  1337. case BTF_KIND_ARRAY: {
  1338. const struct btf_array *a = btf_array(t);
  1339. const struct btf_type *next_t;
  1340. __u32 next_id;
  1341. bool multidim;
  1342. /*
  1343. * GCC has a bug
  1344. * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
  1345. * which causes it to emit extra const/volatile
  1346. * modifiers for an array, if array's element type has
  1347. * const/volatile modifiers. Clang doesn't do that.
  1348. * In general, it doesn't seem very meaningful to have
  1349. * a const/volatile modifier for array, so we are
  1350. * going to silently skip them here.
  1351. */
  1352. btf_dump_drop_mods(d, decls);
  1353. if (decls->cnt == 0) {
  1354. btf_dump_emit_name(d, fname, last_was_ptr);
  1355. btf_dump_printf(d, "[%u]", a->nelems);
  1356. return;
  1357. }
  1358. next_id = decls->ids[decls->cnt - 1];
  1359. next_t = btf__type_by_id(d->btf, next_id);
  1360. multidim = btf_is_array(next_t);
  1361. /* we need space if we have named non-pointer */
  1362. if (fname[0] && !last_was_ptr)
  1363. btf_dump_printf(d, " ");
  1364. /* no parentheses for multi-dimensional array */
  1365. if (!multidim)
  1366. btf_dump_printf(d, "(");
  1367. btf_dump_emit_type_chain(d, decls, fname, lvl);
  1368. if (!multidim)
  1369. btf_dump_printf(d, ")");
  1370. btf_dump_printf(d, "[%u]", a->nelems);
  1371. return;
  1372. }
  1373. case BTF_KIND_FUNC_PROTO: {
  1374. const struct btf_param *p = btf_params(t);
  1375. __u16 vlen = btf_vlen(t);
  1376. int i;
  1377. /*
  1378. * GCC emits extra volatile qualifier for
  1379. * __attribute__((noreturn)) function pointers. Clang
  1380. * doesn't do it. It's a GCC quirk for backwards
  1381. * compatibility with code written for GCC <2.5. So,
  1382. * similarly to extra qualifiers for array, just drop
  1383. * them, instead of handling them.
  1384. */
  1385. btf_dump_drop_mods(d, decls);
  1386. if (decls->cnt) {
  1387. btf_dump_printf(d, " (");
  1388. btf_dump_emit_type_chain(d, decls, fname, lvl);
  1389. btf_dump_printf(d, ")");
  1390. } else {
  1391. btf_dump_emit_name(d, fname, last_was_ptr);
  1392. }
  1393. btf_dump_printf(d, "(");
  1394. /*
  1395. * Clang for BPF target generates func_proto with no
  1396. * args as a func_proto with a single void arg (e.g.,
  1397. * `int (*f)(void)` vs just `int (*f)()`). We are
  1398. * going to emit valid empty args (void) syntax for
  1399. * such case. Similarly and conveniently, valid
  1400. * no args case can be special-cased here as well.
  1401. */
  1402. if (vlen == 0 || (vlen == 1 && p->type == 0)) {
  1403. btf_dump_printf(d, "void)");
  1404. return;
  1405. }
  1406. for (i = 0; i < vlen; i++, p++) {
  1407. if (i > 0)
  1408. btf_dump_printf(d, ", ");
  1409. /* last arg of type void is vararg */
  1410. if (i == vlen - 1 && p->type == 0) {
  1411. btf_dump_printf(d, "...");
  1412. break;
  1413. }
  1414. name = btf_name_of(d, p->name_off);
  1415. btf_dump_emit_type_decl(d, p->type, name, lvl);
  1416. }
  1417. btf_dump_printf(d, ")");
  1418. return;
  1419. }
  1420. default:
  1421. pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
  1422. kind, id);
  1423. return;
  1424. }
  1425. last_was_ptr = kind == BTF_KIND_PTR;
  1426. }
  1427. btf_dump_emit_name(d, fname, last_was_ptr);
  1428. }
  1429. /* show type name as (type_name) */
  1430. static void btf_dump_emit_type_cast(struct btf_dump *d, __u32 id,
  1431. bool top_level)
  1432. {
  1433. const struct btf_type *t;
  1434. /* for array members, we don't bother emitting type name for each
  1435. * member to avoid the redundancy of
  1436. * .name = (char[4])[(char)'f',(char)'o',(char)'o',]
  1437. */
  1438. if (d->typed_dump->is_array_member)
  1439. return;
  1440. /* avoid type name specification for variable/section; it will be done
  1441. * for the associated variable value(s).
  1442. */
  1443. t = btf__type_by_id(d->btf, id);
  1444. if (btf_is_var(t) || btf_is_datasec(t))
  1445. return;
  1446. if (top_level)
  1447. btf_dump_printf(d, "(");
  1448. d->skip_anon_defs = true;
  1449. d->strip_mods = true;
  1450. btf_dump_emit_type_decl(d, id, "", 0);
  1451. d->strip_mods = false;
  1452. d->skip_anon_defs = false;
  1453. if (top_level)
  1454. btf_dump_printf(d, ")");
  1455. }
  1456. /* return number of duplicates (occurrences) of a given name */
  1457. static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
  1458. const char *orig_name)
  1459. {
  1460. char *old_name, *new_name;
  1461. size_t dup_cnt = 0;
  1462. int err;
  1463. new_name = strdup(orig_name);
  1464. if (!new_name)
  1465. return 1;
  1466. (void)hashmap__find(name_map, orig_name, &dup_cnt);
  1467. dup_cnt++;
  1468. err = hashmap__set(name_map, new_name, dup_cnt, &old_name, NULL);
  1469. if (err)
  1470. free(new_name);
  1471. free(old_name);
  1472. return dup_cnt;
  1473. }
  1474. static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
  1475. struct hashmap *name_map)
  1476. {
  1477. struct btf_dump_type_aux_state *s = &d->type_states[id];
  1478. const struct btf_type *t = btf__type_by_id(d->btf, id);
  1479. const char *orig_name = btf_name_of(d, t->name_off);
  1480. const char **cached_name = &d->cached_names[id];
  1481. size_t dup_cnt;
  1482. if (t->name_off == 0)
  1483. return "";
  1484. if (s->name_resolved)
  1485. return *cached_name ? *cached_name : orig_name;
  1486. if (btf_is_fwd(t) || (btf_is_enum(t) && btf_vlen(t) == 0)) {
  1487. s->name_resolved = 1;
  1488. return orig_name;
  1489. }
  1490. dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
  1491. if (dup_cnt > 1) {
  1492. const size_t max_len = 256;
  1493. char new_name[max_len];
  1494. snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
  1495. *cached_name = strdup(new_name);
  1496. }
  1497. s->name_resolved = 1;
  1498. return *cached_name ? *cached_name : orig_name;
  1499. }
  1500. static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
  1501. {
  1502. return btf_dump_resolve_name(d, id, d->type_names);
  1503. }
  1504. static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
  1505. {
  1506. return btf_dump_resolve_name(d, id, d->ident_names);
  1507. }
  1508. static int btf_dump_dump_type_data(struct btf_dump *d,
  1509. const char *fname,
  1510. const struct btf_type *t,
  1511. __u32 id,
  1512. const void *data,
  1513. __u8 bits_offset,
  1514. __u8 bit_sz);
  1515. static const char *btf_dump_data_newline(struct btf_dump *d)
  1516. {
  1517. return d->typed_dump->compact || d->typed_dump->depth == 0 ? "" : "\n";
  1518. }
  1519. static const char *btf_dump_data_delim(struct btf_dump *d)
  1520. {
  1521. return d->typed_dump->depth == 0 ? "" : ",";
  1522. }
  1523. static void btf_dump_data_pfx(struct btf_dump *d)
  1524. {
  1525. int i, lvl = d->typed_dump->indent_lvl + d->typed_dump->depth;
  1526. if (d->typed_dump->compact)
  1527. return;
  1528. for (i = 0; i < lvl; i++)
  1529. btf_dump_printf(d, "%s", d->typed_dump->indent_str);
  1530. }
  1531. /* A macro is used here as btf_type_value[s]() appends format specifiers
  1532. * to the format specifier passed in; these do the work of appending
  1533. * delimiters etc while the caller simply has to specify the type values
  1534. * in the format specifier + value(s).
  1535. */
  1536. #define btf_dump_type_values(d, fmt, ...) \
  1537. btf_dump_printf(d, fmt "%s%s", \
  1538. ##__VA_ARGS__, \
  1539. btf_dump_data_delim(d), \
  1540. btf_dump_data_newline(d))
  1541. static int btf_dump_unsupported_data(struct btf_dump *d,
  1542. const struct btf_type *t,
  1543. __u32 id)
  1544. {
  1545. btf_dump_printf(d, "<unsupported kind:%u>", btf_kind(t));
  1546. return -ENOTSUP;
  1547. }
  1548. static int btf_dump_get_bitfield_value(struct btf_dump *d,
  1549. const struct btf_type *t,
  1550. const void *data,
  1551. __u8 bits_offset,
  1552. __u8 bit_sz,
  1553. __u64 *value)
  1554. {
  1555. __u16 left_shift_bits, right_shift_bits;
  1556. const __u8 *bytes = data;
  1557. __u8 nr_copy_bits;
  1558. __u8 start_bit, nr_bytes;
  1559. __u64 num = 0;
  1560. int i;
  1561. /* Calculate how many bytes cover the bitfield */
  1562. start_bit = bits_offset % 8;
  1563. nr_bytes = (start_bit + bit_sz + 7) / 8;
  1564. /* Bound check */
  1565. if (data + nr_bytes > d->typed_dump->data_end)
  1566. return -E2BIG;
  1567. /* Maximum supported bitfield size is 64 bits */
  1568. if (t->size > 8) {
  1569. pr_warn("unexpected bitfield size %d\n", t->size);
  1570. return -EINVAL;
  1571. }
  1572. /* Bitfield value retrieval is done in two steps; first relevant bytes are
  1573. * stored in num, then we left/right shift num to eliminate irrelevant bits.
  1574. */
  1575. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  1576. for (i = t->size - 1; i >= 0; i--)
  1577. num = num * 256 + bytes[i];
  1578. nr_copy_bits = bit_sz + bits_offset;
  1579. #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  1580. for (i = 0; i < t->size; i++)
  1581. num = num * 256 + bytes[i];
  1582. nr_copy_bits = t->size * 8 - bits_offset;
  1583. #else
  1584. # error "Unrecognized __BYTE_ORDER__"
  1585. #endif
  1586. left_shift_bits = 64 - nr_copy_bits;
  1587. right_shift_bits = 64 - bit_sz;
  1588. *value = (num << left_shift_bits) >> right_shift_bits;
  1589. return 0;
  1590. }
  1591. static int btf_dump_bitfield_check_zero(struct btf_dump *d,
  1592. const struct btf_type *t,
  1593. const void *data,
  1594. __u8 bits_offset,
  1595. __u8 bit_sz)
  1596. {
  1597. __u64 check_num;
  1598. int err;
  1599. err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &check_num);
  1600. if (err)
  1601. return err;
  1602. if (check_num == 0)
  1603. return -ENODATA;
  1604. return 0;
  1605. }
  1606. static int btf_dump_bitfield_data(struct btf_dump *d,
  1607. const struct btf_type *t,
  1608. const void *data,
  1609. __u8 bits_offset,
  1610. __u8 bit_sz)
  1611. {
  1612. __u64 print_num;
  1613. int err;
  1614. err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &print_num);
  1615. if (err)
  1616. return err;
  1617. btf_dump_type_values(d, "0x%llx", (unsigned long long)print_num);
  1618. return 0;
  1619. }
  1620. /* ints, floats and ptrs */
  1621. static int btf_dump_base_type_check_zero(struct btf_dump *d,
  1622. const struct btf_type *t,
  1623. __u32 id,
  1624. const void *data)
  1625. {
  1626. static __u8 bytecmp[16] = {};
  1627. int nr_bytes;
  1628. /* For pointer types, pointer size is not defined on a per-type basis.
  1629. * On dump creation however, we store the pointer size.
  1630. */
  1631. if (btf_kind(t) == BTF_KIND_PTR)
  1632. nr_bytes = d->ptr_sz;
  1633. else
  1634. nr_bytes = t->size;
  1635. if (nr_bytes < 1 || nr_bytes > 16) {
  1636. pr_warn("unexpected size %d for id [%u]\n", nr_bytes, id);
  1637. return -EINVAL;
  1638. }
  1639. if (memcmp(data, bytecmp, nr_bytes) == 0)
  1640. return -ENODATA;
  1641. return 0;
  1642. }
  1643. static bool ptr_is_aligned(const struct btf *btf, __u32 type_id,
  1644. const void *data)
  1645. {
  1646. int alignment = btf__align_of(btf, type_id);
  1647. if (alignment == 0)
  1648. return false;
  1649. return ((uintptr_t)data) % alignment == 0;
  1650. }
  1651. static int btf_dump_int_data(struct btf_dump *d,
  1652. const struct btf_type *t,
  1653. __u32 type_id,
  1654. const void *data,
  1655. __u8 bits_offset)
  1656. {
  1657. __u8 encoding = btf_int_encoding(t);
  1658. bool sign = encoding & BTF_INT_SIGNED;
  1659. char buf[16] __attribute__((aligned(16)));
  1660. int sz = t->size;
  1661. if (sz == 0 || sz > sizeof(buf)) {
  1662. pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
  1663. return -EINVAL;
  1664. }
  1665. /* handle packed int data - accesses of integers not aligned on
  1666. * int boundaries can cause problems on some platforms.
  1667. */
  1668. if (!ptr_is_aligned(d->btf, type_id, data)) {
  1669. memcpy(buf, data, sz);
  1670. data = buf;
  1671. }
  1672. switch (sz) {
  1673. case 16: {
  1674. const __u64 *ints = data;
  1675. __u64 lsi, msi;
  1676. /* avoid use of __int128 as some 32-bit platforms do not
  1677. * support it.
  1678. */
  1679. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  1680. lsi = ints[0];
  1681. msi = ints[1];
  1682. #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  1683. lsi = ints[1];
  1684. msi = ints[0];
  1685. #else
  1686. # error "Unrecognized __BYTE_ORDER__"
  1687. #endif
  1688. if (msi == 0)
  1689. btf_dump_type_values(d, "0x%llx", (unsigned long long)lsi);
  1690. else
  1691. btf_dump_type_values(d, "0x%llx%016llx", (unsigned long long)msi,
  1692. (unsigned long long)lsi);
  1693. break;
  1694. }
  1695. case 8:
  1696. if (sign)
  1697. btf_dump_type_values(d, "%lld", *(long long *)data);
  1698. else
  1699. btf_dump_type_values(d, "%llu", *(unsigned long long *)data);
  1700. break;
  1701. case 4:
  1702. if (sign)
  1703. btf_dump_type_values(d, "%d", *(__s32 *)data);
  1704. else
  1705. btf_dump_type_values(d, "%u", *(__u32 *)data);
  1706. break;
  1707. case 2:
  1708. if (sign)
  1709. btf_dump_type_values(d, "%d", *(__s16 *)data);
  1710. else
  1711. btf_dump_type_values(d, "%u", *(__u16 *)data);
  1712. break;
  1713. case 1:
  1714. if (d->typed_dump->is_array_char) {
  1715. /* check for null terminator */
  1716. if (d->typed_dump->is_array_terminated)
  1717. break;
  1718. if (*(char *)data == '\0') {
  1719. btf_dump_type_values(d, "'\\0'");
  1720. d->typed_dump->is_array_terminated = true;
  1721. break;
  1722. }
  1723. if (isprint(*(char *)data)) {
  1724. btf_dump_type_values(d, "'%c'", *(char *)data);
  1725. break;
  1726. }
  1727. }
  1728. if (sign)
  1729. btf_dump_type_values(d, "%d", *(__s8 *)data);
  1730. else
  1731. btf_dump_type_values(d, "%u", *(__u8 *)data);
  1732. break;
  1733. default:
  1734. pr_warn("unexpected sz %d for id [%u]\n", sz, type_id);
  1735. return -EINVAL;
  1736. }
  1737. return 0;
  1738. }
  1739. union float_data {
  1740. long double ld;
  1741. double d;
  1742. float f;
  1743. };
  1744. static int btf_dump_float_data(struct btf_dump *d,
  1745. const struct btf_type *t,
  1746. __u32 type_id,
  1747. const void *data)
  1748. {
  1749. const union float_data *flp = data;
  1750. union float_data fl;
  1751. int sz = t->size;
  1752. /* handle unaligned data; copy to local union */
  1753. if (!ptr_is_aligned(d->btf, type_id, data)) {
  1754. memcpy(&fl, data, sz);
  1755. flp = &fl;
  1756. }
  1757. switch (sz) {
  1758. case 16:
  1759. btf_dump_type_values(d, "%Lf", flp->ld);
  1760. break;
  1761. case 8:
  1762. btf_dump_type_values(d, "%lf", flp->d);
  1763. break;
  1764. case 4:
  1765. btf_dump_type_values(d, "%f", flp->f);
  1766. break;
  1767. default:
  1768. pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
  1769. return -EINVAL;
  1770. }
  1771. return 0;
  1772. }
  1773. static int btf_dump_var_data(struct btf_dump *d,
  1774. const struct btf_type *v,
  1775. __u32 id,
  1776. const void *data)
  1777. {
  1778. enum btf_func_linkage linkage = btf_var(v)->linkage;
  1779. const struct btf_type *t;
  1780. const char *l;
  1781. __u32 type_id;
  1782. switch (linkage) {
  1783. case BTF_FUNC_STATIC:
  1784. l = "static ";
  1785. break;
  1786. case BTF_FUNC_EXTERN:
  1787. l = "extern ";
  1788. break;
  1789. case BTF_FUNC_GLOBAL:
  1790. default:
  1791. l = "";
  1792. break;
  1793. }
  1794. /* format of output here is [linkage] [type] [varname] = (type)value,
  1795. * for example "static int cpu_profile_flip = (int)1"
  1796. */
  1797. btf_dump_printf(d, "%s", l);
  1798. type_id = v->type;
  1799. t = btf__type_by_id(d->btf, type_id);
  1800. btf_dump_emit_type_cast(d, type_id, false);
  1801. btf_dump_printf(d, " %s = ", btf_name_of(d, v->name_off));
  1802. return btf_dump_dump_type_data(d, NULL, t, type_id, data, 0, 0);
  1803. }
  1804. static int btf_dump_string_data(struct btf_dump *d,
  1805. const struct btf_type *t,
  1806. __u32 id,
  1807. const void *data)
  1808. {
  1809. const struct btf_array *array = btf_array(t);
  1810. const char *chars = data;
  1811. __u32 i;
  1812. /* Make sure it is a NUL-terminated string. */
  1813. for (i = 0; i < array->nelems; i++) {
  1814. if ((void *)(chars + i) >= d->typed_dump->data_end)
  1815. return -E2BIG;
  1816. if (chars[i] == '\0')
  1817. break;
  1818. }
  1819. if (i == array->nelems) {
  1820. /* The caller will print this as a regular array. */
  1821. return -EINVAL;
  1822. }
  1823. btf_dump_data_pfx(d);
  1824. btf_dump_printf(d, "\"");
  1825. for (i = 0; i < array->nelems; i++) {
  1826. char c = chars[i];
  1827. if (c == '\0') {
  1828. /*
  1829. * When printing character arrays as strings, NUL bytes
  1830. * are always treated as string terminators; they are
  1831. * never printed.
  1832. */
  1833. break;
  1834. }
  1835. if (isprint(c))
  1836. btf_dump_printf(d, "%c", c);
  1837. else
  1838. btf_dump_printf(d, "\\x%02x", (__u8)c);
  1839. }
  1840. btf_dump_printf(d, "\"");
  1841. return 0;
  1842. }
  1843. static int btf_dump_array_data(struct btf_dump *d,
  1844. const struct btf_type *t,
  1845. __u32 id,
  1846. const void *data)
  1847. {
  1848. const struct btf_array *array = btf_array(t);
  1849. const struct btf_type *elem_type;
  1850. __u32 i, elem_type_id;
  1851. __s64 elem_size;
  1852. bool is_array_member;
  1853. bool is_array_terminated;
  1854. elem_type_id = array->type;
  1855. elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
  1856. elem_size = btf__resolve_size(d->btf, elem_type_id);
  1857. if (elem_size <= 0) {
  1858. pr_warn("unexpected elem size %zd for array type [%u]\n",
  1859. (ssize_t)elem_size, id);
  1860. return -EINVAL;
  1861. }
  1862. if (btf_is_int(elem_type)) {
  1863. /*
  1864. * BTF_INT_CHAR encoding never seems to be set for
  1865. * char arrays, so if size is 1 and element is
  1866. * printable as a char, we'll do that.
  1867. */
  1868. if (elem_size == 1) {
  1869. if (d->typed_dump->emit_strings &&
  1870. btf_dump_string_data(d, t, id, data) == 0) {
  1871. return 0;
  1872. }
  1873. d->typed_dump->is_array_char = true;
  1874. }
  1875. }
  1876. /* note that we increment depth before calling btf_dump_print() below;
  1877. * this is intentional. btf_dump_data_newline() will not print a
  1878. * newline for depth 0 (since this leaves us with trailing newlines
  1879. * at the end of typed display), so depth is incremented first.
  1880. * For similar reasons, we decrement depth before showing the closing
  1881. * parenthesis.
  1882. */
  1883. d->typed_dump->depth++;
  1884. btf_dump_printf(d, "[%s", btf_dump_data_newline(d));
  1885. /* may be a multidimensional array, so store current "is array member"
  1886. * status so we can restore it correctly later.
  1887. */
  1888. is_array_member = d->typed_dump->is_array_member;
  1889. d->typed_dump->is_array_member = true;
  1890. is_array_terminated = d->typed_dump->is_array_terminated;
  1891. d->typed_dump->is_array_terminated = false;
  1892. for (i = 0; i < array->nelems; i++, data += elem_size) {
  1893. if (d->typed_dump->is_array_terminated)
  1894. break;
  1895. btf_dump_dump_type_data(d, NULL, elem_type, elem_type_id, data, 0, 0);
  1896. }
  1897. d->typed_dump->is_array_member = is_array_member;
  1898. d->typed_dump->is_array_terminated = is_array_terminated;
  1899. d->typed_dump->depth--;
  1900. btf_dump_data_pfx(d);
  1901. btf_dump_type_values(d, "]");
  1902. return 0;
  1903. }
  1904. static int btf_dump_struct_data(struct btf_dump *d,
  1905. const struct btf_type *t,
  1906. __u32 id,
  1907. const void *data)
  1908. {
  1909. const struct btf_member *m = btf_members(t);
  1910. __u16 n = btf_vlen(t);
  1911. int i, err = 0;
  1912. /* note that we increment depth before calling btf_dump_print() below;
  1913. * this is intentional. btf_dump_data_newline() will not print a
  1914. * newline for depth 0 (since this leaves us with trailing newlines
  1915. * at the end of typed display), so depth is incremented first.
  1916. * For similar reasons, we decrement depth before showing the closing
  1917. * parenthesis.
  1918. */
  1919. d->typed_dump->depth++;
  1920. btf_dump_printf(d, "{%s", btf_dump_data_newline(d));
  1921. for (i = 0; i < n; i++, m++) {
  1922. const struct btf_type *mtype;
  1923. const char *mname;
  1924. __u32 moffset;
  1925. __u8 bit_sz;
  1926. mtype = btf__type_by_id(d->btf, m->type);
  1927. mname = btf_name_of(d, m->name_off);
  1928. moffset = btf_member_bit_offset(t, i);
  1929. bit_sz = btf_member_bitfield_size(t, i);
  1930. err = btf_dump_dump_type_data(d, mname, mtype, m->type, data + moffset / 8,
  1931. moffset % 8, bit_sz);
  1932. if (err < 0)
  1933. return err;
  1934. }
  1935. d->typed_dump->depth--;
  1936. btf_dump_data_pfx(d);
  1937. btf_dump_type_values(d, "}");
  1938. return err;
  1939. }
  1940. union ptr_data {
  1941. unsigned int p;
  1942. unsigned long long lp;
  1943. };
  1944. static int btf_dump_ptr_data(struct btf_dump *d,
  1945. const struct btf_type *t,
  1946. __u32 id,
  1947. const void *data)
  1948. {
  1949. if (ptr_is_aligned(d->btf, id, data) && d->ptr_sz == sizeof(void *)) {
  1950. btf_dump_type_values(d, "%p", *(void **)data);
  1951. } else {
  1952. union ptr_data pt;
  1953. memcpy(&pt, data, d->ptr_sz);
  1954. if (d->ptr_sz == 4)
  1955. btf_dump_type_values(d, "0x%x", pt.p);
  1956. else
  1957. btf_dump_type_values(d, "0x%llx", pt.lp);
  1958. }
  1959. return 0;
  1960. }
  1961. static int btf_dump_get_enum_value(struct btf_dump *d,
  1962. const struct btf_type *t,
  1963. const void *data,
  1964. __u32 id,
  1965. __s64 *value)
  1966. {
  1967. bool is_signed = btf_kflag(t);
  1968. if (!ptr_is_aligned(d->btf, id, data)) {
  1969. __u64 val;
  1970. int err;
  1971. err = btf_dump_get_bitfield_value(d, t, data, 0, 0, &val);
  1972. if (err)
  1973. return err;
  1974. *value = (__s64)val;
  1975. return 0;
  1976. }
  1977. switch (t->size) {
  1978. case 8:
  1979. *value = *(__s64 *)data;
  1980. return 0;
  1981. case 4:
  1982. *value = is_signed ? (__s64)*(__s32 *)data : *(__u32 *)data;
  1983. return 0;
  1984. case 2:
  1985. *value = is_signed ? *(__s16 *)data : *(__u16 *)data;
  1986. return 0;
  1987. case 1:
  1988. *value = is_signed ? *(__s8 *)data : *(__u8 *)data;
  1989. return 0;
  1990. default:
  1991. pr_warn("unexpected size %d for enum, id:[%u]\n", t->size, id);
  1992. return -EINVAL;
  1993. }
  1994. }
  1995. static int btf_dump_enum_data(struct btf_dump *d,
  1996. const struct btf_type *t,
  1997. __u32 id,
  1998. const void *data)
  1999. {
  2000. bool is_signed;
  2001. __s64 value;
  2002. int i, err;
  2003. err = btf_dump_get_enum_value(d, t, data, id, &value);
  2004. if (err)
  2005. return err;
  2006. is_signed = btf_kflag(t);
  2007. if (btf_is_enum(t)) {
  2008. const struct btf_enum *e;
  2009. for (i = 0, e = btf_enum(t); i < btf_vlen(t); i++, e++) {
  2010. if (value != e->val)
  2011. continue;
  2012. btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
  2013. return 0;
  2014. }
  2015. btf_dump_type_values(d, is_signed ? "%d" : "%u", value);
  2016. } else {
  2017. const struct btf_enum64 *e;
  2018. for (i = 0, e = btf_enum64(t); i < btf_vlen(t); i++, e++) {
  2019. if (value != btf_enum64_value(e))
  2020. continue;
  2021. btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
  2022. return 0;
  2023. }
  2024. btf_dump_type_values(d, is_signed ? "%lldLL" : "%lluULL",
  2025. (unsigned long long)value);
  2026. }
  2027. return 0;
  2028. }
  2029. static int btf_dump_datasec_data(struct btf_dump *d,
  2030. const struct btf_type *t,
  2031. __u32 id,
  2032. const void *data)
  2033. {
  2034. const struct btf_var_secinfo *vsi;
  2035. const struct btf_type *var;
  2036. __u32 i;
  2037. int err;
  2038. btf_dump_type_values(d, "SEC(\"%s\") ", btf_name_of(d, t->name_off));
  2039. for (i = 0, vsi = btf_var_secinfos(t); i < btf_vlen(t); i++, vsi++) {
  2040. var = btf__type_by_id(d->btf, vsi->type);
  2041. err = btf_dump_dump_type_data(d, NULL, var, vsi->type, data + vsi->offset, 0, 0);
  2042. if (err < 0)
  2043. return err;
  2044. btf_dump_printf(d, ";");
  2045. }
  2046. return 0;
  2047. }
  2048. /* return size of type, or if base type overflows, return -E2BIG. */
  2049. static int btf_dump_type_data_check_overflow(struct btf_dump *d,
  2050. const struct btf_type *t,
  2051. __u32 id,
  2052. const void *data,
  2053. __u8 bits_offset,
  2054. __u8 bit_sz)
  2055. {
  2056. __s64 size;
  2057. if (bit_sz) {
  2058. /* bits_offset is at most 7. bit_sz is at most 128. */
  2059. __u8 nr_bytes = (bits_offset + bit_sz + 7) / 8;
  2060. /* When bit_sz is non zero, it is called from
  2061. * btf_dump_struct_data() where it only cares about
  2062. * negative error value.
  2063. * Return nr_bytes in success case to make it
  2064. * consistent as the regular integer case below.
  2065. */
  2066. return data + nr_bytes > d->typed_dump->data_end ? -E2BIG : nr_bytes;
  2067. }
  2068. size = btf__resolve_size(d->btf, id);
  2069. if (size < 0 || size >= INT_MAX) {
  2070. pr_warn("unexpected size [%zu] for id [%u]\n",
  2071. (size_t)size, id);
  2072. return -EINVAL;
  2073. }
  2074. /* Only do overflow checking for base types; we do not want to
  2075. * avoid showing part of a struct, union or array, even if we
  2076. * do not have enough data to show the full object. By
  2077. * restricting overflow checking to base types we can ensure
  2078. * that partial display succeeds, while avoiding overflowing
  2079. * and using bogus data for display.
  2080. */
  2081. t = skip_mods_and_typedefs(d->btf, id, NULL);
  2082. if (!t) {
  2083. pr_warn("unexpected error skipping mods/typedefs for id [%u]\n",
  2084. id);
  2085. return -EINVAL;
  2086. }
  2087. switch (btf_kind(t)) {
  2088. case BTF_KIND_INT:
  2089. case BTF_KIND_FLOAT:
  2090. case BTF_KIND_PTR:
  2091. case BTF_KIND_ENUM:
  2092. case BTF_KIND_ENUM64:
  2093. if (data + bits_offset / 8 + size > d->typed_dump->data_end)
  2094. return -E2BIG;
  2095. break;
  2096. default:
  2097. break;
  2098. }
  2099. return (int)size;
  2100. }
  2101. static int btf_dump_type_data_check_zero(struct btf_dump *d,
  2102. const struct btf_type *t,
  2103. __u32 id,
  2104. const void *data,
  2105. __u8 bits_offset,
  2106. __u8 bit_sz)
  2107. {
  2108. __s64 value;
  2109. int i, err;
  2110. /* toplevel exceptions; we show zero values if
  2111. * - we ask for them (emit_zeros)
  2112. * - if we are at top-level so we see "struct empty { }"
  2113. * - or if we are an array member and the array is non-empty and
  2114. * not a char array; we don't want to be in a situation where we
  2115. * have an integer array 0, 1, 0, 1 and only show non-zero values.
  2116. * If the array contains zeroes only, or is a char array starting
  2117. * with a '\0', the array-level check_zero() will prevent showing it;
  2118. * we are concerned with determining zero value at the array member
  2119. * level here.
  2120. */
  2121. if (d->typed_dump->emit_zeroes || d->typed_dump->depth == 0 ||
  2122. (d->typed_dump->is_array_member &&
  2123. !d->typed_dump->is_array_char))
  2124. return 0;
  2125. t = skip_mods_and_typedefs(d->btf, id, NULL);
  2126. switch (btf_kind(t)) {
  2127. case BTF_KIND_INT:
  2128. if (bit_sz)
  2129. return btf_dump_bitfield_check_zero(d, t, data, bits_offset, bit_sz);
  2130. return btf_dump_base_type_check_zero(d, t, id, data);
  2131. case BTF_KIND_FLOAT:
  2132. case BTF_KIND_PTR:
  2133. return btf_dump_base_type_check_zero(d, t, id, data);
  2134. case BTF_KIND_ARRAY: {
  2135. const struct btf_array *array = btf_array(t);
  2136. const struct btf_type *elem_type;
  2137. __u32 elem_type_id, elem_size;
  2138. bool ischar;
  2139. elem_type_id = array->type;
  2140. elem_size = btf__resolve_size(d->btf, elem_type_id);
  2141. elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
  2142. ischar = btf_is_int(elem_type) && elem_size == 1;
  2143. /* check all elements; if _any_ element is nonzero, all
  2144. * of array is displayed. We make an exception however
  2145. * for char arrays where the first element is 0; these
  2146. * are considered zeroed also, even if later elements are
  2147. * non-zero because the string is terminated.
  2148. */
  2149. for (i = 0; i < array->nelems; i++) {
  2150. if (i == 0 && ischar && *(char *)data == 0)
  2151. return -ENODATA;
  2152. err = btf_dump_type_data_check_zero(d, elem_type,
  2153. elem_type_id,
  2154. data +
  2155. (i * elem_size),
  2156. bits_offset, 0);
  2157. if (err != -ENODATA)
  2158. return err;
  2159. }
  2160. return -ENODATA;
  2161. }
  2162. case BTF_KIND_STRUCT:
  2163. case BTF_KIND_UNION: {
  2164. const struct btf_member *m = btf_members(t);
  2165. __u16 n = btf_vlen(t);
  2166. /* if any struct/union member is non-zero, the struct/union
  2167. * is considered non-zero and dumped.
  2168. */
  2169. for (i = 0; i < n; i++, m++) {
  2170. const struct btf_type *mtype;
  2171. __u32 moffset;
  2172. mtype = btf__type_by_id(d->btf, m->type);
  2173. moffset = btf_member_bit_offset(t, i);
  2174. /* btf_int_bits() does not store member bitfield size;
  2175. * bitfield size needs to be stored here so int display
  2176. * of member can retrieve it.
  2177. */
  2178. bit_sz = btf_member_bitfield_size(t, i);
  2179. err = btf_dump_type_data_check_zero(d, mtype, m->type, data + moffset / 8,
  2180. moffset % 8, bit_sz);
  2181. if (err != ENODATA)
  2182. return err;
  2183. }
  2184. return -ENODATA;
  2185. }
  2186. case BTF_KIND_ENUM:
  2187. case BTF_KIND_ENUM64:
  2188. err = btf_dump_get_enum_value(d, t, data, id, &value);
  2189. if (err)
  2190. return err;
  2191. if (value == 0)
  2192. return -ENODATA;
  2193. return 0;
  2194. default:
  2195. return 0;
  2196. }
  2197. }
  2198. /* returns size of data dumped, or error. */
  2199. static int btf_dump_dump_type_data(struct btf_dump *d,
  2200. const char *fname,
  2201. const struct btf_type *t,
  2202. __u32 id,
  2203. const void *data,
  2204. __u8 bits_offset,
  2205. __u8 bit_sz)
  2206. {
  2207. int size, err = 0;
  2208. size = btf_dump_type_data_check_overflow(d, t, id, data, bits_offset, bit_sz);
  2209. if (size < 0)
  2210. return size;
  2211. err = btf_dump_type_data_check_zero(d, t, id, data, bits_offset, bit_sz);
  2212. if (err) {
  2213. /* zeroed data is expected and not an error, so simply skip
  2214. * dumping such data. Record other errors however.
  2215. */
  2216. if (err == -ENODATA)
  2217. return size;
  2218. return err;
  2219. }
  2220. btf_dump_data_pfx(d);
  2221. if (!d->typed_dump->skip_names) {
  2222. if (fname && strlen(fname) > 0)
  2223. btf_dump_printf(d, ".%s = ", fname);
  2224. btf_dump_emit_type_cast(d, id, true);
  2225. }
  2226. t = skip_mods_and_typedefs(d->btf, id, NULL);
  2227. switch (btf_kind(t)) {
  2228. case BTF_KIND_UNKN:
  2229. case BTF_KIND_FWD:
  2230. case BTF_KIND_FUNC:
  2231. case BTF_KIND_FUNC_PROTO:
  2232. case BTF_KIND_DECL_TAG:
  2233. err = btf_dump_unsupported_data(d, t, id);
  2234. break;
  2235. case BTF_KIND_INT:
  2236. if (bit_sz)
  2237. err = btf_dump_bitfield_data(d, t, data, bits_offset, bit_sz);
  2238. else
  2239. err = btf_dump_int_data(d, t, id, data, bits_offset);
  2240. break;
  2241. case BTF_KIND_FLOAT:
  2242. err = btf_dump_float_data(d, t, id, data);
  2243. break;
  2244. case BTF_KIND_PTR:
  2245. err = btf_dump_ptr_data(d, t, id, data);
  2246. break;
  2247. case BTF_KIND_ARRAY:
  2248. err = btf_dump_array_data(d, t, id, data);
  2249. break;
  2250. case BTF_KIND_STRUCT:
  2251. case BTF_KIND_UNION:
  2252. err = btf_dump_struct_data(d, t, id, data);
  2253. break;
  2254. case BTF_KIND_ENUM:
  2255. case BTF_KIND_ENUM64:
  2256. /* handle bitfield and int enum values */
  2257. if (bit_sz) {
  2258. __u64 print_num;
  2259. __s64 enum_val;
  2260. err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz,
  2261. &print_num);
  2262. if (err)
  2263. break;
  2264. enum_val = (__s64)print_num;
  2265. err = btf_dump_enum_data(d, t, id, &enum_val);
  2266. } else
  2267. err = btf_dump_enum_data(d, t, id, data);
  2268. break;
  2269. case BTF_KIND_VAR:
  2270. err = btf_dump_var_data(d, t, id, data);
  2271. break;
  2272. case BTF_KIND_DATASEC:
  2273. err = btf_dump_datasec_data(d, t, id, data);
  2274. break;
  2275. default:
  2276. pr_warn("unexpected kind [%u] for id [%u]\n",
  2277. BTF_INFO_KIND(t->info), id);
  2278. return -EINVAL;
  2279. }
  2280. if (err < 0)
  2281. return err;
  2282. return size;
  2283. }
  2284. int btf_dump__dump_type_data(struct btf_dump *d, __u32 id,
  2285. const void *data, size_t data_sz,
  2286. const struct btf_dump_type_data_opts *opts)
  2287. {
  2288. struct btf_dump_data typed_dump = {};
  2289. const struct btf_type *t;
  2290. int ret;
  2291. if (!OPTS_VALID(opts, btf_dump_type_data_opts))
  2292. return libbpf_err(-EINVAL);
  2293. t = btf__type_by_id(d->btf, id);
  2294. if (!t)
  2295. return libbpf_err(-ENOENT);
  2296. d->typed_dump = &typed_dump;
  2297. d->typed_dump->data_end = data + data_sz;
  2298. d->typed_dump->indent_lvl = OPTS_GET(opts, indent_level, 0);
  2299. /* default indent string is a tab */
  2300. if (!OPTS_GET(opts, indent_str, NULL))
  2301. d->typed_dump->indent_str[0] = '\t';
  2302. else
  2303. libbpf_strlcpy(d->typed_dump->indent_str, opts->indent_str,
  2304. sizeof(d->typed_dump->indent_str));
  2305. d->typed_dump->compact = OPTS_GET(opts, compact, false);
  2306. d->typed_dump->skip_names = OPTS_GET(opts, skip_names, false);
  2307. d->typed_dump->emit_zeroes = OPTS_GET(opts, emit_zeroes, false);
  2308. d->typed_dump->emit_strings = OPTS_GET(opts, emit_strings, false);
  2309. ret = btf_dump_dump_type_data(d, NULL, t, id, data, 0, 0);
  2310. d->typed_dump = NULL;
  2311. return libbpf_err(ret);
  2312. }