Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
9d8228a
fix: recover abandoned TaskBlock intervals in beginTaskBlock
jbachorik Oct 27, 2026
684a12a
fix: fail closed on non-HotSpot JNI 19+ platform-thread classification
jbachorik Oct 27, 2026
588104e
fix: fail closed when the TaskBlock duration threshold is zero
jbachorik Oct 27, 2026
58d73c7
test: assert TaskBlock duration encoding
jbachorik Oct 27, 2026
9bbd0fb
test: assert unowned blocked tail carries accumulated weight
jbachorik Oct 27, 2026
8b6707d
fix: count blockEnter skips caused by an active trace context
jbachorik Oct 27, 2026
6d72b7a
test: drop stale registration claim from PrecheckEfficiencyTest comment
jbachorik Oct 27, 2026
9c8282c
fix: keep open TaskBlock interval when begin is rejected in a trace c…
jbachorik Oct 27, 2026
73dd597
fix: count an invalid TaskBlock duration threshold separately
jbachorik Oct 27, 2026
054e491
test: cover recovery of a non-decodable abandoned TaskBlock token
jbachorik Oct 27, 2026
65d5a2f
test: make the no-observer unowned tail write explicit
jbachorik Oct 27, 2026
60e9bf5
test: mirror VM::isHotspot() in the TaskBlock classification predicate
jbachorik Oct 27, 2026
9748bb6
test: establish thread tracking before asserting non-HotSpot TaskBloc…
jbachorik Oct 27, 2026
b626adf
docs: document deferred TaskBlock recovery, share sleeping-state test…
jbachorik Oct 27, 2026
5ef812e
Fix TaskBlock rotation admission, lightweight weights, and thread ove…
kaahos Nov 12, 2026
de0ffd6
Merge TaskBlock core into review fixes
kaahos Nov 13, 2026
eabc68e
Fix recorder linking and synchronous test epoch readiness
kaahos Nov 13, 2026
3af96ec
Document paired TaskBlock recovery and platform-thread admission
kaahos Nov 15, 2026
11afac4
Merge cumulative TaskBlock core into paired-interval recovery
kaahos Nov 16, 2026
693d8d2
Merge crash bootstrap and TaskBlock telemetry into core review fixes
kaahos Nov 17, 2026
2429bf5
Merge upstream #663 test follow-ups into #915
kaahos Nov 17, 2026
b755092
Merge upstream exit-order repair into #915
kaahos Nov 17, 2026
2697811
Merge wall dump epoch guard into #915
kaahos Nov 18, 2026
5a1231b
Mark unprovisionable musl/OpenJ9 combinations not applicable
kaahos Nov 18, 2026
126b6b1
test(ci): make the pipeline exclusion literal explicit
kaahos Nov 18, 2026
1b93a2e
Merge #664 native-memory and stop-capacity repairs into #915
kaahos Nov 19, 2026
bf2e4d2
chore(stack): merge #664 fixes into #915
kaahos Nov 19, 2026
a7bff9c
chore(stack): merge main and #664 fixes into #915
kaahos Nov 19, 2026
0ab9c49
test(taskblock): restore previous recording after thread-table overfl…
kaahos Nov 20, 2026
ce112b8
docs(test): reference VM::initShared() for the HotSpot name check
kaahos Nov 20, 2026
eedf3d9
test(taskblock): assert fail-closed platform-thread classification on…
kaahos Nov 20, 2026
56c005b
chore(stack): merge #664 fixes into #915
kaahos Nov 20, 2026
122b381
chore(stack): merge #664 fixes into #915
kaahos Nov 20, 2026
0260ef4
chore(stack): merge #664 fixes into #915
kaahos Nov 20, 2026
647f91f
chore(stack): merge #664 fixes into #915
kaahos Nov 20, 2026
dad1920
test(taskblock): retry counter-accounted rejection in trace-context i…
kaahos Nov 20, 2026
25a421f
chore(stack): merge #664 fixes into #915
kaahos Nov 20, 2026
fc5fc5d
chore(stack): merge #664 fixes into #915
kaahos Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ or suggested edits on memory files.

# AGENTS.md

<!-- Copyright 2026, Datadog, Inc. -->

