Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Make libsthtread valgrind-aware.
authorArnaud Giersch <arnaud.giersch@univ-fcomte.fr>
Fri, 1 Jul 2022 15:04:19 +0000 (17:04 +0200)
committerArnaud Giersch <arnaud.giersch@univ-fcomte.fr>
Sat, 2 Jul 2022 19:59:31 +0000 (21:59 +0200)
Without this change, libsthread is initialized twice when using valgrind:
one for the valgrind launcher, and one for the target program.

Use the environment variable VALGRIND_LIB to detect the usage of valgrind,
and don't divert main() when RUNNING_ON_VALGRIND returns 0.

Just hope that noboby has VALGRIND_LIB in its environment without using valgrind.
In this case, the check can be reinforced by looking for the substring "valgrind" in argv[0].

For example, run:
valgrind --trace-children=yes env LD_PRELOAD=./lib/libsthread.so ./examples/sthread/pthread-mutex-simple

src/sthread/sthread.c

index 666cb36..24213e0 100644 (file)
@@ -1,12 +1,18 @@
 /* SimGrid's pthread interposer. Redefinition of the pthread symbols (see the comment in sthread.h) */
 
 #define _GNU_SOURCE
+#include "src/internal_config.h"
 #include "src/sthread/sthread.h"
 #include <dlfcn.h>
 #include <pthread.h>
 #include <semaphore.h>
 #include <stdio.h>
 
+#if HAVE_VALGRIND_H
+#include <stdlib.h>
+#include <valgrind/valgrind.h>
+#endif
+
 /* We don't want to intercept pthread within simgrid. Instead we should provide the real implem to simgrid */
 static int (*raw_pthread_create)(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*);
 static int (*raw_pthread_join)(pthread_t, void**);
@@ -212,5 +218,10 @@ int __libc_start_main(int (*main)(int, char**, char**), int argc, char** argv, i
   /* Find the real __libc_start_main()... */
   typeof(&__libc_start_main) orig = dlsym(RTLD_NEXT, "__libc_start_main");
   /* ... and call it with our custom main function */
+#if HAVE_VALGRIND_H
+  /* ... unless valgrind is used, and this instance is not the target program (but the valgrind launcher) */
+  if (getenv("VALGRIND_LIB") && !RUNNING_ON_VALGRIND)
+    return orig(raw_main, argc, argv, init, fini, rtld_fini, stack_end);
+#endif
   return orig(main_hook, argc, argv, init, fini, rtld_fini, stack_end);
 }