Skip to contentSkip to conversation

perf script: Lazy symbol loading

PATCH Applied Alireza Haghdoost 4 participants 21 messages Oct 28 – Nov 15 perf events

v6 of 8 Applied Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v6 cover perf script: Lazy symbol loading

perf script loads the entire ELF symbol table of every DSO that appears in a sample, and keeps each symbol, with its demangled name, until process exit. Most of those symbols are never sampled. On a large profile this turns symbol loading into the main memory cost of perf script, and in a memory-constrained cgroup into an OOM kill.

This series adds an opt-in lazy loader for userspace ELF DSOs, after a regression fix and two preparatory patches:

[1/5] Fix a broken "#ifdef ELF_C_READ_MMAP" guard so perf actually
mmaps ELF files instead of malloc'ing section data. This is a standalone regression fix for 22dd1ac91a77, which Ian's series
[1] also depends on.

[2/5] Split the size, type and binding checks out of
choose_best_symbol(), so that the loader can tell which aliases need their names. No functional change.

[3/5] Make the symbol name a pointer instead of a flexible array, so
that a name can be set after the symbol is in the rb-tree.

[4/5] Add --lazy-load-symbols to load symbol names lazily.

[5/5] Unit and shell tests.

On a perf script run over a 45,073-sample callchain profile of a large C++ service (about 1M symbols), the output is identical in all four cases (medians of five runs):

                                      time    max RSS
  perf-tools-next                     3.3 s   334 MiB
  v6                                  3.2 s   341 MiB
  v6 --lazy-load-symbols              1.5 s   154 MiB
  v5 --lazy-load-symbols              1.4 s   136 MiB

Eager loading remains the default, and costs 8 more bytes per symbol for the name pointer. Lazy loading covers userspace ELF .symtab and .dynsym. The kernel, modules, PPC64 .opd and .gnu_debugdata still load names eagerly.

Ian's series [1], which removes the priv area and replaces the rb-tree with an array, would shrink each symbol further. This series does not depend on it, and I'll rebase on it if it lands first.

[1] https://lore.kernel.org/all/[email protected]/

Changes in v6:

- Keep the symbols in struct symbol and load only their names lazily, instead of v5's separate per-DSO index (Namhyung).
- Drop v5 2/5 ("perf dso: Allow reading DSO data from an explicit file"). Names are read with pread() from the symbol-table file that dso__get_filename() returns. The file remains open only while perf reads the names. This path does not use the data cache (Namhyung).
- Replace v5 3/5 ("perf symbols: Factor out duplicate symbol selection") with 2/5, which only splits out the name-independent checks. struct symbol_candidate is gone, and choose_best_symbol() still takes struct symbol (Ian's v4 question).
- New 3/5: point to the symbol name instead of embedding it.
- 4/5: rewritten for the new design.
- 5/5: replace the index tests (truncated names, lazy address and name lookup, nested range lookup, address lookups racing name lookups, lookups racing DSO data reads) with tests of long and unreadable lazy names and of names loaded concurrently. The duplicate selection test now checks which pairs need names. The eager/lazy parity unit test, the parity shell test and the perf script shell test stay. The parity shell test drops its nested symbol case, since both modes now share the same address lookup. The perf script shell test compares the whole output, and reports a skip only if none of its cases can run.
- Rebase onto current perf-tools-next.

Previous versions:

v5: https://lore.kernel.org/all/[email protected]/
v4: https://lore.kernel.org/all/[email protected]/
v3: https://lore.kernel.org/all/[email protected]/
v2: https://lore.kernel.org/all/[email protected]/
v1: https://lore.kernel.org/all/[email protected]/

---
Alireza Haghdoost (5):
perf symbols: Fix broken ELF_C_READ_MMAP fallback guard perf symbols: Split out name-independent duplicate symbol selection perf symbols: Point to the symbol name instead of embedding it perf script: Add --lazy-load-symbols to load symbol names lazily perf test: Test lazy symbol name loading

 tools/perf/Documentation/perf-script.txt           |   7 +
 tools/perf/builtin-script.c                        |   2 +
 tools/perf/tests/Build                             |   1 +
 tools/perf/tests/builtin-test.c                    |   1 +
 tools/perf/tests/shell/lazy_load_symbols_parity.sh | 284 +++++++++++
 tools/perf/tests/shell/script_lazy_load_symbols.sh | 177 +++++++
 tools/perf/tests/symbol-lazy.c                     | 544 +++++++++++++++++++++
 tools/perf/tests/tests.h                           |   1 +
 tools/perf/ui/browsers/map.c                       |   2 +-
 tools/perf/ui/stdio/hist.c                         |   1 +
 tools/perf/util/dso.c                              |   2 +-
 tools/perf/util/dso.h                              |   3 +-
 tools/perf/util/symbol-elf.c                       | 251 +++++++++-
 tools/perf/util/symbol-minimal.c                   |   6 +
 tools/perf/util/symbol.c                           | 140 +++++-
 tools/perf/util/symbol.h                           |  40 +-
 tools/perf/util/symbol_conf.h                      |   1 +
 17 files changed, 1429 insertions(+), 34 deletions(-)

---
base-commit: e74880764bf94b738102b4b6b6e8304d0c8375d3
change-id: 20260915-perf-symbol-memory-send-e7cfca1ac3d9

Best regards,

Signature · 1 line
Alireza Haghdoost <[email protected]>
#1 lore raw

PATCH v6 1/5 perf symbols: Fix broken ELF_C_READ_MMAP fallback guard

Commit 22dd1ac91a77 ("tools: Remove feature-libelf-mmap feature detection") replaced perf's compile-time feature test with an #ifdef on ELF_C_READ_MMAP. ELF_C_READ_MMAP is an Elf_Cmd enumerator rather than a preprocessor macro, so the condition is always false and perf silently uses ELF_C_READ.

Perf already requires a sufficiently recent elfutils version that provides ELF_C_READ_MMAP. Use the enumerator directly instead of restoring a feature probe or retaining an unreachable fallback.

Fixes 22dd1ac91a77 ("tools: Remove feature-libelf-mmap feature detection")
---
 tools/perf/util/symbol.h | 10 +---------
 1 file changed, 1 insertion(+), 9 deletions(-)
tools/perf/util/symbol.h +1 -9
index d0bac824c79c..46b1649c64fc 100644
@@ -57,15 +57,7 @@ static inline bool is_livepatch_symbol(const char *str)
 	return strstarts(str, KLP_SYM_PREFIX);
 }
 
-/*
- * libelf 0.8.x and earlier do not support ELF_C_READ_MMAP;
- * for newer versions we can use mmap to reduce memory usage:
- */
-#ifdef ELF_C_READ_MMAP
-# define PERF_ELF_C_READ_MMAP ELF_C_READ_MMAP
-#else
-# define PERF_ELF_C_READ_MMAP ELF_C_READ
-#endif
+#define PERF_ELF_C_READ_MMAP ELF_C_READ_MMAP
 
 #ifdef HAVE_LIBELF_SUPPORT
 Elf_Scn *elf_section_by_name(Elf *elf, GElf_Ehdr *ep,
Signature · 1 line
Git-157)
#2 lore raw

Re: [PATCH v6 1/5] perf symbols: Fix broken ELF_C_READ_MMAP fallback guard

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

From: Alireza Haghdoost <[email protected]>

Commit 22dd1ac91a77 ("tools: Remove feature-libelf-mmap feature detection") replaced perf's compile-time feature test with an #ifdef on ELF_C_READ_MMAP. ELF_C_READ_MMAP is an Elf_Cmd enumerator rather than a preprocessor macro, so the condition is always false and perf silently uses ELF_C_READ.

Quoted 6 lines

Perf already requires a sufficiently recent elfutils version that provides ELF_C_READ_MMAP. Use the enumerator directly instead of restoring a feature probe or retaining an unreachable fallback.

Fixes 22dd1ac91a77 ("tools: Remove feature-libelf-mmap feature detection")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
maintainer Applied
#3 lore raw

Re: [PATCH v6 1/5] perf symbols: Fix broken ELF_C_READ_MMAP fallback guard

In reply to Alireza Haghdoost
Quoted 6 lines · Alireza Haghdoost

Commit 22dd1ac91a77 ("tools: Remove feature-libelf-mmap feature detection") replaced perf's compile-time feature test with an #ifdef on ELF_C_READ_MMAP. ELF_C_READ_MMAP is an Elf_Cmd enumerator rather than a preprocessor macro, so the condition is always false and perf silently uses ELF_C_READ.

Quoted 8 lines

Perf already requires a sufficiently recent elfutils version that provides ELF_C_READ_MMAP. Use the enumerator directly instead of restoring a feature probe or retaining an unreachable fallback.

Fixes 22dd1ac91a77 ("tools: Remove feature-libelf-mmap feature detection")

Applied to perf-tools-next, thanks!

Best regards
Namhyung

#4 lore raw

PATCH v6 2/5 perf symbols: Split out name-independent duplicate symbol selection

In reply to Alireza Haghdoost

This patch is a refactoring and does not change behavior. It moves the size, type and binding checks from choose_best_symbol() to choose_best_symbol_by_attrs(). It also adds symbol__choice_needs_names() to report whether choosing between two symbols requires their names.

symbols__fixup_duplicate() keeps one of the symbols that share a start address. It compares size, type and binding first. If those attributes are equal, it compares leading underscores, name lengths and the result of arch__choose_best_symbol().

An unresolved lazy symbol stores a file offset instead of a name pointer. Thus, the lazy loader cannot call choose_best_symbol() until it loads both names. The new helper lets the loader keep the names unresolved when the attributes select a winner. It loads names only when the attributes are equal and duplicate selection needs them.

---
 tools/perf/util/symbol.c | 26 ++++++++++++++++++++++++--
 tools/perf/util/symbol.h |  1 +
 2 files changed, 25 insertions(+), 2 deletions(-)
tools/perf/util/symbol.c +24 -2
index b61a574ce9a3..2d611c05d000 100644
@@ -157,11 +157,15 @@ int __weak arch__choose_best_symbol(struct symbol *syma,
 	return SYMBOL_A;
 }
 
