Build: Convert bl2 dir to modern cmake

Alters cmake files inside the bl2 directory. Moves some bl2 files to
mirror the directory structure of upstream MCUboot. Renames some of the
key files to allow easier programmatic selection. Alters some headers
where the include paths have changed.

WARNING: This change will not build in isolation, it requires _all_
other cmake changes to successfully build. It is split out only for
clarity of changes.

Change-Id: I8fe822d982d5e1635fb3176135e33bc3acf9163a
Signed-off-by: Raef Coles <raef.coles@arm.com>
diff --git a/bl2/ext/mcuboot/CMakeLists.txt b/bl2/ext/mcuboot/CMakeLists.txt
index 996d87c..cc3a54a 100644
--- a/bl2/ext/mcuboot/CMakeLists.txt
+++ b/bl2/ext/mcuboot/CMakeLists.txt
@@ -1,289 +1,227 @@
 #------------------------------------------------------------------------------
-# Copyright (c) 2017-2020, Arm Limited. All rights reserved.
+# Copyright (c) 2020, Arm Limited. All rights reserved.
 #
 # SPDX-License-Identifier: BSD-3-Clause
 #
 #------------------------------------------------------------------------------
 
-cmake_minimum_required(VERSION 3.7)
+cmake_minimum_required(VERSION 3.13)
+cmake_policy(SET CMP0079 NEW)
 
-set(TFM_BUILD_IN_SPE ON)
-
-#Tell cmake where our modules can be found
-list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/../../../cmake)
-
-#Include common stuff to control cmake.
-include("Common/BuildSys")
-
-#Start an embedded project.
-get_filename_component(TFM_ROOT_DIR "${CMAKE_CURRENT_LIST_DIR}/../../.." ABSOLUTE)
-embedded_project_start(CONFIG "${TFM_ROOT_DIR}/configs/ConfigDefault.cmake")
-project(mcuboot LANGUAGES ASM C)
-embedded_project_fixup()
-
-#Check input variables
-if (NOT DEFINED BL2)
-   message(FATAL ERROR "Incomplete build configuration: BL2 is undefined.")
-elseif(NOT BL2)
-    #If mcuboot is not need to be built then stop further processing.
-    return()
+if(TFM_INTERNAL_MCUBOOT)
+    set(MCUBOOT_PATH ${CMAKE_CURRENT_SOURCE_DIR} CACHE PATH "Path to mcuboot (or DOWNLOAD to get automatically" FORCE)
 endif()
 
-#Set the appropriate MCUBoot path
-if (MCUBOOT_REPO STREQUAL "TF-M")
-	get_filename_component(MCUBOOT_DIR ${CMAKE_CURRENT_LIST_DIR} ABSOLUTE)
+set(MCUBOOT_KEY_ENC "${MCUBOOT_PATH}/enc-rsa2048-pub.pem" CACHE FILEPATH "Path to key with which to encrypt binary")
+
+target_include_directories(bl2
+    PUBLIC
+        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
+        $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}> # for mcuboot_config.h only
+        $<BUILD_INTERFACE:${MCUBOOT_PATH}/boot/bootutil/include>
+        $<BUILD_INTERFACE:${MCUBOOT_PATH}/boot>
+)
+
+target_sources(bl2
+    PRIVATE
+        ${CMAKE_CURRENT_SOURCE_DIR}/bl2_main.c
+        ${CMAKE_CURRENT_SOURCE_DIR}/keys.c
+        ${CMAKE_CURRENT_SOURCE_DIR}/flash_map_extended.c
+        ${CMAKE_CURRENT_SOURCE_DIR}/flash_map_legacy.c
+        ${MCUBOOT_PATH}/boot/bootutil/src/loader.c
+        ${MCUBOOT_PATH}/boot/bootutil/src/bootutil_misc.c
+        ${MCUBOOT_PATH}/boot/bootutil/src/image_validate.c
+        ${MCUBOOT_PATH}/boot/bootutil/src/image_rsa.c
+        ${MCUBOOT_PATH}/boot/bootutil/src/tlv.c
+        ${MCUBOOT_PATH}/boot/bootutil/src/boot_record.c
+        $<$<NOT:$<BOOL:${TFM_INTERNAL_MCUBOOT}>>:${MCUBOOT_PATH}/boot/bootutil/src/swap_scratch.c>
+        $<$<NOT:$<BOOL:${TFM_INTERNAL_MCUBOOT}>>:${MCUBOOT_PATH}/boot/bootutil/src/swap_move.c>
+        $<$<NOT:$<BOOL:${TFM_INTERNAL_MCUBOOT}>>:${MCUBOOT_PATH}/boot/bootutil/src/swap_misc.c>
+        $<$<NOT:$<BOOL:${TFM_INTERNAL_MCUBOOT}>>:${MCUBOOT_PATH}/boot/bootutil/src/encrypted.c>
+)
+
+set(MCUBOOT_ALLOWED_LOG_LEVELS OFF ERROR WARNING INFO DEBUG)
+list(FIND MCUBOOT_ALLOWED_LOG_LEVELS ${MCUBOOT_LOG_LEVEL} LOG_LEVEL_ID)
+
+configure_file(include/mcuboot_config/mcuboot_config.h.in
+               ${CMAKE_CURRENT_BINARY_DIR}/mcuboot_config/mcuboot_config.h
+               @ONLY)
+
+############################### IMAGE SIGNING ##################################
+
+find_package(Python3)
+
+set(FLASH_AREA_NUM 0)
+if (MCUBOOT_IMAGE_NUMBER GREATER 1)
+    configure_file(signing_layout.c.in signing_layout_s.c @ONLY)
+    add_library(signing_layout_s OBJECT ${CMAKE_CURRENT_BINARY_DIR}/signing_layout_s.c)
 else()
-	get_filename_component(MCUBOOT_DIR "${TFM_ROOT_DIR}/../mcuboot/boot" ABSOLUTE)
-	if (NOT EXISTS ${MCUBOOT_DIR})
-		message(FATAL_ERROR "Missing MCUBoot. Please clone the MCUBoot repo to directory \"${MCUBOOT_DIR}\".")
-	endif()
+    # Imgtool script requires the s_ns sufix. Since only one sigining layout is
+    # used in this mode the signing_layout_s target's source file is renamed.
+    configure_file(signing_layout.c.in signing_layout_s_ns.c @ONLY)
+    add_library(signing_layout_s OBJECT ${CMAKE_CURRENT_BINARY_DIR}/signing_layout_s_ns.c)
 endif()
 
-if (NOT DEFINED MBEDCRYPTO_C_FLAGS_BL2)
-	message(FATAL_ERROR "Incomplete build configuration: MBEDCRYPTO_C_FLAGS_BL2 is undefined.")
+target_compile_options(signing_layout_s
+    PRIVATE
+        $<$<C_COMPILER_ID:GNU>:-E\;-xc>
+        $<$<C_COMPILER_ID:ARMClang>:-E\;-xc>
+        $<$<C_COMPILER_ID:IAR>:--preprocess=ns\;$<TARGET_OBJECTS:signing_layout_s>>
+)
+target_compile_definitions(signing_layout_s
+    PRIVATE
+        $<$<BOOL:${BL2}>:BL2>
+        $<$<BOOL:${MCUBOOT_IMAGE_NUMBER}>:MCUBOOT_IMAGE_NUMBER=${MCUBOOT_IMAGE_NUMBER}>
+)
+target_link_libraries(signing_layout_s
+    PRIVATE
+        platform_bl2
+)
+
+if(NS)
+    add_custom_target(tfm_s_ns_bin
+        SOURCES tfm_s_ns.bin
+    )
+    add_custom_command(OUTPUT tfm_s_ns.bin
+        DEPENDS $<TARGET_FILE_DIR:tfm_s>/tfm_s.bin
+        DEPENDS $<TARGET_FILE_DIR:tfm_ns>/tfm_ns.bin
+        DEPENDS tfm_s_bin tfm_ns_bin
+        DEPENDS signing_layout_s
+
+        COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/assemble.py
+            --layout $<TARGET_OBJECTS:signing_layout_s>
+            -s $<TARGET_FILE_DIR:tfm_s>/tfm_s.bin
+            -n $<TARGET_FILE_DIR:tfm_ns>/tfm_ns.bin
+            -o tfm_s_ns.bin
+        COMMAND ${CMAKE_COMMAND} -E copy tfm_s_ns.bin $<TARGET_FILE_DIR:bl2>
+    )
 endif()
 
-set(BUILD_CMSIS_CORE On)
-set(BUILD_RETARGET On)
-set(BUILD_NATIVE_DRIVERS On)
-set(BUILD_STARTUP On)
-set(BUILD_TARGET_CFG Off)
-set(BUILD_TARGET_NV_COUNTERS On)
-set(BUILD_CMSIS_DRIVERS On)
-set(BUILD_TIME Off)
-set(BUILD_UART_STDOUT On)
-set(BUILD_FLASH On)
-set(BUILD_PLAT_TEST Off)
-set(BUILD_BOOT_HAL On)
+add_custom_target(tfm_s_signed_bin
+    SOURCES tfm_s_signed.bin
+)
+add_custom_command(OUTPUT tfm_s_signed.bin
+    DEPENDS $<TARGET_FILE_DIR:tfm_s>/tfm_s.bin
+    DEPENDS tfm_s_bin signing_layout_s
+    WORKING_DIRECTORY ${MCUBOOT_PATH}/scripts
 
-if (MCUBOOT_HW_KEY)
-	set(BUILD_TARGET_HARDWARE_KEYS On)
-else()
-	set(BUILD_TARGET_HARDWARE_KEYS Off)
+    #Sign secure binary image with provided secret key
+    COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/wrapper/wrapper.py
+        -v ${MCUBOOT_IMAGE_VERSION_S}
+        --layout $<TARGET_OBJECTS:signing_layout_s>
+        -k ${MCUBOOT_KEY_S}
+        --public-key-format $<IF:$<BOOL:${MCUBOOT_HW_KEY}>,full,hash>
+        --align 1
+        --pad
+        --pad-header
+        -H 0x400
+        -s ${MCUBOOT_SECURITY_COUNTER_S}
+        -d \"\(0,${MCUBOOT_S_IMAGE_MIN_VER}\)\"
+        $<$<STREQUAL:${MCUBOOT_UPGRADE_STRATEGY},OVERWRITE_ONLY>:--overwrite-only>
+        $<$<BOOL:${MCUBOOT_ENC_IMAGES}>:-E${MCUBOOT_KEY_ENC}>
+        $<TARGET_FILE_DIR:tfm_s>/tfm_s.bin
+        ${CMAKE_CURRENT_BINARY_DIR}/tfm_s_signed.bin
+    COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/tfm_s_signed.bin $<TARGET_FILE_DIR:bl2>
+)
+
+if(NS)
+    set(FLASH_AREA_NUM 1)
+    configure_file(signing_layout.c.in signing_layout_ns.c @ONLY)
+
+    add_library(signing_layout_ns OBJECT ${CMAKE_CURRENT_BINARY_DIR}/signing_layout_ns.c)
+    target_compile_options(signing_layout_ns
+        PRIVATE
+            $<$<C_COMPILER_ID:GNU>:-E\;-xc>
+            $<$<C_COMPILER_ID:ARMClang>:-E\;-xc>
+            $<$<C_COMPILER_ID:IAR>:--preprocess=ns\;$<TARGET_OBJECTS:signing_layout_ns>>
+    )
+    target_compile_definitions(signing_layout_ns
+        PRIVATE
+            $<$<BOOL:${BL2}>:BL2>
+            $<$<BOOL:${MCUBOOT_IMAGE_NUMBER}>:MCUBOOT_IMAGE_NUMBER=${MCUBOOT_IMAGE_NUMBER}>
+    )
+    target_link_libraries(signing_layout_ns
+        PRIVATE
+            platform_bl2
+    )
+
+    add_custom_target(tfm_ns_signed_bin
+        SOURCES tfm_ns_signed.bin
+    )
+    add_custom_command(OUTPUT tfm_ns_signed.bin
+        DEPENDS $<TARGET_FILE_DIR:tfm_ns>/tfm_ns.bin
+        DEPENDS tfm_ns_bin signing_layout_ns
+        WORKING_DIRECTORY ${MCUBOOT_PATH}/scripts
+
+        #Sign non-secure binary image with provided secret key
+        COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/wrapper/wrapper.py
+            -v ${MCUBOOT_IMAGE_VERSION_NS}
+            --layout $<TARGET_OBJECTS:signing_layout_ns>
+            -k ${MCUBOOT_KEY_NS}
+            --public-key-format $<IF:$<BOOL:${MCUBOOT_HW_KEY}>,full,hash>
+            --align 1
+            --pad
+            --pad-header
+            -H 0x400
+            -s ${MCUBOOT_SECURITY_COUNTER_NS}
+            -d \"\(1, ${MCUBOOT_NS_IMAGE_MIN_VER}\)\"
+            $<TARGET_FILE_DIR:tfm_ns>/tfm_ns.bin
+            $<$<STREQUAL:${MCUBOOT_UPGRADE_STRATEGY},OVERWRITE_ONLY>:--overwrite-only>
+            $<$<BOOL:${MCUBOOT_ENC_IMAGES}>:-E${MCUBOOT_KEY_ENC}>
+            ${CMAKE_CURRENT_BINARY_DIR}/tfm_ns_signed.bin
+        COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/tfm_ns_signed.bin $<TARGET_FILE_DIR:bl2>
+    )
 endif()
 
