Repository navigation
Make SymbolIndex work on macOS by parsing Mach-O symbol tables - #99014
Conversation
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]>
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]>
…h-O parsing Co-Authored-By: Claude Opus 4.6 <[email protected]>
…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]>
| /// 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; |
There was a problem hiding this comment.
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.
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]>
|
|
||
| /// Mach-O section names are limited to 16 characters. | ||
| /// Truncate for matching. | ||
| if (macho_name.size() > 16) |
There was a problem hiding this comment.
.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.
| #include <boost/noncopyable.hpp> | ||
|
|
||
| #if defined(OS_DARWIN) | ||
| #include <Common/MachO.h> |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
There are 2 total unresolved issues (including 1 from previous review).
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)) |
There was a problem hiding this comment.
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 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]>
| } | ||
| } | ||
|
|
||
| cmd_ptr += cmd->cmdsize; |
There was a problem hiding this comment.
❌ 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.
| if (reinterpret_cast<const char *>(§[j + 1]) > mapped + file_size) | ||
| break; | ||
|
|
||
| if (sect[j].offset + sect[j].size > file_size) |
There was a problem hiding this comment.
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]>
| 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; |
There was a problem hiding this comment.
❌ 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.
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]>
LLVM Coverage Report
PR changed lines: PR changed-lines coverage: 75.53% (71/94, 0 noise lines excluded) |


Summary
SymbolIndexon macOS, using_dyld_*APIs to enumerate loaded images and readingLC_SYMTABfrom the in-memory__LINKEDITsegmentaddressToSymbol(viaSymbolIndexinstead ofdladdr),system.symbols,buildId, and properStackTracesymbolization on macOSDepends on #98982.
Test plan
system.stack_tracereturns correct symbol names for all threadsaddressToSymbolresolves both ClickHouse and system library symbolssystem.symbolsshows ~3M symbols from all loaded Mach-O imagesbuildId()returns the LC_UUID from the Mach-O binaryChangelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
SymbolIndex,addressToSymbol,system.symbols, andbuildIdnow 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.
SymbolIndexnow enumerates loaded images via_dyld_*, parsesLC_SYMTABfrom in-memory__LINKEDIT, and usesLC_UUIDas the build id; macOS symbols are stored as absolute virtual addresses andObjectentries track ASLRslideplus 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 aDwarf(MachO)path; DarwinStackTraceformatting now usesSymbolIndex+Dwarf(including inline frames) instead ofbacktrace_symbols, andaddressToLineconverts runtime addresses viaslide.Enables related introspection features on macOS. Broadens ELF-only compile guards to include
OS_DARWINforbuildId(),addressToSymbol,system.symbols, andsystem.stack_trace;system.stack_traceadds a Darwin implementation usingpthread_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
26.3.1.825