Skip to content

Make SymbolIndex work on macOS by parsing Mach-O symbol tables - #99014

Merged
alexey-milovidov merged 11 commits into
masterfrom
symbolindex-macos
Mar 18, 2026
Merged

alexey-milovidov merged 11 commits into
masterfrom
symbolindex-macos

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 9, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Added Mach-O symbol table parsing to SymbolIndex on macOS, using _dyld_* APIs to enumerate loaded images and reading LC_SYMTAB from the in-memory __LINKEDIT segment
  • Symbols on macOS use absolute virtual addresses (not relative file offsets) to avoid cross-object offset overlap
  • Enabled addressToSymbol (via SymbolIndex instead of dladdr), system.symbols, buildId, and proper StackTrace symbolization on macOS
  • Updated ELF-specific guards across the codebase to also enable macOS paths

Depends on #98982.

Test plan

  • Built and tested on macOS (arm64)
  • system.stack_trace returns correct symbol names for all threads
  • addressToSymbol resolves both ClickHouse and system library symbols
  • system.symbols shows ~3M symbols from all loaded Mach-O images
  • buildId() returns the LC_UUID from the Mach-O binary
  • No overlap/misattribution of symbols between different loaded images

Changelog category (leave one):

  • New Feature

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

SymbolIndex, addressToSymbol, system.symbols, and buildId now work on macOS by parsing Mach-O symbol tables.

🤖 Generated with Claude Code


Note

Medium Risk
Medium risk because it adds new macOS-specific symbol parsing and stack-trace/signal-table logic (Mach-O, dSYM, thread enumeration) that could affect crash diagnostics and introspection behavior on Darwin.

Overview
Adds macOS (Mach-O) support for symbol and source-location resolution. SymbolIndex now enumerates loaded images via _dyld_*, parses LC_SYMTAB from in-memory __LINKEDIT, and uses LC_UUID as the build id; macOS symbols are stored as absolute virtual addresses and Object entries track ASLR slide plus an optional adjacent .dSYM.

Extends DWARF and stack-trace tooling to use dSYM on Darwin. Introduces Common/MachO.{h,cpp} to read DWARF sections from Mach-O files and adds a Dwarf(MachO) path; Darwin StackTrace formatting now uses SymbolIndex + Dwarf (including inline frames) instead of backtrace_symbols, and addressToLine converts runtime addresses via slide.

Enables related introspection features on macOS. Broadens ELF-only compile guards to include OS_DARWIN for buildId(), addressToSymbol, system.symbols, and system.stack_trace; system.stack_trace adds a Darwin implementation using pthread_kill + Mach thread enumeration and adjusts trace address semantics for macOS.

Written by Cursor Bugbot for commit 0d2b320. This will update automatically on new commits. Configure here.

Version info

  • Merged into: 26.3.1.825

On macOS, `SymbolIndex` now enumerates loaded images via
`_dyld_image_count` / `_dyld_get_image_header` / `_dyld_get_image_vmaddr_slide`
and reads the symbol table (LC_SYMTAB) from the in-memory `__LINKEDIT` segment.

Key design decisions:
- Symbols on macOS store absolute virtual addresses (n_value + slide)
  instead of relative file offsets, to avoid overlap between symbols
  from different objects that would share the same relative offset space.
- `findSymbol` on macOS searches directly by virtual address without
  the address-to-offset conversion used on ELF platforms.
- Build ID is extracted from the LC_UUID load command (16-byte UUID).
- Symbol sizes are estimated from gaps between consecutive symbols,
  since Mach-O nlist_64 entries don't include a size field.

This enables on macOS:
- `addressToSymbol` now uses `SymbolIndex` (with private symbols)
  instead of the limited `dladdr`.
- `system.symbols` table is available.
- `buildId` function returns the Mach-O UUID.
- `StackTrace::forEachFrame` uses `SymbolIndex` for proper symbolization.
- `system.stack_trace` stores virtual addresses that work directly
  with `addressToSymbol`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/Common/SymbolIndex.cpp Resolved
macOS stores DWARF debug info in separate `.dSYM` bundles rather than
embedding it in the binary. This commit adds support for reading DWARF
sections from dSYM Mach-O files, enabling `addressToLine`,
`addressToLineWithInlines`, and file/line info in stack traces on macOS.

Key changes:
- New `MachO` class that parses Mach-O files and provides section lookup
  for the `__DWARF` segment, mapping ELF-style names (`.debug_info`) to
  Mach-O names (`__debug_info`)
- `Dwarf` class extended with a `MachO` constructor alongside the
  existing `Elf` constructor
- `SymbolIndex` on macOS now stores ASLR slide per object and
  automatically discovers dSYM bundles next to binaries
- `StackTrace::forEachFrame` on macOS now resolves file/line/column
  and inline frames using DWARF from dSYM
- `addressToLine` and `addressToLineWithInlines` functions enabled on
  macOS with proper address translation (runtime → linked via slide)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@alexey-milovidov
alexey-milovidov changed the base branch from system-stack-trace-macos to master March 9, 2026 02:23
@clickhouse-gh

clickhouse-gh Bot commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [64a3b85]

Summary: ✅

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 9, 2026
Comment thread src/Common/MachO.cpp Resolved
…atch

- `Dwarf.cpp`: use `static_cast<bool>` for `shared_ptr` — libc++ marks
  `operator bool` as explicit, so implicit conversion is an error.
- `SymbolIndex.cpp`: add "Ok" comment to silent `catch (...)` to satisfy
  the style check.

#99014

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/Common/StackTrace.cpp
/// Convert runtime address to linked (pre-ASLR) address for DWARF lookup.
uintptr_t dwarf_addr = uintptr_t(current_frame.virtual_addr) - object->slide;
if (i > 0)
dwarf_addr -= 1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Wrong condition for return address adjustment in DWARF lookup

Medium Severity

The address adjustment if (i > 0) dwarf_addr -= 1 uses i > 0 but the loop starts at i = offset. When offset > 0, the first meaningful frame (at index offset) is an instruction pointer, not a return address, so subtracting 1 is incorrect for it. The condition needs to be i > offset to only adjust subsequent frames which are return addresses. The ELF path doesn't perform this adjustment at all, making this a macOS-only regression that can cause incorrect file/line resolution for the topmost stack frame.

Fix in Cursor Fix in Web

Validate that `segment_command_64` and each `section_64` entry fit within
the mapped file before accessing them. A malformed dSYM with an inflated
`nsects` value could previously read past the mmap'd region.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/Common/MachO.cpp Outdated

/// Mach-O section names are limited to 16 characters.
/// Truncate for matching.
if (macho_name.size() > 16)

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.

⚠️ Truncating ELF-style names to 16 chars is not safe for DWARF5 sections. .debug_str_offsets does not map to a simple truncation (__debug_str_off), while Mach-O commonly uses __debug_str_offs. With the current mapping, str_offsets_ lookup can fail and line resolution for DWARF5 binaries becomes incomplete. Please add an explicit name map for long sections (at least .debug_str_offsets -> __debug_str_offs) instead of generic truncation.

Comment thread src/Common/SymbolIndex.h Outdated
#include <boost/noncopyable.hpp>

#if defined(OS_DARWIN)
#include <Common/MachO.h>

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.

⚠️ SymbolIndex.h is used broadly, but this include pulls in MachO.h (and transitively MMapReadBufferFromFile) into every Darwin translation unit that includes SymbolIndex.h. Here only std::shared_ptr<MachO> is stored, so a forward declaration (class MachO;) is enough and keeps heavy headers in .cpp. This avoids unnecessary compile-time regression.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

}

/// Just in case we will wait for pipe with timeout. In case signal didn't get processed.
if (wait(pipe_read_timeout_ms) && sequence_num.load(std::memory_order_acquire) == data_ready_num.load(std::memory_order_acquire))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Race condition in macOS signal handler causes misattributed stacks

Medium Severity

