Build: Enable building TF-M with original MCUBoot

Enable building TF-M with the original MCUBoot (alongside the forked one
in the TF-M repository). Before building with the upstream MCUBoot repo,
it must be cloned into the TF-M base folder (into which the TF-M was
cloned previously) and the -DMCUBOOT_REPO=UPSTREAM option must be added
to the command line at the CMake configuration step.
The MCUBOOT_REPO option determines the repository from which it will use
the MCUBoot. By default it will use it from the TF-M repository.

Add description of how to build TF-M with upstream MCUBoot to the
documentation.

Change-Id: I2cfa55039943a9ac919156570120367d9603a816
Signed-off-by: David Vincze <david.vincze@arm.com>
diff --git a/bl2/ext/mcuboot/CMakeLists.txt b/bl2/ext/mcuboot/CMakeLists.txt
index 2f47f6c..d8a14cb 100644
--- a/bl2/ext/mcuboot/CMakeLists.txt
+++ b/bl2/ext/mcuboot/CMakeLists.txt
@@ -1,5 +1,5 @@
 #------------------------------------------------------------------------------
-# Copyright (c) 2017-2019, Arm Limited. All rights reserved.
+# Copyright (c) 2017-2020, Arm Limited. All rights reserved.
 #
 # SPDX-License-Identifier: BSD-3-Clause
 #
@@ -12,18 +12,25 @@
 #Tell cmake where our modules can be found
 list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/../../../cmake)
 
-#Set variables to appropriate path
-set(MCUBOOT_DIR ${CMAKE_CURRENT_LIST_DIR})
-get_filename_component(TFM_ROOT_DIR "${MCUBOOT_DIR}/../../.." ABSOLUTE)
-
 #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()
 
+#Set the appropriate MCUBoot path
+if (MCUBOOT_REPO STREQUAL "TF-M")
+	get_filename_component(MCUBOOT_DIR ${CMAKE_CURRENT_LIST_DIR} ABSOLUTE)
+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()
+endif()
+
 #Check input variables
 if (NOT DEFINED BL2)
    message(FATAL ERROR "Incomplete build configuration: BL2 is undefined.")
@@ -71,20 +78,25 @@
 
 #Append all our source files to global lists.
 list(APPEND ALL_SRC_C
-		"${MCUBOOT_DIR}/bl2_main.c"
-		"${MCUBOOT_DIR}/flash_map_extended.c"
-		"${MCUBOOT_DIR}/flash_map_legacy.c"
-		"${MCUBOOT_DIR}/keys.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"
 		"${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"
-		"${TFM_ROOT_DIR}/bl2/src/flash_map.c"
-		"${TFM_ROOT_DIR}/bl2/src/boot_record.c"
-		"${TFM_ROOT_DIR}/bl2/src/security_cnt.c"
 	)
 
+if (MCUBOOT_REPO STREQUAL "TF-M")
+	list(APPEND ALL_SRC_C
+			"${TFM_ROOT_DIR}/bl2/src/boot_record.c"
+			"${TFM_ROOT_DIR}/bl2/src/security_cnt.c"
+		)
+endif()
+
 #Define location of Mbed Crypto source, build, and installation directory.
 set(MBEDTLS_CONFIG_FILE "config-rsa.h")
 set(MBEDTLS_CONFIG_PATH "${TFM_ROOT_DIR}/bl2/ext/mcuboot/include")
@@ -114,7 +126,7 @@
 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 ${TFM_ROOT_DIR}/bl2/ext/mcuboot/bootutil/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)
 
 #Define linker file
@@ -164,6 +176,7 @@
 #Generate binary file from axf
 compiler_generate_binary_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}'.")
@@ -177,6 +190,10 @@
 							MBEDTLS_CONFIG_FILE="${MBEDTLS_CONFIG_FILE}"
 							MCUBOOT_TARGET_CONFIG="flash_layout.h")
 
+if (MCUBOOT_REPO STREQUAL "UPSTREAM")
+	target_compile_definitions(${PROJECT_NAME} PRIVATE MCUBOOT_USE_UPSTREAM)
+endif()
+
 if (MCUBOOT_SIGNATURE_TYPE STREQUAL "RSA-3072")
 	target_compile_definitions(${PROJECT_NAME} PRIVATE MCUBOOT_SIGN_RSA MCUBOOT_SIGN_RSA_LEN=3072)
 elseif(MCUBOOT_SIGNATURE_TYPE STREQUAL "RSA-2048")
