diff --git a/.knowledgebase/memories/find-estimator-rss-conflation-executed.md b/.knowledgebase/memories/find-estimator-rss-conflation-executed.md new file mode 100644 index 0000000000..c92ea2545d --- /dev/null +++ b/.knowledgebase/memories/find-estimator-rss-conflation-executed.md @@ -0,0 +1,19 @@ +--- +id: find-estimator-rss-conflation-executed +title: per-object allocation estimates cannot gate attributable RSS - same estimate, 2x measured residency +kind: finding +tags: [malloc, rss, estimator, mallocfootprint, memory-gate] +applies_to: [ddprof-lib/src/main/cpp/mallocFootprint.h] +source: native-safety-hypothesis-loop/find-estimator-rss-conflation-executed +status: active +recorded: 2026-11-11 +valid_at: 2026-11-11 +--- + + +With the requested/usable estimates held fixed, measured residency at 8192 B +differs by 2x between glibc and musl while `MallocFootprint` returns identical +values for both: the estimator is blind to occupancy and touching. Any memory +gate must state its accounting target - per-object allocator accounting (usable +size plus the probed header) for allocation cost, residency measurements for +attributable memory - and never equate the two. diff --git a/.knowledgebase/memories/find-flake-rule-operationalized.md b/.knowledgebase/memories/find-flake-rule-operationalized.md new file mode 100644 index 0000000000..61b7c7f2b1 --- /dev/null +++ b/.knowledgebase/memories/find-flake-rule-operationalized.md @@ -0,0 +1,19 @@ +--- +id: find-flake-rule-operationalized +title: a single failing gtest run under load is not a catch - require a standalone failure or a majority of repetitions +kind: finding +tags: [testing, flake, gtest, load, ci] +applies_to: [] +source: native-safety-hypothesis-loop/find-flake-rule-operationalized +status: active +recorded: 2026-11-11 +valid_at: 2026-11-11 +--- + + +A clean-source binary fails the same canary gtest in 1 of 12 contended runs - +mutation-independent flake exists at the suite layer. Before treating a native +test failure as a catch, require a standalone (out-of-suite) failure or at +least 2 of 3 in-Gradle repetitions; a single in-suite failure under load is +evidence of nothing. The same rule applies to CI gates: a single failing run of +a load-sensitive check should be rerun before being treated as a regression. diff --git a/.knowledgebase/memories/find-glibc-passive-retention-flat.md b/.knowledgebase/memories/find-glibc-passive-retention-flat.md new file mode 100644 index 0000000000..b9f5186c45 --- /dev/null +++ b/.knowledgebase/memories/find-glibc-passive-retention-flat.md @@ -0,0 +1,24 @@ +--- +id: find-glibc-passive-retention-flat +title: no passive glibc signal distinguishes retained from releasable memory - a retention check needs an actual release step +kind: finding +tags: [glibc, malloc, retention, rss, smaps, memory-gate, testing] +applies_to: [.gitlab/reliability/memory_trend_check.sh] +source: native-safety-hypothesis-loop/find-glibc-passive-retention-flat +status: active +recorded: 2026-11-11 +valid_at: 2026-11-11 +--- + + +Pre-release RSS, mincore and `smaps` `Private_Dirty` stay within 0.2 percent +across the whole allocation-pattern matrix on glibc 2.35 and 2.39 at equal live +bytes, and a field-by-field sweep of every `smaps` field (both libcs, to 0.1 +percent) is equally flat: `MADV_DONTNEED` zeroes everything and `MADV_FREE` +moves `LazyFree` only after a real release. There is no passive glibc signal +that separates retained from releasable memory, so any gate must exercise the +release itself - a harness-issued `malloc_trim`/`madvise` from outside the +profiler, with RSS recorded before and after. musl post-free RSS does +discriminate. The mallinfo2-stall side of the original finding is glibc-version +dependent (no stall on 2.35, 3-17 ms stalls on 2.39); treat any mallinfo2 timing +claim as version-scoped. diff --git a/.knowledgebase/memories/find-paired-traces-adjudicate-r1-cost-confound.md b/.knowledgebase/memories/find-paired-traces-adjudicate-r1-cost-confound.md new file mode 100644 index 0000000000..c18b751ca3 --- /dev/null +++ b/.knowledgebase/memories/find-paired-traces-adjudicate-r1-cost-confound.md @@ -0,0 +1,24 @@ +--- +id: find-paired-traces-adjudicate-r1-cost-confound +title: cost deltas need paired same-window replays of one prerecorded trace - block-ordered estimates only work under small measured drift +kind: finding +tags: [benchmark, estimator, paired, drift, cost, testing] +applies_to: [] +source: native-safety-hypothesis-loop/find-paired-traces-adjudicate-r1-cost-confound +status: active +recorded: 2026-11-11 +valid_at: 2026-11-11 +--- + + +Replaying one prerecorded trace identically in every measured mode with matched +bookkeeping and AB/BA pair-order randomization makes per-mode deltas paired +causal estimates: the A-A noise floor stays non-significant even though absolute +medians drift ~30 percent within a single run, so the pairing carries the +signal. Unpaired before/after medians cannot resolve effects at or below +roughly 10 ns/op. A block-ordered unpaired estimate deviates from the paired +estimate by exactly the within-window drift it fails to cancel - the deviation +tracks the measured drift slope (r=+0.902, permutation p=0.0001) and reaches +±13 ns under heavy drift - so block ordering is adequate only when drift is +measured small, never assumed. Report the paired median with a seeded bootstrap +confidence interval, an exact sign test, and the A-A noise floor. diff --git a/.knowledgebase/memories/find-r6-stall-was-load-confounded.md b/.knowledgebase/memories/find-r6-stall-was-load-confounded.md new file mode 100644 index 0000000000..2927282d3c --- /dev/null +++ b/.knowledgebase/memories/find-r6-stall-was-load-confounded.md @@ -0,0 +1,20 @@ +--- +id: find-r6-stall-was-load-confounded +title: stall and latency verdicts are confounded by host load - record load markers with every timing verdict +kind: finding +tags: [load, psi, stall, testing, benchmark] +applies_to: [] +source: native-safety-hypothesis-loop/find-r6-stall-was-load-confounded +status: active +recorded: 2026-11-11 +valid_at: 2026-11-11 +--- + + +The mallinfo2 stall signature reproduced under pure CPU-spinner containers with +zero allocator activity, and idle repetitions of the same cell showed no stall: +cross-container load is a first-class confound for throughput and stall +comparisons on shared hosts. Timing-based verdicts need recorded load markers +(PSI, loadavg, cgroup throttling), and a loaded run must not pass or fail on +the load - it reports inconclusive or is rerun. Markers must be passive reads of +procfs/sysfs, never instrumentation inside the measured process. diff --git a/.knowledgebase/memories/find-rss-verdict-load-gating-by-mechanism.md b/.knowledgebase/memories/find-rss-verdict-load-gating-by-mechanism.md new file mode 100644 index 0000000000..64a1ed5cc3 --- /dev/null +++ b/.knowledgebase/memories/find-rss-verdict-load-gating-by-mechanism.md @@ -0,0 +1,23 @@ +--- +id: find-rss-verdict-load-gating-by-mechanism +title: gate load-sensitive verdicts on the load signal that actually distorts the measured quantity, not on host busyness +kind: finding +tags: [psi, load, rss, memory-gate, verdict, ci] +applies_to: [.gitlab/reliability/memory_trend_check.py] +source: native-safety-hypothesis-loop/find-r6-stall-was-load-confounded +status: active +recorded: 2026-11-11 +valid_at: 2026-11-11 +--- + + +A load bound calibrated on one host population silently breaks on another: a +CPU-pressure (psi cpu some avg10) bound set from an idle single VM (idle 0.0-0.2, +loaded 45-90) sat inside the normal operating band of shared CI hosts (observed +medians 11.7-40.3, 2026-11-10), turning every row of a memory gate inconclusive. +Choose gating signals by distortion mechanism: scheduler contention shapes +latency/stall verdicts but not RSS trends; memory pressure (reclaim) and cgroup +throttling of the measured workload do alter RSS. Record the non-gating signals +anyway - they explain verdicts later - and mark every bound provisional with +its observed basis, changing it only with recorded-run evidence and engineer +sign-off, never to make one run pass. diff --git a/.knowledgebase/memories/find-s0-band-mapping-is-probe-induced.md b/.knowledgebase/memories/find-s0-band-mapping-is-probe-induced.md new file mode 100644 index 0000000000..05ab58d7ab --- /dev/null +++ b/.knowledgebase/memories/find-s0-band-mapping-is-probe-induced.md @@ -0,0 +1,19 @@ +--- +id: find-s0-band-mapping-is-probe-induced +title: measurement probes perturb what they measure - record markers passively and snapshot before instrumenting +kind: finding +tags: [measurement, probe, mmap, testing, benchmark] +applies_to: [] +source: native-safety-hypothesis-loop/find-s0-band-mapping-is-probe-induced +status: active +recorded: 2026-11-11 +valid_at: 2026-11-11 +--- + + +A band mapping attributed to allocator/kernel behavior appeared only after the +probe wrote its own marker file: the instrumentation's footprint created the +effect it measured. Placement and mapping experiments need a pre-instrumentation +snapshot (4/4 rows showed the effect absent at S0, present at S1), and load +markers must be passive reads of procfs/sysfs - never writes into, code +execution inside, or attaches to the measured process. diff --git a/.knowledgebase/memories/find-window-quota-cfs-shape.md b/.knowledgebase/memories/find-window-quota-cfs-shape.md new file mode 100644 index 0000000000..bcab0cd7c3 --- /dev/null +++ b/.knowledgebase/memories/find-window-quota-cfs-shape.md @@ -0,0 +1,20 @@ +--- +id: find-window-quota-cfs-shape +title: measurement windows under CPU quota must span several CFS periods or the delivered-share reading aliases +kind: finding +tags: [cfs, quota, window, benchmark, load, testing] +applies_to: [] +source: native-safety-hypothesis-loop/find-window-quota-cfs-shape +status: active +recorded: 2026-11-11 +valid_at: 2026-11-11 +--- + + +At a binding CPU quota, CFS delivers CPU in period quanta: windows shorter than +a few periods alias a variable number of quanta and scatter the apparent +delivered share (observed ratio medians 0.73 down to 0.38 as the window grew +from 99 ms to 999 ms), while windows spanning at least 3 periods converge to the +quota share. Any quota- or stall-ratio comparison needs window-length control +aligned to CFS periods, and sampling cadences (e.g. a 5 s memory sampler) sit +far above this aliasing regime. diff --git a/ddprof-lib/src/main/cpp/hotspot/nmethodMethodCheck.cpp b/ddprof-lib/src/main/cpp/hotspot/nmethodMethodCheck.cpp new file mode 100644 index 0000000000..929171d540 --- /dev/null +++ b/ddprof-lib/src/main/cpp/hotspot/nmethodMethodCheck.cpp @@ -0,0 +1,258 @@ +/* + * Copyright 2026, Datadog, Inc. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "nmethodMethodCheck.h" + +#include "hotspot/vmStructs.inline.h" +#include "threadLocalData.h" + +#include + +static constexpr int MAX_READS = 16; + +struct ReadContext { + jmethodID target; + // Slots are claimed with a fetch_add on count. live counts each poster + // from just before its claim to just after its last write, so the + // counters can only be reset for a new batch once no poster can still + // reach a slot. + int count; + int live; + jlong reads[MAX_READS * 3]; +}; + +// Static storage: JVMTI's disable does not join a post that entered before +// it, so a stalled poster can still write after readsForTest returns; every +// such write lands in this buffer at a bounded slot instead of dead stack. +// Single caller (the test child's main thread); concurrent readsForTest +// calls are not supported. +static ReadContext readContext; + +// Disposes the JVMTI environment on every exit path, including the early +// returns after a failed JVMTI call. +class JvmtiEnvOwner { + public: + explicit JvmtiEnvOwner(jvmtiEnv* env) : _env(env) {} + ~JvmtiEnvOwner() { + if (_env != nullptr) { + _env->DisposeEnvironment(); + } + } + JvmtiEnvOwner(const JvmtiEnvOwner&) = delete; + JvmtiEnvOwner& operator=(const JvmtiEnvOwner&) = delete; + + private: + jvmtiEnv* _env; +}; + +static void throwIllegalState(JNIEnv* jni, const char* what) { + jclass ex = jni->FindClass("java/lang/IllegalStateException"); + if (ex != nullptr) { + jni->ThrowNew(ex, what); + } +} + +static void JNICALL onCompiledMethodLoad(jvmtiEnv* jvmti, jmethodID method, jint code_size, + const void* code_addr, jint map_length, + const jvmtiAddrLocationMap* map, const void* compile_info) { + // Never touches the env after entry: a post that survives past the + // env's disposal must not call back into freed JVMTI state. + ReadContext* ctx = &readContext; + // Acquire pairs with readsForTest's release store of target, so a + // poster that entered the callback sees the current call's target. + if (method != __atomic_load_n(&ctx->target, __ATOMIC_ACQUIRE)) { + return; + } + + // The callback can land on a compiler or ServiceThread that never went + // through the profiler's thread hooks; the code-heap read below needs + // the profiler TLS those threads otherwise lack. Events filtered out by + // the target compare above return without touching VM structures, so + // they skip the initialization cost. The initialization itself must stay + // before the live claim: it can allocate on first use for a thread, and + // a poster holding a live slot while doing it could outlast the reader's + // bounded drain wait and get its batch discarded. + ProfiledThread::initCurrentThreadSignalSafe(); + + // The live claim precedes the slot claim so the reader's live == 0 drain + // also waits out slot writes. The claim is a CAS, not an increment: an + // increment landing on the reset sentinel would heal it to a transient 0 + // and let the next poster register into a window the reader still owns, + // which the reader's live = 0 release would then clobber. A poster that + // sees live < 0 backs off without modifying live. + int live = __atomic_load_n(&ctx->live, __ATOMIC_ACQUIRE); + do { + if (live < 0) { + return; + } + } while (!__atomic_compare_exchange_n(&ctx->live, &live, live + 1, true, + __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)); + + // While the event is enabled, the ServiceThread can also post to this env + // for a compile on another thread; the atomic claim with rollback keeps + // concurrent posters on distinct, bounded slots. The claim must be a + // RELEASE RMW: readsForTest snapshots count with an acquire load, and a + // relaxed increment publishes no prior writes, so that snapshot could + // observe the claim without the preceding live registration (arm64 is + // weakly ordered) — the reader would then pass its live == 0 drain wait + // and copy the slot while this poster is still writing it. The count + // rollback below stays relaxed: it publishes nothing, and its RMW reads + // the claim's own written value, keeping it in the claim's release + // sequence. The live decrements stay release: the drain wait pairs its + // acquire loads of live with them. + int slot = __atomic_fetch_add(&ctx->count, 1, __ATOMIC_RELEASE); + if (slot < 0) { + // A rollback racing the reset's store of count can drive it negative: + // such a slot was never claimed, so it must be neither written nor + // rolled back (a rollback would push count lower still). + __atomic_fetch_sub(&ctx->live, 1, __ATOMIC_RELEASE); + return; + } + if (slot >= MAX_READS) { + __atomic_fetch_sub(&ctx->count, 1, __ATOMIC_RELAXED); + __atomic_fetch_sub(&ctx->live, 1, __ATOMIC_RELEASE); + return; + } + + VMNMethod* nm = CodeHeap::findNMethod(code_addr); + jlong status = 1; + jlong read = 0; + if (nm != nullptr && nm->isNMethod()) { + // The raw id(): nullptr and JMETHODID_NOT_WALKABLE are reported as-is, + // the caller distinguishes them from a real jmethodID. + VMMethod* m = nm->method(); + status = 0; + read = m == nullptr ? 0 : reinterpret_cast(m->id()); + } + ctx->reads[slot * 3] = reinterpret_cast(code_addr); + ctx->reads[slot * 3 + 1] = status; + ctx->reads[slot * 3 + 2] = read; + // Release publishes the writes above to the reset and to the reader that + // acquires live. + __atomic_fetch_sub(&ctx->live, 1, __ATOMIC_RELEASE); +} + +// For CI only: NMethodMethodJvmtiValidationTest compares this with JVMTI's +// CompiledMethodLoad. +jlongArray NMethodMethodCheck::readsForTest(JNIEnv* jni, jobject method) { + if (!CodeHeap::available()) { + return nullptr; + } + + jmethodID target = jni->FromReflectedMethod(method); + if (target == nullptr) { + jclass ex = jni->FindClass("java/lang/IllegalArgumentException"); + if (ex != nullptr) { + jni->ThrowNew(ex, "compiledMethodReadsForTest: not a Method object"); + } + return nullptr; + } + + JavaVM* vm = nullptr; + if (jni->GetJavaVM(&vm) != JNI_OK) { + throwIllegalState(jni, "compiledMethodReadsForTest: GetJavaVM failed"); + return nullptr; + } + jvmtiEnv* jvmti = nullptr; + if (vm->GetEnv(reinterpret_cast(&jvmti), JVMTI_VERSION_1_0) != JNI_OK || jvmti == nullptr) { + throwIllegalState(jni, "compiledMethodReadsForTest: GetEnv failed"); + return nullptr; + } + JvmtiEnvOwner owner(jvmti); + + jvmtiCapabilities capabilities = {0}; + capabilities.can_generate_compiled_method_load_events = 1; + if (jvmti->AddCapabilities(&capabilities) != JVMTI_ERROR_NONE) { + throwIllegalState(jni, "compiledMethodReadsForTest: AddCapabilities failed"); + return nullptr; + } + + jvmtiEventCallbacks callbacks = {0}; + callbacks.CompiledMethodLoad = onCompiledMethodLoad; + if (jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)) != JVMTI_ERROR_NONE) { + throwIllegalState(jni, "compiledMethodReadsForTest: SetEventCallbacks failed"); + return nullptr; + } + + __atomic_store_n(&readContext.target, target, __ATOMIC_RELEASE); + // Slots are reused only once no poster can still reach them: the CAS + // claims the reset exclusively, a poster racing in backs off on the + // negative live without modifying it, and a call that finds survivors + // keeps claiming fresh slots past the undrained ones instead of reusing + // theirs. The release store below therefore cannot clobber a registration. + int live = __atomic_load_n(&readContext.live, __ATOMIC_ACQUIRE); + if (live == 0 && __atomic_compare_exchange_n(&readContext.live, &live, -1, false, + __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) { + __atomic_store_n(&readContext.count, 0, __ATOMIC_RELAXED); + __atomic_store_n(&readContext.live, 0, __ATOMIC_RELEASE); + } + // The batch owns the claims from here to the next reset; slots below the + // base belong to an earlier batch whose poster may still be writing. + int base = __atomic_load_n(&readContext.count, __ATOMIC_ACQUIRE); + // The slot<0 back-off leaves count at -1 until the next claim heals it; + // clamp so a transient negative count cannot reach the copy below. + if (base < 0) { + base = 0; + } else if (base > MAX_READS) { + base = MAX_READS; + } + + // HotSpot queues these events only while some env has them enabled, and + // posts them per env: enabled here only around GenerateEvents and disabled + // before returning; async posts in that window race the ctx (atomic slot). + if (jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, nullptr) != JVMTI_ERROR_NONE) { + throwIllegalState(jni, "compiledMethodReadsForTest: SetEventNotificationMode enable failed"); + return nullptr; + } + jvmtiError err = jvmti->GenerateEvents(JVMTI_EVENT_COMPILED_METHOD_LOAD); + // Disable before the result is built and the env disposed, so late + // ServiceThread posts cannot reach this env after the seam returns. + if (jvmti->SetEventNotificationMode(JVMTI_DISABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, nullptr) != JVMTI_ERROR_NONE) { + throwIllegalState(jni, "compiledMethodReadsForTest: SetEventNotificationMode disable failed"); + return nullptr; + } + if (err != JVMTI_ERROR_NONE) { + throwIllegalState(jni, "compiledMethodReadsForTest: GenerateEvents failed"); + return nullptr; + } + + // JVMTI's disable does not join a post that entered before it: the + // callback can still be claiming a slot. Snapshot the batch's claim bound + // first, so a poster claiming afterwards lands outside the copied range, + // then wait for every live poster to finish before reading the slots. + int claimed = __atomic_load_n(&readContext.count, __ATOMIC_ACQUIRE) - base; + int spin = 0; + while (spin < 1000000 && __atomic_load_n(&readContext.live, __ATOMIC_ACQUIRE) != 0) { + spin++; + } + // A completion bound does not identify a completed prefix: a timeout + // leaves a claimed slot unfinished, so discard the batch and let the + // caller retry instead of copying a slot that can still be written. + if (__atomic_load_n(&readContext.live, __ATOMIC_ACQUIRE) != 0) { + claimed = 0; + } else if (claimed < 0) { + claimed = 0; + } else if (claimed > MAX_READS - base) { + // Claims past the capacity rolled back and never wrote a slot. + claimed = MAX_READS - base; + } + + jlongArray result = jni->NewLongArray(1 + claimed * 3); + if (result == nullptr) { + // A null here means NewLongArray failed (pending OutOfMemoryError), not + // "seam unavailable": the Java caller's null handling treats null as a + // permanent unsupported case, so the transient OOM must surface as an + // exception instead, or the validation test would silently skip. + jni->ExceptionClear(); + throwIllegalState(jni, "compiledMethodReadsForTest: NewLongArray failed"); + return nullptr; + } + jlong targetValue = reinterpret_cast(target); + jni->SetLongArrayRegion(result, 0, 1, &targetValue); + if (claimed > 0) { + jni->SetLongArrayRegion(result, 1, claimed * 3, readContext.reads + base * 3); + } + return result; +} diff --git a/ddprof-lib/src/main/cpp/hotspot/nmethodMethodCheck.h b/ddprof-lib/src/main/cpp/hotspot/nmethodMethodCheck.h new file mode 100644 index 0000000000..0d3d35a130 --- /dev/null +++ b/ddprof-lib/src/main/cpp/hotspot/nmethodMethodCheck.h @@ -0,0 +1,24 @@ +/* + * Copyright 2026, Datadog, Inc. + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef _HOTSPOT_NMETHOD_METHOD_CHECK_H +#define _HOTSPOT_NMETHOD_METHOD_CHECK_H + +#include + +// Reads, for each compiled body of `method` that JVMTI reports, the values the +// profiler obtains through its own vmStructs offsets: the JVMTI code address, +// whether the code-heap lookup found an nmethod (0) or not (1), and the +// jmethodID read from the nmethod's _method field. The result holds the +// target's jmethodID at index 0, then up to 16 (code_addr, status, read) +// triples. Returns nullptr when the profiler has no code heap; throws +// IllegalArgumentException when `method` is not a Method object and +// IllegalStateException when a JVMTI call fails. +class NMethodMethodCheck { + public: + static jlongArray readsForTest(JNIEnv* jni, jobject method); +}; + +#endif // _HOTSPOT_NMETHOD_METHOD_CHECK_H diff --git a/ddprof-lib/src/main/cpp/javaApi.cpp b/ddprof-lib/src/main/cpp/javaApi.cpp index b2605d22d9..0689c6df37 100644 --- a/ddprof-lib/src/main/cpp/javaApi.cpp +++ b/ddprof-lib/src/main/cpp/javaApi.cpp @@ -1113,6 +1113,17 @@ Java_com_datadoghq_profiler_JavaProfiler_dumpContext(JNIEnv* env, jclass unused) #include "referenceChains.h" #include +// The seam mutates global JVMTI state (a fresh JVMTI environment per call, +// AddCapabilities, a CompiledMethodLoad callback over the shared ReadContext, +// JVM-wide enable/disable of CompiledMethodLoad), so like the seams below it +// is DEBUG-only; release builds get a null-returning stub. +extern "C" DLLEXPORT jlongArray JNICALL +Java_com_datadoghq_profiler_JavaProfiler_compiledMethodReadsForTest0( + JNIEnv* env, jclass unused, jobject method) { + ProfiledThread::initCurrentThreadSignalSafe(); + return JVMSupport::compiledMethodReadsForTest(env, method); +} + extern "C" DLLEXPORT jboolean JNICALL Java_com_datadoghq_profiler_JavaProfiler_setGcGenerationsEnabled0( JNIEnv *env, jclass unused, jboolean enabled) { @@ -1551,6 +1562,12 @@ Java_com_datadoghq_profiler_JavaProfiler_setGcGenerationsEnabled0( return JNI_FALSE; } +extern "C" DLLEXPORT jlongArray JNICALL +Java_com_datadoghq_profiler_JavaProfiler_compiledMethodReadsForTest0( + JNIEnv *env, jclass unused, jobject method) { + return nullptr; +} + extern "C" DLLEXPORT void JNICALL Java_com_datadoghq_profiler_JavaProfiler_seedKlassPopulationSample0( JNIEnv *env, jclass unused, jint klassId, jint count, jlong epoch) {} diff --git a/ddprof-lib/src/main/cpp/jvmSupport.cpp b/ddprof-lib/src/main/cpp/jvmSupport.cpp index 49f983f7a6..0cf08a226d 100644 --- a/ddprof-lib/src/main/cpp/jvmSupport.cpp +++ b/ddprof-lib/src/main/cpp/jvmSupport.cpp @@ -16,6 +16,7 @@ #include "vmEntry.h" #include "hotspot/hotspotSupport.h" +#include "hotspot/nmethodMethodCheck.h" #include @@ -252,3 +253,7 @@ bool JVMSupport::loadMethodIDsImpl(jvmtiEnv *jvmti, JNIEnv *jni, jclass klass) { } return false; } + +jlongArray JVMSupport::compiledMethodReadsForTest(JNIEnv* jni, jobject method) { + return VM::isHotspot() ? NMethodMethodCheck::readsForTest(jni, method) : nullptr; +} diff --git a/ddprof-lib/src/main/cpp/jvmSupport.h b/ddprof-lib/src/main/cpp/jvmSupport.h index 52df6a7e58..abeb04ac70 100644 --- a/ddprof-lib/src/main/cpp/jvmSupport.h +++ b/ddprof-lib/src/main/cpp/jvmSupport.h @@ -99,6 +99,10 @@ class JVMSupport { // If a class is hidden class static inline bool isHidden(jint modifiers); + + // Test seam: reads nmethod->_method for `method`'s compiled bodies; + // HotSpot only, nullptr elsewhere. + static jlongArray compiledMethodReadsForTest(JNIEnv* jni, jobject method); }; #endif // _JVMSUPPORT_H diff --git a/ddprof-lib/src/main/cpp/linearAllocator.cpp b/ddprof-lib/src/main/cpp/linearAllocator.cpp index 22ea167068..8eeb9e3153 100644 --- a/ddprof-lib/src/main/cpp/linearAllocator.cpp +++ b/ddprof-lib/src/main/cpp/linearAllocator.cpp @@ -20,6 +20,7 @@ #include "nativeMem.h" #include "os.h" #include "common.h" +#include #include #ifdef TSAN_ENABLED #include @@ -193,6 +194,20 @@ void LinearAllocator::freeChunks(ChunkList& chunks) { } void *LinearAllocator::alloc(size_t size) { + #ifdef ASAN_ENABLED + // ASan's shadow granularity is 8 bytes: an allocation whose end is not + // 8-aligned leaves its final shadow granule partially addressable, so + // clear()'s poison cannot cover the tail and a stale use-after-clear access + // to the allocation's last bytes goes undetected. Round the bump (and thus + // the unpoison) to the granule; ASan builds only, production layout is + // unchanged. sizeof(Chunk) is 8-aligned and every bump is rounded, so all + // offsets stay 8-aligned and every poisoned range is granule-aligned. + if (size > SIZE_MAX - 7) { + return nullptr; // the rounded bump would wrap; no chunk can hold it + } + size = (size + 7) & ~(size_t)7; + #endif + Chunk *chunk = __atomic_load_n(&_tail, __ATOMIC_ACQUIRE); // CRITICAL FIX: After detachChunks() fails, _tail may be nullptr. @@ -201,6 +216,14 @@ void *LinearAllocator::alloc(size_t size) { return nullptr; } + // The fast-path check adds size to offs: a huge size would wrap the sum + // past SIZE_MAX, make the check pass, and hand out a pointer past the + // chunk's end. offs never exceeds _chunk_size, so rejecting any size above + // the chunk capacity keeps offs + size far below SIZE_MAX. + if (size > (size_t)_chunk_size) { + return nullptr; + } + do { // Fast path: bump a pointer with CAS for (size_t offs = __atomic_load_n(&chunk->offs, __ATOMIC_ACQUIRE); diff --git a/ddprof-lib/src/main/java/com/datadoghq/profiler/JavaProfiler.java b/ddprof-lib/src/main/java/com/datadoghq/profiler/JavaProfiler.java index f0b3f5f428..96988c7aaa 100644 --- a/ddprof-lib/src/main/java/com/datadoghq/profiler/JavaProfiler.java +++ b/ddprof-lib/src/main/java/com/datadoghq/profiler/JavaProfiler.java @@ -592,6 +592,22 @@ private static native void setTraceContext0( */ public static native boolean testTlsPrimingAvailable(); + /** + * Test seam with no production caller. Debug native builds only; a release build returns {@code + * null}. + * + *

