Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,21 @@ object ConfigurationPresets {
project.logger.lifecycle("Setting up standard build configurations for $currentPlatform-$currentArch")
project.logger.lifecycle("Using compiler: $compiler")

// Opt-in compile-time fault injection. When -PenableFaultInjection is
// passed we append -D__FAULT_INJECTION__ to the standard release/debug
// library builds, so the documented buildRelease / buildDebug workflows
// produce a fault-injected libjavaProfiler.so. It is intentionally NOT
// applied to asan/tsan/fuzzer: those configs install their own SIGSEGV
// interception, which conflicts with the deliberately-faulting loads.
val faultInjection = project.hasProperty("enableFaultInjection")
extension.buildConfigurations.apply {
register("release") {
configureRelease(this, currentPlatform, currentArch, version)
if (faultInjection) compilerArgs.add("-D__FAULT_INJECTION__")
}
register("debug") {
configureDebug(this, currentPlatform, currentArch, version)
if (faultInjection) compilerArgs.add("-D__FAULT_INJECTION__")
}
register("asan") {
configureAsan(this, currentPlatform, currentArch, version, rootDir, compiler)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,13 @@ class GtestTaskBuilder(
// Mark unit-test builds so test-only production APIs are compiled in.
args.add("-DUNIT_TEST")

// Mirror the opt-in fault-injection define so the fault-injection unit
// test can compile the enabled path under -PenableFaultInjection. Guard
// against duplicating it if the config already carries it.
if (project.hasProperty("enableFaultInjection") && !args.contains("-D__FAULT_INJECTION__")) {
args.add("-D__FAULT_INJECTION__")
}

return args
}

Expand Down
30 changes: 29 additions & 1 deletion ddprof-lib/src/main/cpp/counters.h
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,35 @@
* paths (delegated and direct) go into SAMPLES_DROPPED_REC_LOCK. */ \
X(JVMTI_STACKS_DROPPED_LOCK, "jvmti_stacks_dropped_lock") \
X(SAMPLES_DROPPED_REC_LOCK, "samples_dropped_rec_lock") \
X(SAMPLES_DROPPED_THREAD_LOCAL, "samples_dropped_thread_local")
X(SAMPLES_DROPPED_THREAD_LOCAL, "samples_dropped_thread_local") \
X(SAFECOPY_FAILED, "safecopy_failed") \
X(SAFEFETCH_FAILED, "safefetch_failed") \
X(WALKVM_LONGJMP_RECOVERED, "walkvm_longjmp_recovered") \
DD_COUNTER_TABLE_FAULT_INJECTION(X) \
DD_COUNTER_TABLE_DEBUG(X)

// Fault-injection-only counter: number of faults actually injected. Only
// compiled in when __FAULT_INJECTION__ is defined, so it occupies no enum slot
// and adds no storage in normal builds.
#ifdef __FAULT_INJECTION__
#define DD_COUNTER_TABLE_FAULT_INJECTION(X) \
X(FAULTS_INJECTED, "faults_injected")
#else
#define DD_COUNTER_TABLE_FAULT_INJECTION(X)
#endif

// Debug-only counters: SafeAccess reads/copies issued while the thread is
// already inside a walkVM longjmp-protected region (redundant safefetch
// overhead). Not compiled into release builds at all, so they occupy no enum
// slot and add no storage there.
#ifdef DEBUG
#define DD_COUNTER_TABLE_DEBUG(X) \
X(SAFEFETCH_WHILE_PROTECTED, "safefetch_while_protected") \
X(SAFECOPY_WHILE_PROTECTED, "safecopy_while_protected")
#else
#define DD_COUNTER_TABLE_DEBUG(X)
#endif

#define X_ENUM(a, b) a,
typedef enum CounterId : int {
DD_COUNTER_TABLE(X_ENUM) DD_NUM_COUNTERS
Expand Down
124 changes: 124 additions & 0 deletions ddprof-lib/src/main/cpp/faultInjection.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
* Copyright 2026, Datadog, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "faultInjection.h"

// The whole translation unit is empty unless fault injection is enabled, so a
// normal build links a no-op object file.
#ifdef __FAULT_INJECTION__

#include "counters.h" // Counters::increment (FAULTS_INJECTED)
#include "os.h" // OS::page_size
#include "threadLocalData.h" // ProfiledThread::currentSignalSafe / nextFiRandom
#include <atomic>
#include <sys/mman.h>

namespace faultinj {

// Knuth multiplicative constant (== common.h KNUTH_MULTIPLICATIVE_CONSTANT),
// used to hash the function name and to advance the global fallback PRNG.
static constexpr u64 KNUTH = 0x9e3779b97f4a7c15ULL;

// Word-alignment mask for produced addresses.
static constexpr uintptr_t ALIGN_MASK = ~(uintptr_t)(sizeof(void*) - 1);

// Guard region: mmapped once at init() with PROT_NONE so any access faults.
// Written only by init() (off the signal path); read-only afterwards.
static std::atomic<uintptr_t> g_guard_base{0};
static std::atomic<uintptr_t> g_guard_span{0};
static std::atomic<bool> g_guard_ok{false};

// Fallback PRNG for threads with no ProfiledThread context. Relaxed atomics
// keep it lock-free and async-signal-safe; a lost update on a race is harmless.
static std::atomic<u64> g_fallback_rng{KNUTH};

void init() {
// Avoid repeated mmaps (tests call init() in each fixture SetUp()).
if (g_guard_ok.load(std::memory_order_acquire)) {
return;
}

// A handful of pages is plenty of distinct fault addresses; keep it small.
size_t span = 16 * OS::page_size;
void* p = mmap(nullptr, span, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p == MAP_FAILED) {
return;
}

g_guard_base.store((uintptr_t)p, std::memory_order_relaxed);
g_guard_span.store(span, std::memory_order_relaxed);
g_guard_ok.store(true, std::memory_order_release);
}
Comment thread
Copilot marked this conversation as resolved.

u64 nextRandom() {
ProfiledThread* t = ProfiledThread::currentSignalSafe(); // never allocates
if (t != nullptr) {
return t->nextFiRandom();
}
// Fallback: relaxed atomic xorshift64. Not perfectly serialised, but the
// stream only needs to be roughly uniform for injection decisions.
u64 x = g_fallback_rng.load(std::memory_order_relaxed);
if (x == 0) x = 1;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
g_fallback_rng.store(x, std::memory_order_relaxed);
return x;
}

bool shouldFire(u64 threshold, const char* fn) {
// XOR with a per-function hash is a bijection on 64 bits, so it perturbs the
// stream per call site while keeping the fire probability exactly
// threshold/2^64.
u64 r = nextRandom() ^ ((u64)(uintptr_t)fn * KNUTH);
if (__builtin_expect(r < threshold, 0)) {
// Every address/int/long injection routes through here, so this is the one
// place that counts an actually-injected fault.
Counters::increment(FAULTS_INJECTED);
return true;
}
return false;
}

uintptr_t poisonAddress() {
u64 r = nextRandom();
if (g_guard_ok.load(std::memory_order_acquire)) {
// Guaranteed-unmapped guard page — deterministic SIGSEGV.
uintptr_t base = g_guard_base.load(std::memory_order_relaxed);
uintptr_t span = g_guard_span.load(std::memory_order_relaxed);
return (base + (uintptr_t)(r % span)) & ALIGN_MASK;
}
// Fallback: best-effort garbage address if init() failed.
return ((uintptr_t)r | (uintptr_t)0x8000000000000000ULL) & ALIGN_MASK;
}
Comment thread
Copilot marked this conversation as resolved.

int32_t injectInt(int32_t v, u64 threshold, const char* fn) {
if (__builtin_expect(shouldFire(threshold, fn), 0)) {
return (int32_t)nextRandom();
}
return v;
}

int64_t injectLong(int64_t v, u64 threshold, const char* fn) {
if (__builtin_expect(shouldFire(threshold, fn), 0)) {
return (int64_t)nextRandom();
}
return v;
}

} // namespace faultinj

#endif // __FAULT_INJECTION__
123 changes: 123 additions & 0 deletions ddprof-lib/src/main/cpp/faultInjection.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
* Copyright 2026, Datadog, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// Compile-time fault-injection layer for the profiler's memory-access sites.
//
// The macros below wrap a pointer or value expression at a real dereference
// site (VMStructs::at, walkVM, walkFP, walkDwarf). When __FAULT_INJECTION__ is
// defined, each wrapped expression, with the tier's probability, is replaced by
// a deliberately bad address (so the load faults and the profiler's recovery
// path — SafeAccess safefetch or walkVM's setjmp/longjmp — is exercised) or a
// random int/long value. When the flag is NOT defined, every macro is a strict
// identity: it expands to exactly the parenthesized original expression, with
// unchanged type and value category and zero runtime cost.
//
// pc = SafeAccess::load(INJECT_FAULT_ADDRESS_LIKELY((void**)fp));
// VMMethod* m = ((VMMethod**)INJECT_FAULT_ADDRESS_UNLIKELY(fp))[off];
//
// The three tiers name their firing frequency: RARE 0.01%, UNLIKELY 0.1%,
// LIKELY 1%. See faultInjection.cpp for the poison-address and PRNG details.

#ifndef _FAULT_INJECTION_H
#define _FAULT_INJECTION_H

#ifdef __FAULT_INJECTION__

#include "arch.h" // u64
#include <cstdint>

namespace faultinj {

// Firing probability expressed as an xorshift64 threshold (round(p * 2^64)), so
// the hot-path check is a single integer compare (rng < threshold) with no
// floating point in the signal handler.
constexpr u64 PROB_RARE = 1844674407370955ULL; // 1e-4 (0.01%)
constexpr u64 PROB_UNLIKELY = 18446744073709552ULL; // 1e-3 (0.1%)
constexpr u64 PROB_LIKELY = 184467440737095520ULL; // 1e-2 (1%)

// Called once at profiler startup (off the signal path) to mmap the PROT_NONE
// guard region used by poisonAddress(). Safe to call before any injection.
void init();

// Draws one per-thread (or global-fallback) PRNG value. Async-signal-safe.
u64 nextRandom();

// Returns true with probability threshold/2^64. The function name perturbs the
// draw so distinct call sites get statistically independent decisions.
bool shouldFire(u64 threshold, const char* fn);

// A word-aligned address intended to fault on access. When init() has reserved the
// mmap'd PROT_NONE guard region, this returns an address inside it (deterministic
// SIGSEGV). If init() failed, it falls back to a best-effort garbage address.
uintptr_t poisonAddress();

// Returns ptr unchanged, or a poison address (cast to T) when the tier fires.
// Templated so the wrapped expression's static type (void**, const char*,
// uintptr_t, ...) is preserved exactly.
template <typename T>
inline T injectAddress(T ptr, u64 threshold, const char* fn) {
if (__builtin_expect(shouldFire(threshold, fn), 0)) {
// C-style cast intentionally: converts the numeric poison address to any
// pointer type or to uintptr_t. This code only ever compiles under the flag.
return (T)poisonAddress();
}
return ptr;
}

// Returns v unchanged, or a pseudo-random value when the tier fires.
int32_t injectInt(int32_t v, u64 threshold, const char* fn);
int64_t injectLong(int64_t v, u64 threshold, const char* fn);

} // namespace faultinj

#define INJECT_FAULT_ADDRESS_RARE(ptr) \
::faultinj::injectAddress((ptr), ::faultinj::PROB_RARE, __func__)
#define INJECT_FAULT_ADDRESS_UNLIKELY(ptr) \
::faultinj::injectAddress((ptr), ::faultinj::PROB_UNLIKELY, __func__)
#define INJECT_FAULT_ADDRESS_LIKELY(ptr) \
::faultinj::injectAddress((ptr), ::faultinj::PROB_LIKELY, __func__)

#define INJECT_FAULT_INT_RARE(v) \
::faultinj::injectInt((v), ::faultinj::PROB_RARE, __func__)
#define INJECT_FAULT_INT_UNLIKELY(v) \
::faultinj::injectInt((v), ::faultinj::PROB_UNLIKELY, __func__)
#define INJECT_FAULT_INT_LIKELY(v) \
::faultinj::injectInt((v), ::faultinj::PROB_LIKELY, __func__)

#define INJECT_FAULT_LONG_RARE(v) \
::faultinj::injectLong((v), ::faultinj::PROB_RARE, __func__)
#define INJECT_FAULT_LONG_UNLIKELY(v) \
::faultinj::injectLong((v), ::faultinj::PROB_UNLIKELY, __func__)
#define INJECT_FAULT_LONG_LIKELY(v) \
::faultinj::injectLong((v), ::faultinj::PROB_LIKELY, __func__)

#else // __FAULT_INJECTION__ not defined — strict identity, zero cost.

#define INJECT_FAULT_ADDRESS_RARE(ptr) (ptr)
#define INJECT_FAULT_ADDRESS_UNLIKELY(ptr) (ptr)
#define INJECT_FAULT_ADDRESS_LIKELY(ptr) (ptr)

#define INJECT_FAULT_INT_RARE(v) (v)
#define INJECT_FAULT_INT_UNLIKELY(v) (v)
#define INJECT_FAULT_INT_LIKELY(v) (v)

#define INJECT_FAULT_LONG_RARE(v) (v)
#define INJECT_FAULT_LONG_UNLIKELY(v) (v)
#define INJECT_FAULT_LONG_LIKELY(v) (v)

#endif // __FAULT_INJECTION__

#endif // _FAULT_INJECTION_H
16 changes: 9 additions & 7 deletions ddprof-lib/src/main/cpp/hotspot/hotspotSupport.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <climits>
#include <cstdlib>
#include "asyncSampleMutex.h"
#include "faultInjection.h"
#include "frames.h"
#include "guards.h"
#include "hotspot/hotspotSupport.h"
Expand Down Expand Up @@ -370,8 +371,8 @@ __attribute__((no_sanitize("address"))) int HotspotSupport::walkVM(void* ucontex
// entry_fp has been range-checked by isValidFP above; any remaining
// SIGSEGV from a stale/concurrently-freed pointer is caught by the
// setjmp crash protection in walkVM (checkFault -> longjmp).
uintptr_t carrier_fp = *(uintptr_t*)entry_fp;
const void* carrier_pc = ((const void**)entry_fp)[FRAME_PC_SLOT];
uintptr_t carrier_fp = *(uintptr_t*)INJECT_FAULT_ADDRESS_UNLIKELY(entry_fp);
const void* carrier_pc = ((const void**)INJECT_FAULT_ADDRESS_UNLIKELY(entry_fp))[FRAME_PC_SLOT];
uintptr_t carrier_sp = entry_fp + (FRAME_PC_SLOT + 1) * sizeof(void*);
if (!StackWalkValidation::isValidFP(carrier_fp) ||
StackWalkValidation::inDeadZone(carrier_pc) ||
Expand Down Expand Up @@ -496,7 +497,7 @@ __attribute__((no_sanitize("address"))) int HotspotSupport::walkVM(void* ucontex

bool is_plausible_interpreter_frame = StackWalkValidation::isPlausibleInterpreterFrame(fp, sp, bcp_offset);
if (is_plausible_interpreter_frame) {
VMMethod* method = ((VMMethod**)fp)[InterpreterFrame::method_offset];
VMMethod* method = ((VMMethod**)INJECT_FAULT_ADDRESS_UNLIKELY(fp))[InterpreterFrame::method_offset];
jmethodID method_id = getMethodId(method);
if (method_id != JMETHODID_NOT_WALKABLE) {
Counters::increment(WALKVM_JAVA_FRAME_OK);
Expand All @@ -506,7 +507,7 @@ __attribute__((no_sanitize("address"))) int HotspotSupport::walkVM(void* ucontex
fillFrame(frames[depth++], FRAME_INTERPRETED, bci, method_id, method);
sp = ((uintptr_t*)fp)[InterpreterFrame::sender_sp_offset];
pc = stripPointer(((void**)fp)[FRAME_PC_SLOT]);
fp = *(uintptr_t*)fp;
fp = *(uintptr_t*)INJECT_FAULT_ADDRESS_UNLIKELY(fp);
continue;
}
}
Expand All @@ -518,7 +519,7 @@ __attribute__((no_sanitize("address"))) int HotspotSupport::walkVM(void* ucontex
Counters::increment(WALKVM_JAVA_FRAME_OK);
fillFrame(frames[depth++], FRAME_INTERPRETED, 0, method_id, method);
if (is_plausible_interpreter_frame) {
pc = stripPointer(((void**)fp)[FRAME_PC_SLOT]);
pc = stripPointer(((void**)INJECT_FAULT_ADDRESS_UNLIKELY(fp))[FRAME_PC_SLOT]);
sp = frame.senderSP();
fp = *(uintptr_t*)fp;
} else {
Expand Down Expand Up @@ -595,7 +596,7 @@ __attribute__((no_sanitize("address"))) int HotspotSupport::walkVM(void* ucontex
break;
}

fp = ((uintptr_t*)sp)[-FRAME_PC_SLOT - 1];
fp = ((uintptr_t*)INJECT_FAULT_ADDRESS_UNLIKELY(sp))[-FRAME_PC_SLOT - 1];
pc = ((const void**)sp)[-FRAME_PC_SLOT];
continue;
} else if (frame.unwindPrologue(nm, (uintptr_t&)pc, sp, fp)) {
Expand Down Expand Up @@ -737,7 +738,7 @@ __attribute__((no_sanitize("address"))) int HotspotSupport::walkVM(void* ucontex
// In HotSpot, lastJavaFP is non-zero only for interpreter frames;
// compiled frames record FP=0 in the anchor.
if (StackWalkValidation::isPlausibleInterpreterFrame(recovery_fp, recovery_sp, bcp_offset)) {
VMMethod* method = ((VMMethod**)recovery_fp)[InterpreterFrame::method_offset];
VMMethod* method = ((VMMethod**)INJECT_FAULT_ADDRESS_UNLIKELY(recovery_fp))[InterpreterFrame::method_offset];
jmethodID method_id = getMethodId(method);
if (method_id != JMETHODID_NOT_WALKABLE) {
anchor = NULL;
Expand Down Expand Up @@ -969,6 +970,7 @@ void HotspotSupport::checkFault(ProfiledThread* thrd) {
}

thrd->resetCrashHandler();
Counters::increment(WALKVM_LONGJMP_RECOVERED);
longjmp(*thrd->getJmpCtx(), 1);
}

Expand Down
Loading
Loading