Skip to content

Refactor stackwalker - #451

Merged
zhengyu123 merged 11 commits into
mainfrom
zgu/refactor-stackwalk
Apr 9, 2026
Merged

zhengyu123 merged 11 commits into
mainfrom
zgu/refactor-stackwalk

Conversation

@zhengyu123

@zhengyu123 zhengyu123 commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?:
This is the second part of code refactoring that builds better abstraction among different JVM implementations. This PR focuses on stack walker components.

  • jvmSupport to encapsulate different JVM specific implementation details (hotspot/HotspotSupport, j9/J9Support and zing/ZingSupport)
  • Moved Hotspot specific stack walkers (walkVMs) into HotspotSupport
  • Moved hotspot specific JIT'ed code cache management to newly created hotspot/jitCodeCache.h/cpp
  • Renamed J9Ext.h/cpp to J9Support.h/cpp to be consistent with others
  • Removed unused files jvm.h/cpp
  • Moved shared frame creation code to new frames.h

Motivation:
This is the second part of efforts to build abstraction among different JVM implements, so that one implementation specific code does not inadvertently pollute unsupported JVMs. This PR focus on stack walker.

Additional Notes:

How to test the change?:

For Datadog employees:

  • If this PR touches code that signs or publishes builds or packages, or handles
    credentials of any kind, I've requested a review from @DataDog/security-design-and-guidance.
  • This PR doesn't touch any of that.
  • JIRA: PROF-13889

Unsure? Have a question? Request a review!

@dd-octo-sts

dd-octo-sts Bot commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor

Scan-Build Report

User:runner@runnervm35a4x
Working Directory:/home/runner/work/java-profiler/java-profiler/ddprof-lib/src/test/make
Command Line:make -j4 all
Clang Version:Ubuntu clang version 18.1.3 (1ubuntu1)
Date:Thu Apr 9 14:24:49 2026

Bug Summary

Bug TypeQuantityDisplay?
All Bugs1
Logic error
Stack address stored into global variable1

Reports

Bug Group Bug Type ▾ File Function/Method Line Path Length
Logic errorStack address stored into global variablehotspotSupport.cppwalkVM70137

@zhengyu123 zhengyu123 changed the title v0 WIP: Refactor stackwalker Apr 2, 2026
@dd-octo-sts

dd-octo-sts Bot commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor

CI Test Results

Run: #34248691981 | Commit: cf6b341 | Duration: 0s (longest job)

✅ All 0 test jobs passed

Summary: Total: 0 | Passed: 0 | Failed: 0


Updated: 2026-09-08 16:18:37 UTC

@zhengyu123 zhengyu123 changed the title WIP: Refactor stackwalker Refactor stackwalker Apr 7, 2026
@zhengyu123
zhengyu123 marked this pull request as ready for review April 7, 2026 15:40
@zhengyu123
zhengyu123 requested a review from a team as a code owner April 7, 2026 15:40
@zhengyu123
zhengyu123 requested review from jbachorik and rkennke April 7, 2026 15:40

@jbachorik jbachorik left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤖 Review generated by Claude Sonnet (AI assistant) on behalf of @jbachorik . All findings verified against the current state of the PR.


Summary: The refactoring is mostly mechanical code movement and generally clean. There are 2 correctness bugs introduced during the extraction, plus 4 dead-code leftovers. Findings below, roughly by severity.


Additionally (line not in diff context):

