Running self-tests under valgrind
=================================

For projects written in C or similar languages, running the self-tests under Valgrind can reveal hard to find memory issues.  Gnulib supports two ways to make use of Valgrind: one that enables use of Valgrind at configure time, when configure found it to be present; and one at the discretion of the developer.

Using valgrind without developer intervention
---------------------------------------------

The valgrind-tests module searches for Valgrind at configure time and declares the VALGRIND automake variable for use with automake's TESTS_ENVIRONMENT.

After importing the valgrind-tests module to your project, you use it by adding the following to the Makefile.am that runs the self-tests:

     TESTS_ENVIRONMENT = $(VALGRIND)

This will run all self-checks under valgrind.

Using valgrind at the developer's discretion
--------------------------------------------

In this approach, you define a Makefile.am variable VALGRIND (or, more abstractly, CHECKER), that is usually set to empty. When you have configured and built the package and you decide that you want to run the tests with valgrind, you do so by modifying the definition of VALGRIND in the Makefile.

How to use Valgrind with shell scripts
--------------------------------------

It is not desirable to apply valgrind to shell scripts or other non-binaries, because

  * It is wasteful, and you usually don't want to look for memory leaks in bash.

  * On a bi-arch system, you may get an error message such as "valgrind: wrong executable class (eg. 32-bit instead of 64-bit)".

There are two ways to avoid this:

  * You can make use of the build-aux/run-test script from Gnulib. Add these lines to your Makefile.am:

          # This must be the last thing that gets added to TESTS_ENVIRONMENT.
          TESTS_ENVIRONMENT += $(SHELL) $(top_srcdir)/build-aux/run-test '$(VALGRIND)'

  * Using the Automake parallel-tests feature, you can use the following instead:

          AUTOMAKE_OPTIONS = parallel-tests
          TEST_EXTENSIONS = .pl .sh
          LOG_COMPILER = $(VALGRIND)

     Then valgrind will only be used for the non-.sh and non-.pl tests.

However, with this measure in place, binaries invoked through scripts will not be invoked under valgrind.  This can be solved by defining environment variables in the TESTS_ENVIRONMENT variable that are then used by the shell scripts.  For example, add the following:

     TESTS_ENVIRONMENT = VALGRIND='$(VALGRIND)'

And then modify the shell scripts to invoke the binary prefixed with $VALGRIND.