Simvik

Is this image safe to jump to?

Check a firmware image's header, bounds, CRC and vector table before a bootloader starts it. A hard embedded C problem (OTA updates and rollback), run and…

hard · OTA updates and rollback · bootloader · ota · crc · vector-table · robustness

Before a bootloader jumps into an application, it must be sure the image is complete, intact and built for this slot. Jumping into a half-written image is a brick. Write image_check(slot, slot_base, slot_size). slot points at the slot's bytes, which start at address slot_base on the chip.

Read the header from the start of the slot (use memcpy, since slot need not be aligned). Make these checks in this order and return the first that fails:

  1. magic is IMG_MAGIC, or IMG_BAD_MAGIC.
  2. length is at least 8, a multiple of 4, and the header plus the image fit in the slot, or IMG_BAD_LENGTH. Check this before reading any image bytes, and beware of HDR_SIZE + length overflowing.
  3. load_addr is slot_base + HDR_SIZE, where the image actually sits, or IMG_BAD_ADDR.
  4. crc32 of the length image bytes equals img_crc, or IMG_BAD_CRC.
  5. The image starts with its vector table. Word 0 is the initial stack pointer: it must be above RAM_START, at most RAM_END, and a multiple of 8, or IMG_BAD_SP.
  6. Word 1 is the reset handler's address: bit 0 must be set (Thumb), and the address without bit 0 must be inside the image, after the two vector words (from load_addr + 8 up to load_addr + length, exclusive), or IMG_BAD_RESET.

Otherwise return IMG_OK.

Starter code

int image_check(const uint8_t *slot, uint32_t slot_base, uint32_t slot_size) {
  img_hdr_t h;
  memcpy(&h, slot, sizeof h);
  if (h.magic != IMG_MAGIC) return IMG_BAD_MAGIC;
  if (crc32(slot + HDR_SIZE, h.length) != h.img_crc) return IMG_BAD_CRC;
  return IMG_OK;
}

Example tests

A good image, then one flipped byte

build(64, RAM_END, BASE + HDR_SIZE + 0x21);
check("good");
slot[HDR_SIZE + 40] ^= 0x01;
check("flipped");

Expected output:

good: ok
flipped: bad crc

A bad vector table

build(64, RAM_END, BASE + HDR_SIZE + 0x20);
check("arm-mode reset");
build(64, 0x30000000u, BASE + HDR_SIZE + 0x21);
check("sp outside ram");

Expected output:

arm-mode reset: bad reset
sp outside ram: bad sp

Learn it first

More OTA updates and rollback problems