pahole: Support more rust tags and references to dwz alternate debug files
cover pahole: Support more rust tags and references to dwz alternate debug files
Hi,
Add support for Rust discriminated unions (enums with explicit discriminants).
Rust enums like Option<u32> and Result<i32,u8> are represented in DWARF as DW_TAG_variant_part containing DW_TAG_variant children with discriminant values. These patches:
- Load DW_TAG_variant_part containers with discriminant tracking
- Populate DW_TAG_variant children with discriminant values
- Handle DW_FORM_block encoding for discriminant values
- Handle DW_TAG_subprogram inside DW_TAG_enumeration (Rust methods)
- Encode variant parts as BTF_KIND_UNION members
Before: Rust Option<u32> showed as empty struct (0 members)
After: Shows None and Some variants with correct layout
=== pahole --expand_types output ===
struct Option<u32> {
struct None {
} __attribute__((__aligned__(4)));
struct Some {
/* XXX 4 bytes hole, try to pack */
u32 __0 __attribute__((__aligned__(4))); /* 4 4 */
} __attribute__((__aligned__(4)));
} __attribute__((__aligned__(4)));BTF has no discriminated-union kind, so variant parts are tentatively encoded as BTF_KIND_UNION with overlapping members at offset 0. Further discussion is needed to see if we can keep that.
DW_FORM_block byte order fix: uses CU-recorded endianness instead of assuming little-endian when decoding DW_AT_const_value and DW_AT_default_value. Fixes cross-endian DWARF processing (e.g. reading big-endian s390x debug info on x86).
Also add support for cross-CU type references and dwz alternate debug files.
This is needed to improve the support for, among other things, Rust, as noticed in the pretty printing or a perf binary that has rust objects linked, built by clang/llvm that use cross-CU references.
DW_TAG_imported_unit support:
Handle same-file partial units where types are shared across CUs via DW_TAG_imported_unit. Force-merge CUs that contain inter-CU references (DW_FORM_ref_addr) so type lookups resolve correctly.
Fix cus__merging_cu failing to detect DW_FORM_ref_addr when DW_FORM_implicit_const causes dwarf_getabbrevattr() to fail.
dwz alternate debug file support:
Handle DW_FORM_GNU_ref_alt references to dwz-compressed alternate debug files (.dwz). Pre-processes all alternate partial units with separate hash tables and dedup tracking.
Before (Firefox): 1774 "has no entry in cu" errors
After: processes cleanly with 0 errors
Firefox uses dwz compression which moves common types into a separate .dwz file and replaces duplicates with DW_FORM_GNU_ref_alt references. pahole now pre-loads the alternate file's partial units, resolves all cross-file references, and processes Firefox DWARF cleanly.
Includes inter-CU type reference comparison test and vmlinux_comparison.py for DWARF/BTF analysis across kernel configs.
Known limitations:
- Pruning of unreferenced alt PUs is conservatively over-approximated
- Merged-CU path is single-threaded by design
This makes pahole to be able to support more of the CONFIG_DEBUG_ DWARF options, including DWARF5 and compression, see the latest patch in the series for more details about how this table is produced:
┌───────────────────────────┬─────────┬─────┬───────────────────────────────────┬─────────┬───────┬──────────┬────────┬──────────┬─────────┐ │ File │ Size │ Ver │ Producer │ DWARF │ BTF │ DW-Hash │ DW-Out │ BTF-Hash │ BTF-Out │ ├───────────────────────────┼─────────┼─────┼───────────────────────────────────┼─────────┼───────┼──────────┼────────┼──────────┼─────────┤ │ vmlinux.dwarf4 │ 835.7MB │ 4 │ GNU C11 16.1.1 -gdwarf-4 │ 599.2MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.dwarf5 │ 736.3MB │ 5 │ GNU C11 16.1.1 -gdwarf-5 │ 499.7MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.dwarf5.zlib │ 497.8MB │ 5 │ GNU C11 16.1.1 -gdwarf-5 -gz=zlib │ 261.2MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.dwarf5.zstd │ 454.7MB │ 5 │ GNU C11 16.1.1 -gdwarf-5 -gz=zstd │ 218.1MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.toolchain_default │ 736.3MB │ 5 │ GNU C11 16.1.1 │ 499.7MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ └───────────────────────────┴─────────┴─────┴───────────────────────────────────┴─────────┴───────┴──────────┴────────┴──────────┴─────────┘
Split DWARF support (skeleton CUs) will be supported in upcoming work, so as to cover all the possibilities the kernel build system offers for generating DWARF.
- Arnaldo
Arnaldo Carvalho de Melo (12):
dwarf_loader: Initial support for DW_TAG_variant_part
dwarf_loader: Initial support for DW_TAG_subprogram in DW_TAG_enumeration
dwarf_loader: Populate DW_TAG_variant children in DW_TAG_variant_part
btf_encoder: Encode variant parts as union members in BTF
dwarf_loader: Handle DW_FORM_block in attr_numeric for Rust discriminant values
dwarf_loader: Allow forcing the merge of CUs for solving inter CU tag references
dwarf_loader: Support DW_TAG_imported_unit for same-file partial units
dwarf_loader: Fix cus__merging_cu failing to detect DW_FORM_ref_addr
dwarf_loader: Add cu parameter to tag__set_spec() and dwarf_tag__set_attr_type()
dwarf_loader: Support DW_FORM_GNU_ref_alt references to dwz alternate debug files
tests: Add inter-CU type reference comparison test
scripts: Add vmlinux_comparison.py for DWARF/BTF analysis
btf_encoder.c | 66 ++- ctf_encoder.c | 34 +- dwarf_loader.c | 873 ++++++++++++++++++++++++++++++---- dwarves.c | 77 ++- dwarves.h | 63 ++- dwarves_emit.c | 10 +- dwarves_fprintf.c | 54 ++- man-pages/pahole.1 | 18 +- pahole.c | 20 +- scripts/vmlinux_comparison.py | 367 ++++++++++++++ tests/block_endian.sh | 146 ++++++ tests/dwz_alt_file.sh | 204 ++++++++ tests/inter_cu_refs.sh | 50 ++ tests/prettify_perf.data.sh | 4 +- 14 files changed, 1854 insertions(+), 132 deletions(-) create mode 100755 scripts/vmlinux_comparison.py create mode 100755 tests/block_endian.sh create mode 100755 tests/dwz_alt_file.sh create mode 100755 tests/inter_cu_refs.sh
Signature · 1 line
2.55.0
PATCH 1/12 dwarf_loader: Initial support for DW_TAG_variant_part
From: Arnaldo Carvalho de Melo <[email protected]>
Still doesn't handle its sub hierarchy, i.e. the DW_TAG_variant entries and its underlying DW_TAG_member entries.
This was noticed when running the regression test that uses a debug build of perf to process a perf.data file and test pahole's pretty printing features, as now perf has a synthetic workload that is written in rust:
<0><20c95a>: Abbrev Number: 1 (DW_TAG_compile_unit)
<20c95b> DW_AT_producer : (indirect string, offset: 0x4ee5a): clang LLVM (rustc version 1.93.1 (01f6ddf75 2026-02-11) (Fedora 1.93.1-1.fc43))
<20c95f> DW_AT_language : 28 (Rust)
<20c961> DW_AT_name : (indirect string, offset: 0x4eeaa): tests/workloads/code_with_type.rs/@/code_with_type.d6e680867bfb8b27-cgu.0
<20c965> DW_AT_stmt_list : 0x5e1ed
<20c969> DW_AT_comp_dir : (indirect string, offset: 0x487f1): /home/acme/git/perf-tools/tools/perf
<20c96d> DW_AT_low_pc : 0
<20c975> DW_AT_ranges : 0x2d0⬢ [acme@toolbx pahole]$
So lets add some scaffolding for the Rust DWARF constructs involved for us to be able to continue using perf with DWARF to test the pretty printing features.
--- dwarf_loader.c | 26 +++++++++++++++++++++++++- dwarves.c | 27 +++++++++++++++++++++++++++ dwarves.h | 16 ++++++++++++++++ 3 files changed, 68 insertions(+), 1 deletion(-)
dwarf_loader.c +25 -1
@@ -522,6 +522,8 @@ static void tag__init(struct tag *tag, struct cu *cu, Dwarf_Die *die)if (tag->tag == DW_TAG_imported_module || tag->tag == DW_TAG_imported_declaration)dwarf_tag__set_attr_type (dtag, type, die, DW_AT_import); +else if (tag->tag == DW_TAG_variant_part) +dwarf_tag__set_attr_type (dtag, type, die, DW_AT_discr);else dwarf_tag__set_attr_type (dtag, type, die, DW_AT_type);
@@ -1238,6 +1240,18 @@ static struct template_parameter_pack *template_parameter_pack__new(Dwarf_Die *dreturn pack; } +static struct variant_part *variant_part__new (Dwarf_Die *die,struct cu *cu,struct conf_load *conf) +{ +struct variant_part *vpart =tag__alloc (cu,sizeof (*vpart)); + +if (vpart !=NULL ) { +tag__init (&vpart->tag, cu, die); +INIT_LIST_HEAD (&vpart->variants); + } + +return vpart; +} +/* Returns number of locations found or negative value for errors. */ static ptrdiff_t __dwarf_getlocations(Dwarf_Attribute *attr, ptrdiff_t offset, Dwarf_Addr *basep,
@@ -2357,9 +2371,19 @@ static int die__process_class(Dwarf_Die *die, struct type *class,case DW_TAG_GNU_template_template_param:#endif case DW_TAG_subrange_type:// XXX: ADA stuff, its a type tho, will have other entries referencing it... -case DW_TAG_variant_part:// XXX: Rust stuff tag__print_not_supported (die);continue ; +case DW_TAG_variant_part: { +struct variant_part *vpart =variant_part__new (die, cu, conf); + +if (vpart ==NULL ) +return -ENOMEM ; + +// For rust it seems we have just one, but DWARF, according to Gemini, support having +// more than one DW_TAG_variant_part for a given DW_TAG_structure_type, so future proof it +type__add_variant_part (class, vpart); +continue ; + }case DW_TAG_template_type_parameter: {struct template_type_param *ttparm =template_type_param__new (die, cu, conf);
dwarves.c +27 -0
@@ -405,6 +405,7 @@ void __type__init(struct type *type)INIT_LIST_HEAD (&type->type_enum);INIT_LIST_HEAD (&type->template_type_params);INIT_LIST_HEAD (&type->template_value_params); +INIT_LIST_HEAD (&type->variant_parts); type->template_parameter_pack =NULL ; type->sizeof_member =NULL ; type->member_prefix =NULL ;
@@ -1210,12 +1211,31 @@ static void type__delete_class_members(struct type *type, struct cu *cu) } } +static void variant_part__delete (struct variant_part *vpart,struct cu *cu) +{ +if (vpart ==NULL ) +return ; + +cu__tag_free (cu, &vpart->tag); +} + +static void type__delete_variant_parts (struct type *type,struct cu *cu) +{ +struct variant_part *pos, *next; + +type__for_each_variant_part_safe_reverse (type, pos, next) { +list_del_init (&pos->tag.node); +variant_part__delete (pos, cu); + } +} +void class__delete (struct class *class,struct cu *cu) {if (class ==NULL )return ;type__delete_class_members (&class->type, cu); +type__delete_variant_parts (&class->type, cu);cu__tag_free (cu,class__tag (class)); }
@@ -1225,6 +1245,7 @@ void type__delete(struct type *type, struct cu *cu)return ;type__delete_class_members (type, cu); +type__delete_variant_parts (type, cu);if (type->suffix_disambiguation)zfree (&type->namespace.name);
@@ -1288,6 +1309,11 @@ void type__add_template_value_param(struct type *type, struct template_value_parlist_add_tail (&tvparam->tag.node, &type->template_value_params); } +void type__add_variant_part (struct type *type,struct variant_part *vpart) +{ +list_add_tail (&vpart->tag.node, &type->variant_parts); +} +struct class_member *type__last_member (struct type *type) {struct class_member *pos;
@@ -1308,6 +1334,7 @@ static int type__clone_members(struct type *type, const struct type *from, strucINIT_LIST_HEAD (&type->type_enum);INIT_LIST_HEAD (&type->template_type_params);INIT_LIST_HEAD (&type->template_value_params); +INIT_LIST_HEAD (&type->variant_parts);type__for_each_member (from, pos) {struct class_member *clone =class_member__clone (pos, cu);
dwarves.h +16 -0
@@ -1021,6 +1021,11 @@ static inline struct formal_parameter_pack *tag__formal_parameter_pack(const strvoid formal_parameter_pack__add (struct formal_parameter_pack *pack,struct parameter *param); +struct variant_part { +struct tag tag; +struct list_head variants; +}; +/* * tag.tag can be DW_TAG_subprogram_type or DW_TAG_subroutine_type. */
@@ -1292,6 +1297,7 @@ struct type { uint8_t is_signed_enum:1;struct list_head template_type_params;struct list_head template_value_params; +struct list_head variant_parts;struct template_parameter_pack *template_parameter_pack; };
@@ -1409,9 +1415,19 @@ static inline struct class_member *class_member__next(struct class_member *membe#define type__for_each_tag_safe_reverse (type, pos, n) \ list_for_each_entry_safe_reverse(pos, n, &(type)->namespace.tags, tag.node) +/** +* type__for_each_variant_part_safe_reverse - safely iterate thru all variant_parts in a type, in reverse order +* @type: struct type instance to iterate +* @pos: struct variant_part iterator +* @n: struct variant_part temp iterator +*/ +#define type__for_each_variant_part_safe_reverse (type, pos, n) \ + list_for_each_entry_safe_reverse(pos, n, &(type)->variant_parts, tag.node) +void type__add_member (struct type *type,struct class_member *member);void type__add_template_type_param (struct type *type,struct template_type_param *ttparm);void type__add_template_value_param (struct type *type,struct template_value_param *tvparam); +void type__add_variant_part (struct type *type,struct variant_part *vpart);struct class_member * type__find_first_biggest_size_base_type_member(struct type *type,
Signature · 1 line
2.55.0
PATCH 2/12 dwarf_loader: Initial support for DW_TAG_subprogram in DW_TAG_enumeration
In reply to Arnaldo Carvalho de MeloFrom: Arnaldo Carvalho de Melo <[email protected]>
In Rust enums can have subprograms, add initial support for it.
Example of a Rust enumeration with a DW_TAG_subprogram tag.
$ pahole -C ProgramKind /tmp/build/perf-tools-next/tests/workloads/code_with_type.a
enum ProgramKind {
PathLookup = 0,
Relative = 1,
Absolute = 2,
enum ProgramKind new(struct &std::ffi::os_str::OsStr),
} __attribute__((__packed__));
$--- btf_encoder.c | 26 +++++++++++++++++------ ctf_encoder.c | 23 ++++++++++++++------ dwarf_loader.c | 39 +++++++++++++++++++++++++++------- dwarves.c | 10 ++++----- dwarves.h | 2 +- dwarves_emit.c | 10 ++++----- dwarves_fprintf.c | 54 +++++++++++++++++++++++++++++++++++------------ pahole.c | 9 +++++--- 8 files changed, 123 insertions(+), 50 deletions(-)
btf_encoder.c +19 -7
@@ -1888,7 +1888,7 @@ static int32_t btf_encoder__add_struct_type(struct btf_encoder *encoder, struct }static int32_t btf_encoder__add_enum_type (struct btf_encoder *encoder,struct tag *tag, -struct conf_load *conf_load) +const struct cu *cu,struct conf_load *conf_load) {struct type *etype =tag__type (tag);struct enumerator *pos;
@@ -1900,9 +1900,22 @@ static int32_t btf_encoder__add_enum_type(struct btf_encoder *encoder, struct tareturn type_id;type__for_each_enumerator (etype, pos) { - name =enumerator__name (pos); -if (btf_encoder__add_enum_val (encoder, name, pos->value, etype, conf_load)) -return -1 ; +switch (pos->tag.tag) { +case DW_TAG_enumerator: + name =enumerator__name (pos); +if (btf_encoder__add_enum_val (encoder, name, pos->value, etype, conf_load)) +return -1 ; +break ; +case DW_TAG_subprogram: +if (encoder->verbose) +fprintf (stderr,"BTF: DW_TAG_subprogram in enumeration '%s' not supported, skipping\n" , +type__name (etype) ?:"(anonymous)" ); +break ; +default : +fprintf (stderr,"BTF: unexpected DW_TAG_%s in enumeration '%s', skipping\n" , +dwarf_tag_name (pos->tag.tag),type__name (etype) ?:"(anonymous)" ); +break ; + } }return type_id;
@@ -1929,8 +1942,7 @@ static int tag__nr_btf_ids(const struct tag *tag) }static int btf_encoder__encode_tag (struct btf_encoder *encoder,struct tag *tag, -const struct cu *cu__maybe_unused , -struct conf_load *conf_load) +const struct cu *cu,struct conf_load *conf_load) {/* single out type 0 as it represents special type "void" */ uint32_t ref_type_id =btf_encoder__tag_type (encoder, tag->type);
@@ -2000,7 +2012,7 @@ static int btf_encoder__encode_tag(struct btf_encoder *encoder, struct tag *tag,return id; }case DW_TAG_enumeration_type: -return btf_encoder__add_enum_type (encoder, tag, conf_load); +return btf_encoder__add_enum_type (encoder, tag, cu, conf_load);case DW_TAG_subroutine_type:return btf_encoder__add_func_proto_for_ftype (encoder,tag__ftype (tag));case DW_TAG_unspecified_type:
ctf_encoder.c +17 -6
@@ -142,7 +142,7 @@ static int subroutine_type__encode(struct tag *tag, uint32_t core_id, struct ctfreturn 0 ; } -static int enumeration_type__encode (struct tag *tag,uint32_t core_id,struct ctf *ctf) +static int enumeration_type__encode (struct tag *tag,const struct cu *cu,uint32_t core_id,struct ctf *ctf) {struct type *etype =tag__type (tag);int64_t position;
@@ -154,13 +154,24 @@ static int enumeration_type__encode(struct tag *tag, uint32_t core_id, struct ctreturn -1 ;struct enumerator *pos; -type__for_each_enumerator (etype, pos) -ctf__add_enumerator (ctf, pos->name, pos->value, &position); +type__for_each_enumerator (etype, pos) { +switch (pos->tag.tag) { +case DW_TAG_enumerator: +ctf__add_enumerator (ctf, pos->name, pos->value, &position); +break ; +case DW_TAG_subprogram: +break ; +default : +fprintf (stderr,"CTF: unexpected DW_TAG_%s in enumeration '%s', skipping\n" , +dwarf_tag_name (pos->tag.tag),type__name (etype) ?:"(anonymous)" ); +break ; + } + }return 0 ; } -static void tag__encode_ctf (struct tag *tag,uint32_t core_id,struct ctf *ctf) +static void tag__encode_ctf (struct tag *tag,const struct cu *cu,uint32_t core_id,struct ctf *ctf) {switch (tag->tag) {case DW_TAG_base_type:
@@ -190,7 +201,7 @@ static void tag__encode_ctf(struct tag *tag, uint32_t core_id, struct ctf *ctf)subroutine_type__encode (tag, core_id, ctf);break ;case DW_TAG_enumeration_type: -enumeration_type__encode (tag, core_id, ctf); +enumeration_type__encode (tag, cu, core_id, ctf);break ; } }
@@ -253,7 +264,7 @@ int cu__encode_ctf(struct cu *cu, int verbose)uint32_t id;struct tag *pos;cu__for_each_type (cu, id, pos) -tag__encode_ctf (pos, id, ctf); +tag__encode_ctf (pos, cu, id, ctf);struct hlist_head hash_addr[HASHADDR__SIZE ];
dwarf_loader.c +31 -8
@@ -2310,6 +2310,8 @@ out_delete:return NULL ; } +static struct tag *die__create_new_function (Dwarf_Die *die,struct cu *cu,struct conf_load *conf); +static struct tag *die__create_new_enumeration (Dwarf_Die *die,struct cu *cu,struct conf_load *conf) {Dwarf_Die child;
@@ -2331,18 +2333,39 @@ static struct tag *die__create_new_enumeration(Dwarf_Die *die, struct cu *cu, st die = &child;do { -struct enumerator *enumerator; +switch (dwarf_tag (die)) { +case DW_TAG_enumerator: { +struct enumerator *enumerator =enumerator__new (die, cu, conf); + +if (enumerator ==NULL ) + goto out_delete; + +enumeration__add (enumeration, enumerator); +cu__hash (cu, &enumerator->tag); + } +continue ; +case DW_TAG_subprogram: { +struct tag *tag =die__create_new_function (die, cu, conf); +uint32_t id; + +if (tag ==NULL ) + goto out_delete; + +if (cu__table_add_tag (cu, tag, &id) <0 ) { +tag__delete (tag, cu); + goto out_delete; + } -if (dwarf_tag (die) != DW_TAG_enumerator) { +struct dwarf_tag *dtag =tag__dwarf (tag); + dtag->small_id = id; +namespace__add_tag (&enumeration->namespace, tag); +cu__hash (cu, tag); +break ; + } +default :cu__tag_not_handled (cu, die);continue ; } - enumerator =enumerator__new (die, cu, conf); -if (enumerator ==NULL ) - goto out_delete; - -enumeration__add (enumeration, enumerator); -cu__hash (cu, &enumerator->tag); }while (dwarf_siblingof (die, die) ==0 ); out:return &enumeration->namespace.tag;
dwarves.c +4 -6
@@ -1256,11 +1256,6 @@ void type__delete(struct type *type, struct cu *cu)cu__tag_free (cu,type__tag (type)); } -static void enumerator__delete (struct enumerator *enumerator,struct cu *cu) -{ -cu__tag_free (cu, &enumerator->tag); -} -void enumeration__delete (struct type *type,struct cu *cu) {struct enumerator *pos, *n;
@@ -1270,7 +1265,7 @@ void enumeration__delete(struct type *type, struct cu *cu)type__for_each_enumerator_safe_reverse (type, pos, n) {list_del_init (&pos->tag.node); -enumerator__delete (pos, cu); +tag__delete (&pos->tag, cu); }if (type->suffix_disambiguation)
@@ -1928,6 +1923,9 @@ static void enumeration__calc_prefix(struct type *enumeration)struct enumerator *entry;type__for_each_enumerator (enumeration, entry) { +if (entry->tag.tag != DW_TAG_enumerator) +continue ; +const char *curr_name =enumerator__name (entry);if (previous_name) {
dwarves.h +1 -1
@@ -1646,7 +1646,7 @@ static inline const char *enumerator__name(const struct enumerator *enumerator)void enumeration__delete (struct type *type,struct cu *cu);void enumeration__add (struct type *type,struct enumerator *enumerator); -size_t enumeration__fprintf (const struct tag *tag_enum, +size_t enumeration__fprintf (const struct tag *tag_enum,const struct cu *cu,const struct conf_fprintf *conf,FILE *fp);int dwarves__init (void );
dwarves_emit.c +5 -5
@@ -100,7 +100,7 @@ static struct type *type_emissions__find_fwd_decl(const struct type_emissions *ereturn NULL ; } -static int enumeration__emit_definitions (struct tag *tag, +static int enumeration__emit_definitions (struct tag *tag,const struct cu *cu,struct type_emissions *emissions,const struct conf_fprintf *conf,FILE *fp)
@@ -121,7 +121,7 @@ static int enumeration__emit_definitions(struct tag *tag,return 0 ; } -enumeration__fprintf (tag, conf, fp); +enumeration__fprintf (tag, cu, conf, fp);fputs (";\n" , fp);// See comment on enumeration__fprintf(), it seems this happens with DWARF as well
@@ -198,10 +198,10 @@ static int typedef__emit_definitions(struct tag *tdef, struct cu *cu,if (type__name (ctype) ==NULL ) {fputs ("typedef " , fp); conf.suffix =type__name (def); -enumeration__emit_definitions (type, emissions, &conf, fp); +enumeration__emit_definitions (type, cu, emissions, &conf, fp); goto out; }else -enumeration__emit_definitions (type, emissions, &conf, fp); +enumeration__emit_definitions (type, cu, emissions, &conf, fp); }break ;case DW_TAG_structure_type:
@@ -380,7 +380,7 @@ next_indirection:struct conf_fprintf conf = { .suffix =NULL , }; -return enumeration__emit_definitions (type, emissions, &conf, fp); +return enumeration__emit_definitions (type, cu, emissions, &conf, fp); }break ;case DW_TAG_structure_type:
dwarves_fprintf.c +40 -14
103 lines not on this page · raw message
pahole.c +6 -3
@@ -2162,7 +2162,7 @@ static const char *enumeration__lookup_value(struct type *enumeration, uint64_tstruct enumerator *entry;type__for_each_enumerator (enumeration, entry) { -if (entry->value == value) +if (entry->tag.tag == DW_TAG_enumerator && entry->value == value)return enumerator__name (entry); }
@@ -2187,7 +2187,7 @@ static struct enumerator *enumeration__lookup_entry_from_value(struct type *enumstruct enumerator *entry;type__for_each_enumerator (enumeration, entry) { -if (entry->value == value) +if (entry->tag.tag == DW_TAG_enumerator && entry->value == value)return entry; }
@@ -2213,6 +2213,9 @@ static struct enumerator *enumeration__find_enumerator(struct type *enumeration,struct enumerator *entry;type__for_each_enumerator (enumeration, entry) { +if (entry->tag.tag != DW_TAG_enumerator) +continue ; +const char *entry_name =enumerator__name (entry);if (!strcmp (entry_name, name))
@@ -3268,7 +3271,7 @@ static bool print_enumeration_with_enumerator(struct cu *cu, const char *name)cu__for_each_enumeration (cu, id, enumeration) {if (enumeration__find_enumerator (enumeration, name) !=NULL ) { -enumeration__fprintf (type__tag (enumeration), &conf, stdout); +enumeration__fprintf (type__tag (enumeration), cu, &conf, stdout);fputc ('\n' , stdout);return true; }
Signature · 1 line
2.55.0
PATCH 3/12 dwarf_loader: Populate DW_TAG_variant children in DW_TAG_variant_part
In reply to Arnaldo Carvalho de MeloFrom: Arnaldo Carvalho de Melo <[email protected]>
Rust discriminated unions (enums like Option<T> and Result<T,E>) are represented in DWARF as:
DW_TAG_structure_type
DW_TAG_variant_part (DW_AT_discr -> discriminant member)
DW_TAG_variant (DW_AT_discr_value = 0)
DW_TAG_member "None" -> struct None
DW_TAG_variant (DW_AT_discr_value = 1)
DW_TAG_member "Some" -> struct SomeCommit 7b135647cbf22e0c ("dwarf_loader: Initial support for DW_TAG_variant_part") added the variant_part container to pahole's internal representation, but did not process its DW_TAG_variant children. This meant the variant parts were always empty, and any Rust struct backed by a variant_part appeared as a zero-member struct in the output.
Add a struct variant with name and discriminant value fields, a variant__new() loader that extracts the DW_AT_discr_value and the child DW_TAG_member's name and type reference, and wire it into variant_part__new() so DW_TAG_variant children are populated at load time.
Also add type recoding for variant type references in namespace__recode_dwarf_types, so variant member types are resolved from DWARF offsets to CU-local type indices, following the same pattern used for regular struct/union members.
The variant_part__delete destructor is made non-static and extended to clean up variant children, and helper functions and iterator macros are added for the new types.
Before, with a Rust binary like sashiko-cli:
$ pahole -F btf -C 'Option<u32>' code_with_type.o
struct Option<u32> { /* size: 8, cachelines: 1, members: 0 */
/* padding: 8 */
/* last cacheline: 8 bytes */} __attribute__((__aligned__(16)));
After:
$ pahole -F dwarf -C 'Option<u32>' code_with_type.o
struct Option<u32> {
struct None { ... } __attribute__((__aligned__(4)));
struct Some {
u32 __0 __attribute__((__aligned__(4))); /* 4 4 */
} __attribute__((__aligned__(4)));/* size: 8, cachelines: 1, members: 0 */
} __attribute__((__aligned__(4)));
The variant parts are now populated in pahole's internal representation and available for downstream consumers (BTF/CTF encoders, pretty printers).
--- dwarf_loader.c | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++ dwarves.c | 42 ++++++++++++++++++++++++++++- dwarves.h | 24 +++++++++++++++++ 3 files changed, 137 insertions(+), 1 deletion(-)
dwarf_loader.c +72 -0
@@ -1240,6 +1240,32 @@ static struct template_parameter_pack *template_parameter_pack__new(Dwarf_Die *dreturn pack; } +static struct variant *variant__new (Dwarf_Die *die,struct cu *cu,struct conf_load *conf) +{ +struct variant *var =tag__alloc (cu,sizeof (*var)); + +if (var !=NULL ) { +tag__init (&var->tag, cu, die); + var->discr_value =attr_numeric (die, DW_AT_discr_value); + var->name =NULL ; + +Dwarf_Die child; +if (dwarf_child (die, &child) ==0 ) { +do { +if (dwarf_tag (&child) == DW_TAG_member) { +struct dwarf_tag *dtag =tag__dwarf (&var->tag); + + var->name =attr_string (&child, DW_AT_name, conf); +dwarf_tag__set_attr_type (dtag, type, &child, DW_AT_type); +break ; + } + }while (dwarf_siblingof (&child, &child) ==0 ); + } + } + +return var; +} +static struct variant_part *variant_part__new (Dwarf_Die *die,struct cu *cu,struct conf_load *conf) {struct variant_part *vpart =tag__alloc (cu,sizeof (*vpart));
@@ -1247,6 +1273,20 @@ static struct variant_part *variant_part__new(Dwarf_Die *die, struct cu *cu, strif (vpart !=NULL ) {tag__init (&vpart->tag, cu, die);INIT_LIST_HEAD (&vpart->variants); + +Dwarf_Die child; +if (dwarf_child (die, &child) ==0 ) { +do { +if (dwarf_tag (&child) == DW_TAG_variant) { +struct variant *var =variant__new (&child, cu, conf); +if (var ==NULL ) { +variant_part__delete (vpart, cu); +return NULL ; + } +variant_part__add_variant (vpart, var); + } + }while (dwarf_siblingof (&child, &child) ==0 ); + } }return vpart;
@@ -3003,6 +3043,38 @@ check_type: next: pos->type = dtype->small_id; } + +if (tag__is_struct (tag) ||tag__is_union (tag)) { +struct type *type =tag__type (tag); +struct variant_part *vpart; +struct dwarf_cu *dcu = cu->priv; + +type__for_each_variant_part (type, vpart) { +struct variant *variant; +struct dwarf_tag *dvpart =tag__dwarf (&vpart->tag); + +if (dvpart->type !=0 ) { +struct dwarf_tag *dtype =dwarf_cu__find_tag_by_ref (dcu, dvpart, type); +if (dtype !=NULL ) + vpart->tag.type = dtype->small_id; + } + +variant_part__for_each_variant (vpart, variant) { +struct dwarf_tag *dvar =tag__dwarf (&variant->tag); + +if (dvar->type ==0 ) +continue ; + +struct dwarf_tag *dtype =dwarf_cu__find_type_by_ref (dcu, dvar, type); +if (dtype ==NULL ) { +tag__print_type_not_found (&variant->tag); +continue ; + } + variant->tag.type = dtype->small_id; + } + } + } +return 0 ; }
dwarves.c +41 -1
64 lines not on this page · raw message
dwarves.h +24 -0
@@ -1021,6 +1021,12 @@ static inline struct formal_parameter_pack *tag__formal_parameter_pack(const strvoid formal_parameter_pack__add (struct formal_parameter_pack *pack,struct parameter *param); +struct variant { +struct tag tag; +const char *name; +uint64_t discr_value; +}; +struct variant_part {struct tag tag;struct list_head variants;
@@ -1424,10 +1430,28 @@ static inline struct class_member *class_member__next(struct class_member *membe#define type__for_each_variant_part_safe_reverse (type, pos, n) \ list_for_each_entry_safe_reverse(pos, n, &(type)->variant_parts, tag.node) +/** +* type__for_each_variant_part - iterate thru all variant_parts in a type +* @type: struct type instance to iterate +* @pos: struct variant_part iterator +*/ +#define type__for_each_variant_part (type, pos) \ + list_for_each_entry(pos, &(type)->variant_parts, tag.node) +void type__add_member (struct type *type,struct class_member *member);void type__add_template_type_param (struct type *type,struct template_type_param *ttparm);void type__add_template_value_param (struct type *type,struct template_value_param *tvparam);void type__add_variant_part (struct type *type,struct variant_part *vpart); +void variant_part__delete (struct variant_part *vpart,struct cu *cu); +void variant_part__add_variant (struct variant_part *vpart,struct variant *var); + +/** +* variant_part__for_each_variant - iterate thru all variants in a variant_part +* @vpart: struct variant_part instance to iterate +* @pos: struct variant iterator +*/ +#define variant_part__for_each_variant (vpart, pos) \ + list_for_each_entry(pos, &(vpart)->variants, tag.node)struct class_member * type__find_first_biggest_size_base_type_member(struct type *type,
Signature · 1 line
2.55.0
PATCH 4/12 btf_encoder: Encode variant parts as union members in BTF
In reply to Arnaldo Carvalho de MeloFrom: Arnaldo Carvalho de Melo <[email protected]>
With the DWARF loader now populating DW_TAG_variant children (previous commit), wire them into BTF encoding so Rust discriminated unions (Option<T>, Result<T,E>, etc.) are no longer emitted as empty structs.
Two changes:
1. Struct-to-union promotion: when a DW_TAG_structure_type has variant_parts but no regular data members, encode it as BTF_KIND_UNION instead of BTF_KIND_STRUCT, since the variants overlap at offset 0.
2. Variant member encoding: after encoding regular data members, iterate the variant_parts and emit each variant as a BTF union field with the variant's name and resolved type reference.
Testing with the sashiko-cli Rust binary (a real-world async HTTP client using tokio, hyper, serde, etc.):
Before:
$ bpftool btf dump file sashiko-cli | grep -c UNION 2073 $ bpftool btf dump file sashiko-cli | grep 'STRUCT.*vlen=0' | grep -vc 'size=0' 24335
After:
$ bpftool btf dump file sashiko-cli | grep -c UNION 25750 $ bpftool btf dump file sashiko-cli | grep 'STRUCT.*vlen=0' | grep -vc 'size=0' 2236
22,099 types that were previously encoded as empty structs are now properly represented as unions with their variant members:
Before:
$ bpftool btf dump file code_with_type.o | grep -A1 'Option<u32>' [11] STRUCT 'Option<u32>' size=8 vlen=0
After:
$ bpftool btf dump file code_with_type.o | grep -A3 'Option<u32>'
[11] UNION 'Option<u32>' size=8 vlen=2
'None' type_id=9 bits_offset=0
'Some' type_id=10 bits_offset=0--- btf_encoder.c | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-)
btf_encoder.c +35 -2
@@ -1855,6 +1855,12 @@ static void dump_invalid_symbol(const char *msg, const char *sym,fprintf (stderr,"PAHOLE: Error: Use '--btf_encode_force' to ignore such symbols and force emit the btf.\n" ); } +static bool type__has_variant_parts (const struct type *type) +{ +return !list_empty (&type->variant_parts); +} + +static int32_t btf_encoder__add_struct_type (struct btf_encoder *encoder,struct tag *tag) {struct type *type =tag__type (tag);
@@ -1863,8 +1869,18 @@ static int32_t btf_encoder__add_struct_type(struct btf_encoder *encoder, structint32_t type_id;uint8_t kind; - kind = (tag->tag == DW_TAG_union_type) ? -BTF_KIND_UNION :BTF_KIND_STRUCT ; +/* +* Rust discriminated unions (enums) are represented in DWARF as +* DW_TAG_structure_type with DW_TAG_variant_part children. +* If the struct has only variant parts and no regular data members, +* encode it as a BTF union since the variants overlap at offset 0. +*/ +if (tag->tag == DW_TAG_union_type) + kind =BTF_KIND_UNION ; +else if (type__has_variant_parts (type) && type->nr_members ==0 ) + kind =BTF_KIND_UNION ; +else + kind =BTF_KIND_STRUCT ; type_id =btf_encoder__add_struct (encoder, kind, name, type->size);if (type_id <0 )
@@ -1882,6 +1898,23 @@ static int32_t btf_encoder__add_struct_type(struct btf_encoder *encoder, structreturn -1 ; } +if (type__has_variant_parts (type) && kind ==BTF_KIND_UNION ) { +struct variant_part *vpart; + +type__for_each_variant_part (type, vpart) { +struct variant *variant; + +variant_part__for_each_variant (vpart, variant) { +if (variant->tag.type ==0 ) +continue ; + +uint32_t ref_type_id =btf_encoder__tag_type (encoder, variant->tag.type); + +if (btf_encoder__add_field (encoder, variant->name, ref_type_id,0 ,0 )) +return -1 ; + } + } + }return type_id;
Signature · 1 line
2.55.0
Yonghong Song
reviewerRe: [PATCH 04/12] btf_encoder: Encode variant parts as union members in BTF
Quoted 41 lines · Arnaldo Carvalho de Melo
From: Arnaldo Carvalho de Melo <[email protected]>
With the DWARF loader now populating
DW_TAG_variantchildren (previous commit), wire them into BTF encoding so Rust discriminated unions (Option<T>, Result<T,E>, etc.) are no longer emitted as empty structs.Two changes:
1. Struct-to-union promotion: when a
DW_TAG_structure_typehasvariant_partsbut no regular data members, encode it asBTF_KIND_UNIONinstead ofBTF_KIND_STRUCT, since the variants overlap at offset 0.2. Variant member encoding: after encoding regular data members, iterate the
variant_partsand emit each variant as a BTF union field with the variant's name and resolved type reference.Testing with the sashiko-cli Rust binary (a real-world async HTTP client using tokio, hyper, serde, etc.):
Before:
$ bpftool btf dump file sashiko-cli | grep -c UNION 2073 $ bpftool btf dump file sashiko-cli | grep 'STRUCT.*vlen=0' | grep -vc 'size=0' 24335After:
$ bpftool btf dump file sashiko-cli | grep -c UNION 25750 $ bpftool btf dump file sashiko-cli | grep 'STRUCT.*vlen=0' | grep -vc 'size=0' 223622,099 types that were previously encoded as empty structs are now properly represented as unions with their variant members:
Before:
$ bpftool btf dump file code_with_type.o | grep -A1 'Option<u32>' [11] STRUCT 'Option<u32>' size=8 vlen=0
Quoted 6 lines
After:
$ bpftool btf dump file code_with_type.o | grep -A3 'Option<u32>' [11] UNION 'Option<u32>' size=8 vlen=2 'None' type_id=9 bits_offset=0 'Some' type_id=10 bits_offset=0
FYI, the below is for llvm bpf backend to handle DW_TAG_variant_part to generate BTF.
For a rust code like:
; Source:
; #![no_std]
; #![no_main]
;
; pub enum MyEnum {
; First { a: u32, b: i32 },
; Second(u32),
; }
;
; #[unsafe(no_mangle)]
; pub static X: MyEnum = MyEnum::First { a: 54, b: -23 };
;
; #[cfg(not(test))]
; #[panic_handler]
; fn panic(_info: &core::panic::PanicInfo) -> ! {; loop {}
; }
The BTF encoding:
; CHECK-BTF: [1] STRUCT 'MyEnum' size=12 vlen=1
; CHECK-BTF-NEXT: '(anon)' type_id=3 bits_offset=0
; CHECK-BTF-NEXT: [2] INT 'u32' size=4 bits_offset=0 nr_bits=32 encoding=(none) ; CHECK-BTF-NEXT: [3] UNION '(anon)' size=12 vlen=3
; CHECK-BTF-NEXT: '(anon)' type_id=2 bits_offset=0 ; CHECK-BTF-NEXT: 'First' type_id=4 bits_offset=0 ; CHECK-BTF-NEXT: 'Second' type_id=6 bits_offset=0
; CHECK-BTF-NEXT: [4] STRUCT 'First' size=12 vlen=2
; CHECK-BTF-NEXT: 'a' type_id=2 bits_offset=32
; CHECK-BTF-NEXT: 'b' type_id=5 bits_offset=64
; CHECK-BTF-NEXT: [5] INT 'i32' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED ; CHECK-BTF-NEXT: [6] STRUCT 'Second' size=12 vlen=1
; CHECK-BTF-NEXT: '__0' type_id=2 bits_offset=32
; CHECK-BTF-NEXT: [7] VAR 'X' type_id=1, linkage=global
; CHECK-BTF-NEXT: [8] DATASEC '.rodata' size=0 vlen=1
; CHECK-BTF-NEXT: type_id=7 offset=0 size=12
Quoted 69 lines
Assisted-by Claude:claude-sonnet-4-5Signed-off-by Arnaldo Carvalho de Melo <[email protected]>--- btf_encoder.c | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-)btf_encoder.c +35
-2@@ -1855,6 +1855,12 @@ static void dump_invalid_symbol(const char *msg, const char *sym,fprintf (stderr,"PAHOLE: Error: Use '--btf_encode_force' to ignore such symbols and force emit the btf.\n" ); } +static bool type__has_variant_parts (const struct type *type) +{ +return !list_empty (&type->variant_parts); +} + +static int32_t btf_encoder__add_struct_type (struct btf_encoder *encoder,struct tag *tag) {struct type *type =tag__type (tag);@@ -1863,8 +1869,18 @@ static int32_t btf_encoder__add_struct_type(struct btf_encoder *encoder, structint32_t type_id;uint8_t kind; - kind = (tag->tag == DW_TAG_union_type) ? -BTF_KIND_UNION :BTF_KIND_STRUCT ; +/* +* Rust discriminated unions (enums) are represented in DWARF as +* DW_TAG_structure_type with DW_TAG_variant_part children. +* If the struct has only variant parts and no regular data members, +* encode it as a BTF union since the variants overlap at offset 0. +*/ +if (tag->tag == DW_TAG_union_type) + kind =BTF_KIND_UNION ; +else if (type__has_variant_parts (type) && type->nr_members ==0 ) + kind =BTF_KIND_UNION ; +else + kind =BTF_KIND_STRUCT ; type_id =btf_encoder__add_struct (encoder, kind, name, type->size);if (type_id <0 )@@ -1882,6 +1898,23 @@ static int32_t btf_encoder__add_struct_type(struct btf_encoder *encoder, structreturn -1 ; } +if (type__has_variant_parts (type) && kind ==BTF_KIND_UNION ) { +struct variant_part *vpart; + +type__for_each_variant_part (type, vpart) { +struct variant *variant; + +variant_part__for_each_variant (vpart, variant) { +if (variant->tag.type ==0 ) +continue ; + +uint32_t ref_type_id =btf_encoder__tag_type (encoder, variant->tag.type); + +if (btf_encoder__add_field (encoder, variant->name, ref_type_id,0 ,0 )) +return -1 ; + } + } + }return type_id;
PATCH 5/12 dwarf_loader: Handle DW_FORM_block in attr_numeric for Rust discriminant values
In reply to Arnaldo Carvalho de MeloFrom: Arnaldo Carvalho de Melo <[email protected]>
Rust enums with 128-bit discriminant types (i128/u128) encode their DW_AT_discr_value as a DW_FORM_block1 containing a 16-byte little-endian integer, rather than using a standard data form like DW_FORM_data*.
Since attr_numeric did not handle DW_FORM_block*, these discriminant values were not read and produced 311 warnings on a real Rust binary like sashiko-cli:
DW_AT_<0x16>=0xa
DW_AT_<0x16>=0xa
...
(0x16 = DW_AT_discr_value, 0xa = DW_FORM_block1)
Add DW_FORM_block1/block2/block4/block to attr_numeric, reading up to 8 bytes from the block into a uint64_t via memcpy and converting from little-endian with le64toh() so the result is correct on big-endian hosts as well. This covers all practical discriminant values.
Before (sashiko-cli):
$ pahole --btf_encode sashiko-cli 2>&1 | grep -c 'DW_AT_' 311
After:
$ pahole --btf_encode sashiko-cli 2>&1 | wc -l 0
All warnings from Rust DWARF encoding of sashiko-cli are now resolved.
--- dwarf_loader.c | 51 +++++++++++++-- tests/block_endian.sh | 146 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 190 insertions(+), 7 deletions(-) create mode 100755 tests/block_endian.sh
dwarf_loader.c +44 -7
@@ -7,6 +7,7 @@#include <assert.h> #include <dirent.h> #include <dwarf.h> +#include <endian.h> #include <elfutils/libdwfl.h> #include <elfutils/version.h> #include <errno.h>
@@ -335,7 +336,7 @@ static uint64_t __libdw_get_uleb128(uint64_t acc, uint32_t i, var =__libdw_get_uleb128 (var,1 , &(addr)); \ }while (0 ) -static uint64_t attr_numeric(Dwarf_Die *die, uint32_t name) +static uint64_t __attr_numeric(Dwarf_Die *die, uint32_t name, bool little_endian) {Dwarf_Attribute attr;uint32_t form;
@@ -371,6 +372,31 @@ static uint64_t attr_numeric(Dwarf_Die *die, uint32_t name)return value; }break ; +case DW_FORM_block1: +case DW_FORM_block2: +case DW_FORM_block4: +case DW_FORM_block: { +/* Block data is in target byte order, convert to host */ +Dwarf_Block block; +if (dwarf_formblock (&attr, &block) ==0 && block.length >0 ) { +uint64_t value =0 ; +size_t n = block.length >sizeof (value) ?sizeof (value) : block.length; +if (little_endian) { +memcpy (&value, block.data, n); +return le64toh (value); + } +/* +* BE: the least-significant bytes are at the END of +* the block. Skip any high bytes that don't fit in +* uint64_t, then accumulate the rest MSB-first. +*/ +size_t off = block.length - n; +for (size_t i =0 ; i < n; i++) + value = (value <<8 ) | (uint8_t )block.data[off + i]; +return value; + } + } +break ;default :fprintf (stderr,"DW_AT_<0x%x>=0x%x\n" , name, form);break ;
@@ -379,6 +405,16 @@ static uint64_t attr_numeric(Dwarf_Die *die, uint32_t name)return 0 ; } +/* +* Most callers don't use DW_FORM_block, so this wrapper keeps them unchanged. +* When the attribute can be a block (e.g. DW_AT_discr_value), use +* __attr_numeric() with the CU's endianness instead. +*/ +static uint64_t attr_numeric (Dwarf_Die *die,uint32_t name) +{ +return __attr_numeric (die, name, true); +} +static uint64_t attr_alignment (Dwarf_Die *die,struct conf_load *conf) {return conf->ignore_alignment_attr ?0 :attr_numeric (die, DW_AT_alignment);
@@ -712,7 +748,7 @@ static struct enumerator *enumerator__new(Dwarf_Die *die, struct cu *cu, structif (enumerator !=NULL ) {tag__init (&enumerator->tag, cu, die); enumerator->name =attr_string (die, DW_AT_name, conf); - enumerator->value =attr_numeric (die, DW_AT_const_value); + enumerator->value =__attr_numeric (die, DW_AT_const_value, cu->little_endian); }return enumerator;
@@ -801,7 +837,7 @@ static struct constant *constant__new(Dwarf_Die *die, struct cu *cu, struct confif (constant !=NULL ) {tag__init (&constant->tag, cu, die); constant->name =attr_string (die, DW_AT_name, conf); - constant->value =attr_numeric (die, DW_AT_const_value); + constant->value =__attr_numeric (die, DW_AT_const_value, cu->little_endian); }return constant;
@@ -1080,7 +1116,7 @@ static struct class_member *class_member__new(Dwarf_Die *die, struct cu *cu,if (!cu__is_c (cu)) { member->accessibility =attr_numeric (die, DW_AT_accessibility); - member->const_value =attr_numeric (die, DW_AT_const_value); + member->const_value =__attr_numeric (die, DW_AT_const_value, cu->little_endian); member->virtuality =attr_numeric (die, DW_AT_virtuality); } member->hole =0 ;
@@ -1189,8 +1225,8 @@ static struct template_value_param *template_value_param__new(Dwarf_Die *die, stif (tvparm !=NULL ) {tag__init (&tvparm->tag, cu, die); tvparm->name =attr_string (die, DW_AT_name, conf); - tvparm->const_value =attr_numeric (die, DW_AT_const_value); - tvparm->default_value =attr_numeric (die, DW_AT_default_value); + tvparm->const_value =__attr_numeric (die, DW_AT_const_value, cu->little_endian); + tvparm->default_value =__attr_numeric (die, DW_AT_default_value, cu->little_endian); }return tvparm;
@@ -1246,7 +1282,8 @@ static struct variant *variant__new(Dwarf_Die *die, struct cu *cu, struct conf_lif (var !=NULL ) {tag__init (&var->tag, cu, die); - var->discr_value =attr_numeric (die, DW_AT_discr_value); +/* DW_AT_discr_value uses DW_FORM_block, needs target endianness */ + var->discr_value =__attr_numeric (die, DW_AT_discr_value, cu->little_endian); var->name =NULL ;Dwarf_Die child;
tests/block_endian.sh new file +146 -0
146 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH 6/12 dwarf_loader: Allow forcing the merge of CUs for solving inter CU tag references
In reply to Arnaldo Carvalho de MeloFrom: Arnaldo Carvalho de Melo <[email protected]>
The Linux perf tool now includes some Rust code that then gets linked into perf and comes with its DWARF that has tags referencing tags in different CUs, and as the current DWARF loading algorithm uses parallelization and recodes the big DWARF types (DWARF_off, usually 64-bit) into smaller ones as a step into converting to CTF (initially) and later BTF, the resolution fails.
There is a case where this inter CU happens, LTO builds, and so there is an alternative algorithm for that case, that serializes DWARF CU loading and merges all the CUs into just one meta/mega-CU, which then has all the types and thus doesn't have a problem with inter CU references, as the recoding into smaller ids is done only after all CUs are loaded.
So while we don't refactor the loading in a way that allows for inter CU while allowing parallelization, maybe by doing the recoding just at the end of parallel loading, add minimal code to force this CU merging for experimentation in such cases, getting back the regression test prettify_perf.data.sh to work, making it force CU merging.
$ pahole ~/bin/perf > unmerged.txt <Suppress lots of warnings when recoding DWARF types.> $ pahole --features=force_cu_merging ~/bin/perf > merged.txt $
With the current set of Rust types that are representable with the pahole data structures and then pretty printed as if they were C we see 12 differences:
$ diff -u unmerged.txt merged.txt | grep ^@@ | wc -l 12 $ diff -u unmerged.txt merged.txt | wc -l 198
Of this kind, due to some types not being resolved as tags are referencing tags in other CUs.
$ diff -u unmerged.txt merged.txt | head --- unmerged.txt 2026-03-23 17:56:54.971785023 -0300 +++ merged.txt 2026-03-23 17:56:59.826872178 -0300 @@ -9643,10 +9643,11 @@ u64 __0 __attribute__((__aligned__(8))); /* 0 8 */ struct Abbreviation __1 __attribute__((__aligned__(8))); /* 8 112 */
- /* XXX last struct has 5 bytes of padding */
+ /* XXX last struct has 16 bytes of padding, 1 hole */
/* size: 120, cachelines: 2, members: 2 */
$
Now the pretty printing perf.data test case passes:
⬢ [acme@toolbx tests]$ ./prettify_perf.data.sh Pretty printing of files using DWARF type information. Test ./prettify_perf.data.sh passed
⬢ [acme@toolbx tests]$
This was implemented reusing the --btf_features mechanism that now can be accessed as well via --features, as this is not strictly a BTF feature but, as Alan Maguire suggested, it is desirable to ask for that feature to be enabled when we know it is needed bug can't guarantee that the available pahole version has the feature and not have it fail because it doesn't implement --force_cu_merging, which the --btf_features=force_cu_merging, now also avaialbe as --features=force_cu_merging, allows as it ignores unknown features.
--- dwarf_loader.c | 2 +- dwarves.h | 1 + man-pages/pahole.1 | 18 ++++++++++++++++-- pahole.c | 11 ++++++++++- tests/prettify_perf.data.sh | 4 ++-- 5 files changed, 30 insertions(+), 6 deletions(-)
dwarf_loader.c +1 -1
@@ -4693,7 +4693,7 @@ static int cus__load_module(struct cus *cus, struct conf_load *conf,cus__remove (cus, type_cu); } -if (cus__merging_cu (dw, elf)) { +if (conf->force_cu_merging ||cus__merging_cu (dw, elf)) { res =cus__merge_and_process_cu (cus, conf, mod, dw, elf, filename, build_id, build_id_len, type_cu ? type_dcu :NULL );
dwarves.h +1 -0
@@ -112,6 +112,7 @@ struct conf_load {const char *kabi_prefix;struct btf *base_btf;struct conf_fprintf *conf_fprintf; +bool force_cu_merging; };/** struct conf_fprintf - hints to the __fprintf routines
man-pages/pahole.1 +16 -2
@@ -314,8 +314,10 @@ Generate BTF for functions with optimization-related suffixes (.isra, .constprop Allow using all the BTF features supported by pahole. .TP -.B \-\-btf_features=FEATURE_LIST -Encode BTF using the specified feature list, or specify 'default' for all +.B \-\-features=FEATURE_LIST +This is also available as \-\-btf_features=FEATURE_LIST, unknown features, +like those added in newer versions of pahole, are ignored. BTF encoding +configuration is the major user. Using 'default' will enable all standard features supported. This option can be used as an alternative to using multiple BTF-related options, and 'default' represents the standard set of BTF features that are in use for
@@ -364,6 +366,18 @@ Supported non-standard features (not enabled for 'default') layout Encode information about BTF kinds available at encoding time in layout section in BTF. +Non-standard, non-BTF related features: + + force_cu_merging Force merging all CUs into one. Use when there are + references across CUs. This happens in some LTO cases + and was observed with Rust CUs, where types tags + (function parameters, abstract origins for inlines, etc) + reference types in another CU. + For LTO this is being autodetected and the merging of + cus is done automatically, but for the Rust case, and + maybe others this is needed with the current DWARF + loading algorithm. + .fi So for example, specifying \-\-btf_encode=var,enum64 will result in a BTF
pahole.c +10 -1
@@ -1154,6 +1154,7 @@ ARGP_PROGRAM_VERSION_HOOK_DEF = dwarves_print_version;#define ARG_padding 348#define ARGP_with_embedded_flexible_array 349#define ARGP_btf_attributes 350 +#define ARGP_features 351/* --btf_features=feature1[,feature2,..] allows us to specify * a list of requested BTF features or "default" to enable all default
@@ -1241,7 +1242,8 @@ struct btf_feature {BTF_NON_DEFAULT_FEATURE_CHECK (attributes, btf_attributes, false, attributes_check),BTF_NON_DEFAULT_FEATURE (true_signature, true_signature, false), - BTF_NON_DEFAULT_FEATURE_CHECK(layout, btf_gen_layout, false, layout_check) +BTF_NON_DEFAULT_FEATURE_CHECK (layout, btf_gen_layout, false, layout_check), + BTF_NON_DEFAULT_FEATURE(force_cu_merging, force_cu_merging, false), };#define BTF_MAX_FEATURE_STR 1024
@@ -1816,6 +1818,12 @@ static const struct argp_option pahole__options[] = { .arg = "FEATURE_LIST", .doc ="Specify supported BTF features in FEATURE_LIST or 'default' for default set of supported features. See the pahole manual page for the list of supported, default features." }, + { + .name = "features", + .key = ARGP_features, + .arg = "FEATURE_LIST", + .doc ="Specify supported features in FEATURE_LIST or 'default' for default set of supported features. See the pahole manual page for the list of supported, default features." + }, { .name = "supported_btf_features", .key = ARGP_supported_btf_features,
@@ -2028,6 +2036,7 @@ static error_t pahole__options_parser(int key, char *arg, conf_load.reproducible_build = true;break ;case ARGP_running_kernel_vmlinux: show_running_kernel_vmlinux = true;break ; +case ARGP_features:case ARGP_btf_features:parse_btf_features (arg, false);break ;case ARGP_supported_btf_features:
tests/prettify_perf.data.sh +2 -2
@@ -25,7 +25,7 @@ fi perf_lacks_type_info() { local type_keyword=$1 local type_name=$2 - if ! pahole -C $type_name $perf | grep -q "^$type_keyword $type_name {"; then + if ! pahole --features=force_cu_merging -C $type_name $perf | grep -q "^$type_keyword $type_name {"; then info_log "skip: $perf doesn't have '$type_keyword $type_name' type info" test_skip fi
@@ -41,7 +41,7 @@ $perf record --quiet -o $perf_data sleep 0.00001 number_of_filtered_perf_record_metadata() { local metadata_record=$1 - local count=$(pahole -F dwarf -V $perf --header=perf_file_header --seek_bytes '$header.data.offset' --size_bytes='$header.data.size' -C "perf_event_header(sizeof,type,type_enum=perf_event_type+perf_user_event_type,filter=type==PERF_RECORD_$metadata_record)" --prettify $perf_data | grep ".type = PERF_RECORD_$metadata_record," | wc -l) + local count=$(pahole --features=force_cu_merging -F dwarf -V $perf --header=perf_file_header --seek_bytes '$header.data.offset' --size_bytes='$header.data.size' -C "perf_event_header(sizeof,type,type_enum=perf_event_type+perf_user_event_type,filter=type==PERF_RECORD_$metadata_record)" --prettify $perf_data | grep ".type = PERF_RECORD_$metadata_record," | wc -l) echo "$count" }
Signature · 1 line
2.55.0
PATCH 7/12 dwarf_loader: Support DW_TAG_imported_unit for same-file partial units
In reply to Arnaldo Carvalho de MeloFrom: Arnaldo Carvalho de Melo <[email protected]>
Binaries processed by the dwz(1) tool have their DWARF type information deduplicated into DW_TAG_partial_unit entries that are then referenced via DW_TAG_imported_unit from each DW_TAG_compile_unit that uses those types. This is the standard DWARF mechanism for cross-CU type sharing.
On Fedora/RHEL, most debuginfo packages are built with dwz, making this a common pattern. For instance, bash-debuginfo has 10,486 DW_TAG_partial_unit, 384 DW_TAG_compile_unit, and 8,572 DW_TAG_imported_unit entries — all using same-file references (no .dwz alternate DWARF file involved).
Before this patch, pahole skipped DW_TAG_partial_unit with a warning:
WARNING: DW_TAG_partial_unit used, some types will not be considered!
Probably this was optimized using a tool like 'dwz' A future version of pahole will support this.
And DW_TAG_imported_unit was silently ignored (returned NULL), causing pahole to report "file has no dwarf type information" for binaries like bash and glibc.
The fix adds die__process_imported_unit(), called from die__process_unit() when encountering DW_TAG_imported_unit. It follows DW_AT_import to the referenced DW_TAG_partial_unit DIE and processes its children inline into the importing compile unit's type tables. This works because dwarf_formref_die() already handles all DWARF reference forms, and each CU maintains its own independent hash tables — so the same partial unit can be safely imported by multiple CUs, each getting its own copy of the types.
Since imported units can themselves contain DW_TAG_imported_unit entries (nested imports), a depth limit of 64 is enforced to prevent stack overflow from pathological or corrupted DWARF. A warning is emitted if the limit is reached.
Some binaries (e.g. chromium-browser on Fedora 44, built with Rust components) also have DW_TAG_imported_unit entries that reference partial units in an alternate debug file via DW_FORM_GNU_ref_alt (the .gnu_debugaltlink mechanism). When elfutils resolves such a reference, it returns DIEs from the alternate file whose offsets are in a different address space — processing these into the main CU's hash tables corrupts type references and causes a crash during type recoding.
The same DW_FORM_GNU_ref_alt form can also appear on regular type attributes (DW_AT_type, DW_AT_abstract_origin, DW_AT_specification, etc.), not just on DW_TAG_imported_unit's DW_AT_import. Guard all paths via attr_form_is_ref_alt(), which skips the reference and warns once, so users know why some types are missing rather than getting a crash.
The korg/alt_dwarf branch had a previous attempt at this that also handled the .dwz alternate DWARF file case (DW_FORM_GNU_ref_alt), but it was never merged and is now 294 commits behind master. This patch takes a simpler approach focused on the same-file case first, which covers dwz output on Fedora/RHEL where all partial units are within the same .debug file.
Before (bash-5.3.9-3.fc44.x86_64 debuginfo):
$ pahole -F dwarf /usr/lib/debug/usr/bin/bash-5.3.9-3.fc44.x86_64.debug WARNING: DW_TAG_partial_unit used, some types will not be considered! pahole: /usr/lib/debug/usr/bin/bash-5.3.9-3.fc44.x86_64.debug: file has no dwarf type information
After:
$ pahole -F dwarf /usr/lib/debug/usr/bin/bash-5.3.9-3.fc44.x86_64.debug | wc -l
1605
$ pahole -F dwarf -C variable /usr/lib/debug/usr/bin/bash-5.3.9-3.fc44.x86_64.debug
struct variable {
char * name; /* 0 8 */
char * value; /* 8 8 */
...
/* size: 48, cachelines: 1, members: 7 */
};Before (chromium-browser debuginfo, Fedora 44):
$ pahole /usr/lib/debug/.../chromium-browser-149.0.7827.155-1.fc44.x86_64.debug Segmentation fault
After:
$ pahole /usr/lib/debug/.../chromium-browser-149.0.7827.155-1.fc44.x86_64.debug
WARNING: DW_FORM_GNU_ref_alt (dwz alternate debug file) not yet supported,
some types will not be available.--- dwarf_loader.c | 153 ++++++++++++++++++++++++++++++++++++++------- man-pages/pahole.1 | 8 +-- 2 files changed, 135 insertions(+), 26 deletions(-)
dwarf_loader.c +131 -22
@@ -154,6 +154,9 @@ struct dwarf_cu {struct dwarf_tag *last_type_lookup;struct cu *cu;struct dwarf_cu *type_unit; +Dwarf_Off *imported_units; +uint32_t nr_imported_units; +uint32_t allocated_imported_units; };static int dwarf_cu__init (struct dwarf_cu *dcu,struct cu *cu)
@@ -179,6 +182,9 @@ static int dwarf_cu__init(struct dwarf_cu *dcu, struct cu *cu)INIT_HLIST_HEAD (&dcu->hash_types[i]); } dcu->type_unit =NULL ; + dcu->imported_units =NULL ; + dcu->nr_imported_units =0 ; + dcu->allocated_imported_units =0 ;// To avoid a per-lookup check against NULL in dwarf_cu__find_type_by_ref() dcu->last_type_lookup = &sentinel_dtag;return 0 ;
@@ -203,6 +209,7 @@ static void dwarf_cu__delete(struct cu *cu)struct dwarf_cu *dcu = cu->priv; +free (dcu->imported_units);// dcu->hash_tags & dcu->hash_types are on cu->obstack cu__free (cu, dcu); cu->priv =NULL ;
@@ -486,12 +493,32 @@ static const char *attr_string(Dwarf_Die *die, uint32_t name, struct conf_load *return str; } +static bool attr_form_is_ref_alt (Dwarf_Attribute *attr) +{ +if (attr->form == DW_FORM_GNU_ref_alt) { +static bool warned; + +if (!warned) { +fprintf (stderr, +"WARNING: DW_FORM_GNU_ref_alt (dwz alternate debug file) not yet supported,\n" +" some types will not be available.\n" ); + warned = true; + } +return true; + } +return false; +} +static bool attr_type (Dwarf_Die *die,uint32_t attr_name,Dwarf_Off *offset) {Dwarf_Attribute attr;if (dwarf_attr (die, attr_name, &attr) !=NULL ) {Dwarf_Die type_die; +if (attr_form_is_ref_alt (&attr)) { + *offset =0 ; +return 0 ; + }if (dwarf_formref_die (&attr, &type_die) !=NULL ) { *offset =dwarf_dieoffset (&type_die);return attr.form == DW_FORM_ref_sig8;
@@ -722,7 +749,8 @@ static void type__init(struct type *type, Dwarf_Die *die, struct cu *cu, structDwarf_Attribute attr;if (dwarf_attr (die, DW_AT_type, &attr) !=NULL ) {Dwarf_Die type_die; -if (dwarf_formref_die (&attr, &type_die) !=NULL ) { +if (!attr_form_is_ref_alt (&attr) && +dwarf_formref_die (&attr, &type_die) !=NULL ) {uint64_t encoding =attr_numeric (&type_die, DW_AT_encoding);if (encoding == DW_ATE_signed || encoding == DW_ATE_signed_char)
@@ -1036,9 +1064,14 @@ static int add_gnu_annotation_chain(Dwarf_Die *die, int component_idx,Dwarf_Attribute attr;Dwarf_Die annot_die; -while (dwarf_attr (die, DW_AT_GNU_annotation, &attr) !=NULL && -dwarf_formref_die (&attr, &annot_die) !=NULL && -dwarf_tag (&annot_die) == DW_TAG_GNU_annotation) { +while (dwarf_attr (die, DW_AT_GNU_annotation, &attr) !=NULL ) { +if (attr_form_is_ref_alt (&attr)) +break ; +if (dwarf_formref_die (&attr, &annot_die) ==NULL ) +break ; +if (dwarf_tag (&annot_die) != DW_TAG_GNU_annotation) +break ; +int ret =add_tag_annotation (&annot_die, component_idx, conf, head);if (ret)return ret;
@@ -2079,9 +2112,13 @@ check_gnu_attr: goto out;/* Handle GCC-style DW_AT_GNU_annotation attribute */ -while (dwarf_attr (die, DW_AT_GNU_annotation, &attr) !=NULL && -dwarf_formref_die (&attr, &annot_die) !=NULL && -dwarf_tag (&annot_die) == DW_TAG_GNU_annotation) { +while (dwarf_attr (die, DW_AT_GNU_annotation, &attr) !=NULL ) { +if (attr_form_is_ref_alt (&attr)) +break ; +if (dwarf_formref_die (&attr, &annot_die) ==NULL ) +break ; +if (dwarf_tag (&annot_die) != DW_TAG_GNU_annotation) +break ; name =attr_string (&annot_die, DW_AT_name, conf);if (strcmp (name,"btf_type_tag" ) !=0 )break ;
@@ -2906,7 +2943,7 @@ static struct tag *__die__process_tag(Dwarf_Die *die, struct cu *cu,switch (dwarf_tag (die)) {case DW_TAG_imported_unit: -return NULL ;// We don't support imported units yet, so to avoid segfaults +return &unsupported_tag;// Handled in die__process_unit() case DW_TAG_array_type: tag =die__create_new_array (die, cu);break ;case DW_TAG_string_type:// FORTRAN stuff, looks like an array
@@ -2974,9 +3011,90 @@ static struct tag *__die__process_tag(Dwarf_Die *die, struct cu *cu,return tag; } -static int die__process_unit (Dwarf_Die *die,struct cu *cu,struct conf_load *conf) +#define MAX_IMPORTED_UNIT_DEPTH 64 + +static int die__process_unit (Dwarf_Die *die,struct cu *cu,struct conf_load *conf,int import_depth); + +static bool dwarf_cu__imported_unit_visited (struct dwarf_cu *dcu,Dwarf_Off offset) +{ +for (uint32_t i =0 ; i < dcu->nr_imported_units; i++) +if (dcu->imported_units[i] == offset) +return true; +return false; +} + +static int dwarf_cu__mark_imported_unit (struct dwarf_cu *dcu,struct cu *cu,Dwarf_Off offset) +{ +if (dcu->nr_imported_units == dcu->allocated_imported_units) { +uint32_t new_size = dcu->allocated_imported_units ? dcu->allocated_imported_units *2 :16 ; +Dwarf_Off *new_array =realloc (dcu->imported_units, new_size *sizeof (Dwarf_Off)); +if (new_array ==NULL ) +return -ENOMEM ; + dcu->imported_units = new_array; + dcu->allocated_imported_units = new_size; + } + dcu->imported_units[dcu->nr_imported_units++] = offset; +return 0 ; +} + +static int die__process_imported_unit (Dwarf_Die *die,struct cu *cu,struct conf_load *conf,int import_depth) +{ +Dwarf_Attribute attr; + +if (dwarf_attr (die, DW_AT_import, &attr) ==NULL ) +return 0 ; + +if (attr_form_is_ref_alt (&attr)) +return 0 ; + +Dwarf_Die imported_die; + +if (dwarf_formref_die (&attr, &imported_die) ==NULL ) +return 0 ; + +if (dwarf_tag (&imported_die) != DW_TAG_partial_unit) +return 0 ; + +if (import_depth >=MAX_IMPORTED_UNIT_DEPTH ) { +static bool warned; + +if (!warned) { +fprintf (stderr, +"WARNING: DW_TAG_imported_unit nesting too deep (>%d), " +"some types will not be available.\n" , +MAX_IMPORTED_UNIT_DEPTH ); + warned = true; + } +return 0 ; + } + +Dwarf_Off offset =dwarf_dieoffset (&imported_die); +struct dwarf_cu *dcu = cu->priv; + +if (dwarf_cu__imported_unit_visited (dcu, offset)) +return 0 ; + +if (dwarf_cu__mark_imported_unit (dcu, cu, offset)) +return -ENOMEM ; + +Dwarf_Die child; + +if (dwarf_child (&imported_die, &child) ==0 ) +return die__process_unit (&child, cu, conf, import_depth +1 ); + +return 0 ; +} + +static int die__process_unit (Dwarf_Die *die,struct cu *cu,struct conf_load *conf,int import_depth) { do { + if (dwarf_tag(die) == DW_TAG_imported_unit) { + int err = die__process_imported_unit(die, cu, conf, import_depth); + if (err) + return err; + continue; + } + struct tag *tag = die__process_tag(die, cu, 1, conf); if (tag == NULL) return -ENOMEM;
@@ -3822,17 +3940,8 @@ static int die__process(Dwarf_Die *die, struct cu *cu, struct conf_load *conf)return 0 ;// so that other units can be processed } -if (tag == DW_TAG_partial_unit) { -static bool warned; - -if (!warned) { -fprintf (stderr,"WARNING: DW_TAG_partial_unit used, some types will not be considered!\n" -" Probably this was optimized using a tool like 'dwz'\n" -" A future version of pahole will support this.\n" ); - warned = true; - } -return 0 ;// so that other units can be processed - } +if (tag == DW_TAG_partial_unit) +return 0 ;// Processed inline when reached via DW_TAG_imported_unit if (tag != DW_TAG_compile_unit && tag != DW_TAG_type_unit) { fprintf(stderr, "%s: DW_TAG_compile_unit, DW_TAG_type_unit, DW_TAG_partial_unit or DW_TAG_skeleton_unit expected got %s (0x%x) @ %llx!\n",
@@ -3854,7 +3963,7 @@ static int die__process(Dwarf_Die *die, struct cu *cu, struct conf_load *conf)return DWARF_CB_OK ;if (dwarf_child (die, &child) ==0 ) { -int err =die__process_unit (&child, cu, conf); +int err =die__process_unit (&child, cu, conf,0 );if (err)return err; }
@@ -4626,7 +4735,7 @@ static int cus__merge_and_process_cu(struct cus *cus, struct conf_load *conf, filtered = conf->early_cu_filter (&unmerged_cu) ==NULL ; } -if (!filtered &&die__process_unit (&child, cu, conf) !=0 ) +if (!filtered &&die__process_unit (&child, cu, conf,0 ) !=0 ) goto out_abort; }
man-pages/pahole.1 +4 -4
@@ -373,10 +373,10 @@ Non-standard, non-BTF related features: and was observed with Rust CUs, where types tags (function parameters, abstract origins for inlines, etc) reference types in another CU. - For LTO this is being autodetected and the merging of - cus is done automatically, but for the Rust case, and - maybe others this is needed with the current DWARF - loading algorithm. + Imported units (DW_TAG_imported_unit for LTO and Rust) + and .dwz alternate debug files (DW_FORM_GNU_ref_alt) are + now auto-detected and processed automatically, so + force_cu_merging is rarely needed with current pahole. .fi
Signature · 1 line
2.55.0
PATCH 8/12 dwarf_loader: Fix cus__merging_cu failing to detect DW_FORM_ref_addr
In reply to Arnaldo Carvalho de MeloFrom: Arnaldo Carvalho de Melo <[email protected]>
cus__merging_cu() scans abbreviation tables looking for DW_FORM_ref_addr to detect binaries with inter-CU type references (like Rust CUs in perf). When found, it triggers the merged CU loading path that can resolve cross-CU references.
However, dwarf_getabbrevattr() can fail on certain attributes, notably when DW_FORM_implicit_const is used (DWARF5). The function was treating this failure as terminal, returning false immediately without scanning the remaining abbreviations. This prevented detection of DW_FORM_ref_addr in later CUs, causing the parallel path to be taken instead — which cannot resolve cross-CU references.
For example, with the perf binary containing 507 CUs where 7 Rust CUs (CU 209-215) use DW_FORM_ref_addr, the function was failing at CU 0 abbreviation 20 attribute 8 and returning false, never reaching the Rust CUs.
Before:
$ pahole -F dwarf ~/bin/perf 2>&1 | grep "couldn't find" | wc -l
314
$ diff <(pahole -F dwarf ~/bin/perf 2>/dev/null) \
<(pahole --features=force_cu_merging -F dwarf ~/bin/perf 2>/dev/null) \
| grep '^[<>]' | wc -l
70After:
$ pahole -F dwarf ~/bin/perf 2>&1 | grep "couldn't find" | wc -l
0
$ diff <(pahole -F dwarf ~/bin/perf 2>/dev/null) \
<(pahole --features=force_cu_merging -F dwarf ~/bin/perf 2>/dev/null) \
| wc -l
0The fix changes dwarf_getattrcnt() failure to skip the current abbreviation (goto next_abbrev) and dwarf_getabbrevattr() failure to skip to the next attribute (continue), both continuing to scan for DW_FORM_ref_addr instead of aborting the entire detection.
--- dwarf_loader.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
dwarf_loader.c +3 -2
@@ -4287,7 +4287,7 @@ static bool cus__merging_cu(Dwarf *dw, Elf *elf)size_t attrcnt;if (dwarf_getattrcnt (abbrev, &attrcnt) !=0 ) -return false; + goto next_abbrev;unsigned int attr_num, attr_form;Dwarf_Off aboffset;
@@ -4295,10 +4295,11 @@ static bool cus__merging_cu(Dwarf *dw, Elf *elf)for (j =0 ; j < attrcnt; ++j) {if (dwarf_getabbrevattr (abbrev, j, &attr_num, &attr_form, &aboffset)) -return false; +continue ;if (attr_form == DW_FORM_ref_addr)return true; } +next_abbrev: offset += length; }
Signature · 1 line
2.55.0
PATCH 9/12 dwarf_loader: Add cu parameter to tag__set_spec() and dwarf_tag__set_attr_type()
In reply to Arnaldo Carvalho de MeloFrom: Arnaldo Carvalho de Melo <[email protected]>
Thread the cu parameter through the reference-setting helpers, in preparation for using it to track which offset space (main file vs dwz alternate file) each reference targets.
The cu parameter is currently unused: dwarf_tag__set_attr_type() silently ignores the extra macro argument, and tag__set_spec() marks it __maybe_unused.
No functional change.
--- dwarf_loader.c | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-)
dwarf_loader.c +13 -13
@@ -572,7 +572,7 @@ static void tag__free(struct tag *tag, struct cu *cu)cu__free (cu, dtag); } -#define dwarf_tag__set_attr_type (dtag, field, die, attr_name) \ +#define dwarf_tag__set_attr_type (dtag, field, die, attr_name, cu) \ dtag->from_types_section.field = attr_type(die, attr_name, &dtag->field)static void tag__init (struct tag *tag,struct cu *cu,Dwarf_Die *die)
@@ -584,13 +584,13 @@ static void tag__init(struct tag *tag, struct cu *cu, Dwarf_Die *die) dtag->id =dwarf_dieoffset (die);if (tag->tag == DW_TAG_imported_module || tag->tag == DW_TAG_imported_declaration) -dwarf_tag__set_attr_type (dtag, type, die, DW_AT_import); +dwarf_tag__set_attr_type (dtag, type, die, DW_AT_import, cu);else if (tag->tag == DW_TAG_variant_part) -dwarf_tag__set_attr_type (dtag, type, die, DW_AT_discr); +dwarf_tag__set_attr_type (dtag, type, die, DW_AT_discr, cu);else -dwarf_tag__set_attr_type (dtag, type, die, DW_AT_type); +dwarf_tag__set_attr_type (dtag, type, die, DW_AT_type, cu); -dwarf_tag__set_attr_type (dtag, abstract_origin, die, DW_AT_abstract_origin); +dwarf_tag__set_attr_type (dtag, abstract_origin, die, DW_AT_abstract_origin, cu); tag->recursivity_level =0 ; tag->attributes =NULL ;
@@ -633,10 +633,10 @@ static struct tag *tag__new(Dwarf_Die *die, struct cu *cu)return tag; } -static void tag__set_spec (struct tag *tag,Dwarf_Die *die) +static void tag__set_spec (struct tag *tag,Dwarf_Die *die,struct cu *cu__maybe_unused ) {struct dwarf_tag *dtag =tag__dwarf (tag); -dwarf_tag__set_attr_type (dtag, specification, die, DW_AT_specification); +dwarf_tag__set_attr_type (dtag, specification, die, DW_AT_specification, cu); } static struct ptr_to_member_type *ptr_to_member_type__new(Dwarf_Die *die,
@@ -647,7 +647,7 @@ static struct ptr_to_member_type *ptr_to_member_type__new(Dwarf_Die *die,if (ptr !=NULL ) {tag__init (&ptr->tag, cu, die);struct dwarf_tag *dtag =tag__dwarf (&ptr->tag); -dwarf_tag__set_attr_type (dtag, containing_type, die, DW_AT_containing_type); +dwarf_tag__set_attr_type (dtag, containing_type, die, DW_AT_containing_type, cu); }return ptr;
@@ -738,7 +738,7 @@ static void type__init(struct type *type, Dwarf_Die *die, struct cu *cu, struct type->size =attr_numeric (die, DW_AT_byte_size); type->alignment =attr_alignment (die, conf); type->declaration =attr_numeric (die, DW_AT_declaration); -tag__set_spec (&type->namespace.tag, die); +tag__set_spec (&type->namespace.tag, die, cu); type->definition_emitted =0 ; type->fwd_decl_emitted =0 ; type->resized =0 ;
@@ -851,7 +851,7 @@ static struct variable *variable__new(Dwarf_Die *die, struct cu *cu, struct confif (!var->declaration && cu->has_addr_info) var->scope =dwarf__location (die, &var->ip.addr, &var->location);if (has_specification) { -tag__set_spec (&var->ip.tag, die); +tag__set_spec (&var->ip.tag, die, cu); } }
@@ -1326,7 +1326,7 @@ static struct variant *variant__new(Dwarf_Die *die, struct cu *cu, struct conf_lstruct dwarf_tag *dtag =tag__dwarf (&var->tag); var->name =attr_string (&child, DW_AT_name, conf); -dwarf_tag__set_attr_type (dtag, type, &child, DW_AT_type); +dwarf_tag__set_attr_type (dtag, type, &child, DW_AT_type, cu);break ; } }while (dwarf_siblingof (&child, &child) ==0 );
@@ -1779,7 +1779,7 @@ static struct inline_expansion *inline_expansion__new(Dwarf_Die *die, struct cutag__init (&exp->ip.tag, cu, die); dtag->decl_file =attr_string (die, DW_AT_call_file, conf); dtag->decl_line =attr_numeric (die, DW_AT_call_line); -dwarf_tag__set_attr_type (dtag, type, die, DW_AT_abstract_origin); +dwarf_tag__set_attr_type (dtag, type, die, DW_AT_abstract_origin, cu); exp->ip.addr =0 ; exp->high_pc =0 ;
@@ -1941,7 +1941,7 @@ static struct function *function__new(Dwarf_Die *die, struct cu *cu, struct conf func->declaration =dwarf_hasattr (die, DW_AT_declaration); func->external =dwarf_hasattr (die, DW_AT_external); func->abstract_origin =dwarf_hasattr (die, DW_AT_abstract_origin); -tag__set_spec (&func->proto.tag, die); +tag__set_spec (&func->proto.tag, die, cu); func->accessibility =attr_numeric (die, DW_AT_accessibility); func->virtuality =attr_numeric (die, DW_AT_virtuality);INIT_LIST_HEAD (&func->vtable_node);
Signature · 1 line
2.55.0
PATCH 10/12 dwarf_loader: Support DW_FORM_GNU_ref_alt references to dwz alternate debug files
In reply to Arnaldo Carvalho de MeloFrom: Arnaldo Carvalho de Melo <[email protected]>
Binaries processed by dwz(1) can have shared types deduplicated into a separate alternate debug file (.dwz), referenced via DW_FORM_GNU_ref_alt through the .gnu_debugaltlink ELF section. elfutils resolves these references transparently via dwarf_getalt(), but pahole was skipping them with a warning because the alt file's DWARF offset space is separate from the main file's — mixing them in the same hash tables caused type corruption and crashes.
Add a separate dwarf_cu (dcu->alt) with its own hash tables for the alt file's offset space. This mirrors the existing type_unit pattern but uses direct lookup instead of fallback: the DWARF form tells us exactly which hash table to use.
Key changes:
- Add 'from_alt' bitfield to struct dwarf_tag, parallel to from_types_section, marking references that point to the alt file.
- Add 'alt' pointer and 'processing_alt' flag to struct dwarf_cu. When processing children of an alt-file imported unit, processing_alt directs cu__hash() to use dcu->alt hash tables and causes all type references to be marked from_alt.
- Update attr_type() to resolve DW_FORM_GNU_ref_alt via dwarf_formref_die() instead of skipping. Returns the alt offset and sets is_alt so the caller marks from_alt on the dwarf_tag. When the alt file cannot be resolved (missing .gnu_debugaltlink target or build-id mismatch), emit a one-shot warning naming the artifact, the likely cause, and the fix (installing the matching debuginfo package).
- Update dwarf_cu__find_{tag,type}_by_ref() to check from_alt and
go directly to dcu->alt for lookup (not a fallback — the form
is unambiguous). - Create the alt dwarf_cu in cus__merge_and_process_cu() via dwarf_getalt() before processing any CUs, so it's available when die__process_imported_unit() encounters the first alt ref.
- Trigger the merged CU path when dwarf_getalt() finds an alt file, since the alt hash tables are only set up in that path.
- Prune unreferenced alt partial units after processing all CUs:
PUs directly imported by main-file CUs, or imported by any other PU, are conservatively retained — the hit-marking during pre-processing is not limited to main-CU-reachable PUs, so some unreferenced PUs may survive pruning. Pruning creates NULL holes in types_table; a prefix-sum adjustment array in btf_encoder lets
btf_encoder__tag_type() translate small_ids to dense BTF IDs in O(1). This relies on a documented dwz invariant: inter-PU dependencies use DW_TAG_imported_unit, not bare DW_FORM_ref_addr. tag__check_pruned_alt_ref() detects violations at recode time by checking whether a failed from_alt lookup targets a pruned PU.
- Alt PU ranges are kept in a sorted array and located via binary search (dwarf_cu__find_alt_pu), since large dwz alt files can contain thousands of partial units and every type reference needs to identify which PU it belongs to.
- dwarf_cu__delete() now explicitly frees hash_tags and hash_types via cu__free() for all dwarf_cu instances, not just the alt one. Under obstack this is a no-op, but in the non-obstack path it fixes a pre-existing leak.
- Remove attr_form_is_ref_alt() and all its callers — no longer needed since alt refs are now resolved instead of skipped.
- Add tests/dwz_alt_file.sh: creates two binaries sharing types, runs dwz to produce an alt file, verifies pahole resolves the shared types. Includes a negative sub-test that hides the alt file and verifies the one-shot warning fires exactly once and pahole does not crash.
The btf_encoder__tag_type() call site consolidation and the dwarf_tag__set_attr_type() / tag__set_spec() cu parameter threading were split into separate prep patches.
Before (chromium-browser debuginfo, Fedora 44):
$ pahole -F dwarf .../chromium-browser-149.0.7827.155-1.fc44.x86_64.debug
WARNING: DW_FORM_GNU_ref_alt (dwz alternate debug file) not yet supported,
some types will not be available.
[no output]After:
$ pahole -F dwarf .../chromium-browser-149.0.7827.155-1.fc44.x86_64.debug | wc -l 6378
This was based in previous, not AI assisted work back in 2023, as stored in these branches:
https://git.kernel.org/pub/scm/devel/pahole/pahole.git/log/?h=alt_dwarf and
https://git.kernel.org/pub/scm/devel/pahole/pahole.git/commit/?h=WIP-imported-unit
--- btf_encoder.c | 3 +- ctf_encoder.c | 11 + dwarf_loader.c | 579 +++++++++++++++++++++++++++++++++++++----- dwarves.h | 20 ++ tests/dwz_alt_file.sh | 204 +++++++++++++++ 5 files changed, 748 insertions(+), 69 deletions(-) create mode 100755 tests/dwz_alt_file.sh
btf_encoder.c +2 -1
@@ -768,7 +768,8 @@ static int32_t btf_encoder__tag_type(struct btf_encoder *encoder, uint32_t tag_tif (encoder->btf_id_map && tag_type < encoder->btf_id_map_sz)return encoder->btf_id_map[tag_type]; -/* Fallback for map-absent CUs (nr == 0) or out-of-range ids */ +/* Fallback for map-absent CUs (nr == 0) or out-of-range ids; +* adjust for NULL holes left by dwz alt PU pruning */ uint32_t adj = encoder->type_id_null_adj ? encoder->type_id_null_adj[tag_type] :0 ;return encoder->type_id_off + tag_type - adj;
ctf_encoder.c +11 -0
@@ -263,6 +263,17 @@ int cu__encode_ctf(struct cu *cu, int verbose)uint32_t id;struct tag *pos; + +/* CTF IDs must be sequential — NULL holes in the types table +* (from dwz alternate debug files) would desync core vs CTF IDs. +* Bail out rather than generate corrupt CTF. */ +for (id =1 ; id < cu->types_table.nr_entries; ++id) { +if (cu->types_table.entries[id] ==NULL ) { +fprintf (stderr,"ctf_encoder: NULL holes in types table not supported for CTF encoding\n" ); + goto out_delete; + } + } +cu__for_each_type (cu, id, pos)tag__encode_ctf (pos, cu, id, ctf);
dwarf_loader.c +511 -68
778 lines not on this page · raw message
dwarves.h +20 -0
@@ -393,6 +393,25 @@ bool languages__cu_filtered(struct languages *languages, struct cu *cu, bool vercontinue ; \ else +/** +* cu__for_each_type_dense - iterate types, tracking NULL holes +* @cu: struct cu instance to iterate +* @id: type_id_t raw table index +* @pos: struct tag iterator +* @nulls: uint32_t counter incremented for each NULL entry +* +* Like cu__for_each_type but counts NULL entries in @nulls so +* callers that need a dense (hole-free) index can compute it +* as (id - nulls). Use this when the table index must map to +* a sequential output ID (e.g. BTF/CTF encoding). + */ +#define cu__for_each_type_dense (cu, id, pos, nulls) \ + for (id = 1, nulls = 0; \ + id < cu->types_table.nr_entries; ++id) \ + if (!(pos = cu->types_table.entries[id])) \ + ++nulls; \ + else +/** * cu__for_each_struct - iterate thru all the struct tags * @cu: struct cu instance to iterate
@@ -949,6 +968,7 @@ struct parameter {int loc_reg;uint16_t type_byte_size; uint8_t true_sig_type_from_types:1; + uint8_t true_sig_type_from_alt:1; uint8_t has_const_value:1; uint8_t loc_const_value:1; uint8_t loc_stack:1;
tests/dwz_alt_file.sh new file +204 -0
204 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH 11/12 tests: Add inter-CU type reference comparison test
In reply to Arnaldo Carvalho de MeloFrom: Arnaldo Carvalho de Melo <[email protected]>
When the perf binary includes Rust CUs, some DWARF types reference types in other CUs via DW_FORM_ref_addr. The parallel loading path processes each CU independently, so cross-CU references fail during cu__recode_dwarf_types() and the types become unresolved (void).
The force_cu_merging feature worked around this by serializing loading into a mega-CU, but disables parallel DIE processing. This test compares both outputs to validate that cross-CU references are correctly resolved without needing force_cu_merging.
Before the preceding fix, 314 cross-CU references failed, producing 70 lines of output difference across 12 diff hunks:
$ pahole -F dwarf ~/bin/perf 2>/dev/null > parallel.txt $ pahole --features=force_cu_merging -F dwarf ~/bin/perf 2>/dev/null > merged.txt $ diff parallel.txt merged.txt | grep '^[<>]' | wc -l 70 $ diff -u parallel.txt merged.txt | head -20 --- parallel.txt +++ merged.txt @@ -10821,7 +10821,11 @@ usize __0 __attribute__((__aligned__(8))); struct ThreadInfo __1 __attribute__((__aligned__(8)));
+ /* XXX last struct has 8 bytes of padding, 1 hole */
+
/* size: 48, cachelines: 1, members: 2 */
+ /* member types with holes: 1, total: 1 */
+ /* paddings: 1, sum paddings: 8 */
/* forced alignments: 2 */
/* last cacheline: 48 bytes */
} __attribute__((__aligned__(8)));
The preceding commit fixed the detection of DW_FORM_ref_addr in cus__merging_cu(), making this test pass.
--- tests/inter_cu_refs.sh | 50 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100755 tests/inter_cu_refs.sh
tests/inter_cu_refs.sh new file +50 -0
@@ -0,0 +1,50 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0-only +# Copyright © 2026 Red Hat Inc, Arnaldo Carvalho de Melo <[email protected]> +# +# Compare default CU loading with explicit force_cu_merging for binaries +# with inter-CU type references (e.g. Rust CUs in perf). +# +# When cus__merging_cu() correctly detects DW_FORM_ref_addr usage, it +# automatically falls back to the merged CU path. This test verifies +# that the automatic detection produces the same output as explicitly +# forcing CU merging. + +. ./test_lib.sh + +outdir=$(make_tmpdir) +trap cleanup EXIT + +title_log "Compare parallel vs merged CU loading for inter-CU type references." + +perf=$(which perf 2>/dev/null) +if [ -z "$perf" ] ; then + info_log "skip: No 'perf' binary available" + test_skip +fi + +if ! pahole --features=force_cu_merging -F dwarf -C perf_event_header "$perf" 2>/dev/null | grep -q "^struct perf_event_header {" ; then + info_log "skip: $perf doesn't have 'struct perf_event_header' type info" + test_skip +fi + +parallel_out=$outdir/parallel.txt +merged_out=$outdir/merged.txt + +if ! pahole -F dwarf "$perf" > "$parallel_out" 2>/dev/null ; then + error_log "FAIL: pahole failed processing $perf (parallel mode)" + test_fail +fi + +if ! pahole --features=force_cu_merging -F dwarf "$perf" > "$merged_out" 2>/dev/null ; then + error_log "FAIL: pahole failed processing $perf (merged mode)" + test_fail +fi + +if diff -u "$parallel_out" "$merged_out" > /dev/null 2>&1 ; then + test_pass +else + nr_diff=$(diff "$parallel_out" "$merged_out" | grep '^[<>]' | wc -l) + error_log "FAIL: $nr_diff lines differ between parallel and merged CU loading" + test_fail +fi
Signature · 1 line
2.55.0
PATCH 12/12 scripts: Add vmlinux_comparison.py for DWARF/BTF analysis
In reply to Arnaldo Carvalho de MeloFrom: Arnaldo Carvalho de Melo <[email protected]>
Analyzes vmlinux files to compare DWARF versions, compilers, section sizes, and pahole output across different builds. Validates that different DWARF encodings (v4 vs v5, compressed vs uncompressed) produce equivalent pahole output.
The kernel offers several CONFIG_DEBUG_INFO options that affect DWARF encoding:
- CONFIG_DEBUG_INFO_DWARF4: DWARF version 4 format
- CONFIG_DEBUG_INFO_DWARF5: DWARF version 5 (~15% smaller sections)
- CONFIG_DEBUG_INFO_COMPRESSED_ZLIB: zlib-compressed debug sections
- CONFIG_DEBUG_INFO_COMPRESSED_ZSTD: zstd-compressed (smaller/faster)
- CONFIG_DEBUG_INFO_SPLIT: split DWARF with .dwo files (NOT supported yet)
This script validates pahole correctly handles all supported modes by comparing output hashes across different vmlinux builds.
Features:
- Extracts DWARF version and DW_AT_producer from debug info
- Reports file sizes and .debug_*/.BTF* section sizes
- Runs pahole -F dwarf and -F btf, computing output hashes
- Streams pahole output for memory efficiency (handles 800MB+ files)
- Optimized readelf: reads only first 100-200 lines for metadata instead of processing entire debug sections (minutes → seconds)
- Displays results in ASCII table similar to coverage-table
Example output shows DWARF v4 (599MB sections) vs v5 (500MB) vs v5+zlib (261MB) all produce identical pahole output (hash 86e1b611), validating pahole's consistency across different DWARF encodings.
Usage: scripts/vmlinux_comparison.py [directory]
Default directory: ~/dws/
Test vmlinux files covering supported configurations are available in ~/dws/. Split DWARF (DW_TAG_skeleton_unit) support is deferred to the next patch series.
Example:
acme@number:~/git/pahole$ ls -la ~/dws/vmlinux.* -rwxr-xr-x. 1 acme acme 876343656 Jul 16 20:25 /home/acme/dws/vmlinux.dwarf4 -rwxr-xr-x. 1 acme acme 772024544 Jul 16 21:43 /home/acme/dws/vmlinux.dwarf5 -rwxr-xr-x. 1 acme acme 521968168 Jul 17 08:19 /home/acme/dws/vmlinux.dwarf5.zlib -rwxr-xr-x. 1 acme acme 476736632 Jul 17 12:58 /home/acme/dws/vmlinux.dwarf5.zstd -rwxr-xr-x. 1 acme acme 772024248 Jul 16 20:32 /home/acme/dws/vmlinux.toolchain_default acme@number:~/git/pahole$ scripts/vmlinux_comparison.py ~/dws/ Scanning /home/acme/dws/ for vmlinux files... Found 5 vmlinux file(s)
Analyzing vmlinux.dwarf4...
Running pahole -F dwarf...
Running pahole -F btf...
Analyzing vmlinux.dwarf5...
Running pahole -F dwarf...
Running pahole -F btf...
Analyzing vmlinux.dwarf5.zlib...
Running pahole -F dwarf...
Running pahole -F btf...
Analyzing vmlinux.dwarf5.zstd...
Running pahole -F dwarf...
Running pahole -F btf...
Analyzing vmlinux.toolchain_default...
Running pahole -F dwarf...
Running pahole -F btf...
┌───────────────────────────┬─────────┬─────┬───────────────────────────────────┬─────────┬───────┬──────────┬────────┬──────────┬─────────┐ │ File │ Size │ Ver │ Producer │ DWARF │ BTF │ DW-Hash │ DW-Out │ BTF-Hash │ BTF-Out │ ├───────────────────────────┼─────────┼─────┼───────────────────────────────────┼─────────┼───────┼──────────┼────────┼──────────┼─────────┤ │ vmlinux.dwarf4 │ 835.7MB │ 4 │ GNU C11 16.1.1 -gdwarf-4 │ 599.2MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.dwarf5 │ 736.3MB │ 5 │ GNU C11 16.1.1 -gdwarf-5 │ 499.7MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.dwarf5.zlib │ 497.8MB │ 5 │ GNU C11 16.1.1 -gdwarf-5 -gz=zlib │ 261.2MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.dwarf5.zstd │ 454.7MB │ 5 │ GNU C11 16.1.1 -gdwarf-5 -gz=zstd │ 218.1MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.toolchain_default │ 736.3MB │ 5 │ GNU C11 16.1.1 │ 499.7MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ └───────────────────────────┴─────────┴─────┴───────────────────────────────────┴─────────┴───────┴──────────┴────────┴──────────┴─────────┘
Column descriptions:
File : vmlinux filename
Size : Total file size
Ver : DWARF version
Producer : Compiler and flags (truncated)
DWARF : Total size of .debug_* sections
BTF : Total size of .BTF* sections
DW-Hash : SHA256 hash (first 8 chars) of pahole -F dwarf output
DW-Out : Size of pahole -F dwarf output
BTF-Hash : SHA256 hash (first 8 chars) of pahole -F btf output
BTF-Out : Size of pahole -F btf outputNote: Different hashes indicate different pahole output between files.
The output shows that vmlinux variants (different DWARF versions, compression) produce identical pahole output despite different file sizes and debug section sizes, validating pahole's consistency across different DWARF encodings. acme@number:~/git/pahole$
--- scripts/vmlinux_comparison.py | 367 ++++++++++++++++++++++++++++++++++ 1 file changed, 367 insertions(+) create mode 100755 scripts/vmlinux_comparison.py
scripts/vmlinux_comparison.py new file +367 -0
@@ -0,0 +1,367 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +# Arnaldo Carvalho de Melo <[email protected]> +# Assisted-by: Claude:claude-sonnet-4-5 +# +# Compare vmlinux files: DWARF versions, producers, section sizes, and pahole output. +# +# Prompt used to generate this script: +# +# Given a directory with a series of vmlinux files, look at the DW_AT_producer +# DWARF tags to notice what's unique for each of the vmlinux files, look at the +# DWARF version as well, then run pahole -F dwarf and btf to see if the output +# produced changes for both formats in the different vmlinux files, create a +# table like the one in the upcoming coverage-table make target. Add columns for +# each row (DWARF files) with the size of the vmlinux files and the size of the +# DWARF and BTF related ELF sections on each of the vmlinux files. +# +# Usage: +# scripts/vmlinux_comparison.py [DIRECTORY] +# +# Default directory: ~/dws/ + +import argparse +import hashlib +import os +import re +import subprocess +import sys +import tempfile + +def format_size(size_bytes): + """Format byte size in human-readable format.""" + for unit in ['B', 'KB', 'MB', 'GB']: + if size_bytes < 1024.0: + return f"{size_bytes:.1f}{unit}" + size_bytes /= 1024.0 + return f"{size_bytes:.1f}TB" + +def get_file_size(path): + """Get file size in bytes.""" + return os.path.getsize(path) + +def extract_dwarf_version(vmlinux_path): + """Extract DWARF version using readelf (only first 100 lines).""" + try: + # Only read first 100 lines of debug info to find version quickly + cmd = f"readelf --debug-dump=info '{vmlinux_path}' 2>/dev/null | head -100" + result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=10) + if result.returncode != 0: + return 'N/A' + + # Look for first "Version:" in output + for line in result.stdout.splitlines(): + if 'Version:' in line: + match = re.search(r'Version:\s+(\d+)', line) + if match: + return match.group(1) + return 'N/A' + except Exception as e: + return 'N/A' + + +def extract_producer(vmlinux_path): + """Extract DW_AT_producer using readelf (only first 200 lines).""" + try: + # Only read first 200 lines of debug info to find producer quickly + cmd = f"readelf --debug-dump=info '{vmlinux_path}' 2>/dev/null | head -200" + result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=10) + if result.returncode != 0: + return 'N/A' + + # Look for first DW_AT_producer + for line in result.stdout.splitlines(): + if 'DW_AT_producer' in line: + # Extract the actual producer string after the colon + match = re.search(r'DW_AT_producer\s*:\s*(?:\([^)]+\):\s*)?(.+)', line) + if match: + producer = match.group(1).strip() + # Extract key parts: compiler name, version, DWARF flag + # Example: "GNU C11 16.1.1 20260515 (Red Hat 16.1.1-2) ... -gdwarf-4 ..." + + # Get compiler and version + compiler_match = re.search(r'(GNU C\d+|clang)\s+([\d.]+)', producer) + compiler = compiler_match.group(0) if compiler_match else 'unknown' + + # Get DWARF version flag + dwarf_match = re.search(r'-gdwarf-(\d+)', producer) + dwarf_flag = f"-gdwarf-{dwarf_match.group(1)}" if dwarf_match else '' + + # Get compression if present + compress_match = re.search(r'-gz(=\w+)?', producer) + compress = compress_match.group(0) if compress_match else '' + + parts = [compiler, dwarf_flag, compress] + return ' '.join(p for p in parts if p) + return 'N/A' + except Exception as e: + return f'Error: {e}' + + +def get_section_sizes(vmlinux_path): + """Get sizes of DWARF and BTF sections using readelf.""" + try: + cmd = ['readelf', '-S', vmlinux_path] + result = subprocess.run(cmd, capture_output=True, text=True, timeout=30) + if result.returncode != 0: + return 0, 0 + + dwarf_size = 0 + btf_size = 0 + + # Parse section table - readelf outputs sections across two lines: + # Line 1: [Nr] Name Type Address Offset + # Line 2: Size EntSize Flags Link Info Align + lines = result.stdout.splitlines() + i = 0 + while i < len(lines): + line = lines[i] + + # Match section header line: [Nr] Name ... + match = re.match(r'\s*\[\s*\d+\]\s+(\S+)', line) + if match: + section_name = match.group(1) + + # Size is on the next line + if i + 1 < len(lines): + next_line = lines[i + 1] + # Extract first hex number from next line (the size) + size_match = re.search(r'^\s+([0-9a-f]+)', next_line) + if size_match: + size = int(size_match.group(1), 16) + + if section_name.startswith('.debug_'): + dwarf_size += size + elif section_name.startswith('.BTF'): + btf_size += size + + i += 1 + + return dwarf_size, btf_size + except Exception as e: + return 0, 0 + + +def run_pahole_and_hash(vmlinux_path, format_type): + """Run pahole with given format and return output hash.""" + try: + # Run pahole and stream output for hashing (avoids loading into memory) + cmd = ['pahole', '-F', format_type, vmlinux_path] + result = subprocess.Popen(cmd, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL) # Ignore stderr to avoid blocking + + # Stream output and compute hash on the fly + hasher = hashlib.sha256() + file_size = 0 + + while True: + chunk = result.stdout.read(8192) + if not chunk: + break + hasher.update(chunk) + file_size += len(chunk) + + result.wait(timeout=600) # Increase timeout to 10 minutes for large files + + if result.returncode != 0: + return 'ERROR', 0 + + hash_short = hasher.hexdigest()[:8] + return hash_short, file_size + except subprocess.TimeoutExpired: + result.kill() + result.wait() # Clean up zombie process + return 'TIMEOUT', 0 + except Exception as e: + return 'ERROR', 0 + + +def find_vmlinux_files(directory): + """Find all vmlinux* files in directory, excluding text files.""" + vmlinux_files = [] + + if not os.path.isdir(directory): + print(f"Error: {directory} is not a directory", file=sys.stderr) + return [] + + for filename in os.listdir(directory): + path = os.path.join(directory, filename) + + # Skip non-files + if not os.path.isfile(path): + continue + + # Only include files starting with "vmlinux" + if not filename.startswith('vmlinux'): + continue + + # Skip text files (.c, .txt, etc.) + if filename.endswith(('.c', '.txt', '.log', '.md')): + continue + + # Check if it's an ELF file + try: + with open(path, 'rb') as f: + magic = f.read(4) + if magic != b'\x7fELF': + continue + except: + continue + + vmlinux_files.append(path) + + return sorted(vmlinux_files) + + +def analyze_vmlinux(vmlinux_path): + """Analyze a single vmlinux file and return metrics.""" + filename = os.path.basename(vmlinux_path) + + print(f" Analyzing {filename}...", file=sys.stderr) + + file_size = get_file_size(vmlinux_path) + dwarf_version = extract_dwarf_version(vmlinux_path) + producer = extract_producer(vmlinux_path) + dwarf_size, btf_size = get_section_sizes(vmlinux_path) + + print(f" Running pahole -F dwarf...", file=sys.stderr) + dwarf_hash, dwarf_out_size = run_pahole_and_hash(vmlinux_path, 'dwarf') + + print(f" Running pahole -F btf...", file=sys.stderr) + btf_hash, btf_out_size = run_pahole_and_hash(vmlinux_path, 'btf') + + return { + 'filename': filename, + 'file_size': file_size, + 'dwarf_version': dwarf_version, + 'producer': producer, + 'dwarf_section_size': dwarf_size, + 'btf_section_size': btf_size, + 'dwarf_output_hash': dwarf_hash, + 'dwarf_output_size': dwarf_out_size, + 'btf_output_hash': btf_hash, + 'btf_output_size': btf_out_size, + } + + +def print_table(results): + """Print comparison table with box-drawing characters.""" + if not results: + print("No vmlinux files found.") + return + + # Column widths + W_FILE = 30 + W_SIZE = 8 + W_VER = 4 + W_PROD = 35 + W_SECT = 10 + W_HASH = 10 + W_OUT = 10 + + # Header + def print_sep(char='─'): + print(f"┌{char*(W_FILE+2)}┬{char*(W_SIZE+2)}┬{char*(W_VER+2)}┬{char*(W_PROD+2)}┬" + f"{char*(W_SECT+2)}┬{char*(W_SECT+2)}┬" + f"{char*(W_HASH+2)}┬{char*(W_OUT+2)}┬" + f"{char*(W_HASH+2)}┬{char*(W_OUT+2)}┐") + + def print_row_sep(): + print(f"├{'─'*(W_FILE+2)}┼{'─'*(W_SIZE+2)}┼{'─'*(W_VER+2)}┼{'─'*(W_PROD+2)}┼" + f"{'─'*(W_SECT+2)}┼{'─'*(W_SECT+2)}┼" + f"{'─'*(W_HASH+2)}┼{'─'*(W_OUT+2)}┼" + f"{'─'*(W_HASH+2)}┼{'─'*(W_OUT+2)}┤") + + print_sep() + + # Column headers + print(f"│ {'File':<{W_FILE}} │ {'Size':>{W_SIZE}} │ {'Ver':>{W_VER}} │ {'Producer':<{W_PROD}} │ " + f"{'DWARF':>{W_SECT}} │ {'BTF':>{W_SECT}} │ " + f"{'DW-Hash':>{W_HASH}} │ {'DW-Out':>{W_OUT}} │ " + f"{'BTF-Hash':>{W_HASH}} │ {'BTF-Out':>{W_OUT}} │") + + print_row_sep() + + # Data rows + for r in results: + fname = r['filename'] + if len(fname) > W_FILE: + fname = fname[:W_FILE-3] + '...' + + fsize = format_size(r['file_size']) + ver = r['dwarf_version'] + + prod = r['producer'] + if len(prod) > W_PROD: + prod = prod[:W_PROD-3] + '...' + + dwarf_sect = format_size(r['dwarf_section_size']) + btf_sect = format_size(r['btf_section_size']) + + dw_hash = r['dwarf_output_hash'] + dw_out = format_size(r['dwarf_output_size']) + + btf_hash = r['btf_output_hash'] + btf_out = format_size(r['btf_output_size']) + + print(f"│ {fname:<{W_FILE}} │ {fsize:>{W_SIZE}} │ {ver:>{W_VER}} │ {prod:<{W_PROD}} │ " + f"{dwarf_sect:>{W_SECT}} │ {btf_sect:>{W_SECT}} │ " + f"{dw_hash:>{W_HASH}} │ {dw_out:>{W_OUT}} │ " + f"{btf_hash:>{W_HASH}} │ {btf_out:>{W_OUT}} │") + + # Footer + print(f"└{'─'*(W_FILE+2)}┴{'─'*(W_SIZE+2)}┴{'─'*(W_VER+2)}┴{'─'*(W_PROD+2)}┴" + f"{'─'*(W_SECT+2)}┴{'─'*(W_SECT+2)}┴" + f"{'─'*(W_HASH+2)}┴{'─'*(W_OUT+2)}┴" + f"{'─'*(W_HASH+2)}┴{'─'*(W_OUT+2)}┘") + + print() + print("Column descriptions:") + print(" File : vmlinux filename") + print(" Size : Total file size") + print(" Ver : DWARF version") + print(" Producer : Compiler and flags (truncated)") + print(" DWARF : Total size of .debug_* sections") + print(" BTF : Total size of .BTF* sections") + print(" DW-Hash : SHA256 hash (first 8 chars) of pahole -F dwarf output") + print(" DW-Out : Size of pahole -F dwarf output") + print(" BTF-Hash : SHA256 hash (first 8 chars) of pahole -F btf output") + print(" BTF-Out : Size of pahole -F btf output") + print() + print("Note: Different hashes indicate different pahole output between files.") + print() + print("The output shows that vmlinux variants (different DWARF versions, compression)") + print("produce identical pahole output despite different file sizes and debug section") + print("sizes, validating pahole's consistency across different DWARF encodings.") + + +def main(): + parser = argparse.ArgumentParser( + description='Compare vmlinux files: DWARF, BTF, and pahole output') + parser.add_argument('directory', nargs='?', + default=os.path.expanduser('~/dws'), + help='Directory containing vmlinux files (default: ~/dws)') + args = parser.parse_args() + + directory = os.path.expanduser(args.directory) + + print(f"Scanning {directory} for vmlinux files...", file=sys.stderr) + vmlinux_files = find_vmlinux_files(directory) + + if not vmlinux_files: + print(f"No vmlinux files found in {directory}", file=sys.stderr) + sys.exit(1) + + print(f"Found {len(vmlinux_files)} vmlinux file(s)\n", file=sys.stderr) + + results = [] + for vmlinux_path in vmlinux_files: + result = analyze_vmlinux(vmlinux_path) + results.append(result) + + print(file=sys.stderr) + print_table(results) + + +if __name__ == '__main__': + main()
Signature · 1 line
2.55.0
Quoted 29 lines · Arnaldo Carvalho de Melo
Hi,
Add support for Rust discriminated unions (enums with explicit discriminants).
Rust enums like Option<u32> and Result<i32,u8> are represented in DWARF as
DW_TAG_variant_partcontainingDW_TAG_variantchildren with discriminant values. These patches:- Load
DW_TAG_variant_partcontainers with discriminant tracking
- PopulateDW_TAG_variantchildren with discriminant values
- HandleDW_FORM_blockencoding for discriminant values
- HandleDW_TAG_subprograminsideDW_TAG_enumeration(Rust methods)
- Encode variant parts asBTF_KIND_UNIONmembersBefore: Rust Option<u32> showed as empty struct (0 members)
After: Shows None and Some variants with correct layout
=== pahole --expand_types output === struct Option<u32> { struct None { } __attribute__((__aligned__(4))); struct Some { /* XXX 4 bytes hole, try to pack */ u32 __0 __attribute__((__aligned__(4))); /* 4 4 */ } __attribute__((__aligned__(4))); } __attribute__((__aligned__(4)));
Quoted 4 lines
BTF has no discriminated-union kind, so variant parts are tentatively encoded as
BTF_KIND_UNIONwith overlapping members at offset 0. Further discussion is needed to see if we can keep that.
It seems like these variants mostly have a leading discriminating value (telling us which variant is selected), and it looks like it is possible to infer its presence by determining by its members if it has that discriminant (do any members have niche layout? if not it is there) and its size (depends on the number of variants). Given that, would it make sense to have a discriminant too? It seems that the above example Option<u32> has one, so we'd have
struct Option<u32> {
uint8_t tag; // 1 byte: Explicit discriminant
uint8_t pad[3];
struct Some {...
This would give us a better match for the in-memory representation. What do you think, is it doable?
Quoted 97 lines
DW_FORM_blockbyte order fix: uses CU-recorded endianness instead of assuming little-endian when decodingDW_AT_const_valueandDW_AT_default_value. Fixes cross-endian DWARF processing (e.g. reading big-endian s390x debug info on x86).Also add support for cross-CU type references and dwz alternate debug files.
This is needed to improve the support for, among other things, Rust, as noticed in the pretty printing or a perf binary that has rust objects linked, built by clang/llvm that use cross-CU references.
DW_TAG_imported_unitsupport:Handle same-file partial units where types are shared across CUs via
DW_TAG_imported_unit. Force-merge CUs that contain inter-CU references (DW_FORM_ref_addr) so type lookups resolve correctly.Fix
cus__merging_cufailing to detectDW_FORM_ref_addrwhenDW_FORM_implicit_constcausesdwarf_getabbrevattr()to fail.dwz alternate debug file support:
Handle
DW_FORM_GNU_ref_altreferences to dwz-compressed alternate debug files (.dwz). Pre-processes all alternate partial units with separate hash tables and dedup tracking.Before (Firefox): 1774 "has no entry in cu" errors
After: processes cleanly with 0 errorsFirefox uses dwz compression which moves common types into a separate .dwz file and replaces duplicates with
DW_FORM_GNU_ref_altreferences. pahole now pre-loads the alternate file's partial units, resolves all cross-file references, and processes Firefox DWARF cleanly.Includes inter-CU type reference comparison test and
vmlinux_comparison.pyfor DWARF/BTF analysis across kernel configs.Known limitations:
- Pruning of unreferenced alt PUs is conservatively over-approximated
- Merged-CU path is single-threaded by designThis makes pahole to be able to support more of the
CONFIG_DEBUG_DWARF options, including DWARF5 and compression, see the latest patch in the series for more details about how this table is produced:┌───────────────────────────┬─────────┬─────┬───────────────────────────────────┬─────────┬───────┬──────────┬────────┬──────────┬─────────┐ │ File │ Size │ Ver │ Producer │ DWARF │ BTF │ DW-Hash │ DW-Out │ BTF-Hash │ BTF-Out │ ├───────────────────────────┼─────────┼─────┼───────────────────────────────────┼─────────┼───────┼──────────┼────────┼──────────┼─────────┤ │ vmlinux.dwarf4 │ 835.7MB │ 4 │ GNU C11 16.1.1 -gdwarf-4 │ 599.2MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.dwarf5 │ 736.3MB │ 5 │ GNU C11 16.1.1 -gdwarf-5 │ 499.7MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.dwarf5.zlib │ 497.8MB │ 5 │ GNU C11 16.1.1 -gdwarf-5 -gz=zlib │ 261.2MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.dwarf5.zstd │ 454.7MB │ 5 │ GNU C11 16.1.1 -gdwarf-5 -gz=zstd │ 218.1MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.toolchain_default │ 736.3MB │ 5 │ GNU C11 16.1.1 │ 499.7MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ └───────────────────────────┴─────────┴─────┴───────────────────────────────────┴─────────┴───────┴──────────┴────────┴──────────┴─────────┘Split DWARF support (skeleton CUs) will be supported in upcoming work, so as to cover all the possibilities the kernel build system offers for generating DWARF.
- Arnaldo
Arnaldo Carvalho de Melo (12):
dwarf_loader: Initial support forDW_TAG_variant_part
dwarf_loader: Initial support forDW_TAG_subprograminDW_TAG_enumeration
dwarf_loader: PopulateDW_TAG_variantchildren inDW_TAG_variant_part
btf_encoder: Encode variant parts as union members in BTF
dwarf_loader: HandleDW_FORM_blockinattr_numericfor Rust discriminant values
dwarf_loader: Allow forcing the merge of CUs for solving inter CU tag references
dwarf_loader: SupportDW_TAG_imported_unitfor same-file partial units
dwarf_loader: Fixcus__merging_cufailing to detectDW_FORM_ref_addr
dwarf_loader: Add cu parameter totag__set_spec()anddwarf_tag__set_attr_type()
dwarf_loader: SupportDW_FORM_GNU_ref_altreferences to dwz alternate debug files
tests: Add inter-CU type reference comparison test
scripts: Addvmlinux_comparison.pyfor DWARF/BTF analysisbtf_encoder.c | 66 ++- ctf_encoder.c | 34 +- dwarf_loader.c | 873 ++++++++++++++++++++++++++++++---- dwarves.c | 77 ++- dwarves.h | 63 ++- dwarves_emit.c | 10 +- dwarves_fprintf.c | 54 ++- man-pages/pahole.1 | 18 +- pahole.c | 20 +- scripts/vmlinux_comparison.py | 367 ++++++++++++++ tests/block_endian.sh | 146 ++++++ tests/dwz_alt_file.sh | 204 ++++++++ tests/inter_cu_refs.sh | 50 ++ tests/prettify_perf.data.sh | 4 +- 14 files changed, 1854 insertions(+), 132 deletions(-) create mode 100755 scripts/vmlinux_comparison.py create mode 100755 tests/block_endian.sh create mode 100755 tests/dwz_alt_file.sh create mode 100755 tests/inter_cu_refs.sh
Adding Miguel to the CC list, Miguel we're trying to improve BTF support for Rust, this series handles multiple enabling fixes/improvements that gets us to the next level, i.e. we can load everything from DWARF, now its time to try to map it to existing BTF kinds and propose BTF extensions when we can't use existing encodings.
Quoted 40 lines · Alan Maguire
Quoted 27 lines · Arnaldo Carvalho de Melo
Add support for Rust discriminated unions (enums with explicit discriminants).
Rust enums like Option<u32> and Result<i32,u8> are represented in DWARF as
DW_TAG_variant_partcontainingDW_TAG_variantchildren with discriminant values. These patches:- Load
DW_TAG_variant_partcontainers with discriminant tracking
- PopulateDW_TAG_variantchildren with discriminant values
- HandleDW_FORM_blockencoding for discriminant values
- HandleDW_TAG_subprograminsideDW_TAG_enumeration(Rust methods)
- Encode variant parts asBTF_KIND_UNIONmembersBefore: Rust Option<u32> showed as empty struct (0 members)
After: Shows None and Some variants with correct layout
=== pahole --expand_types output === struct Option<u32> { struct None { } __attribute__((__aligned__(4))); struct Some { /* XXX 4 bytes hole, try to pack */ u32 __0 __attribute__((__aligned__(4))); /* 4 4 */ } __attribute__((__aligned__(4))); } __attribute__((__aligned__(4)));Quoted 3 lines
BTF has no discriminated-union kind, so variant parts are tentatively encoded as
BTF_KIND_UNIONwith overlapping members at offset 0. Further discussion is needed to see if we can keep that.It seems like these variants mostly have a leading discriminating value (telling us which variant is selected), and it looks like it is possible to infer its presence by determining by its members if it has that discriminant (do any members have niche layout? if not it is there) and its size (depends on the number of variants). Given that, would it make sense to have a discriminant too? It seems that the above example Option<u32> has one, so we'd have
Quoted 8 lines
struct Option<u32> { uint8_t tag; // 1 byte: Explicit discriminant uint8_t pad[3]; struct Some {...
This would give us a better match for the in-memory representation. What do you think, is it doable?
It seems we have help from DWARF5 for that, I'm studying this Opus 4.8 response:
-------------
Don't infer it, read DW_AT_discr. Per DWARF 5 §5.7.10, DW_TAG_variant_part carries DW_AT_discr referencing a DW_TAG_member child of the variant part itself — the tag, with a real type, real DW_AT_data_member_location, real size. That member is being dropped on the floor today, which is exactly why Some.__0 shows a phantom 4-byte hole instead of the true 1-byte tag + 3-byte pad. Load it as an ordinary member of the enclosing struct and the layout falls out correct with no heuristics. (If DW_AT_discr is absent but DW_AT_type is present on the variant part, the tag exists but isn't separately addressable — that's the spec's signal, not something you compute.)
Inferring from "does any member have a niche layout" means reverse-engineering rustc's layout algorithm, which is explicitly unstable and unspecified. It'd break silently on a compiler bump, with no way to tell from the DWARF that you got it wrong.
Where it gets sharp:
Niche-optimized enums overlap. For Option<&T> or Option<NonZeroU32> the discriminant member is the payload field — same offset, same bytes. Emitting it unconditionally gives you two members at offset 0 covering the same storage. So the rule wants to be: emit as a struct member only when it doesn't overlap any variant's members; otherwise it belongs inside the union encoding, where overlap is already the semantics.
Tag isn't always at offset 0. rustc places it after the payload in some layouts when that shrinks the type. Take the offset from the DIE.
Naming. rustc frequently emits the tag member unnamed/DW_AT_artificial. You'll need a synthetic name, and it lands in BTF where consumers will see it forever. Worth picking something unmistakably synthetic rather than plausible-looking.
DW_AT_discr_list. Niche layouts use range lists (DW_DSC_label/DW_DSC_range in a block), not a scalar DW_AT_discr_value. Your DW_FORM_block handling is the right groundwork but the list form is a separate shape.
-------------
<1><931e405>: Abbrev Number: 6 (DW_TAG_base_type)
<931e406> DW_AT_name : (indirect string, offset: 0x8235d): u32
<931e40a> DW_AT_encoding : 7 (unsigned)
<931e40b> DW_AT_byte_size : 4 <3><92dadb3>: Abbrev Number: 8 (DW_TAG_structure_type)
<92dadb4> DW_AT_name : (indirect string, offset: 0x205eab): Option<u32>
<92dadb8> DW_AT_byte_size : 8
<92dadb9> DW_AT_accessibility: 1 (public)
<92dadba> DW_AT_alignment : 4
<4><92dadbb>: Abbrev Number: 56 (DW_TAG_variant_part)
<92dadbc> DW_AT_discr : <0x92dadc0>
<5><92dadc0>: Abbrev Number: 57 (DW_TAG_member)
<92dadc1> DW_AT_type : <0x931e405>
<92dadc5> DW_AT_alignment : 4
<92dadc6> DW_AT_data_member_location: 0
<92dadc7> DW_AT_artificial : 1
<5><92dadc7>: Abbrev Number: 58 (DW_TAG_variant)
<92dadc8> DW_AT_discr_value : 0
<6><92dadc9>: Abbrev Number: 4 (DW_TAG_member)
<92dadca> DW_AT_name : (indirect string, offset: 0x3c4642): None
<92dadce> DW_AT_type : <0x92dade4>
<92dadd2> DW_AT_alignment : 4
<92dadd3> DW_AT_data_member_location: 0
<6><92dadd4>: Abbrev Number: 0
<5><92dadd5>: Abbrev Number: 58 (DW_TAG_variant)
<92dadd6> DW_AT_discr_value : 1
<6><92dadd7>: Abbrev Number: 4 (DW_TAG_member)
<92dadd8> DW_AT_name : (indirect string, offset: 0x3bf339): Some
<92daddc> DW_AT_type : <0x92dadf6>
<92dade0> DW_AT_alignment : 4
<92dade1> DW_AT_data_member_location: 0
<6><92dade2>: Abbrev Number: 0
<5><92dade3>: Abbrev Number: 0
<4><92dade4>: Abbrev Number: 8 (DW_TAG_structure_type)
<92dade5> DW_AT_name : (indirect string, offset: 0x3c4642): None
<92dade9> DW_AT_byte_size : 8
<92dadea> DW_AT_accessibility: 1 (public)
<92dadeb> DW_AT_alignment : 4
<5><92dadec>: Abbrev Number: 59 (DW_TAG_template_type_param)
<92daded> DW_AT_type : <0x931e405>
<92dadf1> DW_AT_name : (indirect string, offset: 0x29c455): T
<5><92dadf5>: Abbrev Number: 0
<4><92dadf6>: Abbrev Number: 8 (DW_TAG_structure_type)
<92dadf7> DW_AT_name : (indirect string, offset: 0x3bf339): Some
<92dadfb> DW_AT_byte_size : 8
<92dadfc> DW_AT_accessibility: 1 (public)
<92dadfd> DW_AT_alignment : 4
<5><92dadfe>: Abbrev Number: 59 (DW_TAG_template_type_param)
<92dadff> DW_AT_type : <0x931e405>
<92dae03> DW_AT_name : (indirect string, offset: 0x29c455): T
<5><92dae07>: Abbrev Number: 9 (DW_TAG_member)
<92dae08> DW_AT_name : (indirect string, offset: 0x2c1fb): __0
<92dae0c> DW_AT_type : <0x931e405>
<92dae10> DW_AT_alignment : 4
<92dae11> DW_AT_data_member_location: 4
<92dae12> DW_AT_accessibility: 1 (public) <5><92dae13>: Abbrev Number: 0
<4><92dae14>: Abbrev Number: 0
So in this case it says the discriminant is indeed at offset zero:
<4><92dadbb>: Abbrev Number: 56 (DW_TAG_variant_part)
<92dadbc> DW_AT_discr : <0x92dadc0>
<5><92dadc0>: Abbrev Number: 57 (DW_TAG_member)
<92dadc1> DW_AT_type : <0x931e405>
<92dadc5> DW_AT_alignment : 4
<92dadc6> DW_AT_data_member_location: 0
<92dadc7> DW_AT_artificial : 1I.e. DW_AT_discr points to that artificial member, we need to synthesize a name for it as BTF doesn't support nameless members, and we're using it to:
if (tag->tag == DW_TAG_imported_module || tag->tag == DW_TAG_imported_declaration)
dwarf_tag__set_attr_type(dtag, type, die, DW_AT_import, cu);
else if (tag->tag == DW_TAG_variant_part)
dwarf_tag__set_attr_type(dtag, type, die, DW_AT_discr, cu);
else
dwarf_tag__set_attr_type(dtag, type, die, DW_AT_type, cu);Set the variant part type.
_and_
static struct variant *variant__new(Dwarf_Die *die, struct cu *cu, struct conf_load *conf)
{
struct variant *var = tag__alloc(cu, sizeof(*var));
if (var != NULL) {
tag__init(&var->tag, cu, die);
/* DW_AT_discr_value uses DW_FORM_block, needs target endianness */
var->discr_value = __attr_numeric(die, DW_AT_discr_value, cu->little_endian);But that now is just a read only field:
acme@number:~/git/pahole$ grep discr_value *.[ch] dwarf_loader.c: * When the attribute can be a block (e.g. DW_AT_discr_value), use dwarf_loader.c: /* DW_AT_discr_value uses DW_FORM_block, needs target endianness */ dwarf_loader.c: var->discr_value = __attr_numeric(die, DW_AT_discr_value, cu->little_endian); dwarves.h: uint64_t discr_value; acme@number:~/git/pahole$
We need to use it when pretty printing structs, encoding BTF (synthesizing some "__discriminant" member that can be used by the BPF verifier, etc) and in the hole calculations. Pretty printing it with the current C only code would be done with a comment.
So the way this series does now is incomplete, but moves the needle a bit, but lemme try to cook up a patch that removes the "3 bytes hole, try to pack" comment on the alignent hole that sometimes gets after the artifical member that is the discriminant and the payload, as nobody can actually make use of that, i.e. if the member is a discriminant, the comment can be "discriminant hole, unusable" or some other better phrasing.
I.e. something like:
struct Option<u32> {
u8 __discriminant; /* 0 1 */
/* 3 byte discriminant hole, innacessible */
union {
struct None {
};
struct Some {
u32 __0; /* 0 4 */
};
}; /* 4 4 */
};Right now we have:
acme@number:~/git/pahole$ pahole --expand_types -F btf -C 'Option<u32>' vmlinux.btf
union Option<u32> {
struct None {
} __attribute__((__aligned__(16))) None; /* 0 8 */
struct Some {/* XXX 4 bytes hole, try to pack */ u32 __0 __attribute__((__aligned__(8))); /* 4 4 */ } Some; /* 0 8 */ };
acme@number:~/git/pahole$
Which is just not showing the discriminant, so perhaps, to make progress, we can land the series and work on top of it?
Supporting DWARF5 and cross cu references helps testing building the kernel with:
│ vmlinux.dwarf5.zstd │ 454.7MB │ 5 │ GNU C11 16.1.1 -gdwarf-5 -gz=zstd │ 218.1MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │
And if it proves reliable (should be from my tests so far) we can speed up building the kernel, which in itself is a big improvement.
Regards,
- Arnaldo
Quoted 97 lines
Quoted 97 lines
DW_FORM_blockbyte order fix: uses CU-recorded endianness instead of assuming little-endian when decodingDW_AT_const_valueandDW_AT_default_value. Fixes cross-endian DWARF processing (e.g. reading big-endian s390x debug info on x86).Also add support for cross-CU type references and dwz alternate debug files.
This is needed to improve the support for, among other things, Rust, as noticed in the pretty printing or a perf binary that has rust objects linked, built by clang/llvm that use cross-CU references.
DW_TAG_imported_unitsupport:Handle same-file partial units where types are shared across CUs via
DW_TAG_imported_unit. Force-merge CUs that contain inter-CU references (DW_FORM_ref_addr) so type lookups resolve correctly.Fix
cus__merging_cufailing to detectDW_FORM_ref_addrwhenDW_FORM_implicit_constcausesdwarf_getabbrevattr()to fail.dwz alternate debug file support:
Handle
DW_FORM_GNU_ref_altreferences to dwz-compressed alternate debug files (.dwz). Pre-processes all alternate partial units with separate hash tables and dedup tracking.Before (Firefox): 1774 "has no entry in cu" errors
After: processes cleanly with 0 errorsFirefox uses dwz compression which moves common types into a separate .dwz file and replaces duplicates with
DW_FORM_GNU_ref_altreferences. pahole now pre-loads the alternate file's partial units, resolves all cross-file references, and processes Firefox DWARF cleanly.Includes inter-CU type reference comparison test and
vmlinux_comparison.pyfor DWARF/BTF analysis across kernel configs.Known limitations:
- Pruning of unreferenced alt PUs is conservatively over-approximated
- Merged-CU path is single-threaded by designThis makes pahole to be able to support more of the
CONFIG_DEBUG_DWARF options, including DWARF5 and compression, see the latest patch in the series for more details about how this table is produced:┌───────────────────────────┬─────────┬─────┬───────────────────────────────────┬─────────┬───────┬──────────┬────────┬──────────┬─────────┐ │ File │ Size │ Ver │ Producer │ DWARF │ BTF │ DW-Hash │ DW-Out │ BTF-Hash │ BTF-Out │ ├───────────────────────────┼─────────┼─────┼───────────────────────────────────┼─────────┼───────┼──────────┼────────┼──────────┼─────────┤ │ vmlinux.dwarf4 │ 835.7MB │ 4 │ GNU C11 16.1.1 -gdwarf-4 │ 599.2MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.dwarf5 │ 736.3MB │ 5 │ GNU C11 16.1.1 -gdwarf-5 │ 499.7MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.dwarf5.zlib │ 497.8MB │ 5 │ GNU C11 16.1.1 -gdwarf-5 -gz=zlib │ 261.2MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.dwarf5.zstd │ 454.7MB │ 5 │ GNU C11 16.1.1 -gdwarf-5 -gz=zstd │ 218.1MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ │ vmlinux.toolchain_default │ 736.3MB │ 5 │ GNU C11 16.1.1 │ 499.7MB │ 7.3MB │ 86e1b611 │ 7.6MB │ 52123c24 │ 7.4MB │ └───────────────────────────┴─────────┴─────┴───────────────────────────────────┴─────────┴───────┴──────────┴────────┴──────────┴─────────┘Split DWARF support (skeleton CUs) will be supported in upcoming work, so as to cover all the possibilities the kernel build system offers for generating DWARF.
- Arnaldo
Arnaldo Carvalho de Melo (12):
dwarf_loader: Initial support forDW_TAG_variant_part
dwarf_loader: Initial support forDW_TAG_subprograminDW_TAG_enumeration
dwarf_loader: PopulateDW_TAG_variantchildren inDW_TAG_variant_part
btf_encoder: Encode variant parts as union members in BTF
dwarf_loader: HandleDW_FORM_blockinattr_numericfor Rust discriminant values
dwarf_loader: Allow forcing the merge of CUs for solving inter CU tag references
dwarf_loader: SupportDW_TAG_imported_unitfor same-file partial units
dwarf_loader: Fixcus__merging_cufailing to detectDW_FORM_ref_addr
dwarf_loader: Add cu parameter totag__set_spec()anddwarf_tag__set_attr_type()
dwarf_loader: SupportDW_FORM_GNU_ref_altreferences to dwz alternate debug files
tests: Add inter-CU type reference comparison test
scripts: Addvmlinux_comparison.pyfor DWARF/BTF analysisbtf_encoder.c | 66 ++- ctf_encoder.c | 34 +- dwarf_loader.c | 873 ++++++++++++++++++++++++++++++---- dwarves.c | 77 ++- dwarves.h | 63 ++- dwarves_emit.c | 10 +- dwarves_fprintf.c | 54 ++- man-pages/pahole.1 | 18 +- pahole.c | 20 +- scripts/vmlinux_comparison.py | 367 ++++++++++++++ tests/block_endian.sh | 146 ++++++ tests/dwz_alt_file.sh | 204 ++++++++ tests/inter_cu_refs.sh | 50 ++ tests/prettify_perf.data.sh | 4 +- 14 files changed, 1854 insertions(+), 132 deletions(-) create mode 100755 scripts/vmlinux_comparison.py create mode 100755 tests/block_endian.sh create mode 100755 tests/dwz_alt_file.sh create mode 100755 tests/inter_cu_refs.sh
Quoted 4 lines · Arnaldo Carvalho de Melo
Adding Miguel to the CC list, Miguel we're trying to improve BTF support for Rust, this series handles multiple enabling fixes/improvements that gets us to the next level, i.e. we can load everything from DWARF, now
Thanks for the Cc! Cc'ing rust-for-linux and Gary.
Quoted 2 lines
its time to try to map it to existing BTF kinds and propose BTF extensions when we can't use existing encodings.
Sounds cool :)
Quoted 4 lines
Inferring from "does any member have a niche layout" means reverse-engineering rustc's layout algorithm, which is explicitly unstable and unspecified. It'd break silently on a compiler bump, with no way to tell from the DWARF that you got it wrong.
Yeah, the LLM is correct here: the Rust compiler gives very few guarantees for the default repr, i.e. in common cases it has the freedom to use whatever layout it wants (i.e. even for essentially equivalent types in the same compilation unit) -- the official docs are at:
https://doc.rust-lang.org/reference/type-layout.html
Quoted 1 line
u8
__discriminant; /* 0 1 */
For the niche cases like Option<NonZero<u32>>, what would be printed?
Cheers,
Miguel
Quoted 24 lines · Miguel Ojeda
Quoted 4 lines · Arnaldo Carvalho de Melo
Adding Miguel to the CC list, Miguel we're trying to improve BTF support for Rust, this series handles multiple enabling fixes/improvements that gets us to the next level, i.e. we can load everything from DWARF, now
Thanks for the Cc! Cc'ing rust-for-linux and Gary.
Quoted 2 lines
its time to try to map it to existing BTF kinds and propose BTF extensions when we can't use existing encodings.
Sounds cool :)
Quoted 4 lines
Inferring from "does any member have a niche layout" means reverse-engineering rustc's layout algorithm, which is explicitly unstable and unspecified. It'd break silently on a compiler bump, with no way to tell from the DWARF that you got it wrong.
Yeah, the LLM is correct here: the Rust compiler gives very few guarantees for the default
repr, i.e. in common cases it has the freedom to use whatever layout it wants (i.e. even for essentially equivalent types in the same compilation unit) -- the official docs are at:
Quoted 5 lines
https://doc.rust-lang.org/reference/type-layout.html
Quoted 1 line
u8
__discriminant; /* 0 1 */For the niche cases like
Option<NonZero<u32>>, what would be printed?
Can you think about one such niche case that is present in the kernel rust .o files right now? I tried finding the Option<NonZero<u32>> to look at its DWARF but couldn't find one.
- Arnaldo
Gary Guo
reviewerQuoted 27 lines · Arnaldo Carvalho de Melo
Quoted 26 lines · Miguel Ojeda
Quoted 4 lines · Arnaldo Carvalho de Melo
Adding Miguel to the CC list, Miguel we're trying to improve BTF support for Rust, this series handles multiple enabling fixes/improvements that gets us to the next level, i.e. we can load everything from DWARF, now
Thanks for the Cc! Cc'ing rust-for-linux and Gary.
Quoted 2 lines
its time to try to map it to existing BTF kinds and propose BTF extensions when we can't use existing encodings.
Sounds cool :)
Quoted 4 lines
Inferring from "does any member have a niche layout" means reverse-engineering rustc's layout algorithm, which is explicitly unstable and unspecified. It'd break silently on a compiler bump, with no way to tell from the DWARF that you got it wrong.
Yeah, the LLM is correct here: the Rust compiler gives very few guarantees for the default
repr, i.e. in common cases it has the freedom to use whatever layout it wants (i.e. even for essentially equivalent types in the same compilation unit) -- the official docs are at:
Quoted 7 lines
Quoted 3 lines
Quoted 1 line
u8
__discriminant; /* 0 1 */For the niche cases like
Option<NonZero<u32>>, what would be printed?Can you think about one such niche case that is present in the kernel rust .o files right now? I tried finding the
Option<NonZero<u32>>to look at its DWARF but couldn't find one.
For direct use of Option<NonZero<..>> we only have sriov_get_totalvfs which is Option<NonZero<u16>>.
However, we have many case of Result<(), Error> where Error is NonZeroI32, so Ok(()) is mapped to 0.
Best,
Gary
Quoted 26 lines · Arnaldo Carvalho de Melo
Quoted 24 lines · Miguel Ojeda
Quoted 3 lines · Arnaldo Carvalho de Melo
Adding Miguel to the CC list, Miguel we're trying to improve BTF support for Rust, this series handles multiple enabling fixes/improvements that gets us to the next level, i.e. we can load everything from DWARF, now
Thanks for the Cc! Cc'ing rust-for-linux and Gary.
Quoted 2 lines
its time to try to map it to existing BTF kinds and propose BTF extensions when we can't use existing encodings.
Sounds cool :)
Quoted 4 lines
Inferring from "does any member have a niche layout" means reverse-engineering rustc's layout algorithm, which is explicitly unstable and unspecified. It'd break silently on a compiler bump, with no way to tell from the DWARF that you got it wrong.
Yeah, the LLM is correct here: the Rust compiler gives very few guarantees for the default
repr, i.e. in common cases it has the freedom to use whatever layout it wants (i.e. even for essentially equivalent types in the same compilation unit) -- the official docs are at:
Quoted 7 lines
Quoted 3 lines
Quoted 1 line
u8
__discriminant; /* 0 1 */For the niche cases like
Option<NonZero<u32>>, what would be printed?Can you think about one such niche case that is present in the kernel rust .o files right now? I tried finding the
Option<NonZero<u32>>to look at its DWARF but couldn't find one.
Good, so I went ahead and built the exact case, together with the explicit Option<u32> one, so we can compare them. The source, containing the struct I dump below:
use std::num::NonZeroU32;
#[no_mangle]
pub struct Container {
pub a: Option<NonZeroU32>, // niche: 4 bytes, tag == payload
pub b: Option<u32>, // explicit: tag at 0, payload at 4
pub c: Option<i32>,
}
#[no_mangle]
pub fn consume(c: Container) -> u32 {
c.a.map(|x| x.get()).unwrap_or(0) + c.b.unwrap_or(0)
}
fn main() {
let c = Container { a: None, b: Some(3), c: Some(-1) };
let _ = consume(c);
}Compile (rustc 1.93.x here, don't link, just get an object file, otherwise you'll debug 1M+ lines of std DWARF and the type will be there but buried):
acme@number:~/git/pahole$ rustc --edition 2021 --emit=obj -C debuginfo=2 \ option_non_zero.rs -o option_non_zero.o
then dump the DWARF, note that the DW_AT_name has the expanded generic, i.e. 'Option<core::num::nonzero::NonZero<u32>>', the NonZeroU32 alias seems to be expanded at compile time and, thus, doesn't appear in DWARF:
acme@number:~/git/pahole$ readelf --debug-dump=info option_non_zero.o \
| grep -n 'nonzero::NonZero<u32>'
acme@number:~$ readelf --debug-dump=info option_non_zero.o | grep -n 'nonzero::NonZero<u32>'
295: <2ca> DW_AT_name : (indirect string, offset: 0x213): Option<core::num::nonzero::NonZero<u32>>
348: <32e> DW_AT_name : (indirect string, offset: 0x2ef): map<core::num::nonzero::NonZero<u32>, u32, option_non_zero::consume::{closure_env#0}>
acme@number:~$and you can see the niche case layout, size 4, the discriminant member is the payload itself, same offset, same size, and the Some variant doesn't even get a DW_AT_discr_value, it is just the default, so the
answer: nothing separate to print, the tag IS the payload.
Here is the full DIE for the niche case:
acme@number:~$ readelf --debug-dump=info option_non_zero.o | grep -B1 -A25 'Option<core::num::nonzero::NonZero<u32>>'
<3><2c9>: Abbrev Number: 19 (DW_TAG_structure_type)
<2ca> DW_AT_name : (indirect string, offset: 0x213): Option<core::num::nonzero::NonZero<u32>>
<2ce> DW_AT_byte_size : 4
<2cf> DW_AT_accessibility: 1 (public)
<2d0> DW_AT_alignment : 4
<4><2d1>: Abbrev Number: 26 (DW_TAG_variant_part)
<2d2> DW_AT_discr : <0x2d6>
<5><2d6>: Abbrev Number: 27 (DW_TAG_member)
<2d7> DW_AT_type : <0x5b2>
<2db> DW_AT_alignment : 4
<2dc> DW_AT_data_member_location: 0
<2dd> DW_AT_artificial : 1
<5><2dd>: Abbrev Number: 28 (DW_TAG_variant)
<2de> DW_AT_discr_value : 0
<6><2df>: Abbrev Number: 4 (DW_TAG_member)
<2e0> DW_AT_name : (indirect string, offset: 0x1ce): None
<2e4> DW_AT_type : <0x2f9>
<2e8> DW_AT_alignment : 4
<2e9> DW_AT_data_member_location: 0
<6><2ea>: Abbrev Number: 0
<5><2eb>: Abbrev Number: 29 (DW_TAG_variant)
<6><2ec>: Abbrev Number: 4 (DW_TAG_member)
<2ed> DW_AT_name : (indirect string, offset: 0x20e): Some
<2f1> DW_AT_type : <0x30b>
<2f5> DW_AT_alignment : 4
<2f6> DW_AT_data_member_location: 0
<6><2f7>: Abbrev Number: 0
acme@number:~$On the explicit Option<u32> case the picture is different, the tag is a real member at offset 0 with 4 bytes and Some.__0 moved to offset 4:
acme@number:~$ readelf --debug-dump=info option_non_zero.o | grep -B1 -A25 'Option<u32>'
<3><360>: Abbrev Number: 19 (DW_TAG_structure_type)
<361> DW_AT_name : (indirect string, offset: 0x345): Option<u32>
<365> DW_AT_byte_size : 8
<366> DW_AT_accessibility: 1 (public)
<367> DW_AT_alignment : 4
<4><368>: Abbrev Number: 26 (DW_TAG_variant_part)
<369> DW_AT_discr : <0x36d>
<5><36d>: Abbrev Number: 27 (DW_TAG_member)
<36e> DW_AT_type : <0x5b2>
<372> DW_AT_alignment : 4
<373> DW_AT_data_member_location: 0
<374> DW_AT_artificial : 1
<5><374>: Abbrev Number: 28 (DW_TAG_variant)
<375> DW_AT_discr_value : 0
<6><376>: Abbrev Number: 4 (DW_TAG_member)
<377> DW_AT_name : (indirect string, offset: 0x1ce): None
<37b> DW_AT_type : <0x391>
<37f> DW_AT_alignment : 4
<380> DW_AT_data_member_location: 0
<6><381>: Abbrev Number: 0
<5><382>: Abbrev Number: 28 (DW_TAG_variant)
<383> DW_AT_discr_value : 1
<6><384>: Abbrev Number: 4 (DW_TAG_member)
<385> DW_AT_name : (indirect string, offset: 0x20e): Some
<389> DW_AT_type : <0x3a3>
<38d> DW_AT_alignment : 4
<38e> DW_AT_data_member_location: 0
acme@number:~$So this is the one where we want a synthetic __discriminant member.
And what we do today for the niche one, with current pahole (built from this series):
acme@number:~$ pahole -C 'Option<core::num::nonzero::NonZero<u32>>' option_non_zero.o
struct Option<core::num::nonzero::NonZero<u32>> {
struct None { /* size: 4, cachelines: 1, members: 0 */
/* padding: 4 */
/* last cacheline: 4 bytes */
} __attribute__((__aligned__(4)));
struct Some {
public:
struct NonZero<u32> __0 __attribute__((__aligned__(4))); /* 0 4 */
/* size: 4, cachelines: 1, members: 1 */
/* forced alignments: 1 */
/* last cacheline: 4 bytes */
} __attribute__((__aligned__(4)));
struct Option<u32> map<core::num::nonzero::NonZero<u32>, u32, option_non_zero::consume::{closure_env#0}>(struct Option<core::num::nonzero::NonZero<u32>>, struct {closure_env#0});
/* size: 4, cachelines: 1, members: 0 */
/* padding: 4 */
/* last cacheline: 4 bytes */
} __attribute__((__aligned__(4)));acme@number:~$
and on the BTF side, also with this series:
acme@number:~$ pahole --btf_encode option_non_zero.o
acme@number:~$ pahole -F btf -C 'Option<core::num::nonzero::NonZero<u32>>' option_non_zero.o
union Option<core::num::nonzero::NonZero<u32>> {
struct None None; /* 0 4 */
struct Some Some; /* 0 4 */
};acme@number:~$ pahole --expand_types -F btf -C 'Option<core::num::nonzero::NonZero<u32>>' option_non_zero.o
union Option<core::num::nonzero::NonZero<u32>> {
struct None {
} __attribute__((__aligned__(8))) None; /* 0 4 */
struct Some {
struct NonZero<u32> {
struct NonZeroU32Inner {
u32 __0; /* 0 4 */
} __0; /* 0 4 */
} __0; /* 0 4 */
} Some; /* 0 4 */
};acme@number:~$
matches the real in-memory layout, size 4, no extra member.
So for the future __discriminant work the rule should be: only emit it when its location doesn't overlap with the payload, i.e. on the explicit form; on the niche that field is the data itself, adding one would mean two members covering the same bytes, and we'd be lying about the layout.
I'll add a test with both forms, pinning this behavior, so we don't regress it, and then, when we improve support for the synthetic discriminants, we can update it.
And yes, I used OpenCode + DeepSeek to iterate multiple times and manually checked everything before hitting send, it helps me a lot and I hope that if I missed something, you will correct me so that we can make progress.
Regards,
- Arnaldo