Documentation/Debugging with Valgrind

From QEMU

Valgrind

Valgrind works much like QEMU's TCG mode except it has a focus on debugging and testing. You can use it to detect memory corruption and leaks within QEMU as well as threading errors.

memcheck

memcheck is the default tool in valgrind and detects memory leaks, misuses of library functions, use of undefined memory and more. See memcheck manual more details.

helgrind/drd

helgrind and drd detect problems in multi-threaded programs. Right now additional work and annotations are necessary to make this useful for QEMU, as the happens-before machine of valgrind does not work very well with QEMUs rfifolock and its unlocked accesses of several shared variables via memory barriers.

KVM Based QEMU

valgrind's memcheck tool can be used fine with KVM-based QEMU. To avoid false positives some considerations have to be made regarding KVM ioctls when writing code. Newer versions of valgrind have already some annotations for several kvm ioctls and newer versions of QEMU have patches to quiesce false positives.

ioctl handling

All ioctls have to either follow the _IO[R][W] logic or need specific handlers in valgrind.

Valgrind has a default handler for unknown ioctls that parses the _IO[R][W] definition. So in case of an _IOxW ioctl with a structure as parameter, it will complain about undefined parameters if any byte of that structure is not pre-initialized. This is also true for padding and compiler alignment. The most simple "fix" is a designated initializer, e.g.

   struct kvm_blah blah = {
       .field1 = 1,
};

TCG Based QEMU

You will need to use the --smc-check=all (or --smc-check=all-non-file with newer valgrind versions) option to instruct valgrind to detect self-modifying code which TCG makes extensive use of.

softmmu debugging

Valgrind can be simply run by putting the it in-front on your qemu-system invocation

linux-user debugging

This is potentially complicated by the fact that a qemu-linux-user instance is usually run in a guest chroot. However with multi-arch systems you can bind mount the required host paths into your chroot so valgrind (and non-static qemu binaries) can run.

See Also

Another approach is to compile QEMU with a sanitizer enabled compiler. A lot of the same checks valgrind runs can be done with an instrumented build a lot faster.