-static int choose_best_symbol(struct symbol *syma, struct symbol *symb)
+/*
+ * Choose between two symbols at the same address by size, type and binding.
+ * Returns SYMBOL_A or SYMBOL_B, or -1 if only their names can decide.
+ */
+static int choose_best_symbol_by_attrs(const struct symbol *syma,
+				       const struct symbol *symb)
 {
 	s64 a;
 	s64 b;
-	size_t na, nb;
 
 	/* Prefer a symbol with non zero length */
 	a = syma->end - syma->start;
@@ -194,6 +198,24 @@ static int choose_best_symbol(struct symbol *syma, struct symbol *symb)
 	if (b && !a)
 		return SYMBOL_B;
 
+	return -1;
+}
+
+bool symbol__choice_needs_names(const struct symbol *syma, const struct symbol *symb)
+{
+	return choose_best_symbol_by_attrs(syma, symb) < 0;
+}
+
+static int choose_best_symbol(struct symbol *syma, struct symbol *symb)
+{
+	int ret = choose_best_symbol_by_attrs(syma, symb);
+	s64 a;
+	s64 b;
+	size_t na, nb;
+
+	if (ret >= 0)
+		return ret;
+
 	/* Prefer a symbol with less underscores */
 	a = prefix_underscores_count(syma->name);
 	b = prefix_underscores_count(symb->name);
tools/perf/util/symbol.h +1 -0
index 46b1649c64fc..d8386c4a7fc5 100644
@@ -303,6 +303,7 @@ int arch__compare_symbol_names(const char *namea, const char *nameb);
 int arch__compare_symbol_names_n(const char *namea, const char *nameb,
 				 unsigned int n);
 int arch__choose_best_symbol(struct symbol *syma, struct symbol *symb);
+bool symbol__choice_needs_names(const struct symbol *syma, const struct symbol *symb);
 
 enum symbol_tag_include {
 	SYMBOL_TAG_INCLUDE__NONE = 0,
Signature · 1 line
Git-157)
#5 lore raw

Re: [PATCH v6 2/5] perf symbols: Split out name-independent duplicate symbol selection

Sashiko has reviewed this patch and found no issues.
Quoted 12 lines

From: Alireza Haghdoost <[email protected]>

This patch is a refactoring and does not change behavior. It moves the size, type and binding checks from choose_best_symbol() to choose_best_symbol_by_attrs(). It also adds symbol__choice_needs_names() to report whether choosing between two symbols requires their names.

symbols__fixup_duplicate() keeps one of the symbols that share a start address. It compares size, type and binding first. If those attributes are equal, it compares leading underscores, name lengths and the result of arch__choose_best_symbol().

Quoted 7 lines

An unresolved lazy symbol stores a file offset instead of a name pointer. Thus, the lazy loader cannot call choose_best_symbol() until it loads both names. The new helper lets the loader keep the names unresolved when the attributes select a winner. It loads names only when the attributes are equal and duplicate selection needs them.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
reviewer Reviewed-by on v6 2/5
#6 lore raw

Re: [PATCH v6 2/5] perf symbols: Split out name-independent duplicate symbol selection

In reply to Alireza Haghdoost
Quoted 13 lines · On Wed, Oct 28, 2026 at 4:42 PM Alireza Haghdoost via B4 Relay…

From: Alireza Haghdoost <[email protected]>

This patch is a refactoring and does not change behavior. It moves the size, type and binding checks from choose_best_symbol() to choose_best_symbol_by_attrs(). It also adds symbol__choice_needs_names() to report whether choosing between two symbols requires their names.

symbols__fixup_duplicate() keeps one of the symbols that share a start address. It compares size, type and binding first. If those attributes are equal, it compares leading underscores, name lengths and the result of arch__choose_best_symbol().

Quoted 7 lines

An unresolved lazy symbol stores a file offset instead of a name pointer. Thus, the lazy loader cannot call choose_best_symbol() until it loads both names. The new helper lets the loader keep the names unresolved when the attributes select a winner. It loads names only when the attributes are equal and duplicate selection needs them.

Generally I think attr/attribute means perf_event_attr in the code, but I lack naming abilitites, so it works for me.

Thanks,
Ian

Quoted 69 lines
---
 tools/perf/util/symbol.c | 26 ++++++++++++++++++++++++--
 tools/perf/util/symbol.h |  1 +
 2 files changed, 25 insertions(+), 2 deletions(-)
tools/perf/util/symbol.c +24 -2
index b61a574ce9a3..2d611c05d000 100644
@@ -157,11 +157,15 @@ int __weak arch__choose_best_symbol(struct symbol *syma,
        return SYMBOL_A;
 }
 
-static int choose_best_symbol(struct symbol *syma, struct symbol *symb)
+/*
+ * Choose between two symbols at the same address by size, type and binding.
+ * Returns SYMBOL_A or SYMBOL_B, or -1 if only their names can decide.
+ */
+static int choose_best_symbol_by_attrs(const struct symbol *syma,
+                                      const struct symbol *symb)
 {
        s64 a;
        s64 b;
-       size_t na, nb;
 
        /* Prefer a symbol with non zero length */
        a = syma->end - syma->start;
@@ -194,6 +198,24 @@ static int choose_best_symbol(struct symbol *syma, struct symbol *symb)
        if (b && !a)
                return SYMBOL_B;
 
+       return -1;
+}
+
+bool symbol__choice_needs_names(const struct symbol *syma, const struct symbol *symb)
+{
+       return choose_best_symbol_by_attrs(syma, symb) < 0;
+}
+
+static int choose_best_symbol(struct symbol *syma, struct symbol *symb)
+{
+       int ret = choose_best_symbol_by_attrs(syma, symb);
+       s64 a;
+       s64 b;
+       size_t na, nb;
+
+       if (ret >= 0)
+               return ret;
+
        /* Prefer a symbol with less underscores */
        a = prefix_underscores_count(syma->name);
        b = prefix_underscores_count(symb->name);
tools/perf/util/symbol.h +1 -1
index 46b1649c64fc..d8386c4a7fc5 100644
@@ -303,6 +303,7 @@ int arch__compare_symbol_names(const char *namea, const char *nameb);
 int arch__compare_symbol_names_n(const char *namea, const char *nameb,
                                 unsigned int n);
 int arch__choose_best_symbol(struct symbol *syma, struct symbol *symb);
+bool symbol__choice_needs_names(const struct symbol *syma, const struct symbol *symb);
 
 enum symbol_tag_include {
        SYMBOL_TAG_INCLUDE__NONE = 0,
 
--

Git-157)

#7 lore raw

PATCH v6 3/5 perf symbols: Point to the symbol name instead of embedding it

In reply to Alireza Haghdoost

This patch changes the type of the name field in struct symbol from a flexible array (char name[]) to a pointer (char *name). It is a refactoring and does not change behavior, but it adds 8 bytes to each symbol allocation on 64-bit hosts.

The next patch creates symbols whose names are read only when they are needed. When perf creates such a symbol, it does not know the length of the name, so it cannot allocate space for the name after the symbol. Perf also cannot allocate a larger symbol after it reads the name, because the rb-tree and the callers keep pointers to the symbol. With a pointer, perf can allocate the name separately and set the pointer later.

---
 tools/perf/ui/stdio/hist.c | 1 +
 tools/perf/util/symbol.c   | 1 +
 tools/perf/util/symbol.h   | 2 +-
 3 files changed, 3 insertions(+), 1 deletion(-)
tools/perf/ui/stdio/hist.c +1 -0
index 8c4c8925df2c..c65e3aa73a13 100644
@@ -106,6 +106,7 @@ static void init_rem_hits(void)
 		return;
 	}
 
+	rem_sq_bracket->name = (char *)(rem_sq_bracket + 1);
 	strcpy(rem_sq_bracket->name, "[...]");
 	rem_hits.ms.sym = rem_sq_bracket;
 }
tools/perf/util/symbol.c +1 -0
index 2d611c05d000..02c077d7e2a6 100644
@@ -362,6 +362,7 @@ struct symbol *symbol__new(u64 start, u64 len, u8 binding, u8 type, const char *
 
 	pr_debug4("%s: %s %#" PRIx64 "-%#" PRIx64 "\n",
 		  __func__, name, start, sym->end);
+	sym->name = (char *)(sym + 1);
 	memcpy(sym->name, name, namelen);
 
 	return sym;
tools/perf/util/symbol.h +1 -1
index d8386c4a7fc5..c231d8e4427c 100644
@@ -95,7 +95,7 @@ struct symbol {
 	/** Architecture specific. Unused except on PPC where it holds st_other. */
 	u8		arch_sym;
 	/** The name of length namelen associated with the symbol. */
-	char		name[];
+	char		*name;
 };
 
 void symbol__delete(struct symbol *sym);
Signature · 1 line
Git-157)
#8 lore raw

Re: [PATCH v6 3/5] perf symbols: Point to the symbol name instead of embedding it

Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

From: Alireza Haghdoost <[email protected]>

This patch changes the type of the name field in struct symbol from a flexible array (char name[]) to a pointer (char *name). It is a refactoring and does not change behavior, but it adds 8 bytes to each symbol allocation on 64-bit hosts.

Quoted 8 lines

The next patch creates symbols whose names are read only when they are needed. When perf creates such a symbol, it does not know the length of the name, so it cannot allocate space for the name after the symbol. Perf also cannot allocate a larger symbol after it reads the name, because the rb-tree and the callers keep pointers to the symbol. With a pointer, perf can allocate the name separately and set the pointer later.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
reviewer Reviewed-by on v6 3/5
#9 lore raw

Re: [PATCH v6 3/5] perf symbols: Point to the symbol name instead of embedding it

In reply to Alireza Haghdoost
Quoted 7 lines · On Wed, Oct 28, 2026 at 4:42 PM Alireza Haghdoost via B4 Relay…

From: Alireza Haghdoost <[email protected]>

This patch changes the type of the name field in struct symbol from a flexible array (char name[]) to a pointer (char *name). It is a refactoring and does not change behavior, but it adds 8 bytes to each symbol allocation on 64-bit hosts.

I think it is a little worse as we'll need 3 bytes of padding. You could reduce the padding by moving name to before namelen in the struct.

Quoted 8 lines

The next patch creates symbols whose names are read only when they are needed. When perf creates such a symbol, it does not know the length of the name, so it cannot allocate space for the name after the symbol. Perf also cannot allocate a larger symbol after it reads the name, because the rb-tree and the callers keep pointers to the symbol. With a pointer, perf can allocate the name separately and set the pointer later.

This change makes sense to me. I'm wondering if any other things should be cleaned up with this change? For example, namelen is only referenced in about 8 places and we may be able to replace it with strlen(name). Anyway, ordering the variables to pack them is a nit.

Thanks,
Ian

Quoted 48 lines
---
 tools/perf/ui/stdio/hist.c | 1 +
 tools/perf/util/symbol.c   | 1 +
 tools/perf/util/symbol.h   | 2 +-
 3 files changed, 3 insertions(+), 1 deletion(-)
tools/perf/ui/stdio/hist.c +1 -0
index 8c4c8925df2c..c65e3aa73a13 100644
@@ -106,6 +106,7 @@ static void init_rem_hits(void)
                return;
        }
 
+       rem_sq_bracket->name = (char *)(rem_sq_bracket + 1);
        strcpy(rem_sq_bracket->name, "[...]");
        rem_hits.ms.sym = rem_sq_bracket;
 }
tools/perf/util/symbol.c +1 -0
index 2d611c05d000..02c077d7e2a6 100644
@@ -362,6 +362,7 @@ struct symbol *symbol__new(u64 start, u64 len, u8 binding, u8 type, const char *
 
        pr_debug4("%s: %s %#" PRIx64 "-%#" PRIx64 "\n",
                  __func__, name, start, sym->end);
+       sym->name = (char *)(sym + 1);
        memcpy(sym->name, name, namelen);
 
        return sym;
tools/perf/util/symbol.h +1 -2
index d8386c4a7fc5..c231d8e4427c 100644
@@ -95,7 +95,7 @@ struct symbol {
        /** Architecture specific. Unused except on PPC where it holds st_other. */
        u8              arch_sym;
        /** The name of length namelen associated with the symbol. */
-       char            name[];
+       char            *name;
 };
 
 void symbol__delete(struct symbol *sym);
 
--

Git-157)

#10 lore raw

Re: [PATCH v6 3/5] perf symbols: Point to the symbol name instead of embedding it

Quoted 4 lines · Ian Rogers

I think it is a little worse as we'll need 3 bytes of padding. You could reduce the padding by moving name to before namelen in the struct.

Sorry for the late reply, I held it until v7 was ready. Thanks for the review. I checked the layout with offsetof() on x86_64. Before this patch, sizeof(struct symbol) is 48 with name[] at offset 45, and the allocation is sizeof + namelen, so those 3 tail bytes were already allocated and unused. With this patch, arch_sym is at 44, the name pointer at 48 and sizeof is 56, and an eager name is stored right after the struct. That is 8 bytes more per eager symbol, not 11.

Moving name before namelen keeps sizeof at 56, because the struct then ends with namelen, flags and arch_sym at 48..52 and pads to 56. The 3 bytes would only help if the eager name were stored at offsetof(arch_sym) + 1 and the allocation sized from that, with symbol__delete() changed to match. Lazy symbols stay at sizeof either way. I would rather keep this patch simple, so v7 leaves the order as is.

Quoted 4 lines

This change makes sense to me. I'm wondering if any other things should be cleaned up with this change? For example, namelen is only referenced in about 8 places and we may be able to replace it with strlen(name).

Yes. namelen is set in symbol.c and read for column widths in hist.c, in srcline.c and in data-convert-json.c. Dropping it saves 2 bytes, but not sizeof on its own. I can send that as a follow-up after this series.

Thanks,
Alireza

#11 lore raw

PATCH v6 4/5 perf script: Add --lazy-load-symbols to load symbol names lazily

In reply to Alireza Haghdoost

This patch adds the --lazy-load-symbols option to perf script. With this option, perf reads the name of a userspace ELF symbol only when a lookup returns the symbol. Eager loading remains the default.

perf script loads the ELF symbol table of every DSO that appears in a sample and keeps each symbol, with its demangled name, until exit. Most of those symbols are never sampled, and their names take most of the memory. On a large profile this makes symbol loading the main memory cost of perf script, and in a memory-constrained cgroup an OOM kill.

With the option, the loader still creates every symbol, so end fixup, duplicate selection, PLT synthesis and IFUNC marking work as before. But it keeps the file offset of each name instead of copying and demangling the name.

The name pointer and the offset share a union in struct symbol, and SYMBOL_FLAG_LAZY_NAME says which one it holds. The dso__find_symbol*() functions, dso__first_symbol() and dso__last_symbol() load the name of the symbol they return, and code that walks the symbols of a DSO gets them with dso__named_symbols(), which loads every name. So does dso__sort_by_name() before it builds the name-sorted array. A symbol whose name cannot be read is named "[unknown]" instead of being deleted, since address lookups search the symbol tree without the DSO lock. Address lookups return NULL for it, so perf script prints it as an address without a symbol.

During loading, perf reads only the names that it needs:

- the names of aliases that duplicate selection can tell apart only by name,
- the names of IFUNC symbols, which PLT synthesis uses to name the IRELATIVE slots.

The loader also skips a .dynsym entry that copies a lazy .symtab symbol. Duplicate selection would drop the entry, but only after it reads both names, and most exported symbols are such copies.

