diff --git a/.gitignore b/.gitignore index bd2496358..4585d63b1 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/CODSPEED-CHANGELOG.md b/CODSPEED-CHANGELOG.md index 6416e4bf7..d762ea94b 100644 --- a/CODSPEED-CHANGELOG.md +++ b/CODSPEED-CHANGELOG.md @@ -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. diff --git a/VEX/priv/guest_amd64_helpers.c b/VEX/priv/guest_amd64_helpers.c index e73845d5d..7090423d5 100644 --- a/VEX/priv/guest_amd64_helpers.c +++ b/VEX/priv/guest_amd64_helpers.c @@ -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)); @@ -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)); diff --git a/VEX/priv/guest_arm64_helpers.c b/VEX/priv/guest_arm64_helpers.c index e5260b782..03917c40a 100644 --- a/VEX/priv/guest_arm64_helpers.c +++ b/VEX/priv/guest_arm64_helpers.c @@ -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)); @@ -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)); diff --git a/VEX/priv/guest_x86_helpers.c b/VEX/priv/guest_x86_helpers.c index 90722d767..632ecbaaa 100644 --- a/VEX/priv/guest_x86_helpers.c +++ b/VEX/priv/guest_x86_helpers.c @@ -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)); diff --git a/VEX/priv/main_main.c b/VEX/priv/main_main.c index 646dce97b..54a83cd93 100644 --- a/VEX/priv/main_main.c +++ b/VEX/priv/main_main.c @@ -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. */ diff --git a/VEX/priv/main_util.h b/VEX/priv/main_util.h index 57fef2016..83c6b2299 100644 --- a/VEX/priv/main_util.h +++ b/VEX/priv/main_util.h @@ -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) diff --git a/VEX/pub/libvex.h b/VEX/pub/libvex.h index 564fe941d..6f6edb6d0 100644 --- a/VEX/pub/libvex.h +++ b/VEX/pub/libvex.h @@ -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 ---*/ diff --git a/callgrind/tests/Makefile.am b/callgrind/tests/Makefile.am index 0b7f9965d..0dc241660 100644 --- a/callgrind/tests/Makefile.am +++ b/callgrind/tests/Makefile.am @@ -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 \ @@ -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 diff --git a/callgrind/tests/deterministic_time.c b/callgrind/tests/deterministic_time.c new file mode 100644 index 000000000..185bc052d --- /dev/null +++ b/callgrind/tests/deterministic_time.c @@ -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 +#include +#include +#include +#include +#include +#include + +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; +} diff --git a/callgrind/tests/deterministic_time.stderr.exp b/callgrind/tests/deterministic_time.stderr.exp new file mode 100644 index 000000000..e69de29bb diff --git a/callgrind/tests/deterministic_time.stdout.exp b/callgrind/tests/deterministic_time.stdout.exp new file mode 100644 index 000000000..b8a9a93b6 --- /dev/null +++ b/callgrind/tests/deterministic_time.stdout.exp @@ -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 diff --git a/callgrind/tests/deterministic_time.vgtest b/callgrind/tests/deterministic_time.vgtest new file mode 100644 index 000000000..f530c3bf8 --- /dev/null +++ b/callgrind/tests/deterministic_time.vgtest @@ -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 diff --git a/coregrind/Makefile.am b/coregrind/Makefile.am index e7921ffaa..f480598bf 100644 --- a/coregrind/Makefile.am +++ b/coregrind/Makefile.am @@ -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 \ @@ -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 \ diff --git a/coregrind/m_main.c b/coregrind/m_main.c index 24ce30a43..6bd583917 100644 --- a/coregrind/m_main.c +++ b/coregrind/m_main.c @@ -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" @@ -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)) diff --git a/coregrind/m_options.c b/coregrind/m_options.c index c231ba8d7..4f4745723 100644 --- a/coregrind/m_options.c +++ b/coregrind/m_options.c @@ -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; diff --git a/coregrind/m_syswrap/priv_syswrap-generic.h b/coregrind/m_syswrap/priv_syswrap-generic.h index a3e9290f6..b53fc8717 100644 --- a/coregrind/m_syswrap/priv_syswrap-generic.h +++ b/coregrind/m_syswrap/priv_syswrap-generic.h @@ -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); diff --git a/coregrind/m_syswrap/syswrap-generic.c b/coregrind/m_syswrap/syswrap-generic.c index f8da46666..70ec58147 100644 --- a/coregrind/m_syswrap/syswrap-generic.c +++ b/coregrind/m_syswrap/syswrap-generic.c @@ -59,6 +59,7 @@ #include "pub_core_tooliface.h" #include "pub_core_ume.h" #include "pub_core_stacks.h" +#include "pub_core_vclock.h" #include "priv_types_n_macros.h" #include "priv_syswrap-generic.h" @@ -1885,6 +1886,37 @@ SysRes ML_(rng_serve_read)(ThreadId tid, Addr buf, SizeT n) return VG_(mk_SysRes_Success)(n); } +SysRes ML_(copy_to_client)(Addr dst, const void* src, SizeT n) +{ + if (!VG_(am_is_valid_for_client)(dst, n, VKI_PROT_WRITE)) + return VG_(mk_SysRes_Error)(VKI_EFAULT); + VG_(memcpy)((void*)dst, src, n); + return VG_(mk_SysRes_Success)(0); +} + +/* Checks run in kernel order: clock, then the request pointer, then + its contents. A completed sleep yields, as a real one would let + other threads run. */ +void ML_(vclock_serve_sleep)(SyscallStatus* status, UWord* flags, + Int clockid, Bool absolute, Addr req_addr) +{ + const struct vki_timespec* req = (const struct vki_timespec*)req_addr; + if (!VG_(vclock_can_sleep)(clockid)) + return; + *flags &= ~(SfMayBlock | SfPostOnFail); + if (!ML_(safe_to_deref)(req, sizeof(*req))) { + SET_STATUS_Failure(VKI_EFAULT); + return; + } + if (req->tv_sec < 0 || req->tv_nsec < 0 || req->tv_nsec >= 1000000000L) { + SET_STATUS_Failure(VKI_EINVAL); + return; + } + VG_(vclock_sleep)(clockid, absolute, req); + *flags |= SfYieldAfter; + SET_STATUS_Success(0); +} + /* The kernel truncates the count to 32 bits and copies the vector before filling buffers, which may overlap it. */ SysRes ML_(rng_serve_iovec)(ThreadId tid, Addr vec, UInt count, UInt rwf_flags) @@ -4623,6 +4655,21 @@ PRE(sys_gettimeofday) PRE_timeval_WRITE( "gettimeofday(tv)", (Addr)ARG1 ); if (ARG2 != 0) PRE_MEM_WRITE( "gettimeofday(tz)", ARG2, sizeof(struct vki_timezone) ); + + if (VG_(clo_deterministic_time)) { + struct vki_timespec ts; + struct vki_timeval tv; + struct vki_timezone tz = { 0, 0 }; + SysRes res = VG_(mk_SysRes_Success)(0); + VG_(vclock_gettime)(VKI_CLOCK_REALTIME, &ts); + tv.tv_sec = ts.tv_sec; + tv.tv_usec = ts.tv_nsec / 1000; + if (ARG1 != 0) + res = ML_(copy_to_client)(ARG1, &tv, sizeof(tv)); + if (ARG2 != 0 && !sr_isError(res)) + res = ML_(copy_to_client)(ARG2, &tz, sizeof(tz)); + SET_STATUS_from_SysRes(res); + } } POST(sys_gettimeofday) @@ -4995,6 +5042,9 @@ PRE(sys_nanosleep) PRE_MEM_READ( "nanosleep(req)", ARG1, sizeof(struct vki_timespec) ); if (ARG2 != 0) PRE_MEM_WRITE( "nanosleep(rem)", ARG2, sizeof(struct vki_timespec) ); + + if (VG_(clo_deterministic_time)) + ML_(vclock_serve_sleep)(status, flags, VKI_CLOCK_MONOTONIC, False, ARG1); } POST(sys_nanosleep) @@ -5636,6 +5686,17 @@ PRE(sys_time) if (ARG1 != 0) { PRE_MEM_WRITE( "time(t)", ARG1, sizeof(vki_time_t) ); } + + if (VG_(clo_deterministic_time)) { + struct vki_timespec ts; + vki_time_t t; + VG_(vclock_gettime)(VKI_CLOCK_REALTIME, &ts); + t = ts.tv_sec; + if (ARG1 != 0 && sr_isError(ML_(copy_to_client)(ARG1, &t, sizeof(t)))) + SET_STATUS_Failure(VKI_EFAULT); + else + SET_STATUS_Success(t); + } } POST(sys_time) diff --git a/coregrind/m_syswrap/syswrap-linux.c b/coregrind/m_syswrap/syswrap-linux.c index 1265b3e3e..d26aecbbd 100644 --- a/coregrind/m_syswrap/syswrap-linux.c +++ b/coregrind/m_syswrap/syswrap-linux.c @@ -51,6 +51,7 @@ #include "pub_core_scheduler.h" #include "pub_core_signals.h" #include "pub_core_stacks.h" +#include "pub_core_vclock.h" #include "pub_core_syscall.h" #include "pub_core_syswrap.h" #include "pub_core_inner.h" @@ -3225,6 +3226,12 @@ PRE(sys_clock_gettime) PRE_REG_READ2(long, "clock_gettime", vki_clockid_t, clk_id, struct timespec *, tp); PRE_MEM_WRITE( "clock_gettime(tp)", ARG2, sizeof(struct vki_timespec) ); + + if (VG_(clo_deterministic_time)) { + struct vki_timespec ts; + if (VG_(vclock_gettime)(SARG1, &ts)) + SET_STATUS_from_SysRes(ML_(copy_to_client)(ARG2, &ts, sizeof(ts))); + } } POST(sys_clock_gettime) { @@ -3289,6 +3296,10 @@ PRE(sys_clock_nanosleep) PRE_MEM_READ( "clock_nanosleep(rqtp)", ARG3, sizeof(struct vki_timespec) ); if (ARG4 != 0) PRE_MEM_WRITE( "clock_nanosleep(rmtp)", ARG4, sizeof(struct vki_timespec) ); + + if (VG_(clo_deterministic_time)) + ML_(vclock_serve_sleep)(status, flags, SARG1, + (ARG2 & VKI_TIMER_ABSTIME) != 0, ARG3); } POST(sys_clock_nanosleep) { diff --git a/coregrind/m_translate.c b/coregrind/m_translate.c index cfd2b5144..748cdfc6f 100644 --- a/coregrind/m_translate.c +++ b/coregrind/m_translate.c @@ -47,6 +47,7 @@ #include "pub_core_tooliface.h" // VG_(tdict) #include "pub_core_translate.h" +#include "pub_core_vclock.h" // VG_(vclock_instrument) #include "pub_core_transtab.h" #include "pub_core_dispatch.h" // VG_(run_innerloop__dispatch_{un}profiled) // VG_(run_a_noredir_translation__return_point) @@ -685,6 +686,25 @@ IRSB* vg_SP_update_pass ( void* closureV, #undef DO_DIE } +/* The core's own instrumentation, run after the tool's. */ +static +IRSB* vg_core_instrument_pass ( void* closureV, + IRSB* sb_in, + const VexGuestLayout* layout, + const VexGuestExtents* vge, + const VexArchInfo* vai, + IRType gWordTy, + IRType hWordTy ) +{ + if (need_to_handle_SP_assignment()) + sb_in = vg_SP_update_pass(closureV, sb_in, layout, vge, vai, + gWordTy, hWordTy); + if (VG_(clo_deterministic_time)) + sb_in = VG_(vclock_instrument)(closureV, sb_in, layout, vge, vai, + gWordTy, hWordTy); + return sb_in; +} + /*------------------------------------------------------------*/ /*--- Main entry point for the JITter. ---*/ /*------------------------------------------------------------*/ @@ -1530,6 +1550,8 @@ Bool VG_(translate) ( ThreadId tid, &VG_(clo_vex_control) ); if (VG_(clo_deterministic_rng)) LibVEX_SetRandom32(&deterministic_random32); + if (VG_(clo_deterministic_time)) + LibVEX_SetVirtualTSC(&VG_(vclock_ns), VG_VCLOCK_TSC_HZ); vex_init_done = True; } @@ -1802,8 +1824,9 @@ Bool VG_(translate) ( ThreadId tid, vta.instrument1 = g; } /* No need for type kludgery here. */ - vta.instrument2 = need_to_handle_SP_assignment() - ? vg_SP_update_pass + vta.instrument2 = (need_to_handle_SP_assignment() + || VG_(clo_deterministic_time)) + ? vg_core_instrument_pass : NULL; vta.finaltidy = VG_(needs).final_IR_tidy_pass ? VG_(tdict).tool_final_IR_tidy_pass diff --git a/coregrind/m_vclock.c b/coregrind/m_vclock.c new file mode 100644 index 000000000..588c17da6 --- /dev/null +++ b/coregrind/m_vclock.c @@ -0,0 +1,202 @@ + +/*--------------------------------------------------------------------*/ +/*--- A virtual clock driven by guest instructions. m_vclock.c ---*/ +/*--------------------------------------------------------------------*/ + +/* + This file is part of Valgrind, a dynamic binary instrumentation + framework. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see . + + The GNU General Public License is contained in the file COPYING. +*/ + +#include "pub_core_basics.h" +#include "pub_core_vki.h" +#include "pub_core_libcbase.h" +#include "pub_core_vclock.h" + +/* Guest code runs under the big lock, so a plain read-modify-write + from generated code is safe. */ +ULong VG_(vclock_ns) = 0; + +/* CLOCK_REALTIME at virtual time zero: 2024-01-01T00:00:00Z. */ +#define VCLOCK_EPOCH_SECS 1704067200ULL +#define NS_PER_SEC 1000000000ULL + +#if defined(VG_BIGENDIAN) +# define VCLOCK_IEND Iend_BE +#else +# define VCLOCK_IEND Iend_LE +#endif + +/*--- Instrumentation ---*/ + +/* Emit VG_(vclock_ns) += n_insns * VG_VCLOCK_NS_PER_INSN as flat IR. */ +static void add_elapsed ( IRSB* bb, UInt n_insns ) +{ + IRExpr* addr = mkIRExpr_HWord((HWord)&VG_(vclock_ns)); + IRTemp cur = newIRTemp(bb->tyenv, Ity_I64); + IRTemp next = newIRTemp(bb->tyenv, Ity_I64); + ULong delta = (ULong)n_insns * VG_VCLOCK_NS_PER_INSN; + + addStmtToIRSB(bb, IRStmt_WrTmp(cur, + IRExpr_Load(VCLOCK_IEND, Ity_I64, addr))); + addStmtToIRSB(bb, IRStmt_WrTmp(next, + IRExpr_Binop(Iop_Add64, IRExpr_RdTmp(cur), + IRExpr_Const(IRConst_U64(delta))))); + addStmtToIRSB(bb, IRStmt_Store(VCLOCK_IEND, addr, IRExpr_RdTmp(next))); +} + +/* Dirty helpers that read the virtual TSC (see LibVEX_SetVirtualTSC). */ +static Bool reads_tsc ( const IRStmt* st ) +{ + const HChar* name; + if (st->tag != Ist_Dirty) + return False; + name = st->Ist.Dirty.details->cee->name; + return VG_(strcmp)(name, "amd64g_dirtyhelper_RDTSC") == 0 + || VG_(strcmp)(name, "amd64g_dirtyhelper_RDTSCP") == 0 + || VG_(strcmp)(name, "x86g_dirtyhelper_RDTSC") == 0 + || VG_(strcmp)(name, "arm64g_dirtyhelper_MRS_CNTVCT_EL0") == 0; +} + +/* Instructions are counted by their IMarks. The count accumulated since + the previous update is flushed before every conditional exit, before + every TSC read and at the end of the block, so any path through the + block adds exactly the instructions it executed and a TSC read sees + them. Tools keep IMarks, so this runs correctly after their + instrumentation. */ +IRSB* VG_(vclock_instrument) ( void* closureV, + IRSB* sb_in, + const VexGuestLayout* layout, + const VexGuestExtents* vge, + const VexArchInfo* vai, + IRType gWordTy, + IRType hWordTy ) +{ + IRSB* bb = deepCopyIRSBExceptStmts(sb_in); + UInt pending = 0; + Int i; + + for (i = 0; i < sb_in->stmts_used; i++) { + IRStmt* st = sb_in->stmts[i]; + if (st->tag == Ist_IMark) + pending++; + if (pending > 0 && (st->tag == Ist_Exit || reads_tsc(st))) { + add_elapsed(bb, pending); + pending = 0; + } + addStmtToIRSB(bb, st); + } + if (pending > 0) + add_elapsed(bb, pending); + return bb; +} + +/*--- Clocks ---*/ + +typedef enum { ClockUnknown, ClockRealtime, ClockElapsed } ClockKind; + +static ClockKind clock_kind ( Int clockid ) +{ + switch (clockid) { + case VKI_CLOCK_REALTIME: + case VKI_CLOCK_REALTIME_COARSE: + case VKI_CLOCK_REALTIME_ALARM: + case VKI_CLOCK_TAI: + return ClockRealtime; + case VKI_CLOCK_MONOTONIC: + case VKI_CLOCK_MONOTONIC_RAW: + case VKI_CLOCK_MONOTONIC_COARSE: + case VKI_CLOCK_BOOTTIME: + case VKI_CLOCK_BOOTTIME_ALARM: + case VKI_CLOCK_PROCESS_CPUTIME_ID: + case VKI_CLOCK_THREAD_CPUTIME_ID: + return ClockElapsed; + default: + return ClockUnknown; + } +} + +static ULong clock_now_ns ( ClockKind kind ) +{ + ULong ns = VG_(vclock_ns); + if (kind == ClockRealtime) + ns += VCLOCK_EPOCH_SECS * NS_PER_SEC; + return ns; +} + +Bool VG_(vclock_gettime) ( Int clockid, struct vki_timespec* ts ) +{ + ClockKind kind = clock_kind(clockid); + ULong ns; + if (kind == ClockUnknown) + return False; + ns = clock_now_ns(kind); + ts->tv_sec = ns / NS_PER_SEC; + ts->tv_nsec = ns % NS_PER_SEC; + return True; +} + +/* The kernel refuses to sleep on the coarse clocks and on another + thread's CPU clock. */ +Bool VG_(vclock_can_sleep) ( Int clockid ) +{ + switch (clockid) { + case VKI_CLOCK_REALTIME: + case VKI_CLOCK_REALTIME_ALARM: + case VKI_CLOCK_TAI: + case VKI_CLOCK_MONOTONIC: + case VKI_CLOCK_BOOTTIME: + case VKI_CLOCK_BOOTTIME_ALARM: + case VKI_CLOCK_PROCESS_CPUTIME_ID: + return True; + default: + return False; + } +} + +/* The clock never exceeds this, so the realtime offset cannot wrap. */ +#define VCLOCK_MAX_NS (~0ULL - VCLOCK_EPOCH_SECS * NS_PER_SEC) + +/* Saturate instead of wrapping for absurdly long sleeps. */ +static ULong timespec_to_ns ( const struct vki_timespec* ts ) +{ + ULong secs = (ULong)ts->tv_sec; + if (secs > (~0ULL - (ULong)ts->tv_nsec) / NS_PER_SEC) + return ~0ULL; + return secs * NS_PER_SEC + (ULong)ts->tv_nsec; +} + +void VG_(vclock_sleep) ( Int clockid, Bool absolute, + const struct vki_timespec* req ) +{ + ULong target = timespec_to_ns(req); + if (absolute) { + ULong now = clock_now_ns(clock_kind(clockid)); + if (target <= now) + return; + target -= now; + } + if (target > VCLOCK_MAX_NS - VG_(vclock_ns)) + VG_(vclock_ns) = VCLOCK_MAX_NS; + else + VG_(vclock_ns) += target; +} + +/*--------------------------------------------------------------------*/ +/*--- end ---*/ +/*--------------------------------------------------------------------*/ diff --git a/coregrind/pub_core_options.h b/coregrind/pub_core_options.h index b145dc8ba..50c9fd017 100644 --- a/coregrind/pub_core_options.h +++ b/coregrind/pub_core_options.h @@ -129,6 +129,9 @@ extern const HChar* VG_(clo_trace_children_skip_by_arg); without those capabilities, since Valgrind loads them itself. */ extern const HChar* VG_(clo_allow_file_caps); extern Bool VG_(clo_deterministic_rng); +/* Serve clocks from a virtual clock driven by the executed guest + instruction count instead of host time. */ +extern Bool VG_(clo_deterministic_time); /* After a fork, the child's output can become confusingly intermingled with the parent's output. This is especially problematic when VG_(clo_xml) is True. Setting diff --git a/coregrind/pub_core_vclock.h b/coregrind/pub_core_vclock.h new file mode 100644 index 000000000..1931ca27a --- /dev/null +++ b/coregrind/pub_core_vclock.h @@ -0,0 +1,76 @@ + +/*--------------------------------------------------------------------*/ +/*--- A virtual clock driven by guest instructions. pub_core_vclock.h ---*/ +/*--------------------------------------------------------------------*/ + +/* + This file is part of Valgrind, a dynamic binary instrumentation + framework. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see . + + The GNU General Public License is contained in the file COPYING. +*/ + +#ifndef __PUB_CORE_VCLOCK_H +#define __PUB_CORE_VCLOCK_H + +//-------------------------------------------------------------------- +// PURPOSE: With --deterministic-time=yes, every clock the client can +// read is derived from the number of guest instructions executed so +// far, so a given instruction stream always observes the same time. +// Host time never reaches the client. +//-------------------------------------------------------------------- + +#include "pub_core_basics.h" +#include "pub_core_vki.h" +#include "libvex.h" + +/* The virtual CPU retires one instruction per nanosecond. The TSC + (rdtsc, CNTVCT_EL0) ticks once per nanosecond as well. */ +#define VG_VCLOCK_NS_PER_INSN 1ULL +#define VG_VCLOCK_TSC_HZ 1000000000ULL + +/* Nanoseconds elapsed since the client started. Generated code adds + executed instructions to it; sleeps add their duration. */ +extern ULong VG_(vclock_ns); + +/* VEX instrument2 pass: add the executed instruction count of each + path through the superblock to VG_(vclock_ns). */ +extern IRSB* VG_(vclock_instrument) ( void* closureV, + IRSB* sb_in, + const VexGuestLayout* layout, + const VexGuestExtents* vge, + const VexArchInfo* vai, + IRType gWordTy, + IRType hWordTy ); + +/* Fill *ts with the virtual time of CLOCKID. Returns False for clocks + the kernel must serve (dynamic and unknown ids). */ +extern Bool VG_(vclock_gettime) ( Int clockid, struct vki_timespec* ts ); + +/* Whether a sleep on CLOCKID is served here; otherwise the kernel + handles it and reports the error it would normally give. */ +extern Bool VG_(vclock_can_sleep) ( Int clockid ); + +/* Complete a sleep by moving the virtual clock forward. REQ is a valid + timespec, relative to now, or absolute on CLOCKID when ABSOLUTE. */ +extern void VG_(vclock_sleep) ( Int clockid, Bool absolute, + const struct vki_timespec* req ); + +#endif // __PUB_CORE_VCLOCK_H + +/*--------------------------------------------------------------------*/ +/*--- end ---*/ +/*--------------------------------------------------------------------*/ diff --git a/docs/xml/manual-core.xml b/docs/xml/manual-core.xml index d82bea4b8..2fd578623 100644 --- a/docs/xml/manual-core.xml +++ b/docs/xml/manual-core.xml @@ -863,6 +863,38 @@ in most cases. We group the available options by rough categories. + + + + + + When enabled, every clock the client can read is derived + from the number of guest instructions executed so far, at + 1 ns per instruction, so the same instruction stream always + observes the same time. Valgrind's own work does not advance + the clock. clock_gettime + serves the realtime clocks as a fixed epoch + (2024-01-01T00:00:00Z) plus the virtual time and the monotonic, + boottime and CPU-time clocks as the virtual time; + gettimeofday and + time follow the realtime clock. + nanosleep and + clock_nanosleep move the clock + forward by the requested duration and return at once. On + amd64, RDTSC and + RDTSCP return the virtual time + in nanoseconds; on arm64, + CNTVCT_EL0 does the same and + CNTFRQ_EL0 reports 1 GHz. + Timeouts on blocking calls, interval timers, + getrusage and + times still use host time. + The clock is shared by all threads, so in multithreaded programs + the time one thread observes still depends on the host's + thread interleaving. The epoch and rate cannot be changed. + + + diff --git a/include/vki/vki-linux.h b/include/vki/vki-linux.h index 8d9c957a1..5921e59c1 100644 --- a/include/vki/vki-linux.h +++ b/include/vki/vki-linux.h @@ -304,6 +304,15 @@ struct vki_sysinfo { #define VKI_CLOCK_MONOTONIC 1 #define VKI_CLOCK_PROCESS_CPUTIME_ID 2 #define VKI_CLOCK_THREAD_CPUTIME_ID 3 +#define VKI_CLOCK_MONOTONIC_RAW 4 +#define VKI_CLOCK_REALTIME_COARSE 5 +#define VKI_CLOCK_MONOTONIC_COARSE 6 +#define VKI_CLOCK_BOOTTIME 7 +#define VKI_CLOCK_REALTIME_ALARM 8 +#define VKI_CLOCK_BOOTTIME_ALARM 9 +#define VKI_CLOCK_TAI 11 + +#define VKI_TIMER_ABSTIME 0x01 struct vki_timespec { vki_time_t tv_sec; /* seconds */ diff --git a/none/tests/cmdline1.stdout.exp b/none/tests/cmdline1.stdout.exp index 112905132..bc047359f 100644 --- a/none/tests/cmdline1.stdout.exp +++ b/none/tests/cmdline1.stdout.exp @@ -24,6 +24,8 @@ usage: valgrind [options] prog-and-args they do not get under Valgrind --deterministic-rng=no|yes serve AT_RANDOM, getrandom() and /dev/urandom and hardware RNG insns from a fixed-seed PRNG [no] + --deterministic-time=no|yes serve clocks, sleeps and TSC reads from a + virtual clock of 1ns per guest instruction [no] --child-silent-after-fork=no|yes omit child output between fork & exec? [no] --vgdb=no|yes|full activate gdbserver? [yes] full is slower but provides precise watchpoint/step diff --git a/none/tests/cmdline2.stdout.exp b/none/tests/cmdline2.stdout.exp index 926a2513a..0750b6765 100644 --- a/none/tests/cmdline2.stdout.exp +++ b/none/tests/cmdline2.stdout.exp @@ -24,6 +24,8 @@ usage: valgrind [options] prog-and-args they do not get under Valgrind --deterministic-rng=no|yes serve AT_RANDOM, getrandom() and /dev/urandom and hardware RNG insns from a fixed-seed PRNG [no] + --deterministic-time=no|yes serve clocks, sleeps and TSC reads from a + virtual clock of 1ns per guest instruction [no] --child-silent-after-fork=no|yes omit child output between fork & exec? [no] --vgdb=no|yes|full activate gdbserver? [yes] full is slower but provides precise watchpoint/step