-if(NOT DEFINED PLATFORM_CMAKE_FILE)
-	message (FATAL_ERROR "Platform specific CMake is not defined. Please set PLATFORM_CMAKE_FILE.")
-elseif(NOT EXISTS ${PLATFORM_CMAKE_FILE})
-	message (FATAL_ERROR "Platform specific CMake \"${PLATFORM_CMAKE_FILE}\" file does not exist. Please fix value of PLATFORM_CMAKE_FILE.")
-else()
-	include(${PLATFORM_CMAKE_FILE})
+if(NS)
+    add_custom_target(tfm_s_ns_signed_bin
+        ALL
+        SOURCES tfm_s_ns_signed.bin
+    )
+    if (MCUBOOT_IMAGE_NUMBER GREATER 1)
+        add_custom_command(OUTPUT tfm_s_ns_signed.bin
+            DEPENDS tfm_s_signed_bin $<TARGET_FILE_DIR:tfm_s>/tfm_s.bin
+            DEPENDS tfm_ns_signed_bin $<TARGET_FILE_DIR:tfm_ns>/tfm_ns.bin
+            DEPENDS signing_layout_s
+
+            # Create concatenated binary image from the two independently signed
+            # binary file. This only uses the local assemble.py script (not from
+            # upstream mcuboot) because that script is geared towards zephyr
+            # support
+            COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/assemble.py
+                --layout $<TARGET_OBJECTS:signing_layout_s>
+                -s $<TARGET_FILE_DIR:bl2>/tfm_s_signed.bin
+                -n $<TARGET_FILE_DIR:bl2>/tfm_ns_signed.bin
+                -o tfm_s_ns_signed.bin
+            COMMAND ${CMAKE_COMMAND} -E copy tfm_s_ns_signed.bin $<TARGET_FILE_DIR:bl2>
+        )
+    else()
+        add_custom_command(OUTPUT tfm_s_ns_signed.bin
+            DEPENDS tfm_s_ns_bin tfm_s_ns.bin
+            DEPENDS signing_layout_s
+
+        COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/wrapper/wrapper.py
+            -v ${MCUBOOT_IMAGE_VERSION_S}
+            --layout $<TARGET_OBJECTS:signing_layout_s>
+            -k ${MCUBOOT_KEY_S}
+            --public-key-format $<IF:$<BOOL:${MCUBOOT_HW_KEY}>,full,hash>
+            --align 1
+            --pad
+            --pad-header
+            -H 0x400
+            -s ${MCUBOOT_SECURITY_COUNTER_S}
+            -d \"\(0, ${MCUBOOT_S_IMAGE_MIN_VER}\)\"
+            -d \"\(1, ${MCUBOOT_NS_IMAGE_MIN_VER}\)\"
+            $<$<STREQUAL:${MCUBOOT_UPGRADE_STRATEGY},OVERWRITE_ONLY>:--overwrite-only>
+            $<$<BOOL:${MCUBOOT_ENC_IMAGES}>:-E${MCUBOOT_KEY_ENC}>
+            tfm_s_ns.bin
+            ${CMAKE_CURRENT_BINARY_DIR}/tfm_s_ns_signed.bin
+        COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/tfm_s_ns_signed.bin $<TARGET_FILE_DIR:bl2>
+        )
+    endif()
 endif()
 
