build-system.rst 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. ==================================
  2. The QEMU build system architecture
  3. ==================================
  4. This document aims to help developers understand the architecture of the
  5. QEMU build system. As with projects using GNU autotools, the QEMU build
  6. system has two stages; first the developer runs the "configure" script
  7. to determine the local build environment characteristics, then they run
  8. "make" to build the project. This is about where the similarities with
  9. GNU autotools end, so try to forget what you know about them.
  10. The two general ways to perform a build are as follows:
  11. - build artifacts outside of QEMU source tree entirely::
  12. cd ../
  13. mkdir build
  14. cd build
  15. ../qemu/configure
  16. make
  17. - build artifacts in a subdir of QEMU source tree::
  18. mkdir build
  19. cd build
  20. ../configure
  21. make
  22. Most of the actual build process uses Meson under the hood, therefore
  23. build artifacts cannot be placed in the source tree itself.
  24. Stage 1: configure
  25. ==================
  26. The configure script has five tasks:
  27. - detect the host architecture
  28. - list the targets for which to build emulators; the list of
  29. targets also affects which firmware binaries and tests to build
  30. - find the compilers (native and cross) used to build executables,
  31. firmware and tests. The results are written as either Makefile
  32. fragments (``config-host.mak``) or a Meson machine file
  33. (``config-meson.cross``)
  34. - create a virtual environment in which all Python code runs during
  35. the build, and possibly install packages into it from PyPI
  36. - invoke Meson in the virtual environment, to perform the actual
  37. configuration step for the emulator build
  38. The configure script automatically recognizes command line options for
  39. which a same-named Meson option exists; dashes in the command line are
  40. replaced with underscores.
  41. Almost all QEMU developers that need to modify the build system will
  42. only be concerned with Meson, and therefore can skip the rest of this
  43. section.
  44. Modifying ``configure``
  45. -----------------------
  46. ``configure`` is a shell script; it uses ``#!/bin/sh`` and therefore
  47. should be compatible with any POSIX shell. It is important to avoid
  48. using bash-isms to avoid breaking development platforms where bash is
  49. the primary host.
  50. The configure script provides a variety of functions to help writing
  51. portable shell code and providing consistent behavior across architectures
  52. and operating systems:
  53. ``error_exit $MESSAGE $MORE...``
  54. Print $MESSAGE to stderr, followed by $MORE... and then exit from the
  55. configure script with non-zero status.
  56. ``has $COMMAND``
  57. Determine if $COMMAND exists in the current environment, either as a
  58. shell builtin, or executable binary, returning 0 on success. The
  59. replacement in Meson is ``find_program()``.
  60. ``probe_target_compiler $TARGET``
  61. Detect a cross compiler and cross tools for the QEMU target $TARGET (e.g.,
  62. ``$CPU-softmmu``, ``$CPU-linux-user``, ``$CPU-bsd-user``). If a working
  63. compiler is present, return success and set variables ``$target_cc``,
  64. ``$target_ar``, etc. to non-empty values.
  65. ``write_target_makefile``
  66. Write a Makefile fragment to stdout, exposing the result of the most
  67. ``probe_target_compiler`` call as the usual Make variables (``CC``,
  68. ``AR``, ``LD``, etc.).
  69. Configure does not generally perform tests for compiler options beyond
  70. basic checks to detect the host platform and ensure the compiler is
  71. functioning. These are performed using a few more helper functions:
  72. ``compile_object $CFLAGS``
  73. Attempt to compile a test program with the system C compiler using
  74. $CFLAGS. The test program must have been previously written to a file
  75. called $TMPC.
  76. ``compile_prog $CFLAGS $LDFLAGS``
  77. Attempt to compile a test program with the system C compiler using
  78. $CFLAGS and link it with the system linker using $LDFLAGS. The test
  79. program must have been previously written to a file called $TMPC.
  80. ``check_define $NAME``
  81. Determine if the macro $NAME is defined by the system C compiler.
  82. ``do_compiler $CC $ARGS...``
  83. Attempt to run the C compiler $CC, passing it $ARGS... This function
  84. does not use flags passed via options such as ``--extra-cflags``, and
  85. therefore can be used to check for cross compilers. However, most
  86. such checks are done at ``make`` time instead (see for example the
  87. ``cc-option`` macro in ``pc-bios/option-rom/Makefile``).
  88. ``write_c_skeleton``
  89. Write a minimal C program main() function to the temporary file
  90. indicated by $TMPC.
  91. Python virtual environments and the build process
  92. -------------------------------------------------
  93. An important step in ``configure`` is to create a Python virtual
  94. environment (venv) during the configuration phase. The Python interpreter
  95. comes from the ``--python`` command line option, the ``$PYTHON`` variable
  96. from the environment, or the system PATH, in this order. The venv resides
  97. in the ``pyvenv`` directory in the build tree, and provides consistency
  98. in how the build process runs Python code.
  99. At this stage, ``configure`` also queries the chosen Python interpreter
  100. about QEMU's build dependencies. Note that the build process does *not*
  101. look for ``meson``, ``sphinx-build`` or ``avocado`` binaries in the PATH;
  102. likewise, there are no options such as ``--meson`` or ``--sphinx-build``.
  103. This avoids a potential mismatch, where Meson and Sphinx binaries on the
  104. PATH might operate in a different Python environment than the one chosen
  105. by the user during the build process. On the other hand, it introduces
  106. a potential source of confusion where the user installs a dependency but
  107. ``configure`` is not able to find it. When this happens, the dependency
  108. was installed in the ``site-packages`` directory of another interpreter,
  109. or with the wrong ``pip`` program.
  110. If a package is available for the chosen interpreter, ``configure``
  111. prepares a small script that invokes it from the venv itself\ [#distlib]_.
  112. If not, ``configure`` can also optionally install dependencies in the
  113. virtual environment with ``pip``, either from wheels in ``python/wheels``
  114. or by downloading the package with PyPI. Downloading can be disabled with
  115. ``--disable-download``; and anyway, it only happens when a ``configure``
  116. option (currently, only ``--enable-docs``) is explicitly enabled but
  117. the dependencies are not present\ [#pip]_.
  118. .. [#distlib] The scripts are created based on the package's metadata,
  119. specifically the ``console_script`` entry points. This is the
  120. same mechanism that ``pip`` uses when installing a package.
  121. Currently, in all cases it would be possible to use ``python -m``
  122. instead of an entry point script, which makes this approach a
  123. bit overkill. On the other hand, creating the scripts is
  124. future proof and it makes the contents of the ``pyvenv/bin``
  125. directory more informative. Portability is also not an issue,
  126. because the Python Packaging Authority provides a package
  127. ``distlib.scripts`` to perform this task.
  128. .. [#pip] ``pip`` might also be used when running ``make check-avocado``
  129. if downloading is enabled, to ensure that Avocado is
  130. available.
  131. The required versions of the packages are stored in a configuration file
  132. ``pythondeps.toml``. The format is custom to QEMU, but it is documented
  133. at the top of the file itself and it should be easy to understand. The
  134. requirements should make it possible to use the version that is packaged
  135. that is provided by supported distros.
  136. When dependencies are downloaded, instead, ``configure`` uses a "known
  137. good" version that is also listed in ``pythondeps.toml``. In this
  138. scenario, ``pythondeps.toml`` behaves like the "lock file" used by
  139. ``cargo``, ``poetry`` or other dependency management systems.
  140. Bundled Python packages
  141. -----------------------
  142. Python packages that are **mandatory** dependencies to build QEMU,
  143. but are not available in all supported distros, are bundled with the
  144. QEMU sources. The only one is currently Meson (outdated in Ubuntu
  145. 22.04 and openSUSE Leap).
  146. In order to include a new or updated wheel, modify and rerun the
  147. ``python/scripts/vendor.py`` script. The script embeds the
  148. sha256 hash of package sources and checks it. The pypi.org web site
  149. provides an easy way to retrieve the sha256 hash of the sources.
  150. Stage 2: Meson
  151. ==============
  152. The Meson build system describes the build and install process for:
  153. 1) executables, which include:
  154. - Tools - ``qemu-img``, ``qemu-nbd``, ``qemu-ga`` (guest agent), etc
  155. - System emulators - ``qemu-system-$ARCH``
  156. - Userspace emulators - ``qemu-$ARCH``
  157. - Unit tests
  158. 2) documentation
  159. 3) ROMs, whether provided as binary blobs in the QEMU distributions
  160. or cross compiled under the direction of the configure script
  161. 4) other data files, such as icons or desktop files
  162. All executables are built by default, except for some ``contrib/``
  163. binaries that are known to fail to build on some platforms (for example
  164. 32-bit or big-endian platforms). Tests are also built by default,
  165. though that might change in the future.
  166. The source code is highly modularized, split across many files to
  167. facilitate building of all of these components with as little duplicated
  168. compilation as possible. Using the Meson "sourceset" functionality,
  169. ``meson.build`` files group the source files in rules that are
  170. enabled according to the available system libraries and to various
  171. configuration symbols. Sourcesets belong to one of four groups:
  172. Subsystem sourcesets:
  173. Various subsystems that are common to both tools and emulators have
  174. their own sourceset, for example ``block_ss`` for the block device subsystem,
  175. ``chardev_ss`` for the character device subsystem, etc. These sourcesets
  176. are then turned into static libraries as follows::
  177. libchardev = static_library('chardev', chardev_ss.sources(),
  178. build_by_default: false)
  179. chardev = declare_dependency(objects: libchardev.extract_all_objects(recursive: false),
  180. dependencies: chardev_ss.dependencies())
  181. Target-independent emulator sourcesets:
  182. Various general purpose helper code is compiled only once and
  183. the .o files are linked into all output binaries that need it.
  184. This includes error handling infrastructure, standard data structures,
  185. platform portability wrapper functions, etc.
  186. Target-independent code lives in the ``common_ss``, ``system_ss`` and
  187. ``user_ss`` sourcesets. ``common_ss`` is linked into all emulators,
  188. ``system_ss`` only in system emulators, ``user_ss`` only in user-mode
  189. emulators.
  190. Target-dependent emulator sourcesets:
  191. In the target-dependent set lives CPU emulation, some device emulation and
  192. much glue code. This sometimes also has to be compiled multiple times,
  193. once for each target being built. Target-dependent files are included
  194. in the ``specific_ss`` sourceset.
  195. Each emulator also includes sources for files in the ``hw/`` and ``target/``
  196. subdirectories. The subdirectory used for each emulator comes
  197. from the target's definition of ``TARGET_BASE_ARCH`` or (if missing)
  198. ``TARGET_ARCH``, as found in ``default-configs/targets/*.mak``.
  199. Each subdirectory in ``hw/`` adds one sourceset to the ``hw_arch`` dictionary,
  200. for example::
  201. arm_ss = ss.source_set()
  202. arm_ss.add(files('boot.c'), fdt)
  203. ...
  204. hw_arch += {'arm': arm_ss}
  205. The sourceset is only used for system emulators.
  206. Each subdirectory in ``target/`` instead should add one sourceset to each
  207. of the ``target_arch`` and ``target_system_arch``, which are used respectively
  208. for all emulators and for system emulators only. For example::
  209. arm_ss = ss.source_set()
  210. arm_system_ss = ss.source_set()
  211. ...
  212. target_arch += {'arm': arm_ss}
  213. target_system_arch += {'arm': arm_system_ss}
  214. Module sourcesets:
  215. There are two dictionaries for modules: ``modules`` is used for
  216. target-independent modules and ``target_modules`` is used for
  217. target-dependent modules. When modules are disabled the ``module``
  218. source sets are added to ``system_ss`` and the ``target_modules``
  219. source sets are added to ``specific_ss``.
  220. Both dictionaries are nested. One dictionary is created per
  221. subdirectory, and these per-subdirectory dictionaries are added to
  222. the toplevel dictionaries. For example::
  223. hw_display_modules = {}
  224. qxl_ss = ss.source_set()
  225. ...
  226. hw_display_modules += { 'qxl': qxl_ss }
  227. modules += { 'hw-display': hw_display_modules }
  228. Utility sourcesets:
  229. All binaries link with a static library ``libqemuutil.a``. This library
  230. is built from several sourcesets; most of them however host generated
  231. code, and the only two of general interest are ``util_ss`` and ``stub_ss``.
  232. The separation between these two is purely for documentation purposes.
  233. ``util_ss`` contains generic utility files. Even though this code is only
  234. linked in some binaries, sometimes it requires hooks only in some of
  235. these and depend on other functions that are not fully implemented by
  236. all QEMU binaries. ``stub_ss`` links dummy stubs that will only be linked
  237. into the binary if the real implementation is not present. In a way,
  238. the stubs can be thought of as a portable implementation of the weak
  239. symbols concept.
  240. The following files concur in the definition of which files are linked
  241. into each emulator:
  242. ``default-configs/devices/*.mak``
  243. The files under ``default-configs/devices/`` control the boards and devices
  244. that are built into each QEMU system emulation targets. They merely contain
  245. a list of config variable definitions such as::
  246. include arm-softmmu.mak
  247. CONFIG_XLNX_ZYNQMP_ARM=y
  248. CONFIG_XLNX_VERSAL=y
  249. ``*/Kconfig``
  250. These files are processed together with ``default-configs/devices/*.mak`` and
  251. describe the dependencies between various features, subsystems and
  252. device models. They are described in :ref:`kconfig`
  253. ``default-configs/targets/*.mak``
  254. These files mostly define symbols that appear in the ``*-config-target.h``
  255. file for each emulator\ [#cfgtarget]_. However, the ``TARGET_ARCH``
  256. and ``TARGET_BASE_ARCH`` will also be used to select the ``hw/`` and
  257. ``target/`` subdirectories that are compiled into each target.
  258. .. [#cfgtarget] This header is included by ``qemu/osdep.h`` when
  259. compiling files from the target-specific sourcesets.
  260. These files rarely need changing unless you are adding a completely
  261. new target, or enabling new devices or hardware for a particular
  262. system/userspace emulation target
  263. Adding checks
  264. -------------
  265. Compiler checks can be as simple as the following::
  266. config_host_data.set('HAVE_BTRFS_H', cc.has_header('linux/btrfs.h'))
  267. A more complex task such as adding a new dependency usually
  268. comprises the following tasks:
  269. - Add a Meson build option to meson_options.txt.
  270. - Add code to perform the actual feature check.
  271. - Add code to include the feature status in ``config-host.h``
  272. - Add code to print out the feature status in the configure summary
  273. upon completion.
  274. Taking the probe for SDL2_Image as an example, we have the following
  275. in ``meson_options.txt``::
  276. option('sdl_image', type : 'feature', value : 'auto',
  277. description: 'SDL Image support for icons')
  278. Unless the option was given a non-``auto`` value (on the configure
  279. command line), the detection code must be performed only if the
  280. dependency will be used::
  281. sdl_image = not_found
  282. if not get_option('sdl_image').auto() or have_system
  283. sdl_image = dependency('SDL2_image', required: get_option('sdl_image'),
  284. method: 'pkg-config')
  285. endif
  286. This avoids warnings on static builds of user-mode emulators, for example.
  287. Most of the libraries used by system-mode emulators are not available for
  288. static linking.
  289. The other supporting code is generally simple::
  290. # Create config-host.h (if applicable)
  291. config_host_data.set('CONFIG_SDL_IMAGE', sdl_image.found())
  292. # Summary
  293. summary_info += {'SDL image support': sdl_image.found()}
  294. For the configure script to parse the new option, the
  295. ``scripts/meson-buildoptions.sh`` file must be up-to-date; ``make
  296. update-buildoptions`` (or just ``make``) will take care of updating it.
  297. Support scripts
  298. ---------------
  299. Meson has a special convention for invoking Python scripts: if their
  300. first line is ``#! /usr/bin/env python3`` and the file is *not* executable,
  301. find_program() arranges to invoke the script under the same Python
  302. interpreter that was used to invoke Meson. This is the most common
  303. and preferred way to invoke support scripts from Meson build files,
  304. because it automatically uses the value of configure's --python= option.
  305. In case the script is not written in Python, use a ``#! /usr/bin/env ...``
  306. line and make the script executable.
  307. Scripts written in Python, where it is desirable to make the script
  308. executable (for example for test scripts that developers may want to
  309. invoke from the command line, such as tests/qapi-schema/test-qapi.py),
  310. should be invoked through the ``python`` variable in meson.build. For
  311. example::
  312. test('QAPI schema regression tests', python,
  313. args: files('test-qapi.py'),
  314. env: test_env, suite: ['qapi-schema', 'qapi-frontend'])
  315. This is needed to obey the --python= option passed to the configure
  316. script, which may point to something other than the first python3
  317. binary on the path.
  318. By the time Meson runs, Python dependencies are available in the virtual
  319. environment and should be invoked through the scripts that ``configure``
  320. places under ``pyvenv``. One way to do so is as follows, using Meson's
  321. ``find_program`` function::
  322. sphinx_build = find_program(
  323. fs.parent(python.full_path()) / 'sphinx-build',
  324. required: get_option('docs'))
  325. Stage 3: Make
  326. =============
  327. The next step in building QEMU is to invoke make. GNU Make is required
  328. to build QEMU, and may be installed as ``gmake`` on some hosts.
  329. The output of Meson is a ``build.ninja`` file, which is used with the
  330. Ninja build tool. However, QEMU's build comprises other components than
  331. just the emulators (namely firmware and the tests in ``tests/tcg``) which
  332. need different cross compilers. The QEMU Makefile wraps both Ninja and
  333. the smaller build systems for firmware and tests; it also takes care of
  334. running ``configure`` again when the script changes. Apart from invoking
  335. these sub-Makefiles, the resulting build is largely non-recursive.
  336. Tests, whether defined in ``meson.build`` or not, are also ran by the
  337. Makefile with the traditional ``make check`` phony target, while benchmarks
  338. are run with ``make bench``. Meson test suites such as ``unit`` can be ran
  339. with ``make check-unit``, and ``make check-tcg`` builds and runs "non-Meson"
  340. tests for all targets.
  341. If desired, it is also possible to use ``ninja`` and ``meson test``,
  342. respectively to build emulators and run tests defined in meson.build.
  343. The main difference is that ``make`` needs the ``-jN`` flag in order to
  344. enable parallel builds or tests.
  345. Useful make targets
  346. -------------------
  347. ``help``
  348. Print a help message for the most common build targets.
  349. ``print-VAR``
  350. Print the value of the variable VAR. Useful for debugging the build
  351. system.
  352. Important files for the build system
  353. ====================================
  354. Statically defined files
  355. ------------------------
  356. The following key files are statically defined in the source tree, with
  357. the rules needed to build QEMU. Their behaviour is influenced by a
  358. number of dynamically created files listed later.
  359. ``Makefile``
  360. The main entry point used when invoking make to build all the components
  361. of QEMU. The default 'all' target will naturally result in the build of
  362. every component.
  363. ``*/meson.build``
  364. The meson.build file in the root directory is the main entry point for the
  365. Meson build system, and it coordinates the configuration and build of all
  366. executables. Build rules for various subdirectories are included in
  367. other meson.build files spread throughout the QEMU source tree.
  368. ``python/scripts/mkvenv.py``
  369. A wrapper for the Python ``venv`` and ``distlib.scripts`` packages.
  370. It handles creating the virtual environment, creating scripts in
  371. ``pyvenv/bin``, and calling ``pip`` to install dependencies.
  372. ``tests/Makefile.include``
  373. Rules for external test harnesses. These include the TCG tests
  374. and the Avocado-based integration tests.
  375. ``tests/docker/Makefile.include``
  376. Rules for Docker tests. Like ``tests/Makefile.include``, this file is
  377. included directly by the top level Makefile, anything defined in this
  378. file will influence the entire build system.
  379. ``tests/vm/Makefile.include``
  380. Rules for VM-based tests. Like ``tests/Makefile.include``, this file is
  381. included directly by the top level Makefile, anything defined in this
  382. file will influence the entire build system.
  383. Dynamically created files
  384. -------------------------
  385. The following files are generated at run-time in order to control the
  386. behaviour of the Makefiles. This avoids the need for QEMU makefiles to
  387. go through any pre-processing as seen with autotools, where configure
  388. generates ``Makefile`` from ``Makefile.in``.
  389. Built by configure:
  390. ``config-host.mak``
  391. When configure has determined the characteristics of the build host it
  392. will write the paths to various tools to this file, for use in ``Makefile``
  393. and to a smaller extent ``meson.build``.
  394. ``config-host.mak`` is also used as a dependency checking mechanism. If make
  395. sees that the modification timestamp on configure is newer than that on
  396. ``config-host.mak``, then configure will be re-run.
  397. ``config-meson.cross``
  398. A Meson "cross file" (or native file) used to communicate the paths to
  399. the toolchain and other configuration options.
  400. ``config.status``
  401. A small shell script that will invoke configure again with the same
  402. environment variables that were set during the first run. It's used to
  403. rerun configure after changes to the source code, but it can also be
  404. inspected manually to check the contents of the environment.
  405. ``Makefile.prereqs``
  406. A set of Makefile dependencies that order the build and execution of
  407. firmware and tests after the container images and emulators that they
  408. need.
  409. ``pc-bios/*/config.mak``, ``tests/tcg/config-host.mak``, ``tests/tcg/*/config-target.mak``
  410. Configuration variables used to build the firmware and TCG tests,
  411. including paths to cross compilation toolchains.
  412. ``pyvenv``
  413. A Python virtual environment that is used for all Python code running
  414. during the build. Using a virtual environment ensures that even code
  415. that is run via ``sphinx-build``, ``meson`` etc. uses the same interpreter
  416. and packages.
  417. Built by Meson:
  418. ``config-host.h``
  419. Used by C code to determine the properties of the build environment
  420. and the set of enabled features for the entire build.
  421. ``${TARGET-NAME}-config-devices.mak``
  422. TARGET-NAME is the name of a system emulator. The file is
  423. generated by Meson using files under ``configs/devices`` as input.
  424. ``${TARGET-NAME}-config-target.mak``
  425. TARGET-NAME is the name of a system or usermode emulator. The file is
  426. generated by Meson using files under ``configs/targets`` as input.
  427. ``$TARGET_NAME-config-target.h``, ``$TARGET_NAME-config-devices.h``
  428. Used by C code to determine the properties and enabled
  429. features for each target. enabled. They are generated from
  430. the contents of the corresponding ``*.mak`` files using Meson's
  431. ``configure_file()`` function; each target can include them using
  432. the ``CONFIG_TARGET`` and ``CONFIG_DEVICES`` macro respectively.
  433. ``build.ninja``
  434. The build rules.
  435. Built by Makefile:
  436. ``Makefile.ninja``
  437. A Makefile include that bridges to ninja for the actual build. The
  438. Makefile is mostly a list of targets that Meson included in build.ninja.
  439. ``Makefile.mtest``
  440. The Makefile definitions that let "make check" run tests defined in
  441. meson.build. The rules are produced from Meson's JSON description of
  442. tests (obtained with "meson introspect --tests") through the script
  443. scripts/mtest2make.py.