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