-#Add platform specific definitions in SPE
-if (DEFINED TFM_PLATFORM_SECURE_DEFS)
-	embedded_set_target_compile_defines(TARGET ${PROJECT_NAME} LANGUAGE C DEFINES ${TFM_PLATFORM_SECURE_DEFS} APPEND)
-	embedded_set_target_compile_defines(TARGET ${PROJECT_NAME} LANGUAGE ASM DEFINES ${TFM_PLATFORM_SECURE_DEFS} APPEND)
-endif()
-
-if (DEFINED CMSE_FLAGS)
-	embedded_set_target_compile_flags(TARGET ${PROJECT_NAME} LANGUAGE C APPEND FLAGS ${CMSE_FLAGS})
-endif()
-
-#Append all our source files to global lists.
-list(APPEND ALL_SRC_C
-		"${TFM_ROOT_DIR}/bl2/ext/mcuboot/bl2_main.c"
-		"${TFM_ROOT_DIR}/bl2/ext/mcuboot/flash_map_extended.c"
-		"${TFM_ROOT_DIR}/bl2/ext/mcuboot/flash_map_legacy.c"
-		"${TFM_ROOT_DIR}/bl2/ext/mcuboot/keys.c"
-		"${TFM_ROOT_DIR}/bl2/src/flash_map.c"
-		"${TFM_ROOT_DIR}/bl2/src/security_cnt.c"
-		"${MCUBOOT_DIR}/bootutil/src/loader.c"
-		"${MCUBOOT_DIR}/bootutil/src/bootutil_misc.c"
-		"${MCUBOOT_DIR}/bootutil/src/image_validate.c"
-		"${MCUBOOT_DIR}/bootutil/src/image_rsa.c"
-		"${MCUBOOT_DIR}/bootutil/src/tlv.c"
-	)
-
-if (MCUBOOT_REPO STREQUAL "TF-M")
-	list(APPEND ALL_SRC_C
-			"${TFM_ROOT_DIR}/bl2/src/boot_record.c"
-		)
-else()
-	list(APPEND ALL_SRC_C
-			"${MCUBOOT_DIR}/bootutil/src/boot_record.c"
-			"${MCUBOOT_DIR}/bootutil/src/swap_scratch.c"
-			"${MCUBOOT_DIR}/bootutil/src/swap_move.c"
-			"${MCUBOOT_DIR}/bootutil/src/swap_misc.c"
-			"${MCUBOOT_DIR}/bootutil/src/encrypted.c"
-	)
-endif()
-
-#Define location of Mbed-Crypto(MbedTLS) source, build, and installation directory.
-set(MBEDTLS_CONFIG_FILE "config-rsa.h")
-set(MBEDTLS_CONFIG_PATH "${TFM_ROOT_DIR}/bl2/ext/mcuboot/include")
-
-get_filename_component(MBEDCRYPTO_SOURCE_DIR "${TFM_ROOT_DIR}/../mbedtls" ABSOLUTE)
-if(NOT EXISTS ${MBEDCRYPTO_SOURCE_DIR})
-    message(FATAL_ERROR "Missing mbed-crypto(mbedtls). Please clone the mbedtls repo to directory \"${MBEDCRYPTO_SOURCE_DIR}\".")
-endif()
-set (MBEDCRYPTO_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/mbed-crypto/build")
-set (MBEDCRYPTO_INSTALL_DIR ${MBEDCRYPTO_BINARY_DIR}/../install)
-
-if (CRYPTO_HW_ACCELERATOR OR CRYPTO_HW_ACCELERATOR_OTP_STATE STREQUAL "PROVISIONING")
-	if(NOT DEFINED CRYPTO_HW_ACCELERATOR_CMAKE_BUILD)
-		message(FATAL_ERROR "CRYPTO_HW_ACCELERATOR_CMAKE_BUILD not defined.")
-	endif()
-	include(${CRYPTO_HW_ACCELERATOR_CMAKE_BUILD})
-endif()
-
-if(MCUBOOT_SIGNATURE_TYPE STREQUAL "RSA-3072")
-	set(MCUBOOT_MBEDCRYPTO_SIGNATURE " -DMCUBOOT_SIGN_RSA_LEN=3072")
-elseif(MCUBOOT_SIGNATURE_TYPE STREQUAL "RSA-2048")
-	set(MCUBOOT_MBEDCRYPTO_SIGNATURE " -DMCUBOOT_SIGN_RSA_LEN=2048")
-else()
-	set(MCUBOOT_MBEDCRYPTO_SIGNATURE "")
-endif()
-
-string(APPEND MBEDCRYPTO_C_FLAGS_BL2 " ${MCUBOOT_MBEDCRYPTO_SIGNATURE} -I${MBEDTLS_CONFIG_PATH}")
-
-#Build Mbed Crypto as external project.
-#This ensures Mbed Crypto is built with exactly defined settings.
-#Mbed Crypto will be used from its install location
-string(APPEND MBEDCRYPTO_C_FLAGS " ${MBEDCRYPTO_C_FLAGS_BL2}")
-set(MBEDCRYPTO_TARGET_NAME "mbedcrypto_mcuboot_lib")
-include(${TFM_ROOT_DIR}/BuildMbedCrypto.cmake)
-
-#Setting include directories
-embedded_target_include_directories(TARGET ${PROJECT_NAME} PATH ${TFM_ROOT_DIR} ABSOLUTE APPEND)
-embedded_target_include_directories(TARGET ${PROJECT_NAME} PATH ${TFM_ROOT_DIR}/interface/include ABSOLUTE APPEND)
-embedded_target_include_directories(TARGET ${PROJECT_NAME} PATH ${TFM_ROOT_DIR}/bl2/include ABSOLUTE APPEND)
-embedded_target_include_directories(TARGET ${PROJECT_NAME} PATH ${TFM_ROOT_DIR}/bl2/ext/mcuboot/include ABSOLUTE APPEND)
-embedded_target_include_directories(TARGET ${PROJECT_NAME} PATH ${MCUBOOT_DIR}/bootutil/include ABSOLUTE APPEND)
-embedded_target_include_directories(TARGET ${PROJECT_NAME} PATH ${MBEDCRYPTO_INSTALL_DIR}/include ABSOLUTE APPEND)
-embedded_target_include_directories(TARGET ${PROJECT_NAME} PATH ${CMAKE_CURRENT_BINARY_DIR} ABSOLUTE APPEND)
-
-#Define linker file
-if(NOT DEFINED BL2_LINKER_CONFIG)
-	message(FATAL_ERROR "ERROR: Incomplete Configuration: BL2_LINKER_CONFIG is not defined.")
-endif()
-embedded_set_target_linker_file(TARGET ${PROJECT_NAME} PATH "${BL2_LINKER_CONFIG}")
-
-if(NOT DEFINED PLATFORM_LINK_INCLUDES)
-	message(FATAL_ERROR "ERROR: Incomplete Configuration: PLATFORM_LINK_INCLUDES is not defined.")
-endif()
-embedded_set_target_link_includes(TARGET ${PROJECT_NAME} INCLUDES "${PLATFORM_LINK_INCLUDES}")
-
-add_executable(${PROJECT_NAME} ${ALL_SRC_ASM} ${ALL_SRC_C_BL2} ${ALL_SRC_ASM_BL2} ${ALL_SRC_C} ${ALL_SRC_CXX})
-
-#Set common compiler and linker flags
-config_setting_shared_compiler_flags(${PROJECT_NAME})
-config_setting_shared_linker_flags(${PROJECT_NAME})
-
-#Add BL2 and MCUBOOT_IMAGE_NUMBER defines to linker to resolve symbols in region_defs.h and flash_layout.h
-embedded_set_target_link_defines(TARGET ${PROJECT_NAME} DEFINES "BL2" "MCUBOOT_IMAGE_NUMBER=${MCUBOOT_IMAGE_NUMBER}")
-
-if(NOT DEFINED TEST_FRAMEWORK_S)
-	message(FATAL_ERROR "Incomplete build configuration: TEST_FRAMEWORK_S is undefined.")
-elseif(TEST_FRAMEWORK_S)
-	embedded_set_target_link_defines(TARGET ${PROJECT_NAME} DEFINES "TEST_FRAMEWORK_S")
-endif()
-
-if(NOT DEFINED TEST_FRAMEWORK_NS)
-	message(FATAL_ERROR "Incomplete build configuration: TEST_FRAMEWORK_NS is undefined.")
-elseif(TEST_FRAMEWORK_NS)
-	embedded_set_target_link_defines(TARGET ${PROJECT_NAME} DEFINES "TEST_FRAMEWORK_NS")
-endif()
-
-#Link mbedcrypto library to project
-target_link_libraries(${PROJECT_NAME} "${MBEDCRYPTO_INSTALL_DIR}/lib/${CMAKE_STATIC_LIBRARY_PREFIX_C}mbedcrypto${CMAKE_STATIC_LIBRARY_SUFFIX_C}")
-add_dependencies(${PROJECT_NAME} ${MBEDCRYPTO_TARGET_NAME}_install)
-
-#Link crypto accelerator libraries if applicable
-if (CRYPTO_HW_ACCELERATOR OR CRYPTO_HW_ACCELERATOR_OTP_STATE STREQUAL "PROVISIONING")
-	if(NOT DEFINED CRYPTO_HW_ACCELERATOR_CMAKE_LINK)
-		message(FATAL_ERROR "CRYPTO_HW_ACCELERATOR_CMAKE_LINK not defined.")
-	endif()
-	include(${CRYPTO_HW_ACCELERATOR_CMAKE_LINK})
-endif()
-
-#Generate binary file from axf
-compiler_generate_binary_output(${PROJECT_NAME})
-
-#Generate intel hex file from axf
-compiler_generate_hex_output(${PROJECT_NAME})
-
-#Generate elf file from axf
-compiler_generate_elf_output(${PROJECT_NAME})
-
-message("- MCUBOOT_REPO: '${MCUBOOT_REPO}'.")
-message("- MCUBOOT_IMAGE_NUMBER: '${MCUBOOT_IMAGE_NUMBER}'.")
-message("- MCUBOOT_UPGRADE_STRATEGY: '${MCUBOOT_UPGRADE_STRATEGY}'.")
-message("- MCUBOOT_SIGNATURE_TYPE: '${MCUBOOT_SIGNATURE_TYPE}'.")
-message("- MCUBOOT_HW_KEY: '${MCUBOOT_HW_KEY}'.")
-message("- MCUBOOT_LOG_LEVEL: '${MCUBOOT_LOG_LEVEL}'.")
-
-get_property(_log_levels CACHE MCUBOOT_LOG_LEVEL PROPERTY STRINGS)
-list(FIND _log_levels ${MCUBOOT_LOG_LEVEL} LOG_LEVEL_ID)
-
-if (MCUBOOT_REPO STREQUAL "UPSTREAM")
-	set(MCUBOOT_HW_ROLLBACK_PROT On)
-	set(MCUBOOT_MEASURED_BOOT On)
-
-	#FixMe: This becomes unnecessary and can be deleted once the sign_key.c file
-	#in upstream MCUboot includes the mcuboot_config.h file and starts "reading"
-	#the configuration macros from there.
-	if (MCUBOOT_HW_KEY)
-		target_compile_definitions(${PROJECT_NAME} PRIVATE MCUBOOT_HW_KEY)
-	endif()
-endif()
-
-if(MCUBOOT_SIGNATURE_TYPE STREQUAL "RSA-3072")
-	set(MCUBOOT_SIGN_RSA On)
-	set(MCUBOOT_SIGN_RSA_LEN 3072)
-elseif(MCUBOOT_SIGNATURE_TYPE STREQUAL "RSA-2048")
-	set(MCUBOOT_SIGN_RSA On)
-	set(MCUBOOT_SIGN_RSA_LEN 2048)
-endif()
-
-if (${MCUBOOT_UPGRADE_STRATEGY} STREQUAL "OVERWRITE_ONLY")
-	set(MCUBOOT_OVERWRITE_ONLY On)
-elseif(${MCUBOOT_UPGRADE_STRATEGY} STREQUAL "NO_SWAP")
-	set(MCUBOOT_NO_SWAP On)
-elseif (${MCUBOOT_UPGRADE_STRATEGY} STREQUAL "RAM_LOADING")
-	set(MCUBOOT_RAM_LOADING On)
-endif()
-
-#FixMe: This becomes unnecessary and can be deleted once the sign_key.c file
-#in upstream MCUboot includes the mcuboot_config.h file and starts "reading"
-#the configuration macros from there.
-if (MCUBOOT_REPO STREQUAL "UPSTREAM" AND MCUBOOT_HW_KEY)
-	set(MCUBOOT_HW_KEY Off)
-	configure_file("${CMAKE_CURRENT_LIST_DIR}/include/mcuboot_config/mcuboot_config.h.in"
-				   "${CMAKE_CURRENT_BINARY_DIR}/mcuboot_config/mcuboot_config.h"
-				   @ONLY)
-	set(MCUBOOT_HW_KEY On)
-else()
-	configure_file("${CMAKE_CURRENT_LIST_DIR}/include/mcuboot_config/mcuboot_config.h.in"
-				   "${CMAKE_CURRENT_BINARY_DIR}/mcuboot_config/mcuboot_config.h"
-				   @ONLY)
-endif()
-
-target_compile_definitions(${PROJECT_NAME} PRIVATE MBEDTLS_CONFIG_FILE="${MBEDTLS_CONFIG_FILE}")
-
-if (NOT MCUBOOT_SIGNATURE_TYPE STREQUAL "RSA-3072" AND NOT MCUBOOT_SIGNATURE_TYPE STREQUAL "RSA-2048")
-	message(FATAL_ERROR "${MCUBOOT_SIGNATURE_TYPE} is not supported as firmware signing algorithm")
-endif()
-
-validate_cache_value(MCUBOOT_UPGRADE_STRATEGY)
-
-#Set install location. Keep original value to avoid overriding command line settings.
-if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
-	set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/install" CACHE PATH "Default install location for MCUBoot." FORCE)
-endif()
-
-#Collect executables to common location: build/install/outputs/
-install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.axf
-			  ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.bin
-			  ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.hex
-			  ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.elf
-		DESTINATION outputs/${TARGET_PLATFORM}/)
-
-install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.axf
-			  ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.bin
-			  ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.hex
-			  ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.elf
-		DESTINATION outputs/fvp/)
-
-#Finally let cmake system apply changes after the whole project is defined.
-embedded_project_end(${PROJECT_NAME})
+add_custom_target(signed_images
+    ALL
+    DEPENDS $<$<BOOL:${NS}>:tfm_s_ns_signed_bin>
+)
diff --git a/bl2/ext/mcuboot/MCUBoot.cmake b/bl2/ext/mcuboot/MCUBoot.cmake
deleted file mode 100644
index 915f684..0000000
--- a/bl2/ext/mcuboot/MCUBoot.cmake
+++ /dev/null
@@ -1,362 +0,0 @@
-#-------------------------------------------------------------------------------
-# Copyright (c) 2018-2020, Arm Limited. All rights reserved.
-#
-# SPDX-License-Identifier: BSD-3-Clause
-#
-#-------------------------------------------------------------------------------
-
-cmake_minimum_required(VERSION 3.7)
-
-function(mcuboot_create_boot_payload)
-	set( _OPTIONS_ARGS)										  #Option (on/off) arguments (e.g. IGNORE_CASE)
-	set( _ONE_VALUE_ARGS S_BIN NS_BIN FULL_BIN SIGN_BIN POSTFIX) #Single option arguments (e.g. PATH "./foo/bar")
-	set( _MULTI_VALUE_ARGS)									  #List arguments (e.g. LANGUAGES C ASM CXX)
-	cmake_parse_arguments(_MY_PARAMS "${_OPTIONS_ARGS}" "${_ONE_VALUE_ARGS}" "${_MULTI_VALUE_ARGS}" ${ARGN})
-
-	if (NOT DEFINED _MY_PARAMS_S_BIN)
-		message(FATAL_ERROR "mcuboot_create_boot_payload(): mandatory parameter 'S_BIN' missing.")
-	endif()
-
-	if (NOT DEFINED _MY_PARAMS_NS_BIN)
-		message(FATAL_ERROR "mcuboot_create_boot_payload(): mandatory parameter 'NS_BIN' missing.")
-	endif()
-
-	if (NOT DEFINED _MY_PARAMS_FULL_BIN)
-		message(FATAL_ERROR "mcuboot_create_boot_payload(): mandatory parameter 'FULL_BIN' missing.")
-	endif()
-
-	if (NOT DEFINED _MY_PARAMS_SIGN_BIN)
-		message(FATAL_ERROR "mcuboot_create_boot_payload(): mandatory parameter 'SIGN_BIN' missing.")
-	endif()
-
-	if (DEFINED _MY_PARAMS_POSTFIX)
-		if (${_MY_PARAMS_POSTFIX} STREQUAL "_1")
-			set(MY_POSTFIX "1")
-		else()
-			message(FATAL_ERROR "Unknown artefacts postfix: ${_MY_PARAMS_POSTFIX}")
-		endif()
-	endif()
-
-	#Find Python3.x interpreter
-	find_package(PythonInterp 3)
-	if (NOT PYTHONINTERP_FOUND)
-		message(FATAL_ERROR "Failed to find Python3.x interpreter. Pyhton3 must be installed and available on the PATH.")
-	endif()
-
-	if(NOT DEFINED FLASH_LAYOUT)
-		message(FATAL_ERROR "ERROR: Incomplete Configuration: FLASH_LAYOUT is not defined.")
-	endif()
-
-	if (MCUBOOT_SIGNATURE_TYPE STREQUAL "RSA-3072")
-		set(KEY_FILE    "${MCUBOOT_DIR}/root-rsa-3072.pem")
-		set(KEY_FILE_S  "${MCUBOOT_DIR}/root-rsa-3072.pem")
-		set(KEY_FILE_NS "${MCUBOOT_DIR}/root-rsa-3072_1.pem")
-	elseif(MCUBOOT_SIGNATURE_TYPE STREQUAL "RSA-2048")
-		set(KEY_FILE    "${MCUBOOT_DIR}/root-rsa-2048.pem")
-		set(KEY_FILE_S  "${MCUBOOT_DIR}/root-rsa-2048.pem")
-		set(KEY_FILE_NS "${MCUBOOT_DIR}/root-rsa-2048_1.pem")
-	else()
-		message(FATAL_ERROR "${MCUBOOT_SIGNATURE_TYPE} is not supported as firmware signing algorithm")
-	endif()
-
-	if(MCUBOOT_ENCRYPT_RSA)
-		set(ADD_ENCRYPTION "-E${TFM_ROOT_DIR}/../mcuboot/enc-rsa2048-pub.pem")
-	else()
-		set(ADD_ENCRYPTION "")
-	endif()
-
-	#Configure in which format (full or hash) include the public key to the image manifest
-	#
-	#|-----------------------|-----------------------|-------------------|--------------------|
-	#|                       |Key format in manifest |Key in MCUBoot code|     Key in HW      |
-	#|-----------------------|-----------------------|-------------------|--------------------|
-	#|MCUBOOT_HW_KEY ==  On  |    Full public key    |  No key embedded  | Hash of public key |
-	#|-----------------------|-----------------------|-------------------|--------------------|
-	#|MCUBOOT_HW_KEY ==  Off |   Hash of public key  |  Full public key  |   No key in HW     |
-	#|-----------------------|-----------------------|-------------------|--------------------|
-	if (MCUBOOT_HW_KEY)
-		set(PUBLIC_KEY_FORMAT "full")
-	else()
-		set(PUBLIC_KEY_FORMAT "hash")
-	endif()
-
-	set(PARTIAL_CONTENT_FOR_PREPROCESSING "#include \"${FLASH_LAYOUT}\"\n\n"
-		"/* Enumeration that is used by the assemble.py and imgtool.py scripts\n"
-		" * for correct binary generation when nested macros are used\n"
-		" */\n"
-		"enum image_attributes {\n"
-		"\tRE_SECURE_IMAGE_OFFSET = SECURE_IMAGE_OFFSET,\n"
-		"\tRE_SECURE_IMAGE_MAX_SIZE = SECURE_IMAGE_MAX_SIZE,\n"
-		"\tRE_NON_SECURE_IMAGE_OFFSET = NON_SECURE_IMAGE_OFFSET,\n"
-		"\tRE_NON_SECURE_IMAGE_MAX_SIZE = NON_SECURE_IMAGE_MAX_SIZE,\n"
-		"#ifdef IMAGE_LOAD_ADDRESS\n"
-		"\tRE_IMAGE_LOAD_ADDRESS = IMAGE_LOAD_ADDRESS,\n"
-		"#endif\n"
-	)
-
-if (MCUBOOT_IMAGE_NUMBER GREATER 1)
-	if (SECURITY_COUNTER_S)
-		set(ADD_SECURITY_COUNTER_S "-s ${SECURITY_COUNTER_S}")
-	else()
-		set(ADD_SECURITY_COUNTER_S "-sauto")
-	endif()
-	if (SECURITY_COUNTER_NS)
-		set(ADD_SECURITY_COUNTER_NS "-s ${SECURITY_COUNTER_NS}")
-	else()
-		set(ADD_SECURITY_COUNTER_NS "-sauto")
-	endif()
-	if (DEFINED SECURITY_COUNTER)
-		message(WARNING "In case of multiple updatable images the security counter value can be specified"
-			" for the Secure and Non-secure images separately with the SECURITY_COUNTER_S and SECURITY_COUNTER_NS"
-			" defines. The value of SECURITY_COUNTER was ignored.")
-		set(SECURITY_COUNTER "")
-	endif()
-
-	if (NOT IMAGE_VERSION_S)
-		set(IMAGE_VERSION_S 0.0.0+0)
-	endif()
-	if (NOT IMAGE_VERSION_NS)
-		set(IMAGE_VERSION_NS 0.0.0+0)
-	endif()
-	if (DEFINED IMAGE_VERSION)
-		message(WARNING "In case of multiple updatable images the image version can be specified"
-			" for the Secure and Non-secure images separately with the IMAGE_VERSION_S and IMAGE_VERSION_NS"
-			" defines. The value of IMAGE_VERSION was ignored.")
-		set(IMAGE_VERSION "")
-	endif()
-
-	if (S_IMAGE_MIN_VER)
-		set(ADD_S_IMAGE_MIN_VER "-d \"(0,${S_IMAGE_MIN_VER})\"")
-	else()
-		set(ADD_S_IMAGE_MIN_VER "")
-	endif()
-	if (NS_IMAGE_MIN_VER)
-		set(ADD_NS_IMAGE_MIN_VER "-d \"(1,${NS_IMAGE_MIN_VER})\"")
-	else()
-		set(ADD_NS_IMAGE_MIN_VER "")
-	endif()
-
-	if (${MCUBOOT_UPGRADE_STRATEGY} STREQUAL "OVERWRITE_ONLY")
-		set(OVERWRITE "--overwrite-only")
-	else()
-		set(OVERWRITE "")
-	endif()
-
-	set(FILE_TO_PREPROCESS ${CMAKE_BINARY_DIR}/image_macros_to_preprocess)
-	set(PREPROCESSED_FILE ${CMAKE_BINARY_DIR}/image_macros_preprocessed)
-
-	#Create files that will be preprocessed later in order to be able to handle
-	# nested macros in header files for certain macros
-	string(CONCAT CONTENT_FOR_PREPROCESSING ${PARTIAL_CONTENT_FOR_PREPROCESSING}
-			"\tRE_SIGN_BIN_SIZE = FLASH_AREA_0_SIZE,\n}\;")
-	file(WRITE ${FILE_TO_PREPROCESS}_s.c ${CONTENT_FOR_PREPROCESSING})
-	string(CONCAT CONTENT_FOR_PREPROCESSING ${PARTIAL_CONTENT_FOR_PREPROCESSING}
-			"\tRE_SIGN_BIN_SIZE = FLASH_AREA_1_SIZE,\n}\;")
-	file(WRITE ${FILE_TO_PREPROCESS}_ns.c ${CONTENT_FOR_PREPROCESSING})
-
-	#Preprocess the _s.c file that contains the secure image related macros
-	compiler_preprocess_file(SRC ${FILE_TO_PREPROCESS}_s.c
-							DST ${PREPROCESSED_FILE}_s.c
-							BEFORE_TARGET ${_MY_PARAMS_S_BIN}
-							TARGET_PREFIX ${_MY_PARAMS_S_BIN}
-							DEFINES "MCUBOOT_IMAGE_NUMBER=${MCUBOOT_IMAGE_NUMBER}")
-
-	#Preprocess the _ns.c file that contains the non-secure image related macros
-	compiler_preprocess_file(SRC ${FILE_TO_PREPROCESS}_ns.c
-							DST ${PREPROCESSED_FILE}_ns.c
-							BEFORE_TARGET ${_MY_PARAMS_NS_BIN}
-							TARGET_PREFIX ${_MY_PARAMS_NS_BIN}
-							DEFINES "MCUBOOT_IMAGE_NUMBER=${MCUBOOT_IMAGE_NUMBER}")
-
-	add_custom_command(TARGET ${_MY_PARAMS_NS_BIN}
-						POST_BUILD
-
-						#Sign secure binary image with default public key in mcuboot folder
-						COMMAND ${PYTHON_EXECUTABLE} ${MCUBOOT_DIR}/scripts/wrapper/wrapper.py
-						ARGS -k ${KEY_FILE_S}
-							 ${ADD_ENCRYPTION}
-							 --public-key-format ${PUBLIC_KEY_FORMAT}
-							 --align 1
-							 ${OVERWRITE}
-							 -v ${IMAGE_VERSION_S}
-							 ${ADD_NS_IMAGE_MIN_VER}
-							 ${ADD_SECURITY_COUNTER_S}
-							 -l ${PREPROCESSED_FILE}_s.c
-							 --pad
-							 --pad-header
-							 -H 0x400
-							 $<TARGET_FILE_DIR:${_MY_PARAMS_S_BIN}>/${_MY_PARAMS_S_BIN}.bin
-							 ${CMAKE_BINARY_DIR}/${_MY_PARAMS_S_BIN}_signed.bin
-
-						#Sign non-secure binary image with default public key in mcuboot folder
-						COMMAND ${PYTHON_EXECUTABLE} ${MCUBOOT_DIR}/scripts/wrapper/wrapper.py
-						ARGS -k ${KEY_FILE_NS}
-							 ${ADD_ENCRYPTION}
-							 --public-key-format ${PUBLIC_KEY_FORMAT}
-							 --align 1
-							 ${OVERWRITE}
-							 -v ${IMAGE_VERSION_NS}
-							 ${ADD_S_IMAGE_MIN_VER}
-							 ${ADD_SECURITY_COUNTER_NS}
-							 -l ${PREPROCESSED_FILE}_ns.c
-							 --pad
-							 --pad-header
-							 -H 0x400
-							 $<TARGET_FILE_DIR:${_MY_PARAMS_NS_BIN}>/${_MY_PARAMS_NS_BIN}.bin
-							 ${CMAKE_BINARY_DIR}/${_MY_PARAMS_NS_BIN}_signed.bin
-
-						#Create concatenated binary image from the two independently signed binary file
-						COMMAND ${PYTHON_EXECUTABLE} ${MCUBOOT_DIR}/scripts/assemble.py
-						ARGS --layout ${PREPROCESSED_FILE}_s.c
-							 -s ${CMAKE_BINARY_DIR}/${_MY_PARAMS_S_BIN}_signed.bin
-							 -n ${CMAKE_BINARY_DIR}/${_MY_PARAMS_NS_BIN}_signed.bin
-							 -o ${CMAKE_BINARY_DIR}/${_MY_PARAMS_SIGN_BIN}.bin)
-
-else() # MCUBOOT_IMAGE_NUMBER = 1
-	if (SECURITY_COUNTER)
-		set(ADD_SECURITY_COUNTER "-s ${SECURITY_COUNTER}")
-	else()
-		set(ADD_SECURITY_COUNTER "-sauto")
-	endif()
-	if (DEFINED SECURITY_COUNTER_S OR
-		DEFINED SECURITY_COUNTER_NS)
-		message(WARNING "In case of a single updatable image the security counter value can be specified with"
-			" the SECURITY_COUNTER define. The values of SECURITY_COUNTER_S and/or SECURITY_COUNTER_NS were ignored.")
-		set(SECURITY_COUNTER_S "")
-		set(SECURITY_COUNTER_NS "")
-	endif()
-
-	if (NOT IMAGE_VERSION)
-		set(IMAGE_VERSION 0.0.0+0)
-	endif()
-	if (DEFINED IMAGE_VERSION_S OR
-		DEFINED IMAGE_VERSION_NS)
-		message(WARNING "In case of a single updatable image the image version can be specified with"
-			" the IMAGE_VERSION define. The values of IMAGE_VERSION_S and/or IMAGE_VERSION_NS were ignored.")
-		set(IMAGE_VERSION_S "")
-		set(IMAGE_VERSION_NS "")
-	endif()
-
-	if (DEFINED S_IMAGE_MIN_VER OR
-		DEFINED NS_IMAGE_MIN_VER)
-		message(WARNING "WARNING: In case of a single updatable image a dependency cannot be specified between"
-			" the S and NS images. The S_IMAGE_MIN_VER and/or NS_IMAGE_MIN_VER defines were ignored.")
-		set(S_IMAGE_MIN_VER "")
-		set(NS_IMAGE_MIN_VER "")
-	endif()
-
-	set(FILE_TO_PREPROCESS ${CMAKE_BINARY_DIR}/image_macros_to_preprocess.c)
-	set(PREPROCESSED_FILE ${CMAKE_BINARY_DIR}/image_macros_preprocessed.c)
-	string(CONCAT CONTENT_FOR_PREPROCESSING ${PARTIAL_CONTENT_FOR_PREPROCESSING}
-			"\tRE_SIGN_BIN_SIZE = FLASH_AREA_0_SIZE,\n}\;")
-
-	#Create a file that will be preprocessed later in order to be able to handle nested macros
-	#in header files for certain macros
-	file(WRITE ${FILE_TO_PREPROCESS} ${CONTENT_FOR_PREPROCESSING})
-
-	#Preprocess the .c file that contains the image related macros
-	compiler_preprocess_file(SRC ${FILE_TO_PREPROCESS}
-							DST ${PREPROCESSED_FILE}
-							BEFORE_TARGET ${_MY_PARAMS_NS_BIN}
-							TARGET_PREFIX ${_MY_PARAMS_NS_BIN}
-							DEFINES "MCUBOOT_IMAGE_NUMBER=${MCUBOOT_IMAGE_NUMBER}")
-
-	add_custom_command(TARGET ${_MY_PARAMS_NS_BIN}
-						POST_BUILD
-						#Create concatenated binary image from the two binary file
-						COMMAND ${PYTHON_EXECUTABLE} ${MCUBOOT_DIR}/scripts/assemble.py
-						ARGS --layout ${PREPROCESSED_FILE}
-							 -s $<TARGET_FILE_DIR:${_MY_PARAMS_S_BIN}>/${_MY_PARAMS_S_BIN}.bin
-							 -n $<TARGET_FILE_DIR:${_MY_PARAMS_NS_BIN}>/${_MY_PARAMS_NS_BIN}.bin
-							 -o ${CMAKE_BINARY_DIR}/${_MY_PARAMS_FULL_BIN}.bin
-
-						#Sign concatenated binary image with default public key in mcuboot folder
-						COMMAND ${PYTHON_EXECUTABLE} ${MCUBOOT_DIR}/scripts/wrapper/wrapper.py
-						ARGS -k ${KEY_FILE}
-							 ${ADD_ENCRYPTION}
-							 --public-key-format ${PUBLIC_KEY_FORMAT}
-							 --align 1
-							 ${OVERWRITE}
-							 -v ${IMAGE_VERSION}
-							 ${ADD_SECURITY_COUNTER}
-							 -l ${PREPROCESSED_FILE}
-							 --pad
-							 --pad-header
-							 -H 0x400
-							 ${CMAKE_BINARY_DIR}/${_MY_PARAMS_FULL_BIN}.bin
-							 ${CMAKE_BINARY_DIR}/${_MY_PARAMS_SIGN_BIN}.bin)
-
-endif()
-
-	#Collect executables to common location: build/install/outputs/
-	set(TFM_SIGN_NAME tfm_s_ns_signed)
-
-	if (DEFINED MY_POSTFIX)
-		install(FILES  ${CMAKE_BINARY_DIR}/${_MY_PARAMS_SIGN_BIN}.bin
-				RENAME tfm_sig${MY_POSTFIX}.bin
-				DESTINATION outputs/${TARGET_PLATFORM}/)
-	else()
-		install(FILES ${CMAKE_BINARY_DIR}/${_MY_PARAMS_SIGN_BIN}.bin
-				DESTINATION outputs/${TARGET_PLATFORM}/)
-	endif()
-
-	install(FILES  ${CMAKE_BINARY_DIR}/${_MY_PARAMS_SIGN_BIN}.bin
-			RENAME ${TFM_SIGN_NAME}${_MY_PARAMS_POSTFIX}.bin
-			DESTINATION outputs/fvp/)
-
-if (MCUBOOT_IMAGE_NUMBER GREATER 1)
-	install(FILES ${CMAKE_BINARY_DIR}/${_MY_PARAMS_S_BIN}_signed.bin
-			${CMAKE_BINARY_DIR}/${_MY_PARAMS_NS_BIN}_signed.bin
-			DESTINATION outputs/${TARGET_PLATFORM}/)
-	install(FILES ${CMAKE_BINARY_DIR}/${_MY_PARAMS_S_BIN}_signed.bin
-			${CMAKE_BINARY_DIR}/${_MY_PARAMS_NS_BIN}_signed.bin
-			DESTINATION outputs/fvp/)
-
-else() # MCUBOOT_IMAGE_NUMBER = 1
-	set(TFM_FULL_NAME tfm_s_ns_concatenated)
-
-	install(FILES  ${CMAKE_BINARY_DIR}/${_MY_PARAMS_FULL_BIN}.bin
-			DESTINATION outputs/${TARGET_PLATFORM}/)
-	install(FILES  ${CMAKE_BINARY_DIR}/${_MY_PARAMS_FULL_BIN}.bin
-			RENAME ${TFM_FULL_NAME}${_MY_PARAMS_POSTFIX}.bin
-			DESTINATION outputs/fvp/)
-endif()
-endfunction()
-
-#Validate and override the upgrade strategy to be used by the bootloader.
-#
-# If the given upgrade strategy is not supported with the current value
-# of the MCUBOOT_IMAGE_NUMBER variable then the function will override its
-# previously set value.
-#
-#Examples:
-#  mcuboot_override_upgrade_strategy("SWAP")
-#
-#INPUTS:
-#  strategy - (mandatory) - Upgrade strategy to be used.
-#
-#OUTPUTS:
-#  MCUBOOT_UPGRADE_STRATEGY variable is set to the new strategy.
-#
-function(mcuboot_override_upgrade_strategy strategy)
-	if ((${strategy} STREQUAL "NO_SWAP" OR
-		 ${strategy} STREQUAL "RAM_LOADING") AND
-		NOT (MCUBOOT_IMAGE_NUMBER EQUAL 1))
-		message(WARNING "The number of separately updatable images with the NO_SWAP or the RAM_LOADING"
-			" upgrade strategy can be only '1'. Your choice was overriden.")
-		set(MCUBOOT_IMAGE_NUMBER 1 PARENT_SCOPE)
-	endif()
-	get_property(_validation_list CACHE MCUBOOT_UPGRADE_STRATEGY PROPERTY STRINGS)
-	#Check if validation list is set.
-	if (NOT _validation_list)
-		#Set the default upgrade strategy if the CACHE variable has not been set yet.
-		set(MCUBOOT_UPGRADE_STRATEGY "OVERWRITE_ONLY" CACHE STRING "Configure BL2 which upgrade strategy to use")
-		if (MCUBOOT_REPO STREQUAL "TF-M")
-			set_property(CACHE MCUBOOT_UPGRADE_STRATEGY PROPERTY STRINGS "OVERWRITE_ONLY;SWAP;NO_SWAP;RAM_LOADING")
-		else()
-			set_property(CACHE MCUBOOT_UPGRADE_STRATEGY PROPERTY STRINGS "OVERWRITE_ONLY;SWAP")
-		endif()
-	endif()
-	set(MCUBOOT_UPGRADE_STRATEGY ${strategy} PARENT_SCOPE)
-	validate_cache_value(MCUBOOT_UPGRADE_STRATEGY STRINGS)
-endfunction()
diff --git a/bl2/ext/mcuboot/MCUBootConfig.cmake b/bl2/ext/mcuboot/MCUBootConfig.cmake
deleted file mode 100644
index e77728e..0000000
--- a/bl2/ext/mcuboot/MCUBootConfig.cmake
+++ /dev/null
@@ -1,117 +0,0 @@
-#-------------------------------------------------------------------------------
-# Copyright (c) 2019-2020, Arm Limited. All rights reserved.
-#
-# SPDX-License-Identifier: BSD-3-Clause
-#
-#-------------------------------------------------------------------------------
-
-#Include BL2 bootloader related functions
-include("${CMAKE_CURRENT_LIST_DIR}/MCUBoot.cmake")
-
-set(BL2 True CACHE BOOL "Configure TF-M to use BL2 and enable building BL2")
-
-if (BL2)
-	add_definitions(-DBL2)
-
-	set(MCUBOOT_REPO "UPSTREAM" CACHE STRING "Configure which repository use the MCUBoot from")
-	set_property(CACHE MCUBOOT_REPO PROPERTY STRINGS "TF-M;UPSTREAM")
-	validate_cache_value(MCUBOOT_REPO)
-
-	set(MCUBOOT_IMAGE_NUMBER 2 CACHE STRING "Configure the number of separately updatable firmware images")
-	set_property(CACHE MCUBOOT_IMAGE_NUMBER PROPERTY STRINGS "1;2")
-	validate_cache_value(MCUBOOT_IMAGE_NUMBER STRINGS)
-
-	set(MCUBOOT_UPGRADE_STRATEGY "OVERWRITE_ONLY" CACHE STRING "Configure BL2 which upgrade strategy to use")
-	set_property(CACHE MCUBOOT_UPGRADE_STRATEGY PROPERTY STRINGS "OVERWRITE_ONLY;SWAP;NO_SWAP;RAM_LOADING")
-	validate_cache_value(MCUBOOT_UPGRADE_STRATEGY)
-
-	set(MCUBOOT_SIGNATURE_TYPE "RSA-3072" CACHE STRING "Algorithm used by MCUBoot to validate signatures.")
-	set_property(CACHE MCUBOOT_SIGNATURE_TYPE PROPERTY STRINGS "RSA-3072;RSA-2048")
-	validate_cache_value(MCUBOOT_SIGNATURE_TYPE)
-
-	#FixMe: These checks can be removed when the upgrade strategies in question are upstreamed to the original MCUBoot repo.
-	if (TARGET_PLATFORM STREQUAL "MUSCA_A" OR TARGET_PLATFORM STREQUAL "AN524")
-		if (MCUBOOT_REPO STREQUAL "UPSTREAM")
-		    message(WARNING "The 'UPSTREAM' MCUBoot repository cannot be used when building for ${TARGET_PLATFORM}. Your choice was overridden.")
-		endif()
-		set(MCUBOOT_REPO "TF-M")
-	endif()
-
-	set(MCUBOOT_HW_KEY On CACHE BOOL "Configure to use HW key for image verification. Otherwise key is embedded in MCUBoot image.")
-
-	set(MCUBOOT_ENCRYPT_RSA Off CACHE BOOL "Add encrypted image support to BL2. Also encrypts the signed images.")
-
-	set(MCUBOOT_LOG_LEVEL "LOG_LEVEL_INFO" CACHE STRING "Configure the level of logging in MCUBoot.")
-	set_property(CACHE MCUBOOT_LOG_LEVEL PROPERTY STRINGS "LOG_LEVEL_OFF;LOG_LEVEL_ERROR;LOG_LEVEL_WARNING;LOG_LEVEL_INFO;LOG_LEVEL_DEBUG")
-	if (NOT CMAKE_BUILD_TYPE STREQUAL "debug")
-		set(MCUBOOT_LOG_LEVEL "LOG_LEVEL_OFF")
-	endif()
-
-	validate_cache_value(MCUBOOT_LOG_LEVEL)
-
-	if ((${MCUBOOT_UPGRADE_STRATEGY} STREQUAL "NO_SWAP" OR
-		 ${MCUBOOT_UPGRADE_STRATEGY} STREQUAL "RAM_LOADING") AND
-		NOT (MCUBOOT_IMAGE_NUMBER EQUAL 1))
-		message(WARNING "The number of separately updatable images with the NO_SWAP or the RAM_LOADING"
-			" upgrade strategy can be only '1'. Your choice was overriden.")
-		set(MCUBOOT_IMAGE_NUMBER 1)
-	endif()
-
-	if (MCUBOOT_REPO STREQUAL "UPSTREAM")
-		if(MCUBOOT_ENCRYPT_RSA)
-			set(MCUBOOT_ENC_IMAGES On)
-		endif()
-
-		set_property(CACHE MCUBOOT_UPGRADE_STRATEGY PROPERTY STRINGS "OVERWRITE_ONLY;SWAP")
-		if (${MCUBOOT_UPGRADE_STRATEGY} STREQUAL "NO_SWAP" OR
-			${MCUBOOT_UPGRADE_STRATEGY} STREQUAL "RAM_LOADING")
-			message(WARNING "The ${MCUBOOT_UPGRADE_STRATEGY} upgrade strategy cannot be used when building against"
-				" upstream MCUBoot. Your choice was overriden.")
-			mcuboot_override_upgrade_strategy("OVERWRITE_ONLY")
-		endif()
-	elseif (MCUBOOT_REPO STREQUAL "TF-M")
-		if (MCUBOOT_ENCRYPT_RSA)
-			set(MCUBOOT_ENCRYPT_RSA Off)
-			message(WARNING "BL2 encryption cannot be used when building against the TF-M MCUBoot fork. Your choice was overridden.")
-		endif()
-	endif()
-
-else() #BL2 is turned off
-
-	if (DEFINED MCUBOOT_IMAGE_NUMBER OR
-		DEFINED MCUBOOT_UPGRADE_STRATEGY OR
-		DEFINED MCUBOOT_SIGNATURE_TYPE OR
-		DEFINED MCUBOOT_HW_KEY OR
-		DEFINED MCUBOOT_LOG_LEVEL)
-			message(WARNING "Ignoring the values of MCUBOOT_* variables as BL2 option is set to False.")
-			set(MCUBOOT_IMAGE_NUMBER "")
-			set(MCUBOOT_UPGRADE_STRATEGY "")
-			set(MCUBOOT_SIGNATURE_TYPE "")
-			set(MCUBOOT_HW_KEY "")
-			set(MCUBOOT_LOG_LEVEL "")
-	endif()
-
-	if (DEFINED SECURITY_COUNTER OR
-		DEFINED SECURITY_COUNTER_S OR
-		DEFINED SECURITY_COUNTER_NS)
-			message(WARNING "Ignoring the values of SECURITY_COUNTER and/or SECURITY_COUNTER_* variables as BL2 option is set to False.")
-			set(SECURITY_COUNTER "")
-			set(SECURITY_COUNTER_S "")
-			set(SECURITY_COUNTER_NS "")
-	endif()
-
-	if (DEFINED IMAGE_VERSION OR
-		DEFINED IMAGE_VERSION_S OR
-		DEFINED IMAGE_VERSION_NS)
-			message(WARNING "Ignoring the values of IMAGE_VERSION and/or IMAGE_VERSION_* variables as BL2 option is set to False.")
-			set(IMAGE_VERSION "")
-			set(IMAGE_VERSION_S "")
-			set(IMAGE_VERSION_NS "")
-	endif()
-	if (DEFINED S_IMAGE_MIN_VER OR
-		DEFINED NS_IMAGE_MIN_VER)
-			message(WARNING "Ignoring the values of *_IMAGE_MIN_VER variables as BL2 option is set to False.")
-			set(S_IMAGE_MIN_VER "")
-			set(NS_IMAGE_MIN_VER "")
-	endif()
-endif()
diff --git a/bl2/ext/mcuboot/bl2_main.c b/bl2/ext/mcuboot/bl2_main.c
index c428d5e..7cbc9a5 100644
--- a/bl2/ext/mcuboot/bl2_main.c
+++ b/bl2/ext/mcuboot/bl2_main.c
@@ -26,7 +26,7 @@
 #include "bootutil/image.h"
 #include "bootutil/bootutil.h"
 #include "flash_map_backend/flash_map_backend.h"
