Skip to content

Fix wrong shared library symbol resolution in stack traces - #101435

Draft
azat wants to merge 21 commits into
ClickHouse:masterfrom
azat:fix-shared-library-symbol-resolution
Draft

azat wants to merge 21 commits into
ClickHouse:masterfrom
azat:fix-shared-library-symbol-resolution

Conversation

@azat

@azat azat commented Mar 31, 2026

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fix wrong shared library symbol resolution in stack traces

SymbolIndex stored all symbols from all loaded objects (main binary + shared libs) in a single flat vector sorted by file-relative offset (st_value). Different shared libraries have overlapping file offset ranges, so a binary search could return a symbol from the wrong library.

Fix by storing absolute virtual addresses (info->addr + st_value) instead of raw file offsets. This matches the approach already used on macOS (n_value + slide). For non-PIE builds info->addr is 0 for the main executable, so the change is a no-op for main binary symbols.

Consistently store virtual addresses in all consumers:

  • SymbolIndex: store info->addr + st_value in both collectSymbolsFromProgramHeaders and collectSymbolsFromELFSymbolTable
  • findSymbol: simplify to a direct lookup (no findObject + subtraction)
  • StackTrace: pass virtual_addr instead of physical_addr to findSymbol
  • StorageSystemStackTrace: store virtual addresses in the trace column (remove findObject + subtraction)
  • TraceCollector: remove address normalization (was subtracting address_begin, which breaks PIE builds where address_begin != 0)
  • addressToLine, TraceLog: convert virtual address to file offset before DWARF lookups (addr - address_begin), since DWARF uses file-relative addresses

Note, I've checked this and it looks valid I also manually tested it and it looks ok:

@clickhouse-gh

clickhouse-gh Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4c687c6]

Summary: ❌

job_name test_name status info comment
Docs check (Mintlify) FAIL
No direct edits to generated or read-only docs FAIL cidb
Fast test (arm_darwin) ERROR
Build (amd_darwin) ERROR
Build (arm_darwin) ERROR
Build (arm_v80compat) ERROR
Build (amd_freebsd) ERROR
Build (ppc64le) ERROR
Build (amd_compat) ERROR
Build (amd_musl) ERROR
Build (riscv64) ERROR

AI Review

Summary

This PR fixes the live shared-library symbol lookup by switching SymbolIndex and the profiler consumers to absolute virtual addresses and by resolving DWARF against the containing object instead of always the main binary. The runtime fix looks directionally correct, but I still see one unresolved persisted-format problem on PIE builds, the new shared-library file:line path still lacks focused regression coverage, and one trace_log contract string is now stale.

PR Metadata
  • Changelog category should be Bug Fix, not Improvement: this change corrects wrong symbol and source-line resolution rather than adding new behavior.
  • Changelog entry is required for either category, and the current entry is specific and user-readable.
  • Exact replacement:
### Changelog category (leave one):
- Bug Fix
Findings

⚠️ Majors

  • src/Interpreters/TraceCollector.cpp:165 The durable system.trace_log.trace encoding is still not stable on PIE builds. New rows now store raw virtual addresses that stop symbolizing after restart, and the consumers no longer accept the previous main-binary file-offset encoding, so older PIE rows also stop round-tripping through addressToSymbol, addressToLine, and flameGraph after upgrade. The existing review thread on this design tradeoff should stay open until the table stores object identity plus file-relative offset, or the readers keep a compatibility path for old rows.
  • src/Common/tests/gtest_symbol_index.cpp:26 The new regression test only proves findSymbol on a shared-library address. The actual line-resolution fix in addressToLine / system.trace_log.lines still has no focused automated coverage, so that path could regress while this test keeps passing.
  • src/Interpreters/TraceLog.cpp:112 system.trace_log.lines now resolves shared-library frames too, but the source column description and the manual trace_log docs still say ELF source locations are only available for main-binary frames. That leaves system.columns.comment and the docs advertising weaker behavior than the code now implements.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Mar 31, 2026
