Boot: add original files from MCUBoot and Zephyr project
Aligned with MCUBoot version 1.0.0
MCUBoot files:
-- bl2/ext/mcuboot
Aligned with Zephyr version 1.10.0
Zephyr files:
-- bl2/ext/mcuboot/include/util.h
-- platform/ext/target/common/flash.h
Change-Id: I314c3efa2bd2c13a4a2eaefeb5da43e53e988638
Signed-off-by: Tamas Ban <tamas.ban@arm.com>
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil.h b/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil.h
new file mode 100644
index 0000000..5f65866
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil.h
@@ -0,0 +1,96 @@
+/*
+ * 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.
+ */
+
+#ifndef H_BOOTUTIL_
+#define H_BOOTUTIL_
+
+#include <inttypes.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Attempt to boot the contents of slot 0. */
+#define BOOT_SWAP_TYPE_NONE 1
+
+/** Swap to slot 1. Absent a confirm command, revert back on next boot. */
+#define BOOT_SWAP_TYPE_TEST 2
+
+/** Swap to slot 1, and permanently switch to booting its contents. */
+#define BOOT_SWAP_TYPE_PERM 3
+
+/** Swap back to alternate slot. A confirm changes this state to NONE. */
+#define BOOT_SWAP_TYPE_REVERT 4
+
+/** Swap failed because image to be run is not valid */
+#define BOOT_SWAP_TYPE_FAIL 5
+
+/** Swapping encountered an unrecoverable error */
+#define BOOT_SWAP_TYPE_PANIC 0xff
+
+#define MAX_FLASH_ALIGN 8
+extern const uint32_t BOOT_MAX_ALIGN;
+
+struct image_header;
+/**
+ * A response object provided by the boot loader code; indicates where to jump
+ * to execute the main image.
+ */
+struct boot_rsp {
+ /** A pointer to the header of the image to be executed. */
+ const struct image_header *br_hdr;
+
+ /**
+ * The flash offset of the image to execute. Indicates the position of
+ * the image header within its flash device.
+ */
+ uint8_t br_flash_dev_id;
+ uint32_t br_image_off;
+};
+
+/* This is not actually used by mcuboot's code but can be used by apps
+ * when attempting to read/write a trailer.
+ */
+struct image_trailer {
+ uint8_t copy_done;
+ uint8_t pad1[MAX_FLASH_ALIGN - 1];
+ uint8_t image_ok;
+ uint8_t pad2[MAX_FLASH_ALIGN - 1];
+ uint8_t magic[16];
+};
+
+/* you must have pre-allocated all the entries within this structure */
+int boot_go(struct boot_rsp *rsp);
+
+int boot_swap_type(void);
+
+int boot_set_pending(int permanent);
+int boot_set_confirmed(void);
+
+#define SPLIT_GO_OK (0)
+#define SPLIT_GO_NON_MATCHING (-1)
+#define SPLIT_GO_ERR (-2)
+int
+split_go(int loader_slot, int split_slot, void **entry);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil_log.h b/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil_log.h
new file mode 100644
index 0000000..643fc99
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil_log.h
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 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.
+ */
+
+#ifndef H_BOOTUTIL_LOG_H_
+#define H_BOOTUTIL_LOG_H_
+
+#include "ignore.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * When building for targets running Zephyr, delegate to its native
+ * logging subsystem.
+ *
+ * In this case:
+ *
+ * - BOOT_LOG_LEVEL determines SYS_LOG_LEVEL,
+ * - BOOT_LOG_ERR() and friends are SYS_LOG_ERR() etc.
+ * - SYS_LOG_DOMAIN is unconditionally set to "MCUBOOT"
+ */
+#ifdef __ZEPHYR__
+
+#define BOOT_LOG_LEVEL_OFF SYS_LOG_LEVEL_OFF
+#define BOOT_LOG_LEVEL_ERROR SYS_LOG_LEVEL_ERROR
+#define BOOT_LOG_LEVEL_WARNING SYS_LOG_LEVEL_WARNING
+#define BOOT_LOG_LEVEL_INFO SYS_LOG_LEVEL_INFO
+#define BOOT_LOG_LEVEL_DEBUG SYS_LOG_LEVEL_DEBUG
+
+/* Treat BOOT_LOG_LEVEL equivalently to SYS_LOG_LEVEL. */
+#ifndef BOOT_LOG_LEVEL
+#define BOOT_LOG_LEVEL CONFIG_SYS_LOG_DEFAULT_LEVEL
+#elif (BOOT_LOG_LEVEL < CONFIG_SYS_LOG_OVERRIDE_LEVEL)
+#undef BOOT_LOG_LEVEL
+#define BOOT_LOG_LEVEL CONFIG_SYS_LOG_OVERRIDE_LEVEL
+#endif
+
+#define SYS_LOG_LEVEL BOOT_LOG_LEVEL
+
+#undef SYS_LOG_DOMAIN
+#define SYS_LOG_DOMAIN "MCUBOOT"
+
+#define BOOT_LOG_ERR(...) SYS_LOG_ERR(__VA_ARGS__)
+#define BOOT_LOG_WRN(...) SYS_LOG_WRN(__VA_ARGS__)
+#define BOOT_LOG_INF(...) SYS_LOG_INF(__VA_ARGS__)
+#define BOOT_LOG_DBG(...) SYS_LOG_DBG(__VA_ARGS__)
+
+#include <logging/sys_log.h>
+
+/*
+ * When built on the simulator, just use printf().
+ */
+#elif defined(__BOOTSIM__) /* !defined(__ZEPHYR__) */
+
+#include <stdio.h>
+
+#define BOOT_LOG_LEVEL_OFF 0
+#define BOOT_LOG_LEVEL_ERROR 1
+#define BOOT_LOG_LEVEL_WARNING 2
+#define BOOT_LOG_LEVEL_INFO 3
+#define BOOT_LOG_LEVEL_DEBUG 4
+
+/*
+ * The compiled log level determines the maximum level that can be
+ * printed. Messages at or below this level can be printed, provided
+ * they are also enabled through the Rust logging system, such as by
+ * setting RUST_LOG to bootsim::api=info.
+ */
+#ifndef BOOT_LOG_LEVEL
+#define BOOT_LOG_LEVEL BOOT_LOG_LEVEL_INFO
+#endif
+
+int sim_log_enabled(int level);
+
+#if BOOT_LOG_LEVEL >= BOOT_LOG_LEVEL_ERROR
+#define BOOT_LOG_ERR(_fmt, ...) \
+ do { \
+ if (sim_log_enabled(BOOT_LOG_LEVEL_ERROR)) { \
+ fprintf(stderr, "[ERR] " _fmt "\n", ##__VA_ARGS__); \
+ } \
+ } while (0)
+#else
+#define BOOT_LOG_ERR(...) IGNORE(__VA_ARGS__)
+#endif
+
+#if BOOT_LOG_LEVEL >= BOOT_LOG_LEVEL_WARNING
+#define BOOT_LOG_WRN(_fmt, ...) \
+ do { \
+ if (sim_log_enabled(BOOT_LOG_LEVEL_WARNING)) { \
+ fprintf(stderr, "[WRN] " _fmt "\n", ##__VA_ARGS__); \
+ } \
+ } while (0)
+#else
+#define BOOT_LOG_WRN(...) IGNORE(__VA_ARGS__)
+#endif
+
+#if BOOT_LOG_LEVEL >= BOOT_LOG_LEVEL_INFO
+#define BOOT_LOG_INF(_fmt, ...) \
+ do { \
+ if (sim_log_enabled(BOOT_LOG_LEVEL_INFO)) { \
+ fprintf(stderr, "[INF] " _fmt "\n", ##__VA_ARGS__); \
+ } \
+ } while (0)
+#else
+#define BOOT_LOG_INF(...) IGNORE(__VA_ARGS__)
+#endif
+
+#if BOOT_LOG_LEVEL >= BOOT_LOG_LEVEL_DEBUG
+#define BOOT_LOG_DBG(_fmt, ...) \
+ do { \
+ if (sim_log_enabled(BOOT_LOG_LEVEL_DEBUG)) { \
+ fprintf(stderr, "[DBG] " _fmt "\n", ##__VA_ARGS__); \
+ } \
+ } while (0)
+#else
+#define BOOT_LOG_DBG(...) IGNORE(__VA_ARGS__)
+#endif
+
+/*
+ * In other environments, logging calls are no-ops.
+ */
+#else /* !defined(__BOOTSIM__) */
+
+#define BOOT_LOG_LEVEL_OFF 0
+#define BOOT_LOG_LEVEL_ERROR 1
+#define BOOT_LOG_LEVEL_WARNING 2
+#define BOOT_LOG_LEVEL_INFO 3
+#define BOOT_LOG_LEVEL_DEBUG 4
+
+#define BOOT_LOG_ERR(...) IGNORE(__VA_ARGS__)
+#define BOOT_LOG_WRN(...) IGNORE(__VA_ARGS__)
+#define BOOT_LOG_INF(...) IGNORE(__VA_ARGS__)
+#define BOOT_LOG_DBG(...) IGNORE(__VA_ARGS__)
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil_test.h b/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil_test.h
new file mode 100644
index 0000000..4188bb1
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil_test.h
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+
+#ifndef H_BOOTUTIL_TEST_
+#define H_BOOTUTIL_TEST_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int boot_test_all(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/caps.h b/bl2/ext/mcuboot/bootutil/include/bootutil/caps.h
new file mode 100644
index 0000000..a0c324a
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/include/bootutil/caps.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 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.
+ */
+
+#ifndef H_BOOTUTIL_CAPS_H_
+#define H_BOOTUTIL_CAPS_H_
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * The bootloader can be compile with different capabilities selected
+ * at compile time. This function provides runtime access to these
+ * capabilities. This is intended primarily for testing, although
+ * these will possibly be available at runtime to the application
+ * running within the bootloader.
+ */
+uint32_t bootutil_get_caps(void);
+
+#define BOOTUTIL_CAP_RSA2048 (1<<0)
+#define BOOTUTIL_CAP_ECDSA_P224 (1<<1)
+#define BOOTUTIL_CAP_ECDSA_P256 (1<<2)
+#define BOOTUTIL_CAP_SWAP_UPGRADE (1<<3)
+#define BOOTUTIL_CAP_OVERWRITE_UPGRADE (1<<4)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/ignore.h b/bl2/ext/mcuboot/bootutil/include/bootutil/ignore.h
new file mode 100644
index 0000000..46282a0
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/include/bootutil/ignore.h
@@ -0,0 +1,64 @@
+/*
+ * 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.
+ */
+
+#ifndef H_IGNORE_
+#define H_IGNORE_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * These macros prevent the "set but not used" warnings for log writes below
+ * the log level.
+ */
+
+#define IGN_1(X) ((void)(X))
+#define IGN_2(X, ...) ((void)(X));IGN_1(__VA_ARGS__)
+#define IGN_3(X, ...) ((void)(X));IGN_2(__VA_ARGS__)
+#define IGN_4(X, ...) ((void)(X));IGN_3(__VA_ARGS__)
+#define IGN_5(X, ...) ((void)(X));IGN_4(__VA_ARGS__)
+#define IGN_6(X, ...) ((void)(X));IGN_5(__VA_ARGS__)
+#define IGN_7(X, ...) ((void)(X));IGN_6(__VA_ARGS__)
+#define IGN_8(X, ...) ((void)(X));IGN_7(__VA_ARGS__)
+#define IGN_9(X, ...) ((void)(X));IGN_8(__VA_ARGS__)
+#define IGN_10(X, ...) ((void)(X));IGN_9(__VA_ARGS__)
+#define IGN_11(X, ...) ((void)(X));IGN_10(__VA_ARGS__)
+#define IGN_12(X, ...) ((void)(X));IGN_11(__VA_ARGS__)
+#define IGN_13(X, ...) ((void)(X));IGN_12(__VA_ARGS__)
+#define IGN_14(X, ...) ((void)(X));IGN_13(__VA_ARGS__)
+#define IGN_15(X, ...) ((void)(X));IGN_14(__VA_ARGS__)
+#define IGN_16(X, ...) ((void)(X));IGN_15(__VA_ARGS__)
+#define IGN_17(X, ...) ((void)(X));IGN_16(__VA_ARGS__)
+#define IGN_18(X, ...) ((void)(X));IGN_17(__VA_ARGS__)
+#define IGN_19(X, ...) ((void)(X));IGN_18(__VA_ARGS__)
+#define IGN_20(X, ...) ((void)(X));IGN_19(__VA_ARGS__)
+
+#define GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, \
+ _13, _14, _15, _16, _17, _18, _19, _20, NAME, ...) NAME
+#define IGNORE(...) \
+ GET_MACRO(__VA_ARGS__, IGN_20, IGN_19, IGN_18, IGN_17, IGN_16, IGN_15, \
+ IGN_14, IGN_13, IGN_12, IGN_11, IGN_10, IGN_9, IGN_8, IGN_7, \
+ IGN_6, IGN_5, IGN_4, IGN_3, IGN_2, IGN_1)(__VA_ARGS__)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/image.h b/bl2/ext/mcuboot/bootutil/include/bootutil/image.h
new file mode 100644
index 0000000..10e7be0
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/include/bootutil/image.h
@@ -0,0 +1,115 @@
+/*
+ * 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.
+ */
+
+#ifndef H_IMAGE_
+#define H_IMAGE_
+
+#include <inttypes.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct flash_area;
+
+#define IMAGE_MAGIC 0x96f3b83d
+#define IMAGE_MAGIC_V1 0x96f3b83c
+#define IMAGE_MAGIC_NONE 0xffffffff
+#define IMAGE_TLV_INFO_MAGIC 0x6907
+
+#define IMAGE_HEADER_SIZE 32
+
+/*
+ * Image header flags.
+ */
+#define IMAGE_F_PIC 0x00000001 /* Not supported. */
+#define IMAGE_F_NON_BOOTABLE 0x00000010 /* Split image app. */
+/*
+ * Indicates that this image should be loaded into RAM instead of run
+ * directly from flash. The address to load should be in the
+ * ih_load_addr field of the header.
+ */
+#define IMAGE_F_RAM_LOAD 0x00000020
+
+/*
+ * ECSDA224 is with NIST P-224
+ * ECSDA256 is with NIST P-256
+ */
+
+/*
+ * Image trailer TLV types.
+ *
+ * Signature is generated by computing signature over the image hash.
+ * Currently the only image hash type is SHA256.
+ *
+ * Signature comes in the form of 2 TLVs.
+ * 1st on identifies the public key which should be used to verify it.
+ * 2nd one is the actual signature.
+ */
+#define IMAGE_TLV_KEYHASH 0x01 /* hash of the public key */
+#define IMAGE_TLV_SHA256 0x10 /* SHA256 of image hdr and body */
+#define IMAGE_TLV_RSA2048_PSS 0x20 /* RSA2048 of hash output */
+#define IMAGE_TLV_ECDSA224 0x21 /* ECDSA of hash output */
+#define IMAGE_TLV_ECDSA256 0x22 /* ECDSA of hash output */
+
+struct image_version {
+ uint8_t iv_major;
+ uint8_t iv_minor;
+ uint16_t iv_revision;
+ uint32_t iv_build_num;
+};
+
+/** Image header. All fields are in little endian byte order. */
+struct image_header {
+ uint32_t ih_magic;
+ uint32_t ih_load_addr;
+ uint16_t ih_hdr_size; /* Size of image header (bytes). */
+ uint16_t _pad2;
+ uint32_t ih_img_size; /* Does not include header. */
+ uint32_t ih_flags; /* IMAGE_F_[...]. */
+ struct image_version ih_ver;
+ uint32_t _pad3;
+};
+
+/** Image TLV header. All fields in little endian. */
+struct image_tlv_info {
+ uint16_t it_magic;
+ uint16_t it_tlv_tot; /* size of TLV area (including tlv_info header) */
+};
+
+/** Image trailer TLV format. All fields in little endian. */
+struct image_tlv {
+ uint8_t it_type; /* IMAGE_TLV_[...]. */
+ uint8_t _pad;
+ uint16_t it_len; /* Data length (not including TLV header). */
+};
+
+_Static_assert(sizeof(struct image_header) == IMAGE_HEADER_SIZE,
+ "struct image_header not required size");
+
+int bootutil_img_validate(struct image_header *hdr,
+ const struct flash_area *fap,
+ uint8_t *tmp_buf, uint32_t tmp_buf_sz,
+ uint8_t *seed, int seed_len, uint8_t *out_hash);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/sha256.h b/bl2/ext/mcuboot/bootutil/include/bootutil/sha256.h
new file mode 100644
index 0000000..cc52b07
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/include/bootutil/sha256.h
@@ -0,0 +1,106 @@
+/*
+ * 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.
+ */
+
+/*
+ * This module provides a thin abstraction over some of the crypto
+ * primitives to make it easier to swap out the used crypto library.
+ *
+ * At this point, there are two choices: MCUBOOT_USE_MBED_TLS, or
+ * MCUBOOT_USE_TINYCRYPT. It is a compile error there is not exactly
+ * one of these defined.
+ */
+
+#ifndef __BOOTUTIL_CRYPTO_H_
+#define __BOOTUTIL_CRYPTO_H_
+
+#ifdef MCUBOOT_MYNEWT
+#include "mcuboot_config/mcuboot_config.h"
+#endif
+
+#if defined(MCUBOOT_USE_MBED_TLS) && defined(MCUBOOT_USE_TINYCRYPT)
+ #error "Cannot define both MBED_TLS and TINYCRYPT"
+#endif
+
+#if !defined(MCUBOOT_USE_MBED_TLS) && !defined(MCUBOOT_USE_TINYCRYPT)
+ #error "One of MBED_TLS or TINYCRYPT must be defined"
+#endif
+
+#ifdef MCUBOOT_USE_MBED_TLS
+ #include <mbedtls/sha256.h>
+#endif /* MCUBOOT_USE_MBED_TLS */
+
+#ifdef MCUBOOT_USE_TINYCRYPT
+ #include <tinycrypt/sha256.h>
+#endif /* MCUBOOT_USE_TINYCRYPT */
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef MCUBOOT_USE_MBED_TLS
+typedef mbedtls_sha256_context bootutil_sha256_context;
+
+static inline void bootutil_sha256_init(bootutil_sha256_context *ctx)
+{
+ mbedtls_sha256_init(ctx);
+ mbedtls_sha256_starts(ctx, 0);
+}
+
+static inline void bootutil_sha256_update(bootutil_sha256_context *ctx,
+ const void *data,
+ uint32_t data_len)
+{
+ mbedtls_sha256_update(ctx, data, data_len);
+}
+
+static inline void bootutil_sha256_finish(bootutil_sha256_context *ctx,
+ uint8_t *output)
+{
+ mbedtls_sha256_finish(ctx, output);
+}
+#endif /* MCUBOOT_USE_MBED_TLS */
+
+#ifdef MCUBOOT_USE_TINYCRYPT
+typedef struct tc_sha256_state_struct bootutil_sha256_context;
+static inline void bootutil_sha256_init(bootutil_sha256_context *ctx)
+{
+ tc_sha256_init(ctx);
+}
+
+static inline void bootutil_sha256_update(bootutil_sha256_context *ctx,
+ const void *data,
+ uint32_t data_len)
+{
+ tc_sha256_update(ctx, data, data_len);
+}
+
+static inline void bootutil_sha256_finish(bootutil_sha256_context *ctx,
+ uint8_t *output)
+{
+ tc_sha256_final(output, ctx);
+}
+#endif /* MCUBOOT_USE_TINYCRYPT */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BOOTUTIL_SIGN_KEY_H_ */
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/sign_key.h b/bl2/ext/mcuboot/bootutil/include/bootutil/sign_key.h
new file mode 100644
index 0000000..47b2570
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/include/bootutil/sign_key.h
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+
+#ifndef __BOOTUTIL_SIGN_KEY_H_
+#define __BOOTUTIL_SIGN_KEY_H_
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct bootutil_key {
+ const uint8_t *key;
+ const unsigned int *len;
+};
+
+extern const struct bootutil_key bootutil_keys[];
+extern const int bootutil_key_cnt;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BOOTUTIL_SIGN_KEY_H_ */
diff --git a/bl2/ext/mcuboot/bootutil/src/bootutil_misc.c b/bl2/ext/mcuboot/bootutil/src/bootutil_misc.c
new file mode 100644
index 0000000..bf4e9b8
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/src/bootutil_misc.c
@@ -0,0 +1,559 @@
+/*
+ * 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.
+ */
+
+#include <assert.h>
+#include <string.h>
+#include <inttypes.h>
+#include <stddef.h>
+
+#include "sysflash/sysflash.h"
+#include "hal/hal_bsp.h"
+#include "hal/hal_flash.h"
+#include "flash_map/flash_map.h"
+#include "os/os.h"
+#include "bootutil/image.h"
+#include "bootutil/bootutil.h"
+#include "bootutil_priv.h"
+
+#define BOOT_LOG_LEVEL BOOT_LOG_LEVEL_INFO
+#include "bootutil/bootutil_log.h"
+
+int boot_current_slot;
+
+const uint32_t boot_img_magic[] = {
+ 0xf395c277,
+ 0x7fefd260,
+ 0x0f505235,
+ 0x8079b62c,
+};
+
+const uint32_t BOOT_MAGIC_SZ = sizeof boot_img_magic;
+const uint32_t BOOT_MAX_ALIGN = MAX_FLASH_ALIGN;
+
+struct boot_swap_table {
+ /** * For each field, a value of 0 means "any". */
+ uint8_t magic_slot0;
+ uint8_t magic_slot1;
+ uint8_t image_ok_slot0;
+ uint8_t image_ok_slot1;
+ uint8_t copy_done_slot0;
+
+ uint8_t swap_type;
+};
+
+/**
+ * This set of tables maps image trailer contents to swap operation type.
+ * When searching for a match, these tables must be iterated sequentially.
+ *
+ * NOTE: the table order is very important. The settings in Slot 1 always
+ * are priority to Slot 0 and should be located earlier in the table.
+ *
+ * The table lists only states where there is action needs to be taken by
+ * the bootloader, as in starting/finishing a swap operation.
+ */
+static const struct boot_swap_table boot_swap_tables[] = {
+ {
+ .magic_slot0 = 0,
+ .magic_slot1 = BOOT_MAGIC_GOOD,
+ .image_ok_slot0 = 0,
+ .image_ok_slot1 = 0xff,
+ .copy_done_slot0 = 0,
+ .swap_type = BOOT_SWAP_TYPE_TEST,
+ },
+ {
+ .magic_slot0 = 0,
+ .magic_slot1 = BOOT_MAGIC_GOOD,
+ .image_ok_slot0 = 0,
+ .image_ok_slot1 = 0x01,
+ .copy_done_slot0 = 0,
+ .swap_type = BOOT_SWAP_TYPE_PERM,
+ },
+ {
+ .magic_slot0 = BOOT_MAGIC_GOOD,
+ .magic_slot1 = BOOT_MAGIC_UNSET,
+ .image_ok_slot0 = 0xff,
+ .image_ok_slot1 = 0,
+ .copy_done_slot0 = 0x01,
+ .swap_type = BOOT_SWAP_TYPE_REVERT,
+ },
+};
+
+#define BOOT_SWAP_TABLES_COUNT \
+ (sizeof boot_swap_tables / sizeof boot_swap_tables[0])
+
+int
+boot_magic_code(const uint32_t *magic)
+{
+ int i;
+
+ if (memcmp(magic, boot_img_magic, BOOT_MAGIC_SZ) == 0) {
+ return BOOT_MAGIC_GOOD;
+ }
+
+ for (i = 0; i < BOOT_MAGIC_SZ / sizeof *magic; i++) {
+ if (magic[i] != 0xffffffff) {
+ return BOOT_MAGIC_BAD;
+ }
+ }
+
+ return BOOT_MAGIC_UNSET;
+}
+
+uint32_t
+boot_slots_trailer_sz(uint8_t min_write_sz)
+{
+ return /* state for all sectors */
+ BOOT_STATUS_MAX_ENTRIES * BOOT_STATUS_STATE_COUNT * min_write_sz +
+ BOOT_MAX_ALIGN * 3 /* copy_done + image_ok + swap_size */ +
+ BOOT_MAGIC_SZ;
+}
+
+static uint32_t
+boot_scratch_trailer_sz(uint8_t min_write_sz)
+{
+ return BOOT_STATUS_STATE_COUNT * min_write_sz + /* state for one sector */
+ BOOT_MAX_ALIGN * 2 + /* image_ok + swap_size */
+ BOOT_MAGIC_SZ;
+}
+
+static uint32_t
+boot_magic_off(const struct flash_area *fap)
+{
+ assert(offsetof(struct image_trailer, magic) == 16);
+ return fap->fa_size - BOOT_MAGIC_SZ;
+}
+
+int
+boot_status_entries(const struct flash_area *fap)
+{
+ switch (fap->fa_id) {
+ case FLASH_AREA_IMAGE_0:
+ case FLASH_AREA_IMAGE_1:
+ return BOOT_STATUS_STATE_COUNT * BOOT_STATUS_MAX_ENTRIES;
+ case FLASH_AREA_IMAGE_SCRATCH:
+ return BOOT_STATUS_STATE_COUNT;
+ default:
+ return BOOT_EBADARGS;
+ }
+}
+
+uint32_t
+boot_status_off(const struct flash_area *fap)
+{
+ uint32_t off_from_end;
+ uint8_t elem_sz;
+
+ elem_sz = flash_area_align(fap);
+
+ if (fap->fa_id == FLASH_AREA_IMAGE_SCRATCH) {
+ off_from_end = boot_scratch_trailer_sz(elem_sz);
+ } else {
+ off_from_end = boot_slots_trailer_sz(elem_sz);
+ }
+
+ assert(off_from_end <= fap->fa_size);
+ return fap->fa_size - off_from_end;
+}
+
+static uint32_t
+boot_copy_done_off(const struct flash_area *fap)
+{
+ assert(fap->fa_id != FLASH_AREA_IMAGE_SCRATCH);
+ assert(offsetof(struct image_trailer, copy_done) == 0);
+ return fap->fa_size - BOOT_MAGIC_SZ - BOOT_MAX_ALIGN * 2;
+}
+
+static uint32_t
+boot_image_ok_off(const struct flash_area *fap)
+{
+ assert(offsetof(struct image_trailer, image_ok) == 8);
+ return fap->fa_size - BOOT_MAGIC_SZ - BOOT_MAX_ALIGN;
+}
+
+static uint32_t
+boot_swap_size_off(const struct flash_area *fap)
+{
+ /*
+ * The "swap_size" field if located just before the trailer.
+ * The scratch slot doesn't store "copy_done"...
+ */
+ if (fap->fa_id == FLASH_AREA_IMAGE_SCRATCH) {
+ return fap->fa_size - BOOT_MAGIC_SZ - BOOT_MAX_ALIGN * 2;
+ }
+
+ return fap->fa_size - BOOT_MAGIC_SZ - BOOT_MAX_ALIGN * 3;
+}
+
+int
+boot_read_swap_state(const struct flash_area *fap,
+ struct boot_swap_state *state)
+{
+ uint32_t magic[BOOT_MAGIC_SZ];
+ uint32_t off;
+ int rc;
+
+ off = boot_magic_off(fap);
+ rc = flash_area_read(fap, off, magic, BOOT_MAGIC_SZ);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+ state->magic = boot_magic_code(magic);
+
+ if (fap->fa_id != FLASH_AREA_IMAGE_SCRATCH) {
+ off = boot_copy_done_off(fap);
+ rc = flash_area_read(fap, off, &state->copy_done, sizeof state->copy_done);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+ }
+
+ off = boot_image_ok_off(fap);
+ rc = flash_area_read(fap, off, &state->image_ok, sizeof state->image_ok);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+
+ return 0;
+}
+
+/**
+ * Reads the image trailer from the scratch area.
+ */
+int
+boot_read_swap_state_by_id(int flash_area_id, struct boot_swap_state *state)
+{
+ const struct flash_area *fap;
+ int rc;
+
+ switch (flash_area_id) {
+ case FLASH_AREA_IMAGE_SCRATCH:
+ case FLASH_AREA_IMAGE_0:
+ case FLASH_AREA_IMAGE_1:
+ rc = flash_area_open(flash_area_id, &fap);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+ break;
+ default:
+ return BOOT_EBADARGS;
+ }
+
+ rc = boot_read_swap_state(fap, state);
+ flash_area_close(fap);
+ return rc;
+}
+
+int
+boot_read_swap_size(uint32_t *swap_size)
+{
+ uint32_t magic[BOOT_MAGIC_SZ];
+ uint32_t off;
+ const struct flash_area *fap;
+ int rc;
+
+ /*
+ * In the middle a swap, tries to locate the saved swap size. Looks
+ * for a valid magic, first on Slot 0, then on scratch. Both "slots"
+ * can end up being temporary storage for a swap and it is assumed
+ * that if magic is valid then swap size is too, because magic is
+ * always written in the last step.
+ */
+
+ rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+
+ off = boot_magic_off(fap);
+ rc = flash_area_read(fap, off, magic, BOOT_MAGIC_SZ);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto out;
+ }
+
+ if (memcmp(magic, boot_img_magic, BOOT_MAGIC_SZ) != 0) {
+ /*
+ * If Slot 0 's magic is not valid, try scratch...
+ */
+
+ flash_area_close(fap);
+
+ rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH, &fap);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+
+ off = boot_magic_off(fap);
+ rc = flash_area_read(fap, off, magic, BOOT_MAGIC_SZ);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto out;
+ }
+
+ assert(memcmp(magic, boot_img_magic, BOOT_MAGIC_SZ) == 0);
+ }
+
+ off = boot_swap_size_off(fap);
+ rc = flash_area_read(fap, off, swap_size, sizeof *swap_size);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ }
+
+out:
+ flash_area_close(fap);
+ return rc;
+}
+
+
+int
+boot_write_magic(const struct flash_area *fap)
+{
+ uint32_t off;
+ int rc;
+
+ off = boot_magic_off(fap);
+
+ rc = flash_area_write(fap, off, boot_img_magic, BOOT_MAGIC_SZ);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+
+ return 0;
+}
+
+static int
+boot_write_flag(int flag, const struct flash_area *fap)
+{
+ uint32_t off;
+ int rc;
+ uint8_t buf[BOOT_MAX_ALIGN];
+ uint8_t align;
+
+ switch (flag) {
+ case BOOT_FLAG_COPY_DONE:
+ off = boot_copy_done_off(fap);
+ break;
+ case BOOT_FLAG_IMAGE_OK:
+ off = boot_image_ok_off(fap);
+ break;
+ default:
+ return BOOT_EBADARGS;
+ }
+
+ align = hal_flash_align(fap->fa_device_id);
+ assert(align <= BOOT_MAX_ALIGN);
+ memset(buf, 0xFF, BOOT_MAX_ALIGN);
+ buf[0] = BOOT_FLAG_SET;
+
+ rc = flash_area_write(fap, off, buf, align);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+
+ return 0;
+}
+
+int
+boot_write_copy_done(const struct flash_area *fap)
+{
+ return boot_write_flag(BOOT_FLAG_COPY_DONE, fap);
+}
+
+int
+boot_write_image_ok(const struct flash_area *fap)
+{
+ return boot_write_flag(BOOT_FLAG_IMAGE_OK, fap);
+}
+
+int
+boot_write_swap_size(const struct flash_area *fap, uint32_t swap_size)
+{
+ uint32_t off;
+ int rc;
+ uint8_t buf[BOOT_MAX_ALIGN];
+ uint8_t align;
+
+ off = boot_swap_size_off(fap);
+ align = hal_flash_align(fap->fa_device_id);
+ assert(align <= BOOT_MAX_ALIGN);
+ if (align < sizeof swap_size) {
+ align = sizeof swap_size;
+ }
+ memset(buf, 0xFF, BOOT_MAX_ALIGN);
+ memcpy(buf, (uint8_t *)&swap_size, sizeof swap_size);
+
+ rc = flash_area_write(fap, off, buf, align);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+
+ return 0;
+}
+
+int
+boot_swap_type(void)
+{
+ const struct boot_swap_table *table;
+ struct boot_swap_state slot0;
+ struct boot_swap_state slot1;
+ int rc;
+ int i;
+
+ rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_0, &slot0);
+ if (rc) {
+ return BOOT_SWAP_TYPE_PANIC;
+ }
+
+ rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_1, &slot1);
+ if (rc) {
+ return BOOT_SWAP_TYPE_PANIC;
+ }
+
+ for (i = 0; i < BOOT_SWAP_TABLES_COUNT; i++) {
+ table = boot_swap_tables + i;
+
+ if ((!table->magic_slot0 || table->magic_slot0 == slot0.magic ) &&
+ (!table->magic_slot1 || table->magic_slot1 == slot1.magic ) &&
+ (!table->image_ok_slot0 || table->image_ok_slot0 == slot0.image_ok ) &&
+ (!table->image_ok_slot1 || table->image_ok_slot1 == slot1.image_ok ) &&
+ (!table->copy_done_slot0 || table->copy_done_slot0 == slot0.copy_done)) {
+ BOOT_LOG_INF("Swap type: %s",
+ table->swap_type == BOOT_SWAP_TYPE_TEST ? "test" :
+ table->swap_type == BOOT_SWAP_TYPE_PERM ? "perm" :
+ table->swap_type == BOOT_SWAP_TYPE_REVERT ? "revert" :
+ "BUG; can't happen");
+ assert(table->swap_type == BOOT_SWAP_TYPE_TEST ||
+ table->swap_type == BOOT_SWAP_TYPE_PERM ||
+ table->swap_type == BOOT_SWAP_TYPE_REVERT);
+ return table->swap_type;
+ }
+ }
+
+ BOOT_LOG_INF("Swap type: none");
+ return BOOT_SWAP_TYPE_NONE;
+}
+
+/**
+ * Marks the image in slot 1 as pending. On the next reboot, the system will
+ * perform a one-time boot of the slot 1 image.
+ *
+ * @param permanent Whether the image should be used permanently or
+ * only tested once:
+ * 0=run image once, then confirm or revert.
+ * 1=run image forever.
+ *
+ * @return 0 on success; nonzero on failure.
+ */
+int
+boot_set_pending(int permanent)
+{
+ const struct flash_area *fap;
+ struct boot_swap_state state_slot1;
+ int rc;
+
+ rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_1, &state_slot1);
+ if (rc != 0) {
+ return rc;
+ }
+
+ switch (state_slot1.magic) {
+ case BOOT_MAGIC_GOOD:
+ /* Swap already scheduled. */
+ return 0;
+
+ case BOOT_MAGIC_UNSET:
+ rc = flash_area_open(FLASH_AREA_IMAGE_1, &fap);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ } else {
+ rc = boot_write_magic(fap);
+ }
+
+ if (rc == 0 && permanent) {
+ rc = boot_write_image_ok(fap);
+ }
+
+ flash_area_close(fap);
+ return rc;
+
+ default:
+ /* XXX: Temporary assert. */
+ assert(0);
+ return -1;
+ }
+}
+
+/**
+ * Marks the image in slot 0 as confirmed. The system will continue booting into the image in slot 0 until told to boot from a different slot.
+ *
+ * @return 0 on success; nonzero on failure.
+ */
+int
+boot_set_confirmed(void)
+{
+ const struct flash_area *fap;
+ struct boot_swap_state state_slot0;
+ int rc;
+
+ rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_0, &state_slot0);
+ if (rc != 0) {
+ return rc;
+ }
+
+ switch (state_slot0.magic) {
+ case BOOT_MAGIC_GOOD:
+ /* Confirm needed; proceed. */
+ break;
+
+ case BOOT_MAGIC_UNSET:
+ /* Already confirmed. */
+ return 0;
+
+ case BOOT_MAGIC_BAD:
+ /* Unexpected state. */
+ return BOOT_EBADVECT;
+ }
+
+ if (state_slot0.copy_done == BOOT_FLAG_UNSET) {
+ /* Swap never completed. This is unexpected. */
+ return BOOT_EBADVECT;
+ }
+
+ if (state_slot0.image_ok != BOOT_FLAG_UNSET) {
+ /* Already confirmed. */
+ return 0;
+ }
+
+ rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+ if (rc) {
+ rc = BOOT_EFLASH;
+ goto done;
+ }
+
+ rc = boot_write_image_ok(fap);
+ if (rc != 0) {
+ goto done;
+ }
+
+ rc = 0;
+
+done:
+ flash_area_close(fap);
+ return rc;
+}
diff --git a/bl2/ext/mcuboot/bootutil/src/bootutil_priv.h b/bl2/ext/mcuboot/bootutil/src/bootutil_priv.h
new file mode 100644
index 0000000..c1cf779
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/src/bootutil_priv.h
@@ -0,0 +1,300 @@
+/*
+ * 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.
+ */
+
+#ifndef H_BOOTUTIL_PRIV_
+#define H_BOOTUTIL_PRIV_
+
+#include "sysflash/sysflash.h"
+#include "flash_map/flash_map.h"
+#include "bootutil/image.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct flash_area;
+
+#define BOOT_EFLASH 1
+#define BOOT_EFILE 2
+#define BOOT_EBADIMAGE 3
+#define BOOT_EBADVECT 4
+#define BOOT_EBADSTATUS 5
+#define BOOT_ENOMEM 6
+#define BOOT_EBADARGS 7
+
+#define BOOT_TMPBUF_SZ 256
+
+/*
+ * Maintain state of copy progress.
+ */
+struct boot_status {
+ uint32_t idx; /* Which area we're operating on */
+ uint8_t state; /* Which part of the swapping process are we at */
+ uint8_t use_scratch; /* Are status bytes ever written to scratch? */
+ uint32_t swap_size; /* Total size of swapped image */
+};
+
+#define BOOT_MAGIC_GOOD 1
+#define BOOT_MAGIC_BAD 2
+#define BOOT_MAGIC_UNSET 3
+
+/**
+ * End-of-image slot structure.
+ *
+ * 0 1 2 3
+ * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * ~ ~
+ * ~ Swap status (variable, aligned) ~
+ * ~ ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * | Swap size |
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * ~ 0xff padding (MAX ALIGN - 4) ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * | Copy done | 0xff padding (MAX ALIGN - 1) ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * | Image OK | 0xff padding (MAX ALIGN - 1) ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * ~ MAGIC (16 octets) ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ */
+
+extern const uint32_t boot_img_magic[4];
+
+struct boot_swap_state {
+ uint8_t magic; /* One of the BOOT_MAGIC_[...] values. */
+ uint8_t copy_done;
+ uint8_t image_ok;
+};
+
+#define BOOT_STATUS_STATE_COUNT 3
+#define BOOT_STATUS_MAX_ENTRIES 128
+
+#define BOOT_STATUS_SOURCE_NONE 0
+#define BOOT_STATUS_SOURCE_SCRATCH 1
+#define BOOT_STATUS_SOURCE_SLOT0 2
+
+#define BOOT_FLAG_IMAGE_OK 0
+#define BOOT_FLAG_COPY_DONE 1
+
+#define BOOT_FLAG_SET 0x01
+#define BOOT_FLAG_UNSET 0xff
+
+extern const uint32_t BOOT_MAGIC_SZ;
+
+/** Number of image slots in flash; currently limited to two. */
+#define BOOT_NUM_SLOTS 2
+
+/** Maximum number of image sectors supported by the bootloader. */
+#define BOOT_MAX_IMG_SECTORS 120
+
+/**
+ * Compatibility shim for flash sector type.
+ *
+ * This can be deleted when flash_area_to_sectors() is removed.
+ */
+#ifdef MCUBOOT_USE_FLASH_AREA_GET_SECTORS
+typedef struct flash_sector boot_sector_t;
+#else
+typedef struct flash_area boot_sector_t;
+#endif
+
+/** Private state maintained during boot. */
+struct boot_loader_state {
+ struct {
+ struct image_header hdr;
+ const struct flash_area *area;
+ boot_sector_t *sectors;
+ size_t num_sectors;
+ } imgs[BOOT_NUM_SLOTS];
+
+ const struct flash_area *scratch_area;
+
+ uint8_t write_sz;
+};
+
+int bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen,
+ uint8_t key_id);
+
+uint32_t boot_slots_trailer_sz(uint8_t min_write_sz);
+int boot_status_entries(const struct flash_area *fap);
+uint32_t boot_status_off(const struct flash_area *fap);
+int boot_read_swap_state(const struct flash_area *fap,
+ struct boot_swap_state *state);
+int boot_read_swap_state_by_id(int flash_area_id,
+ struct boot_swap_state *state);
+int boot_write_magic(const struct flash_area *fap);
+int boot_write_status(struct boot_status *bs);
+int boot_schedule_test_swap(void);
+int boot_write_copy_done(const struct flash_area *fap);
+int boot_write_image_ok(const struct flash_area *fap);
+int boot_write_swap_size(const struct flash_area *fap, uint32_t swap_size);
+int boot_read_swap_size(uint32_t *swap_size);
+
+/*
+ * Accessors for the contents of struct boot_loader_state.
+ */
+
+/* These are macros so they can be used as lvalues. */
+#define BOOT_IMG_AREA(state, slot) ((state)->imgs[(slot)].area)
+#define BOOT_SCRATCH_AREA(state) ((state)->scratch_area)
+#define BOOT_WRITE_SZ(state) ((state)->write_sz)
+
+static inline struct image_header*
+boot_img_hdr(struct boot_loader_state *state, size_t slot)
+{
+ return &state->imgs[slot].hdr;
+}
+
+static inline uint8_t
+boot_img_fa_device_id(struct boot_loader_state *state, size_t slot)
+{
+ return state->imgs[slot].area->fa_device_id;
+}
+
+static inline uint8_t
+boot_scratch_fa_device_id(struct boot_loader_state *state)
+{
+ return state->scratch_area->fa_device_id;
+}
+
+static inline size_t
+boot_img_num_sectors(struct boot_loader_state *state, size_t slot)
+{
+ return state->imgs[slot].num_sectors;
+}
+
+/*
+ * Offset of the slot from the beginning of the flash device.
+ */
+static inline uint32_t
+boot_img_slot_off(struct boot_loader_state *state, size_t slot)
+{
+ return state->imgs[slot].area->fa_off;
+}
+
+static inline size_t boot_scratch_area_size(struct boot_loader_state *state)
+{
+ return state->scratch_area->fa_size;
+}
+
+#ifndef MCUBOOT_USE_FLASH_AREA_GET_SECTORS
+
+static inline size_t
+boot_img_sector_size(struct boot_loader_state *state,
+ size_t slot, size_t sector)
+{
+ return state->imgs[slot].sectors[sector].fa_size;
+}
+
+/*
+ * Offset of the sector from the beginning of the image, NOT the flash
+ * device.
+ */
+static inline uint32_t
+boot_img_sector_off(struct boot_loader_state *state, size_t slot,
+ size_t sector)
+{
+ return state->imgs[slot].sectors[sector].fa_off -
+ state->imgs[slot].sectors[0].fa_off;
+}
+
+static inline int
+boot_initialize_area(struct boot_loader_state *state, int flash_area)
+{
+ int num_sectors = BOOT_MAX_IMG_SECTORS;
+ size_t slot;
+ int rc;
+
+ switch (flash_area) {
+ case FLASH_AREA_IMAGE_0:
+ slot = 0;
+ break;
+ case FLASH_AREA_IMAGE_1:
+ slot = 1;
+ break;
+ default:
+ return BOOT_EFLASH;
+ }
+
+ rc = flash_area_to_sectors(flash_area, &num_sectors,
+ state->imgs[slot].sectors);
+ if (rc != 0) {
+ return rc;
+ }
+ state->imgs[slot].num_sectors = (size_t)num_sectors;
+ return 0;
+}
+
+#else /* defined(MCUBOOT_USE_FLASH_AREA_GET_SECTORS) */
+
+static inline size_t
+boot_img_sector_size(struct boot_loader_state *state,
+ size_t slot, size_t sector)
+{
+ return state->imgs[slot].sectors[sector].fs_size;
+}
+
+static inline uint32_t
+boot_img_sector_off(struct boot_loader_state *state, size_t slot,
+ size_t sector)
+{
+ return state->imgs[slot].sectors[sector].fs_off -
+ state->imgs[slot].sectors[0].fs_off;
+}
+
+static inline int
+boot_initialize_area(struct boot_loader_state *state, int flash_area)
+{
+ uint32_t num_sectors;
+ struct flash_sector *out_sectors;
+ size_t *out_num_sectors;
+ int rc;
+
+ switch (flash_area) {
+ case FLASH_AREA_IMAGE_0:
+ num_sectors = BOOT_MAX_IMG_SECTORS;
+ out_sectors = state->imgs[0].sectors;
+ out_num_sectors = &state->imgs[0].num_sectors;
+ break;
+ case FLASH_AREA_IMAGE_1:
+ num_sectors = BOOT_MAX_IMG_SECTORS;
+ out_sectors = state->imgs[1].sectors;
+ out_num_sectors = &state->imgs[1].num_sectors;
+ break;
+ default:
+ return -1;
+ }
+
+ rc = flash_area_get_sectors(flash_area, &num_sectors, out_sectors);
+ if (rc != 0) {
+ return rc;
+ }
+ *out_num_sectors = num_sectors;
+ return 0;
+}
+
+#endif /* !defined(MCUBOOT_USE_FLASH_AREA_GET_SECTORS) */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/bl2/ext/mcuboot/bootutil/src/caps.c b/bl2/ext/mcuboot/bootutil/src/caps.c
new file mode 100644
index 0000000..61d4f3f
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/src/caps.c
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 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.
+ */
+
+#include <bootutil/caps.h>
+
+uint32_t bootutil_get_caps(void)
+{
+ uint32_t res = 0;
+
+#if defined(MCUBOOT_SIGN_RSA)
+ res |= BOOTUTIL_CAP_RSA2048;
+#endif
+#if defined(MCUBOOT_SIGN_EC)
+ res |= BOOTUTIL_CAP_ECDSA_P224;
+#endif
+#if defined(MCUBOOT_SIGN_EC256)
+ res |= BOOTUTIL_CAP_ECDSA_P256;
+#endif
+#if defined(MCUBOOT_OVERWRITE_ONLY)
+ res |= BOOTUTIL_CAP_OVERWRITE_UPGRADE;
+#else
+ res |= BOOTUTIL_CAP_SWAP_UPGRADE;
+#endif
+
+ return res;
+}
diff --git a/bl2/ext/mcuboot/bootutil/src/image_rsa.c b/bl2/ext/mcuboot/bootutil/src/image_rsa.c
new file mode 100644
index 0000000..88ec784
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/src/image_rsa.c
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+#include <string.h>
+
+#ifdef MCUBOOT_MYNEWT
+#include "mcuboot_config/mcuboot_config.h"
+#endif
+
+#ifdef MCUBOOT_SIGN_RSA
+#include "bootutil/sign_key.h"
+#include "bootutil/sha256.h"
+
+#include "mbedtls/rsa.h"
+#include "mbedtls/asn1.h"
+
+#include "bootutil_priv.h"
+
+/*
+ * Constants for this particular constrained implementation of
+ * RSA-PSS. In particular, we support RSA 2048, with a SHA256 hash,
+ * and a 32-byte salt. A signature with different parameters will be
+ * rejected as invalid.
+ */
+
+/* The size, in octets, of the message. */
+#define PSS_EMLEN 256
+
+/* The size of the hash function. For SHA256, this is 32 bytes. */
+#define PSS_HLEN 32
+
+/* Size of the salt, should be fixed. */
+#define PSS_SLEN 32
+
+/* The length of the mask: emLen - hLen - 1. */
+#define PSS_MASK_LEN (256 - PSS_HLEN - 1)
+
+#define PSS_HASH_OFFSET PSS_MASK_LEN
+
+/* For the mask itself, how many bytes should be all zeros. */
+#define PSS_MASK_ZERO_COUNT (PSS_MASK_LEN - PSS_SLEN - 1)
+#define PSS_MASK_ONE_POS PSS_MASK_ZERO_COUNT
+
+/* Where the salt starts. */
+#define PSS_MASK_SALT_POS (PSS_MASK_ONE_POS + 1)
+
+static const uint8_t pss_zeros[8] = {0};
+
+/*
+ * Parse the public key used for signing. Simple RSA format.
+ */
+static int
+bootutil_parse_rsakey(mbedtls_rsa_context *ctx, uint8_t **p, uint8_t *end)
+{
+ int rc;
+ size_t len;
+
+ if ((rc = mbedtls_asn1_get_tag(p, end, &len,
+ MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
+ return -1;
+ }
+
+ if (*p + len != end) {
+ return -2;
+ }
+
+ if ((rc = mbedtls_asn1_get_mpi(p, end, &ctx->N)) != 0 ||
+ (rc = mbedtls_asn1_get_mpi(p, end, &ctx->E)) != 0) {
+ return -3;
+ }
+
+ if (*p != end) {
+ return -4;
+ }
+
+ if ((rc = mbedtls_rsa_check_pubkey(ctx)) != 0) {
+ return -5;
+ }
+
+ ctx->len = mbedtls_mpi_size(&ctx->N);
+
+ return 0;
+}
+
+/*
+ * Compute the RSA-PSS mask-generation function, MGF1. Assumptions
+ * are that the mask length will be less than 256 * PSS_HLEN, and
+ * therefore we never need to increment anything other than the low
+ * byte of the counter.
+ *
+ * This is described in PKCS#1, B.2.1.
+ */
+static void
+pss_mgf1(uint8_t *mask, const uint8_t *hash)
+{
+ bootutil_sha256_context ctx;
+ uint8_t counter[4] = { 0, 0, 0, 0 };
+ uint8_t htmp[PSS_HLEN];
+ int count = PSS_MASK_LEN;
+ int bytes;
+
+ while (count > 0) {
+ bootutil_sha256_init(&ctx);
+ bootutil_sha256_update(&ctx, hash, PSS_HLEN);
+ bootutil_sha256_update(&ctx, counter, 4);
+ bootutil_sha256_finish(&ctx, htmp);
+
+ counter[3]++;
+
+ bytes = PSS_HLEN;
+ if (bytes > count)
+ bytes = count;
+
+ memcpy(mask, htmp, bytes);
+ mask += bytes;
+ count -= bytes;
+ }
+}
+
+/*
+ * Validate an RSA signature, using RSA-PSS, as described in PKCS #1
+ * v2.2, section 9.1.2, with many parameters required to have fixed
+ * values.
+ */
+static int
+bootutil_cmp_rsasig(mbedtls_rsa_context *ctx, uint8_t *hash, uint32_t hlen,
+ uint8_t *sig)
+{
+ bootutil_sha256_context shactx;
+ uint8_t em[MBEDTLS_MPI_MAX_SIZE];
+ uint8_t db_mask[PSS_MASK_LEN];
+ uint8_t h2[PSS_HLEN];
+ int i;
+
+ if (ctx->len != PSS_EMLEN || PSS_EMLEN > MBEDTLS_MPI_MAX_SIZE) {
+ return -1;
+ }
+
+ if (hlen != PSS_HLEN) {
+ return -1;
+ }
+
+ if (mbedtls_rsa_public(ctx, sig, em)) {
+ return -1;
+ }
+
+ /*
+ * PKCS #1 v2.2, 9.1.2 EMSA-PSS-Verify
+ *
+ * emBits is 2048
+ * emLen = ceil(emBits/8) = 256
+ *
+ * The salt length is not known at the beginning.
+ */
+
+ /* Step 1. The message is constrained by the address space of a
+ * 32-bit processor, which is far less than the 2^61-1 limit of
+ * SHA-256.
+ */
+
+ /* Step 2. mHash is passed in as 'hash', with hLen the hlen
+ * argument. */
+
+ /* Step 3. if emLen < hLen + sLen + 2, inconsistent and stop.
+ * The salt length is not known at this point.
+ */
+
+ /* Step 4. If the rightmost octect of EM does have the value
+ * 0xbc, output inconsistent and stop.
+ */
+ if (em[PSS_EMLEN - 1] != 0xbc) {
+ return -1;
+ }
+
+ /* Step 5. Let maskedDB be the leftmost emLen - hLen - 1 octets
+ * of EM, and H be the next hLen octets.
+ *
+ * maskedDB is then the first 256 - 32 - 1 = 0-222
+ * H is 32 bytes 223-254
+ */
+
+ /* Step 6. If the leftmost 8emLen - emBits bits of the leftmost
+ * octet in maskedDB are not all equal to zero, output
+ * inconsistent and stop.
+ *
+ * 8emLen - emBits is zero, so there is nothing to test here.
+ */
+
+ /* Step 7. let dbMask = MGF(H, emLen - hLen - 1). */
+ pss_mgf1(db_mask, &em[PSS_HASH_OFFSET]);
+
+ /* Step 8. let DB = maskedDB xor dbMask.
+ * To avoid needing an additional buffer, store the 'db' in the
+ * same buffer as db_mask. From now, to the end of this function,
+ * db_mask refers to the unmasked 'db'. */
+ for (i = 0; i < PSS_MASK_LEN; i++) {
+ db_mask[i] ^= em[i];
+ }
+
+ /* Step 9. Set the leftmost 8emLen - emBits bits of the leftmost
+ * octet in DB to zero.
+ * pycrypto seems to always make the emBits 2047, so we need to
+ * clear the top bit. */
+ db_mask[0] &= 0x7F;
+
+ /* Step 10. If the emLen - hLen - sLen - 2 leftmost octets of DB
+ * are not zero or if the octet at position emLen - hLen - sLen -
+ * 1 (the leftmost position is "position 1") does not have
+ * hexadecimal value 0x01, output "inconsistent" and stop. */
+ for (i = 0; i < PSS_MASK_ZERO_COUNT; i++) {
+ if (db_mask[i] != 0) {
+ return -1;
+ }
+ }
+
+ if (db_mask[PSS_MASK_ONE_POS] != 1) {
+ return -1;
+ }
+
+ /* Step 11. Let salt be the last sLen octets of DB */
+
+ /* Step 12. Let M' = 0x00 00 00 00 00 00 00 00 || mHash || salt; */
+
+ /* Step 13. Let H' = Hash(M') */
+ bootutil_sha256_init(&shactx);
+ bootutil_sha256_update(&shactx, pss_zeros, 8);
+ bootutil_sha256_update(&shactx, hash, PSS_HLEN);
+ bootutil_sha256_update(&shactx, &db_mask[PSS_MASK_SALT_POS], PSS_SLEN);
+ bootutil_sha256_finish(&shactx, h2);
+
+ /* Step 14. If H = H', output "consistent". Otherwise, output
+ * "inconsistent". */
+ if (memcmp(h2, &em[PSS_HASH_OFFSET], PSS_HLEN) != 0) {
+ return -1;
+ }
+
+ return 0;
+}
+
+int
+bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen,
+ uint8_t key_id)
+{
+ mbedtls_rsa_context ctx;
+ int rc;
+ uint8_t *cp;
+ uint8_t *end;
+
+ mbedtls_rsa_init(&ctx, 0, 0);
+
+ cp = (uint8_t *)bootutil_keys[key_id].key;
+ end = cp + *bootutil_keys[key_id].len;
+
+ rc = bootutil_parse_rsakey(&ctx, &cp, end);
+ if (rc || slen != ctx.len) {
+ mbedtls_rsa_free(&ctx);
+ return rc;
+ }
+ rc = bootutil_cmp_rsasig(&ctx, hash, hlen, sig);
+ mbedtls_rsa_free(&ctx);
+
+ return rc;
+}
+#endif /* MCUBOOT_SIGN_RSA */
diff --git a/bl2/ext/mcuboot/bootutil/src/image_validate.c b/bl2/ext/mcuboot/bootutil/src/image_validate.c
new file mode 100644
index 0000000..5b2b9a0
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/src/image_validate.c
@@ -0,0 +1,260 @@
+/*
+ * 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.
+ */
+
+#include <assert.h>
+#include <stddef.h>
+#include <inttypes.h>
+#include <string.h>
+
+#include "hal/hal_flash.h"
+#include "flash_map/flash_map.h"
+#include "bootutil/image.h"
+#include "bootutil/sha256.h"
+#include "bootutil/sign_key.h"
+
+#ifdef MCUBOOT_MYNEWT
+#include "mcuboot_config/mcuboot_config.h"
+#endif
+
+#ifdef MCUBOOT_SIGN_RSA
+#include "mbedtls/rsa.h"
+#endif
+#if defined(MCUBOOT_SIGN_EC) || defined(MCUBOOT_SIGN_EC256)
+#include "mbedtls/ecdsa.h"
+#endif
+#include "mbedtls/asn1.h"
+
+#include "bootutil_priv.h"
+
+/*
+ * Compute SHA256 over the image.
+ */
+static int
+bootutil_img_hash(struct image_header *hdr, const struct flash_area *fap,
+ uint8_t *tmp_buf, uint32_t tmp_buf_sz,
+ uint8_t *hash_result, uint8_t *seed, int seed_len)
+{
+ bootutil_sha256_context sha256_ctx;
+ uint32_t blk_sz;
+ uint32_t size;
+ uint32_t off;
+ int rc;
+
+ bootutil_sha256_init(&sha256_ctx);
+
+ /* in some cases (split image) the hash is seeded with data from
+ * the loader image */
+ if(seed && (seed_len > 0)) {
+ bootutil_sha256_update(&sha256_ctx, seed, seed_len);
+ }
+
+ size = hdr->ih_img_size + hdr->ih_hdr_size;
+
+ /*
+ * Hash is computed over image header and image itself. No TLV is
+ * included ATM.
+ */
+ size = hdr->ih_img_size + hdr->ih_hdr_size;
+ for (off = 0; off < size; off += blk_sz) {
+ blk_sz = size - off;
+ if (blk_sz > tmp_buf_sz) {
+ blk_sz = tmp_buf_sz;
+ }
+ rc = flash_area_read(fap, off, tmp_buf, blk_sz);
+ if (rc) {
+ return rc;
+ }
+ bootutil_sha256_update(&sha256_ctx, tmp_buf, blk_sz);
+ }
+ bootutil_sha256_finish(&sha256_ctx, hash_result);
+
+ return 0;
+}
+
+/*
+ * Currently, we only support being able to verify one type of
+ * signature, because there is a single verification function that we
+ * call. List the type of TLV we are expecting. If we aren't
+ * configured for any signature, don't define this macro.
+ */
+#if defined(MCUBOOT_SIGN_RSA)
+# define EXPECTED_SIG_TLV IMAGE_TLV_RSA2048_PSS
+# define EXPECTED_SIG_LEN(x) ((x) == 256) /* 2048 bits */
+# if defined(MCUBOOT_SIGN_EC) || defined(MCUBOOT_SIGN_EC256)
+# error "Multiple signature types not yet supported"
+# endif
+#elif defined(MCUBOOT_SIGN_EC)
+# define EXPECTED_SIG_TLV IMAGE_TLV_ECDSA224
+# define EXPECTED_SIG_LEN(x) ((x) >= 64) /* oids + 2 * 28 bytes */
+# if defined(MCUBOOT_SIGN_EC256)
+# error "Multiple signature types not yet supported"
+# endif
+#elif defined(MCUBOOT_SIGN_EC256)
+# define EXPECTED_SIG_TLV IMAGE_TLV_ECDSA256
+# define EXPECTED_SIG_LEN(x) ((x) >= 72) /* oids + 2 * 32 bytes */
+#endif
+
+#ifdef EXPECTED_SIG_TLV
+static int
+bootutil_find_key(uint8_t *keyhash, uint8_t keyhash_len)
+{
+ bootutil_sha256_context sha256_ctx;
+ int i;
+ const struct bootutil_key *key;
+ uint8_t hash[32];
+
+ assert(keyhash_len <= 32);
+
+ for (i = 0; i < bootutil_key_cnt; i++) {
+ key = &bootutil_keys[i];
+ bootutil_sha256_init(&sha256_ctx);
+ bootutil_sha256_update(&sha256_ctx, key->key, *key->len);
+ bootutil_sha256_finish(&sha256_ctx, hash);
+ if (!memcmp(hash, keyhash, keyhash_len)) {
+ return i;
+ }
+ }
+ return -1;
+}
+#endif
+
+/*
+ * Verify the integrity of the image.
+ * Return non-zero if image could not be validated/does not validate.
+ */
+int
+bootutil_img_validate(struct image_header *hdr, const struct flash_area *fap,
+ uint8_t *tmp_buf, uint32_t tmp_buf_sz,
+ uint8_t *seed, int seed_len, uint8_t *out_hash)
+{
+ uint32_t off;
+ uint32_t end;
+ int sha256_valid = 0;
+ struct image_tlv_info info;
+#ifdef EXPECTED_SIG_TLV
+ int valid_signature = 0;
+ int key_id = -1;
+#endif
+ struct image_tlv tlv;
+ uint8_t buf[256];
+ uint8_t hash[32];
+ int rc;
+
+ rc = bootutil_img_hash(hdr, fap, tmp_buf, tmp_buf_sz, hash,
+ seed, seed_len);
+ if (rc) {
+ return rc;
+ }
+
+ if (out_hash) {
+ memcpy(out_hash, hash, 32);
+ }
+
+ /* The TLVs come after the image. */
+ /* After image there are TLVs. */
+ off = hdr->ih_img_size + hdr->ih_hdr_size;
+
+ rc = flash_area_read(fap, off, &info, sizeof(info));
+ if (rc) {
+ return rc;
+ }
+ if (info.it_magic != IMAGE_TLV_INFO_MAGIC) {
+ return -1;
+ }
+ end = off + info.it_tlv_tot;
+ off += sizeof(info);
+
+ /*
+ * Traverse through all of the TLVs, performing any checks we know
+ * and are able to do.
+ */
+ for (; off < end; off += sizeof(tlv) + tlv.it_len) {
+ rc = flash_area_read(fap, off, &tlv, sizeof tlv);
+ if (rc) {
+ return rc;
+ }
+
+ if (tlv.it_type == IMAGE_TLV_SHA256) {
+ /*
+ * Verify the SHA256 image hash. This must always be
+ * present.
+ */
+ if (tlv.it_len != sizeof(hash)) {
+ return -1;
+ }
+ rc = flash_area_read(fap, off + sizeof(tlv), buf, sizeof hash);
+ if (rc) {
+ return rc;
+ }
+ if (memcmp(hash, buf, sizeof(hash))) {
+ return -1;
+ }
+
+ sha256_valid = 1;
+#ifdef EXPECTED_SIG_TLV
+ } else if (tlv.it_type == IMAGE_TLV_KEYHASH) {
+ /*
+ * Determine which key we should be checking.
+ */
+ if (tlv.it_len > 32) {
+ return -1;
+ }
+ rc = flash_area_read(fap, off + sizeof tlv, buf, tlv.it_len);
+ if (rc) {
+ return rc;
+ }
+ key_id = bootutil_find_key(buf, tlv.it_len);
+ /*
+ * The key may not be found, which is acceptable. There
+ * can be multiple signatures, each preceded by a key.
+ */
+ } else if (tlv.it_type == EXPECTED_SIG_TLV) {
+ /* Ignore this signature if it is out of bounds. */
+ if (key_id < 0 || key_id >= bootutil_key_cnt) {
+ key_id = -1;
+ continue;
+ }
+ if (!EXPECTED_SIG_LEN(tlv.it_len) || tlv.it_len > sizeof(buf)) {
+ return -1;
+ }
+ rc = flash_area_read(fap, off + sizeof(tlv), buf, tlv.it_len);
+ if (rc) {
+ return -1;
+ }
+ rc = bootutil_verify_sig(hash, sizeof(hash), buf, tlv.it_len, key_id);
+ if (rc == 0) {
+ valid_signature = 1;
+ }
+ key_id = -1;
+#endif
+ }
+ }
+
+ if (!sha256_valid) {
+ return -1;
+ }
+
+#ifdef EXPECTED_SIG_TLV
+ if (!valid_signature) {
+ return -1;
+ }
+#endif
+
+ return 0;
+}
diff --git a/bl2/ext/mcuboot/bootutil/src/loader.c b/bl2/ext/mcuboot/bootutil/src/loader.c
new file mode 100644
index 0000000..30ac131
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/src/loader.c
@@ -0,0 +1,1440 @@
+/*
+ * 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.
+ */
+
+/**
+ * This file provides an interface to the boot loader. Functions defined in
+ * this file should only be called while the boot loader is running.
+ */
+
+#include <assert.h>
+#include <stddef.h>
+#include <stdbool.h>
+#include <inttypes.h>
+#include <stdlib.h>
+#include <string.h>
+#include <hal/hal_flash.h>
+#include <os/os_malloc.h>
+#include "bootutil/bootutil.h"
+#include "bootutil/image.h"
+#include "bootutil_priv.h"
+
+#define BOOT_LOG_LEVEL BOOT_LOG_LEVEL_INFO
+#include "bootutil/bootutil_log.h"
+
+#ifdef MCUBOOT_MYNEWT
+#include "mcuboot_config/mcuboot_config.h"
+#endif
+
+static struct boot_loader_state boot_data;
+
+struct boot_status_table {
+ /**
+ * For each field, a value of 0 means "any".
+ */
+ uint8_t bst_magic_slot0;
+ uint8_t bst_magic_scratch;
+ uint8_t bst_copy_done_slot0;
+ uint8_t bst_status_source;
+};
+
+/**
+ * This set of tables maps swap state contents to boot status location.
+ * When searching for a match, these tables must be iterated in order.
+ */
+static const struct boot_status_table boot_status_tables[] = {
+ {
+ /* | slot-0 | scratch |
+ * ----------+------------+------------|
+ * magic | Good | Any |
+ * copy-done | 0x01 | N/A |
+ * ----------+------------+------------'
+ * source: none |
+ * ------------------------------------'
+ */
+ .bst_magic_slot0 = BOOT_MAGIC_GOOD,
+ .bst_magic_scratch = 0,
+ .bst_copy_done_slot0 = 0x01,
+ .bst_status_source = BOOT_STATUS_SOURCE_NONE,
+ },
+
+ {
+ /* | slot-0 | scratch |
+ * ----------+------------+------------|
+ * magic | Good | Any |
+ * copy-done | 0xff | N/A |
+ * ----------+------------+------------'
+ * source: slot 0 |
+ * ------------------------------------'
+ */
+ .bst_magic_slot0 = BOOT_MAGIC_GOOD,
+ .bst_magic_scratch = 0,
+ .bst_copy_done_slot0 = 0xff,
+ .bst_status_source = BOOT_STATUS_SOURCE_SLOT0,
+ },
+
+ {
+ /* | slot-0 | scratch |
+ * ----------+------------+------------|
+ * magic | Any | Good |
+ * copy-done | Any | N/A |
+ * ----------+------------+------------'
+ * source: scratch |
+ * ------------------------------------'
+ */
+ .bst_magic_slot0 = 0,
+ .bst_magic_scratch = BOOT_MAGIC_GOOD,
+ .bst_copy_done_slot0 = 0,
+ .bst_status_source = BOOT_STATUS_SOURCE_SCRATCH,
+ },
+
+ {
+ /* | slot-0 | scratch |
+ * ----------+------------+------------|
+ * magic | Unset | Any |
+ * copy-done | 0xff | N/A |
+ * ----------+------------+------------|
+ * source: varies |
+ * ------------------------------------+------------------------------+
+ * This represents one of two cases: |
+ * o No swaps ever (no status to read, so no harm in checking). |
+ * o Mid-revert; status in slot 0. |
+ * -------------------------------------------------------------------'
+ */
+ .bst_magic_slot0 = BOOT_MAGIC_UNSET,
+ .bst_magic_scratch = 0,
+ .bst_copy_done_slot0 = 0xff,
+ .bst_status_source = BOOT_STATUS_SOURCE_SLOT0,
+ },
+};
+
+#define BOOT_STATUS_TABLES_COUNT \
+ (sizeof boot_status_tables / sizeof boot_status_tables[0])
+
+#define BOOT_LOG_SWAP_STATE(area, state) \
+ BOOT_LOG_INF("%s: magic=%s, copy_done=0x%x, image_ok=0x%x", \
+ (area), \
+ ((state)->magic == BOOT_MAGIC_GOOD ? "good" : \
+ (state)->magic == BOOT_MAGIC_UNSET ? "unset" : \
+ "bad"), \
+ (state)->copy_done, \
+ (state)->image_ok)
+
+/**
+ * Determines where in flash the most recent boot status is stored. The boot
+ * status is necessary for completing a swap that was interrupted by a boot
+ * loader reset.
+ *
+ * @return A BOOT_STATUS_SOURCE_[...] code indicating where * status should be read from.
+ */
+static int
+boot_status_source(void)
+{
+ const struct boot_status_table *table;
+ struct boot_swap_state state_scratch;
+ struct boot_swap_state state_slot0;
+ int rc;
+ int i;
+ uint8_t source;
+
+ rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_0, &state_slot0);
+ assert(rc == 0);
+
+ rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SCRATCH, &state_scratch);
+ assert(rc == 0);
+
+ BOOT_LOG_SWAP_STATE("Image 0", &state_slot0);
+ BOOT_LOG_SWAP_STATE("Scratch", &state_scratch);
+
+ for (i = 0; i < BOOT_STATUS_TABLES_COUNT; i++) {
+ table = &boot_status_tables[i];
+
+ if ((table->bst_magic_slot0 == 0 ||
+ table->bst_magic_slot0 == state_slot0.magic) &&
+ (table->bst_magic_scratch == 0 ||
+ table->bst_magic_scratch == state_scratch.magic) &&
+ (table->bst_copy_done_slot0 == 0 ||
+ table->bst_copy_done_slot0 == state_slot0.copy_done)) {
+ source = table->bst_status_source;
+ BOOT_LOG_INF("Boot source: %s",
+ source == BOOT_STATUS_SOURCE_NONE ? "none" :
+ source == BOOT_STATUS_SOURCE_SCRATCH ? "scratch" :
+ source == BOOT_STATUS_SOURCE_SLOT0 ? "slot 0" :
+ "BUG; can't happen");
+ return source;
+ }
+ }
+
+ BOOT_LOG_INF("Boot source: none");
+ return BOOT_STATUS_SOURCE_NONE;
+}
+
+/**
+ * Calculates the type of swap that just completed.
+ *
+ * This is used when a swap is interrupted by an external event. After
+ * finishing the swap operation determines what the initial request was.
+ */
+static int
+boot_previous_swap_type(void)
+{
+ int post_swap_type;
+
+ post_swap_type = boot_swap_type();
+
+ switch (post_swap_type) {
+ case BOOT_SWAP_TYPE_NONE : return BOOT_SWAP_TYPE_PERM;
+ case BOOT_SWAP_TYPE_REVERT : return BOOT_SWAP_TYPE_TEST;
+ case BOOT_SWAP_TYPE_PANIC : return BOOT_SWAP_TYPE_PANIC;
+ }
+
+ return BOOT_SWAP_TYPE_FAIL;
+}
+
+/*
+ * Compute the total size of the given image. Includes the size of
+ * the TLVs.
+ */
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static int
+boot_read_image_size(int slot, struct image_header *hdr, uint32_t *size)
+{
+ const struct flash_area *fap;
+ struct image_tlv_info info;
+ int area_id;
+ int rc;
+
+ area_id = flash_area_id_from_image_slot(slot);
+ rc = flash_area_open(area_id, &fap);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto done;
+ }
+
+ rc = flash_area_read(fap, hdr->ih_hdr_size + hdr->ih_img_size,
+ &info, sizeof(info));
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto done;
+ }
+ if (info.it_magic != IMAGE_TLV_INFO_MAGIC) {
+ rc = BOOT_EBADIMAGE;
+ goto done;
+ }
+ *size = hdr->ih_hdr_size + hdr->ih_img_size + info.it_tlv_tot;
+ rc = 0;
+
+done:
+ flash_area_close(fap);
+ return rc;
+}
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+
+static int
+boot_read_image_header(int slot, struct image_header *out_hdr)
+{
+ const struct flash_area *fap;
+ int area_id;
+ int rc;
+
+ area_id = flash_area_id_from_image_slot(slot);
+ rc = flash_area_open(area_id, &fap);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto done;
+ }
+
+ rc = flash_area_read(fap, 0, out_hdr, sizeof *out_hdr);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto done;
+ }
+
+ rc = 0;
+
+done:
+ flash_area_close(fap);
+ return rc;
+}
+
+static int
+boot_read_image_headers(void)
+{
+ int rc;
+ int i;
+
+ for (i = 0; i < BOOT_NUM_SLOTS; i++) {
+ rc = boot_read_image_header(i, boot_img_hdr(&boot_data, i));
+ if (rc != 0) {
+ /* If at least the first slot's header was read successfully, then
+ * the boot loader can attempt a boot. Failure to read any headers
+ * is a fatal error.
+ */
+ if (i > 0) {
+ return 0;
+ } else {
+ return rc;
+ }
+ }
+ }
+
+ return 0;
+}
+
+static uint8_t
+boot_write_sz(void)
+{
+ uint8_t elem_sz;
+ uint8_t align;
+
+ /* Figure out what size to write update status update as. The size depends
+ * on what the minimum write size is for scratch area, active image slot.
+ * We need to use the bigger of those 2 values.
+ */
+ elem_sz = hal_flash_align(boot_img_fa_device_id(&boot_data, 0));
+ align = hal_flash_align(boot_scratch_fa_device_id(&boot_data));
+ if (align > elem_sz) {
+ elem_sz = align;
+ }
+
+ return elem_sz;
+}
+
+static int
+boot_slots_compatible(void)
+{
+ size_t num_sectors_0 = boot_img_num_sectors(&boot_data, 0);
+ size_t num_sectors_1 = boot_img_num_sectors(&boot_data, 1);
+ size_t size_0, size_1;
+ size_t i;
+
+ /* Ensure both image slots have identical sector layouts. */
+ if (num_sectors_0 != num_sectors_1) {
+ return 0;
+ }
+ for (i = 0; i < num_sectors_0; i++) {
+ size_0 = boot_img_sector_size(&boot_data, 0, i);
+ size_1 = boot_img_sector_size(&boot_data, 1, i);
+ if (size_0 != size_1) {
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+/**
+ * Determines the sector layout of both image slots and the scratch area.
+ * This information is necessary for calculating the number of bytes to erase
+ * and copy during an image swap. The information collected during this
+ * function is used to populate the boot_data global.
+ */
+static int
+boot_read_sectors(void)
+{
+ int rc;
+
+ rc = boot_initialize_area(&boot_data, FLASH_AREA_IMAGE_0);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+
+ rc = boot_initialize_area(&boot_data, FLASH_AREA_IMAGE_1);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+
+ BOOT_WRITE_SZ(&boot_data) = boot_write_sz();
+
+ return 0;
+}
+
+static uint32_t
+boot_status_internal_off(int idx, int state, int elem_sz)
+{
+ int idx_sz;
+
+ idx_sz = elem_sz * BOOT_STATUS_STATE_COUNT;
+
+ return idx * idx_sz + state * elem_sz;
+}
+
+/**
+ * Reads the status of a partially-completed swap, if any. This is necessary
+ * to recover in case the boot lodaer was reset in the middle of a swap
+ * operation.
+ */
+static int
+boot_read_status_bytes(const struct flash_area *fap, struct boot_status *bs)
+{
+ uint32_t off;
+ uint8_t status;
+ int max_entries;
+ int found;
+ int rc;
+ int i;
+
+ off = boot_status_off(fap);
+ max_entries = boot_status_entries(fap);
+
+ found = 0;
+ for (i = 0; i < max_entries; i++) {
+ rc = flash_area_read(fap, off + i * BOOT_WRITE_SZ(&boot_data),
+ &status, 1);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+
+ if (status == 0xff) {
+ if (found) {
+ break;
+ }
+ } else if (!found) {
+ found = 1;
+ }
+ }
+
+ if (found) {
+ i--;
+ bs->idx = i / BOOT_STATUS_STATE_COUNT;
+ bs->state = i % BOOT_STATUS_STATE_COUNT;
+ }
+
+ return 0;
+}
+
+/**
+ * Reads the boot status from the flash. The boot status contains
+ * the current state of an interrupted image copy operation. If the boot
+ * status is not present, or it indicates that previous copy finished,
+ * there is no operation in progress.
+ */
+static int
+boot_read_status(struct boot_status *bs)
+{
+ const struct flash_area *fap;
+ int status_loc;
+ int area_id;
+ int rc;
+
+ memset(bs, 0, sizeof *bs);
+
+ status_loc = boot_status_source();
+ switch (status_loc) {
+ case BOOT_STATUS_SOURCE_NONE:
+ return 0;
+
+ case BOOT_STATUS_SOURCE_SCRATCH:
+ area_id = FLASH_AREA_IMAGE_SCRATCH;
+ break;
+
+ case BOOT_STATUS_SOURCE_SLOT0:
+ area_id = FLASH_AREA_IMAGE_0;
+ break;
+
+ default:
+ assert(0);
+ return BOOT_EBADARGS;
+ }
+
+ rc = flash_area_open(area_id, &fap);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+
+ rc = boot_read_status_bytes(fap, bs);
+
+ flash_area_close(fap);
+ return rc;
+}
+
+/**
+ * Writes the supplied boot status to the flash file system. The boot status
+ * contains the current state of an in-progress image copy operation.
+ *
+ * @param bs The boot status to write.
+ *
+ * @return 0 on success; nonzero on failure.
+ */
+int
+boot_write_status(struct boot_status *bs)
+{
+ const struct flash_area *fap;
+ uint32_t off;
+ int area_id;
+ int rc;
+ uint8_t buf[BOOT_MAX_ALIGN];
+ uint8_t align;
+
+ /* NOTE: The first sector copied (that is the last sector on slot) contains
+ * the trailer. Since in the last step SLOT 0 is erased, the first
+ * two status writes go to the scratch which will be copied to SLOT 0!
+ */
+
+ if (bs->use_scratch) {
+ /* Write to scratch. */
+ area_id = FLASH_AREA_IMAGE_SCRATCH;
+ } else {
+ /* Write to slot 0. */
+ area_id = FLASH_AREA_IMAGE_0;
+ }
+
+ rc = flash_area_open(area_id, &fap);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto done;
+ }
+
+ off = boot_status_off(fap) +
+ boot_status_internal_off(bs->idx, bs->state,
+ BOOT_WRITE_SZ(&boot_data));
+
+ align = hal_flash_align(fap->fa_device_id);
+ memset(buf, 0xFF, BOOT_MAX_ALIGN);
+ buf[0] = bs->state;
+
+ rc = flash_area_write(fap, off, buf, align);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto done;
+ }
+
+ rc = 0;
+
+done:
+ flash_area_close(fap);
+ return rc;
+}
+
+/*
+ * Validate image hash/signature in a slot.
+ */
+static int
+boot_image_check(struct image_header *hdr, const struct flash_area *fap)
+{
+ static uint8_t tmpbuf[BOOT_TMPBUF_SZ];
+
+ if (bootutil_img_validate(hdr, fap, tmpbuf, BOOT_TMPBUF_SZ,
+ NULL, 0, NULL)) {
+ return BOOT_EBADIMAGE;
+ }
+ return 0;
+}
+
+static int
+split_image_check(struct image_header *app_hdr,
+ const struct flash_area *app_fap,
+ struct image_header *loader_hdr,
+ const struct flash_area *loader_fap)
+{
+ static void *tmpbuf;
+ uint8_t loader_hash[32];
+
+ if (!tmpbuf) {
+ tmpbuf = malloc(BOOT_TMPBUF_SZ);
+ if (!tmpbuf) {
+ return BOOT_ENOMEM;
+ }
+ }
+
+ if (bootutil_img_validate(loader_hdr, loader_fap, tmpbuf, BOOT_TMPBUF_SZ,
+ NULL, 0, loader_hash)) {
+ return BOOT_EBADIMAGE;
+ }
+
+ if (bootutil_img_validate(app_hdr, app_fap, tmpbuf, BOOT_TMPBUF_SZ,
+ loader_hash, 32, NULL)) {
+ return BOOT_EBADIMAGE;
+ }
+
+ return 0;
+}
+
+static int
+boot_validate_slot(int slot)
+{
+ const struct flash_area *fap;
+ struct image_header *hdr;
+ int rc;
+
+ hdr = boot_img_hdr(&boot_data, slot);
+ if (hdr->ih_magic == 0xffffffff || hdr->ih_flags & IMAGE_F_NON_BOOTABLE) {
+ /* No bootable image in slot; continue booting from slot 0. */
+ return -1;
+ }
+
+ rc = flash_area_open(flash_area_id_from_image_slot(slot), &fap);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+
+ if ((hdr->ih_magic != IMAGE_MAGIC || boot_image_check(hdr, fap) != 0)) {
+ if (slot != 0) {
+ flash_area_erase(fap, 0, fap->fa_size);
+ /* Image in slot 1 is invalid. Erase the image and
+ * continue booting from slot 0.
+ */
+ }
+ BOOT_LOG_ERR("Image in slot %d is not valid!", slot);
+ return -1;
+ }
+
+ flash_area_close(fap);
+
+ /* Image in slot 1 is valid. */
+ return 0;
+}
+
+/**
+ * Determines which swap operation to perform, if any. If it is determined
+ * that a swap operation is required, the image in the second slot is checked
+ * for validity. If the image in the second slot is invalid, it is erased, and
+ * a swap type of "none" is indicated.
+ *
+ * @return The type of swap to perform (BOOT_SWAP_TYPE...)
+ */
+static int
+boot_validated_swap_type(void)
+{
+ int swap_type;
+
+ swap_type = boot_swap_type();
+ switch (swap_type) {
+ case BOOT_SWAP_TYPE_TEST:
+ case BOOT_SWAP_TYPE_PERM:
+ case BOOT_SWAP_TYPE_REVERT:
+ /* Boot loader wants to switch to slot 1. Ensure image is valid. */
+ if (boot_validate_slot(1) != 0) {
+ swap_type = BOOT_SWAP_TYPE_FAIL;
+ }
+ }
+
+ return swap_type;
+}
+
+/**
+ * Calculates the number of sectors the scratch area can contain. A "last"
+ * source sector is specified because images are copied backwards in flash
+ * (final index to index number 0).
+ *
+ * @param last_sector_idx The index of the last source sector
+ * (inclusive).
+ * @param out_first_sector_idx The index of the first source sector
+ * (inclusive) gets written here.
+ *
+ * @return The number of bytes comprised by the
+ * [first-sector, last-sector] range.
+ */
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static uint32_t
+boot_copy_sz(int last_sector_idx, int *out_first_sector_idx)
+{
+ size_t scratch_sz;
+ uint32_t new_sz;
+ uint32_t sz;
+ int i;
+
+ sz = 0;
+
+ scratch_sz = boot_scratch_area_size(&boot_data);
+ for (i = last_sector_idx; i >= 0; i--) {
+ new_sz = sz + boot_img_sector_size(&boot_data, 0, i);
+ if (new_sz > scratch_sz) {
+ break;
+ }
+ sz = new_sz;
+ }
+
+ /* i currently refers to a sector that doesn't fit or it is -1 because all
+ * sectors have been processed. In both cases, exclude sector i.
+ */
+ *out_first_sector_idx = i + 1;
+ return sz;
+}
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+
+/**
+ * Erases a region of flash.
+ *
+ * @param flash_area_idx The ID of the flash area containing the region
+ * to erase.
+ * @param off The offset within the flash area to start the
+ * erase.
+ * @param sz The number of bytes to erase.
+ *
+ * @return 0 on success; nonzero on failure.
+ */
+static int
+boot_erase_sector(int flash_area_id, uint32_t off, uint32_t sz)
+{
+ const struct flash_area *fap;
+ int rc;
+
+ rc = flash_area_open(flash_area_id, &fap);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto done;
+ }
+
+ rc = flash_area_erase(fap, off, sz);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto done;
+ }
+
+ rc = 0;
+
+done:
+ flash_area_close(fap);
+ return rc;
+}
+
+/**
+ * Copies the contents of one flash region to another. You must erase the
+ * destination region prior to calling this function.
+ *
+ * @param flash_area_id_src The ID of the source flash area.
+ * @param flash_area_id_dst The ID of the destination flash area.
+ * @param off_src The offset within the source flash area to
+ * copy from.
+ * @param off_dst The offset within the destination flash area to
+ * copy to.
+ * @param sz The number of bytes to copy.
+ *
+ * @return 0 on success; nonzero on failure.
+ */
+static int
+boot_copy_sector(int flash_area_id_src, int flash_area_id_dst,
+ uint32_t off_src, uint32_t off_dst, uint32_t sz)
+{
+ const struct flash_area *fap_src;
+ const struct flash_area *fap_dst;
+ uint32_t bytes_copied;
+ int chunk_sz;
+ int rc;
+
+ static uint8_t buf[1024];
+
+ fap_src = NULL;
+ fap_dst = NULL;
+
+ rc = flash_area_open(flash_area_id_src, &fap_src);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto done;
+ }
+
+ rc = flash_area_open(flash_area_id_dst, &fap_dst);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto done;
+ }
+
+ bytes_copied = 0;
+ while (bytes_copied < sz) {
+ if (sz - bytes_copied > sizeof buf) {
+ chunk_sz = sizeof buf;
+ } else {
+ chunk_sz = sz - bytes_copied;
+ }
+
+ rc = flash_area_read(fap_src, off_src + bytes_copied, buf, chunk_sz);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto done;
+ }
+
+ rc = flash_area_write(fap_dst, off_dst + bytes_copied, buf, chunk_sz);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto done;
+ }
+
+ bytes_copied += chunk_sz;
+ }
+
+ rc = 0;
+
+done:
+ if (fap_src) {
+ flash_area_close(fap_src);
+ }
+ if (fap_dst) {
+ flash_area_close(fap_dst);
+ }
+ return rc;
+}
+
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static inline int
+boot_status_init_by_id(int flash_area_id, const struct boot_status *bs)
+{
+ const struct flash_area *fap;
+ struct boot_swap_state swap_state;
+ int rc;
+
+ rc = flash_area_open(flash_area_id, &fap);
+ assert(rc == 0);
+
+ rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_1, &swap_state);
+ assert(rc == 0);
+
+ if (swap_state.image_ok == BOOT_FLAG_SET) {
+ rc = boot_write_image_ok(fap);
+ assert(rc == 0);
+ }
+
+ rc = boot_write_swap_size(fap, bs->swap_size);
+ assert(rc == 0);
+
+ rc = boot_write_magic(fap);
+ assert(rc == 0);
+
+ flash_area_close(fap);
+
+ return 0;
+}
+#endif
+
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static int
+boot_erase_last_sector_by_id(int flash_area_id)
+{
+ uint8_t slot;
+ uint32_t last_sector;
+ int rc;
+
+ switch (flash_area_id) {
+ case FLASH_AREA_IMAGE_0:
+ slot = 0;
+ break;
+ case FLASH_AREA_IMAGE_1:
+ slot = 1;
+ break;
+ default:
+ return BOOT_EFLASH;
+ }
+
+ last_sector = boot_img_num_sectors(&boot_data, slot) - 1;
+ rc = boot_erase_sector(flash_area_id,
+ boot_img_sector_off(&boot_data, slot, last_sector),
+ boot_img_sector_size(&boot_data, slot, last_sector));
+ assert(rc == 0);
+
+ return rc;
+}
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+
+/**
+ * Swaps the contents of two flash regions within the two image slots.
+ *
+ * @param idx The index of the first sector in the range of
+ * sectors being swapped.
+ * @param sz The number of bytes to swap.
+ * @param bs The current boot status. This struct gets
+ * updated according to the outcome.
+ *
+ * @return 0 on success; nonzero on failure.
+ */
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static void
+boot_swap_sectors(int idx, uint32_t sz, struct boot_status *bs)
+{
+ const struct flash_area *fap;
+ uint32_t copy_sz;
+ uint32_t trailer_sz;
+ uint32_t img_off;
+ uint32_t scratch_trailer_off;
+ struct boot_swap_state swap_state;
+ size_t last_sector;
+ int rc;
+
+ /* Calculate offset from start of image area. */
+ img_off = boot_img_sector_off(&boot_data, 0, idx);
+
+ copy_sz = sz;
+ trailer_sz = boot_slots_trailer_sz(BOOT_WRITE_SZ(&boot_data));
+
+ /* sz in this function is always is always sized on a multiple of the
+ * sector size. The check against the start offset of the last sector
+ * is to determine if we're swapping the last sector. The last sector
+ * needs special handling because it's where the trailer lives. If we're
+ * copying it, we need to use scratch to write the trailer temporarily.
+ *
+ * NOTE: `use_scratch` is a temporary flag (never written to flash) which
+ * controls if special handling is needed (swapping last sector).
+ */
+ last_sector = boot_img_num_sectors(&boot_data, 0) - 1;
+ if (img_off + sz > boot_img_sector_off(&boot_data, 0, last_sector)) {
+ copy_sz -= trailer_sz;
+ }
+
+ bs->use_scratch = (bs->idx == 0 && copy_sz != sz);
+
+ if (bs->state == 0) {
+ rc = boot_erase_sector(FLASH_AREA_IMAGE_SCRATCH, 0, sz);
+ assert(rc == 0);
+
+ rc = boot_copy_sector(FLASH_AREA_IMAGE_1, FLASH_AREA_IMAGE_SCRATCH,
+ img_off, 0, copy_sz);
+ assert(rc == 0);
+
+ if (bs->idx == 0) {
+ if (bs->use_scratch) {
+ boot_status_init_by_id(FLASH_AREA_IMAGE_SCRATCH, bs);
+ } else {
+ /* Prepare the status area... here it is known that the
+ * last sector is not being used by the image data so it's
+ * safe to erase.
+ */
+ rc = boot_erase_last_sector_by_id(FLASH_AREA_IMAGE_0);
+ assert(rc == 0);
+
+ boot_status_init_by_id(FLASH_AREA_IMAGE_0, bs);
+ }
+ }
+
+ bs->state = 1;
+ rc = boot_write_status(bs);
+ assert(rc == 0);
+ }
+
+ if (bs->state == 1) {
+ rc = boot_erase_sector(FLASH_AREA_IMAGE_1, img_off, sz);
+ assert(rc == 0);
+
+ rc = boot_copy_sector(FLASH_AREA_IMAGE_0, FLASH_AREA_IMAGE_1,
+ img_off, img_off, copy_sz);
+ assert(rc == 0);
+
+ if (bs->idx == 0 && !bs->use_scratch) {
+ /* If not all sectors of the slot are being swapped,
+ * guarantee here that only slot0 will have the state.
+ */
+ rc = boot_erase_last_sector_by_id(FLASH_AREA_IMAGE_1);
+ assert(rc == 0);
+ }
+
+ bs->state = 2;
+ rc = boot_write_status(bs);
+ assert(rc == 0);
+ }
+
+ if (bs->state == 2) {
+ rc = boot_erase_sector(FLASH_AREA_IMAGE_0, img_off, sz);
+ assert(rc == 0);
+
+ /* NOTE: also copy trailer from scratch (has status info) */
+ rc = boot_copy_sector(FLASH_AREA_IMAGE_SCRATCH, FLASH_AREA_IMAGE_0,
+ 0, img_off, copy_sz);
+ assert(rc == 0);
+
+ if (bs->use_scratch) {
+ rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH, &fap);
+ assert(rc == 0);
+
+ scratch_trailer_off = boot_status_off(fap);
+
+ flash_area_close(fap);
+
+ rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+ assert(rc == 0);
+
+ /* copy current status that is being maintained in scratch */
+ rc = boot_copy_sector(FLASH_AREA_IMAGE_SCRATCH, FLASH_AREA_IMAGE_0,
+ scratch_trailer_off,
+ img_off + copy_sz,
+ BOOT_STATUS_STATE_COUNT * BOOT_WRITE_SZ(&boot_data));
+ assert(rc == 0);
+
+ rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SCRATCH,
+ &swap_state);
+ assert(rc == 0);
+
+ if (swap_state.image_ok == BOOT_FLAG_SET) {
+ rc = boot_write_image_ok(fap);
+ assert(rc == 0);
+ }
+
+ rc = boot_write_swap_size(fap, bs->swap_size);
+ assert(rc == 0);
+
+ rc = boot_write_magic(fap);
+ assert(rc == 0);
+
+ flash_area_close(fap);
+ }
+
+ bs->idx++;
+ bs->state = 0;
+ bs->use_scratch = 0;
+ rc = boot_write_status(bs);
+ assert(rc == 0);
+ }
+}
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+
+/**
+ * Swaps the two images in flash. If a prior copy operation was interrupted
+ * by a system reset, this function completes that operation.
+ *
+ * @param bs The current boot status. This function reads
+ * this struct to determine if it is resuming
+ * an interrupted swap operation. This
+ * function writes the updated status to this
+ * function on return.
+ *
+ * @return 0 on success; nonzero on failure.
+ */
+#ifdef MCUBOOT_OVERWRITE_ONLY
+static int
+boot_copy_image(struct boot_status *bs)
+{
+ size_t sect_count;
+ size_t sect;
+ int rc;
+ size_t size = 0;
+ size_t this_size;
+
+ BOOT_LOG_INF("Image upgrade slot1 -> slot0");
+ BOOT_LOG_INF("Erasing slot0");
+
+ sect_count = boot_img_num_sectors(&boot_data, 0);
+ for (sect = 0; sect < sect_count; sect++) {
+ this_size = boot_img_sector_size(&boot_data, 0, sect);
+ rc = boot_erase_sector(FLASH_AREA_IMAGE_0,
+ size,
+ this_size);
+ assert(rc == 0);
+
+ size += this_size;
+ }
+
+ BOOT_LOG_INF("Copying slot 1 to slot 0: 0x%lx bytes", size);
+ rc = boot_copy_sector(FLASH_AREA_IMAGE_1, FLASH_AREA_IMAGE_0,
+ 0, 0, size);
+
+ /* Erase slot 1 so that we don't do the upgrade on every boot.
+ * TODO: Perhaps verify slot 0's signature again? */
+ rc = boot_erase_sector(FLASH_AREA_IMAGE_1,
+ 0, boot_img_sector_size(&boot_data, 1, 0));
+ assert(rc == 0);
+
+ return 0;
+}
+#else
+static int
+boot_copy_image(struct boot_status *bs)
+{
+ uint32_t sz;
+ int first_sector_idx;
+ int last_sector_idx;
+ int swap_idx;
+ struct image_header *hdr;
+ uint32_t size;
+ uint32_t copy_size;
+ int rc;
+
+ /* FIXME: just do this if asked by user? */
+
+ size = copy_size = 0;
+
+ if (bs->idx == 0 && bs->state == 0) {
+ /*
+ * No swap ever happened, so need to find the largest image which
+ * will be used to determine the amount of sectors to swap.
+ */
+ hdr = boot_img_hdr(&boot_data, 0);
+ if (hdr->ih_magic == IMAGE_MAGIC) {
+ rc = boot_read_image_size(0, hdr, ©_size);
+ assert(rc == 0);
+ }
+
+ hdr = boot_img_hdr(&boot_data, 1);
+ if (hdr->ih_magic == IMAGE_MAGIC) {
+ rc = boot_read_image_size(1, hdr, &size);
+ assert(rc == 0);
+ }
+
+ if (size > copy_size) {
+ copy_size = size;
+ }
+
+ bs->swap_size = copy_size;
+ } else {
+ /*
+ * If a swap was under way, the swap_size should already be present
+ * in the trailer...
+ */
+ rc = boot_read_swap_size(&bs->swap_size);
+ assert(rc == 0);
+
+ copy_size = bs->swap_size;
+ }
+
+ size = 0;
+ last_sector_idx = 0;
+ while (1) {
+ size += boot_img_sector_size(&boot_data, 0, last_sector_idx);
+ if (size >= copy_size) {
+ break;
+ }
+ last_sector_idx++;
+ }
+
+ swap_idx = 0;
+ while (last_sector_idx >= 0) {
+ sz = boot_copy_sz(last_sector_idx, &first_sector_idx);
+ if (swap_idx >= bs->idx) {
+ boot_swap_sectors(first_sector_idx, sz, bs);
+ }
+
+ last_sector_idx = first_sector_idx - 1;
+ swap_idx++;
+ }
+
+ return 0;
+}
+#endif
+
+/**
+ * Marks the image in slot 0 as fully copied.
+ */
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static int
+boot_set_copy_done(void)
+{
+ const struct flash_area *fap;
+ int rc;
+
+ rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+
+ rc = boot_write_copy_done(fap);
+ flash_area_close(fap);
+ return rc;
+}
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+
+/**
+ * Marks a reverted image in slot 0 as confirmed. This is necessary to ensure
+ * the status bytes from the image revert operation don't get processed on a
+ * subsequent boot.
+ *
+ * NOTE: image_ok is tested before writing because if there's a valid permanent
+ * image installed on slot0 and the new image to be upgrade to has a bad sig,
+ * image_ok would be overwritten.
+ */
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static int
+boot_set_image_ok(void)
+{
+ const struct flash_area *fap;
+ struct boot_swap_state state;
+ int rc;
+
+ rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+ if (rc != 0) {
+ return BOOT_EFLASH;
+ }
+
+ rc = boot_read_swap_state(fap, &state);
+ if (rc != 0) {
+ rc = BOOT_EFLASH;
+ goto out;
+ }
+
+ if (state.image_ok == BOOT_FLAG_UNSET) {
+ rc = boot_write_image_ok(fap);
+ }
+
+out:
+ flash_area_close(fap);
+ return rc;
+}
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+
+/**
+ * Performs an image swap if one is required.
+ *
+ * @param out_swap_type On success, the type of swap performed gets
+ * written here.
+ *
+ * @return 0 on success; nonzero on failure.
+ */
+static int
+boot_swap_if_needed(int *out_swap_type)
+{
+ struct boot_status bs;
+ int swap_type;
+ int rc;
+
+ /* Determine if we rebooted in the middle of an image swap
+ * operation.
+ */
+ rc = boot_read_status(&bs);
+ assert(rc == 0);
+ if (rc != 0) {
+ return rc;
+ }
+
+ /* If a partial swap was detected, complete it. */
+ if (bs.idx != 0 || bs.state != 0) {
+ rc = boot_copy_image(&bs);
+ assert(rc == 0);
+
+ /* NOTE: here we have finished a swap resume. The initial request
+ * was either a TEST or PERM swap, which now after the completed
+ * swap will be determined to be respectively REVERT (was TEST)
+ * or NONE (was PERM).
+ */
+
+ /* Extrapolate the type of the partial swap. We need this
+ * information to know how to mark the swap complete in flash.
+ */
+ swap_type = boot_previous_swap_type();
+ } else {
+ swap_type = boot_validated_swap_type();
+ switch (swap_type) {
+ case BOOT_SWAP_TYPE_TEST:
+ case BOOT_SWAP_TYPE_PERM:
+ case BOOT_SWAP_TYPE_REVERT:
+ rc = boot_copy_image(&bs);
+ assert(rc == 0);
+ break;
+ }
+ }
+
+ *out_swap_type = swap_type;
+ return 0;
+}
+
+/**
+ * Prepares the booting process. This function moves images around in flash as
+ * appropriate, and tells you what address to boot from.
+ *
+ * @param rsp On success, indicates how booting should occur.
+ *
+ * @return 0 on success; nonzero on failure.
+ */
+int
+boot_go(struct boot_rsp *rsp)
+{
+ int swap_type;
+ size_t slot;
+ int rc;
+ int fa_id;
+ bool reload_headers = false;
+
+ /* The array of slot sectors are defined here (as opposed to file scope) so
+ * that they don't get allocated for non-boot-loader apps. This is
+ * necessary because the gcc option "-fdata-sections" doesn't seem to have
+ * any effect in older gcc versions (e.g., 4.8.4).
+ */
+ static boot_sector_t slot0_sectors[BOOT_MAX_IMG_SECTORS];
+ static boot_sector_t slot1_sectors[BOOT_MAX_IMG_SECTORS];
+ boot_data.imgs[0].sectors = slot0_sectors;
+ boot_data.imgs[1].sectors = slot1_sectors;
+
+ /* Open boot_data image areas for the duration of this call. */
+ for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
+ fa_id = flash_area_id_from_image_slot(slot);
+ rc = flash_area_open(fa_id, &BOOT_IMG_AREA(&boot_data, slot));
+ assert(rc == 0);
+ }
+ rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH,
+ &BOOT_SCRATCH_AREA(&boot_data));
+ assert(rc == 0);
+
+ /* Determine the sector layout of the image slots and scratch area. */
+ rc = boot_read_sectors();
+ if (rc != 0) {
+ goto out;
+ }
+
+ /* Attempt to read an image header from each slot. */
+ rc = boot_read_image_headers();
+ if (rc != 0) {
+ goto out;
+ }
+
+ /* If the image slots aren't compatible, no swap is possible. Just boot
+ * into slot 0.
+ */
+ if (boot_slots_compatible()) {
+ rc = boot_swap_if_needed(&swap_type);
+ assert(rc == 0);
+ if (rc != 0) {
+ goto out;
+ }
+
+ /*
+ * The following states need image_ok be explicitly set after the
+ * swap was finished to avoid a new revert.
+ */
+ if (swap_type == BOOT_SWAP_TYPE_REVERT || swap_type == BOOT_SWAP_TYPE_FAIL) {
+#ifndef MCUBOOT_OVERWRITE_ONLY
+ rc = boot_set_image_ok();
+ if (rc != 0) {
+ swap_type = BOOT_SWAP_TYPE_PANIC;
+ }
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+ }
+ } else {
+ swap_type = BOOT_SWAP_TYPE_NONE;
+ }
+
+ switch (swap_type) {
+ case BOOT_SWAP_TYPE_NONE:
+ slot = 0;
+ break;
+
+ case BOOT_SWAP_TYPE_TEST: /* fallthrough */
+ case BOOT_SWAP_TYPE_PERM: /* fallthrough */
+ case BOOT_SWAP_TYPE_REVERT:
+ slot = 1;
+ reload_headers = true;
+#ifndef MCUBOOT_OVERWRITE_ONLY
+ rc = boot_set_copy_done();
+ if (rc != 0) {
+ swap_type = BOOT_SWAP_TYPE_PANIC;
+ }
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+ break;
+
+ case BOOT_SWAP_TYPE_FAIL:
+ /* The image in slot 1 was invalid and is now erased. Ensure we don't
+ * try to boot into it again on the next reboot. Do this by pretending
+ * we just reverted back to slot 0.
+ */
+ slot = 0;
+ reload_headers = true;
+ break;
+
+ default:
+ swap_type = BOOT_SWAP_TYPE_PANIC;
+ }
+
+ if (swap_type == BOOT_SWAP_TYPE_PANIC) {
+ BOOT_LOG_ERR("panic!");
+ assert(0);
+
+ /* Loop forever... */
+ while (1) {}
+ }
+
+#ifdef MCUBOOT_VALIDATE_SLOT0
+ if (reload_headers) {
+ rc = boot_read_image_headers();
+ if (rc != 0) {
+ goto out;
+ }
+ /* Since headers were reloaded, it can be assumed we just performed a
+ * swap or overwrite. Now the header info that should be used to
+ * provide the data for the bootstrap, which previously was at Slot 1,
+ * was updated to Slot 0.
+ */
+ slot = 0;
+ }
+
+ rc = boot_validate_slot(0);
+ assert(rc == 0);
+ if (rc != 0) {
+ rc = BOOT_EBADIMAGE;
+ goto out;
+ }
+#else
+ (void)reload_headers;
+#endif
+
+ /* Always boot from the primary slot. */
+ rsp->br_flash_dev_id = boot_img_fa_device_id(&boot_data, 0);
+ rsp->br_image_off = boot_img_slot_off(&boot_data, 0);
+ rsp->br_hdr = boot_img_hdr(&boot_data, slot);
+
+ out:
+ flash_area_close(BOOT_SCRATCH_AREA(&boot_data));
+ for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
+ flash_area_close(BOOT_IMG_AREA(&boot_data, BOOT_NUM_SLOTS - 1 - slot));
+ }
+ return rc;
+}
+
+int
+split_go(int loader_slot, int split_slot, void **entry)
+{
+ boot_sector_t *sectors;
+ uintptr_t entry_val;
+ int loader_flash_id;
+ int split_flash_id;
+ int rc;
+
+ sectors = malloc(BOOT_MAX_IMG_SECTORS * 2 * sizeof *sectors);
+ if (sectors == NULL) {
+ return SPLIT_GO_ERR;
+ }
+ boot_data.imgs[loader_slot].sectors = sectors + 0;
+ boot_data.imgs[split_slot].sectors = sectors + BOOT_MAX_IMG_SECTORS;
+
+ loader_flash_id = flash_area_id_from_image_slot(loader_slot);
+ rc = flash_area_open(loader_flash_id,
+ &BOOT_IMG_AREA(&boot_data, split_slot));
+ assert(rc == 0);
+ split_flash_id = flash_area_id_from_image_slot(split_slot);
+ rc = flash_area_open(split_flash_id,
+ &BOOT_IMG_AREA(&boot_data, split_slot));
+ assert(rc == 0);
+
+ /* Determine the sector layout of the image slots and scratch area. */
+ rc = boot_read_sectors();
+ if (rc != 0) {
+ rc = SPLIT_GO_ERR;
+ goto done;
+ }
+
+ rc = boot_read_image_headers();
+ if (rc != 0) {
+ goto done;
+ }
+
+ /* Don't check the bootable image flag because we could really call a
+ * bootable or non-bootable image. Just validate that the image check
+ * passes which is distinct from the normal check.
+ */
+ rc = split_image_check(boot_img_hdr(&boot_data, split_slot),
+ BOOT_IMG_AREA(&boot_data, split_slot),
+ boot_img_hdr(&boot_data, loader_slot),
+ BOOT_IMG_AREA(&boot_data, loader_slot));
+ if (rc != 0) {
+ rc = SPLIT_GO_NON_MATCHING;
+ goto done;
+ }
+
+ entry_val = boot_img_slot_off(&boot_data, split_slot) +
+ boot_img_hdr(&boot_data, split_slot)->ih_hdr_size;
+ *entry = (void *) entry_val;
+ rc = SPLIT_GO_OK;
+
+done:
+ flash_area_close(BOOT_IMG_AREA(&boot_data, split_slot));
+ flash_area_close(BOOT_IMG_AREA(&boot_data, loader_slot));
+ free(sectors);
+ return rc;
+}
diff --git a/bl2/ext/mcuboot/flash_map.c b/bl2/ext/mcuboot/flash_map.c
new file mode 100644
index 0000000..899c5ad
--- /dev/null
+++ b/bl2/ext/mcuboot/flash_map.c
@@ -0,0 +1,360 @@
+/*
+ * 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.
+ */
+
+#include <zephyr.h>
+#include <flash.h>
+
+#include "target.h"
+
+#include <flash_map/flash_map.h>
+#include <hal/hal_flash.h>
+#include <sysflash/sysflash.h>
+
+#define BOOT_LOG_LEVEL BOOT_LOG_LEVEL_INFO
+#include "bootutil/bootutil_log.h"
+
+extern struct device *boot_flash_device;
+
+/*
+ * For now, we only support one flash device.
+ *
+ * Pick a random device ID for it that's unlikely to collide with
+ * anything "real".
+ */
+#define FLASH_DEVICE_ID 100
+#define FLASH_DEVICE_BASE CONFIG_FLASH_BASE_ADDRESS
+
+#define FLASH_MAP_ENTRY_MAGIC 0xd00dbeef
+
+struct flash_map_entry {
+ const uint32_t magic;
+ const struct flash_area area;
+ unsigned int ref_count;
+};
+
+/*
+ * The flash area describes essentially the partition table of the
+ * flash. In this case, it starts with FLASH_AREA_IMAGE_0.
+ */
+static struct flash_map_entry part_map[] = {
+ {
+ .magic = FLASH_MAP_ENTRY_MAGIC,
+ .area = {
+ .fa_id = FLASH_AREA_IMAGE_0,
+ .fa_device_id = FLASH_DEVICE_ID,
+ .fa_off = FLASH_AREA_IMAGE_0_OFFSET,
+ .fa_size = FLASH_AREA_IMAGE_0_SIZE,
+ },
+ },
+ {
+ .magic = FLASH_MAP_ENTRY_MAGIC,
+ .area = {
+ .fa_id = FLASH_AREA_IMAGE_1,
+ .fa_device_id = FLASH_DEVICE_ID,
+ .fa_off = FLASH_AREA_IMAGE_1_OFFSET,
+ .fa_size = FLASH_AREA_IMAGE_1_SIZE,
+ },
+ },
+ {
+ .magic = FLASH_MAP_ENTRY_MAGIC,
+ .area = {
+ .fa_id = FLASH_AREA_IMAGE_SCRATCH,
+ .fa_device_id = FLASH_DEVICE_ID,
+ .fa_off = FLASH_AREA_IMAGE_SCRATCH_OFFSET,
+ .fa_size = FLASH_AREA_IMAGE_SCRATCH_SIZE,
+ },
+ }
+};
+
+int flash_device_base(uint8_t fd_id, uintptr_t *ret)
+{
+ if (fd_id != FLASH_DEVICE_ID) {
+ BOOT_LOG_ERR("invalid flash ID %d; expected %d",
+ fd_id, FLASH_DEVICE_ID);
+ return -EINVAL;
+ }
+ *ret = FLASH_DEVICE_BASE;
+ return 0;
+}
+
+/*
+ * `open` a flash area. The `area` in this case is not the individual
+ * sectors, but describes the particular flash area in question.
+ */
+int flash_area_open(uint8_t id, const struct flash_area **area)
+{
+ int i;
+
+ BOOT_LOG_DBG("area %d", id);
+
+ for (i = 0; i < ARRAY_SIZE(part_map); i++) {
+ if (id == part_map[i].area.fa_id) {
+ break;
+ }
+ }
+ if (i == ARRAY_SIZE(part_map)) {
+ return -1;
+ }
+
+ *area = &part_map[i].area;
+ part_map[i].ref_count++;
+ return 0;
+}
+
+/*
+ * Nothing to do on close.
+ */
+void flash_area_close(const struct flash_area *area)
+{
+ struct flash_map_entry *entry;
+
+ if (!area) {
+ return;
+ }
+
+ entry = CONTAINER_OF(area, struct flash_map_entry, area);
+ if (entry->magic != FLASH_MAP_ENTRY_MAGIC) {
+ BOOT_LOG_ERR("invalid area %p (id %u)", area, area->fa_id);
+ return;
+ }
+ if (entry->ref_count == 0) {
+ BOOT_LOG_ERR("area %u use count underflow", area->fa_id);
+ return;
+ }
+ entry->ref_count--;
+}
+
+void zephyr_flash_area_warn_on_open(void)
+{
+ int i;
+
+ for (i = 0; i < ARRAY_SIZE(part_map); i++) {
+ struct flash_map_entry *entry = &part_map[i];
+ if (entry->ref_count) {
+ BOOT_LOG_WRN("area %u has %u users",
+ entry->area.fa_id, entry->ref_count);
+ }
+ }
+}
+
+int flash_area_read(const struct flash_area *area, uint32_t off, void *dst,
+ uint32_t len)
+{
+ BOOT_LOG_DBG("area=%d, off=%x, len=%x", area->fa_id, off, len);
+ return flash_read(boot_flash_device, area->fa_off + off, dst, len);
+}
+
+int flash_area_write(const struct flash_area *area, uint32_t off, const void *src,
+ uint32_t len)
+{
+ int rc = 0;
+
+ BOOT_LOG_DBG("area=%d, off=%x, len=%x", area->fa_id, off, len);
+ flash_write_protection_set(boot_flash_device, false);
+ rc = flash_write(boot_flash_device, area->fa_off + off, src, len);
+ flash_write_protection_set(boot_flash_device, true);
+ return rc;
+}
+
+int flash_area_erase(const struct flash_area *area, uint32_t off, uint32_t len)
+{
+ int rc;
+
+ BOOT_LOG_DBG("area=%d, off=%x, len=%x", area->fa_id, off, len);
+ flash_write_protection_set(boot_flash_device, false);
+ rc = flash_erase(boot_flash_device, area->fa_off + off, len);
+ flash_write_protection_set(boot_flash_device, true);
+ return rc;
+}
+
+uint8_t flash_area_align(const struct flash_area *area)
+{
+ return hal_flash_align(area->fa_id);
+}
+
+/*
+ * This depends on the mappings defined in sysflash.h, and assumes
+ * that slot 0, slot 1, and the scratch area area contiguous.
+ */
+int flash_area_id_from_image_slot(int slot)
+{
+ return slot + FLASH_AREA_IMAGE_0;
+}
+
+/*
+ * This is used by the legacy file as well; don't mark it static until
+ * that file is removed.
+ */
+int flash_area_get_bounds(int idx, uint32_t *off, uint32_t *len)
+{
+ /*
+ * This simple layout has uniform slots, so just fill in the
+ * right one.
+ */
+ if (idx < FLASH_AREA_IMAGE_0 || idx > FLASH_AREA_IMAGE_SCRATCH) {
+ return -1;
+ }
+
+ switch (idx) {
+ case FLASH_AREA_IMAGE_0:
+ *off = FLASH_AREA_IMAGE_0_OFFSET;
+ *len = FLASH_AREA_IMAGE_0_SIZE;
+ break;
+ case FLASH_AREA_IMAGE_1:
+ *off = FLASH_AREA_IMAGE_1_OFFSET;
+ *len = FLASH_AREA_IMAGE_1_SIZE;
+ break;
+ case FLASH_AREA_IMAGE_SCRATCH:
+ *off = FLASH_AREA_IMAGE_SCRATCH_OFFSET;
+ *len = FLASH_AREA_IMAGE_SCRATCH_SIZE;
+ break;
+ default:
+ BOOT_LOG_ERR("unknown flash area %d", idx);
+ return -1;
+ }
+
+ BOOT_LOG_DBG("area %d: offset=0x%x, length=0x%x", idx, *off, *len);
+ return 0;
+}
+
+/*
+ * The legacy fallbacks are used instead if the flash driver doesn't
+ * provide page layout support.
+ */
+#if defined(CONFIG_FLASH_PAGE_LAYOUT)
+struct layout_data {
+ uint32_t area_idx;
+ uint32_t area_off;
+ uint32_t area_len;
+ void *ret; /* struct flash_area* or struct flash_sector* */
+ uint32_t ret_idx;
+ uint32_t ret_len;
+ int status;
+};
+
+/*
+ * Generic page layout discovery routine. This is kept separate to
+ * support both the deprecated flash_area_to_sectors() and the current
+ * flash_area_get_sectors(). A lot of this can be inlined once
+ * flash_area_to_sectors() is removed.
+ */
+static int flash_area_layout(int idx, int *cnt, void *ret,
+ flash_page_cb cb, struct layout_data *cb_data)
+{
+ cb_data->area_idx = idx;
+ if (flash_area_get_bounds(idx, &cb_data->area_off, &cb_data->area_len)) {
+ return -1;
+ }
+ cb_data->ret = ret;
+ cb_data->ret_idx = 0;
+ cb_data->ret_len = *cnt;
+ cb_data->status = 0;
+
+ flash_page_foreach(boot_flash_device, cb, cb_data);
+
+ if (cb_data->status == 0) {
+ *cnt = cb_data->ret_idx;
+ }
+
+ return cb_data->status;
+}
+
+/*
+ * Check if a flash_page_foreach() callback should exit early, due to
+ * one of the following conditions:
+ *
+ * - The flash page described by "info" is before the area of interest
+ * described in "data"
+ * - The flash page is after the end of the area
+ * - There are too many flash pages on the device to fit in the array
+ * held in data->ret. In this case, data->status is set to -ENOMEM.
+ *
+ * The value to return to flash_page_foreach() is stored in
+ * "bail_value" if the callback should exit early.
+ */
+static bool should_bail(const struct flash_pages_info *info,
+ struct layout_data *data,
+ bool *bail_value)
+{
+ if (info->start_offset < data->area_off) {
+ *bail_value = true;
+ return true;
+ } else if (info->start_offset >= data->area_off + data->area_len) {
+ *bail_value = false;
+ return true;
+ } else if (data->ret_idx >= data->ret_len) {
+ data->status = -ENOMEM;
+ *bail_value = false;
+ return true;
+ }
+
+ return false;
+}
+
+static bool to_sectors_cb(const struct flash_pages_info *info, void *datav)
+{
+ struct layout_data *data = datav;
+ struct flash_area *ret = data->ret;
+ bool bail;
+
+ if (should_bail(info, data, &bail)) {
+ return bail;
+ }
+
+ ret[data->ret_idx].fa_id = data->area_idx;
+ ret[data->ret_idx].fa_device_id = 0;
+ ret[data->ret_idx].pad16 = 0;
+ ret[data->ret_idx].fa_off = info->start_offset;
+ ret[data->ret_idx].fa_size = info->size;
+ data->ret_idx++;
+
+ return true;
+}
+
+int flash_area_to_sectors(int idx, int *cnt, struct flash_area *ret)
+{
+ struct layout_data data;
+
+ return flash_area_layout(idx, cnt, ret, to_sectors_cb, &data);
+}
+
+static bool get_sectors_cb(const struct flash_pages_info *info, void *datav)
+{
+ struct layout_data *data = datav;
+ struct flash_sector *ret = data->ret;
+ bool bail;
+
+ if (should_bail(info, data, &bail)) {
+ return bail;
+ }
+
+ ret[data->ret_idx].fs_off = info->start_offset - data->area_off;
+ ret[data->ret_idx].fs_size = info->size;
+ data->ret_idx++;
+
+ return true;
+}
+
+int flash_area_get_sectors(int idx, uint32_t *cnt, struct flash_sector *ret)
+{
+ struct layout_data data;
+
+ return flash_area_layout(idx, cnt, ret, get_sectors_cb, &data);
+}
+#endif /* defined(CONFIG_FLASH_PAGE_LAYOUT) */
diff --git a/bl2/ext/mcuboot/hal_flash.c b/bl2/ext/mcuboot/hal_flash.c
new file mode 100644
index 0000000..17b6124
--- /dev/null
+++ b/bl2/ext/mcuboot/hal_flash.c
@@ -0,0 +1,29 @@
+/*
+ * 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.
+ */
+
+#include <zephyr.h>
+
+#include "target.h"
+
+#include "hal/hal_flash.h"
+
+uint8_t hal_flash_align(uint8_t flash_id)
+{
+ return FLASH_ALIGN;
+}
diff --git a/bl2/ext/mcuboot/include/config-boot.h b/bl2/ext/mcuboot/include/config-boot.h
new file mode 100644
index 0000000..a81a02f
--- /dev/null
+++ b/bl2/ext/mcuboot/include/config-boot.h
@@ -0,0 +1,97 @@
+/*
+ * Minimal configuration for using TLS in the bootloader
+ *
+ * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * Copyright (C) 2016, Linaro Ltd
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * 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 part of mbed TLS (https://tls.mbed.org)
+ */
+
+/*
+ * Minimal configuration for using TLS in the bootloader
+ *
+ * - RSA or ECDSA signature verification
+ */
+
+#ifndef MBEDTLS_CONFIG_BOOT_H
+#define MBEDTLS_CONFIG_BOOT_H
+
+/* TODO: Configure this between app and target. Really, we want the
+ * config to come from the app. */
+#define CONFIG_BOOT_VERIFY_RSA_SIGNATURE
+
+/* System support */
+#define MBEDTLS_PLATFORM_C
+#define MBEDTLS_PLATFORM_MEMORY
+#define MBEDTLS_MEMORY_BUFFER_ALLOC_C
+#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS
+#define MBEDTLS_PLATFORM_EXIT_ALT
+#define MBEDTLS_NO_PLATFORM_ENTROPY
+#define MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES
+#define MBEDTLS_PLATFORM_PRINTF_ALT
+
+#if !defined(CONFIG_ARM)
+#define MBEDTLS_HAVE_ASM
+#endif
+
+#if defined(CONFIG_MBEDTLS_TEST)
+#define MBEDTLS_SELF_TEST
+#define MBEDTLS_DEBUG_C
+#else
+#define MBEDTLS_ENTROPY_C
+#define MBEDTLS_TEST_NULL_ENTROPY
+#endif
+
+/* mbed TLS feature support */
+#ifdef CONFIG_BOOT_VERIFY_ECDSA_SIGNATURE
+#define MBEDTLS_ECP_DP_SECP256R1_ENABLED
+#define MBEDTLS_ECP_DP_SECP224R1_ENABLED
+#define MBEDTLS_ECP_NIST_OPTIM
+#define MBEDTLS_ECDSA_C
+#define MBEDTLS_ECDH_C
+#define MBEDTLS_ECP_C
+#endif
+
+#ifdef CONFIG_BOOT_VERIFY_RSA_SIGNATURE
+#define MBEDTLS_RSA_C
+#define MBEDTLS_PKCS1_V15
+#endif
+
+/* mbed TLS modules */
+#define MBEDTLS_ASN1_PARSE_C
+#define MBEDTLS_ASN1_WRITE_C
+#define MBEDTLS_BIGNUM_C
+#define MBEDTLS_MD_C
+#define MBEDTLS_OID_C
+#define MBEDTLS_SHA256_C
+
+/* Save RAM by adjusting to our exact needs */
+#ifdef CONFIG_BOOT_VERIFY_RSA_SIGNATURE
+#define MBEDTLS_ECP_MAX_BITS 2048
+#define MBEDTLS_MPI_MAX_SIZE 256
+#else
+#define MBEDTLS_ECP_MAX_BITS 256
+#define MBEDTLS_MPI_MAX_SIZE 32 // 256 bits is 32 bytes
+#endif
+
+#define MBEDTLS_SSL_MAX_CONTENT_LEN 1024
+
+/* Save ROM and a few bytes of RAM by specifying our own ciphersuite list */
+#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8
+
+#include "mbedtls/check_config.h"
+
+#endif /* MBEDTLS_CONFIG_BOOT_H */
diff --git a/bl2/ext/mcuboot/include/flash_map/flash_map.h b/bl2/ext/mcuboot/include/flash_map/flash_map.h
new file mode 100644
index 0000000..506f266
--- /dev/null
+++ b/bl2/ext/mcuboot/include/flash_map/flash_map.h
@@ -0,0 +1,148 @@
+/*
+ * 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.
+ */
+
+#ifndef H_UTIL_FLASH_MAP_
+#define H_UTIL_FLASH_MAP_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ *
+ * Provides abstraction of flash regions for type of use.
+ * I.e. dude where's my image?
+ *
+ * System will contain a map which contains flash areas. Every
+ * region will contain flash identifier, offset within flash and length.
+ *
+ * 1. This system map could be in a file within filesystem (Initializer
+ * must know/figure out where the filesystem is at).
+ * 2. Map could be at fixed location for project (compiled to code)
+ * 3. Map could be at specific place in flash (put in place at mfg time).
+ *
+ * Note that the map you use must be valid for BSP it's for,
+ * match the linker scripts when platform executes from flash,
+ * and match the target offset specified in download script.
+ */
+#include <inttypes.h>
+
+/**
+ * @brief Structure describing an area on a flash device.
+ *
+ * Multiple flash devices may be available in the system, each of
+ * which may have its own areas. For this reason, flash areas track
+ * which flash device they are part of.
+ */
+struct flash_area {
+ /**
+ * This flash area's ID; unique in the system.
+ */
+ uint8_t fa_id;
+
+ /**
+ * ID of the flash device this area is a part of.
+ */
+ uint8_t fa_device_id;
+
+ uint16_t pad16;
+
+ /**
+ * This area's offset, relative to the beginning of its flash
+ * device's storage.
+ */
+ uint32_t fa_off;
+
+ /**
+ * This area's size, in bytes.
+ */
+ uint32_t fa_size;
+};
+
+/**
+ * @brief Structure describing a sector within a flash area.
+ *
+ * Each sector has an offset relative to the start of its flash area
+ * (NOT relative to the start of its flash device), and a size. A
+ * flash area may contain sectors with different sizes.
+ */
+struct flash_sector {
+ /**
+ * Offset of this sector, from the start of its flash area (not device).
+ */
+ uint32_t fs_off;
+
+ /**
+ * Size of this sector, in bytes.
+ */
+ uint32_t fs_size;
+};
+
+/*
+ * Retrieve a memory-mapped flash device's base address.
+ *
+ * On success, the address will be stored in the value pointed to by
+ * ret.
+ *
+ * Returns 0 on success, or an error code on failure.
+ */
+int flash_device_base(uint8_t fd_id, uintptr_t *ret);
+
+/*
+ * Start using flash area.
+ */
+int flash_area_open(uint8_t id, const struct flash_area **);
+
+void flash_area_close(const struct flash_area *);
+
+/*
+ * Read/write/erase. Offset is relative from beginning of flash area.
+ */
+int flash_area_read(const struct flash_area *, uint32_t off, void *dst,
+ uint32_t len);
+int flash_area_write(const struct flash_area *, uint32_t off, const void *src,
+ uint32_t len);
+int flash_area_erase(const struct flash_area *, uint32_t off, uint32_t len);
+
+/*
+ * Alignment restriction for flash writes.
+ */
+uint8_t flash_area_align(const struct flash_area *);
+
+/*
+ * Given flash area ID, return info about sectors within the area.
+ */
+int flash_area_get_sectors(int fa_id, uint32_t *count,
+ struct flash_sector *sectors);
+
+/*
+ * Similar to flash_area_get_sectors(), but return the values in an
+ * array of struct flash_area instead.
+ */
+__attribute__((deprecated))
+int flash_area_to_sectors(int idx, int *cnt, struct flash_area *ret);
+
+int flash_area_id_from_image_slot(int slot);
+int flash_area_id_to_image_slot(int area_id);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* H_UTIL_FLASH_MAP_ */
diff --git a/bl2/ext/mcuboot/include/hal/hal_flash.h b/bl2/ext/mcuboot/include/hal/hal_flash.h
new file mode 100644
index 0000000..2895479
--- /dev/null
+++ b/bl2/ext/mcuboot/include/hal/hal_flash.h
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+
+#ifndef H_HAL_FLASH_
+#define H_HAL_FLASH_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <inttypes.h>
+
+int hal_flash_read(uint8_t flash_id, uint32_t address, void *dst,
+ uint32_t num_bytes);
+int hal_flash_write(uint8_t flash_id, uint32_t address, const void *src,
+ uint32_t num_bytes);
+int hal_flash_erase_sector(uint8_t flash_id, uint32_t sector_address);
+int hal_flash_erase(uint8_t flash_id, uint32_t address, uint32_t num_bytes);
+uint8_t hal_flash_align(uint8_t flash_id);
+int hal_flash_init(void);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* H_HAL_FLASH_ */
diff --git a/bl2/ext/mcuboot/include/os/os_heap.h b/bl2/ext/mcuboot/include/os/os_heap.h
new file mode 100644
index 0000000..4413568
--- /dev/null
+++ b/bl2/ext/mcuboot/include/os/os_heap.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.
+ */
+
+#ifndef H_OS_HEAP_
+#define H_OS_HEAP_
+
+#include <stddef.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void *os_malloc(size_t size);
+void os_free(void *mem);
+void *os_realloc(void *ptr, size_t size);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
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..32b72c2
--- /dev/null
+++ b/bl2/ext/mcuboot/include/os/os_malloc.h
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+#ifndef H_OS_MALLOC_
+#define H_OS_MALLOC_
+
+#include "os/os_heap.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#undef malloc
+#define malloc os_malloc
+
+#undef free
+#define free os_free
+
+#undef realloc
+#define realloc os_realloc
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/bl2/ext/mcuboot/include/target.h b/bl2/ext/mcuboot/include/target.h
new file mode 100644
index 0000000..9ccc032
--- /dev/null
+++ b/bl2/ext/mcuboot/include/target.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2017, Linaro Ltd
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+#ifndef H_TARGETS_TARGET_
+#define H_TARGETS_TARGET_
+
+#if defined(MCUBOOT_TARGET_CONFIG)
+/*
+ * Target-specific definitions are permitted in legacy cases that
+ * don't provide the information via DTS, etc.
+ */
+#include MCUBOOT_TARGET_CONFIG
+#else
+/*
+ * Otherwise, the Zephyr SoC header and the DTS provide most
+ * everything we need.
+ */
+#include <soc.h>
+
+#define FLASH_ALIGN FLASH_WRITE_BLOCK_SIZE
+
+/*
+ * TODO: remove soc_family_kinetis.h once its flash driver supports
+ * FLASH_PAGE_LAYOUT.
+ */
+#if defined(CONFIG_SOC_FAMILY_KINETIS)
+#include "soc_family_kinetis.h"
+#endif
+#endif /* !defined(MCUBOOT_TARGET_CONFIG) */
+
+/*
+ * Sanity check the target support.
+ */
+#if !defined(FLASH_DRIVER_NAME) || \
+ !defined(FLASH_ALIGN) || \
+ !defined(FLASH_AREA_IMAGE_0_OFFSET) || \
+ !defined(FLASH_AREA_IMAGE_0_SIZE) || \
+ !defined(FLASH_AREA_IMAGE_1_OFFSET) || \
+ !defined(FLASH_AREA_IMAGE_1_SIZE) || \
+ !defined(FLASH_AREA_IMAGE_SCRATCH_OFFSET) || \
+ !defined(FLASH_AREA_IMAGE_SCRATCH_SIZE)
+#error "Target support is incomplete; cannot build mcuboot."
+#endif
+
+#endif
diff --git a/bl2/ext/mcuboot/include/util.h b/bl2/ext/mcuboot/include/util.h
new file mode 100644
index 0000000..ba29386
--- /dev/null
+++ b/bl2/ext/mcuboot/include/util.h
@@ -0,0 +1,309 @@
+/*
+ * Copyright (c) 2011-2014, Wind River Systems, Inc.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+/**
+ * @file
+ * @brief Misc utilities
+ *
+ * Misc utilities usable by the kernel and application code.
+ */
+
+#ifndef _UTIL__H_
+#define _UTIL__H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef _ASMLANGUAGE
+
+#include <zephyr/types.h>
+
+/* Helper to pass a int as a pointer or vice-versa.
+ * Those are available for 32 bits architectures:
+ */
+#define POINTER_TO_UINT(x) ((u32_t) (x))
+#define UINT_TO_POINTER(x) ((void *) (x))
+#define POINTER_TO_INT(x) ((s32_t) (x))
+#define INT_TO_POINTER(x) ((void *) (x))
+
+/* Evaluates to 0 if cond is true-ish; compile error otherwise */
+#define ZERO_OR_COMPILE_ERROR(cond) ((int) sizeof(char[1 - 2 * !(cond)]) - 1)
+
+/* Evaluates to 0 if array is an array; compile error if not array (e.g.
+ * pointer)
+ */
+#define IS_ARRAY(array) \
+ ZERO_OR_COMPILE_ERROR( \
+ !__builtin_types_compatible_p(__typeof__(array), \
+ __typeof__(&(array)[0])))
+
+/* Evaluates to number of elements in an array; compile error if not
+ * an array (e.g. pointer)
+ */
+#define ARRAY_SIZE(array) \
+ ((unsigned long) (IS_ARRAY(array) + \
+ (sizeof(array) / sizeof((array)[0]))))
+
+/* Evaluates to 1 if ptr is part of array, 0 otherwise; compile error if
+ * "array" argument is not an array (e.g. "ptr" and "array" mixed up)
+ */
+#define PART_OF_ARRAY(array, ptr) \
+ ((ptr) && ((ptr) >= &array[0] && (ptr) < &array[ARRAY_SIZE(array)]))
+
+#define CONTAINER_OF(ptr, type, field) \
+ ((type *)(((char *)(ptr)) - offsetof(type, field)))
+
+/* round "x" up/down to next multiple of "align" (which must be a power of 2) */
+#define ROUND_UP(x, align) \
+ (((unsigned long)(x) + ((unsigned long)align - 1)) & \
+ ~((unsigned long)align - 1))
+#define ROUND_DOWN(x, align) ((unsigned long)(x) & ~((unsigned long)align - 1))
+
+#define ceiling_fraction(numerator, divider) \
+ (((numerator) + ((divider) - 1)) / (divider))
+
+#ifdef INLINED
+#define INLINE inline
+#else
+#define INLINE
+#endif
+
+#ifndef max
+#define max(a, b) (((a) > (b)) ? (a) : (b))
+#endif
+
+#ifndef min
+#define min(a, b) (((a) < (b)) ? (a) : (b))
+#endif
+
+static inline int is_power_of_two(unsigned int x)
+{
+ return (x != 0) && !(x & (x - 1));
+}
+
+static inline s64_t arithmetic_shift_right(s64_t value, u8_t shift)
+{
+ s64_t sign_ext;
+
+ if (shift == 0) {
+ return value;
+ }
+
+ /* extract sign bit */
+ sign_ext = (value >> 63) & 1;
+
+ /* make all bits of sign_ext be the same as the value's sign bit */
+ sign_ext = -sign_ext;
+
+ /* shift value and fill opened bit positions with sign bit */
+ return (value >> shift) | (sign_ext << (64 - shift));
+}
+
+#endif /* !_ASMLANGUAGE */
+
+/* KB, MB, GB */
+#define KB(x) ((x) << 10)
+#define MB(x) (KB(x) << 10)
+#define GB(x) (MB(x) << 10)
+
+/* KHZ, MHZ */
+#define KHZ(x) ((x) * 1000)
+#define MHZ(x) (KHZ(x) * 1000)
+
+#ifndef BIT
+#define BIT(n) (1UL << (n))
+#endif
+
+#define BIT_MASK(n) (BIT(n) - 1)
+
+/**
+ * @brief Check for macro definition in compiler-visible expressions
+ *
+ * This trick was pioneered in Linux as the config_enabled() macro.
+ * The madness has the effect of taking a macro value that may be
+ * defined to "1" (e.g. CONFIG_MYFEATURE), or may not be defined at
+ * all and turning it into a literal expression that can be used at
+ * "runtime". That is, it works similarly to
+ * "defined(CONFIG_MYFEATURE)" does except that it is an expansion
+ * that can exist in a standard expression and be seen by the compiler
+ * and optimizer. Thus much ifdef usage can be replaced with cleaner
+ * expressions like:
+ *
+ * if (IS_ENABLED(CONFIG_MYFEATURE))
+ * myfeature_enable();
+ *
+ * INTERNAL
+ * First pass just to expand any existing macros, we need the macro
+ * value to be e.g. a literal "1" at expansion time in the next macro,
+ * not "(1)", etc... Standard recursive expansion does not work.
+ */
+#define IS_ENABLED(config_macro) _IS_ENABLED1(config_macro)
+
+/* Now stick on a "_XXXX" prefix, it will now be "_XXXX1" if config_macro
+ * is "1", or just "_XXXX" if it's undefined.
+ * ENABLED: _IS_ENABLED2(_XXXX1)
+ * DISABLED _IS_ENABLED2(_XXXX)
+ */
+#define _IS_ENABLED1(config_macro) _IS_ENABLED2(_XXXX##config_macro)
+
+/* Here's the core trick, we map "_XXXX1" to "_YYYY," (i.e. a string
+ * with a trailing comma), so it has the effect of making this a
+ * two-argument tuple to the preprocessor only in the case where the
+ * value is defined to "1"
+ * ENABLED: _YYYY, <--- note comma!
+ * DISABLED: _XXXX
+ */
+#define _XXXX1 _YYYY,
+
+/* Then we append an extra argument to fool the gcc preprocessor into
+ * accepting it as a varargs macro.
+ * arg1 arg2 arg3
+ * ENABLED: _IS_ENABLED3(_YYYY, 1, 0)
+ * DISABLED _IS_ENABLED3(_XXXX 1, 0)
+ */
+#define _IS_ENABLED2(one_or_two_args) _IS_ENABLED3(one_or_two_args 1, 0)
+
+/* And our second argument is thus now cooked to be 1 in the case
+ * where the value is defined to 1, and 0 if not:
+ */
+#define _IS_ENABLED3(ignore_this, val, ...) val
+
+/**
+ * Macros for doing code-generation with the preprocessor.
+ *
+ * Generally it is better to generate code with the preprocessor than
+ * to copy-paste code or to generate code with the build system /
+ * python script's etc.
+ *
+ * http://stackoverflow.com/a/12540675
+ */
+#define UTIL_EMPTY(...)
+#define UTIL_DEFER(...) __VA_ARGS__ UTIL_EMPTY()
+#define UTIL_OBSTRUCT(...) __VA_ARGS__ UTIL_DEFER(UTIL_EMPTY)()
+#define UTIL_EXPAND(...) __VA_ARGS__
+
+#define UTIL_EVAL(...) UTIL_EVAL1(UTIL_EVAL1(UTIL_EVAL1(__VA_ARGS__)))
+#define UTIL_EVAL1(...) UTIL_EVAL2(UTIL_EVAL2(UTIL_EVAL2(__VA_ARGS__)))
+#define UTIL_EVAL2(...) UTIL_EVAL3(UTIL_EVAL3(UTIL_EVAL3(__VA_ARGS__)))
+#define UTIL_EVAL3(...) UTIL_EVAL4(UTIL_EVAL4(UTIL_EVAL4(__VA_ARGS__)))
+#define UTIL_EVAL4(...) UTIL_EVAL5(UTIL_EVAL5(UTIL_EVAL5(__VA_ARGS__)))
+#define UTIL_EVAL5(...) __VA_ARGS__
+
+#define UTIL_CAT(a, ...) UTIL_PRIMITIVE_CAT(a, __VA_ARGS__)
+#define UTIL_PRIMITIVE_CAT(a, ...) a##__VA_ARGS__
+
+#define UTIL_INC(x) UTIL_PRIMITIVE_CAT(UTIL_INC_, x)
+#define UTIL_INC_0 1
+#define UTIL_INC_1 2
+#define UTIL_INC_2 3
+#define UTIL_INC_3 4
+#define UTIL_INC_4 5
+#define UTIL_INC_5 6
+#define UTIL_INC_6 7
+#define UTIL_INC_7 8
+#define UTIL_INC_8 9
+#define UTIL_INC_9 10
+#define UTIL_INC_10 11
+#define UTIL_INC_11 12
+#define UTIL_INC_12 13
+#define UTIL_INC_13 14
+#define UTIL_INC_14 15
+#define UTIL_INC_15 16
+#define UTIL_INC_16 17
+#define UTIL_INC_17 18
+#define UTIL_INC_18 19
+#define UTIL_INC_19 19
+
+#define UTIL_DEC(x) UTIL_PRIMITIVE_CAT(UTIL_DEC_, x)
+#define UTIL_DEC_0 0
+#define UTIL_DEC_1 0
+#define UTIL_DEC_2 1
+#define UTIL_DEC_3 2
+#define UTIL_DEC_4 3
+#define UTIL_DEC_5 4
+#define UTIL_DEC_6 5
+#define UTIL_DEC_7 6
+#define UTIL_DEC_8 7
+#define UTIL_DEC_9 8
+#define UTIL_DEC_10 9
+#define UTIL_DEC_11 10
+#define UTIL_DEC_12 11
+#define UTIL_DEC_13 12
+#define UTIL_DEC_14 13
+#define UTIL_DEC_15 14
+#define UTIL_DEC_16 15
+#define UTIL_DEC_17 16
+#define UTIL_DEC_18 17
+#define UTIL_DEC_19 18
+
+#define UTIL_CHECK_N(x, n, ...) n
+#define UTIL_CHECK(...) UTIL_CHECK_N(__VA_ARGS__, 0,)
+
+#define UTIL_NOT(x) UTIL_CHECK(UTIL_PRIMITIVE_CAT(UTIL_NOT_, x))
+#define UTIL_NOT_0 ~, 1,
+
+#define UTIL_COMPL(b) UTIL_PRIMITIVE_CAT(UTIL_COMPL_, b)
+#define UTIL_COMPL_0 1
+#define UTIL_COMPL_1 0
+
+#define UTIL_BOOL(x) UTIL_COMPL(UTIL_NOT(x))
+
+#define UTIL_IIF(c) UTIL_PRIMITIVE_CAT(UTIL_IIF_, c)
+#define UTIL_IIF_0(t, ...) __VA_ARGS__
+#define UTIL_IIF_1(t, ...) t
+
+#define UTIL_IF(c) UTIL_IIF(UTIL_BOOL(c))
+
+#define UTIL_EAT(...)
+#define UTIL_EXPAND(...) __VA_ARGS__
+#define UTIL_WHEN(c) UTIL_IF(c)(UTIL_EXPAND, UTIL_EAT)
+
+#define UTIL_REPEAT(count, macro, ...) \
+ UTIL_WHEN(count) \
+ ( \
+ UTIL_OBSTRUCT(UTIL_REPEAT_INDIRECT) () \
+ ( \
+ UTIL_DEC(count), macro, __VA_ARGS__ \
+ ) \
+ UTIL_OBSTRUCT(macro) \
+ ( \
+ UTIL_DEC(count), __VA_ARGS__ \
+ ) \
+ )
+#define UTIL_REPEAT_INDIRECT() UTIL_REPEAT
+
+/**
+ * Generates a sequence of code.
+ * Useful for generating code like;
+ *
+ * NRF_PWM0, NRF_PWM1, NRF_PWM2,
+ *
+ * @arg LEN: The length of the sequence. Must be defined and less than
+ * 20.
+ *
+ * @arg F(i, F_ARG): A macro function that accepts two arguments.
+ * F is called repeatedly, the first argument
+ * is the index in the sequence, and the second argument is the third
+ * argument given to UTIL_LISTIFY.
+ *
+ * Example:
+ *
+ * \#define FOO(i, _) NRF_PWM ## i ,
+ * { UTIL_LISTIFY(PWM_COUNT, FOO) }
+ * // The above two lines will generate the below:
+ * { NRF_PWM0 , NRF_PWM1 , }
+ *
+ * @note Calling UTIL_LISTIFY with undefined arguments has undefined
+ * behaviour.
+ */
+#define UTIL_LISTIFY(LEN, F, F_ARG) UTIL_EVAL(UTIL_REPEAT(LEN, F, F_ARG))
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _UTIL__H_ */
diff --git a/bl2/ext/mcuboot/keys.c b/bl2/ext/mcuboot/keys.c
new file mode 100644
index 0000000..56b78df
--- /dev/null
+++ b/bl2/ext/mcuboot/keys.c
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ */
+
+#include <bootutil/sign_key.h>
+
+#if defined(MCUBOOT_SIGN_RSA)
+const unsigned char root_pub_der[] = {
+ 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xd1, 0x06, 0x08,
+ 0x1a, 0x18, 0x44, 0x2c, 0x18, 0xe8, 0xfb, 0xfd, 0xf7, 0x0d, 0xa3, 0x4f,
+ 0x1f, 0xbb, 0xee, 0x5e, 0xf9, 0xaa, 0xd2, 0x4b, 0x18, 0xd3, 0x5a, 0xe9,
+ 0x6d, 0x18, 0x80, 0x19, 0xf9, 0xf0, 0x9c, 0x34, 0x1b, 0xcb, 0xf3, 0xbc,
+ 0x74, 0xdb, 0x42, 0xe7, 0x8c, 0x7f, 0x10, 0x53, 0x7e, 0x43, 0x5e, 0x0d,
+ 0x57, 0x2c, 0x44, 0xd1, 0x67, 0x08, 0x0f, 0x0d, 0xbb, 0x5c, 0xee, 0xec,
+ 0xb3, 0x99, 0xdf, 0xe0, 0x4d, 0x84, 0x0b, 0xaa, 0x77, 0x41, 0x60, 0xed,
+ 0x15, 0x28, 0x49, 0xa7, 0x01, 0xb4, 0x3c, 0x10, 0xe6, 0x69, 0x8c, 0x2f,
+ 0x5f, 0xac, 0x41, 0x4d, 0x9e, 0x5c, 0x14, 0xdf, 0xf2, 0xf8, 0xcf, 0x3d,
+ 0x1e, 0x6f, 0xe7, 0x5b, 0xba, 0xb4, 0xa9, 0xc8, 0x88, 0x7e, 0x47, 0x3c,
+ 0x94, 0xc3, 0x77, 0x67, 0x54, 0x4b, 0xaa, 0x8d, 0x38, 0x35, 0xca, 0x62,
+ 0x61, 0x7e, 0xb7, 0xe1, 0x15, 0xdb, 0x77, 0x73, 0xd4, 0xbe, 0x7b, 0x72,
+ 0x21, 0x89, 0x69, 0x24, 0xfb, 0xf8, 0x65, 0x6e, 0x64, 0x3e, 0xc8, 0x0e,
+ 0xd7, 0x85, 0xd5, 0x5c, 0x4a, 0xe4, 0x53, 0x0d, 0x2f, 0xff, 0xb7, 0xfd,
+ 0xf3, 0x13, 0x39, 0x83, 0x3f, 0xa3, 0xae, 0xd2, 0x0f, 0xa7, 0x6a, 0x9d,
+ 0xf9, 0xfe, 0xb8, 0xce, 0xfa, 0x2a, 0xbe, 0xaf, 0xb8, 0xe0, 0xfa, 0x82,
+ 0x37, 0x54, 0xf4, 0x3e, 0xe1, 0x2b, 0xd0, 0xd3, 0x08, 0x58, 0x18, 0xf6,
+ 0x5e, 0x4c, 0xc8, 0x88, 0x81, 0x31, 0xad, 0x5f, 0xb0, 0x82, 0x17, 0xf2,
+ 0x8a, 0x69, 0x27, 0x23, 0xf3, 0xab, 0x87, 0x3e, 0x93, 0x1a, 0x1d, 0xfe,
+ 0xe8, 0xf8, 0x1a, 0x24, 0x66, 0x59, 0xf8, 0x1c, 0xab, 0xdc, 0xce, 0x68,
+ 0x1b, 0x66, 0x64, 0x35, 0xec, 0xfa, 0x0d, 0x11, 0x9d, 0xaf, 0x5c, 0x3a,
+ 0xa7, 0xd1, 0x67, 0xc6, 0x47, 0xef, 0xb1, 0x4b, 0x2c, 0x62, 0xe1, 0xd1,
+ 0xc9, 0x02, 0x03, 0x01, 0x00, 0x01
+};
+const unsigned int root_pub_der_len = 270;
+#elif defined(MCUBOOT_SIGN_EC256)
+const unsigned char root_pub_der[] = {
+ 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
+ 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
+ 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
+ 0x42, 0x00, 0x04, 0x2a, 0xcb, 0x40, 0x3c, 0xe8,
+ 0xfe, 0xed, 0x5b, 0xa4, 0x49, 0x95, 0xa1, 0xa9,
+ 0x1d, 0xae, 0xe8, 0xdb, 0xbe, 0x19, 0x37, 0xcd,
+ 0x14, 0xfb, 0x2f, 0x24, 0x57, 0x37, 0xe5, 0x95,
+ 0x39, 0x88, 0xd9, 0x94, 0xb9, 0xd6, 0x5a, 0xeb,
+ 0xd7, 0xcd, 0xd5, 0x30, 0x8a, 0xd6, 0xfe, 0x48,
+ 0xb2, 0x4a, 0x6a, 0x81, 0x0e, 0xe5, 0xf0, 0x7d,
+ 0x8b, 0x68, 0x34, 0xcc, 0x3a, 0x6a, 0xfc, 0x53,
+ 0x8e, 0xfa, 0xc1, };
+const unsigned int root_pub_der_len = 91;
+#else
+#error "No public key available for given signing algorithm."
+#endif
+
+#if defined(MCUBOOT_SIGN_RSA) || defined(MCUBOOT_SIGN_EC256)
+const struct bootutil_key bootutil_keys[] = {
+ {
+ .key = root_pub_der,
+ .len = &root_pub_der_len,
+ },
+};
+const int bootutil_key_cnt = 1;
+#endif
diff --git a/bl2/ext/mcuboot/main.c b/bl2/ext/mcuboot/main.c
new file mode 100644
index 0000000..cdd4139
--- /dev/null
+++ b/bl2/ext/mcuboot/main.c
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2012-2014 Wind River Systems, Inc.
+ *
+ * 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.
+ */
+
+#include <assert.h>
+#include <zephyr.h>
+#include <flash.h>
+#include <asm_inline.h>
+#include <drivers/system_timer.h>
+
+#include "target.h"
+
+#define BOOT_LOG_LEVEL BOOT_LOG_LEVEL_INFO
+#include "bootutil/bootutil_log.h"
+#include "bootutil/image.h"
+#include "bootutil/bootutil.h"
+#include "flash_map/flash_map.h"
+
+struct device *boot_flash_device;
+
+void os_heap_init(void);
+
+extern void zephyr_flash_area_warn_on_open(void);
+
+#if defined(CONFIG_ARM)
+struct arm_vector_table {
+ uint32_t msp;
+ uint32_t reset;
+};
+
+static void do_boot(struct boot_rsp *rsp)
+{
+ struct arm_vector_table *vt;
+ uintptr_t flash_base;
+ int rc;
+
+ /* The beginning of the image is the ARM vector table, containing
+ * the initial stack pointer address and the reset vector
+ * consecutively. Manually set the stack pointer and jump into the
+ * reset vector
+ */
+ rc = flash_device_base(rsp->br_flash_dev_id, &flash_base);
+ assert(rc == 0);
+
+ vt = (struct arm_vector_table *)(flash_base +
+ rsp->br_image_off +
+ rsp->br_hdr->ih_hdr_size);
+ irq_lock();
+ sys_clock_disable();
+ _MspSet(vt->msp);
+ ((void (*)(void))vt->reset)();
+}
+#else
+/* Default: Assume entry point is at the very beginning of the image. Simply
+ * lock interrupts and jump there. This is the right thing to do for X86 and
+ * possibly other platforms.
+ */
+static void do_boot(struct boot_rsp *rsp)
+{
+ uintptr_t flash_base;
+ void *start;
+ int rc;
+
+ rc = flash_device_base(rsp->br_flash_dev_id, &flash_base);
+ assert(rc == 0);
+
+ start = (void *)(flash_base + rsp->br_image_off +
+ rsp->br_hdr->ih_hdr_size);
+
+ /* Lock interrupts and dive into the entry point */
+ irq_lock();
+ ((void (*)(void))start)();
+}
+#endif
+
+void main(void)
+{
+ struct boot_rsp rsp;
+ int rc;
+
+ BOOT_LOG_INF("Starting bootloader");
+
+ os_heap_init();
+
+ boot_flash_device = device_get_binding(FLASH_DRIVER_NAME);
+ if (!boot_flash_device) {
+ BOOT_LOG_ERR("Flash device not found");
+ while (1)
+ ;
+ }
+
+ rc = boot_go(&rsp);
+ if (rc != 0) {
+ BOOT_LOG_ERR("Unable to find bootable image");
+ while (1)
+ ;
+ }
+
+ BOOT_LOG_INF("Bootloader chainload address offset: 0x%x",
+ rsp.br_image_off);
+ zephyr_flash_area_warn_on_open();
+ BOOT_LOG_INF("Jumping to the first image slot");
+ do_boot(&rsp);
+
+ BOOT_LOG_ERR("Never should get here");
+ while (1)
+ ;
+}
diff --git a/bl2/ext/mcuboot/os.c b/bl2/ext/mcuboot/os.c
new file mode 100644
index 0000000..0a5abbd
--- /dev/null
+++ b/bl2/ext/mcuboot/os.c
@@ -0,0 +1,52 @@
+/*
+ * 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.
+ */
+
+#include <zephyr.h>
+#include <string.h>
+
+#include "os/os_heap.h"
+
+#define MBEDTLS_CONFIG_FILE CONFIG_MBEDTLS_CFG_FILE
+#include <mbedtls/platform.h>
+
+/* D(void *os_malloc(size_t size)) */
+void *os_calloc(size_t nelem, size_t size)
+{
+ /* Note that this doesn't check for overflow. Assume the
+ * calls only come from within the app. */
+ size_t total = nelem * size;
+ void *buf = k_malloc(total);
+ if (buf) {
+ memset(buf, 0, total);
+ }
+ return buf;
+}
+
+void os_free(void *ptr)
+{
+ k_free(ptr);
+}
+
+/*
+ * Initialize mbedtls to be able to use the local heap.
+ */
+void os_heap_init(void)
+{
+ mbedtls_platform_set_calloc_free(os_calloc, os_free);
+}
diff --git a/bl2/ext/mcuboot/root-rsa-2048.pem b/bl2/ext/mcuboot/root-rsa-2048.pem
new file mode 100644
index 0000000..78c0c34
--- /dev/null
+++ b/bl2/ext/mcuboot/root-rsa-2048.pem
@@ -0,0 +1,27 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIEowIBAAKCAQEA0QYIGhhELBjo+/33DaNPH7vuXvmq0ksY01rpbRiAGfnwnDQb
+y/O8dNtC54x/EFN+Q14NVyxE0WcIDw27XO7ss5nf4E2EC6p3QWDtFShJpwG0PBDm
+aYwvX6xBTZ5cFN/y+M89Hm/nW7q0qciIfkc8lMN3Z1RLqo04NcpiYX634RXbd3PU
+vntyIYlpJPv4ZW5kPsgO14XVXErkUw0v/7f98xM5gz+jrtIPp2qd+f64zvoqvq+4
+4PqCN1T0PuEr0NMIWBj2XkzIiIExrV+wghfyimknI/Orhz6TGh3+6PgaJGZZ+Byr
+3M5oG2ZkNez6DRGdr1w6p9FnxkfvsUssYuHRyQIDAQABAoIBAEahFCHFK1v/OtLT
+eSSZl0Xw2dYr5QXULFpWsOOVUMv2QdB2ZyIehQKziEL3nYPlwpd+82EOa16awwVb
+LYF0lnUFvLltV/4dJtjnqJTqnSCamc1mJIVrwiJA8XwJ07GWDuL2G//p7jJ3v05T
+nZOV/KmD9xfqSvshZun+LgolqHqcrAa1f4cmuP9C9oqenZryljyfj7piaIZGI0JR
+PrJJ5kImYJqRcMgKTyHP4L8nwQ4moMJr6zbfbWxxb5TC7KVZSQ9UKZZ+ZLuy/pkU
+Qe4G8XSE0r+R9u4JCg87I1vgHhn8WJSxVX027OVUq5HfOzg2skQBTcExph5V9B2b
+onNxd8UCgYEA/32PW+ZwRcdKXMj+QVkxXUd6xkXy7mTXPEaQuOLWZQgrSqAFH1l4
+5/6d099KAJrjM6kR8pKXtz72IIyMHTPm332ghymjKvaEl2XP9sF+f6FmYURar4y6
+8Zh3eivP86+Q/YzOGKwtRSziBMzrAfoIXgtwH8pwIPYLP3zBV4449ZsCgYEA0XC/
+gu2ub5M6EXBnjq9K2d4LlTyAPsIbAcMSwkhOUH4YJFS22qXLYQUA9zM+DUyLCrl/
+PKN2G0HQVgMb4DIbeHv8kXB5oGm5zfbWorWqOomXB3AsI7X8YDMtf/PsZV2amBei
+qVskmPJQV21qFyeOcHlT+dHuRb0O0un3dK8RHmsCgYEApDCH4dJ80osZoflVVJ/C
+VqTqJOOtFEFgBQ+AUCEPEQyn7aRaxmPUjJsXyKJVx3/ChV+g9hf5Qj1HJXHNVbMW
+KwhsEpDSmHimizlV5clBxzntNpMcCHdTaJHILo5bbMqmThugE0ELMsp+UgFzAeky
+WWXWX8fUOYqFff5prh/rQQMCgYBQQ8FhT+113Rp37HgDerJY5HvT6afMZV8sQbJC
+uqsotepSohShnsBeoihIlF7HgfoXVhepCYwNzh8ll3NrbEiS2BFnO4+hJmOKx3pi
+SPTAElLLCvYfiXL6+yII01ZZUpIYj5ZLCR7xbovTtZ7e2M4B1L2WFBoYp+eydO/c
+y+rnmQKBgCh0gfyBT/OKPkfKv+Bbt8HcoxgEj+TyH+vYdeTbP9ZSJ6y5utMbPg7z
+iLLbJ+9IcSwPCwJSmI+I0Om4xEp4ZblCrzAG7hWvG2NNzxQjmoOOrAANyTvJR/ap
+N+UkQA4WrMSKEYyBlRS/hR9Unz31vMc2k9Re0ukWhWh/QksQGDfJ
+-----END RSA PRIVATE KEY-----
diff --git a/bl2/ext/mcuboot/scripts/assemble.py b/bl2/ext/mcuboot/scripts/assemble.py
new file mode 100644
index 0000000..7a38985
--- /dev/null
+++ b/bl2/ext/mcuboot/scripts/assemble.py
@@ -0,0 +1,114 @@
+#! /usr/bin/env python3
+#
+# 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.
+
+"""
+Assemble multiple images into a single image that can be flashed on the device.
+"""
+
+import argparse
+import errno
+import io
+import re
+import os.path
+
+def same_keys(a, b):
+ """Determine if the dicts a and b have the same keys in them"""
+ for ak in a.keys():
+ if ak not in b:
+ return False
+ for bk in b.keys():
+ if bk not in a:
+ return False
+ return True
+
+offset_re = re.compile(r"^#define FLASH_AREA_([0-9A-Z_]+)_OFFSET_0\s+((0x)?[0-9a-fA-F]+)")
+size_re = re.compile(r"^#define FLASH_AREA_([0-9A-Z_]+)_SIZE_0\s+((0x)?[0-9a-fA-F]+)")
+
+class Assembly():
+ def __init__(self, output, bootdir):
+ self.find_slots(bootdir)
+ try:
+ os.unlink(output)
+ except OSError as e:
+ if e.errno != errno.ENOENT:
+ raise
+ self.output = output
+
+ def find_slots(self, bootdir):
+ offsets = {}
+ sizes = {}
+ with open(os.path.join(bootdir, 'include', 'generated', 'generated_dts_board.h'), 'r') as fd:
+ for line in fd:
+ m = offset_re.match(line)
+ if m is not None:
+ offsets[m.group(1)] = int(m.group(2), 0)
+ m = size_re.match(line)
+ if m is not None:
+ sizes[m.group(1)] = int(m.group(2), 0)
+
+ if not same_keys(offsets, sizes):
+ raise Exception("Inconsistent data in generated_dts_board.h")
+
+ # We care about the MCUBOOT, IMAGE_0, and IMAGE_1 partitions.
+ if 'MCUBOOT' not in offsets:
+ raise Exception("Board partition table does not have mcuboot partition")
+
+ if 'IMAGE_0' not in offsets:
+ raise Exception("Board partition table does not have image-0 partition")
+
+ if 'IMAGE_1' not in offsets:
+ raise Exception("Board partition table does not have image-1 partition")
+
+ self.offsets = offsets
+ self.sizes = sizes
+
+ def add_image(self, source, partition):
+ with open(self.output, 'ab') as ofd:
+ pos = ofd.tell()
+ print("partition {}, pos={}, offset={}".format(partition, pos, self.offsets[partition]))
+ if pos > self.offsets[partition]:
+ raise Exception("Partitions not in order, unsupported")
+ if pos < self.offsets[partition]:
+ buf = b'\xFF' * (self.offsets[partition] - pos)
+ ofd.write(buf)
+ with open(source, 'rb') as rfd:
+ ibuf = rfd.read()
+ if len(ibuf) > self.sizes[partition]:
+ raise Exception("Image {} is too large for partition".format(source))
+ ofd.write(ibuf)
+
+def main():
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument('-b', '--bootdir', required=True,
+ help='Directory of built bootloader')
+ parser.add_argument('-p', '--primary', required=True,
+ help='Signed image file for primary image')
+ parser.add_argument('-s', '--secondary',
+ help='Signed image file for secondary image')
+ parser.add_argument('-o', '--output', required=True,
+ help='Filename to write full image to')
+
+ args = parser.parse_args()
+ output = Assembly(args.output, args.bootdir)
+
+ output.add_image(os.path.join(args.bootdir, "zephyr.bin"), 'MCUBOOT')
+ output.add_image(args.primary, "IMAGE_0")
+ if args.secondary is not None:
+ output.add_image(args.secondary, "IMAGE_1")
+
+if __name__ == '__main__':
+ main()
diff --git a/bl2/ext/mcuboot/scripts/imgtool.py b/bl2/ext/mcuboot/scripts/imgtool.py
new file mode 100644
index 0000000..bc67252
--- /dev/null
+++ b/bl2/ext/mcuboot/scripts/imgtool.py
@@ -0,0 +1,119 @@
+#! /usr/bin/env python3
+#
+# 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.
+
+import argparse
+from imgtool import keys
+from imgtool import image
+from imgtool import version
+import sys
+
+def gen_rsa2048(args):
+ keys.RSA2048.generate().export_private(args.key)
+def gen_ecdsa_p256(args):
+ keys.ECDSA256P1.generate().export_private(args.key)
+def gen_ecdsa_p224(args):
+ print("TODO: p-224 not yet implemented")
+
+keygens = {
+ 'rsa-2048': gen_rsa2048,
+ 'ecdsa-p256': gen_ecdsa_p256,
+ 'ecdsa-p224': gen_ecdsa_p224, }
+
+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()
+ elif args.lang == 'rust':
+ key.emit_rust()
+ else:
+ msg = "Unsupported language, valid are: c, or rust"
+ raise argparse.ArgumentTypeError(msg)
+
+def do_sign(args):
+ if args.rsa_pkcs1_15:
+ keys.sign_rsa_pss = False
+ img = image.Image.load(args.infile, version=args.version,
+ header_size=args.header_size,
+ included_header=args.included_header,
+ pad=args.pad)
+ key = keys.load(args.key) if args.key else None
+ img.sign(key)
+
+ if args.pad:
+ img.pad_to(args.pad, args.align)
+
+ img.save(args.outfile)
+
+subcmds = {
+ 'keygen': do_keygen,
+ 'getpub': do_getpub,
+ 'sign': do_sign, }
+
+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('-k', '--key', metavar='filename')
+ sign.add_argument("--align", type=alignment_value, required=True)
+ sign.add_argument("-v", "--version", type=version.decode_version, required=True)
+ 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("--pad", type=intparse,
+ help='Pad image to this many bytes, adding trailer magic')
+ 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")
+
+ 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/__init__.py b/bl2/ext/mcuboot/scripts/imgtool/__init__.py
new file mode 100644
index 0000000..107921f
--- /dev/null
+++ b/bl2/ext/mcuboot/scripts/imgtool/__init__.py
@@ -0,0 +1,13 @@
+# 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.
diff --git a/bl2/ext/mcuboot/scripts/imgtool/image.py b/bl2/ext/mcuboot/scripts/imgtool/image.py
new file mode 100644
index 0000000..79a342d
--- /dev/null
+++ b/bl2/ext/mcuboot/scripts/imgtool/image.py
@@ -0,0 +1,189 @@
+# 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.
+
+"""
+Image signing and management.
+"""
+
+from . import version as versmod
+import hashlib
+import struct
+
+IMAGE_MAGIC = 0x96f3b83d
+IMAGE_HEADER_SIZE = 32
+
+# Image header flags.
+IMAGE_F = {
+ 'PIC': 0x0000001,
+ 'NON_BOOTABLE': 0x0000010, }
+
+TLV_VALUES = {
+ 'KEYHASH': 0x01,
+ 'SHA256': 0x10,
+ 'RSA2048': 0x20,
+ 'ECDSA224': 0x21,
+ 'ECDSA256': 0x22, }
+
+TLV_INFO_SIZE = 4
+TLV_INFO_MAGIC = 0x6907
+TLV_HEADER_SIZE = 4
+
+# 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 = bytes([
+ 0x77, 0xc2, 0x95, 0xf3,
+ 0x60, 0xd2, 0xef, 0x7f,
+ 0x35, 0x52, 0x50, 0x0f,
+ 0x2c, 0xb6, 0x79, 0x80, ])
+
+class TLV():
+ def __init__(self):
+ self.buf = bytearray()
+
+ 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):
+ header = struct.pack('<HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
+ 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=None, header_size=IMAGE_HEADER_SIZE, pad=0):
+ self.version = version or versmod.decode_version("0")
+ self.header_size = header_size or IMAGE_HEADER_SIZE
+ self.pad = pad
+
+ def __repr__(self):
+ return "<Image version={}, header_size={}, pad={}, payloadlen=0x{:x}>".format(
+ self.version,
+ self.header_size,
+ 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 for v in self.payload[0:self.header_size]):
+ raise Exception("Padding requested, but image does not start with zeros")
+
+ def sign(self, key):
+ self.add_header(key)
+
+ tlv = TLV()
+
+ # Note that ecdsa wants to do the hashing itself, which means
+ # we get to hash it twice.
+ sha = hashlib.sha256()
+ sha.update(self.payload)
+ digest = sha.digest()
+
+ tlv.add('SHA256', digest)
+
+ if key is not None:
+ pub = key.get_public_bytes()
+ sha = hashlib.sha256()
+ sha.update(pub)
+ pubbytes = sha.digest()
+ tlv.add('KEYHASH', pubbytes)
+
+ sig = key.sign(self.payload)
+ tlv.add(key.sig_tlv(), sig)
+
+ self.payload += tlv.get()
+
+ def add_header(self, key):
+ """Install the image header.
+
+ The key is needed to know the type of signature, and
+ approximate the size of the signature."""
+
+ flags = 0
+ tlvsz = 0
+ if key is not None:
+ tlvsz += TLV_HEADER_SIZE + key.sig_len()
+
+ tlvsz += 4 + hashlib.sha256().digest_size
+ tlvsz += 4 + hashlib.sha256().digest_size
+
+ fmt = ('<' +
+ # type ImageHdr struct {
+ 'I' + # Magic uint32
+ 'H' + # TlvSz uint16
+ 'B' + # KeyId uint8
+ 'B' + # Pad1 uint8
+ 'H' + # HdrSz uint16
+ 'H' + # Pad2 uint16
+ 'I' + # ImgSz uint32
+ 'I' + # Flags uint32
+ 'BBHI' + # Vers ImageVersion
+ 'I' # Pad3 uint32
+ ) # }
+ assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
+ header = struct.pack(fmt,
+ IMAGE_MAGIC,
+ tlvsz, # TlvSz
+ 0, # KeyId (TODO: allow other ids)
+ 0, # Pad1
+ self.header_size,
+ 0, # Pad2
+ len(self.payload) - self.header_size, # ImageSz
+ flags, # Flags
+ self.version.major,
+ self.version.minor or 0,
+ self.version.revision or 0,
+ self.version.build or 0,
+ 0) # Pad3
+ 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/keys.py b/bl2/ext/mcuboot/scripts/imgtool/keys.py
new file mode 100644
index 0000000..ee54a0f
--- /dev/null
+++ b/bl2/ext/mcuboot/scripts/imgtool/keys.py
@@ -0,0 +1,183 @@
+# 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.
+
+"""
+Cryptographic key management for imgtool.
+"""
+
+from Crypto.Hash import SHA256
+from Crypto.PublicKey import RSA
+from Crypto.Signature import PKCS1_v1_5, PKCS1_PSS
+from ecdsa import SigningKey, NIST256p, util
+import hashlib
+from pyasn1.type import namedtype, univ
+from pyasn1.codec.der.encoder import encode
+
+# 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 RSAPublicKey(univ.Sequence):
+ componentType = namedtype.NamedTypes(
+ namedtype.NamedType('modulus', univ.Integer()),
+ namedtype.NamedType('publicExponent', univ.Integer()))
+
+class RSA2048():
+ def __init__(self, key):
+ """Construct an RSA2048 key with the given key data"""
+ self.key = key
+
+ @staticmethod
+ def generate():
+ return RSA2048(RSA.generate(2048))
+
+ def export_private(self, path):
+ with open(path, 'wb') as f:
+ f.write(self.key.exportKey('PEM'))
+
+ def get_public_bytes(self):
+ node = RSAPublicKey()
+ node['modulus'] = self.key.n
+ node['publicExponent'] = self.key.e
+ return bytearray(encode(node))
+
+ 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 emit_rust(self):
+ print(AUTOGEN_MESSAGE)
+ print("static RSA_PUB_KEY: &'static [u8] = &[", end='')
+ encoded = self.get_public_bytes()
+ for count, b in enumerate(encoded):
+ if count % 8 == 0:
+ print("\n ", end='')
+ else:
+ print(" ", end='')
+ print("0x{:02x},".format(b), end='')
+ print("\n];")
+
+ def sig_type(self):
+ """Return the type of this signature (as a string)"""
+ if sign_rsa_pss:
+ return "PKCS1_PSS_RSA2048_SHA256"
+ else:
+ return "PKCS15_RSA2048_SHA256"
+
+ def sig_len(self):
+ return 256
+
+ def sig_tlv(self):
+ return "RSA2048"
+
+ def sign(self, payload):
+ sha = SHA256.new(payload)
+ if sign_rsa_pss:
+ signer = PKCS1_PSS.new(self.key)
+ else:
+ signer = PKCS1_v1_5.new(self.key)
+ signature = signer.sign(sha)
+ assert len(signature) == self.sig_len()
+ return signature
+
+class ECDSA256P1():
+ def __init__(self, key):
+ """Construct an ECDSA P-256 private key"""
+ self.key = key
+
+ @staticmethod
+ def generate():
+ return ECDSA256P1(SigningKey.generate(curve=NIST256p))
+
+ def export_private(self, path):
+ with open(path, 'wb') as f:
+ f.write(self.key.to_pem())
+
+ def get_public_bytes(self):
+ vk = self.key.get_verifying_key()
+ return bytes(vk.to_der())
+
+ def emit_c(self):
+ vk = self.key.get_verifying_key()
+ print(AUTOGEN_MESSAGE)
+ print("const unsigned char ecdsa_pub_key[] = {", end='')
+ encoded = bytes(vk.to_der())
+ 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 ecdsa_pub_key_len = {};".format(len(encoded)))
+
+ def emit_rust(self):
+ vk = self.key.get_verifying_key()
+ print(AUTOGEN_MESSAGE)
+ print("static ECDSA_PUB_KEY: &'static [u8] = &[", end='')
+ encoded = bytes(vk.to_der())
+ for count, b in enumerate(encoded):
+ if count % 8 == 0:
+ print("\n ", end='')
+ else:
+ print(" ", end='')
+ print("0x{:02x},".format(b), end='')
+ print("\n];")
+
+ def sign(self, payload):
+ # To make this fixed length, possibly pad with zeros.
+ sig = self.key.sign(payload, hashfunc=hashlib.sha256, sigencode=util.sigencode_der)
+ sig += b'\000' * (self.sig_len() - len(sig))
+ return sig
+
+ def sig_len(self):
+ # The DER encoding depends on the high bit, and can be
+ # anywhere from 70 to 72 bytes. Because we have to fill in
+ # the length field before computing the signature, however,
+ # we'll give the largest, and the sig checking code will allow
+ # for it to be up to two bytes larger than the actual
+ # signature.
+ return 72
+
+ def sig_type(self):
+ """Return the type of this signature (as a string)"""
+ return "ECDSA256_SHA256"
+
+ def sig_tlv(self):
+ return "ECDSA256"
+
+def load(path):
+ with open(path, 'rb') as f:
+ pem = f.read()
+ try:
+ key = RSA.importKey(pem)
+ if key.n.bit_length() != 2048:
+ raise Exception("Unsupported RSA bit length, only 2048 supported")
+ return RSA2048(key)
+ except ValueError:
+ key = SigningKey.from_pem(pem)
+ if key.curve.name != 'NIST256p':
+ raise Exception("Unsupported ECDSA curve")
+ return ECDSA256P1(key)
diff --git a/bl2/ext/mcuboot/scripts/imgtool/version.py b/bl2/ext/mcuboot/scripts/imgtool/version.py
new file mode 100644
index 0000000..64962e9
--- /dev/null
+++ b/bl2/ext/mcuboot/scripts/imgtool/version.py
@@ -0,0 +1,47 @@
+# 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.
+
+"""
+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'])
+
+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)
+ # print("decode:", text, m.groups())
+ 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"))