Skip to contentSkip to conversation

Implement MODVERSIONS for Rust

PATCH Superseded Sami Tolvanen 6 participants 37 messages Jun 17, 2024 – Aug 1, 2024

Subsystems (4)

v1 of 8 Superseded Latest is v8 →

lore
Share & tools
lore

Sami Tolvanen

author maintainer
#0 lore raw

cover Implement MODVERSIONS for Rust

Hi folks,

This series implements CONFIG_MODVERSIONS for Rust, an important feature for distributions like Android that want to ship Rust kernel modules, and depend on modversions to help ensure module ABI compatibility.

There have been earlier proposals [1][2] that would allow Rust modules to coexist with modversions, but none that actually implement symbol versioning. Unlike C, Rust source code doesn't have sufficient information about the final ABI, as the compiler has considerable freedom in adjusting structure layout for improved performance [3], for example, which makes using a source code parser like genksyms a non-starter. Based on Matt's suggestion and previous feedback from maintainers, this series uses DWARF debugging information for computing versions. DWARF is an established and relatively stable format, which includes all the necessary ABI details, and adding a CONFIG_DEBUG_INFO dependency for Rust symbol versioning seems like a reasonable trade-off.

The first 12 patches of this series add a small tool for computing symbol versions from DWARF, called gendwarfksyms. When passed a list of exported symbols, the tool generates an expanded type string for each symbol, and computes symbol CRCs similarly to genksyms. gendwarfksyms is written in C and uses libdw to process DWARF, mainly because of the existing support for C host tools that use elfutils (e.g., objtool).

Another compatibility issue is fitting the extremely long mangled Rust symbol names into struct modversion_info, which can only hold 55-character names (on 64-bit systems). Previous proposals suggested changing the structure to support longer names, but the conclusion was that we cannot break userspace tools that parse the version table.

The next two patches of the series implement support for hashed symbol names in struct modversion_info, where names longer than 55 characters are hashed, and the hash is stored in the name field. To avoid breaking userspace tools, the binary hash is prefixed with a null-terminated string containing the name of the hash function. While userspace tools can later be updated to potentially produce more useful information about the long symbols, this allows them to continue working in the meantime.

The final patch allows CONFIG_MODVERSIONS to be selected with Rust, provided that debugging information is also available.

[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://lore.kernel.org/rust-for-linux/[email protected]/
[3] https://lore.kernel.org/rust-for-linux/CAGSQo005hRiUZdeppCifDqG9zFDJRwahpBLE4x7-MyfJscn7tQ@mail.gmail.com/

Sami

Sami Tolvanen (15):
tools: Add gendwarfksyms
gendwarfksyms: Add symbol list input handling
gendwarfksyms: Add CRC calculation
gendwarfksyms: Expand base_type
gendwarfksyms: Add a cache
gendwarfksyms: Expand type modifiers and typedefs
gendwarfksyms: Add pretty-printing
gendwarfksyms: Expand subroutine_type
gendwarfksyms: Expand array_type
gendwarfksyms: Expand structure types
gendwarfksyms: Limit structure expansion
gendwarfksyms: Add inline debugging
modpost: Add support for hashing long symbol names
module: Support hashed symbol names when checking modversions
kbuild: Use gendwarfksyms to generate Rust symbol versions

 Makefile                            |   6 +
 init/Kconfig                        |   2 +-
 kernel/module/version.c             |  38 +-
 rust/Makefile                       |  30 +-
 scripts/mod/Makefile                |   4 +-
 scripts/mod/modpost.c               |  20 +-
 scripts/mod/modpost.h               |  20 +
 scripts/mod/symhash.c               | 327 +++++++++++++
 tools/Makefile                      |  11 +-
 tools/gendwarfksyms/Build           |   5 +
 tools/gendwarfksyms/Makefile        |  49 ++
 tools/gendwarfksyms/cache.c         | 209 +++++++++
 tools/gendwarfksyms/crc32.c         |  69 +++
 tools/gendwarfksyms/crc32.h         |  34 ++
 tools/gendwarfksyms/gendwarfksyms.c | 141 ++++++
 tools/gendwarfksyms/gendwarfksyms.h | 173 +++++++
 tools/gendwarfksyms/symbols.c       | 193 ++++++++
 tools/gendwarfksyms/types.c         | 697 ++++++++++++++++++++++++++++
 18 files changed, 2008 insertions(+), 20 deletions(-)
 create mode 100644 scripts/mod/symhash.c
 create mode 100644 tools/gendwarfksyms/Build
 create mode 100644 tools/gendwarfksyms/Makefile
 create mode 100644 tools/gendwarfksyms/cache.c
 create mode 100644 tools/gendwarfksyms/crc32.c
 create mode 100644 tools/gendwarfksyms/crc32.h
 create mode 100644 tools/gendwarfksyms/gendwarfksyms.c
 create mode 100644 tools/gendwarfksyms/gendwarfksyms.h
 create mode 100644 tools/gendwarfksyms/symbols.c
 create mode 100644 tools/gendwarfksyms/types.c

base-commit: 6ba59ff4227927d3a8530fc2973b80e94b54d58f

Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#1 lore raw

PATCH 1/15 tools: Add gendwarfksyms

Add a basic DWARF parser, which uses libdw to traverse the debugging information in an object file and looks for functions and variables. In follow-up patches, this will be expanded to produce symbol versions for CONFIG_MODVERSIONS from DWARF. This tool is needed mainly for Rust kernel module compatibility.

---
 tools/Makefile                      |  11 +--
 tools/gendwarfksyms/Build           |   2 +
 tools/gendwarfksyms/Makefile        |  49 +++++++++++
 tools/gendwarfksyms/gendwarfksyms.c | 128 ++++++++++++++++++++++++++++
 tools/gendwarfksyms/gendwarfksyms.h |  71 +++++++++++++++
 tools/gendwarfksyms/types.c         |  87 +++++++++++++++++++
 6 files changed, 343 insertions(+), 5 deletions(-)
 create mode 100644 tools/gendwarfksyms/Build
 create mode 100644 tools/gendwarfksyms/Makefile
 create mode 100644 tools/gendwarfksyms/gendwarfksyms.c
 create mode 100644 tools/gendwarfksyms/gendwarfksyms.h
 create mode 100644 tools/gendwarfksyms/types.c
tools/Makefile +6 -5
index 276f5d0d53a4..60806ff753b7 100644
@@ -17,6 +17,7 @@ help:
 	@echo '  firewire               - the userspace part of nosy, an IEEE-1394 traffic sniffer'
 	@echo '  firmware               - Firmware tools'
 	@echo '  freefall               - laptop accelerometer program for disk protection'
+	@echo '  gendwarfksyms          - generates symbol versions from DWARF'
 	@echo '  gpio                   - GPIO tools'
 	@echo '  hv                     - tools used when in Hyper-V clients'
 	@echo '  iio                    - IIO tools'
@@ -68,7 +69,7 @@ acpi: FORCE
 cpupower: FORCE
 	$(call descend,power/$@)
 
-counter firewire hv guest bootconfig spi usb virtio mm bpf iio gpio objtool leds wmi pci firmware debugging tracing: FORCE
+counter firewire hv guest bootconfig spi usb virtio mm bpf iio gendwarfksyms gpio objtool leds wmi pci firmware debugging tracing: FORCE
 	$(call descend,$@)
 
 bpf/%: FORCE
@@ -154,8 +155,8 @@ freefall_install:
 kvm_stat_install:
 	$(call descend,kvm/$(@:_install=),install)
 
-install: acpi_install counter_install cpupower_install gpio_install \
-		hv_install firewire_install iio_install \
+install: acpi_install counter_install cpupower_install gendwarfksyms_install \
+		gpio_install hv_install firewire_install iio_install \
 		perf_install selftests_install turbostat_install usb_install \
 		virtio_install mm_install bpf_install x86_energy_perf_policy_install \
 		tmon_install freefall_install objtool_install kvm_stat_install \
@@ -168,7 +169,7 @@ acpi_clean:
 cpupower_clean:
 	$(call descend,power/cpupower,clean)
 
-counter_clean hv_clean firewire_clean bootconfig_clean spi_clean usb_clean virtio_clean mm_clean wmi_clean bpf_clean iio_clean gpio_clean objtool_clean leds_clean pci_clean firmware_clean debugging_clean tracing_clean:
+counter_clean hv_clean firewire_clean bootconfig_clean spi_clean usb_clean virtio_clean mm_clean wmi_clean bpf_clean iio_clean gendwarfksyms_clean gpio_clean objtool_clean leds_clean pci_clean firmware_clean debugging_clean tracing_clean:
 	$(call descend,$(@:_clean=),clean)
 
 libapi_clean:
@@ -211,7 +212,7 @@ build_clean:
 clean: acpi_clean counter_clean cpupower_clean hv_clean firewire_clean \
 		perf_clean selftests_clean turbostat_clean bootconfig_clean spi_clean usb_clean virtio_clean \
 		mm_clean bpf_clean iio_clean x86_energy_perf_policy_clean tmon_clean \
-		freefall_clean build_clean libbpf_clean libsubcmd_clean \
+		freefall_clean build_clean libbpf_clean libsubcmd_clean gendwarfksyms_clean \
 		gpio_clean objtool_clean leds_clean wmi_clean pci_clean firmware_clean debugging_clean \
 		intel-speed-select_clean tracing_clean thermal_clean thermometer_clean thermal-engine_clean
 
tools/gendwarfksyms/Build new file +2 -0
new file mode 100644
index 000000000000..805591b6df80
@@ -0,0 +1,2 @@
+gendwarfksyms-y += gendwarfksyms.o
+gendwarfksyms-y += types.o
tools/gendwarfksyms/Makefile new file +49 -0

49 lines not on this page · raw message

tools/gendwarfksyms/gendwarfksyms.c new file +128 -0

128 lines not on this page · raw message

tools/gendwarfksyms/gendwarfksyms.h new file +71 -0

71 lines not on this page · raw message

tools/gendwarfksyms/types.c new file +87 -0

87 lines not on this page · raw message

Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#2 lore raw

PATCH 2/15 gendwarfksyms: Add symbol list input handling

In reply to Sami Tolvanen

Support passing a list of exported symbols to gendwarfksyms via stdin and filter non-exported symbols from the output.

The symbol list input has the format 'symbol-address symbol-name' to allow the parser to discover exported symbols also by address. This is necessary for aliased symbols, where only one name appears in the debugging information.

---
 tools/gendwarfksyms/Build           |   1 +
 tools/gendwarfksyms/gendwarfksyms.c |   2 +
 tools/gendwarfksyms/gendwarfksyms.h |  17 ++++
 tools/gendwarfksyms/symbols.c       | 130 ++++++++++++++++++++++++++++
 tools/gendwarfksyms/types.c         |  70 ++++++++++++++-
 5 files changed, 219 insertions(+), 1 deletion(-)
 create mode 100644 tools/gendwarfksyms/symbols.c
tools/gendwarfksyms/Build +1 -0
index 805591b6df80..a83c59bfef8b 100644
@@ -1,2 +1,3 @@
 gendwarfksyms-y += gendwarfksyms.o
+gendwarfksyms-y += symbols.o
 gendwarfksyms-y += types.o
tools/gendwarfksyms/gendwarfksyms.c +2 -0
index 4a2dea307849..4a1bd9239182 100644
@@ -96,6 +96,8 @@ int main(int argc, const char **argv)
 	if (parse_options(argc, argv, &filename) < 0)
 		return usage();
 
+	check(symbol_read_list(stdin));
+
 	fd = open(filename, O_RDONLY);
 	if (fd == -1) {
 		error("open failed for '%s': %s", filename, strerror(errno));
tools/gendwarfksyms/gendwarfksyms.h +17 -0
index 44e94f1d9671..b77855cc94a7 100644
@@ -49,6 +49,21 @@ extern bool debug;
 		__res;                                          \
 	})
 
+/*
+ * symbols.c
+ */
+
+/* Exported symbol -- matching either the name or the address */
+struct symbol {
+	const char *name;
+	uintptr_t addr;
+	struct hlist_node addr_hash;
+	struct hlist_node name_hash;
+};
+
+extern int symbol_read_list(FILE *file);
+extern struct symbol *symbol_get(uintptr_t addr, const char *name);
+
 /*
  * types.c
  */
@@ -56,6 +71,8 @@ extern bool debug;
 struct state {
 	Dwfl_Module *mod;
 	Dwarf *dbg;
+	struct symbol *sym;
+	Dwarf_Die origin;
 };
 
 typedef int (*die_callback_t)(struct state *state, Dwarf_Die *die);
tools/gendwarfksyms/symbols.c new file +130 -0

130 lines not on this page · raw message

tools/gendwarfksyms/types.c +69 -1

88 lines not on this page · raw message

Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#3 lore raw

PATCH 3/15 gendwarfksyms: Add CRC calculation

In reply to Sami Tolvanen

Add a basic CRC32 implementation adapted from genksyms, and produce matching output from type strings.

Example usage:

  $ nm -p --defined-only rust/alloc.o | \
      awk '/ (T|R|D) / {printf "%s %s\n",$1, $3}' | \
      tools/gendwarfksyms/gendwarfksyms rust/alloc.o

Output:

#SYMVER _RNvNvMs_NtCscg2doA4GLaz_5alloc3vecINtB6_3VecppE11swap_remove13assert_failed 0x985f94dd
#SYMVER _RNvXs1_NtCscg2doA4GLaz_5alloc11collectionsNtB5_15TryReserveErrorNtNtCs5QSdWC790r4_4core3fmt7Display3fmt 0x985f94dd #SYMVER _RNvNvMs_NtCscg2doA4GLaz_5alloc3vecINtB6_3VecppE6remove13assert_failed 0x985f94dd
...

Note that type strings are not yet expanded, so the CRCs can only distinguish between functions and variables for now.

---
 tools/gendwarfksyms/Build           |  1 +
 tools/gendwarfksyms/crc32.c         | 69 ++++++++++++++++++++++++++++
 tools/gendwarfksyms/crc32.h         | 34 ++++++++++++++
 tools/gendwarfksyms/gendwarfksyms.c |  1 +
 tools/gendwarfksyms/gendwarfksyms.h |  6 +++
 tools/gendwarfksyms/symbols.c       | 71 +++++++++++++++++++++++++++--
 tools/gendwarfksyms/types.c         | 19 ++++++--
 7 files changed, 194 insertions(+), 7 deletions(-)
 create mode 100644 tools/gendwarfksyms/crc32.c
 create mode 100644 tools/gendwarfksyms/crc32.h
tools/gendwarfksyms/Build +1 -0
index a83c59bfef8b..518642c9b9de 100644
@@ -1,3 +1,4 @@
 gendwarfksyms-y += gendwarfksyms.o
+gendwarfksyms-y += crc32.o
 gendwarfksyms-y += symbols.o
 gendwarfksyms-y += types.o
tools/gendwarfksyms/crc32.c new file +69 -0

69 lines not on this page · raw message

tools/gendwarfksyms/crc32.h new file +34 -0
new file mode 100644
index 000000000000..89e4454b2a70
@@ -0,0 +1,34 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Based on scripts/genksyms/genksyms.c, which has the following
+ * notice:
+ *
+ * Generate kernel symbol version hashes.
+ * Copyright 1996, 1997 Linux International.
+ *
+ * New implementation contributed by Richard Henderson <[email protected]>
+ * Based on original work by Bjorn Ekwall <[email protected]>
+ *
+ * This file was part of the Linux modutils 2.4.22: moved back into the
+ * kernel sources by Rusty Russell/Kai Germaschewski.
+ */
+
+#ifndef __CRC32_H
+#define __CRC32_H
+
+extern const unsigned int crctab32[];
+
+static inline unsigned long partial_crc32_one(unsigned char c,
+					      unsigned long crc)
+{
+	return crctab32[(crc ^ c) & 0xff] ^ (crc >> 8);
+}
+
+static inline unsigned long partial_crc32(const char *s, unsigned long crc)
+{
+	while (*s)
+		crc = partial_crc32_one(*s++, crc);
+	return crc;
+}
+
+#endif /* __CRC32_H */
tools/gendwarfksyms/gendwarfksyms.c +1 -0
index 4a1bd9239182..7938b7440674 100644
@@ -125,6 +125,7 @@ int main(int argc, const char **argv)
 	}
 
 	dwfl_end(dwfl);
+	symbol_print_versions();
 
 	return 0;
 }
tools/gendwarfksyms/gendwarfksyms.h +6 -0
index b77855cc94a7..7440f1c73500 100644
@@ -52,17 +52,22 @@ extern bool debug;
 /*
  * symbols.c
  */
+enum symbol_state { UNPROCESSED, PROCESSED_ADDR, PROCESSED_NAME };
 
 /* Exported symbol -- matching either the name or the address */
 struct symbol {
 	const char *name;
 	uintptr_t addr;
+	enum symbol_state state;
+	unsigned long crc;
 	struct hlist_node addr_hash;
 	struct hlist_node name_hash;
 };
 