@azat
azat marked this pull request as draft April 1, 2026 06:52
`SymbolIndex` stored all symbols from all loaded objects (main binary +
shared libs) in a single flat vector sorted by file-relative offset
(`st_value`). Different shared libraries have overlapping file offset
ranges, so a binary search could return a symbol from the wrong library.

Fix by storing absolute virtual addresses (`info->addr + st_value`)
instead of raw file offsets. This matches the approach already used on
macOS (`n_value + slide`). For non-PIE builds `info->addr` is 0 for the
main executable, so the change is a no-op for main binary symbols.

Consistently store virtual addresses in all consumers:
- `SymbolIndex`: store `info->addr + st_value` in both
  `collectSymbolsFromProgramHeaders` and `collectSymbolsFromELFSymbolTable`
- `findSymbol`: simplify to a direct lookup (no `findObject` + subtraction)
- `StackTrace`: pass `virtual_addr` instead of `physical_addr` to `findSymbol`
- `StorageSystemStackTrace`: store virtual addresses in the `trace` column
  (remove `findObject` + subtraction)
- `TraceCollector`: remove address normalization (was subtracting
  `address_begin`, which breaks PIE builds where `address_begin` != 0)
- `addressToLine`, `TraceLog`: convert virtual address to file offset
  before DWARF lookups (`addr - address_begin`), since DWARF uses
  file-relative addresses

v2: fix system.symbols.symbol_demangled
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@azat
azat force-pushed the fix-shared-library-symbol-resolution branch from 12c1975 to 1ded14c Compare April 1, 2026 09:12
@azat
azat marked this pull request as ready for review April 1, 2026 09:12
@azat

azat commented Apr 1, 2026 •

Copy link
Copy Markdown
Member Author

The problem with XRAY was that the symbols has relative offsets, fixed in the new patch version

@azat
azat marked this pull request as draft April 2, 2026 15:08
@azat

azat commented Apr 2, 2026

Copy link
Copy Markdown
Member Author

Actually now we have a virtual addresses in trace_log, and after restart they cannot be resolved anymore

@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged latest master into the branch (it was ~14k commits behind and red).

  • The merge is conflict-free; the net diff is unchanged (the same 8 source files).
  • The prior CI failures were all the flaky 03172_error_log_table_not_empty, which is unrelated to this change (this PR does not touch that test) and was fixed on master by e7449c8e5eb ("fix flaky 03172_error_log_table_not_empty"), now included via the merge. The Stress test (arm_msan) fix from Fix MSan use-of-uninitialized-value in SimSIMD SVE functions #101239 (merged) is also picked up, as requested.
  • Built clickhouse cleanly (0 errors) and empirically verified symbol resolution with a fresh server:
    • system.stack_trace → addressToSymbol/demangle resolves correct names across objects (e.g. libc __syscall_cancel_arch/start_thread mixed with DB::TCPHandler::run()).
    • addressToLine resolves correct src/...:line locations (DWARF file-relative conversion via addr - address_begin).
    • system.trace_log (query profiler / TraceCollector path) resolves correct names too.

Note for reviewers: this still leaves the open question you raised — with absolute virtual addresses stored in trace_log, entries collected before a server restart can no longer be symbolized (PIE/ASLR changes the base). That is a design tradeoff for @azat / maintainers to decide; I did not change the approach here.

#endif

trace.emplace_back(static_cast<UInt64>(addr) - offset);
trace.emplace_back(static_cast<UInt64>(addr));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This stores ASLR-dependent virtual addresses in durable system.trace_log.trace rows, but the row does not keep the load base needed to rebase them later. After a server restart, addressToSymbol, addressToLine, and flameGraph search the current process ranges, so rows collected before the restart can no longer symbolize even when build_id matches; before this change, main-binary frames were normalized to stable file-relative offsets.

Please keep a stable persisted representation for trace (for example, object identity plus file-relative offset, or at least the previous main-binary file offsets) or store enough load-base metadata to rebase old rows before symbolization.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a real trade-off worth a maintainer decision, so leaving it open for @azat / @al13n321 rather than resolving it here.

The concern is valid: storing absolute (ASLR-dependent) virtual addresses in the durable system.trace_log.trace means rows collected before a restart can no longer be symbolized after a PIE binary is reloaded at a different base, whereas the previous code normalized main-binary frames to stable file-relative offsets.

