xref: /openbmc/qemu/docs/devel/testing.rst (revision 5591b745)
1.. _testing:
2
3Testing in QEMU
4===============
5
6This document describes the testing infrastructure in QEMU.
7
8Testing with "make check"
9-------------------------
10
11The "make check" testing family includes most of the C based tests in QEMU. For
12a quick help, run ``make check-help`` from the source tree.
13
14The usual way to run these tests is:
15
16.. code::
17
18  make check
19
20which includes QAPI schema tests, unit tests, QTests and some iotests.
21Different sub-types of "make check" tests will be explained below.
22
23Before running tests, it is best to build QEMU programs first. Some tests
24expect the executables to exist and will fail with obscure messages if they
25cannot find them.
26
27Unit tests
28~~~~~~~~~~
29
30Unit tests, which can be invoked with ``make check-unit``, are simple C tests
31that typically link to individual QEMU object files and exercise them by
32calling exported functions.
33
34If you are writing new code in QEMU, consider adding a unit test, especially
35for utility modules that are relatively stateless or have few dependencies. To
36add a new unit test:
37
381. Create a new source file. For example, ``tests/unit/foo-test.c``.
39
402. Write the test. Normally you would include the header file which exports
41   the module API, then verify the interface behaves as expected from your
42   test. The test code should be organized with the glib testing framework.
43   Copying and modifying an existing test is usually a good idea.
44
453. Add the test to ``tests/unit/meson.build``. The unit tests are listed in a
46   dictionary called ``tests``.  The values are any additional sources and
47   dependencies to be linked with the test.  For a simple test whose source
48   is in ``tests/unit/foo-test.c``, it is enough to add an entry like::
49
50     {
51       ...
52       'foo-test': [],
53       ...
54     }
55
56Since unit tests don't require environment variables, the simplest way to debug
57a unit test failure is often directly invoking it or even running it under
58``gdb``. However there can still be differences in behavior between ``make``
59invocations and your manual run, due to ``$MALLOC_PERTURB_`` environment
60variable (which affects memory reclamation and catches invalid pointers better)
61and gtester options. If necessary, you can run
62
63.. code::
64
65  make check-unit V=1
66
67and copy the actual command line which executes the unit test, then run
68it from the command line.
69
70QTest
71~~~~~
72
73QTest is a device emulation testing framework.  It can be very useful to test
74device models; it could also control certain aspects of QEMU (such as virtual
75clock stepping), with a special purpose "qtest" protocol.  Refer to
76:doc:`qtest` for more details.
77
78QTest cases can be executed with
79
80.. code::
81
82   make check-qtest
83
84Writing portable test cases
85~~~~~~~~~~~~~~~~~~~~~~~~~~~
86Both unit tests and qtests can run on POSIX hosts as well as Windows hosts.
87Care must be taken when writing portable test cases that can be built and run
88successfully on various hosts. The following list shows some best practices:
89
90* Use portable APIs from glib whenever necessary, e.g.: g_setenv(),
91  g_mkdtemp(), g_mkdir().
92* Avoid using hardcoded /tmp for temporary file directory.
93  Use g_get_tmp_dir() instead.
94* Bear in mind that Windows has different special string representation for
95  stdin/stdout/stderr and null devices. For example if your test case uses
96  "/dev/fd/2" and "/dev/null" on Linux, remember to use "2" and "nul" on
97  Windows instead. Also IO redirection does not work on Windows, so avoid
98  using "2>nul" whenever necessary.
99* If your test cases uses the blkdebug feature, use relative path to pass
100  the config and image file paths in the command line as Windows absolute
101  path contains the delimiter ":" which will confuse the blkdebug parser.
102* Use double quotes in your extra QEMU command line in your test cases
103  instead of single quotes, as Windows does not drop single quotes when
104  passing the command line to QEMU.
105* Windows opens a file in text mode by default, while a POSIX compliant
106  implementation treats text files and binary files the same. So if your
107  test cases opens a file to write some data and later wants to compare the
108  written data with the original one, be sure to pass the letter 'b' as
109  part of the mode string to fopen(), or O_BINARY flag for the open() call.
110* If a certain test case can only run on POSIX or Linux hosts, use a proper
111  #ifdef in the codes. If the whole test suite cannot run on Windows, disable
112  the build in the meson.build file.
113
114QAPI schema tests
115~~~~~~~~~~~~~~~~~
116
117The QAPI schema tests validate the QAPI parser used by QMP, by feeding
118predefined input to the parser and comparing the result with the reference
119output.
120
121The input/output data is managed under the ``tests/qapi-schema`` directory.
122Each test case includes four files that have a common base name:
123
124  * ``${casename}.json`` - the file contains the JSON input for feeding the
125    parser
126  * ``${casename}.out`` - the file contains the expected stdout from the parser
127  * ``${casename}.err`` - the file contains the expected stderr from the parser
128  * ``${casename}.exit`` - the expected error code
129
130Consider adding a new QAPI schema test when you are making a change on the QAPI
131parser (either fixing a bug or extending/modifying the syntax). To do this:
132
1331. Add four files for the new case as explained above. For example:
134
135  ``$EDITOR tests/qapi-schema/foo.{json,out,err,exit}``.
136
1372. Add the new test in ``tests/Makefile.include``. For example:
138
139  ``qapi-schema += foo.json``
140
141check-block
142~~~~~~~~~~~
143
144``make check-block`` runs a subset of the block layer iotests (the tests that
145are in the "auto" group).
146See the "QEMU iotests" section below for more information.
147
148QEMU iotests
149------------
150
151QEMU iotests, under the directory ``tests/qemu-iotests``, is the testing
152framework widely used to test block layer related features. It is higher level
153than "make check" tests and 99% of the code is written in bash or Python
154scripts.  The testing success criteria is golden output comparison, and the
155test files are named with numbers.
156
157To run iotests, make sure QEMU is built successfully, then switch to the
158``tests/qemu-iotests`` directory under the build directory, and run ``./check``
159with desired arguments from there.
160
161By default, "raw" format and "file" protocol is used; all tests will be
162executed, except the unsupported ones. You can override the format and protocol
163with arguments:
164
165.. code::
166
167  # test with qcow2 format
168  ./check -qcow2
169  # or test a different protocol
170  ./check -nbd
171
172It's also possible to list test numbers explicitly:
173
174.. code::
175
176  # run selected cases with qcow2 format
177  ./check -qcow2 001 030 153
178
179Cache mode can be selected with the "-c" option, which may help reveal bugs
180that are specific to certain cache mode.
181
182More options are supported by the ``./check`` script, run ``./check -h`` for
183help.
184
185Writing a new test case
186~~~~~~~~~~~~~~~~~~~~~~~
187
188Consider writing a tests case when you are making any changes to the block
189layer. An iotest case is usually the choice for that. There are already many
190test cases, so it is possible that extending one of them may achieve the goal
191and save the boilerplate to create one.  (Unfortunately, there isn't a 100%
192reliable way to find a related one out of hundreds of tests.  One approach is
193using ``git grep``.)
194
195Usually an iotest case consists of two files. One is an executable that
196produces output to stdout and stderr, the other is the expected reference
197output. They are given the same number in file names. E.g. Test script ``055``
198and reference output ``055.out``.
199
200In rare cases, when outputs differ between cache mode ``none`` and others, a
201``.out.nocache`` file is added. In other cases, when outputs differ between
202image formats, more than one ``.out`` files are created ending with the
203respective format names, e.g. ``178.out.qcow2`` and ``178.out.raw``.
204
205There isn't a hard rule about how to write a test script, but a new test is
206usually a (copy and) modification of an existing case.  There are a few
207commonly used ways to create a test:
208
209* A Bash script. It will make use of several environmental variables related
210  to the testing procedure, and could source a group of ``common.*`` libraries
211  for some common helper routines.
212
213* A Python unittest script. Import ``iotests`` and create a subclass of
214  ``iotests.QMPTestCase``, then call ``iotests.main`` method. The downside of
215  this approach is that the output is too scarce, and the script is considered
216  harder to debug.
217
218* A simple Python script without using unittest module. This could also import
219  ``iotests`` for launching QEMU and utilities etc, but it doesn't inherit
220  from ``iotests.QMPTestCase`` therefore doesn't use the Python unittest
221  execution. This is a combination of 1 and 2.
222
223Pick the language per your preference since both Bash and Python have
224comparable library support for invoking and interacting with QEMU programs. If
225you opt for Python, it is strongly recommended to write Python 3 compatible
226code.
227
228Both Python and Bash frameworks in iotests provide helpers to manage test
229images. They can be used to create and clean up images under the test
230directory. If no I/O or any protocol specific feature is needed, it is often
231more convenient to use the pseudo block driver, ``null-co://``, as the test
232image, which doesn't require image creation or cleaning up. Avoid system-wide
233devices or files whenever possible, such as ``/dev/null`` or ``/dev/zero``.
234Otherwise, image locking implications have to be considered.  For example,
235another application on the host may have locked the file, possibly leading to a
236test failure.  If using such devices are explicitly desired, consider adding
237``locking=off`` option to disable image locking.
238
239Debugging a test case
240~~~~~~~~~~~~~~~~~~~~~
241
242The following options to the ``check`` script can be useful when debugging
243a failing test:
244
245* ``-gdb`` wraps every QEMU invocation in a ``gdbserver``, which waits for a
246  connection from a gdb client.  The options given to ``gdbserver`` (e.g. the
247  address on which to listen for connections) are taken from the ``$GDB_OPTIONS``
248  environment variable.  By default (if ``$GDB_OPTIONS`` is empty), it listens on
249  ``localhost:12345``.
250  It is possible to connect to it for example with
251  ``gdb -iex "target remote $addr"``, where ``$addr`` is the address
252  ``gdbserver`` listens on.
253  If the ``-gdb`` option is not used, ``$GDB_OPTIONS`` is ignored,
254  regardless of whether it is set or not.
255
256* ``-valgrind`` attaches a valgrind instance to QEMU. If it detects
257  warnings, it will print and save the log in
258  ``$TEST_DIR/<valgrind_pid>.valgrind``.
259  The final command line will be ``valgrind --log-file=$TEST_DIR/
260  <valgrind_pid>.valgrind --error-exitcode=99 $QEMU ...``
261
262* ``-d`` (debug) just increases the logging verbosity, showing
263  for example the QMP commands and answers.
264
265* ``-p`` (print) redirects QEMU’s stdout and stderr to the test output,
266  instead of saving it into a log file in
267  ``$TEST_DIR/qemu-machine-<random_string>``.
268
269Test case groups
270~~~~~~~~~~~~~~~~
271
272"Tests may belong to one or more test groups, which are defined in the form
273of a comment in the test source file. By convention, test groups are listed
274in the second line of the test file, after the "#!/..." line, like this:
275
276.. code::
277
278  #!/usr/bin/env python3
279  # group: auto quick
280  #
281  ...
282
283Another way of defining groups is creating the tests/qemu-iotests/group.local
284file. This should be used only for downstream (this file should never appear
285in upstream). This file may be used for defining some downstream test groups
286or for temporarily disabling tests, like this:
287
288.. code::
289
290  # groups for some company downstream process
291  #
292  # ci - tests to run on build
293  # down - our downstream tests, not for upstream
294  #
295  # Format of each line is:
296  # TEST_NAME TEST_GROUP [TEST_GROUP ]...
297
298  013 ci
299  210 disabled
300  215 disabled
301  our-ugly-workaround-test down ci
302
303Note that the following group names have a special meaning:
304
305- quick: Tests in this group should finish within a few seconds.
306
307- auto: Tests in this group are used during "make check" and should be
308  runnable in any case. That means they should run with every QEMU binary
309  (also non-x86), with every QEMU configuration (i.e. must not fail if
310  an optional feature is not compiled in - but reporting a "skip" is ok),
311  work at least with the qcow2 file format, work with all kind of host
312  filesystems and users (e.g. "nobody" or "root") and must not take too
313  much memory and disk space (since CI pipelines tend to fail otherwise).
314
315- disabled: Tests in this group are disabled and ignored by check.
316
317.. _container-ref:
318
319Container based tests
320---------------------
321
322Introduction
323~~~~~~~~~~~~
324
325The container testing framework in QEMU utilizes public images to
326build and test QEMU in predefined and widely accessible Linux
327environments. This makes it possible to expand the test coverage
328across distros, toolchain flavors and library versions. The support
329was originally written for Docker although we also support Podman as
330an alternative container runtime. Although many of the target
331names and scripts are prefixed with "docker" the system will
332automatically run on whichever is configured.
333
334The container images are also used to augment the generation of tests
335for testing TCG. See :ref:`checktcg-ref` for more details.
336
337Docker Prerequisites
338~~~~~~~~~~~~~~~~~~~~
339
340Install "docker" with the system package manager and start the Docker service
341on your development machine, then make sure you have the privilege to run
342Docker commands. Typically it means setting up passwordless ``sudo docker``
343command or login as root. For example:
344
345.. code::
346
347  $ sudo yum install docker
348  $ # or `apt-get install docker` for Ubuntu, etc.
349  $ sudo systemctl start docker
350  $ sudo docker ps
351
352The last command should print an empty table, to verify the system is ready.
353
354An alternative method to set up permissions is by adding the current user to
355"docker" group and making the docker daemon socket file (by default
356``/var/run/docker.sock``) accessible to the group:
357
358.. code::
359
360  $ sudo groupadd docker
361  $ sudo usermod $USER -a -G docker
362  $ sudo chown :docker /var/run/docker.sock
363
364Note that any one of above configurations makes it possible for the user to
365exploit the whole host with Docker bind mounting or other privileged
366operations.  So only do it on development machines.
367
368Podman Prerequisites
369~~~~~~~~~~~~~~~~~~~~
370
371Install "podman" with the system package manager.
372
373.. code::
374
375  $ sudo dnf install podman
376  $ podman ps
377
378The last command should print an empty table, to verify the system is ready.
379
380Quickstart
381~~~~~~~~~~
382
383From source tree, type ``make docker-help`` to see the help. Testing
384can be started without configuring or building QEMU (``configure`` and
385``make`` are done in the container, with parameters defined by the
386make target):
387
388.. code::
389
390  make docker-test-build@centos8
391
392This will create a container instance using the ``centos8`` image (the image
393is downloaded and initialized automatically), in which the ``test-build`` job
394is executed.
395
396Registry
397~~~~~~~~
398
399The QEMU project has a container registry hosted by GitLab at
400``registry.gitlab.com/qemu-project/qemu`` which will automatically be
401used to pull in pre-built layers. This avoids unnecessary strain on
402the distro archives created by multiple developers running the same
403container build steps over and over again. This can be overridden
404locally by using the ``NOCACHE`` build option:
405
406.. code::
407
408   make docker-image-debian-arm64-cross NOCACHE=1
409
410Images
411~~~~~~
412
413Along with many other images, the ``centos8`` image is defined in a Dockerfile
414in ``tests/docker/dockerfiles/``, called ``centos8.docker``. ``make docker-help``
415command will list all the available images.
416
417A ``.pre`` script can be added beside the ``.docker`` file, which will be
418executed before building the image under the build context directory. This is
419mainly used to do necessary host side setup. One such setup is ``binfmt_misc``,
420for example, to make qemu-user powered cross build containers work.
421
422Most of the existing Dockerfiles were written by hand, simply by creating a
423a new ``.docker`` file under the ``tests/docker/dockerfiles/`` directory.
424This has led to an inconsistent set of packages being present across the
425different containers.
426
427Thus going forward, QEMU is aiming to automatically generate the Dockerfiles
428using the ``lcitool`` program provided by the ``libvirt-ci`` project:
429
430  https://gitlab.com/libvirt/libvirt-ci
431
432``libvirt-ci`` contains an ``lcitool`` program as well as a list of
433mappings to distribution package names for a wide variety of third
434party projects.  ``lcitool`` applies the mappings to a list of build
435pre-requisites in ``tests/lcitool/projects/qemu.yml``, determines the
436list of native packages to install on each distribution, and uses them
437to generate build environments (dockerfiles and Cirrus CI variable files)
438that are consistent across OS distribution.
439
440
441Adding new build pre-requisites
442^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
443
444When preparing a patch series that adds a new build
445pre-requisite to QEMU, the prerequisites should to be added to
446``tests/lcitool/projects/qemu.yml`` in order to make the dependency
447available in the CI build environments.
448
449In the simple case where the pre-requisite is already known to ``libvirt-ci``
450the following steps are needed:
451
452 * Edit ``tests/lcitool/projects/qemu.yml`` and add the pre-requisite
453
454 * Run ``make lcitool-refresh`` to re-generate all relevant build environment
455   manifests
456
457It may be that ``libvirt-ci`` does not know about the new pre-requisite.
458If that is the case, some extra preparation steps will be required
459first to contribute the mapping to the ``libvirt-ci`` project:
460
461 * Fork the ``libvirt-ci`` project on gitlab
462
463 * Add an entry for the new build prerequisite to
464   ``lcitool/facts/mappings.yml``, listing its native package name on as
465   many OS distros as practical.  Run ``python -m pytest --regenerate-output``
466   and check that the changes are correct.
467
468 * Commit the ``mappings.yml`` change together with the regenerated test
469   files, and submit a merge request to the ``libvirt-ci`` project.
470   Please note in the description that this is a new build pre-requisite
471   desired for use with QEMU.
472
473 * CI pipeline will run to validate that the changes to ``mappings.yml``
474   are correct, by attempting to install the newly listed package on
475   all OS distributions supported by ``libvirt-ci``.
476
477 * Once the merge request is accepted, go back to QEMU and update
478   the ``tests/lcitool/libvirt-ci`` submodule to point to a commit that
479   contains the ``mappings.yml`` update.  Then add the prerequisite and
480   run ``make lcitool-refresh``.
481
482 * Please also trigger gitlab container generation pipelines on your change
483   for as many OS distros as practical to make sure that there are no
484   obvious breakages when adding the new pre-requisite. Please see
485   `CI <https://www.qemu.org/docs/master/devel/ci.html>`__ documentation
486   page on how to trigger gitlab CI pipelines on your change.
487
488For enterprise distros that default to old, end-of-life versions of the
489Python runtime, QEMU uses a separate set of mappings that work with more
490recent versions.  These can be found in ``tests/lcitool/mappings.yml``.
491Modifying this file should not be necessary unless the new pre-requisite
492is a Python library or tool.
493
494
495Adding new OS distros
496^^^^^^^^^^^^^^^^^^^^^
497
498In some cases ``libvirt-ci`` will not know about the OS distro that is
499desired to be tested. Before adding a new OS distro, discuss the proposed
500addition:
501
502 * Send a mail to qemu-devel, copying people listed in the
503   MAINTAINERS file for ``Build and test automation``.
504
505   There are limited CI compute resources available to QEMU, so the
506   cost/benefit tradeoff of adding new OS distros needs to be considered.
507
508 * File an issue at https://gitlab.com/libvirt/libvirt-ci/-/issues
509   pointing to the qemu-devel mail thread in the archives.
510
511   This alerts other people who might be interested in the work
512   to avoid duplication, as well as to get feedback from libvirt-ci
513   maintainers on any tips to ease the addition
514
515Assuming there is agreement to add a new OS distro then
516
517 * Fork the ``libvirt-ci`` project on gitlab
518
519 * Add metadata under ``lcitool/facts/targets/`` for the new OS
520   distro. There might be code changes required if the OS distro
521   uses a package format not currently known. The ``libvirt-ci``
522   maintainers can advise on this when the issue is filed.
523
524 * Edit the ``lcitool/facts/mappings.yml`` change to add entries for
525   the new OS, listing the native package names for as many packages
526   as practical.  Run ``python -m pytest --regenerate-output`` and
527   check that the changes are correct.
528
529 * Commit the changes to ``lcitool/facts`` and the regenerated test
530   files, and submit a merge request to the ``libvirt-ci`` project.
531   Please note in the description that this is a new build pre-requisite
532   desired for use with QEMU
533
534 * CI pipeline will run to validate that the changes to ``mappings.yml``
535   are correct, by attempting to install the newly listed package on
536   all OS distributions supported by ``libvirt-ci``.
537
538 * Once the merge request is accepted, go back to QEMU and update
539   the ``libvirt-ci`` submodule to point to a commit that contains
540   the ``mappings.yml`` update.
541
542
543Tests
544~~~~~
545
546Different tests are added to cover various configurations to build and test
547QEMU.  Docker tests are the executables under ``tests/docker`` named
548``test-*``. They are typically shell scripts and are built on top of a shell
549library, ``tests/docker/common.rc``, which provides helpers to find the QEMU
550source and build it.
551
552The full list of tests is printed in the ``make docker-help`` help.
553
554Debugging a Docker test failure
555~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
556
557When CI tasks, maintainers or yourself report a Docker test failure, follow the
558below steps to debug it:
559
5601. Locally reproduce the failure with the reported command line. E.g. run
561   ``make docker-test-mingw@fedora J=8``.
5622. Add "V=1" to the command line, try again, to see the verbose output.
5633. Further add "DEBUG=1" to the command line. This will pause in a shell prompt
564   in the container right before testing starts. You could either manually
565   build QEMU and run tests from there, or press Ctrl-D to let the Docker
566   testing continue.
5674. If you press Ctrl-D, the same building and testing procedure will begin, and
568   will hopefully run into the error again. After that, you will be dropped to
569   the prompt for debug.
570
571Options
572~~~~~~~
573
574Various options can be used to affect how Docker tests are done. The full
575list is in the ``make docker`` help text. The frequently used ones are:
576
577* ``V=1``: the same as in top level ``make``. It will be propagated to the
578  container and enable verbose output.
579* ``J=$N``: the number of parallel tasks in make commands in the container,
580  similar to the ``-j $N`` option in top level ``make``. (The ``-j`` option in
581  top level ``make`` will not be propagated into the container.)
582* ``DEBUG=1``: enables debug. See the previous "Debugging a Docker test
583  failure" section.
584
585Thread Sanitizer
586----------------
587
588Thread Sanitizer (TSan) is a tool which can detect data races.  QEMU supports
589building and testing with this tool.
590
591For more information on TSan:
592
593https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual
594
595Thread Sanitizer in Docker
596~~~~~~~~~~~~~~~~~~~~~~~~~~
597TSan is currently supported in the ubuntu2204 docker.
598
599The test-tsan test will build using TSan and then run make check.
600
601.. code::
602
603  make docker-test-tsan@ubuntu2204
604
605TSan warnings under docker are placed in files located at build/tsan/.
606
607We recommend using DEBUG=1 to allow launching the test from inside the docker,
608and to allow review of the warnings generated by TSan.
609
610Building and Testing with TSan
611~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
612
613It is possible to build and test with TSan, with a few additional steps.
614These steps are normally done automatically in the docker.
615
616There is a one time patch needed in clang-9 or clang-10 at this time:
617
618.. code::
619
620  sed -i 's/^const/static const/g' \
621      /usr/lib/llvm-10/lib/clang/10.0.0/include/sanitizer/tsan_interface.h
622
623To configure the build for TSan:
624
625.. code::
626
627  ../configure --enable-tsan --cc=clang-10 --cxx=clang++-10 \
628               --disable-werror --extra-cflags="-O0"
629
630The runtime behavior of TSAN is controlled by the TSAN_OPTIONS environment
631variable.
632
633More information on the TSAN_OPTIONS can be found here:
634
635https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags
636
637For example:
638
639.. code::
640
641  export TSAN_OPTIONS=suppressions=<path to qemu>/tests/tsan/suppressions.tsan \
642                      detect_deadlocks=false history_size=7 exitcode=0 \
643                      log_path=<build path>/tsan/tsan_warning
644
645The above exitcode=0 has TSan continue without error if any warnings are found.
646This allows for running the test and then checking the warnings afterwards.
647If you want TSan to stop and exit with error on warnings, use exitcode=66.
648
649TSan Suppressions
650~~~~~~~~~~~~~~~~~
651Keep in mind that for any data race warning, although there might be a data race
652detected by TSan, there might be no actual bug here.  TSan provides several
653different mechanisms for suppressing warnings.  In general it is recommended
654to fix the code if possible to eliminate the data race rather than suppress
655the warning.
656
657A few important files for suppressing warnings are:
658
659tests/tsan/suppressions.tsan - Has TSan warnings we wish to suppress at runtime.
660The comment on each suppression will typically indicate why we are
661suppressing it.  More information on the file format can be found here:
662
663https://github.com/google/sanitizers/wiki/ThreadSanitizerSuppressions
664
665tests/tsan/blacklist.tsan - Has TSan warnings we wish to disable
666at compile time for test or debug.
667Add flags to configure to enable:
668
669"--extra-cflags=-fsanitize-blacklist=<src path>/tests/tsan/blacklist.tsan"
670
671More information on the file format can be found here under "Blacklist Format":
672
673https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags
674
675TSan Annotations
676~~~~~~~~~~~~~~~~
677include/qemu/tsan.h defines annotations.  See this file for more descriptions
678of the annotations themselves.  Annotations can be used to suppress
679TSan warnings or give TSan more information so that it can detect proper
680relationships between accesses of data.
681
682Annotation examples can be found here:
683
684https://github.com/llvm/llvm-project/tree/master/compiler-rt/test/tsan/
685
686Good files to start with are: annotate_happens_before.cpp and ignore_race.cpp
687
688The full set of annotations can be found here:
689
690https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/tsan/rtl/tsan_interface_ann.cpp
691
692docker-binfmt-image-debian-% targets
693------------------------------------
694
695It is possible to combine Debian's bootstrap scripts with a configured
696``binfmt_misc`` to bootstrap a number of Debian's distros including
697experimental ports not yet supported by a released OS. This can
698simplify setting up a rootfs by using docker to contain the foreign
699rootfs rather than manually invoking chroot.
700
701Setting up ``binfmt_misc``
702~~~~~~~~~~~~~~~~~~~~~~~~~~
703
704You can use the script ``qemu-binfmt-conf.sh`` to configure a QEMU
705user binary to automatically run binaries for the foreign
706architecture. While the scripts will try their best to work with
707dynamically linked QEMU's a statically linked one will present less
708potential complications when copying into the docker image. Modern
709kernels support the ``F`` (fix binary) flag which will open the QEMU
710executable on setup and avoids the need to find and re-open in the
711chroot environment. This is triggered with the ``--persistent`` flag.
712
713Example invocation
714~~~~~~~~~~~~~~~~~~
715
716For example to setup the HPPA ports builds of Debian::
717
718  make docker-binfmt-image-debian-sid-hppa \
719    DEB_TYPE=sid DEB_ARCH=hppa \
720    DEB_URL=http://ftp.ports.debian.org/debian-ports/ \
721    DEB_KEYRING=/usr/share/keyrings/debian-ports-archive-keyring.gpg \
722    EXECUTABLE=(pwd)/qemu-hppa V=1
723
724The ``DEB_`` variables are substitutions used by
725``debian-boostrap.pre`` which is called to do the initial debootstrap
726of the rootfs before it is copied into the container. The second stage
727is run as part of the build. The final image will be tagged as
728``qemu/debian-sid-hppa``.
729
730VM testing
731----------
732
733This test suite contains scripts that bootstrap various guest images that have
734necessary packages to build QEMU. The basic usage is documented in ``Makefile``
735help which is displayed with ``make vm-help``.
736
737Quickstart
738~~~~~~~~~~
739
740Run ``make vm-help`` to list available make targets. Invoke a specific make
741command to run build test in an image. For example, ``make vm-build-freebsd``
742will build the source tree in the FreeBSD image. The command can be executed
743from either the source tree or the build dir; if the former, ``./configure`` is
744not needed. The command will then generate the test image in ``./tests/vm/``
745under the working directory.
746
747Note: images created by the scripts accept a well-known RSA key pair for SSH
748access, so they SHOULD NOT be exposed to external interfaces if you are
749concerned about attackers taking control of the guest and potentially
750exploiting a QEMU security bug to compromise the host.
751
752QEMU binaries
753~~~~~~~~~~~~~
754
755By default, ``qemu-system-x86_64`` is searched in $PATH to run the guest. If
756there isn't one, or if it is older than 2.10, the test won't work. In this case,
757provide the QEMU binary in env var: ``QEMU=/path/to/qemu-2.10+``.
758
759Likewise the path to ``qemu-img`` can be set in QEMU_IMG environment variable.
760
761Make jobs
762~~~~~~~~~
763
764The ``-j$X`` option in the make command line is not propagated into the VM,
765specify ``J=$X`` to control the make jobs in the guest.
766
767Debugging
768~~~~~~~~~
769
770Add ``DEBUG=1`` and/or ``V=1`` to the make command to allow interactive
771debugging and verbose output. If this is not enough, see the next section.
772``V=1`` will be propagated down into the make jobs in the guest.
773
774Manual invocation
775~~~~~~~~~~~~~~~~~
776
777Each guest script is an executable script with the same command line options.
778For example to work with the netbsd guest, use ``$QEMU_SRC/tests/vm/netbsd``:
779
780.. code::
781
782    $ cd $QEMU_SRC/tests/vm
783
784    # To bootstrap the image
785    $ ./netbsd --build-image --image /var/tmp/netbsd.img
786    <...>
787
788    # To run an arbitrary command in guest (the output will not be echoed unless
789    # --debug is added)
790    $ ./netbsd --debug --image /var/tmp/netbsd.img uname -a
791
792    # To build QEMU in guest
793    $ ./netbsd --debug --image /var/tmp/netbsd.img --build-qemu $QEMU_SRC
794
795    # To get to an interactive shell
796    $ ./netbsd --interactive --image /var/tmp/netbsd.img sh
797
798Adding new guests
799~~~~~~~~~~~~~~~~~
800
801Please look at existing guest scripts for how to add new guests.
802
803Most importantly, create a subclass of BaseVM and implement ``build_image()``
804method and define ``BUILD_SCRIPT``, then finally call ``basevm.main()`` from
805the script's ``main()``.
806
807* Usually in ``build_image()``, a template image is downloaded from a
808  predefined URL. ``BaseVM._download_with_cache()`` takes care of the cache and
809  the checksum, so consider using it.
810
811* Once the image is downloaded, users, SSH server and QEMU build deps should
812  be set up:
813
814  - Root password set to ``BaseVM.ROOT_PASS``
815  - User ``BaseVM.GUEST_USER`` is created, and password set to
816    ``BaseVM.GUEST_PASS``
817  - SSH service is enabled and started on boot,
818    ``$QEMU_SRC/tests/keys/id_rsa.pub`` is added to ssh's ``authorized_keys``
819    file of both root and the normal user
820  - DHCP client service is enabled and started on boot, so that it can
821    automatically configure the virtio-net-pci NIC and communicate with QEMU
822    user net (10.0.2.2)
823  - Necessary packages are installed to untar the source tarball and build
824    QEMU
825
826* Write a proper ``BUILD_SCRIPT`` template, which should be a shell script that
827  untars a raw virtio-blk block device, which is the tarball data blob of the
828  QEMU source tree, then configure/build it. Running "make check" is also
829  recommended.
830
831Image fuzzer testing
832--------------------
833
834An image fuzzer was added to exercise format drivers. Currently only qcow2 is
835supported. To start the fuzzer, run
836
837.. code::
838
839  tests/image-fuzzer/runner.py -c '[["qemu-img", "info", "$test_img"]]' /tmp/test qcow2
840
841Alternatively, some command different from ``qemu-img info`` can be tested, by
842changing the ``-c`` option.
843
844Integration tests using the Avocado Framework
845---------------------------------------------
846
847The ``tests/avocado`` directory hosts integration tests. They're usually
848higher level tests, and may interact with external resources and with
849various guest operating systems.
850
851These tests are written using the Avocado Testing Framework (which must
852be installed separately) in conjunction with a the ``avocado_qemu.Test``
853class, implemented at ``tests/avocado/avocado_qemu``.
854
855Tests based on ``avocado_qemu.Test`` can easily:
856
857 * Customize the command line arguments given to the convenience
858   ``self.vm`` attribute (a QEMUMachine instance)
859
860 * Interact with the QEMU monitor, send QMP commands and check
861   their results
862
863 * Interact with the guest OS, using the convenience console device
864   (which may be useful to assert the effectiveness and correctness of
865   command line arguments or QMP commands)
866
867 * Interact with external data files that accompany the test itself
868   (see ``self.get_data()``)
869
870 * Download (and cache) remote data files, such as firmware and kernel
871   images
872
873 * Have access to a library of guest OS images (by means of the
874   ``avocado.utils.vmimage`` library)
875
876 * Make use of various other test related utilities available at the
877   test class itself and at the utility library:
878
879   - http://avocado-framework.readthedocs.io/en/latest/api/test/avocado.html#avocado.Test
880   - http://avocado-framework.readthedocs.io/en/latest/api/utils/avocado.utils.html
881
882Running tests
883~~~~~~~~~~~~~
884
885You can run the avocado tests simply by executing:
886
887.. code::
888
889  make check-avocado
890
891This involves the automatic installation, from PyPI, of all the
892necessary avocado-framework dependencies into the QEMU venv within the
893build tree (at ``./pyvenv``). Test results are also saved within the
894build tree (at ``tests/results``).
895
896Note: the build environment must be using a Python 3 stack, and have
897the ``venv`` and ``pip`` packages installed.  If necessary, make sure
898``configure`` is called with ``--python=`` and that those modules are
899available.  On Debian and Ubuntu based systems, depending on the
900specific version, they may be on packages named ``python3-venv`` and
901``python3-pip``.
902
903It is also possible to run tests based on tags using the
904``make check-avocado`` command and the ``AVOCADO_TAGS`` environment
905variable:
906
907.. code::
908
909   make check-avocado AVOCADO_TAGS=quick
910
911Note that tags separated with commas have an AND behavior, while tags
912separated by spaces have an OR behavior. For more information on Avocado
913tags, see:
914
915 https://avocado-framework.readthedocs.io/en/latest/guides/user/chapters/tags.html
916
917To run a single test file, a couple of them, or a test within a file
918using the ``make check-avocado`` command, set the ``AVOCADO_TESTS``
919environment variable with the test files or test names. To run all
920tests from a single file, use:
921
922 .. code::
923
924  make check-avocado AVOCADO_TESTS=$FILEPATH
925
926The same is valid to run tests from multiple test files:
927
928 .. code::
929
930  make check-avocado AVOCADO_TESTS='$FILEPATH1 $FILEPATH2'
931
932To run a single test within a file, use:
933
934 .. code::
935
936  make check-avocado AVOCADO_TESTS=$FILEPATH:$TESTCLASS.$TESTNAME
937
938The same is valid to run single tests from multiple test files:
939
940 .. code::
941
942  make check-avocado AVOCADO_TESTS='$FILEPATH1:$TESTCLASS1.$TESTNAME1 $FILEPATH2:$TESTCLASS2.$TESTNAME2'
943
944The scripts installed inside the virtual environment may be used
945without an "activation".  For instance, the Avocado test runner
946may be invoked by running:
947
948 .. code::
949
950  pyvenv/bin/avocado run $OPTION1 $OPTION2 tests/avocado/
951
952Note that if ``make check-avocado`` was not executed before, it is
953possible to create the Python virtual environment with the dependencies
954needed running:
955
956 .. code::
957
958  make check-venv
959
960It is also possible to run tests from a single file or a single test within
961a test file. To run tests from a single file within the build tree, use:
962
963 .. code::
964
965  pyvenv/bin/avocado run tests/avocado/$TESTFILE
966
967To run a single test within a test file, use:
968
969 .. code::
970
971  pyvenv/bin/avocado run tests/avocado/$TESTFILE:$TESTCLASS.$TESTNAME
972
973Valid test names are visible in the output from any previous execution
974of Avocado or ``make check-avocado``, and can also be queried using:
975
976 .. code::
977
978  pyvenv/bin/avocado list tests/avocado
979
980Manual Installation
981~~~~~~~~~~~~~~~~~~~
982
983To manually install Avocado and its dependencies, run:
984
985.. code::
986
987  pip install --user avocado-framework
988
989Alternatively, follow the instructions on this link:
990
991  https://avocado-framework.readthedocs.io/en/latest/guides/user/chapters/installing.html
992
993Overview
994~~~~~~~~
995
996The ``tests/avocado/avocado_qemu`` directory provides the
997``avocado_qemu`` Python module, containing the ``avocado_qemu.Test``
998class.  Here's a simple usage example:
999
1000.. code::
1001
1002  from avocado_qemu import QemuSystemTest
1003
1004
1005  class Version(QemuSystemTest):
1006      """
1007      :avocado: tags=quick
1008      """
1009      def test_qmp_human_info_version(self):
1010          self.vm.launch()
1011          res = self.vm.command('human-monitor-command',
1012                                command_line='info version')
1013          self.assertRegexpMatches(res, r'^(\d+\.\d+\.\d)')
1014
1015To execute your test, run:
1016
1017.. code::
1018
1019  avocado run version.py
1020
1021Tests may be classified according to a convention by using docstring
1022directives such as ``:avocado: tags=TAG1,TAG2``.  To run all tests
1023in the current directory, tagged as "quick", run:
1024
1025.. code::
1026
1027  avocado run -t quick .
1028
1029The ``avocado_qemu.Test`` base test class
1030^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1031
1032The ``avocado_qemu.Test`` class has a number of characteristics that
1033are worth being mentioned right away.
1034
1035First of all, it attempts to give each test a ready to use QEMUMachine
1036instance, available at ``self.vm``.  Because many tests will tweak the
1037QEMU command line, launching the QEMUMachine (by using ``self.vm.launch()``)
1038is left to the test writer.
1039
1040The base test class has also support for tests with more than one
1041QEMUMachine. The way to get machines is through the ``self.get_vm()``
1042method which will return a QEMUMachine instance. The ``self.get_vm()``
1043method accepts arguments that will be passed to the QEMUMachine creation
1044and also an optional ``name`` attribute so you can identify a specific
1045machine and get it more than once through the tests methods. A simple
1046and hypothetical example follows:
1047
1048.. code::
1049
1050  from avocado_qemu import QemuSystemTest
1051
1052
1053  class MultipleMachines(QemuSystemTest):
1054      def test_multiple_machines(self):
1055          first_machine = self.get_vm()
1056          second_machine = self.get_vm()
1057          self.get_vm(name='third_machine').launch()
1058
1059          first_machine.launch()
1060          second_machine.launch()
1061
1062          first_res = first_machine.command(
1063              'human-monitor-command',
1064              command_line='info version')
1065
1066          second_res = second_machine.command(
1067              'human-monitor-command',
1068              command_line='info version')
1069
1070          third_res = self.get_vm(name='third_machine').command(
1071              'human-monitor-command',
1072              command_line='info version')
1073
1074          self.assertEquals(first_res, second_res, third_res)
1075
1076At test "tear down", ``avocado_qemu.Test`` handles all the QEMUMachines
1077shutdown.
1078
1079The ``avocado_qemu.LinuxTest`` base test class
1080^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1081
1082The ``avocado_qemu.LinuxTest`` is further specialization of the
1083``avocado_qemu.Test`` class, so it contains all the characteristics of
1084the later plus some extra features.
1085
1086First of all, this base class is intended for tests that need to
1087interact with a fully booted and operational Linux guest.  At this
1088time, it uses a Fedora 31 guest image.  The most basic example looks
1089like this:
1090
1091.. code::
1092
1093  from avocado_qemu import LinuxTest
1094
1095
1096  class SomeTest(LinuxTest):
1097
1098      def test(self):
1099          self.launch_and_wait()
1100          self.ssh_command('some_command_to_be_run_in_the_guest')
1101
1102Please refer to tests that use ``avocado_qemu.LinuxTest`` under
1103``tests/avocado`` for more examples.
1104
1105QEMUMachine
1106~~~~~~~~~~~
1107
1108The QEMUMachine API is already widely used in the Python iotests,
1109device-crash-test and other Python scripts.  It's a wrapper around the
1110execution of a QEMU binary, giving its users:
1111
1112 * the ability to set command line arguments to be given to the QEMU
1113   binary
1114
1115 * a ready to use QMP connection and interface, which can be used to
1116   send commands and inspect its results, as well as asynchronous
1117   events
1118
1119 * convenience methods to set commonly used command line arguments in
1120   a more succinct and intuitive way
1121
1122QEMU binary selection
1123^^^^^^^^^^^^^^^^^^^^^
1124
1125The QEMU binary used for the ``self.vm`` QEMUMachine instance will
1126primarily depend on the value of the ``qemu_bin`` parameter.  If it's
1127not explicitly set, its default value will be the result of a dynamic
1128probe in the same source tree.  A suitable binary will be one that
1129targets the architecture matching host machine.
1130
1131Based on this description, test writers will usually rely on one of
1132the following approaches:
1133
11341) Set ``qemu_bin``, and use the given binary
1135
11362) Do not set ``qemu_bin``, and use a QEMU binary named like
1137   "qemu-system-${arch}", either in the current
1138   working directory, or in the current source tree.
1139
1140The resulting ``qemu_bin`` value will be preserved in the
1141``avocado_qemu.Test`` as an attribute with the same name.
1142
1143Attribute reference
1144~~~~~~~~~~~~~~~~~~~
1145
1146Test
1147^^^^
1148
1149Besides the attributes and methods that are part of the base
1150``avocado.Test`` class, the following attributes are available on any
1151``avocado_qemu.Test`` instance.
1152
1153vm
1154''
1155
1156A QEMUMachine instance, initially configured according to the given
1157``qemu_bin`` parameter.
1158
1159arch
1160''''
1161
1162The architecture can be used on different levels of the stack, e.g. by
1163the framework or by the test itself.  At the framework level, it will
1164currently influence the selection of a QEMU binary (when one is not
1165explicitly given).
1166
1167Tests are also free to use this attribute value, for their own needs.
1168A test may, for instance, use the same value when selecting the
1169architecture of a kernel or disk image to boot a VM with.
1170
1171The ``arch`` attribute will be set to the test parameter of the same
1172name.  If one is not given explicitly, it will either be set to
1173``None``, or, if the test is tagged with one (and only one)
1174``:avocado: tags=arch:VALUE`` tag, it will be set to ``VALUE``.
1175
1176cpu
1177'''
1178
1179The cpu model that will be set to all QEMUMachine instances created
1180by the test.
1181
1182The ``cpu`` attribute will be set to the test parameter of the same
1183name. If one is not given explicitly, it will either be set to
1184``None ``, or, if the test is tagged with one (and only one)
1185``:avocado: tags=cpu:VALUE`` tag, it will be set to ``VALUE``.
1186
1187machine
1188'''''''
1189
1190The machine type that will be set to all QEMUMachine instances created
1191by the test.
1192
1193The ``machine`` attribute will be set to the test parameter of the same
1194name.  If one is not given explicitly, it will either be set to
1195``None``, or, if the test is tagged with one (and only one)
1196``:avocado: tags=machine:VALUE`` tag, it will be set to ``VALUE``.
1197
1198qemu_bin
1199''''''''
1200
1201The preserved value of the ``qemu_bin`` parameter or the result of the
1202dynamic probe for a QEMU binary in the current working directory or
1203source tree.
1204
1205LinuxTest
1206^^^^^^^^^
1207
1208Besides the attributes present on the ``avocado_qemu.Test`` base
1209class, the ``avocado_qemu.LinuxTest`` adds the following attributes:
1210
1211distro
1212''''''
1213
1214The name of the Linux distribution used as the guest image for the
1215test.  The name should match the **Provider** column on the list
1216of images supported by the avocado.utils.vmimage library:
1217
1218https://avocado-framework.readthedocs.io/en/latest/guides/writer/libs/vmimage.html#supported-images
1219
1220distro_version
1221''''''''''''''
1222
1223The version of the Linux distribution as the guest image for the
1224test.  The name should match the **Version** column on the list
1225of images supported by the avocado.utils.vmimage library:
1226
1227https://avocado-framework.readthedocs.io/en/latest/guides/writer/libs/vmimage.html#supported-images
1228
1229distro_checksum
1230'''''''''''''''
1231
1232The sha256 hash of the guest image file used for the test.
1233
1234If this value is not set in the code or by a test parameter (with the
1235same name), no validation on the integrity of the image will be
1236performed.
1237
1238Parameter reference
1239~~~~~~~~~~~~~~~~~~~
1240
1241To understand how Avocado parameters are accessed by tests, and how
1242they can be passed to tests, please refer to::
1243
1244  https://avocado-framework.readthedocs.io/en/latest/guides/writer/chapters/writing.html#accessing-test-parameters
1245
1246Parameter values can be easily seen in the log files, and will look
1247like the following:
1248
1249.. code::
1250
1251  PARAMS (key=qemu_bin, path=*, default=./qemu-system-x86_64) => './qemu-system-x86_64
1252
1253Test
1254^^^^
1255
1256arch
1257''''
1258
1259The architecture that will influence the selection of a QEMU binary
1260(when one is not explicitly given).
1261
1262Tests are also free to use this parameter value, for their own needs.
1263A test may, for instance, use the same value when selecting the
1264architecture of a kernel or disk image to boot a VM with.
1265
1266This parameter has a direct relation with the ``arch`` attribute.  If
1267not given, it will default to None.
1268
1269cpu
1270'''
1271
1272The cpu model that will be set to all QEMUMachine instances created
1273by the test.
1274
1275machine
1276'''''''
1277
1278The machine type that will be set to all QEMUMachine instances created
1279by the test.
1280
1281qemu_bin
1282''''''''
1283
1284The exact QEMU binary to be used on QEMUMachine.
1285
1286LinuxTest
1287^^^^^^^^^
1288
1289Besides the parameters present on the ``avocado_qemu.Test`` base
1290class, the ``avocado_qemu.LinuxTest`` adds the following parameters:
1291
1292distro
1293''''''
1294
1295The name of the Linux distribution used as the guest image for the
1296test.  The name should match the **Provider** column on the list
1297of images supported by the avocado.utils.vmimage library:
1298
1299https://avocado-framework.readthedocs.io/en/latest/guides/writer/libs/vmimage.html#supported-images
1300
1301distro_version
1302''''''''''''''
1303
1304The version of the Linux distribution as the guest image for the
1305test.  The name should match the **Version** column on the list
1306of images supported by the avocado.utils.vmimage library:
1307
1308https://avocado-framework.readthedocs.io/en/latest/guides/writer/libs/vmimage.html#supported-images
1309
1310distro_checksum
1311'''''''''''''''
1312
1313The sha256 hash of the guest image file used for the test.
1314
1315If this value is not set in the code or by this parameter no
1316validation on the integrity of the image will be performed.
1317
1318Skipping tests
1319~~~~~~~~~~~~~~
1320
1321The Avocado framework provides Python decorators which allow for easily skip
1322tests running under certain conditions. For example, on the lack of a binary
1323on the test system or when the running environment is a CI system. For further
1324information about those decorators, please refer to::
1325
1326  https://avocado-framework.readthedocs.io/en/latest/guides/writer/chapters/writing.html#skipping-tests
1327
1328While the conditions for skipping tests are often specifics of each one, there
1329are recurring scenarios identified by the QEMU developers and the use of
1330environment variables became a kind of standard way to enable/disable tests.
1331
1332Here is a list of the most used variables:
1333
1334AVOCADO_ALLOW_LARGE_STORAGE
1335^^^^^^^^^^^^^^^^^^^^^^^^^^^
1336Tests which are going to fetch or produce assets considered *large* are not
1337going to run unless that ``AVOCADO_ALLOW_LARGE_STORAGE=1`` is exported on
1338the environment.
1339
1340The definition of *large* is a bit arbitrary here, but it usually means an
1341asset which occupies at least 1GB of size on disk when uncompressed.
1342
1343AVOCADO_ALLOW_UNTRUSTED_CODE
1344^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1345There are tests which will boot a kernel image or firmware that can be
1346considered not safe to run on the developer's workstation, thus they are
1347skipped by default. The definition of *not safe* is also arbitrary but
1348usually it means a blob which either its source or build process aren't
1349public available.
1350
1351You should export ``AVOCADO_ALLOW_UNTRUSTED_CODE=1`` on the environment in
1352order to allow tests which make use of those kind of assets.
1353
1354AVOCADO_TIMEOUT_EXPECTED
1355^^^^^^^^^^^^^^^^^^^^^^^^
1356The Avocado framework has a timeout mechanism which interrupts tests to avoid the
1357test suite of getting stuck. The timeout value can be set via test parameter or
1358property defined in the test class, for further details::
1359
1360  https://avocado-framework.readthedocs.io/en/latest/guides/writer/chapters/writing.html#setting-a-test-timeout
1361
1362Even though the timeout can be set by the test developer, there are some tests
1363that may not have a well-defined limit of time to finish under certain
1364conditions. For example, tests that take longer to execute when QEMU is
1365compiled with debug flags. Therefore, the ``AVOCADO_TIMEOUT_EXPECTED`` variable
1366has been used to determine whether those tests should run or not.
1367
1368GITLAB_CI
1369^^^^^^^^^
1370A number of tests are flagged to not run on the GitLab CI. Usually because
1371they proved to the flaky or there are constraints on the CI environment which
1372would make them fail. If you encounter a similar situation then use that
1373variable as shown on the code snippet below to skip the test:
1374
1375.. code::
1376
1377  @skipIf(os.getenv('GITLAB_CI'), 'Running on GitLab')
1378  def test(self):
1379      do_something()
1380
1381Uninstalling Avocado
1382~~~~~~~~~~~~~~~~~~~~
1383
1384If you've followed the manual installation instructions above, you can
1385easily uninstall Avocado.  Start by listing the packages you have
1386installed::
1387
1388  pip list --user
1389
1390And remove any package you want with::
1391
1392  pip uninstall <package_name>
1393
1394If you've used ``make check-avocado``, the Python virtual environment where
1395Avocado is installed will be cleaned up as part of ``make check-clean``.
1396
1397.. _checktcg-ref:
1398
1399Testing with "make check-tcg"
1400-----------------------------
1401
1402The check-tcg tests are intended for simple smoke tests of both
1403linux-user and softmmu TCG functionality. However to build test
1404programs for guest targets you need to have cross compilers available.
1405If your distribution supports cross compilers you can do something as
1406simple as::
1407
1408  apt install gcc-aarch64-linux-gnu
1409
1410The configure script will automatically pick up their presence.
1411Sometimes compilers have slightly odd names so the availability of
1412them can be prompted by passing in the appropriate configure option
1413for the architecture in question, for example::
1414
1415  $(configure) --cross-cc-aarch64=aarch64-cc
1416
1417There is also a ``--cross-cc-cflags-ARCH`` flag in case additional
1418compiler flags are needed to build for a given target.
1419
1420If you have the ability to run containers as the user the build system
1421will automatically use them where no system compiler is available. For
1422architectures where we also support building QEMU we will generally
1423use the same container to build tests. However there are a number of
1424additional containers defined that have a minimal cross-build
1425environment that is only suitable for building test cases. Sometimes
1426we may use a bleeding edge distribution for compiler features needed
1427for test cases that aren't yet in the LTS distros we support for QEMU
1428itself.
1429
1430See :ref:`container-ref` for more details.
1431
1432Running subset of tests
1433~~~~~~~~~~~~~~~~~~~~~~~
1434
1435You can build the tests for one architecture::
1436
1437  make build-tcg-tests-$TARGET
1438
1439And run with::
1440
1441  make run-tcg-tests-$TARGET
1442
1443Adding ``V=1`` to the invocation will show the details of how to
1444invoke QEMU for the test which is useful for debugging tests.
1445
1446TCG test dependencies
1447~~~~~~~~~~~~~~~~~~~~~
1448
1449The TCG tests are deliberately very light on dependencies and are
1450either totally bare with minimal gcc lib support (for softmmu tests)
1451or just glibc (for linux-user tests). This is because getting a cross
1452compiler to work with additional libraries can be challenging.
1453
1454Other TCG Tests
1455---------------
1456
1457There are a number of out-of-tree test suites that are used for more
1458extensive testing of processor features.
1459
1460KVM Unit Tests
1461~~~~~~~~~~~~~~
1462
1463The KVM unit tests are designed to run as a Guest OS under KVM but
1464there is no reason why they can't exercise the TCG as well. It
1465provides a minimal OS kernel with hooks for enabling the MMU as well
1466as reporting test results via a special device::
1467
1468  https://git.kernel.org/pub/scm/virt/kvm/kvm-unit-tests.git
1469
1470Linux Test Project
1471~~~~~~~~~~~~~~~~~~
1472
1473The LTP is focused on exercising the syscall interface of a Linux
1474kernel. It checks that syscalls behave as documented and strives to
1475exercise as many corner cases as possible. It is a useful test suite
1476to run to exercise QEMU's linux-user code::
1477
1478  https://linux-test-project.github.io/
1479
1480GCC gcov support
1481----------------
1482
1483``gcov`` is a GCC tool to analyze the testing coverage by
1484instrumenting the tested code. To use it, configure QEMU with
1485``--enable-gcov`` option and build. Then run the tests as usual.
1486
1487If you want to gather coverage information on a single test the ``make
1488clean-gcda`` target can be used to delete any existing coverage
1489information before running a single test.
1490
1491You can generate a HTML coverage report by executing ``make
1492coverage-html`` which will create
1493``meson-logs/coveragereport/index.html``.
1494
1495Further analysis can be conducted by running the ``gcov`` command
1496directly on the various .gcda output files. Please read the ``gcov``
1497documentation for more information.
1498