# Detecting when a port is running under Valgrind



## Paul Floyd (Nov 22, 2021)

Over the weekend I analyzed (and Yuri fixed) a problem with google-perftools. Ports that use this would likely crash when running under Valgrind.

I was wondering if there are any other ports that have the same problem.

If you are a port maintainer and your port has its own memory pool or memory manager, please could you check whether it is using the RUNNING_UNDER_VALGRIND macro?

For info the code in question originally was


```
static int GetRunningOnValgrind(void) {
#ifdef RUNNING_ON_VALGRIND
  if (RUNNING_ON_VALGRIND) return 1;
#endif
  const char *running_on_valgrind_str = TCMallocGetenvSafe("RUNNING_ON_VALGRIND");
  if (running_on_valgrind_str) {
    return strcmp(running_on_valgrind_str, "0") != 0;
  }
  return 0;
}
```

which requires the user to know about the RUNNING_ON_VALGRIND environment variable and to set it (Valgrind does not set it).

It seems that google-perftools does not have a configure option to detect that Valgrind is installed and if so include "valgrind.h". It has this comment in the header for the above C source file.


```
/* Return non-zero value if running under valgrind.

  If "valgrind.h" is included into dynamic_annotations.c,
  the regular valgrind mechanism will be used.
  See http://valgrind.org/docs/manual/manual-core-adv.html about
  RUNNING_ON_VALGRIND and other valgrind "client requests".
  The file "valgrind.h" may be obtained by doing
     svn co svn://svn.valgrind.org/valgrind/trunk/include

  If for some reason you can't use "valgrind.h" or want to fake valgrind,
  there are two ways to make this function return non-zero:
    - Use environment variable: export RUNNING_ON_VALGRIND=1
    - Make your tool intercept the function RunningOnValgrind() and
      change its return value.
 */
```

The patch that Yuri created is https://github.com/freebsd/freebsd-...s/files/patch-src_base_dynamic__annotations.c which checks LD_[32_]PRELOAD instead,


----------