+extern int symbol_set_crc(struct symbol *sym, unsigned long crc);
 extern int symbol_read_list(FILE *file);
 extern struct symbol *symbol_get(uintptr_t addr, const char *name);
+extern void symbol_print_versions(void);
 
 /*
  * types.c
@@ -73,6 +78,7 @@ struct state {
 	Dwarf *dbg;
 	struct symbol *sym;
 	Dwarf_Die origin;
+	unsigned long crc;
 };
 
 typedef int (*die_callback_t)(struct state *state, Dwarf_Die *die);
tools/gendwarfksyms/symbols.c +67 -4

110 lines not on this page · raw message

tools/gendwarfksyms/types.c +16 -3
index f1ce7bfcf510..47ae967d42ee 100644
@@ -4,6 +4,7 @@
  */
 
 #include "gendwarfksyms.h"
+#include "crc32.h"
 
 #define DEFINE_GET_ATTR(attr, type)                                    \
 	static bool get_##attr##_attr(Dwarf_Die *die, unsigned int id, \
@@ -68,7 +69,7 @@ static Dwarf_Die *get_exported(struct state *state, Dwarf_Die *die)
 }
 
 /*
- * Type string processing
+ * Type string and CRC processing
  */
 static int process(struct state *state, const char *s)
 {
@@ -77,6 +78,7 @@ static int process(struct state *state, const char *s)
 	if (debug)
 		fputs(s, stderr);
 
+	state->crc = partial_crc32(s, state->crc);
 	return 0;
 }
 
@@ -101,6 +103,11 @@ int process_die_container(struct state *state, Dwarf_Die *die,
 	return 0;
 }
 
+static void state_init(struct state *state)
+{
+	state->crc = 0xffffffff;
+}
+
 /*
  * Exported symbol processing
  */
@@ -130,17 +137,23 @@ static int process_exported_symbols(struct state *state, Dwarf_Die *die)
 	case DW_TAG_subprogram:
 	case DW_TAG_variable:
 		die = get_exported(state, die);
-		if (!die || !state->sym)
+		if (!die || !state->sym || state->sym->state != UNPROCESSED)
 			return 0;
 
+		/*
+		 * For each exported symbol, compute a CRC of the expanded type
+		 * description.
+		 */
 		debug("%s (@ %lx)", state->sym->name, state->sym->addr);
+		state_init(state);
 
 		if (tag == DW_TAG_subprogram)
 			check(process_subprogram(state, die));
 		else
 			check(process_variable(state, die));
 
-		return 0;
+		return check(
+			symbol_set_crc(state->sym, state->crc ^ 0xffffffff));
 	default:
 		return 0;
 	}
Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#4 lore raw

PATCH 4/15 gendwarfksyms: Expand base_type

In reply to Sami Tolvanen

Add support for expanding basic DWARF attributes and DW_TAG_base_type types.

Example usage:

  $ nm -p --defined-only vmlinux.o | \
      awk '/ (T|R|D) / {printf "%s %s\n",$1, $3}' | \
      grep loops_per_jiffy | \
      ./tools/gendwarfksyms/gendwarfksyms --debug vmlinux.o

Output:

  gendwarfksyms: symbol_read_list: adding { 4b0, "loops_per_jiffy" }
  gendwarfksyms: process_modules: vmlinux.o
  gendwarfksyms: process_exported_symbols: loops_per_jiffy (@ 4b0)
  variable base_type unsigned long byte_size(8);
  #SYMVER loops_per_jiffy 0xc694aefc
---
 tools/gendwarfksyms/types.c | 109 +++++++++++++++++++++++++++++++++++-
 1 file changed, 108 insertions(+), 1 deletion(-)
tools/gendwarfksyms/types.c +108 -1
index 47ae967d42ee..7508d0fb8b80 100644
@@ -16,6 +16,7 @@
 	}
 
 DEFINE_GET_ATTR(addr, Dwarf_Addr)
+DEFINE_GET_ATTR(udata, Dwarf_Word)
 
 static bool get_ref_die_attr(Dwarf_Die *die, unsigned int id, Dwarf_Die *value)
 {
@@ -82,6 +83,73 @@ static int process(struct state *state, const char *s)
 	return 0;
 }
 
+#define MAX_FMT_BUFFER_SIZE 128
+
+static int process_fmt(struct state *state, const char *fmt, ...)
+{
+	char buf[MAX_FMT_BUFFER_SIZE];
+	va_list args;
+	int res;
+
+	va_start(args, fmt);
+
+	res = check(vsnprintf(buf, sizeof(buf), fmt, args));
+	if (res >= MAX_FMT_BUFFER_SIZE - 1) {
+		error("vsnprintf overflow: increase MAX_FMT_BUFFER_SIZE");
+		res = -1;
+	} else {
+		check(process(state, buf));
+	}
+
+	va_end(args);
+	return res;
+}
+
+/* Process a fully qualified name from DWARF scopes */
+static int process_fqn(struct state *state, Dwarf_Die *die)
+{
+	Dwarf_Die *scopes = NULL;
+	const char *name;
+	int res;
+	int i;
+
+	res = check(dwarf_getscopes_die(die, &scopes));
+	if (!res) {
+		name = get_name(die);
+		name = name ?: "<unnamed>";
+		return check(process(state, name));
+	}
+
+	for (i = res - 1; i >= 0; i--) {
+		if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
+			continue;
+
+		name = get_name(&scopes[i]);
+		name = name ?: "<unnamed>";
+		check(process(state, name));
+		if (i > 0)
+			check(process(state, "::"));
+	}
+
+	free(scopes);
+	return 0;
+}
+
+#define DEFINE_PROCESS_UDATA_ATTRIBUTE(attribute)                         \
+	static int process_##attribute##_attr(struct state *state,        \
+					      Dwarf_Die *die)             \
+	{                                                                 \
+		Dwarf_Word value;                                         \
+		if (get_udata_attr(die, DW_AT_##attribute, &value))       \
+			check(process_fmt(state,                          \
+					  " " #attribute "(%" PRIu64 ")", \
+					  value));                        \
+		return 0;                                                 \
+	}
+
+DEFINE_PROCESS_UDATA_ATTRIBUTE(alignment)
+DEFINE_PROCESS_UDATA_ATTRIBUTE(byte_size)
+
 bool match_all(Dwarf_Die *die)
 {
 	return true;
@@ -103,11 +171,48 @@ int process_die_container(struct state *state, Dwarf_Die *die,
 	return 0;
 }
 
+static int process_type(struct state *state, Dwarf_Die *die);
+
+static int process_type_attr(struct state *state, Dwarf_Die *die)
+{
+	Dwarf_Die type;
+
+	if (get_ref_die_attr(die, DW_AT_type, &type))
+		return check(process_type(state, &type));
+
+	/* Compilers can omit DW_AT_type -- print out 'void' to clarify */
+	return check(process(state, "base_type void"));
+}
+
+static int process_base_type(struct state *state, Dwarf_Die *die)
+{
+	check(process(state, "base_type "));
+	check(process_fqn(state, die));
+	check(process_byte_size_attr(state, die));
+	return check(process_alignment_attr(state, die));
+}
+
 static void state_init(struct state *state)
 {
 	state->crc = 0xffffffff;
 }
 
+static int process_type(struct state *state, Dwarf_Die *die)
+{
+	int tag = dwarf_tag(die);
+
+	switch (tag) {
+	case DW_TAG_base_type:
+		check(process_base_type(state, die));
+		break;
+	default:
+		debug("unimplemented type: %x", tag);
+		break;
+	}
+
+	return 0;
+}
+
 /*
  * Exported symbol processing
  */
@@ -118,7 +223,9 @@ static int process_subprogram(struct state *state, Dwarf_Die *die)
 
 static int process_variable(struct state *state, Dwarf_Die *die)
 {
-	return check(process(state, "variable;\n"));
+	check(process(state, "variable "));
+	check(process_type_attr(state, die));
+	return check(process(state, ";\n"));
 }
 
 static int process_exported_symbols(struct state *state, Dwarf_Die *die)
Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#5 lore raw

PATCH 5/15 gendwarfksyms: Add a cache

In reply to Sami Tolvanen

Basic types in DWARF repeat frequently and traversing the DIEs using libdw is relatively slow. Add a simple hashtable based cache for the processed DIEs.

---
 tools/gendwarfksyms/Build           |   1 +
 tools/gendwarfksyms/cache.c         | 147 ++++++++++++++++++++++++++++
 tools/gendwarfksyms/gendwarfksyms.c |   4 +
 tools/gendwarfksyms/gendwarfksyms.h |  37 ++++++-
 tools/gendwarfksyms/types.c         | 140 ++++++++++++++++++--------
 5 files changed, 286 insertions(+), 43 deletions(-)
 create mode 100644 tools/gendwarfksyms/cache.c
tools/gendwarfksyms/Build +1 -0
index 518642c9b9de..220a4aa9b380 100644
@@ -1,4 +1,5 @@
 gendwarfksyms-y += gendwarfksyms.o
+gendwarfksyms-y += cache.o
 gendwarfksyms-y += crc32.o
 gendwarfksyms-y += symbols.o
 gendwarfksyms-y += types.o
tools/gendwarfksyms/cache.c new file +147 -0

147 lines not on this page · raw message

tools/gendwarfksyms/gendwarfksyms.c +4 -0
index 7938b7440674..38ccaeb72426 100644
@@ -15,12 +15,15 @@
 
 /* Print type descriptions and debugging output to stderr */
 bool debug;
+/* Don't use caching */
+bool no_cache;
 
 static const struct {
 	const char *arg;
 	bool *flag;
 } options[] = {
 	{ "--debug", &debug },
+	{ "--no-cache", &no_cache },
 };
 
 static int usage(void)
@@ -126,6 +129,7 @@ int main(int argc, const char **argv)
 
 	dwfl_end(dwfl);
 	symbol_print_versions();
+	cache_free();
 
 	return 0;
 }
tools/gendwarfksyms/gendwarfksyms.h +34 -3
index 7440f1c73500..ea5a9fbda66f 100644
@@ -18,6 +18,7 @@
  * Options -- in gendwarfksyms.c
  */
 extern bool debug;
+extern bool no_cache;
 
 /*
  * Output helpers
@@ -69,6 +70,35 @@ extern int symbol_read_list(FILE *file);
 extern struct symbol *symbol_get(uintptr_t addr, const char *name);
 extern void symbol_print_versions(void);
 
+/*
+ * cache.c
+ */
+enum cached_item_type { EMPTY, STRING, DIE };
+
+struct cached_item {
+	enum cached_item_type type;
+	union {
+		char *str;
+		uintptr_t addr;
+	} data;
+	struct cached_item *next;
+};
+
+enum cached_die_state { INCOMPLETE, COMPLETE };
+
+struct cached_die {
+	enum cached_die_state state;
+	uintptr_t addr;
+	struct cached_item *list;
+	struct hlist_node hash;
+};
+
+extern int cache_get(Dwarf_Die *die, enum cached_die_state state,
+		     struct cached_die **res);
+extern int cache_add_string(struct cached_die *pd, const char *str);
+extern int cache_add_die(struct cached_die *pd, Dwarf_Die *die);
+extern void cache_free(void);
+
 /*
  * types.c
  */
@@ -81,12 +111,13 @@ struct state {
 	unsigned long crc;
 };
 
-typedef int (*die_callback_t)(struct state *state, Dwarf_Die *die);
+typedef int (*die_callback_t)(struct state *state, struct cached_die *cache,
+			      Dwarf_Die *die);
 typedef bool (*die_match_callback_t)(Dwarf_Die *die);
 extern bool match_all(Dwarf_Die *die);
 
-extern int process_die_container(struct state *state, Dwarf_Die *die,
-				 die_callback_t func,
+extern int process_die_container(struct state *state, struct cached_die *cache,
+				 Dwarf_Die *die, die_callback_t func,
 				 die_match_callback_t match);
 
 extern int process_module(Dwfl_Module *mod, Dwarf *dbg, Dwarf_Die *cudie);
tools/gendwarfksyms/types.c +100 -40

254 lines not on this page · raw message

Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#6 lore raw

PATCH 6/15 gendwarfksyms: Expand type modifiers and typedefs

In reply to Sami Tolvanen

Add support for expanding DWARF type modifiers, such as pointers, const values etc., and typedefs. These types all have DW_AT_type attribute pointing the underlying type, and thus produce similar output.

---
 tools/gendwarfksyms/gendwarfksyms.h |  3 ++
 tools/gendwarfksyms/types.c         | 54 +++++++++++++++++++++++++++--
 2 files changed, 54 insertions(+), 3 deletions(-)
tools/gendwarfksyms/gendwarfksyms.h +3 -0
index ea5a9fbda66f..d5ebfe405445 100644
@@ -50,6 +50,9 @@ extern bool no_cache;
 		__res;                                          \
 	})
 
+/* Consistent aliases (DW_TAG_<type>_type) for DWARF tags */
+#define DW_TAG_typedef_type DW_TAG_typedef
+
 /*
  * symbols.c
  */
tools/gendwarfksyms/types.c +51 -3

72 lines not on this page · raw message

Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#7 lore raw

PATCH 7/15 gendwarfksyms: Add pretty-printing

In reply to Sami Tolvanen

Add linebreaks and indentation to --debug output. This will be particularly useful for more complex structures.

Example output with --debug:

  variable pointer_type <unnamed> {
    base_type char byte_size(1)
  };

And the same with --debug --no-pretty-print:

  variable pointer_type <unnamed> {base_type char byte_size(1)};
---
 tools/gendwarfksyms/cache.c         | 13 +++++++++++++
 tools/gendwarfksyms/gendwarfksyms.c |  3 +++
 tools/gendwarfksyms/gendwarfksyms.h |  5 ++++-
 tools/gendwarfksyms/types.c         | 22 ++++++++++++++++++++++
 4 files changed, 42 insertions(+), 1 deletion(-)
tools/gendwarfksyms/cache.c +13 -0
index 9adda113e0b6..85a2adeb649d 100644
@@ -133,6 +133,19 @@ int cache_add_string(struct cached_die *cd, const char *str)
 	return 0;
 }
 