-#include "boot_record.h"
+#include "bootutil/boot_record.h"
 #include "security_cnt.h"
 #include "boot_hal.h"
 #include "region.h"
diff --git a/bl2/ext/mcuboot/boot/bootutil/include/bootutil/boot_record.h b/bl2/ext/mcuboot/boot/bootutil/include/bootutil/boot_record.h
new file mode 100644
index 0000000..c39d752
--- /dev/null
+++ b/bl2/ext/mcuboot/boot/bootutil/include/bootutil/boot_record.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2018-2020, Arm Limited. All rights reserved.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ */
+
+#ifndef __BOOT_RECORD_H__
+#define __BOOT_RECORD_H__
+
+#include <stdint.h>
+#include <stddef.h>
+#include <limits.h>
+#include "bootutil/image.h"
+#include "flash_map/flash_map.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+ * \enum shared_data_err_t
+ *
+ * \brief Return values for adding data entry to shared memory area
+ */
+enum shared_memory_err_t {
+    SHARED_MEMORY_OK = 0,
+    SHARED_MEMORY_OVERFLOW = 1,
+    SHARED_MEMORY_OVERWRITE = 2,
+    SHARED_MEMORY_GEN_ERROR = 3,
+
+    /* This is used to force the maximum size */
+    TLV_TYPE_MAX = INT_MAX
+};
+
+/*!
+ * \enum boot_status_err_t
+ *
+ * \brief Return values for saving boot status information to shared memory area
+ */
+enum boot_status_err_t {
+    BOOT_STATUS_OK,
+    BOOT_STATUS_ERROR,
+};
+
+/*!
+ * \brief Add a data item to the shared data area between bootloader and
+ *        runtime SW
+ *
+ * \param[in] major_type  TLV major type, identify consumer
+ * \param[in] minor_type  TLV minor type, identify TLV type
+ * \param[in] size        length of added data
+ * \param[in] data        pointer to data
+ *
+ * \return Returns error code as specified in \ref shared_memory_err_t
+ */
+enum shared_memory_err_t
+boot_add_data_to_shared_area(uint8_t        major_type,
+                             uint16_t       minor_type,
+                             size_t         size,
+                             const uint8_t *data);
+
+/*!
+ * \brief Add an image's all boot status information to the shared data area
+ *        between bootloader and runtime SW
+ *
+ * \param[in]  sw_module  Identifier of the SW component
+ * \param[in]  hdr        Pointer to the image header stored in RAM
+ * \param[in]  fap        Pointer to the flash area where image is stored
+ *
+ * \return Returns error code as specified in \ref boot_status_err_t
+ */
+enum boot_status_err_t
+boot_save_boot_status(uint8_t sw_module,
+                      const struct image_header *hdr,
+                      const struct flash_area *fap);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BOOT_RECORD_H__ */
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil.h b/bl2/ext/mcuboot/boot/bootutil/include/bootutil/bootutil.h
similarity index 100%
rename from bl2/ext/mcuboot/bootutil/include/bootutil/bootutil.h
rename to bl2/ext/mcuboot/boot/bootutil/include/bootutil/bootutil.h
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil_log.h b/bl2/ext/mcuboot/boot/bootutil/include/bootutil/bootutil_log.h
similarity index 100%
rename from bl2/ext/mcuboot/bootutil/include/bootutil/bootutil_log.h
rename to bl2/ext/mcuboot/boot/bootutil/include/bootutil/bootutil_log.h
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil_test.h b/bl2/ext/mcuboot/boot/bootutil/include/bootutil/bootutil_test.h
similarity index 100%
rename from bl2/ext/mcuboot/bootutil/include/bootutil/bootutil_test.h
rename to bl2/ext/mcuboot/boot/bootutil/include/bootutil/bootutil_test.h
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/ignore.h b/bl2/ext/mcuboot/boot/bootutil/include/bootutil/ignore.h
similarity index 100%
rename from bl2/ext/mcuboot/bootutil/include/bootutil/ignore.h
rename to bl2/ext/mcuboot/boot/bootutil/include/bootutil/ignore.h
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/image.h b/bl2/ext/mcuboot/boot/bootutil/include/bootutil/image.h
similarity index 100%
rename from bl2/ext/mcuboot/bootutil/include/bootutil/image.h
rename to bl2/ext/mcuboot/boot/bootutil/include/bootutil/image.h
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/sha256.h b/bl2/ext/mcuboot/boot/bootutil/include/bootutil/sha256.h
similarity index 100%
rename from bl2/ext/mcuboot/bootutil/include/bootutil/sha256.h
rename to bl2/ext/mcuboot/boot/bootutil/include/bootutil/sha256.h
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/sign_key.h b/bl2/ext/mcuboot/boot/bootutil/include/bootutil/sign_key.h
similarity index 100%
rename from bl2/ext/mcuboot/bootutil/include/bootutil/sign_key.h
rename to bl2/ext/mcuboot/boot/bootutil/include/bootutil/sign_key.h
diff --git a/bl2/ext/mcuboot/boot/bootutil/src/boot_record.c b/bl2/ext/mcuboot/boot/bootutil/src/boot_record.c
new file mode 100644
index 0000000..534b9d8
--- /dev/null
+++ b/bl2/ext/mcuboot/boot/bootutil/src/boot_record.c
@@ -0,0 +1,229 @@
+/*
+ * Copyright (c) 2018-2020, Arm Limited. All rights reserved.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ */
+
+#include "mcuboot_config/mcuboot_config.h"
+#include "bootutil/boot_record.h"
+#include "region_defs.h"
+#include "tfm_boot_status.h"
+#include "target.h"
+#include "bootutil_priv.h"
+#include "bootutil/image.h"
+#include "bootutil/sha256.h"
+#include "flash_map/flash_map.h"
+#include <stdint.h>
+#include <string.h>
+#include <stdio.h>
+
+#define SHA256_HASH_SIZE    (32u)
+#if defined(MCUBOOT_SIGN_RSA) && defined(MCUBOOT_HW_KEY)
+#   define SIG_BUF_SIZE     (MCUBOOT_SIGN_RSA_LEN / 8)
+#endif
+
+/*!
+ * \var shared_memory_init_done
+ *
+ * \brief Indicates whether shared memory area was already initialized.
+ *
+ */
+static uint32_t shared_memory_init_done;
+
+/*!
+ * \def SHARED_MEMORY_UNINITIALZED
+ *
+ * \brief Indicates that shared memory is uninitialized.
+ */
+#define SHARED_MEMORY_UNINITIALZED (0u)
+
+/*!
+ * \def SHARED_MEMORY_INITIALZED
+ *
+ * \brief Indicates that shared memory was already initialized.
+ */
+#define SHARED_MEMORY_INITIALZED   (1u)
+
+/* Compile time check to verify that shared data region is not overlapping with
+ * non-secure data area.
+ */
+#if ((BOOT_TFM_SHARED_DATA_BASE  >= NS_DATA_START && \
+      BOOT_TFM_SHARED_DATA_BASE  <= NS_DATA_LIMIT) || \
+     (BOOT_TFM_SHARED_DATA_LIMIT >= NS_DATA_START && \
+      BOOT_TFM_SHARED_DATA_LIMIT <= NS_DATA_LIMIT))
+#error "Shared data area and non-secure data area is overlapping"
+#endif
+
+/* See in boot_record.h */
+enum shared_memory_err_t
+boot_add_data_to_shared_area(uint8_t        major_type,
+                             uint16_t       minor_type,
+                             size_t         size,
+                             const uint8_t *data)
+{
+    struct shared_data_tlv_entry tlv_entry = {0};
+    struct tfm_boot_data *boot_data;
+    uint8_t *next_tlv;
+    uint16_t boot_data_size;
+    uintptr_t tlv_end, offset;
+
+    boot_data = (struct tfm_boot_data *)BOOT_TFM_SHARED_DATA_BASE;
+
+    /* Check whether first time to call this function. If does then initialise
+     * shared data area.
+     */
+    if (shared_memory_init_done == SHARED_MEMORY_UNINITIALZED) {
+        memset((void *)BOOT_TFM_SHARED_DATA_BASE, 0, BOOT_TFM_SHARED_DATA_SIZE);
+        boot_data->header.tlv_magic   = SHARED_DATA_TLV_INFO_MAGIC;
+        boot_data->header.tlv_tot_len = SHARED_DATA_HEADER_SIZE;
+        shared_memory_init_done = SHARED_MEMORY_INITIALZED;
+    }
+
+    /* Check whether TLV entry is already added.
+     * Get the boundaries of TLV section
+     */
+    tlv_end = BOOT_TFM_SHARED_DATA_BASE + boot_data->header.tlv_tot_len;
+    offset  = BOOT_TFM_SHARED_DATA_BASE + SHARED_DATA_HEADER_SIZE;
+
+    /* Iterates over the TLV section looks for the same entry if found then
+     * returns with error: SHARED_MEMORY_OVERWRITE
+     */
+    for (; offset < tlv_end; offset += tlv_entry.tlv_len) {
+        /* Create local copy to avoid unaligned access */
+        memcpy(&tlv_entry, (const void *)offset, SHARED_DATA_ENTRY_HEADER_SIZE);
+        if (GET_MAJOR(tlv_entry.tlv_type) == major_type &&
+            GET_MINOR(tlv_entry.tlv_type) == minor_type) {
+            return SHARED_MEMORY_OVERWRITE;
+        }
+    }
+
+    /* Add TLV entry */
+    tlv_entry.tlv_type = SET_TLV_TYPE(major_type, minor_type);
+    tlv_entry.tlv_len  = SHARED_DATA_ENTRY_SIZE(size);
+
+    if (!boot_u16_safe_add(&boot_data_size, boot_data->header.tlv_tot_len,
+                           tlv_entry.tlv_len)) {
+        return SHARED_MEMORY_GEN_ERROR;
+    }
+
+    /* Verify overflow of shared area */
+    if (boot_data_size > BOOT_TFM_SHARED_DATA_SIZE) {
+        return SHARED_MEMORY_OVERFLOW;
+    }
+
+    next_tlv = (uint8_t *)boot_data + boot_data->header.tlv_tot_len;
+    memcpy(next_tlv, &tlv_entry, SHARED_DATA_ENTRY_HEADER_SIZE);
+
+    next_tlv += SHARED_DATA_ENTRY_HEADER_SIZE;
+    memcpy(next_tlv, data, size);
+
+    boot_data->header.tlv_tot_len += tlv_entry.tlv_len;
+
+    return SHARED_MEMORY_OK;
+}
+
+/* See in boot_record.h */
+enum boot_status_err_t
+boot_save_boot_status(uint8_t sw_module,
+                      const struct image_header *hdr,
+                      const struct flash_area *fap)
+{
+    struct image_tlv_iter it;
+    uint32_t offset;
+    uint16_t len;
+    uint8_t type;
+    size_t record_len = 0;
+    uint8_t image_hash[32]; /* SHA256 - 32 Bytes */
+    uint8_t buf[MAX_BOOT_RECORD_SZ];
+    uint32_t boot_record_found = 0;
+    uint32_t hash_found = 0;
+    uint16_t ias_minor;
+    int32_t res;
+    enum shared_memory_err_t res2;
+
+    /* Manifest data is concatenated to the end of the image.
+     * It is encoded in TLV format.
+     */
+
+    res = bootutil_tlv_iter_begin(&it, hdr, fap, IMAGE_TLV_ANY, false);
+    if (res) {
+        return BOOT_STATUS_ERROR;
+    }
+
+    /* Traverse through the TLV area to find the boot record
+     * and image hash TLVs.
+     */
+    while (true) {
+        res = bootutil_tlv_iter_next(&it, &offset, &len, &type);
+        if (res < 0) {
+            return BOOT_STATUS_ERROR;
+        } else if (res > 0) {
+            break;
+        }
+
+        if (type == IMAGE_TLV_BOOT_RECORD) {
+            if (len > sizeof(buf)) {
+                return BOOT_STATUS_ERROR;
+            }
+            res = LOAD_IMAGE_DATA(hdr, fap, offset, buf, len);
+            if (res) {
+                return BOOT_STATUS_ERROR;
+            }
+
+            record_len = len;
+            boot_record_found = 1;
+
+        } else if (type == IMAGE_TLV_SHA256) {
+            /* Get the image's hash value from the manifest section. */
+            if (len > sizeof(image_hash)) {
+                return BOOT_STATUS_ERROR;
+            }
+            res = LOAD_IMAGE_DATA(hdr, fap, offset, image_hash, len);
+            if (res) {
+                return BOOT_STATUS_ERROR;
+            }
+
+            hash_found = 1;
+
+            /* The boot record TLV is part of the protected TLV area which is
+             * located before the other parts of the TLV area (including the
+             * image hash) so at this point it is okay to break the loop
+             * as the boot record TLV should have already been found.
+             */
+            break;
+        }
+    }
+
+
+    if (!boot_record_found || !hash_found) {
+        return BOOT_STATUS_ERROR;
+    }
+
+    /* Update the measurement value (hash of the image) data item in the
+     * boot record. It is always the last item in the structure to make
+     * it easy to calculate its position.
+     * The image hash is computed over the image header, the image itself and
+     * the protected TLV area (which should already include the image hash as
+     * part of the boot record TLV). For this reason this field has been
+     * filled with zeros during the image signing process.
+     */
+    offset = record_len - sizeof(image_hash);
+    /* Avoid buffer overflow. */
+    if ((offset + sizeof(image_hash)) > sizeof(buf)) {
+        return BOOT_STATUS_ERROR;
+    }
+    memcpy(buf + offset, image_hash, sizeof(image_hash));
+
+    /* Add the CBOR encoded boot record to the shared data area. */
+    ias_minor = SET_IAS_MINOR(sw_module, SW_BOOT_RECORD);
+    res2 = boot_add_data_to_shared_area(TLV_MAJOR_IAS,
+                                        ias_minor,
+                                        record_len,
+                                        buf);
+    if (res2) {
+        return BOOT_STATUS_ERROR;
+    }
+
+    return BOOT_STATUS_OK;
+}
diff --git a/bl2/ext/mcuboot/bootutil/src/bootutil_misc.c b/bl2/ext/mcuboot/boot/bootutil/src/bootutil_misc.c
similarity index 100%
rename from bl2/ext/mcuboot/bootutil/src/bootutil_misc.c
rename to bl2/ext/mcuboot/boot/bootutil/src/bootutil_misc.c
diff --git a/bl2/ext/mcuboot/bootutil/src/bootutil_priv.h b/bl2/ext/mcuboot/boot/bootutil/src/bootutil_priv.h
similarity index 100%
rename from bl2/ext/mcuboot/bootutil/src/bootutil_priv.h
rename to bl2/ext/mcuboot/boot/bootutil/src/bootutil_priv.h
diff --git a/bl2/ext/mcuboot/bootutil/src/image_rsa.c b/bl2/ext/mcuboot/boot/bootutil/src/image_rsa.c
similarity index 100%
rename from bl2/ext/mcuboot/bootutil/src/image_rsa.c
rename to bl2/ext/mcuboot/boot/bootutil/src/image_rsa.c
diff --git a/bl2/ext/mcuboot/bootutil/src/image_validate.c b/bl2/ext/mcuboot/boot/bootutil/src/image_validate.c
similarity index 99%
rename from bl2/ext/mcuboot/bootutil/src/image_validate.c
rename to bl2/ext/mcuboot/boot/bootutil/src/image_validate.c
index efcf123..e5414b7 100644
--- a/bl2/ext/mcuboot/bootutil/src/image_validate.c
+++ b/bl2/ext/mcuboot/boot/bootutil/src/image_validate.c
@@ -46,7 +46,7 @@
 #include "bootutil_priv.h"
 
 #ifdef MCUBOOT_HW_KEY
