summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDaniel Kahn Gillmor <dkg@fifthhorseman.net>2021-02-23 21:42:42 -0500
committerDaniel Kahn Gillmor <dkg@fifthhorseman.net>2021-02-23 22:19:08 -0500
commit004222585e0c0300be491f296f1f6f7713e34fd9 (patch)
treee62e0b349208b4911c8cf36ced968f4a3c769850
parent46dc62564280cbe59d38073bdb0a57219c819213 (diff)
downloadlibfaketime-004222585e0c0300be491f296f1f6f7713e34fd9.tar.gz
Enable intercepting getpid()
I went with the runtime environment variable being FAKETIME_FAKEPID since it seems less likely to collide with anything else. Closes: #297
-rw-r--r--src/Makefile3
-rw-r--r--src/libfaketime.c23
-rwxr-xr-xtest/pidtest.sh19
3 files changed, 45 insertions, 0 deletions
diff --git a/src/Makefile b/src/Makefile
index 2af4804..e8c7fac 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -41,6 +41,9 @@
# FAKE_RANDOM
# - Intercept getrandom()
#
+# FAKE_PID
+# - Intercept getpid()
+#
# FORCE_MONOTONIC_FIX
# - If the test program hangs forever on
# " pthread_cond_timedwait: CLOCK_MONOTONIC test
diff --git a/src/libfaketime.c b/src/libfaketime.c
index a09bae2..ccf5164 100644
--- a/src/libfaketime.c
+++ b/src/libfaketime.c
@@ -226,6 +226,9 @@ static int (*real_futimens) (int fd, const struct timespec times
#ifdef FAKE_RANDOM
static ssize_t (*real_getrandom) (void *buf, size_t buflen, unsigned int flags);
#endif
+#ifdef FAKE_PID
+static pid_t (*real_getpid) ();
+#endif
static int initialized = 0;
@@ -2453,6 +2456,10 @@ static void ftpl_init(void)
real_getrandom = dlsym(RTLD_NEXT, "getrandom");
#endif
+#ifdef FAKE_PID
+ real_getpid = dlsym(RTLD_NEXT, "getpid");
+#endif
+
#ifdef FAKE_PTHREAD
#ifdef __GLIBC__
@@ -3689,6 +3696,22 @@ ssize_t getrandom(void *buf, size_t buflen, unsigned int flags) {
}
#endif
+#ifdef FAKE_PID
+pid_t getpid() {
+ const char *pidstring = getenv("FAKETIME_FAKEPID");
+ if (pidstring != NULL) {
+ long int pid = strtol(pidstring, NULL, 0);
+ return (pid_t)(pid);
+ } else {
+ if (!initialized)
+ {
+ ftpl_init();
+ }
+ return real_getpid();
+ }
+}
+#endif
+
/*
* Editor modelines
*
diff --git a/test/pidtest.sh b/test/pidtest.sh
new file mode 100755
index 0000000..617bad8
--- /dev/null
+++ b/test/pidtest.sh
@@ -0,0 +1,19 @@
+#!/bin/sh
+
+FTPL="${FAKETIME_TESTLIB:-../src/libfaketime.so.1}"
+
+set -e
+run1=$(LD_PRELOAD="$FTPL" sh -c 'echo $$')
+run2=$(LD_PRELOAD="$FTPL" sh -c 'echo $$')
+
+if [ $run1 = $run2 ]; then
+ printf >&2 'got the same pid twice in a row without setting FAKETIME_FAKEPID\n'
+ exit 1
+fi
+
+output=$(FAKETIME_FAKEPID=13 LD_PRELOAD="$FTPL" sh -c 'echo $$')
+
+if [ $output != 13 ]; then
+ printf >&2 'Failed to enforce a rigid response to getpid()\n'
+ exit 2
+fi