Other names are read with pread() from the file that dso__get_filename() returns for dso__symtab_type(). The file is open only while perf reads the names, so no descriptor stays open per DSO.

The kernel, modules, PPC64 .opd and .gnu_debugdata, whose symbol table is a temporary file, still load names eagerly.

On a perf script run over a 45,073-sample callchain profile of a large C++ service, where eager loading creates about 1M symbols, lazy loading reduces max RSS from 341 MiB to 154 MiB and time from 3.2 to 1.5 seconds, with identical output.

---
 tools/perf/Documentation/perf-script.txt |   7 +
 tools/perf/builtin-script.c              |   2 +
 tools/perf/ui/browsers/map.c             |   2 +-
 tools/perf/util/dso.c                    |   2 +-
 tools/perf/util/dso.h                    |   3 +-
 tools/perf/util/symbol-elf.c             | 251 +++++++++++++++++++++++++++++--
 tools/perf/util/symbol-minimal.c         |   6 +
 tools/perf/util/symbol.c                 | 113 +++++++++++++-
 tools/perf/util/symbol.h                 |  29 +++-
 tools/perf/util/symbol_conf.h            |   1 +
 10 files changed, 393 insertions(+), 23 deletions(-)
tools/perf/Documentation/perf-script.txt +7 -0
index f0228e784ced..57b3533e6c2a 100644
@@ -343,6 +343,13 @@ include::itrace.txt[]
 
         Default: 127
 
+--lazy-load-symbols::
+	Read and demangle userspace ELF symbol names only when perf needs
+	them. By default, perf reads every symbol name from each binary
+	referenced by a sample. This option reduces memory use and usually
+	improves performance when samples reference only a small fraction
+	of a large binary's symbols.
+
 --ns::
 	Use 9 decimal places when displaying time (i.e. show the nanoseconds)
 
tools/perf/builtin-script.c +2 -0
index b6691ebb1b4e..88aaf9cfd132 100644
@@ -4287,6 +4287,8 @@ int cmd_script(int argc, const char **argv)
 		     "Set the maximum stack depth when parsing the callchain, "
 		     "anything beyond the specified depth will be ignored. "
 		     "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