-#include "platform/include/tfm_plat_crypto_keys.h"
+#include "tfm_plat_crypto_keys.h"
 #endif
 
 /*
diff --git a/bl2/ext/mcuboot/bootutil/src/loader.c b/bl2/ext/mcuboot/boot/bootutil/src/loader.c
similarity index 99%
rename from bl2/ext/mcuboot/bootutil/src/loader.c
rename to bl2/ext/mcuboot/boot/bootutil/src/loader.c
index 956d066..a3fea2e 100644
--- a/bl2/ext/mcuboot/bootutil/src/loader.c
+++ b/bl2/ext/mcuboot/boot/bootutil/src/loader.c
@@ -42,8 +42,8 @@
 #include "bootutil/image.h"
 #include "bootutil_priv.h"
 #include "bootutil/bootutil_log.h"
-#include "bl2/include/tfm_boot_status.h"
-#include "bl2/include/boot_record.h"
+#include "tfm_boot_status.h"
+#include "bootutil/boot_record.h"
 #include "security_cnt.h"
 #include "mcuboot_config/mcuboot_config.h"
 
diff --git a/bl2/ext/mcuboot/bootutil/src/tlv.c b/bl2/ext/mcuboot/boot/bootutil/src/tlv.c
similarity index 100%
rename from bl2/ext/mcuboot/bootutil/src/tlv.c
rename to bl2/ext/mcuboot/boot/bootutil/src/tlv.c
diff --git a/bl2/ext/mcuboot/include/mcuboot_config/mcuboot_config.h.in b/bl2/ext/mcuboot/include/mcuboot_config/mcuboot_config.h.in
index 49f07dd..3a5ccf1 100644
--- a/bl2/ext/mcuboot/include/mcuboot_config/mcuboot_config.h.in
+++ b/bl2/ext/mcuboot/include/mcuboot_config/mcuboot_config.h.in
@@ -33,20 +33,6 @@
 #define MCUBOOT_USE_FLASH_AREA_GET_SECTORS
 #define MCUBOOT_TARGET_CONFIG "flash_layout.h"
 
-/*
- * Signature types
- */
-#cmakedefine MCUBOOT_SIGN_RSA
-#cmakedefine MCUBOOT_SIGN_RSA_LEN @MCUBOOT_SIGN_RSA_LEN@
-
-/*
- * Upgrade mode
- */
-#cmakedefine MCUBOOT_OVERWRITE_ONLY
-#cmakedefine MCUBOOT_NO_SWAP
-#cmakedefine MCUBOOT_RAM_LOADING
-
-#cmakedefine MCUBOOT_HW_KEY
 #cmakedefine MCUBOOT_HW_ROLLBACK_PROT
 #cmakedefine MCUBOOT_MEASURED_BOOT
 
diff --git a/bl2/ext/mcuboot/keys.c b/bl2/ext/mcuboot/keys.c
index a12ef63..ed7665b 100644
--- a/bl2/ext/mcuboot/keys.c
+++ b/bl2/ext/mcuboot/keys.c
@@ -27,7 +27,7 @@
 #include <stddef.h>
 #include <bootutil/sign_key.h>
 #include "mcuboot_config/mcuboot_config.h"
-#include "platform/include/tfm_plat_crypto_keys.h"
+#include "tfm_plat_crypto_keys.h"
 
 #ifdef MCUBOOT_ENC_IMAGES
 unsigned char enc_priv_key[] = {
diff --git a/bl2/ext/mcuboot/root-rsa-2048.pem b/bl2/ext/mcuboot/root-RSA-2048.pem
similarity index 100%
rename from bl2/ext/mcuboot/root-rsa-2048.pem
rename to bl2/ext/mcuboot/root-RSA-2048.pem
diff --git a/bl2/ext/mcuboot/root-rsa-2048_1.pem b/bl2/ext/mcuboot/root-RSA-2048_1.pem
similarity index 100%
rename from bl2/ext/mcuboot/root-rsa-2048_1.pem
rename to bl2/ext/mcuboot/root-RSA-2048_1.pem
diff --git a/bl2/ext/mcuboot/root-rsa-3072.pem b/bl2/ext/mcuboot/root-RSA-3072.pem
similarity index 100%
rename from bl2/ext/mcuboot/root-rsa-3072.pem
rename to bl2/ext/mcuboot/root-RSA-3072.pem
diff --git a/bl2/ext/mcuboot/root-rsa-3072_1.pem b/bl2/ext/mcuboot/root-RSA-3072_1.pem
similarity index 100%
rename from bl2/ext/mcuboot/root-rsa-3072_1.pem
rename to bl2/ext/mcuboot/root-RSA-3072_1.pem
diff --git a/bl2/ext/mcuboot/scripts/assemble.py b/bl2/ext/mcuboot/scripts/assemble.py
old mode 100644
new mode 100755
diff --git a/bl2/ext/mcuboot/scripts/imgtool.py b/bl2/ext/mcuboot/scripts/imgtool.py
deleted file mode 100644
index b524245..0000000
--- a/bl2/ext/mcuboot/scripts/imgtool.py
+++ /dev/null
@@ -1,254 +0,0 @@
-#! /usr/bin/env python3
-#
-# Copyright 2017 Linaro Limited
-# Copyright (c) 2018-2019, Arm Limited.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-from __future__ import print_function
-import os
-import re
-import argparse
-from imgtool_lib import keys
-from imgtool_lib import image
-from imgtool_lib import version
-import sys
-import macro_parser
-import fileinput
-
-sign_bin_size_re = re.compile(r"^\s*RE_SIGN_BIN_SIZE\s*=\s*(.*)")
-image_load_address_re = re.compile(r"^\s*RE_IMAGE_LOAD_ADDRESS\s*=\s*(.*)")
-
-# Returns the last version number if present, or None if not
-def get_last_version(path):
-    if (os.path.isfile(path) == False): # Version file not present
-        return None
-    else: # Version file is present, check it has a valid number inside it
-        with open(path, "r") as oldFile:
-            fileContents = oldFile.read()
-            if version.version_re.match(fileContents): # number is valid
-                return version.decode_version(fileContents)
-            else:
-                return None
-
-def next_version_number(args, defaultVersion, path):
-    newVersion = None
-    versionProvided = False
-    if (version.compare(args.version, defaultVersion) == 0): # Default version
-        lastVersion = get_last_version(path)
-        if (lastVersion is not None):
-            newVersion = version.increment_build_num(lastVersion)
-        else:
-            newVersion = version.increment_build_num(defaultVersion)
-    else: # Version number has been explicitly provided (not using the default)
-        versionProvided = True
-        newVersion = args.version
-    versionString = "{a}.{b}.{c}+{d}".format(
-                    a=str(newVersion.major),
-                    b=str(newVersion.minor),
-                    c=str(newVersion.revision),
-                    d=str(newVersion.build)
-    )
-    if not versionProvided:
-        with open(path, "w") as newFile:
-            newFile.write(versionString)
-    print("**[INFO]** Image version number set to " + versionString)
-    return newVersion
-
-def gen_rsa2048(args):
-    keys.RSAutil.generate().export_private(args.key)
-
-def gen_rsa3072(args):
-    keys.RSAutil.generate(key_size=3072).export_private(args.key)
-
-keygens = {
-        'rsa-2048': gen_rsa2048,
-        'rsa-3072': gen_rsa3072, }
-
-def do_keygen(args):
-    if args.type not in keygens:
-        msg = "Unexpected key type: {}".format(args.type)
-        raise argparse.ArgumentTypeError(msg)
-    keygens[args.type](args)
-
-def do_getpub(args):
-    key = keys.load(args.key)
-    if args.lang == 'c':
-        key.emit_c()
-    else:
-        msg = "Unsupported language, valid are: c"
-        raise argparse.ArgumentTypeError(msg)
-
-def do_sign(args):
-    if args.rsa_pkcs1_15:
-        keys.sign_rsa_pss = False
-
-    version_num = next_version_number(args,
-                                      version.decode_version("0"),
-                                      "lastVerNum.txt")
-
-    if args.security_counter is None:
-        # Security counter has not been explicitly provided,
-        # generate it from the version number
-        args.security_counter = ((version_num.major << 24)
-                                 + (version_num.minor << 16)
-                                 + version_num.revision)
-
-    if "_s.c" in args.layout:
-        sw_type = "SPE"
-    elif "_ns.c" in args.layout:
-        sw_type = "NSPE"
-    else:
-        sw_type = "NSPE_SPE"
-
-    pad_size = macro_parser.evaluate_macro(args.layout, sign_bin_size_re, 0, 1)
-    img = image.Image.load(args.infile,
-                           version=version_num,
-                           header_size=args.header_size,
-                           security_cnt=args.security_counter,
-                           included_header=args.included_header,
-                           pad=pad_size)
-    key = keys.load(args.key, args.public_key_format) if args.key else None
-    ram_load_address = macro_parser.evaluate_macro(args.layout, image_load_address_re, 0, 1)
-    img.sign(sw_type, key, ram_load_address, args.dependencies)
-
-    if pad_size:
-        img.pad_to(pad_size, args.align)
-
-    img.save(args.outfile)
-
-def do_flash(args):
-    image_value_re = re.compile(r"^\s*"+args.macro+"\s*=\s*(.*)")
-    value = macro_parser.evaluate_macro(args.layout, image_value_re, 0, 1,
-                                        True)
-    if args.setting == 1:
-        begin_line="set "+args.begin
-    else:
-        begin_line=args.begin
-
-    for line in fileinput.input(args.infile, inplace=True):
-        if line.startswith(begin_line):
-            if args.division:
-                value = int(value/int(args.division))
-            if args.phexa == 0:
-                line = begin_line+"="+str(value)+"\n"
-            else:
-                line = begin_line+"="+hex(value)+"\n"
-        sys.stdout.write(line)
-
-subcmds = {
-        'keygen': do_keygen,
-        'getpub': do_getpub,
-        'sign': do_sign,
-        'flash': do_flash, }
-
-
-def get_dependencies(text):
-    if text is not None:
-        versions = []
-        images = re.findall(r"\((\d+)", text)
-        if len(images) == 0:
-            msg = "Image dependency format is invalid: {}".format(text)
-            raise argparse.ArgumentTypeError(msg)
-        raw_versions = re.findall(r",\s*([0-9.+]+)\)", text)
-        if len(images) != len(raw_versions):
-            msg = '''There's a mismatch between the number of dependency images
-            and versions in: {}'''.format(text)
-            raise argparse.ArgumentTypeError(msg)
-        for raw_version in raw_versions:
-            try:
-                versions.append(version.decode_version(raw_version))
-            except ValueError as e:
-                print(e)
-        dependencies = dict()
-        dependencies[image.DEP_IMAGES_KEY] = images
-        dependencies[image.DEP_VERSIONS_KEY] = versions
-        return dependencies
-
-
-def alignment_value(text):
-    value = int(text)
-    if value not in [1, 2, 4, 8]:
-        msg = "{} must be one of 1, 2, 4 or 8".format(value)
-        raise argparse.ArgumentTypeError(msg)
-    return value
-
-def intparse(text):
-    """Parse a command line argument as an integer.
-
-    Accepts 0x and other prefixes to allow other bases to be used."""
-    return int(text, 0)
-
-def args():
-    parser = argparse.ArgumentParser()
-    subs = parser.add_subparsers(help='subcommand help', dest='subcmd')
-
-    keygenp = subs.add_parser('keygen', help='Generate pub/private keypair')
-    keygenp.add_argument('-k', '--key', metavar='filename', required=True)
-    keygenp.add_argument('-t', '--type', metavar='type',
-                         choices=keygens.keys(), required=True)
-
-    getpub = subs.add_parser('getpub', help='Get public key from keypair')
-    getpub.add_argument('-k', '--key', metavar='filename', required=True)
-    getpub.add_argument('-l', '--lang', metavar='lang', default='c')
-
-    sign = subs.add_parser('sign', help='Sign an image with a private key')
-    sign.add_argument('-l', '--layout', required=True,
-                      help='Location of the file that contains preprocessed macros')
-    sign.add_argument('-k', '--key', metavar='filename')
-    sign.add_argument("-K", "--public-key-format",
-                      help='In what format to add the public key to the image manifest: full or hash',
-                      metavar='pub_key_format', choices=['full', 'hash'], default='hash')
-    sign.add_argument("--align", type=alignment_value, required=True)
-    sign.add_argument("-v", "--version", type=version.decode_version,
-                      default="0.0.0+0")
-    sign.add_argument("-d", "--dependencies", type=get_dependencies,
-                      required=False, help='''Add dependence on another image,
-                      format: "(<image_ID>,<image_version>), ... "''')
-    sign.add_argument("-s", "--security-counter", type=intparse,
-                      help='Specify explicitly the security counter value')
-    sign.add_argument("-H", "--header-size", type=intparse, required=True)
-    sign.add_argument("--included-header", default=False, action='store_true',
-                      help='Image has gap for header')
-    sign.add_argument("--rsa-pkcs1-15",
-                      help='Use old PKCS#1 v1.5 signature algorithm',
-                      default=False, action='store_true')
-    sign.add_argument("infile")
-    sign.add_argument("outfile")
-
-    flash = subs.add_parser('flash', help='modify flash script')
-    flash.add_argument("infile")
-    flash.add_argument('-l', '--layout', required=True,
-                      help='Location of the file that contains preprocessed macros')
-    flash.add_argument('-m', '--macro', required =True,
-                      help='macro symbol string to grep in preprocessed file')
-    flash.add_argument('-b', '--begin', required=True,
-                      help='begin of line to replace ')
-    flash.add_argument('-s', '--setting',type=intparse,required=False,default=0,
-                      help='search for window batch set variable')
-    flash.add_argument('-d', '--division',
-                       required=False,type=intparse,default=0,
-                      help='search for window batch set variable')
-    flash.add_argument('-p', '--phexa',
-                       required=False,type=intparse,default=1,
-                      help='print value in hexa')
-
-    args = parser.parse_args()
-    if args.subcmd is None:
-        print('Must specify a subcommand', file=sys.stderr)
-        sys.exit(1)
-
-    subcmds[args.subcmd](args)
-
-if __name__ == '__main__':
-    args()
diff --git a/bl2/ext/mcuboot/scripts/imgtool_lib/__init__.py b/bl2/ext/mcuboot/scripts/imgtool_lib/__init__.py
deleted file mode 100644
index fd24044..0000000
--- a/bl2/ext/mcuboot/scripts/imgtool_lib/__init__.py
+++ /dev/null
@@ -1,18 +0,0 @@
-# Copyright 2017 Linaro Limited
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# This file is intentionally empty.
-#
-# The __init__.py files are required to make Python treat the directories as
-# containing packages.
\ No newline at end of file
diff --git a/bl2/ext/mcuboot/scripts/imgtool_lib/boot_record.py b/bl2/ext/mcuboot/scripts/imgtool_lib/boot_record.py
deleted file mode 100644
index 41887bb..0000000
--- a/bl2/ext/mcuboot/scripts/imgtool_lib/boot_record.py
+++ /dev/null
@@ -1,77 +0,0 @@
-
-# Copyright (c) 2019, Arm Limited.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import os
-import sys
-import cbor
-
-
-# SW component IDs
-SW_COMPONENT_RANGE = 0
-SW_COMPONENT_TYPE = SW_COMPONENT_RANGE + 1
-MEASUREMENT_VALUE = SW_COMPONENT_RANGE + 2
-SW_COMPONENT_VERSION = SW_COMPONENT_RANGE + 4
-SIGNER_ID = SW_COMPONENT_RANGE + 5
-MEASUREMENT_DESCRIPTION = SW_COMPONENT_RANGE + 6
-
-
-def create_sw_component_data(sw_type, sw_version, sw_measurement_type,
-                             sw_measurement_value, sw_signer_id):
-
-    # List of SW component claims (key ID + value)
-    key_value_list = [
-        SW_COMPONENT_TYPE, sw_type,
-        SW_COMPONENT_VERSION, sw_version,
-        SIGNER_ID, sw_signer_id,
-        MEASUREMENT_DESCRIPTION, sw_measurement_type,
-        MEASUREMENT_VALUE, sw_measurement_value
-    ]
-    # The measurement value should be the last item (key + value) in the list
-    # to make it easier to modify its value later in the bootloader.
-    # A dictionary would be the best suited data structure to store these
-    # key-value pairs (claims), however dictionaries are not sorted, but for
-    # example the lists do keep to order of items which we care about now.
-    # An ordered dictionary could be used instead, but it would be converted
-    # to a dict before the encoding and this conversion may not keep the order
-    # of the items.
-
-    if (len(key_value_list) % 2) != 0:
-        print('Error: The length of the sw component claim list must '
-              'be even (key + value).', file=sys.stderr)
-        sys.exit(1)
-    else:
-        claim_number = (int)(len(key_value_list) / 2)
-
-    # The output of this function must be a CBOR encoded map (dictionary) of
-    # the SW component claims. The CBOR representation of an array and a map
-    # (dictionary) is quite similar. To convert the encoded list to a map, it
-    # is enough to modify the first byte (CBOR data item header) of the
-    # data. This applies up to 23 items (11 claims in this case) - until the 5
-    # lower bits of the item header are used as an item count specifier.
-
-    if claim_number > 11:
-        print('Error: There are more than 11 claims in the '
-              'list of sw component claims.', file=sys.stderr)
-        sys.exit(1)
-
-    record_array = bytearray(cbor.dumps(key_value_list))
-    # Modify the CBOR data item header (from array to map)
-    # 7..5 bits : Major type
-    #             Array - 0x80
-    #             Map   - 0xA0
-    # 4..0 bits : Number of items
-    record_array[0] = 0xA0 + claim_number
-
-    return bytes(record_array)
diff --git a/bl2/ext/mcuboot/scripts/imgtool_lib/image.py b/bl2/ext/mcuboot/scripts/imgtool_lib/image.py
deleted file mode 100644
index d790a75..0000000
--- a/bl2/ext/mcuboot/scripts/imgtool_lib/image.py
+++ /dev/null
@@ -1,267 +0,0 @@
-# Copyright 2017 Linaro Limited
-# Copyright (c) 2018-2019, Arm Limited.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""
-Image signing and management.
-"""
-
-from . import version as versmod
-from . import boot_record as br
-import hashlib
-import struct
-
-IMAGE_MAGIC = 0x96f3b83d
-IMAGE_HEADER_SIZE = 32
-TLV_HEADER_SIZE = 4
-PAYLOAD_DIGEST_SIZE = 32  # SHA256 hash
-KEYHASH_SIZE = 32
-DEP_IMAGES_KEY = "images"
-DEP_VERSIONS_KEY = "versions"
-
-# Image header flags.
-IMAGE_F = {
-        'PIC':                   0x0000001,
-        'NON_BOOTABLE':          0x0000010,
-        'RAM_LOAD':              0x0000020, }
-TLV_VALUES = {
-        'KEYHASH': 0x01,
-        'KEY'    : 0x02,
-        'SHA256' : 0x10,
-        'RSA2048': 0x20,
-        'RSA3072': 0x23,
-        'DEPENDENCY': 0x40,
-        'SEC_CNT': 0x50,
-        'BOOT_RECORD': 0x60, }
-
-TLV_INFO_SIZE = 4
-TLV_INFO_MAGIC = 0x6907
-TLV_PROT_INFO_MAGIC = 0x6908
-
-# Sizes of the image trailer, depending on flash write size.
-trailer_sizes = {
-    write_size: 128 * 3 * write_size + 8 * 2 + 16
-    for write_size in [1, 2, 4, 8]
-}
-
-boot_magic = bytearray([
-    0x77, 0xc2, 0x95, 0xf3,
-    0x60, 0xd2, 0xef, 0x7f,
-    0x35, 0x52, 0x50, 0x0f,
-    0x2c, 0xb6, 0x79, 0x80, ])
-
-class TLV():
-    def __init__(self, magic=TLV_INFO_MAGIC):
-        self.magic = magic
-        self.buf = bytearray()
-
-    def __len__(self):
-        return TLV_INFO_SIZE + len(self.buf)
-
-    def add(self, kind, payload):
-        """
-        Add a TLV record.  Kind should be a string found in TLV_VALUES above.
-        """
-        buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
-        self.buf += buf
-        self.buf += payload
-
-    def get(self):
-        if len(self.buf) == 0:
-            return bytes()
-        header = struct.pack('<HH', self.magic, len(self))
-        return header + bytes(self.buf)
-
-class Image():
-    @classmethod
-    def load(cls, path, included_header=False, **kwargs):
-        """Load an image from a given file"""
-        with open(path, 'rb') as f:
-            payload = f.read()
-        obj = cls(**kwargs)
-        obj.payload = payload
-
-        # Add the image header if needed.
-        if not included_header and obj.header_size > 0:
-            obj.payload = (b'\000' * obj.header_size) + obj.payload
-
-        obj.check()
-        return obj
-
-    def __init__(self, version, header_size=IMAGE_HEADER_SIZE, security_cnt=0,
-                 pad=0):
-        self.version = version
-        self.header_size = header_size or IMAGE_HEADER_SIZE
-        self.security_cnt = security_cnt
-        self.pad = pad
-
-    def __repr__(self):
-        return "<Image version={}, header_size={}, security_counter={}, \
-                 pad={}, payloadlen=0x{:x}>".format(
-                self.version,
-                self.header_size,
-                self.security_cnt,
-                self.pad,
-                len(self.payload))
-
-    def save(self, path):
-        with open(path, 'wb') as f:
-            f.write(self.payload)
-
-    def check(self):
-        """Perform some sanity checking of the image."""
-        # If there is a header requested, make sure that the image
-        # starts with all zeros.
-        if self.header_size > 0:
-            if any(v != 0 and v != b'\000' for v in self.payload[0:self.header_size]):
-                raise Exception("Padding requested, but image does not start with zeros")
-
-    def sign(self, sw_type, key, ramLoadAddress, dependencies=None):
-        image_version = (str(self.version.major) + '.'
-                      + str(self.version.minor) + '.'
-                      + str(self.version.revision))
-
-        # Calculate the hash of the public key
-        if key is not None:
-            pub = key.get_public_bytes()
-            sha = hashlib.sha256()
-            sha.update(pub)
-            pubbytes = sha.digest()
-        else:
-            pubbytes = bytes(KEYHASH_SIZE)
-
-        # The image hash is computed over the image header, the image itself
-        # and the protected TLV area. However, the boot record TLV (which is
-        # part of the protected area) should contain this hash before it is
-        # even calculated. For this reason the script fills this field with
-        # zeros and the bootloader will insert the right value later.
-        image_hash = bytes(PAYLOAD_DIGEST_SIZE)
-
-        # Create CBOR encoded boot record
-        boot_record = br.create_sw_component_data(sw_type, image_version,
-                                                  "SHA256", image_hash,
-                                                  pubbytes)
-
-        # Mandatory protected TLV area: TLV info header
-        #                               + security counter TLV
-        #                               + boot record TLV
-        # Size of the security counter TLV: header ('BBH') + payload ('I')
-        #                                   = 8 Bytes
-        protected_tlv_size = TLV_INFO_SIZE + 8 + TLV_HEADER_SIZE \
-                           + len(boot_record)
-
-        if dependencies is None:
-            dependencies_num = 0
-        else:
-            # Size of a dependency TLV:
-            # header ('BBH') + payload('IBBHI') = 16 Bytes
-            dependencies_num = len(dependencies[DEP_IMAGES_KEY])
-            protected_tlv_size += (dependencies_num * 16)
-
-        # At this point the image is already on the payload, this adds
-        # the header to the payload as well
-        self.add_header(key, protected_tlv_size, ramLoadAddress)
-
-        prot_tlv = TLV(TLV_PROT_INFO_MAGIC)
-
-        # Protected TLVs must be added first, because they are also included
-        # in the hash calculation
-        payload = struct.pack('I', self.security_cnt)
-        prot_tlv.add('SEC_CNT', payload)
-        prot_tlv.add('BOOT_RECORD', boot_record)
-
-        if dependencies_num != 0:
-            for i in range(dependencies_num):
-                payload = struct.pack(
-                                '<'+'B3x'+'BBHI',
-                                int(dependencies[DEP_IMAGES_KEY][i]),
-                                dependencies[DEP_VERSIONS_KEY][i].major,
-                                dependencies[DEP_VERSIONS_KEY][i].minor,
-                                dependencies[DEP_VERSIONS_KEY][i].revision,
-                                dependencies[DEP_VERSIONS_KEY][i].build
-                                )
-                prot_tlv.add('DEPENDENCY', payload)
-
-        self.payload += prot_tlv.get()
-
-        sha = hashlib.sha256()
-        sha.update(self.payload)
-        image_hash = sha.digest()
-
-        tlv = TLV()
-
-        tlv.add('SHA256', image_hash)
-
-        if key is not None:
-            if key.get_public_key_format() == 'hash':
-                tlv.add('KEYHASH', pubbytes)
-            else:
-                tlv.add('KEY', pub)
-
-            sig = key.sign(self.payload)
-            tlv.add(key.sig_tlv(), sig)
-
-        self.payload += tlv.get()
-
-    def add_header(self, key, protected_tlv_size, ramLoadAddress):
-        """Install the image header.
-
-        The key is needed to know the type of signature, and
-        approximate the size of the signature."""
-
-        flags = 0
-        if ramLoadAddress is not None:
-            # add the load address flag to the header to indicate that an SRAM
-            # load address macro has been defined
-            flags |= IMAGE_F["RAM_LOAD"]
-
-        fmt = ('<' +
-            # type ImageHdr struct {
-            'I' +    # Magic    uint32
-            'I' +    # LoadAddr uint32
-            'H' +    # HdrSz    uint16
-            'H' +    # PTLVSz   uint16
-            'I' +    # ImgSz    uint32
-            'I' +    # Flags    uint32
-            'BBHI' + # Vers     ImageVersion
-            'I'      # Pad1     uint32
-            ) # }
-        assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
-        header = struct.pack(fmt,
-                IMAGE_MAGIC,
-                0 if (ramLoadAddress is None) else ramLoadAddress, # LoadAddr
-                self.header_size,
-                protected_tlv_size,  # TLV info header + Protected TLVs
-                len(self.payload) - self.header_size,  # ImageSz
-                flags,
-                self.version.major,
-                self.version.minor or 0,
-                self.version.revision or 0,
-                self.version.build or 0,
-                0)  # Pad1
-        self.payload = bytearray(self.payload)
-        self.payload[:len(header)] = header
-
-    def pad_to(self, size, align):
-        """Pad the image to the given size, with the given flash alignment."""
-        tsize = trailer_sizes[align]
-        padding = size - (len(self.payload) + tsize)
-        if padding < 0:
-            msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
-                    len(self.payload), tsize, size)
-            raise Exception(msg)
-        pbytes  = b'\xff' * padding
-        pbytes += b'\xff' * (tsize - len(boot_magic))
-        pbytes += boot_magic
-        self.payload += pbytes
diff --git a/bl2/ext/mcuboot/scripts/imgtool_lib/keys.py b/bl2/ext/mcuboot/scripts/imgtool_lib/keys.py
deleted file mode 100644
index 1f6ef90..0000000
--- a/bl2/ext/mcuboot/scripts/imgtool_lib/keys.py
+++ /dev/null
@@ -1,136 +0,0 @@
-# Copyright (c) 2017,2019 Linaro Limited.
-# Copyright (c) 2017-2019, Arm Limited.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""
-Cryptographic key management for imgtool.
-"""
-
-from __future__ import print_function
-from cryptography.hazmat.backends import default_backend
-from cryptography.hazmat.primitives import serialization
-from cryptography.hazmat.primitives.hashes import SHA256
-from cryptography.hazmat.primitives.asymmetric import rsa
-from cryptography.hazmat.primitives.asymmetric.padding import PSS, PKCS1v15
-from cryptography.hazmat.primitives.asymmetric.padding import MGF1
-import hashlib
-from pyasn1.type import namedtype, univ
-from pyasn1.codec.der.encoder import encode
-
-# Sizes that bootutil will recognize
-RSA_KEY_SIZES = [2048, 3072]
-
-# Public exponent
-PUBLIC_EXPONENT = 65537
-
-# By default, we use RSA-PSS (PKCS 2.1).  That can be overridden on
-# the command line to support the older (less secure) PKCS1.5
-sign_rsa_pss = True
-
-AUTOGEN_MESSAGE = "/* Autogenerated by imgtool.py, do not edit. */"
-
-class RSAUsageError(Exception):
-    pass
-
-class RSAutil():
-    def __init__(self, key, public_key_format='hash'):
-        """Construct an RSA key with the given key data"""
-        self.key = key
-        self.public_key_format = public_key_format
-
-    def key_size(self):
-        return self.key.key_size
-
-    def get_public_key_format(self):
-        return self.public_key_format
-
-    @staticmethod
-    def generate(key_size=2048):
-        if key_size not in RSA_KEY_SIZES:
-            raise RSAUsageError("Key size {} is not supported by MCUboot"
-                                .format(key_size))
-        return RSAutil(rsa.generate_private_key(
-                public_exponent=PUBLIC_EXPONENT,
-                key_size=key_size,
-                backend=default_backend()))
-
-    def export_private(self, path):
-        with open(path, 'wb') as f:
-            f.write(self.key.private_bytes(
-                    encoding=serialization.Encoding.PEM,
-                    format=serialization.PrivateFormat.TraditionalOpenSSL,
-                    encryption_algorithm=serialization.NoEncryption()))
-
-    def get_public_bytes(self):
-        return self.key.public_key().public_bytes(
-                encoding=serialization.Encoding.DER,
-                format=serialization.PublicFormat.PKCS1)
-
-    def emit_c(self):
-        print(AUTOGEN_MESSAGE)
-        print("const unsigned char rsa_pub_key[] = {", end='')
-        encoded = self.get_public_bytes()
-        for count, b in enumerate(encoded):
-            if count % 8 == 0:
-                print("\n\t", end='')
-            else:
-                print(" ", end='')
-            print("0x{:02x},".format(b), end='')
-        print("\n};")
-        print("const unsigned int rsa_pub_key_len = {};".format(len(encoded)))
-
-    def sig_type(self):
-        """Return the type of this signature (as a string)"""
-        if sign_rsa_pss:
-            return "PKCS1_PSS_RSA{}_SHA256".format(self.key_size())
-        else:
-            return "PKCS15_RSA{}_SHA256".format(self.key_size())
-
-    def sig_len(self):
-        return 256 if self.key_size() == 2048 else 384
-
-    def sig_tlv(self):
-        return "RSA2048" if self.key_size() == 2048 else "RSA3072"
-
-    def sign(self, payload):
-        if sign_rsa_pss:
-            signature = self.key.sign(
-                data=bytes(payload),
-                padding=PSS(
-                    mgf=MGF1(SHA256()),
-                    salt_length=32
-                ),
-                algorithm=SHA256()
-            )
-        else:
-            signature = self.key.sign(
-                data=bytes(payload),
-                padding=PKCS1v15(),
-                algorithm=SHA256()
-            )
-        assert len(signature) == self.sig_len()
-        return signature
-
-def load(path, public_key_format='hash'):
-    with open(path, 'rb') as f:
-        pem = f.read()
-    try:
-        key = serialization.load_pem_private_key(
-            pem,
-            password=None,
-            backend=default_backend()
-        )
-        return RSAutil(key, public_key_format)
-    except ValueError:
-        raise Exception("Unsupported RSA key file")
diff --git a/bl2/ext/mcuboot/scripts/imgtool_lib/version.py b/bl2/ext/mcuboot/scripts/imgtool_lib/version.py
deleted file mode 100644
index d1d45f0..0000000
--- a/bl2/ext/mcuboot/scripts/imgtool_lib/version.py
+++ /dev/null
@@ -1,66 +0,0 @@
-# Copyright 2017 Linaro Limited
-# Copyright (c) 2018, Arm Limited.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""
-Semi Semantic Versioning
-
-Implements a subset of semantic versioning that is supportable by the image header.
-"""
-
-import argparse
-from collections import namedtuple
-import re
-
-SemiSemVersion = namedtuple('SemiSemVersion', ['major', 'minor', 'revision', 'build'])
-
-def increment_build_num(lastVer):
-    newVer = SemiSemVersion(lastVer.major, lastVer.minor, lastVer.revision, lastVer.build + 1)
-    return newVer
-
-# -1 if a is older than b; 0 if they're the same version; 1 if a is newer than b
-def compare(a, b):
-    if (a.major > b.major): return 1
-    elif (a.major < b.major): return -1
-    else:
-        if (a.minor > b.minor): return 1
-        elif (a.minor < b.minor): return -1
-        else:
-            if (a.revision > b.revision): return 1
-            elif (a.revision < b.revision): return -1
-            else:
-                if (a.build > b.build): return 1
-                elif (a.build < b.build): return -1
-                else: return 0
-
-version_re = re.compile(r"""^([1-9]\d*|0)(\.([1-9]\d*|0)(\.([1-9]\d*|0)(\+([1-9]\d*|0))?)?)?$""")
-def decode_version(text):
-    """Decode the version string, which should be of the form maj.min.rev+build"""
-    m = version_re.match(text)
-    if m:
-        result = SemiSemVersion(
-                int(m.group(1)) if m.group(1) else 0,
-                int(m.group(3)) if m.group(3) else 0,
-                int(m.group(5)) if m.group(5) else 0,
-                int(m.group(7)) if m.group(7) else 0)
-        return result
-    else:
-        msg = "Invalid version number, should be maj.min.rev+build with later parts optional"
-        raise argparse.ArgumentTypeError(msg)
-
-if __name__ == '__main__':
-    print(decode_version("1.2"))
-    print(decode_version("1.0"))
-    print(decode_version("0.0.2+75"))
-    print(decode_version("0.0.0+00"))
diff --git a/bl2/ext/mcuboot/scripts/wrapper/wrapper.py b/bl2/ext/mcuboot/scripts/wrapper/wrapper.py
old mode 100644
new mode 100755
index 0944336..7799ce0
--- a/bl2/ext/mcuboot/scripts/wrapper/wrapper.py
+++ b/bl2/ext/mcuboot/scripts/wrapper/wrapper.py
@@ -11,9 +11,15 @@
 import os
 import sys
 import click
+
+# Add the cwd to the path so that if there is a version of imgtool in there then
+# it gets used over the system imgtool. Used so that imgtool from upstream
+# mcuboot is preferred over system imgtool
+cwd = os.getcwd()
+sys.path = [cwd] + sys.path
 import imgtool
 import imgtool.main
-# Import macro_parser script
+
 parser_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
 sys.path.append(parser_path)
 import macro_parser
@@ -86,9 +92,9 @@
     slot_size = macro_parser.evaluate_macro(layout, sign_bin_size_re, 0, 1)
     load_addr = macro_parser.evaluate_macro(layout, load_addr_re, 0, 1)
 
-    if "_s.c" in layout:
+    if "_s" in layout:
         boot_record = "SPE"
-    elif "_ns.c" in layout:
+    elif "_ns" in layout:
         boot_record = "NSPE"
     else:
         boot_record = "NSPE_SPE"
diff --git a/bl2/ext/mcuboot/signing_layout.c.in b/bl2/ext/mcuboot/signing_layout.c.in
new file mode 100644
index 0000000..f0d490c
--- /dev/null
+++ b/bl2/ext/mcuboot/signing_layout.c.in
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2020, Arm Limited. All rights reserved.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ */
+#include "flash_layout.h"
+/* Enumeration that is used by the assemble.py and imgtool.py scripts
+ * for correct binary generation when nested macros are used
+ */
+enum image_attributes {
+    RE_SECURE_IMAGE_OFFSET       = SECURE_IMAGE_OFFSET,
+    RE_SECURE_IMAGE_MAX_SIZE     = SECURE_IMAGE_MAX_SIZE,
+    RE_NON_SECURE_IMAGE_OFFSET   = NON_SECURE_IMAGE_OFFSET,
+    RE_NON_SECURE_IMAGE_MAX_SIZE = NON_SECURE_IMAGE_MAX_SIZE,
+#ifdef IMAGE_LOAD_ADDRESS
+    RE_IMAGE_LOAD_ADDRESS = IMAGE_LOAD_ADDRESS,
+#endif
+    RE_SIGN_BIN_SIZE = FLASH_AREA_@FLASH_AREA_NUM@_SIZE,
+};