profiler.h lines 114–117 + constructor init: _stubs_lock, _runtime_stubs, _call_stub_begin, _call_stub_end are still declared in Profiler and initialised in its constructor, but every usage was removed from profiler.cpp in this PR — all stub routing moved to JitCodeCache. These four fields are now dead weight. The alignment comment on line 63 (// _class_map_lock, _locks[], and _stubs_lock) should also be updated once _stubs_lock is removed.

Comment thread ddprof-lib/src/main/cpp/jvmSupport.cpp Resolved
Comment thread ddprof-lib/src/main/cpp/j9/j9Support.h Resolved
Comment thread ddprof-lib/src/main/cpp/profiler.h Resolved
Comment thread ddprof-lib/src/main/cpp/stackWalker.h Resolved

@jbachorik jbachorik left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤖 Second review pass (ivoanjo lens) by Claude Sonnet on behalf of @jbachorik. All findings verified against the current state of the PR.

Six additional findings: 3 dead-code items, 1 mode inconsistency, 1 doc drift, 1 minor atomics issue.

Comment thread ddprof-lib/src/main/cpp/jvmSupport.h Resolved
Comment thread ddprof-lib/src/main/cpp/frames.h Resolved
Comment thread ddprof-lib/src/main/cpp/jvmSupport.cpp Resolved

@jbachorik jbachorik left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Good to go, pending #455 sub-pr

@zhengyu123
zhengyu123 merged commit cf6b341 into main Apr 9, 2026
83 checks passed
@zhengyu123
zhengyu123 deleted the zgu/refactor-stackwalk branch April 9, 2026 14:58
@github-actions github-actions Bot added this to the 1.41.0 milestone Apr 9, 2026
@zhengyu123 zhengyu123 added the fixed_version: v_1.41.0 Version this PR's fix shipped in label Sep 8, 2026
rkennke added a commit that referenced this pull request Sep 25, 2026
…rame

walkDwarf and walkVM carried two copies of the same unwind step. 61959b0
and 06ab5b6 reconciled the five differences between them; this moves what
is left into one always_inline helper in dwarfStep.inline.h and calls it from
both. 183 lines of duplication become 10.

always_inline is load-bearing, not an optimisation. AddressSanitizer
instruments per function after inlining, so an inlined body takes its
caller's sanitizer attribute. walkVM is no_sanitize("address") because it
reads arbitrary stack memory while sampling; walkDwarf is deliberately
instrumented, and both have been that way since before the two were split
apart in #451. Out of line, one attribute would have to serve both -- either
dropping walkDwarf's instrumentation or adding to walkVM the instrumentation
the attribute exists to avoid. Measured on the built objects rather than
assumed: with always_inline the helper emits no out-of-line symbol at all,
walkVM still contains zero __asan references and walkDwarf still contains
its own.

What moved and what did not:

  - Both callers keep their own `bottom`, computed from their own frame, and
    pass it in.
  - `depth` is a parameter because the two callers disagree on it. walkVM's
    fp-chain fallback reaches the step through `goto dwarf_unwind`, which
    skips its fillFrame(frames[depth++], ...), so on that path it arrives one
    lower than walkDwarf does at the same logical position. Passing it
    through is what keeps this a move rather than a merge; the header says so
    at the parameter.
  - The lookup goes inside, so the helper takes Profiler* rather than the
    CodeCache* the ticket sketched: the DW_REG_PLT arm needs attribution_pc
    to decide the stub offset, so a caller-side lookup would have to
    recompute walk_pc.attribution() anyway.
  - walkVM's prev_native_walk_pc/have_prev_native_pc bookkeeping stays at the
    call site, hoisted to just above the call from the middle of the step.
    Nothing between those two points mutates walk_pc, and a stop leaves the
    loop, so the only reader -- the MARK_THREAD_ENTRY check on the next
    iteration -- cannot tell the difference.

Each of the nine break sites becomes a `return false`; the count was checked
mechanically before and after rather than by eye, since four of them sit on
arms no test in the suite reaches.

Equivalence was checked against the disassembly, not only the tests.
walkDwarf's call sequence is identical instruction-for-instruction in
release; walkVM's call multiset is identical with one static-guard pair
reordered. Neither is byte-identical -- inlining a function changes what the
scheduler and register allocator see, so release moves 313 -> 308
instructions in walkDwarf and 2997 -> 3061 in walkVM. The sanitizer configs
compile at -O0, where the helper's parameters and its FrameDesc copy
materialise as real stack traffic, so walkDwarf grows there (1020 -> 1173
instructions, 9 -> 25 instrumented accesses). Those configs are test-only;
the shipped release build is the one above.

Full native suite green on linux-x64 in debug and release, and the three
binaries over this code green under ASan and TSan.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
rkennke added a commit that referenced this pull request Sep 29, 2026
…OF-16059) (#813)

* fix(profiling): select rows and symbols in walkVM by attribution address

walkVM fed the raw walking pc to findLibraryByAddress, findFrameDesc and the
DW_REG_PLT stub-offset test. Past the leaf that pc is a return address, so a
call that is the last instruction of its caller selected the following
function's CFA row, derived a sender sp from it, and could miss a
MARK_THREAD_ENTRY sitting on the caller -- the same defect already fixed in
StackWalker::walkFP/walkDwarf, on the path CSTACK_DEFAULT actually resolves to.

Track per-frame whether the pc came out of a return-address slot and route the
range-based lookups through attributionPC(). Exact-address consumers
(isContReturnBarrier, isContEntryReturnPc, isEntryFrame), the DW_PC_OFFSET
arithmetic and the no-progress guard keep the raw pc, and a signal-frame CIE
suppresses the adjustment exactly as it does in walkDwarf.

resolveNativeFrameForWalkVM was using one address for two jobs. It now takes
the attribution address for findLibraryByAddress/binarySearch while the emitted
pc_offset keeps deriving from the raw pc, so the remote-symbolication wire
value is unchanged and no cross-team contract moves.

unwindPrologue/unwindEpilogue/unwindStub are left alone: x86_64 already folds
the adjustment into the pc they return and does so inconsistently (the
isFrameComplete branch omits it) while aarch64 returns it raw, so their results
are flagged as non-return-addresses and cannot be adjusted twice. Unifying that
contract also fixes the exact-address comparisons those helpers currently break
on x86_64, and is left to its own change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(profiling): gate the lookup/wire-format address split in walkVM resolution

resolveNativeFrameForWalkVM uses two addresses for two jobs: range lookups key
off the attribution address so a call that is the last instruction of its
caller still resolves to the caller, while the emitted pc_offset keeps deriving
from the raw pc because its meaning is a wire contract rather than a local
detail. Neither half was gated by a test.

Both are now pinned at a synthetic zero-gap symbol boundary, the shape where
the two addresses disagree: flagging the pc as a return address must move the
resolved symbol from the following function back to the caller, and must leave
the emitted offset untouched. A third case pins that an address well inside a
function resolves identically either way, so the adjustment cannot be read as a
blanket shift.

Both assertions were mutation-checked -- reverting the lookup to the raw pc
fails the boundary case alone, and deriving pc_offset from the attribution
address fails the wire case alone.

The fixtures publish synthetic CodeCaches through a new test-only entry point
rather than the test binary's own symbols, which is what makes a controlled
zero-gap boundary possible at all and keeps these tests free of the
GNU-as/ELF-CFI and updateSymbols() dependencies that confine
returnAddressAttribution_ut to Linux.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(profiling): carry walkVM's pc and its nature as one value

walkVM tracked "is this pc a return address?" in a bool sitting beside the pc,
so the two could drift: a newly added `pc = ...` inherited whatever the
previous frame had set, silently attributing the next lookup to the wrong
address. That is the exact hazard WalkPc was introduced for in walkFP/walkDwarf,
and walkVM is the default cstack path, so it is the one that most needed it.

walkVM now drives a WalkPc. Every pc source states what it produced --
setReturnAddress for a saved-pc slot or link register, setRecoveredPc for a
DWARF row, setExactAddress where the arch unwind helpers already folded the
adjustment in -- and consumers read raw() or attribution() explicitly. Adding a
pc source is now a compile-time decision instead of something a reviewer has to
notice.

Threading the seed through surfaced a real gap: walkVM is entered either from a
ucontext, whose pc is the exact interrupted address, or from callerPC(), which
is a genuine return address on every architecture where
CALLER_PC_IS_RETURN_ADDRESS holds. Both arrived as a bare pointer and were
treated as exact, so the callerPC() entry never got the adjustment it needed.
The private overload now takes that distinction from its caller, the same way
walkFP and walkDwarf seed themselves.

No behaviour change otherwise: the mutator chosen at each site reproduces the
flag that site already set.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(profiling): name the walk seed instead of branching twice at the call

walkVM's public entry point built its two starting states inline, so the pc and
the flag describing it were separate arguments chosen a few tokens apart in two
near-identical call expressions. Nothing bound them together, which is the same
drift the walk itself now avoids by carrying a WalkPc.

Both states are one named value instead. walkVMSeed() decides where a walk
starts -- register set and the nature of the pc together -- and the entry point
delegates without a branch of its own.

The frame no longer outlives the decision: its pc/sp/fp are copied out as
scalars, which is all the callee ever used, and the ucontext they point into
outlives the walk regardless.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(profiling): keep the library test seam out of release builds

Three review follow-ups.

addLibraryForTest shipped in every build. Every other test hook in this
codebase is either behind #ifdef UNIT_TEST or reached through a friend
*TestAccessor, so a publicly callable mutator for the process-wide library set
was both inconsistent and present where nothing should be able to call it. It
is now compiled only into gtest binaries, which is where its one caller lives.

prev_native_pc lost its last reader when the walk started carrying the previous
frame as a WalkPc; the declaration stayed behind. Unused-variable warnings are
not errors here, so nothing caught it.

RemoteSymbolication.md still described the two-argument
resolveNativeFrameForWalkVM. It now names the third parameter and says what it
selects -- lookups move to the attribution address, the emitted pc_offset does
not -- since the wire value being unchanged is the part a reader of that
document needs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(profiling): adjust sender pcs the arm64 unwind helpers hand back raw

The three arch unwind helpers were all treated as having already applied the
attribution adjustment. That holds on x86_64, which subtracts one inside the
helper, but not on aarch64: every branch walkVM can reach there assigns the
link register or a saved-pc slot, both raw return addresses. The one aarch64
branch that does subtract is guarded by `&pc == &this->pc()`, true only on the
AsyncGetCallTrace path where the caller passes the frame's own pc rather than a
local, so walkVM never takes it.

A sample leaving a generated frame for a native caller whose call is the last
instruction before a symbol or FDE boundary was therefore still attributed to
whatever follows, on arm64, for exactly the frames this change set out to fix.

recordUnwoundPc() names the difference in one place. x86_64 behaviour is
unchanged; the distinction disappears once the helpers agree on a contract.

Reported by Codex review on #813.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(profiling): realign walkVM's DWARF step with walkDwarf's

The two copies of this unwind step have drifted. Each gap is taken from
walkDwarf, which is the one that got the attention:

  - The link register was fed to findFrameDesc unstripped. On aarch64 it
    carries PAC bits, so the lookup address is nonsense. walkDwarf strips it
    and says why; this side never picked that up. Only reachable through a
    frame table carrying DW_LINK_REGISTER, which DwarfParser does not emit
    and SFrameParser does, so it is latent rather than live today.

  - The frame-pointer slot was dereferenced without checking its alignment,
    while the pc slot three lines below is checked. Same load, same exposure.

  - Neither slot load carried a fault-injection hook, so the recovery path
    around them went unexercised. LIKELY matches the existing convention:
    walkVM's seven UNLIKELY sites are raw dereferences, these two go through
    SafeAccess.

Reconciling these first keeps the extraction that follows a pure move, with
no behaviour hidden inside it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(profiling): drive walkVM end to end without a JVM

walkVM read its VMThread through JVMThread::current(), which asserts its
thread-local key is live -- something only a JVM attach sets up. Nothing below
that line needs the thread on the native path, and every use of it is already
NULL-guarded, so it now asks whether one exists instead of requiring it. With a
JVM attached the answer is always yes and nothing changes; without one the walk
takes the same degraded path it would on an unattached thread, and
WALKVM_NO_VMTHREAD still records that it did.

That is the whole of what stood between walkVM and a unit test. VMStructs stays
uninitialised, so CodeHeap::contains() is false for every address and the walk
goes down the native branch on every frame -- which is the branch the
attribution work touches.

The test plants one synthetic linked frame so the walk steps off an exact
ucontext leaf onto a caller whose pc comes out of a return-address slot. Both
land on the same zero-gap boundary, so they must resolve to different functions
purely because of that difference. Mutating the DWARF recovery to claim its pc
is exact fails it, reporting the following function where the caller belongs.

Two platform details the fixture has to respect, both found the hard way:
uc_mcontext is a pointer on Darwin and embedded on Linux, so a zeroed
ucontext_t needs storage to point at or the first register access faults in a
loop behind the profiler's own SIGSEGV handler; and the frame layout has to
come from FrameDesc::default_frame, which is what a table-less CodeCache
returns, not fallback_default_frame(), which differs from it on Apple aarch64.

This covers the DWARF recovery path only. The saved-pc slots in the compiled
and stub arms sit behind CodeHeap::contains() and stay unreachable here.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(profiling): reconcile the last two divergences in walkVM's DWARF step

61959b0 reconciled three gaps between walkVM's copy of the DWARF unwind
step and walkDwarf's, all of them in the pc/fp recovery half. A mechanical
diff of the two bodies shows the CFA half still diverges in two places, and
unlike the earlier three these resolve in opposite directions -- so the
extraction that follows could not have been the pure move that commit
claimed it was setting up.

walkVM falls through on a CFA register it does not implement.

walkDwarf ends its cfa_reg chain with an else that stops the walk. walkVM
instead pre-screened DW_REG_INVALID and anything past DW_REG_PLT, then ran
the same three arms with no else. With DW_REG_FP 6, DW_REG_SP 7 and
DW_REG_PLT 128 on x86_64, a register in 0..5 or 8..127 matches no arm and is
not rejected: sp keeps the value it had on entry to the step, and the walk
reads the caller's pc and fp out of the current frame's own slots.

It is reachable from ordinary DWARF. DwarfParser takes the register straight
off the wire under DW_CFA_def_cfa, _def_cfa_register and _def_cfa_sf, and
addRecord() only rejects it above 0xFF, so nothing narrows it to the three
the walkers implement -- a function whose CFA is based on any other register
lands in the hole. WalkVmAlsoStopsOnAnUnhandledCfaRegister plants exactly
that row and shows walkVM recording a second frame off an unmoved sp where
walkDwarf stops at the leaf.

walkVM's pre-screen is subsumed by the new else and goes away with it; every
value it rejected now falls out of the same arm as the rest.

walkDwarf trusts a frame pointer walkVM checks.

The other direction: walkVM sanity-checks fp for bounds and alignment before
deriving a CFA from it, walkDwarf did not. A misaligned fp whose row offset
re-aligns the result slips past every later test, all of which look at sp,
so only a check on fp itself stops it. 61959b0's rule was that each gap is
taken from walkDwarf; this one goes the other way, and the comment travels
with the code so the reason is not lost.

Both changes are gated, each verified to fail with its fix reverted:

  WalkDwarfStopsOnAnUnhandledCfaRegister      baseline, passes throughout
  WalkVmAlsoStopsOnAnUnhandledCfaRegister     gates the else
  WalkDwarfRejectsAMisalignedFramePointer     gates the fp check

Two properties of the fixture are load-bearing and commented as such:
DW_PC_OFFSET is 1, so fp_off must be even or the step takes the DW_OP_breg
arithmetic branch instead of the memory-slot one under test; and cfa_off must
be non-zero or the aarch64 defaultSenderSP() branch fires. A DW_REG_INVALID
row above each planted leaf stops whichever walker does step past it, so a
failure reports a wrong depth rather than running into unplanted memory.

With this the two bodies differ only in where attribution_pc is declared and
in walkVM's prev_native_walk_pc/have_prev_native_pc bookkeeping, which stays
at the call site. advanceDwarfFrame() can now be extracted as a pure move.

Full native suite green on linux-x64 in debug and release, and this binary
green in all four configurations. That is also the first Linux run of the
walkVM fixtures, which had only been exercised on macOS/arm64.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(profiling): extract the shared DWARF step into advanceDwarfFrame

walkDwarf and walkVM carried two copies of the same unwind step. 61959b0
and 06ab5b6 reconciled the five differences between them; this moves what
is left into one always_inline helper in dwarfStep.inline.h and calls it from
both. 183 lines of duplication become 10.

always_inline is load-bearing, not an optimisation. AddressSanitizer
instruments per function after inlining, so an inlined body takes its
caller's sanitizer attribute. walkVM is no_sanitize("address") because it
reads arbitrary stack memory while sampling; walkDwarf is deliberately
instrumented, and both have been that way since before the two were split
apart in #451. Out of line, one attribute would have to serve both -- either
dropping walkDwarf's instrumentation or adding to walkVM the instrumentation
the attribute exists to avoid. Measured on the built objects rather than
assumed: with always_inline the helper emits no out-of-line symbol at all,
walkVM still contains zero __asan references and walkDwarf still contains
its own.

What moved and what did not:

  - Both callers keep their own `bottom`, computed from their own frame, and
    pass it in.
  - `depth` is a parameter because the two callers disagree on it. walkVM's
    fp-chain fallback reaches the step through `goto dwarf_unwind`, which
    skips its fillFrame(frames[depth++], ...), so on that path it arrives one
    lower than walkDwarf does at the same logical position. Passing it
    through is what keeps this a move rather than a merge; the header says so
    at the parameter.
  - The lookup goes inside, so the helper takes Profiler* rather than the
    CodeCache* the ticket sketched: the DW_REG_PLT arm needs attribution_pc
    to decide the stub offset, so a caller-side lookup would have to
    recompute walk_pc.attribution() anyway.
  - walkVM's prev_native_walk_pc/have_prev_native_pc bookkeeping stays at the
    call site, hoisted to just above the call from the middle of the step.
    Nothing between those two points mutates walk_pc, and a stop leaves the
    loop, so the only reader -- the MARK_THREAD_ENTRY check on the next
    iteration -- cannot tell the difference.

Each of the nine break sites becomes a `return false`; the count was checked
mechanically before and after rather than by eye, since four of them sit on
arms no test in the suite reaches.

Equivalence was checked against the disassembly, not only the tests.
walkDwarf's call sequence is identical instruction-for-instruction in
release; walkVM's call multiset is identical with one static-guard pair
reordered. Neither is byte-identical -- inlining a function changes what the
scheduler and register allocator see, so release moves 313 -> 308
instructions in walkDwarf and 2997 -> 3061 in walkVM. The sanitizer configs
compile at -O0, where the helper's parameters and its FrameDesc copy
materialise as real stack traffic, so walkDwarf grows there (1020 -> 1173
instructions, 9 -> 25 instrumented accesses). Those configs are test-only;
the shipped release build is the one above.

Full native suite green on linux-x64 in debug and release, and the three
binaries over this code green under ASan and TSan.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* THROWAWAY: run walkVmAttribution_ut directly on aarch64 to see which test fails

Revert before merge. Diagnostic only, no product change.

gtestDebug_walkVmAttribution_ut fails on every aarch64 cell and has since
66eea0c, while amd64 is green in every configuration. Which assertion
fails is not recoverable from the logs: the Gradle daemon swallows the test
binary's stdout, so the job reports only the task name. .gitlab/sanitizer-tests
already works around this by using Gradle for compile+link and then running
each binary straight from the shell; this does the same for one binary on the
glibc-aarch64 job.

Placed before the Test step, which would otherwise fail the job first, and
marked continue-on-error so it can only add output.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(test): stop the walkVM fixture terminating its chain with a zero fp

CallerFrameFromReturnSlotAttributesToTheCaller failed on every Linux/aarch64
cell since it was added, returning depth 1 where it expects 2. It passes on
Apple aarch64 and on x86_64, which is why it went in green.

plantCallerFrame ended the chain by storing 0 into the caller's frame-pointer
slot, on the reasoning that an unwalkable fp stops the walk. On Linux/aarch64
that stops it one frame too early. There default_frame carries cfa_off == 0
and EMPTY_FRAME_SIZE is 0, so the step ends in

    sp = defaultSenderSP(sp, fp)

and defaultSenderSP returns fp on Linux, where it returns sp + 16 on Apple.
The planted zero therefore becomes a zero sp, which trips the `sp < prev_sp`
check inside the very step that had just recovered the caller's pc -- so the
walk stops before the caller frame is recorded and the pc the test exists to
check never reaches the chain. Apple aarch64 never reads fp there, and on
x86_64 EMPTY_FRAME_SIZE > 0 keeps that branch out of the path entirely.

The fixture now points the slot at a higher, still-plausible slot in the same
scratch buffer and lets the frame above terminate the walk on its own zeroed
pc -- a dead-zone stop on x86_64, the same sp check on aarch64, in both cases
one frame later than before, which is where the assertion wants it.

This is the third platform asymmetry this fixture has hit, after the
uc_mcontext pointer-vs-value split and default_frame vs
fallback_default_frame. The comment says which branch fires where, since
none of them are visible from the test body.

Verified on x86_64 (7/7 in debug and release) and by simulating the aarch64
step arithmetic against its own constants: the old fixture reproduces the
observed depth 1, the new one gives depth 2. The aarch64 run itself arrives
with the pipeline.

Also reverts a1a4480, the throwaway CI step that produced the gtest output
this was diagnosed from -- the Gradle daemon swallows the binary's stdout, so
the job had only ever reported the task name. Worth noting for next time:
.gitlab/sanitizer-tests already runs its binaries straight from the shell for
exactly this reason, and those jobs are where a gtest failure is legible.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(profiling): read the null-ucontext seed in walkVM's own frame

callerPC/callerSP/callerFP are __builtin_return_address and
__builtin_frame_address underneath, so they describe whichever frame evaluates
them. Folding them into a seed helper moved that frame: wherever the helper is
not inlined -- debug and sanitizer builds, which is where it matters -- the
walk started one frame too deep, inside the profiler. A malloc or socket
sample then spends depth on a profiler frame before reaching the
MARK_JAVA_PROFILER boundary, and a shallow one can run out before it gets
there and record nothing useful.

The wrapper reads them inline again, as it did before the seed struct, with
the reason written down so the next person tidying this does not repeat it.
Nothing else needed the struct once the two branches were back in place.

Also drops an if-initializer whose continuation line sat well out of step with
the surrounding indentation; a plain else block reads the same and looks like
the rest of the function.

Reported by Codex and Datadog review on #813.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Jaroslav Bachorik <jaroslav.bachorik@datadoghq.com>
jbachorik added a commit that referenced this pull request Sep 29, 2026
…OF-16059) (#813)

* fix(profiling): select rows and symbols in walkVM by attribution address

walkVM fed the raw walking pc to findLibraryByAddress, findFrameDesc and the
DW_REG_PLT stub-offset test. Past the leaf that pc is a return address, so a
call that is the last instruction of its caller selected the following
function's CFA row, derived a sender sp from it, and could miss a
MARK_THREAD_ENTRY sitting on the caller -- the same defect already fixed in
StackWalker::walkFP/walkDwarf, on the path CSTACK_DEFAULT actually resolves to.

Track per-frame whether the pc came out of a return-address slot and route the
range-based lookups through attributionPC(). Exact-address consumers
(isContReturnBarrier, isContEntryReturnPc, isEntryFrame), the DW_PC_OFFSET
arithmetic and the no-progress guard keep the raw pc, and a signal-frame CIE
suppresses the adjustment exactly as it does in walkDwarf.

resolveNativeFrameForWalkVM was using one address for two jobs. It now takes
the attribution address for findLibraryByAddress/binarySearch while the emitted
pc_offset keeps deriving from the raw pc, so the remote-symbolication wire
value is unchanged and no cross-team contract moves.

unwindPrologue/unwindEpilogue/unwindStub are left alone: x86_64 already folds
the adjustment into the pc they return and does so inconsistently (the
isFrameComplete branch omits it) while aarch64 returns it raw, so their results
are flagged as non-return-addresses and cannot be adjusted twice. Unifying that
contract also fixes the exact-address comparisons those helpers currently break
on x86_64, and is left to its own change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(profiling): gate the lookup/wire-format address split in walkVM resolution

resolveNativeFrameForWalkVM uses two addresses for two jobs: range lookups key
off the attribution address so a call that is the last instruction of its
caller still resolves to the caller, while the emitted pc_offset keeps deriving
from the raw pc because its meaning is a wire contract rather than a local
detail. Neither half was gated by a test.

Both are now pinned at a synthetic zero-gap symbol boundary, the shape where
the two addresses disagree: flagging the pc as a return address must move the
resolved symbol from the following function back to the caller, and must leave
the emitted offset untouched. A third case pins that an address well inside a
function resolves identically either way, so the adjustment cannot be read as a
blanket shift.

Both assertions were mutation-checked -- reverting the lookup to the raw pc
fails the boundary case alone, and deriving pc_offset from the attribution
address fails the wire case alone.

The fixtures publish synthetic CodeCaches through a new test-only entry point
rather than the test binary's own symbols, which is what makes a controlled
zero-gap boundary possible at all and keeps these tests free of the
GNU-as/ELF-CFI and updateSymbols() dependencies that confine
returnAddressAttribution_ut to Linux.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(profiling): carry walkVM's pc and its nature as one value

walkVM tracked "is this pc a return address?" in a bool sitting beside the pc,
so the two could drift: a newly added `pc = ...` inherited whatever the
previous frame had set, silently attributing the next lookup to the wrong
address. That is the exact hazard WalkPc was introduced for in walkFP/walkDwarf,
and walkVM is the default cstack path, so it is the one that most needed it.

walkVM now drives a WalkPc. Every pc source states what it produced --
setReturnAddress for a saved-pc slot or link register, setRecoveredPc for a
DWARF row, setExactAddress where the arch unwind helpers already folded the
adjustment in -- and consumers read raw() or attribution() explicitly. Adding a
pc source is now a compile-time decision instead of something a reviewer has to
notice.

Threading the seed through surfaced a real gap: walkVM is entered either from a
ucontext, whose pc is the exact interrupted address, or from callerPC(), which
is a genuine return address on every architecture where
CALLER_PC_IS_RETURN_ADDRESS holds. Both arrived as a bare pointer and were
treated as exact, so the callerPC() entry never got the adjustment it needed.
The private overload now takes that distinction from its caller, the same way
walkFP and walkDwarf seed themselves.

No behaviour change otherwise: the mutator chosen at each site reproduces the
flag that site already set.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(profiling): name the walk seed instead of branching twice at the call

walkVM's public entry point built its two starting states inline, so the pc and
the flag describing it were separate arguments chosen a few tokens apart in two
near-identical call expressions. Nothing bound them together, which is the same
drift the walk itself now avoids by carrying a WalkPc.

Both states are one named value instead. walkVMSeed() decides where a walk
starts -- register set and the nature of the pc together -- and the entry point
delegates without a branch of its own.

The frame no longer outlives the decision: its pc/sp/fp are copied out as
scalars, which is all the callee ever used, and the ucontext they point into
outlives the walk regardless.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(profiling): keep the library test seam out of release builds

Three review follow-ups.

addLibraryForTest shipped in every build. Every other test hook in this
codebase is either behind #ifdef UNIT_TEST or reached through a friend
*TestAccessor, so a publicly callable mutator for the process-wide library set
was both inconsistent and present where nothing should be able to call it. It
is now compiled only into gtest binaries, which is where its one caller lives.

prev_native_pc lost its last reader when the walk started carrying the previous
frame as a WalkPc; the declaration stayed behind. Unused-variable warnings are
not errors here, so nothing caught it.

RemoteSymbolication.md still described the two-argument
resolveNativeFrameForWalkVM. It now names the third parameter and says what it
selects -- lookups move to the attribution address, the emitted pc_offset does
not -- since the wire value being unchanged is the part a reader of that
document needs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(profiling): adjust sender pcs the arm64 unwind helpers hand back raw

The three arch unwind helpers were all treated as having already applied the
attribution adjustment. That holds on x86_64, which subtracts one inside the
helper, but not on aarch64: every branch walkVM can reach there assigns the
link register or a saved-pc slot, both raw return addresses. The one aarch64
branch that does subtract is guarded by `&pc == &this->pc()`, true only on the
AsyncGetCallTrace path where the caller passes the frame's own pc rather than a
local, so walkVM never takes it.

A sample leaving a generated frame for a native caller whose call is the last
instruction before a symbol or FDE boundary was therefore still attributed to
whatever follows, on arm64, for exactly the frames this change set out to fix.

recordUnwoundPc() names the difference in one place. x86_64 behaviour is
unchanged; the distinction disappears once the helpers agree on a contract.

Reported by Codex review on #813.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(profiling): realign walkVM's DWARF step with walkDwarf's

The two copies of this unwind step have drifted. Each gap is taken from
walkDwarf, which is the one that got the attention:

  - The link register was fed to findFrameDesc unstripped. On aarch64 it
    carries PAC bits, so the lookup address is nonsense. walkDwarf strips it
    and says why; this side never picked that up. Only reachable through a
    frame table carrying DW_LINK_REGISTER, which DwarfParser does not emit
    and SFrameParser does, so it is latent rather than live today.

  - The frame-pointer slot was dereferenced without checking its alignment,
    while the pc slot three lines below is checked. Same load, same exposure.

  - Neither slot load carried a fault-injection hook, so the recovery path
    around them went unexercised. LIKELY matches the existing convention:
    walkVM's seven UNLIKELY sites are raw dereferences, these two go through
    SafeAccess.

Reconciling these first keeps the extraction that follows a pure move, with
no behaviour hidden inside it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(profiling): drive walkVM end to end without a JVM

walkVM read its VMThread through JVMThread::current(), which asserts its
thread-local key is live -- something only a JVM attach sets up. Nothing below
that line needs the thread on the native path, and every use of it is already
NULL-guarded, so it now asks whether one exists instead of requiring it. With a
JVM attached the answer is always yes and nothing changes; without one the walk
takes the same degraded path it would on an unattached thread, and
WALKVM_NO_VMTHREAD still records that it did.

That is the whole of what stood between walkVM and a unit test. VMStructs stays
uninitialised, so CodeHeap::contains() is false for every address and the walk
goes down the native branch on every frame -- which is the branch the
attribution work touches.

The test plants one synthetic linked frame so the walk steps off an exact
ucontext leaf onto a caller whose pc comes out of a return-address slot. Both
land on the same zero-gap boundary, so they must resolve to different functions
purely because of that difference. Mutating the DWARF recovery to claim its pc
is exact fails it, reporting the following function where the caller belongs.

Two platform details the fixture has to respect, both found the hard way:
uc_mcontext is a pointer on Darwin and embedded on Linux, so a zeroed
ucontext_t needs storage to point at or the first register access faults in a
loop behind the profiler's own SIGSEGV handler; and the frame layout has to
come from FrameDesc::default_frame, which is what a table-less CodeCache
returns, not fallback_default_frame(), which differs from it on Apple aarch64.

This covers the DWARF recovery path only. The saved-pc slots in the compiled
and stub arms sit behind CodeHeap::contains() and stay unreachable here.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(profiling): reconcile the last two divergences in walkVM's DWARF step

61959b0 reconciled three gaps between walkVM's copy of the DWARF unwind
step and walkDwarf's, all of them in the pc/fp recovery half. A mechanical
diff of the two bodies shows the CFA half still diverges in two places, and
unlike the earlier three these resolve in opposite directions -- so the
extraction that follows could not have been the pure move that commit
claimed it was setting up.

walkVM falls through on a CFA register it does not implement.

walkDwarf ends its cfa_reg chain with an else that stops the walk. walkVM
instead pre-screened DW_REG_INVALID and anything past DW_REG_PLT, then ran
the same three arms with no else. With DW_REG_FP 6, DW_REG_SP 7 and
DW_REG_PLT 128 on x86_64, a register in 0..5 or 8..127 matches no arm and is
not rejected: sp keeps the value it had on entry to the step, and the walk
reads the caller's pc and fp out of the current frame's own slots.

It is reachable from ordinary DWARF. DwarfParser takes the register straight
off the wire under DW_CFA_def_cfa, _def_cfa_register and _def_cfa_sf, and
addRecord() only rejects it above 0xFF, so nothing narrows it to the three
the walkers implement -- a function whose CFA is based on any other register
lands in the hole. WalkVmAlsoStopsOnAnUnhandledCfaRegister plants exactly
that row and shows walkVM recording a second frame off an unmoved sp where
walkDwarf stops at the leaf.

walkVM's pre-screen is subsumed by the new else and goes away with it; every
value it rejected now falls out of the same arm as the rest.

walkDwarf trusts a frame pointer walkVM checks.

The other direction: walkVM sanity-checks fp for bounds and alignment before
deriving a CFA from it, walkDwarf did not. A misaligned fp whose row offset
re-aligns the result slips past every later test, all of which look at sp,
so only a check on fp itself stops it. 61959b0's rule was that each gap is
taken from walkDwarf; this one goes the other way, and the comment travels
with the code so the reason is not lost.

Both changes are gated, each verified to fail with its fix reverted:

  WalkDwarfStopsOnAnUnhandledCfaRegister      baseline, passes throughout
  WalkVmAlsoStopsOnAnUnhandledCfaRegister     gates the else
  WalkDwarfRejectsAMisalignedFramePointer     gates the fp check

Two properties of the fixture are load-bearing and commented as such:
DW_PC_OFFSET is 1, so fp_off must be even or the step takes the DW_OP_breg
arithmetic branch instead of the memory-slot one under test; and cfa_off must
be non-zero or the aarch64 defaultSenderSP() branch fires. A DW_REG_INVALID
row above each planted leaf stops whichever walker does step past it, so a
failure reports a wrong depth rather than running into unplanted memory.

With this the two bodies differ only in where attribution_pc is declared and
in walkVM's prev_native_walk_pc/have_prev_native_pc bookkeeping, which stays
at the call site. advanceDwarfFrame() can now be extracted as a pure move.

Full native suite green on linux-x64 in debug and release, and this binary
green in all four configurations. That is also the first Linux run of the
walkVM fixtures, which had only been exercised on macOS/arm64.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(profiling): extract the shared DWARF step into advanceDwarfFrame

walkDwarf and walkVM carried two copies of the same unwind step. 61959b0
and 06ab5b6 reconciled the five differences between them; this moves what
is left into one always_inline helper in dwarfStep.inline.h and calls it from
both. 183 lines of duplication become 10.

always_inline is load-bearing, not an optimisation. AddressSanitizer
instruments per function after inlining, so an inlined body takes its
caller's sanitizer attribute. walkVM is no_sanitize("address") because it
reads arbitrary stack memory while sampling; walkDwarf is deliberately
instrumented, and both have been that way since before the two were split
apart in #451. Out of line, one attribute would have to serve both -- either
dropping walkDwarf's instrumentation or adding to walkVM the instrumentation
the attribute exists to avoid. Measured on the built objects rather than
assumed: with always_inline the helper emits no out-of-line symbol at all,
walkVM still contains zero __asan references and walkDwarf still contains
its own.

What moved and what did not:

  - Both callers keep their own `bottom`, computed from their own frame, and
    pass it in.
  - `depth` is a parameter because the two callers disagree on it. walkVM's
    fp-chain fallback reaches the step through `goto dwarf_unwind`, which
    skips its fillFrame(frames[depth++], ...), so on that path it arrives one
    lower than walkDwarf does at the same logical position. Passing it
    through is what keeps this a move rather than a merge; the header says so
    at the parameter.
  - The lookup goes inside, so the helper takes Profiler* rather than the
    CodeCache* the ticket sketched: the DW_REG_PLT arm needs attribution_pc
    to decide the stub offset, so a caller-side lookup would have to
    recompute walk_pc.attribution() anyway.
  - walkVM's prev_native_walk_pc/have_prev_native_pc bookkeeping stays at the
    call site, hoisted to just above the call from the middle of the step.
    Nothing between those two points mutates walk_pc, and a stop leaves the
    loop, so the only reader -- the MARK_THREAD_ENTRY check on the next
    iteration -- cannot tell the difference.

Each of the nine break sites becomes a `return false`; the count was checked
mechanically before and after rather than by eye, since four of them sit on
arms no test in the suite reaches.

Equivalence was checked against the disassembly, not only the tests.
walkDwarf's call sequence is identical instruction-for-instruction in
release; walkVM's call multiset is identical with one static-guard pair
reordered. Neither is byte-identical -- inlining a function changes what the
scheduler and register allocator see, so release moves 313 -> 308
instructions in walkDwarf and 2997 -> 3061 in walkVM. The sanitizer configs
compile at -O0, where the helper's parameters and its FrameDesc copy
materialise as real stack traffic, so walkDwarf grows there (1020 -> 1173
instructions, 9 -> 25 instrumented accesses). Those configs are test-only;
the shipped release build is the one above.

Full native suite green on linux-x64 in debug and release, and the three
binaries over this code green under ASan and TSan.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* THROWAWAY: run walkVmAttribution_ut directly on aarch64 to see which test fails

Revert before merge. Diagnostic only, no product change.

gtestDebug_walkVmAttribution_ut fails on every aarch64 cell and has since
66eea0c, while amd64 is green in every configuration. Which assertion
fails is not recoverable from the logs: the Gradle daemon swallows the test
binary's stdout, so the job reports only the task name. .gitlab/sanitizer-tests
already works around this by using Gradle for compile+link and then running
each binary straight from the shell; this does the same for one binary on the
glibc-aarch64 job.

Placed before the Test step, which would otherwise fail the job first, and
marked continue-on-error so it can only add output.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(test): stop the walkVM fixture terminating its chain with a zero fp

CallerFrameFromReturnSlotAttributesToTheCaller failed on every Linux/aarch64
cell since it was added, returning depth 1 where it expects 2. It passes on
Apple aarch64 and on x86_64, which is why it went in green.

plantCallerFrame ended the chain by storing 0 into the caller's frame-pointer
slot, on the reasoning that an unwalkable fp stops the walk. On Linux/aarch64
that stops it one frame too early. There default_frame carries cfa_off == 0
and EMPTY_FRAME_SIZE is 0, so the step ends in

    sp = defaultSenderSP(sp, fp)

and defaultSenderSP returns fp on Linux, where it returns sp + 16 on Apple.
The planted zero therefore becomes a zero sp, which trips the `sp < prev_sp`
check inside the very step that had just recovered the caller's pc -- so the
walk stops before the caller frame is recorded and the pc the test exists to
check never reaches the chain. Apple aarch64 never reads fp there, and on
x86_64 EMPTY_FRAME_SIZE > 0 keeps that branch out of the path entirely.

The fixture now points the slot at a higher, still-plausible slot in the same
scratch buffer and lets the frame above terminate the walk on its own zeroed
pc -- a dead-zone stop on x86_64, the same sp check on aarch64, in both cases
one frame later than before, which is where the assertion wants it.

This is the third platform asymmetry this fixture has hit, after the
uc_mcontext pointer-vs-value split and default_frame vs
fallback_default_frame. The comment says which branch fires where, since
none of them are visible from the test body.

Verified on x86_64 (7/7 in debug and release) and by simulating the aarch64
step arithmetic against its own constants: the old fixture reproduces the
observed depth 1, the new one gives depth 2. The aarch64 run itself arrives
with the pipeline.

Also reverts a1a4480, the throwaway CI step that produced the gtest output
this was diagnosed from -- the Gradle daemon swallows the binary's stdout, so
the job had only ever reported the task name. Worth noting for next time:
.gitlab/sanitizer-tests already runs its binaries straight from the shell for
exactly this reason, and those jobs are where a gtest failure is legible.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(profiling): read the null-ucontext seed in walkVM's own frame

callerPC/callerSP/callerFP are __builtin_return_address and
__builtin_frame_address underneath, so they describe whichever frame evaluates
them. Folding them into a seed helper moved that frame: wherever the helper is
not inlined -- debug and sanitizer builds, which is where it matters -- the
walk started one frame too deep, inside the profiler. A malloc or socket
sample then spends depth on a profiler frame before reaching the
MARK_JAVA_PROFILER boundary, and a shallow one can run out before it gets
there and record nothing useful.

The wrapper reads them inline again, as it did before the seed struct, with
the reason written down so the next person tidying this does not repeat it.
Nothing else needed the struct once the two branches were back in place.

Also drops an if-initializer whose continuation line sat well out of step with
the surrounding indentation; a plain else block reads the same and looks like
the rest of the function.

Reported by Codex and Datadog review on #813.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Jaroslav Bachorik <jaroslav.bachorik@datadoghq.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fixed_version: v_1.41.0 Version this PR's fix shipped in

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants