From f41c3585e631622ba24b43be8ab83527d112fdbe Mon Sep 17 00:00:00 2001
From: pennam <m.pennasilico@arduino.cc>
Date: Mon, 4 Apr 2022 11:26:40 +0200
Subject: [PATCH 1/5] Do not build main() from mcuboot repository

---
 mbed_app.json          | 3 ++-
 mbed_app_bootutil.json | 3 ++-
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/mbed_app.json b/mbed_app.json
index 887eba3..ab80fe7 100644
--- a/mbed_app.json
+++ b/mbed_app.json
@@ -75,7 +75,8 @@
             "mcuboot.application-dfu": true,
             "mcuboot.signature-algorithm": "SIGNATURE_TYPE_EC256",
             "mcuboot.encrypt-ec256": true,
-            "mcuboot.include-keys": null
+            "mcuboot.include-keys": null,
+            "mcuboot.bootloader-build": false
         }
     }
 }
diff --git a/mbed_app_bootutil.json b/mbed_app_bootutil.json
index 44bbed8..00fa61f 100644
--- a/mbed_app_bootutil.json
+++ b/mbed_app_bootutil.json
@@ -75,7 +75,8 @@
             "mcuboot.application-dfu": null,
             "mcuboot.signature-algorithm": "SIGNATURE_TYPE_EC256",
             "mcuboot.encrypt-ec256": true,
-            "mcuboot.include-keys": null
+            "mcuboot.include-keys": null,
+            "mcuboot.bootloader-build": false
         }
     }
 }

From 57e946fbe1bd32abb58fae3d9e1b6c03f6c10407 Mon Sep 17 00:00:00 2001
From: pennam <m.pennasilico@arduino.cc>
Date: Mon, 4 Apr 2022 11:27:21 +0200
Subject: [PATCH 2/5] Cleanup unrelevant targets configurations

---
 mbed_app.json | 31 -------------------------------
 1 file changed, 31 deletions(-)

diff --git a/mbed_app.json b/mbed_app.json
index ab80fe7..ab9f5e7 100644
--- a/mbed_app.json
+++ b/mbed_app.json
@@ -15,37 +15,6 @@
             "mbed-trace.enable": false,
             "mbed-trace.fea-ipv6": false
         },