On HotSpot, reports, for each compiled body of {@code method} that JVMTI CompiledMethodLoad + * reports: the code address, the code-heap lookup status (0 = nmethod found, 1 = not found), and + * the jmethodID read from that nmethod's {@code _method} field. Element 0 is the target's + * jmethodID, followed by up to 16 (code address, status, read) triples. + * + *

Returns {@code null} when the JVM is not HotSpot, the profiler has no code heap, or the + * native library is a release build; throws {@link IllegalArgumentException} when {@code method} + * is not a {@link java.lang.reflect.Method}, and {@link IllegalStateException} when a JVMTI call + * fails. + */ + static native long[] compiledMethodReadsForTest0(Method method); + /** * Test seam (debug native builds only - a no-op returning {@code false}/{@code 0}/an empty array * in release builds). This and every reference-chain/liveness seam below (plus {@link #getTid()}) diff --git a/ddprof-lib/src/test/cpp/linearAllocator_asan_poison_ut.cpp b/ddprof-lib/src/test/cpp/linearAllocator_asan_poison_ut.cpp new file mode 100644 index 0000000000..de253c5625 --- /dev/null +++ b/ddprof-lib/src/test/cpp/linearAllocator_asan_poison_ut.cpp @@ -0,0 +1,134 @@ +// Copyright 2026, Datadog, Inc. + +#include "common.h" // ASAN_ENABLED (toolchain-agnostic sanitizer detection) + +#include "gtest/gtest.h" +#include "linearAllocator.h" +#include "nativeMem.h" + +#ifdef ASAN_ENABLED +#include + +// The stale-after-clear partial-granule miss: ASan's shadow granularity is 8 +// bytes, so an allocation ending mid-granule leaves its final granule +// partially addressable. clear() then cannot fully poison the tail, and a +// stale access to the allocation's last bytes reads as addressable shadow. +// alloc() rounds every bump to the granule in ASan builds, so every byte of +// every former allocation must read as poisoned after clear(). +// These tests compile only in ASan builds; in other configurations the file +// contributes no tests. + +static const size_t CHUNK_SIZE = 64 * 1024; + +class LinearAllocatorAsanPoisonTest : public ::testing::Test { +protected: + // Static-duration objects elsewhere in the binary record into these same + // categories before main() runs; restore their baseline in TearDown so + // their destructors don't underflow a category this fixture zeroed. + // (Same rationale as LinearAllocatorNativeMemTest in + // linearAllocator_nativemem_ut.cpp.) + long long _baseline[NM_NUM_CATEGORIES]; + + void SetUp() override { + for (int c = 0; c < NM_NUM_CATEGORIES; c++) { + _baseline[c] = NativeMem::live((NativeMemCategory)c); + } + NativeMem::reset(); + } + void TearDown() override { + NativeMem::reset(); + for (int c = 0; c < NM_NUM_CATEGORIES; c++) { + NativeMem::setLive((NativeMemCategory)c, _baseline[c]); + } + } +}; + +TEST_F(LinearAllocatorAsanPoisonTest, StaleTailOfUnalignedAllocationIsPoisonedAfterClear) { + LinearAllocator allocator(CHUNK_SIZE); + // 26 bytes: end offset is not 8-aligned -- the shape that hid stale tails + // before rounding. A separator allocation makes the first chunk's used + // range end mid-granule too. + char *first = (char *)allocator.alloc(26); + char *separator = (char *)allocator.alloc(1); + ASSERT_NE(nullptr, first); + ASSERT_NE(nullptr, separator); + + allocator.clear(); + + EXPECT_TRUE(__asan_address_is_poisoned(first)) + << "the first byte of a former allocation must read as poisoned"; + EXPECT_TRUE(__asan_address_is_poisoned(first + 25)) + << "the last byte of an unaligned allocation must read as poisoned -- " + "the partial-granule shadow tail is closed by granule rounding"; +} + +TEST_F(LinearAllocatorAsanPoisonTest, AllocatedRegionIsAddressableAndAligned) { + LinearAllocator allocator(CHUNK_SIZE); + char *p = (char *)allocator.alloc(26); + ASSERT_NE(nullptr, p); + + // The granule-aligned offset invariant clear()'s whole-granule poison + // relies on: every returned pointer is 8-aligned. + EXPECT_EQ(0, (uintptr_t)p % 8) << "alloc() must hand out 8-aligned pointers in ASan builds"; + + for (size_t i = 0; i < 26; i++) { + EXPECT_FALSE(__asan_address_is_poisoned(p + i)) + << "byte " << i << " of a live allocation must be addressable"; + } + // Write-read proves addressability end to end, not just shadow state. + p[0] = 1; + p[25] = 2; + EXPECT_EQ(1, p[0]); + EXPECT_EQ(2, p[25]); +} + +TEST_F(LinearAllocatorAsanPoisonTest, RoundedAccountingStaysSymmetric) { + // alloc() records the rounded size so the ledger matches the offs-based + // decrements in clear() and freeChunks(). Two 26-byte allocations consume + // 2 * 32 bytes; the accounting must be exact, not approximate. + LinearAllocator allocator(CHUNK_SIZE); + ASSERT_NE(nullptr, allocator.alloc(26)); + ASSERT_NE(nullptr, allocator.alloc(26)); + EXPECT_EQ(64, NativeMem::live(NM_CALLTRACE)) + << "ASan builds count granule-rounded bytes (2 x 26 -> 2 x 32)"; + + ChunkList detached = allocator.detachChunks(); + EXPECT_EQ(64, NativeMem::live(NM_CALLTRACE)) + << "detaching frees nothing"; + LinearAllocator::freeChunks(detached); + EXPECT_EQ(0, NativeMem::live(NM_CALLTRACE)) + << "freeChunks() un-records exactly the rounded bytes alloc() recorded"; +} + +TEST_F(LinearAllocatorAsanPoisonTest, ReuseAfterClearIsUnpoisoned) { + // clear() leaves poison for use-after-clear detection; a fresh allocation + // over the same region must be fully addressable again (no false positive + // on reuse). + LinearAllocator allocator(CHUNK_SIZE); + char *first = (char *)allocator.alloc(26); + ASSERT_NE(nullptr, first); + allocator.clear(); + + char *second = (char *)allocator.alloc(32); + ASSERT_NE(nullptr, second); + EXPECT_EQ(0, (uintptr_t)second % 8); + for (size_t i = 0; i < 32; i++) { + EXPECT_FALSE(__asan_address_is_poisoned(second + i)) + << "byte " << i << " of a reallocated region must be addressable"; + } + second[0] = 7; + second[31] = 9; + EXPECT_EQ(7, second[0]); + EXPECT_EQ(9, second[31]); +} + +#endif // ASAN_ENABLED + +#ifndef ASAN_ENABLED +// The TU must reference the gtest runtime in every configuration: GNU ld +// resolves libgtest.a members left-to-right, so an empty TU leaves +// gtest_main.o's own testing:: references undefined. +TEST(LinearAllocatorAsanPoison, RequiresAsanBuild) { + GTEST_SKIP() << "granule rounding is compiled only in ASan builds"; +} +#endif diff --git a/ddprof-lib/src/test/cpp/linearAllocator_nativemem_ut.cpp b/ddprof-lib/src/test/cpp/linearAllocator_nativemem_ut.cpp index 8a0299127a..2bc7bd3086 100644 --- a/ddprof-lib/src/test/cpp/linearAllocator_nativemem_ut.cpp +++ b/ddprof-lib/src/test/cpp/linearAllocator_nativemem_ut.cpp @@ -1,3 +1,8 @@ +/* + * Copyright 2026, Datadog, Inc. + * SPDX-License-Identifier: Apache-2.0 + */ + #include "gtest/gtest.h" #include "linearAllocator.h" #include "nativeMem.h" @@ -99,3 +104,16 @@ TEST_F(LinearAllocatorNativeMemTest, FreeChunksReturnsLiveToZero) { EXPECT_EQ(0, NativeMem::live(NM_CALLTRACE)) << "freeing the detached chunks un-records exactly what alloc() recorded"; } + +TEST_F(LinearAllocatorNativeMemTest, OversizedAllocIsRejected) { + LinearAllocator allocator(CHUNK_SIZE); + // A size above the chunk capacity must be rejected outright: the fast-path + // check adds size to offs, and for a huge size the sum wraps past SIZE_MAX, + // passes the capacity test, and hands out a pointer past the chunk's end. + // SIZE_MAX - 1024 survives every smaller bound (including the ASan rounding + // guard) and would wrap in offs + size without the capacity rejection. + EXPECT_EQ(nullptr, allocator.alloc(SIZE_MAX - 1024)); + EXPECT_EQ(nullptr, allocator.alloc((size_t)CHUNK_SIZE + 1)); + // The rejection must not poison the allocator: a normal allocation still works. + EXPECT_NE(nullptr, allocator.alloc(128)); +} diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/ExternalLauncher.java b/ddprof-test/src/test/java/com/datadoghq/profiler/ExternalLauncher.java index 62819faac8..437d507e45 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/ExternalLauncher.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/ExternalLauncher.java @@ -46,6 +46,10 @@ * profiler, spins in {@code com.datadoghq.profiler.generated.LazyTraceIdProbe} (defined by * its own class loader, so it has no jmethodIDs until the profiler resolves its frames) and * stops the profiler + *

  • nmethod-method <comma delimited profiler command list, required> - starts the + * profiler, forces compilation of {@code nmethodMethodTarget} and prints the jmethodID the + * profiler reads through each compiled body's {@code _method} field; see {@code + * NMethodMethodJvmtiValidationTest} *
  • entry-frames <comma delimited profiler command list, required> - starts the profiler, * then burns CPU concurrently on the main thread, on a plain {@code new Thread(Runnable)} and * on a two-level {@link Thread} subclass, and stops the profiler again. The resulting @@ -172,6 +176,22 @@ private static void entryFrameBurn(long millis) { entryFrameSink = acc; } + private static volatile long nmethodMethodSink; + + /** + * Xorshift state mixing, 64 rounds per call: enough work for its own compilation, cheap enough to + * call 20 000 times per round. Package-private so tests can name it reflectively. + */ + static long nmethodMethodTarget(long x) { + long r = x; + for (int i = 0; i < 64; i++) { + r ^= r << 13; + r ^= r >>> 7; + r ^= r << 17; + } + return r; + } + /** * Splits a scenario mode's single {@code "|||"} argument * (packed so launch()'s (target, commands) contract needs no extra argument). @@ -277,6 +297,54 @@ public static void main(String[] args) throws Exception { probe.getMethod("spin", long.class).invoke(null, 2_000_000_000L); // Stopping dumps the recording, which resolves the probe's raw frames. instance.stop(); + } else if (args[0].equals("nmethod-method")) { + if (args.length < 2 || args[1].isEmpty()) { + throw new IllegalArgumentException("nmethod-method requires a profiler command list"); + } + JavaProfiler instance = JavaProfiler.getInstance(); + // The profiler must be started: its SIGSEGV handler backs the safe reads the + // seam performs while resolving the target's nmethod. + instance.execute(args[1]); + Method target = ExternalLauncher.class.getDeclaredMethod("nmethodMethodTarget", long.class); + long[] reads = null; + long acc = 0; + // A seam failure must still stop the profiler: the child must not + // exit with profiling live and without its recording dumped. + try { + for (int round = 0; round < 50 && (reads == null || reads.length <= 1); round++) { + // Long arithmetic only: an allocation here would stop the loop and its + // callee from being compiled as the steady state under test. + for (int i = 0; i < 20_000; i++) { + acc += nmethodMethodTarget(acc); + } + reads = JavaProfiler.compiledMethodReadsForTest0(target); + if (reads == null) { + break; // unsupported: a retry cannot change that + } + } + nmethodMethodSink = acc; + if (reads == null) { + System.out.println("[nmethod-method] unsupported"); + } else { + StringBuilder sb = + new StringBuilder("[nmethod-method] target=") + .append(Long.toHexString(reads[0])) + .append(" reads="); + for (int i = 1; i + 2 < reads.length; i += 3) { + if (i > 1) { + sb.append(','); + } + sb.append(Long.toHexString(reads[i])) + .append('/') + .append(Long.toHexString(reads[i + 1])) + .append('/') + .append(Long.toHexString(reads[i + 2])); + } + System.out.println(sb); + } + } finally { + instance.stop(); + } } else if (args[0].equals("lazy-calibration-preexisting-arrays")) { if (args.length < 2 || args[1].isEmpty()) { throw new IllegalArgumentException( diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/cpu/LazyTraceIdJfrValidationTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/cpu/LazyTraceIdJfrValidationTest.java index 7e09d0a80c..709e035497 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/cpu/LazyTraceIdJfrValidationTest.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/cpu/LazyTraceIdJfrValidationTest.java @@ -6,6 +6,7 @@ package com.datadoghq.profiler.cpu; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.datadoghq.profiler.AbstractProcessProfilerTest; @@ -16,11 +17,11 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.jupiter.api.Assumptions; @@ -75,7 +76,9 @@ public void calibratedTraceIdMatchesJfrClassId() throws Exception { " ", "")); try { - AtomicLong loggedId = new AtomicLong(-1); + // The line consumer runs on the reader thread. + Set loggedIds = Collections.synchronizedSet(new HashSet<>()); + AtomicBoolean malformed = new AtomicBoolean(false); AtomicBoolean traceIdTags = new AtomicBoolean(false); AtomicBoolean tagsLogged = new AtomicBoolean(false); LaunchResult result = @@ -98,9 +101,11 @@ public void calibratedTraceIdMatchesJfrClassId() throws Exception { Matcher m = LOGGED_ID.matcher(line); if (m.find()) { try { - loggedId.set(Long.parseLong(m.group(1))); - } catch (NumberFormatException ignored) { - // Leaves loggedId unset; the assertion below reports it. + // The log line prints the id unsigned (%llu); parse it + // unsigned so ids at or above 2^63 keep JFR's getId bits. + loggedIds.add(Long.parseUnsignedLong(m.group(1))); + } catch (NumberFormatException e) { + malformed.set(true); } } return LineConsumerResult.CONTINUE; @@ -113,15 +118,21 @@ public void calibratedTraceIdMatchesJfrClassId() throws Exception { // on every other JDK calibration must find it. Assumptions.assumeTrue(Platform.hasJfr(), "JDK without JFR"); assertTrue(traceIdTags.get(), "calibration did not find the trace ID offset"); - assertTrue(loggedId.get() > 0, "the profiler did not log the probe class's trace ID"); + assertFalse(loggedIds.isEmpty(), "the profiler did not log the probe class's trace ID"); + assertFalse(malformed.get(), "the profiler logged a malformed trace ID line"); Set jfrIds = jfrClassIds(jfrRecording, PROBE_CLASS); - System.out.println("profiler trace id=" + loggedId.get() + ", JFR class ids=" + jfrIds); + System.out.println("profiler trace ids=" + loggedIds + ", JFR class ids=" + jfrIds); assertTrue(!jfrIds.isEmpty(), "JFR recorded no jdk.ClassDefine for " + PROBE_CLASS); assertEquals( - new HashSet<>(Arrays.asList(loggedId.get())), jfrIds, - "the calibrated Klass::_trace_id offset does not read JFR's class ID"); + loggedIds, + "the calibrated Klass::_trace_id offset does not read JFR's class ID" + + " (profiler read " + + loggedIds + + ", JFR recorded " + + jfrIds + + ")"); } finally { try { Files.deleteIfExists(jfrRecording); diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/cpu/NMethodMethodJvmtiValidationTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/cpu/NMethodMethodJvmtiValidationTest.java new file mode 100644 index 0000000000..cb1da81a0e --- /dev/null +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/cpu/NMethodMethodJvmtiValidationTest.java @@ -0,0 +1,151 @@ +/* + * Copyright 2026, Datadog, Inc. + * SPDX-License-Identifier: Apache-2.0 + */ + +package com.datadoghq.profiler.cpu; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.datadoghq.profiler.AbstractProcessProfilerTest; +import com.datadoghq.profiler.Platform; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +/** + * Validates, against JVMTI itself, the {@code nmethod::_method} offset the profiler reads when it + * resolves a compiled method. + * + *

    A child JVM starts the profiler, forces {@code ExternalLauncher.nmethodMethodTarget} to be + * compiled, and asks the profiler's test seam for every compiled body of that method. For each body + * the child prints the code address JVMTI {@code CompiledMethodLoad} gives for it, whether the + * profiler's code-heap lookup found the nmethod, and the jmethodID the profiler reads through that + * nmethod's {@code _method} field. The test compares the last value with the jmethodID JVMTI + * reports for the same code address. + * + *

    The two values come from independent sources: HotSpot produces the event from its own + * nmethod-to-{@code Method} link, which never passes through the profiler's vmStructs offsets. + * {@code -Xbatch} makes compilation synchronous, so the target is compiled when the seam runs, and + * the {@code dontinline} compile command gives the target its own nmethod instead of letting it be + * inlined into the calling loop. + */ +public class NMethodMethodJvmtiValidationTest extends AbstractProcessProfilerTest { + private static final String TARGET = "ExternalLauncher.nmethodMethodTarget"; + + private static final String UNSUPPORTED = "[nmethod-method] unsupported"; + + // The reads body is empty or "//" triples; Long.toHexString is always + // non-empty lowercase hex, so each token is bounded to at least one digit. + private static final Pattern REPORT = + Pattern.compile( + "\\[nmethod-method\\] target=([0-9a-f]+) reads=((?:[0-9a-f]+/[0-9a-f]+/[0-9a-f]+)?(?:,[0-9a-f]+/[0-9a-f]+/[0-9a-f]+)*)"); + + @Test + @Timeout(120) + public void nmethodMethodReadMatchesJvmti() throws Exception { + Assumptions.assumeFalse( + Platform.isZing() || Platform.isJ9() || Platform.isGraal(), "HotSpot only"); + Path recording = Files.createTempFile("nmethod-method-", ".jfr"); + try { + // The line consumer runs on the reader thread. + AtomicReference report = new AtomicReference<>(); + LaunchResult result = + launch( + "nmethod-method", + Arrays.asList( + "-Xbatch", + "-XX:CompileCommand=quiet", + "-XX:CompileCommand=dontinline,com/datadoghq/profiler/ExternalLauncher.nmethodMethodTarget"), + "start,cpu=10ms,cstack=vm,jfr,file=" + recording, + Collections.emptyMap(), + 60, + line -> { + if (line.startsWith("[nmethod-method] ")) { + report.set(line); + } + return LineConsumerResult.CONTINUE; + }, + null); + assertTrue(result.inTime, "child JVM did not finish in time"); + assertEquals(0, result.exitCode, "child JVM failed"); + String line = report.get(); + assertTrue(line != null, "the child did not report nmethod reads"); + Assumptions.assumeFalse( + line.equals(UNSUPPORTED), + "the compiled-method-read seam is unavailable (no code heap on this JVM, " + + "or a release native build where the debug-only seam returns null)"); + long[] values = parseReport(line); + long target = values[0]; + // A null target or code address makes the read == target check below + // degenerate: an all-zero report must fail, not pass as a match. + assertTrue(target != 0, "the seam resolved no jmethodID for " + TARGET); + assertTrue(values.length > 1, "JVMTI reported no compiled code for " + TARGET); + for (int i = 1; i + 2 < values.length; i += 3) { + long addr = values[i]; + assertTrue(addr != 0, "a reported read has no code address"); + long status = values[i + 1]; + long read = values[i + 2]; + assertEquals( + 0, + status, + "the profiler found no nmethod at JVMTI code address 0x" + Long.toHexString(addr)); + assertEquals( + target, + read, + "nmethod::_method at 0x" + + Long.toHexString(addr) + + " resolves to jmethodID 0x" + + Long.toHexString(read) + + ", JVMTI reports 0x" + + Long.toHexString(target) + + " for " + + TARGET); + } + } finally { + Files.deleteIfExists(recording); + } + } + + /** + * Parses a {@code [nmethod-method] target= reads=//,...} line into + * {@code {target, addr, status, read, ...}}. Fails with "malformed nmethod-method report: " plus + * the offending line when the line deviates from the format, instead of leaking a bare {@link + * NumberFormatException}. + */ + private static long[] parseReport(String line) { + try { + Matcher m = REPORT.matcher(line); + if (!m.matches()) { + throw new NumberFormatException(line); + } + List values = new ArrayList<>(); + values.add(Long.parseUnsignedLong(m.group(1), 16)); + if (!m.group(2).isEmpty()) { + for (String triple : m.group(2).split(",")) { + String[] parts = triple.split("/"); + values.add(Long.parseUnsignedLong(parts[0], 16)); + values.add(Long.parseUnsignedLong(parts[1], 16)); + values.add(Long.parseUnsignedLong(parts[2], 16)); + } + } + long[] parsed = new long[values.size()]; + for (int i = 0; i < parsed.length; i++) { + parsed[i] = values.get(i); + } + return parsed; + } catch (NumberFormatException e) { + throw new AssertionError("malformed nmethod-method report: " + line, e); + } + } +}