Skip to contentSkip to conversation

CTF rework to work with modules.builtin.ranges

PATCH In review Nick Alcock 1 participant 4 messages Oct 1, 2024

Subsystems (15)
Documentation Arm (32-bit) x86 Kbuild +11 more subsystems
lore
Share & tools
lore
#0 lore raw

v2 cover CTF rework to work with modules.builtin.ranges

This is the same as the non-v2 patch, only squashed back into the previous commits. I also squashed away the iterator, since it's now basically part of the CTF stuff and unlikely to be used elsewhere: so this is now the *entire* CTF series (modulo specfile adjustments that don't belong in a vanilla tree). I fixed a couple of tiny .gitignore bugs in the process (one unnecessary line, one stupid typo).

... perhaps I should move scripts/module_objnames.* into scripts/ctf? WDYT?

Nick Alcock (2):
ctf: generate CTF information for the kernel
ctf: work around binutils bug in ctf_link_add_cu_mapping()

 .gitignore                        |   2 +
 Documentation/process/changes.rst |   3 +
 Makefile                          |   8 +-
 arch/arm/vdso/Makefile            |   4 +
 arch/arm64/kernel/vdso/Makefile   |   4 +
 arch/loongarch/vdso/Makefile      |   3 +-
 arch/mips/vdso/Makefile           |   3 +-
 arch/sparc/vdso/Makefile          |   2 +-
 arch/x86/entry/vdso/Makefile      |   2 +
 arch/x86/um/vdso/Makefile         |   2 +-
 include/asm-generic/vmlinux.lds.h |   1 +
 init/Kconfig                      |   6 +
 lib/Kconfig                       |  11 +
 scripts/.gitignore                |   1 +
 scripts/Makefile                  |   1 +
 scripts/Makefile.ctfa             |  92 +++++++
 scripts/Makefile.ctfa-toplevel    |  51 ++++
 scripts/Makefile.modfinal         |   7 +-
 scripts/Makefile.vmlinux_o        |  20 +-
 scripts/ctf-module-objnames.sh    |  35 +++
 scripts/ctf/.gitignore            |   1 +
 scripts/ctf/Makefile              |   5 +
 scripts/ctf/ctfarchive.c          | 393 ++++++++++++++++++++++++++++++
 scripts/ctf/module_objnames.c     |   2 +
 scripts/ctf/module_objnames.h     |   2 +
 scripts/mod/modpost.c             |   1 +
 scripts/module_objnames.c         | 160 ++++++++++++
 scripts/module_objnames.h         |  48 ++++
 scripts/package/kernel.spec       |   6 +
 scripts/package/mkspec            |   5 +
 scripts/remove-ctf-lds.awk        |  12 +
 31 files changed, 883 insertions(+), 10 deletions(-)
 create mode 100644 scripts/Makefile.ctfa
 create mode 100644 scripts/Makefile.ctfa-toplevel
 create mode 100755 scripts/ctf-module-objnames.sh
 create mode 100644 scripts/ctf/.gitignore
 create mode 100644 scripts/ctf/Makefile
 create mode 100644 scripts/ctf/ctfarchive.c
 create mode 100644 scripts/ctf/module_objnames.c
 create mode 100644 scripts/ctf/module_objnames.h
 create mode 100644 scripts/module_objnames.c
 create mode 100644 scripts/module_objnames.h
 create mode 100644 scripts/remove-ctf-lds.awk
Signature · 1 line
2.46.0.278.g36e3a12567
#1 lore raw

PATCH v2 1/2 ctf: generate CTF information for the kernel

This introduces a new config option, CONFIG_CTF, which causes the compiler to be run with -gctf to emit information on the kernel's types and global variables, and a tool, ctfarchive, which runs whenever 'make ctf' is run, deduplicating that information into a mmappable type archive named vmlinux.ctfa, which is installed at 'make ctf_install' time into /lib/modules/$(uname -r)/kernel/. You can view the contents of this archive via

objdump --ctf --ctf-parent=shared_ctf /lib/modules/$(uname -r)/kernel/vmlinux.ctfa

from binutils 2.41+ (but only binutils 2.35+ is needed for generation).

Out-of-tree modules cannot participate in this mechanism since vmlinux.ctfa is already written: so, as happens for normal userspace binaries, the compiler emits .ctf sections into the modules themselves, and the linker deduplicates them. strip does not strip such sections out, but additional care should be taken not to strip such sections into debug RPMs (they are small enough that this should not be a problem).

For in-tree modules and the core kernel, ctfarchive uses the same code (in libctf) to do the deduplication into vmlinux.ctfa as the linker does for out-of-tree modules and userspace code compiled with -gctf: there is no code duplication.

Within the ctfa file, the type information is divided into a shared repository, containing all types used by more than one module, CTF for the core kernel, and separate CTF for each module built, whether or not this module has been compiled in or not: if a file *could* be built as a module, it will be considered to be a module from the perspective of CTF file emission. This ensures that external consumers such as DTrace always find types for a given module in the same place, regardless of the local kernel configuration, as long as that module is present at all, assisting in portability of D scripts between installations.

This process needs a mapping from the names of object files to the modules that make them up, so we compute such a mapping (under the name .tmp_module.objnames) by scanning the .cmd files left behind by the build process and filtering it using modules.builtin: see scripts/ctf-module-objnames.sh. We add an iterator over these in scripts/module_objnames.c: it's not in scripts/ctf purely because the general idea has nothing much to do with CTF, but I'm happy to migrate it into scripts/ctf if wanted.

We use separate targets for CTF deduplication and installation so that you don't pay the cost of cross-module CTF deduplication while iterating on kernel development, and so that ordinary kernel make install targets don't surprise scripts with extra files. I could be convinced that it makes more sense to install the CTF via make install iff it exists.

One downside of separating make modules_install and make ctf_install is that since make modules_install deletes /lib/modules/$(uname -r), make ctf_install only has an effect if you run it after make modules_install, not before.

This introduces new kernel build-time dependencies on a sufficiently new binutils, a CTF-capable GCC, and libctf: if any of these is not found, CONFIG_CTF is disabled and all this machinery has no effect. Even if it is turned on, in the absence of 'make ctf', the CTF is deduplicated into the modules and then stripped from them and discarded; and in the absence of 'make ctf_install', the deduplicated vmlinux.ctfa is not installed.

Source-wise, outside of various places turning CTF off where not desired (mostly the vDSO), and deleting the CTF from the final modules and kernel, there is hardly any impact to the existing source tree: the new rules are mostly centralized in a new scripts/Makefile.ctfa and scripts/Makefile.ctfa-toplevel, and a small utility 'ctfarchive' to do the final deduplication.

---
 .gitignore                        |   2 +
 Documentation/process/changes.rst |   3 +
 Makefile                          |   8 +-
 arch/arm/vdso/Makefile            |   4 +
 arch/arm64/kernel/vdso/Makefile   |   4 +
 arch/loongarch/vdso/Makefile      |   3 +-
 arch/mips/vdso/Makefile           |   3 +-
 arch/sparc/vdso/Makefile          |   2 +-
 arch/x86/entry/vdso/Makefile      |   2 +
 arch/x86/um/vdso/Makefile         |   2 +-
 include/asm-generic/vmlinux.lds.h |   1 +
 init/Kconfig                      |   6 +
 lib/Kconfig                       |  11 ++
 scripts/.gitignore                |   1 +
 scripts/Makefile                  |   1 +
 scripts/Makefile.ctfa             |  92 ++++++++++
 scripts/Makefile.ctfa-toplevel    |  51 ++++++
 scripts/Makefile.modfinal         |   7 +-
 scripts/Makefile.vmlinux_o        |  20 +-
 scripts/ctf-module-objnames.sh    |  35 ++++
 scripts/ctf/.gitignore            |   1 +
 scripts/ctf/Makefile              |   5 +
 scripts/ctf/ctfarchive.c          | 295 ++++++++++++++++++++++++++++++
 scripts/ctf/module_objnames.c     |   2 +
 scripts/ctf/module_objnames.h     |   2 +
 scripts/mod/modpost.c             |   1 +
 scripts/module_objnames.c         | 160 ++++++++++++++++
 scripts/module_objnames.h         |  48 +++++
 scripts/package/kernel.spec       |   6 +
 scripts/package/mkspec            |   5 +
 scripts/remove-ctf-lds.awk        |  12 ++
 31 files changed, 785 insertions(+), 10 deletions(-)
 create mode 100644 scripts/Makefile.ctfa
 create mode 100644 scripts/Makefile.ctfa-toplevel
 create mode 100755 scripts/ctf-module-objnames.sh
 create mode 100644 scripts/ctf/.gitignore
 create mode 100644 scripts/ctf/Makefile
 create mode 100644 scripts/ctf/ctfarchive.c
 create mode 100644 scripts/ctf/module_objnames.c
 create mode 100644 scripts/ctf/module_objnames.h
 create mode 100644 scripts/module_objnames.c
 create mode 100644 scripts/module_objnames.h
 create mode 100644 scripts/remove-ctf-lds.awk
.gitignore +2 -0
index 56972adb5031..f2c1c3367431 100644
@@ -16,6 +16,7 @@
 *.bin
 *.bz2
 *.c.[012]*.*
+*.ctf
 *.dt.yaml
 *.dtb
 *.dtbo
@@ -64,6 +65,7 @@ modules.order
 /vmlinux.32
 /vmlinux.map
 /vmlinux.symvers
+/vmlinux.ctfa
 /vmlinux-gdb.py
 /vmlinuz
 /System.map
Documentation/process/changes.rst +3 -0
index 00f1ed7c59c3..a8baff63b44a 100644
@@ -65,9 +65,12 @@ gtags (optional)       6.6.5            gtags --version
 mkimage (optional)     2017.01          mkimage --version
 Python (optional)      3.5.x            python3 --version
 GNU AWK (optional)     5.1.0            gawk --version
+GNU C\ [#f2]_          12.0             gcc --version
+binutils\ [#f2]_       2.36             ld -v
 ====================== ===============  ========================================
 
 .. [#f1] Sphinx is needed only to build the Kernel documentation
+.. [#f2] These are needed at build-time when CONFIG_CTF is enabled
 
 Kernel compilation
 ******************
Makefile +6 -2
index 187a4ce2728e..9737c601ad39 100644
@@ -1019,6 +1019,7 @@ include-$(CONFIG_UBSAN)		+= scripts/Makefile.ubsan
 include-$(CONFIG_KCOV)		+= scripts/Makefile.kcov
 include-$(CONFIG_RANDSTRUCT)	+= scripts/Makefile.randstruct
 include-$(CONFIG_GCC_PLUGINS)	+= scripts/Makefile.gcc-plugins
+include-$(CONFIG_CTF)		+= scripts/Makefile.ctfa-toplevel
 
 include $(addprefix $(srctree)/, $(include-y))
 
@@ -1494,7 +1495,8 @@ CLEAN_FILES += vmlinux.symvers modules-only.symvers \
 	       modules.builtin modules.builtin.modinfo modules.nsdeps \
 	       modules.builtin.ranges vmlinux.o.map \
 	       compile_commands.json rust/test \
-	       rust-project.json .vmlinux.objs .vmlinux.export.c
+	       rust-project.json .vmlinux.objs .vmlinux.export.c \
+	       vmlinux.ctfa
 
 # Directories & files removed with 'make mrproper'
 MRPROPER_FILES += include/config include/generated          \
@@ -1588,6 +1590,8 @@ help:
 	@echo  '                    (requires a recent binutils and recent build (System.map))'
 	@echo  '  dir/file.ko     - Build module including final link'
 	@echo  '  modules_prepare - Set up for building external modules'
+	@echo  '  ctf             - Generate CTF type information, installed by make ctf_install'
+	@echo  '  ctf_install     - Install CTF to INSTALL_MOD_PATH (default: /)'
 	@echo  '  tags/TAGS	  - Generate tags file for editors'
 	@echo  '  cscope	  - Generate cscope index'
 	@echo  '  gtags           - Generate GNU GLOBAL index'
@@ -1944,7 +1948,7 @@ clean: $(clean-dirs)
 	$(call cmd,rmfiles)
 	@find $(or $(KBUILD_EXTMOD), .) $(RCS_FIND_IGNORE) \
 		\( -name '*.[aios]' -o -name '*.rsi' -o -name '*.ko' -o -name '.*.cmd' \
-		-o -name '*.ko.*' \
+		-o -name '*.ko.*' -o -name '*.ctf' \
 		-o -name '*.dtb' -o -name '*.dtbo' \
 		-o -name '*.dtb.S' -o -name '*.dtbo.S' \
 		-o -name '*.dt.yaml' -o -name 'dtbs-list' \
arch/arm/vdso/Makefile +4 -0
index 01067a2bc43b..d2193b8dfad8 100644
@@ -14,6 +14,10 @@ obj-vdso := $(addprefix $(obj)/, $(obj-vdso))
 ccflags-y := -fPIC -fno-common -fno-builtin -fno-stack-protector
 ccflags-y += -DDISABLE_BRANCH_PROFILING -DBUILD_VDSO32
 
+# CTF in the vDSO would introduce a new section, which would
+# expand the vDSO to more than a page.
+ccflags-y += $(call cc-option,-gctf0)
+
 ldflags-$(CONFIG_CPU_ENDIAN_BE8) := --be8
 ldflags-y := -Bsymbolic --no-undefined -soname=linux-vdso.so.1 \
 	    -z max-page-size=4096 -shared $(ldflags-y) \
arch/arm64/kernel/vdso/Makefile +4 -0
index 35685c036044..894258136450 100644
@@ -33,6 +33,10 @@ ldflags-y += -T
 ccflags-y := -fno-common -fno-builtin -fno-stack-protector -ffixed-x18
 ccflags-y += -DDISABLE_BRANCH_PROFILING -DBUILD_VDSO
 
+# CTF in the vDSO would introduce a new section, which would
+# expand the vDSO to more than a page.
+ccflags-y += $(call cc-option,-gctf0)
+
 # -Wmissing-prototypes and -Wmissing-declarations are removed from
 # the CFLAGS to make possible to build the kernel with CONFIG_WERROR enabled.
 CC_FLAGS_REMOVE_VDSO := $(CC_FLAGS_FTRACE) -Os $(CC_FLAGS_SCS) \
arch/loongarch/vdso/Makefile +2 -1
index 40c1175823d6..0ab86476ea45 100644
@@ -22,7 +22,8 @@ cflags-vdso := $(ccflags-vdso) \
 	-O2 -g -fno-strict-aliasing -fno-common -fno-builtin \
 	-fno-stack-protector -fno-jump-tables -DDISABLE_BRANCH_PROFILING \
 	$(call cc-option, -fno-asynchronous-unwind-tables) \
-	$(call cc-option, -fno-stack-protector)
+	$(call cc-option, -fno-stack-protector) \
+	$(call cc-option,-gctf0)
 aflags-vdso := $(ccflags-vdso) \
 	-D__ASSEMBLY__ -Wa,-gdwarf-2
 
arch/mips/vdso/Makefile +2 -1
index b289b2c1b294..6c8d777525f9 100644
@@ -30,7 +30,8 @@ cflags-vdso := $(ccflags-vdso) \
 	-O3 -g -fPIC -fno-strict-aliasing -fno-common -fno-builtin -G 0 \
 	-mrelax-pic-calls $(call cc-option, -mexplicit-relocs) \
 	-fno-stack-protector -fno-jump-tables -DDISABLE_BRANCH_PROFILING \
-	$(call cc-option, -fno-asynchronous-unwind-tables)
+	$(call cc-option, -fno-asynchronous-unwind-tables) \
+	$(call cc-option,-gctf0)
 aflags-vdso := $(ccflags-vdso) \
 	-D__ASSEMBLY__ -Wa,-gdwarf-2
 
arch/sparc/vdso/Makefile +1 -1
index 243dbfc4609d..e4f3e47074e9 100644
@@ -44,7 +44,7 @@ $(obj)/vdso-image-%.c: $(obj)/vdso%.so.dbg $(obj)/vdso%.so $(obj)/vdso2c FORCE
 CFL := $(PROFILING) -mcmodel=medlow -fPIC -O2 -fasynchronous-unwind-tables -m64 \
        $(filter -g%,$(KBUILD_CFLAGS)) -fno-stack-protector \
        -fno-omit-frame-pointer -foptimize-sibling-calls \
-       -DDISABLE_BRANCH_PROFILING -DBUILD_VDSO
+       $(call cc-option,-gctf0) -DDISABLE_BRANCH_PROFILING -DBUILD_VDSO
 
 SPARC_REG_CFLAGS = -ffixed-g4 -ffixed-g5 -fcall-used-g5 -fcall-used-g7
 
arch/x86/entry/vdso/Makefile +2 -0
index c9216ac4fb1e..fbbf4de9ff8e 100644
@@ -54,6 +54,7 @@ $(obj)/vdso-image-%.c: $(obj)/vdso%.so.dbg $(obj)/vdso%.so $(obj)/vdso2c FORCE
 CFL := $(PROFILING) -mcmodel=small -fPIC -O2 -fasynchronous-unwind-tables -m64 \
        $(filter -g%,$(KBUILD_CFLAGS)) -fno-stack-protector \
        -fno-omit-frame-pointer -foptimize-sibling-calls \
+       $(call cc-option,-gctf0) \
        -DDISABLE_BRANCH_PROFILING -DBUILD_VDSO
 
 ifdef CONFIG_MITIGATION_RETPOLINE
@@ -132,6 +133,7 @@ KBUILD_CFLAGS_32 += -m32 -msoft-float -mregparm=0 -fpic
 KBUILD_CFLAGS_32 += -fno-stack-protector
 KBUILD_CFLAGS_32 += $(call cc-option, -foptimize-sibling-calls)
 KBUILD_CFLAGS_32 += -fno-omit-frame-pointer
+KBUILD_CFLAGS_32 += $(call cc-option,-gctf0)
 KBUILD_CFLAGS_32 += -DDISABLE_BRANCH_PROFILING
 
 ifdef CONFIG_MITIGATION_RETPOLINE
arch/x86/um/vdso/Makefile +1 -1
index 6a77ea6434ff..6db233b5edd7 100644
@@ -40,7 +40,7 @@ $(obj)/%.so: $(obj)/%.so.dbg FORCE
 #
 CFL := $(PROFILING) -mcmodel=small -fPIC -O2 -fasynchronous-unwind-tables -m64 \
        $(filter -g%,$(KBUILD_CFLAGS)) -fno-stack-protector \
-       -fno-omit-frame-pointer -foptimize-sibling-calls
+       -fno-omit-frame-pointer -foptimize-sibling-calls $(call cc-option,-gctf0)
 
 $(vobjs): KBUILD_CFLAGS += $(CFL)
 
include/asm-generic/vmlinux.lds.h +1 -0
index eeadbaeccf88..6cfb06659d01 100644
@@ -1012,6 +1012,7 @@
 	*(.discard.*)							\
 	*(.export_symbol)						\
 	*(.modinfo)							\
+	*(.ctf)								\
 	/* ld.bfd warns about .gnu.version* even when not emitted */	\
 	*(.gnu.version*)						\
 
init/Kconfig +6 -0
index fbd0cb06a50a..4a6614f4f453 100644
@@ -120,6 +120,12 @@ config PAHOLE_VERSION
 	int
 	default $(shell,$(srctree)/scripts/pahole-version.sh $(PAHOLE))
 
+config HAVE_CTF_TOOLCHAIN
+	def_bool $(cc-option,-gctf) && $(success,$(LD) $(KBUILD_LDFLAGS) -lbfd -liberty -lctf -lbfd -liberty -lz -ldl -lc -o /dev/null)
+	depends on CC_IS_GCC
+	help
+	  GCC and binutils support CTF generation.
+
 config CONSTRUCTORS
 	bool
 
lib/Kconfig +11 -0
index b38849af6f13..d449c7652cda 100644
@@ -634,6 +634,17 @@ config DIMLIB
 #
 config LIBFDT
 	bool
+#
+# CTF support is select'ed if needed
+#
+config CTF
+        bool "Compact Type Format generation"
+        default y
+        depends on HAVE_CTF_TOOLCHAIN
+        help
+          Emit a compact, compressed description of the kernel's datatypes and
+          global variables into the vmlinux.ctfa archive (for in-tree modules)
+          or into .ctf sections in kernel modules (for out-of-tree modules).
 
 config OID_REGISTRY
 	tristate
scripts/.gitignore +1 -0
index 3dbb8bb2457b..434e5da6c75f 100644
@@ -11,3 +11,4 @@
 /sorttable
 /target.json
 /unifdef
+!/Makefile.ctf
scripts/Makefile +1 -0
index 6bcda4b9d054..52739793ba3e 100644
@@ -54,6 +54,7 @@ targets += module.lds
 
 subdir-$(CONFIG_GCC_PLUGINS) += gcc-plugins
 subdir-$(CONFIG_MODVERSIONS) += genksyms
+subdir-$(CONFIG_CTF)         += ctf
 subdir-$(CONFIG_SECURITY_SELINUX) += selinux
 subdir-$(CONFIG_SECURITY_IPE) += ipe
 
scripts/Makefile.ctfa new file +92 -0

92 lines not on this page · raw message

scripts/Makefile.ctfa-toplevel new file +51 -0

51 lines not on this page · raw message

scripts/Makefile.modfinal +6 -1
index 1482884ec3ca..cf87ae7e6fa1 100644
@@ -33,11 +33,16 @@ quiet_cmd_cc_o_c = CC [M]  $@
 $(extmod_prefix).module-common.o: $(srctree)/scripts/module-common.c FORCE
 	$(call if_changed_dep,cc_o_c)
 
+# for module-ctf-postlink
+include $(srctree)/scripts/Makefile.ctfa
+
 quiet_cmd_ld_ko_o = LD [M]  $@
       cmd_ld_ko_o =							\
 	$(LD) -r $(KBUILD_LDFLAGS)					\
 		$(KBUILD_LDFLAGS_MODULE) $(LDFLAGS_MODULE)		\
-		-T scripts/module.lds -o $@ $(filter %.o, $^)
+		-T scripts/module.lds $(LDFLAGS_$(modname)) -o [email protected]	\
+		$(filter %.o, $^) &&					\
+	$(call module-ctf-postlink,$@)					\
 
 quiet_cmd_btf_ko = BTF [M] $@
       cmd_btf_ko = 							\
scripts/Makefile.vmlinux_o +17 -3
index 0b6e2ebf60dc..70d508288b32 100644
@@ -27,6 +27,18 @@ ifdef CONFIG_LTO_CLANG
 initcalls-lds := .tmp_initcalls.lds
 endif
 
+# Generate a linker script to delete CTF sections
+# -----------------------------------------------
+
+quiet_cmd_gen_remove_ctf.lds = GEN     $@
+      cmd_gen_remove_ctf.lds = \
+	$(LD) -r --verbose | awk -f $(real-prereqs) > $@
+
+.tmp_remove-ctf.lds: $(srctree)/scripts/remove-ctf-lds.awk FORCE
+	$(call if_changed,gen_remove_ctf.lds)
+
+targets := .tmp_remove-ctf.lds
+
 # objtool for vmlinux.o
 # ---------------------------------------------------------------------------
 #
@@ -42,7 +54,9 @@ vmlinux-objtool-args-$(CONFIG_NOINSTR_VALIDATION)	+= --noinstr \
 
 objtool-args = $(vmlinux-objtool-args-y) --link
 
-# Link of vmlinux.o used for section mismatch analysis
+# Link of vmlinux.o used for section mismatch analysis: we also strip the CTF
+# section out at this stage, since ctfarchive gets it from the underlying object
+# files and linking it further is a waste of time.
 # ---------------------------------------------------------------------------
 
 vmlinux-o-ld-args-$(CONFIG_BUILTIN_MODULE_RANGES)	+= [email protected]
@@ -51,7 +65,7 @@ quiet_cmd_ld_vmlinux.o = LD      $@
       cmd_ld_vmlinux.o = \
 	$(LD) ${KBUILD_LDFLAGS} -r -o $@ \
 	$(vmlinux-o-ld-args-y) \
-	$(addprefix -T , $(initcalls-lds)) \
+	$(addprefix -T , $(initcalls-lds)) -T .tmp_remove-ctf.lds \
 	--whole-archive vmlinux.a --no-whole-archive \
 	--start-group $(KBUILD_VMLINUX_LIBS) --end-group \
 	$(cmd_objtool)
@@ -61,7 +75,7 @@ define rule_ld_vmlinux.o
 	$(call cmd,gen_objtooldep)
 endef
 
-vmlinux.o: $(initcalls-lds) vmlinux.a $(KBUILD_VMLINUX_LIBS) FORCE
+vmlinux.o: $(initcalls-lds) vmlinux.a $(KBUILD_VMLINUX_LIBS) .tmp_remove-ctf.lds FORCE
 	$(call if_changed_rule,ld_vmlinux.o)
 
 targets += vmlinux.o
scripts/ctf-module-objnames.sh new file +35 -0
new file mode 100755
index 000000000000..4fc8f24b8888
@@ -0,0 +1,35 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0+
+# Produce a file mapping module names to object file names for all built-in
+# modules in the kernel.  Used by ctfarchive.
+
+set -e
+
+# Translate e.g. ./lib/zstd/common/entropy_common.o into
+# ./lib/zstd/common/.entropy_common.o.cmd, and extract the module name from
+# that.
+
+sed 's,^\(.*/\)\(.*\)$,\1.\2.cmd,g' .tmp_objects.builtin |\
+    xargs grep -o -- '-DKBUILD_MODNAME=[^ ]*' | \
+    # Translate e.g. ./lib/zstd/common/.entropy_common.o.cmd:
+    # -KDBUILD_MODNAME='"zstd_common"' into zstd_common
+    # ./lib/zstd/common/entropy_common.o, and sort the result so the same module
+    # always occupies consecutive lines.
+    sed 's,^\([^:]*/\)\.\([^:]*\).cmd.*-DKBUILD_MODNAME=."\([^"]*\)".*$,\3 \1\2,' | sort -k1 | \
+    # Accumulate filename portions for the same module into one line.
+    awk -F ' ' 'BEGIN { mod=""; objs="";}
+                $1 != mod { printf ("%s %s\n", mod, objs); mod=$1; objs=""; }
+                { objs=objs $2 " "; }
+                END { printf ("%s %s\n", mod, objs); }' > .tmp_possible_modobjs
+
+# Filter out the maybe-module names from this list, and sort them.
+sed 's, .*,,' < .tmp_possible_modobjs | sort -u -k 1b,1 > .tmp_possible_modules
+
+# Filter the list of possible modules by the list of modules actually in the
+# kernel, then use that to exclude non-modules from the list we computed
+# earlier.  Trim off trailing spaces, to help the iterator in
+# modules_builtin.c.  Complicated a bit by the need to trim off the leading
+# kernel/ from modules.builtin.
+sed 's,^.*/\([^/]*\)\.ko$,\1,' modules.builtin | sort -u -k 1b,1 | \
+    comm - .tmp_possible_modules -12 | join -j 1 - .tmp_possible_modobjs | \
+    sed 's, *$,,'> $1
scripts/ctf/.gitignore new file +1 -0
new file mode 100644
index 000000000000..6a0eb1c3ceea
@@ -0,0 +1 @@
+ctfarchive
scripts/ctf/Makefile new file +5 -0
new file mode 100644
index 000000000000..cddf9710ef55
@@ -0,0 +1,5 @@
+ifdef CONFIG_CTF
+hostprogs-always-y	:= ctfarchive
+ctfarchive-objs		:= ctfarchive.o module_objnames.o
+HOSTLDLIBS_ctfarchive := -lctf
+endif
scripts/ctf/ctfarchive.c new file +295 -0

295 lines not on this page · raw message

scripts/ctf/module_objnames.c new file +2 -0
new file mode 100644
index 000000000000..4e3d1d6c6389
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#include "../module_objnames.c"
scripts/ctf/module_objnames.h new file +2 -0
new file mode 100644
index 000000000000..b22906bff02f
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#include "../module_objnames.h"
scripts/mod/modpost.c +1 -0
index 107393a8c48a..4514e8a8d522 100644
@@ -726,6 +726,7 @@ static const char *const section_white_list[] =
 	".comment*",
 	".debug*",
 	".zdebug*",		/* Compressed debug sections. */
+        ".ctf",			/* Type info */
 	".GCC.command.line",	/* record-gcc-switches */
 	".mdebug*",        /* alpha, score, mips etc. */
 	".pdr",            /* alpha, score, mips etc. */
scripts/module_objnames.c new file +160 -0

160 lines not on this page · raw message

scripts/module_objnames.h new file +48 -0

48 lines not on this page · raw message

scripts/package/kernel.spec +6 -0
index ac3e5ac01d8a..fc0e9e51529c 100644
@@ -53,12 +53,18 @@ patch -p1 < %{SOURCE2}
 
 %build
 %{make} %{makeflags} KERNELRELEASE=%{KERNELRELEASE} KBUILD_BUILD_VERSION=%{release}
+%if %{with_ctf}
+%{make} %{makeflags} KERNELRELEASE=%{KERNELRELEASE} KBUILD_BUILD_VERSION=%{release} ctf
+%endif
 
 %install
 mkdir -p %{buildroot}/lib/modules/%{KERNELRELEASE}
 cp $(%{make} %{makeflags} -s image_name) %{buildroot}/lib/modules/%{KERNELRELEASE}/vmlinuz
 # DEPMOD=true makes depmod no-op. We do not package depmod-generated files.
 %{make} %{makeflags} INSTALL_MOD_PATH=%{buildroot} DEPMOD=true modules_install
+%if %{with_ctf}
+%{make} %{makeflags} INSTALL_MOD_PATH=%{buildroot} ctf_install
+%endif
 %{make} %{makeflags} INSTALL_HDR_PATH=%{buildroot}/usr headers_install
 cp System.map %{buildroot}/lib/modules/%{KERNELRELEASE}
 cp .config %{buildroot}/lib/modules/%{KERNELRELEASE}/config
scripts/package/mkspec +5 -0
index 4dc1466dfc81..ddbdefbc538b 100755
@@ -23,6 +23,11 @@ else
 echo '%define with_devel 0'
 fi
 
+if grep -q CONFIG_CTF=y include/config/auto.conf; then
+echo '%define with_ctf %{?_without_ctf: 0} %{?!_without_ctf: 1}'
+else
+echo '%define with_ctf 0'
+fi
 cat<<EOF
 %define ARCH ${ARCH}
 %define KERNELRELEASE ${KERNELRELEASE}
scripts/remove-ctf-lds.awk new file +12 -0
new file mode 100644
index 000000000000..5d94d6ee9922
@@ -0,0 +1,12 @@
+# SPDX-License-Identifier: GPL-2.0
+# See Makefile.vmlinux_o
+
+BEGIN {
+    discards = 0; p = 0
+}
+
+/^====/ { p = 1; next; }
+p && /\.ctf/ { next; }
+p && !discards && /DISCARD/ { sub(/\} *$/, " *(.ctf) }"); discards = 1 }
+p && /^\}/ && !discards { print "  /DISCARD/ : { *(.ctf) }"; }
+p { print $0; }
Signature · 1 line
2.46.0.278.g36e3a12567
#2 lore raw

PATCH v2 2/2 ctf: work around binutils bug in ctf_link_add_cu_mapping()

In reply to Nick Alcock

All binutilses to date have a bug in ctf_link_add_cu_mapping(), which we use to cause multi-object-file modules (including the core vmlinux itself) to be represented as one great big child CTF dict rather than one dict per translation unit. The idea is that you can call it repeatedly with different object file -> child dict name mappings, and the last with a given object file name takes precedence: but instead inconsistent and unhelpful things happen, and usually the net effect is to end up with most built-in modules empty, and their contents emptied into vmlinux instead.

Fix this by adding a crude hash table to ctfarchive which accumulates calls to ctf_link_add_cu_mapping() and keeps only the last one seen for any given FROM.

The fact that we need to *implement* a hash table means that this adds almost a third to the total bulk of ctfarchive.c, none of which would be necessary if we could rely on a fixed binutils. But we won't be able to do that for a while...

Orabug: 29891866

---
 scripts/ctf/ctfarchive.c | 106 +++++++++++++++++++++++++++++++++++++--
 1 file changed, 102 insertions(+), 4 deletions(-)
scripts/ctf/ctfarchive.c +102 -4
index a852856ee676..eac15b5b707b 100644
@@ -47,6 +47,100 @@ static void add_to_link(const char *fn)
 	}
 }
 
+struct from_to
+{
+	char *from;
+	char *to;
+};
+
+/*
+ * The world's stupidest hash table of FROM -> TO.
+ */
+static struct from_to **from_tos[256];
+static size_t alloc_from_tos[256];
+static size_t num_from_tos[256];
+
+static unsigned char from_to_hash(const char *from)
+{
+	unsigned char hval = 0;
+
+	const char *p;
+	for (p = from; *p; p++)
+		hval += *p;
+
+	return hval;
+}
+
+/*
+ * Note that we will need to add a CU mapping later on.
+ *
+ * Present purely to work around a binutils bug that stops
+ * ctf_link_add_cu_mapping() working right when called repeatedly
+ * with the same FROM.
+ */
+static int add_cu_mapping(const char *from, const char *to)
+{
+	ssize_t i, j;
+
+	i = from_to_hash(from);
+
+	for (j = 0; j < num_from_tos[i]; j++)
+		if (strcmp(from, from_tos[i][j]->from) == 0) {
+			char *tmp;
+
+			free(from_tos[i][j]->to);
+			tmp = strdup(to);
+			if (!tmp)
+				goto oom;
+			from_tos[i][j]->to = tmp;
+			return 0;
+		    }
+
+	if (num_from_tos[i] >= alloc_from_tos[i]) {
+		struct from_to **tmp;
+		if (alloc_from_tos[i] < 16)
+			alloc_from_tos[i] = 16;
+		else
+			alloc_from_tos[i] *= 2;
+
+		tmp = realloc(from_tos[i], alloc_from_tos[i] * sizeof(struct from_to *));
+		if (!tmp)
+			goto oom;
+
+		from_tos[i] = tmp;
+	}
+
+	j = num_from_tos[i];
+	from_tos[i][j] = malloc(sizeof(struct from_to));
+	if (from_tos[i][j] == NULL)
+		goto oom;
+	from_tos[i][j]->from = strdup(from);
+	from_tos[i][j]->to = strdup(to);
+	if (!from_tos[i][j]->from || !from_tos[i][j]->to)
+		goto oom;
+	num_from_tos[i]++;
+
+	return 0;
+  oom:
+	fprintf(stderr,
+		"out of memory in add_cu_mapping\n");
+	exit(1);
+}
+
+/*
+ * Finally tell binutils to add all the CU mappings, with duplicate FROMs
+ * replaced with the most recent one.
+ */
+static void commit_cu_mappings(void)
+{
+	ssize_t i, j;
+
+	for (i = 0; i < 256; i++)
+		for (j = 0; j < num_from_tos[i]; j++)
+			ctf_link_add_cu_mapping(output, from_tos[i][j]->from,
+						from_tos[i][j]->to);
+}
+
 /*
  * Add a CU mapping to the link.
  *
@@ -88,7 +182,7 @@ static void add_cu_mappings(const char *fn)
 
 		n -= strlen(".ko.ctf");
 		mod = strndup(modname, n);
-		ctf_link_add_cu_mapping(output, fn, mod);
+		add_cu_mapping(fn, mod);
 		free(mod);
 	}
 	free(dynmodname);
@@ -99,7 +193,7 @@ static void add_cu_mappings(const char *fn)
  */
 static void add_builtins(const char *fn)
 {
-	if (ctf_link_add_cu_mapping(output, fn, "vmlinux") < 0)
+	if (add_cu_mapping(fn, "vmlinux") < 0)
 	{
 		fprintf(stderr, "Cannot add CTF CU mapping from %s to \"vmlinux\"\n",
 			ctf_errmsg(ctf_errno(output)));
@@ -164,8 +258,7 @@ static void suck_in_modules(const char *module_objnames_name)
 		size_t j;
 
 		for (j = 0; paths[j] != NULL; j++) {
-			if (ctf_link_add_cu_mapping(output, paths[j],
-						    module_name) < 0) {
+			if (add_cu_mapping(paths[j], module_name) < 0) {
 				fprintf(stderr, "Cannot add path -> module mapping for "
 					"%s -> %s: %s\n", paths[j], module_name,
 					ctf_errmsg(ctf_errno(output)));
@@ -248,6 +341,11 @@ int main(int argc, char *argv[])
 	 */
 	suck_in_modules(argv[3]);
 
+	/*
+	 * Commit the added CU mappings.
+	 */
+	commit_cu_mappings();
+
 	/*
 	 * Arrange to fix up the module names.
 	 */
Signature · 1 line
2.46.0.278.g36e3a12567
#3 lore raw

Re: [PATCH v2 2/2] ctf: work around binutils bug in ctf_link_add_cu_mapping()

On 1 Oct 2024, Nick Alcock told this:

Quoted 4 lines

The fact that we need to *implement* a hash table means that this adds almost a third to the total bulk of ctfarchive.c, none of which would be necessary if we could rely on a fixed binutils. But we won't be able to do that for a while...

"A while" has become less extreme, since when we move to CTFv4/BTF-in-toolchain building, we'll have to bump the required binutils version anyway.

So btfarchive will not have this horrible patch in it. :)

Signature · 1 line
NULL && (void)