Skip to contentSkip to conversation

perf script: Bounded and lazy symbol loading

PATCH Superseded Alireza Haghdoost 3 participants 21 messages Sep 25 – Sep 30 perf events

v3 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v3 cover perf script: Bounded and lazy symbol loading

perf script loads the entire ELF symbol table of every DSO that appears in a sample, allocating each symbol into an rb-tree held until process exit. Therefore, a large enough profile turns symbol loading into an OOM kill. This does not scale to profiling a large cgroup with many large binaries on a production system with limited free memory.

This series adds two independent, opt-in mechanisms, a leading regression fix, and two preparatory patches:

[1/6] 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.

[2/6] Let a DSO read its data from one explicit file through the DSO
data cache. This fixes the split-debuginfo case where offsets from the debuginfo file would be applied to the runtime image.

[3/6] Factor duplicate-symbol selection so it works on symbol
attributes rather than struct symbol. No functional change.

[4/6] --max-symbol-bytes <size>: a byte budget on struct symbol
allocations (and the lazy index) enforced at the ELF symbol loader, degrading to [unknown] with a warning past the cap. An unbounded profile doesn't just risk OOM-killing itself. It also forces memory pressure on the whole host, pushing the kernel to reclaim from co-located latency-sensitive processes. Capping it lets the user bound that footprint up front and choose the trade-off explicitly.

[5/6] --lazy-load-symbols: build a compact per-DSO sorted index and
resolve only the sampled addresses, reading names through the DSO data cache at lookup time. On the production fixture, peak RssAnon drops from 265 MiB to 39 MiB (6.8x) and wall time from 3.1 s to 1.85 s (1.7x). Memory optimizations usually cost time; this one does not because lazy loading skips a lot of calloc and demangle calls.

[6/6] Shell and unit tests for both options.

Lazy loading handles the common userspace ELF symtab/dynsym path. Eager loading remains available for dense coverage and for PPC64 .opd and .gnu_debugdata.

Changes in v3:

- Rebase onto current perf-tools-next.
- Pick up Namhyung's Reviewed-by for patch 1.
- Split the exact-path DSO data support into its own patch (2/6), with a DSO data test for reading and reopening through an explicit path.
- Move the duplicate-selection refactor into a preparatory patch (3/6) and factor the whole lazy alias-group handling (traversal, demangling, IFUNC propagation, compaction) into one helper.
- Keep struct symbol::namelen as u16. Charge symbol bytes from the stored namelen on both allocation and free, and drop the 64 KiB-name test.
- Fix lazy-loading races reported by Sashiko: in lazy mode, address lookups always take the DSO lock, and building the name-sorted array materializes and frees the lazy index even when the budget truncates it, so the name array is never invalidated. dso__reset_symbol_names() is gone. Add a concurrent budget-truncation test.
- In lazy mode, when no PT_LOAD covers a symbol and its section is NOBITS in the debuginfo file, adjust with the runtime section header as eager loading does. Add a lazy/eager symbol parity test and a split-debuginfo shell test that exercises this path.
- Keep each unit test with the code it needs (DSO data in 2/6, budget reservation in 4/6); the other tests stay in 6/6.

Changes in v2:

- Replace direct pread() name reads with the exact symbol source's DSO data cache, preserving split-debuginfo offsets and descriptor reopen behavior.
- Drop the byte-identical-output claim and retain eager loading for PPC64 .opd and .gnu_debugdata.
- Make the symbol budget atomic and strict, account complete name lengths, accept a bare 0 as unlimited, and keep partial zero-sized ranges from covering omitted symbols.
- Align lazy lookup with eager duplicate and IFUNC selection, PLT clipping, and name-sorted materialization.
- Move option documentation into the feature patches. Add unit and shell coverage for cache reopen, truncated names, budget truncation, and skip handling.

---
Alireza Haghdoost (6):
perf symbols: Fix broken ELF_C_READ_MMAP fallback guard perf dso: Allow reading DSO data from an explicit file perf symbols: Factor out duplicate symbol selection perf script: Add --max-symbol-bytes to bound ELF symbol memory perf script: Add --lazy-load-symbols for lazy symbol loading perf test: Test lazy symbol loading and symbol memory limits

 tools/perf/Documentation/perf-script.txt           |  26 +
 tools/perf/arch/powerpc/util/sym-handling.c        |   6 +-
 tools/perf/builtin-script.c                        |  44 ++
 tools/perf/tests/Build                             |   1 +
 tools/perf/tests/builtin-test.c                    |   1 +
 tools/perf/tests/dso-data.c                        |  42 ++
 .../tests/shell/lazy_load_symbols_split_debug.sh   | 113 ++++
 tools/perf/tests/shell/script_lazy_load_symbols.sh | 278 ++++++++
 .../tests/shell/script_lazy_load_symbols_skip.sh   |  26 +
 tools/perf/tests/symbol-bytes.c                    | 599 +++++++++++++++++
 tools/perf/tests/tests.h                           |   1 +
 tools/perf/util/dso.c                              |  60 +-
 tools/perf/util/dso.h                              |  47 ++
 tools/perf/util/map.c                              |  19 +-
 tools/perf/util/symbol-elf.c                       | 728 ++++++++++++++++++++-
 tools/perf/util/symbol-minimal.c                   |  16 +
 tools/perf/util/symbol.c                           | 143 +++-
 tools/perf/util/symbol.h                           |  30 +-
 tools/perf/util/symbol_conf.h                      |   2 +
 19 files changed, 2133 insertions(+), 49 deletions(-)

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

Best regards,

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

PATCH v3 1/6 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 v3 1/6] perf symbols: Fix broken ELF_C_READ_MMAP fallback guard

Sashiko has reviewed this patch and found no issues. It looks great!
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. It looks great!

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

PATCH v3 2/6 perf dso: Allow reading DSO data from an explicit file

In reply to Alireza Haghdoost

The DSO data cache derives the file to open from the DSO's binary type, which can resolve to the runtime image rather than the file a symbol table was read from. With split debuginfo, offsets taken from the debuginfo file (for example string-table offsets) are then applied to an unrelated file.

Add dso__data_set_path() so a DSO can be configured to read from one exact file while keeping the data cache's descriptor eviction and reopening. Such DSOs may be owned privately rather than being part of a dsos collection, so drop the assertion that every opened data DSO is in one.

Add a DSO data test that reads through an explicit path, closes the descriptor, and reads an uncached offset to exercise reopening.

---
 tools/perf/tests/dso-data.c | 42 ++++++++++++++++++++++++++++++++++++++++++
 tools/perf/util/dso.c       | 43 ++++++++++++++++++++++++++++++++++---------
 tools/perf/util/dso.h       |  2 ++
 3 files changed, 78 insertions(+), 9 deletions(-)
tools/perf/tests/dso-data.c +42 -0
index 46bc3f597260..fbfb2f08d3ba 100644
@@ -393,11 +393,53 @@ static int test__dso_data_reopen(struct test_suite *test __maybe_unused, int sub
 	return 0;
 }
 
+static int test__dso_data_path(struct test_suite *test __maybe_unused, int subtest __maybe_unused)
+{
+	u8 expect[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
+	char *file = test_file(TEST_FILE_SIZE);
+	struct dso *dso;
+	long nr, nr_end;
+	u8 buf[10];
+
+	TEST_ASSERT_VAL("No test file", file);
+	nr = open_files_cnt();
+
+	/*
+	 * The DSO name does not exist and the DSO is not in a dsos
+	 * collection; reads must come from the configured path.
+	 */
+	dso = dso__new("/nonexistent/perf-test-dso-data-path");
+	TEST_ASSERT_VAL("Failed to create dso", dso);
+	dso__set_binary_type(dso, DSO_BINARY_TYPE__SYSTEM_PATH_DSO);
+	TEST_ASSERT_VAL("Failed to set path", !dso__data_set_path(dso, file));
+
+	TEST_ASSERT_VAL("Wrong size",
+			dso__data_read_offset(dso, NULL, 10, buf, 10) == 10);
+	TEST_ASSERT_VAL("Wrong data", !memcmp(buf, expect, 10));
+
+	/* An uncached offset after close must reopen the configured path. */
+	dso__data_close(dso);
+	memset(buf, 0, sizeof(buf));
+	TEST_ASSERT_VAL("Wrong size after reopen",
+			dso__data_read_offset(dso, NULL, DSO__DATA_CACHE_SIZE * 2 + 10,
+					      buf, 10) == 10);
+	TEST_ASSERT_VAL("Wrong data after reopen",
+			buf[0] == (DSO__DATA_CACHE_SIZE * 2 + 10) % 10);
+
+	dso__data_close(dso);
+	dso__put(dso);
+	unlink(file);
+
+	nr_end = open_files_cnt();
+	TEST_ASSERT_VAL("failed leaking files", nr == nr_end);
+	return 0;
+}
 
 static struct test_case tests__dso_data[] = {
 	TEST_CASE("read", dso_data),
 	TEST_CASE("cache", dso_data_cache),
 	TEST_CASE("reopen", dso_data_reopen),
+	TEST_CASE("explicit path", dso_data_path),
 	{	.name = NULL, }
 };
 
tools/perf/util/dso.c +34 -9

70 lines not on this page · raw message

tools/perf/util/dso.h +2 -0
index e7d5f4bbf894..ff2c91e9a2b9 100644
@@ -264,6 +264,7 @@ struct dso_data {
 #ifdef REFCNT_CHECKING
 	struct dso	 *dso;
 #endif
+	char		 *path;
 	int		 fd;
 	int		 status;
 	u32		 status_seen;
@@ -910,6 +911,7 @@ bool dso__data_get_fd(struct dso *dso, struct machine *machine, int *fd)
 	EXCLUSIVE_TRYLOCK_FUNCTION(true, _dso__data_open_lock);
 void dso__data_put_fd(struct dso *dso) UNLOCK_FUNCTION(_dso__data_open_lock);
 void dso__data_close(struct dso *dso) LOCKS_EXCLUDED(_dso__data_open_lock);
+int dso__data_set_path(struct dso *dso, const char *path);
 
 int dso__data_file_size(struct dso *dso, struct machine *machine);
 off_t dso__data_size(struct dso *dso, struct machine *machine);
Signature · 1 line
Git-157)
#4 lore raw

Re: [PATCH v3 2/6] perf dso: Allow reading DSO data from an explicit file

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 14 lines

From: Alireza Haghdoost <[email protected]>

The DSO data cache derives the file to open from the DSO's binary type, which can resolve to the runtime image rather than the file a symbol table was read from. With split debuginfo, offsets taken from the debuginfo file (for example string-table offsets) are then applied to an unrelated file.

Add dso__data_set_path() so a DSO can be configured to read from one exact file while keeping the data cache's descriptor eviction and reopening. Such DSOs may be owned privately rather than being part of a dsos collection, so drop the assertion that every opened data DSO is in one.

Quoted 4 lines

Add a DSO data test that reads through an explicit path, closes the descriptor, and reads an uncached offset to exercise reopening.

Sashiko has reviewed this patch and found no issues. It looks great!

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

PATCH v3 3/6 perf symbols: Factor out duplicate symbol selection

In reply to Alireza Haghdoost

symbols__fixup_duplicate() chooses between symbols with the same start address through choose_best_symbol(), which needs fully constructed struct symbol objects. A loader that selects among aliases before allocating symbols cannot use it.

Move the policy into symbol__choose_best(), which compares the size, name, type and binding of two candidates described by struct symbol_candidate, and pass the same description to the arch__choose_best_symbol() hook. choose_best_symbol() becomes a wrapper that describes two struct symbols. No functional change intended.

---
 tools/perf/arch/powerpc/util/sym-handling.c |  6 ++--
 tools/perf/util/symbol.c                    | 43 +++++++++++++++++++++--------
 tools/perf/util/symbol.h                    | 14 +++++++++-
 3 files changed, 47 insertions(+), 16 deletions(-)
tools/perf/arch/powerpc/util/sym-handling.c +3 -3
index 947bfad7aa59..c263cbfefba5 100644
@@ -10,10 +10,10 @@
 #include "probe-event.h"
 #include "probe-file.h"
 
-int arch__choose_best_symbol(struct symbol *syma,
-			     struct symbol *symb __maybe_unused)
+int arch__choose_best_symbol(const struct symbol_candidate *syma,
+			     const struct symbol_candidate *symb __maybe_unused)
 {
-	char *sym = syma->name;
+	const char *sym = syma->name;
 
 #if !defined(_CALL_ELF) || _CALL_ELF != 2
 	/* Skip over any initial dot */
tools/perf/util/symbol.c +31 -12

83 lines not on this page · raw message

tools/perf/util/symbol.h +13 -1
index 46b1649c64fc..b9fa722a9a14 100644
@@ -299,10 +299,22 @@ const char *arch__normalize_symbol_name(const char *name);
 #define SYMBOL_A 0
 #define SYMBOL_B 1
 
+/* Attributes used to choose between symbols that share a start address. */
+struct symbol_candidate {
+	u64		size;
+	const char	*name;
+	u8		type;
+	u8		binding;
+};
+
+int symbol__choose_best(const struct symbol_candidate *a,
+			const struct symbol_candidate *b);
+
 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);
+int arch__choose_best_symbol(const struct symbol_candidate *a,
+			     const struct symbol_candidate *b);
 
 enum symbol_tag_include {
 	SYMBOL_TAG_INCLUDE__NONE = 0,
Signature · 1 line
Git-157)
#6 lore raw

Re: [PATCH v3 3/6] perf symbols: Factor out duplicate symbol selection

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 7 lines

From: Alireza Haghdoost <[email protected]>

symbols__fixup_duplicate() chooses between symbols with the same start address through choose_best_symbol(), which needs fully constructed struct symbol objects. A loader that selects among aliases before allocating symbols cannot use it.

Quoted 7 lines

Move the policy into symbol__choose_best(), which compares the size, name, type and binding of two candidates described by struct symbol_candidate, and pass the same description to the arch__choose_best_symbol() hook. choose_best_symbol() becomes a wrapper that describes two struct symbols. No functional change intended.

Sashiko has reviewed this patch and found no issues. It looks great!

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

Re: [PATCH v3 3/6] perf symbols: Factor out duplicate symbol selection

In reply to Alireza Haghdoost
Quoted 144 lines · On Fri, Sep 25, 2026 at 12:15 PM Alireza Haghdoost via B4 Relay…

From: Alireza Haghdoost <[email protected]>

symbols__fixup_duplicate() chooses between symbols with the same start address through choose_best_symbol(), which needs fully constructed struct symbol objects. A loader that selects among aliases before allocating symbols cannot use it.

Move the policy into symbol__choose_best(), which compares the size, name, type and binding of two candidates described by struct symbol_candidate, and pass the same description to the arch__choose_best_symbol() hook. choose_best_symbol() becomes a wrapper that describes two struct symbols. No functional change intended.

---
 tools/perf/arch/powerpc/util/sym-handling.c |  6 ++--
 tools/perf/util/symbol.c                    | 43 +++++++++++++++++++++--------
 tools/perf/util/symbol.h                    | 14 +++++++++-
 3 files changed, 47 insertions(+), 16 deletions(-)
tools/perf/arch/powerpc/util/sym-handling.c +3 -3
index 947bfad7aa59..c263cbfefba5 100644
@@ -10,10 +10,10 @@
 #include "probe-event.h"
 #include "probe-file.h"
 
-int arch__choose_best_symbol(struct symbol *syma,
-                            struct symbol *symb __maybe_unused)
+int arch__choose_best_symbol(const struct symbol_candidate *syma,
+                            const struct symbol_candidate *symb __maybe_unused)
 {
-       char *sym = syma->name;
+       const char *sym = syma->name;
 
 #if !defined(_CALL_ELF) || _CALL_ELF != 2
        /* Skip over any initial dot */
tools/perf/util/symbol.c +31 -12
index 163652f071c6..4b50250d07fa 100644
@@ -145,8 +145,8 @@ int __weak arch__compare_symbol_names_n(const char *namea, const char *nameb,
        return strncmp(namea, nameb, n);
 }
 
-int __weak arch__choose_best_symbol(struct symbol *syma,
-                                   struct symbol *symb __maybe_unused)
+int __weak arch__choose_best_symbol(const struct symbol_candidate *syma,
+                                   const struct symbol_candidate *symb __maybe_unused)
 {
        /* Avoid "SyS" kernel syscall aliases */
        if (strlen(syma->name) >= 3 && !strncmp(syma->name, "SyS", 3))
@@ -157,38 +157,39 @@ int __weak arch__choose_best_symbol(struct symbol *syma,
        return SYMBOL_A;
 }
 
-static int choose_best_symbol(struct symbol *syma, struct symbol *symb)
+int symbol__choose_best(const struct symbol_candidate *syma,
+                       const struct symbol_candidate *symb)
 {
        s64 a;
        s64 b;
        size_t na, nb;
 
        /* Prefer a symbol with non zero length */
-       a = syma->end - syma->start;
-       b = symb->end - symb->start;
+       a = syma->size;
+       b = symb->size;
        if ((b == 0) && (a > 0))
                return SYMBOL_A;
        else if ((a == 0) && (b > 0))
                return SYMBOL_B;
 
-       if (symbol__type(syma) != symbol__type(symb)) {
-               if (symbol__type(syma) == STT_NOTYPE)
+       if (syma->type != symb->type) {
+               if (syma->type == STT_NOTYPE)
                        return SYMBOL_B;
-               if (symbol__type(symb) == STT_NOTYPE)
+               if (symb->type == STT_NOTYPE)
                        return SYMBOL_A;
        }
 
        /* Prefer a non weak symbol over a weak one */
-       a = symbol__binding(syma) == STB_WEAK;
-       b = symbol__binding(symb) == STB_WEAK;
+       a = syma->binding == STB_WEAK;
+       b = symb->binding == STB_WEAK;
        if (b && !a)
                return SYMBOL_A;
        if (a && !b)
                return SYMBOL_B;
 
        /* Prefer a global symbol over a non global one */
-       a = symbol__binding(syma) == STB_GLOBAL;
-       b = symbol__binding(symb) == STB_GLOBAL;
+       a = syma->binding == STB_GLOBAL;
+       b = symb->binding == STB_GLOBAL;
        if (a && !b)
                return SYMBOL_A;
        if (b && !a)
@@ -213,6 +214,24 @@ static int choose_best_symbol(struct symbol *syma, struct symbol *symb)
        return arch__choose_best_symbol(syma, symb);
 }
 
+static int choose_best_symbol(struct symbol *syma, struct symbol *symb)
+{
+       struct symbol_candidate a = {
+               .size = syma->end - syma->start,
+               .name = syma->name,
+               .type = symbol__type(syma),
+               .binding = symbol__binding(syma),
+       };
+       struct symbol_candidate b = {
+               .size = symb->end - symb->start,
+               .name = symb->name,
+               .type = symbol__type(symb),
+               .binding = symbol__binding(symb),
+       };
+
+       return symbol__choose_best(&a, &b);
+}
+
 void symbols__fixup_duplicate(struct rb_root_cached *symbols)
 {
        struct rb_node *nd;
tools/perf/util/symbol.h +7 -0
index 46b1649c64fc..b9fa722a9a14 100644
@@ -299,10 +299,22 @@ const char *arch__normalize_symbol_name(const char *name);
 #define SYMBOL_A 0
 #define SYMBOL_B 1
 
+/* Attributes used to choose between symbols that share a start address. */
+struct symbol_candidate {
+       u64             size;
+       const char      *name;
+       u8              type;
+       u8              binding;
+};

tools/perf/util/symbol.h const char *arch__normalize_symbol_name(const char *name); · line 317

Quoted 10 lines
tools/perf/util/symbol.h +6 -1
+
+int symbol__choose_best(const struct symbol_candidate *a,
+                       const struct symbol_candidate *b);
+
 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);
+int arch__choose_best_symbol(const struct symbol_candidate *a,
+                            const struct symbol_candidate *b);

Given you can change this function definition and only change 1 C file, is there any reason not to make the function static in symbol.c and move the struct symbol_candidate definition also to symbol.c?

Thanks,
Ian

Quoted 8 lines
tools/perf/util/symbol.h +0 -1
 enum symbol_tag_include {
        SYMBOL_TAG_INCLUDE__NONE = 0,
 
--

Git-157)

#8 lore raw

Re: [PATCH v3 3/6] perf symbols: Factor out duplicate symbol selection

Quoted 8 lines

tools/perf/util/symbol.h const char *arch__normalize_symbol_name(const char *name); · line 317

Quoted 3 lines
tools/perf/util/symbol.h +2 -1
-int arch__choose_best_symbol(struct symbol *syma, struct symbol *symb);
+int arch__choose_best_symbol(const struct symbol_candidate *a,
+                            const struct symbol_candidate *b);

Given you can change this function definition and only change 1 C file, is there any reason not to make the function static in symbol.c and move the struct symbol_candidate definition also to symbol.c?

Thanks for the review. Patch 5 calls symbol__choose_best() from symbol-elf.c: the lazy index resolves same-address duplicates from its index entries, not from struct symbols, and uses the same policy as the eager loader. That's why patch 3 makes it non-static.

struct symbol_candidate has to stay in symbol.h as well, because arch__choose_best_symbol() takes it and powerpc overrides that weak function in arch/powerpc/util/sym-handling.c.

I can say this in the patch 3 commit message in v4.

Thanks,
Alireza

reviewer
#9 lore raw

Re: [PATCH v3 3/6] perf symbols: Factor out duplicate symbol selection

Quoted 15 lines · Alireza Haghdoost
Quoted 9 lines

tools/perf/util/symbol.h const char *arch__normalize_symbol_name(const char *name); · line 317

Quoted 4 lines
tools/perf/util/symbol.h +2 -1
-int arch__choose_best_symbol(struct symbol *syma, struct symbol *symb);
+int arch__choose_best_symbol(const struct symbol_candidate *a,
+                            const struct symbol_candidate *b);

Given you can change this function definition and only change 1 C file, is there any reason not to make the function static in symbol.c and move the struct symbol_candidate definition also to symbol.c?

Thanks for the review. Patch 5 calls symbol__choose_best() from symbol-elf.c: the lazy index resolves same-address duplicates from its index entries, not from struct symbols, and uses the same policy as the eager loader. That's why patch 3 makes it non-static.

Quoted 5 lines

struct symbol_candidate has to stay in symbol.h as well, because arch__choose_best_symbol() takes it and powerpc overrides that weak function in arch/powerpc/util/sym-handling.c.

I can say this in the patch 3 commit message in v4.

Thanks, I saw this when I got to the later patches, sorry for the noise.

Ian

Quoted 2 lines

Thanks,
Alireza

#10 lore raw

PATCH v3 4/6 perf script: Add --max-symbol-bytes to bound ELF symbol memory

In reply to Alireza Haghdoost

perf script eagerly materializes every ELF symbol into an rb-tree kept until process exit. Large profiles can therefore consume substantial anonymous memory, causing perf script to be OOM-killed or forcing the kernel to reclaim memory from co-located workloads.

This patch adds --max-symbol-bytes to bound struct symbol allocations. Once the budget is reached, the ELF loader stops loading symbols, warns once, and lets unresolved addresses appear as [unknown]. This allows users to bound the memory footprint upfront and explicitly choose between complete symbolization and avoiding unbounded host memory pressure. perf record already provides a similar --max-size option to bound disk usage.

The counter includes every symbol__new() allocation, but this patch enforces the limit only in the ELF loader, which is the source of the unbounded memory growth addressed here. In this path, reaching the limit can safely produce [unknown] symbols. Other loaders currently treat a failed symbol allocation as an error. Capping those paths would therefore require separate changes whose complexity may outweigh the potential memory savings.

The cap applies to userspace DSOs, vmlinux-as-ELF, and kernel modules. Sizes require a B/K/M/G suffix, except that a bare 0 and the default mean unlimited. Reservations are atomic so concurrent loaders cannot exceed the limit, and partial zero-sized symbol ranges do not cover omitted addresses. Allocation and free both charge the stored u16 name length, so accounting stays balanced; names longer than U16_MAX are charged at the truncated length.

Document the option with the code that introduces it and add a concurrent-reservation test.

---
 tools/perf/Documentation/perf-script.txt | 10 ++++
 tools/perf/builtin-script.c              | 42 ++++++++++++++
 tools/perf/tests/Build                   |  1 +
 tools/perf/tests/builtin-test.c          |  1 +
 tools/perf/tests/symbol-bytes.c          | 94 ++++++++++++++++++++++++++++++++
 tools/perf/tests/tests.h                 |  1 +
 tools/perf/util/symbol-elf.c             | 66 ++++++++++++++++++----
 tools/perf/util/symbol.c                 | 91 +++++++++++++++++++++++++++++--
 tools/perf/util/symbol.h                 |  6 ++
 tools/perf/util/symbol_conf.h            |  1 +
 10 files changed, 299 insertions(+), 14 deletions(-)
tools/perf/Documentation/perf-script.txt +10 -0
index 200ea25891d8..217167a2e56b 100644
@@ -412,6 +412,16 @@ include::itrace.txt[]
 
         Default: 127
 
+--max-symbol-bytes::
+	Limit the bytes held in struct symbol allocations for DSOs on the
+	libelf symbol-loader path: userspace DSOs, vmlinux-as-ELF, and kernel
+	modules. This is not a cap on all symbol memory or RSS: symbols from
+	kallsyms, JIT maps, and libbfd are counted but not capped. Accepts a
+	size with a B/K/M/G suffix (e.g. 128M). When the budget is exceeded,
+	the ELF loader stops adding symbols; addresses not covered by symbols
+	already loaded are then printed as [unknown]. A warning is printed.
+	Default: 0 (unlimited).
+
 --ns::
 	Use 9 decimal places when displaying time (i.e. show the nanoseconds)
 
tools/perf/builtin-script.c +42 -0

60 lines not on this page · raw message

tools/perf/tests/Build +1 -0
index 81c311b131b7..fe92bfdea724 100644
@@ -67,6 +67,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-bytes.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 d2f594921e25..45482a7a91d2 100644
@@ -154,6 +154,7 @@ static struct test_suite *generic_tests[] = {
 	&suite__event_groups,
 	&suite__hybrid_merge,
 	&suite__symbols,
+	&suite__symbol_bytes,
 	&suite__util,
 	&suite__subcmd_help,
 	&suite__kallsyms_split,
tools/perf/tests/symbol-bytes.c new file +94 -0

94 lines not on this page · raw message

tools/perf/tests/tests.h +1 -0
index 9c96f33483d1..4a53e063e73d 100644
@@ -179,6 +179,7 @@ DECLARE_SUITE(sigtrap);
 DECLARE_SUITE(event_groups);
 DECLARE_SUITE(hybrid_merge);
 DECLARE_SUITE(symbols);
+DECLARE_SUITE(symbol_bytes);
 DECLARE_SUITE(util);
 DECLARE_SUITE(uncore_event_sorting);
 DECLARE_SUITE(subcmd_help);
tools/perf/util/symbol-elf.c +56 -10

128 lines not on this page · raw message

tools/perf/util/symbol.c +87 -4

114 lines not on this page · raw message

tools/perf/util/symbol.h +6 -0
index b9fa722a9a14..de4ac1c51732 100644
@@ -227,6 +227,12 @@ 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_bounded(u64 start, u64 len, u8 binding, u8 type,
+				  const char *name, bool *budget_exceeded);
+size_t symbol__bytes_used(void);
+void symbol__account_bytes(size_t bytes);
+bool symbol__try_account_bytes(size_t bytes);
+void symbol__unaccount_bytes(size_t bytes);
 size_t __symbol__fprintf_symname_offs(const struct symbol *sym,
 				      const struct addr_location *al,
 				      bool unknown_as_addr,
tools/perf/util/symbol_conf.h +1 -0
index 37d35f42dcc1..30cbc53cbcd0 100644
@@ -123,6 +123,7 @@ struct symbol_conf {
 	int		pad_output_len_dso;
 	int		group_sort_idx;
 	int		addr_range;
+	unsigned long	max_symbol_bytes;
 	DECLARE_BITMAP(parallelism_filter, MAX_NR_CPUS + 1);
 };
 
Signature · 1 line
Git-157)
#11 lore raw

Re: [PATCH v3 4/6] perf script: Add --max-symbol-bytes to bound ELF symbol memory

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] perf: missing <string.h> inclusion for string functions --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] perf: missing <string.h> inclusion for string functions
--

commit 79450839068bd1d9b33fd4d112e056707965c93e
Author: Alireza Haghdoost <[email protected]>

perf script: Add --max-symbol-bytes to bound ELF symbol memory

This commit adds a --max-symbol-bytes option to perf script to bound the memory footprint of struct symbol allocations on the ELF loader path. Once the budget is exceeded, it stops loading symbols and leaves unresolved addresses as [unknown].

Quoted 4 lines
tools/perf/builtin-script.c +0 -0
index 0174489d1c0fd..6c459ce6f433e 100644

[ ... ]

Quoted 7 lines
tools/perf/builtin-script.c +3 -0
@@ -4110,6 +4111,44 @@ static int parse_callret_trace(const struct option *opt __maybe_unused,
 	return 0;
 }
 
+static int parse_max_symbol_bytes(const struct option *opt,
+				  const char *str, int unset)
+{

[ ... ]

tools/perf/builtin-script.c static int parse_callret_trace(const struct option *opt __maybe_unused, · line 4140

Quoted 8 lines
tools/perf/builtin-script.c +8 -0
+	if (!strcmp(str, "0")) {
+		*max_bytes = 0;
+		return 0;
+	}
+
+	len = strlen(str);
+	if (len < 2 || !strchr("BKMG", str[len - 1]) ||
+	    strspn(str, "0123456789") != len - 1)

[Severity: Low]
Does this file need an explicit #include <string.h>?

The new parse_max_symbol_bytes() function relies on POSIX string functions (strcmp, strlen, strchr, strspn). To ensure build compatibility across standard C libraries like musl, standard header files should be explicitly included rather than relying on implicit inclusion from other headers.

Quoted 10 lines
tools/perf/builtin-script.c +10 -0
+		return -1;
+
+	bytes = parse_tag_value(str, size_tags);
+	if (bytes != (unsigned long)-1) {
+		*max_bytes = bytes;
+		return 0;
+	}
+
+	return -1;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#12 lore raw

PATCH v3 5/6 perf script: Add --lazy-load-symbols for lazy symbol loading

In reply to Alireza Haghdoost

perf script eagerly materializes eligible symbols from every DSO encountered in samples. On a production fixture, it loaded about 765k symbols to resolve about 45k distinct (DSO, symbol) frames, exceeding the memory available in a memory-constrained cgroup.

This patch adds --lazy-load-symbols for userspace ELF DSOs. It builds a compact sorted index, resolves sampled addresses by binary search, reads symbol names through a private data-source DSO, and caches resolved symbols in the existing rb-tree. The private DSO uses the normal DSO data cache, so the exact split-debuginfo source can be reopened after descriptor eviction. If the source cannot be read during preflight, perf discards the index and eagerly loads that DSO instead.

On the same fixture, peak RssAnon drops from 265 MiB to 39 MiB and wall time from 3.1 seconds to 1.85 seconds. Memory optimizations usually cost time; this one does not because lazy loading skips many unnecessary calloc() calls and demangling operations.

Lazy loading is most effective when samples reference only a small fraction of the available symbols, such as profiles spanning many large DSOs. It still builds an index proportional to the total symbol count. Eager loading remains available for dense symbol coverage or cases requiring its broader ELF and architecture support.

This does not claim full parity with the eager loader. Lazy loading supports the common userspace ELF symtab/dynsym case; .gnu_debugdata and PPC64 .opd continue through the eager loader.

Materialization is serialized with the DSO lock. Name lookups materialize the remaining index before constructing the name-sorted array. Lazy loading shares eager duplicate and IFUNC selection, and clips ranges that cross .plt before synthesizing PLT symbols.

In lazy mode, address lookups always take the DSO lock. Name lookups also free the index before the name-sorted array is built, even when the symbol budget stops materialization early, so a DSO with a name array never changes again. When no PT_LOAD covers a symbol, it falls back to the section header as the eager loader does, using the runtime section for NOBITS sections of a debuginfo file.

---
 tools/perf/Documentation/perf-script.txt |  16 +
 tools/perf/builtin-script.c              |   2 +
 tools/perf/util/dso.c                    |  17 +
 tools/perf/util/dso.h                    |  45 +++
 tools/perf/util/map.c                    |  19 +-
 tools/perf/util/symbol-elf.c             | 662 +++++++++++++++++++++++++++++++
 tools/perf/util/symbol-minimal.c         |  16 +
 tools/perf/util/symbol.c                 |   9 +
 tools/perf/util/symbol_conf.h            |   1 +
 9 files changed, 786 insertions(+), 1 deletion(-)
tools/perf/Documentation/perf-script.txt +16 -0
index 217167a2e56b..615c3ba1aab6 100644
@@ -412,6 +412,21 @@ include::itrace.txt[]
 
         Default: 127
 
+--lazy-load-symbols::
+	Resolve symbols lazily instead of eagerly loading the full
+	symbol table of every DSO that appears in a sample. A compact
+	sorted index is built per DSO and only the addresses that appear
+	in samples are materialized into symbols, with names read from the
+	file's string table through the DSO data cache at lookup time. This
+	sharply reduces memory (and usually time) for profiles of large
+	binaries where only a small fraction of the symbol table is
+	referenced. This applies only to userspace ELF DSOs; kernel DSOs and
+	modules always load eagerly. Operations that look up a symbol by name
+	materialize the remainder of that DSO's index first to preserve
+	name-lookup behavior.
+	Output may differ from the default loader for some targets
+	(e.g. PPC64 .opd or .gnu_debugdata). Default: off.
+
 --max-symbol-bytes::
 	Limit the bytes held in struct symbol allocations for DSOs on the
 	libelf symbol-loader path: userspace DSOs, vmlinux-as-ELF, and kernel
@@ -420,6 +435,7 @@ include::itrace.txt[]
 	size with a B/K/M/G suffix (e.g. 128M). When the budget is exceeded,
 	the ELF loader stops adding symbols; addresses not covered by symbols
 	already loaded are then printed as [unknown]. A warning is printed.
+	With --lazy-load-symbols, the lazy symbol index is also counted.
 	Default: 0 (unlimited).
 
 --ns::
tools/perf/builtin-script.c +2 -0
index 6c459ce6f433..f7b8b5f03ef4 100644
@@ -4252,6 +4252,8 @@ int cmd_script(int argc, const char **argv)
 	OPT_CALLBACK(0, "max-symbol-bytes", &symbol_conf.max_symbol_bytes,
 		     "size", "Limit bytes for ELF struct symbol (e.g. 128M; 0=unlimited)",
 		     parse_max_symbol_bytes),
+	OPT_BOOLEAN(0, "lazy-load-symbols", &symbol_conf.lazy_load_symbols,
+		    "Resolve symbols lazily instead of loading full symtabs"),
 	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/util/dso.c +17 -0
index c88b2a771832..9cbde0a7977e 100644
@@ -1704,6 +1704,20 @@ void dso__set_sorted_by_name(struct dso *dso)
 	RC_CHK_ACCESS(dso)->sorted_by_name = true;
 }
 
+void dso__free_ondemand(struct dso *dso)
+{
+	struct dso_ondemand *od = RC_CHK_ACCESS(dso)->ondemand;
+
+	if (!od)
+		return;
+	RC_CHK_ACCESS(dso)->ondemand = NULL;
+	free(od->sorted);
+	symbol__unaccount_bytes(od->nr_alloc * sizeof(*od->sorted));
+	dso__data_close(od->data_dso);
+	dso__put(od->data_dso);
+	free(od);
+}
+
 struct dso *dso__new_id(const char *name, const struct dso_id *id)
 {
 	RC_STRUCT(dso) *dso = zalloc(sizeof(*dso) + strlen(name) + 1);
@@ -1785,6 +1799,9 @@ void dso__delete(struct dso *dso)
 
 	dso__data_close(dso);
 	auxtrace_cache__free(RC_CHK_ACCESS(dso)->auxtrace_cache);
+	mutex_lock(dso__lock(dso));
+	dso__free_ondemand(dso);
+	mutex_unlock(dso__lock(dso));
 	dso_cache__free(dso);
 	zfree(&RC_CHK_ACCESS(dso)->data.path);
 	dso__free_a2l(dso);
tools/perf/util/dso.h +45 -0

69 lines not on this page · raw message

tools/perf/util/map.c +18 -1
index 41cdddc987ee..d0fff55eab92 100644
@@ -382,10 +382,27 @@ int map__load(struct map *map)
 
 struct symbol *map__find_symbol(struct map *map, u64 addr)
 {
+	struct dso *dso;
+	struct symbol *sym;
+
 	if (map__load(map) < 0)
 		return NULL;
 
-	return dso__find_symbol(map__dso(map), addr);
+	dso = map__dso(map);
+	if (!symbol_conf.lazy_load_symbols)
+		return dso__find_symbol(dso, addr);
+
+	/*
+	 * A lazily loaded DSO inserts symbols into its rb-tree on lookup and
+	 * drops its index once fully materialized. Look up and materialize
+	 * under the DSO lock so readers never race with either change.
+	 */
+	mutex_lock(dso__lock(dso));
+	sym = dso__find_symbol(dso, addr);
+	if (!sym)
+		sym = dso__find_symbol_ondemand(dso, addr);
+	mutex_unlock(dso__lock(dso));
+	return sym;
 }
 
 struct symbol *map__find_symbol_by_name_idx(struct map *map, const char *name, size_t *idx)
tools/perf/util/symbol-elf.c +662 -0

716 lines not on this page · raw message

tools/perf/util/symbol-minimal.c +16 -0
index 0a71d1463952..b932ced5f878 100644
@@ -373,6 +373,22 @@ void symbol__elf_init(void)
 {
 }
 
+struct symbol *dso__find_symbol_ondemand(struct dso *dso __maybe_unused,
+					 u64 addr __maybe_unused)
+{
+	return NULL;
+}
+
+struct symbol *dso__find_symbol_ondemand_exact(struct dso *dso __maybe_unused,
+					       u64 addr __maybe_unused)
+{
+	return NULL;
+}
+
+void dso__materialize_symbols_ondemand(struct dso *dso __maybe_unused)
+{
+}
+
 bool filename__has_section(const char *filename __maybe_unused, const char *sec __maybe_unused)
 {
 	return false;
tools/perf/util/symbol.c +9 -0
index cf92a7604a67..d234f7c29cb2 100644
@@ -773,6 +773,7 @@ void dso__sort_by_name(struct dso *dso)
 	if (!dso__sorted_by_name(dso)) {
 		size_t len = 0;
 
+		dso__materialize_symbols_ondemand(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);
@@ -2019,11 +2020,19 @@ int dso__load(struct dso *dso, struct map *map)
 		}
 
 #ifdef HAVE_LIBBFD_SUPPORT
+#ifdef HAVE_LIBELF_SUPPORT
+		if (is_reg && !symbol_conf.lazy_load_symbols)
+#else
 		if (is_reg)
+#endif
 			bfdrc = dso__load_bfd_symbols(dso, name);
 #endif
 		if (is_reg && bfdrc < 0)
 			sirc = symsrc__init(ss, dso, name, symtab_type);
+#if defined(HAVE_LIBBFD_SUPPORT) && defined(HAVE_LIBELF_SUPPORT)
+		if (is_reg && symbol_conf.lazy_load_symbols && sirc < 0)
+			bfdrc = dso__load_bfd_symbols(dso, name);
+#endif
 
 		if (nsexit)
 			nsinfo__mountns_enter(dso__nsinfo(dso), &nsc);
tools/perf/util/symbol_conf.h +1 -0
index 30cbc53cbcd0..763d158bc611 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)
#13 lore raw

Re: [PATCH v3 5/6] perf script: Add --lazy-load-symbols for lazy symbol loading

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] perf: heap buffer overflow in dso__build_ondemand_index via concurrent ELF modification --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] perf: heap buffer overflow in dso__build_ondemand_index via concurrent ELF modification --

commit d40c3742b741bb2166cbf2426b72bf61c6192a01
Author: Alireza Haghdoost <[email protected]>

perf script: Add --lazy-load-symbols for lazy symbol loading

This commit adds the --lazy-load-symbols option to perf script to lazily load eligible symbols from userspace ELF DSOs. It builds a compact sorted index per DSO, resolving sampled addresses via binary search and reading symbol names on demand to reduce memory and time overhead.

Quoted 3 lines
tools/perf/util/symbol-elf.c +0 -0

[ ... ]

Quoted 4 lines
tools/perf/util/symbol-elf.c +4 -0
+static int dso__build_ondemand_index(struct dso *dso, struct symsrc *syms_ss,
+				     struct symsrc *runtime_ss,
+				     int dynsym)
+{

[ ... ]

Quoted 13 lines
tools/perf/util/symbol-elf.c +13 -0
+	for (i = 0; i < nr_entries; i++) {
+		if (!gelf_getsym(syms, i, &sym))
+			continue;
+		if (ondemand_sym_ok(elf, secstrs, &sym, shdr.sh_link,
+				    ehdr.e_machine))
+			count++;
+	}
+
+	if (!count)
+		return 0;
+	if (check_mul_overflow((size_t)count, sizeof(*od->sorted),
+			       &index_bytes))
+		return -EOVERFLOW;

[ ... ]

Quoted 25 lines
tools/perf/util/symbol-elf.c +25 -0
+	od->sorted = zalloc(index_bytes);
+	if (!od->sorted) {
+		symbol__unaccount_bytes(index_bytes);
+		free(od);
+		return -1;
+	}
+	od->nr_alloc = count;
+	name_offsets = malloc(count * sizeof(*name_offsets));
+	if (!name_offsets) {
+		symbol__unaccount_bytes(index_bytes);
+		free(od->sorted);
+		free(od);
+		return -1;
+	}
+
+	j = 0;
+	for (i = 0; i < nr_entries; i++) {
+		u64 adjusted;
+		GElf_Phdr phdr;
+
+		if (!gelf_getsym(syms, i, &sym))
+			continue;
+		if (!ondemand_sym_ok(elf, secstrs, &sym, shdr.sh_link,
+				     ehdr.e_machine))
+			continue;

[ ... ]

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

Quoted 8 lines
tools/perf/util/symbol-elf.c +8 -0
+		od->sorted[j].start = adjusted;
+		od->sorted[j].end = sym.st_size;
+		name_offsets[j] = sym.st_name;
+		od->sorted[j].name_off = j;
+		od->sorted[j].binding = GELF_ST_BIND(sym.st_info);
+		od->sorted[j].type = GELF_ST_TYPE(sym.st_info);
+		j++;
+	}

[Severity: High]
Does this code have a bounds checking issue if the ELF file is modified concurrently?

The algorithm in dso__build_ondemand_index() performs a two-pass scan on the ELF file mapped into memory by libelf. The first pass computes the count of valid symbols and allocates the od->sorted and name_offsets arrays based on that exact count.

If the underlying ELF file (e.g. symbol table or string table) is modified while this process is running, the memory-mapped data can change between the two passes. This could cause the second pass to encounter more valid symbols than originally counted, resulting in j exceeding count (or od->nr_alloc) without any bounds checking.

Could this result in a heap buffer overflow when writing to od->sorted[j] and name_offsets[j] if an administrator analyzes a dynamically modified, user-writable ELF binary?

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

PATCH v3 6/6 perf test: Test lazy symbol loading and symbol memory limits

In reply to Alireza Haghdoost

Add a perf script shell test for --lazy-load-symbols and --max-symbol-bytes.

Record a small callchain fixture, require evidence that the controlled perf DSO built an on-demand index, and compare only extracted occurrences of the controlled test_loop symbol. This avoids coupling the test to addresses, diagnostics, or architecture-specific symbols for which the eager and lazy loaders have documented differences.

Derive the constrained lazy budget from the unlimited run's index-reservation peak. This gives a deterministic boundary where the index fits and later materialization reaches the limit. Also verify eager limiting, malformed size rejection, and one-time warning behavior.

Report unsupported recording, missing controlled output, unavailable libelf, and unavailable dependent data as skips without replacing a prior failure. Keep helper returns safe under set -e, and cover skip-status preservation separately.

Add unit tests for the shared duplicate-selection policy, truncated string-table reads, lazy address and name lookup across a closed data descriptor, and address lookups racing name lookups while the symbol budget truncates materialization. The last test also checks that a DSO does not change once its name-sorted array has been built.

Add a unit test that loads a DSO (perf itself, or the one given with --dso) eagerly and lazily and compares every symbol address and name. Run it from a shell test on a hand-built 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.

---
 .../tests/shell/lazy_load_symbols_split_debug.sh   | 113 +++++
 tools/perf/tests/shell/script_lazy_load_symbols.sh | 278 ++++++++++++
 .../tests/shell/script_lazy_load_symbols_skip.sh   |  26 ++
 tools/perf/tests/symbol-bytes.c                    | 505 +++++++++++++++++++++
 4 files changed, 922 insertions(+)
tools/perf/tests/shell/lazy_load_symbols_split_debug.sh new file +113 -0
new file mode 100755
index 000000000000..4e6335d88377
@@ -0,0 +1,113 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+# lazy symbol loading with split debuginfo
+
+# Build a stripped binary whose symbols live in a --only-keep-debug file,
+# where a function's section is NOBITS (with a different sh_offset) and has
+# no PT_LOAD in the runtime ELF. Lazy and eager loading must then both fall
+# back to the runtime section header and agree on the symbol addresses.
+
+set -e
+
+err=0
+tmpdir=$(mktemp -d /tmp/__perf_test.lazy_split_debug.XXXXX)
+
+cleanup() {
+	rm -rf "${tmpdir}"
+	trap - EXIT TERM INT
+}
+
+trap_cleanup() {
+	echo "Unexpected signal in ${FUNCNAME[1]}"
+	cleanup
+	exit 1
+}
+trap trap_cleanup EXIT TERM INT
+
+skip() {
+	echo "Lazy-load split debuginfo [Skipped: $1]"
+	cleanup
+	exit 2
+}
+
+if ! perf check feature -q libelf; then
+	skip "no libelf support"
+fi
+
+for tool in cc objcopy strip readelf dd; do
+	if ! command -v "${tool}" > /dev/null; then
+		skip "${tool} not found"
+	fi
+done
+
+cat > "${tmpdir}/prog.c" << EOF
+__attribute__((section("splittext"), noinline, used))
+int split_func(int x)
+{
+	return x * 3 + 1;
+}
+
+int main(int argc, char **argv)
+{
+	(void)argv;
+	return split_func(argc);
+}
+EOF
+
+prog="${tmpdir}/prog"
+if ! cc -O1 -g -o "${prog}" "${tmpdir}/prog.c" \
+	-Wl,--section-start=splittext=0x800000 2> /dev/null; then
+	skip "cannot build test program"
+fi
+objcopy --only-keep-debug "${prog}" "${prog}.debug"
+strip -s "${prog}"
+objcopy --add-gnu-debuglink="${prog}.debug" "${prog}"
+
+# The debug file must keep splittext as NOBITS at a stale offset.
+debug_sec=$(readelf -SW "${prog}.debug" | grep ' splittext ' || true)
+run_sec=$(readelf -SW "${prog}" | grep ' splittext ' || true)
+if ! echo "${debug_sec}" | grep -q NOBITS; then
+	skip "splittext is not NOBITS in the debug file"
+fi
+debug_off=$(echo "${debug_sec}" | sed 's/.*splittext *//' | awk '{print $3}')
+run_off=$(echo "${run_sec}" | sed 's/.*splittext *//' | awk '{print $3}')
+if [ -z "${run_off}" ] || [ "${debug_off}" = "${run_off}" ]; then
+	skip "splittext offsets do not differ"
+fi
+
+# Drop the PT_LOAD covering splittext so program header lookup fails.
+phoff=$(readelf -hW "${prog}" | awk '/Start of program headers/ {print $5}')
+phentsize=$(readelf -hW "${prog}" | awk '/Size of program headers/ {print $5}')
+idx=$(readelf -lW "${prog}" | awk '
+	/^Program Headers:/ { in_ph = 1; next }
+	in_ph && /^  Type/ { next }
+	in_ph && /^ *$/ { exit }
+	in_ph && /^  [A-Z]/ {
+		if ($1 == "LOAD" && $3 ~ /^0x0*800000$/) { print n; exit }
+		n++
+	}')
+if [ -z "${phoff}" ] || [ -z "${phentsize}" ] || [ -z "${idx}" ]; then
+	skip "no PT_LOAD for splittext"
+fi
+dd if=/dev/zero of="${prog}" bs=1 seek=$((phoff + idx * phentsize)) count=4 \
+	conv=notrunc 2> /dev/null
+if readelf -lW "${prog}" 2> /dev/null | grep -q 'LOAD .*0x0*800000 '; then
+	echo "Lazy-load split debuginfo [Failed to drop PT_LOAD]"
+	err=1
+fi
+
+if [ "${err}" -eq 0 ]; then
+	export PERF_BUILDID_DIR="${tmpdir}/buildid"
+	if ! perf test --dso "${prog}" "Lazy and eager symbol parity" 2>&1 | \
+		grep -q ': Ok$'; then
+		perf test --dso "${prog}" -vv "Lazy and eager symbol parity" 2>&1 | \
+			grep -E 'symbols$|mismatch|no symbols|no lazy' || true
+		echo "Lazy-load split debuginfo [Failed parity]"
+		err=1
+	else
+		echo "Lazy-load split debuginfo [Success]"
+	fi
+fi
+
+cleanup
+exit ${err}
tools/perf/tests/shell/script_lazy_load_symbols.sh new file +278 -0

278 lines not on this page · raw message

tools/perf/tests/shell/script_lazy_load_symbols_skip.sh new file +26 -0
new file mode 100755
index 000000000000..136503863fdd
@@ -0,0 +1,26 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+# perf script lazy symbol loading skip status
+
+set -e
+
+shelldir=$(dirname "$0")
+PERF_LAZY_LOAD_SYMBOLS_TEST_HELPERS=1
+. "${shelldir}"/script_lazy_load_symbols.sh
+unset PERF_LAZY_LOAD_SYMBOLS_TEST_HELPERS
+
+err=0
+mark_skip
+if [ "${err}" -ne 2 ]; then
+	echo "Lazy-load skip status [Failed expected 2, got ${err}]"
+	exit 1
+fi
+
+err=1
+mark_skip
+if [ "${err}" -ne 1 ]; then
+	echo "Lazy-load skip status [Failed skip overwrote failure: ${err}]"
+	exit 1
+fi
+
+echo "Lazy-load skip status [Success]"
tools/perf/tests/symbol-bytes.c +505 -0

525 lines not on this page · raw message

Signature · 1 line
Git-157)
#15 lore raw

Re: [PATCH v3 6/6] perf test: Test lazy symbol loading and symbol memory limits

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 20 lines

From: Alireza Haghdoost <[email protected]>

Add a perf script shell test for --lazy-load-symbols and --max-symbol-bytes.

Record a small callchain fixture, require evidence that the controlled perf DSO built an on-demand index, and compare only extracted occurrences of the controlled test_loop symbol. This avoids coupling the test to addresses, diagnostics, or architecture-specific symbols for which the eager and lazy loaders have documented differences.

Derive the constrained lazy budget from the unlimited run's index-reservation peak. This gives a deterministic boundary where the index fits and later materialization reaches the limit. Also verify eager limiting, malformed size rejection, and one-time warning behavior. [ ... ]
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.

Quoted 1 line

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
reviewer
#16 lore raw
In reply to Alireza Haghdoost
Quoted 38 lines · On Fri, Sep 25, 2026 at 12:15 PM Alireza Haghdoost via B4 Relay…

perf script loads the entire ELF symbol table of every DSO that appears in a sample, allocating each symbol into an rb-tree held until process exit. Therefore, a large enough profile turns symbol loading into an OOM kill. This does not scale to profiling a large cgroup with many large binaries on a production system with limited free memory.

This series adds two independent, opt-in mechanisms, a leading regression fix, and two preparatory patches:

[1/6] 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.

[2/6] Let a DSO read its data from one explicit file through the DSO
data cache. This fixes the split-debuginfo case where offsets from the debuginfo file would be applied to the runtime image.

[3/6] Factor duplicate-symbol selection so it works on symbol
attributes rather than struct symbol. No functional change.

[4/6] --max-symbol-bytes <size>: a byte budget on struct symbol
allocations (and the lazy index) enforced at the ELF symbol loader, degrading to [unknown] with a warning past the cap. An unbounded profile doesn't just risk OOM-killing itself. It also forces memory pressure on the whole host, pushing the kernel to reclaim from co-located latency-sensitive processes. Capping it lets the user bound that footprint up front and choose the trade-off explicitly.

[5/6] --lazy-load-symbols: build a compact per-DSO sorted index and
resolve only the sampled addresses, reading names through the DSO data cache at lookup time. On the production fixture, peak RssAnon drops from 265 MiB to 39 MiB (6.8x) and wall time from 3.1 s to 1.85 s (1.7x). Memory optimizations usually cost time; this one does not because lazy loading skips a lot of calloc and demangle calls.

Quoted 5 lines

[6/6] Shell and unit tests for both options.

Lazy loading handles the common userspace ELF symtab/dynsym path. Eager loading remains available for dense coverage and for PPC64 .opd and .gnu_debugdata.

So currently we have a symbol as:

```
/**
 * A symtab entry. When allocated this may be preceded by an annotation (see
 * symbol__annotation) and/or a browser_index (see symbol__browser_index).
 */
struct symbol {
        struct rb_node  rb_node;
        /** Range of symbol [start, end). */
        u64             start;
        u64             end;
        /** Length of the string name. */
        u16             namelen;
        _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[];
};
```
and the struct rb_node is a significant size cost:
```
struct rb_node {
        unsigned long  __rb_parent_color;
        struct rb_node *rb_right;
        struct rb_node *rb_left;
} __attribute__((aligned(sizeof(long))));
```

A sorted array of symbols would only require 1 pointer per entry, saving 2 words. The array could reside in the "symbols" variable passed around something like this:

```
struct symbols {
        struct rw_semaphore lock;
        struct symbol **symbols;
        unsigned int cnt;
        unsigned int allocated;
        bool sorted;
};
```

This is basically what we do with struct dso and dsos. With a struct symbols we can add a lock and ensure operations are appropriately synchronized. On top of this we can build lazy symbol resolution. For the bounded memory size, I'd prefer something like a reference count in every symbol (which uses one word we previously saved). We can periodically scan the symbols array for symbols with a reference count of 1 and then lower that count, knowing it is safe to release the symbol's memory because no other thread is referencing it. This would avoid having symbols appear as "[unknown]". We should really have a similar scan of the dsos to free up their memory.

If we have a reference count then symbol__annotation and symbol__browser_index can reference a symbol rather than using container_of.

I think the patches 4 and 5 do the core work, but they introduce some warts that I wish didn't have to exist. How do you feel about reference counting? To avoid reference count leaks we adding a checking framework that is documented here:
https://perfwiki.github.io/main/reference-count-checking/

Thanks,
Ian

Quoted 79 lines

Changes in v3:

- Rebase onto current perf-tools-next.
- Pick up Namhyung's Reviewed-by for patch 1.
- Split the exact-path DSO data support into its own patch (2/6), with a DSO data test for reading and reopening through an explicit path.
- Move the duplicate-selection refactor into a preparatory patch (3/6) and factor the whole lazy alias-group handling (traversal, demangling, IFUNC propagation, compaction) into one helper.
- Keep struct symbol::namelen as u16. Charge symbol bytes from the stored namelen on both allocation and free, and drop the 64 KiB-name test.
- Fix lazy-loading races reported by Sashiko: in lazy mode, address lookups always take the DSO lock, and building the name-sorted array materializes and frees the lazy index even when the budget truncates it, so the name array is never invalidated. dso__reset_symbol_names() is gone. Add a concurrent budget-truncation test.
- In lazy mode, when no PT_LOAD covers a symbol and its section is NOBITS in the debuginfo file, adjust with the runtime section header as eager loading does. Add a lazy/eager symbol parity test and a split-debuginfo shell test that exercises this path.
- Keep each unit test with the code it needs (DSO data in 2/6, budget reservation in 4/6); the other tests stay in 6/6.

Changes in v2:

- Replace direct pread() name reads with the exact symbol source's DSO data cache, preserving split-debuginfo offsets and descriptor reopen behavior.
- Drop the byte-identical-output claim and retain eager loading for PPC64 .opd and .gnu_debugdata.
- Make the symbol budget atomic and strict, account complete name lengths, accept a bare 0 as unlimited, and keep partial zero-sized ranges from covering omitted symbols.
- Align lazy lookup with eager duplicate and IFUNC selection, PLT clipping, and name-sorted materialization.
- Move option documentation into the feature patches. Add unit and shell coverage for cache reopen, truncated names, budget truncation, and skip handling.

---
Alireza Haghdoost (6):
perf symbols: Fix broken ELF_C_READ_MMAP fallback guard perf dso: Allow reading DSO data from an explicit file perf symbols: Factor out duplicate symbol selection perf script: Add --max-symbol-bytes to bound ELF symbol memory perf script: Add --lazy-load-symbols for lazy symbol loading perf test: Test lazy symbol loading and symbol memory limits

 tools/perf/Documentation/perf-script.txt           |  26 +
 tools/perf/arch/powerpc/util/sym-handling.c        |   6 +-
 tools/perf/builtin-script.c                        |  44 ++
 tools/perf/tests/Build                             |   1 +
 tools/perf/tests/builtin-test.c                    |   1 +
 tools/perf/tests/dso-data.c                        |  42 ++
 .../tests/shell/lazy_load_symbols_split_debug.sh   | 113 ++++
 tools/perf/tests/shell/script_lazy_load_symbols.sh | 278 ++++++++
 .../tests/shell/script_lazy_load_symbols_skip.sh   |  26 +
 tools/perf/tests/symbol-bytes.c                    | 599 +++++++++++++++++
 tools/perf/tests/tests.h                           |   1 +
 tools/perf/util/dso.c                              |  60 +-
 tools/perf/util/dso.h                              |  47 ++
 tools/perf/util/map.c                              |  19 +-
 tools/perf/util/symbol-elf.c                       | 728 ++++++++++++++++++++-
 tools/perf/util/symbol-minimal.c                   |  16 +
 tools/perf/util/symbol.c                           | 143 +++-
 tools/perf/util/symbol.h                           |  30 +-
 tools/perf/util/symbol_conf.h                      |   2 +
 19 files changed, 2133 insertions(+), 49 deletions(-)

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

Best regards,
--
Alireza Haghdoost <[email protected]>

#17 lore raw
Quoted 42 lines

So currently we have a symbol as:

```
/**
 * A symtab entry. When allocated this may be preceded by an annotation (see
 * symbol__annotation) and/or a browser_index (see symbol__browser_index).
 */
struct symbol {
        struct rb_node  rb_node;
        /** Range of symbol [start, end). */
        u64             start;
        u64             end;
        /** Length of the string name. */
        u16             namelen;
        _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[];
};
```
and the struct rb_node is a significant size cost:
```
struct rb_node {
        unsigned long  __rb_parent_color;
        struct rb_node *rb_right;
        struct rb_node *rb_left;
} __attribute__((aligned(sizeof(long))));
```

A sorted array of symbols would only require 1 pointer per entry, saving 2 words. The array could reside in the "symbols" variable passed around something like this:

```
struct symbols {
        struct rw_semaphore lock;
        struct symbol **symbols;
        unsigned int cnt;
        unsigned int allocated;
        bool sorted;
};
```
Quoted 4 lines

This is basically what we do with struct dso and dsos. With a struct symbols we can add a lock and ensure operations are appropriately synchronized. On top of this we can build lazy symbol resolution.

I agree that a sorted struct symbols array with its own lock would be a cleaner container than the rb-tree. However, it would not save much memory on its own. On a sample fixture, perf script materializes about 765k symbols and peaks at 265 MiB RssAnon. Replacing the rb_node with one pointer per symbol saves 16 bytes each, about 12 MiB in total. Most of the memory goes to materializing symbols that are never sampled. Lazy loading avoids that work and brings the peak down to 39 MiB. Lazily materialized symbols are inserted one at a time between lookups, which suits a tree better than a sorted array.

If the maintainers prefer the sorted array, I'm open to it, but I'd like to be clear about the cost. The symbol rb-tree is used at around 100 call sites in 18 files under tools/perf, so the conversion would be a separate series that has to land first. It should also cover both eager and lazy loading, so there is one container for materialized symbols rather than a tree in one mode and an array in the other.

Quoted 9 lines

...For
the bounded memory size, I'd prefer something like a reference count in every symbol (which uses one word we previously saved). We can periodically scan the symbols array for symbols with a reference count of 1 and then lower that count, knowing it is safe to release the symbol's memory because no other thread is referencing it. This would avoid having symbols appear as "[unknown]". We should really have a similar scan of the dsos to free up their memory.

Eviction would bound the steady state, but it doesn't bound the peak on its own. Eager loading materializes the whole symtab when the DSO is loaded, before anything can be evicted, and this series does not add lazy loading for every loader (PPC64 .opd, .gnu_debugdata, the kernel and modules still load eagerly). --max-symbol-bytes covers those paths too. It is opt-in and off by default, and is meant for hosts where perf shares memory with latency-sensitive services and the operator needs a guaranteed upper bound. Like perf record --max-size, what happens past the cap is deterministic: perf warns and reports [unknown].

Quoted 6 lines

I think the patches 4 and 5 do the core work, but they introduce some warts that I wish didn't have to exist. How do you feel about reference counting? To avoid reference count leaks we adding a checking framework that is documented here:
https://perfwiki.github.io/main/reference-count-checking/

Reference counting would be useful for symbol lifetime and for the annotation and browser_index cleanup, and freeing unreferenced symbols would reduce steady-state memory. As above, I see it as a complement to the cap rather than a replacement, since it can't guarantee an upper bound.

Refcounting struct symbol touches every holder of a symbol pointer, so I'd suggest doing it as a separate series using the refcount checking framework rather than in this series.

If there are specific parts of patches 4 and 5 you see as warts, please point me at them and I'll address them in v4.

For v4 I currently plan to bound the second pass of dso__build_ondemand_index() by the allocated count, as reported by Sashiko.

Thanks,
Alireza

reviewer
#18 lore raw
Quoted 103 lines · Alireza Haghdoost
Quoted 43 lines

So currently we have a symbol as:

```
/**
 * A symtab entry. When allocated this may be preceded by an annotation (see
 * symbol__annotation) and/or a browser_index (see symbol__browser_index).
 */
struct symbol {
        struct rb_node  rb_node;
        /** Range of symbol [start, end). */
        u64             start;
        u64             end;
        /** Length of the string name. */
        u16             namelen;
        _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[];
};
```
and the struct rb_node is a significant size cost:
```
struct rb_node {
        unsigned long  __rb_parent_color;
        struct rb_node *rb_right;
        struct rb_node *rb_left;
} __attribute__((aligned(sizeof(long))));
```

A sorted array of symbols would only require 1 pointer per entry, saving 2 words. The array could reside in the "symbols" variable passed around something like this:

```
struct symbols {
        struct rw_semaphore lock;
        struct symbol **symbols;
        unsigned int cnt;
        unsigned int allocated;
        bool sorted;
};
```
Quoted 4 lines

This is basically what we do with struct dso and dsos. With a struct symbols we can add a lock and ensure operations are appropriately synchronized. On top of this we can build lazy symbol resolution.

I agree that a sorted struct symbols array with its own lock would be a cleaner container than the rb-tree. However, it would not save much memory on its own. On a sample fixture, perf script materializes about 765k symbols and peaks at 265 MiB RssAnon. Replacing the rb_node with one pointer per symbol saves 16 bytes each, about 12 MiB in total. Most of the memory goes to materializing symbols that are never sampled. Lazy loading avoids that work and brings the peak down to 39 MiB. Lazily materialized symbols are inserted one at a time between lookups, which suits a tree better than a sorted array.

If the maintainers prefer the sorted array, I'm open to it, but I'd like to be clear about the cost. The symbol rb-tree is used at around 100 call sites in 18 files under tools/perf, so the conversion would be a separate series that has to land first. It should also cover both eager and lazy loading, so there is one container for materialized symbols rather than a tree in one mode and an array in the other.

Quoted 9 lines

...For
the bounded memory size, I'd prefer something like a reference count in every symbol (which uses one word we previously saved). We can periodically scan the symbols array for symbols with a reference count of 1 and then lower that count, knowing it is safe to release the symbol's memory because no other thread is referencing it. This would avoid having symbols appear as "[unknown]". We should really have a similar scan of the dsos to free up their memory.

Eviction would bound the steady state, but it doesn't bound the peak on its own. Eager loading materializes the whole symtab when the DSO is loaded, before anything can be evicted, and this series does not add lazy loading for every loader (PPC64 .opd, .gnu_debugdata, the kernel and modules still load eagerly). --max-symbol-bytes covers those paths too. It is opt-in and off by default, and is meant for hosts where perf shares memory with latency-sensitive services and the operator needs a guaranteed upper bound. Like perf record --max-size, what happens past the cap is deterministic: perf warns and reports [unknown].

Quoted 6 lines

I think the patches 4 and 5 do the core work, but they introduce some warts that I wish didn't have to exist. How do you feel about reference counting? To avoid reference count leaks we adding a checking framework that is documented here:
https://perfwiki.github.io/main/reference-count-checking/

Reference counting would be useful for symbol lifetime and for the annotation and browser_index cleanup, and freeing unreferenced symbols would reduce steady-state memory. As above, I see it as a complement to the cap rather than a replacement, since it can't guarantee an upper bound.

Refcounting struct symbol touches every holder of a symbol pointer, so I'd suggest doing it as a separate series using the refcount checking framework rather than in this series.

Quoted 6 lines

If there are specific parts of patches 4 and 5 you see as warts, please point me at them and I'll address them in v4.

For v4 I currently plan to bound the second pass of dso__build_ondemand_index() by the allocated count, as reported by Sashiko.

So, I'm pretty against the complexity of dealing with symbols that may fail due to a memory pressure issue. I'm also against having memory of symbols bound, while memory for say debuginfo isn't. Ideally we'd have a language runtime that'd allow us to express some notion of weakly holding symbols live. I think we can implement a global function to reduce the memory footprint by iterating through sessions, machines, dsos, and symbols, squeezing them when possible. The problem with implementing that on top of patches 4 and 5 is that it's hard to see what would be kept, so we'd just revert the changes and start implementing the reference counting solution again.

In the change there seems to be the addition of helper functions and structs like symbol_candidate. These appear in header files to be shared across C files. We have multiple notions of symbols, with and without libelf. I'd rather the change were more minimal given I think this is the wrong direction.

Thanks,
Ian

Quoted 2 lines

Thanks,
Alireza

#19 lore raw
Quoted 3 lines · Ian Rogers

So, I'm pretty against the complexity of dealing with symbols that may fail due to a memory pressure issue.

Hi Ian,

That was aimed at --max-symbol-bytes. I'll drop it in v4.

Following the other thread [1], it looks like we agree that lazy loading is worth having on its own. Whether or not the reference-counting series lands, loading a name only when a sample needs it is a good change. As in the numbers I posted there, it cuts memory use substantially and makes perf script faster. I'll prepare v4 of this series without the cap:

1. the ELF_C_READ_MMAP fix
2. reading DSO data from the debug file the symbol table came from
3. the shared duplicate-symbol selection
4. --lazy-load-symbols
5. the lazy-loading tests

Patches 2 and 3 stay because lazy loading needs them, and Namhyung asked for them.

Namhyung, on that thread you suggested a limit that prints an offset when the name is not loaded. I said I could do that for the byte cap in v4. I'd rather land lazy loading first and add that limit later if there is a need or interest.

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

Thanks,
Alireza

reviewer
#20 lore raw
Quoted 27 lines · Alireza Haghdoost
Quoted 3 lines · Ian Rogers

So, I'm pretty against the complexity of dealing with symbols that may fail due to a memory pressure issue.

Hi Ian,

That was aimed at --max-symbol-bytes. I'll drop it in v4.

Following the other thread [1], it looks like we agree that lazy loading is worth having on its own. Whether or not the reference-counting series lands, loading a name only when a sample needs it is a good change. As in the numbers I posted there, it cuts memory use substantially and makes perf script faster. I'll prepare v4 of this series without the cap:

1. the ELF_C_READ_MMAP fix
2. reading DSO data from the debug file the symbol table came from
3. the shared duplicate-symbol selection
4. --lazy-load-symbols
5. the lazy-loading tests

Patches 2 and 3 stay because lazy loading needs them, and Namhyung asked for them.

Quoted 6 lines

Namhyung, on that thread you suggested a limit that prints an offset when the name is not loaded. I said I could do that for the byte cap in v4. I'd rather land lazy loading first and add that limit later if there is a need or interest.

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

I agree with what you are saying. Without --max-symbol-bytes, I think your series is good. I'm unsure about the symbol changes if we're not embedding the name anymore; it sounds complex and possibly brittle, but I got distracted by the max-symbol thing and lost focus on that part of the change. I am still working on a v2 patch series, but I'm using a slower but hopefully better AI agent. I've been unhappy with the shrinking then causing reloading, then causing shrinking and so-on, when running perf top. We should be able to do better. I've also added back into my series a patch I dropped a while ago where missing line maps could trigger useless execution of addr2line and a lot of wasted time:
https://lore.kernel.org/linux-perf-users/[email protected]/

If you post a v4 I'm happy to review it. You know where I'm coming from with reference counting and shrinking, so hopefully all the work can complement each other and reduce memory usage. Perhaps put the less controversial patches first so they can be merged and not get blocked by a discussion on a later patch.

Thanks,
Ian

Quoted 2 lines

Thanks,
Alireza