After a timeout, SCOPE_EXIT increments sequence_num but expected_responding_thread still holds the previous thread's identity. A delayed signal handler from thread A can run in this window, pass both the pthread_self() pre-check and re-check (since expected_responding_thread hasn't been updated yet), read the already-incremented sequence_num (N+1), write it to data_ready_num and the pipe. When the next iteration sends a signal to thread B and calls wait(), it reads A's stale pipe data and accepts it because sequence_num == data_ready_num == N+1. This causes thread A's stack trace to be reported as thread B's. On Linux this race doesn't exist because the signal payload carries the specific sequence number assigned at send time.

Additional Locations (1)
Fix in Cursor Fix in Web

- Fix DWARF5 section name mapping: add explicit mappings for long names like
  `.debug_str_offsets` -> `__debug_str_offs` instead of relying on truncation
- Forward-declare `MachO` in `SymbolIndex.h` to avoid pulling heavy includes
  into every translation unit; move `#include <Common/MachO.h>` to SymbolIndex.cpp
- Fix return address adjustment: use `i > offset` instead of `i > 0` so the
  topmost frame (instruction pointer) is not incorrectly decremented
- Fix race condition in macOS signal handler: reset `expected_responding_thread`
  immediately after `wait` to prevent a delayed handler from writing the new
  `sequence_num` and having its response misattributed to the next thread

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Common/MachO.cpp
}
}

cmd_ptr += cmd->cmdsize;

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.

❌ cmd->cmdsize is used to advance cmd_ptr without validating it first. For malformed Mach-O input, cmdsize can be 0 or smaller than sizeof(load_command), so the parser keeps re-reading the same bytes for up to header->ncmds iterations (and can become a CPU-heavy loop for large ncmds). Please validate cmdsize before consuming the command, e.g. reject/break when cmd->cmdsize < sizeof(load_command) or when cmd_ptr + cmd->cmdsize goes past file bounds.

Comment thread src/Common/MachO.cpp Outdated
if (reinterpret_cast<const char *>(&sect[j + 1]) > mapped + file_size)
break;

if (sect[j].offset + sect[j].size > file_size)

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.

Potential out-of-bounds read due to integer overflow in the section-size check.

sect[j].offset + sect[j].size > file_size can wrap for crafted values, letting an invalid range pass and then using mapped + sect[j].offset with a too-large size. Please switch to a non-overflowing form, e.g. if (sect[j].offset > file_size || sect[j].size > file_size - sect[j].offset) continue;.

Validate `cmdsize` before using it to advance the command pointer — a
zero or too-small value would cause an infinite loop, and a value past
the file boundary would read unmapped memory.

Use overflow-safe arithmetic for the section offset+size check so that
crafted values wrapping past `SIZE_MAX` cannot bypass the bounds guard.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Common/SymbolIndex.h
std::shared_ptr<Elf> elf;
#if defined(OS_DARWIN)
/// ASLR slide for this image. Subtract from runtime address to get linked (DWARF) address.
uintptr_t slide = 0;

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.

❌ slide is stored as uintptr_t, but _dyld_get_image_vmaddr_slide returns intptr_t (signed). A negative slide wraps here, and later addr - object->slide in StackTrace / addressToLine becomes incorrect due to unsigned arithmetic, producing wrong DWARF addresses and failed symbolization. Please keep slide signed (e.g., intptr_t) and do signed subtraction with a bounds check before converting to uintptr_t.

alexey-milovidov and others added 3 commits March 16, 2026 21:14
The `assert` fires when the fuzzer produces an inconsistent AST with
`has_attach_from_path` set but `attach` not set. Replace with `chassert`
which is appropriate for invariants that can be violated by fuzzed ASTs.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99014&sha=26d0057040d788fd2d1a1078d4d6b3a4201f1047&name_0=PR

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.80% 83.70% -0.10%
Functions 23.90% 23.90% +0.00%
Branches 76.30% 76.30% +0.00%

PR changed lines: PR changed-lines coverage: 75.53% (71/94, 0 noise lines excluded)
Diff coverage report
Uncovered code

@alexey-milovidov
alexey-milovidov merged commit 9e66cb9 into master Mar 18, 2026
159 checks passed
@alexey-milovidov
alexey-milovidov deleted the symbolindex-macos branch March 18, 2026 17:14
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants