image_check.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * @file image_check.c
  3. * @brief 升级包镜像校验(Header 字段链 + NOR 裸镜像 CRC32)
  4. */
  5. #include "image_check.h"
  6. #include "Int_flash.h"
  7. #include "boot_crc.h"
  8. #include "boot_layout.h"
  9. #include <string.h>
  10. #define IC_CHUNK 4096U
  11. static uint8_t s_chunk[IC_CHUNK] __attribute__((aligned(32)));
  12. uint32_t ic_read_staging(uint32_t off, uint8_t *out, uint32_t len)
  13. {
  14. return (Int_flash_read(out, NOR_IMG_STAGING_ADDR + off, len) == 0) ? 0 : 1;
  15. }
  16. boot_err_t image_check(fw_image_header_t *hdr, uint32_t running_ver, uint8_t allow_downgrade_dev)
  17. {
  18. uint32_t crc;
  19. uint32_t done;
  20. /* ① 读 64B Header */
  21. if (Int_flash_read((uint8_t *)hdr, NOR_IMG_STAGING_ADDR, sizeof(*hdr)) != 0)
  22. return BOOT_ERR_NOR_READ;
  23. /* ② 字段链 */
  24. if (hdr->magic != FW_HDR_MAGIC) return BOOT_ERR_HDR_MAGIC;
  25. if (hdr->header_ver != FW_HDR_VERSION) return BOOT_ERR_HDR_VERSION;
  26. if (hdr->product_id != PRODUCT_ID) return BOOT_ERR_PRODUCT_MISMATCH;
  27. if (hdr->hw_version != HW_VERSION) return BOOT_ERR_HW_MISMATCH;
  28. if (hdr->entry != FW_ENTRY_APP_ADDR) return BOOT_ERR_HDR_MAGIC;
  29. /* ③ Header CRC */
  30. crc = boot_crc32((const uint8_t *)hdr, 0x2CU);
  31. if (crc != hdr->header_crc32) return BOOT_ERR_HDR_CRC;
  32. /* ④ size 合法性 */
  33. if (hdr->image_size == 0U || hdr->image_size > APP_SIZE_MAX)
  34. return BOOT_ERR_SIZE_ERROR;
  35. if ((uint64_t)hdr->image_size + sizeof(*hdr) > NOR_IMG_STAGING_SIZE)
  36. return BOOT_ERR_SIZE_ERROR;
  37. /* ⑤ 版本策略: 默认禁止降级 */
  38. if (!allow_downgrade_dev && !(hdr->flags & FW_FLAG_ALLOW_DOWNGRADE))
  39. {
  40. if (running_ver != 0U && hdr->app_version < running_ver)
  41. return BOOT_ERR_VERSION_DENIED;
  42. }
  43. /* ⑥ 整镜像 CRC32(从 NOR 流式) */
  44. crc = boot_crc32_init();
  45. done = 0;
  46. while (done < hdr->image_size)
  47. {
  48. uint32_t n = hdr->image_size - done;
  49. if (n > IC_CHUNK) n = IC_CHUNK;
  50. if (Int_flash_read(s_chunk, NOR_IMG_STAGING_ADDR + sizeof(*hdr) + done, n) != 0)
  51. return BOOT_ERR_NOR_READ;
  52. crc = boot_crc32_update(crc, s_chunk, n);
  53. done += n;
  54. }
  55. if (boot_crc32_finish(crc) != hdr->image_crc32)
  56. return BOOT_ERR_IMAGE_CRC;
  57. return BOOT_ERR_NONE;
  58. }