However, the previous representation was not stable/correct either: it only normalized main-binary frames and stored raw virtual addresses for shared-library frames, and — more importantly — file offsets overlap between objects, which is exactly the wrong-symbol bug this PR fixes. There is no single UInt64 representation that is both unambiguous across objects and stable across restarts.

A proper persisted fix would need object identity (e.g. build-id) plus a file-relative offset per frame, which is a larger trace_log schema change and out of scope for this PR. The live consumers (system.stack_trace, exception traces) are unaffected since they symbolize against the current process. Flagging for a decision on whether to accept the cross-restart limitation here or follow up with a schema change.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pushed 73a65a9163a taking the "explicitly document" path the bot offered as an alternative to a schema change, since the proper fix (object identity + file-relative offset per frame) is a trace_log schema change that is a maintainer call:

  • Added an explanatory comment in TraceCollector::run next to where the address is stored, spelling out that we now persist the absolute (ASLR-dependent) virtual address — unambiguous across objects (file offsets overlap between the main binary and shared libraries), which is the bug this PR fixes — and the trade-off that such rows symbolize only while the collecting process is alive and may not re-symbolize after a restart of a PIE binary.
  • Documented the same on the trace column in docs/en/operations/system-tables/trace_log.md.

The cross-object correctness fix is the point of this PR and the live consumers (system.stack_trace, exception traces, in-process system.trace_log symbolization) are unaffected. Leaving this thread open for @azat / @al13n321 to decide whether the cross-restart limitation is acceptable here or warrants the follow-up schema change.

Comment thread src/Functions/addressToLine.h Resolved
Comment thread src/Interpreters/TraceLog.cpp Resolved
After switching SymbolIndex to absolute virtual addresses, a trace frame may
belong to a shared library rather than the main binary. `addressToLine`,
`addressToLineWithInlines` and `TraceLog`'s line resolution still hardcoded
`thisObject()` (the main binary) for every DWARF lookup, so a `libc` frame
would be looked up in ClickHouse DWARF and return the ClickHouse binary path or
an empty result, even though `findSymbol` already resolved the correct symbol.

Use `findObject` to resolve the object that actually contains the address and
use that object's `elf`/`address_begin` (or `dsym`/`slide` on macOS). For
main-binary frames `findObject` returns the same object as `thisObject`, so
behavior is unchanged there.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Picked this up to move it forward (CI was green, branch ~719 commits behind master but no conflicts, so no re-merge needed).

Addressed two of the three review-bot threads (pushed 9215b8ffd54):

  • addressToLine.h and TraceLog.cpp line resolution still hardcoded thisObject() (the main binary) for every DWARF lookup. Now that SymbolIndex stores absolute virtual addresses and findSymbol resolves shared-library frames, these lookups have to use the containing object too — otherwise a libc frame symbolizes correctly but its line is queried against ClickHouse DWARF. Switched both to findObject(addr) and use that object's elf/address_begin (and dsym/slide on macOS). For main-binary frames findObject returns the same object as thisObject, so behavior is unchanged there.