+	OPT_BOOLEAN(0, "lazy-load-symbols", &symbol_conf.lazy_load_symbols,
+		    "Read symbol names only when they are needed"),
 	OPT_BOOLEAN(0, "reltime", &reltime, "Show time stamps relative to start"),
 	OPT_BOOLEAN(0, "deltatime", &deltatime, "Show time stamps relative to previous event"),
 	OPT_BOOLEAN('I', "show-info", &show_full_info,
tools/perf/ui/browsers/map.c +1 -1
index 075a575cdc5d..ef8f75699a07 100644
@@ -108,7 +108,7 @@ int map__browse(struct map *map)
 {
 	struct map_browser mb = {
 		.b = {
-			.entries = dso__symbols(map__dso(map)),
+			.entries = dso__named_symbols(map__dso(map)),
 			.refresh = ui_browser__rb_tree_refresh,
 			.seek	 = ui_browser__rb_tree_seek,
 			.write	 = map_browser__write,
tools/perf/util/dso.c +1 -1
index ce98613868e7..f41abf442476 100644
@@ -2013,7 +2013,7 @@ size_t dso__fprintf(struct dso *dso, FILE *fp)
 	ret += fprintf(fp, "%sloaded, ", dso__loaded(dso) ? "" : "NOT ");
 	ret += dso__fprintf_buildid(dso, fp);
 	ret += fprintf(fp, ")\n");
-	for (nd = rb_first_cached(dso__symbols(dso)); nd; nd = rb_next(nd)) {
+	for (nd = rb_first_cached(dso__named_symbols(dso)); nd; nd = rb_next(nd)) {
 		struct symbol *pos = rb_entry(nd, struct symbol, rb_node);
 		ret += symbol__fprintf(pos, fp);
 	}
tools/perf/util/dso.h +2 -1
index 3329f417810c..4a60c883cc37 100644
@@ -369,7 +369,7 @@ int dso_id__cmp(const struct dso_id *a, const struct dso_id *b);
  * @n: the 'struct rb_node *' to use as a temporary storage
  */
 #define dso__for_each_symbol(dso, pos, n)	\
-	symbols__for_each_entry(dso__symbols(dso), pos, n)
+	symbols__for_each_entry(dso__named_symbols(dso), pos, n)
 
 static inline void *dso__a2l(const struct dso *dso)
 {
@@ -831,6 +831,7 @@ char *dso__filename_with_chroot(const struct dso *dso, const char *filename);
 bool dso__sorted_by_name(const struct dso *dso);
 void dso__set_sorted_by_name(struct dso *dso);
 void dso__sort_by_name(struct dso *dso);
+struct rb_root_cached *dso__named_symbols(struct dso *dso);
 
 int dso__swap_init(struct dso *dso, unsigned char eidata);
 
tools/perf/util/symbol-elf.c +241 -10

308 lines not on this page · raw message

tools/perf/util/symbol-minimal.c +6 -0
index 0a71d1463952..fa87c2d9de2a 100644
@@ -330,6 +330,12 @@ enum dso_type dso__type_fd(int fd)
 	return DSO__TYPE_32BIT;
 }
 
+void dso__load_symbol_names(struct dso *dso __maybe_unused,
+			    struct symbol **syms __maybe_unused,
+			    size_t nr __maybe_unused)
+{
+}
+
 int dso__load_sym(struct dso *dso, struct map *map __maybe_unused,
 		  struct symsrc *ss,
 		  struct symsrc *runtime_ss __maybe_unused,
tools/perf/util/symbol.c +105 -8

176 lines not on this page · raw message

tools/perf/util/symbol.h +27 -2
index c231d8e4427c..5ab222b0655b 100644
@@ -80,9 +80,18 @@ enum symbol_idle_kind {
 #define SYMBOL_FLAG_INLINED         (1 << 11)
 #define SYMBOL_FLAG_ANNOTATE2       (1 << 12)
 #define SYMBOL_FLAG_IFUNC_ALIAS     (1 << 13)
+#define SYMBOL_FLAG_LAZY_NAME       (1 << 14)
 /**
  * A symtab entry. When allocated this may be preceded by an annotation (see
  * symbol__annotation) and/or a browser_index (see symbol__browser_index).
+ *
+ * With symbol_conf.lazy_load_symbols, the ELF loader may create symbols
+ * with SYMBOL_FLAG_LAZY_NAME, whose name is still in the symbol table file.
+ * The functions that return a symbol of a DSO, such as dso__find_symbol(),
+ * load its name first, and dso__named_symbols() loads them all for code
+ * that walks the symbols. A symbol whose name cannot be read is named
+ * "[unknown]", and address lookups return NULL for it. Code that walks
+ * dso__symbols() directly must not read the name of a lazy symbol.
  */
 struct symbol {
 	struct rb_node	rb_node;
@@ -94,13 +103,24 @@ struct symbol {
 	_Atomic uint16_t flags;
 	/** Architecture specific. Unused except on PPC where it holds st_other. */
 	u8		arch_sym;
-	/** The name of length namelen associated with the symbol. */
-	char		*name;
+	union {
+		/** The name of length namelen associated with the symbol. */
+		char	*name;
+		/** File offset of the name while SYMBOL_FLAG_LAZY_NAME is set. */
+		u64	name_off;
+	};
 };
 
 void symbol__delete(struct symbol *sym);
 void symbols__delete(struct rb_root_cached *symbols);
 
+/* Pairs with the release in symbol__set_lazy_name(). */
+static inline bool symbol__has_lazy_name(const struct symbol *sym)
+{
+	return (atomic_load_explicit(&sym->flags, memory_order_acquire) &
+		SYMBOL_FLAG_LAZY_NAME) != 0;
+}
+
 static inline u8 symbol__type(const struct symbol *sym)
 {
 	return (atomic_load_explicit(&sym->flags, memory_order_relaxed) &
@@ -227,6 +247,9 @@ void symbol__elf_init(void);
 int symbol__annotation_init(void);
 
 struct symbol *symbol__new(u64 start, u64 len, u8 binding, u8 type, const char *name);
+struct symbol *symbol__new_lazy(u64 start, u64 len, u8 binding, u8 type, u64 name_off);
+void symbol__set_lazy_name(struct symbol *sym, char *name);
+void symbol__set_unknown_name(struct symbol *sym);
 size_t __symbol__fprintf_symname_offs(const struct symbol *sym,
 				      const struct addr_location *al,
 				      bool unknown_as_addr,
@@ -257,11 +280,13 @@ int dso__load_bfd_symbols(struct dso *dso, const char *debugfile);
 int dso__load_sym(struct dso *dso, struct map *map, struct symsrc *syms_ss,
 		  struct symsrc *runtime_ss, int kmodule);
 int dso__synthesize_plt_symbols(struct dso *dso, struct symsrc *ss);
+void dso__load_symbol_names(struct dso *dso, struct symbol **syms, size_t nr);
 
 char *dso__demangle_sym(struct dso *dso, int kmodule, const char *elf_name);
 
 void __symbols__insert(struct rb_root_cached *symbols, struct symbol *sym);
 void symbols__insert(struct rb_root_cached *symbols, struct symbol *sym);
+struct symbol *symbols__find(struct rb_root_cached *symbols, u64 ip);
 void symbols__fixup_duplicate(struct rb_root_cached *symbols);
 void symbols__fixup_end(struct rb_root_cached *symbols, bool is_kallsyms);
 
tools/perf/util/symbol_conf.h +1 -0
index 37d35f42dcc1..434b6c51288b 100644
@@ -77,6 +77,7 @@ struct symbol_conf {
 			no_buildid_mmap2,
 			guest_code,
 			lazy_load_kernel_maps,
+			lazy_load_symbols,
 			keep_exited_threads,
 			annotate_data_member,
 			annotate_data_sample,
Signature · 1 line
Git-157)
#12 lore raw

Re: [PATCH v6 4/5] perf script: Add --lazy-load-symbols to load symbol names lazily

Sashiko has reviewed this patch and found no issues.
Quoted 20 lines

From: Alireza Haghdoost <[email protected]>

This patch adds the --lazy-load-symbols option to perf script. With this option, perf reads the name of a userspace ELF symbol only when a lookup returns the symbol. Eager loading remains the default.

perf script loads the ELF symbol table of every DSO that appears in a sample and keeps each symbol, with its demangled name, until exit. Most of those symbols are never sampled, and their names take most of the memory. On a large profile this makes symbol loading the main memory cost of perf script, and in a memory-constrained cgroup an OOM kill.

With the option, the loader still creates every symbol, so end fixup, duplicate selection, PLT synthesis and IFUNC marking work as before. But it keeps the file offset of each name instead of copying and demangling [ ... ]
C++ service, where eager loading creates about 1M symbols, lazy loading reduces max RSS from 341 MiB to 154 MiB and time from 3.2 to 1.5 seconds, with identical output.

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
reviewer
#13 lore raw

Re: [PATCH v6 4/5] perf script: Add --lazy-load-symbols to load symbol names lazily

In reply to Alireza Haghdoost
Quoted 71 lines · On Wed, Oct 28, 2026 at 4:42 PM Alireza Haghdoost via B4 Relay…

From: Alireza Haghdoost <[email protected]>

This patch adds the --lazy-load-symbols option to perf script. With this option, perf reads the name of a userspace ELF symbol only when a lookup returns the symbol. Eager loading remains the default.

perf script loads the ELF symbol table of every DSO that appears in a sample and keeps each symbol, with its demangled name, until exit. Most of those symbols are never sampled, and their names take most of the memory. On a large profile this makes symbol loading the main memory cost of perf script, and in a memory-constrained cgroup an OOM kill.

With the option, the loader still creates every symbol, so end fixup, duplicate selection, PLT synthesis and IFUNC marking work as before. But it keeps the file offset of each name instead of copying and demangling the name.

The name pointer and the offset share a union in struct symbol, and SYMBOL_FLAG_LAZY_NAME says which one it holds. The dso__find_symbol*() functions, dso__first_symbol() and dso__last_symbol() load the name of the symbol they return, and code that walks the symbols of a DSO gets them with dso__named_symbols(), which loads every name. So does dso__sort_by_name() before it builds the name-sorted array. A symbol whose name cannot be read is named "[unknown]" instead of being deleted, since address lookups search the symbol tree without the DSO lock. Address lookups return NULL for it, so perf script prints it as an address without a symbol.

During loading, perf reads only the names that it needs:

- the names of aliases that duplicate selection can tell apart only by name,
- the names of IFUNC symbols, which PLT synthesis uses to name the IRELATIVE slots.

The loader also skips a .dynsym entry that copies a lazy .symtab symbol. Duplicate selection would drop the entry, but only after it reads both names, and most exported symbols are such copies.

Other names are read with pread() from the file that dso__get_filename() returns for dso__symtab_type(). The file is open only while perf reads the names, so no descriptor stays open per DSO.

The kernel, modules, PPC64 .opd and .gnu_debugdata, whose symbol table is a temporary file, still load names eagerly.

On a perf script run over a 45,073-sample callchain profile of a large C++ service, where eager loading creates about 1M symbols, lazy loading reduces max RSS from 341 MiB to 154 MiB and time from 3.2 to 1.5 seconds, with identical output.

---
 tools/perf/Documentation/perf-script.txt |   7 +
 tools/perf/builtin-script.c              |   2 +
 tools/perf/ui/browsers/map.c             |   2 +-
 tools/perf/util/dso.c                    |   2 +-
 tools/perf/util/dso.h                    |   3 +-
 tools/perf/util/symbol-elf.c             | 251 +++++++++++++++++++++++++++++--
 tools/perf/util/symbol-minimal.c         |   6 +
 tools/perf/util/symbol.c                 | 113 +++++++++++++-
 tools/perf/util/symbol.h                 |  29 +++-
 tools/perf/util/symbol_conf.h            |   1 +
 10 files changed, 393 insertions(+), 23 deletions(-)
tools/perf/Documentation/perf-script.txt +0 -0
index f0228e784ced..57b3533e6c2a 100644

tools/perf/Documentation/perf-script.txt include::itrace.txt[] · line 352

Quoted 10 lines
tools/perf/Documentation/perf-script.txt +7 -0
@@ -343,6 +343,13 @@ include::itrace.txt[]
 
         Default: 127
 
+--lazy-load-symbols::
+       Read and demangle userspace ELF symbol names only when perf needs
+       them. By default, perf reads every symbol name from each binary
+       referenced by a sample. This option reduces memory use and usually
+       improves performance when samples reference only a small fraction
+       of a large binary's symbols.
+

Won't it also improve performance if you say link against a library but then only use a portion of that library's contents? I'm thinking this option should really be the default, requiring people to opt out. I may even be tempted to hide this flag so that we have the option later of just always using lazy loading. Since the flag isn't a huge cost in the code, and non-lazy loading is needed in other contexts, perhaps we can make the lazy loading the default behavior and have the flag here be say, "--eager-loading" ?

Quoted 94 lines
tools/perf/Documentation/perf-script.txt +0 -0
 --ns::
        Use 9 decimal places when displaying time (i.e. show the nanoseconds)
 
tools/perf/builtin-script.c +2 -0
index b6691ebb1b4e..88aaf9cfd132 100644
@@ -4287,6 +4287,8 @@ int cmd_script(int argc, const char **argv)
                     "Set the maximum stack depth when parsing the callchain, "
                     "anything beyond the specified depth will be ignored. "
                     "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
+       OPT_BOOLEAN(0, "lazy-load-symbols", &symbol_conf.lazy_load_symbols,
+                   "Read symbol names only when they are needed"),
        OPT_BOOLEAN(0, "reltime", &reltime, "Show time stamps relative to start"),
        OPT_BOOLEAN(0, "deltatime", &deltatime, "Show time stamps relative to previous event"),
        OPT_BOOLEAN('I', "show-info", &show_full_info,
tools/perf/ui/browsers/map.c +1 -1
index 075a575cdc5d..ef8f75699a07 100644
@@ -108,7 +108,7 @@ int map__browse(struct map *map)
 {
        struct map_browser mb = {
                .b = {
-                       .entries = dso__symbols(map__dso(map)),
+                       .entries = dso__named_symbols(map__dso(map)),
                        .refresh = ui_browser__rb_tree_refresh,
                        .seek    = ui_browser__rb_tree_seek,
                        .write   = map_browser__write,
tools/perf/util/dso.c +1 -1
index ce98613868e7..f41abf442476 100644
@@ -2013,7 +2013,7 @@ size_t dso__fprintf(struct dso *dso, FILE *fp)
        ret += fprintf(fp, "%sloaded, ", dso__loaded(dso) ? "" : "NOT ");
        ret += dso__fprintf_buildid(dso, fp);
        ret += fprintf(fp, ")\n");
-       for (nd = rb_first_cached(dso__symbols(dso)); nd; nd = rb_next(nd)) {
+       for (nd = rb_first_cached(dso__named_symbols(dso)); nd; nd = rb_next(nd)) {
                struct symbol *pos = rb_entry(nd, struct symbol, rb_node);
                ret += symbol__fprintf(pos, fp);
        }
tools/perf/util/dso.h +2 -1
index 3329f417810c..4a60c883cc37 100644
@@ -369,7 +369,7 @@ int dso_id__cmp(const struct dso_id *a, const struct dso_id *b);
  * @n: the 'struct rb_node *' to use as a temporary storage
  */
 #define dso__for_each_symbol(dso, pos, n)      \
-       symbols__for_each_entry(dso__symbols(dso), pos, n)
+       symbols__for_each_entry(dso__named_symbols(dso), pos, n)
 
 static inline void *dso__a2l(const struct dso *dso)
 {
@@ -831,6 +831,7 @@ char *dso__filename_with_chroot(const struct dso *dso, const char *filename);
 bool dso__sorted_by_name(const struct dso *dso);
 void dso__set_sorted_by_name(struct dso *dso);
 void dso__sort_by_name(struct dso *dso);
+struct rb_root_cached *dso__named_symbols(struct dso *dso);
 
 int dso__swap_init(struct dso *dso, unsigned char eidata);
 
tools/perf/util/symbol-elf.c +3 -2
index 1e2716c6af45..bce6c6aef20c 100644
@@ -17,6 +17,7 @@
 #include "machine.h"
 #include "vdso.h"
 #include "debug.h"
+#include "namespaces.h"
 #include "util/copyfile.h"
 #include <linux/ctype.h>
 #include <linux/kernel.h>
@@ -348,7 +349,7 @@ static bool get_ifunc_name(Elf *elf, struct dso *dso, GElf_Ehdr *ehdr,
 
        addr -= phdr.p_vaddr - phdr.p_offset;
 
-       sym = dso__find_symbol_nocache(dso, addr);
+       sym = symbols__find(dso__symbols(dso), addr);
 
        /* Expecting the address to be an IFUNC or IFUNC alias */
        if (!sym || sym->start != addr ||
@@ -629,7 +630,7 @@ int dso__synthesize_plt_symbols(struct dso *dso, struct symsrc *ss)
         * by symbols__fixup_end() to overlap .plt. Truncate it before adding
         * a symbol for .plt header.
         */
-       f = dso__find_symbol_nocache(dso, shdr_plt.sh_offset);
+       f = symbols__find(dso__symbols(dso), shdr_plt.sh_offset);
        if (f && f->start < shdr_plt.sh_offset && f->end > shdr_plt.sh_offset)
                f->end = shdr_plt.sh_offset;
 

tools/perf/util/symbol-elf.c static int dso__process_kernel_symbol(struct dso *dso, struct map *map, · line 1520

Quoted 4 lines
tools/perf/util/symbol-elf.c +1 -0
@@ -1516,6 +1517,190 @@ static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
        return 0;
 }
 
+static DEFINE_MUTEX(lazy_names_lock);

I'm curious if this is global just to avoid the expense of a mutex per symbol or it needs to be global? We have tools/perf/util/sharded_mutex.h as a way of doing a cheaper per object mutex, but perhaps the dso__lock works?

Thanks,
Ian

Quoted 580 lines
tools/perf/util/symbol-elf.c +237 -8
+
+static char *read_name_at(int fd, u64 off)
+{
+       char small[256], *buf = NULL, *tmp;
+       size_t size = sizeof(small);
+       ssize_t n = pread(fd, small, size, off);
+
+       if (n > 0 && memchr(small, '\0', n))
+               return strdup(small);
+
+       while (n == (ssize_t)size) {
+               size *= 2;
+               tmp = realloc(buf, size);
+               if (!tmp)
+                       break;
+               buf = tmp;
+               n = pread(fd, buf, size, off);
+               if (n > 0 && memchr(buf, '\0', n))
+                       return buf;
+       }
+       free(buf);
+       return NULL;
+}
+
+static int load_symbol_names(struct dso *dso, int fd, struct symbol **syms, size_t nr)
+{
+       int err = 0;
+
+       for (size_t i = 0; i < nr; i++) {
+               char *name, *demangled;
+
+               if (!symbol__has_lazy_name(syms[i]))
+                       continue;
+               name = read_name_at(fd, syms[i]->name_off);
+               if (!name) {
+                       pr_debug("%s: cannot read the symbol name at %#" PRIx64 "\n",
+                                dso__long_name(dso), syms[i]->name_off);
+                       err = -1;
+                       continue;
+               }
+               demangled = dso__demangle_sym(dso, /*kmodule=*/0, name);
+               if (demangled) {
+                       free(name);
+                       name = demangled;
+               }
+               symbol__set_lazy_name(syms[i], name);
+       }
+       return err;
+}
+
+/*
+ * Load the lazy names in @syms, which are symbols of @dso, from the file of
+ * dso__symtab_type(). A name that cannot be read becomes "[unknown]".
+ */
+void dso__load_symbol_names(struct dso *dso, struct symbol **syms, size_t nr)
+{
+       enum dso_binary_type type = dso__symtab_type(dso);
+       /* As in dso__load(), the build-id cache is in perf's mount namespace. */
+       bool own_ns = type == DSO_BINARY_TYPE__BUILD_ID_CACHE ||
+                     type == DSO_BINARY_TYPE__BUILD_ID_CACHE_DEBUGINFO;
+       struct nscookie nsc;
+       bool decomp;
+       char *name;
+       int fd = -1;
+
+       mutex_lock(&lazy_names_lock);
+       if (!own_ns)
+               nsinfo__mountns_enter(dso__nsinfo(dso), &nsc);
+       name = dso__get_filename(dso, "", &decomp, type);
+       if (name)
+               fd = open(name, O_RDONLY | O_CLOEXEC);
+       if (!own_ns)
+               nsinfo__mountns_exit(&nsc);
+
+       if (fd >= 0) {
+               load_symbol_names(dso, fd, syms, nr);
+               close(fd);
+       } else {
+               pr_debug("%s: cannot open the symbol table file\n", dso__long_name(dso));
+       }
+       if (name)
+               dso__put_filename(dso, name, decomp);
+       for (size_t i = 0; i < nr; i++) {
+               if (symbol__has_lazy_name(syms[i]))
+                       symbol__set_unknown_name(syms[i]);
+       }
+       mutex_unlock(&lazy_names_lock);
+}
+
+/*
+ * Return the lazy symbol in @symbols that the .dynsym entry @sym named
+ * @name copies, with the same address, size, binding, type and name.
+ * symbols__fixup_duplicate() would keep that symbol and drop the copy.
+ */
+static struct symbol *lazy_dynsym_copy(struct rb_root_cached *symbols, Elf *elf,
+                                      const GElf_Sym *sym, const char *name)
+{
+       struct rb_node *nd = symbols->rb_root.rb_node, *prev;
+       const char *image;
+       struct symbol *s;
+       size_t size;
+
+       if (!sym->st_size)
+               return NULL;
+       image = elf_rawfile(elf, &size);
+       if (!image)
+               return NULL;
+
+       while (nd) {
+               s = rb_entry(nd, struct symbol, rb_node);
+               if (sym->st_value < s->start)
+                       nd = nd->rb_left;
+               else if (sym->st_value > s->start)
+                       nd = nd->rb_right;
+               else
+                       break;
+       }
+       if (!nd)
+               return NULL;
+       while ((prev = rb_prev(nd)) &&
+              rb_entry(prev, struct symbol, rb_node)->start == sym->st_value)
+               nd = prev;
+
+       for (; nd; nd = rb_next(nd)) {
+               s = rb_entry(nd, struct symbol, rb_node);
+               if (s->start != sym->st_value)
+                       break;
+               if (s->end == s->start + sym->st_size &&
+                   symbol__binding(s) == GELF_ST_BIND(sym->st_info) &&
+                   symbol__type(s) == GELF_ST_TYPE(sym->st_info) &&
+                   symbol__has_lazy_name(s) && s->name_off < size &&
+                   !strncmp(image + s->name_off, name, size - s->name_off))
+                       return s;
+       }
+       return NULL;
+}
+
+/*
+ * symbols__fixup_duplicate() compares the names of symbols at the same
+ * address only when their size, type and binding tie. Load those names.
+ */
+static int dso__load_alias_names(struct dso *dso, int fd)
+{
+       struct rb_node *nd = rb_first_cached(dso__symbols(dso));
+
+       while (nd) {
+               struct symbol *first = rb_entry(nd, struct symbol, rb_node);
+               struct rb_node *end = rb_next(nd), *a, *b;
+
+               while (end && rb_entry(end, struct symbol, rb_node)->start == first->start)
+                       end = rb_next(end);
+
+               for (a = nd; a != end; a = rb_next(a)) {
+                       for (b = rb_next(a); b != end; b = rb_next(b)) {
+                               struct symbol *pair[2] = {
+                                       rb_entry(a, struct symbol, rb_node),
+                                       rb_entry(b, struct symbol, rb_node),
+                               };
+
+                               if (symbol__choice_needs_names(pair[0], pair[1]) &&
+                                   load_symbol_names(dso, fd, pair, 2))
+                                       return -1;
+                       }
+               }
+               nd = end;
+       }
+       return 0;
+}
+
+/* PLT synthesis names IRELATIVE slots after IFUNC symbols. Load those names. */
+static int dso__load_ifunc_names(struct dso *dso, int fd)
+{
+       struct symbol *pos;
+       struct rb_node *nd;
+
+       symbols__for_each_entry(dso__symbols(dso), pos, nd) {
+               if ((symbol__type(pos) == STT_GNU_IFUNC || symbol__ifunc_alias(pos)) &&
+                   load_symbol_names(dso, fd, &pos, 1))
+                       return -1;
+       }
+       return 0;
+}
+
 static int
 dso__load_sym_internal(struct dso *dso, struct map *map, struct symsrc *syms_ss,
                       struct symsrc *runtime_ss, int kmodule, int dynsym)
@@ -1533,9 +1718,19 @@ dso__load_sym_internal(struct dso *dso, struct map *map, struct symsrc *syms_ss,
        GElf_Sym sym;
        Elf_Scn *sec, *sec_strndx;
        Elf *elf;
-       int nr = 0;
+       int nr = 0, nr_lazy = 0;
        bool remap_kernel = false, adjust_kernel_syms = false;
        u64 max_text_sh_offset = 0;
+       /*
+        * Names are read later from the file of dso__symtab_type(). The
+        * .gnu_debugdata symbol table is a temporary file.
+        */
+       bool lazy_allowed = symbol_conf.lazy_load_symbols && !dso__kernel(dso) &&
+                         !kmodule && syms_ss->type == dso__symtab_type(dso) &&
+                         syms_ss->type != DSO_BINARY_TYPE__GNU_DEBUGDATA &&
+                         !runtime_ss->opdsec;
+       bool lazy_names = false;
+       GElf_Shdr strshdr;
 
        if (kmap && !kmaps)
                return -1;
@@ -1571,6 +1766,11 @@ dso__load_sym_internal(struct dso *dso, struct map *map, struct symsrc *syms_ss,
        if (symstrs == NULL)
                goto out_elf_end;
 
+       /* Names are read with pread(), so the string table must be stored as is. */
+       if (lazy_allowed && gelf_getshdr(sec, &strshdr) &&
+           strshdr.sh_type == SHT_STRTAB && !(strshdr.sh_flags & SHF_COMPRESSED))
+               lazy_names = true;
+
        sec_strndx = elf_getscn(runtime_ss->elf, runtime_ss->ehdr.e_shstrndx);
        if (sec_strndx == NULL)
                goto out_elf_end;
@@ -1772,14 +1972,36 @@ dso__load_sym_internal(struct dso *dso, struct map *map, struct symsrc *syms_ss,
                        }
                }
 
-               demangled = dso__demangle_sym(dso, kmodule, elf_name);
-               if (demangled != NULL)
-                       elf_name = demangled;
+               /*
+                * Most .dynsym entries are copies of .symtab symbols, which
+                * duplicate selection would drop anyway. Skip them here, so
+                * that perf does not read both names just to choose one.
+                */
+               if (lazy_names && dynsym && !symbol_conf.allow_aliases) {
+                       f = lazy_dynsym_copy(dso__symbols(curr_dso), elf, &sym, elf_name);
+                       if (f) {
+                               if (GELF_ST_TYPE(sym.st_info) == STT_GNU_IFUNC)
+                                       symbol__set_ifunc_alias(f, true);
+                               continue;
+                       }
+               }
 
-               f = symbol__new(sym.st_value, sym.st_size,
-                               GELF_ST_BIND(sym.st_info),
-                               GELF_ST_TYPE(sym.st_info), elf_name);
-               free(demangled);
+               if (lazy_names && sym.st_name < strshdr.sh_size) {
+                       f = symbol__new_lazy(sym.st_value, sym.st_size,
+                                            GELF_ST_BIND(sym.st_info),
+                                            GELF_ST_TYPE(sym.st_info),
+                                            strshdr.sh_offset + sym.st_name);
+                       nr_lazy++;
+               } else {
+                       demangled = dso__demangle_sym(dso, kmodule, elf_name);
+                       if (demangled != NULL)
+                               elf_name = demangled;
+
+                       f = symbol__new(sym.st_value, sym.st_size,
+                                       GELF_ST_BIND(sym.st_info),
+                                       GELF_ST_TYPE(sym.st_info), elf_name);
+                       free(demangled);
+               }
                if (!f)
                        goto out_elf_end;
 
@@ -1790,12 +2012,21 @@ dso__load_sym_internal(struct dso *dso, struct map *map, struct symsrc *syms_ss,
        }
        dso__put(curr_dso);
 
+       if (lazy_names)
+               pr_debug("%s: %d %s symbols with lazy names\n", dso__long_name(dso),
+                        nr_lazy, dynsym ? ".dynsym" : ".symtab");
+
        /*
         * For misannotated, zeroed, ASM function sizes.
         */
        if (nr > 0) {
                symbols__fixup_end(dso__symbols(dso), false);
+               if (lazy_allowed && !symbol_conf.allow_aliases &&
+                   dso__load_alias_names(dso, syms_ss->fd))
+                       return -1;
                symbols__fixup_duplicate(dso__symbols(dso));
+               if (lazy_allowed && dso__load_ifunc_names(dso, syms_ss->fd))
+                       return -1;
                if (kmap) {
                        /*
                         * We need to fixup this here too because we create new
tools/perf/util/symbol-minimal.c +6 -0
index 0a71d1463952..fa87c2d9de2a 100644
@@ -330,6 +330,12 @@ enum dso_type dso__type_fd(int fd)
        return DSO__TYPE_32BIT;
 }
 
+void dso__load_symbol_names(struct dso *dso __maybe_unused,
+                           struct symbol **syms __maybe_unused,
+                           size_t nr __maybe_unused)
+{
+}
+
 int dso__load_sym(struct dso *dso, struct map *map __maybe_unused,
                  struct symsrc *ss,
                  struct symsrc *runtime_ss __maybe_unused,
tools/perf/util/symbol.c +105 -8
index 02c077d7e2a6..4b5cde4d13be 100644
@@ -338,9 +338,9 @@ void symbols__fixup_end(struct rb_root_cached *symbols, bool is_kallsyms)
                curr->end = roundup(curr->start, 4096) + 4096;
 }
 
-struct symbol *symbol__new(u64 start, u64 len, u8 binding, u8 type, const char *name)
+static struct symbol *symbol__alloc(u64 start, u64 len, u8 binding, u8 type,
+                                   u16 flags, size_t namelen)
 {
-       size_t namelen = strlen(name) + 1;
        struct symbol *sym = calloc(1, (symbol_conf.priv_size +
                                        sizeof(*sym) + namelen));
        if (sym == NULL)
@@ -357,7 +357,18 @@ struct symbol *symbol__new(u64 start, u64 len, u8 binding, u8 type, const char *
        sym->start   = start;
        sym->end     = len ? start + len : start;
        atomic_init(&sym->flags, (type << SYMBOL_FLAG_TYPE_SHIFT) |
-                                (binding << SYMBOL_FLAG_BINDING_SHIFT));
+                                (binding << SYMBOL_FLAG_BINDING_SHIFT) | flags);
+       return sym;
+}
+
+struct symbol *symbol__new(u64 start, u64 len, u8 binding, u8 type, const char *name)
+{
+       size_t namelen = strlen(name) + 1;
+       struct symbol *sym = symbol__alloc(start, len, binding, type, 0, namelen);
+
+       if (sym == NULL)
+               return NULL;
+
        sym->namelen = namelen - 1;
 
        pr_debug4("%s: %s %#" PRIx64 "-%#" PRIx64 "\n",
@@ -368,8 +379,38 @@ struct symbol *symbol__new(u64 start, u64 len, u8 binding, u8 type, const char *
        return sym;
 }
 
+struct symbol *symbol__new_lazy(u64 start, u64 len, u8 binding, u8 type, u64 name_off)
+{
+       struct symbol *sym = symbol__alloc(start, len, binding, type,
+                                          SYMBOL_FLAG_LAZY_NAME, 0);
+
+       if (sym)
+               sym->name_off = name_off;
+       return sym;
+}
+
+/* @sym takes ownership of @name. */
+void symbol__set_lazy_name(struct symbol *sym, char *name)
+{
+       sym->namelen = strlen(name);
+       sym->name = name;
+       atomic_fetch_and(&sym->flags, ~SYMBOL_FLAG_LAZY_NAME);
+}
+
+/* The name of the symbols whose lazy name cannot be read. */
+static const char unknown_name[] = "[unknown]";
+
+void symbol__set_unknown_name(struct symbol *sym)
+{
+       symbol__set_lazy_name(sym, (char *)unknown_name);
+}
+
 void symbol__delete(struct symbol *sym)
 {
+       /* A loaded lazy name is allocated apart from the symbol. */
+       if (!symbol__has_lazy_name(sym) && sym->name != (char *)(sym + 1) &&
+           sym->name != unknown_name)
+               free(sym->name);
        if (symbol_conf.priv_size) {
                if (symbol_conf.init_annotation) {
                        struct annotation *notes = symbol__annotation(sym);
@@ -463,7 +504,7 @@ void symbols__insert(struct rb_root_cached *symbols, struct symbol *sym)
        __symbols__insert(symbols, sym);
 }
 
-static struct symbol *symbols__find(struct rb_root_cached *symbols, u64 ip)
+struct symbol *symbols__find(struct rb_root_cached *symbols, u64 ip)
 {
        struct rb_node *n;
 
@@ -638,6 +679,16 @@ void dso__delete_symbol(struct dso *dso, struct symbol *sym)
        dso__reset_find_symbol_cache(dso);
 }
 
+/* Return @sym with its name loaded, or NULL if the name cannot be read. */
+static struct symbol *dso__named_symbol(struct dso *dso, struct symbol *sym)
+{
+       if (sym && symbol__has_lazy_name(sym))
+               dso__load_symbol_names(dso, &sym, 1);
+       if (sym && sym->name == unknown_name)
+               return NULL;
+       return sym;
+}
+
 struct symbol *dso__find_symbol(struct dso *dso, u64 addr)
 {
        if (dso__last_find_result_addr(dso) != addr || dso__last_find_result_symbol(dso) == NULL) {
@@ -645,22 +696,22 @@ struct symbol *dso__find_symbol(struct dso *dso, u64 addr)
                dso__set_last_find_result_symbol(dso, symbols__find(dso__symbols(dso), addr));
        }
 
-       return dso__last_find_result_symbol(dso);
+       return dso__named_symbol(dso, dso__last_find_result_symbol(dso));
 }
 
 struct symbol *dso__find_symbol_nocache(struct dso *dso, u64 addr)
 {
-       return symbols__find(dso__symbols(dso), addr);
+       return dso__named_symbol(dso, symbols__find(dso__symbols(dso), addr));
 }
 
 struct symbol *dso__first_symbol(struct dso *dso)
 {
-       return symbols__first(dso__symbols(dso));
+       return symbols__first(dso__named_symbols(dso));
 }
 
 struct symbol *dso__last_symbol(struct dso *dso)
 {
-       return symbols__last(dso__symbols(dso));
+       return symbols__last(dso__named_symbols(dso));
 }
 
 struct symbol *dso__next_symbol(struct symbol *sym)
@@ -692,12 +743,58 @@ struct symbol *dso__find_symbol_by_name(struct dso *dso, const char *name, size_
        return s;
 }
 
+/*
+ * Load every lazy name. Do not delete the symbols whose name cannot be
+ * read, since address lookups search the tree without the DSO lock.
+ */
+static void __dso__load_all_symbol_names(struct dso *dso)
+{
+       struct rb_node *nd = rb_first_cached(dso__symbols(dso));
+       struct symbol *batch[512];
+
+       while (nd) {
+               size_t nr = 0;
+
+               for (; nd && nr < ARRAY_SIZE(batch); nd = rb_next(nd)) {
+                       struct symbol *pos = rb_entry(nd, struct symbol, rb_node);
+
+                       if (symbol__has_lazy_name(pos))
+                               batch[nr++] = pos;
+               }
+               if (nr)
+                       dso__load_symbol_names(dso, batch, nr);
+       }
+}
+
+/*
+ * Lazy names exist only in userspace DSOs, and are all loaded once the DSO
+ * is sorted by name. Checking that first avoids taking the DSO lock, which
+ * the callers that walk kernel symbols may hold.
+ */
+static bool dso__may_have_lazy_names(struct dso *dso)
+{
+       return symbol_conf.lazy_load_symbols && !dso__kernel(dso) &&
+              !dso__sorted_by_name(dso);
+}
+
+struct rb_root_cached *dso__named_symbols(struct dso *dso)
+{
+       if (dso__may_have_lazy_names(dso)) {
+               mutex_lock(dso__lock(dso));
+               __dso__load_all_symbol_names(dso);
+               mutex_unlock(dso__lock(dso));
+       }
+       return dso__symbols(dso);
+}
+
 void dso__sort_by_name(struct dso *dso)
 {
        mutex_lock(dso__lock(dso));
        if (!dso__sorted_by_name(dso)) {
                size_t len = 0;
 
+               if (dso__may_have_lazy_names(dso))
+                       __dso__load_all_symbol_names(dso);
                dso__set_symbol_names(dso, symbols__sort_by_name(dso__symbols(dso), &len));
                if (dso__symbol_names(dso)) {
                        dso__set_symbol_names_len(dso, len);
tools/perf/util/symbol.h +27 -2
index c231d8e4427c..5ab222b0655b 100644
@@ -80,9 +80,18 @@ enum symbol_idle_kind {
 #define SYMBOL_FLAG_INLINED         (1 << 11)
 #define SYMBOL_FLAG_ANNOTATE2       (1 << 12)
 #define SYMBOL_FLAG_IFUNC_ALIAS     (1 << 13)
+#define SYMBOL_FLAG_LAZY_NAME       (1 << 14)
 /**
  * A symtab entry. When allocated this may be preceded by an annotation (see
  * symbol__annotation) and/or a browser_index (see symbol__browser_index).
+ *
+ * With symbol_conf.lazy_load_symbols, the ELF loader may create symbols
+ * with SYMBOL_FLAG_LAZY_NAME, whose name is still in the symbol table file.
+ * The functions that return a symbol of a DSO, such as dso__find_symbol(),
+ * load its name first, and dso__named_symbols() loads them all for code
+ * that walks the symbols. A symbol whose name cannot be read is named
+ * "[unknown]", and address lookups return NULL for it. Code that walks
+ * dso__symbols() directly must not read the name of a lazy symbol.
  */
 struct symbol {
        struct rb_node  rb_node;
@@ -94,13 +103,24 @@ struct symbol {
        _Atomic uint16_t flags;
        /** Architecture specific. Unused except on PPC where it holds st_other. */
        u8              arch_sym;
-       /** The name of length namelen associated with the symbol. */
-       char            *name;
+       union {
+               /** The name of length namelen associated with the symbol. */
+               char    *name;
+               /** File offset of the name while SYMBOL_FLAG_LAZY_NAME is set. */
+               u64     name_off;
+       };
 };
 
 void symbol__delete(struct symbol *sym);
 void symbols__delete(struct rb_root_cached *symbols);
 
+/* Pairs with the release in symbol__set_lazy_name(). */
+static inline bool symbol__has_lazy_name(const struct symbol *sym)
+{
+       return (atomic_load_explicit(&sym->flags, memory_order_acquire) &
+               SYMBOL_FLAG_LAZY_NAME) != 0;
+}
+
 static inline u8 symbol__type(const struct symbol *sym)
 {
        return (atomic_load_explicit(&sym->flags, memory_order_relaxed) &
@@ -227,6 +247,9 @@ void symbol__elf_init(void);
 int symbol__annotation_init(void);
 
 struct symbol *symbol__new(u64 start, u64 len, u8 binding, u8 type, const char *name);
+struct symbol *symbol__new_lazy(u64 start, u64 len, u8 binding, u8 type, u64 name_off);
+void symbol__set_lazy_name(struct symbol *sym, char *name);
+void symbol__set_unknown_name(struct symbol *sym);
 size_t __symbol__fprintf_symname_offs(const struct symbol *sym,
                                      const struct addr_location *al,
                                      bool unknown_as_addr,
@@ -257,11 +280,13 @@ int dso__load_bfd_symbols(struct dso *dso, const char *debugfile);
 int dso__load_sym(struct dso *dso, struct map *map, struct symsrc *syms_ss,
                  struct symsrc *runtime_ss, int kmodule);
 int dso__synthesize_plt_symbols(struct dso *dso, struct symsrc *ss);
+void dso__load_symbol_names(struct dso *dso, struct symbol **syms, size_t nr);
 
 char *dso__demangle_sym(struct dso *dso, int kmodule, const char *elf_name);
 
 void __symbols__insert(struct rb_root_cached *symbols, struct symbol *sym);
 void symbols__insert(struct rb_root_cached *symbols, struct symbol *sym);
+struct symbol *symbols__find(struct rb_root_cached *symbols, u64 ip);
 void symbols__fixup_duplicate(struct rb_root_cached *symbols);
 void symbols__fixup_end(struct rb_root_cached *symbols, bool is_kallsyms);
 
tools/perf/util/symbol_conf.h +1 -1
index 37d35f42dcc1..434b6c51288b 100644
@@ -77,6 +77,7 @@ struct symbol_conf {
                        no_buildid_mmap2,
                        guest_code,
                        lazy_load_kernel_maps,
+                       lazy_load_symbols,
                        keep_exited_threads,
                        annotate_data_member,
                        annotate_data_sample,
 
--

Git-157)

maintainer
#14 lore raw

Re: [PATCH v6 4/5] perf script: Add --lazy-load-symbols to load symbol names lazily

Quoted 76 lines · Ian Rogers
Quoted 74 lines · On Wed, Oct 28, 2026 at 4:42 PM Alireza Haghdoost via B4 Relay…

From: Alireza Haghdoost <[email protected]>

This patch adds the --lazy-load-symbols option to perf script. With this option, perf reads the name of a userspace ELF symbol only when a lookup returns the symbol. Eager loading remains the default.

perf script loads the ELF symbol table of every DSO that appears in a sample and keeps each symbol, with its demangled name, until exit. Most of those symbols are never sampled, and their names take most of the memory. On a large profile this makes symbol loading the main memory cost of perf script, and in a memory-constrained cgroup an OOM kill.

With the option, the loader still creates every symbol, so end fixup, duplicate selection, PLT synthesis and IFUNC marking work as before. But it keeps the file offset of each name instead of copying and demangling the name.

The name pointer and the offset share a union in struct symbol, and SYMBOL_FLAG_LAZY_NAME says which one it holds. The dso__find_symbol*() functions, dso__first_symbol() and dso__last_symbol() load the name of the symbol they return, and code that walks the symbols of a DSO gets them with dso__named_symbols(), which loads every name. So does dso__sort_by_name() before it builds the name-sorted array. A symbol whose name cannot be read is named "[unknown]" instead of being deleted, since address lookups search the symbol tree without the DSO lock. Address lookups return NULL for it, so perf script prints it as an address without a symbol.

During loading, perf reads only the names that it needs:

- the names of aliases that duplicate selection can tell apart only by name,
- the names of IFUNC symbols, which PLT synthesis uses to name the IRELATIVE slots.

The loader also skips a .dynsym entry that copies a lazy .symtab symbol. Duplicate selection would drop the entry, but only after it reads both names, and most exported symbols are such copies.

Other names are read with pread() from the file that dso__get_filename() returns for dso__symtab_type(). The file is open only while perf reads the names, so no descriptor stays open per DSO.

The kernel, modules, PPC64 .opd and .gnu_debugdata, whose symbol table is a temporary file, still load names eagerly.

On a perf script run over a 45,073-sample callchain profile of a large C++ service, where eager loading creates about 1M symbols, lazy loading reduces max RSS from 341 MiB to 154 MiB and time from 3.2 to 1.5 seconds, with identical output.

---
 tools/perf/Documentation/perf-script.txt |   7 +
 tools/perf/builtin-script.c              |   2 +
 tools/perf/ui/browsers/map.c             |   2 +-
 tools/perf/util/dso.c                    |   2 +-
 tools/perf/util/dso.h                    |   3 +-
 tools/perf/util/symbol-elf.c             | 251 +++++++++++++++++++++++++++++--
 tools/perf/util/symbol-minimal.c         |   6 +
 tools/perf/util/symbol.c                 | 113 +++++++++++++-
 tools/perf/util/symbol.h                 |  29 +++-
 tools/perf/util/symbol_conf.h            |   1 +
 10 files changed, 393 insertions(+), 23 deletions(-)
tools/perf/Documentation/perf-script.txt +0 -0
index f0228e784ced..57b3533e6c2a 100644
@@ -343,6 +343,13 @@ include::itrace.txt[]
 
         Default: 127
 
Quoted 16 lines

tools/perf/Documentation/perf-script.txt include::itrace.txt[] · line 352

Quoted 7 lines
tools/perf/Documentation/perf-script.txt +7 -0
+--lazy-load-symbols::
+       Read and demangle userspace ELF symbol names only when perf needs
+       them. By default, perf reads every symbol name from each binary
+       referenced by a sample. This option reduces memory use and usually
+       improves performance when samples reference only a small fraction
+       of a large binary's symbols.
+

Won't it also improve performance if you say link against a library but then only use a portion of that library's contents? I'm thinking this option should really be the default, requiring people to opt out. I may even be tempted to hide this flag so that we have the option later of just always using lazy loading. Since the flag isn't a huge cost in the code, and non-lazy loading is needed in other contexts, perhaps we can make the lazy loading the default behavior and have the flag here be say, "--eager-loading" ?

Agreed on making it default. I'm not sure what's the case that needs eager loading. We can change the code to load all symbols just before it (oh, it seems the patch already handles the cases) then no option would be needed. :)

Quoted 98 lines
Quoted 98 lines
tools/perf/Documentation/perf-script.txt +0 -0
 --ns::
        Use 9 decimal places when displaying time (i.e. show the nanoseconds)
 
tools/perf/builtin-script.c +2 -0
index b6691ebb1b4e..88aaf9cfd132 100644
@@ -4287,6 +4287,8 @@ int cmd_script(int argc, const char **argv)
                     "Set the maximum stack depth when parsing the callchain, "
                     "anything beyond the specified depth will be ignored. "
                     "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
+       OPT_BOOLEAN(0, "lazy-load-symbols", &symbol_conf.lazy_load_symbols,
+                   "Read symbol names only when they are needed"),
        OPT_BOOLEAN(0, "reltime", &reltime, "Show time stamps relative to start"),
        OPT_BOOLEAN(0, "deltatime", &deltatime, "Show time stamps relative to previous event"),
        OPT_BOOLEAN('I', "show-info", &show_full_info,
tools/perf/ui/browsers/map.c +1 -1
index 075a575cdc5d..ef8f75699a07 100644
@@ -108,7 +108,7 @@ int map__browse(struct map *map)
 {
        struct map_browser mb = {
                .b = {
-                       .entries = dso__symbols(map__dso(map)),
+                       .entries = dso__named_symbols(map__dso(map)),
                        .refresh = ui_browser__rb_tree_refresh,
                        .seek    = ui_browser__rb_tree_seek,
                        .write   = map_browser__write,
tools/perf/util/dso.c +1 -1
index ce98613868e7..f41abf442476 100644
@@ -2013,7 +2013,7 @@ size_t dso__fprintf(struct dso *dso, FILE *fp)
        ret += fprintf(fp, "%sloaded, ", dso__loaded(dso) ? "" : "NOT ");
        ret += dso__fprintf_buildid(dso, fp);
        ret += fprintf(fp, ")\n");
-       for (nd = rb_first_cached(dso__symbols(dso)); nd; nd = rb_next(nd)) {
+       for (nd = rb_first_cached(dso__named_symbols(dso)); nd; nd = rb_next(nd)) {
                struct symbol *pos = rb_entry(nd, struct symbol, rb_node);
                ret += symbol__fprintf(pos, fp);
        }
tools/perf/util/dso.h +2 -1
index 3329f417810c..4a60c883cc37 100644
@@ -369,7 +369,7 @@ int dso_id__cmp(const struct dso_id *a, const struct dso_id *b);
  * @n: the 'struct rb_node *' to use as a temporary storage
  */
 #define dso__for_each_symbol(dso, pos, n)      \
-       symbols__for_each_entry(dso__symbols(dso), pos, n)
+       symbols__for_each_entry(dso__named_symbols(dso), pos, n)
 
 static inline void *dso__a2l(const struct dso *dso)
 {
@@ -831,6 +831,7 @@ char *dso__filename_with_chroot(const struct dso *dso, const char *filename);
 bool dso__sorted_by_name(const struct dso *dso);
 void dso__set_sorted_by_name(struct dso *dso);
 void dso__sort_by_name(struct dso *dso);
+struct rb_root_cached *dso__named_symbols(struct dso *dso);
 
 int dso__swap_init(struct dso *dso, unsigned char eidata);
 
tools/perf/util/symbol-elf.c +3 -2
index 1e2716c6af45..bce6c6aef20c 100644
@@ -17,6 +17,7 @@
 #include "machine.h"
 #include "vdso.h"
 #include "debug.h"
+#include "namespaces.h"
 #include "util/copyfile.h"
 #include <linux/ctype.h>
 #include <linux/kernel.h>
@@ -348,7 +349,7 @@ static bool get_ifunc_name(Elf *elf, struct dso *dso, GElf_Ehdr *ehdr,
 
        addr -= phdr.p_vaddr - phdr.p_offset;
 
-       sym = dso__find_symbol_nocache(dso, addr);
+       sym = symbols__find(dso__symbols(dso), addr);
 
        /* Expecting the address to be an IFUNC or IFUNC alias */
        if (!sym || sym->start != addr ||
@@ -629,7 +630,7 @@ int dso__synthesize_plt_symbols(struct dso *dso, struct symsrc *ss)
         * by symbols__fixup_end() to overlap .plt. Truncate it before adding
         * a symbol for .plt header.
         */
-       f = dso__find_symbol_nocache(dso, shdr_plt.sh_offset);
+       f = symbols__find(dso__symbols(dso), shdr_plt.sh_offset);
        if (f && f->start < shdr_plt.sh_offset && f->end > shdr_plt.sh_offset)
                f->end = shdr_plt.sh_offset;
 
@@ -1516,6 +1517,190 @@ static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
        return 0;
 }
 
Quoted 6 lines

tools/perf/util/symbol-elf.c static int dso__process_kernel_symbol(struct dso *dso, struct map *map, · line 1520

Quoted 1 line
tools/perf/util/symbol-elf.c +1 -0
+static DEFINE_MUTEX(lazy_names_lock);

I'm curious if this is global just to avoid the expense of a mutex per symbol or it needs to be global? We have tools/perf/util/sharded_mutex.h as a way of doing a cheaper per object mutex, but perhaps the dso__lock works?

Probably. dso__load() already takes the dso lock.

Quoted 26 lines
Quoted 26 lines
tools/perf/util/symbol-elf.c +25 -0
+
+static char *read_name_at(int fd, u64 off)
+{
+       char small[256], *buf = NULL, *tmp;
+       size_t size = sizeof(small);
+       ssize_t n = pread(fd, small, size, off);
+
+       if (n > 0 && memchr(small, '\0', n))
+               return strdup(small);
+
+       while (n == (ssize_t)size) {
+               size *= 2;
+               tmp = realloc(buf, size);
+               if (!tmp)
+                       break;
+               buf = tmp;
+               n = pread(fd, buf, size, off);
+               if (n > 0 && memchr(buf, '\0', n))
+                       return buf;
+       }
+       free(buf);
+       return NULL;
+}
+
+static int load_symbol_names(struct dso *dso, int fd, struct symbol **syms, size_t nr)
Quoted 8 lines

tools/perf/util/symbol-elf.c static int dso__process_kernel_symbol(struct dso *dso, struct map *map, · line 1553

Quoted 8 lines
tools/perf/util/symbol-elf.c +8 -0
+{
+       int err = 0;
+
+       for (size_t i = 0; i < nr; i++) {
+               char *name, *demangled;
+
+               if (!symbol__has_lazy_name(syms[i]))
+                       continue;

Nit: I'm hesitate to argue about naming, but it seems a bit confusing. Why does it skip to load when it doesn't have a (lazy) name? Probably symbol__needs_lazy_name() would be a little better...?

Thanks,
Namhyung

Quoted 16 lines
Quoted 16 lines
tools/perf/util/symbol-elf.c +16 -0
+               name = read_name_at(fd, syms[i]->name_off);
+               if (!name) {
+                       pr_debug("%s: cannot read the symbol name at %#" PRIx64 "\n",
+                                dso__long_name(dso), syms[i]->name_off);
+                       err = -1;
+                       continue;
+               }
+               demangled = dso__demangle_sym(dso, /*kmodule=*/0, name);
+               if (demangled) {
+                       free(name);
+                       name = demangled;
+               }
+               symbol__set_lazy_name(syms[i], name);
+       }
+       return err;
+}
#15 lore raw

Re: [PATCH v6 4/5] perf script: Add --lazy-load-symbols to load symbol names lazily

Quoted 9 lines · Namhyung Kim
Quoted 2 lines · Ian Rogers

I'm thinking this option should really be the default, requiring people to opt out.

Agreed on making it default. I'm not sure what's the case that needs eager loading. We can change the code to load all symbols just before it (oh, it seems the patch already handles the cases) then no option would be needed. :)

Sorry for the slow reply. I wanted to have v7 ready before answering. I agree that lazy loading should become the default, but I would like to keep it opt-in in v7 and flip it in a separate patch later.

While checking what default-on would change, I found that a binary replaced during the run gave wrong names. Lazy loading reads a name later, at the offset the symbol table had at load time. If a deploy replaces the binary in between, or the path resolves to another file because the process of a mount namespace exited, perf read the names from the new file. I reproduced it by swapping the binary under gdb; perf printed names of the other build. Eager loading reads every name at load time, so it is not affected. I fixed that in v7 and kept the device, inode,
size and modification time of the file and checks them whenever it opens the file again. If they changed, perf warns once and shows the remaining symbols of that DSO as [unknown].

Also, each batch of names opens the file again, resolves its name and enters the mount namespace. On my test profile this is cheap (1.3 s lazy vs 2.9 s eager, identical output), but I have not measured it for containers or debuglink layouts. The type-aware data cache that we discussed on v5 would remove most of that cost.

So my plan is to run lazy loading in our continuous profiling at scale first, and then send a patch that makes it the default. By that time, hopefully we will have already added the type-aware data cache. Does that work for you?

Quoted 4 lines
Quoted 2 lines

I'm curious if this is global just to avoid the expense of a mutex per symbol or it needs to be global? [...] but perhaps the dso__lock works?

Probably. dso__load() already takes the dso lock.

It was global because dso__named_symbols() and dso__sort_by_name() already hold the DSO lock when they load names, and the mutex is not recursive. Nothing that holds the DSO lock looks up symbols, so v7 uses it: a lookup takes it only when the symbol it returns still needs its name, and the batch loader requires it held.

Quoted 3 lines

Nit: I'm hesitate to argue about naming, but it seems a bit confusing. Why does it skip to load when it doesn't have a (lazy) name? Probably symbol__needs_lazy_name() would be a little better...?

Agreed, renamed in v7.

Thanks,
Alireza

maintainer
#16 lore raw

Re: [PATCH v6 4/5] perf script: Add --lazy-load-symbols to load symbol names lazily

Quoted 15 lines · Alireza Haghdoost
Quoted 9 lines · Namhyung Kim
Quoted 2 lines · Ian Rogers

I'm thinking this option should really be the default, requiring people to opt out.

Agreed on making it default. I'm not sure what's the case that needs eager loading. We can change the code to load all symbols just before it (oh, it seems the patch already handles the cases) then no option would be needed. :)

Sorry for the slow reply. I wanted to have v7 ready before answering. I agree that lazy loading should become the default, but I would like to keep it opt-in in v7 and flip it in a separate patch later.

Quoted 12 lines

While checking what default-on would change, I found that a binary replaced during the run gave wrong names. Lazy loading reads a name later, at the offset the symbol table had at load time. If a deploy replaces the binary in between, or the path resolves to another file because the process of a mount namespace exited, perf read the names from the new file. I reproduced it by swapping the binary under gdb; perf printed names of the other build. Eager loading reads every name at load time, so it is not affected. I fixed that in v7 and kept the device, inode,
size and modification time of the file and checks them whenever it opens the file again. If they changed, perf warns once and shows the remaining symbols of that DSO as [unknown].

We have struct dso_id to identify the binary. The build-ID is the preferred method to check it.

Quoted 6 lines

Also, each batch of names opens the file again, resolves its name and enters the mount namespace. On my test profile this is cheap (1.3 s lazy vs 2.9 s eager, identical output), but I have not measured it for containers or debuglink layouts. The type-aware data cache that we discussed on v5 would remove most of that cost.

Right, having a fd in the cache, would solve many problems.

Quoted 5 lines

So my plan is to run lazy loading in our continuous profiling at scale first, and then send a patch that makes it the default. By that time, hopefully we will have already added the type-aware data cache. Does that work for you?

Sounds good. A real world testing would be great. I'll find time to work on the DSO access.

Quoted 12 lines
Quoted 5 lines
Quoted 3 lines

I'm curious if this is global just to avoid the expense of a mutex per symbol or it needs to be global? [...] but perhaps the dso__lock works?

Probably. dso__load() already takes the dso lock.

It was global because dso__named_symbols() and dso__sort_by_name() already hold the DSO lock when they load names, and the mutex is not recursive. Nothing that holds the DSO lock looks up symbols, so v7 uses it: a lookup takes it only when the symbol it returns still needs its name, and the batch loader requires it held.

Quoted 5 lines
Quoted 3 lines

Nit: I'm hesitate to argue about naming, but it seems a bit confusing. Why does it skip to load when it doesn't have a (lazy) name? Probably symbol__needs_lazy_name() would be a little better...?

Agreed, renamed in v7.

Thanks,
Namhyung

#17 lore raw

Re: [PATCH v6 4/5] perf script: Add --lazy-load-symbols to load symbol names lazily

Quoted 3 lines · Namhyung Kim

We have struct dso_id to identify the binary. The build-ID is the preferred method to check it.

Good point, I'll use the build-ID from dso_id for this check in v8.

Thanks,
Alireza

#18 lore raw

PATCH v6 5/5 perf test: Test lazy symbol name loading

In reply to Alireza Haghdoost

Add a "Lazy symbol loading" unit test suite:

- "Duplicate selection without names" checks which pairs of symbols symbol__choice_needs_names() leaves to their names.
- "Lazy symbol names" looks up lazy symbols whose names take one, two and three reads, and two whose names cannot be read: one with no NUL before the end of the file and one past the end. Lookups do not return those, and dso__sort_by_name() keeps them, named "[unknown]".
- "Lazy symbol names loaded concurrently" looks up the same lazy symbols, some of them with names that cannot be read, from several threads while another walks them with dso__for_each_symbol(), and checks every name.
- "Lazy and eager symbol parity" loads a DSO (perf itself, or the one given with --dso) eagerly and lazily. Lookups of the first and last address of each eager symbol must find the same symbol before and after every lazy name is loaded, and then the ranges and names of all symbols must match.

Run the parity test from a shell test on four hand-built binaries:

- a split-debuginfo binary whose function section is NOBITS in the debug file and has no PT_LOAD in the runtime file, so both loaders must fall back to the runtime section header;
- a shared library with symbols present only in .dynsym, one of them

    an alias that duplicate selection prefers over its .symtab twin;
  - a stripped shared library whose local symbols are in .gnu_debugdata,
    one of them an alias of a .dynsym symbol, which must load eagerly;

- on x86_64, a binary with an IRELATIVE PLT slot whose IFUNC loses duplicate selection to an alias that loses to another one in turn, so the PLT symbol name depends on how the IFUNC mark is passed on.

Add a perf script shell test for --lazy-load-symbols. Record a small callchain fixture, require evidence that the perf binary was loaded with lazy names, check that the controlled test_loop symbol resolves, and compare the eager and lazy output. When run as root, also profile perf in a private mount namespace whose build-id cache directory is hidden by a tmpfs, so that names must be read from the build-id cache in perf's own namespace. The test reports a skip only if neither case can run, for example when libelf is missing or recording is not supported.

---
 tools/perf/tests/Build                             |   1 +
 tools/perf/tests/builtin-test.c                    |   1 +
 tools/perf/tests/shell/lazy_load_symbols_parity.sh | 284 +++++++++++
 tools/perf/tests/shell/script_lazy_load_symbols.sh | 177 +++++++
 tools/perf/tests/symbol-lazy.c                     | 544 +++++++++++++++++++++
 tools/perf/tests/tests.h                           |   1 +
 6 files changed, 1008 insertions(+)
tools/perf/tests/Build +1 -0
index 58858f3d2bf9..39a8e110eeae 100644
@@ -68,6 +68,7 @@ perf-test-y += sigtrap.o
 perf-test-y += event_groups.o
 perf-test-y += hybrid-merge.o
 perf-test-y += symbols.o
+perf-test-y += symbol-lazy.o
 perf-test-y += util.o
 perf-test-y += hwmon_pmu.o
 perf-test-y += tool_pmu.o
tools/perf/tests/builtin-test.c +1 -0
index 0b8897fd42ca..716a24423282 100644
@@ -174,6 +174,7 @@ static struct test_suite *generic_tests[] = {
 	&suite__event_groups,
 	&suite__hybrid_merge,
 	&suite__symbols,
+	&suite__symbol_lazy,
 	&suite__util,
 	&suite__subcmd_help,
 	&suite__kallsyms_split,
tools/perf/tests/shell/lazy_load_symbols_parity.sh new file +284 -0

284 lines not on this page · raw message

tools/perf/tests/shell/script_lazy_load_symbols.sh new file +177 -0

177 lines not on this page · raw message

tools/perf/tests/symbol-lazy.c new file +544 -0

544 lines not on this page · raw message

tools/perf/tests/tests.h +1 -0
index 20ae3609892b..902e3c13968f 100644
@@ -197,6 +197,7 @@ DECLARE_SUITE(sigtrap);
 DECLARE_SUITE(event_groups);
 DECLARE_SUITE(hybrid_merge);
 DECLARE_SUITE(symbols);
+DECLARE_SUITE(symbol_lazy);
 DECLARE_SUITE(util);
 DECLARE_SUITE(uncore_event_sorting);
 DECLARE_SUITE(subcmd_help);
Signature · 1 line
Git-157)
#19 lore raw

Re: [PATCH v6 5/5] perf test: Test lazy symbol name loading

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Medium] perf test: missing skip when .opd or .gnu_debugdata disables lazy names - [Medium] perf test…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Medium] perf test: missing skip when .opd or .gnu_debugdata disables lazy names
- [Medium] perf test: script_lazy_load_symbols.sh fails before reaching skip check
- [Medium] perf test: assertion failure or OOB read in sym_loader__init() on kernel DSO
- [Low] perf test symbol-lazy: missing explicit <stdio.h> and <stdbool.h> includes --

commit 80f2faac89471ac12d3bce19d66d36a7c65ef72f
Author: Alireza Haghdoost <[email protected]>

perf test: Test lazy symbol name loading

This commit adds a unit test suite in tools/perf/tests/symbol-lazy.c and two shell tests (lazy_load_symbols_parity.sh and script_lazy_load_symbols.sh) to verify lazy symbol name loading, concurrency, and parity with eager loading.

Quoted 6 lines
tools/perf/tests/shell/lazy_load_symbols_parity.sh new file +0 -0
new file mode 100755
index 0000000000000..af1555d7f8d09
@@ -0,0 +1,284 @@

[ ... ]

Quoted 8 lines
tools/perf/tests/shell/lazy_load_symbols_parity.sh new file +8 -0
+# check_parity NAME FILE [eager]
+# Lazy loading must leave names of FILE unread, or none if "eager" is given.
+check_parity() {
+	local out="${tmpdir}/parity.out"
+	local lazy="[0-9][0-9]* symbols with lazy names"
+
+	if [ "$3" = eager ]; then
+		lazy="no lazy names"

tools/perf/tests/shell/lazy_load_symbols_parity.sh line 67

Quoted 10 lines
tools/perf/tests/shell/lazy_load_symbols_parity.sh new file +10 -0
+	fi
+	perf test --dso "$2" -vv "Lazy and eager symbol parity" > "${out}" 2>&1 || true
+	if grep -q ': Ok$' "${out}" && grep -q "^$2: ${lazy}$" "${out}"; then
+		echo "Lazy-load parity $1 [Success]"
+		return
+	fi
+	grep -E 'symbols$|names$|mismatch|lookup|no symbols' "${out}" || true
+	echo "Lazy-load parity $1 [Failed]"
+	err=1
+}

[Severity: Medium]
In tools/perf/util/symbol-elf.c, dso__load_sym_internal() disables lazy symbol name loading when an .opd section is present (such as on PPC64 ELFv1), when symbols come from .gnu_debugdata, or when .strtab has SHF_COMPRESSED:

tools/perf/util/symbol-elf.c:dso__load_sym_internal() {
	...
	bool lazy_allowed = symbol_conf.lazy_load_symbols && !dso__kernel(dso) &&
			  !kmodule && syms_ss->type == dso__symtab_type(dso) &&
			  syms_ss->type != DSO_BINARY_TYPE__GNU_DEBUGDATA &&
			  !runtime_ss->opdsec;
	...
}

In lazy_load_symbols_parity.sh, test_split_debug() and test_dynsym_only() call check_parity() without the eager argument, requiring a non-zero count of lazy names in the output of test__symbol_lazy_parity(). Similarly, in tools/perf/tests/shell/script_lazy_load_symbols.sh, skip_test_missing_symbol passes as long as eager symbol loading resolves test_loop, and then test_lazy_load_identical() and test_lazy_load_mount_ns() require lazy names on perf_path.

Won't these tests fail with err=1 instead of skipping on PPC64 ELFv1 hosts where the compiler emits an .opd section, or when the perf binary uses .gnu_debugdata MiniDebugInfo or SHF_COMPRESSED string tables?

Quoted 6 lines
tools/perf/tests/shell/script_lazy_load_symbols.sh new file +0 -0
new file mode 100755
index 0000000000000..88840bfafdf64
@@ -0,0 +1,177 @@

[ ... ]

Quoted 27 lines
tools/perf/tests/shell/script_lazy_load_symbols.sh new file +27 -0
+test_lazy_load_identical() {
+	echo "Lazy-load output matches eager loader"
+
+	if ! perf record -o "${perfdata}" -g -- perf test -w thloop 2> /dev/null
+	then
+		echo "Lazy-load identical [Skipped record not supported]"
+		return 0
+	fi
+
+	if ! perf script -i "${perfdata}" 2> /dev/null > "${eager_out}" || \
+	   ! perf script -v --lazy-load-symbols -i "${perfdata}" \
+		2> "${lazy_err}" > "${lazy_out}"
+	then
+		echo "Lazy-load identical [Failed perf script error]"
+		err=1
+		return
+	fi
+	if ! grep -Eq "${lazy_names}" "${lazy_err}"
+	then
+		echo "Lazy-load identical [Failed lazy loader fell back to eager]"
+		err=1
+		return
+	fi
+	if ! grep -F "${perf_path}: " "${lazy_err}" | grep -Eq "${lazy_names}"
+	then
+		echo "Lazy-load identical [Failed controlled DSO has no lazy names]"
+		err=1

tools/perf/tests/shell/script_lazy_load_symbols.sh line 88

Quoted 10 lines
tools/perf/tests/shell/script_lazy_load_symbols.sh new file +10 -0
+		return
+	fi
+
+	# The comparison is only meaningful if something actually resolved;
+	# two all-[unknown] outputs would also match.
+	if ! grep -q "${testsym}" "${eager_out}"
+	then
+		echo "Lazy-load identical [Skipped no ${testsym} resolved]"
+		return 0
+	fi

[Severity: Medium]
In perf script, user-space DSOs are only loaded on demand via thread__find_symbol() -> map__find_symbol() -> map__load() -> dso__load() when a sample or callchain IP falls within that DSO's map.

If perf record succeeds but captures no samples in perf_path (for example, in a virtualized or CPU-constrained environment), dso__load_sym_internal() is never called for perf_path, so lazy_err will not contain lazy symbol messages for perf_path.

Because test_lazy_load_identical() checks lazy_err before checking whether testsym was resolved in eager_out, won't it fail with err=1 before ever reaching the skip check for testsym? Should the check that testsym is present in eager_out happen first (and likewise in test_lazy_load_mount_ns() when the 1-second attached recording captures no samples in testsym)?

Quoted 6 lines
tools/perf/tests/symbol-lazy.c new file +0 -0
new file mode 100644
index 0000000000000..52d4a9850e19b

tools/perf/tests/symbol-lazy.c line 9

Quoted 9 lines
tools/perf/tests/symbol-lazy.c new file +9 -0
@@ -0,0 +1,544 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <inttypes.h>
+#include <limits.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <unistd.h>
+#include <linux/kernel.h>

[Severity: Low]
In tools/perf/tests/symbol-lazy.c, lazy_fixture__init() uses FILE *, fdopen(), fputc(), fwrite(), and fclose(), and test__symbol_lazy_choice() and other functions use bool, true, false, and ELF symbol constants (STT_FUNC, STT_NOTYPE, STT_GNU_IFUNC, STB_GLOBAL, STB_WEAK, STB_LOCAL).

Could <stdio.h>, <stdbool.h>, and <elf.h> be explicitly included at the top of tools/perf/tests/symbol-lazy.c so the build does not rely on transitive header inclusions, particularly when building against musl libc?

[ ... ]

Quoted 5 lines
tools/perf/tests/symbol-lazy.c new file +5 -0
+static int sym_loader__init(struct sym_loader *l, const char *filename, bool lazy)
+{
+	memset(l, 0, sizeof(*l));
+	perf_env__init(&l->env);
+	symbol_conf.lazy_load_symbols = lazy;

tools/perf/tests/symbol-lazy.c line 419

Quoted 10 lines
tools/perf/tests/symbol-lazy.c new file +10 -0
+	l->machine = machine__new_host(&l->env);
+	if (l->machine)
+		l->thread = machine__findnew_thread(l->machine, 100, 100);
+	if (l->thread)
+		l->map = map__new(l->machine, 0x100000, 0xffffffff, 0, &dso_id_empty,
+				  PROT_EXEC, /*flags=*/0, (char *)filename, l->thread);
+	if (!l->map) {
+		sym_loader__exit(l);
+		return TEST_FAIL;
+	}

[Severity: Medium]
In sym_loader__init(), machine__new_host() populates l->machine->dsos with the host kernel and all currently loaded kernel modules (which have dso__kernel(dso) != DSO_SPACE__USER).

If a user runs perf test with --dso pointing to a currently loaded kernel module or kernel DSO, test__symbol_lazy_parity() passes that path into sym_loader__init() -> map__new(), where machine__findnew_dso_id() returns the existing kernel DSO:

tools/perf/util/map.c:map__new() {
	...
	dso = machine__findnew_dso_id(machine, filename, id);

	if (dso == NULL)
		goto out_delete;

	assert(!dso__kernel(dso));
	...
}

In default builds, won't this trigger assert(!dso__kernel(dso)), and in builds with -DNDEBUG, cause dso__load() -> dso__load_sym_internal() -> map__kmap() to read past the end of the map allocation because map__new() did not allocate space for struct kmap? Should sym_loader__init() handle kernel DSOs similarly to create_map() in tools/perf/tests/symbols.c?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
reviewer
#20 lore raw

Re: [PATCH v6 5/5] perf test: Test lazy symbol name loading

In reply to Alireza Haghdoost
Quoted 43 lines · On Wed, Oct 28, 2026 at 4:42 PM Alireza Haghdoost via B4 Relay…

From: Alireza Haghdoost <[email protected]>

Add a "Lazy symbol loading" unit test suite:

- "Duplicate selection without names" checks which pairs of symbols symbol__choice_needs_names() leaves to their names.
- "Lazy symbol names" looks up lazy symbols whose names take one, two and three reads, and two whose names cannot be read: one with no NUL before the end of the file and one past the end. Lookups do not return those, and dso__sort_by_name() keeps them, named "[unknown]".
- "Lazy symbol names loaded concurrently" looks up the same lazy symbols, some of them with names that cannot be read, from several threads while another walks them with dso__for_each_symbol(), and checks every name.
- "Lazy and eager symbol parity" loads a DSO (perf itself, or the one given with --dso) eagerly and lazily. Lookups of the first and last address of each eager symbol must find the same symbol before and after every lazy name is loaded, and then the ranges and names of all symbols must match.

Run the parity test from a shell test on four hand-built binaries:

- a split-debuginfo binary whose function section is NOBITS in the debug file and has no PT_LOAD in the runtime file, so both loaders must fall back to the runtime section header;
- a shared library with symbols present only in .dynsym, one of them

    an alias that duplicate selection prefers over its .symtab twin;
  - a stripped shared library whose local symbols are in .gnu_debugdata,
    one of them an alias of a .dynsym symbol, which must load eagerly;

- on x86_64, a binary with an IRELATIVE PLT slot whose IFUNC loses duplicate selection to an alias that loses to another one in turn, so the PLT symbol name depends on how the IFUNC mark is passed on.

Add a perf script shell test for --lazy-load-symbols. Record a small callchain fixture, require evidence that the perf binary was loaded with lazy names, check that the controlled test_loop symbol resolves, and compare the eager and lazy output. When run as root, also profile perf in a private mount namespace whose build-id cache directory is hidden by a tmpfs, so that names must be read from the build-id cache in perf's own namespace. The test reports a skip only if neither case can run, for example when libelf is missing or recording is not supported.

Quoted 1 line

Huge fan of testing, and Sashiko can be a pain about corner cases. Thanks for working on this! I'm happy to add a tag when Sashiko is more happy.

Ian