xref: /qemu/docs/devel/testing/main.rst (revision 52e9ed6d3ac44424e098333772077a41bb88c4db)
1.. _testing:
2
3Testing in QEMU
4===============
5
6QEMU's testing infrastructure is fairly complex as it covers
7everything from unit testing and exercising specific sub-systems all
8the way to full blown functional tests. To get an overview of the
9tests you can run ``make check-help`` from either the source or build
10tree.
11
12Most (but not all) tests are also integrated as an automated test into
13the meson build system so can be run directly from the build tree,
14for example::
15
16  [./pyvenv/bin/]meson test --suite qemu:softfloat
17
18will run just the softfloat tests.
19
20An automated test is written with one of the test frameworks using its
21generic test functions/classes. The test framework can run the tests and
22report their success or failure [1]_.
23
24An automated test has essentially three parts:
25
261. The test initialization of the parameters, where the expected parameters,
27   like inputs and expected results, are set up;
282. The call to the code that should be tested;
293. An assertion, comparing the result from the previous call with the expected
30   result set during the initialization of the parameters. If the result
31   matches the expected result, the test has been successful; otherwise, it has
32   failed.
33
34The rest of this document will cover the details for specific test
35groups.
36
37Testing with "make check"
38-------------------------
39
40The "make check" testing family includes most of the C based tests in QEMU.
41
42The usual way to run these tests is:
43
44.. code::
45
46  make check
47
48which includes QAPI schema tests, unit tests, QTests and some iotests.
49Different sub-types of "make check" tests will be explained below.
50
51Before running tests, it is best to build QEMU programs first. Some tests
52expect the executables to exist and will fail with obscure messages if they
53cannot find them.
54
55.. _unit-tests:
56
57Unit tests
58~~~~~~~~~~
59
60A unit test is responsible for exercising individual software components as a
61unit, like interfaces, data structures, and functionality, uncovering errors
62within the boundaries of a component. The verification effort is in the
63smallest software unit and focuses on the internal processing logic and data
64structures. A test case of unit tests should be designed to uncover errors
65due to erroneous computations, incorrect comparisons, or improper control
66flow [2]_.
67
68In QEMU, unit tests can be invoked with ``make check-unit``. They are
69simple C tests that typically link to individual QEMU object files and
70exercise them by calling exported functions.
71
72If you are writing new code in QEMU, consider adding a unit test, especially
73for utility modules that are relatively stateless or have few dependencies. To
74add a new unit test:
75
761. Create a new source file. For example, ``tests/unit/foo-test.c``.
77
782. Write the test. Normally you would include the header file which exports
79   the module API, then verify the interface behaves as expected from your
80   test. The test code should be organized with the glib testing framework.
81   Copying and modifying an existing test is usually a good idea.
82
833. Add the test to ``tests/unit/meson.build``. The unit tests are listed in a
84   dictionary called ``tests``.  The values are any additional sources and
85   dependencies to be linked with the test.  For a simple test whose source
86   is in ``tests/unit/foo-test.c``, it is enough to add an entry like::
87
88     {
89       ...
90       'foo-test': [],
91       ...
92     }
93
94Since unit tests don't require environment variables, the simplest way to debug
95a unit test failure is often directly invoking it or even running it under
96``gdb``. However there can still be differences in behavior between ``make``
97invocations and your manual run, due to ``$MALLOC_PERTURB_`` environment
98variable (which affects memory reclamation and catches invalid pointers better)
99and gtester options. If necessary, you can run
100
101.. code::
102
103  make check-unit V=1
104
105and copy the actual command line which executes the unit test, then run
106it from the command line.
107
108QTest
109~~~~~
110
111QTest is a device emulation testing framework.  It can be very useful to test
112device models; it could also control certain aspects of QEMU (such as virtual
113clock stepping), with a special purpose "qtest" protocol.  Refer to
114:doc:`qtest` for more details.
115
116QTest cases can be executed with
117
118.. code::
119
120   make check-qtest
121
122Writing portable test cases
123~~~~~~~~~~~~~~~~~~~~~~~~~~~
124Both unit tests and qtests can run on POSIX hosts as well as Windows hosts.
125Care must be taken when writing portable test cases that can be built and run
126successfully on various hosts. The following list shows some best practices:
127
128* Use portable APIs from glib whenever necessary, e.g.: g_setenv(),
129  g_mkdtemp(), g_mkdir().
130* Avoid using hardcoded /tmp for temporary file directory.
131  Use g_get_tmp_dir() instead.
132* Bear in mind that Windows has different special string representation for
133  stdin/stdout/stderr and null devices. For example if your test case uses
134  "/dev/fd/2" and "/dev/null" on Linux, remember to use "2" and "nul" on
135  Windows instead. Also IO redirection does not work on Windows, so avoid
136  using "2>nul" whenever necessary.
137* If your test cases uses the blkdebug feature, use relative path to pass
138  the config and image file paths in the command line as Windows absolute
139  path contains the delimiter ":" which will confuse the blkdebug parser.
140* Use double quotes in your extra QEMU command line in your test cases
141  instead of single quotes, as Windows does not drop single quotes when
142  passing the command line to QEMU.
143* Windows opens a file in text mode by default, while a POSIX compliant
144  implementation treats text files and binary files the same. So if your
145  test cases opens a file to write some data and later wants to compare the
146  written data with the original one, be sure to pass the letter 'b' as
147  part of the mode string to fopen(), or O_BINARY flag for the open() call.
148* If a certain test case can only run on POSIX or Linux hosts, use a proper
149  #ifdef in the codes. If the whole test suite cannot run on Windows, disable
150  the build in the meson.build file.
151
152.. _qapi-tests:
153
154QAPI schema tests
155~~~~~~~~~~~~~~~~~
156
157The QAPI schema tests validate the QAPI parser used by QMP, by feeding
158predefined input to the parser and comparing the result with the reference
159output.
160
161The input/output data is managed under the ``tests/qapi-schema`` directory.
162Each test case includes four files that have a common base name:
163
164  * ``${casename}.json`` - the file contains the JSON input for feeding the
165    parser
166  * ``${casename}.out`` - the file contains the expected stdout from the parser
167  * ``${casename}.err`` - the file contains the expected stderr from the parser
168  * ``${casename}.exit`` - the expected error code
169
170Consider adding a new QAPI schema test when you are making a change on the QAPI
171parser (either fixing a bug or extending/modifying the syntax). To do this:
172
1731. Add four files for the new case as explained above. For example:
174
175  ``$EDITOR tests/qapi-schema/foo.{json,out,err,exit}``.
176
1772. Add the new test in ``tests/Makefile.include``. For example:
178
179  ``qapi-schema += foo.json``
180
181check-block
182~~~~~~~~~~~
183
184``make check-block`` runs a subset of the block layer iotests (the tests that
185are in the "auto" group).
186See the "QEMU iotests" section below for more information.
187
188.. _qemu-iotests:
189
190QEMU iotests
191------------
192
193QEMU iotests, under the directory ``tests/qemu-iotests``, is the testing
194framework widely used to test block layer related features. It is higher level
195than "make check" tests and 99% of the code is written in bash or Python
196scripts.  The testing success criteria is golden output comparison, and the
197test files are named with numbers.
198
199To run iotests, make sure QEMU is built successfully, then switch to the
200``tests/qemu-iotests`` directory under the build directory, and run ``./check``
201with desired arguments from there.
202
203By default, "raw" format and "file" protocol is used; all tests will be
204executed, except the unsupported ones. You can override the format and protocol
205with arguments:
206
207.. code::
208
209  # test with qcow2 format
210  ./check -qcow2
211  # or test a different protocol
212  ./check -nbd
213
214It's also possible to list test numbers explicitly:
215
216.. code::
217
218  # run selected cases with qcow2 format
219  ./check -qcow2 001 030 153
220
221Cache mode can be selected with the "-c" option, which may help reveal bugs
222that are specific to certain cache mode.
223
224More options are supported by the ``./check`` script, run ``./check -h`` for
225help.
226
227Writing a new test case
228~~~~~~~~~~~~~~~~~~~~~~~
229
230Consider writing a tests case when you are making any changes to the block
231layer. An iotest case is usually the choice for that. There are already many
232test cases, so it is possible that extending one of them may achieve the goal
233and save the boilerplate to create one.  (Unfortunately, there isn't a 100%
234reliable way to find a related one out of hundreds of tests.  One approach is
235using ``git grep``.)
236
237Usually an iotest case consists of two files. One is an executable that
238produces output to stdout and stderr, the other is the expected reference
239output. They are given the same number in file names. E.g. Test script ``055``
240and reference output ``055.out``.
241
242In rare cases, when outputs differ between cache mode ``none`` and others, a
243``.out.nocache`` file is added. In other cases, when outputs differ between
244image formats, more than one ``.out`` files are created ending with the
245respective format names, e.g. ``178.out.qcow2`` and ``178.out.raw``.
246
247There isn't a hard rule about how to write a test script, but a new test is
248usually a (copy and) modification of an existing case.  There are a few
249commonly used ways to create a test:
250
251* A Bash script. It will make use of several environmental variables related
252  to the testing procedure, and could source a group of ``common.*`` libraries
253  for some common helper routines.
254
255* A Python unittest script. Import ``iotests`` and create a subclass of
256  ``iotests.QMPTestCase``, then call ``iotests.main`` method. The downside of
257  this approach is that the output is too scarce, and the script is considered
258  harder to debug.
259
260* A simple Python script without using unittest module. This could also import
261  ``iotests`` for launching QEMU and utilities etc, but it doesn't inherit
262  from ``iotests.QMPTestCase`` therefore doesn't use the Python unittest
263  execution. This is a combination of 1 and 2.
264
265Pick the language per your preference since both Bash and Python have
266comparable library support for invoking and interacting with QEMU programs. If
267you opt for Python, it is strongly recommended to write Python 3 compatible
268code.
269
270Both Python and Bash frameworks in iotests provide helpers to manage test
271images. They can be used to create and clean up images under the test
272directory. If no I/O or any protocol specific feature is needed, it is often
273more convenient to use the pseudo block driver, ``null-co://``, as the test
274image, which doesn't require image creation or cleaning up. Avoid system-wide
275devices or files whenever possible, such as ``/dev/null`` or ``/dev/zero``.
276Otherwise, image locking implications have to be considered.  For example,
277another application on the host may have locked the file, possibly leading to a
278test failure.  If using such devices are explicitly desired, consider adding
279``locking=off`` option to disable image locking.
280
281Debugging a test case
282~~~~~~~~~~~~~~~~~~~~~
283
284The following options to the ``check`` script can be useful when debugging
285a failing test:
286
287* ``-gdb`` wraps every QEMU invocation in a ``gdbserver``, which waits for a
288  connection from a gdb client.  The options given to ``gdbserver`` (e.g. the
289  address on which to listen for connections) are taken from the ``$GDB_OPTIONS``
290  environment variable.  By default (if ``$GDB_OPTIONS`` is empty), it listens on
291  ``localhost:12345``.
292  It is possible to connect to it for example with
293  ``gdb -iex "target remote $addr"``, where ``$addr`` is the address
294  ``gdbserver`` listens on.
295  If the ``-gdb`` option is not used, ``$GDB_OPTIONS`` is ignored,
296  regardless of whether it is set or not.
297
298* ``-valgrind`` attaches a valgrind instance to QEMU. If it detects
299  warnings, it will print and save the log in
300  ``$TEST_DIR/<valgrind_pid>.valgrind``.
301  The final command line will be ``valgrind --log-file=$TEST_DIR/
302  <valgrind_pid>.valgrind --error-exitcode=99 $QEMU ...``
303
304* ``-d`` (debug) just increases the logging verbosity, showing
305  for example the QMP commands and answers.
306
307* ``-p`` (print) redirects QEMU’s stdout and stderr to the test output,
308  instead of saving it into a log file in
309  ``$TEST_DIR/qemu-machine-<random_string>``.
310
311Test case groups
312~~~~~~~~~~~~~~~~
313
314"Tests may belong to one or more test groups, which are defined in the form
315of a comment in the test source file. By convention, test groups are listed
316in the second line of the test file, after the "#!/..." line, like this:
317
318.. code::
319
320  #!/usr/bin/env python3
321  # group: auto quick
322  #
323  ...
324
325Another way of defining groups is creating the tests/qemu-iotests/group.local
326file. This should be used only for downstream (this file should never appear
327in upstream). This file may be used for defining some downstream test groups
328or for temporarily disabling tests, like this:
329
330.. code::
331
332  # groups for some company downstream process
333  #
334  # ci - tests to run on build
335  # down - our downstream tests, not for upstream
336  #
337  # Format of each line is:
338  # TEST_NAME TEST_GROUP [TEST_GROUP ]...
339
340  013 ci
341  210 disabled
342  215 disabled
343  our-ugly-workaround-test down ci
344
345Note that the following group names have a special meaning:
346
347- quick: Tests in this group should finish within a few seconds.
348
349- auto: Tests in this group are used during "make check" and should be
350  runnable in any case. That means they should run with every QEMU binary
351  (also non-x86), with every QEMU configuration (i.e. must not fail if
352  an optional feature is not compiled in - but reporting a "skip" is ok),
353  work at least with the qcow2 file format, work with all kind of host
354  filesystems and users (e.g. "nobody" or "root") and must not take too
355  much memory and disk space (since CI pipelines tend to fail otherwise).
356
357- disabled: Tests in this group are disabled and ignored by check.
358
359.. _container-ref:
360
361Container based tests
362---------------------
363
364Introduction
365~~~~~~~~~~~~
366
367The container testing framework in QEMU utilizes public images to
368build and test QEMU in predefined and widely accessible Linux
369environments. This makes it possible to expand the test coverage
370across distros, toolchain flavors and library versions. The support
371was originally written for Docker although we also support Podman as
372an alternative container runtime. Although many of the target
373names and scripts are prefixed with "docker" the system will
374automatically run on whichever is configured.
375
376The container images are also used to augment the generation of tests
377for testing TCG. See :ref:`checktcg-ref` for more details.
378
379Docker Prerequisites
380~~~~~~~~~~~~~~~~~~~~
381
382Install "docker" with the system package manager and start the Docker service
383on your development machine, then make sure you have the privilege to run
384Docker commands. Typically it means setting up passwordless ``sudo docker``
385command or login as root. For example:
386
387.. code::
388
389  $ sudo yum install docker
390  $ # or `apt-get install docker` for Ubuntu, etc.
391  $ sudo systemctl start docker
392  $ sudo docker ps
393
394The last command should print an empty table, to verify the system is ready.
395
396An alternative method to set up permissions is by adding the current user to
397"docker" group and making the docker daemon socket file (by default
398``/var/run/docker.sock``) accessible to the group:
399
400.. code::
401
402  $ sudo groupadd docker
403  $ sudo usermod $USER -a -G docker
404  $ sudo chown :docker /var/run/docker.sock
405
406Note that any one of above configurations makes it possible for the user to
407exploit the whole host with Docker bind mounting or other privileged
408operations.  So only do it on development machines.
409
410Podman Prerequisites
411~~~~~~~~~~~~~~~~~~~~
412
413Install "podman" with the system package manager.
414
415.. code::
416
417  $ sudo dnf install podman
418  $ podman ps
419
420The last command should print an empty table, to verify the system is ready.
421
422Quickstart
423~~~~~~~~~~
424
425From source tree, type ``make docker-help`` to see the help. Testing
426can be started without configuring or building QEMU (``configure`` and
427``make`` are done in the container, with parameters defined by the
428make target):
429
430.. code::
431
432  make docker-test-build@debian
433
434This will create a container instance using the ``debian`` image (the image
435is downloaded and initialized automatically), in which the ``test-build`` job
436is executed.
437
438Registry
439~~~~~~~~
440
441The QEMU project has a container registry hosted by GitLab at
442``registry.gitlab.com/qemu-project/qemu`` which will automatically be
443used to pull in pre-built layers. This avoids unnecessary strain on
444the distro archives created by multiple developers running the same
445container build steps over and over again. This can be overridden
446locally by using the ``NOCACHE`` build option:
447
448.. code::
449
450   make docker-image-debian-arm64-cross NOCACHE=1
451
452Images
453~~~~~~
454
455Along with many other images, the ``debian`` image is defined in a Dockerfile
456in ``tests/docker/dockerfiles/``, called ``debian.docker``. ``make docker-help``
457command will list all the available images.
458
459A ``.pre`` script can be added beside the ``.docker`` file, which will be
460executed before building the image under the build context directory. This is
461mainly used to do necessary host side setup. One such setup is ``binfmt_misc``,
462for example, to make qemu-user powered cross build containers work.
463
464Most of the existing Dockerfiles were written by hand, simply by creating a
465a new ``.docker`` file under the ``tests/docker/dockerfiles/`` directory.
466This has led to an inconsistent set of packages being present across the
467different containers.
468
469Thus going forward, QEMU is aiming to automatically generate the Dockerfiles
470using the ``lcitool`` program provided by the ``libvirt-ci`` project:
471
472  https://gitlab.com/libvirt/libvirt-ci
473
474``libvirt-ci`` contains an ``lcitool`` program as well as a list of
475mappings to distribution package names for a wide variety of third
476party projects.  ``lcitool`` applies the mappings to a list of build
477pre-requisites in ``tests/lcitool/projects/qemu.yml``, determines the
478list of native packages to install on each distribution, and uses them
479to generate build environments (dockerfiles and Cirrus CI variable files)
480that are consistent across OS distribution.
481
482
483Adding new build pre-requisites
484^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
485
486When preparing a patch series that adds a new build
487pre-requisite to QEMU, the prerequisites should to be added to
488``tests/lcitool/projects/qemu.yml`` in order to make the dependency
489available in the CI build environments.
490
491In the simple case where the pre-requisite is already known to ``libvirt-ci``
492the following steps are needed:
493
494 * Edit ``tests/lcitool/projects/qemu.yml`` and add the pre-requisite
495
496 * Run ``make lcitool-refresh`` to re-generate all relevant build environment
497   manifests
498
499It may be that ``libvirt-ci`` does not know about the new pre-requisite.
500If that is the case, some extra preparation steps will be required
501first to contribute the mapping to the ``libvirt-ci`` project:
502
503 * Fork the ``libvirt-ci`` project on gitlab
504
505 * Add an entry for the new build prerequisite to
506   ``lcitool/facts/mappings.yml``, listing its native package name on as
507   many OS distros as practical.  Run ``python -m pytest --regenerate-output``
508   and check that the changes are correct.
509
510 * Commit the ``mappings.yml`` change together with the regenerated test
511   files, and submit a merge request to the ``libvirt-ci`` project.
512   Please note in the description that this is a new build pre-requisite
513   desired for use with QEMU.
514
515 * CI pipeline will run to validate that the changes to ``mappings.yml``
516   are correct, by attempting to install the newly listed package on
517   all OS distributions supported by ``libvirt-ci``.
518
519 * Once the merge request is accepted, go back to QEMU and update
520   the ``tests/lcitool/libvirt-ci`` submodule to point to a commit that
521   contains the ``mappings.yml`` update.  Then add the prerequisite and
522   run ``make lcitool-refresh``.
523
524 * Please also trigger gitlab container generation pipelines on your change
525   for as many OS distros as practical to make sure that there are no
526   obvious breakages when adding the new pre-requisite. Please see
527   `CI <https://www.qemu.org/docs/master/devel/ci.html>`__ documentation
528   page on how to trigger gitlab CI pipelines on your change.
529
530For enterprise distros that default to old, end-of-life versions of the
531Python runtime, QEMU uses a separate set of mappings that work with more
532recent versions.  These can be found in ``tests/lcitool/mappings.yml``.
533Modifying this file should not be necessary unless the new pre-requisite
534is a Python library or tool.
535
536
537Adding new OS distros
538^^^^^^^^^^^^^^^^^^^^^
539
540In some cases ``libvirt-ci`` will not know about the OS distro that is
541desired to be tested. Before adding a new OS distro, discuss the proposed
542addition:
543
544 * Send a mail to qemu-devel, copying people listed in the
545   MAINTAINERS file for ``Build and test automation``.
546
547   There are limited CI compute resources available to QEMU, so the
548   cost/benefit tradeoff of adding new OS distros needs to be considered.
549
550 * File an issue at https://gitlab.com/libvirt/libvirt-ci/-/issues
551   pointing to the qemu-devel mail thread in the archives.
552
553   This alerts other people who might be interested in the work
554   to avoid duplication, as well as to get feedback from libvirt-ci
555   maintainers on any tips to ease the addition
556
557Assuming there is agreement to add a new OS distro then
558
559 * Fork the ``libvirt-ci`` project on gitlab
560
561 * Add metadata under ``lcitool/facts/targets/`` for the new OS
562   distro. There might be code changes required if the OS distro
563   uses a package format not currently known. The ``libvirt-ci``
564   maintainers can advise on this when the issue is filed.
565
566 * Edit the ``lcitool/facts/mappings.yml`` change to add entries for
567   the new OS, listing the native package names for as many packages
568   as practical.  Run ``python -m pytest --regenerate-output`` and
569   check that the changes are correct.
570
571 * Commit the changes to ``lcitool/facts`` and the regenerated test
572   files, and submit a merge request to the ``libvirt-ci`` project.
573   Please note in the description that this is a new build pre-requisite
574   desired for use with QEMU
575
576 * CI pipeline will run to validate that the changes to ``mappings.yml``
577   are correct, by attempting to install the newly listed package on
578   all OS distributions supported by ``libvirt-ci``.
579
580 * Once the merge request is accepted, go back to QEMU and update
581   the ``libvirt-ci`` submodule to point to a commit that contains
582   the ``mappings.yml`` update.
583
584
585Tests
586~~~~~
587
588Different tests are added to cover various configurations to build and test
589QEMU.  Docker tests are the executables under ``tests/docker`` named
590``test-*``. They are typically shell scripts and are built on top of a shell
591library, ``tests/docker/common.rc``, which provides helpers to find the QEMU
592source and build it.
593
594The full list of tests is printed in the ``make docker-help`` help.
595
596Debugging a Docker test failure
597~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
598
599When CI tasks, maintainers or yourself report a Docker test failure, follow the
600below steps to debug it:
601
6021. Locally reproduce the failure with the reported command line. E.g. run
603   ``make docker-test-mingw@fedora-win64-cross J=8``.
6042. Add "V=1" to the command line, try again, to see the verbose output.
6053. Further add "DEBUG=1" to the command line. This will pause in a shell prompt
606   in the container right before testing starts. You could either manually
607   build QEMU and run tests from there, or press Ctrl-D to let the Docker
608   testing continue.
6094. If you press Ctrl-D, the same building and testing procedure will begin, and
610   will hopefully run into the error again. After that, you will be dropped to
611   the prompt for debug.
612
613Options
614~~~~~~~
615
616Various options can be used to affect how Docker tests are done. The full
617list is in the ``make docker`` help text. The frequently used ones are:
618
619* ``V=1``: the same as in top level ``make``. It will be propagated to the
620  container and enable verbose output.
621* ``J=$N``: the number of parallel tasks in make commands in the container,
622  similar to the ``-j $N`` option in top level ``make``. (The ``-j`` option in
623  top level ``make`` will not be propagated into the container.)
624* ``DEBUG=1``: enables debug. See the previous "Debugging a Docker test
625  failure" section.
626
627Thread Sanitizer
628----------------
629
630Thread Sanitizer (TSan) is a tool which can detect data races.  QEMU supports
631building and testing with this tool.
632
633For more information on TSan:
634
635https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual
636
637Thread Sanitizer in Docker
638~~~~~~~~~~~~~~~~~~~~~~~~~~
639TSan is currently supported in the ubuntu2204 docker.
640
641The test-tsan test will build using TSan and then run make check.
642
643.. code::
644
645  make docker-test-tsan@ubuntu2204
646
647TSan warnings under docker are placed in files located at build/tsan/.
648
649We recommend using DEBUG=1 to allow launching the test from inside the docker,
650and to allow review of the warnings generated by TSan.
651
652Building and Testing with TSan
653~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
654
655It is possible to build and test with TSan, with a few additional steps.
656These steps are normally done automatically in the docker.
657
658TSan is supported for clang and gcc.
659One particularity of sanitizers is that all the code, including shared objects
660dependencies, should be built with it.
661In the case of TSan, any synchronization primitive from glib (GMutex for
662instance) will not be recognized, and will lead to false positives.
663
664To build a tsan version of glib:
665
666.. code::
667
668   $ git clone --depth=1 --branch=2.81.0 https://github.com/GNOME/glib.git
669   $ cd glib
670   $ CFLAGS="-O2 -g -fsanitize=thread" meson build
671   $ ninja -C build
672
673To configure the build for TSan:
674
675.. code::
676
677  ../configure --enable-tsan \
678               --disable-werror --extra-cflags="-O0"
679
680When executing qemu, don't forget to point to tsan glib:
681
682.. code::
683
684   $ glib_dir=/path/to/glib
685   $ export LD_LIBRARY_PATH=$glib_dir/build/gio:$glib_dir/build/glib:$glib_dir/build/gmodule:$glib_dir/build/gobject:$glib_dir/build/gthread
686   # check correct version is used
687   $ ldd build/qemu-x86_64 | grep glib
688   $ qemu-system-x86_64 ...
689
690The runtime behavior of TSAN is controlled by the TSAN_OPTIONS environment
691variable.
692
693More information on the TSAN_OPTIONS can be found here:
694
695https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags
696
697For example:
698
699.. code::
700
701  export TSAN_OPTIONS=suppressions=<path to qemu>/tests/tsan/suppressions.tsan \
702                      detect_deadlocks=false history_size=7 exitcode=0 \
703                      log_path=<build path>/tsan/tsan_warning
704
705The above exitcode=0 has TSan continue without error if any warnings are found.
706This allows for running the test and then checking the warnings afterwards.
707If you want TSan to stop and exit with error on warnings, use exitcode=66.
708
709.. _tsan-suppressions:
710
711TSan Suppressions
712~~~~~~~~~~~~~~~~~
713Keep in mind that for any data race warning, although there might be a data race
714detected by TSan, there might be no actual bug here.  TSan provides several
715different mechanisms for suppressing warnings.  In general it is recommended
716to fix the code if possible to eliminate the data race rather than suppress
717the warning.
718
719A few important files for suppressing warnings are:
720
721tests/tsan/suppressions.tsan - Has TSan warnings we wish to suppress at runtime.
722The comment on each suppression will typically indicate why we are
723suppressing it.  More information on the file format can be found here:
724
725https://github.com/google/sanitizers/wiki/ThreadSanitizerSuppressions
726
727tests/tsan/ignore.tsan - Has TSan warnings we wish to disable
728at compile time for test or debug.
729Add flags to configure to enable:
730
731"--extra-cflags=-fsanitize-blacklist=<src path>/tests/tsan/ignore.tsan"
732
733More information on the file format can be found here under "Blacklist Format":
734
735https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags
736
737TSan Annotations
738~~~~~~~~~~~~~~~~
739include/qemu/tsan.h defines annotations.  See this file for more descriptions
740of the annotations themselves.  Annotations can be used to suppress
741TSan warnings or give TSan more information so that it can detect proper
742relationships between accesses of data.
743
744Annotation examples can be found here:
745
746https://github.com/llvm/llvm-project/tree/master/compiler-rt/test/tsan/
747
748Good files to start with are: annotate_happens_before.cpp and ignore_race.cpp
749
750The full set of annotations can be found here:
751
752https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/tsan/rtl/tsan_interface_ann.cpp
753
754docker-binfmt-image-debian-% targets
755------------------------------------
756
757It is possible to combine Debian's bootstrap scripts with a configured
758``binfmt_misc`` to bootstrap a number of Debian's distros including
759experimental ports not yet supported by a released OS. This can
760simplify setting up a rootfs by using docker to contain the foreign
761rootfs rather than manually invoking chroot.
762
763Setting up ``binfmt_misc``
764~~~~~~~~~~~~~~~~~~~~~~~~~~
765
766You can use the script ``qemu-binfmt-conf.sh`` to configure a QEMU
767user binary to automatically run binaries for the foreign
768architecture. While the scripts will try their best to work with
769dynamically linked QEMU's a statically linked one will present less
770potential complications when copying into the docker image. Modern
771kernels support the ``F`` (fix binary) flag which will open the QEMU
772executable on setup and avoids the need to find and re-open in the
773chroot environment. This is triggered with the ``--persistent`` flag.
774
775Example invocation
776~~~~~~~~~~~~~~~~~~
777
778For example to setup the HPPA ports builds of Debian::
779
780  make docker-binfmt-image-debian-sid-hppa \
781    DEB_TYPE=sid DEB_ARCH=hppa \
782    DEB_URL=http://ftp.ports.debian.org/debian-ports/ \
783    DEB_KEYRING=/usr/share/keyrings/debian-ports-archive-keyring.gpg \
784    EXECUTABLE=(pwd)/qemu-hppa V=1
785
786The ``DEB_`` variables are substitutions used by
787``debian-bootstrap.pre`` which is called to do the initial debootstrap
788of the rootfs before it is copied into the container. The second stage
789is run as part of the build. The final image will be tagged as
790``qemu/debian-sid-hppa``.
791
792VM testing
793----------
794
795This test suite contains scripts that bootstrap various guest images that have
796necessary packages to build QEMU. The basic usage is documented in ``Makefile``
797help which is displayed with ``make vm-help``.
798
799Quickstart
800~~~~~~~~~~
801
802Run ``make vm-help`` to list available make targets. Invoke a specific make
803command to run build test in an image. For example, ``make vm-build-freebsd``
804will build the source tree in the FreeBSD image. The command can be executed
805from either the source tree or the build dir; if the former, ``./configure`` is
806not needed. The command will then generate the test image in ``./tests/vm/``
807under the working directory.
808
809Note: images created by the scripts accept a well-known RSA key pair for SSH
810access, so they SHOULD NOT be exposed to external interfaces if you are
811concerned about attackers taking control of the guest and potentially
812exploiting a QEMU security bug to compromise the host.
813
814QEMU binaries
815~~~~~~~~~~~~~
816
817By default, ``qemu-system-x86_64`` is searched in $PATH to run the guest. If
818there isn't one, or if it is older than 2.10, the test won't work. In this case,
819provide the QEMU binary in env var: ``QEMU=/path/to/qemu-2.10+``.
820
821Likewise the path to ``qemu-img`` can be set in QEMU_IMG environment variable.
822
823Make jobs
824~~~~~~~~~
825
826The ``-j$X`` option in the make command line is not propagated into the VM,
827specify ``J=$X`` to control the make jobs in the guest.
828
829Debugging
830~~~~~~~~~
831
832Add ``DEBUG=1`` and/or ``V=1`` to the make command to allow interactive
833debugging and verbose output. If this is not enough, see the next section.
834``V=1`` will be propagated down into the make jobs in the guest.
835
836Manual invocation
837~~~~~~~~~~~~~~~~~
838
839Each guest script is an executable script with the same command line options.
840For example to work with the netbsd guest, use ``$QEMU_SRC/tests/vm/netbsd``:
841
842.. code::
843
844    $ cd $QEMU_SRC/tests/vm
845
846    # To bootstrap the image
847    $ ./netbsd --build-image --image /var/tmp/netbsd.img
848    <...>
849
850    # To run an arbitrary command in guest (the output will not be echoed unless
851    # --debug is added)
852    $ ./netbsd --debug --image /var/tmp/netbsd.img uname -a
853
854    # To build QEMU in guest
855    $ ./netbsd --debug --image /var/tmp/netbsd.img --build-qemu $QEMU_SRC
856
857    # To get to an interactive shell
858    $ ./netbsd --interactive --image /var/tmp/netbsd.img sh
859
860Adding new guests
861~~~~~~~~~~~~~~~~~
862
863Please look at existing guest scripts for how to add new guests.
864
865Most importantly, create a subclass of BaseVM and implement ``build_image()``
866method and define ``BUILD_SCRIPT``, then finally call ``basevm.main()`` from
867the script's ``main()``.
868
869* Usually in ``build_image()``, a template image is downloaded from a
870  predefined URL. ``BaseVM._download_with_cache()`` takes care of the cache and
871  the checksum, so consider using it.
872
873* Once the image is downloaded, users, SSH server and QEMU build deps should
874  be set up:
875
876  - Root password set to ``BaseVM.ROOT_PASS``
877  - User ``BaseVM.GUEST_USER`` is created, and password set to
878    ``BaseVM.GUEST_PASS``
879  - SSH service is enabled and started on boot,
880    ``$QEMU_SRC/tests/keys/id_rsa.pub`` is added to ssh's ``authorized_keys``
881    file of both root and the normal user
882  - DHCP client service is enabled and started on boot, so that it can
883    automatically configure the virtio-net-pci NIC and communicate with QEMU
884    user net (10.0.2.2)
885  - Necessary packages are installed to untar the source tarball and build
886    QEMU
887
888* Write a proper ``BUILD_SCRIPT`` template, which should be a shell script that
889  untars a raw virtio-blk block device, which is the tarball data blob of the
890  QEMU source tree, then configure/build it. Running "make check" is also
891  recommended.
892
893Image fuzzer testing
894--------------------
895
896An image fuzzer was added to exercise format drivers. Currently only qcow2 is
897supported. To start the fuzzer, run
898
899.. code::
900
901  tests/image-fuzzer/runner.py -c '[["qemu-img", "info", "$test_img"]]' /tmp/test qcow2
902
903Alternatively, some command different from ``qemu-img info`` can be tested, by
904changing the ``-c`` option.
905
906Functional tests using Python
907-----------------------------
908
909A functional test focuses on the functional requirement of the software,
910attempting to find errors like incorrect functions, interface errors,
911behavior errors, and initialization and termination errors [3]_.
912
913The ``tests/functional`` directory hosts functional tests written in
914Python. You can run the functional tests simply by executing:
915
916.. code::
917
918  make check-functional
919
920See :ref:`checkfunctional-ref` for more details.
921
922.. _checktcg-ref:
923
924Testing with "make check-tcg"
925-----------------------------
926
927The check-tcg tests are intended for simple smoke tests of both
928linux-user and softmmu TCG functionality. However to build test
929programs for guest targets you need to have cross compilers available.
930If your distribution supports cross compilers you can do something as
931simple as::
932
933  apt install gcc-aarch64-linux-gnu
934
935The configure script will automatically pick up their presence.
936Sometimes compilers have slightly odd names so the availability of
937them can be prompted by passing in the appropriate configure option
938for the architecture in question, for example::
939
940  $(configure) --cross-cc-aarch64=aarch64-cc
941
942There is also a ``--cross-cc-cflags-ARCH`` flag in case additional
943compiler flags are needed to build for a given target.
944
945If you have the ability to run containers as the user the build system
946will automatically use them where no system compiler is available. For
947architectures where we also support building QEMU we will generally
948use the same container to build tests. However there are a number of
949additional containers defined that have a minimal cross-build
950environment that is only suitable for building test cases. Sometimes
951we may use a bleeding edge distribution for compiler features needed
952for test cases that aren't yet in the LTS distros we support for QEMU
953itself.
954
955See :ref:`container-ref` for more details.
956
957Running subset of tests
958~~~~~~~~~~~~~~~~~~~~~~~
959
960You can build the tests for one architecture::
961
962  make build-tcg-tests-$TARGET
963
964And run with::
965
966  make run-tcg-tests-$TARGET
967
968Adding ``V=1`` to the invocation will show the details of how to
969invoke QEMU for the test which is useful for debugging tests.
970
971Running individual tests
972~~~~~~~~~~~~~~~~~~~~~~~~
973
974Tests can also be run directly from the test build directory. If you
975run ``make help`` from the test build directory you will get a list of
976all the tests that can be run. Please note that same binaries are used
977in multiple tests, for example::
978
979  make run-plugin-test-mmap-with-libinline.so
980
981will run the mmap test with the ``libinline.so`` TCG plugin. The
982gdbstub tests also re-use the test binaries but while exercising gdb.
983
984TCG test dependencies
985~~~~~~~~~~~~~~~~~~~~~
986
987The TCG tests are deliberately very light on dependencies and are
988either totally bare with minimal gcc lib support (for system-mode tests)
989or just glibc (for linux-user tests). This is because getting a cross
990compiler to work with additional libraries can be challenging.
991
992Other TCG Tests
993---------------
994
995There are a number of out-of-tree test suites that are used for more
996extensive testing of processor features.
997
998KVM Unit Tests
999~~~~~~~~~~~~~~
1000
1001The KVM unit tests are designed to run as a Guest OS under KVM but
1002there is no reason why they can't exercise the TCG as well. It
1003provides a minimal OS kernel with hooks for enabling the MMU as well
1004as reporting test results via a special device::
1005
1006  https://git.kernel.org/pub/scm/virt/kvm/kvm-unit-tests.git
1007
1008Linux Test Project
1009~~~~~~~~~~~~~~~~~~
1010
1011The LTP is focused on exercising the syscall interface of a Linux
1012kernel. It checks that syscalls behave as documented and strives to
1013exercise as many corner cases as possible. It is a useful test suite
1014to run to exercise QEMU's linux-user code::
1015
1016  https://linux-test-project.github.io/
1017
1018GCC gcov support
1019----------------
1020
1021``gcov`` is a GCC tool to analyze the testing coverage by
1022instrumenting the tested code. To use it, configure QEMU with
1023``--enable-gcov`` option and build. Then run the tests as usual.
1024
1025If you want to gather coverage information on a single test the ``make
1026clean-gcda`` target can be used to delete any existing coverage
1027information before running a single test.
1028
1029You can generate a HTML coverage report by executing ``make
1030coverage-html`` which will create
1031``meson-logs/coveragereport/index.html``.
1032
1033Further analysis can be conducted by running the ``gcov`` command
1034directly on the various .gcda output files. Please read the ``gcov``
1035documentation for more information.
1036
1037Flaky tests
1038-----------
1039
1040A flaky test is defined as a test that exhibits both a passing and a failing
1041result with the same code on different runs. Some usual reasons for an
1042intermittent/flaky test are async wait, concurrency, and test order dependency
1043[4]_.
1044
1045In QEMU, tests that are identified to be flaky are normally disabled by
1046default. Set the QEMU_TEST_FLAKY_TESTS environment variable before running
1047the tests to enable them.
1048
1049References
1050----------
1051
1052.. [1] Sommerville, Ian (2016). Software Engineering. p. 233.
1053.. [2] Pressman, Roger S. & Maxim, Bruce R. (2020). Software Engineering,
1054       A Practitioner’s Approach. p. 48, 376, 378, 381.
1055.. [3] Pressman, Roger S. & Maxim, Bruce R. (2020). Software Engineering,
1056       A Practitioner’s Approach. p. 388.
1057.. [4] Luo, Qingzhou, et al. An empirical analysis of flaky tests.
1058       Proceedings of the 22nd ACM SIGSOFT International Symposium on
1059       Foundations of Software Engineering. 2014.
1060