diff --git a/bl2/ext/mcuboot/MCUBoot.cmake b/bl2/ext/mcuboot/MCUBoot.cmake
index ad97724..e344e3e 100644
--- a/bl2/ext/mcuboot/MCUBoot.cmake
+++ b/bl2/ext/mcuboot/MCUBoot.cmake
@@ -1,5 +1,5 @@
 #-------------------------------------------------------------------------------
-# Copyright (c) 2018-2019, Arm Limited. All rights reserved.
+# Copyright (c) 2018-2020, Arm Limited. All rights reserved.
 #
 # SPDX-License-Identifier: BSD-3-Clause
 #
@@ -329,7 +329,11 @@
 	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")
-		set_property(CACHE MCUBOOT_UPGRADE_STRATEGY PROPERTY STRINGS "OVERWRITE_ONLY;SWAP;NO_SWAP;RAM_LOADING")
+		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)
diff --git a/bl2/ext/mcuboot/MCUBootConfig.cmake b/bl2/ext/mcuboot/MCUBootConfig.cmake
index 02c68a3..f421ee6 100644
--- a/bl2/ext/mcuboot/MCUBootConfig.cmake
+++ b/bl2/ext/mcuboot/MCUBootConfig.cmake
@@ -1,5 +1,5 @@
 #-------------------------------------------------------------------------------
-# Copyright (c) 2019, Arm Limited. All rights reserved.
+# Copyright (c) 2019-2020, Arm Limited. All rights reserved.
 #
 # SPDX-License-Identifier: BSD-3-Clause
 #
@@ -13,6 +13,10 @@
 if (BL2)
 	add_definitions(-DBL2)
 
+	set(MCUBOOT_REPO "TF-M" 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)
@@ -25,7 +29,15 @@
 	set_property(CACHE MCUBOOT_SIGNATURE_TYPE PROPERTY STRINGS "RSA-3072;RSA-2048")
 	validate_cache_value(MCUBOOT_SIGNATURE_TYPE)
 
-	set(MCUBOOT_HW_KEY On CACHE BOOL "Configure to use HW key for image verification. Otherwise key is embedded in MCUBoot image.")
+	if (MCUBOOT_REPO STREQUAL "TF-M")
+		set(MCUBOOT_HW_KEY On CACHE BOOL "Configure to use HW key for image verification. Otherwise key is embedded in MCUBoot image.")
+	else() #Using upstream MCUBoot
+		if (MCUBOOT_HW_KEY)
+			message(WARNING "Cannot use HW key for image verification when building against upstream MCUBoot."
+				" Your choice was overriden (MCUBOOT_HW_KEY=Off).")
+		endif()
+		set(MCUBOOT_HW_KEY Off)
+	endif()
 
 	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")
@@ -42,6 +54,27 @@
 		set(MCUBOOT_IMAGE_NUMBER 1)
 	endif()
 
+	if (MCUBOOT_REPO STREQUAL "UPSTREAM")
+		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()
+
+		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"
+					" upstream MCUBoot does not support rollback protection.")
+				set(SECURITY_COUNTER "")
+				set(SECURITY_COUNTER_S "")
+				set(SECURITY_COUNTER_NS "")
+		endif()
+
+	endif()
+
 else() #BL2 is turned off
 
 	if (DEFINED MCUBOOT_IMAGE_NUMBER OR
@@ -49,35 +82,35 @@
 		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 "")
+			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 "")
+			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 "")
+			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 "")
+			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 33d2156..08dccfb 100644
--- a/bl2/ext/mcuboot/bl2_main.c
+++ b/bl2/ext/mcuboot/bl2_main.c
@@ -192,12 +192,14 @@
             ;
     }
 
+#ifndef MCUBOOT_USE_UPSTREAM
     rc = boot_nv_security_counter_init();
     if (rc != 0) {
         BOOT_LOG_ERR("Error while initializing the security counter");
         while (1)
             ;
     }
+#endif /* !MCUBOOT_USE_UPSTREAM */
 
     rc = boot_go(&rsp);
     if (rc != 0) {
diff --git a/bl2/ext/mcuboot/include/os/os_malloc.h b/bl2/ext/mcuboot/include/os/os_malloc.h
new file mode 100644
index 0000000..2338ce1
--- /dev/null
+++ b/bl2/ext/mcuboot/include/os/os_malloc.h
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+/*
+ * Original code taken from mcuboot project at:
+ * https://github.com/JuulLabs-OSS/mcuboot
+ * Git SHA of the original version: ac55554059147fff718015be9f4bd3108123f50a
+ * Modifications are Copyright (c) 2020 Arm Limited.
+ */
+
+#ifndef H_OS_MALLOC_
+#define H_OS_MALLOC_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* H_OS_MALLOC_ */