Left the TraceCollector.cpp persistence thread open for a maintainer call — storing ASLR-dependent virtual addresses in the durable system.trace_log is a real trade-off (old rows can't symbolize across a restart) but the previous file-offset representation had the cross-object overlap bug this PR fixes, and a fully stable fix needs an object-identity + offset schema change. Details in the thread.

Verification (locally built clickhouse, fresh server):

  • 02420_stracktrace_debug_symbols — main-binary file:line:col resolves (Common/Exception.cpp:139:7: DB::Exception::Exception).
  • 02161_addressToLineWithInlines — matches reference (has inlines: 1) + FUNCTION_NOT_ALLOWED guard (code 446).
  • Shared-library resolution confirmed: start_thread / thread_start now resolve to the correct glibc symbol and addressToLine returns the glibc debug object path instead of the ClickHouse binary (this is the behavior the bot's addressToLine/TraceLog threads asked for).

Comment thread src/Common/SymbolIndex.cpp Resolved
Address review feedback on src/Common/SymbolIndex.cpp: add a focused unit
test that resolves a known address from a loaded shared library (the
runtime address of `getpid`, obtained via `dlsym` to avoid a main-binary
PLT stub) and verifies that `SymbolIndex::findSymbol` returns the symbol
that actually contains the address and starts exactly at the C library
symbol reported by `dladdr`.

This exercises the cross-object lookup path that the fix repairs: before
storing absolute virtual addresses, the file-relative offset ranges of
the main binary and shared libraries overlapped, so the lookup could
return a symbol from the wrong object. The test skips on fully static
builds (for example, musl) where the C library is part of the main
binary.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

This is very low priority - the only shared library we use is libc, and even that we will remove soon.

alexey-milovidov and others added 5 commits June 11, 2026 05:49
…log.trace

Switching `SymbolIndex` and its consumers to absolute virtual addresses fixes
wrong cross-object symbol resolution, but it also changes the durable
`system.trace_log.trace` representation: it now stores ASLR-dependent runtime
addresses instead of the previous main-binary file-offset normalization.

Document the trade-off explicitly (as raised in the review thread): such rows
symbolize correctly only while the collecting process is alive and may no longer
symbolize after a restart of a PIE binary. Add an explanatory comment in
`TraceCollector::run` and a note on the `trace` column in the system table docs.
A representation that is both unambiguous across objects and stable across
restarts would require object identity plus a file-relative offset (a
`trace_log` schema change), left as a follow-up for maintainers.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…description

The warning that `system.trace_log.trace` stores absolute (ASLR-dependent)
virtual addresses was added only to the autogenerated block of
`docs/en/operations/system-tables/trace_log.md`, while
`TraceLogElement::getColumnsDescription` still carried the old shorter `trace`
contract.

That block is regenerated from `system.columns` comments by
`utils/generate-system-tables-docs`, so the warning would be overwritten on the
next regeneration, and `system.columns.comment` for `trace` would keep exposing
the incomplete description.

Move the exact warning text into the `trace` column description in
`src/Interpreters/TraceLog.cpp` so the canonical source carries it. The text
matches the existing `.md` block byte-for-byte, so regenerating the docs leaves
the autogenerated block unchanged.

Addresses the AI review finding on `docs/en/operations/system-tables/trace_log.md:37`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Common/SymbolIndex.h Resolved
Comment thread src/Functions/addressToLine.h Resolved
alexey-milovidov and others added 3 commits June 29, 2026 13:42
After switching `SymbolIndex` to store absolute virtual addresses instead
of file-relative offsets, `system.symbols.address_begin`/`address_end`
expose those absolute addresses. Update the `StorageSystemSymbols` column
descriptions and the matching `docs/en/operations/system-tables/symbols.md`
to say so, and spell out that for position-independent (PIE) builds these
are ASLR-dependent runtime addresses (for the default non-PIE build they
still match the address in the binary).

Addresses the AI review finding on src/Common/SymbolIndex.h.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Now that `addressToLine`/`addressToLineWithInlines` resolve the object that
contains the address via `findObject`, the argument must be an absolute
virtual address from the running process (e.g. `system.trace_log.trace` or
`system.stack_trace`). Note in the function documentation that the numeric
addresses in the examples come from one specific build and will not match
the reader's binary, and that for position-independent (PIE) builds they are
ASLR-dependent and change between restarts.

Addresses the AI review finding on src/Functions/addressToLine.h.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Common/StackTrace.cpp Resolved
alexey-milovidov and others added 2 commits July 21, 2026 21:19
…solution

# Conflicts:
#	src/Interpreters/TraceLog.cpp
…races

The PR unified `SymbolIndex`, `findSymbol`, `addressToSymbol`,
`addressToLine`, `system.stack_trace.trace`, and `system.trace_log.trace`
on absolute virtual addresses, but `toStringEveryLineImpl` still rendered
the file-relative `physical_addr` after the `@` marker. On PIE and
shared-library frames that meant an address copied out of a text stack
trace no longer round-tripped through those introspection tools.

Print `frame.virtual_addr` instead so every surface exposes the same
address contract.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Common/StackTrace.cpp Resolved
# Conflicts:
#	docs/en/operations/system-tables/trace_log.md
#	src/Interpreters/TraceLog.cpp
Two findings on the previous commit, both about absolute (runtime) virtual
addresses reaching surfaces that are not explicitly introspective:

- `StackTrace::toString` is embedded in client-visible exception text and in
  the server log, so it goes back to printing the object-relative
  `physical_addr`. To keep such an address unambiguous (file offsets overlap
  between the main binary and shared libraries, which is the bug this pull
  request fixes), the object name is now printed for frames outside the main
  binary.
- `system.stack_trace.trace` now contains raw runtime addresses, while the
  table did not perform any introspection check, unlike `system.symbols`.
  Reading the `trace` column now requires `AccessType::INTROSPECTION`; the
  other columns are still available with a plain `SELECT` grant. Added
  `04653_system_stack_trace_trace_requires_introspection`.
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 122/130 (93.85%) · Uncovered code

Full report · Diff report

Resolved conflicts: master removed the legacy Docusaurus tree (docs/en), so the PR's updates to the `trace`, `address_begin`, and `address_end` column descriptions were ported to the new autogenerated blocks in docs/reference/system-tables/{stack_trace,symbols,trace_log}.mdx, byte-identical to the C++ column comments.
/// return a symbol from the wrong object. `SymbolIndex` now stores absolute virtual
/// addresses (`info->addr + st_value`), so a shared library address resolves to the
/// symbol that actually contains it.
TEST(SymbolIndex, ResolveSharedLibrarySymbol)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still only proves the findSymbol half of the change. The actual line-resolution fix was in addressToLine / TraceLog::lines, which stopped hardcoding thisObject() and now has to resolve the containing object's DWARF via findObject(addr).

Reverting those call sites back to the main-binary lookup would still leave this test green, so the shared-library file:line path has no focused regression coverage yet. Please add a test that runs a known shared-library address through addressToLine (or through system.trace_log.lines) and checks that we resolve the shared object's source path rather than the ClickHouse binary.

/// Resolve the object that actually contains the address. The trace stores absolute
/// virtual addresses, so a frame may belong to a shared library rather than the main
/// binary, and the DWARF lookup has to use that object's `elf`/`dsym` and load base.
const auto * object = symbol_index.findObject(reinterpret_cast<const void *>(addr));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AddressToLineCache::impl now resolves the containing object for every frame, so system.trace_log.lines can return shared-library source locations too. The lines column description in getColumnsDescription() and the manual paragraph in docs/reference/system-tables/trace_log.mdx still say that on ELF platforms source locations are only resolved for frames inside the main ClickHouse binary.

That leaves both system.columns.comment and the docs advertising weaker behavior than the code now implements. Please update the source description (and the manual trace_log text outside the autogenerated block) to match the new contract.

@abashkeev abashkeev added the comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). label Sep 4, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 8, 2026
system.errors.last_error_trace, system.error_log.last_error_trace and
system.crash_log.trace stored raw runtime addresses. addressToSymbol
resolves those while the process that produced them is alive, because
SymbolIndex::findSymbol converts an address it finds an object for, but
once the row is flushed and the server restarts, or the row is shipped
to a central cluster, the address means nothing: the load base differs
on every start of a position independent binary. last_error_trace is
the worst case of the three, being the only address column with no
symbolized column beside it, so nothing else in the row identifies the
frames. The column description claiming "physical addresses" was true
only for the position dependent release builds this branch removes.

Frames in the main executable are now stored as their file offsets,
which is what system.trace_log and system.stack_trace already store and
what addr2line and llvm-symbolizer take. Frames in other objects keep
their runtime address: a bare number column has nowhere to record which
object an offset belongs to, and addressToSymbol on a library offset
would answer with the main executable's symbol at the same offset,
which is worse than not resolving. Fixing that ambiguity for the
columns that do normalize per containing object is ClickHouse#101435's subject.

The stored value is computed on read rather than at capture, so the
exception path does an object lookup per frame only for the rows a
query or a log flush actually produces.
@al13n321
al13n321 removed their request for review October 29, 2026 16:40

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants