Skip to contentSkip to conversation

kallsyms: reliable symbol->address lookup with /proc/kallmodsyms

PATCH Superseded Nick Alcock 3 participants 33 messages Nov 9, 2022 – Nov 21, 2022

Subsystems (5)

v9 of 10 Superseded Latest is v10 →

lore
Share & tools
lore
#0 lore raw

PATCH v9 1/1 kallsyms: reliable symbol->address lookup with /proc/kallmodsyms

The kallmodsyms patch series was originally posted in Nov 2019, and the thread
(https://lore.kernel.org/linux-kbuild/[email protected]/t/#u)
shows review comments, questions, and feedback from interested parties.

All review comments have been satisfied, as far as I know: in particular Yamada's note about translation units that are shared between built-in modules is satisfied with a better representation which is also much, much smaller.

A kernel tree containing this series alone:
https://github.com/oracle/dtrace-linux-kernel kallmodsyms/6.1-rc4

The whole point of symbols is that their names are unique: you can look up a symbol and get back a unique address, and vice versa. Alas, because /proc/kallsyms (rightly) reports all symbols, even hidden ones, it does not really satisfy this requirement. Large numbers of symbols are duplicated many times (just search for __list_del_entry!), and while usually these are just out-of-lined things defined in header files and thus all have the same implementation, it does make it needlessly hard to figure out which one is which in stack dumps, when tracing, and such things. Right now the kernel has no way at all to tell these apart, and nor has the user: their address differs and that's all. Which module did they come from? Which object file? We don't know. Figuring out which is which when tracing needs a combination of guesswork and luck. In discussions at LPC it became clear that this is not just annoying me but Steve Rostedt and others, so it's probably desirable to fix this.

It turns out that the linker, and the kernel build system, can be made to give us everything we need to resolve this once and for all. This series provides a new /proc/kallmodsyms which is like /proc/kallsyms except that it annotates every (textual) symbol which comes from a built-in kernel module with the module's name, in square brackets: if a symbol is used by multiple modules, it gets [multiple] [names]. (We also add corresponding new fields in the kallsyms iterator.)

But that's not quite enough: some symbols are still ambiguous, particularly those that appear in the non-modular parts of the core kernel but also some things that appear in built-in modules. We annotate such symbols with cut-down {object file} names: the combination of symbol, [module] [names] and {object file name} is unique. (The object file names are cut down to save space: we store only the shortest suffix needed to distinguish symbols from each other. It's fairly rare even to see two/level names, let alone three/level/ones. We also save even more space by annotating every symbol in a given object file with the object file name if we annotate any of them.)

In brief we do this by mapping from address ranges to object files (with assistance from the linker map file), then mapping from those object files to built-in kernel modules and object file names. Because the number of object files is much smaller than the number of symbols, because we fuse address range and object file entries together if possible, and becasue we don't even store object file names unless we need to, this is a fairly efficient representation, even with a bit of extra complexity to allow object files to be in more than one module at once.

The size impact of all of this is minimal: in testing, vmlinux grew by 16632 bytes, and the compressed vmlinux only grew by 12544 bytes (about .1% of a 10MiB kernel): though this is very configuration-dependent, it seems likely to scale roughly with the kernel as a whole.

This is all controlled by a new config parameter CONFIG_KALLMODSYMS, which when set results in output in /proc/kallmodsyms that looks like this:

ffffffff97606e50 t not_visible
ffffffff97606e70 T perf_msr_probe
ffffffff97606f80 t test_msr [rapl]

ffffffffa6007350 t rapl_pmu_event_stop  [rapl]
ffffffffa6007440 t rapl_pmu_event_del   [rapl]
ffffffffa6007460 t rapl_hrtimer_handle  [rapl]
ffffffffa6007500 t rapl_pmu_event_read  [rapl]
ffffffffa6007520 t rapl_pmu_event_init  [rapl]
ffffffffa6007630 t rapl_cpu_offline     [rapl]
ffffffffa6007710 t amd_pmu_event_map    {core.o}
ffffffffa6007750 t amd_pmu_add_event    {core.o}

ffffffffa6007760 t amd_put_event_constraints_f17h {core.o}

The modular symbols are notated as [rapl] even if rapl is built into the kernel. Further, at least one symbol nottated as {core.o} would have been ambiguous without that notation. If we look a little further down, we see:

ffffffff97607a70 t cmask_show   {core.o}
ffffffff97607ab0 t inv_show     {core.o}
ffffffff97607ae0 t edge_show    {core.o}
ffffffff97607b10 t umask_show   {core.o}
ffffffff97607b40 t event_show   {core.o}

where event_show in particular is highly ambiguous and appears in many object files, all of which are now notated with different {object file names}.

Further down, we see what happens when object files are reused by multiple modules, all of which are built in to the kernel, and some of which contain symbols that are ambiguously-named even within that set of modules:

ffffffff97d7aed0 t liquidio_pcie_mmio_enabled [liquidio]
ffffffff97d7aef0 t liquidio_pcie_resume [liquidio] ffffffff97d7af00 t liquidio_ptp_adjtime [liquidio] ffffffff97d7af50 t liquidio_ptp_enable [liquidio] ffffffff97d7af70 t liquidio_get_stats64 [liquidio]
ffffffff97d7b0f0 t liquidio_fix_features [liquidio]
ffffffff97d7b1c0 t liquidio_get_port_parent_id [liquidio] [...]
ffffffff97d824c0 t lio_vf_rep_modinit [liquidio]
ffffffff97d824f0 t lio_vf_rep_modexit [liquidio]
ffffffff97d82520 t lio_ethtool_get_channels [liquidio] [liquidio_vf]
ffffffff97d82600 t lio_ethtool_get_ringparam [liquidio] [liquidio_vf]

ffffffff97d826a0 t lio_get_msglevel     [liquidio] [liquidio_vf]
ffffffff97d826c0 t lio_vf_set_msglevel  [liquidio] [liquidio_vf]
ffffffff97d826e0 t lio_get_pauseparam   [liquidio] [liquidio_vf]

ffffffff97d82710 t lio_get_ethtool_stats [liquidio] [liquidio_vf]
ffffffff97d82e70 t lio_vf_get_ethtool_stats [liquidio] [liquidio_vf]
[...]
ffffffff97d91a80 t cn23xx_vf_mbox_thread [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d91aa0 t cpumask_weight.constprop.0 [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d91ac0 t cn23xx_vf_msix_interrupt_handler [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d91bd0 t cn23xx_vf_get_oq_ticks [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d91c00 t cn23xx_vf_ask_pf_to_do_flr [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d91c70 t cn23xx_octeon_pfvf_handshake [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d91e20 t cn23xx_setup_octeon_vf_device [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d92060 t octeon_mbox_read [liquidio] [liquidio_vf]
ffffffff97d92230 t octeon_mbox_write [liquidio] [liquidio_vf]
[...]
ffffffff97d946b0 t octeon_alloc_soft_command_resp [liquidio] [liquidio_vf]
ffffffff97d947e0 t octnet_send_nic_data_pkt [liquidio] [liquidio_vf]
ffffffff97d94820 t octnet_send_nic_ctrl_pkt [liquidio] [liquidio_vf]
ffffffff97d94ab0 t liquidio_get_stats64 [liquidio_vf]
ffffffff97d94c10 t liquidio_fix_features [liquidio_vf]
ffffffff97d94cd0 t wait_for_pending_requests [liquidio_vf]

Like /proc/kallsyms, the output is sorted by address, so keeps the curious property of /proc/kallsyms that symbols may appear repeatedly with different
addresses: but now, unlike in /proc/kallsyms, we can see that those symbols appear repeatedly because they are *different symbols* that ultimately belong to different modules or different object files, all of which are built in to the kernel.

Note that kernel symbols for built-in modules will probably appear interspersed with other symbols that are part of different modules and non-modular always-built-in symbols, which, as usual, have no square-bracketed module denotation (though they might have an {object file name}.

As with /proc/kallsyms, non-root usage produces addresses that are all zero.

(Now that kallmodsyms data uses very little space, the new CONFIG_KALLMODSYMS option might perhaps be something people don't want to bother with: maybe we can just control it via CONFIG_KALLSYMS or something?)

Limitations:

- this approach only works for textual symbols (and weak ones). I don't see any way to make it work for data symbols etc: except for initialized data they don't really have corresponding object files at all and they tend to get merged together anyway.

- Non-built-in modules can also have ambiguous symbols in them in different input object files: they aren't handled yet because kallsyms never runs over modules to create the necessary sections. This is fixable, but it's probably best handled in another patch series. (kallsyms would need to do much less work for modules: only the sections introduced by this patch series would need emission at all, and no [module] notations would be needed, only {objfile}.)

- Section start/end symbols necessarily lie on the boundary between object files, so are sometimes misreported as being in the wrong object file or module. This is unlikely to be too troublesome for these symbols in particular, but if anyone can figure out a way to fix this I'd be happy to do it.

- There is no BPF iterator support yet (it's just a matter of adding it if needed).

The commits in this series all have reviewed-by tags: they're all from internal reviews, so please ignore them.

Differences from v8, February 2022:

- Add object file name handling, emitting only those object names needed to disambiguate symbols, shortening them as much as possible compatible with that.
- Rename .kallsyms_module_names to .kallsyms_mod_objnames now that it contains object file names too.
- Fix a bug in optimize_obj2mod that prevented proper reuse of module names for object files appearing in both multimodule modules and single-module
modules: saves a few KiB more, often more than the space increase due to object file name handling.
- Rebased atop v6.1-rc2: move modules_thick.builtin generation into the top-level Kbuild accordingly, and adjust to getopt_long use in scripts/kallsyms.
- Significant revisions to the cover letter.
- Add proof-of-concept kallmodsyms module support to perf.
- (This ping) confirmed that series applies atop v6.1-rc4 without further changes.

Differences from v7, December 2021:

- Adjust for changes in the v5.17 merge window. Adjust a few commit messages and shrink the cover letter.
- Drop the symbol-size patch, probably better done from userspace.

Differences from v6, November 2021:

- Adjust for rewrite of confdata machinery in v5.16 (tristate.conf handling is now more of a rewrite than a reversion)

Differences from v5, October 2021:

- Fix generation of mapfiles under UML

Differences from v4, September 2021:

- Fix building of tristate.conf if missing (usually concealed by the syncconfig being run for other reasons, but not always: the kernel test robot spotted it).
- Forward-port atop v5.15-rc3.

Differences from v3, August 2021:

- Fix a kernel test robot warning in get_ksymbol_core (possible use of uninitialized variable if kallmodsyms was wanted but kallsyms_module_offsets was not present, which is most unlikely).

Differences from v2, June 2021:

- Split the series up. In particular, the size impact of the table optimizer is now quantified, and the symbol-size patch is split out and turned into an RFC patch, with the /proc/kallmodsyms format before that patch lacking a size column. Some speculation on how to make the symbol sizes less space-wasteful is added (but not yet implemented).

- Drop a couple of unnecessary #includes, one unnecessarily exported symbol, and a needless de-staticing.

Differences from v1, in 2019:

- Move from a straight symbol->module name mapping to a mapping from address-range to TU to module name list, bringing major space savings over the previous approach and support for object files used by many built-in modules at the same time, at the cost of a slightly more complex approach (unavoidably so, I think, given that we have to merge three data sources together: the link map in .tmp_vmlinux.ranges, the nm output on stdin, and the mapping from TU name to module names in modules_thick.builtin).

We do opportunistic merging of TUs if they cite the same modules and reuse module names where doing so is simple: see optimize_obj2mod below. I considered more extensive searches for mergeable entries and more intricate encodings of the module name list allowing TUs that are used by overlapping sets of modules to share their names, but such modules are rare enough (and such overlapping sharings are vanishingly rare) that it seemed likely to save only a few bytes at the cost of much more hard-to-test code. This is doubly true now that the tables needed are only a few kilobytes in length.

Nick Alcock (8):
kbuild: bring back tristate.conf
kbuild: add modules_thick.builtin
kbuild: generate an address ranges map at vmlinux link time
kallsyms: introduce sections needed to map symbols to built-in modules
kallsyms: optimize .kallsyms_modules*
kallsyms: distinguish text symbols fully using object file names
kallsyms: add /proc/kallmodsyms for text symbol disambiguation
perf: proof-of-concept kallmodsyms support

 .gitignore                       |    1 +
 Documentation/dontdiff           |    1 +
 Documentation/kbuild/kconfig.rst |    5 +
 Kbuild                           |   22 +
 Makefile                         |    9 +-
 init/Kconfig                     |    9 +
 kernel/kallsyms.c                |  277 ++++++-
 kernel/kallsyms_internal.h       |   14 +
 scripts/Kbuild.include           |    6 +
 scripts/Makefile                 |    6 +
 scripts/Makefile.modbuiltin      |   56 ++
 scripts/kallsyms.c               | 1187 +++++++++++++++++++++++++++++-
 scripts/kconfig/confdata.c       |   41 +-
 scripts/link-vmlinux.sh          |   15 +-
 scripts/modules_thick.c          |  200 +++++
 scripts/modules_thick.h          |   48 ++
 tools/perf/builtin-kallsyms.c    |   35 +-
 tools/perf/util/event.c          |   14 +-
 tools/perf/util/machine.c        |    6 +-
 tools/perf/util/machine.h        |    1 +
 tools/perf/util/symbol.c         |  207 ++++--
 tools/perf/util/symbol.h         |   12 +-
 22 files changed, 2073 insertions(+), 99 deletions(-)
 create mode 100644 scripts/Makefile.modbuiltin
 create mode 100644 scripts/modules_thick.c
 create mode 100644 scripts/modules_thick.h
Signature · 1 line
2.38.0.266.g481848f278
#1 lore raw

PATCH v9 1/8 kbuild: bring back tristate.conf

tristate.conf was dropped because it is not needed to build a modules.builtin (although dropping it introduces a few false positives into modules.builtin support), and doing so avoids one round of recursion through the build tree to build it. But kallmodsyms support requires building a mapping from object file name to built-in module name for all builtin modules: this seems to me impossible to accomplish without parsing all makefiles under the influence of tristate.conf, since the makefiles are the only place this mapping is recorded.

So bring it back for this purpose. (Thanks to the refactoring in the 5.16 timeframe, this is basically a reimplementation of commit 8b41fc4454e36fbfdbb23f940d023d4dece2de29 rather than a simple reversion.)

---

Notes:
v7: rewrite in terms of the new confdata refactoring
v8: adjust for changes in 5.17 merge window

 Documentation/kbuild/kconfig.rst |  5 ++++
 Makefile                         |  2 +-
 scripts/kconfig/confdata.c       | 41 +++++++++++++++++++++++++++-----
 3 files changed, 41 insertions(+), 7 deletions(-)
Documentation/kbuild/kconfig.rst +5 -0
index 5967c79c3baa..e2c78760d442 100644
@@ -162,6 +162,11 @@ KCONFIG_AUTOCONFIG
 This environment variable can be set to specify the path & name of the
 "auto.conf" file.  Its default value is "include/config/auto.conf".
 
+KCONFIG_TRISTATE
+----------------
+This environment variable can be set to specify the path & name of the
+"tristate.conf" file.  Its default value is "include/config/tristate.conf".
+
 KCONFIG_AUTOHEADER
 ------------------
 This environment variable can be set to specify the path & name of the
Makefile +1 -1
index d148a55bfd0f..5d26447fecb8 100644
@@ -793,7 +793,7 @@ $(KCONFIG_CONFIG):
 #
 # Do not use $(call cmd,...) here. That would suppress prompts from syncconfig,
 # so you cannot notice that Kconfig is waiting for the user input.
-%/config/auto.conf %/config/auto.conf.cmd %/generated/autoconf.h %/generated/rustc_cfg: $(KCONFIG_CONFIG)
+%/config/auto.conf %/config/auto.conf.cmd %/generated/autoconf.h %/generated/rustc_cfg %/tristate.conf: $(KCONFIG_CONFIG)
 	$(Q)$(kecho) "  SYNC    $@"
 	$(Q)$(MAKE) -f $(srctree)/Makefile syncconfig
 else # !may-sync-config
scripts/kconfig/confdata.c +35 -6

90 lines not on this page · raw message

Signature · 1 line
2.38.0.266.g481848f278
maintainer
#2 lore raw

Re: [PATCH v9 1/8] kbuild: bring back tristate.conf

Quoted 9 lines · Nick Alcock

tristate.conf was dropped because it is not needed to build a modules.builtin (although dropping it introduces a few false positives into modules.builtin support), and doing so avoids one round of recursion through the build tree to build it. But kallmodsyms support requires building a mapping from object file name to built-in module name for all builtin modules: this seems to me impossible to accomplish without parsing all makefiles under the influence of tristate.conf, since the makefiles are the only place this mapping is recorded.

Quoted 8 lines

So bring it back for this purpose. (Thanks to the refactoring in the 5.16 timeframe, this is basically a reimplementation of commit 8b41fc4454e36fbfdbb23f940d023d4dece2de29 rather than a simple reversion.)

I don't see the need, see the review of next patch.

Luis

#3 lore raw

PATCH v9 2/8 kbuild: add modules_thick.builtin

In reply to Nick Alcock

This is similar to modules.builtin, and constructed in a similar way to the way that used to be built before commit 8b41fc4454e36fbfdbb23f940d023d4dece2de29, via tristate.conf inclusion and recursive concatenation up the tree. Unlike modules.builtin, modules_thick.builtin gives the names of the object files that make up modules that are comprised of more than one object file, using a syntax similar to that of makefiles, e.g.:

crypto/crypto.o: crypto/api.o crypto/cipher.o crypto/compress.o crypto/memneq.o crypto/crypto_algapi.o: crypto/algapi.o crypto/proc.o crypto/scatterwalk.o crypto/aead.o:
crypto/geniv.o:

(where the latter two are single-file modules).

An upcoming commit will use this mapping to populate /proc/kallmodsyms.

A parser is included that yields a stram of (module, objfile name[])
mappings: it's a bit baroque, but then parsing text files in C is quite painful, and I'd rather put the complexity in here than in its callers. The parser is not built in this commit, nor does it have any callers yet; nor is any rule added that causes modules_thick.builtin to actually be constructed. (Again, see a later commit for that.)

I am not wedded to the approach used to construct this file, but I don't see any other way to do it despite spending a week or so trying to tie it into Kbuild without using a separate Makefile.modbuiltin: unlike the names of builtin modules (which are also recorded in the source files themseves via MODULE_*() macros) the mapping from object file name to built-in module name is not recorded anywhere but in the makefiles themselves, so we have to at least reparse them with something to indicate the builtin-ness of each module (i.e., tristate.conf) if we are to figure out which modules are built-in and which are not.

---

Notes:
v9: move modules_thick.builtin generation into the top-level Kbuild

 .gitignore                  |   1 +
 Documentation/dontdiff      |   1 +
 Kbuild                      |  16 +++
 Makefile                    |   2 +-
 scripts/Kbuild.include      |   6 ++
 scripts/Makefile.modbuiltin |  56 ++++++++++
 scripts/modules_thick.c     | 200 ++++++++++++++++++++++++++++++++++++
 scripts/modules_thick.h     |  48 +++++++++
 8 files changed, 329 insertions(+), 1 deletion(-)
 create mode 100644 scripts/Makefile.modbuiltin
 create mode 100644 scripts/modules_thick.c
 create mode 100644 scripts/modules_thick.h
.gitignore +1 -0
index 5da004814678..f129bf52cbd4 100644
@@ -52,6 +52,7 @@
 *.zst
 Module.symvers
 modules.order
+modules_thick.builtin
 
 #
 # Top-level generic files
Documentation/dontdiff +1 -0
index 352ff53a2306..077d43b9675d 100644
@@ -183,6 +183,7 @@ modules.builtin
 modules.builtin.modinfo
 modules.nsdeps
 modules.order
+modules_thick.builtin
 modversions.h*
 nconf
 nconf-cfg
Kbuild +16 -0
index 464b34a08f51..a84e8312c174 100644
@@ -97,3 +97,19 @@ obj-$(CONFIG_SAMPLES)	+= samples/
 obj-$(CONFIG_NET)	+= net/
 obj-y			+= virt/
 obj-y			+= $(ARCH_DRIVERS)
+
+# Generate modules_thick.builtin if needed.
+#
+# modules_thick.builtin maps from kernel modules (or rather the object file
+# names they would have had had they not been built in) to their constituent
+# object files: we can use this to determine which modules any given object
+# file is part of.  (We cannot eliminate the slight redundancy here without
+# double-expansion.)
+
+modthickbuiltin-files := $(addsuffix modules_thick.builtin, $(filter %/,$(obj-y)))
+
+$(modthickbuiltin-files): include/config/tristate.conf
+	$(Q)$(MAKE) $(modbuiltin)=$(patsubst %/modules_thick.builtin,%,$@) builtin-file=modules_thick.builtin
+
+modules_thick.builtin: $(modthickbuiltin-files) $(obj-y)
+	$(Q)$(AWK) '!x[$$0]++' $(patsubst %/built-in.a, %/$@, $(filter %/built-in.a,$(obj-y))) > $@
Makefile +1 -1
index 5d26447fecb8..21117f9d4202 100644
@@ -2008,7 +2008,7 @@ clean: $(clean-dirs)
 		-o -name '*.lex.c' -o -name '*.tab.[ch]' \
 		-o -name '*.asn1.[ch]' \
 		-o -name '*.symtypes' -o -name 'modules.order' \
-		-o -name '.tmp_*' \
+		-o -name '.tmp_*' -o -name modules_thick.builtin \
 		-o -name '*.c.[012]*.*' \
 		-o -name '*.ll' \
 		-o -name '*.gcno' \
scripts/Kbuild.include +6 -0
index 2bc08ace38a3..28d5eb7a9b61 100644
@@ -78,6 +78,12 @@ endef
 # $(Q)$(MAKE) $(build)=dir
 build := -f $(srctree)/scripts/Makefile.build obj
 
+###
+# Shorthand for $(Q)$(MAKE) -f scripts/Makefile.modbuiltin obj=
+# Usage:
+# $(Q)$(MAKE) $(modbuiltin)=dir
+modbuiltin := -f $(srctree)/scripts/Makefile.modbuiltin obj
+
 ###
 # Shorthand for $(Q)$(MAKE) -f scripts/Makefile.dtbinst obj=
 # Usage:
scripts/Makefile.modbuiltin new file +56 -0

56 lines not on this page · raw message

scripts/modules_thick.c new file +200 -0

200 lines not on this page · raw message

scripts/modules_thick.h new file +48 -0

48 lines not on this page · raw message

Signature · 1 line
2.38.0.266.g481848f278
maintainer
#4 lore raw

Re: [PATCH v9 2/8] kbuild: add modules_thick.builtin

Quoted 9 lines · Nick Alcock

I am not wedded to the approach used to construct this file, but I don't see any other way to do it despite spending a week or so trying to tie it into Kbuild without using a separate Makefile.modbuiltin: unlike the names of builtin modules (which are also recorded in the source files themseves via MODULE_*() macros) the mapping from object file name to built-in module name is not recorded anywhere but in the makefiles themselves, so we have to at least reparse them with something to indicate the builtin-ness of each module (i.e., tristate.conf) if we are to figure out which modules are built-in and which are not.

Please try this patch, unless I am not understanding perhaps we may be able to replace the first two patches with this one? It also seems to capture a bit more data than the modules_thick.builtin file.

From 3e5ce9141c25fd4eb23b5423d9aa9f1c4ebe4e8e Mon Sep 17 00:00:00 2001
From: Luis Chamberlain <[email protected]>
Date: Wed, 9 Nov 2022 17:58:57 -0800
Subject: [PATCH] kbuild: add modules.builtin.objs

The file modules.builtin contains all modules that are built into the kernel and this is used by modprobe to not fail when trying to load something builtin. But for tools which want to see which object files come from what modules we want to help them with such a mapping as it is not easy to get this otherwise.

We do this by just extending scripts/Makefile.lib with a new variable and define to capture all possible objects, and stuff this into a new modinfo.

Note that this doesn't bloat the kernel as all because as you can see in include/asm-generic/vmlinux.lds.h, the .modinfo section is discarded at the link stage.

---
 .gitignore                      |  2 +-
 Documentation/dontdiff          |  2 +-
 Documentation/kbuild/kbuild.rst |  5 +++++
 Makefile                        | 10 +++++++---
 include/linux/module.h          |  4 +++-
 scripts/Makefile.lib            |  5 ++++-
 scripts/Makefile.vmlinux_o      | 15 ++++++++++++++-
 7 files changed, 35 insertions(+), 8 deletions(-)
.gitignore +1 -1
index 5da004814678..ef8665c64f21 100644
@@ -67,7 +67,7 @@ modules.order
 /System.map
 /Module.markers
 /modules.builtin
-/modules.builtin.modinfo
+/modules.builtin.*
 /modules.nsdeps
 
 #
Documentation/dontdiff +1 -1
index 352ff53a2306..ed1fbc711f33 100644
@@ -180,7 +180,7 @@ mkutf8data
 modpost
 modules-only.symvers
 modules.builtin
-modules.builtin.modinfo
+modules.builtin.*
 modules.nsdeps
 modules.order
 modversions.h*
Documentation/kbuild/kbuild.rst +5 -0
index 08f575e6236c..504f31517cb4 100644
@@ -17,6 +17,11 @@ modules.builtin
 This file lists all modules that are built into the kernel. This is used
 by modprobe to not fail when trying to load something builtin.
 
+modules.builtin.objs
+-----------------------
+This file contains object mapping of modules that are built into the kernel
+to their corresponding object files used to build the module.
+
 modules.builtin.modinfo
 -----------------------
 This file contains modinfo from all modules that are built into the kernel.
Makefile +7 -3
index d148a55bfd0f..cd563d9713c9 100644
@@ -1228,7 +1228,11 @@ PHONY += vmlinux_o
 vmlinux_o: vmlinux.a $(KBUILD_VMLINUX_LIBS)
 	$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.vmlinux_o
 
-vmlinux.o modules.builtin.modinfo modules.builtin: vmlinux_o
+MODULES_BUILTIN := modules.builtin.modinfo
+MODULES_BUILTIN += modules.builtin
+MODULES_BUILTIN += modules.builtin.objs
+
+vmlinux.o $(MODULES_BUILTIN): vmlinux_o
 	@:
 
 PHONY += vmlinux
@@ -1558,7 +1562,7 @@ __modinst_pre:
 	fi
 	@sed 's:^:kernel/:' modules.order > $(MODLIB)/modules.order
 	@cp -f modules.builtin $(MODLIB)/
-	@cp -f $(objtree)/modules.builtin.modinfo $(MODLIB)/
+	@cp -f $(objtree)/modules.builtin.* $(MODLIB)/
 
 endif # CONFIG_MODULES
 
@@ -1571,7 +1575,7 @@ endif # CONFIG_MODULES
 
 # Directories & files removed with 'make clean'
 CLEAN_FILES += include/ksym vmlinux.symvers modules-only.symvers \
-	       modules.builtin modules.builtin.modinfo modules.nsdeps \
+	       modules.builtin modules.builtin.* modules.nsdeps \
 	       compile_commands.json .thinlto-cache rust/test rust/doc \
 	       .vmlinux.objs .vmlinux.export.c
 
include/linux/module.h +3 -1
index ec61fb53979a..ce044cffd43d 100644
@@ -179,7 +179,9 @@ extern void cleanup_module(void);
 #ifdef MODULE
 #define MODULE_FILE
 #else
-#define MODULE_FILE	MODULE_INFO(file, KBUILD_MODFILE);
+#define MODULE_FILE					                      \
+			MODULE_INFO(file, KBUILD_MODFILE);                    \
+			MODULE_INFO(objs, KBUILD_MODOBJS);
 #endif
 
 /*
scripts/Makefile.lib +4 -1
index 3aa384cec76b..f7e5a83572fa 100644
@@ -112,6 +112,8 @@ modname-multi = $(sort $(foreach m,$(multi-obj-ym),\
 __modname = $(or $(modname-multi),$(basetarget))
 
 modname = $(subst $(space),:,$(__modname))
+modname-objs = $($(modname)-objs) $($(modname)-y) $($(modname)-Y)
+modname-objs-prefixed = $(sort $(strip $(addprefix $(obj)/, $(modname-objs))))
 modfile = $(addprefix $(obj)/,$(__modname))
 
 # target with $(obj)/ and its suffix stripped
@@ -125,7 +127,8 @@ name-fix = $(call stringify,$(call name-fix-token,$1))
 basename_flags = -DKBUILD_BASENAME=$(call name-fix,$(basetarget))
 modname_flags  = -DKBUILD_MODNAME=$(call name-fix,$(modname)) \
 		 -D__KBUILD_MODNAME=kmod_$(call name-fix-token,$(modname))
-modfile_flags  = -DKBUILD_MODFILE=$(call stringify,$(modfile))
+modfile_flags  = -DKBUILD_MODFILE=$(call stringify,$(modfile)) \
+                 -DKBUILD_MODOBJS=$(call stringify,$(modfile).o:$(subst $(space),|,$(modname-objs-prefixed)))
 
 _c_flags       = $(filter-out $(CFLAGS_REMOVE_$(target-stem).o), \
                      $(filter-out $(ccflags-remove-y), \
scripts/Makefile.vmlinux_o +14 -1
index 0edfdb40364b..9b4ca83f0695 100644
@@ -1,7 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0-only
 
 PHONY := __default
-__default: vmlinux.o modules.builtin.modinfo modules.builtin
+__default: vmlinux.o modules.builtin.modinfo modules.builtin modules.builtin.objs
 
 include include/config/auto.conf
 include $(srctree)/scripts/Kbuild.include
@@ -86,6 +86,19 @@ targets += modules.builtin
 modules.builtin: modules.builtin.modinfo FORCE
 	$(call if_changed,modules_builtin)
 
+# module.builtin.objs
+# ---------------------------------------------------------------------------
+quiet_cmd_modules_builtin_objs = GEN     $@
+      cmd_modules_builtin_objs = \
+	tr '\0' '\n' < $< | \
+	sed -n 's/^[[:alnum:]:_]*\.objs=//p' | \
+	tr ' ' '\n' | uniq | sed -e 's|:|: |' -e 's:|: :g' | \
+	tr -s ' ' > $@
+
+targets += modules.builtin.objs
+modules.builtin.objs: modules.builtin.modinfo FORCE
+	$(call if_changed,modules_builtin_objs)
+
 # Add FORCE to the prequisites of a target to force it to be always rebuilt.
 # ---------------------------------------------------------------------------
 
Signature · 1 line
2.35.1
#5 lore raw

Re: [PATCH v9 2/8] kbuild: add modules_thick.builtin

On 10 Nov 2022, Luis Chamberlain uttered the following:

Quoted 11 lines · Nick Alcock
Quoted 9 lines

I am not wedded to the approach used to construct this file, but I don't see any other way to do it despite spending a week or so trying to tie it into Kbuild without using a separate Makefile.modbuiltin: unlike the names of builtin modules (which are also recorded in the source files themseves via MODULE_*() macros) the mapping from object file name to built-in module name is not recorded anywhere but in the makefiles themselves, so we have to at least reparse them with something to indicate the builtin-ness of each module (i.e., tristate.conf) if we are to figure out which modules are built-in and which are not.

Quoted 3 lines

Please try this patch, unless I am not understanding perhaps we may be able to replace the first two patches with this one? It also seems to capture a bit more data than the modules_thick.builtin file.

Oh thank you! At first sight this looks really good. I had trouble believing it could be that much simpler :)

...

But... it's not quite doing the same thing, so perhaps it can't be that much simpler. Picking the first item that appears in my test build of this but not in modules_thick.builtin:

+arch/x86/crypto/libblake2s-x86_64.o: arch/x86/crypto/blake2s-core.o arch/x86/crypto/blake2s-glue.o

But...

obj-$(CONFIG_CRYPTO_BLAKE2S_X86) += libblake2s-x86_64.o libblake2s-x86_64-y := blake2s-core.o blake2s-glue.o

config CRYPTO_BLAKE2S_X86

        bool "Hash functions: BLAKE2s (SSSE3/AVX-512)"

This cannot be built as a module. The point of modules_thick.builtin was not to capture things that can be built into the kernel or left unconfigured entirely (though that is *also* a nice thing to capture, and should probably be captured regardless) but to capture *those things that can possibly be built as modules*, i.e. those things which are tristates in Kbuild and might possibly get built into .ko's. That was the whole reason we needed the tristate stuff in the first place, and I'm still not sure how to do it without that.

(The reason: if your tracer or whatever has a distinct notation used by users for things in named modules, then you'd usually like to keep that notation the same if you choose to build something into the kernel that might otherwise be a module. Things that cannot be built as modules could just use the in-the-core-kernel notation unconditionally, because there's no way they can ever be found anywhere else: and users are likely to expect that. At least, when I broke it in DTrace years ago, I got complaints!)

Signature · 1 line
NULL && (void)
#6 lore raw

Re: [PATCH v9 2/8] kbuild: add modules_thick.builtin

Quoted 14 lines · Nick Alcock

But... it's not quite doing the same thing, so perhaps it can't be that much simpler. Picking the first item that appears in my test build of this but not in modules_thick.builtin:

+arch/x86/crypto/libblake2s-x86_64.o: arch/x86/crypto/blake2s-core.o arch/x86/crypto/blake2s-glue.o

But...

obj-$(CONFIG_CRYPTO_BLAKE2S_X86) += libblake2s-x86_64.o libblake2s-x86_64-y := blake2s-core.o blake2s-glue.o

config CRYPTO_BLAKE2S_X86

        bool "Hash functions: BLAKE2s (SSSE3/AVX-512)"
Quoted 8 lines

This cannot be built as a module. The point of modules_thick.builtin was not to capture things that can be built into the kernel or left unconfigured entirely (though that is *also* a nice thing to capture, and should probably be captured regardless) but to capture *those things that can possibly be built as modules*, i.e. those things which are tristates in Kbuild and might possibly get built into .ko's. That was the whole reason we needed the tristate stuff in the first place, and I'm still not sure how to do it without that.

OK, I think I should be able to combine your patch with (a variant of) the tristate stuff and get the best of both worlds (only-modular plus the efficiency of building and simplicity of your patch, with no nasty separate recursion like I had for modules_thick.builtin). Working on that...

maintainer
#7 lore raw

Re: [PATCH v9 2/8] kbuild: add modules_thick.builtin

In reply to Nick Alcock
Quoted 11 lines · Nick Alcock

+arch/x86/crypto/libblake2s-x86_64.o: arch/x86/crypto/blake2s-core.o arch/x86/crypto/blake2s-glue.o

But...

obj-$(CONFIG_CRYPTO_BLAKE2S_X86) += libblake2s-x86_64.o libblake2s-x86_64-y := blake2s-core.o blake2s-glue.o

config CRYPTO_BLAKE2S_X86

        bool "Hash functions: BLAKE2s (SSSE3/AVX-512)"

This cannot be built as a module.

mcgrof@fulton ~/linux (git::modules-next)$ git grep MODULE_LICENSE arch/x86/crypto/blake2s-* arch/x86/crypto/blake2s-glue.c:MODULE_LICENSE("GPL v2");

Try removing that.

Luis

#8 lore raw

Re: [PATCH v9 2/8] kbuild: add modules_thick.builtin

On 11 Nov 2022, Luis Chamberlain outgrape:

Quoted 11 lines · Nick Alcock
Quoted 10 lines

+arch/x86/crypto/libblake2s-x86_64.o: arch/x86/crypto/blake2s-core.o arch/x86/crypto/blake2s-glue.o

But...

obj-$(CONFIG_CRYPTO_BLAKE2S_X86) += libblake2s-x86_64.o libblake2s-x86_64-y := blake2s-core.o blake2s-glue.o

config CRYPTO_BLAKE2S_X86

        bool "Hash functions: BLAKE2s (SSSE3/AVX-512)"
Quoted 6 lines
Quoted 1 line

This cannot be built as a module.

mcgrof@fulton ~/linux (git::modules-next)$ git grep MODULE_LICENSE arch/x86/crypto/blake2s-* arch/x86/crypto/blake2s-glue.c:MODULE_LICENSE("GPL v2");

Try removing that.

OK, that works!

So if we're using the presence of MODULE_LICENSE to indicate that something is potentially modular, I guess this means I need to do a sweep through the kernel and find everywhere that cites a MODULE_LICENSE and cannot be built as a module before this will say things are modules that really are.

Should be easy enough to do semiautomatically, I hope (by comparison with the output of the old thing using tristate on a make allyesconfig build).

Hm. Maybe we need some sort of checking target that can use something like the old tristate recursor to detect this problem to stop it recurring. (Said target would only be run when requested, so it wouldn't slow the build down the way it used to.)

... assuming that people even think the presence of a MODULE_LICENSE in things that can't be modular is actually a problem. If it's not, my chances of getting fixes for all these cases in seems low.

maintainer
#9 lore raw

Re: [PATCH v9 2/8] kbuild: add modules_thick.builtin

Quoted 20 lines · Nick Alcock

On 11 Nov 2022, Luis Chamberlain outgrape:

Quoted 11 lines · Nick Alcock
Quoted 10 lines

+arch/x86/crypto/libblake2s-x86_64.o: arch/x86/crypto/blake2s-core.o arch/x86/crypto/blake2s-glue.o

But...

obj-$(CONFIG_CRYPTO_BLAKE2S_X86) += libblake2s-x86_64.o libblake2s-x86_64-y := blake2s-core.o blake2s-glue.o

config CRYPTO_BLAKE2S_X86

        bool "Hash functions: BLAKE2s (SSSE3/AVX-512)"
Quoted 6 lines
Quoted 1 line

This cannot be built as a module.

mcgrof@fulton ~/linux (git::modules-next)$ git grep MODULE_LICENSE arch/x86/crypto/blake2s-* arch/x86/crypto/blake2s-glue.c:MODULE_LICENSE("GPL v2");

Try removing that.

Quoted 7 lines

OK, that works!

So if we're using the presence of MODULE_LICENSE to indicate that something is potentially modular, I guess this means I need to do a sweep through the kernel and find everywhere that cites a MODULE_LICENSE and cannot be built as a module before this will say things are modules that really are.

Yes, make allyesconfig builds + a verifier for tristate would be nice. scripts/kconfig/streamline_config.pl has an iterator over kconfig files and also objects which you might find useful.

At build time such a thing could nag about issues like the above.

Luis

#10 lore raw

Re: [PATCH v9 2/8] kbuild: add modules_thick.builtin

On 15 Nov 2022, Luis Chamberlain uttered the following:

Quoted 29 lines · Nick Alcock
Quoted 20 lines

On 11 Nov 2022, Luis Chamberlain outgrape:

Quoted 11 lines · Nick Alcock
Quoted 10 lines

+arch/x86/crypto/libblake2s-x86_64.o: arch/x86/crypto/blake2s-core.o arch/x86/crypto/blake2s-glue.o

But...

obj-$(CONFIG_CRYPTO_BLAKE2S_X86) += libblake2s-x86_64.o libblake2s-x86_64-y := blake2s-core.o blake2s-glue.o

config CRYPTO_BLAKE2S_X86

        bool "Hash functions: BLAKE2s (SSSE3/AVX-512)"
Quoted 6 lines
Quoted 1 line

This cannot be built as a module.

mcgrof@fulton ~/linux (git::modules-next)$ git grep MODULE_LICENSE arch/x86/crypto/blake2s-* arch/x86/crypto/blake2s-glue.c:MODULE_LICENSE("GPL v2");

Try removing that.

Quoted 7 lines

OK, that works!

So if we're using the presence of MODULE_LICENSE to indicate that something is potentially modular, I guess this means I need to do a sweep through the kernel and find everywhere that cites a MODULE_LICENSE and cannot be built as a module before this will say things are modules that really are.

Quoted 5 lines

Yes, make allyesconfig builds + a verifier for tristate would be nice. scripts/kconfig/streamline_config.pl has an iterator over kconfig files and also objects which you might find useful.

At build time such a thing could nag about issues like the above.

OK, I've got enough of this working now that weird edge cases are popping out and it's starting to become fun rather than frustrating!

Some of them are bugs in the tristate-checker side of things, e.g. in net/bridge/Makefile we see

bridge-$(subst m,y,$(CONFIG_BRIDGE_NETFILTER)) += br_nf_core.o

and my code is tripping over because while it runs CONFIG_BRIDGE_NETFILTER comes from tristate.conf and has an uppercase value. This sort of thing is rare (a dozen cases at most across the tree) and easily fixable in the individual makefiles as part of the tristate checker commit, so I'll just do that.

But some are I think obscure bugs in the new machinery. e.g. in security/keys/encrypted-keys/Makefile we have this wonderfully crazy thing:

masterkey-$(CONFIG_TRUSTED_KEYS)-$(CONFIG_ENCRYPTED_KEYS) := masterkey_trusted.o

This produces things that look like masterkey-y-y, which does not match $(modname)-y. I'll come up with a more complete list shortly (a make allyesconfig is spinning now). We can probably hack around these by also expanding $(modname)-y-y etc, for as many steps out as it seems people are actually doing in the tree right now. I can submit a patch that does that if you like. (If there's a less gross and fragile approach, I'd be happy to do that instead.)

One question: do you think it's worthwhile me submitting patches to de-MODULE_* things that need it? It looks like I need to tear all the MODULE_ lines out before the .modinfo section goes away and this gives accurate results. This isn't actually deleting copyright lines, but it's making me a bit worried anyway: it feels morally equivalent somehow.

Is it actually considered OK to just delete MODULE_LICENSE, MODULE_AUTHOR etc for non-modules when they were written by someone else? (Commenting them out, leaving them as documentation, is presumably less likely to anger people but might be considered ugly.)

maintainer
#11 lore raw

Re: [PATCH v9 2/8] kbuild: add modules_thick.builtin

Quoted 2 lines · Nick Alcock

One question: do you think it's worthwhile me submitting patches to de-MODULE_* things that need it?

100% yes.

Yes please remove all that module declration helpers for things that are not modules, and after you add your helper which will nag at build time when it finds new ones.

For justification just mention in the commit log that after commit 8b41fc4454e ("kbuild: create modules.builtin without Makefile.modbuiltin or tristate.conf") we rely on the module license tag to generate the modules.builtin file and so built-in code which uses module helpers just need to be removed.

Luis

maintainer
#12 lore raw

Re: [PATCH v9 2/8] kbuild: add modules_thick.builtin

Quoted 10 lines · Luis Chamberlain
Quoted 2 lines · Nick Alcock

One question: do you think it's worthwhile me submitting patches to de-MODULE_* things that need it?

100% yes.

Yes please remove all that module declration helpers for things that are not modules, and after you add your helper which will nag at build time when it finds new ones.

Quoted 5 lines

For justification just mention in the commit log that after commit 8b41fc4454e ("kbuild: create modules.builtin without Makefile.modbuiltin or tristate.conf") we rely on the module license tag to generate the modules.builtin file and so built-in code which uses module helpers just need to be removed.

You should also mention what modules.builtin is used for as per our Documentation/kbuild/kbuild.rst, and that it is only used for modprobe to *not* fail when trying to load a module which is built-in.

And so, the removing these tags doesn't fix anything critical in particular, but it does fix false positive uses of userspace modprobe use against built-in symbols.

That would *complete* the commit log with a clear justification and evaluation of impact.

How many of these are we talking about? I'm happy to take them via modules-next. I'd hope to not run accross many conflicts against other trees.

Luis

#13 lore raw

Re: [PATCH v9 2/8] kbuild: add modules_thick.builtin

On 21 Nov 2022, Luis Chamberlain spake thusly:

Quoted 17 lines · Luis Chamberlain
Quoted 10 lines · Nick Alcock
Quoted 2 lines

One question: do you think it's worthwhile me submitting patches to de-MODULE_* things that need it?

100% yes.

Yes please remove all that module declration helpers for things that are not modules, and after you add your helper which will nag at build time when it finds new ones.

Quoted 5 lines

For justification just mention in the commit log that after commit 8b41fc4454e ("kbuild: create modules.builtin without Makefile.modbuiltin or tristate.conf") we rely on the module license tag to generate the modules.builtin file and so built-in code which uses module helpers just need to be removed.

Quoted 4 lines

You should also mention what modules.builtin is used for as per our Documentation/kbuild/kbuild.rst, and that it is only used for modprobe to *not* fail when trying to load a module which is built-in.

Yep! (Which is an extremely damn useful improvement, I must say. I'm relying on it already.)

Only two remaining problems in your patch that I can see (hacked around in the checker, but consumers shouldn't have to hack around this sort of thing). First, some very strange lines like this in modules.builtin.objs:

drivers/hid/hid-uclogic.o: drivers/hid/hid-uclogic-core.o drivers/hid/hid-uclogic-params.o drivers/hid/hid-uclogic-rdesc.o drivers/hid/hid-uclogic
drivers/hid/hid-uclogic-test.o:

(note the line with no .o or colon at all.)

This seems to be a consequence of lines like

hid-uclogic-objs                := hid-uclogic-core.o \
                                   hid-uclogic-rdesc.o \
                                   hid-uclogic-params.o

obj-$(CONFIG_HID_UCLOGIC) += hid-uclogic.o

i.e. use of -objs as a completely random variable for holding object files which might or might not be in a module. This seems a bit.. risky to me. Looking for a fix... maybe we can just ignore *-objs on the grounds that if it matters it will always land in some other variable too? ... maybe?

One other definite problem: drivers/staging/media/atomisp/Makefile says:

obj-$(CONFIG_VIDEO_ATOMISP) += pci/atomisp_gmin_platform.o

This subdirectory is lost from KBUILD_MODOBJS, leading to the file entry in modinfo and thus the resulting modules.builtin.objs pointing to a file named drivers/staging/media/atomisp/atomisp_gmin_platform.o, which does not exist. (This is also seen in some non-staging directories, e.g. kernel/trace/rv.)

Quoted 3 lines

How many of these are we talking about? I'm happy to take them via modules-next. I'd hope to not run accross many conflicts against other trees.

Going by an x86 allyesconfig run, 169 total (probably plus a few given errors like the one above), plus no doubt a few more for other arches. So not a vast number, but enough that hacking up a checker was clearly not a waste of time.

If there turn out to be any conflicts that aren't spurious I'd be very surprised. Hardly anyone ever even adjusts their email address in MODULE_AUTHOR when they change it :P

Signature · 1 line
NULL && (void)
#14 lore raw

PATCH v9 3/8 kbuild: generate an address ranges map at vmlinux link time

In reply to Nick Alcock

This emits a new file, .tmp_vmlinux.ranges, which maps address range/size pairs in vmlinux to the object files which make them up, e.g., in part:

0x0000000000000000 0x30 arch/x86/kernel/cpu/common.o 0x0000000000001000 0x1000 arch/x86/events/intel/ds.o 0x0000000000002000 0x4000 arch/x86/kernel/irq_64.o 0x0000000000006000 0x5000 arch/x86/kernel/process.o 0x000000000000b000 0x1000 arch/x86/kernel/cpu/common.o 0x000000000000c000 0x5000 arch/x86/mm/cpu_entry_area.o 0x0000000000011000 0x10 arch/x86/kernel/espfix_64.o 0x0000000000011010 0x2 arch/x86/kernel/cpu/common.o [...]

In my simple tests this seems to work with clang too, but if I'm not sure how stable the format of clang's linker mapfiles is: if it turns out not to work in some versions, the mapfile-massaging awk script added here might need some adjustment.

---

Notes:

    v6: use ${wl} where appropriate to avoid failure on UML
 scripts/link-vmlinux.sh | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
scripts/link-vmlinux.sh +14 -1
index 918470d768e9..287a2b2c4d46 100755
@@ -101,7 +101,7 @@ vmlinux_link()
 	${ld} ${ldflags} -o ${output}					\
 		${wl}--whole-archive ${objs} ${wl}--no-whole-archive	\
 		${wl}--start-group ${libs} ${wl}--end-group		\
-		$@ ${ldlibs}
+		${wl}-Map=.tmp_vmlinux.map $@ ${ldlibs}
 }
 
 # generate .BTF typeinfo from DWARF debuginfo
@@ -144,6 +144,19 @@ kallsyms()
 {
 	local kallsymopt;
 
+	# read the linker map to identify ranges of addresses:
+	#   - for each *.o file, report address, size, pathname
+	#       - most such lines will have four fields
+	#       - but sometimes there is a line break after the first field
+	#   - start reading at "Linker script and memory map"
+	#   - stop reading at ".brk"
+	${AWK} '
+	    /\.o$/ && start==1 { print $(NF-2), $(NF-1), $NF }
+	    /^Linker script and memory map/ { start = 1 }
+	    /^\.brk/ { exit(0) }
+	' .tmp_vmlinux.map | sort > .tmp_vmlinux.ranges
+
+	# get kallsyms options
 	if is_enabled CONFIG_KALLSYMS_ALL; then
 		kallsymopt="${kallsymopt} --all-symbols"
 	fi
Signature · 1 line
2.38.0.266.g481848f278
maintainer
#15 lore raw

Re: [PATCH v9 3/8] kbuild: generate an address ranges map at vmlinux link time

Quoted 4 lines · Nick Alcock

This emits a new file, .tmp_vmlinux.ranges, which maps address range/size pairs in vmlinux to the object files which make them up, e.g., in part:

Quoted 9 lines

0x0000000000000000 0x30 arch/x86/kernel/cpu/common.o 0x0000000000001000 0x1000 arch/x86/events/intel/ds.o 0x0000000000002000 0x4000 arch/x86/kernel/irq_64.o 0x0000000000006000 0x5000 arch/x86/kernel/process.o 0x000000000000b000 0x1000 arch/x86/kernel/cpu/common.o 0x000000000000c000 0x5000 arch/x86/mm/cpu_entry_area.o 0x0000000000011000 0x10 arch/x86/kernel/espfix_64.o 0x0000000000011010 0x2 arch/x86/kernel/cpu/common.o [...]

This does't say why we'd want this. So either you merge it with its first user or you explain here why anyone might find this useful.

Luis

#16 lore raw

Re: [PATCH v9 3/8] kbuild: generate an address ranges map at vmlinux link time

[Added Steve Rostedt to Cc:]

On 13 Nov 2022, Luis Chamberlain stated:

Quoted 15 lines · Nick Alcock
Quoted 4 lines

This emits a new file, .tmp_vmlinux.ranges, which maps address range/size pairs in vmlinux to the object files which make them up, e.g., in part:

Quoted 9 lines

0x0000000000000000 0x30 arch/x86/kernel/cpu/common.o 0x0000000000001000 0x1000 arch/x86/events/intel/ds.o 0x0000000000002000 0x4000 arch/x86/kernel/irq_64.o 0x0000000000006000 0x5000 arch/x86/kernel/process.o 0x000000000000b000 0x1000 arch/x86/kernel/cpu/common.o 0x000000000000c000 0x5000 arch/x86/mm/cpu_entry_area.o 0x0000000000011000 0x10 arch/x86/kernel/espfix_64.o 0x0000000000011010 0x2 arch/x86/kernel/cpu/common.o [...]

Quoted 2 lines

This does't say why we'd want this. So either you merge it with its first user or you explain here why anyone might find this useful.

Uh... the first user is later in this patch series? If you want each commit to have a self-contained explanation, I could certainly note why it's useful for said first user in this commit message (and adjust other messages similarly), but I had previous complaints that commit log messages and the cover letter were repeating points, so I was trying to reduce that kind of thing.

Signature · 1 line
NULL && (void)
maintainer
#17 lore raw

Re: [PATCH v9 3/8] kbuild: generate an address ranges map at vmlinux link time

Quoted 22 lines · Nick Alcock

[Added Steve Rostedt to Cc:]

On 13 Nov 2022, Luis Chamberlain stated:

Quoted 15 lines · Nick Alcock
Quoted 4 lines

This emits a new file, .tmp_vmlinux.ranges, which maps address range/size pairs in vmlinux to the object files which make them up, e.g., in part:

Quoted 9 lines

0x0000000000000000 0x30 arch/x86/kernel/cpu/common.o 0x0000000000001000 0x1000 arch/x86/events/intel/ds.o 0x0000000000002000 0x4000 arch/x86/kernel/irq_64.o 0x0000000000006000 0x5000 arch/x86/kernel/process.o 0x000000000000b000 0x1000 arch/x86/kernel/cpu/common.o 0x000000000000c000 0x5000 arch/x86/mm/cpu_entry_area.o 0x0000000000011000 0x10 arch/x86/kernel/espfix_64.o 0x0000000000011010 0x2 arch/x86/kernel/cpu/common.o [...]

Quoted 2 lines

This does't say why we'd want this. So either you merge it with its first user or you explain here why anyone might find this useful.

Quoted 6 lines

Uh... the first user is later in this patch series? If you want each commit to have a self-contained explanation, I could certainly note why it's useful for said first user in this commit message (and adjust other messages similarly), but I had previous complaints that commit log messages and the cover letter were repeating points, so I was trying to reduce that kind of thing.

Commit logs should be self contained. The reason for *why* we want to add ranges should go here, not the cover letter. You can be terse in the cover letter over the general solution.

Luis

#18 lore raw

Re: [PATCH v9 3/8] kbuild: generate an address ranges map at vmlinux link time

On 15 Nov 2022, Luis Chamberlain verbalised:

Quoted 14 lines · Nick Alcock
Quoted 6 lines

[Added Steve Rostedt to Cc:]

On 13 Nov 2022, Luis Chamberlain stated:

Quoted 2 lines

This does't say why we'd want this. So either you merge it with its first user or you explain here why anyone might find this useful.

Quoted 6 lines

Uh... the first user is later in this patch series? If you want each commit to have a self-contained explanation, I could certainly note why it's useful for said first user in this commit message (and adjust other messages similarly), but I had previous complaints that commit log messages and the cover letter were repeating points, so I was trying to reduce that kind of thing.

Quoted 3 lines

Commit logs should be self contained. The reason for *why* we want to add ranges should go here, not the cover letter. You can be terse in the cover letter over the general solution.

Ah, OK, my apologies: I was writing things precisely backwards then (rationale in the cover letter, self-contained-but-no-rationale in the individual patches then tying it together in the user at the end). Whoops!

I'll rephrase as you suggest in the next round.

(And I'll definitely rephrase the cover letter again -- I tried to add a decent rationale in there but from the sounds of things comprehensively failed this time. Sorry!)

Signature · 1 line
NULL && (void)
#19 lore raw

PATCH v9 4/8 kallsyms: introduce sections needed to map symbols to built-in modules

In reply to Nick Alcock

The mapping consists of three new symbols, computed by integrating the information in the (just-added) .tmp_vmlinux.ranges and modules_thick.builtin: taken together, they map address ranges (corresponding to object files on the input) to the names of zero or more modules containing those address ranges.

- kallsyms_module_addresses/kallsyms_module_offsets encodes the address/offset of each object file (derived from the linker map), in exactly the same way as kallsyms_addresses/kallsyms_offsets does for symbols. There is no size: instead, the object files are assumed to tile the address space. (This is slightly more space-efficient than using a size). Non-text-section addresses are skipped: for now, all the users of this interface only need module/non-module information for instruction pointer addresses, not absolute-addressed symbols and the like. This restriction can easily be lifted in future. (Regarding the name: right now the entries correspond pretty closely to object files, so we could call the section kallsyms_objfiles or something, but the optimizer added in the next commit will change this.)

- kallsyms_mod_objnames encodes the name of each module in a modified form of strtab: notably, if an object file appears in *multiple* modules, all of which are built in, this is encoded via a zero byte, a one-byte module count, then a series of that many null-terminated strings. As a special case, the table starts with a single zero byte which does *not* represent the start of a multi-module list.

(The name is "objnames" because in an upcoming commit it will store some object file names too.)

- kallsyms_modules connects the two, encoding a table associated 1:1 with kallsyms_module_addresses / kallsyms_module_offsets, pointing at an offset in kallsyms_module_names describing which module (or modules, for a multi-module list) the code occupying this address range is part of. If an address range is part of no module (always built-in) it points at 0 (the null byte at the start of the kallsyms_module_names list).

There is no optimization yet: kallsyms_modules and kallsyms_module_names will almost certainly contain many duplicate entries, and kallsyms_module_{addresses,offsets} may contain consecutive entries that point to the same place. The size hit is fairly substantial as a result, though still much less than a naive implementation mapping each symbol to a module name would be: 50KiB or so.

Since this commit is the first user of modules_thick.builtin, introduce rules to actually build it when CONFIG_KALLMODSYMS is set (similarly to modules.order, it is named in the top-level makefile purely for documentation purposes, then reiterated in the makefile where it is actually built, in this case the top-level Kbuild). Since it's also the first user of the new Kconfig symbol to enable compiling-out of /proc/kallmodsyms support, introduce that symbol too.

---

Notes:
v9: Rename .kallsyms_module_names to .kallsyms_mod_objnames now that it
contains object file names too. Adjustments to the Kconfig wording; adjustments to modules_thick.builtin rules. Adjust to getopt_long use in scripts/kallsyms.

 Kbuild             |   6 +
 Makefile           |   5 +-
 init/Kconfig       |   9 ++
 scripts/Makefile   |   6 +
 scripts/kallsyms.c | 375 ++++++++++++++++++++++++++++++++++++++++++++-
 5 files changed, 392 insertions(+), 9 deletions(-)
Kbuild +6 -0
index a84e8312c174..2bd36178ae64 100644
@@ -113,3 +113,9 @@ $(modthickbuiltin-files): include/config/tristate.conf
 
 modules_thick.builtin: $(modthickbuiltin-files) $(obj-y)
 	$(Q)$(AWK) '!x[$$0]++' $(patsubst %/built-in.a, %/$@, $(filter %/built-in.a,$(obj-y))) > $@
+
+ifdef CONFIG_KALLMODSYMS
+ifdef need-builtin
+extra-y += modules_thick.builtin
+endif
+endif
Makefile +4 -1
index 21117f9d4202..71f4d7abd6ed 100644
@@ -1232,7 +1232,7 @@ vmlinux.o modules.builtin.modinfo modules.builtin: vmlinux_o
 	@:
 
 PHONY += vmlinux
-vmlinux: vmlinux.o $(KBUILD_LDS) modpost
+vmlinux: vmlinux.o $(KBUILD_LDS) modules_thick.builtin modpost
 	$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.vmlinux
 
 # The actual objects are generated when descending,
@@ -1562,6 +1562,9 @@ __modinst_pre:
 
 endif # CONFIG_MODULES
 
+modules_thick.builtin: $(build-dir)
+	@:
+
 ###
 # Cleaning is done on three levels.
 # make clean     Delete most generated files
init/Kconfig +9 -0
index abf65098f1b6..70cc2e67bef7 100644
@@ -1570,6 +1570,15 @@ config POSIX_TIMERS
 
 	  If unsure say y.
 
+config KALLMODSYMS
+	default y
+	bool "Enable support for /proc/kallmodsyms" if EXPERT
+	depends on KALLSYMS
+	help
+	  This option enables the /proc/kallmodsyms file, which unambiguously
+	  maps built-in kernel symbols and their associated object files and
+	  modules to addresses.
+
 config PRINTK
 	default y
 	bool "Enable support for printk" if EXPERT
scripts/Makefile +6 -0
index 1575af84d557..acd46bfeedc3 100644
@@ -32,6 +32,12 @@ ifdef CONFIG_BUILDTIME_MCOUNT_SORT
 HOSTCFLAGS_sorttable.o += -DMCOUNT_SORT_ENABLED
 endif
 
+kallsyms-objs  := kallsyms.o
+
+ifdef CONFIG_KALLMODSYMS
+kallsyms-objs += modules_thick.o
+endif
+
 # The following programs are only built on demand
 hostprogs += unifdef
 
scripts/kallsyms.c +367 -8

468 lines not on this page · raw message

Signature · 1 line
2.38.0.266.g481848f278
maintainer
#20 lore raw

Re: [PATCH v9 4/8] kallsyms: introduce sections needed to map symbols to built-in modules

Quoted 1 line · Nick Alcock

The mapping consists of three new symbols

The entire commit log does not describe *why*.

Can I also trouble you to rebase on top of modules-next [0]

Does the kallsyms loop more than 3 times now with Zhen Lei's work and your new symbols on top on a allyesconfig build?

[0] https://git.kernel.org/pub/scm/linux/kernel/git/mcgrof/linux.git/log/?h=modules-next

Luis

#21 lore raw

Re: [PATCH v9 4/8] kallsyms: introduce sections needed to map symbols to built-in modules

On 13 Nov 2022, Luis Chamberlain outgrape:

Quoted 4 lines · Nick Alcock
Quoted 1 line

The mapping consists of three new symbols

The entire commit log does not describe *why*.

... because it's in the other commit logs and the cover letter. I can repeat the motivation in this log too if you like.

Quoted 1 line

Can I also trouble you to rebase on top of modules-next [0]

Sure!

Quoted 2 lines

Does the kallsyms loop more than 3 times now with Zhen Lei's work and your new symbols on top on a allyesconfig build?

I don't understand the question, sorry. If this is about the number of KALLSYMS invocations in the kernel build, that should be unchanged by this patch. This was an explicit design goal because it's quite slow to run kallsyms more times and I was already feeling guilty about having to bring back the tristate recursion.

I haven't tried it with Zhen Lei's work: will try for the next iteration, as a matter of course after the rebase. (And, looking at the patch series at the top of modules-next, wow is that quite a hefty performance improvement. And a hefty memory usage increase :( I have a horrible feeling that one of my machines won't have enough memory to boot after this goes in, but it was terribly outdated anyway.)

#22 lore raw

Re: [PATCH v9 4/8] kallsyms: introduce sections needed to map symbols to built-in modules

Quoted 23 lines · Nick Alcock

On 13 Nov 2022, Luis Chamberlain outgrape:

Quoted 4 lines · Nick Alcock
Quoted 1 line

The mapping consists of three new symbols

The entire commit log does not describe *why*.

... because it's in the other commit logs and the cover letter. I can repeat the motivation in this log too if you like.

Quoted 1 line

Can I also trouble you to rebase on top of modules-next [0]

Sure!

Quoted 2 lines

Does the kallsyms loop more than 3 times now with Zhen Lei's work and your new symbols on top on a allyesconfig build?

I don't understand the question, sorry. If this is about the number of KALLSYMS invocations in the kernel build, that should be unchanged by this patch. This was an explicit design goal because it's quite slow to run kallsyms more times and I was already feeling guilty about having to bring back the tristate recursion.

Quoted 6 lines

I haven't tried it with Zhen Lei's work: will try for the next iteration, as a matter of course after the rebase. (And, looking at the patch series at the top of modules-next, wow is that quite a hefty performance improvement. And a hefty memory usage increase :( I have a horrible feeling that one of my machines won't have enough memory to boot after this goes in, but it was terribly outdated anyway.)

It's only about 500K. It shouldn't be a problem. Your machine boot from flash?

Quoted 2 lines

.

Signature · 2 lines
Regards,
  Zhen Lei
#23 lore raw

Re: [PATCH v9 4/8] kallsyms: introduce sections needed to map symbols to built-in modules

On 15 Nov 2022, Leizhen spake thusly:

Quoted 7 lines · Nick Alcock
Quoted 6 lines

I don't understand the question, sorry. If this is about the number of KALLSYMS invocations in the kernel build, that should be unchanged by this patch. This was an explicit design goal because it's quite slow to run kallsyms more times and I was already feeling guilty about having to bring back the tristate recursion.

Quoted 8 lines
Quoted 6 lines

I haven't tried it with Zhen Lei's work: will try for the next iteration, as a matter of course after the rebase. (And, looking at the patch series at the top of modules-next, wow is that quite a hefty performance improvement. And a hefty memory usage increase :( I have a horrible feeling that one of my machines won't have enough memory to boot after this goes in, but it was terribly outdated anyway.)

It's only about 500K. It shouldn't be a problem. Your machine boot from flash?

It's more that it only has 1GiB RAM... but it's also wildly obsolete and I shouldn't be worrying.

(I'm also a bit miffed because people are worrying about 10K of overhead at the same time as a patch is going in adding half a meg ;) but that's just me being childish. And I know you can't add overhead indefinitely or the system turns into a slug, and I know the speedups from your change are amazing...)

Signature · 1 line
NULL && (void)
maintainer
#24 lore raw

Re: [PATCH v9 4/8] kallsyms: introduce sections needed to map symbols to built-in modules

Quoted 2 lines · Nick Alcock

(I'm also a bit miffed because people are worrying about 10K of overhead at the same time as a patch is going in adding half a meg ;)

You are missing that the reason why your patch lacks much traction is it lacks a clear *use* case. It has nothing to do with space. The cover letter can be really summarized in a condensed way to get the point accross to just include the text on your first paragraph you had at Plumbers:

https://lpc.events/event/16/contributions/1379/

This gets the point accross well.

The rest of the cover letter is just pure noise and gets me lost.

But for instance, when I reviewed the patch for adding ranges, your cover letter describes the *justification*, the *why* to do that, but the patch does not at all.

Please make sure that your commits describe *why* clearly. Please get a bit of help from your team to condense to the cover letter to only include what is needed if someone is reading the patchset for the very first time.

And then users.. we need users clearly documented, who the heck is using this or wants this / is going to use it and why.

Luis

maintainer
#25 lore raw

Re: [PATCH v9 4/8] kallsyms: introduce sections needed to map symbols to built-in modules

Quoted 2 lines · Luis Chamberlain

And then users.. we need users clearly documented, who the heck is using this or wants this / is going to use it and why.

What issues did existing users run into? Why is this an issue? If no bugs have been reported why isn't this an issue then? Why does the existing duplicate stuff not cause issues in-kernel for symbol lookups?

Who is dying for this feature? What userspace tools / whatever has support for this and can't wait to get their hands on this?

Luis

#26 lore raw

PATCH v9 5/8 kallsyms: optimize .kallsyms_modules*

In reply to Nick Alcock

These symbols are terribly inefficiently stored at the moment. Add a simple optimizer which fuses obj2mod_elem entries and uses this to implement three cheap optimizations:

- duplicate names are eliminated from .kallsyms_module_names.

- entries in .kallsyms_modules which point at single-file modules which also appear in a multi-module list are redirected to point inside that list, and the single-file entry is dropped from .kallsyms_module_names. Thus, modules which contain some object files shared with other modules and some object files exclusive to them do not double up the module name. (There might still be some duplication between multiple multi-module lists, but this is an extremely marginal size effect, and resolving it would require an extra layer of lookup tables which would be even more complex, and incompressible to boot).

- Entries in .kallsyms_modules that would contain the same value after the above optimizations are fused together, along with their corresponding .kallsyms_module_addresses/offsets entries. Due to this fusion process, and because object files can be split apart into multiple parts by the linker for hot/cold partitioning and the like, entries in .kallsyms_module_addresses/offsets no longer correspond 1:1 to object files, but more to some contiguous range of addresses which are guaranteed to belong to a single built-in module, but which may well stretch over multiple object files.

The optimizer's time complexity is O(log n) in the number of objfiles at most (and probably much lower), so, given the relatively low number of objfiles, its runtime overhead is in the noise.

Optimization reduces the overhead of the kallmodsyms tables by about 7500 items, dropping the .tmp_kallsyms2.o object file size by about 33KiB, leaving it 8672 bytes larger than before: a gain of .4%.

The vmlinux size is not yet affected because the variables are not used and are eliminated by the linker: but if they were used (after the next commit but one), the size impact of all of this on the final kernel is
minimal: in my testing, vmlinux grew by 0.17% (10824 bytes), and the compressed vmlinux only grew by 0.08% (7552 bytes): though this is very configuration-dependent, it seems likely to scale roughly with the kernel as a whole. (The next commit changes these numbers a bit, but not much.)

---

Notes:
v9: Fix a bug in optimize_obj2mod that prevented proper reuse of
module names for object files appearing in both multimodule modules and single-module modules. Adjustments to allow for objfile support. Tiny style fixes.

 scripts/kallsyms.c | 297 +++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 288 insertions(+), 9 deletions(-)
scripts/kallsyms.c +288 -9
index 6b9654a151fb..f89f569eb3c9 100644
@@ -102,6 +102,17 @@ static unsigned int strhash(const char *s)
 	return hash;
 }
 
+static unsigned int memhash(char *s, size_t len)
+{
+	/* fnv32 hash */
+	unsigned int hash = 2166136261U;
+	size_t i;
+
+	for (i = 0; i < len; i++)
+		hash = (hash ^ *(s + i)) * 0x01000193;
+	return hash;
+}
+
 #define OBJ2MOD_BITS 10
 #define OBJ2MOD_N (1 << OBJ2MOD_BITS)
 #define OBJ2MOD_MASK (OBJ2MOD_N - 1)
@@ -111,14 +122,35 @@ struct obj2mod_elem {
 	size_t nmods;		/* number of modules in "mods" */
 	size_t mods_size;	/* size of all mods together */
 	int mod_offset;		/* offset of module name in .kallsyms_mod_objnames */
+
+	/*
+	 * Hash values of all module names in this elem, combined: used for
+	 * rapid comparisons.  Populated quite late, at optimize_obj2mod time.
+	 */
+	unsigned int modhash;
+
+	/*
+	 * If set at emission time, this points at another obj2mod entry that
+	 * contains the module name we need (possibly at a slightly later
+	 * offset, if the entry is for an objfile that appears in many modules).
+	 */
+	struct obj2mod_elem *xref;
+
+	/*
+	 * Chain links for object -> module and module->object mappings.
+	 */
 	struct obj2mod_elem *obj2mod_next;
+	struct obj2mod_elem *mod2obj_next;
 };
 
 /*
- * Map from object files to obj2mod entries (a unique mapping).
+ * Map from object files to obj2mod entries (a unique mapping), and vice versa
+ * (not unique, but entries for objfiles in more than one module in this hash
+ * are ignored).
  */
 
 static struct obj2mod_elem *obj2mod[OBJ2MOD_N];
+static struct obj2mod_elem *mod2obj[OBJ2MOD_N];
 static size_t num_objfiles;
 
 /*
@@ -162,6 +194,8 @@ static void obj2mod_add(char *obj, char *mod)
 
 	elem = obj2mod_get(obj);
 	if (!elem) {
+		int j = strhash(mod) & OBJ2MOD_MASK;
+
 		elem = malloc(sizeof(struct obj2mod_elem));
 		if (!elem)
 			goto oom;
@@ -175,8 +209,15 @@ static void obj2mod_add(char *obj, char *mod)
 
 		elem->obj2mod_next = obj2mod[i];
 		obj2mod[i] = elem;
+		elem->mod2obj_next = mod2obj[j];
+		mod2obj[j] = elem;
 		num_objfiles++;
 	} else {
+		/*
+		 * objfile appears in multiple modules.  mod2obj for this entry
+		 * will be ignored from now on, except insofar as it is needed
+		 * to maintain the hash chain.
+		 */
 		elem->mods = realloc(elem->mods, elem->mods_size +
 				     strlen(mod) + 1);
 		if (!elem->mods)
@@ -196,6 +237,162 @@ static void obj2mod_add(char *obj, char *mod)
 	fprintf(stderr, "kallsyms: out of memory\n");
 	exit(1);
 }
+
+static int qstrcmp(const void *a, const void *b)
+{
+	return strcmp((const char *) a, (const char *) b);
+}
+
+static int qmodhash(const void *a, const void *b)
+{
+	struct obj2mod_elem * const *el_a = a;
+	struct obj2mod_elem * const *el_b = b;
+	if ((*el_a)->modhash < (*el_b)->modhash)
+		return -1;
+	else if ((*el_a)->modhash > (*el_b)->modhash)
+		return 1;
+	return 0;
+}
+
+/*
+ * Associate all object files in obj2mod which refer to the same module with a
+ * single obj2mod entry for emission, preferring to point into the module list
+ * in a multi-module objfile.
+ */
+static void optimize_obj2mod(void)
+{
+	size_t i;
+	size_t n = 0;
+	struct obj2mod_elem *elem;
+	struct obj2mod_elem *dedup;
+
+	/* An array of all obj2mod_elems, later sorted by hashval.  */
+	struct obj2mod_elem **uniq;
+	struct obj2mod_elem *last;
+
+	/*
+	 * Canonicalize all module lists by sorting them, then compute their
+	 * hash values.
+	 */
+	uniq = malloc(sizeof(struct obj2mod_elem *) * num_objfiles);
+	if (uniq == NULL)
+		goto oom;
+
+	for (i = 0; i < OBJ2MOD_N; i++) {
+		for (elem = obj2mod[i]; elem; elem = elem->obj2mod_next) {
+			if (elem->nmods >= 2) {
+				char **sorter;
+				char *walk;
+				char *tmp_mods;
+				size_t j;
+
+				tmp_mods = malloc(elem->mods_size);
+				sorter = malloc(sizeof(char *) * elem->nmods);
+				if (sorter == NULL || tmp_mods == NULL)
+					goto oom;
+				memcpy(tmp_mods, elem->mods, elem->mods_size);
+
+				for (j = 0, walk = tmp_mods; j < elem->nmods;
+				     j++) {
+					sorter[j] = walk;
+					walk += strlen(walk) + 1;
+				}
+				qsort(sorter, elem->nmods, sizeof (char *),
+				      qstrcmp);
+				for (j = 0, walk = elem->mods; j < elem->nmods;
+				     j++) {
+					strcpy(walk, sorter[j]);
+					walk += strlen(walk) + 1;
+				}
+				free(tmp_mods);
+				free(sorter);
+			}
+
+			uniq[n] = elem;
+			uniq[n]->modhash = memhash(elem->mods, elem->mods_size);
+			n++;
+		}
+	}
+
+	qsort(uniq, num_objfiles, sizeof (struct obj2mod_elem *), qmodhash);
+
+	/*
+	 * Work over multimodule entries.  These must be emitted into
+	 * .kallsyms_mod_objnames as a unit, but we can still optimize by
+	 * reusing some other identical entry.  Single-file modules are amenable
+	 * to the same optimization, but we avoid doing it for now so that we
+	 * can prefer to point them directly inside a multimodule entry.
+	 */
+	for (i = 0, last = NULL; i < num_objfiles; i++) {
+		const char *onemod;
+		size_t j;
+
+		if (uniq[i]->nmods < 2)
+			continue;
+
+		/* Duplicate multimodule.  Reuse the first we saw.  */
+		if (last != NULL && last->modhash == uniq[i]->modhash &&
+			memcmp(uniq[i]->mods, last->mods,
+			       uniq[i]->mods_size) == 0) {
+			uniq[i]->xref = last;
+			continue;
+		}
+
+		/*
+		 * Single-module entries relating to modules also emitted as
+		 * part of this multimodule entry can refer to it: later, we
+		 * will hunt down the right specific module name within this
+		 * multimodule entry and point directly to it.
+		 */
+		onemod = uniq[i]->mods;
+		for (j = uniq[i]->nmods; j > 0; j--) {
+			int h = strhash(onemod) & OBJ2MOD_MASK;
+
+			for (dedup = mod2obj[h]; dedup;
+			     dedup = dedup->mod2obj_next) {
+				if (dedup->nmods > 1)
+					continue;
+
+				if (strcmp(dedup->mods, onemod) != 0)
+					continue;
+				dedup->xref = uniq[i];
+				assert(uniq[i]->xref == NULL);
+			}
+			onemod += strlen(onemod) + 1;
+		}
+
+		last = uniq[i];
+	}
+
+	/*
+	 * Now traverse all single-module entries, xreffing every one that
+	 * relates to a given module to the first one we saw that refers to that
+	 * module.
+	 */
+	for (i = 0, last = NULL; i < num_objfiles; i++) {
+		if (uniq[i]->nmods > 1)
+			continue;
+
+		if (uniq[i]->xref != NULL)
+			continue;
+
+		/* Duplicate module name.  Reuse the first we saw.  */
+		if (last != NULL && last->modhash == uniq[i]->modhash &&
+		    memcmp(uniq[i]->mods, last->mods, uniq[i]->mods_size) == 0) {
+			uniq[i]->xref = last;
+			assert(last->xref == NULL);
+			continue;
+		}
+		last = uniq[i];
+	}
+
+	free(uniq);
+
+	return;
+oom:
+	fprintf(stderr, "kallsyms: out of memory optimizing module list\n");
+	exit(EXIT_FAILURE);
+}
 #endif /* CONFIG_KALLMODSYMS */
 
 static void usage(void)
@@ -507,8 +704,8 @@ static void output_kallmodsyms_mod_objnames(void)
 	size_t i;
 
 	/*
-	 * Traverse and emit, updating mod_offset accordingly.  Emit a single \0
-	 * at the start, to encode non-modular objfiles.
+	 * Traverse and emit, chasing xref and updating mod_offset accordingly.
+	 * Emit a single \0 at the start, to encode non-modular objfiles.
 	 */
 	output_label("kallsyms_mod_objnames");
 	printf("\t.byte\t0\n");
@@ -517,9 +714,25 @@ static void output_kallmodsyms_mod_objnames(void)
 		     elem = elem->obj2mod_next) {
 			const char *onemod;
 			size_t i;
+			struct obj2mod_elem *out_elem = elem;
 
-			elem->mod_offset = offset;
-			onemod = elem->mods;
+			/*
+			 * Single-module ref to a multimodule: will be emitted
+			 * as a whole, so avoid emitting pieces of it (which
+			 * would go unreferenced in any case).
+			 */
+			if (elem->xref &&
+			    elem->nmods == 1 && elem->xref->nmods > 1)
+				continue;
+
+			if (elem->xref)
+				out_elem = elem->xref;
+
+			if (out_elem->mod_offset != 0)
+				continue;	/* Already emitted.  */
+
+			out_elem->mod_offset = offset;
+			onemod = out_elem->mods;
 
 			/*
 			 * Technically this is a waste of space: we could just
@@ -528,13 +741,14 @@ static void output_kallmodsyms_mod_objnames(void)
 			 * entry, but doing it this way makes it more obvious
 			 * when an entry is a multimodule entry.
 			 */
-			if (elem->nmods != 1) {
+			if (out_elem->nmods != 1) {
 				printf("\t.byte\t0\n");
-				printf("\t.byte\t%zi\n", elem->nmods);
+				printf("\t.byte\t%zi\n", out_elem->nmods);
 				offset += 2;
 			}
 
-			for (i = elem->nmods; i > 0; i--) {
+			for (i = out_elem->nmods; i > 0; i--) {
+				printf("/* 0x%lx */\n", offset);
 				printf("\t.asciz\t\"%s\"\n", onemod);
 				offset += strlen(onemod) + 1;
 				onemod += strlen(onemod) + 1;
@@ -561,6 +775,13 @@ static void output_kallmodsyms_objfiles(void)
 		long long offset;
 		int overflow;
 
+                /*
+                 * Fuse consecutive address ranges citing the same object file
+                 * into one.
+                 */
+                if (i > 0 && addrmap[i-1].objfile == addrmap[i].objfile)
+                        continue;
+
 		if (base_relative) {
 			if (!absolute_percpu) {
 				offset = addrmap[i].addr - relative_base;
@@ -586,6 +807,13 @@ static void output_kallmodsyms_objfiles(void)
 
 	for (i = 0; i < addrmap_num; i++) {
 		struct obj2mod_elem *elem = addrmap[i].objfile;
+		int orig_nmods;
+		const char *orig_modname;
+		int mod_offset;
+
+		if (i > 0 && addrmap[i-1].objfile == addrmap[i].objfile)
+			continue;
+
 		/*
 		 * Address range cites no modular object file: point at 0, the
 		 * built-in module.
@@ -596,13 +824,63 @@ static void output_kallmodsyms_objfiles(void)
 			continue;
 		}
 
+		orig_nmods = elem->nmods;
+		orig_modname = elem->mods;
+
+		/*
+		 * Chase down xrefs, if need be.  There can only be one layer of
+		 * these: from single-module entry to other single-module
+		 * entry, or from single- or multi-module entry to another
+		 * multi-module entry.  Single -> single and multi -> multi
+		 * always points at the start of the xref target, so its offset
+		 * can be used as is.
+		 */
+		if (elem->xref)
+			elem = elem->xref;
+
+		if (elem->nmods == 1 || orig_nmods > 1) {
+
+			if (elem->nmods == 1)
+				printf("/* 0x%llx--0x%llx: module %s */\n",
+				       addrmap[i].addr, addrmap[i].end_addr,
+				       elem->mods);
+			else
+				printf("/* 0x%llx--0x%llx: multimodule */\n",
+				       addrmap[i].addr, addrmap[i].end_addr);
+
+			mod_offset = elem->mod_offset;
+		} else {
+			/*
+			 * If this is a reference from a single-module entry to
+			 * a multi-module entry, hunt down the offset to this
+			 * specific module's name (which is guaranteed to be
+			 * present: see optimize_obj2mod).
+			 */
+
+			size_t j = elem->nmods;
+			const char *onemod = elem->mods;
+			mod_offset = elem->mod_offset;
+
+			for (; j > 0; j--) {
+				if (strcmp(orig_modname, onemod) == 0)
+					break;
+				onemod += strlen(onemod) + 1;
+			}
+			assert(j > 0);
+			/*
+			 * +2 to skip the null byte and count at the start of
+			 * the multimodule entry.
+			 */
+			mod_offset += onemod - elem->mods + 2;
+		}
+
 		/*
 		 * Zero offset is the initial \0, there to catch uninitialized
 		 * obj2mod entries, and is forbidden.
 		 */
 		assert(elem->mod_offset != 0);
 
-		printf("\t.long\t0x%x\n", elem->mod_offset);
+		printf("\t.long\t0x%x\n", mod_offset);
 		emitted_objfiles++;
 	}
 
@@ -1146,6 +1424,7 @@ static void read_modules(const char *modules_builtin)
 
 	free(module_name);
 	modules_thick_iter_free(i);
+	optimize_obj2mod();
 
 	/*
 	 * Read linker map.
Signature · 1 line
2.38.0.266.g481848f278
#27 lore raw

PATCH v9 6/8 kallsyms: distinguish text symbols fully using object file names

In reply to Nick Alcock

The commits before this one allow you to distinguish identically-named text symbols located in different built-in object files from each other; but identically-named symbols can appear in any object files at all, including object files that cannot be built as modules.

We already have nearly all the machinery to disambiguate these symbols as well. Since any given object file can contain at most one definition of a given symbol, it suffices to name the object files containing any symbol which is otherwise ambiguous. (No others need be named, saving a bunch of space).

We associate address ranges with object file names using a new .kallsyms_objfiles section just like the previously-added .kallsyms_modules section.

But that's not quite enough. Even the object file name is ambiguous in some cases: e.g. there are a lot of files named "core.o" in the kernel. We could just store the full pathname for every object file, but this is needlessly wasteful: doing this eats more than 50KiB in object file names alone, and nearly all the content of every name is repeated for many names. But if we store the object file names in the same section as the built-in module names, drop the .o, and store minimal path suffixes, we can save almost all that space. (For example, "core.o" would be stored as "core" unless there are ambiguous symbols in two different object files both named "core", in which case they'd be named "sched/core" and "futex/core", etc, possibly re-extending to "kernel/sched/core" if still ambiguous).

We do this by a repeated-rehashing process. First, we compute a hash value for symbol\0modhash for every symbol (the modhash is ignored if this is a built-in symbol). Any two symbols with the same such hash are
identically-named: add the maximally-shortened (one-component, .o-stripped) object file name for all such symbols, and rehash, this time hashing symbol\0objname\0modhash. Any two symbols which still have the same hash are still ambiguous: lengthen the name given to one of the symbols' object files and repeat. Eventually, all the ambiguity will go away. (We do have to take care not to re-lengthen anything we already lengthened in any given hashing round.)

This involves multiple sorting passes but the impact on compilation time appears to be nearly zero, and the impact on space in the running kernel is noticeable: only a few dozen names need lengthening, so we can completely ignore the overhead from storing repeated path components because there are hardly any of them.

But that's not all. We can also do similar optimization tricks to what was done with .kallsyms_modules, reusing module names and names of already-emitted object files: so any given object file name only appears once in the strtab, and can be cited by many address ranges and even by module entries.

Put all this together and the net overhead of this in my testing is about 3KiB of new object file names in the .kallsyms_mod_objnames table and 6KiB for the .kallsyms_objfiles table (mostly zeroes: in future maybe we can find a way to elide some of those, but 6KiB is small enough that it's not worth taking too much effort).

No ambiguous textual symbols remain outside actual modules (which can still contain identically-named symbols in different object files because kallsyms doesn't run over them so none of these tables can be built for them. At least, it doesn't yet.)

---

Notes:

    v9: new.
 scripts/kallsyms.c | 559 +++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 546 insertions(+), 13 deletions(-)
scripts/kallsyms.c +546 -13
index f89f569eb3c9..ffb69a8f6ff8 100644
@@ -113,6 +113,9 @@ static unsigned int memhash(char *s, size_t len)
 	return hash;
 }
 
+/*
+ * Object file -> module and shortened object file name tracking machinery.
+ */
 #define OBJ2MOD_BITS 10
 #define OBJ2MOD_N (1 << OBJ2MOD_BITS)
 #define OBJ2MOD_MASK (OBJ2MOD_N - 1)
@@ -143,15 +146,40 @@ struct obj2mod_elem {
 	struct obj2mod_elem *mod2obj_next;
 };
 
+/*
+ * Shortened object file names.  These are only ever consulted after checking
+ * the obj2mod hashes: names that already exist in there are used directly from
+ * there (pointed to via the mod_xref field) rather than being re-emitted.
+ * Entries that do not exist there are added to the end of the mod_objnames
+ * list.
+ */
+struct obj2short_elem {
+	const char *obj;
+	char *desuffixed;	/* objname sans suffix */
+	const char *short_obj;	/* shortened at / and suffix */
+	int short_offset;	/* offset of short name in .kallsyms_mod_objnames */
+	int last_rehash;	/* used during disambiguate_hash_syms */
+
+	struct obj2mod_elem *mod_xref;
+	struct obj2short_elem *short_xref;
+	struct obj2short_elem *short_next;
+};
+
 /*
  * Map from object files to obj2mod entries (a unique mapping), and vice versa
  * (not unique, but entries for objfiles in more than one module in this hash
- * are ignored).
+ * are ignored); also map from object file names to shortened names for them
+ * (also unique: there is no point storing both longer and shorter forms of one
+ * name, so if a longer name is needed we consistently use it instead of the
+ * shorter form.)
+ *
+ * obj2short is populated very late, at disambiguate_syms time.
  */
 
 static struct obj2mod_elem *obj2mod[OBJ2MOD_N];
 static struct obj2mod_elem *mod2obj[OBJ2MOD_N];
-static size_t num_objfiles;
+static struct obj2short_elem *obj2short[OBJ2MOD_N];
+static size_t num_objfiles, num_shortnames;
 
 /*
  * An ordered list of address ranges and the objfile that occupies that range.
@@ -165,6 +193,9 @@ struct addrmap_entry {
 static struct addrmap_entry *addrmap;
 static int addrmap_num, addrmap_alloced;
 
+static void disambiguate_syms(void);
+static void optimize_objnames(void);
+
 static void obj2mod_init(void)
 {
 	memset(obj2mod, 0, sizeof(obj2mod));
@@ -182,6 +213,18 @@ static struct obj2mod_elem *obj2mod_get(const char *obj)
 	return NULL;
 }
 
+static struct obj2short_elem *obj2short_get(const char *obj)
+{
+	int i = strhash(obj) & OBJ2MOD_MASK;
+	struct obj2short_elem *elem;
+
+	for (elem = obj2short[i]; elem; elem = elem->short_next) {
+		if (strcmp(elem->obj, obj) == 0)
+			return elem;
+	}
+	return NULL;
+}
+
 /*
  * Note that a given object file is found in some module, interning it in the
  * obj2mod hash.  Should not be called more than once for any given (module,
@@ -254,6 +297,12 @@ static int qmodhash(const void *a, const void *b)
 	return 0;
 }
 
+static int qobj2short(const void *a, const void *b)
+{
+	return strcmp((*(struct obj2short_elem **)a)->short_obj,
+		      (*(struct obj2short_elem **)b)->short_obj);
+}
+
 /*
  * Associate all object files in obj2mod which refer to the same module with a
  * single obj2mod entry for emission, preferring to point into the module list
@@ -393,6 +442,336 @@ static void optimize_obj2mod(void)
 	fprintf(stderr, "kallsyms: out of memory optimizing module list\n");
 	exit(EXIT_FAILURE);
 }
+
+/*
+ * Associate all short-name entries in obj2short that refer to the same short
+ * name with a single entry for emission, either (preferably) a module that
+ * shares that name or (alternatively) the first obj2short entry referencing
+ * that name.
+ */
+static void optimize_objnames(void)
+{
+	size_t i;
+	size_t num_objnames = 0;
+	struct obj2short_elem *elem;
+	struct obj2short_elem **uniq;
+	struct obj2short_elem *last;
+
+	uniq = malloc(sizeof(struct obj2short_elem *) * num_shortnames);
+	if (uniq == NULL) {
+		fprintf(stderr, "kallsyms: out of memory optimizing object file name list\n");
+		exit(EXIT_FAILURE);
+	}
+
+	/*
+	 * Much like optimize_obj2mod, except there is no need to canonicalize
+	 * anything or handle multimodule entries, and we need to chase down
+	 * possible entries in mod2obj first (so as not to duplicate them in the
+	 * final kallsyms_mod_objnames strtab).
+	 */
+	for (i = 0; i < OBJ2MOD_N; i++)
+		for (elem = obj2short[i]; elem; elem = elem->short_next)
+			uniq[num_objnames++] = elem;
+
+	qsort(uniq, num_objnames, sizeof(struct obj2short_elem *), qobj2short);
+
+	for (i = 0, last = NULL; i < num_objnames; i++) {
+		int h = strhash(uniq[i]->short_obj) & OBJ2MOD_MASK;
+		struct obj2mod_elem *mod_elem;
+
+		for (mod_elem = mod2obj[h]; mod_elem;
+		     mod_elem = mod_elem->mod2obj_next) {
+			/*
+			 * mod_elem entries are only valid if they are for
+			 * single-module objfiles: see obj2mod_add
+			 */
+			if (mod_elem->nmods > 1)
+				continue;
+
+			if (strcmp(mod_elem->mods, uniq[i]->short_obj) != 0)
+				continue;
+			uniq[i]->mod_xref = mod_elem;
+			break;
+		}
+
+		/*
+		 * Only look for a short_xref match if we don't already have one
+		 * in mod_xref.  (This means that multiple objfiles with the
+		 * same short name that is also a module name all chain directly
+		 * to the module name via mod_xref, rather than going through a
+		 * chain of short_xrefs.)
+		 */
+		if (uniq[i]->mod_xref)
+			continue;
+
+		if (last != NULL && strcmp(last->short_obj,
+					   uniq[i]->short_obj) == 0) {
+			uniq[i]->short_xref = last;
+			continue;
+		}
+
+		last = uniq[i];
+	}
+
+	free(uniq);
+}
+
+/*
+ * Used inside disambiguate_syms to identify colliding symbols.  We spot this by
+ * hashing symbol\0modhash (or just the symbol name if this is in the core
+ * kernel) and seeing if that collides.  (This means we don't need to bother
+ * canonicalizing the module list, since optimize_obj2mod already did it for
+ * us.)
+ *
+ * If that collides, we try disambiguating by adding ever-longer pieces of the
+ * object file name before the modhash until we no longer collide.  The result
+ * of this repeated addition becomes the obj2short hashtab.
+ */
+struct sym_maybe_collides {
+	struct sym_entry *sym;
+	struct addrmap_entry *addr;
+	struct obj2short_elem *short_objname;
+	unsigned int symhash;
+};
+
+static int qsymhash(const void *a, const void *b)
+{
+	const struct sym_maybe_collides *el_a = a;
+	const struct sym_maybe_collides *el_b = b;
+	if (el_a->symhash < el_b->symhash)
+		return -1;
+	else if (el_a->symhash > el_b->symhash)
+		return 1;
+	return 0;
+}
+
+static int find_addrmap(const void *a, const void *b)
+{
+	const struct sym_entry *sym = a;
+	const struct addrmap_entry *map = b;
+
+	if (sym->addr < map->addr)
+		return -1;
+	else if (sym->addr >= map->end_addr)
+		return 1;
+	return 0;
+}
+
+/*
+ * Allocate or lengthen an object file name for a symbol that needs it.
+ */
+static int lengthen_short_name(struct sym_maybe_collides *sym, int hash_cycle)
+{
+	struct obj2short_elem *short_objname = obj2short_get(sym->addr->obj);
+
+	if (!short_objname) {
+		int i = strhash(sym->addr->obj) & OBJ2MOD_MASK;
+		char *p;
+
+		short_objname = malloc(sizeof(struct obj2short_elem));
+		if (short_objname == NULL)
+			goto oom;
+
+		/*
+		 * New symbol: try maximal shortening, which is just the object
+		 * file name (no directory) with the suffix removed (the suffix
+		 * is useless for disambiguation since it is almost always .o).
+		 *
+		 * Add a bit of paranoia to allow for names starting with /,
+		 * ending with ., and names with no suffix.  (At least two of
+		 * these are most unlikely, but possible.)
+		 */
+
+		memset(short_objname, 0, sizeof(struct obj2short_elem));
+		short_objname->obj = sym->addr->obj;
+
+		p = strrchr(sym->addr->obj, '.');
+		if (p)
+			short_objname->desuffixed = strndup(sym->addr->obj,
+							    p - sym->addr->obj);
+		else
+			short_objname->desuffixed = strdup(sym->addr->obj);
+
+		if (short_objname->desuffixed == NULL)
+			goto oom;
+
+		p = strrchr(short_objname->desuffixed, '/');
+		if (p && p[1] != 0)
+			short_objname->short_obj = p + 1;
+		else
+			short_objname->short_obj = short_objname->desuffixed;
+
+		short_objname->short_next = obj2short[i];
+		short_objname->last_rehash = hash_cycle;
+		obj2short[i] = short_objname;
+
+		num_shortnames++;
+		return 1;
+	}
+
+	/*
+	 * Objname already lengthened by a previous symbol clash: do nothing
+	 * until we rehash again.
+	 */
+	if (short_objname->last_rehash == hash_cycle)
+		return 0;
+	short_objname->last_rehash = hash_cycle;
+
+	/*
+	 * Existing symbol: lengthen the objname we already have.
+	 */
+
+	if (short_objname->desuffixed == short_objname->short_obj) {
+		fprintf(stderr, "Cannot disambiguate %s: objname %s is "
+			"max-length but still colliding\n",
+			sym->sym->sym, short_objname->short_obj);
+		return 0;
+	}
+
+	/*
+	 * Allow for absolute paths, where the first byte is '/'.
+	 */
+
+	if (short_objname->desuffixed >= short_objname->short_obj - 2)
+		short_objname->short_obj = short_objname->desuffixed;
+	else {
+		for (short_objname->short_obj -= 2;
+		     short_objname->short_obj > short_objname->desuffixed &&
+		     *short_objname->short_obj != '/';
+		     short_objname->short_obj--);
+
+		if (*short_objname->short_obj == '/')
+			short_objname->short_obj++;
+	}
+	return 1;
+ oom:
+	fprintf(stderr, "Out of memory disambiguating syms\n");
+	exit(EXIT_FAILURE);
+}
+
+/*
+ * Do one round of disambiguation-check symbol hashing, factoring in the current
+ * set of applicable shortened object file names for those symbols that need
+ * them.
+ */
+static void disambiguate_hash_syms(struct sym_maybe_collides *syms)
+{
+	size_t i;
+	for (i = 0; i < table_cnt; i++) {
+		struct obj2short_elem *short_objname = NULL;
+		char *tmp, *p;
+		size_t tmp_size;
+
+		if (syms[i].sym == NULL) {
+			syms[i].symhash = 0;
+			continue;
+		}
+
+		short_objname = obj2short_get(syms[i].addr->obj);
+
+		tmp_size = strlen((char *) &(syms[i].sym->sym[1])) + 1;
+
+		if (short_objname)
+			tmp_size += strlen(short_objname->short_obj) + 1;
+
+		if (syms[i].addr->objfile)
+			tmp_size += sizeof(syms[i].addr->objfile->modhash);
+
+		tmp = malloc(tmp_size);
+		if (tmp == NULL) {
+			fprintf(stderr, "Out of memory disambiguating syms\n");
+			exit(EXIT_FAILURE);
+		}
+
+		p = stpcpy(tmp, (char *) &(syms[i].sym->sym[1]));
+		p++;
+		if (short_objname) {
+			p = stpcpy(p, short_objname->short_obj);
+			p++;
+		}
+		if (syms[i].addr->objfile)
+			memcpy(p, &(syms[i].addr->objfile->modhash),
+			       sizeof(syms[i].addr->objfile->modhash));
+
+		syms[i].symhash = memhash(tmp, tmp_size);
+		free(tmp);
+	}
+
+	qsort(syms, table_cnt, sizeof (struct sym_maybe_collides), qsymhash);
+}
+
+/*
+ * Figure out which object file names are necessary to disambiguate all symbols
+ * in the linked kernel: transform them for minimum length while retaining
+ * disambiguity: point to them in obj2short.
+ */
+static void disambiguate_syms(void)
+{
+	size_t i;
+	int retry;
+	int hash_cycle = 0;
+	unsigned int lasthash;
+	struct sym_maybe_collides *syms;
+
+	syms = calloc(table_cnt, sizeof(struct sym_maybe_collides));
+
+	if (syms == NULL)
+		goto oom;
+
+	/*
+	 * Initial table population: symbol-dependent things not affected by
+	 * disambiguation rounds.
+	 */
+	for (i = 0; i < table_cnt; i++) {
+		struct addrmap_entry *addr;
+
+		/*
+		 * Only bother doing anything for function symbols.
+		 */
+		if (table[i]->sym[0] != 't' && table[i]->sym[0] != 'T' &&
+		    table[i]->sym[0] != 'w' && table[i]->sym[0] != 'W')
+			continue;
+
+		addr = bsearch(table[i], addrmap, addrmap_num,
+			       sizeof(struct addrmap_entry), find_addrmap);
+
+		/*
+		 * Some function symbols (section start symbols, discarded
+		 * non-text-range symbols, etc) don't appear in the linker map
+		 * at all.
+		 */
+		if (addr == NULL)
+			continue;
+
+		syms[i].sym = table[i];
+		syms[i].addr = addr;
+	}
+
+	do {
+		hash_cycle++;
+		retry = 0;
+		lasthash = 0;
+		disambiguate_hash_syms(syms);
+
+		for (i = 0; i < table_cnt; i++) {
+			if (syms[i].sym == NULL)
+				continue;
+			if (syms[i].symhash == lasthash) {
+				if (lengthen_short_name(&syms[i], hash_cycle))
+					retry = 1;
+			}
+			lasthash = syms[i].symhash;
+		}
+	} while (retry);
+
+	free(syms);
+	return;
+ oom:
+	fprintf(stderr, "kallsyms: out of memory disambiguating syms\n");
+	exit(EXIT_FAILURE);
+
+}
+
 #endif /* CONFIG_KALLMODSYMS */
 
 static void usage(void)
@@ -424,6 +803,7 @@ static bool is_ignored_symbol(const char *name, char type)
 		"kallsyms_relative_base",
 		"kallsyms_num_syms",
 		"kallsyms_num_modules",
+		"kallsyms_num_objfiles",
 		"kallsyms_names",
 		"kallsyms_markers",
 		"kallsyms_token_table",
@@ -431,6 +811,7 @@ static bool is_ignored_symbol(const char *name, char type)
 		"kallsyms_module_offsets",
 		"kallsyms_module_addresses",
 		"kallsyms_modules",
+		"kallsyms_objfiles",
 		"kallsyms_mod_objnames",
 		"kallsyms_mod_objnames_len",
 		/* Exclude linker generated symbols which vary between passes */
@@ -700,6 +1081,7 @@ static void output_address(unsigned long long addr)
 static void output_kallmodsyms_mod_objnames(void)
 {
 	struct obj2mod_elem *elem;
+	struct obj2short_elem *short_elem;
 	size_t offset = 1;
 	size_t i;
 
@@ -755,15 +1137,75 @@ static void output_kallmodsyms_mod_objnames(void)
 			}
 		}
 	}
+
+	/*
+	 * Module names are done; now emit objfile names that don't match
+	 * objfile names.  They go in the same section to enable deduplication
+	 * between (maximally-shortened) objfile names and module names.
+	 * (This is another reason why objfile names drop the suffix.)
+	 */
+	for (i = 0; i < OBJ2MOD_N; i++) {
+		for (short_elem = obj2short[i]; short_elem;
+		     short_elem = short_elem->short_next) {
+
+			/* Already emitted? */
+			if (short_elem->mod_xref)
+				continue;
+
+			if (short_elem->short_xref)
+				short_elem = short_elem->short_xref;
+
+			if (short_elem->short_offset != 0)
+				continue;
+
+			printf("/* 0x%lx: shortened from %s */\n", offset,
+			       short_elem->obj);
+
+			short_elem->short_offset = offset;
+			printf("\t.asciz\t\"%s\"\n", short_elem->short_obj);
+			offset += strlen(short_elem->short_obj) + 1;
+		}
+	}
+
 	printf("\n");
 	output_label("kallsyms_mod_objnames_len");
 	printf("\t.long\t%zi\n", offset);
 }
 
+/*
+ * Return 1 if this address range cites the same built-in module and objfile
+ * name as the previous one.
+ */
+static int same_kallmodsyms_range(int i)
+{
+	struct obj2short_elem *last_short;
+	struct obj2short_elem *this_short;
+	if (i == 0)
+		return 0;
+
+	last_short = obj2short_get(addrmap[i-1].obj);
+	this_short = obj2short_get(addrmap[i].obj);
+
+	if (addrmap[i-1].objfile == addrmap[i].objfile) {
+
+		if ((last_short == NULL && this_short != NULL) ||
+		    (last_short != NULL && this_short == NULL))
+			return 0;
+
+		if (last_short == NULL && this_short == NULL)
+			return 1;
+
+		if (strcmp(last_short->short_obj, this_short->short_obj) == 0)
+			return 1;
+	}
+	return 0;
+}
+
 static void output_kallmodsyms_objfiles(void)
 {
 	size_t i = 0;
 	size_t emitted_offsets = 0;
+	size_t emitted_modules = 0;
 	size_t emitted_objfiles = 0;
 
 	if (base_relative)
@@ -775,12 +1217,15 @@ static void output_kallmodsyms_objfiles(void)
 		long long offset;
 		int overflow;
 
-                /*
-                 * Fuse consecutive address ranges citing the same object file
-                 * into one.
-                 */
-                if (i > 0 && addrmap[i-1].objfile == addrmap[i].objfile)
-                        continue;
+		printf("/* 0x%llx--0x%llx: %s */\n", addrmap[i].addr,
+		       addrmap[i].end_addr, addrmap[i].obj);
+
+		/*
+		 * Fuse consecutive address ranges citing the same built-in
+		 * module and objfile name into one.
+		 */
+		if (same_kallmodsyms_range(i))
+			continue;
 
 		if (base_relative) {
 			if (!absolute_percpu) {
@@ -807,11 +1252,12 @@ static void output_kallmodsyms_objfiles(void)
 
 	for (i = 0; i < addrmap_num; i++) {
 		struct obj2mod_elem *elem = addrmap[i].objfile;
+		struct obj2mod_elem *orig_elem = NULL;
 		int orig_nmods;
 		const char *orig_modname;
 		int mod_offset;
 
-		if (i > 0 && addrmap[i-1].objfile == addrmap[i].objfile)
+		if (same_kallmodsyms_range(i))
 			continue;
 
 		/*
@@ -819,8 +1265,10 @@ static void output_kallmodsyms_objfiles(void)
 		 * built-in module.
 		 */
 		if (addrmap[i].objfile == NULL) {
+			printf("/* 0x%llx--0x%llx: %s: built-in */\n",
+			       addrmap[i].addr, addrmap[i].end_addr, addrmap[i].obj);
 			printf("\t.long\t0x0\n");
-			emitted_objfiles++;
+			emitted_modules++;
 			continue;
 		}
 
@@ -835,8 +1283,10 @@ static void output_kallmodsyms_objfiles(void)
 		 * always points at the start of the xref target, so its offset
 		 * can be used as is.
 		 */
-		if (elem->xref)
+		if (elem->xref) {
+			orig_elem = elem;
 			elem = elem->xref;
+		}
 
 		if (elem->nmods == 1 || orig_nmods > 1) {
 
@@ -872,6 +1322,19 @@ static void output_kallmodsyms_objfiles(void)
 			 * the multimodule entry.
 			 */
 			mod_offset += onemod - elem->mods + 2;
+
+			/*
+			 * If this was the result of an xref chase, store this
+			 * mod_offset in the original entry so we can just reuse
+			 * it if an objfile shares this name.
+			 */
+
+			printf("/* 0x%llx--0x%llx: %s: single-module ref to %s in multimodule at %x */\n",
+			       addrmap[i].addr, addrmap[i].end_addr,
+			       orig_elem->mods, onemod, elem->mod_offset);
+
+			if (orig_elem)
+				orig_elem->mod_offset = mod_offset;
 		}
 
 		/*
@@ -881,12 +1344,68 @@ static void output_kallmodsyms_objfiles(void)
 		assert(elem->mod_offset != 0);
 
 		printf("\t.long\t0x%x\n", mod_offset);
-		emitted_objfiles++;
+		emitted_modules++;
 	}
 
-	assert(emitted_offsets == emitted_objfiles);
+	assert(emitted_offsets == emitted_modules);
 	output_label("kallsyms_num_modules");
+	printf("\t.long\t%zi\n", emitted_modules);
+
+	output_label("kallsyms_objfiles");
+
+	for (i = 0; i < addrmap_num; i++) {
+		struct obj2short_elem *elem;
+		int mod_offset;
+
+		if (same_kallmodsyms_range(i))
+			continue;
+
+		/*
+		 * No corresponding objfile name: no disambiguation needed;
+		 * point at 0.
+		 */
+		elem = obj2short_get(addrmap[i].obj);
+
+		if (elem == NULL) {
+			printf("/* 0x%llx--0x%llx: %s: unambiguous */\n",
+			       addrmap[i].addr, addrmap[i].end_addr,
+			       addrmap[i].obj);
+			printf("\t.long\t0x0\n");
+			emitted_objfiles++;
+			continue;
+		}
+
+		/*
+		 * Maybe the name is also used for a module: if it is, it cannot
+		 * be a multimodule.
+		 */
+
+		if (elem->mod_xref) {
+			assert(elem->mod_xref->nmods == 1);
+			mod_offset = elem->mod_xref->mod_offset;
+			printf("/* 0x%llx--0x%llx: %s: shortened as %s, references module */\n",
+			       addrmap[i].addr, addrmap[i].end_addr,
+			       addrmap[i].obj, elem->short_obj);
+		} else {
+			/*
+			 * A name only used for objfiles.  Chase down xrefs to
+			 * reuse existing entries.
+			 */
+			if (elem->short_xref)
+				elem = elem->short_xref;
+
+			mod_offset = elem->short_offset;
+			printf("/* 0x%llx--0x%llx: %s: shortened as %s */\n",
+			       addrmap[i].addr, addrmap[i].end_addr,
+			       addrmap[i].obj, elem->short_obj);
+		}
+		printf("\t.long\t0x%x\n", mod_offset);
+		emitted_objfiles++;
+	}
+	assert(emitted_offsets == emitted_objfiles);
+	output_label("kallsyms_num_objfiles");
 	printf("\t.long\t%zi\n", emitted_objfiles);
+
 	printf("\n");
 }
 #endif /* CONFIG_KALLMODSYMS */
@@ -1430,6 +1949,20 @@ static void read_modules(const char *modules_builtin)
 	 * Read linker map.
 	 */
 	read_linker_map();
+
+	/*
+	 * Now the modules are sorted out and we know their address ranges, use
+	 * the modhashes computed in optimize_obj2mod to identify any symbols
+	 * that are still ambiguous and set up the minimal representation of
+	 * their objfile name to disambiguate them.
+	 */
+	disambiguate_syms();
+
+	/*
+	 * Now we have objfile names, optimize the objfile list.
+	 */
+	optimize_objnames();
+
 }
 #else
 static void read_modules(const char *unused) {}
Signature · 1 line
2.38.0.266.g481848f278
#28 lore raw

PATCH v9 7/8 kallsyms: add /proc/kallmodsyms for text symbol disambiguation

In reply to Nick Alcock

Use the tables added in the previous commits to introduce a new /proc/kallmodsyms, in which [module names] are also given for things that *could* have been modular had they not been built in to the kernel. So symbols that are part of, say, ext4 are reported as [ext4] even if ext4 happens to be buiilt in to the kernel in this configuration.

This helps disambiguate symbols with identical names when some are in built-in modules are some are not, but if symbols are still ambiguous, {object file names} are added as needed to disambiguate them. The object file names are only shown if they would prevent ambiguity, and are minimized by chopping off as many leading path components as possible without (symbol, module, objfile) combinations becoming ambiguous again. (Not every symbol with an {object file name} is necessarily ambiguous, but at least one symbol in any such object file would have been ambiguous if the object file was not mentioned.)

Symbols that are part of multiple modules at the same time are shown with [multiple] [module names]: consumers will have to be ready to handle such lines. Also, kernel symbols for built-in modules will be sorted by address, as usual for the core kernel, so will probably appear interspersed with other symbols that are part of different modules and non-modular always-built-in symbols, which, as usual, have no square-bracketed module denotation. This differs from /proc/kallsyms; even though /proc/kallsyms shows the same symbols as /proc/kallmodsyms in the same order, the only modules it names are loadable ones, which are necessarily in single contiguous blocks and thus shown contiguously.

The result looks like this: ([...] to show where lines are omitted for brevity):

ffffffff97606e50 t not_visible
ffffffff97606e70 T perf_msr_probe
ffffffff97606f80 t test_msr [rapl]
ffffffff97606fa0 t __rapl_pmu_event_start [rapl]
[...]

ffffffffa6007350 t rapl_pmu_event_stop  [rapl]
ffffffffa6007440 t rapl_pmu_event_del   [rapl]
ffffffffa6007460 t rapl_hrtimer_handle  [rapl]
ffffffffa6007500 t rapl_pmu_event_read  [rapl]
ffffffffa6007520 t rapl_pmu_event_init  [rapl]
ffffffffa6007630 t rapl_cpu_offline     [rapl]
ffffffffa6007710 t amd_pmu_event_map    {core.o}
ffffffffa6007750 t amd_pmu_add_event    {core.o}

ffffffffa6007760 t amd_put_event_constraints_f17h {core.o}

The [rapl] notation is emitted even if rapl is built into the kernel (but, obviously, not if it's not in the .config at all, or is in a loadable module that is not loaded). The {core.o} is an object file name.

Further down, we see what happens when object files are reused by multiple modules, all of which are built in to the kernel, and some of which have symbols that would be ambiguous without an object file name attached in addition to the module names:

ffffffff97d7aed0 t liquidio_pcie_mmio_enabled [liquidio]
ffffffff97d7aef0 t liquidio_pcie_resume [liquidio] ffffffff97d7af00 t liquidio_ptp_adjtime [liquidio] ffffffff97d7af50 t liquidio_ptp_enable [liquidio] ffffffff97d7af70 t liquidio_get_stats64 [liquidio]
ffffffff97d7b0f0 t liquidio_fix_features [liquidio]
ffffffff97d7b1c0 t liquidio_get_port_parent_id [liquidio] [...]
ffffffff97d824c0 t lio_vf_rep_modinit [liquidio]
ffffffff97d824f0 t lio_vf_rep_modexit [liquidio]
ffffffff97d82520 t lio_ethtool_get_channels [liquidio] [liquidio_vf]
ffffffff97d82600 t lio_ethtool_get_ringparam [liquidio] [liquidio_vf]

ffffffff97d826a0 t lio_get_msglevel     [liquidio] [liquidio_vf]
ffffffff97d826c0 t lio_vf_set_msglevel  [liquidio] [liquidio_vf]
ffffffff97d826e0 t lio_get_pauseparam   [liquidio] [liquidio_vf]

ffffffff97d82710 t lio_get_ethtool_stats [liquidio] [liquidio_vf]
ffffffff97d82e70 t lio_vf_get_ethtool_stats [liquidio] [liquidio_vf]
[...]
ffffffff97d91a80 t cn23xx_vf_mbox_thread [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d91aa0 t cpumask_weight.constprop.0 [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d91ac0 t cn23xx_vf_msix_interrupt_handler [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d91bd0 t cn23xx_vf_get_oq_ticks [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d91c00 t cn23xx_vf_ask_pf_to_do_flr [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d91c70 t cn23xx_octeon_pfvf_handshake [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d91e20 t cn23xx_setup_octeon_vf_device [liquidio] [liquidio_vf] {cn23xx_vf_device.o}
ffffffff97d92060 t octeon_mbox_read [liquidio] [liquidio_vf]
ffffffff97d92230 t octeon_mbox_write [liquidio] [liquidio_vf]
[...]
ffffffff97d946b0 t octeon_alloc_soft_command_resp [liquidio] [liquidio_vf]
ffffffff97d947e0 t octnet_send_nic_data_pkt [liquidio] [liquidio_vf]
ffffffff97d94820 t octnet_send_nic_ctrl_pkt [liquidio] [liquidio_vf]
ffffffff97d94ab0 t liquidio_get_stats64 [liquidio_vf]
ffffffff97d94c10 t liquidio_fix_features [liquidio_vf]
ffffffff97d94cd0 t wait_for_pending_requests [liquidio_vf]

Like /proc/kallsyms, the output is driven by address, so keeps the curious property of /proc/kallsyms that symbols may appear repeatedly with different addresses: but now, unlike in /proc/kallsyms, we can see that those symbols appear repeatedly because they are *different symbols* that ultimately belong to different modules or different object files within a module, all of which are built in to the kernel.

As with /proc/kallsyms, non-root usage produces addresses that are all zero.

I am not wedded to the name or format of /proc/kallmodsyms, but felt it best to split it out of /proc/kallsyms to avoid breaking existing kallsyms parsers.

This is currently driven by a new config option, but now that kallmodsyms data uses very little space, this option might be something people don't want to bother with: maybe we can just control it via CONFIG_KALLSYMS or something.

Internally, this uses a new kallsyms_builtin_module_address() almost identical to kallsyms_sym_address() to get the address corresponding to a given .kallsyms_modules index, and a new get_builtin_modobj_idx quite similar to get_symbol_pos to determine the index in the .kallsyms_modules and .kallsyms_objfiles arrays that relate to a given address. We save a little time by exploiting the fact that all callers will only ever traverse this list from start to end by allowing them to pass in the previous index returned from this function as a hint: thus very few bsearches are actually needed. (In theory this could change to just walk straight down kallsyms_module_addresses/offsets and not bother bsearching at all, but doing it this way is hardly any slower and much more robust.)

We explicitly filter out displaying modules for non-text symbols (perhaps this could be lifted for initialized data symbols in future). There might be occasional incorrect module or objfile names for section start/end symbols.

The display process is complicated a little by the weird format of the .kallsyms_mod_objnames table: we have to look for multimodule entries and print them as space-separated lists of module names.

---

Notes:
v9: add objfile support. Commit message adjustments.

 kernel/kallsyms.c          | 277 ++++++++++++++++++++++++++++++++++---
 kernel/kallsyms_internal.h |  14 ++
 2 files changed, 274 insertions(+), 17 deletions(-)
kernel/kallsyms.c +260 -17
index 60c20f301a6b..9667962173f1 100644
@@ -187,6 +187,25 @@ static bool cleanup_symbol_name(char *s)
 	return false;
 }
 
+#ifdef CONFIG_KALLMODSYMS
+static unsigned long kallsyms_builtin_module_address(int idx)
+{
+	if (!IS_ENABLED(CONFIG_KALLSYMS_BASE_RELATIVE))
+		return kallsyms_module_addresses[idx];
+
+	/* values are unsigned offsets if --absolute-percpu is not in effect */
+	if (!IS_ENABLED(CONFIG_KALLSYMS_ABSOLUTE_PERCPU))
+		return kallsyms_relative_base + (u32)kallsyms_module_offsets[idx];
+
+	/* ...otherwise, positive offsets are absolute values */
+	if (kallsyms_module_offsets[idx] >= 0)
+		return kallsyms_module_offsets[idx];
+
+	/* ...and negative offsets are relative to kallsyms_relative_base - 1 */
+	return kallsyms_relative_base - 1 - kallsyms_module_offsets[idx];
+}
+#endif
+
 /* Lookup the address for this symbol. Returns 0 if not found. */
 unsigned long kallsyms_lookup_name(const char *name)
 {
@@ -293,6 +312,54 @@ static unsigned long get_symbol_pos(unsigned long addr,
 	return low;
 }
 
+/*
+ * The caller passes in an address, and we return an index to the corresponding
+ * builtin module index in .kallsyms_modules and .kallsyms_objfiles, or
+ * (unsigned long) -1 if none match.
+ *
+ * The hint_idx, if set, is a hint as to the possible return value, to handle
+ * the common case in which consecutive runs of addresses relate to the same
+ * index.
+ */
+#ifdef CONFIG_KALLMODSYMS
+static unsigned long get_builtin_modobj_idx(unsigned long addr, unsigned long hint_idx)
+{
+	unsigned long low, high, mid;
+
+	if (!IS_ENABLED(CONFIG_KALLSYMS_BASE_RELATIVE))
+		BUG_ON(!kallsyms_module_addresses);
+	else
+		BUG_ON(!kallsyms_module_offsets);
+
+	/*
+	 * Do a binary search on the sorted kallsyms_modules array.  The last
+	 * entry in this array indicates the end of the text section, not an
+	 * object file.
+	 */
+	low = 0;
+	high = kallsyms_num_modules - 1;
+
+	if (hint_idx > low && hint_idx < (high - 1) &&
+	    addr >= kallsyms_builtin_module_address(hint_idx) &&
+	    addr < kallsyms_builtin_module_address(hint_idx + 1))
+		return hint_idx;
+
+	if (addr >= kallsyms_builtin_module_address(low)
+	    && addr < kallsyms_builtin_module_address(high)) {
+		while (high - low > 1) {
+			mid = low + (high - low) / 2;
+			if (kallsyms_builtin_module_address(mid) <= addr)
+				low = mid;
+			else
+				high = mid;
+		}
+		return low;
+	}
+
+	return (unsigned long) -1;
+}
+#endif
+
 /*
  * Lookup an address but don't bother to find any names.
  */
@@ -564,6 +631,9 @@ struct kallsym_iter {
 	char type;
 	char name[KSYM_NAME_LEN];
 	char module_name[MODULE_NAME_LEN];
+	const char *builtin_module_names;
+	const char *builtin_objfile_name;
+	unsigned long hint_builtin_modobj_idx;
 	int exported;
 	int show_value;
 };
@@ -594,6 +664,9 @@ static int get_ksymbol_mod(struct kallsym_iter *iter)
 				     &iter->value, &iter->type,
 				     iter->name, iter->module_name,
 				     &iter->exported);
+	iter->builtin_module_names = NULL;
+	iter->builtin_objfile_name = NULL;
+
 	if (ret < 0) {
 		iter->pos_mod_end = iter->pos;
 		return 0;
@@ -613,6 +686,9 @@ static int get_ksymbol_ftrace_mod(struct kallsym_iter *iter)
 					 &iter->value, &iter->type,
 					 iter->name, iter->module_name,
 					 &iter->exported);
+	iter->builtin_module_names = NULL;
+	iter->builtin_objfile_name = NULL;
+
 	if (ret < 0) {
 		iter->pos_ftrace_mod_end = iter->pos;
 		return 0;
@@ -627,6 +703,8 @@ static int get_ksymbol_bpf(struct kallsym_iter *iter)
 
 	strlcpy(iter->module_name, "bpf", MODULE_NAME_LEN);
 	iter->exported = 0;
+	iter->builtin_module_names = NULL;
+	iter->builtin_objfile_name = NULL;
 	ret = bpf_get_kallsym(iter->pos - iter->pos_ftrace_mod_end,
 			      &iter->value, &iter->type,
 			      iter->name);
@@ -647,23 +725,74 @@ static int get_ksymbol_kprobe(struct kallsym_iter *iter)
 {
 	strlcpy(iter->module_name, "__builtin__kprobes", MODULE_NAME_LEN);
 	iter->exported = 0;
+	iter->builtin_module_names = NULL;
+	iter->builtin_objfile_name = NULL;
 	return kprobe_get_kallsym(iter->pos - iter->pos_bpf_end,
 				  &iter->value, &iter->type,
 				  iter->name) < 0 ? 0 : 1;
 }
 
 /* Returns space to next name. */
-static unsigned long get_ksymbol_core(struct kallsym_iter *iter)
+static unsigned long get_ksymbol_core(struct kallsym_iter *iter, int kallmodsyms)
 {
 	unsigned off = iter->nameoff;
 
-	iter->module_name[0] = '\0';
+	iter->exported = 0;
 	iter->value = kallsyms_sym_address(iter->pos);
 
 	iter->type = kallsyms_get_symbol_type(off);
 
+	iter->module_name[0] = '\0';
+	iter->builtin_module_names = NULL;
+	iter->builtin_objfile_name = NULL;
+
 	off = kallsyms_expand_symbol(off, iter->name, ARRAY_SIZE(iter->name));
+#ifdef CONFIG_KALLMODSYMS
+	if (kallmodsyms) {
+		unsigned long modobj_idx = (unsigned long) -1;
+
+		if (kallsyms_module_offsets)
+			modobj_idx =
+			  get_builtin_modobj_idx(iter->value,
+						 iter->hint_builtin_modobj_idx);
 
+		/*
+		 * This is a built-in module iff the tables of built-in modules
+		 * (address->module name mappings), object files (ditto), and
+		 * module/objfile names are known, and if the address was found
+		 * there, and if the corresponding module index is nonzero, and
+		 * iff this is a text (or weak) symbol.  All other cases mean
+		 * off the end of the binary or in a non-modular range in
+		 * between one or more modules.
+		 *
+		 * The same rules are true for kallsyms_objfiles, except that
+		 * zero entries are much more common because we only record
+		 * object file names if we need them to disambiguate one or more
+		 * symbols: see scripts/kallsyms.c:disambiguate_syms.
+		 *
+		 * (Also guard against corrupt kallsyms_modules or
+		 * kallsyms_objfiles arrays pointing off the end of
+		 * kallsyms_mod_objnames.)
+		 */
+		if (kallsyms_modules != NULL && kallsyms_mod_objnames != NULL &&
+		    kallsyms_objfiles != NULL &&
+		    (iter->type == 't' || iter->type == 'T' ||
+		     iter->type == 'w' || iter->type == 'W') &&
+		    modobj_idx != (unsigned long) -1) {
+
+			if (kallsyms_modules[modobj_idx] != 0 &&
+			    kallsyms_modules[modobj_idx] < kallsyms_mod_objnames_len)
+				iter->builtin_module_names =
+					&kallsyms_mod_objnames[kallsyms_modules[modobj_idx]];
+
+			if (kallsyms_objfiles[modobj_idx] != 0 &&
+			    kallsyms_objfiles[modobj_idx] < kallsyms_mod_objnames_len)
+				iter->builtin_objfile_name =
+					&kallsyms_mod_objnames[kallsyms_objfiles[modobj_idx]];
+		}
+		iter->hint_builtin_modobj_idx = modobj_idx;
+	}
+#endif
 	return off - iter->nameoff;
 }
 
@@ -709,7 +838,7 @@ static int update_iter_mod(struct kallsym_iter *iter, loff_t pos)
 }
 
 /* Returns false if pos at or past end of file. */
-static int update_iter(struct kallsym_iter *iter, loff_t pos)
+static int update_iter(struct kallsym_iter *iter, loff_t pos, int kallmodsyms)
 {
 	/* Module symbols can be accessed randomly. */
 	if (pos >= kallsyms_num_syms)
@@ -719,7 +848,7 @@ static int update_iter(struct kallsym_iter *iter, loff_t pos)
 	if (pos != iter->pos)
 		reset_iter(iter, pos);
 
-	iter->nameoff += get_ksymbol_core(iter);
+	iter->nameoff += get_ksymbol_core(iter, kallmodsyms);
 	iter->pos++;
 
 	return 1;
@@ -729,14 +858,14 @@ static void *s_next(struct seq_file *m, void *p, loff_t *pos)
 {
 	(*pos)++;
 
-	if (!update_iter(m->private, *pos))
+	if (!update_iter(m->private, *pos, 0))
 		return NULL;
 	return p;
 }
 
 static void *s_start(struct seq_file *m, loff_t *pos)
 {
-	if (!update_iter(m->private, *pos))
+	if (!update_iter(m->private, *pos, 0))
 		return NULL;
 	return m->private;
 }
@@ -745,7 +874,7 @@ static void s_stop(struct seq_file *m, void *p)
 {
 }
 
-static int s_show(struct seq_file *m, void *p)
+static int s_show_internal(struct seq_file *m, void *p, int kallmodsyms)
 {
 	void *value;
 	struct kallsym_iter *iter = m->private;
@@ -756,23 +885,82 @@ static int s_show(struct seq_file *m, void *p)
 
 	value = iter->show_value ? (void *)iter->value : NULL;
 
-	if (iter->module_name[0]) {
+	/*
+	 * Real module, or built-in module and /proc/kallsyms being shown.
+	 */
+	if (iter->module_name[0] != '\0' ||
+	    (iter->builtin_module_names != NULL && kallmodsyms != 0)) {
 		char type;
 
 		/*
-		 * Label it "global" if it is exported,
-		 * "local" if not exported.
+		 * Label it "global" if it is exported, "local" if not exported.
 		 */
 		type = iter->exported ? toupper(iter->type) :
 					tolower(iter->type);
-		seq_printf(m, "%px %c %s\t[%s]\n", value,
-			   type, iter->name, iter->module_name);
-	} else
-		seq_printf(m, "%px %c %s\n", value,
+#ifdef CONFIG_KALLMODSYMS
+		if (kallmodsyms) {
+			/*
+			 * /proc/kallmodsyms, built as a module.
+			 */
+			if (iter->builtin_module_names == NULL)
+				seq_printf(m, "%px %c %s\t[%s]", value,
+					   type, iter->name,
+					   iter->module_name);
+			/*
+			 * /proc/kallmodsyms, single-module symbol.
+			 */
+			else if (*iter->builtin_module_names != '\0')
+				seq_printf(m, "%px %c %s\t[%s]", value,
+					   type, iter->name,
+					   iter->builtin_module_names);
+			/*
+			 * /proc/kallmodsyms, multimodule symbol.  Formatted
+			 * as \0MODULE_COUNTmodule-1\0module-2\0, where
+			 * MODULE_COUNT is a single byte, 2 or higher.
+			 */
+			else {
+				size_t i = *(char *)(iter->builtin_module_names + 1);
+				const char *walk = iter->builtin_module_names + 2;
+
+				seq_printf(m, "%px %c %s\t[%s]", value,
+					   type, iter->name, walk);
+
+                                while (--i > 0) {
+					walk += strlen(walk) + 1;
+					seq_printf(m, " [%s]", walk);
+				}
+			}
+			/*
+			 * Possibly there is an objfile name too, if needed to
+			 * disambiguate at least one symbol.
+			 */
+			if (iter->builtin_objfile_name)
+				seq_printf(m, " {%s.o}", iter->builtin_objfile_name);
+
+			seq_printf(m, "\n");
+		} else				/* !kallmodsyms */
+#endif /* CONFIG_KALLMODSYMS */
+			seq_printf(m, "%px %c %s\t[%s]\n", value,
+				   type, iter->name, iter->module_name);
+	} else {
+		seq_printf(m, "%px %c %s", value,
 			   iter->type, iter->name);
+#ifdef CONFIG_KALLMODSYMS
+		if (kallmodsyms) {
+			if (iter->builtin_objfile_name)
+				seq_printf(m, "\t{%s.o}", iter->builtin_objfile_name);
+		}
+#endif /* CONFIG_KALLMODSYMS */
+		seq_printf(m, "\n");
+	}
 	return 0;
 }
 
+static int s_show(struct seq_file *m, void *p)
+{
+	return s_show_internal(m, p, 0);
+}
+
 static const struct seq_operations kallsyms_op = {
 	.start = s_start,
 	.next = s_next,
@@ -780,6 +968,36 @@ static const struct seq_operations kallsyms_op = {
 	.show = s_show
 };
 
+#ifdef CONFIG_KALLMODSYMS
+static int s_mod_show(struct seq_file *m, void *p)
+{
+	return s_show_internal(m, p, 1);
+}
+
+static void *s_mod_next(struct seq_file *m, void *p, loff_t *pos)
+{
+	(*pos)++;
+
+	if (!update_iter(m->private, *pos, 1))
+		return NULL;
+	return p;
+}
+
+static void *s_mod_start(struct seq_file *m, loff_t *pos)
+{
+	if (!update_iter(m->private, *pos, 1))
+		return NULL;
+	return m->private;
+}
+
+static const struct seq_operations kallmodsyms_op = {
+	.start = s_mod_start,
+	.next = s_mod_next,
+	.stop = s_stop,
+	.show = s_mod_show
+};
+#endif
+
 #ifdef CONFIG_BPF_SYSCALL
 
 struct bpf_iter__ksym {
@@ -905,7 +1123,8 @@ bool kallsyms_show_value(const struct cred *cred)
 	}
 }
 
-static int kallsyms_open(struct inode *inode, struct file *file)
+static int kallsyms_open_internal(struct inode *inode, struct file *file,
+	const struct seq_operations *ops)
 {
 	/*
 	 * We keep iterator in m->private, since normal case is to
@@ -913,7 +1132,7 @@ static int kallsyms_open(struct inode *inode, struct file *file)
 	 * using get_symbol_offset for every symbol.
 	 */
 	struct kallsym_iter *iter;
-	iter = __seq_open_private(file, &kallsyms_op, sizeof(*iter));
+	iter = __seq_open_private(file, ops, sizeof(*iter));
 	if (!iter)
 		return -ENOMEM;
 	reset_iter(iter, 0);
@@ -926,6 +1145,18 @@ static int kallsyms_open(struct inode *inode, struct file *file)
 	return 0;
 }
 
+static int kallsyms_open(struct inode *inode, struct file *file)
+{
+	return kallsyms_open_internal(inode, file, &kallsyms_op);
+}
+
+#ifdef CONFIG_KALLMODSYMS
+static int kallmodsyms_open(struct inode *inode, struct file *file)
+{
+	return kallsyms_open_internal(inode, file, &kallmodsyms_op);
+}
+#endif
+
 #ifdef	CONFIG_KGDB_KDB
 const char *kdb_walk_kallsyms(loff_t *pos)
 {
@@ -936,7 +1167,7 @@ const char *kdb_walk_kallsyms(loff_t *pos)
 		reset_iter(&kdb_walk_kallsyms_iter, 0);
 	}
 	while (1) {
-		if (!update_iter(&kdb_walk_kallsyms_iter, *pos))
+		if (!update_iter(&kdb_walk_kallsyms_iter, *pos, 0))
 			return NULL;
 		++*pos;
 		/* Some debugging symbols have no name.  Ignore them. */
@@ -953,9 +1184,21 @@ static const struct proc_ops kallsyms_proc_ops = {
 	.proc_release	= seq_release_private,
 };
 
+#ifdef CONFIG_KALLMODSYMS
+static const struct proc_ops kallmodsyms_proc_ops = {
+	.proc_open	= kallmodsyms_open,
+	.proc_read	= seq_read,
+	.proc_lseek	= seq_lseek,
+	.proc_release	= seq_release_private,
+};
+#endif
+
 static int __init kallsyms_init(void)
 {
 	proc_create("kallsyms", 0444, NULL, &kallsyms_proc_ops);
+#ifdef CONFIG_KALLMODSYMS
+	proc_create("kallmodsyms", 0444, NULL, &kallmodsyms_proc_ops);
+#endif
 	return 0;
 }
 device_initcall(kallsyms_init);
kernel/kallsyms_internal.h +14 -0
index 2d0c6f2f0243..0ee6d97b732e 100644
@@ -22,8 +22,22 @@ __section(".rodata") __attribute__((weak));
 extern const unsigned long kallsyms_relative_base
 __section(".rodata") __attribute__((weak));
 
+extern const unsigned long kallsyms_num_modules
+__section(".rodata") __attribute__((weak));
+
+extern const unsigned long kallsyms_num_objfiles
+__section(".rodata") __attribute__((weak));
+
+extern const unsigned long kallsyms_mod_objnames_len
+__section(".rodata") __attribute__((weak));
+
 extern const char kallsyms_token_table[] __weak;
 extern const u16 kallsyms_token_index[] __weak;
+extern const unsigned long kallsyms_module_addresses[] __weak;
+extern const int kallsyms_module_offsets[] __weak;
+extern const u32 kallsyms_modules[] __weak;
+extern const u32 kallsyms_objfiles[] __weak;
+extern const char kallsyms_mod_objnames[] __weak;
 
 extern const unsigned int kallsyms_markers[] __weak;
 
Signature · 1 line
2.38.0.266.g481848f278
maintainer
#29 lore raw

Re: [PATCH v9 7/8] kallsyms: add /proc/kallmodsyms for text symbol disambiguation

Quoted 3 lines · Nick Alcock

This helps disambiguate symbols with identical names when some are in built-in modules are some are not, but if symbols are still ambiguous, {object file names} are added as needed to disambiguate them.

*Why* would we ever want to trouble ourselves with expanding all this data into the kernel? The commit log does a poor effort to describe any value-add doing this could ever have.

Quoted 3 lines

I am not wedded to the name or format of /proc/kallmodsyms, but felt it best to split it out of /proc/kallsyms to avoid breaking existing kallsyms parsers.

I'd like much more review from other parties other than Oracle on this then. If this is generally useful, I'd image interested parties would be raving about all this but so far I don't see it. Please try to engage folks outside of Oracle.

Luis

#30 lore raw

Re: [PATCH v9 7/8] kallsyms: add /proc/kallmodsyms for text symbol disambiguation

Quoted 8 lines · Luis Chamberlain
Quoted 3 lines · Nick Alcock

This helps disambiguate symbols with identical names when some are in built-in modules are some are not, but if symbols are still ambiguous, {object file names} are added as needed to disambiguate them.

*Why* would we ever want to trouble ourselves with expanding all this data into the kernel? The commit log does a poor effort to describe any value-add doing this could ever have.

Er... the cover letter says:

Quoted 6 lines

The whole point of symbols is that their names are unique: you can look up a symbol and get back a unique address, and vice versa. Alas, because /proc/kallsyms (rightly) reports all symbols, even hidden ones, it does not really satisfy this requirement. Large numbers of symbols are duplicated many times (just search for __list_del_entry!), and while usually these are just out-of-lined things defined in header files and thus all have the same

Quoted 8 lines

implementation, it does make it needlessly hard to figure out which one is which in stack dumps, when tracing, and such things. Right now the kernel has no way at all to tell these apart, and nor has the user: their address differs and that's all. Which module did they come from? Which object file? We don't know. Figuring out which is which when tracing needs a combination of guesswork and luck. In discussions at LPC it became clear that this is not just annoying me but Steve Rostedt and others, so it's probably desirable to fix this.

This *is* the motivation. Previous iterations of this series only added module names, but that doesn't disambiguate all symbols, and only *partially* disambiguating symbols isn't really much use. If all symbols can be completely unambiguously identified (via a triplet of (name, module, translation unit), and mapped to a single address, you can be sure that you can unambiguously cite a single such triple and get a single address back, and vice versa: e.g. trace output could finally give you names that you could be sure came from one specific place, and thus often with one particular caller, even if that symbol appears in fifty different places in the kernel with callers in fifty different translation units that do quite different things.

(Plus, with notational additions in tracers, you could in future use this to trace, say, only *one* instance of __list_del_entry, rather than being forced to either trace all of them or none, or guess which entry was which and do a tiresome binary search of repeated traces to get the right one after lots of trials.)

(And also it's not actually that much data any more: 10KiB or so. :) )

I can add some of this to the commit log too if you like. (As noted in earlier messages -- which you haven't yet had time to read -- I was trying to keep that sort of duplication down, perhaps unwisely.)

Quoted 5 lines
Quoted 3 lines

I am not wedded to the name or format of /proc/kallmodsyms, but felt it best to split it out of /proc/kallsyms to avoid breaking existing kallsyms parsers.

I'd like much more review from other parties other than Oracle on this then.

Well, yes. That's what these postings are all about. If I was supposed to get review from someone else as well, I'm happy to add those people to the Cc: of future iterations.

maintainer
#31 lore raw

Re: [PATCH v9 7/8] kallsyms: add /proc/kallmodsyms for text symbol disambiguation

Quoted 5 lines · Nick Alcock
Quoted 1 line

I'd like much more review from other parties other than Oracle on this then.

Well, yes. That's what these postings are all about. If I was supposed to get review from someone else as well, I'm happy to add those people to the Cc: of future iterations.

Yes, given Zhen is active on the same exact area I figured his input would be of great value here too. I'd be wonderful if you can get those eager to see this upstream on the toolside too.

Luis

#32 lore raw

PATCH v9 8/8 perf: proof-of-concept kallmodsyms support

In reply to Nick Alcock

This is only very partial: it adds support to 'perf kallsyms', allowing you to say, e.g.

% ./perf kallsyms __scsi_device_lookup
__scsi_device_lookup: scsi_mod (built-in) 0xffffffff9b901de0-0xffffffff9b901e30 (0xffffffff9b901de0-0xffffffff9b901e30)

and get told that this is in a built-in module. We also handle symbols that are in multiple modules at once:

% ./perf kallsyms lio_set_fecparam
lio_set_fecparam: liquidio, liquidio_vf (built-in) 0xffffffff9b934da0-0xffffffff9b934e10 (0xffffffff9b934da0-0xffffffff9b934e10)

We do this the simplistic way, by augmenting symbols with a module array field, the members of which are atoms in a new machine.modules red-black tree (structured the same, and managed with the same code, as the existing transient tree that is used to compare /proc/modules against each other).

kallsyms symbols no longer carry a [module name] around with them that needs cutting off whenever it's used (all users that relied on this adjusted, I hope) but instead have that name hived off into the per-symbol module array, with a new 'built_in' field to tell users whether this is a built-in module or not. Since we cannot use the presence of '[' to detect modules any more, we do it at kallmodsyms read time by spotting _end and considering it to denote the end of the core kernel and the start of the modular range. (I *think* this works on all arches.)

---
 tools/perf/builtin-kallsyms.c |  35 +++++-
 tools/perf/util/event.c       |  14 ++-
 tools/perf/util/machine.c     |   6 +-
 tools/perf/util/machine.h     |   1 +
 tools/perf/util/symbol.c      | 207 +++++++++++++++++++++++++---------
 tools/perf/util/symbol.h      |  12 +-
 6 files changed, 211 insertions(+), 64 deletions(-)
tools/perf/builtin-kallsyms.c +31 -4
index c08ee81529e8..6bcec2522d2d 100644
@@ -35,10 +35,37 @@ static int __cmd_kallsyms(int argc, const char **argv)
 			continue;
 		}
 
-		printf("%s: %s %s %#" PRIx64 "-%#" PRIx64 " (%#" PRIx64 "-%#" PRIx64")\n",
-			symbol->name, map->dso->short_name, map->dso->long_name,
-			map->unmap_ip(map, symbol->start), map->unmap_ip(map, symbol->end),
-			symbol->start, symbol->end);
+		if (!symbol->modules) {
+			printf("%s: %s %s %#" PRIx64 "-%#" PRIx64 " (%#" PRIx64 "-%#" PRIx64")\n",
+			       symbol->name, map->dso->short_name, map->dso->long_name,
+			       map->unmap_ip(map, symbol->start), map->unmap_ip(map, symbol->end),
+			       symbol->start, symbol->end);
+		} else {
+			if (!symbol->built_in)
+				printf("%s: %s %s %#" PRIx64 "-%#" PRIx64 " (%#" PRIx64 "-%#" PRIx64")\n",
+				       symbol->name, map->dso->short_name, map->dso->long_name,
+				       map->unmap_ip(map, symbol->start), map->unmap_ip(map, symbol->end),
+				       symbol->start, symbol->end);
+			else if (symbol->modules[1] == 0)
+				printf("%s: %s (built-in) %#" PRIx64 "-%#" PRIx64 " (%#" PRIx64 "-%#" PRIx64")\n",
+				       symbol->name, symbol->modules[0], map->unmap_ip(map, symbol->start),
+				       map->unmap_ip(map, symbol->end), symbol->start, symbol->end);
+			else { /* Symbol in multiple modules at once  */
+				char **mod;
+
+				printf("%s: ", symbol->name);
+
+				for (mod = symbol->modules; *mod; mod++) {
+					if (mod != symbol->modules)
+						printf(", ");
+					printf("%s", *mod);
+				}
+
+				printf (" (built-in) %#" PRIx64 "-%#" PRIx64 " (%#" PRIx64 "-%#" PRIx64")\n",
+				       map->unmap_ip(map, symbol->start), map->unmap_ip(map, symbol->end),
+					symbol->start, symbol->end);
+			}
+		}
 	}
 
 	machine__delete(machine);
tools/perf/util/event.c +13 -1
index 1fa14598b916..a344b35f7e38 100644
@@ -97,16 +97,28 @@ static int find_symbol_cb(void *arg, const char *name, char type,
 			  u64 start)
 {
 	struct process_symbol_args *args = arg;
+	char *chop, *tmp_alloc = NULL;
+	const char *tmp = name;
+
+	if ((chop = strchr(name, '\t')) != NULL) {
+		tmp_alloc = strndup(name, name - chop);
+		if (tmp_alloc == NULL)
+			return -ENOMEM;
+		tmp = tmp_alloc;
+	}
 
 	/*
 	 * Must be a function or at least an alias, as in PARISC64, where "_text" is
 	 * an 'A' to the same address as "_stext".
 	 */
 	if (!(kallsyms__is_function(type) ||
-	      type == 'A') || strcmp(name, args->name))
+	      type == 'A') || strcmp(tmp, args->name)) {
+		free(tmp_alloc);
 		return 0;
+	}
 
 	args->start = start;
+	free(tmp_alloc);
 	return 1;
 }
 
tools/perf/util/machine.c +4 -2
index 76316e459c3d..2be5a3c1a267 100644
@@ -173,7 +173,7 @@ struct machine *machine__new_kallsyms(void)
 	 *    ask for not using the kcore parsing code, once this one is fixed
 	 *    to create a map per module.
 	 */
-	if (machine && machine__load_kallsyms(machine, "/proc/kallsyms") <= 0) {
+	if (machine && machine__load_kallsyms(machine, "/proc/kallmodsyms") <= 0) {
 		machine__delete(machine);
 		machine = NULL;
 	}
@@ -237,6 +237,7 @@ void machine__exit(struct machine *machine)
 	zfree(&machine->mmap_name);
 	zfree(&machine->current_tid);
 	zfree(&machine->kallsyms_filename);
+	modules__delete_modules(&machine->modules);
 
 	for (i = 0; i < THREADS__TABLE_SIZE; i++) {
 		struct threads *threads = &machine->threads[i];
@@ -1410,7 +1411,8 @@ int machines__create_kernel_maps(struct machines *machines, pid_t pid)
 int machine__load_kallsyms(struct machine *machine, const char *filename)
 {
 	struct map *map = machine__kernel_map(machine);
-	int ret = __dso__load_kallsyms(map->dso, filename, map, true);
+	int ret = __dso__load_kallsyms(map->dso, filename, map, &machine->modules,
+				       true);
 
 	if (ret > 0) {
 		dso__set_loaded(map->dso);
tools/perf/util/machine.h +1 -0
index 74935dfaa937..393063840cd1 100644
@@ -55,6 +55,7 @@ struct machine {
 	struct dsos	  dsos;
 	struct maps	  *kmaps;
 	struct map	  *vmlinux_map;
+	struct rb_root	  modules;
 	u64		  kernel_start;
 	pid_t		  *current_tid;
 	size_t		  current_tid_sz;
tools/perf/util/symbol.c +152 -55

393 lines not on this page · raw message

tools/perf/util/symbol.h +10 -2
index 0b893dcc8ea6..9ca218e09acf 100644
@@ -66,6 +66,11 @@ struct symbol {
 	u8		annotate2:1;
 	/** Architecture specific. Unused except on PPC where it holds st_other. */
 	u8		arch_sym;
+	/** Null-terminated array of pointers to names of containing modules in the
+	    modules red-black tree.  May be NULL for none.  */
+	char		**modules;
+	/** Set if this symbol is built in to the core kernel.  */
+	int		built_in;
 	/** The name of length namelen associated with the symbol. */
 	char		name[];
 };
@@ -137,8 +142,9 @@ int dso__load_vmlinux(struct dso *dso, struct map *map,
 		      const char *vmlinux, bool vmlinux_allocated);
 int dso__load_vmlinux_path(struct dso *dso, struct map *map);
 int __dso__load_kallsyms(struct dso *dso, const char *filename, struct map *map,
-			 bool no_kcore);
-int dso__load_kallsyms(struct dso *dso, const char *filename, struct map *map);
+			 struct rb_root *modules, bool no_kcore);
+int dso__load_kallsyms(struct dso *dso, const char *filename, struct map *map,
+		       struct rb_root *modules);
 
 void dso__insert_symbol(struct dso *dso,
 			struct symbol *sym);
@@ -161,6 +167,8 @@ int sysfs__read_build_id(const char *filename, struct build_id *bid);
 int modules__parse(const char *filename, void *arg,
 		   int (*process_module)(void *arg, const char *name,
 					 u64 start, u64 size));
+void modules__delete_modules(struct rb_root *modules);
+
 int filename__read_debuglink(const char *filename, char *debuglink,
 			     size_t size);
 
Signature · 1 line
2.38.0.266.g481848f278