-        "NRF52840_DK": {
-            "target.features_remove": ["CRYPTOCELL310"],
-            "target.macros_remove": ["MBEDTLS_CONFIG_HW_SUPPORT"],
-            "mcuboot.primary-slot-address": "0x20000",
-            "mcuboot.slot-size": "0xC0000",
-            "mcuboot.scratch-address": "0xE0000",
-            "mcuboot.scratch-size": "0x20000",
-            "mcuboot.max-img-sectors": "0x180",
-            "mcuboot.read-granularity": 4,
-            "qspif.QSPI_MIN_PROG_SIZE": 4
-        },
-        "EP_AGORA": {
-            "target.features_remove": ["CRYPTOCELL310"],
-            "target.macros_remove": ["MBEDTLS_CONFIG_HW_SUPPORT"],
-            "mcuboot.primary-slot-address": "0x20000",
-            "mcuboot.slot-size": "0xC0000",
-            "mcuboot.scratch-address": "0xE0000",
-            "mcuboot.scratch-size": "0x20000",
-            "mcuboot.max-img-sectors": "0x180",
-            "mcuboot.read-granularity": 4,
-            "qspif.QSPI_MIN_PROG_SIZE": 4
-        },
-        "DISCO_L475VG_IOT01A": {
-            "mcuboot.primary-slot-address": "0x8020000",
-            "mcuboot.slot-size": "0xC0000",
-            "mcuboot.scratch-address": "0x80E0000",
-            "mcuboot.scratch-size": "0x20000",
-            "mcuboot.max-img-sectors": "0x180",
-            "mcuboot.read-granularity": 1,
-            "qspif.QSPI_MIN_PROG_SIZE": 1
-        },
         "PORTENTA_H7_M7": {
             "target.clock_source": "USE_PLL_HSE_EXTC",
             "target.use-mpu": false,

From a667661ebca18395831cc1f5fc2a22ded22c6eb4 Mon Sep 17 00:00:00 2001
From: pennam <m.pennasilico@arduino.cc>
Date: Mon, 4 Apr 2022 11:28:16 +0200
Subject: [PATCH 3/5] Move default_bd file inside app folder

---
 default_bd.cpp => app/default_bd.cpp | 0
 1 file changed, 0 insertions(+), 0 deletions(-)
 rename default_bd.cpp => app/default_bd.cpp (100%)

diff --git a/default_bd.cpp b/app/default_bd.cpp
similarity index 100%
rename from default_bd.cpp
rename to app/default_bd.cpp

From 7cf17bd69a3b48daa45fcea11f6d99e6cadfa54b Mon Sep 17 00:00:00 2001
From: pennam <m.pennasilico@arduino.cc>
Date: Mon, 4 Apr 2022 11:31:06 +0200
Subject: [PATCH 4/5] Rename target files: main.cpp and board.h

---
 app/{target.h => board.h}    | 0
 app/{target.cpp => main.cpp} | 2 +-
 2 files changed, 1 insertion(+), 1 deletion(-)
 rename app/{target.h => board.h} (100%)
 rename app/{target.cpp => main.cpp} (99%)

diff --git a/app/target.h b/app/board.h
similarity index 100%
rename from app/target.h
rename to app/board.h
diff --git a/app/target.cpp b/app/main.cpp
similarity index 99%
rename from app/target.cpp
rename to app/main.cpp
index 61e18da..6919a28 100644
--- a/app/target.cpp
+++ b/app/main.cpp
@@ -19,7 +19,7 @@
 #if  MCUBOOT_APPLICATION_HOOKS
 
 #include "mbed.h"
-#include "target.h"
+#include "board.h"
 #include "ota.h"
 #include "rtc.h"
 #include "bootutil/bootutil_log.h"

From f92beb30704ac96b09bd36e1cbd5210c21fcc6fb Mon Sep 17 00:00:00 2001
From: pennam <m.pennasilico@arduino.cc>
Date: Mon, 4 Apr 2022 12:16:32 +0200
Subject: [PATCH 5/5] Restore secure application boot

---
 app/default_bd.cpp         |   2 +-
 app/dfu/usbd_conf.c        |   2 +-
 app/dfu/usbd_dfu_flash.cpp |   2 +-
 app/main.cpp               | 107 +++++++++++++++++++++++++------------
 4 files changed, 76 insertions(+), 37 deletions(-)

diff --git a/app/default_bd.cpp b/app/default_bd.cpp
index a756d7d..56a834b 100644
--- a/app/default_bd.cpp
+++ b/app/default_bd.cpp
@@ -20,7 +20,7 @@
 
 #include "ota.h"
 #include "rtc.h"
-#include "target.h"
+#include "board.h"
 #include "bootutil/bootutil_log.h"
 
 #include "SlicingBlockDevice.h"
diff --git a/app/dfu/usbd_conf.c b/app/dfu/usbd_conf.c
index 4ce85ae..b8c028e 100644
--- a/app/dfu/usbd_conf.c
+++ b/app/dfu/usbd_conf.c
@@ -20,7 +20,7 @@
 #if  MCUBOOT_APPLICATION_HOOKS && MCUBOOT_APPLICATION_DFU
 
 /* Includes ------------------------------------------------------------------ */
-#include "target.h"
+#include "board.h"
 
 /* Private typedef ----------------------------------------------------------- */
 /* Private define ------------------------------------------------------------ */
diff --git a/app/dfu/usbd_dfu_flash.cpp b/app/dfu/usbd_dfu_flash.cpp
index 6a78d69..e74c929 100644
--- a/app/dfu/usbd_dfu_flash.cpp
+++ b/app/dfu/usbd_dfu_flash.cpp
@@ -23,7 +23,7 @@
 #include "usbd_dfu_flash.h"
 //#include "option_bits.h"
 #include "mbed.h"
-#include "target.h"
+#include "board.h"
 #include "BlockDevice.h"
 #include "FlashSimBlockDevice.h"
 #include "flash_map_backend/secondary_bd.h"
diff --git a/app/main.cpp b/app/main.cpp
index 6919a28..4f73c12 100644
--- a/app/main.cpp
+++ b/app/main.cpp
@@ -23,6 +23,9 @@
 #include "ota.h"
 #include "rtc.h"
 #include "bootutil/bootutil_log.h"
+#include "bootutil/bootutil.h"
+#include "bootutil/image.h"
+#include "mbedtls/platform.h"
 
 // clock source is selected with CLOCK_SOURCE in json config
 #define USE_PLL_HSE_EXTC     0x8  // Use external clock (ST Link MCO)
@@ -136,7 +139,42 @@ int target_led_off(void) {
   return 0;
 }
 
-int target_init(void) {
+int start_secure_application(void) {
+
+  int rc;
+
+  BOOT_LOG_INF("Starting MCUboot");
+
+  // Initialize mbedtls crypto for use by MCUboot
+  mbedtls_platform_context unused_ctx;
+  rc = mbedtls_platform_setup(&unused_ctx);
+  if(rc != 0) {
+    BOOT_LOG_ERR("Failed to setup Mbed TLS, error: %d", rc);
+    return -1;
+  }
+
+  struct boot_rsp rsp;
+  rc = boot_go(&rsp);
+  if(rc != 0) {
+    BOOT_LOG_ERR("Failed to locate firmware image, error: %d\n", rc);
+    return -1;
+  }
+
+  target_led_off();
+
+  // Run the application in the primary slot
+  // Add header size offset to calculate the actual start address of application
+  uint32_t address = rsp.br_image_off + rsp.br_hdr->ih_hdr_size;
+  BOOT_LOG_INF("Booting firmware image at 0x%x\n", address);
+  mbed_start_application(address);
+}
+
+int main(void) {
+
+  target_debug_init();
+
+  BOOT_LOG_INF("Starting Arduino bootloader");
+
   int magic = RTCGetBKPRegister(RTC_BKP_DR0);
 
   // in case we have been reset let's wait 500 ms to see if user is trying to stay in bootloader
@@ -236,47 +274,48 @@ int target_init(void) {
 
   HAL_Delay(10);
 
-  if (magic == 0xDF59) {
-    /* Boot stopped by double reset */
-    return 1;
-  }
+  if (magic != 0xDF59) {
+    if (target_empty_keys()) {
+      BOOT_LOG_INF("Secure keys not configured");
+      if ( magic == 0x07AA ) {
+        /* Try unsecure OTA */
+        // DR1 contains the backing storage type, DR2 the offset in case of raw device / MBR
+        storageType storage_type = (storageType)RTCGetBKPRegister(RTC_BKP_DR1);
+        uint32_t offset = RTCGetBKPRegister(RTC_BKP_DR2);
+        uint32_t update_size = RTCGetBKPRegister(RTC_BKP_DR3);
+        BOOT_LOG_INF("Start OTA 0x%X 0x%X 0x%X", storage_type, offset, update_size);
+        int ota_result = tryOTA(storage_type, offset, update_size);
+        if (ota_result == 0) {
+          // clean reboot with success flag
+          BOOT_LOG_INF("Sketch updated");
+          RTCSetBKPRegister(RTC_BKP_DR0, 0);
+          HAL_FLASH_Lock();
+          // wait for external reboot (watchdog)
+          while (1) {}
+        } else {
+          RTCSetBKPRegister(RTC_BKP_DR0, ota_result);
+        }
+      }
 
-  if (target_empty_keys()) {
-    BOOT_LOG_INF("Secure keys not configured");
-    if ( magic == 0x07AA ) {
-      /* Try unsecure OTA */
-      // DR1 contains the backing storage type, DR2 the offset in case of raw device / MBR
-      storageType storage_type = (storageType)RTCGetBKPRegister(RTC_BKP_DR1);
-      uint32_t offset = RTCGetBKPRegister(RTC_BKP_DR2);
-      uint32_t update_size = RTCGetBKPRegister(RTC_BKP_DR3);
-      BOOT_LOG_INF("Start OTA 0x%X 0x%X 0x%X", storage_type, offset, update_size);
-      int ota_result = tryOTA(storage_type, offset, update_size);
-      if (ota_result == 0) {
-        // clean reboot with success flag
-        BOOT_LOG_INF("Sketch updated");
+      if (valid_application()) {
+        /* Boot Sketch */
+        BOOT_LOG_INF("Booting sketch at 0x%x\n", APP_DEFAULT_ADD);
         RTCSetBKPRegister(RTC_BKP_DR0, 0);
-        HAL_FLASH_Lock();
-        // wait for external reboot (watchdog)
-        while (1) {}
+        mbed_start_application(APP_DEFAULT_ADD);
       } else {
-        RTCSetBKPRegister(RTC_BKP_DR0, ota_result);
+        BOOT_LOG_INF("No sketch found");
       }
-    }
 
-    if (valid_application()) {
-      /* Boot Sketch */
-      BOOT_LOG_INF("Booting sketch at 0x%x\n", APP_DEFAULT_ADD);
-      mbed_start_application(APP_DEFAULT_ADD);
     } else {
-      BOOT_LOG_INF("No sketch found");
-      return 1;
+      /* MCUboot secure boot */
+      swap_ticker.attach(&swap_feedback, 250ms);
+      RTCSetBKPRegister(RTC_BKP_DR0, 0);
+      start_secure_application();
     }
-
-  } else {
-    /* MCUboot secure boot */
-    swap_ticker.attach(&swap_feedback, 250ms);
-    return 0;
   }
+  target_loop();
+
+  return 0;
 }
 
 #if MCUBOOT_APPLICATION_DFU