fixed_clock.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // LD_PRELOAD shim for regression renders: the wall clock (time(), gettimeofday(),
  2. // clock_gettime(CLOCK_REALTIME*)) always reads LWE_FIXED_CLOCK (unix seconds). That covers
  3. // the day/night uniform, text clocks and script Date objects (V8's Math.random seed is pinned by the engine
  4. // itself, --random-seed under LWE_FIXED_TIMESTEP).
  5. // Monotonic clocks are left alone so frame pacing and timeouts keep working.
  6. #define _GNU_SOURCE
  7. #include <dlfcn.h>
  8. #include <stdlib.h>
  9. #include <sys/time.h>
  10. #include <time.h>
  11. static time_t fixed_seconds (void) {
  12. static time_t value = -1;
  13. if (value == -1) {
  14. const char* env = getenv ("LWE_FIXED_CLOCK");
  15. value = env != NULL ? (time_t) strtoll (env, NULL, 10) : 1767268800; // 2026-01-01 12:00 UTC
  16. }
  17. return value;
  18. }
  19. time_t time (time_t* out) {
  20. const time_t now = fixed_seconds ();
  21. if (out != NULL) {
  22. *out = now;
  23. }
  24. return now;
  25. }
  26. int gettimeofday (struct timeval* tv, void* tz) {
  27. if (tv != NULL) {
  28. tv->tv_sec = fixed_seconds ();
  29. tv->tv_usec = 0;
  30. }
  31. return 0;
  32. }
  33. int clock_gettime (clockid_t clock, struct timespec* ts) {
  34. static int (*real) (clockid_t, struct timespec*) = NULL;
  35. if (clock == CLOCK_REALTIME || clock == CLOCK_REALTIME_COARSE) {
  36. ts->tv_sec = fixed_seconds ();
  37. ts->tv_nsec = 0;
  38. return 0;
  39. }
  40. if (real == NULL) {
  41. real = (int (*) (clockid_t, struct timespec*)) dlsym (RTLD_NEXT, "clock_gettime");
  42. }
  43. return real (clock, ts);
  44. }