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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@
/callgrind/tests/runtime_obj_skip_underflow
/callgrind/tests/prctl_get_auxv
/callgrind/tests/deterministic_rng
/callgrind/tests/deterministic_time
/callgrind/tests/*.so
/callgrind/tests/out_dbg
/callgrind/tests/test-suite-overall.log
Expand Down
26 changes: 26 additions & 0 deletions CODSPEED-CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,32 @@ results are unchanged.
Reduce simulated cache-miss variation from argument and environment sizes
by keeping the Linux initial stack pointer at a fixed offset from the stack top.

### Deterministic time: `--deterministic-time`

**Feature**: Added `--deterministic-time=no|yes` (default `no`). When enabled, every clock the client can read is derived from the number of guest instructions executed so far. The same instruction stream always observes the same time, however long Valgrind takes to run it.

**Motivation**: Runtimes make decisions from elapsed time: benchmark harnesses pick iteration and warmup counts, garbage collectors and schedulers use time-based heuristics, and time-bounded loops run until a deadline. Under Callgrind the host clock runs 20 to 100 times faster relative to the program than it does natively, and it varies from run to run, so all of these turn into instruction-count noise.

**How it works**:
- A virtual clock advances by 1 ns per executed guest instruction: a 1 GHz CPU retiring one instruction per cycle. Valgrind's own work (translation, syscall wrappers, tool instrumentation) does not advance it.
- A core instrumentation pass adds the executed instruction count to the clock at every superblock exit and before every TSC read, so a syscall or TSC read always sees the instructions executed before it. It runs after the tool's instrumentation, so tool costs are unchanged.
- `clock_gettime` serves the realtime clocks (`REALTIME`, `REALTIME_COARSE`, `REALTIME_ALARM`, `TAI`) as a fixed epoch (2024-01-01T00:00:00Z) plus the virtual time, and the other standard clocks (`MONOTONIC`, `MONOTONIC_RAW`, `MONOTONIC_COARSE`, `BOOTTIME`, `BOOTTIME_ALARM`, `PROCESS_CPUTIME_ID`, `THREAD_CPUTIME_ID`) as the virtual time. `gettimeofday` and `time` follow the realtime clock. The vDSO is already disabled under Valgrind, so libc reaches these syscalls.
- `nanosleep` and `clock_nanosleep` move the virtual clock forward by the requested duration (or up to the absolute deadline) and return at once. Argument errors (`EINVAL`, `EFAULT`) match the kernel.
- On amd64, `RDTSC` and `RDTSCP` return the virtual time in nanoseconds (a 1 GHz TSC); `RDTSCP` reports `TSC_AUX` as 0. On arm64, `CNTVCT_EL0` returns the virtual time and `CNTFRQ_EL0` reports 1 GHz.
- A forked child continues from its parent's clock. Under `--trace-children=yes` each exec'd program starts again from zero.

**Usage**:
```bash
valgrind --tool=callgrind --deterministic-time=yes ./your_program
```

**Limitations**:
- Timeouts on blocking calls (`futex`, `poll`, `epoll_wait`, `select`), interval timers (`setitimer`, `timer_create`, `timerfd`, `alarm`), `getrusage` and `times` still use host time.
- The clock is global to the process. In multithreaded programs the thread interleaving still depends on the host, so time observed by one thread can vary with how much work other threads did first. A served sleep yields to other threads but does not block.
- `CPUID` still reports the host TSC frequency on amd64. Code that converts `RDTSC` deltas with it, instead of calibrating against `clock_gettime`, gets a scaled but still deterministic result.
- `clock_gettime` on dynamic clock ids (from `clock_getcpuclockid`) reaches the kernel.
- The epoch and the rate are fixed; there is no option to change them.

### Deterministic randomness: `--deterministic-rng`

**Feature**: Added `--deterministic-rng=no|yes` (default `no`). When enabled, randomness the client reads from the kernel or the CPU comes from a fixed-seed PRNG, so it is identical across runs.
Expand Down
9 changes: 9 additions & 0 deletions VEX/priv/guest_amd64_helpers.c
Original file line number Diff line number Diff line change
Expand Up @@ -3859,6 +3859,8 @@ ULong amd64g_calculate_pclmul(ULong a, ULong b, ULong which)
/* Horrible hack. On non-amd64 platforms, return 1. */
ULong amd64g_dirtyhelper_RDTSC ( void )
{
if (vex_virtual_tsc)
return *vex_virtual_tsc;
# if defined(__x86_64__)
UInt eax, edx;
__asm__ __volatile__("rdtsc" : "=a" (eax), "=d" (edx));
Expand All @@ -3877,6 +3879,13 @@ ULong amd64g_dirtyhelper_RDTSC ( void )
on amd64. */
void amd64g_dirtyhelper_RDTSCP ( VexGuestAMD64State* st )
{
if (vex_virtual_tsc) {
ULong tsc = *vex_virtual_tsc;
st->guest_RAX = tsc & 0xFFFFFFFFULL;
st->guest_RCX = 0;
st->guest_RDX = tsc >> 32;
return;
}
# if defined(__x86_64__)
UInt eax, ecx, edx;
__asm__ __volatile__("rdtscp" : "=a" (eax), "=d" (edx), "=c" (ecx));
Expand Down
4 changes: 4 additions & 0 deletions VEX/priv/guest_arm64_helpers.c
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,8 @@ ULong arm64g_dirtyhelper_MRS_DCZID_EL0 ( void )
/* Horrible hack. On non-arm64 platforms, return 0. */
ULong arm64g_dirtyhelper_MRS_CNTVCT_EL0 ( void )
{
if (vex_virtual_tsc)
return *vex_virtual_tsc;
# if defined(__aarch64__) && !defined(__arm__)
ULong w = 0x5555555555555555ULL; /* overwritten */
__asm__ __volatile__("mrs %0, cntvct_el0" : "=r"(w));
Expand All @@ -810,6 +812,8 @@ ULong arm64g_dirtyhelper_MRS_CNTVCT_EL0 ( void )
/* Horrible hack. On non-arm64 platforms, return 0. */
ULong arm64g_dirtyhelper_MRS_CNTFRQ_EL0 ( void )
{
if (vex_virtual_tsc)
return vex_virtual_tsc_hz;
# if defined(__aarch64__) && !defined(__arm__)
ULong w = 0x5555555555555555ULL; /* overwritten */
__asm__ __volatile__("mrs %0, cntfrq_el0" : "=r"(w));
Expand Down
2 changes: 2 additions & 0 deletions VEX/priv/guest_x86_helpers.c
Original file line number Diff line number Diff line change
Expand Up @@ -2285,6 +2285,8 @@ UInt x86g_calculate_aad_aam ( UInt flags_and_AX, UInt opcode )
/* Horrible hack. On non-x86 platforms, return 1. */
ULong x86g_dirtyhelper_RDTSC ( void )
{
if (vex_virtual_tsc)
return *vex_virtual_tsc;
# if defined(__i386__)
ULong res;
__asm__ __volatile__("rdtsc" : "=A" (res));
Expand Down
10 changes: 10 additions & 0 deletions VEX/priv/main_main.c
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,16 @@ void LibVEX_SetRandom32 ( UInt (*random32)(void) )
vex_random32 = random32;
}

const ULong* vex_virtual_tsc = NULL;
ULong vex_virtual_tsc_hz = 0;

void LibVEX_SetVirtualTSC ( const ULong* ticks, ULong hz )
{
vassert(vex_initdone);
vex_virtual_tsc = ticks;
vex_virtual_tsc_hz = hz;
}


/* Exported to library client. */

Expand Down
2 changes: 2 additions & 0 deletions VEX/priv/main_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@
#define NULL ((void*)0)

extern UInt (*vex_random32)(void);
extern const ULong* vex_virtual_tsc;
extern ULong vex_virtual_tsc_hz;

#if defined(_MSC_VER) // building with MSVC
# define LIKELY(x) (x)
Expand Down
5 changes: 5 additions & 0 deletions VEX/pub/libvex.h
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,11 @@ extern void LibVEX_Init (
The callback runs on the executing guest thread and returns 32 random bits. */
extern void LibVEX_SetRandom32 ( UInt (*random32)(void) );

/* Install before guest execution. NULL preserves the host counters.
TICKS is read on every RDTSC/RDTSCP (amd64) and CNTVCT_EL0 (arm64);
CNTFRQ_EL0 then reports HZ. RDTSCP reports TSC_AUX as 0. */
extern void LibVEX_SetVirtualTSC ( const ULong* ticks, ULong hz );


/*-------------------------------------------------------*/
/*--- Make a translation ---*/
Expand Down
4 changes: 3 additions & 1 deletion callgrind/tests/Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ EXTRA_DIST = \
prctl_get_auxv.stdout.exp \
deterministic_rng.vgtest deterministic_rng.stderr.exp \
deterministic_rng.stdout.exp \
deterministic_time.vgtest deterministic_time.stderr.exp \
deterministic_time.stdout.exp \
find_debuginfo.vgtest find_debuginfo.stderr.exp find_debuginfo.post.exp \
runtime_obj_skip_py.vgtest runtime_obj_skip_py.stderr.exp runtime_obj_skip_py.post.exp \
runtime_obj_skip_py.py runtime_obj_skip_py_shim.c \
Expand All @@ -46,7 +48,7 @@ EXTRA_DIST = \
inline-crossfile.vgtest inline-crossfile.stderr.exp inline-crossfile.stdout.exp inline-crossfile.post.exp \
inline-crossfile-helper1.h inline-crossfile-helper2.h filter_inline

check_PROGRAMS = clreq register_desc register_desc_threads find_debuginfo simwork threads inline-samefile inline-crossfile runtime_obj_skip_c runtime_obj_skip_underflow deterministic_rng
check_PROGRAMS = clreq register_desc register_desc_threads find_debuginfo simwork threads inline-samefile inline-crossfile runtime_obj_skip_c runtime_obj_skip_underflow deterministic_rng deterministic_time
if HAVE_PR_GET_AUXV
check_PROGRAMS += prctl_get_auxv
endif
Expand Down
166 changes: 166 additions & 0 deletions callgrind/tests/deterministic_time.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
/* Properties of the virtual clock that hold on every host and compiler:
the clocks agree with each other, sleeps move them forward instead of
waiting, and identical work takes identical time. Absolute values are
not pinned because the instruction count before main() depends on
libc. */
#define _GNU_SOURCE
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>

enum {
NS_PER_SEC = 1000000000,
EPOCH_SECS = 1704067200, /* 2024-01-01T00:00:00Z */
SLEEP_NS = 100 * 1000 * 1000,
/* Allowance for the instructions around a clock read. */
SLACK_NS = 1000 * 1000,
WORK_ITERATIONS = 100000,
BACK_TO_BACK_MAX_TICKS = 64,
};

static void check(const char* name, int ok)
{
printf("%s: %s\n", name, ok ? "ok" : "FAIL");
}

static int64_t now_ns(clockid_t clk)
{
struct timespec ts;
if (clock_gettime(clk, &ts) != 0) {
perror("clock_gettime");
return -1;
}
return ts.tv_sec * (int64_t)NS_PER_SEC + ts.tv_nsec;
}

static int64_t abs64(int64_t v) { return v < 0 ? -v : v; }

static int within_slack(int64_t measured, int64_t expected)
{
return measured >= expected && measured < expected + SLACK_NS;
}

static uint64_t read_tsc(void)
{
#if defined(__x86_64__)
uint32_t lo, hi;
__asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi));
return ((uint64_t)hi << 32) | lo;
#elif defined(__aarch64__)
uint64_t v;
__asm__ __volatile__("mrs %0, cntvct_el0" : "=r"(v));
return v;
#else
return 0;
#endif
}

static volatile uint64_t sink;

static int64_t timed_work(void)
{
int64_t start = now_ns(CLOCK_MONOTONIC);
uint64_t acc = 0;
for (unsigned i = 0; i < WORK_ITERATIONS; i++)
acc += (uint64_t)i * i;
sink = acc;
return now_ns(CLOCK_MONOTONIC) - start;
}

static void check_clocks(void)
{
struct timeval tv;
int64_t mono = now_ns(CLOCK_MONOTONIC);

check("realtime starts at the fixed epoch",
now_ns(CLOCK_REALTIME) / NS_PER_SEC == EPOCH_SECS);
check("gettimeofday agrees with realtime",
gettimeofday(&tv, NULL) == 0 && tv.tv_sec == EPOCH_SECS);
check("time agrees with realtime", time(NULL) == EPOCH_SECS);
check("monotonic advances with work",
now_ns(CLOCK_MONOTONIC) > mono &&
within_slack(now_ns(CLOCK_MONOTONIC) - mono, 0));
check("boottime agrees with monotonic",
within_slack(now_ns(CLOCK_BOOTTIME) - mono, 0));
check("process cputime agrees with monotonic",
within_slack(now_ns(CLOCK_PROCESS_CPUTIME_ID) - mono, 0));
}

static void check_sleeps(void)
{
struct timespec req = {0, SLEEP_NS};
struct timespec deadline;
int64_t before;

before = now_ns(CLOCK_MONOTONIC);
check("nanosleep succeeds", nanosleep(&req, NULL) == 0);
check("nanosleep advances the clock",
within_slack(now_ns(CLOCK_MONOTONIC) - before, SLEEP_NS));

clock_gettime(CLOCK_REALTIME, &deadline);
deadline.tv_sec += 1;
before = now_ns(CLOCK_REALTIME);
check("absolute sleep succeeds",
clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &deadline, NULL) == 0);
check("absolute sleep reaches its deadline",
within_slack(now_ns(CLOCK_REALTIME) - before, NS_PER_SEC));

deadline.tv_sec -= 10;
before = now_ns(CLOCK_REALTIME);
check("sleep until a past deadline returns at once",
clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &deadline, NULL) == 0 &&
within_slack(now_ns(CLOCK_REALTIME) - before, 0));
}

static void check_tsc(void)
{
struct timespec req = {0, SLEEP_NS};
uint64_t tsc_before = read_tsc();
int64_t mono_before = now_ns(CLOCK_MONOTONIC);
int64_t mono_after, tsc_delta;
uint64_t first, second;

nanosleep(&req, NULL);
mono_after = now_ns(CLOCK_MONOTONIC);
tsc_delta = (int64_t)(read_tsc() - tsc_before);
check("tsc ticks once per virtual nanosecond",
abs64(tsc_delta - (mono_after - mono_before)) < SLACK_NS);

/* Both reads sit in one superblock; the second must still see the
instructions between them. */
first = read_tsc();
second = read_tsc();
check("back-to-back tsc reads advance",
second > first && second - first < BACK_TO_BACK_MAX_TICKS);
}

static void check_errors(void)
{
struct timespec bad = {0, NS_PER_SEC};
struct timespec ts;

check("nanosleep rejects tv_nsec out of range",
nanosleep(&bad, NULL) == -1 && errno == EINVAL);
check("nanosleep rejects an unmapped request",
syscall(SYS_nanosleep, (void*)8, NULL) == -1 && errno == EFAULT);
check("clock_gettime rejects an unmapped result",
syscall(SYS_clock_gettime, CLOCK_MONOTONIC, (void*)8) == -1 &&
errno == EFAULT);
check("unknown clock ids reach the kernel",
clock_gettime(12345, &ts) == -1 && errno == EINVAL);
}

int main(void)
{
check_clocks();
check_sleeps();
check_tsc();
timed_work(); /* resolve PLT entries outside the comparison */
check("identical work takes identical time", timed_work() == timed_work());
check_errors();
return 0;
}
Empty file.
18 changes: 18 additions & 0 deletions callgrind/tests/deterministic_time.stdout.exp
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
realtime starts at the fixed epoch: ok
gettimeofday agrees with realtime: ok
time agrees with realtime: ok
monotonic advances with work: ok
boottime agrees with monotonic: ok
process cputime agrees with monotonic: ok
nanosleep succeeds: ok
nanosleep advances the clock: ok
absolute sleep succeeds: ok
absolute sleep reaches its deadline: ok
sleep until a past deadline returns at once: ok
tsc ticks once per virtual nanosecond: ok
back-to-back tsc reads advance: ok
identical work takes identical time: ok
nanosleep rejects tv_nsec out of range: ok
nanosleep rejects an unmapped request: ok
clock_gettime rejects an unmapped result: ok
unknown clock ids reach the kernel: ok
3 changes: 3 additions & 0 deletions callgrind/tests/deterministic_time.vgtest
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
prog: deterministic_time
vgopts: -q --deterministic-time=yes --callgrind-out-file=callgrind.out.deterministic_time
cleanup: rm -f callgrind.out.deterministic_time
2 changes: 2 additions & 0 deletions coregrind/Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@ noinst_HEADERS = \
pub_core_tooliface.h \
pub_core_trampoline.h \
pub_core_translate.h \
pub_core_vclock.h \
pub_core_transtab.h \
pub_core_transtab_asm.h \
pub_core_ume.h \
Expand Down Expand Up @@ -348,6 +349,7 @@ COREGRIND_SOURCES_COMMON = \
m_trampoline.S \
m_translate.c \
m_transtab.c \
m_vclock.c \
m_vki.c \
m_vkiscnums.c \
m_wordfm.c \
Expand Down
4 changes: 4 additions & 0 deletions coregrind/m_main.c
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ static void usage_NORETURN ( int need_help )
" they do not get under Valgrind\n"
" --deterministic-rng=no|yes serve AT_RANDOM, getrandom() and /dev/urandom\n"
" and hardware RNG insns from a fixed-seed PRNG [no]\n"
" --deterministic-time=no|yes serve clocks, sleeps and TSC reads from a\n"
" virtual clock of 1ns per guest instruction [no]\n"
" --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n"
" --vgdb=no|yes|full activate gdbserver? [yes]\n"
" full is slower but provides precise watchpoint/step\n"
Expand Down Expand Up @@ -574,6 +576,8 @@ static void process_option (Clo_Mode mode,
early_process_cmd_line_options. */
else if VG_BOOL_CLO(arg, "--sigill-diagnostics", VG_(clo_sigill_diag))
pos->sigill_diag_set = True;
else if VG_BOOL_CLOM(cloPD, arg, "--deterministic-time",
VG_(clo_deterministic_time)) {}

else if VG_BOOL_CLOM(cloPD, arg, "--stats", VG_(clo_stats)) {}
else if VG_BOOL_CLO(arg, "--xml", VG_(clo_xml))
Expand Down
1 change: 1 addition & 0 deletions coregrind/m_options.c
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ const HChar* VG_(clo_trace_children_skip) = NULL;
const HChar* VG_(clo_trace_children_skip_by_arg) = NULL;
const HChar* VG_(clo_allow_file_caps) = NULL;
Bool VG_(clo_deterministic_rng) = False;
Bool VG_(clo_deterministic_time) = False;
Bool VG_(clo_child_silent_after_fork) = False;
const HChar *VG_(clo_log_fname_unexpanded) = NULL;
const HChar *VG_(clo_xml_fname_unexpanded) = NULL;
Expand Down
7 changes: 7 additions & 0 deletions coregrind/m_syswrap/priv_syswrap-generic.h
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ extern SysRes ML_(rng_serve_proc_read)(ThreadId tid,
Long offset,
RngReadKind read_kind);

/* Copy N bytes into client memory; EFAULT if it is not writable. */
extern SysRes ML_(copy_to_client) (Addr dst, const void* src, SizeT n);
/* Complete a sleep on the virtual clock instead of blocking. Leaves
the syscall to the kernel for clocks it cannot sleep on. */
extern void ML_(vclock_serve_sleep) (SyscallStatus* status, UWord* flags,
Int clockid, Bool absolute, Addr req);

extern void ML_(record_fd_close) (ThreadId tid, Int fd);
extern Int ML_(get_fd_count) (void);
extern void ML_(record_fd_close_range) (ThreadId tid, Int fd);
Expand Down
Loading
Loading