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