1##################
2Build instructions
3##################
4
5.. warning::
6    The build process was changed a lot in Q3 2023 and included into the release v2.0.
7    For building instructions for early versions please refer to the documentation of respective
8    versions.
9
10As you know from the :doc:`introduction </introduction/readme>` TF-M implements
11:term:`SPE` with a set of secure services.
12TF-M application as :term:`NSPE` client uses those services through isolation boundary via
13:term:`PSA-FF-M` API.
14Both SPE and NSPE are separate binaries and built independently.
15SPE and NSPE binaries are combined and signed making the final image for downloading onto targets
16when building NSPE.
17
18.. Note::
19    This document describes the process of building a single SPE alone.
20    Refer to :doc:`Building Tests </building/tests_build_instruction>` on how to build TF-M
21    regression tests and PSA Arch tests to verify TF-M.
22
23TF-M uses `CMake <https://cmake.org/overview/>`__ **v3.21** or higher.
24Before starting please make sure you have all required software installed and
25configured as explained in the
26:doc:`TF-M getting started </getting_started/tfm_getting_started>`.
27
28.. contents:: Contents
29    :depth: 2
30    :local:
31
32The additional building materials you can find in the following links:TF-M source folder
33
34.. toctree::
35    :maxdepth: 1
36
37    Build Tests <tests_build_instruction>
38    Run TF-M tests and applications <run_tfm_examples_on_arm_platforms>
39    Building the documentation <documentation_generation>
40    IAR toolchain <tfm_build_instruction_iar>
41
42.. _Building SPE:
43
44*******************
45Building TF-M (SPE)
46*******************
47This build generates the SPE binary and artifacts, necessary for :ref:`Building NSPE`.
48
49.. _Getting the source-code:
50
51Getting the source code
52=======================
53.. code-block:: bash
54
55    cd <base folder>
56    git clone https://git.trustedfirmware.org/TF-M/trusted-firmware-m.git
57
58In this documentation, the cloned ``trusted-firmware-m`` repository will be referenced as
59``<TF-M source dir>``.
60Additionally, TF-M depends on several external projects, handled by CMake automatically but
61you can alter that behaviour using :ref:`Dependency management`.
62
63.. Note::
64
65 - For building with Armclang compiler, please follow the note
66   in :doc:`TF-M getting started </getting_started/tfm_getting_started>`.
67 - For building with the IAR toolchain, please see the notes in
68   :doc:`IAR software requirements <tfm_build_instruction_iar>`
69 - Please use "/" instead of "\\" for paths when running CMAKE commands under
70   Windows Command Prompt.
71
72Configuring
73===========
74TF-M has many config options for configuring and fine-tuning. Please check the
75:ref:`tf-m_configuration` section for the details. The **base** (default) configuration
76contains only essential components such as SPM and HW platform support hence the
77only mandatory argument to TF-M build is a platform name, provided via
78CMake command-line option ``-DTFM_PLATFORM=<platform name>``, it can be:
79
80- A relative path under ``<TF-M source dir>/platform/ext/target``, for example ``arm/mps2/an521``.
81- An absolute path of target platform, mainly used for out-of-tree platform build.
82- A basename of the target platform folder, for example ``an521``.
83
84Essential Directories
85---------------------
86There are 3 essential directories used by CMake for building TF-M:
87
88- Source code directory ``<TF-M source dir>``
89- Build directory ``<Build Dir>`` - the location of all intermediate files required to produce
90  a build target.
91- Install directory ``<Artifact Dir>`` - the location of the build output files.
92
93Note::
94    It's recommended to use absolute paths for all directories. Relative paths may not fully work.
95
96.. _Toolchains:
97
98Toolchains
99----------
100TF-M supports 4 toolchains for cross-compiling and building the project binaries:
101
102- GNU - **default**
103- ArmClang
104- IAR
105- LLVM Embedded Toolchain for Arm
106
107Each toolchain has a configuration file for the compiler and linker.
108They are located at the root directory of TF-M.
109Use ``TFM_TOOLCHAIN_FILE`` option to provide the absolute path to the preferred toolchain file,
110or relative path to working directory.
111The default **toolchain_GNUARM.cmake** is selected by `config_base.cmake`
112file if the option is omitted.
113
114.. _Build type:
115
116Build type
117----------
118By default, a MinSizeRel configuration is built. Alternate build types can be
119specified with the ``CMAKE_BUILD_TYPE`` variable. The possible
120types are:
121
122- Debug
123- RelWithDebInfo
124- Release
125- MinSizeRel - **default**
126
127Debug symbols are added by default to all builds, but can be removed from
128*Release* and *MinSizeRel* builds by setting ``TFM_DEBUG_SYMBOLS`` to `OFF`.
129
130*RelWithDebInfo*, *Release* and *MinSizeRel* all have different
131optimizations turned on and hence will produce smaller, faster code than
132*Debug*. *MinSizeRel* will produce the smallest code and hence is often
133a good idea on RAM or flash-constrained systems.
134
135.. _Output files:
136
137Output files
138------------
139In a successful build, a set of files will be created in the ``<Artifact Dir>``.
140By default, it is ``<Build Dir>\api_ns`` subfolder but you can redirect the
141output to any location using ``CMAKE_INSTALL_PREFIX`` option. It can be an
142absolute path or relative to your current directory. For the contents of the
143artifact directory please refer to :ref:`Artifacts structure`.
144
145Other build parameters
146----------------------
147The full list of default options is in ``config/config_base.cmake`` and
148explained in :ref:`tfm_cmake_configuration`. Several important options
149are listed below.
150
151+----------------------------+------------------------------------------+---------------+
152| Parameter                  | Description                              | Default value |
153+============================+==========================================+===============+
154| BL2                        | Build level 2 secure bootloader.         | ON            |
155+----------------------------+------------------------------------------+---------------+
156| PROJECT_CONFIG_HEADER_FILE | User defined header file for TF-M config |               |
157+----------------------------+------------------------------------------+---------------+
158| TFM_ISOLATION_LEVEL        | Set TF-M isolation level.                | 1             |
159+----------------------------+------------------------------------------+---------------+
160| TFM_PROFILE                | See :ref:`tf-m_profiles`.                |               |
161+----------------------------+------------------------------------------+---------------+
162
163Project Config Header File
164--------------------------
165CMake variable ``PROJECT_CONFIG_HEADER_FILE`` can be set by a user the full path to a
166configuration header file, which is used to fine-tune component options. The detailed reference
167for the project config header file is in :ref:`Header_configuration`.
168
169Building binaries
170=================
171
172The command below shows a general template for building TF-M as a typical CMake project:
173
174.. code-block:: bash
175
176    cmake -S <TF-M source dir> -B <Build Dir> -DTFM_PLATFORM=<platform>
177    cmake --build <Build Dir> -- install
178
179.. Note::
180    It is recommended to clean up the build directory before re-build if the config
181    header file is updated. CMake is unable to automatically recognize the
182    dependency when the header file is defined as a macro.
183
184Building default configuration for an521
185----------------------------------------
186
187.. code-block:: bash
188
189    cd <TF-M source dir>
190    cmake -S . -B build -DTFM_PLATFORM=arm/mps2/an521
191    cmake --build build -- install
192
193The command above is intended to do:
194  - take TF-M sources in the current ``.`` folder
195  - build SPE in the ``build`` folder
196  - for **an521** platform
197  - using GNU toolchain *by default*. Use ``-DTFM_TOOLCHAIN_FILE=<toolchain file>``
198    for alternatives as described in :ref:`Toolchains`
199  - install output files in ``build/api_ns`` folder *by default*. You can specify
200    a different directory using ``-DCMAKE_INSTALL_PREFIX=<Artifact dir>``
201    as described in :ref:`Output files`
202
203.. Note::
204    It is recommended to build each different build configuration in a separate
205    build directory.
206
207CMake can generate code for many native build systems. TF-M is tested with
208``Unix Makefiles`` (default) and ``Ninja``. The ``-G`` option can specify
209alternative generators. For example for building with Ninja in the Debug
210:ref:`Build type` using ArmClang :ref:`Toolchains` you can use the following:
211
212.. code-block:: bash
213
214    cd <TF-M source dir>
215    cmake -S . -B build -DTFM_PLATFORM=arm/mps2/an521 -GNinja -DTFM_TOOLCHAIN_FILE=toolchain_ARMCLANG.cmake -DCMAKE_BUILD_TYPE=Debug
216    cmake --build build -- install
217
218.. _Dependency management:
219
220Dependency management
221=====================
222
223The TF-M build system will fetch all dependencies by default with appropriate
224versions and store them inside the build tree. In this case, the build tree
225location is ``<build_dir>/lib/ext``.
226
227If you have local copies already and wish to avoid having the libraries
228downloaded every time the build directory is deleted, then the following
229variables can be set to the paths to the root directories of the local repos.
230This will disable the automatic downloading for that dependencies and speed up
231development iterations or allow usage of a dependency version different from the
232current one.
233Additionally, these path variables can be set in ``localrepos.cmake``
234file which will be included in a build if it exists.
235This file is ignored in TF-M git settings.
236
237The following table lists the commonly used repos. For others, you can refer to ``lib/ext``.
238
239+----------------+---------------------+-----------------------------------------------------+
240| Dependency     | Cmake variable      | Git repo URL                                        |
241+================+=====================+=====================================================+
242| Mbed Crypto    | MBEDCRYPTO_PATH     | https://github.com/Mbed-TLS/mbedtls                 |
243+----------------+---------------------+-----------------------------------------------------+
244| MCUboot        | MCUBOOT_PATH        | https://github.com/mcu-tools/mcuboot                |
245+----------------+---------------------+-----------------------------------------------------+
246| QCBOR          | QCBOR_PATH          | https://github.com/laurencelundblade/QCBOR.git      |
247+----------------+---------------------+-----------------------------------------------------+
248
249The recommended versions of the dependencies are listed in ``config/config_base.cmake``.
250
251.. Note::
252
253 - Some repositories might need patches to allow building it as a part of TF-M.
254   While these patches are being upstreamed they are stored in a
255   dependency folder under ``lib/ext/``.
256   In order to use local repositories those patches shall be applied to original source.
257   An alternative is to copy out the auto-downloaded repos under the ``<build_dir>/lib/ext``.
258   They have been applied with patches and can be used directly.
259
260Example: building TF-M with local Mbed Crypto repo
261--------------------------------------------------
262
263Preparing a local repository consists of 2 steps: cloning and patching.
264This is only required to be done once. For dependencies without ``.patch``
265files in their ``lib/ext`` directory the only required step is
266cloning the repo and checking out the correct branch.
267
268.. code-block:: bash
269
270    cd <Mbed Crypto base folder>
271    git clone https://github.com/ARMmbed/mbedtls
272    cd mbedtls
273    git checkout <MBEDCRYPTO_VERSION> from <TF-M source dir>/config/config_base.cmake>
274    git apply <TF-M source dir>/lib/ext/mbedcrypto/*.patch
275
276.. Note::
277
278   ``<Mbed Crypto base folder>`` does not need to have any fixed position related
279   to the TF-M repo so alternative method to get prepared dependency repos is to
280   let TF-M download it once and then copy them out of the ``build/lib/ext`` folder.
281
282Now build TF-M binaries
283
284.. code-block:: bash
285
286    cd <TF-M source dir>
287    cmake -S . -B build -DTFM_PLATFORM=arm/mps2/an521 -DMBEDCRYPTO_PATH=<Mbed Crypto base folder>/mbedtls
288    cmake --build build -- install
289
290.. _Building NSPE:
291
292***************************
293Building Application (NSPE)
294***************************
295
296As a result of :ref:`Building SPE` you will get a set of :ref:`Output files` in
297``<Artifact Dir>`` required for building TF-M application. Essentially, SPE
298exports a binary and a set of C source files for PSA interface and platform.
299Please note that NSPE and SPE are independent projects and can be built using
300different toolchains and toolchain options.
301
302.. _Artifacts structure:
303
304SPE artifacts structure
305=======================
306
307SPE components prepared and installed for NSPE usage in ``<Artifact Dir>``
308will have the following structure:
309
310.. code-block:: none
311
312    <Artifact Dir>
313    ├── bin
314    ├── cmake
315    ├── config
316    ├── image_signing
317    ├── interface
318    ├── platform
319    └── CMakeLists.txt
320
321With certain configurations, additional folders may also be installed.
322These folders have the following content:
323
324- **bin** - binary images of SPE, Bootloader(optional) and combined.
325- **cmake** - CMake scripts like SPE configuration and :ref:`NSPE toolchains`.
326- **config** - Configuration files
327- **image_signing** - binary image signing tool and keys.
328- **interface** - PSA interface exposed by SPE.
329- **platform** - source code for a selected hardware platform.
330- **CMakeLists.txt** - CMake script for the artifacts integration in NSPE.
331
332The content of ``<Artifact Dir>`` is an exported directory for integration with CMake projects.
333
334.. Note::
335    Attempting to change any file in <Artifact Dir> may cause incompatibility issues.
336    Instead, please change the corresponding file in the <TF-M source dir>.
337
338.. _NSPE toolchains:
339
340NSPE toolchains
341===============
342
343SPE prepares and exports CMake toolchain files for building NSPE in all
344supported :ref:`Toolchains` in ``<Artifact Dir>/cmake`` folder.
345Toolchain used to build NSPE can be different from what is used to build SPE.
346
347Basic SPE integration
348=====================
349Refer to the
350`example <https://git.trustedfirmware.org/TF-M/tf-m-extras.git/+/refs/heads/main/examples/tf-m-example-ns-app/>`__
351of TF-M applications in **tf-m-extras** repository.
352
353--------------
354
355*Copyright (c) 2017-2024, Arm Limited. All rights reserved.*
356*Copyright (c) 2022, Cypress Semiconductor Corporation. All rights reserved.*
357