1# Copyright (c) 2021-2023 Nordic Semiconductor
2#
3# SPDX-License-Identifier: Apache-2.0
4
5# Usage:
6#   load_cache(IMAGE <image> BINARY_DIR <dir>)
7#
8# This function will load the CMakeCache.txt file from the binary directory
9# given by the BINARY_DIR argument.
10#
11# All CMake cache variables are stored in a custom target which is identified by
12# the name given as value to the IMAGE argument.
13#
14# IMAGE:      image name identifying the cache for later sysbuild_get() lookup calls.
15# BINARY_DIR: binary directory (build dir) containing the CMakeCache.txt file to load.
16function(load_cache)
17  set(single_args IMAGE BINARY_DIR)
18  cmake_parse_arguments(LOAD_CACHE "" "${single_args}" "" ${ARGN})
19
20  if(NOT TARGET ${LOAD_CACHE_IMAGE}_cache)
21    add_custom_target(${LOAD_CACHE_IMAGE}_cache)
22  endif()
23  file(STRINGS "${LOAD_CACHE_BINARY_DIR}/CMakeCache.txt" cache_strings ENCODING UTF-8)
24  foreach(str ${cache_strings})
25    # Using a regex for matching whole 'VAR_NAME:TYPE=VALUE' will strip semi-colons
26    # thus resulting in lists to become strings.
27    # Therefore we first fetch VAR_NAME and TYPE, and afterwards extract
28    # remaining of string into a value that populates the property.
29    # This method ensures that both quoted values and ;-separated list stays intact.
30    string(REGEX MATCH "([^:]*):([^=]*)=" variable_identifier ${str})
31    if(NOT "${variable_identifier}" STREQUAL "")
32      string(LENGTH ${variable_identifier} variable_identifier_length)
33      string(SUBSTRING "${str}" ${variable_identifier_length} -1 variable_value)
34      set_property(TARGET ${LOAD_CACHE_IMAGE}_cache APPEND PROPERTY "CACHE:VARIABLES" "${CMAKE_MATCH_1}")
35      set_property(TARGET ${LOAD_CACHE_IMAGE}_cache PROPERTY "${CMAKE_MATCH_1}:TYPE" "${CMAKE_MATCH_2}")
36      set_property(TARGET ${LOAD_CACHE_IMAGE}_cache PROPERTY "${CMAKE_MATCH_1}" "${variable_value}")
37      if("${CMAKE_MATCH_1}" MATCHES "^BYPRODUCT_.*")
38        set_property(TARGET ${LOAD_CACHE_IMAGE}_cache APPEND
39                     PROPERTY "EXTRA_BYPRODUCTS" "${variable_value}"
40        )
41      endif()
42    endif()
43  endforeach()
44endfunction()
45
46# Usage:
47#   sysbuild_get(<variable> IMAGE <image> [VAR <image-variable>] <KCONFIG|CACHE>)
48#
49# This function will return the variable found in the CMakeCache.txt file
50# identified by image.
51# If `VAR` is provided, the name given as parameter will be looked up, but if
52# `VAR` is not given, the `<variable>` name provided will be used both for
53# lookup and value return.
54#
55# The result will be returned in `<variable>`.
56#
57# Example use:
58#   sysbuild_get(PROJECT_NAME IMAGE my_sample CACHE)
59#     will lookup PROJECT_NAME from the CMakeCache identified by `my_sample` and
60#     and return the value in the local variable `PROJECT_NAME`.
61#
62#   sysbuild_get(my_sample_PROJECT_NAME IMAGE my_sample VAR PROJECT_NAME CACHE)
63#     will lookup PROJECT_NAME from the CMakeCache identified by `my_sample` and
64#     and return the value in the local variable `my_sample_PROJECT_NAME`.
65#
66#   sysbuild_get(my_sample_CONFIG_FOO IMAGE my_sample VAR CONFIG_FOO KCONFIG)
67#     will lookup CONFIG_FOO from the KConfig identified by `my_sample` and
68#     and return the value in the local variable `my_sample_CONFIG_FOO`.
69#
70# <variable>: variable used for returning CMake cache value. Also used as lookup
71#             variable if `VAR` is not provided.
72# IMAGE:      image name identifying the cache to use for variable lookup.
73# VAR:        name of the CMake cache variable name to lookup.
74# KCONFIG:    Flag indicating that a Kconfig setting should be fetched.
75# CACHE:      Flag indicating that a CMake cache variable should be fetched.
76function(sysbuild_get variable)
77  cmake_parse_arguments(GET_VAR "CACHE;KCONFIG" "IMAGE;VAR" "" ${ARGN})
78
79  if(NOT DEFINED GET_VAR_IMAGE)
80    message(FATAL_ERROR "sysbuild_get(...) requires IMAGE.")
81  endif()
82
83  if(DEFINED ${variable} AND NOT DEFINED GET_VAR_VAR)
84    message(WARNING "Return variable ${variable} already defined with a value. "
85                    "sysbuild_get(${variable} ...) may overwrite existing value. "
86		    "Please use sysbuild_get(<variable> ... VAR <image-variable>) "
87		    "where <variable> is undefined."
88    )
89  endif()
90
91  if(NOT DEFINED GET_VAR_VAR)
92    set(GET_VAR_VAR ${variable})
93  endif()
94
95  if(GET_VAR_KCONFIG)
96    set(variable_target ${GET_VAR_IMAGE})
97  elseif(GET_VAR_CACHE)
98    set(variable_target ${GET_VAR_IMAGE}_cache)
99  else()
100    message(WARNING "<CACHE> or <KCONFIG> not specified, defaulting to CACHE")
101    set(variable_target ${GET_VAR_IMAGE}_cache)
102  endif()
103
104  get_property(${GET_VAR_IMAGE}_${GET_VAR_VAR} TARGET ${variable_target} PROPERTY ${GET_VAR_VAR})
105  if(DEFINED ${GET_VAR_IMAGE}_${GET_VAR_VAR})
106    set(${variable} ${${GET_VAR_IMAGE}_${GET_VAR_VAR}} PARENT_SCOPE)
107  endif()
108endfunction()
109
110# Usage:
111#   sysbuild_cache(CREATE APPLICATION <name> [CMAKE_RERUN])
112#
113# This function works on the sysbuild cache for sysbuild managed applications.
114#
115# Arguments:
116# CREATE            : Create or update existing sysbuild cache file for the application.
117#                     The sysbuild cache is only updated if it contain changes.
118# APPLICATION <name>: Name of the application.
119# CMAKE_RERUN       : Force a CMake rerun for the application during next build
120#                     invocation if the sysbuild cache has changed. It is
121#                     advised to always use this flag. Not using this flag can
122#                     reduce build time, but only do so if application is
123#                     guaranteed to be up-to-date.
124#
125function(sysbuild_cache)
126  cmake_parse_arguments(SB_CACHE "CREATE;CMAKE_RERUN" "APPLICATION" "" ${ARGN})
127  zephyr_check_arguments_required(sysbuild_cache SB_CACHE APPLICATION)
128  zephyr_check_flags_required(sysbuild_cache SB_CACHE CREATE)
129
130  get_target_property(${SB_CACHE_APPLICATION}_MAIN_APP ${SB_CACHE_APPLICATION} MAIN_APP)
131  get_cmake_property(sysbuild_cache CACHE_VARIABLES)
132
133  foreach(var_name ${sysbuild_cache})
134    if(NOT "${var_name}" MATCHES "^(CMAKE_.*|BOARD)$")
135      # Perform a dummy read to prevent a false warning about unused variables
136      # being emitted due to a cmake bug: https://gitlab.kitware.com/cmake/cmake/-/issues/24555
137      set(unused_tmp_var ${${var_name}})
138
139      # We don't want to pass internal CMake variables.
140      # Required CMake variable to be passed, like CMAKE_BUILD_TYPE must be
141      # passed using `-D` on command invocation.
142      get_property(var_type CACHE ${var_name} PROPERTY TYPE)
143      set(cache_entry "${var_name}:${var_type}=$CACHE{${var_name}}")
144      string(REPLACE ";" "\;" cache_entry "${cache_entry}")
145      list(APPEND sysbuild_cache_strings "${cache_entry}\n")
146    endif()
147  endforeach()
148  if(DEFINED BOARD_REVISION)
149    list(APPEND sysbuild_cache_strings "BOARD:STRING=${BOARD}@${BOARD_REVISION}${BOARD_QUALIFIERS}\n")
150  else()
151    list(APPEND sysbuild_cache_strings "BOARD:STRING=${BOARD}${BOARD_QUALIFIERS}\n")
152  endif()
153  list(APPEND sysbuild_cache_strings "SYSBUILD_NAME:STRING=${SB_CACHE_APPLICATION}\n")
154
155  if(${SB_CACHE_APPLICATION}_MAIN_APP)
156    list(APPEND sysbuild_cache_strings "SYSBUILD_MAIN_APP:BOOL=True\n")
157  endif()
158
159  if(${SB_CACHE_APPLICATION}_BOARD AND NOT DEFINED CACHE{${SB_CACHE_APPLICATION}_BOARD})
160    # Only set image specific board if provided.
161    # The sysbuild BOARD is exported through sysbuild cache, and will be used
162    # unless <image>_BOARD is defined.
163    list(APPEND sysbuild_cache_strings
164         "${SB_CACHE_APPLICATION}_BOARD:STRING=${${SB_CACHE_APPLICATION}_BOARD}\n"
165    )
166  endif()
167
168  get_target_property(${SB_CACHE_APPLICATION}_CACHE_FILE ${SB_CACHE_APPLICATION} CACHE_FILE)
169  file(WRITE ${${SB_CACHE_APPLICATION}_CACHE_FILE}.tmp ${sysbuild_cache_strings})
170  if(SB_CACHE_CMAKE_RERUN)
171    execute_process(COMMAND ${CMAKE_COMMAND} -E compare_files
172                    ${${SB_CACHE_APPLICATION}_CACHE_FILE}.tmp
173                    ${${SB_CACHE_APPLICATION}_CACHE_FILE}
174                    RESULT_VARIABLE compare_res
175    )
176    if(NOT compare_res EQUAL 0)
177      zephyr_file_copy(${${SB_CACHE_APPLICATION}_CACHE_FILE}.tmp
178                       ${${SB_CACHE_APPLICATION}_CACHE_FILE}
179      )
180      ExternalProject_Get_Property(${SB_CACHE_APPLICATION} BINARY_DIR)
181      file(TOUCH_NOCREATE ${BINARY_DIR}/CMakeCache.txt)
182    endif()
183  else()
184    zephyr_file_copy(${${SB_CACHE_APPLICATION}_CACHE_FILE}.tmp
185                     ${${SB_CACHE_APPLICATION}_CACHE_FILE} ONLY_IF_DIFFERENT
186    )
187  endif()
188
189endfunction()
190
191# Usage:
192#   ExternalZephyrProject_Add(APPLICATION <name>
193#                             SOURCE_DIR <dir>
194#                             [BOARD <board> [BOARD_REVISION <revision>]]
195#                             [APP_TYPE <MAIN|BOOTLOADER>]
196#   )
197#
198# This function includes a Zephyr based build system into the multiimage
199# build system
200#
201# APPLICATION: <name>:       Name of the application, name will also be used for build
202#                            folder of the application
203# SOURCE_DIR <dir>:          Source directory of the application
204# BOARD <board>:             Use <board> for application build instead user defined BOARD.
205# BOARD_REVISION <revision>: Use <revision> of <board> for application (only valid if
206#                            <board> is also supplied).
207# APP_TYPE <MAIN|BOOTLOADER>: Application type.
208#                             MAIN indicates this application is the main application
209#                             and where user defined settings should be passed on as-is
210#                             except for multi image build flags.
211#                             For example, -DCONF_FILES=<files> will be passed on to the
212#                             MAIN_APP unmodified.
213#                             BOOTLOADER indicates this app is a bootloader
214# BUILD_ONLY <bool>:          Mark the application as build-only. If <bool> evaluates to
215#                             true, then this application will be excluded from flashing
216#                             and debugging.
217#
218function(ExternalZephyrProject_Add)
219  set(app_types MAIN BOOTLOADER)
220  cmake_parse_arguments(ZBUILD "" "APPLICATION;BOARD;BOARD_REVISION;SOURCE_DIR;APP_TYPE;BUILD_ONLY" "" ${ARGN})
221
222  if(ZBUILD_UNPARSED_ARGUMENTS)
223    message(FATAL_ERROR
224      "ExternalZephyrProject_Add(${ARGV0} <val> ...) given unknown arguments:"
225      " ${ZBUILD_UNPARSED_ARGUMENTS}"
226    )
227  endif()
228
229  if(TARGET ${ZBUILD_APPLICATION})
230    message(FATAL_ERROR
231      "ExternalZephyrProject_Add(APPLICATION ${ZBUILD_APPLICATION} ...) "
232      "already exists. Application names must be unique."
233    )
234  endif()
235
236  if(DEFINED ZBUILD_APP_TYPE)
237    if(NOT ZBUILD_APP_TYPE IN_LIST app_types)
238      message(FATAL_ERROR
239        "ExternalZephyrProject_Add(APP_TYPE <val> ...) given unknown type: ${ZBUILD_APP_TYPE}\n"
240        "Valid types are: ${app_types}"
241      )
242    endif()
243
244  endif()
245
246  if(NOT DEFINED SYSBUILD_CURRENT_SOURCE_DIR)
247    message(FATAL_ERROR
248      "ExternalZephyrProject_Add(${ARGV0} <val> ...) must not be called outside of"
249      " sysbuild_add_subdirectory(). SYSBUILD_CURRENT_SOURCE_DIR is undefined."
250    )
251  endif()
252  set_property(
253    DIRECTORY "${SYSBUILD_CURRENT_SOURCE_DIR}"
254    APPEND PROPERTY sysbuild_images ${ZBUILD_APPLICATION}
255  )
256  set_property(
257    GLOBAL
258    APPEND PROPERTY sysbuild_images ${ZBUILD_APPLICATION}
259  )
260
261  set(sysbuild_image_conf_dir ${APP_DIR}/sysbuild)
262  set(sysbuild_image_name_conf_dir ${APP_DIR}/sysbuild/${ZBUILD_APPLICATION})
263  # User defined `-D<image>_CONF_FILE=<file.conf>` takes precedence over anything else.
264  if (NOT ${ZBUILD_APPLICATION}_CONF_FILE)
265    if(EXISTS ${sysbuild_image_name_conf_dir})
266      set(${ZBUILD_APPLICATION}_APPLICATION_CONFIG_DIR ${sysbuild_image_name_conf_dir}
267          CACHE INTERNAL "Application configuration dir controlled by sysbuild"
268      )
269    endif()
270
271    # Check for sysbuild related configuration fragments.
272    # The contents of these are appended to the image existing configuration
273    # when user is not specifying custom fragments.
274    zephyr_file(CONF_FILES ${sysbuild_image_conf_dir} KCONF sysbuild_image_conf_fragment
275                NAMES ${ZBUILD_APPLICATION}.conf SUFFIX ${FILE_SUFFIX}
276    )
277
278    if (NOT (${ZBUILD_APPLICATION}_OVERLAY_CONFIG OR ${ZBUILD_APPLICATION}_EXTRA_CONF_FILE)
279        AND EXISTS ${sysbuild_image_conf_fragment}
280    )
281      set(${ZBUILD_APPLICATION}_EXTRA_CONF_FILE ${sysbuild_image_conf_fragment}
282          CACHE INTERNAL "Kconfig fragment defined by main application"
283      )
284    endif()
285
286    # Check for overlay named <ZBUILD_APPLICATION>.overlay.
287    set(sysbuild_image_dts_overlay ${sysbuild_image_conf_dir}/${ZBUILD_APPLICATION}.overlay)
288    if (NOT ${ZBUILD_APPLICATION}_DTC_OVERLAY_FILE AND EXISTS ${sysbuild_image_dts_overlay})
289      set(${ZBUILD_APPLICATION}_DTC_OVERLAY_FILE ${sysbuild_image_dts_overlay}
290          CACHE INTERNAL "devicetree overlay file defined by main application"
291      )
292    endif()
293  endif()
294
295  # Update ROOT variables with relative paths to use absolute paths based on
296  # the source application directory.
297  foreach(type MODULE_EXT BOARD SOC ARCH SCA)
298    if(DEFINED CACHE{${ZBUILD_APPLICATION}_${type}_ROOT} AND NOT IS_ABSOLUTE $CACHE{${ZBUILD_APPLICATION}_${type}_ROOT})
299      set(rel_path $CACHE{${ZBUILD_APPLICATION}_${type}_ROOT})
300      cmake_path(ABSOLUTE_PATH rel_path BASE_DIRECTORY "${ZBUILD_SOURCE_DIR}" NORMALIZE OUTPUT_VARIABLE abs_path)
301      set(${ZBUILD_APPLICATION}_${type}_ROOT ${abs_path} CACHE PATH "Sysbuild adjusted absolute path" FORCE)
302    endif()
303  endforeach()
304
305  # CMake variables which must be known by all Zephyr CMake build systems
306  # Those are settings which controls the build and must be known to CMake at
307  # invocation time, and thus cannot be passed though the sysbuild cache file.
308  set(
309    shared_cmake_variables_list
310    CMAKE_BUILD_TYPE
311    CMAKE_VERBOSE_MAKEFILE
312  )
313
314  set(sysbuild_cache_file ${CMAKE_BINARY_DIR}/${ZBUILD_APPLICATION}_sysbuild_cache.txt)
315
316  set(shared_cmake_vars_argument)
317  foreach(shared_var ${shared_cmake_variables_list})
318    if(DEFINED CACHE{${ZBUILD_APPLICATION}_${shared_var}})
319      get_property(var_type  CACHE ${ZBUILD_APPLICATION}_${shared_var} PROPERTY TYPE)
320      list(APPEND shared_cmake_vars_argument
321           "-D${shared_var}:${var_type}=$CACHE{${ZBUILD_APPLICATION}_${shared_var}}"
322      )
323    elseif(DEFINED CACHE{${shared_var}})
324      get_property(var_type  CACHE ${shared_var} PROPERTY TYPE)
325      list(APPEND shared_cmake_vars_argument
326           "-D${shared_var}:${var_type}=$CACHE{${shared_var}}"
327      )
328    endif()
329  endforeach()
330
331  foreach(kconfig_target
332      menuconfig
333      hardenconfig
334      guiconfig
335      $CACHE{EXTRA_KCONFIG_TARGETS}
336      )
337
338    if(NOT ZBUILD_APP_TYPE STREQUAL "MAIN")
339      set(image_prefix "${ZBUILD_APPLICATION}_")
340    endif()
341
342    add_custom_target(${image_prefix}${kconfig_target}
343      ${CMAKE_MAKE_PROGRAM} ${kconfig_target}
344      WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/${ZBUILD_APPLICATION}
345      USES_TERMINAL
346      )
347  endforeach()
348
349  set(list_separator ",")
350  set(image_extra_kconfig_targets "-DEXTRA_KCONFIG_TARGETS=$CACHE{EXTRA_KCONFIG_TARGETS}")
351  string(REPLACE ";" "${list_separator}" image_extra_kconfig_targets "${image_extra_kconfig_targets}")
352  foreach(target $CACHE{EXTRA_KCONFIG_TARGETS})
353    list(APPEND image_extra_kconfig_targets
354         -DEXTRA_KCONFIG_TARGET_COMMAND_FOR_${target}=$CACHE{EXTRA_KCONFIG_TARGET_COMMAND_FOR_${target}}
355    )
356  endforeach()
357
358  include(ExternalProject)
359  set(application_binary_dir ${CMAKE_BINARY_DIR}/${ZBUILD_APPLICATION})
360  ExternalProject_Add(
361    ${ZBUILD_APPLICATION}
362    SOURCE_DIR ${ZBUILD_SOURCE_DIR}
363    BINARY_DIR ${application_binary_dir}
364    CONFIGURE_COMMAND ""
365    LIST_SEPARATOR "${list_separator}"
366    CMAKE_ARGS -DSYSBUILD:BOOL=True
367               -DSYSBUILD_CACHE:FILEPATH=${sysbuild_cache_file}
368               ${shared_cmake_vars_argument}
369               ${image_extra_kconfig_targets}
370    BUILD_COMMAND ${CMAKE_COMMAND} --build .
371    INSTALL_COMMAND ""
372    BUILD_ALWAYS True
373    USES_TERMINAL_BUILD True
374  )
375  set_property(TARGET ${ZBUILD_APPLICATION} PROPERTY APP_TYPE ${ZBUILD_APP_TYPE})
376  set_property(TARGET ${ZBUILD_APPLICATION} PROPERTY CONFIG
377               "# sysbuild controlled configuration settings\n"
378  )
379  set_target_properties(${ZBUILD_APPLICATION} PROPERTIES CACHE_FILE ${sysbuild_cache_file})
380  set_target_properties(${ZBUILD_APPLICATION} PROPERTIES KCONFIG_BINARY_DIR
381                        ${application_binary_dir}/Kconfig
382  )
383  if("${ZBUILD_APP_TYPE}" STREQUAL "MAIN")
384    set_target_properties(${ZBUILD_APPLICATION} PROPERTIES MAIN_APP True)
385  endif()
386
387  set(image_default "${CMAKE_SOURCE_DIR}/image_configurations/ALL_image_default.cmake")
388
389  if(DEFINED ZBUILD_APP_TYPE)
390    list(APPEND image_default "${CMAKE_SOURCE_DIR}/image_configurations/${ZBUILD_APP_TYPE}_image_default.cmake")
391  endif()
392
393  set_target_properties(${ZBUILD_APPLICATION} PROPERTIES IMAGE_CONF_SCRIPT "${image_default}")
394
395  if(DEFINED ZBUILD_BOARD)
396    # Only set image specific board if provided.
397    # The sysbuild BOARD is exported through sysbuild cache, and will be used
398    # unless <image>_BOARD is defined.
399    if(DEFINED ZBUILD_BOARD_REVISION)
400      # Use provided board revision
401      if(ZBUILD_BOARD MATCHES "/")
402        # HWMv2 requires adding version to the board, split elements up, attach version, then
403        # reassemble into a complete string
404        string(REPLACE "/" ";" split_board_qualifiers "${ZBUILD_BOARD}")
405        list(GET split_board_qualifiers 0 target_board)
406        set(target_board ${target_board}@${ZBUILD_BOARD_REVISION})
407        list(REMOVE_AT split_board_qualifiers 0)
408        list(PREPEND split_board_qualifiers ${target_board})
409        string(REPLACE ";" "/" board_qualifiers "${split_board_qualifiers}")
410        set_target_properties(${ZBUILD_APPLICATION} PROPERTIES BOARD ${board_qualifiers})
411        set(split_board_qualifiers)
412        set(board_qualifiers)
413      else()
414        # Legacy HWMv1 support, version goes at end
415        set_target_properties(${ZBUILD_APPLICATION} PROPERTIES BOARD ${ZBUILD_BOARD}@${ZBUILD_BOARD_REVISION})
416      endif()
417    else()
418      set_target_properties(${ZBUILD_APPLICATION} PROPERTIES BOARD ${ZBUILD_BOARD})
419    endif()
420  elseif(DEFINED ZBUILD_BOARD_REVISION)
421    message(FATAL_ERROR
422      "ExternalZephyrProject_Add(... BOARD_REVISION ${ZBUILD_BOARD_REVISION})"
423      " requires BOARD."
424    )
425  endif()
426
427  if(DEFINED ZBUILD_BUILD_ONLY)
428    set_target_properties(${ZBUILD_APPLICATION} PROPERTIES BUILD_ONLY ${ZBUILD_BUILD_ONLY})
429  endif()
430endfunction()
431
432# Usage:
433#   ExternalZephyrProject_Cmake(APPLICATION <name>)
434#
435# This function invokes the CMake configure step on an external Zephyr project
436# which has been added at an earlier stage using `ExternalZephyrProject_Add()`
437#
438# If the application is not due to ExternalZephyrProject_Add() being called,
439# then an error is raised.
440#
441# The image output files are added as target properties on the image target as:
442# ELF_OUT: property specifying the generated elf file.
443# BIN_OUT: property specifying the generated bin file.
444# HEX_OUT: property specifying the generated hex file.
445# S19_OUT: property specifying the generated s19 file.
446# UF2_OUT: property specifying the generated uf2 file.
447# EXE_OUT: property specifying the generated exe file.
448#
449# the property is only set if the image is configured to generate the output
450# format. Elf files are always created.
451#
452# APPLICATION: <name>: Name of the application.
453#
454function(ExternalZephyrProject_Cmake)
455  cmake_parse_arguments(ZCMAKE "" "APPLICATION" "" ${ARGN})
456
457  if(ZBUILD_UNPARSED_ARGUMENTS)
458    message(FATAL_ERROR
459      "ExternalZephyrProject_Cmake(${ARGV0} <val> ...) given unknown arguments:"
460      " ${ZBUILD_UNPARSED_ARGUMENTS}"
461    )
462  endif()
463
464  if(NOT DEFINED ZCMAKE_APPLICATION)
465    message(FATAL_ERROR "Missing required argument: APPLICATION")
466  endif()
467
468  if(NOT TARGET ${ZCMAKE_APPLICATION})
469    message(FATAL_ERROR
470      "${ZCMAKE_APPLICATION} does not exists. Remember to call "
471      "ExternalZephyrProject_Add(APPLICATION ${ZCMAKE_APPLICATION} ...) first."
472    )
473  endif()
474
475  set(image_banner "* Running CMake for ${ZCMAKE_APPLICATION} *")
476  string(LENGTH "${image_banner}" image_banner_width)
477  string(REPEAT "*" ${image_banner_width} image_banner_header)
478  message(STATUS "\n   ${image_banner_header}\n"
479                 "   ${image_banner}\n"
480                 "   ${image_banner_header}\n"
481  )
482
483  ExternalProject_Get_Property(${ZCMAKE_APPLICATION} SOURCE_DIR BINARY_DIR CMAKE_ARGS LIST_SEPARATOR)
484  get_target_property(${ZCMAKE_APPLICATION}_BOARD      ${ZCMAKE_APPLICATION} BOARD)
485
486  get_property(${ZCMAKE_APPLICATION}_CONF_SCRIPT TARGET ${ZCMAKE_APPLICATION}
487               PROPERTY IMAGE_CONF_SCRIPT
488  )
489
490  sysbuild_cache(CREATE APPLICATION ${ZCMAKE_APPLICATION})
491
492  foreach(script ${${ZCMAKE_APPLICATION}_CONF_SCRIPT})
493    include(${script})
494  endforeach()
495
496  set(dotconfigsysbuild ${BINARY_DIR}/zephyr/.config.sysbuild)
497  get_target_property(config_content ${ZCMAKE_APPLICATION} CONFIG)
498  string(CONFIGURE "${config_content}" config_content)
499  file(WRITE ${dotconfigsysbuild} ${config_content})
500
501  string(REPLACE "${LIST_SEPARATOR}" "\\;" CMAKE_ARGS "${CMAKE_ARGS}")
502  execute_process(
503    COMMAND ${CMAKE_COMMAND}
504      -G${CMAKE_GENERATOR}
505        ${CMAKE_ARGS}
506      -DFORCED_CONF_FILE:FILEPATH=${dotconfigsysbuild}
507      -B${BINARY_DIR}
508      -S${SOURCE_DIR}
509    RESULT_VARIABLE   return_val
510    WORKING_DIRECTORY ${BINARY_DIR}
511  )
512
513  if(return_val)
514    message(FATAL_ERROR
515            "CMake configure failed for Zephyr project: ${ZCMAKE_APPLICATION}\n"
516            "Location: ${SOURCE_DIR}"
517    )
518  endif()
519  load_cache(IMAGE ${ZCMAKE_APPLICATION} BINARY_DIR ${BINARY_DIR})
520  import_kconfig(CONFIG_ ${BINARY_DIR}/zephyr/.config TARGET ${ZCMAKE_APPLICATION})
521
522  # This custom target informs CMake how the BYPRODUCTS are generated if a target
523  # depends directly on the BYPRODUCT instead of depending on the image target.
524  get_target_property(${ZCMAKE_APPLICATION}_byproducts ${ZCMAKE_APPLICATION}_cache EXTRA_BYPRODUCTS)
525  add_custom_target(${ZCMAKE_APPLICATION}_extra_byproducts
526                    COMMAND ${CMAKE_COMMAND} -E true
527                    BYPRODUCTS ${${ZCMAKE_APPLICATION}_byproducts}
528                    DEPENDS ${ZCMAKE_APPLICATION}
529  )
530endfunction()
531
532# Usage:
533#   sysbuild_module_call(<hook> MODULES <modules> IMAGES <images> [IMAGE <image>] [EXTRA_ARGS <arguments>])
534#
535# This function invokes the sysbuild hook provided as <hook> for <modules>.
536#
537# `IMAGES` contains the list of images to the hook, if `IMAGE` is passed, this will be provided
538# to the hook.
539#
540# `EXTRA_ARGS` can be used to pass extra arguments to the hook.
541#
542# Valid <hook> values:
543# PRE_CMAKE       : Invoke pre-CMake call for modules before CMake configure is invoked for images
544# POST_CMAKE      : Invoke post-CMake call for modules after CMake configure has been invoked for
545# PRE_IMAGE_CMAKE : Invoke pre-CMake call for modules before CMake configure is invoked for each
546#                   image
547# POST_IMAGE_CMAKE: Invoke post-CMake call for modules after CMake configure has been invoked for
548#                   each image
549# PRE_DOMAINS     : Invoke pre-domains call for modules before creating domains yaml
550# POST_DOMAINS    : Invoke post-domains call for modules after creation of domains yaml
551#
552# For the `PRE_IMAGE_CMAKE` and `POST_IMAGE_CMAKE` hooks, `IMAGE` is provided
553#
554function(sysbuild_module_call)
555  set(options "PRE_CMAKE;POST_CMAKE;PRE_IMAGE_CMAKE;POST_IMAGE_CMAKE;PRE_DOMAINS;POST_DOMAINS")
556  set(multi_args "MODULES;IMAGES;IMAGE;EXTRA_ARGS")
557  cmake_parse_arguments(SMC "${options}" "${test_args}" "${multi_args}" ${ARGN})
558
559  zephyr_check_flags_required("sysbuild_module_call" SMC ${options})
560  zephyr_check_flags_exclusive("sysbuild_module_call" SMC ${options})
561
562  if(NOT DEFINED SMC_IMAGES)
563    message(FATAL_ERROR
564            "sysbuild_module_call(...) missing required IMAGES option")
565  endif()
566
567  if(DEFINED SMC_IMAGE)
568    set(IMAGE_ARG IMAGE ${SMC_IMAGE})
569  elseif(SMC_PRE_IMAGE_CMAKE)
570    message(FATAL_ERROR
571            "sysbuild_module_call(PRE_IMAGE_CMAKE ...) missing required IMAGE option")
572  elseif(SMC_POST_IMAGE_CMAKE)
573    message(FATAL_ERROR
574            "sysbuild_module_call(POST_IMAGE_CMAKE ...) missing required IMAGE option")
575  endif()
576
577  foreach(call ${options})
578    if(SMC_${call})
579      foreach(module ${SMC_MODULES})
580        if(COMMAND ${module}_${call})
581          cmake_language(CALL ${module}_${call} IMAGES ${SMC_IMAGES} ${IMAGE_ARG} ${SMC_EXTRA_ARGS})
582        endif()
583      endforeach()
584    endif()
585  endforeach()
586endfunction()
587
588# Usage:
589#   sysbuild_cache_set(VAR <variable> [APPEND [REMOVE_DUPLICATES]] <value>)
590#
591# This function will set the specified value of the sysbuild cache variable in
592# the CMakeCache.txt file which can then be accessed by images.
593# `VAR` specifies the variable name to set/update.
594#
595# The result will be returned in `<variable>`.
596#
597# Example use:
598#   sysbuild_cache_set(VAR ATTRIBUTES APPEND REMOVE_DUPLICATES battery)
599#     Will add the item `battery` to the `ATTRIBUTES` variable as a new element
600#     in the list in the CMakeCache and remove any duplicates from the list.
601#
602# <variable>:        Name of variable in CMake cache.
603# APPEND:            If specified then will append the supplied data to the
604#                    existing value as a list.
605# REMOVE_DUPLICATES: If specified then remove duplicate entries contained
606#                    within the list before saving to the cache.
607# <value>:           Value to set/update.
608function(sysbuild_cache_set)
609  cmake_parse_arguments(VARS "APPEND;REMOVE_DUPLICATES" "VAR" "" ${ARGN})
610
611  zephyr_check_arguments_required(sysbuild_cache_set VARS VAR)
612
613  if(NOT VARS_UNPARSED_ARGUMENTS AND VARS_APPEND)
614    # Nothing to append so do nothing
615    return()
616  elseif(VARS_REMOVE_DUPLICATES AND NOT VARS_APPEND)
617    message(FATAL_ERROR
618            "sysbuild_cache_set(VAR <var> APPEND REMOVE_DUPLICATES ...) missing required APPEND option")
619  endif()
620
621  get_property(var_type CACHE ${VARS_VAR} PROPERTY TYPE)
622  get_property(var_help CACHE ${VARS_VAR} PROPERTY HELPSTRING)
623
624  # If the variable type is not set, use UNINITIALIZED which will not apply any
625  # specific formatting.
626  if(NOT var_type)
627    set(var_type "UNINITIALIZED")
628  endif()
629
630  if(VARS_APPEND)
631    set(var_new "$CACHE{${VARS_VAR}}")
632
633    # Search for these exact items in the existing value and prevent adding
634    # them if they are already present which avoids issues with double addition
635    # when cmake is reran.
636    if("${VARS_UNPARSED_ARGUMENTS}" IN_LIST var_new)
637      return()
638    endif()
639
640    list(APPEND var_new "${VARS_UNPARSED_ARGUMENTS}")
641
642    if(VARS_REMOVE_DUPLICATES)
643      list(REMOVE_DUPLICATES var_new)
644    endif()
645  else()
646    set(var_new "${VARS_UNPARSED_ARGUMENTS}")
647  endif()
648
649  set(${VARS_VAR} "${var_new}" CACHE "${var_type}" "${var_help}" FORCE)
650endfunction()
651
652function(set_config_bool image setting value)
653  if(${value})
654    set_property(TARGET ${image} APPEND_STRING PROPERTY CONFIG "${setting}=y\n")
655  else()
656    set_property(TARGET ${image} APPEND_STRING PROPERTY CONFIG "${setting}=n\n")
657  endif()
658endfunction()
659
660function(set_config_string image setting value)
661  set_property(TARGET ${image} APPEND_STRING PROPERTY CONFIG "${setting}=\"${value}\"\n")
662endfunction()
663
664function(set_config_int image setting value)
665  set_property(TARGET ${image} APPEND_STRING PROPERTY CONFIG "${setting}=${value}\n")
666endfunction()
667
668# Usage:
669#   sysbuild_add_subdirectory(<source_dir> [<binary_dir>])
670#
671# This function extends the standard add_subdirectory() command with additional,
672# recursive processing of the sysbuild images added via <source_dir>.
673#
674# After exiting <source_dir>, this function will take every image added so far,
675# and include() its sysbuild.cmake file (if found). If more images get added at
676# this stage, their sysbuild.cmake files will be included as well, and so on.
677# This continues until all expected images have been added, before returning.
678#
679function(sysbuild_add_subdirectory source_dir)
680  if(ARGC GREATER 2)
681    message(FATAL_ERROR
682      "sysbuild_add_subdirectory(...) called with incorrect number of arguments"
683      " (expected at most 2, got ${ARGC})"
684    )
685  endif()
686  set(binary_dir ${ARGN})
687
688  # Update SYSBUILD_CURRENT_SOURCE_DIR in this scope, to support nesting
689  # of sysbuild_add_subdirectory() and even regular add_subdirectory().
690  cmake_path(ABSOLUTE_PATH source_dir NORMALIZE OUTPUT_VARIABLE SYSBUILD_CURRENT_SOURCE_DIR)
691  add_subdirectory(${source_dir} ${binary_dir})
692
693  while(TRUE)
694    get_property(added_images DIRECTORY "${SYSBUILD_CURRENT_SOURCE_DIR}" PROPERTY sysbuild_images)
695    if(NOT added_images)
696      break()
697    endif()
698    set_property(DIRECTORY "${SYSBUILD_CURRENT_SOURCE_DIR}" PROPERTY sysbuild_images "")
699
700    foreach(image ${added_images})
701      ExternalProject_Get_property(${image} SOURCE_DIR)
702      include(${SOURCE_DIR}/sysbuild.cmake OPTIONAL)
703    endforeach()
704  endwhile()
705endfunction()
706
707# Usage:
708#   sysbuild_add_dependencies(<CONFIGURE | FLASH> <image> [<image-dependency> ...])
709#
710# This function makes an image depend on other images in the configuration or
711# flashing order. Each image named "<image-dependency>" will be ordered before
712# the image named "<image>".
713#
714# CONFIGURE: Add CMake configuration dependencies. This will determine the order
715#            in which `ExternalZephyrProject_Cmake()` will be called.
716# FLASH:     Add flashing dependencies. This will determine the order in which
717#            all images will appear in `domains.yaml`.
718#
719function(sysbuild_add_dependencies dependency_type image)
720  set(valid_dependency_types CONFIGURE FLASH)
721  if(NOT dependency_type IN_LIST valid_dependency_types)
722    list(JOIN valid_dependency_types ", " valid_dependency_types)
723    message(FATAL_ERROR "sysbuild_add_dependencies(...) dependency type "
724                        "${dependency_type} must be one of the following: "
725                        "${valid_dependency_types}"
726    )
727  endif()
728
729  if(NOT TARGET ${image})
730    message(FATAL_ERROR
731      "${image} does not exist. Remember to call "
732      "ExternalZephyrProject_Add(APPLICATION ${image} ...) first."
733    )
734  endif()
735
736  get_target_property(image_is_build_only ${image} BUILD_ONLY)
737  if(image_is_build_only AND dependency_type STREQUAL "FLASH")
738    message(FATAL_ERROR
739      "sysbuild_add_dependencies(...) cannot add FLASH dependencies to "
740      "BUILD_ONLY image ${image}."
741    )
742  endif()
743
744  set(property_name ${dependency_type}_DEPENDS)
745  set_property(TARGET ${image} APPEND PROPERTY ${property_name} ${ARGN})
746endfunction()
747
748# Usage:
749#   sysbuild_images_order(<variable> <CONFIGURE | FLASH> IMAGES <images>)
750#
751# This function will sort the provided `<images>` to satisfy the dependencies
752# specified using `sysbuild_add_dependencies()`. The result will be returned in
753# `<variable>`.
754#
755function(sysbuild_images_order variable dependency_type)
756  cmake_parse_arguments(SIS "" "" "IMAGES" ${ARGN})
757  zephyr_check_arguments_required_all("sysbuild_images_order" SIS IMAGES)
758
759  set(valid_dependency_types CONFIGURE FLASH)
760  if(NOT dependency_type IN_LIST valid_dependency_types)
761    list(JOIN valid_dependency_types ", " valid_dependency_types)
762    message(FATAL_ERROR "sysbuild_images_order(...) dependency type "
763                        "${dependency_type} must be one of the following: "
764                        "${valid_dependency_types}"
765    )
766  endif()
767
768  set(property_name ${dependency_type}_DEPENDS)
769  topological_sort(TARGETS ${SIS_IMAGES} PROPERTY_NAME ${property_name} RESULT sorted)
770  set(${variable} ${sorted} PARENT_SCOPE)
771endfunction()
772