1#-------------------------------------------------------------------------------
2# Copyright (c) 2023, Arm Limited. All rights reserved.
3#
4# SPDX-License-Identifier: BSD-3-Clause
5#
6#-------------------------------------------------------------------------------
7cmake_minimum_required(VERSION 3.15)
8
9SET(CMAKE_SYSTEM_NAME Generic)
10
11set(CMAKE_C_COMPILER_FORCED TRUE)
12set(CMAKE_CXX_COMPILER_FORCED TRUE)
13
14if(NOT DEFINED CROSS_COMPILE)
15    set(CROSS_COMPILE    arm-none-eabi CACHE STRING "Cross-compiler prefix")
16endif()
17
18set(CMAKE_C_COMPILER armclang)
19set(CMAKE_CXX_COMPILER armclang)
20set(CMAKE_ASM_COMPILER armasm)
21
22# This variable name is a bit of a misnomer. The file it is set to is included
23# at a particular step in the compiler initialisation. It is used here to
24# configure the extensions for object files. Despite the name, it also works
25# with the Ninja generator.
26set(CMAKE_USER_MAKE_RULES_OVERRIDE ${CMAKE_CURRENT_LIST_DIR}/set_extensions.cmake)
27
28if(NOT DEFINED CMAKE_OBJCOPY)
29    set(CMAKE_OBJCOPY ${CROSS_COMPILE}-objcopy CACHE FILEPATH "Path to objcopy")
30endif()
31
32# Set compiler ID explicitly as it's not detected at this moment
33set(CMAKE_C_COMPILER_ID ARMClang)
34
35macro(tfm_toolchain_reset_compiler_flags)
36    set_property(DIRECTORY PROPERTY COMPILE_OPTIONS "")
37
38    add_compile_options(
39        $<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-Wno-ignored-optimization-argument>
40        $<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-Wno-unused-command-line-argument>
41        $<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-Wall>
42        # Don't error when the MBEDTLS_NULL_ENTROPY warning is shown
43        $<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-Wno-error=cpp>
44        $<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-c>
45        $<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-fdata-sections>
46        $<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-ffunction-sections>
47        $<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-fno-builtin>
48        $<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-fshort-enums>
49        $<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-fshort-wchar>
50        $<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-funsigned-char>
51        $<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-masm=auto>
52        $<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-nostdlib>
53        $<$<COMPILE_LANGUAGE:C>:-std=c99>
54        $<$<COMPILE_LANGUAGE:CXX>:-std=c++11>
55        $<$<COMPILE_LANGUAGE:ASM>:--cpu=${CMAKE_ASM_CPU_FLAG}>
56        $<$<AND:$<COMPILE_LANGUAGE:C>,$<BOOL:${TFM_DEBUG_SYMBOLS}>>:-g>
57        $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<BOOL:${TFM_DEBUG_SYMBOLS}>>:-g>
58    )
59endmacro()
60
61set(MEMORY_USAGE_FLAG --info=summarysizes,sizes,totals,unused,veneers)
62
63macro(tfm_toolchain_reset_linker_flags)
64    set_property(DIRECTORY PROPERTY LINK_OPTIONS "")
65
66    add_link_options(
67        ${MEMORY_USAGE_FLAG}
68        --strict
69        --symbols
70        --xref
71        $<$<AND:$<VERSION_GREATER:${TFM_ISOLATION_LEVEL},1>,$<STREQUAL:"${TEST_PSA_API}","IPC">>:--no-merge>
72        # Suppress link warnings that are consistant (and therefore hopefully
73        # harmless)
74        # https://developer.arm.com/documentation/100074/0608/linker-errors-and-warnings/list-of-the-armlink-error-and-warning-messages
75        # Empty region description
76        --diag_suppress=6312
77        # Ns section matches pattern
78        --diag_suppress=6314
79        # Duplicate input files
80        --diag_suppress=6304
81        # Pattern only matches removed unused sections.
82        --diag_suppress=6329
83    )
84endmacro()
85
86macro(tfm_toolchain_set_processor_arch)
87    if (DEFINED TFM_SYSTEM_PROCESSOR)
88        set(CMAKE_SYSTEM_PROCESSOR       ${TFM_SYSTEM_PROCESSOR})
89
90        if (TFM_SYSTEM_ARCHITECTURE STREQUAL "armv8.1-m.main")
91            message(WARNING "MVE is not yet supported using ARMCLANG")
92            string(APPEND CMAKE_SYSTEM_PROCESSOR "+nomve")
93        endif()
94
95        if (DEFINED TFM_SYSTEM_DSP)
96            if(NOT TFM_SYSTEM_DSP)
97                string(APPEND CMAKE_SYSTEM_PROCESSOR "+nodsp")
98            endif()
99        endif()
100
101        # ARMCLANG specifies that '+nofp' is available on following M-profile cpus:
102        # 'cortex-m4', 'cortex-m7', 'cortex-m33', 'cortex-m35p', 'cortex-m55' and 'cortex-m85'.
103        # Build fails if other M-profile cpu, such as 'cortex-m23', is added with '+nofp'.
104        # Explicitly list those cpu to align with ARMCLANG description.
105        if (NOT CONFIG_TFM_FLOAT_ABI STREQUAL "hard" AND
106            (TFM_SYSTEM_PROCESSOR STREQUAL "cortex-m4"
107            OR TFM_SYSTEM_PROCESSOR STREQUAL "cortex-m7"
108            OR TFM_SYSTEM_PROCESSOR STREQUAL "cortex-m33"
109            OR TFM_SYSTEM_PROCESSOR STREQUAL "cortex-m35p"
110            OR TFM_SYSTEM_PROCESSOR STREQUAL "cortex-m55"
111            OR TFM_SYSTEM_PROCESSOR STREQUAL "cortex-m85"))
112                string(APPEND CMAKE_SYSTEM_PROCESSOR "+nofp")
113        endif()
114
115        string(REGEX REPLACE "\\+nodsp" ".no_dsp" CMAKE_ASM_CPU_FLAG "${CMAKE_SYSTEM_PROCESSOR}")
116        string(REGEX REPLACE "\\+nomve" ".no_mve" CMAKE_ASM_CPU_FLAG "${CMAKE_ASM_CPU_FLAG}")
117        string(REGEX REPLACE "\\+nofp" ".no_fp" CMAKE_ASM_CPU_FLAG "${CMAKE_ASM_CPU_FLAG}")
118    else()
119        set(CMAKE_ASM_CPU_FLAG  ${TFM_SYSTEM_ARCHITECTURE})
120
121        # Armasm uses different syntax than armclang for architecture targets
122        string(REGEX REPLACE "\\armv" "" CMAKE_ASM_CPU_FLAG "${CMAKE_ASM_CPU_FLAG}")
123        string(REGEX REPLACE "\\armv" "" CMAKE_ASM_CPU_FLAG "${CMAKE_ASM_CPU_FLAG}")
124
125        # Modifiers are additive instead of subtractive (.fp Vs .no_fp)
126        if (TFM_SYSTEM_DSP)
127            string(APPEND CMAKE_ASM_CPU_FLAG ".dsp")
128        endif()
129
130        if (CONFIG_TFM_FLOAT_ABI STREQUAL "hard")
131            string(APPEND CMAKE_ASM_CPU_FLAG ".fp")
132        endif()
133    endif()
134
135    # CMAKE_SYSTEM_ARCH is an ARMCLANG CMAKE internal variable, used to set
136    # compile and linker flags up until CMake 3.21 where CMP0123 was introduced:
137    # https://cmake.org/cmake/help/latest/policy/CMP0123.html
138    # This behavior is overwritten by setting CMAKE_C_FLAGS in
139    # tfm_toolchain_reload_compiler.
140    # Another use of this variable is to statisfy a requirement for ARMCLANG to
141    # set either the target CPU or the Architecture. This variable needs to be
142    # set to allow targeting architectures without a specific CPU.
143    set(CMAKE_SYSTEM_ARCH            ${TFM_SYSTEM_ARCHITECTURE})
144
145    set(CMAKE_C_COMPILER_TARGET      arm-${CROSS_COMPILE})
146    set(CMAKE_CXX_COMPILER_TARGET    arm-${CROSS_COMPILE})
147    set(CMAKE_ASM_COMPILER_TARGET    arm-${CROSS_COMPILE})
148
149    # MVE is currently not supported in case of armclang
150    if (TFM_SYSTEM_ARCHITECTURE STREQUAL "armv8.1-m.main")
151        string(APPEND CMAKE_SYSTEM_ARCH "+nomve")
152    endif()
153
154    if (DEFINED TFM_SYSTEM_DSP)
155        if(NOT TFM_SYSTEM_DSP)
156            string(APPEND CMAKE_SYSTEM_ARCH "+nodsp")
157        endif()
158    endif()
159
160    # Cmake's ARMClang support has several issues with compiler validation. To
161    # avoid these, we set the list of supported -mcpu and -march variables to
162    # the ones we intend to use so that the validation will never fail.
163    include(Compiler/ARMClang)
164    set(CMAKE_C_COMPILER_PROCESSOR_LIST ${CMAKE_SYSTEM_PROCESSOR})
165    set(CMAKE_C_COMPILER_ARCH_LIST ${CMAKE_SYSTEM_ARCH})
166    set(CMAKE_CXX_COMPILER_PROCESSOR_LIST ${CMAKE_SYSTEM_PROCESSOR})
167    set(CMAKE_CXX_COMPILER_ARCH_LIST ${CMAKE_SYSTEM_ARCH})
168    set(CMAKE_ASM_COMPILER_PROCESSOR_LIST ${CMAKE_SYSTEM_PROCESSOR})
169    set(CMAKE_ASM_COMPILER_ARCH_LIST ${CMAKE_SYSTEM_ARCH})
170endmacro()
171
172macro(tfm_toolchain_reload_compiler)
173    tfm_toolchain_set_processor_arch()
174    tfm_toolchain_reset_compiler_flags()
175    tfm_toolchain_reset_linker_flags()
176
177    unset(CMAKE_C_FLAGS_INIT)
178    unset(CMAKE_CXX_FLAGS_INIT)
179    unset(CMAKE_C_LINK_FLAGS)
180    unset(CMAKE_ASM_FLAGS_INIT)
181    unset(CMAKE_ASM_LINK_FLAGS)
182    unset(__mcpu_flag_set)
183    unset(__march_flag_set)
184
185    include(Compiler/ARMClang)
186    __compiler_armclang(C)
187    include(Compiler/ARMCC-ASM)
188    __compiler_armcc(ASM)
189
190    if (CMAKE_C_COMPILER_VERSION VERSION_LESS 6.13)
191        message(FATAL_ERROR "Please select newer Arm compiler version starting from 6.13.")
192    endif()
193
194    if (CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL 6.15 AND
195        CMAKE_C_COMPILER_VERSION VERSION_LESS 6.18)
196        message(FATAL_ERROR "Armclang 6.15~6.17 may cause MemManage fault."
197                            " This defect has been fixed since Armclang 6.18."
198                            " See [SDCOMP-59788] in Armclang 6.18 release note for details."
199                            " Please use other Armclang versions instead.")
200    endif()
201
202    set(CMAKE_ASM_FLAGS ${CMAKE_ASM_FLAGS_INIT})
203
204    if (DEFINED TFM_SYSTEM_PROCESSOR)
205        set(CMAKE_C_FLAGS "-mcpu=${CMAKE_SYSTEM_PROCESSOR}")
206        set(CMAKE_C_LINK_FLAGS   "--cpu=${CMAKE_SYSTEM_PROCESSOR}")
207        set(CMAKE_CXX_LINK_FLAGS "--cpu=${CMAKE_SYSTEM_PROCESSOR}")
208        set(CMAKE_ASM_LINK_FLAGS "--cpu=${CMAKE_SYSTEM_PROCESSOR}")
209        # But armlink doesn't support this +dsp syntax
210        string(REGEX REPLACE "\\+nodsp" "" CMAKE_C_LINK_FLAGS   "${CMAKE_C_LINK_FLAGS}")
211        string(REGEX REPLACE "\\+nodsp" "" CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS}")
212        string(REGEX REPLACE "\\+nodsp" "" CMAKE_ASM_LINK_FLAGS "${CMAKE_ASM_LINK_FLAGS}")
213        # And uses different syntax for +nofp
214        string(REGEX REPLACE "\\+nofp" ".no_fp" CMAKE_C_LINK_FLAGS   "${CMAKE_C_LINK_FLAGS}")
215        string(REGEX REPLACE "\\+nofp" ".no_fp" CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS}")
216        string(REGEX REPLACE "\\+nofp" ".no_fp" CMAKE_ASM_LINK_FLAGS "${CMAKE_ASM_LINK_FLAGS}")
217
218        string(REGEX REPLACE "\\+nomve" ".no_mve" CMAKE_C_LINK_FLAGS   "${CMAKE_C_LINK_FLAGS}")
219        string(REGEX REPLACE "\\+nomve" ".no_mve" CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS}")
220        string(REGEX REPLACE "\\+nomve" ".no_mve" CMAKE_ASM_LINK_FLAGS "${CMAKE_ASM_LINK_FLAGS}")
221    else()
222        set(CMAKE_C_FLAGS "-march=${CMAKE_SYSTEM_ARCH}")
223        set(CMAKE_CXX_FLAGS "-march=${CMAKE_SYSTEM_ARCH}")
224    endif()
225
226    # This flag is used to check if toolchain has fixed VLLDM vulnerability
227    # Check command will fail if C flags consist of keyword other than cpu/arch type.
228    set(CP_CHECK_C_FLAGS ${CMAKE_C_FLAGS})
229
230    if (CONFIG_TFM_FLOAT_ABI STREQUAL "hard")
231        set(COMPILER_CP_C_FLAG "-mfloat-abi=hard")
232        if (CONFIG_TFM_ENABLE_FP)
233            set(COMPILER_CP_C_FLAG "-mfloat-abi=hard -mfpu=${CONFIG_TFM_FP_ARCH}")
234            set(COMPILER_CP_ASM_FLAG "--fpu=${CONFIG_TFM_FP_ARCH_ASM}")
235            # armasm and armlink have the same option "--fpu" and are both used to
236            # specify the target FPU architecture. So the supported FPU architecture
237            # names can be shared by armasm and armlink.
238            set(LINKER_CP_OPTION "--fpu=${CONFIG_TFM_FP_ARCH_ASM}")
239        endif()
240    else()
241        set(COMPILER_CP_C_FLAG   "-mfpu=softvfp")
242        set(COMPILER_CP_ASM_FLAG "--fpu=softvfp")
243        set(LINKER_CP_OPTION     "--fpu=SoftVFP")
244    endif()
245
246    string(APPEND CMAKE_C_FLAGS " " ${COMPILER_CP_C_FLAG})
247    string(APPEND CMAKE_ASM_FLAGS " " ${COMPILER_CP_ASM_FLAG})
248    string(APPEND CMAKE_C_LINK_FLAGS " " ${LINKER_CP_OPTION})
249    string(APPEND CMAKE_ASM_LINK_FLAGS " " ${LINKER_CP_OPTION})
250
251    # Workaround for issues with --depend-single-line with armasm and Ninja
252    if (CMAKE_GENERATOR STREQUAL "Ninja")
253        set( CMAKE_DEPFILE_FLAGS_ASM "--depend=<OBJECT>.d")
254    endif()
255
256    set(CMAKE_C_FLAGS_MINSIZEREL "-Oz -DNDEBUG")
257endmacro()
258
259# Configure environment for the compiler setup run by cmake at the first
260# `project` call in <tfm_root>/CMakeLists.txt. After this mandatory setup is
261# done, all further compiler setup is done via tfm_toolchain_reload_compiler()
262tfm_toolchain_set_processor_arch()
263tfm_toolchain_reset_compiler_flags()
264tfm_toolchain_reset_linker_flags()
265
266macro(add_convert_to_bin_target target)
267    get_target_property(bin_dir ${target} RUNTIME_OUTPUT_DIRECTORY)
268
269    add_custom_target(${target}_bin
270        SOURCES ${bin_dir}/${target}.bin
271    )
272    add_custom_command(OUTPUT ${bin_dir}/${target}.bin
273        DEPENDS ${target}
274        COMMAND fromelf
275            --bincombined $<TARGET_FILE:${target}>
276            --output=${bin_dir}/${target}.bin
277    )
278
279    add_custom_target(${target}_elf
280        SOURCES ${bin_dir}/${target}.elf
281    )
282    add_custom_command(OUTPUT ${bin_dir}/${target}.elf
283        DEPENDS ${target}
284        COMMAND fromelf
285            --elf $<TARGET_FILE:${target}>
286            --output=${bin_dir}/${target}.elf
287    )
288
289    add_custom_target(${target}_hex
290        SOURCES ${bin_dir}/${target}.hex
291    )
292    add_custom_command(OUTPUT ${bin_dir}/${target}.hex
293        DEPENDS ${target}
294        COMMAND fromelf
295            --i32combined $<TARGET_FILE:${target}>
296            --output=${bin_dir}/${target}.hex
297    )
298
299    add_custom_target(${target}_binaries
300        ALL
301        DEPENDS ${target}_bin
302        DEPENDS ${target}_elf
303        DEPENDS ${target}_hex
304    )
305endmacro()
306
307# Specify the scatter file used to link `target`.
308# Behaviour for handling scatter files is so wildly divergent between compilers
309# that this macro is required.
310#
311# Vendor platform can set a scatter file as property INTERFACE_LINK_DEPENDS of platform_ns.
312# `target` can fetch the scatter file from platform_ns.
313#
314# Alternatively, NS build can call target_add_scatter_file() with the install directory of
315# scatter files.
316#     target_add_scatter_file(target, install_dir)
317#
318# target_add_scatter_file() fetch a scatter file from the install directory.
319macro(target_add_scatter_file target)
320
321    # Try if scatter_file is passed from platform_ns
322    get_target_property(scatter_file
323                        platform_ns
324                        INTERFACE_LINK_DEPENDS
325    )
326
327    # If scatter_file is not passed from platform_ns
328    # Try if any scatter file is exported in install directory
329    # The intall directory is passed as an optinal argument
330    if(${scatter_file} STREQUAL "scatter_file-NOTFOUND")
331        set(install_dir ${ARGN})
332        list(LENGTH install_dir nr_install_dir)
333
334        # If nr_install_dir == 1, search for sct file under install dir
335        if(${nr_install_dir} EQUAL 1)
336            file(GLOB scatter_file "${install_dir}/*.sct")
337        endif()
338    endif()
339
340    if(NOT EXISTS ${scatter_file})
341        message(FATAL_ERROR "Unable to find NS scatter file ${scatter_file}")
342    endif()
343
344    add_library(${target}_scatter OBJECT)
345    target_sources(${target}_scatter
346        PRIVATE
347            ${scatter_file}
348    )
349
350    # Cmake cannot use generator expressions in the
351    # set_source_file_properties command, so instead we just parse the regex
352    # for the filename and set the property on all files, regardless of if
353    # the generator expression would evaluate to true or not.
354    string(REGEX REPLACE ".*>:(.*)>$" "\\1" SCATTER_FILE_PATH "${scatter_file}")
355    set_source_files_properties(${SCATTER_FILE_PATH}
356        PROPERTIES
357        LANGUAGE C
358    )
359
360    target_link_options(${target}
361        PRIVATE
362            --scatter=$<TARGET_OBJECTS:${target}_scatter>
363    )
364
365    target_link_libraries(${target}_scatter
366        PRIVATE
367            platform_region_defs
368    )
369
370    target_compile_options(${target}_scatter
371        PRIVATE
372            -E
373            -xc
374    )
375
376    add_dependencies(${target} ${target}_scatter)
377    set_target_properties(${target} PROPERTIES LINK_DEPENDS $<TARGET_OBJECTS:${target}_scatter>)
378
379endmacro()
380