mcuboot - Initial migration.
diff --git a/bootutil/src/bootutil_misc.c b/bootutil/src/bootutil_misc.c
new file mode 100644
index 0000000..f3ab9d5
--- /dev/null
+++ b/bootutil/src/bootutil_misc.c
@@ -0,0 +1,456 @@
+/*
+ * 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 "syscfg/syscfg.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"
+
+int boot_current_slot;
+
+const uint32_t boot_img_magic[4] = {
+    0xf395c277,
+    0x7fefd260,
+    0x0f505235,
+    0x8079b62c,
+};
+
+struct boot_swap_table {
+    /** * For each field, a value of 0 means "any". */
+    uint8_t bsw_magic_slot0;
+    uint8_t bsw_magic_slot1;
+    uint8_t bsw_image_ok_slot0;
+
+    uint8_t bsw_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.
+ */
+static const struct boot_swap_table boot_swap_tables[] = {
+    {
+        /*          | slot-0     | slot-1     |
+         *----------+------------+------------|
+         *    magic | Unset      | Unset      |
+         * image-ok | Any        | N/A        |
+         * ---------+------------+------------'
+         * swap: none                         |
+         * -----------------------------------'
+         */
+        .bsw_magic_slot0 =      BOOT_MAGIC_UNSET,
+        .bsw_magic_slot1 =      BOOT_MAGIC_UNSET,
+        .bsw_image_ok_slot0 =   0,
+        .bsw_swap_type =        BOOT_SWAP_TYPE_NONE,
+    },
+
+    {
+        /*          | slot-0     | slot-1     |
+         *----------+------------+------------|
+         *    magic | Any        | Good       |
+         * image-ok | Any        | N/A        |
+         * ---------+------------+------------'
+         * swap: test                         |
+         * -----------------------------------'
+         */
+        .bsw_magic_slot0 =      0,
+        .bsw_magic_slot1 =      BOOT_MAGIC_GOOD,
+        .bsw_image_ok_slot0 =   0,
+        .bsw_swap_type =        BOOT_SWAP_TYPE_TEST,
+    },
+
+    {
+        /*          | slot-0     | slot-1     |
+         *----------+------------+------------|
+         *    magic | Good       | Unset      |
+         * image-ok | 0xff       | N/A        |
+         * ---------+------------+------------'
+         * swap: revert (test image running)  |
+         * -----------------------------------'
+         */
+        .bsw_magic_slot0 =      BOOT_MAGIC_GOOD,
+        .bsw_magic_slot1 =      BOOT_MAGIC_UNSET,
+        .bsw_image_ok_slot0 =   0xff,
+        .bsw_swap_type =        BOOT_SWAP_TYPE_REVERT,
+    },
+
+    {
+        /*          | slot-0     | slot-1     |
+         *----------+------------+------------|
+         *    magic | Good       | Unset      |
+         * image-ok | 0x01       | N/A        |
+         * ---------+------------+------------'
+         * swap: none (confirmed test image)  |
+         * -----------------------------------'
+         */
+        .bsw_magic_slot0 =      BOOT_MAGIC_GOOD,
+        .bsw_magic_slot1 =      BOOT_MAGIC_UNSET,
+        .bsw_image_ok_slot0 =   0x01,
+        .bsw_swap_type =        BOOT_SWAP_TYPE_NONE,
+    },
+};
+
+#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, sizeof boot_img_magic) == 0) {
+        return BOOT_MAGIC_GOOD;
+    }
+
+    for (i = 0; i < 4; i++) {
+        if (magic[i] == 0xffffffff) {
+            return BOOT_MAGIC_UNSET;
+        }
+    }
+
+    return BOOT_MAGIC_BAD;
+}
+
+uint32_t
+boot_status_sz(uint8_t min_write_sz)
+{
+    return BOOT_STATUS_MAX_ENTRIES * BOOT_STATUS_STATE_COUNT * min_write_sz;
+}
+
+uint32_t
+boot_trailer_sz(uint8_t min_write_sz)
+{
+    return sizeof boot_img_magic            +
+           boot_status_sz(min_write_sz)     +
+           min_write_sz * 2;
+}
+
+static uint32_t
+boot_magic_off(const struct flash_area *fap)
+{
+    uint32_t off_from_end;
+    uint8_t elem_sz;
+
+    elem_sz = flash_area_align(fap);
+
+    off_from_end = boot_trailer_sz(elem_sz);
+
+    assert(off_from_end <= fap->fa_size);
+    return fap->fa_size - off_from_end;
+}
+
+uint32_t
+boot_status_off(const struct flash_area *fap)
+{
+    return boot_magic_off(fap) + sizeof boot_img_magic;
+}
+
+static uint32_t
+boot_copy_done_off(const struct flash_area *fap)
+{
+    return fap->fa_size - flash_area_align(fap) * 2;
+}
+
+static uint32_t
+boot_image_ok_off(const struct flash_area *fap)
+{
+    return fap->fa_size - flash_area_align(fap);
+}
+
+int
+boot_read_swap_state(const struct flash_area *fap,
+                     struct boot_swap_state *state)
+{
+    uint32_t magic[4];
+    uint32_t off;
+    int rc;
+
+    off = boot_magic_off(fap);
+    rc = flash_area_read(fap, off, magic, sizeof magic);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+    state->magic = boot_magic_code(magic);
+
+    off = boot_copy_done_off(fap);
+    rc = flash_area_read(fap, off, &state->copy_done, 1);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    off = boot_image_ok_off(fap);
+    rc = flash_area_read(fap, off, &state->image_ok, 1);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    return 0;
+}
+
+/**
+ * Reads the image trailer from the scratch area.
+ */
+int
+boot_read_swap_state_scratch(struct boot_swap_state *state)
+{
+    const struct flash_area *fap;
+    int rc;
+
+    rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH, &fap);
+    if (rc) {
+        rc = BOOT_EFLASH;
+        goto done;
+    }
+
+    rc = boot_read_swap_state(fap, state);
+    if (rc != 0) {
+        goto done;
+    }
+
+    rc = 0;
+
+done:
+    flash_area_close(fap);
+    return rc;
+}
+
+/**
+ * Reads the image trailer from a given image slot.
+ */
+int
+boot_read_swap_state_img(int slot, struct boot_swap_state *state)
+{
+    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 = boot_read_swap_state(fap, state);
+    if (rc != 0) {
+        goto done;
+    }
+
+    rc = 0;
+
+done:
+    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, sizeof boot_img_magic);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    return 0;
+}
+
+int
+boot_write_copy_done(const struct flash_area *fap)
+{
+    uint32_t off;
+    uint8_t val;
+    int rc;
+
+    off = boot_copy_done_off(fap);
+
+    val = 1;
+    rc = flash_area_write(fap, off, &val, 1);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    return 0;
+}
+
+int
+boot_write_image_ok(const struct flash_area *fap)
+{
+    uint32_t off;
+    uint8_t val;
+    int rc;
+
+    off = boot_image_ok_off(fap);
+
+    val = 1;
+    rc = flash_area_write(fap, off, &val, 1);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    return 0;
+}
+
+int
+boot_swap_type(void)
+{
+    const struct boot_swap_table *table;
+    struct boot_swap_state state_slot0;
+    struct boot_swap_state state_slot1;
+    int rc;
+    int i;
+
+    rc = boot_read_swap_state_img(0, &state_slot0);
+    assert(rc == 0);
+
+    rc = boot_read_swap_state_img(1, &state_slot1);
+    assert(rc == 0);
+
+    for (i = 0; i < BOOT_SWAP_TABLES_COUNT; i++) {
+        table = boot_swap_tables + i;
+
+        if ((table->bsw_magic_slot0     == 0    ||
+             table->bsw_magic_slot0     == state_slot0.magic)           &&
+            (table->bsw_magic_slot1     == 0    ||
+             table->bsw_magic_slot1     == state_slot1.magic)           &&
+            (table->bsw_image_ok_slot0  == 0    ||
+             table->bsw_image_ok_slot0  == state_slot0.image_ok)) {
+
+            return table->bsw_swap_type;
+        }
+    }
+
+    assert(0);
+    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.
+ *
+ * @return                  0 on success; nonzero on failure.
+ */
+int
+boot_set_pending(void)
+{
+    const struct flash_area *fap;
+    struct boot_swap_state state_slot1;
+    int area_id;
+    int rc;
+
+    rc = boot_read_swap_state_img(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:
+        area_id = flash_area_id_from_image_slot(1);
+        rc = flash_area_open(area_id, &fap);
+        if (rc != 0) {
+            rc = BOOT_EFLASH;
+        } else {
+            rc = boot_write_magic(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_img(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 == 0xff) {
+        /* Swap never completed.  This is unexpected. */
+        return BOOT_EBADVECT;
+    }
+
+    if (state_slot0.image_ok != 0xff) {
+        /* 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/bootutil/src/bootutil_priv.h b/bootutil/src/bootutil_priv.h
new file mode 100644
index 0000000..79885ae
--- /dev/null
+++ b/bootutil/src/bootutil_priv.h
@@ -0,0 +1,109 @@
+/*
+ * 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 "syscfg/syscfg.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 */
+};
+
+#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
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * ~                        MAGIC (16 octets)                      ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * ~                                                               ~
+ * ~                Swap status (variable, aligned)                ~
+ * ~                                                               ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * |   Copy done   |     0xff padding (up to min-write-sz - 1)     ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * |   Image OK    |     0xff padding (up to min-write-sz - 1)     ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ */
+
+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
+
+int bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen,
+    uint8_t key_id);
+
+uint32_t boot_trailer_sz(uint8_t min_write_sz);
+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_img(int slot, struct boot_swap_state *state);
+int boot_read_swap_state_scratch(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);
+
+uint32_t boot_status_sz(uint8_t min_write_sz);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/bootutil/src/image_ec.c b/bootutil/src/image_ec.c
new file mode 100644
index 0000000..6ddac59
--- /dev/null
+++ b/bootutil/src/image_ec.c
@@ -0,0 +1,121 @@
+/*
+ * 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 "syscfg/syscfg.h"
+
+#if MYNEWT_VAL(BOOTUTIL_SIGN_EC)
+#include "bootutil/sign_key.h"
+
+#include "mbedtls/sha256.h"
+#include "mbedtls/ecdsa.h"
+#include "mbedtls/oid.h"
+#include "mbedtls/asn1.h"
+
+#include "bootutil_priv.h"
+
+/*
+ * Declaring these like this adds NULL termination.
+ */
+static const uint8_t ec_pubkey_oid[] = MBEDTLS_OID_EC_ALG_UNRESTRICTED;
+static const uint8_t ec_secp224r1_oid[] = MBEDTLS_OID_EC_GRP_SECP224R1;
+
+/*
+ * Parse the public key used for signing. Simple RSA format.
+ */
+static int
+bootutil_parse_eckey(mbedtls_ecdsa_context *ctx, uint8_t **p, uint8_t *end)
+{
+    size_t len;
+    mbedtls_asn1_buf alg;
+    mbedtls_asn1_buf param;
+
+    if (mbedtls_asn1_get_tag(p, end, &len,
+        MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
+        return -1;
+    }
+    end = *p + len;
+
+    if (mbedtls_asn1_get_alg(p, end, &alg, &param)) {
+        return -2;
+    }
+    if (alg.len != sizeof(ec_pubkey_oid) - 1 ||
+      memcmp(alg.p, ec_pubkey_oid, sizeof(ec_pubkey_oid) - 1)) {
+        return -3;
+    }
+    if (param.len != sizeof(ec_secp224r1_oid) - 1||
+      memcmp(param.p, ec_secp224r1_oid, sizeof(ec_secp224r1_oid) - 1)) {
+        return -4;
+    }
+
+    if (mbedtls_ecp_group_load_secp224r1(&ctx->grp)) {
+        return -5;
+    }
+
+    if (mbedtls_asn1_get_bitstring_null(p, end, &len)) {
+        return -6;
+    }
+    if (*p + len != end) {
+        return -7;
+    }
+
+    if (mbedtls_ecp_point_read_binary(&ctx->grp, &ctx->Q, *p, end - *p)) {
+        return -8;
+    }
+
+    if (mbedtls_ecp_check_pubkey(&ctx->grp, &ctx->Q)) {
+        return -9;
+    }
+    return 0;
+}
+
+static int
+bootutil_cmp_sig(mbedtls_ecdsa_context *ctx, uint8_t *hash, uint32_t hlen,
+  uint8_t *sig, int slen)
+{
+    return mbedtls_ecdsa_read_signature(ctx, hash, hlen, sig, slen);
+}
+
+int
+bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen,
+  uint8_t key_id)
+{
+    int rc;
+    uint8_t *cp;
+    uint8_t *end;
+    mbedtls_ecdsa_context ctx;
+
+    mbedtls_ecdsa_init(&ctx);
+
+    cp = (uint8_t *)bootutil_keys[key_id].key;
+    end = cp + *bootutil_keys[key_id].len;
+
+    rc = bootutil_parse_eckey(&ctx, &cp, end);
+    if (rc) {
+        return -1;
+    }
+
+    while (sig[slen - 1] == '\0') {
+        slen--;
+    }
+    rc = bootutil_cmp_sig(&ctx, hash, hlen, sig, slen);
+    mbedtls_ecdsa_free(&ctx);
+
+    return rc;
+}
+#endif /* MYNEWT_VAL(BOOTUTIL_SIGN_EC) */
diff --git a/bootutil/src/image_rsa.c b/bootutil/src/image_rsa.c
new file mode 100644
index 0000000..7b1f4d4
--- /dev/null
+++ b/bootutil/src/image_rsa.c
@@ -0,0 +1,144 @@
+/*
+ * 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 "syscfg/syscfg.h"
+
+#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA)
+#include "bootutil/sign_key.h"
+
+#include "mbedtls/rsa.h"
+#include "mbedtls/asn1.h"
+
+#include "bootutil_priv.h"
+
+static const uint8_t sha256_oid[] = {
+    0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
+    0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
+    0x00, 0x04, 0x20
+};
+
+/*
+ * 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;
+}
+
+/*
+ * PKCS1.5 using RSA2048 computed over SHA256.
+ */
+static int
+bootutil_cmp_rsasig(mbedtls_rsa_context *ctx, uint8_t *hash, uint32_t hlen,
+  uint8_t *sig)
+{
+    uint8_t buf[MBEDTLS_MPI_MAX_SIZE];
+    uint8_t *p;
+
+    if (ctx->len != 256) {
+        return -1;
+    }
+
+    if (mbedtls_rsa_public(ctx, sig, buf)) {
+        return -1;
+    }
+
+    p = buf;
+
+    if (*p++ != 0 || *p++ != MBEDTLS_RSA_SIGN) {
+        return -1;
+    }
+
+    while (*p != 0) {
+        if (p >= buf + ctx->len - 1 || *p != 0xFF) {
+            return -1;
+        }
+        p++;
+    }
+    p++;
+
+    if ((p - buf) + sizeof(sha256_oid) + hlen != ctx->len) {
+        return -1;
+    }
+
+    if (memcmp(p, sha256_oid, sizeof(sha256_oid))) {
+        return -1;
+    }
+    p += sizeof(sha256_oid);
+
+    if (memcmp(p, hash, hlen)) {
+        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 /* MYNEWT_VAL(BOOTUTIL_SIGN_RSA) */
diff --git a/bootutil/src/image_validate.c b/bootutil/src/image_validate.c
new file mode 100644
index 0000000..98fdc9b
--- /dev/null
+++ b/bootutil/src/image_validate.c
@@ -0,0 +1,200 @@
+/*
+ * 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 "syscfg/syscfg.h"
+#include "hal/hal_flash.h"
+#include "flash_map/flash_map.h"
+#include "bootutil/image.h"
+#include "bootutil/sign_key.h"
+
+#include "mbedtls/sha256.h"
+#include "mbedtls/rsa.h"
+#include "mbedtls/ecdsa.h"
+#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)
+{
+    mbedtls_sha256_context sha256_ctx;
+    uint32_t blk_sz;
+    uint32_t size;
+    uint32_t off;
+    int rc;
+
+    mbedtls_sha256_init(&sha256_ctx);
+    mbedtls_sha256_starts(&sha256_ctx, 0);
+
+    /* in some cases (split image) the hash is seeded with data from
+     * the loader image */
+    if(seed && (seed_len > 0)) {
+        mbedtls_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;
+        }
+        mbedtls_sha256_update(&sha256_ctx, tmp_buf, blk_sz);
+    }
+    mbedtls_sha256_finish(&sha256_ctx, hash_result);
+
+    return 0;
+}
+
+/*
+ * 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 size;
+    uint32_t sha_off = 0;
+#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA) || MYNEWT_VAL(BOOTUTIL_SIGN_EC)
+    uint32_t sig_off = 0;
+    uint32_t sig_len = 0;
+#endif
+    struct image_tlv tlv;
+    uint8_t buf[256];
+    uint8_t hash[32];
+    int rc;
+
+#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA)
+    if ((hdr->ih_flags & IMAGE_F_PKCS15_RSA2048_SHA256) == 0) {
+        return -1;
+    }
+#endif
+#if MYNEWT_VAL(BOOTUTIL_SIGN_EC)
+    if ((hdr->ih_flags & IMAGE_F_ECDSA224_SHA256) == 0) {
+        return -1;
+    }
+#endif
+    if ((hdr->ih_flags & IMAGE_F_SHA256) == 0) {
+        return -1;
+    }
+
+    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);
+    }
+
+    /* After image there are TLVs. */
+    off = hdr->ih_img_size + hdr->ih_hdr_size;
+    size = off + hdr->ih_tlv_size;
+
+    for (; off < size; 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) {
+            if (tlv.it_len != sizeof(hash)) {
+                return -1;
+            }
+            sha_off = off + sizeof(tlv);
+        }
+#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA)
+        if (tlv.it_type == IMAGE_TLV_RSA2048) {
+            if (tlv.it_len != 256) { /* 2048 bits */
+                return -1;
+            }
+            sig_off = off + sizeof(tlv);
+            sig_len = tlv.it_len;
+        }
+#endif
+#if MYNEWT_VAL(BOOTUTIL_SIGN_EC)
+        if (tlv.it_type == IMAGE_TLV_ECDSA224) {
+            if (tlv.it_len < 64) { /* oids + 2 * 28 bytes */
+                return -1;
+            }
+            sig_off = off + sizeof(tlv);
+            sig_len = tlv.it_len;
+        }
+#endif
+    }
+    if (hdr->ih_flags & IMAGE_F_SHA256) {
+        if (!sha_off) {
+            /*
+             * Header said there should be hash TLV, no TLV found.
+             */
+            return -1;
+        }
+        rc = flash_area_read(fap, sha_off, buf, sizeof hash);
+        if (rc) {
+            return rc;
+        }
+        if (memcmp(hash, buf, sizeof(hash))) {
+            return -1;
+        }
+    }
+#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA) || MYNEWT_VAL(BOOTUTIL_SIGN_EC)
+    if (!sig_off) {
+        /*
+         * Header said there should be PKCS1.v5 signature, no TLV
+         * found.
+         */
+        return -1;
+    }
+    rc = flash_area_read(fap, sig_off, buf, sig_len);
+    if (rc) {
+        return -1;
+    }
+
+    if (hdr->ih_key_id >= bootutil_key_cnt) {
+        return -1;
+    }
+    rc = bootutil_verify_sig(hash, sizeof(hash), buf, sig_len, hdr->ih_key_id);
+    if (rc) {
+        return -1;
+    }
+#endif
+    return 0;
+}
diff --git a/bootutil/src/loader.c b/bootutil/src/loader.c
new file mode 100644
index 0000000..4d17291
--- /dev/null
+++ b/bootutil/src/loader.c
@@ -0,0 +1,1100 @@
+/*
+ * 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 <inttypes.h>
+#include <stdlib.h>
+#include <string.h>
+#include "sysflash/sysflash.h"
+#include "flash_map/flash_map.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_MAX_IMG_SECTORS        120
+
+/** Number of image slots in flash; currently limited to two. */
+#define BOOT_NUM_SLOTS              2
+
+static struct {
+    struct {
+        struct image_header hdr;
+        struct flash_area *sectors;
+    } imgs[BOOT_NUM_SLOTS];
+
+    int num_img_sectors;
+    struct flash_area scratch_sector;
+
+    uint8_t write_sz;
+} 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])
+
+/**
+ * This table indicates the next swap type that should be performed.  The first
+ * column contains the current swap type.  The second column contains the swap
+ * type that should be effected after the first completes.
+ */
+static const uint8_t boot_swap_trans_table[][2] = {
+    /*     From                     To             */
+    { BOOT_SWAP_TYPE_REVERT,    BOOT_SWAP_TYPE_NONE },
+    { BOOT_SWAP_TYPE_TEST,      BOOT_SWAP_TYPE_REVERT },
+};
+
+#define BOOT_SWAP_TRANS_TABLE_SIZE   \
+    (sizeof boot_swap_trans_table / sizeof boot_swap_trans_table[0])
+
+/**
+ * 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;
+    struct boot_swap_state state_slot1;
+    int rc;
+    int i;
+
+    rc = boot_read_swap_state_img(0, &state_slot0);
+    assert(rc == 0);
+
+    rc = boot_read_swap_state_img(1, &state_slot1);
+    assert(rc == 0);
+
+    rc = boot_read_swap_state_scratch(&state_scratch);
+    assert(rc == 0);
+
+    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)) {
+
+            return table->bst_status_source;
+        }
+    }
+
+    return BOOT_STATUS_SOURCE_NONE;
+}
+
+/**
+ * Calculates the type of swap that just completed.
+ */
+static int
+boot_previous_swap_type(void)
+{
+    int post_swap_type;
+    int i;
+
+    post_swap_type = boot_swap_type();
+
+    for (i = 0; i < BOOT_SWAP_TRANS_TABLE_SIZE; i++){
+        if (boot_swap_trans_table[i][1] == post_swap_type) {
+            return boot_swap_trans_table[i][0];
+        }
+    }
+    
+    /* XXX: Temporary assert. */
+    assert(0);
+
+    return BOOT_SWAP_TYPE_REVERT;
+}
+
+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_data.imgs[i].hdr);
+        if (rc != 0) {
+            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_data.imgs[0].sectors[0].fa_device_id);
+    align = hal_flash_align(boot_data.scratch_sector.fa_device_id);
+    if (align > elem_sz) {
+        elem_sz = align;
+    }
+
+    return elem_sz;
+}
+
+/**
+ * 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)
+{
+    const struct flash_area *sector0;
+    const struct flash_area *sector1;
+    const struct flash_area *scratch;
+    int num_sectors_slot0;
+    int num_sectors_slot1;
+    int rc;
+    int i;
+
+    num_sectors_slot0 = BOOT_MAX_IMG_SECTORS;
+    rc = flash_area_to_sectors(FLASH_AREA_IMAGE_0, &num_sectors_slot0,
+                               boot_data.imgs[0].sectors);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    num_sectors_slot1 = BOOT_MAX_IMG_SECTORS;
+    rc = flash_area_to_sectors(FLASH_AREA_IMAGE_1, &num_sectors_slot1,
+                               boot_data.imgs[1].sectors);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH, &scratch);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+    boot_data.scratch_sector = *scratch;
+    boot_data.write_sz = hal_flash_align(scratch->fa_device_id);
+
+    /* Ensure both image slots have identical sector layouts. */
+    if (num_sectors_slot0 != num_sectors_slot1) {
+        return BOOT_EFLASH;
+    }
+    for (i = 0; i < num_sectors_slot0; i++) {
+        sector0 = boot_data.imgs[0].sectors + i;
+        sector1 = boot_data.imgs[1].sectors + i;
+        if (sector0->fa_size != sector1->fa_size) {
+            return BOOT_EFLASH;
+        }
+    }
+
+    boot_data.num_img_sectors = num_sectors_slot0;
+
+    boot_data.write_sz = 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 found;
+    int rc;
+    int i;
+
+    off = boot_status_off(fap);
+
+    found = 0;
+    for (i = 0; i < BOOT_STATUS_MAX_ENTRIES; i++) {
+        rc = flash_area_read(fap, off + i * boot_data.write_sz, &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);
+    if (rc != 0) {
+        return rc;
+    }
+
+    return 0;
+}
+
+/**
+ * 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;
+
+    if (bs->idx == 0) {
+        /* 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_data.write_sz);
+
+    rc = flash_area_write(fap, off, &bs->state, 1);
+    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 void *tmpbuf;
+
+    if (!tmpbuf) {
+        tmpbuf = malloc(BOOT_TMPBUF_SZ);
+        if (!tmpbuf) {
+            return BOOT_ENOMEM;
+        }
+    }
+    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_slot1(void)
+{
+    const struct flash_area *fap;
+    int rc;
+    
+    if (boot_data.imgs[1].hdr.ih_magic == 0xffffffff ||
+        boot_data.imgs[1].hdr.ih_flags & IMAGE_F_NON_BOOTABLE) {
+
+        /* No bootable image in slot 1; continue booting from slot 0. */
+        return -1;
+    }
+
+    /* Image in slot 1 is invalid.  Erase the image and continue booting
+     * from slot 0.
+     */
+    rc = flash_area_open(FLASH_AREA_IMAGE_1, &fap);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    if (boot_data.imgs[1].hdr.ih_magic != IMAGE_MAGIC ||
+        boot_image_check(&boot_data.imgs[1].hdr, fap) != 0) {
+
+        /* Image in slot 1 is invalid.  Erase the image and continue booting
+         * from slot 0.
+         */
+        flash_area_erase(fap, 0, fap->fa_size);
+        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;
+    int rc;
+
+    swap_type = boot_swap_type();
+    if (swap_type == BOOT_SWAP_TYPE_NONE) {
+        /* Continue using slot 0. */
+        return BOOT_SWAP_TYPE_NONE;
+    }
+
+    /* Boot loader wants to switch to slot 1.  Ensure image is valid. */
+    rc = boot_validate_slot1();
+    if (rc != 0) {
+        return 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.
+ */
+static uint32_t
+boot_copy_sz(int last_sector_idx, int *out_first_sector_idx)
+{
+    uint32_t new_sz;
+    uint32_t sz;
+    int i;
+
+    sz = 0;
+
+    for (i = last_sector_idx; i >= 0; i--) {
+        new_sz = sz + boot_data.imgs[0].sectors[i].fa_size;
+        if (new_sz > boot_data.scratch_sector.fa_size) {
+            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;
+}
+
+/**
+ * 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:
+    flash_area_close(fap_src);
+    flash_area_close(fap_dst);
+    return rc;
+}
+
+/**
+ * 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.
+ */
+static int
+boot_swap_sectors(int idx, uint32_t sz, struct boot_status *bs)
+{
+    uint32_t copy_sz;
+    uint32_t img_off;
+    int rc;
+
+    /* Calculate offset from start of image area. */
+    img_off = boot_data.imgs[0].sectors[idx].fa_off -
+              boot_data.imgs[0].sectors[0].fa_off;
+
+    if (bs->state == 0) {
+        rc = boot_erase_sector(FLASH_AREA_IMAGE_SCRATCH, 0, sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        rc = boot_copy_sector(FLASH_AREA_IMAGE_1, FLASH_AREA_IMAGE_SCRATCH,
+                              img_off, 0, sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        bs->state = 1;
+        (void)boot_write_status(bs);
+    }
+    if (bs->state == 1) {
+        rc = boot_erase_sector(FLASH_AREA_IMAGE_1, img_off, sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        copy_sz = sz;
+        if (boot_data.imgs[0].sectors[idx].fa_off + sz >=
+            boot_data.imgs[1].sectors[0].fa_off) {
+
+            /* This is the end of the area.  Don't copy the image state into
+             * slot 1.
+             */
+            copy_sz -= boot_trailer_sz(boot_data.write_sz);
+        }
+
+        rc = boot_copy_sector(FLASH_AREA_IMAGE_0, FLASH_AREA_IMAGE_1,
+                              img_off, img_off, copy_sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        bs->state = 2;
+        (void)boot_write_status(bs);
+    }
+    if (bs->state == 2) {
+        rc = boot_erase_sector(FLASH_AREA_IMAGE_0, img_off, sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        rc = boot_copy_sector(FLASH_AREA_IMAGE_SCRATCH, FLASH_AREA_IMAGE_0,
+                              0, img_off, sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        bs->idx++;
+        bs->state = 0;
+        (void)boot_write_status(bs);
+    }
+
+    return 0;
+}
+
+/**
+ * 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.
+ */
+static int
+boot_copy_image(struct boot_status *bs)
+{
+    uint32_t sz;
+    int first_sector_idx;
+    int last_sector_idx;
+    int swap_idx;
+
+    swap_idx = 0;
+    last_sector_idx = boot_data.num_img_sectors - 1;
+    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;
+}
+
+/**
+ * Marks a test image in slot 0 as fully copied.
+ */
+static int
+boot_finalize_test_swap(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);
+    if (rc != 0) {
+        return rc;
+    }
+
+    return 0;
+}
+
+/**
+ * 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.
+ */
+static int
+boot_finalize_revert_swap(void)
+{
+    const struct flash_area *fap;
+    struct boot_swap_state state_slot0;
+    int rc;
+
+    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    rc = boot_read_swap_state(fap, &state_slot0);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    if (state_slot0.magic == BOOT_MAGIC_UNSET) {
+        rc = boot_write_magic(fap);
+        if (rc != 0) {
+            return rc;
+        }
+    }
+
+    if (state_slot0.copy_done == 0xff) {
+        rc = boot_write_copy_done(fap);
+        if (rc != 0) {
+            return rc;
+        }
+    }
+
+    if (state_slot0.image_ok == 0xff) {
+        rc = boot_write_image_ok(fap);
+        if (rc != 0) {
+            return rc;
+        }
+    }
+
+    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)
+{
+    struct boot_status bs;
+    int swap_type;
+    int slot;
+    int rc;
+
+    /* 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 for some reason.
+     */
+    static struct flash_area slot0_sectors[BOOT_MAX_IMG_SECTORS];
+    static struct flash_area slot1_sectors[BOOT_MAX_IMG_SECTORS];
+    boot_data.imgs[0].sectors = slot0_sectors;
+    boot_data.imgs[1].sectors = slot1_sectors;
+
+    /* Determine the sector layout of the image slots and scratch area. */
+    rc = boot_read_sectors();
+    if (rc != 0) {
+        return rc;
+    }
+
+    /* Attempt to read an image header from each slot. */
+    rc = boot_read_image_headers();
+    if (rc != 0) {
+        return rc;
+    }
+
+    /* Determine if we rebooted in the middle of an image swap operation. */
+    rc = boot_read_status(&bs);
+    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);
+
+        /* 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_REVERT:
+            rc = boot_copy_image(&bs);
+            assert(rc == 0);
+            break;
+        }
+    }
+
+    switch (swap_type) {
+    case BOOT_SWAP_TYPE_NONE:
+        slot = 0;
+        break;
+
+    case BOOT_SWAP_TYPE_TEST:
+        slot = 1;
+        boot_finalize_test_swap();
+        break;
+
+    case BOOT_SWAP_TYPE_REVERT:
+        slot = 1;
+        boot_finalize_revert_swap();
+        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;
+        boot_finalize_revert_swap();
+        break;
+
+    default:
+        assert(0);
+        slot = 0;
+        break;
+    }
+
+    /* Always boot from the primary slot. */
+    rsp->br_flash_id = boot_data.imgs[0].sectors[0].fa_device_id;
+    rsp->br_image_addr = boot_data.imgs[0].sectors[0].fa_off;
+    rsp->br_hdr = &boot_data.imgs[slot].hdr;
+
+    return 0;
+}
+
+int
+split_go(int loader_slot, int split_slot, void **entry)
+{
+    const struct flash_area *loader_fap;
+    const struct flash_area *app_fap;
+    struct flash_area *sectors;
+    uint32_t entry_val;
+    int loader_flash_id;
+    int app_flash_id;
+    int rc;
+
+    app_fap = NULL;
+    loader_fap = NULL;
+
+    sectors = malloc(BOOT_MAX_IMG_SECTORS * 2 * sizeof *sectors);
+    if (sectors == NULL) {
+        rc = SPLIT_GO_ERR;
+        goto done;
+    }
+    boot_data.imgs[0].sectors = sectors + 0;
+    boot_data.imgs[1].sectors = sectors + BOOT_MAX_IMG_SECTORS;
+
+    /* 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;
+    }
+
+    app_flash_id = flash_area_id_from_image_slot(split_slot);
+    rc = flash_area_open(app_flash_id, &app_fap);
+    if (rc != 0) {
+        rc = BOOT_EFLASH;
+        goto done;
+    }
+
+    loader_flash_id = flash_area_id_from_image_slot(loader_slot);
+    rc = flash_area_open(loader_flash_id, &loader_fap);
+    if (rc != 0) {
+        rc = BOOT_EFLASH;
+        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_data.imgs[split_slot].hdr,
+                           app_fap,
+                           &boot_data.imgs[loader_slot].hdr,
+                           loader_fap);
+    if (rc != 0) {
+        rc = SPLIT_GO_NON_MATCHING;
+        goto done;
+    }
+
+    entry_val = boot_data.imgs[split_slot].sectors[0].fa_off +
+                boot_data.imgs[split_slot].hdr.ih_hdr_size;
+    *entry = (void*) entry_val;
+    rc = SPLIT_GO_OK;
+
+done:
+    free(sectors);
+    flash_area_close(app_fap);
+    flash_area_close(loader_fap);
+    return rc;
+}