This file provides guidance to AI coding assistants when working with code in this
repository. It is deliberately a thin index: rules that must always be in context live
here; subsystem details live in `doc/` (start at the [doc/README.md](doc/README.md)
Expand Down
10 changes: 9 additions & 1 deletion ddprof-lib/src/main/cpp/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ before working on a subsystem.
| Call trace storage (triple-buffered ACTIVE/STANDBY/SCRATCH, 64-bit instance+slot trace IDs, lock-free rotation, freed on stop, reusable unowned wall-clock roots) | [doc/architecture/CallTraceStorage.md](/doc/architecture/CallTraceStorage.md) |
| String dictionary (lazily allocated arena chunks, rotation/clear/release protocols) | [doc/architecture/StringDictionary.md](/doc/architecture/StringDictionary.md) |
| RefCountGuard (lock-free RAII reader-drain before reclamation) | [doc/architecture/RefCountGuard.md](/doc/architecture/RefCountGuard.md) |
| TLS context (thread-local tracing, owner context-window membership, retained unowned wall context and sampling-epoch weight provenance) | [doc/architecture/TLSContext.md](/doc/architecture/TLSContext.md) |
| TLS context (thread-local tracing, owner context-window membership, paired TaskBlock interval recovery, retained unowned wall context and sampling-epoch weight provenance) | [doc/architecture/TLSContext.md](/doc/architecture/TLSContext.md) |
| JVM support (HotSpot, J9, Zing) | [doc/architecture/JvmSupportLayer.md](/doc/architecture/JvmSupportLayer.md) |
| Profiling engines (CPU, monotonic wall-clock cadence, allocation, native memory, liveness; prechecks preserve reservoir selections in epoch accounting; timer TID metadata lookup is capped at 256 probes and fails open to ordinary signals; lazy wall-block backing survives recording resets; unowned teardown tails retain slot custody until written, and stop counts the weight of the ones it cannot write as dropped; allocation/liveness stack capture via `allocstack`, with JVMTI retry for unsafe frames, depth-limit truncation and separate verification scratch) | [doc/architecture/ProfilingEngines.md](/doc/architecture/ProfilingEngines.md) |
| JFR integration (FlightRecorder, metadata, constant pools, buffers; bounded DEBUG TaskBlock transition receipts survive recording teardown; wall epochs settle before chunk seals; retained tails carry originating metadata across dumps; stop archives full thread tables before bounded tail-admission retries) | [doc/architecture/JfrIntegration.md](/doc/architecture/JfrIntegration.md) |
Expand Down Expand Up @@ -198,6 +198,14 @@ See [CallTraceStorage](/doc/architecture/CallTraceStorage.md#reusable-unowned-wa
Only owner-side entry/exit changes membership; signals and timers do not walk remote TLS.
See [TLSContext](/doc/architecture/TLSContext.md#context-window-membership).

**Paired TaskBlock intervals.** Run begin admission checks before discarding a pending interval.
Recovery emits no event and closes only the token's matching current slot and generation.
See [TLSContext](/doc/architecture/TLSContext.md#paired-taskblock-intervals).

**Platform-thread classification.** Verify the caller before mutating Java-owned TaskBlock TLS.
`JVMSupport::isPlatformThread()` rejects non-HotSpot JNI >= 19 without reading slot 234.
See [JvmSupportLayer](/doc/architecture/JvmSupportLayer.md#platform-thread-classification).

**Atomic memory ordering (arm64).** arm64 is weakly ordered (x86 is TSO); relaxed-ordering
bugs are silent arm64-only lockups. Cross-thread reads: acquire ordering
(`__ATOMIC_ACQUIRE` / `std::memory_order_acquire`), including loads of pointers published
Expand Down
3 changes: 3 additions & 0 deletions ddprof-lib/src/main/cpp/counters.h
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,15 @@
X(TASK_BLOCK_SKIPPED_TRACE_CONTEXT, "task_block_skipped_trace_context") \
X(TASK_BLOCK_SKIPPED_CONTEXT_WINDOW, "task_block_skipped_context_window") \
X(TASK_BLOCK_SKIPPED_TOO_SHORT, "task_block_skipped_too_short") \
X(TASK_BLOCK_THRESHOLD_INVALID, "task_block_threshold_invalid") \
X(TASK_BLOCK_STACK_CAPTURE_FAILED, "task_block_stack_capture_failed") \
X(TASK_BLOCK_RECORD_FAILED, "task_block_record_failed") \
X(TASK_BLOCK_DROPPED_ROTATION, "task_block_dropped_rotation") \
X(TASK_BLOCK_DROPPED_ADMISSION, "task_block_dropped_admission") \
X(TASK_BLOCK_SKIPPED_THREAD_MISMATCH, "task_block_skipped_thread_mismatch") \
X(TASK_BLOCK_ROTATION_TIMEOUT, "task_block_rotation_timeout") \
X(TASK_BLOCK_RECOVERED_ABANDONED, "task_block_recovered_abandoned") \
X(BLOCK_ENTER_SKIPPED_TRACE_CONTEXT, "block_enter_skipped_trace_context") \
X(UNWINDING_TIME_ASYNC, "unwinding_ticks_async") \
X(UNWINDING_TIME_JVMTI, "unwinding_ticks_jvmti") \
X(ALLOC_STACK_VM, "alloc_stack_vm") \
Expand Down
14 changes: 14 additions & 0 deletions ddprof-lib/src/main/cpp/javaApi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,12 @@ Java_com_datadoghq_profiler_JavaProfiler_taskBlockSupportedForTest0(
return Profiler::instance()->taskBlockSupportedForTest(env, thread) ? JNI_TRUE : JNI_FALSE;
}

extern "C" DLLEXPORT jboolean JNICALL
Java_com_datadoghq_profiler_JavaProfiler_platformThreadForTest0(
JNIEnv* env, jclass unused, jthread thread) {
return JVMSupport::isPlatformThread(env, thread) ? JNI_TRUE : JNI_FALSE;
}

extern "C" DLLEXPORT jlong JNICALL
Java_com_datadoghq_profiler_JavaProfiler_blockEnter0(
JNIEnv *env, jclass unused, jint state) {
Expand All @@ -586,6 +592,7 @@ Java_com_datadoghq_profiler_JavaProfiler_blockEnter0(
u64 span_id = 0, root_span_id = 0;
ContextApi::get(span_id, root_span_id);
if (span_id != 0) {
Counters::increment(BLOCK_ENTER_SKIPPED_TRACE_CONTEXT);
return 0;
}
Profiler *profiler = Profiler::instance();
Expand Down Expand Up @@ -648,10 +655,17 @@ Java_com_datadoghq_profiler_JavaProfiler_beginTaskBlock0(

Context context = ContextApi::snapshot();
if (context.spanId != 0) {
// A traced nested begin must preserve the pending interval for its end.
// An abandoned interval is indistinguishable here, so recovery also waits.
Counters::increment(TASK_BLOCK_SKIPPED_TRACE_CONTEXT);
return 0;
}

WallClockBlockTracker *tracker = profiler->blockTracker();
// Supersede pending TLS state only after the admission checks above.
// Slot/generation checks keep recovery from closing a different run.
recoverAbandonedTaskBlock(current, tracker, slot_id);

#if defined(DEBUG) || defined(UNIT_TEST)
TaskBlockDiagnosticRecord diagnostic{};
TaskBlockDiagnosticRecord* diagnostic_ptr = &diagnostic;
Expand Down
7 changes: 6 additions & 1 deletion ddprof-lib/src/main/cpp/jvmSupport.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,12 @@ bool JVMSupport::isPlatformThread(JNIEnv* jni, jthread thread) {
jint jni_version = jni->GetVersion();
if (jni_version <= 0) return false;
if (jni_version < JNI_VERSION_19_VALUE) return true;
if (!VM::isHotspot()) return true;
// IS_VIRTUAL_THREAD_INDEX is a hardcoded JNI function-table offset that
// is only trusted on HotSpot. On any other VM reporting JNI >= 19 the
// thread may be virtual and the table entry is not read, so fail closed:
// every thread is reported as non-platform, which keeps the task-block
// hooks disabled there until that VM's table layout is verified.
if (!VM::isHotspot()) return false;

const JniFunction* functions =
reinterpret_cast<const JniFunction*>(jni->functions);
Expand Down
1 change: 1 addition & 0 deletions ddprof-lib/src/main/cpp/jvmSupport.h
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ class JVMSupport {
public:
// Java-owned profiler state is carrier-local and may only be used by platform threads.
// IsVirtualThread was added to the JNI function table in JDK 19.
// Non-HotSpot VMs reporting JNI >= 19 always get false (fail closed).
static bool isPlatformThread(JNIEnv* jni, jthread thread);

// Initialize JVM support - check JVM related resources are available.
Expand Down
49 changes: 46 additions & 3 deletions ddprof-lib/src/main/cpp/taskBlockRecorder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,61 @@
static const u64 kMinTaskBlockNanos = 1000000;
static std::atomic<u64> g_min_task_block_ticks{0};

#ifdef UNIT_TEST
static std::atomic<TaskBlockFrequencySource> g_test_frequency_source{nullptr};

void resetTaskBlockDurationThresholdForTest() {
g_min_task_block_ticks.store(0, std::memory_order_release);
}

void setTaskBlockFrequencySourceForTest(TaskBlockFrequencySource source) {
g_test_frequency_source.store(source, std::memory_order_release);
}
#endif

static u64 taskBlockTscFrequency() {
#ifdef UNIT_TEST
TaskBlockFrequencySource source =
g_test_frequency_source.load(std::memory_order_acquire);
if (source != nullptr) return source();
#endif
return TSC::frequency();
}

static u64 computeMinTaskBlockTicks() {
return (TSC::frequency() * kMinTaskBlockNanos) / NANOTIME_FREQ;
return (taskBlockTscFrequency() * kMinTaskBlockNanos) / NANOTIME_FREQ;
}

void initializeTaskBlockDurationThreshold() {
g_min_task_block_ticks.store(computeMinTaskBlockTicks(), std::memory_order_release);
}

bool exceedsMinTaskBlockDuration(u64 start_ticks, u64 end_ticks) {
TaskBlockDurationCheck checkTaskBlockDuration(u64 start_ticks, u64 end_ticks) {
u64 min_ticks = g_min_task_block_ticks.load(std::memory_order_acquire);
if (min_ticks == 0) min_ticks = computeMinTaskBlockTicks();
return end_ticks > start_ticks && end_ticks - start_ticks >= min_ticks;
// The threshold is 0 when TSC::frequency() is below 1 kHz, for example 0
// when uncalibrated. Comparing against 0 would accept every block, so
// reject instead. A separate result lets the caller count this as
// TASK_BLOCK_THRESHOLD_INVALID, not as TASK_BLOCK_SKIPPED_TOO_SHORT.
if (min_ticks == 0) return TaskBlockDurationCheck::THRESHOLD_INVALID;
return end_ticks > start_ticks && end_ticks - start_ticks >= min_ticks
? TaskBlockDurationCheck::ELIGIBLE
: TaskBlockDurationCheck::TOO_SHORT;
}

bool recoverAbandonedTaskBlock(ProfiledThread* current,
WallClockBlockTracker* tracker,
ThreadFilter::SlotID current_slot) {
u64 abandoned = current->abandonTaskBlock();
if (abandoned == 0) return false;
Counters::increment(TASK_BLOCK_RECOVERED_ABANDONED);
ThreadFilter::SlotID slot_id = -1;
u64 generation = 0;
if (WallClockBlockTracker::decodeBlockRunToken(abandoned, slot_id, generation) &&
slot_id == current_slot) {
tracker->exitBlockedRun(slot_id, generation);
}
return true;
}

#if defined(DEBUG) || defined(UNIT_TEST)
Expand Down
65 changes: 53 additions & 12 deletions ddprof-lib/src/main/cpp/taskBlockRecorder.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,42 @@
#include "tsc.h"

void initializeTaskBlockDurationThreshold();
bool exceedsMinTaskBlockDuration(u64 start_ticks, u64 end_ticks);

enum class TaskBlockDurationCheck {
ELIGIBLE,
TOO_SHORT,
// The 1 ms threshold computes to 0 ticks (TSC::frequency() below 1 kHz,
// e.g. 0), so no block can be checked against it.
THRESHOLD_INVALID,
};

// Compares the block duration with the 1 ms threshold. Does not count the
// result; taskBlockPassesBasicEligibility() does. Fails closed with
// THRESHOLD_INVALID when the threshold is 0, so sub-millisecond blocks cannot
// pass the filter.
TaskBlockDurationCheck checkTaskBlockDuration(u64 start_ticks, u64 end_ticks);

#ifdef UNIT_TEST
// Clears the cached threshold so the next checkTaskBlockDuration() call
// takes its lazy recompute path.
void resetTaskBlockDurationThresholdForTest();
// Replaces TSC::frequency() as the threshold's frequency source; nullptr
// restores TSC::frequency().
using TaskBlockFrequencySource = u64 (*)();
void setTaskBlockFrequencySourceForTest(TaskBlockFrequencySource source);
#endif

// Recovers a TASK_BLOCK interval whose endTaskBlock0 was never reached (for
// example, an exception thrown without a finally block). Clears the pending
// TLS token and closes its block run with the generation-checked
// exitBlockedRun(), which is a no-op if the slot has since started another
// run. The run is closed only when the token's slot is current_slot: a
// different slot means a registry reset already cleared the run and the slot
// may now belong to another thread. Counts TASK_BLOCK_RECOVERED_ABANDONED.
// Returns true when an abandoned interval was found.
bool recoverAbandonedTaskBlock(ProfiledThread* current,
WallClockBlockTracker* tracker,
ThreadFilter::SlotID current_slot);

bool recordTaskBlockAtExit(ProfiledThread* current, ThreadFilter* thread_filter,
WallClockBlockTracker* tracker, jthread thread,
Expand Down Expand Up @@ -64,19 +99,25 @@ static inline bool taskBlockPassesBasicEligibility(u64 start_ticks, u64 end_tick
Counters::increment(TASK_BLOCK_SKIPPED_TRACE_CONTEXT);
return false;
}
if (!exceedsMinTaskBlockDuration(start_ticks, end_ticks)) {
switch (checkTaskBlockDuration(start_ticks, end_ticks)) {
case TaskBlockDurationCheck::ELIGIBLE:
TASK_BLOCK_DIAGNOSTIC(BASIC_ELIGIBLE, diagnostic, 0);
return true;
case TaskBlockDurationCheck::THRESHOLD_INVALID:
Counters::increment(TASK_BLOCK_THRESHOLD_INVALID);
return false;
case TaskBlockDurationCheck::TOO_SHORT:
break;
}
#if defined(DEBUG) || defined(UNIT_TEST)
if (end_ticks <= start_ticks) {
TASK_BLOCK_DIAGNOSTIC(REJECT_DURATION_NOT_POSITIVE, diagnostic, 0);
} else {
TASK_BLOCK_DIAGNOSTIC(REJECT_DURATION_BELOW_MINIMUM, diagnostic, 0);
}
#endif
Counters::increment(TASK_BLOCK_SKIPPED_TOO_SHORT);
return false;
if (end_ticks <= start_ticks) {
TASK_BLOCK_DIAGNOSTIC(REJECT_DURATION_NOT_POSITIVE, diagnostic, 0);
} else {
TASK_BLOCK_DIAGNOSTIC(REJECT_DURATION_BELOW_MINIMUM, diagnostic, 0);
}
TASK_BLOCK_DIAGNOSTIC(BASIC_ELIGIBLE, diagnostic, 0);
return true;
#endif
Counters::increment(TASK_BLOCK_SKIPPED_TOO_SHORT);
return false;
}

static inline bool recordTaskBlockIfEligible(
Expand Down
10 changes: 10 additions & 0 deletions ddprof-lib/src/main/cpp/threadLocalData.h
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,16 @@ class ProfiledThread : public ThreadLocalData {
return true;
}

// Drops the pending TASK_BLOCK interval and returns its token, or 0 when
// none is pending. Lets beginTaskBlock0 recover an interval whose
// endTaskBlock0 was never reached; without this, taskBlockEnter() keeps
// failing for the rest of the thread's life.
inline u64 abandonTaskBlock() {
u64 token = _task_block_token;
_task_block_token = 0;
return token;
}

inline bool taskBlockExit(u64 token, u64& start_ticks, Context& context) {
if (token == 0 || _task_block_token != token) return false;
start_ticks = _task_block_start_ticks;
Expand Down
2 changes: 2 additions & 0 deletions ddprof-lib/src/main/cpp/vmEntry.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,8 @@ bool VM::initShared(JavaVM* vm) {
bool is_zero_vm = false;
char *prop;
if (_jvmti->GetSystemProperty("java.vm.name", &prop) == 0) {
// TaskBlockAssertions.platformThreadClassificationSupported() (ddprof-test)
// mirrors this name test; keep its marker list in sync.
_hotspot = strstr(prop, "OpenJDK") != NULL ||
strstr(prop, "HotSpot") != NULL ||
strstr(prop, "GraalVM") != NULL ||
Expand Down
5 changes: 2 additions & 3 deletions ddprof-lib/src/main/cpp/wallClock.h
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,8 @@ class BaseWallClock : public Engine {
WallSampleRequest prepareWallSampleRequestForTest(ProfiledThread* current, bool& suppressed);
#endif
#if defined(UNIT_TEST) || defined(DEBUG)
// Normal-thread drivers wait for the timer's real epoch without publishing one.
static bool awaitInitialSamplingEpochForTest(u64 timeout_nanos);
static void setForceStartFailureForTest(bool force) {
_force_start_failure_for_test.store(force, std::memory_order_release);
}
Expand All @@ -342,9 +344,6 @@ class BaseWallClock : public Engine {
ProfiledThread* current, bool unowned_fallback, OSThreadState observed_state,
u64& weight, bool recorded = false);
#endif
#if defined(DEBUG) || defined(UNIT_TEST)
static bool awaitInitialSamplingEpochForTest(u64 timeout_nanos);
#endif
#ifdef DEBUG
// Drives the real precheck/recording path with controlled OS-state inputs
// and an intervening JFR dump. Called synchronously from the JNI test hook.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
* default temp directory as the scratch where the bundled library will be exploded before
* linking.
*/
public static JavaProfiler getInstance() throws IOException {

Check warning on line 82 in ddprof-lib/src/main/java/com/datadoghq/profiler/JavaProfiler.java

View workflow job for this annotation

GitHub Actions / check-javadoc

no @throws for java.io.IOException

Check warning on line 82 in ddprof-lib/src/main/java/com/datadoghq/profiler/JavaProfiler.java

View workflow job for this annotation

GitHub Actions / check-javadoc

return getInstance(null, null);
}

Expand All @@ -89,7 +89,7 @@
*
* @param scratchDir directory where the bundled library will be exploded before linking
*/
public static JavaProfiler getInstance(String scratchDir) throws IOException {

Check warning on line 92 in ddprof-lib/src/main/java/com/datadoghq/profiler/JavaProfiler.java

View workflow job for this annotation

GitHub Actions / check-javadoc

no @throws for java.io.IOException

Check warning on line 92 in ddprof-lib/src/main/java/com/datadoghq/profiler/JavaProfiler.java

View workflow job for this annotation

GitHub Actions / check-javadoc

return getInstance(null, scratchDir);
}

Expand All @@ -101,7 +101,7 @@
* @param scratchDir directory where the bundled library will be exploded before linking; ignored
* when 'libLocation' is {@literal null}
*/
public static synchronized JavaProfiler getInstance(String libLocation, String scratchDir)

Check warning on line 104 in ddprof-lib/src/main/java/com/datadoghq/profiler/JavaProfiler.java

View workflow job for this annotation

GitHub Actions / check-javadoc

no @throws for java.io.IOException

Check warning on line 104 in ddprof-lib/src/main/java/com/datadoghq/profiler/JavaProfiler.java

View workflow job for this annotation

GitHub Actions / check-javadoc

throws IOException {
if (instance != null) {
return instance;
Expand Down Expand Up @@ -197,7 +197,7 @@
}

/** Records the completion of the trace root */
public boolean recordTraceRoot(

Check warning on line 200 in ddprof-lib/src/main/java/com/datadoghq/profiler/JavaProfiler.java

View workflow job for this annotation

GitHub Actions / check-javadoc

no @PARAM for operation

Check warning on line 200 in ddprof-lib/src/main/java/com/datadoghq/profiler/JavaProfiler.java

View workflow job for this annotation

GitHub Actions / check-javadoc

no @PARAM for endpoint

Check warning on line 200 in ddprof-lib/src/main/java/com/datadoghq/profiler/JavaProfiler.java

View workflow job for this annotation

GitHub Actions / check-javadoc

no @PARAM for rootSpanId
long rootSpanId, String endpoint, String operation, int sizeLimit) {
return recordTrace0(rootSpanId, endpoint, operation, sizeLimit);
}
Expand Down Expand Up @@ -457,10 +457,24 @@
* Begins an explicitly instrumented {@link Thread#sleep(long) sleeping} interval on the current
* platform thread. The resulting {@code TaskBlock} event is classified as {@code SLEEPING}. The
* returned token is bound to the current thread and must be passed to {@link #endTaskBlock(long,
* long, long)}.
* long, long)}. Call {@code endTaskBlock} in a {@code finally} block so that the interval is
* closed on every exit path, including exceptions.
*
* <p>A thread has at most one active interval. If an interval is still open when this method is
* called again on the same thread (a nested call, or a previous interval whose {@code
* endTaskBlock} was never reached), the open interval is discarded without an event and this call
* proceeds as if no interval were open. A later {@code endTaskBlock} with the discarded token
* returns {@code false}. The open interval is kept only when this call returns {@code 0} because
* TaskBlock recording is inactive, the current thread is not classified as a platform thread, the
* profiler cannot track or verify the current thread, or a trace context is active on the current
* thread.
*
* <p>On non-HotSpot JVMs running JDK 19 or later, no thread is classified as a platform thread,
* so this method always returns {@code 0} there.
*
* @return an opaque token, or {@code 0} when the interval could not be armed or the current
* thread is virtual; any non-zero value, including a negative value, is valid
* thread is not classified as a platform thread; any non-zero value, including a negative
* value, is valid
*/
public long beginTaskBlock() {
return beginTaskBlock0(Thread.currentThread());
Expand All @@ -486,6 +500,11 @@
return taskBlockSupportedForTest0(Thread.currentThread());
}

/** Test-only probe of the native platform-thread classification of the calling thread. */
boolean platformThreadForTest() {
return platformThreadForTest0(Thread.currentThread());
}

/**
* Test-only hook exercising {@link #beginTaskBlock0} with an explicit {@code thread}, to cover
* the rejection path when it does not identify the calling thread.
Expand Down Expand Up @@ -605,6 +624,8 @@

private static native boolean taskBlockSupportedForTest0(Thread thread);

private static native boolean platformThreadForTest0(Thread thread);

private static native long beginTaskBlock0(Thread thread);

private static native boolean endTaskBlock0(
Expand Down
18 changes: 12 additions & 6 deletions ddprof-lib/src/test/cpp/jvmSupport_ut.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -269,10 +269,10 @@ TEST_F(JvmSupportThreadClassificationTest, MissingJni21FunctionFailsClosed) {
}

// ---------------------------------------------------------------------------
// JvmSupportNonHotspotTest — verifies isPlatformThread() short-circuits to
// true on non-HotSpot JVMs at JNI>=19 without ever indexing the HotSpot-only
// IsVirtualThread vtable slot (which may not even be a valid function
// pointer there).
// JvmSupportNonHotspotTest — verifies isPlatformThread() fails closed
// (returns false) on non-HotSpot JVMs at JNI>=19 without ever indexing the
// IsVirtualThread table slot, whose hardcoded offset is only trusted on
// HotSpot (it may not even be a valid function pointer there).
// ---------------------------------------------------------------------------
class JvmSupportNonHotspotTest : public ::testing::Test {
protected:
Expand Down Expand Up @@ -315,8 +315,14 @@ class JvmSupportNonHotspotTest : public ::testing::Test {
}
};

TEST_F(JvmSupportNonHotspotTest, Jni21ThreadIsAcceptedWithoutIndexingVtable) {
EXPECT_TRUE(JVMSupport::isPlatformThread(&jni, thread));
TEST_F(JvmSupportNonHotspotTest, Jni21ThreadIsRejectedWithoutIndexingVtable) {
EXPECT_FALSE(JVMSupport::isPlatformThread(&jni, thread));
EXPECT_EQ(0, is_virtual_thread_calls);
}

TEST_F(JvmSupportNonHotspotTest, Jni19ThreadIsRejectedWithoutIndexingVtable) {
jni_version = 0x00130000;
EXPECT_FALSE(JVMSupport::isPlatformThread(&jni, thread));
EXPECT_EQ(0, is_virtual_thread_calls);
}

Expand Down
Loading
Loading