+int cache_add_linebreak(struct cached_die *cd, int linebreak)
+{
+	struct cached_item *ci;
+
+	if (!cd)
+		return 0;
+
+	check(append_item(cd, &ci));
+	ci->data.linebreak = linebreak;
+	ci->type = LINEBREAK;
+	return 0;
+}
+
 int cache_add_die(struct cached_die *cd, Dwarf_Die *die)
 {
 	struct cached_item *ci;
tools/gendwarfksyms/gendwarfksyms.c +3 -0
index 38ccaeb72426..7095f0ecccab 100644
@@ -17,6 +17,8 @@
 bool debug;
 /* Don't use caching */
 bool no_cache;
+/* Don't pretty-print (with --debug) */
+bool no_pretty_print;
 
 static const struct {
 	const char *arg;
@@ -24,6 +26,7 @@ static const struct {
 } options[] = {
 	{ "--debug", &debug },
 	{ "--no-cache", &no_cache },
+	{ "--no-pretty-print", &no_pretty_print },
 };
 
 static int usage(void)
tools/gendwarfksyms/gendwarfksyms.h +4 -1
index d5ebfe405445..43eff91e2f2f 100644
@@ -19,6 +19,7 @@
  */
 extern bool debug;
 extern bool no_cache;
+extern bool no_pretty_print;
 
 /*
  * Output helpers
@@ -76,12 +77,13 @@ extern void symbol_print_versions(void);
 /*
  * cache.c
  */
-enum cached_item_type { EMPTY, STRING, DIE };
+enum cached_item_type { EMPTY, STRING, LINEBREAK, DIE };
 
 struct cached_item {
 	enum cached_item_type type;
 	union {
 		char *str;
+		int linebreak;
 		uintptr_t addr;
 	} data;
 	struct cached_item *next;
@@ -99,6 +101,7 @@ struct cached_die {
 extern int cache_get(Dwarf_Die *die, enum cached_die_state state,
 		     struct cached_die **res);
 extern int cache_add_string(struct cached_die *pd, const char *str);
+extern int cache_add_linebreak(struct cached_die *pd, int linebreak);
 extern int cache_add_die(struct cached_die *pd, Dwarf_Die *die);
 extern void cache_free(void);
 
tools/gendwarfksyms/types.c +22 -0
index 27169c77937f..74b3755c3e16 100644
@@ -6,6 +6,17 @@
 #include "gendwarfksyms.h"
 #include "crc32.h"
 
+static bool do_linebreak;
+static int indentation_level;
+
+/* Line breaks and indentation for pretty-printing */
+static int process_linebreak(struct cached_die *cache, int n)
+{
+	indentation_level += n;
+	do_linebreak = true;
+	return check(cache_add_linebreak(cache, n));
+}
+
 #define DEFINE_GET_ATTR(attr, type)                                    \
 	static bool get_##attr##_attr(Dwarf_Die *die, unsigned int id, \
 				      type *value)                     \
@@ -76,6 +87,12 @@ static int process(struct state *state, struct cached_die *cache, const char *s)
 {
 	s = s ?: "<null>";
 
+	if (debug && !no_pretty_print && do_linebreak) {
+		fputs("\n", stderr);
+		for (int i = 0; i < indentation_level; i++)
+			fputs("  ", stderr);
+		do_linebreak = false;
+	}
 	if (debug)
 		fputs(s, stderr);
 
@@ -196,7 +213,9 @@ static int __process_type(struct state *state, struct cached_die *cache,
 	check(process(state, cache, type));
 	check(process_fqn(state, cache, die));
 	check(process(state, cache, " {"));
+	check(process_linebreak(cache, 1));
 	check(process_type_attr(state, cache, die));
+	check(process_linebreak(cache, -1));
 	check(process(state, cache, "}"));
 	check(process_byte_size_attr(state, cache, die));
 	return check(process_alignment_attr(state, cache, die));
@@ -241,6 +260,9 @@ static int process_cached(struct state *state, struct cached_die *cache,
 		case STRING:
 			check(process(state, NULL, ci->data.str));
 			break;
+		case LINEBREAK:
+			check(process_linebreak(NULL, ci->data.linebreak));
+			break;
 		case DIE:
 			if (!dwarf_die_addr_die(state->dbg,
 						(void *)ci->data.addr,
Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#8 lore raw

PATCH 8/15 gendwarfksyms: Expand subroutine_type

In reply to Sami Tolvanen

Add support for expanding DW_TAG_subroutine_type and the parameters in DW_TAG_formal_parameter. Use also to expand subprograms.

Example output with --debug:

subprogram(
formal_parameter base_type usize byte_size(8), formal_parameter base_type usize byte_size(8),
)
-> base_type void;

---
 tools/gendwarfksyms/gendwarfksyms.h |  1 +
 tools/gendwarfksyms/types.c         | 58 ++++++++++++++++++++++++++++-
 2 files changed, 58 insertions(+), 1 deletion(-)
tools/gendwarfksyms/gendwarfksyms.h +1 -0
index 43eff91e2f2f..03d8a4a039c3 100644
@@ -52,6 +52,7 @@ extern bool no_pretty_print;
 	})
 
 /* Consistent aliases (DW_TAG_<type>_type) for DWARF tags */
+#define DW_TAG_formal_parameter_type DW_TAG_formal_parameter
 #define DW_TAG_typedef_type DW_TAG_typedef
 
 /*
tools/gendwarfksyms/types.c +57 -1

90 lines not on this page · raw message

Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#9 lore raw

PATCH 9/15 gendwarfksyms: Expand array_type

In reply to Sami Tolvanen

Add support for expanding DW_TAG_array_type, and the subrange type indicating array size.

Example output with --debug:

  variable array_type [34] {
    pointer_type <unnamed> {
      const_type <unnamed> {
        base_type char byte_size(1)
      }
    }
  };
---
 tools/gendwarfksyms/types.c | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
tools/gendwarfksyms/types.c +28 -0
index a56aeaa4f3a1..b1b82d166eb8 100644
@@ -177,6 +177,7 @@ DEFINE_PROCESS_UDATA_ATTRIBUTE(byte_size)
 	}
 
 DEFINE_MATCH(formal_parameter)
+DEFINE_MATCH(subrange)
 
 bool match_all(Dwarf_Die *die)
 {
@@ -268,6 +269,31 @@ DEFINE_PROCESS_TYPE(shared)
 DEFINE_PROCESS_TYPE(volatile)
 DEFINE_PROCESS_TYPE(typedef)
 
+static int process_subrange_type(struct state *state, struct cached_die *cache,
+				 Dwarf_Die *die)
+{
+	Dwarf_Word count = 0;
+
+	if (get_udata_attr(die, DW_AT_count, &count))
+		return check(process_fmt(state, cache, "[%" PRIu64 "]", count));
+
+	return check(process(state, cache, "[]"));
+}
+
+static int process_array_type(struct state *state, struct cached_die *cache,
+			      Dwarf_Die *die)
+{
+	check(process(state, cache, "array_type "));
+	/* Array size */
+	check(process_die_container(state, cache, die, process_type,
+				    match_subrange_type));
+	check(process(state, cache, " {"));
+	check(process_linebreak(cache, 1));
+	check(process_type_attr(state, cache, die));
+	check(process_linebreak(cache, -1));
+	return check(process(state, cache, "}"));
+}
+
 static int __process_subroutine_type(struct state *state,
 				     struct cached_die *cache, Dwarf_Die *die,
 				     const char *type)
@@ -378,7 +404,9 @@ static int process_type(struct state *state, struct cached_die *parent,
 	PROCESS_TYPE(volatile)
 	/* Subtypes */
 	PROCESS_TYPE(formal_parameter)
+	PROCESS_TYPE(subrange)
 	/* Other types */
+	PROCESS_TYPE(array)
 	PROCESS_TYPE(base)
 	PROCESS_TYPE(subroutine)
 	PROCESS_TYPE(typedef)
Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#10 lore raw

PATCH 10/15 gendwarfksyms: Expand structure types

In reply to Sami Tolvanen

Recursively expand DWARF structure types, e.g. structs, unions, and enums. Type strings also encode structure member layout, which allows us to determine ABI breakages if the compiler decides to reorder members or otherwise change the layout.

Example output with --debug:

  subprogram(
    formal_parameter pointer_type *mut &str {
      structure_type &str {
        member pointer_type <unnamed> {
          base_type u8 byte_size(1)
        } data_member_location(0),
        member base_type usize byte_size(8) data_member_location(8),
      } byte_size(16) alignment(8)
    },
  )
  -> base_type void;
---
 tools/gendwarfksyms/gendwarfksyms.h |   5 ++
 tools/gendwarfksyms/types.c         | 127 +++++++++++++++++++++++++++-
 2 files changed, 130 insertions(+), 2 deletions(-)
tools/gendwarfksyms/gendwarfksyms.h +5 -0
index 03d8a4a039c3..4646eaf5c85e 100644
@@ -52,8 +52,13 @@ extern bool no_pretty_print;
 	})
 
 /* Consistent aliases (DW_TAG_<type>_type) for DWARF tags */
+#define DW_TAG_enumerator_type DW_TAG_enumerator
 #define DW_TAG_formal_parameter_type DW_TAG_formal_parameter
+#define DW_TAG_member_type DW_TAG_member
+#define DW_TAG_template_type_parameter_type DW_TAG_template_type_parameter
 #define DW_TAG_typedef_type DW_TAG_typedef
+#define DW_TAG_variant_part_type DW_TAG_variant_part
+#define DW_TAG_variant_type DW_TAG_variant
 
 /*
  * symbols.c
tools/gendwarfksyms/types.c +125 -2

182 lines not on this page · raw message

Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#11 lore raw

PATCH 11/15 gendwarfksyms: Limit structure expansion

In reply to Sami Tolvanen

Expand each structure type only once per exported symbol. This is necessary to support self-referential structures, which would otherwise result in infinite recursion. Expanding each structure type just once is enough to catch ABI changes.

For pointers to structure types, limit expansion to three levels inside the pointer. This should be plenty for catching ABI differences and stops us from pulling in half the kernel for structs that contain pointers to large structs like task_struct.

---
 tools/gendwarfksyms/cache.c         | 49 ++++++++++++++++
 tools/gendwarfksyms/gendwarfksyms.h |  9 ++-
 tools/gendwarfksyms/types.c         | 87 ++++++++++++++++++++++++++---
 3 files changed, 136 insertions(+), 9 deletions(-)
tools/gendwarfksyms/cache.c +49 -0
index 85a2adeb649d..1d6eb27d799d 100644
@@ -158,3 +158,52 @@ int cache_add_die(struct cached_die *cd, Dwarf_Die *die)
 	ci->type = DIE;
 	return 0;
 }
+
+/* A list of structure types that were already expanded for the current symbol */
+struct expanded {
+	uintptr_t addr;
+	struct hlist_node hash;
+};
+
+/* die->addr -> struct expanded */
+DEFINE_HASHTABLE(expansion_cache, DIE_HASH_BITS);
+
+int cache_mark_expanded(Dwarf_Die *die)
+{
+	struct expanded *es;
+
+	es = malloc(sizeof(struct expanded));
+	if (!es) {
+		error("malloc failed");
+		return -1;
+	}
+
+	es->addr = (uintptr_t)die->addr;
+	hash_add(expansion_cache, &es->hash, es->addr);
+	return 0;
+}
+
+bool cache_was_expanded(Dwarf_Die *die)
+{
+	struct expanded *es;
+	uintptr_t addr = (uintptr_t)die->addr;
+
+	hash_for_each_possible(expansion_cache, es, hash, addr) {
+		if (es->addr == addr)
+			return true;
+	}
+
+	return false;
+}
+
+void cache_clear_expanded(void)
+{
+	struct hlist_node *tmp;
+	struct expanded *es;
+	int i;
+
+	hash_for_each_safe(expansion_cache, i, tmp, es, hash) {
+		free(es);
+	}
+	hash_init(expansion_cache);
+}
tools/gendwarfksyms/gendwarfksyms.h +8 -1
index 4646eaf5c85e..568f3727017e 100644
@@ -95,7 +95,7 @@ struct cached_item {
 	struct cached_item *next;
 };
 
-enum cached_die_state { INCOMPLETE, COMPLETE };
+enum cached_die_state { INCOMPLETE, UNEXPANDED, COMPLETE };
 
 struct cached_die {
 	enum cached_die_state state;
@@ -111,6 +111,10 @@ extern int cache_add_linebreak(struct cached_die *pd, int linebreak);
 extern int cache_add_die(struct cached_die *pd, Dwarf_Die *die);
 extern void cache_free(void);
 
+extern int cache_mark_expanded(Dwarf_Die *die);
+extern bool cache_was_expanded(Dwarf_Die *die);
+extern void cache_clear_expanded(void);
+
 /*
  * types.c
  */
@@ -120,6 +124,9 @@ struct state {
 	Dwarf *dbg;
 	struct symbol *sym;
 	Dwarf_Die origin;
+	unsigned int ptr_expansion_depth;
+	bool in_pointer_type;
+	bool expand;
 	unsigned long crc;
 };
 
tools/gendwarfksyms/types.c +79 -8

137 lines not on this page · raw message

Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#12 lore raw

PATCH 12/15 gendwarfksyms: Add inline debugging

In reply to Sami Tolvanen

Understanding the operation and caching of the tool can be somewhat challenging without a debugger. Add inline debugging information with the --inline-debug command, which adds highlighted tags to the --debug output with information about cache states etc.

---
 tools/gendwarfksyms/gendwarfksyms.c |  3 +++
 tools/gendwarfksyms/gendwarfksyms.h | 29 +++++++++++++++++++++++++++++
 tools/gendwarfksyms/types.c         | 14 ++++++++++++++
 3 files changed, 46 insertions(+)
tools/gendwarfksyms/gendwarfksyms.c +3 -0
index 7095f0ecccab..acf4b44238e2 100644
@@ -15,6 +15,8 @@
 
 /* Print type descriptions and debugging output to stderr */
 bool debug;
+/* Print inline debugging information to stderr (with --debug) */
+bool inline_debug;
 /* Don't use caching */
 bool no_cache;
 /* Don't pretty-print (with --debug) */
@@ -25,6 +27,7 @@ static const struct {
 	bool *flag;
 } options[] = {
 	{ "--debug", &debug },
+	{ "--inline-debug", &inline_debug },
 	{ "--no-cache", &no_cache },
 	{ "--no-pretty-print", &no_pretty_print },
 };
tools/gendwarfksyms/gendwarfksyms.h +29 -0
index 568f3727017e..34d1be3cfb7f 100644
@@ -18,6 +18,7 @@
  * Options -- in gendwarfksyms.c
  */
 extern bool debug;
+extern bool inline_debug;
 extern bool no_cache;
 extern bool no_pretty_print;
 
@@ -38,6 +39,18 @@ extern bool no_pretty_print;
 #define warn(format, ...) __println("warning: ", format, ##__VA_ARGS__)
 #define error(format, ...) __println("error: ", format, ##__VA_ARGS__)
 
+#define __inline_debug(color, format, ...)                              \
+	do {                                                            \
+		if (debug && inline_debug)                              \
+			fprintf(stderr,                                 \
+				"\033[" #color "m<" format ">\033[39m", \
+				__VA_ARGS__);                           \
+	} while (0)
+
+#define inline_debug_r(format, ...) __inline_debug(91, format, __VA_ARGS__)
+#define inline_debug_g(format, ...) __inline_debug(92, format, __VA_ARGS__)
+#define inline_debug_b(format, ...) __inline_debug(94, format, __VA_ARGS__)
+
 /*
  * Error handling helpers
  */
@@ -51,6 +64,9 @@ extern bool no_pretty_print;
 		__res;                                          \
 	})
 
+/*
+ * DWARF helpers
+ */
 /* Consistent aliases (DW_TAG_<type>_type) for DWARF tags */
 #define DW_TAG_enumerator_type DW_TAG_enumerator
 #define DW_TAG_formal_parameter_type DW_TAG_formal_parameter
@@ -97,6 +113,19 @@ struct cached_item {
 
 enum cached_die_state { INCOMPLETE, UNEXPANDED, COMPLETE };
 
+static inline const char *cache_state_name(enum cached_die_state state)
+{
+	switch (state) {
+	default:
+	case INCOMPLETE:
+		return "INCOMPLETE";
+	case UNEXPANDED:
+		return "UNEXPANDED";
+	case COMPLETE:
+		return "COMPLETE";
+	}
+}
+
 struct cached_die {
 	enum cached_die_state state;
 	uintptr_t addr;
tools/gendwarfksyms/types.c +14 -0
index da3aa2ad9f57..694b33cdd606 100644
@@ -97,6 +97,7 @@ static int process(struct state *state, struct cached_die *cache, const char *s)
 		fputs(s, stderr);
 
 	state->crc = partial_crc32(s, state->crc);
+	inline_debug_r("cache %p string '%s'", cache, s);
 	return cache_add_string(cache, s);
 }
 
@@ -456,6 +457,8 @@ static int process_cached(struct state *state, struct cached_die *cache,
 	while (ci) {
 		switch (ci->type) {
 		case STRING:
+			inline_debug_b("cache %p STRING '%s'", cache,
+				       ci->data.str);
 			check(process(state, NULL, ci->data.str));
 			break;
 		case LINEBREAK:
@@ -468,6 +471,8 @@ static int process_cached(struct state *state, struct cached_die *cache,
 				error("dwarf_die_addr_die failed");
 				return -1;
 			}
+			inline_debug_b("cache %p DIE addr %lx tag %d", cache,
+				       ci->data.addr, dwarf_tag(&child));
 			check(process_type(state, NULL, &child));
 			break;
 		default:
@@ -561,6 +566,9 @@ static int process_type(struct state *state, struct cached_die *parent,
 		check(cache_get(die, want_state, &cache));
 
 		if (cache->state == want_state) {
+			inline_debug_g("cached addr %p tag %d -- %s", die->addr,
+				       tag, cache_state_name(cache->state));
+
 			if (want_state == COMPLETE && is_expanded_type(tag))
 				check(cache_mark_expanded(die));
 
@@ -572,6 +580,9 @@ static int process_type(struct state *state, struct cached_die *parent,
 		}
 	}
 
+	inline_debug_g("addr %p tag %d -- INCOMPLETE -> %s", die->addr, tag,
+		       cache_state_name(want_state));
+
 	switch (tag) {
 	/* Type modifiers */
 	PROCESS_TYPE(atomic)
@@ -608,6 +619,9 @@ static int process_type(struct state *state, struct cached_die *parent,
 	}
 
 	if (!no_cache) {
+		inline_debug_r("parent %p cache %p die addr %p tag %d", parent,
+			       cache, die->addr, tag);
+
 		/* Update cache state and append to the parent (if any) */
 		cache->state = want_state;
 		check(cache_add_die(parent, die));
Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#13 lore raw

PATCH 13/15 modpost: Add support for hashing long symbol names

In reply to Sami Tolvanen

Rust frequently has symbol names longer than MODULE_NAME_LEN, because the full namespace path is encoded into the mangled name. Instead of modpost failing when running into a long name with CONFIG_MODVERSIONS, store a hash of the name in struct modversion_info.

To avoid breaking userspace tools that parse the __versions array, include a null-terminated hash function name at the beginning of the name string, followed by a binary hash. In order to keep .mod.c files more human-readable, add a comment with the full symbol name before the array entry. Example output in rust_minimal.mod.c:

static const struct modversion_info ____versions[]

  __used __section("__versions") = {
        /* _RNvNtNtCs1cdwasc6FUb_6kernel5print14format_strings4INFO */
        { 0x9ec5442f, "sha256\x00\x56\x96\xf4\x27\xdb\x4a\xbf[...]" },
        { 0x1d6595b1, "_RNvNtCs1cdwasc6FUb_6kernel5print11call_printk" },
        { 0x3c642974, "__rust_dealloc" },
        ...

};

modprobe output for the resulting module:

  $ modprobe --dump-modversions rust_minimal.ko
  0x9ec5442f	sha256
  0x1d6595b1	_RNvNtCs1cdwasc6FUb_6kernel5print11call_printk
  0x3c642974	__rust_dealloc
  ...

While the output is less useful, the tool continues to work and can be later updated to produce more helpful output for hashed symbols.

Note that this patch adds a generic SHA-256 implementation to modpost adapted from the Crypto API, but other hash functions may be used in future if needed.

---
 scripts/mod/Makefile  |   4 +-
 scripts/mod/modpost.c |  20 ++-
 scripts/mod/modpost.h |  20 +++
 scripts/mod/symhash.c | 327 ++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 364 insertions(+), 7 deletions(-)
 create mode 100644 scripts/mod/symhash.c
scripts/mod/Makefile +2 -2
index c729bc936bae..ddd59ea9027e 100644
@@ -4,7 +4,7 @@ CFLAGS_REMOVE_empty.o += $(CC_FLAGS_LTO)
 hostprogs-always-y	+= modpost mk_elfconfig
 always-y		+= empty.o
 
-modpost-objs	:= modpost.o file2alias.o sumversion.o symsearch.o
+modpost-objs	:= modpost.o file2alias.o symhash.o sumversion.o symsearch.o
 
 devicetable-offsets-file := devicetable-offsets.h
 
@@ -15,7 +15,7 @@ targets += $(devicetable-offsets-file) devicetable-offsets.s
 
 # dependencies on generated files need to be listed explicitly
 
-$(obj)/modpost.o $(obj)/file2alias.o $(obj)/sumversion.o $(obj)/symsearch.o: $(obj)/elfconfig.h
+$(obj)/modpost.o $(obj)/file2alias.o $(obj)/symhash.o $(obj)/sumversion.o $(obj)/symsearch.o: $(obj)/elfconfig.h
 $(obj)/file2alias.o: $(obj)/$(devicetable-offsets-file)
 
 quiet_cmd_elfconfig = MKELF   $@
scripts/mod/modpost.c +15 -5
index f48d72d22dc2..2631e3e75a5c 100644
@@ -1900,7 +1900,10 @@ static void add_exported_symbols(struct buffer *buf, struct module *mod)
  **/
 static void add_versions(struct buffer *b, struct module *mod)
 {
+	char hash[SYMHASH_STR_LEN];
 	struct symbol *s;
+	const char *name;
+	size_t len;
 
 	if (!modversions)
 		return;
@@ -1917,13 +1920,20 @@ static void add_versions(struct buffer *b, struct module *mod)
 				s->name, mod->name);
 			continue;
 		}
-		if (strlen(s->name) >= MODULE_NAME_LEN) {
-			error("too long symbol \"%s\" [%s.ko]\n",
-			      s->name, mod->name);
-			break;
+		len = strlen(s->name);
+		/*
+		 * For symbols with a long name, use the hash format, but include
+		 * the full symbol name as a comment to keep the generated files
+		 * human-readable.
+		 */
+		if (len >= MODULE_NAME_LEN) {
+			buf_printf(b, "\t/* %s */\n", s->name);
+			name = symhash_str(s->name, len, hash);
+		} else {
+			name = s->name;
 		}
 		buf_printf(b, "\t{ %#8x, \"%s\" },\n",
-			   s->crc, s->name);
+			   s->crc, name);
 	}
 
 	buf_printf(b, "};\n");
scripts/mod/modpost.h +20 -0
index ee43c7950636..cd2eb718936b 100644
@@ -183,6 +183,26 @@ void handle_moddevtable(struct module *mod, struct elf_info *info,
 			Elf_Sym *sym, const char *symname);
 void add_moddevtable(struct buffer *buf, struct module *mod);
 
+/* symhash.c */
+/*
+ * For symbol names longer than MODULE_NAME_LEN, encode a hash of the
+ * symbol name in version information as follows:
+ *
+ * <hash name>\0<binary hash of the symbol name>
+ *
+ * e.g. as a string in .mod.c files:
+ * "sha256\x00\xNN{32}"
+ *
+ * The string is null terminated after the hash name to avoid breaking
+ * userspace tools that parse the __versions table and don't understand
+ * the format.
+ */
+#define SYMHASH_STR_PREFIX	"sha256\\x00"
+#define SYMHASH_STR_PREFIX_LEN	(sizeof(SYMHASH_STR_PREFIX) - 1)
+#define SYMHASH_STR_LEN		(SYMHASH_STR_PREFIX_LEN + 4*32 + 1)
+
+char *symhash_str(const char *name, size_t len, char hash_str[SYMHASH_STR_LEN]);
+
 /* sumversion.c */
 void get_src_version(const char *modname, char sum[], unsigned sumlen);
 
scripts/mod/symhash.c new file +327 -0

327 lines not on this page · raw message

Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
#14 lore raw

Re: [PATCH 13/15] modpost: Add support for hashing long symbol names

Quoted 159 lines · Sami Tolvanen

Rust frequently has symbol names longer than MODULE_NAME_LEN, because the full namespace path is encoded into the mangled name. Instead of modpost failing when running into a long name with CONFIG_MODVERSIONS, store a hash of the name in struct modversion_info.

To avoid breaking userspace tools that parse the __versions array, include a null-terminated hash function name at the beginning of the name string, followed by a binary hash. In order to keep .mod.c files more human-readable, add a comment with the full symbol name before the array entry. Example output in rust_minimal.mod.c:

static const struct modversion_info ____versions[]

  __used __section("__versions") = {
        /* _RNvNtNtCs1cdwasc6FUb_6kernel5print14format_strings4INFO */
        { 0x9ec5442f, "sha256\x00\x56\x96\xf4\x27\xdb\x4a\xbf[...]" },
        { 0x1d6595b1, "_RNvNtCs1cdwasc6FUb_6kernel5print11call_printk" },
        { 0x3c642974, "__rust_dealloc" },
        ...

};

modprobe output for the resulting module:

  $ modprobe --dump-modversions rust_minimal.ko
  0x9ec5442f    sha256
  0x1d6595b1    _RNvNtCs1cdwasc6FUb_6kernel5print11call_printk
  0x3c642974    __rust_dealloc
  ...

While the output is less useful, the tool continues to work and can be later updated to produce more helpful output for hashed symbols.

Note that this patch adds a generic SHA-256 implementation to modpost adapted from the Crypto API, but other hash functions may be used in future if needed.

---
 scripts/mod/Makefile  |   4 +-
 scripts/mod/modpost.c |  20 ++-
 scripts/mod/modpost.h |  20 +++
 scripts/mod/symhash.c | 327 ++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 364 insertions(+), 7 deletions(-)
 create mode 100644 scripts/mod/symhash.c
scripts/mod/Makefile +2 -2
index c729bc936bae..ddd59ea9027e 100644
@@ -4,7 +4,7 @@ CFLAGS_REMOVE_empty.o += $(CC_FLAGS_LTO)
 hostprogs-always-y     += modpost mk_elfconfig
 always-y               += empty.o
 
-modpost-objs   := modpost.o file2alias.o sumversion.o symsearch.o
+modpost-objs   := modpost.o file2alias.o symhash.o sumversion.o symsearch.o
 
 devicetable-offsets-file := devicetable-offsets.h
 
@@ -15,7 +15,7 @@ targets += $(devicetable-offsets-file) devicetable-offsets.s
 
 # dependencies on generated files need to be listed explicitly
 
-$(obj)/modpost.o $(obj)/file2alias.o $(obj)/sumversion.o $(obj)/symsearch.o: $(obj)/elfconfig.h
+$(obj)/modpost.o $(obj)/file2alias.o $(obj)/symhash.o $(obj)/sumversion.o $(obj)/symsearch.o: $(obj)/elfconfig.h
 $(obj)/file2alias.o: $(obj)/$(devicetable-offsets-file)
 
 quiet_cmd_elfconfig = MKELF   $@
scripts/mod/modpost.c +15 -5
index f48d72d22dc2..2631e3e75a5c 100644
@@ -1900,7 +1900,10 @@ static void add_exported_symbols(struct buffer *buf, struct module *mod)
  **/
 static void add_versions(struct buffer *b, struct module *mod)
 {
+       char hash[SYMHASH_STR_LEN];
        struct symbol *s;
+       const char *name;
+       size_t len;
 
        if (!modversions)
                return;
@@ -1917,13 +1920,20 @@ static void add_versions(struct buffer *b, struct module *mod)
                                s->name, mod->name);
                        continue;
                }
-               if (strlen(s->name) >= MODULE_NAME_LEN) {
-                       error("too long symbol \"%s\" [%s.ko]\n",
-                             s->name, mod->name);
-                       break;
+               len = strlen(s->name);
+               /*
+                * For symbols with a long name, use the hash format, but include
+                * the full symbol name as a comment to keep the generated files
+                * human-readable.
+                */
+               if (len >= MODULE_NAME_LEN) {
+                       buf_printf(b, "\t/* %s */\n", s->name);
+                       name = symhash_str(s->name, len, hash);
+               } else {
+                       name = s->name;
                }
                buf_printf(b, "\t{ %#8x, \"%s\" },\n",
-                          s->crc, s->name);
+                          s->crc, name);
        }
 
        buf_printf(b, "};\n");
scripts/mod/modpost.h +20 -0
index ee43c7950636..cd2eb718936b 100644
@@ -183,6 +183,26 @@ void handle_moddevtable(struct module *mod, struct elf_info *info,
                        Elf_Sym *sym, const char *symname);
 void add_moddevtable(struct buffer *buf, struct module *mod);
 
+/* symhash.c */
+/*
+ * For symbol names longer than MODULE_NAME_LEN, encode a hash of the
+ * symbol name in version information as follows:
+ *
+ * <hash name>\0<binary hash of the symbol name>
+ *
+ * e.g. as a string in .mod.c files:
+ * "sha256\x00\xNN{32}"
+ *
+ * The string is null terminated after the hash name to avoid breaking
+ * userspace tools that parse the __versions table and don't understand
+ * the format.
+ */
+#define SYMHASH_STR_PREFIX     "sha256\\x00"
+#define SYMHASH_STR_PREFIX_LEN (sizeof(SYMHASH_STR_PREFIX) - 1)
+#define SYMHASH_STR_LEN                (SYMHASH_STR_PREFIX_LEN + 4*32 + 1)
+
+char *symhash_str(const char *name, size_t len, char hash_str[SYMHASH_STR_LEN]);
+
 /* sumversion.c */
 void get_src_version(const char *modname, char sum[], unsigned sumlen);
 
scripts/mod/symhash.c new file +13 -0
new file mode 100644
index 000000000000..d0c9cf5f1f6c
@@ -0,0 +1,327 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * symhash.c
+ *
+ * Symbol name hashing using a SHA-256 implementation adapted from the
+ * Cryptographic API.
+ */
+#include <byteswap.h>
+#include "modpost.h"
+
+#if HOST_ELFDATA == ELFDATA2MSB
+/* Big endian */
+#define be32_to_cpu(val) (val)

scripts/mod/symhash.c line 23

Quoted 10 lines
scripts/mod/symhash.c new file +10 -0
+#define cpu_to_be32(val) (val)
+#define cpu_to_be64(val) (val)
+#else
+/* Little endian */
+#define be32_to_cpu(val) bswap_32(val)
+#define cpu_to_be32(val) bswap_32(val)
+#define cpu_to_be64(val) bswap_64(val)
+#endif
+
+#define barrier_data(ptr) __asm__ __volatile__("": :"r"(ptr) :"memory")

I know this is a copy-paste of the kernel space code, but is barrier_data() also necessary for host programs?

scripts/mod/symhash.c line 30

Quoted 7 lines
scripts/mod/symhash.c new file +7 -0
+
+static inline void memzero_explicit(void *s, size_t count)
+{
+       memset(s, 0, count);
+       barrier_data(s);
+}
+

--
Best Regards
Masahiro Yamada

author maintainer
#15 lore raw

Re: [PATCH 13/15] modpost: Add support for hashing long symbol names

Quoted 9 lines · Masahiro Yamada
Quoted 2 lines · Sami Tolvanen

+#define barrier_data(ptr) __asm__ __volatile__("": :"r"(ptr) :"memory")

I know this is a copy-paste of the kernel space code, but is barrier_data() also necessary for host programs?

I tested this with Clang and it worked fine without the barrier, but with gcc, the code no longer produces correct values. Presumably this is a load bearing data barrier.

Sami

author maintainer
#16 lore raw

PATCH 14/15 module: Support hashed symbol names when checking modversions

In reply to Sami Tolvanen

When checking modversions for symbol names longer than MODULE_NAME_LEN, look for the hashed symbol name instead. This is needed for Rust modules, which frequently use symbol names longer than the maximum length supported by struct modversion_info.

---
 kernel/module/version.c | 38 +++++++++++++++++++++++++++++++++++++-
 1 file changed, 37 insertions(+), 1 deletion(-)
kernel/module/version.c +37 -1
index 53f43ac5a73e..0b33ca085138 100644
@@ -8,8 +8,36 @@
 #include <linux/module.h>
 #include <linux/string.h>
 #include <linux/printk.h>
+#include <crypto/sha2.h>
 #include "internal.h"
 
+/*
+ * For symbol names longer than MODULE_NAME_LEN, the version table includes
+ * a hash of the symbol name in the following format:
+ *
+ * <hash name>\0<binary hash of the symbol name>
+ */
+#define SYMHASH_PREFIX		"sha256"
+#define SYMHASH_PREFIX_LEN	sizeof(SYMHASH_PREFIX) /* includes \0 */
+#define SYMHASH_LEN		(SYMHASH_PREFIX_LEN + SHA256_DIGEST_SIZE)
+
+static void symhash(const char *name, size_t len, u8 hash[SYMHASH_LEN])
+{
+	memcpy(hash, SYMHASH_PREFIX, SYMHASH_PREFIX_LEN);
+	sha256(name, len, &hash[SYMHASH_PREFIX_LEN]);
+}
+
+static int symcmp(const char *version_name, const char *name, size_t len,
+		  const u8 *hash)
+{
+	BUILD_BUG_ON(SYMHASH_LEN > MODULE_NAME_LEN);
+
+	if (len >= MODULE_NAME_LEN)
+		return memcmp(version_name, hash, SYMHASH_LEN);
+
+	return strcmp(version_name, name);
+}
+
 int check_version(const struct load_info *info,
 		  const char *symname,
 			 struct module *mod,
@@ -19,6 +47,8 @@ int check_version(const struct load_info *info,
 	unsigned int versindex = info->index.vers;
 	unsigned int i, num_versions;
 	struct modversion_info *versions;
+	u8 hash[SYMHASH_LEN];
+	size_t len;
 
 	/* Exporting module didn't supply crcs?  OK, we're already tainted. */
 	if (!crc)
@@ -32,10 +62,16 @@ int check_version(const struct load_info *info,
 	num_versions = sechdrs[versindex].sh_size
 		/ sizeof(struct modversion_info);
 
+	len = strlen(symname);
+
+	/* For symbols with a long name, use the hash format. */
+	if (len >= MODULE_NAME_LEN)
+		symhash(symname, len, hash);
+
 	for (i = 0; i < num_versions; i++) {
 		u32 crcval;
 
-		if (strcmp(versions[i].name, symname) != 0)
+		if (symcmp(versions[i].name, symname, len, hash) != 0)
 			continue;
 
 		crcval = *crc;
Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
author maintainer
#17 lore raw

PATCH 15/15 kbuild: Use gendwarfksyms to generate Rust symbol versions

In reply to Sami Tolvanen

Use gendwarfksyms to generate symbol versions for exported Rust symbols, and allow CONFIG_MODVERSIONS to be enabled with CONFIG_RUST, assuming the debugging information needed by gendwarfksyms is also available.

---
 Makefile      |  6 ++++++
 init/Kconfig  |  2 +-
 rust/Makefile | 30 ++++++++++++++++++++++++------
 3 files changed, 31 insertions(+), 7 deletions(-)
Makefile +6 -0
index 14427547dc1e..0701917c5172 100644
@@ -1344,6 +1344,12 @@ prepare: tools/bpf/resolve_btfids
 endif
 endif
 
+ifdef CONFIG_MODVERSIONS
+ifdef CONFIG_RUST
+prepare: tools/gendwarfksyms
+endif
+endif
+
 PHONY += resolve_btfids_clean
 
 resolve_btfids_O = $(abspath $(objtree))/tools/bpf/resolve_btfids
init/Kconfig +1 -1
index 72404c1f2157..ef29f002e932 100644
@@ -1903,7 +1903,7 @@ config RUST
 	depends on HAVE_RUST
 	depends on RUST_IS_AVAILABLE
 	depends on !CFI_CLANG
-	depends on !MODVERSIONS
+	depends on !MODVERSIONS || (DEBUG_INFO && !DEBUG_INFO_REDUCED && !DEBUG_INFO_SPLIT)
 	depends on !GCC_PLUGINS
 	depends on !RANDSTRUCT
 	depends on !DEBUG_INFO_BTF || PAHOLE_HAS_LANG_EXCLUDE
rust/Makefile +24 -6
index f70d5e244fee..385cdf5dc320 100644
@@ -356,10 +356,11 @@ $(obj)/bindings/bindings_helpers_generated.rs: private bindgen_target_extra = ;
 $(obj)/bindings/bindings_helpers_generated.rs: $(src)/helpers.c FORCE
 	$(call if_changed_dep,bindgen)
 
+rust_exports = $(NM) -p --defined-only $(1) | awk '/ (T|R|D) / { printf $(2),$(3) }'
+
 quiet_cmd_exports = EXPORTS $@
       cmd_exports = \
-	$(NM) -p --defined-only $< \
-		| awk '/ (T|R|D) / {printf "EXPORT_SYMBOL_RUST_GPL(%s);\n",$$3}' > $@
+	$(call rust_exports,$<,"EXPORT_SYMBOL_RUST_GPL(%s);\n",$$3) > $@
 
 $(obj)/exports_core_generated.h: $(obj)/core.o FORCE
 	$(call if_changed,exports)
@@ -420,12 +421,29 @@ ifneq ($(or $(CONFIG_ARM64),$(and $(CONFIG_RISCV),$(CONFIG_64BIT))),)
 		__ashlti3 __lshrti3
 endif
 
+ifdef CONFIG_MODVERSIONS
+# When module versioning is enabled, calculate symbol versions from the DWARF
+# debugging information. We can't use a source code parser like genksyms,
+# because the source files don't have information about the final structure
+# layout and emitted symbols.
+gendwarfksyms := $(objtree)/tools/gendwarfksyms/gendwarfksyms
+
+cmd_gendwarfksyms = \
+	$(call rust_exports,$@,"%s %s\n",$$1$(comma)$$3) \
+		| $(gendwarfksyms) $@ >> $(dot-target).cmd
+endif
+
+define rule_rustc_library_with_exports
+	$(call cmd_and_fixdep,rustc_library)
+	$(call cmd,gendwarfksyms)
+endef
+
 $(obj)/core.o: private skip_clippy = 1
 $(obj)/core.o: private skip_flags = -Dunreachable_pub
 $(obj)/core.o: private rustc_objcopy = $(foreach sym,$(redirect-intrinsics),--redefine-sym $(sym)=__rust$(sym))
 $(obj)/core.o: private rustc_target_flags = $(core-cfgs)
 $(obj)/core.o: $(RUST_LIB_SRC)/core/src/lib.rs FORCE
-	+$(call if_changed_dep,rustc_library)
+	+$(call if_changed_rule,rustc_library_with_exports)
 ifdef CONFIG_X86_64
 $(obj)/core.o: scripts/target.json
 endif
@@ -438,7 +456,7 @@ $(obj)/alloc.o: private skip_clippy = 1
 $(obj)/alloc.o: private skip_flags = -Dunreachable_pub
 $(obj)/alloc.o: private rustc_target_flags = $(alloc-cfgs)
 $(obj)/alloc.o: $(RUST_LIB_SRC)/alloc/src/lib.rs $(obj)/compiler_builtins.o FORCE
-	+$(call if_changed_dep,rustc_library)
+	+$(call if_changed_rule,rustc_library_with_exports)
 
 $(obj)/build_error.o: $(src)/build_error.rs $(obj)/compiler_builtins.o FORCE
 	+$(call if_changed_dep,rustc_library)
@@ -447,7 +465,7 @@ $(obj)/bindings.o: $(src)/bindings/lib.rs \
     $(obj)/compiler_builtins.o \
     $(obj)/bindings/bindings_generated.rs \
     $(obj)/bindings/bindings_helpers_generated.rs FORCE
-	+$(call if_changed_dep,rustc_library)
+	+$(call if_changed_rule,rustc_library_with_exports)
 
 $(obj)/uapi.o: $(src)/uapi/lib.rs \
     $(obj)/compiler_builtins.o \
@@ -458,6 +476,6 @@ $(obj)/kernel.o: private rustc_target_flags = --extern alloc \
     --extern build_error --extern macros --extern bindings --extern uapi
 $(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/alloc.o $(obj)/build_error.o \
     $(obj)/libmacros.so $(obj)/bindings.o $(obj)/uapi.o FORCE
-	+$(call if_changed_dep,rustc_library)
+	+$(call if_changed_rule,rustc_library_with_exports)
 
 endif # CONFIG_RUST
Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
#18 lore raw
In reply to Sami Tolvanen
Quoted 44 lines · Sami Tolvanen

Hi folks,

This series implements CONFIG_MODVERSIONS for Rust, an important feature for distributions like Android that want to ship Rust kernel modules, and depend on modversions to help ensure module ABI compatibility.

There have been earlier proposals [1][2] that would allow Rust modules to coexist with modversions, but none that actually implement symbol versioning. Unlike C, Rust source code doesn't have sufficient information about the final ABI, as the compiler has considerable freedom in adjusting structure layout for improved performance [3], for example, which makes using a source code parser like genksyms a non-starter. Based on Matt's suggestion and previous feedback from maintainers, this series uses DWARF debugging information for computing versions. DWARF is an established and relatively stable format, which includes all the necessary ABI details, and adding a CONFIG_DEBUG_INFO dependency for Rust symbol versioning seems like a reasonable trade-off.

The first 12 patches of this series add a small tool for computing symbol versions from DWARF, called gendwarfksyms. When passed a list of exported symbols, the tool generates an expanded type string for each symbol, and computes symbol CRCs similarly to genksyms. gendwarfksyms is written in C and uses libdw to process DWARF, mainly because of the existing support for C host tools that use elfutils (e.g., objtool).

Another compatibility issue is fitting the extremely long mangled Rust symbol names into struct modversion_info, which can only hold 55-character names (on 64-bit systems). Previous proposals suggested changing the structure to support longer names, but the conclusion was that we cannot break userspace tools that parse the version table.

The next two patches of the series implement support for hashed symbol names in struct modversion_info, where names longer than 55 characters are hashed, and the hash is stored in the name field. To avoid breaking userspace tools, the binary hash is prefixed with a null-terminated string containing the name of the hash function. While userspace tools can later be updated to potentially produce more useful information about the long symbols, this allows them to continue working in the meantime.

Quoted 2 lines

The final patch allows CONFIG_MODVERSIONS to be selected with Rust, provided that debugging information is also available.

I am surprised at someone who attempts to add another variant of genksyms.

I am also surprised at the tool being added under the tools/ directory.

At least, we can avoid the latter misfortune, though.

A patch attached (on top of your patch set).

Such a tool can be compiled in scripts/, or even better in rust/Makefile if it is only used in rust/Makefile.

--
Best Regards
Masahiro Yamada

From dcd8a348af34bc2cd89ef62765a716b8d63d5b0d Mon Sep 17 00:00:00 2001
From: Masahiro Yamada <[email protected]>
Date: Tue, 18 Jun 2024 10:58:55 +0900
Subject: [PATCH] kbuild: move tools/gendwarfksyms to scripts/gendwarfksyms

There is no good reason to use the tool's fragile build system. Move tools/gendwarfksyms/ to scripts/gendwarfksyms/.

Add scripts/gendwarfksyms/.gitignore to ignore gendwarfksyms.

---
 Makefile                                      |  6 ---
 rust/Makefile                                 |  2 +-
 scripts/Makefile                              |  1 +
 scripts/gendwarfksyms/.gitignore              |  2 +
 scripts/gendwarfksyms/Makefile                | 10 ++++
 {tools => scripts}/gendwarfksyms/cache.c      |  0
 {tools => scripts}/gendwarfksyms/crc32.c      |  0
 {tools => scripts}/gendwarfksyms/crc32.h      |  0
 .../gendwarfksyms/gendwarfksyms.c             |  0
 .../gendwarfksyms/gendwarfksyms.h             |  0
 {tools => scripts}/gendwarfksyms/symbols.c    |  0
 {tools => scripts}/gendwarfksyms/types.c      |  0
 tools/Makefile                                |  7 ++-
 tools/gendwarfksyms/Build                     |  5 --
 tools/gendwarfksyms/Makefile                  | 49 -------------------
 15 files changed, 17 insertions(+), 65 deletions(-)
 create mode 100644 scripts/gendwarfksyms/.gitignore
 create mode 100644 scripts/gendwarfksyms/Makefile
 rename {tools => scripts}/gendwarfksyms/cache.c (100%)
 rename {tools => scripts}/gendwarfksyms/crc32.c (100%)
 rename {tools => scripts}/gendwarfksyms/crc32.h (100%)
 rename {tools => scripts}/gendwarfksyms/gendwarfksyms.c (100%)
 rename {tools => scripts}/gendwarfksyms/gendwarfksyms.h (100%)
 rename {tools => scripts}/gendwarfksyms/symbols.c (100%)
 rename {tools => scripts}/gendwarfksyms/types.c (100%)
 delete mode 100644 tools/gendwarfksyms/Build
 delete mode 100644 tools/gendwarfksyms/Makefile
Makefile +0 -6
index 1499b9352634..925a75b8ba7d 100644
@@ -1344,12 +1344,6 @@ prepare: tools/bpf/resolve_btfids
 endif
 endif
 
-ifdef CONFIG_MODVERSIONS
-ifdef CONFIG_RUST
-prepare: tools/gendwarfksyms
-endif
-endif
-
 PHONY += resolve_btfids_clean
 
 resolve_btfids_O = $(abspath $(objtree))/tools/bpf/resolve_btfids
rust/Makefile +1 -1
index 385cdf5dc320..93bf3cf16d6f 100644
@@ -426,7 +426,7 @@ ifdef CONFIG_MODVERSIONS
 # debugging information. We can't use a source code parser like genksyms,
 # because the source files don't have information about the final structure
 # layout and emitted symbols.
-gendwarfksyms := $(objtree)/tools/gendwarfksyms/gendwarfksyms
+gendwarfksyms := scripts/gendwarfksyms/gendwarfksyms
 
 cmd_gendwarfksyms = \
 	$(call rust_exports,$@,"%s %s\n",$$1$(comma)$$3) \
scripts/Makefile +1 -0
index fe56eeef09dd..8bed26489dcc 100644
@@ -55,6 +55,7 @@ targets += module.lds
 subdir-$(CONFIG_GCC_PLUGINS) += gcc-plugins
 subdir-$(CONFIG_MODVERSIONS) += genksyms
 subdir-$(CONFIG_SECURITY_SELINUX) += selinux
+subdir-$(if $(CONFIG_RUST),$(CONFIG_MODVERSIONS)) += gendwarfksyms
 
 # Let clean descend into subdirs
 subdir-	+= basic dtc gdb kconfig mod
scripts/gendwarfksyms/.gitignore new file +2 -0
new file mode 100644
index 000000000000..ab8c763b3afe
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0-only
+/gendwarfksyms
scripts/gendwarfksyms/Makefile new file +10 -0
new file mode 100644
index 000000000000..88039d97bdd8
@@ -0,0 +1,10 @@
+hostprogs-always-y += gendwarfksyms
+
+gendwarfksyms-objs += gendwarfksyms.o
+gendwarfksyms-objs += cache.o
+gendwarfksyms-objs += crc32.o
+gendwarfksyms-objs += symbols.o
+gendwarfksyms-objs += types.o
+
+HOST_EXTRACFLAGS := -I $(srctree)/tools/include
+HOSTLDLIBS_gendwarfksyms := -ldw -lelf
scripts/gendwarfksyms/cache.c renamed from tools/gendwarfksyms/cache.c +0 -0
similarity index 100%
rename from tools/gendwarfksyms/cache.c
rename to scripts/gendwarfksyms/cache.c
scripts/gendwarfksyms/crc32.c renamed from tools/gendwarfksyms/crc32.c +0 -0
similarity index 100%
rename from tools/gendwarfksyms/crc32.c
rename to scripts/gendwarfksyms/crc32.c
scripts/gendwarfksyms/crc32.h renamed from tools/gendwarfksyms/crc32.h +0 -0
similarity index 100%
rename from tools/gendwarfksyms/crc32.h
rename to scripts/gendwarfksyms/crc32.h
scripts/gendwarfksyms/gendwarfksyms.c renamed from tools/gendwarfksyms/gendwarfksyms.c +0 -0
similarity index 100%
rename from tools/gendwarfksyms/gendwarfksyms.c
rename to scripts/gendwarfksyms/gendwarfksyms.c
scripts/gendwarfksyms/gendwarfksyms.h renamed from tools/gendwarfksyms/gendwarfksyms.h +0 -0
similarity index 100%
rename from tools/gendwarfksyms/gendwarfksyms.h
rename to scripts/gendwarfksyms/gendwarfksyms.h
scripts/gendwarfksyms/symbols.c renamed from tools/gendwarfksyms/symbols.c +0 -0
similarity index 100%
rename from tools/gendwarfksyms/symbols.c
rename to scripts/gendwarfksyms/symbols.c
scripts/gendwarfksyms/types.c renamed from tools/gendwarfksyms/types.c +0 -0
similarity index 100%
rename from tools/gendwarfksyms/types.c
rename to scripts/gendwarfksyms/types.c
tools/Makefile +3 -4
index 60806ff753b7..fb0f84e492cb 100644
@@ -17,7 +17,6 @@ help:
 	@echo '  firewire               - the userspace part of nosy, an IEEE-1394 traffic sniffer'
 	@echo '  firmware               - Firmware tools'
 	@echo '  freefall               - laptop accelerometer program for disk protection'
-	@echo '  gendwarfksyms          - generates symbol versions from DWARF'
 	@echo '  gpio                   - GPIO tools'
 	@echo '  hv                     - tools used when in Hyper-V clients'
 	@echo '  iio                    - IIO tools'
@@ -69,7 +68,7 @@ acpi: FORCE
 cpupower: FORCE
 	$(call descend,power/$@)
 
-counter firewire hv guest bootconfig spi usb virtio mm bpf iio gendwarfksyms gpio objtool leds wmi pci firmware debugging tracing: FORCE
+counter firewire hv guest bootconfig spi usb virtio mm bpf iio gpio objtool leds wmi pci firmware debugging tracing: FORCE
 	$(call descend,$@)
 
 bpf/%: FORCE
@@ -155,7 +154,7 @@ freefall_install:
 kvm_stat_install:
 	$(call descend,kvm/$(@:_install=),install)
 
-install: acpi_install counter_install cpupower_install gendwarfksyms_install \
+install: acpi_install counter_install cpupower_install \
 		gpio_install hv_install firewire_install iio_install \
 		perf_install selftests_install turbostat_install usb_install \
 		virtio_install mm_install bpf_install x86_energy_perf_policy_install \
@@ -169,7 +168,7 @@ acpi_clean:
 cpupower_clean:
 	$(call descend,power/cpupower,clean)
 
-counter_clean hv_clean firewire_clean bootconfig_clean spi_clean usb_clean virtio_clean mm_clean wmi_clean bpf_clean iio_clean gendwarfksyms_clean gpio_clean objtool_clean leds_clean pci_clean firmware_clean debugging_clean tracing_clean:
+counter_clean hv_clean firewire_clean bootconfig_clean spi_clean usb_clean virtio_clean mm_clean wmi_clean bpf_clean iio_clean gpio_clean objtool_clean leds_clean pci_clean firmware_clean debugging_clean tracing_clean:
 	$(call descend,$(@:_clean=),clean)
 
 libapi_clean:
tools/gendwarfksyms/Build deleted +0 -5
deleted file mode 100644
index 220a4aa9b380..000000000000
@@ -1,5 +0,0 @@
-gendwarfksyms-y += gendwarfksyms.o
-gendwarfksyms-y += cache.o
-gendwarfksyms-y += crc32.o
-gendwarfksyms-y += symbols.o
-gendwarfksyms-y += types.o
tools/gendwarfksyms/Makefile deleted +0 -49

49 lines not on this page · raw message

Signature · 1 line
2.43.0
author maintainer
#19 lore raw

Hi Masahiro,

Quoted 1 line · Masahiro Yamada

I am surprised at someone who attempts to add another variant of genksyms.

The options are rather limited if we want Rust modules that are compatible with modversions. We either come up with a way to version Rust symbols or we bypass version checks for them, which is basically what Matt's earlier patch set did:

https://lore.kernel.org/rust-for-linux/[email protected]/

If there are better solutions, I would be happy to hear them.

Quoted 1 line

I am also surprised at the tool being added under the tools/ directory.

I picked this location because that's where objtool lives, and wasn't aware that this was frowned upon. I'm fine with moving the tool elsewhere too.

Sami

#20 lore raw
In reply to Sami Tolvanen
Quoted 20 lines · Sami Tolvanen

Hi folks,

This series implements CONFIG_MODVERSIONS for Rust, an important feature for distributions like Android that want to ship Rust kernel modules, and depend on modversions to help ensure module ABI compatibility.

There have been earlier proposals [1][2] that would allow Rust modules to coexist with modversions, but none that actually implement symbol versioning. Unlike C, Rust source code doesn't have sufficient information about the final ABI, as the compiler has considerable freedom in adjusting structure layout for improved performance [3], for example, which makes using a source code parser like genksyms a non-starter. Based on Matt's suggestion and previous feedback from maintainers, this series uses DWARF debugging information for computing versions. DWARF is an established and relatively stable format, which includes all the necessary ABI details, and adding a CONFIG_DEBUG_INFO dependency for Rust symbol versioning seems like a reasonable trade-off.

Quoted 7 lines

The first 12 patches of this series add a small tool for computing symbol versions from DWARF, called gendwarfksyms. When passed a list of exported symbols, the tool generates an expanded type string for each symbol, and computes symbol CRCs similarly to genksyms. gendwarfksyms is written in C and uses libdw to process DWARF, mainly because of the existing support for C host tools that use elfutils (e.g., objtool).

That's cool, can the C code be switched to also use this? That way we only have one path/code for all of this?

thanks,

greg k-h

#21 lore raw
Quoted 30 lines · Greg Kroah-Hartman
Quoted 20 lines · Sami Tolvanen

Hi folks,

This series implements CONFIG_MODVERSIONS for Rust, an important feature for distributions like Android that want to ship Rust kernel modules, and depend on modversions to help ensure module ABI compatibility.

There have been earlier proposals [1][2] that would allow Rust modules to coexist with modversions, but none that actually implement symbol versioning. Unlike C, Rust source code doesn't have sufficient information about the final ABI, as the compiler has considerable freedom in adjusting structure layout for improved performance [3], for example, which makes using a source code parser like genksyms a non-starter. Based on Matt's suggestion and previous feedback from maintainers, this series uses DWARF debugging information for computing versions. DWARF is an established and relatively stable format, which includes all the necessary ABI details, and adding a CONFIG_DEBUG_INFO dependency for Rust symbol versioning seems like a reasonable trade-off.

Quoted 7 lines

The first 12 patches of this series add a small tool for computing symbol versions from DWARF, called gendwarfksyms. When passed a list of exported symbols, the tool generates an expanded type string for each symbol, and computes symbol CRCs similarly to genksyms. gendwarfksyms is written in C and uses libdw to process DWARF, mainly because of the existing support for C host tools that use elfutils (e.g., objtool).

Quoted 2 lines

That's cool, can the C code be switched to also use this? That way we only have one path/code for all of this?

As the description says, it requires CONFIG_DEBUG_INFO.
We can strip the debug info from the final vmlinux, but
I guess the build speed will be even slower than the current genksyms.

Signature · 2 lines
Best Regards
Masahiro Yamada
#22 lore raw
Quoted 32 lines · Masahiro Yamada
Quoted 30 lines · Greg Kroah-Hartman
Quoted 27 lines · Sami Tolvanen

Hi folks,

This series implements CONFIG_MODVERSIONS for Rust, an important feature for distributions like Android that want to ship Rust kernel modules, and depend on modversions to help ensure module ABI compatibility.

There have been earlier proposals [1][2] that would allow Rust modules to coexist with modversions, but none that actually implement symbol versioning. Unlike C, Rust source code doesn't have sufficient information about the final ABI, as the compiler has considerable freedom in adjusting structure layout for improved performance [3], for example, which makes using a source code parser like genksyms a non-starter. Based on Matt's suggestion and previous feedback from maintainers, this series uses DWARF debugging information for computing versions. DWARF is an established and relatively stable format, which includes all the necessary ABI details, and adding a CONFIG_DEBUG_INFO dependency for Rust symbol versioning seems like a reasonable trade-off.

The first 12 patches of this series add a small tool for computing symbol versions from DWARF, called gendwarfksyms. When passed a list of exported symbols, the tool generates an expanded type string for each symbol, and computes symbol CRCs similarly to genksyms. gendwarfksyms is written in C and uses libdw to process DWARF, mainly because of the existing support for C host tools that use elfutils (e.g., objtool).

Quoted 7 lines
Quoted 2 lines

That's cool, can the C code be switched to also use this? That way we only have one path/code for all of this?

As the description says, it requires CONFIG_DEBUG_INFO.
We can strip the debug info from the final vmlinux, but
I guess the build speed will be even slower than the current genksyms.

For people who want genksyms (i.e. distros), don't they normally already enable DEBUG_INFO as well? The problems of genksyms are well known and a pain (I speak from experience), so replacing it with info based on DWARF would be great, I'll gladly trade off the DEBUG_INFO issue for stablilty!

thanks,

greg k-h

#23 lore raw
Quoted 48 lines · Greg Kroah-Hartman
Quoted 32 lines · Masahiro Yamada
Quoted 30 lines · Greg Kroah-Hartman
Quoted 27 lines · Sami Tolvanen

Hi folks,

This series implements CONFIG_MODVERSIONS for Rust, an important feature for distributions like Android that want to ship Rust kernel modules, and depend on modversions to help ensure module ABI compatibility.

There have been earlier proposals [1][2] that would allow Rust modules to coexist with modversions, but none that actually implement symbol versioning. Unlike C, Rust source code doesn't have sufficient information about the final ABI, as the compiler has considerable freedom in adjusting structure layout for improved performance [3], for example, which makes using a source code parser like genksyms a non-starter. Based on Matt's suggestion and previous feedback from maintainers, this series uses DWARF debugging information for computing versions. DWARF is an established and relatively stable format, which includes all the necessary ABI details, and adding a CONFIG_DEBUG_INFO dependency for Rust symbol versioning seems like a reasonable trade-off.

The first 12 patches of this series add a small tool for computing symbol versions from DWARF, called gendwarfksyms. When passed a list of exported symbols, the tool generates an expanded type string for each symbol, and computes symbol CRCs similarly to genksyms. gendwarfksyms is written in C and uses libdw to process DWARF, mainly because of the existing support for C host tools that use elfutils (e.g., objtool).

Quoted 7 lines
Quoted 2 lines

That's cool, can the C code be switched to also use this? That way we only have one path/code for all of this?

As the description says, it requires CONFIG_DEBUG_INFO.
We can strip the debug info from the final vmlinux, but
I guess the build speed will be even slower than the current genksyms.

For people who want genksyms (i.e. distros), don't they normally already enable DEBUG_INFO as well? The problems of genksyms are well known and a pain (I speak from experience), so replacing it with info based on DWARF would be great, I'll gladly trade off the DEBUG_INFO issue for stablilty!

Quoted 4 lines

thanks,

greg k-h

I do not think gendwarfksyms is a drop-in replacement, because it relies on libelf and libdw, which will not work with LLVM bitcode when CONFIG_LTO_CLANG=y.

His "Let's postpone this until final linking" stuff will come back?
Then, vmlinux.o is processed to extract the CRC of all symbols?

In my benchmark, this tool took 3.84 sec just for processing a single rust/core.o object.

I'd love to see how long it will take to process vmlinux.o

And this occurs even when a single source file is changed and vmlinux.o is re-linked.

--
Best Regards
Masahiro Yamada

author maintainer
#24 lore raw
Quoted 28 lines · Masahiro Yamada
Quoted 19 lines · Greg Kroah-Hartman
Quoted 10 lines · Masahiro Yamada
Quoted 3 lines · Greg Kroah-Hartman

That's cool, can the C code be switched to also use this? That way we only have one path/code for all of this?

As the description says, it requires CONFIG_DEBUG_INFO.
We can strip the debug info from the final vmlinux, but
I guess the build speed will be even slower than the current genksyms.

For people who want genksyms (i.e. distros), don't they normally already enable DEBUG_INFO as well? The problems of genksyms are well known and a pain (I speak from experience), so replacing it with info based on DWARF would be great, I'll gladly trade off the DEBUG_INFO issue for stablilty!

Quoted 4 lines

thanks,

greg k-h

Quoted 8 lines

I do not think gendwarfksyms is a drop-in replacement, because it relies on libelf and libdw, which will not work with LLVM bitcode when CONFIG_LTO_CLANG=y.

His "Let's postpone this until final linking" stuff will come back?
Then, vmlinux.o is processed to extract the CRC of all symbols?

I agree, this won't work with LTO unless we process vmlinux.o.

Quoted 2 lines

In my benchmark, this tool took 3.84 sec just for processing a single rust/core.o object.

To be fair, Rust currently exports all globals and core.o has 400 exported symbols as a result. During my brief testing, this tool is faster than genksyms for normal C code.

Quoted 1 line

I'd love to see how long it will take to process vmlinux.o

It's obviously going to be quite slow, my defconfig vmlinux.o has 14k exported symbols:

Performance counter stats for './tools/gendwarfksyms/gendwarfksyms vmlinux.o':

        371,527.67 msec task-clock:u                     #    1.000 CPUs utilized
                 0      context-switches:u               #    0.000 /sec
                 0      cpu-migrations:u                 #    0.000 /sec
           231,554      page-faults:u                    #  623.248 /sec
   <not supported>      cycles:u
   <not supported>      instructions:u
   <not supported>      branches:u
   <not supported>      branch-misses:u
     371.686151684 seconds time elapsed

     370.534637000 seconds user
       0.987825000 seconds sys

The tool is currently single-threaded, so if we really want to go this route, it could probably be made a bit faster.

Quoted 2 lines

And this occurs even when a single source file is changed and vmlinux.o is re-linked.

I suppose anyone using LTO already knows it won't be a quick rebuild though.

Sami

maintainer
#25 lore raw
In reply to Sami Tolvanen
Quoted 7 lines · Sami Tolvanen

Hi folks,

This series implements CONFIG_MODVERSIONS for Rust, an important feature for distributions like Android that want to ship Rust kernel modules, and depend on modversions to help ensure module ABI compatibility.

Quoted 12 lines

There have been earlier proposals [1][2] that would allow Rust modules to coexist with modversions, but none that actually implement symbol versioning. Unlike C, Rust source code doesn't have sufficient information about the final ABI, as the compiler has considerable freedom in adjusting structure layout for improved performance [3], for example, which makes using a source code parser like genksyms a non-starter. Based on Matt's suggestion and previous feedback from maintainers, this series uses DWARF debugging information for computing versions. DWARF is an established and relatively stable format, which includes all the necessary ABI details, and adding a CONFIG_DEBUG_INFO dependency for Rust symbol versioning seems like a reasonable trade-off.

OK sure.

Quoted 4 lines

The first 12 patches of this series add a small tool for computing symbol versions from DWARF, called gendwarfksyms. When passed a list of exported symbols, the tool generates an expanded type string for each symbol, and computes symbol CRCs similarly to genksyms.

So this is too word centric Rust, let's think about this generically. We still ahve a symbol limitation even in the C world then, and this solution can solve that problem also for other reasons for *whatever* reason we devise to-come-up-with-in-the-future for augmenting symbols. Today Rust, tomorrow, who knows.

Quoted 3 lines

gendwarfksyms is written in C and uses libdw to process DWARF, mainly because of the existing support for C host tools that use elfutils (e.g., objtool).

I agree with Masahiro, that testing this with vmlinux would be eye opening to what challenges we really have ahead. So, to help with this let's try to re-think about this from another perspective.

Yes, old userspace should not break, but you can add yet another option to let you opt-in to a new world order of how these crc are mapped to hashed repersentations of the symbols. This would allow us to:

a) Ensure correctness for all users / tools, so that proper plumbing is really done. By considering all symbols you increase your scope of awareness of anything that could really break.

b) Remove the "Rust" nature about this

c) Rust modules just becomes a *user* of this approach

It gets me wondering, given Kris is also working on allowing traces to map symbols to module names, how does this fit into that world [0]?

As for a) the reason I'm thinking about having the ability to test a full real kernel and moules with this is, without that, how are you sure you have the full scope of the changes needed?

[0] https://lkml.kernel.org/r/[email protected]

Luis

author maintainer
#26 lore raw

Hi Luis,

Quoted 11 lines · Luis Chamberlain
Quoted 4 lines · Sami Tolvanen

The first 12 patches of this series add a small tool for computing symbol versions from DWARF, called gendwarfksyms. When passed a list of exported symbols, the tool generates an expanded type string for each symbol, and computes symbol CRCs similarly to genksyms.

So this is too word centric Rust, let's think about this generically. We still ahve a symbol limitation even in the C world then, and this solution can solve that problem also for other reasons for *whatever* reason we devise to-come-up-with-in-the-future for augmenting symbols. Today Rust, tomorrow, who knows.

If you're referring to the symbol hashing in the __versions table, that's not specific to Rust. Rust just happens to be the only source of long symbol names right now.

Quoted 11 lines
Quoted 3 lines

gendwarfksyms is written in C and uses libdw to process DWARF, mainly because of the existing support for C host tools that use elfutils (e.g., objtool).

I agree with Masahiro, that testing this with vmlinux would be eye opening to what challenges we really have ahead. So, to help with this let's try to re-think about this from another perspective.

Yes, old userspace should not break, but you can add yet another option to let you opt-in to a new world order of how these crc are mapped to hashed repersentations of the symbols. This would allow us to:

We did run into an issue with depmod in our testing, where it needs to be taught about hashed names to avoid 'unknown symbol' warnings. I'm not sure if this is acceptable, so I would like to hear feedback about the viability of the hashing scheme in general.

If old userspace can't have any regressions because of long symbol names, I suspect we'll have to go back to omitting long symbols from struct modversion_info and adding a v2 of the __versions table with no symbol name length limitations. Happy to hear your thoughts.

Quoted 7 lines

a) Ensure correctness for all users / tools, so that proper plumbing is really done. By considering all symbols you increase your scope of awareness of anything that could really break.

b) Remove the "Rust" nature about this

c) Rust modules just becomes a *user* of this approach

I believe the only Rust nature here is the last patch that enables gendwarfksyms only for Rust. Otherwise, there shouldn't be anything strictly Rust specific.

Quoted 2 lines

It gets me wondering, given Kris is also working on allowing traces to map symbols to module names, how does this fit into that world [0]?

AFAIK long symbol names are only a problem for struct modversion_info, which uses a relatively short name buffer, so I'm hoping other efforts won't be affected.

Quoted 3 lines

As for a) the reason I'm thinking about having the ability to test a full real kernel and moules with this is, without that, how are you sure you have the full scope of the changes needed?

Sure, I can look into hooking this up for the entire kernel and seeing what breaks, in addition the issues Masahiro pointed out, of course.

Sami

maintainer
#27 lore raw
Quoted 7 lines · Sami Tolvanen

Hi Luis,

Quoted 4 lines · Luis Chamberlain

a) Ensure correctness for all users / tools, so that proper plumbing is really done. By considering all symbols you increase your scope of awareness of anything that could really break.

Quoted 7 lines
Quoted 3 lines

b) Remove the "Rust" nature about this

c) Rust modules just becomes a *user* of this approach

I believe the only Rust nature here is the last patch that enables gendwarfksyms only for Rust. Otherwise, there shouldn't be anything strictly Rust specific.

Right now the check for length is generic, and assumes a hash may exist without considering that check is moot for non-rust modules. So the inverse is true, but doesn't provide a solution or proper architecture for it.

Quoted 6 lines
Quoted 2 lines

It gets me wondering, given Kris is also working on allowing traces to map symbols to module names, how does this fit into that world [0]?

AFAIK long symbol names are only a problem for struct modversion_info, which uses a relatively short name buffer, so I'm hoping other efforts won't be affected.

We'll see!

Quoted 6 lines
Quoted 3 lines

As for a) the reason I'm thinking about having the ability to test a full real kernel and moules with this is, without that, how are you sure you have the full scope of the changes needed?

Sure, I can look into hooking this up for the entire kernel and seeing what breaks, in addition the issues Masahiro pointed out, of course.

:) should be fun!

I think once its revised as a "generic" strategy and not a Rust one, the proper architecture will be considered. Right now, it just looks like a cheap band aid for Rust.

Luis

maintainer
#28 lore raw
In reply to Sami Tolvanen
Quoted 6 lines · Sami Tolvanen

Hi folks,

This series implements CONFIG_MODVERSIONS for Rust, an important feature for distributions like Android that want to ship Rust kernel modules, and depend on modversions to help ensure module ABI compatibility.

Thanks for working on this. Below is some feedback with my (open)SUSE hat on, although it should be quite general.

Quoted 4 lines

There have been earlier proposals [1][2] that would allow Rust modules to coexist with modversions, but none that actually implement symbol versioning. Unlike C, Rust source code doesn't have sufficient information about the final ABI, as the compiler has considerable

Quoted 8 lines

freedom in adjusting structure layout for improved performance [3], for example, which makes using a source code parser like genksyms a non-starter. Based on Matt's suggestion and previous feedback from maintainers, this series uses DWARF debugging information for computing versions. DWARF is an established and relatively stable format, which includes all the necessary ABI details, and adding a CONFIG_DEBUG_INFO dependency for Rust symbol versioning seems like a reasonable trade-off.

Using the DWARF data makes sense to me. Distribution kernels are normally built with debuginfo because one has to be able to debug them later, unsurprisingly. Besides that, one now typically wants to use BPF together with built-in BTF data (CONFIG_DEBUG_INFO_BTF), which also requires building the kernel with debuginfo.

I would however keep in mind that producing all DWARF data has some cost. From a quick test, an x86_64-defconfig build is ~30% slower for me with CONFIG_DEBUG_INFO=y. The current genksyms tool allows to have debuginfo disabled when backporting some patches and consequently have a quicker feedback whether modversions changed. This option would disappear with gendwarfksyms but I think it is acceptable.

Quoted 8 lines

The first 12 patches of this series add a small tool for computing symbol versions from DWARF, called gendwarfksyms. When passed a list of exported symbols, the tool generates an expanded type string for each symbol, and computes symbol CRCs similarly to genksyms. gendwarfksyms is written in C and uses libdw to process DWARF, mainly because of the existing support for C host tools that use elfutils (e.g., objtool).

In addition to calculating CRCs of exported symbols, genksyms has other features which I think are important.

Firstly, the genksyms tool has a human-readable storage format for input data used in the calculation of symbol CRCs. Setting the make variable KBUILD_SYMTYPES enables dumping this data and storing it in *.symtypes files.

When a developer later modifies the kernel and wants to check if some symbols have changed, they can take these files and feed them as *.symref back to genksyms. This allows the tool to provide an actual reason why some symbols have changed, instead of just printing that their CRCs are different.

Is there any plan to add the same functionality to gendwarfksyms, or do you envison that people will use libabigail, Symbol-Type Graph, or another tool for making this type of comparison?

Secondly, when distributions want to maintain stable kABI, they need to be able to deal with patch backports that add new members to structures. One common approach is to have placeholders in important structures which can be later replaced by the new members as needed. __GENKSYMS__ ifdefs are then used at the C source level to hide these kABI-compatible changes from genksyms.

Gendwarfksyms works on the resulting binary and so using such ifdefs wouldn't work. Instead, I suspect that what is required is a mechanism to tell the tool that a given change is ok, probably by allowing to specify some map from the original definition to the new one.

Is there a plan to implement something like this, or how could it be addressed?

Quoted 6 lines

Another compatibility issue is fitting the extremely long mangled Rust symbol names into struct modversion_info, which can only hold 55-character names (on 64-bit systems). Previous proposals suggested changing the structure to support longer names, but the conclusion was that we cannot break userspace tools that parse the version table.

Quoted 8 lines

The next two patches of the series implement support for hashed symbol names in struct modversion_info, where names longer than 55 characters are hashed, and the hash is stored in the name field. To avoid breaking userspace tools, the binary hash is prefixed with a null-terminated string containing the name of the hash function. While userspace tools can later be updated to potentially produce more useful information about the long symbols, this allows them to continue working in the meantime.

I think this approach with hashed names is quite complex. I'd personally be also in favor of having a new section with variable-length strings to store the names of imported symbols. As yet another alternative, it should be also possible to refer directly into .symtab/.strtab to avoid duplicating the names, but I suspect it would be non-trivial to implement.

Cheers,
Petr

author maintainer
#29 lore raw

Hi Petr,

Quoted 11 lines · Petr Pavlu
Quoted 6 lines · Sami Tolvanen

Hi folks,

This series implements CONFIG_MODVERSIONS for Rust, an important feature for distributions like Android that want to ship Rust kernel modules, and depend on modversions to help ensure module ABI compatibility.

Thanks for working on this. Below is some feedback with my (open)SUSE hat on, although it should be quite general.

Great, thanks for taking a look!

Quoted 19 lines
Quoted 4 lines

There have been earlier proposals [1][2] that would allow Rust modules to coexist with modversions, but none that actually implement symbol versioning. Unlike C, Rust source code doesn't have sufficient information about the final ABI, as the compiler has considerable

Quoted 8 lines

freedom in adjusting structure layout for improved performance [3], for example, which makes using a source code parser like genksyms a non-starter. Based on Matt's suggestion and previous feedback from maintainers, this series uses DWARF debugging information for computing versions. DWARF is an established and relatively stable format, which includes all the necessary ABI details, and adding a CONFIG_DEBUG_INFO dependency for Rust symbol versioning seems like a reasonable trade-off.

Using the DWARF data makes sense to me. Distribution kernels are normally built with debuginfo because one has to be able to debug them later, unsurprisingly. Besides that, one now typically wants to use BPF together with built-in BTF data (CONFIG_DEBUG_INFO_BTF), which also requires building the kernel with debuginfo.

Quoted 6 lines

I would however keep in mind that producing all DWARF data has some cost. From a quick test, an x86_64-defconfig build is ~30% slower for me with CONFIG_DEBUG_INFO=y. The current genksyms tool allows to have debuginfo disabled when backporting some patches and consequently have a quicker feedback whether modversions changed. This option would disappear with gendwarfksyms but I think it is acceptable.

Yes, this matches my benchmarks too. Presumably folks who care about build times and are not interested in debugging information or Rust support would prefer genksyms instead. I'm planning to turn this into a Kconfig choice in the next version.

Quoted 22 lines
Quoted 7 lines

The first 12 patches of this series add a small tool for computing symbol versions from DWARF, called gendwarfksyms. When passed a list of exported symbols, the tool generates an expanded type string for each symbol, and computes symbol CRCs similarly to genksyms. gendwarfksyms is written in C and uses libdw to process DWARF, mainly because of the existing support for C host tools that use elfutils (e.g., objtool).

In addition to calculating CRCs of exported symbols, genksyms has other features which I think are important.

Firstly, the genksyms tool has a human-readable storage format for input data used in the calculation of symbol CRCs. Setting the make variable KBUILD_SYMTYPES enables dumping this data and storing it in *.symtypes files.

When a developer later modifies the kernel and wants to check if some symbols have changed, they can take these files and feed them as *.symref back to genksyms. This allows the tool to provide an actual reason why some symbols have changed, instead of just printing that their CRCs are different.

Quoted 3 lines

Is there any plan to add the same functionality to gendwarfksyms, or do you envison that people will use libabigail, Symbol-Type Graph, or another tool for making this type of comparison?

gendwarfksyms also uses human-readable input for the CRC calculations, and it prints out the input strings with the --debug option. I plan to hook this up to KBUILD_SYMTYPES in v2. It should be convenient enough to simply compare the pretty-printed output with diff, so I'm not sure if a built-in comparison option is needed. Any other DWARF analysis tool can be used to spot the differences too, as you mentioned.

Quoted 7 lines

Secondly, when distributions want to maintain stable kABI, they need to be able to deal with patch backports that add new members to structures. One common approach is to have placeholders in important structures which can be later replaced by the new members as needed. __GENKSYMS__ ifdefs are then used at the C source level to hide these kABI-compatible changes from genksyms.

Quoted 7 lines

Gendwarfksyms works on the resulting binary and so using such ifdefs wouldn't work. Instead, I suspect that what is required is a mechanism to tell the tool that a given change is ok, probably by allowing to specify some map from the original definition to the new one.

Is there a plan to implement something like this, or how could it be addressed?

That's a great question. Here's what Android uses currently to maintain a stable kABI, I assume you're doing something similar?

https://android.googlesource.com/kernel/common/+/refs/heads/android15-6.6/include/linux/android_kabi.h

If using unions here is acceptable to everyone, a simple solution would be to use a known name prefix for the reserved members and teach gendwarfksyms to only print out the original type for the replaced ones. For example:

The initial placeholder:

    u8 __kabi_reserved_1[8];

After replacement:

    union {
            u64 new_member;
            struct {
                    u8 __kabi_reserved_1[8];
            };
    }

Here gendwarfksyms would see the __kabi_reserved prefix and only use u8 [8] for the CRC calculation. Does this sound reasonable?

Greg, I know you've been dealing with this for a long time, any thoughts?

Quoted 15 lines
Quoted 6 lines

Another compatibility issue is fitting the extremely long mangled Rust symbol names into struct modversion_info, which can only hold 55-character names (on 64-bit systems). Previous proposals suggested changing the structure to support longer names, but the conclusion was that we cannot break userspace tools that parse the version table.

Quoted 8 lines

The next two patches of the series implement support for hashed symbol names in struct modversion_info, where names longer than 55 characters are hashed, and the hash is stored in the name field. To avoid breaking userspace tools, the binary hash is prefixed with a null-terminated string containing the name of the hash function. While userspace tools can later be updated to potentially produce more useful information about the long symbols, this allows them to continue working in the meantime.

Quoted 6 lines

I think this approach with hashed names is quite complex. I'd personally be also in favor of having a new section with variable-length strings to store the names of imported symbols. As yet another alternative, it should be also possible to refer directly into .symtab/.strtab to avoid duplicating the names, but I suspect it would be non-trivial to implement.

Thanks for the feedback. I think for the next version we'll look into reviving the relevant bits of Matt's previous patch series, which implemented a new section that supports variable-length names:

https://lore.kernel.org/lkml/CAGSQo03R+HYcX2JJDSm7LA8V370s_3hrbTBc2s51Pp9nxWTz5w@mail.gmail.com/

Sami

#30 lore raw
Quoted 8 lines · Sami Tolvanen

If using unions here is acceptable to everyone, a simple solution would be to use a known name prefix for the reserved members and teach gendwarfksyms to only print out the original type for the replaced ones. For example:

The initial placeholder:

    u8 __kabi_reserved_1[8];

Don't use u8, use u64 please, it makes things simpler :)

Quoted 8 lines

After replacement:

    union {
            u64 new_member;
            struct {
                    u8 __kabi_reserved_1[8];
            };
    }

Note, such a thing would only be for the distros that want it, you can add support for this to the tool, but there is no need for any __kabi_reserved fields in mainline.

Quoted 4 lines

Here gendwarfksyms would see the __kabi_reserved prefix and only use u8 [8] for the CRC calculation. Does this sound reasonable?

Greg, I know you've been dealing with this for a long time, any thoughts?

It's a good start, yes. Also watch out for when structures go from "anonymous" to "fully described" when new #include lines get added to files. The current tooling has issues with that, so we need to use __GENKSYMS__ #ifdef lines in some places to keep crc generation stable. Don't know if dwarf output would be susceptible to the same issues with that or not, but you should check.

thanks,

greg k-h

author maintainer
#31 lore raw
Quoted 10 lines · Greg Kroah-Hartman
Quoted 9 lines

After replacement:

    union {
            u64 new_member;
            struct {
                    u8 __kabi_reserved_1[8];
            };
    }
Quoted 3 lines

Note, such a thing would only be for the distros that want it, you can add support for this to the tool, but there is no need for any __kabi_reserved fields in mainline.

Sure. I assume modversions are primarily useful for distros, so I just want to make sure this scheme can handle all the common issues as well.

Quoted 8 lines
Quoted 1 line

Greg, I know you've been dealing with this for a long time, any thoughts?

It's a good start, yes. Also watch out for when structures go from "anonymous" to "fully described" when new #include lines get added to files. The current tooling has issues with that, so we need to use __GENKSYMS__ #ifdef lines in some places to keep crc generation stable. Don't know if dwarf output would be susceptible to the same issues with that or not, but you should check.

That's a great point. DWARF output has the exact same problem if a structure declaration later becomes a definition, but I think we can come up with a solution for this issue too in v2.

Sami

maintainer
#32 lore raw
In reply to Sami Tolvanen
Quoted 28 lines · Sami Tolvanen
Quoted 23 lines · Petr Pavlu
Quoted 7 lines · Sami Tolvanen

The first 12 patches of this series add a small tool for computing symbol versions from DWARF, called gendwarfksyms. When passed a list of exported symbols, the tool generates an expanded type string for each symbol, and computes symbol CRCs similarly to genksyms. gendwarfksyms is written in C and uses libdw to process DWARF, mainly because of the existing support for C host tools that use elfutils (e.g., objtool).

In addition to calculating CRCs of exported symbols, genksyms has other features which I think are important.

Firstly, the genksyms tool has a human-readable storage format for input data used in the calculation of symbol CRCs. Setting the make variable KBUILD_SYMTYPES enables dumping this data and storing it in *.symtypes files.

When a developer later modifies the kernel and wants to check if some symbols have changed, they can take these files and feed them as *.symref back to genksyms. This allows the tool to provide an actual reason why some symbols have changed, instead of just printing that their CRCs are different.

Quoted 3 lines

Is there any plan to add the same functionality to gendwarfksyms, or do you envison that people will use libabigail, Symbol-Type Graph, or another tool for making this type of comparison?

Quoted 6 lines

gendwarfksyms also uses human-readable input for the CRC calculations, and it prints out the input strings with the --debug option. I plan to hook this up to KBUILD_SYMTYPES in v2. It should be convenient enough to simply compare the pretty-printed output with diff, so I'm not sure if a built-in comparison option is needed. Any other DWARF analysis tool can be used to spot the differences too, as you mentioned.

From my perspective, I'm okay if gendwarfksyms doesn't provide functionality to compare a new object file with its reference symtypes file.

As mentioned, genksyms has this functionality but I actually think the way it works is not ideal. Its design is to operate on one compilation unit at the time. This has the advantage that a comparison of each file is performed in parallel during the build, simply because of the make job system. On the other hand, it has two problems.

The first one is that genksyms doesn't provide a comparison of the kernel as a whole. This means that the tool gives rather scattered and duplicated output about changed structs in the build log. Ideally, one would like to see a single compact report about what changed at the end of the build.

The second problem is the handling of symtypes files. This data is large and if one wants to store them in a Git repository together with the kernel source, it is advisable to first compress/consolidate it in some way. This is trivial because these files typically contain many duplicates. However, the issue is that to feed the data back to genksyms, they need to be unpacked during each build which can take some time.

I think a better approach is to have a tool that can be given a consolidated symtypes file as one input and can compare it with all new symtypes files produced during a kernel build. An example of a tool that takes this approach is the kabi Python script in UEK [1].

A few months ago, I also started working on a tool inspired by this script. The goal is to have similar functionality but hopefully with a much faster implementation. Hence, this tool is written in a compiled language (Rust at the moment) and should also become multi-threaded. I'm hoping to find some time to make progress on it and make the code public. It could later be added to the upstream kernel to replace the comparison functionality implemented by genksyms, if there is interest.

So as mentioned, I'm fine if gendwarfksyms doesn't have this functionality. However, for distributions that rely on the symtypes format, I'd be interested in having gendwarfksyms output its dump data in this format as well.

For example, instead of producing:

gendwarfksyms: process_exported_symbols: _some_mangled_func_name (@ XYZ) subprogram(
[formal parameters...]
)
-> structure_type core::result::Result<(), core::fmt::Error> {
[a description of the structure...]
};

.. the output could be something like this:

S#'core::result::Result<(), core::fmt::Error>' structure_type core::result::Result<(), core::fmt::Error> { [a description of the structure...] } _some_mangled_func_name subprogram _some_mangled_func_name ( [formal parameters...] ) -> S#'core::result::Result<(), core::fmt::Error>'

Quoted 12 lines
Quoted 12 lines

Secondly, when distributions want to maintain stable kABI, they need to be able to deal with patch backports that add new members to structures. One common approach is to have placeholders in important structures which can be later replaced by the new members as needed. __GENKSYMS__ ifdefs are then used at the C source level to hide these kABI-compatible changes from genksyms.

Gendwarfksyms works on the resulting binary and so using such ifdefs wouldn't work. Instead, I suspect that what is required is a mechanism to tell the tool that a given change is ok, probably by allowing to specify some map from the original definition to the new one.

Quoted 5 lines
Quoted 2 lines

Is there a plan to implement something like this, or how could it be addressed?

That's a great question. Here's what Android uses currently to maintain a stable kABI, I assume you're doing something similar?

Correct, (open)SUSE kernels have placeholders in likely-to-change structs which can be used for new members. Or if no placeholder is present, it might be necessary to place a new member in a gap (padding) in the struct layout.

Quoted 21 lines

https://android.googlesource.com/kernel/common/+/refs/heads/android15-6.6/include/linux/android_kabi.h

If using unions here is acceptable to everyone, a simple solution would be to use a known name prefix for the reserved members and teach gendwarfksyms to only print out the original type for the replaced ones. For example:

The initial placeholder:

    u8 __kabi_reserved_1[8];

After replacement:

    union {
            u64 new_member;
            struct {
                    u8 __kabi_reserved_1[8];
            };
    }
Quoted 2 lines

Here gendwarfksyms would see the __kabi_reserved prefix and only use u8 [8] for the CRC calculation. Does this sound reasonable?

I like this idea. I think it's good that the necessary kABI information about an updated member can be expressed at the source code level in place of the actual change, and it isn't needed to feed additional input to the tool.

[1] https://github.com/oracle/linux-uek/blob/dbdd7f3611cb03e607e156834497dd2767103530/uek-rpm/tools/kabi

Thanks,
Petr

author maintainer
#33 lore raw

Hi Petr,

Quoted 11 lines · Petr Pavlu

From my perspective, I'm okay if gendwarfksyms doesn't provide functionality to compare a new object file with its reference symtypes file.

As mentioned, genksyms has this functionality but I actually think the way it works is not ideal. Its design is to operate on one compilation unit at the time. This has the advantage that a comparison of each file is performed in parallel during the build, simply because of the make job system. On the other hand, it has two problems.

Quoted 5 lines

The first one is that genksyms doesn't provide a comparison of the kernel as a whole. This means that the tool gives rather scattered and duplicated output about changed structs in the build log. Ideally, one would like to see a single compact report about what changed at the end of the build.

Sure, that makes sense. Android uses STG for this, which might be useful to other folks too:

https://android.googlesource.com/platform/external/stg/
https://android.googlesource.com/platform/external/stg/+/refs/heads/main/doc/stgdiff.md#output-formats

Quoted 8 lines

A few months ago, I also started working on a tool inspired by this script. The goal is to have similar functionality but hopefully with a much faster implementation. Hence, this tool is written in a compiled language (Rust at the moment) and should also become multi-threaded. I'm hoping to find some time to make progress on it and make the code public. It could later be added to the upstream kernel to replace the comparison functionality implemented by genksyms, if there is interest.

Quoted 4 lines

So as mentioned, I'm fine if gendwarfksyms doesn't have this functionality. However, for distributions that rely on the symtypes format, I'd be interested in having gendwarfksyms output its dump data in this format as well.

We can definitely tweak the output format, but I'm not sure if making it fully compatible with the genksyms symtypes format is feasible, especially for Rust code. I also intentionally decided to use DWARF tag names in the output instead of shorthands like s# etc. to make it a bit more readable.

Quoted 10 lines

For example, instead of producing:

gendwarfksyms: process_exported_symbols: _some_mangled_func_name (@ XYZ) subprogram(
[formal parameters...]
)
-> structure_type core::result::Result<(), core::fmt::Error> {
[a description of the structure...]
};

Quoted 4 lines

.. the output could be something like this:

S#'core::result::Result<(), core::fmt::Error>' structure_type core::result::Result<(), core::fmt::Error> { [a description of the structure...] } _some_mangled_func_name subprogram _some_mangled_func_name ( [formal parameters...] ) -> S#'core::result::Result<(), core::fmt::Error>'

This wouldn't be enough to make the output format compatible with symtypes though. genksyms basically produces a simple key-value pair database while gendwarfksyms currently outputs the fully expanded type string for each symbol. If you need the tool to produce a type database, it might also be worth discussing if we should use a bit less ad hoc format in that case.

One more thing to note about the current --debug output is that it directly correlates with the debugging information and thus may not contain all aliases. For example, the Rust compiler deduplicates identical function implementations (e.g. Deref::deref and DerefMut::deref_mut etc.), but only one of the symbol names appears in DWARF. We use symbol addresses to print out #SYMVERs also for the aliases, but they don't show up in the debugging output right now.

Quoted 18 lines
Quoted 18 lines

If using unions here is acceptable to everyone, a simple solution would be to use a known name prefix for the reserved members and teach gendwarfksyms to only print out the original type for the replaced ones. For example:

The initial placeholder:

    u8 __kabi_reserved_1[8];

After replacement:

    union {
            u64 new_member;
            struct {
                    u8 __kabi_reserved_1[8];
            };
    }
Quoted 7 lines
Quoted 2 lines

Here gendwarfksyms would see the __kabi_reserved prefix and only use u8 [8] for the CRC calculation. Does this sound reasonable?

I like this idea. I think it's good that the necessary kABI information about an updated member can be expressed at the source code level in place of the actual change, and it isn't needed to feed additional input to the tool.

OK, cool. I agree that being able to specify these details in source code is much cleaner. I'll add an implementation for this, and for the definition visibility issue Greg mentioned in v2.

Sami

#34 lore raw
Quoted 103 lines · EDT Sami Tolvanen

Hi Petr,

Quoted 10 lines · Petr Pavlu

From my perspective, I'm okay if gendwarfksyms doesn't provide functionality to compare a new object file with its reference symtypes file.

As mentioned, genksyms has this functionality but I actually think the way it works is not ideal. Its design is to operate on one compilation unit at the time. This has the advantage that a comparison of each file is performed in parallel during the build, simply because of the make job system. On the other hand, it has two problems.

Quoted 5 lines

The first one is that genksyms doesn't provide a comparison of the kernel as a whole. This means that the tool gives rather scattered and duplicated output about changed structs in the build log. Ideally, one would like to see a single compact report about what changed at the end of the build.

Sure, that makes sense. Android uses STG for this, which might be useful to other folks too:

https://android.googlesource.com/platform/external/stg/
https://android.googlesource.com/platform/external/stg/+/refs/heads/main/doc
/stgdiff.md#output-formats

Quoted 8 lines

A few months ago, I also started working on a tool inspired by this script. The goal is to have similar functionality but hopefully with a much faster implementation. Hence, this tool is written in a compiled language (Rust at the moment) and should also become multi-threaded. I'm hoping to find some time to make progress on it and make the code public. It could later be added to the upstream kernel to replace the comparison functionality implemented by genksyms, if there is interest.

Quoted 4 lines

So as mentioned, I'm fine if gendwarfksyms doesn't have this functionality. However, for distributions that rely on the symtypes format, I'd be interested in having gendwarfksyms output its dump data in this format as well.

We can definitely tweak the output format, but I'm not sure if making it fully compatible with the genksyms symtypes format is feasible, especially for Rust code. I also intentionally decided to use DWARF tag names in the output instead of shorthands like s# etc. to make it a bit more readable.

Quoted 14 lines

For example, instead of producing:

gendwarfksyms: process_exported_symbols: _some_mangled_func_name (@ XYZ) subprogram(

[formal parameters...]

)
-> structure_type core::result::Result<(), core::fmt::Error> {

[a description of the structure...]

};

Quoted 7 lines

.. the output could be something like this:

S#'core::result::Result<(), core::fmt::Error>' structure_type core::result::Result<(), core::fmt::Error> { [a description of the structure...] } _some_mangled_func_name subprogram _some_mangled_func_name ( [formal parameters...] ) -> S#'core::result::Result<(), core::fmt::Error>'

This wouldn't be enough to make the output format compatible with symtypes though. genksyms basically produces a simple key-value pair database while gendwarfksyms currently outputs the fully expanded type string for each symbol. If you need the tool to produce a type database, it might also be worth discussing if we should use a bit less ad hoc format in that case.

One more thing to note about the current --debug output is that it directly correlates with the debugging information and thus may not contain all aliases. For example, the Rust compiler deduplicates identical function implementations (e.g. Deref::deref and DerefMut::deref_mut etc.), but only one of the symbol names appears in DWARF. We use symbol addresses to print out #SYMVERs also for the aliases, but they don't show up in the debugging output right now.

Quoted 23 lines
Quoted 22 lines

If using unions here is acceptable to everyone, a simple solution would be to use a known name prefix for the reserved members and teach gendwarfksyms to only print out the original type for the replaced ones. For example:

The initial placeholder:

    u8 __kabi_reserved_1[8];

After replacement:

    union {
    
            u64 new_member;
            struct {
            
                    u8 __kabi_reserved_1[8];
            
            };
    
    }

Here gendwarfksyms would see the __kabi_reserved prefix and only use u8 [8] for the CRC calculation. Does this sound reasonable?

Quoted 9 lines
Quoted 4 lines

I like this idea. I think it's good that the necessary kABI information about an updated member can be expressed at the source code level in place of the actual change, and it isn't needed to feed additional input to the tool.

OK, cool. I agree that being able to specify these details in source code is much cleaner. I'll add an implementation for this, and for the definition visibility issue Greg mentioned in v2.

Could you please add myself, Hector, and Janne (along with the Asahi Linux mailing list) to the recipients when you send the v2 patch set? We're also interested in this. :)

Thanks in advance!

Signature · 1 line
真実はいつも一つ!/ Always, there's only one truth!
maintainer
#35 lore raw
In reply to Sami Tolvanen
Quoted 18 lines · Sami Tolvanen
Quoted 11 lines · Petr Pavlu

From my perspective, I'm okay if gendwarfksyms doesn't provide functionality to compare a new object file with its reference symtypes file.

As mentioned, genksyms has this functionality but I actually think the way it works is not ideal. Its design is to operate on one compilation unit at the time. This has the advantage that a comparison of each file is performed in parallel during the build, simply because of the make job system. On the other hand, it has two problems.

Quoted 5 lines

The first one is that genksyms doesn't provide a comparison of the kernel as a whole. This means that the tool gives rather scattered and duplicated output about changed structs in the build log. Ideally, one would like to see a single compact report about what changed at the end of the build.

Quoted 5 lines

Sure, that makes sense. Android uses STG for this, which might be useful to other folks too:

https://android.googlesource.com/platform/external/stg/
https://android.googlesource.com/platform/external/stg/+/refs/heads/main/doc/stgdiff.md#output-formats

STG is an interesting tool. I've played with it a bit last year. To be frank, I was surprised to see a new tool being proposed by Google to generate modversion CRCs from DWARF instead of potentially extending your STG project for this purpose. I'm not sure if it is something that you folks have considered and evaluated.

Quoted 13 lines
Quoted 8 lines

A few months ago, I also started working on a tool inspired by this script. The goal is to have similar functionality but hopefully with a much faster implementation. Hence, this tool is written in a compiled language (Rust at the moment) and should also become multi-threaded. I'm hoping to find some time to make progress on it and make the code public. It could later be added to the upstream kernel to replace the comparison functionality implemented by genksyms, if there is interest.

Quoted 4 lines

So as mentioned, I'm fine if gendwarfksyms doesn't have this functionality. However, for distributions that rely on the symtypes format, I'd be interested in having gendwarfksyms output its dump data in this format as well.

Quoted 5 lines

We can definitely tweak the output format, but I'm not sure if making it fully compatible with the genksyms symtypes format is feasible, especially for Rust code. I also intentionally decided to use DWARF tag names in the output instead of shorthands like s# etc. to make it a bit more readable.

Sure, it might be necessary to extend the symtypes format a bit, for example, by allowing spaces in type names. What other problems do you see?

The example I showed preserves the DWARF tag names in type descriptions. Cross-references and the target type names use the s# prefix as they they need to be distinguished from other tokens.

Quoted 15 lines
Quoted 10 lines

For example, instead of producing:

gendwarfksyms: process_exported_symbols: _some_mangled_func_name (@ XYZ) subprogram(
[formal parameters...]
)
-> structure_type core::result::Result<(), core::fmt::Error> {
[a description of the structure...]
};

Quoted 4 lines

.. the output could be something like this:

S#'core::result::Result<(), core::fmt::Error>' structure_type core::result::Result<(), core::fmt::Error> { [a description of the structure...] } _some_mangled_func_name subprogram _some_mangled_func_name ( [formal parameters...] ) -> S#'core::result::Result<(), core::fmt::Error>'

Quoted 6 lines

This wouldn't be enough to make the output format compatible with symtypes though. genksyms basically produces a simple key-value pair database while gendwarfksyms currently outputs the fully expanded type string for each symbol. If you need the tool to produce a type database, it might also be worth discussing if we should use a bit less ad hoc format in that case.

What I think is needed is the ability to compare an updated kernel with some previous reference and have an output that clearly and accurately shows why CRCs of some symbols changed. The previous reference should be possible to store in Git together with the kernel source. It means it should be ideally some text format and limited in size. This is what distributions that care about stable kABI do in some form currently.

This functionality would be needed if some distribution wants to maintain stable Rust kABI (not sure if it is actually feasible), or if the idea is for gendwarfksyms to be a general tool that could replace genksyms. I assume for the sake of argument that this is the case.

Gendwarfksyms could implement this functionality on its own, or as discussed, I believe it could provide a symtypes-like dump and a second tool could be used to work with this format and for comparing it.

From my point of view, the current --debug format is not suitable for this purpose because its expanded and unstructured form means it is bloated and hard to compare with a previous reference.

I'm also not quite yet sold on using separate DWARF tooling, such as libabigail or STG, to actually understand why gendwarfksyms produced a different CRC for some symbol. Using these tools makes sense in the genksyms world, where genksyms operates on the source code level and this additional tooling can only work on debug data.

With gendwarfksyms working directly with DWARF data, it doesn't seem appealing to me to first run gendwarfksyms to produce CRCs, compare them with their reference, and if they are different, use a second tool to process the same DWARF data again and with some luck hopefully get an actual answer why the CRCs changed. I'm worried that users might encounter inaccurate answers if the two tools interpret the input data differently.

Quoted 8 lines

One more thing to note about the current --debug output is that it directly correlates with the debugging information and thus may not contain all aliases. For example, the Rust compiler deduplicates identical function implementations (e.g. Deref::deref and DerefMut::deref_mut etc.), but only one of the symbol names appears in DWARF. We use symbol addresses to print out #SYMVERs also for the aliases, but they don't show up in the debugging output right now.

Thanks,
Petr

author maintainer
#36 lore raw

Hi Petr,

Quoted 6 lines · Petr Pavlu

STG is an interesting tool. I've played with it a bit last year. To be frank, I was surprised to see a new tool being proposed by Google to generate modversion CRCs from DWARF instead of potentially extending your STG project for this purpose. I'm not sure if it is something that you folks have considered and evaluated.

Yes. STG is fairly large and written in C++, so it didn't seem like a great candidate for inclusion in the kernel tree, and it's presumably not shipped by most distributions, so it's not really ideal as a dependency either.

Quoted 7 lines

Sure, it might be necessary to extend the symtypes format a bit, for example, by allowing spaces in type names. What other problems do you see?

The example I showed preserves the DWARF tag names in type descriptions. Cross-references and the target type names use the s# prefix as they they need to be distinguished from other tokens.

What I meant is that genksyms output is basically preprocessed C with references scattered in, so if you want something that's fully backwards compatible, that might not be possible. However, if you're happy with just the same database structure and don't care about the exact type description format beyond that, that should be doable, but like you said, still requires extending the format to support more complex type names.

Quoted 12 lines

What I think is needed is the ability to compare an updated kernel with some previous reference and have an output that clearly and accurately shows why CRCs of some symbols changed. The previous reference should be possible to store in Git together with the kernel source. It means it should be ideally some text format and limited in size. This is what distributions that care about stable kABI do in some form currently.

This functionality would be needed if some distribution wants to maintain stable Rust kABI (not sure if it is actually feasible), or if the idea is for gendwarfksyms to be a general tool that could replace genksyms. I assume for the sake of argument that this is the case.

Quoted 7 lines

Gendwarfksyms could implement this functionality on its own, or as discussed, I believe it could provide a symtypes-like dump and a second tool could be used to work with this format and for comparing it.

From my point of view, the current --debug format is not suitable for this purpose because its expanded and unstructured form means it is bloated and hard to compare with a previous reference.

I do see your point, there's a ton of duplication in the --debug output as each symbol expands all the types it uses.

Quoted 6 lines

I'm also not quite yet sold on using separate DWARF tooling, such as libabigail or STG, to actually understand why gendwarfksyms produced a different CRC for some symbol. Using these tools makes sense in the genksyms world, where genksyms operates on the source code level and this additional tooling can only work on debug data.

Quoted 7 lines

With gendwarfksyms working directly with DWARF data, it doesn't seem appealing to me to first run gendwarfksyms to produce CRCs, compare them with their reference, and if they are different, use a second tool to process the same DWARF data again and with some luck hopefully get an actual answer why the CRCs changed. I'm worried that users might encounter inaccurate answers if the two tools interpret the input data differently.

I agree, there might be other DWARF changes that we don't care about, but that nevertheless make it harder to figure out what caused the actual CRC to change.

My initial thought was that simply running a diff between the --debug output would be sufficient, as it would directly tell you what changed, but I didn't consider that the size of the output dump would be of concern as well. I'll look into adding a symtypes-style output format in the next version. Thanks again for the feedback!

Sami