bootloader_utility.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. /*
  2. * SPDX-FileCopyrightText: 2018-2023 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <string.h>
  7. #include <stdint.h>
  8. #include <limits.h>
  9. #include <sys/param.h>
  10. #include "esp_attr.h"
  11. #include "esp_log.h"
  12. #include "esp_rom_sys.h"
  13. #include "esp_rom_uart.h"
  14. #include "sdkconfig.h"
  15. #if CONFIG_IDF_TARGET_ESP32
  16. #include "soc/dport_reg.h"
  17. #include "esp32/rom/cache.h"
  18. #include "esp32/rom/secure_boot.h"
  19. #elif CONFIG_IDF_TARGET_ESP32S2
  20. #include "esp32s2/rom/secure_boot.h"
  21. #elif CONFIG_IDF_TARGET_ESP32S3
  22. #include "esp32s3/rom/secure_boot.h"
  23. #elif CONFIG_IDF_TARGET_ESP32C3
  24. #include "esp32c3/rom/efuse.h"
  25. #include "esp32c3/rom/crc.h"
  26. #include "esp32c3/rom/uart.h"
  27. #include "esp32c3/rom/gpio.h"
  28. #include "esp32c3/rom/secure_boot.h"
  29. #elif CONFIG_IDF_TARGET_ESP32C2
  30. #include "esp32c2/rom/efuse.h"
  31. #include "esp32c2/rom/crc.h"
  32. #include "esp32c2/rom/rtc.h"
  33. #include "esp32c2/rom/uart.h"
  34. #include "esp32c2/rom/gpio.h"
  35. #include "esp32c2/rom/secure_boot.h"
  36. #elif CONFIG_IDF_TARGET_ESP32C6
  37. #include "esp32c6/rom/efuse.h"
  38. #include "esp32c6/rom/crc.h"
  39. #include "esp32c6/rom/rtc.h"
  40. #include "esp32c6/rom/uart.h"
  41. #include "esp32c6/rom/gpio.h"
  42. #include "esp32c6/rom/secure_boot.h"
  43. #elif CONFIG_IDF_TARGET_ESP32H2
  44. #include "esp32h2/rom/efuse.h"
  45. #include "esp32h2/rom/crc.h"
  46. #include "esp32h2/rom/rtc.h"
  47. #include "esp32h2/rom/uart.h"
  48. #include "esp32h2/rom/gpio.h"
  49. #include "esp32h2/rom/secure_boot.h"
  50. #else // CONFIG_IDF_TARGET_*
  51. #error "Unsupported IDF_TARGET"
  52. #endif
  53. #include "esp_rom_spiflash.h"
  54. #include "soc/soc.h"
  55. #include "soc/rtc.h"
  56. #include "soc/gpio_periph.h"
  57. #include "soc/efuse_periph.h"
  58. #include "soc/rtc_periph.h"
  59. #include "soc/timer_periph.h"
  60. #include "hal/mmu_hal.h"
  61. #include "hal/cache_types.h"
  62. #include "hal/cache_ll.h"
  63. #include "hal/cache_hal.h"
  64. #include "esp_cpu.h"
  65. #include "esp_image_format.h"
  66. #include "esp_app_desc.h"
  67. #include "esp_secure_boot.h"
  68. #include "esp_flash_encrypt.h"
  69. #include "esp_flash_partitions.h"
  70. #include "bootloader_flash_priv.h"
  71. #include "bootloader_random.h"
  72. #include "bootloader_config.h"
  73. #include "bootloader_common.h"
  74. #include "bootloader_utility.h"
  75. #include "bootloader_sha.h"
  76. #include "bootloader_console.h"
  77. #include "bootloader_soc.h"
  78. #include "esp_efuse.h"
  79. #include "esp_fault.h"
  80. static const char *TAG = "boot";
  81. /* Reduce literal size for some generic string literals */
  82. #define MAP_ERR_MSG "Image contains multiple %s segments. Only the last one will be mapped."
  83. static bool ota_has_initial_contents;
  84. static void load_image(const esp_image_metadata_t *image_data);
  85. static void unpack_load_app(const esp_image_metadata_t *data);
  86. static void set_cache_and_start_app(uint32_t drom_addr,
  87. uint32_t drom_load_addr,
  88. uint32_t drom_size,
  89. uint32_t irom_addr,
  90. uint32_t irom_load_addr,
  91. uint32_t irom_size,
  92. uint32_t entry_addr);
  93. esp_err_t bootloader_common_read_otadata(const esp_partition_pos_t *ota_info, esp_ota_select_entry_t *two_otadata)
  94. {
  95. const esp_ota_select_entry_t *ota_select_map;
  96. if (ota_info->offset == 0) {
  97. return ESP_ERR_NOT_FOUND;
  98. }
  99. // partition table has OTA data partition
  100. if (ota_info->size < 2 * SPI_SEC_SIZE) {
  101. ESP_LOGE(TAG, "ota_info partition size %"PRIu32" is too small (minimum %d bytes)", ota_info->size, (2 * SPI_SEC_SIZE));
  102. return ESP_FAIL; // can't proceed
  103. }
  104. ESP_LOGD(TAG, "OTA data offset 0x%"PRIx32, ota_info->offset);
  105. ota_select_map = bootloader_mmap(ota_info->offset, ota_info->size);
  106. if (!ota_select_map) {
  107. ESP_LOGE(TAG, "bootloader_mmap(0x%"PRIx32", 0x%"PRIx32") failed", ota_info->offset, ota_info->size);
  108. return ESP_FAIL; // can't proceed
  109. }
  110. memcpy(&two_otadata[0], ota_select_map, sizeof(esp_ota_select_entry_t));
  111. memcpy(&two_otadata[1], (uint8_t *)ota_select_map + SPI_SEC_SIZE, sizeof(esp_ota_select_entry_t));
  112. bootloader_munmap(ota_select_map);
  113. return ESP_OK;
  114. }
  115. esp_err_t bootloader_common_get_partition_description(const esp_partition_pos_t *partition, esp_app_desc_t *app_desc)
  116. {
  117. if (partition == NULL || app_desc == NULL || partition->offset == 0) {
  118. return ESP_ERR_INVALID_ARG;
  119. }
  120. const uint32_t app_desc_offset = sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t);
  121. const uint32_t mmap_size = app_desc_offset + sizeof(esp_app_desc_t);
  122. const uint8_t *image = bootloader_mmap(partition->offset, mmap_size);
  123. if (image == NULL) {
  124. ESP_LOGE(TAG, "bootloader_mmap(0x%"PRIx32", 0x%"PRIx32") failed", partition->offset, mmap_size);
  125. return ESP_FAIL;
  126. }
  127. memcpy(app_desc, image + app_desc_offset, sizeof(esp_app_desc_t));
  128. bootloader_munmap(image);
  129. if (app_desc->magic_word != ESP_APP_DESC_MAGIC_WORD) {
  130. return ESP_ERR_NOT_FOUND;
  131. }
  132. return ESP_OK;
  133. }
  134. bool bootloader_utility_load_partition_table(bootloader_state_t *bs)
  135. {
  136. const esp_partition_info_t *partitions;
  137. const char *partition_usage;
  138. esp_err_t err;
  139. int num_partitions;
  140. partitions = bootloader_mmap(ESP_PARTITION_TABLE_OFFSET, ESP_PARTITION_TABLE_MAX_LEN);
  141. if (!partitions) {
  142. ESP_LOGE(TAG, "bootloader_mmap(0x%x, 0x%x) failed", ESP_PARTITION_TABLE_OFFSET, ESP_PARTITION_TABLE_MAX_LEN);
  143. return false;
  144. }
  145. ESP_LOGD(TAG, "mapped partition table 0x%x at 0x%x", ESP_PARTITION_TABLE_OFFSET, (intptr_t)partitions);
  146. err = esp_partition_table_verify(partitions, true, &num_partitions);
  147. if (err != ESP_OK) {
  148. ESP_LOGE(TAG, "Failed to verify partition table");
  149. return false;
  150. }
  151. ESP_LOGI(TAG, "Partition Table:");
  152. ESP_LOGI(TAG, "## Label Usage Type ST Offset Length");
  153. for (int i = 0; i < num_partitions; i++) {
  154. const esp_partition_info_t *partition = &partitions[i];
  155. ESP_LOGD(TAG, "load partition table entry 0x%x", (intptr_t)partition);
  156. ESP_LOGD(TAG, "type=%x subtype=%x", partition->type, partition->subtype);
  157. partition_usage = "unknown";
  158. /* valid partition table */
  159. switch (partition->type) {
  160. case PART_TYPE_APP: /* app partition */
  161. switch (partition->subtype) {
  162. case PART_SUBTYPE_FACTORY: /* factory binary */
  163. bs->factory = partition->pos;
  164. partition_usage = "factory app";
  165. break;
  166. case PART_SUBTYPE_TEST: /* test binary */
  167. bs->test = partition->pos;
  168. partition_usage = "test app";
  169. break;
  170. default:
  171. /* OTA binary */
  172. if ((partition->subtype & ~PART_SUBTYPE_OTA_MASK) == PART_SUBTYPE_OTA_FLAG) {
  173. bs->ota[partition->subtype & PART_SUBTYPE_OTA_MASK] = partition->pos;
  174. ++bs->app_count;
  175. partition_usage = "OTA app";
  176. } else {
  177. partition_usage = "Unknown app";
  178. }
  179. break;
  180. }
  181. break; /* PART_TYPE_APP */
  182. case PART_TYPE_DATA: /* data partition */
  183. switch (partition->subtype) {
  184. case PART_SUBTYPE_DATA_OTA: /* ota data */
  185. bs->ota_info = partition->pos;
  186. partition_usage = "OTA data";
  187. break;
  188. case PART_SUBTYPE_DATA_RF:
  189. partition_usage = "RF data";
  190. break;
  191. case PART_SUBTYPE_DATA_WIFI:
  192. partition_usage = "WiFi data";
  193. break;
  194. case PART_SUBTYPE_DATA_NVS_KEYS:
  195. partition_usage = "NVS keys";
  196. break;
  197. case PART_SUBTYPE_DATA_EFUSE_EM:
  198. partition_usage = "efuse";
  199. #ifdef CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH
  200. esp_efuse_init_virtual_mode_in_flash(partition->pos.offset, partition->pos.size);
  201. #endif
  202. break;
  203. default:
  204. partition_usage = "Unknown data";
  205. break;
  206. }
  207. break; /* PARTITION_USAGE_DATA */
  208. default: /* other partition type */
  209. break;
  210. }
  211. /* print partition type info */
  212. ESP_LOGI(TAG, "%2d %-16s %-16s %02x %02x %08"PRIx32" %08"PRIx32, i, partition->label, partition_usage,
  213. partition->type, partition->subtype,
  214. partition->pos.offset, partition->pos.size);
  215. }
  216. bootloader_munmap(partitions);
  217. ESP_LOGI(TAG, "End of partition table");
  218. return true;
  219. }
  220. /* Given a partition index, return the partition position data from the bootloader_state_t structure */
  221. static esp_partition_pos_t index_to_partition(const bootloader_state_t *bs, int index)
  222. {
  223. if (index == FACTORY_INDEX) {
  224. return bs->factory;
  225. }
  226. if (index == TEST_APP_INDEX) {
  227. return bs->test;
  228. }
  229. if (index >= 0 && index < MAX_OTA_SLOTS && index < (int)bs->app_count) {
  230. return bs->ota[index];
  231. }
  232. esp_partition_pos_t invalid = { 0 };
  233. return invalid;
  234. }
  235. static void log_invalid_app_partition(int index)
  236. {
  237. const char *not_bootable = " is not bootable"; /* save a few string literal bytes */
  238. switch (index) {
  239. case FACTORY_INDEX:
  240. ESP_LOGE(TAG, "Factory app partition%s", not_bootable);
  241. break;
  242. case TEST_APP_INDEX:
  243. ESP_LOGE(TAG, "Factory test app partition%s", not_bootable);
  244. break;
  245. default:
  246. ESP_LOGE(TAG, "OTA app partition slot %d%s", index, not_bootable);
  247. break;
  248. }
  249. }
  250. static esp_err_t write_otadata(esp_ota_select_entry_t *otadata, uint32_t offset, bool write_encrypted)
  251. {
  252. esp_err_t err = bootloader_flash_erase_sector(offset / FLASH_SECTOR_SIZE);
  253. if (err == ESP_OK) {
  254. err = bootloader_flash_write(offset, otadata, sizeof(esp_ota_select_entry_t), write_encrypted);
  255. }
  256. if (err != ESP_OK) {
  257. ESP_LOGE(TAG, "Error in write_otadata operation. err = 0x%x", err);
  258. }
  259. return err;
  260. }
  261. static bool check_anti_rollback(const esp_partition_pos_t *partition)
  262. {
  263. #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
  264. esp_app_desc_t app_desc = {};
  265. esp_err_t err = bootloader_common_get_partition_description(partition, &app_desc);
  266. if (err != ESP_OK) {
  267. ESP_LOGE(TAG, "Failed to get partition description %d", err);
  268. return false;
  269. }
  270. bool sec_ver = esp_efuse_check_secure_version(app_desc.secure_version);
  271. /* Anti FI check */
  272. ESP_FAULT_ASSERT(sec_ver == esp_efuse_check_secure_version(app_desc.secure_version));
  273. return sec_ver;
  274. #else
  275. return true;
  276. #endif
  277. }
  278. #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
  279. static void update_anti_rollback(const esp_partition_pos_t *partition)
  280. {
  281. esp_app_desc_t app_desc;
  282. esp_err_t err = bootloader_common_get_partition_description(partition, &app_desc);
  283. if (err == ESP_OK) {
  284. esp_efuse_update_secure_version(app_desc.secure_version);
  285. } else {
  286. ESP_LOGE(TAG, "Failed to get partition description %d", err);
  287. }
  288. }
  289. static int get_active_otadata_with_check_anti_rollback(const bootloader_state_t *bs, esp_ota_select_entry_t *two_otadata)
  290. {
  291. uint32_t ota_seq;
  292. uint32_t ota_slot;
  293. bool valid_otadata[2];
  294. valid_otadata[0] = bootloader_common_ota_select_valid(&two_otadata[0]);
  295. valid_otadata[1] = bootloader_common_ota_select_valid(&two_otadata[1]);
  296. bool sec_ver_valid_otadata[2] = { 0 };
  297. for (int i = 0; i < 2; ++i) {
  298. if (valid_otadata[i] == true) {
  299. ota_seq = two_otadata[i].ota_seq - 1; // Raw OTA sequence number. May be more than # of OTA slots
  300. ota_slot = ota_seq % bs->app_count; // Actual OTA partition selection
  301. if (check_anti_rollback(&bs->ota[ota_slot]) == false) {
  302. // invalid. This otadata[i] will not be selected as active.
  303. ESP_LOGD(TAG, "OTA slot %"PRIu32" has an app with secure_version, this version is smaller than in the device. This OTA slot will not be selected.", ota_slot);
  304. } else {
  305. sec_ver_valid_otadata[i] = true;
  306. }
  307. }
  308. }
  309. return bootloader_common_select_otadata(two_otadata, sec_ver_valid_otadata, true);
  310. }
  311. #endif
  312. int bootloader_utility_get_selected_boot_partition(const bootloader_state_t *bs)
  313. {
  314. esp_ota_select_entry_t otadata[2];
  315. int boot_index = FACTORY_INDEX;
  316. if (bs->ota_info.offset == 0) {
  317. return FACTORY_INDEX;
  318. }
  319. if (bootloader_common_read_otadata(&bs->ota_info, otadata) != ESP_OK) {
  320. return INVALID_INDEX;
  321. }
  322. ota_has_initial_contents = false;
  323. ESP_LOGD(TAG, "otadata[0]: sequence values 0x%08"PRIx32, otadata[0].ota_seq);
  324. ESP_LOGD(TAG, "otadata[1]: sequence values 0x%08"PRIx32, otadata[1].ota_seq);
  325. #ifdef CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
  326. bool write_encrypted = esp_flash_encryption_enabled();
  327. for (int i = 0; i < 2; ++i) {
  328. if (otadata[i].ota_state == ESP_OTA_IMG_PENDING_VERIFY) {
  329. ESP_LOGD(TAG, "otadata[%d] is marking as ABORTED", i);
  330. otadata[i].ota_state = ESP_OTA_IMG_ABORTED;
  331. write_otadata(&otadata[i], bs->ota_info.offset + FLASH_SECTOR_SIZE * i, write_encrypted);
  332. }
  333. }
  334. #endif
  335. #ifndef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
  336. if ((bootloader_common_ota_select_invalid(&otadata[0]) &&
  337. bootloader_common_ota_select_invalid(&otadata[1])) ||
  338. bs->app_count == 0) {
  339. ESP_LOGD(TAG, "OTA sequence numbers both empty (all-0xFF) or partition table does not have bootable ota_apps (app_count=%"PRIu32")", bs->app_count);
  340. if (bs->factory.offset != 0) {
  341. ESP_LOGI(TAG, "Defaulting to factory image");
  342. boot_index = FACTORY_INDEX;
  343. } else {
  344. ESP_LOGI(TAG, "No factory image, trying OTA 0");
  345. boot_index = 0;
  346. // Try to boot from ota_0.
  347. if ((otadata[0].ota_seq == UINT32_MAX || otadata[0].crc != bootloader_common_ota_select_crc(&otadata[0])) &&
  348. (otadata[1].ota_seq == UINT32_MAX || otadata[1].crc != bootloader_common_ota_select_crc(&otadata[1]))) {
  349. // Factory is not found and both otadata are initial(0xFFFFFFFF) or incorrect crc.
  350. // will set correct ota_seq.
  351. ota_has_initial_contents = true;
  352. }
  353. }
  354. } else {
  355. int active_otadata = bootloader_common_get_active_otadata(otadata);
  356. #else
  357. ESP_LOGI(TAG, "Enabled a check secure version of app for anti rollback");
  358. ESP_LOGI(TAG, "Secure version (from eFuse) = %"PRIu32, esp_efuse_read_secure_version());
  359. // When CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK is enabled factory partition should not be in partition table, only two ota_app are there.
  360. if ((otadata[0].ota_seq == UINT32_MAX || otadata[0].crc != bootloader_common_ota_select_crc(&otadata[0])) &&
  361. (otadata[1].ota_seq == UINT32_MAX || otadata[1].crc != bootloader_common_ota_select_crc(&otadata[1]))) {
  362. ESP_LOGI(TAG, "otadata[0..1] in initial state");
  363. // both otadata are initial(0xFFFFFFFF) or incorrect crc.
  364. // will set correct ota_seq.
  365. ota_has_initial_contents = true;
  366. } else {
  367. int active_otadata = get_active_otadata_with_check_anti_rollback(bs, otadata);
  368. #endif
  369. if (active_otadata != -1) {
  370. ESP_LOGD(TAG, "Active otadata[%d]", active_otadata);
  371. uint32_t ota_seq = otadata[active_otadata].ota_seq - 1; // Raw OTA sequence number. May be more than # of OTA slots
  372. boot_index = ota_seq % bs->app_count; // Actual OTA partition selection
  373. ESP_LOGD(TAG, "Mapping seq %"PRIu32" -> OTA slot %d", ota_seq, boot_index);
  374. #ifdef CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
  375. if (otadata[active_otadata].ota_state == ESP_OTA_IMG_NEW) {
  376. ESP_LOGD(TAG, "otadata[%d] is selected as new and marked PENDING_VERIFY state", active_otadata);
  377. otadata[active_otadata].ota_state = ESP_OTA_IMG_PENDING_VERIFY;
  378. write_otadata(&otadata[active_otadata], bs->ota_info.offset + FLASH_SECTOR_SIZE * active_otadata, write_encrypted);
  379. }
  380. #endif // CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
  381. #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
  382. if (otadata[active_otadata].ota_state == ESP_OTA_IMG_VALID) {
  383. update_anti_rollback(&bs->ota[boot_index]);
  384. }
  385. #endif // CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
  386. } else if (bs->factory.offset != 0) {
  387. ESP_LOGE(TAG, "ota data partition invalid, falling back to factory");
  388. boot_index = FACTORY_INDEX;
  389. } else {
  390. ESP_LOGE(TAG, "ota data partition invalid and no factory, will try all partitions");
  391. boot_index = FACTORY_INDEX;
  392. }
  393. }
  394. return boot_index;
  395. }
  396. /* Return true if a partition has a valid app image that was successfully loaded */
  397. static bool try_load_partition(const esp_partition_pos_t *partition, esp_image_metadata_t *data)
  398. {
  399. if (partition->size == 0) {
  400. ESP_LOGD(TAG, "Can't boot from zero-length partition");
  401. return false;
  402. }
  403. #ifdef BOOTLOADER_BUILD
  404. if (bootloader_load_image(partition, data) == ESP_OK) {
  405. ESP_LOGI(TAG, "Loaded app from partition at offset 0x%x",
  406. partition->offset);
  407. return true;
  408. }
  409. #endif
  410. return false;
  411. }
  412. // ota_has_initial_contents flag is set if factory does not present in partition table and
  413. // otadata has initial content(0xFFFFFFFF), then set actual ota_seq.
  414. static void set_actual_ota_seq(const bootloader_state_t *bs, int index)
  415. {
  416. if (index > FACTORY_INDEX && ota_has_initial_contents == true) {
  417. esp_ota_select_entry_t otadata;
  418. memset(&otadata, 0xFF, sizeof(otadata));
  419. otadata.ota_seq = index + 1;
  420. otadata.ota_state = ESP_OTA_IMG_VALID;
  421. otadata.crc = bootloader_common_ota_select_crc(&otadata);
  422. bool write_encrypted = esp_flash_encryption_enabled();
  423. write_otadata(&otadata, bs->ota_info.offset + FLASH_SECTOR_SIZE * 0, write_encrypted);
  424. ESP_LOGI(TAG, "Set actual ota_seq=%"PRIu32" in otadata[0]", otadata.ota_seq);
  425. #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
  426. update_anti_rollback(&bs->ota[index]);
  427. #endif
  428. }
  429. #if CONFIG_BOOTLOADER_RESERVE_RTC_MEM
  430. #ifdef CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP
  431. esp_partition_pos_t partition = index_to_partition(bs, index);
  432. bootloader_common_update_rtc_retain_mem(&partition, true);
  433. #else
  434. bootloader_common_update_rtc_retain_mem(NULL, true);
  435. #endif
  436. #endif // CONFIG_BOOTLOADER_RESERVE_RTC_MEM
  437. }
  438. #ifdef CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP
  439. void bootloader_utility_load_boot_image_from_deep_sleep(void)
  440. {
  441. if (esp_rom_get_reset_reason(0) == RESET_REASON_CORE_DEEP_SLEEP) {
  442. esp_partition_pos_t *partition = bootloader_common_get_rtc_retain_mem_partition();
  443. if (partition != NULL) {
  444. esp_image_metadata_t image_data;
  445. if (bootloader_load_image_no_verify(partition, &image_data) == ESP_OK) {
  446. ESP_LOGI(TAG, "Fast booting app from partition at offset 0x%"PRIx32, partition->offset);
  447. bootloader_common_update_rtc_retain_mem(NULL, true);
  448. load_image(&image_data);
  449. }
  450. }
  451. ESP_LOGE(TAG, "Fast booting is not successful");
  452. ESP_LOGI(TAG, "Try to load an app as usual with all validations");
  453. }
  454. }
  455. #endif
  456. #define TRY_LOG_FORMAT "Trying partition index %d offs 0x%"PRIx32" size 0x%"PRIx32
  457. void bootloader_utility_load_boot_image(const bootloader_state_t *bs, int start_index)
  458. {
  459. int index = start_index;
  460. esp_partition_pos_t part;
  461. esp_image_metadata_t image_data = {0};
  462. if (start_index == TEST_APP_INDEX) {
  463. if (check_anti_rollback(&bs->test) && try_load_partition(&bs->test, &image_data)) {
  464. load_image(&image_data);
  465. } else {
  466. ESP_LOGE(TAG, "No bootable test partition in the partition table");
  467. bootloader_reset();
  468. }
  469. }
  470. /* work backwards from start_index, down to the factory app */
  471. for (index = start_index; index >= FACTORY_INDEX; index--) {
  472. part = index_to_partition(bs, index);
  473. if (part.size == 0) {
  474. continue;
  475. }
  476. ESP_LOGD(TAG, TRY_LOG_FORMAT, index, part.offset, part.size);
  477. if (check_anti_rollback(&part) && try_load_partition(&part, &image_data)) {
  478. set_actual_ota_seq(bs, index);
  479. load_image(&image_data);
  480. }
  481. log_invalid_app_partition(index);
  482. }
  483. /* failing that work forwards from start_index, try valid OTA slots */
  484. for (index = start_index + 1; index < (int)bs->app_count; index++) {
  485. part = index_to_partition(bs, index);
  486. if (part.size == 0) {
  487. continue;
  488. }
  489. ESP_LOGD(TAG, TRY_LOG_FORMAT, index, part.offset, part.size);
  490. if (check_anti_rollback(&part) && try_load_partition(&part, &image_data)) {
  491. set_actual_ota_seq(bs, index);
  492. load_image(&image_data);
  493. }
  494. log_invalid_app_partition(index);
  495. }
  496. if (check_anti_rollback(&bs->test) && try_load_partition(&bs->test, &image_data)) {
  497. ESP_LOGW(TAG, "Falling back to test app as only bootable partition");
  498. load_image(&image_data);
  499. }
  500. ESP_LOGE(TAG, "No bootable app partitions in the partition table");
  501. bzero(&image_data, sizeof(esp_image_metadata_t));
  502. bootloader_reset();
  503. }
  504. // Copy loaded segments to RAM, set up caches for mapped segments, and start application.
  505. static void load_image(const esp_image_metadata_t *image_data)
  506. {
  507. /**
  508. * Rough steps for a first boot, when encryption and secure boot are both disabled:
  509. * 1) Generate secure boot key and write to EFUSE.
  510. * 2) Write plaintext digest based on plaintext bootloader
  511. * 3) Generate flash encryption key and write to EFUSE.
  512. * 4) Encrypt flash in-place including bootloader, then digest,
  513. * then app partitions and other encrypted partitions
  514. * 5) Burn EFUSE to enable flash encryption (FLASH_CRYPT_CNT)
  515. * 6) Burn EFUSE to enable secure boot (ABS_DONE_0)
  516. *
  517. * If power failure happens during Step 1, probably the next boot will continue from Step 2.
  518. * There is some small chance that EFUSEs will be part-way through being written so will be
  519. * somehow corrupted here. Thankfully this window of time is very small, but if that's the
  520. * case, one has to use the espefuse tool to manually set the remaining bits and enable R/W
  521. * protection. Once the relevant EFUSE bits are set and R/W protected, Step 1 will be skipped
  522. * successfully on further reboots.
  523. *
  524. * If power failure happens during Step 2, Step 1 will be skipped and Step 2 repeated:
  525. * the digest will get re-written on the next boot.
  526. *
  527. * If power failure happens during Step 3, it's possible that EFUSE was partially written
  528. * with the generated flash encryption key, though the time window for that would again
  529. * be very small. On reboot, Step 1 will be skipped and Step 2 repeated, though, Step 3
  530. * may fail due to the above mentioned reason, in which case, one has to use the espefuse
  531. * tool to manually set the remaining bits and enable R/W protection. Once the relevant EFUSE
  532. * bits are set and R/W protected, Step 3 will be skipped successfully on further reboots.
  533. *
  534. * If power failure happens after start of 4 and before end of 5, the next boot will fail
  535. * (bootloader header is encrypted and flash encryption isn't enabled yet, so it looks like
  536. * noise to the ROM bootloader). The check in the ROM is pretty basic so if the first byte of
  537. * ciphertext happens to be the magic byte E9 then it may try to boot, but it will definitely
  538. * crash (no chance that the remaining ciphertext will look like a valid bootloader image).
  539. * Only solution is to reflash with all plaintext and the whole process starts again: skips
  540. * Step 1, repeats Step 2, skips Step 3, etc.
  541. *
  542. * If power failure happens after 5 but before 6, the device will reboot with flash
  543. * encryption on and will regenerate an encrypted digest in Step 2. This should still
  544. * be valid as the input data for the digest is read via flash cache (so will be decrypted)
  545. * and the code in secure_boot_generate() tells bootloader_flash_write() to encrypt the data
  546. * on write if flash encryption is enabled. Steps 3 - 5 are skipped (encryption already on),
  547. * then Step 6 enables secure boot.
  548. */
  549. #if defined(CONFIG_SECURE_BOOT) || defined(CONFIG_SECURE_FLASH_ENC_ENABLED)
  550. esp_err_t err;
  551. #endif
  552. #ifdef CONFIG_SECURE_BOOT_FLASH_ENC_KEYS_BURN_TOGETHER
  553. if (esp_secure_boot_enabled() ^ esp_flash_encrypt_initialized_once()) {
  554. ESP_LOGE(TAG, "Secure Boot and Flash Encryption cannot be enabled separately, only together (their keys go into one eFuse key block)");
  555. return;
  556. }
  557. if (!esp_secure_boot_enabled() || !esp_flash_encryption_enabled()) {
  558. esp_efuse_batch_write_begin();
  559. }
  560. #endif // CONFIG_SECURE_BOOT_FLASH_ENC_KEYS_BURN_TOGETHER
  561. #ifdef CONFIG_SECURE_BOOT_V2_ENABLED
  562. err = esp_secure_boot_v2_permanently_enable(image_data);
  563. if (err != ESP_OK) {
  564. ESP_LOGE(TAG, "Secure Boot v2 failed (%d)", err);
  565. return;
  566. }
  567. #endif
  568. #ifdef CONFIG_SECURE_BOOT_V1_ENABLED
  569. /* Steps 1 & 2 (see above for full description):
  570. * 1) Generate secure boot EFUSE key
  571. * 2) Compute digest of plaintext bootloader
  572. */
  573. err = esp_secure_boot_generate_digest();
  574. if (err != ESP_OK) {
  575. ESP_LOGE(TAG, "Bootloader digest generation for secure boot failed (%d).", err);
  576. return;
  577. }
  578. #endif
  579. #ifdef CONFIG_SECURE_FLASH_ENC_ENABLED
  580. /* Steps 3, 4 & 5 (see above for full description):
  581. * 3) Generate flash encryption EFUSE key
  582. * 4) Encrypt flash contents
  583. * 5) Burn EFUSE to enable flash encryption
  584. */
  585. ESP_LOGI(TAG, "Checking flash encryption...");
  586. bool flash_encryption_enabled = esp_flash_encrypt_state();
  587. if (!flash_encryption_enabled) {
  588. #ifdef CONFIG_SECURE_FLASH_REQUIRE_ALREADY_ENABLED
  589. ESP_LOGE(TAG, "flash encryption is not enabled, and SECURE_FLASH_REQUIRE_ALREADY_ENABLED is set, refusing to boot.");
  590. return;
  591. #endif // CONFIG_SECURE_FLASH_REQUIRE_ALREADY_ENABLED
  592. if (esp_flash_encrypt_is_write_protected(true)) {
  593. return;
  594. }
  595. err = esp_flash_encrypt_init();
  596. if (err != ESP_OK) {
  597. ESP_LOGE(TAG, "Initialization of Flash Encryption key failed (%d)", err);
  598. return;
  599. }
  600. }
  601. #ifdef CONFIG_SECURE_BOOT_FLASH_ENC_KEYS_BURN_TOGETHER
  602. if (!esp_secure_boot_enabled() || !flash_encryption_enabled) {
  603. err = esp_efuse_batch_write_commit();
  604. if (err != ESP_OK) {
  605. ESP_LOGE(TAG, "Error programming eFuses (err=0x%x).", err);
  606. return;
  607. }
  608. assert(esp_secure_boot_enabled());
  609. ESP_LOGI(TAG, "Secure boot permanently enabled");
  610. }
  611. #endif // CONFIG_SECURE_BOOT_FLASH_ENC_KEYS_BURN_TOGETHER
  612. if (!flash_encryption_enabled) {
  613. err = esp_flash_encrypt_contents();
  614. if (err != ESP_OK) {
  615. ESP_LOGE(TAG, "Encryption flash contents failed (%d)", err);
  616. return;
  617. }
  618. err = esp_flash_encrypt_enable();
  619. if (err != ESP_OK) {
  620. ESP_LOGE(TAG, "Enabling of Flash encryption failed (%d)", err);
  621. return;
  622. }
  623. }
  624. #endif // CONFIG_SECURE_FLASH_ENC_ENABLED
  625. #ifdef CONFIG_SECURE_BOOT_V1_ENABLED
  626. /* Step 6 (see above for full description):
  627. * 6) Burn EFUSE to enable secure boot
  628. */
  629. ESP_LOGI(TAG, "Checking secure boot...");
  630. err = esp_secure_boot_permanently_enable();
  631. if (err != ESP_OK) {
  632. ESP_LOGE(TAG, "FAILED TO ENABLE SECURE BOOT (%d).", err);
  633. /* Panic here as secure boot is not properly enabled
  634. due to one of the reasons in above function
  635. */
  636. abort();
  637. }
  638. #endif
  639. #ifdef CONFIG_SECURE_FLASH_ENC_ENABLED
  640. if (!flash_encryption_enabled && esp_flash_encryption_enabled()) {
  641. /* Flash encryption was just enabled for the first time,
  642. so issue a system reset to ensure flash encryption
  643. cache resets properly */
  644. ESP_LOGI(TAG, "Resetting with flash encryption enabled...");
  645. esp_rom_uart_tx_wait_idle(0);
  646. bootloader_reset();
  647. }
  648. #endif
  649. ESP_LOGI(TAG, "Disabling RNG early entropy source...");
  650. bootloader_random_disable();
  651. /* Disable glitch reset after all the security checks are completed.
  652. * Glitch detection can be falsely triggered by EMI interference (high RF TX power, etc)
  653. * and to avoid such false alarms, disable it.
  654. */
  655. bootloader_ana_clock_glitch_reset_config(false);
  656. // copy loaded segments to RAM, set up caches for mapped segments, and start application
  657. unpack_load_app(image_data);
  658. }
  659. #if SOC_MMU_DI_VADDR_SHARED
  660. static void unpack_load_app(const esp_image_metadata_t *data)
  661. {
  662. /**
  663. * note:
  664. * On chips with shared D/I external vaddr, we don't divide them into either D or I,
  665. * as essentially they are the same.
  666. * We integrate all the hardware difference into this `unpack_load_app` function.
  667. */
  668. uint32_t rom_addr[2] = {};
  669. uint32_t rom_load_addr[2] = {};
  670. uint32_t rom_size[2] = {};
  671. int rom_index = 0; //shall not exceed 2
  672. // Find DROM & IROM addresses, to configure MMU mappings
  673. for (int i = 0; i < data->image.segment_count; i++) {
  674. const esp_image_segment_header_t *header = &data->segments[i];
  675. //`SOC_DROM_LOW` and `SOC_DROM_HIGH` are the same as `SOC_IROM_LOW` and `SOC_IROM_HIGH`, reasons are in above `note`
  676. if (header->load_addr >= SOC_DROM_LOW && header->load_addr < SOC_DROM_HIGH) {
  677. /**
  678. * D/I are shared, but there should not be a third segment on flash
  679. */
  680. assert(rom_index < 2);
  681. rom_addr[rom_index] = data->segment_data[i];
  682. rom_load_addr[rom_index] = header->load_addr;
  683. rom_size[rom_index] = header->data_len;
  684. rom_index++;
  685. }
  686. }
  687. assert(rom_index == 2);
  688. ESP_EARLY_LOGD(TAG, "calling set_cache_and_start_app");
  689. set_cache_and_start_app(rom_addr[0],
  690. rom_load_addr[0],
  691. rom_size[0],
  692. rom_addr[1],
  693. rom_load_addr[1],
  694. rom_size[1],
  695. data->image.entry_addr);
  696. }
  697. #else //!SOC_MMU_DI_VADDR_SHARED
  698. static void unpack_load_app(const esp_image_metadata_t *data)
  699. {
  700. uint32_t drom_addr = 0;
  701. uint32_t drom_load_addr = 0;
  702. uint32_t drom_size = 0;
  703. uint32_t irom_addr = 0;
  704. uint32_t irom_load_addr = 0;
  705. uint32_t irom_size = 0;
  706. // Find DROM & IROM addresses, to configure MMU mappings
  707. for (int i = 0; i < data->image.segment_count; i++) {
  708. const esp_image_segment_header_t *header = &data->segments[i];
  709. if (header->load_addr >= SOC_DROM_LOW && header->load_addr < SOC_DROM_HIGH) {
  710. if (drom_addr != 0) {
  711. ESP_EARLY_LOGE(TAG, MAP_ERR_MSG, "DROM");
  712. } else {
  713. ESP_EARLY_LOGD(TAG, "Mapping segment %d as %s", i, "DROM");
  714. }
  715. drom_addr = data->segment_data[i];
  716. drom_load_addr = header->load_addr;
  717. drom_size = header->data_len;
  718. }
  719. if (header->load_addr >= SOC_IROM_LOW && header->load_addr < SOC_IROM_HIGH) {
  720. if (irom_addr != 0) {
  721. ESP_EARLY_LOGE(TAG, MAP_ERR_MSG, "IROM");
  722. } else {
  723. ESP_EARLY_LOGD(TAG, "Mapping segment %d as %s", i, "IROM");
  724. }
  725. irom_addr = data->segment_data[i];
  726. irom_load_addr = header->load_addr;
  727. irom_size = header->data_len;
  728. }
  729. }
  730. ESP_EARLY_LOGD(TAG, "calling set_cache_and_start_app");
  731. set_cache_and_start_app(drom_addr,
  732. drom_load_addr,
  733. drom_size,
  734. irom_addr,
  735. irom_load_addr,
  736. irom_size,
  737. data->image.entry_addr);
  738. }
  739. #endif //#if SOC_MMU_DI_VADDR_SHARED
  740. static void set_cache_and_start_app(
  741. uint32_t drom_addr,
  742. uint32_t drom_load_addr,
  743. uint32_t drom_size,
  744. uint32_t irom_addr,
  745. uint32_t irom_load_addr,
  746. uint32_t irom_size,
  747. uint32_t entry_addr)
  748. {
  749. int rc __attribute__((unused));
  750. ESP_EARLY_LOGD(TAG, "configure drom and irom and start");
  751. //-----------------------Disable Cache to do the mapping---------
  752. #if CONFIG_IDF_TARGET_ESP32
  753. Cache_Read_Disable(0);
  754. Cache_Flush(0);
  755. #else
  756. cache_hal_disable(CACHE_TYPE_ALL);
  757. #endif
  758. //reset MMU table first
  759. mmu_hal_unmap_all();
  760. //-----------------------MAP DROM--------------------------
  761. uint32_t drom_load_addr_aligned = drom_load_addr & MMU_FLASH_MASK;
  762. uint32_t drom_addr_aligned = drom_addr & MMU_FLASH_MASK;
  763. ESP_EARLY_LOGV(TAG, "rodata starts from paddr=0x%08x, vaddr=0x%08x, size=0x%x", drom_addr, drom_load_addr, drom_size);
  764. //The addr is aligned, so we add the mask off length to the size, to make sure the corresponding buses are enabled.
  765. drom_size = (drom_load_addr - drom_load_addr_aligned) + drom_size;
  766. #if CONFIG_IDF_TARGET_ESP32
  767. uint32_t drom_page_count = (drom_size + SPI_FLASH_MMU_PAGE_SIZE - 1) / SPI_FLASH_MMU_PAGE_SIZE;
  768. rc = cache_flash_mmu_set(0, 0, drom_load_addr_aligned, drom_addr_aligned, 64, drom_page_count);
  769. ESP_EARLY_LOGV(TAG, "rc=%d", rc);
  770. rc = cache_flash_mmu_set(1, 0, drom_load_addr_aligned, drom_addr_aligned, 64, drom_page_count);
  771. ESP_EARLY_LOGV(TAG, "rc=%d", rc);
  772. ESP_EARLY_LOGV(TAG, "after mapping rodata, starting from paddr=0x%08x and vaddr=0x%08x, 0x%x bytes are mapped", drom_addr_aligned, drom_load_addr_aligned, drom_page_count * SPI_FLASH_MMU_PAGE_SIZE);
  773. #else
  774. uint32_t actual_mapped_len = 0;
  775. mmu_hal_map_region(0, MMU_TARGET_FLASH0, drom_load_addr_aligned, drom_addr_aligned, drom_size, &actual_mapped_len);
  776. ESP_EARLY_LOGV(TAG, "after mapping rodata, starting from paddr=0x%08x and vaddr=0x%08x, 0x%x bytes are mapped", drom_addr_aligned, drom_load_addr_aligned, actual_mapped_len);
  777. #endif
  778. //-----------------------MAP IROM--------------------------
  779. uint32_t irom_load_addr_aligned = irom_load_addr & MMU_FLASH_MASK;
  780. uint32_t irom_addr_aligned = irom_addr & MMU_FLASH_MASK;
  781. ESP_EARLY_LOGV(TAG, "text starts from paddr=0x%08x, vaddr=0x%08x, size=0x%x", irom_addr, irom_load_addr, irom_size);
  782. //The addr is aligned, so we add the mask off length to the size, to make sure the corresponding buses are enabled.
  783. irom_size = (irom_load_addr - irom_load_addr_aligned) + irom_size;
  784. #if CONFIG_IDF_TARGET_ESP32
  785. uint32_t irom_page_count = (irom_size + SPI_FLASH_MMU_PAGE_SIZE - 1) / SPI_FLASH_MMU_PAGE_SIZE;
  786. rc = cache_flash_mmu_set(0, 0, irom_load_addr_aligned, irom_addr_aligned, 64, irom_page_count);
  787. ESP_EARLY_LOGV(TAG, "rc=%d", rc);
  788. rc = cache_flash_mmu_set(1, 0, irom_load_addr_aligned, irom_addr_aligned, 64, irom_page_count);
  789. ESP_LOGV(TAG, "rc=%d", rc);
  790. ESP_EARLY_LOGV(TAG, "after mapping text, starting from paddr=0x%08x and vaddr=0x%08x, 0x%x bytes are mapped", irom_addr_aligned, irom_load_addr_aligned, irom_page_count * SPI_FLASH_MMU_PAGE_SIZE);
  791. #else
  792. mmu_hal_map_region(0, MMU_TARGET_FLASH0, irom_load_addr_aligned, irom_addr_aligned, irom_size, &actual_mapped_len);
  793. ESP_EARLY_LOGV(TAG, "after mapping text, starting from paddr=0x%08x and vaddr=0x%08x, 0x%x bytes are mapped", irom_addr_aligned, irom_load_addr_aligned, actual_mapped_len);
  794. #endif
  795. //----------------------Enable corresponding buses----------------
  796. cache_bus_mask_t bus_mask = cache_ll_l1_get_bus(0, drom_load_addr_aligned, drom_size);
  797. cache_ll_l1_enable_bus(0, bus_mask);
  798. bus_mask = cache_ll_l1_get_bus(0, irom_load_addr_aligned, irom_size);
  799. cache_ll_l1_enable_bus(0, bus_mask);
  800. #if !CONFIG_FREERTOS_UNICORE
  801. bus_mask = cache_ll_l1_get_bus(1, drom_load_addr_aligned, drom_size);
  802. cache_ll_l1_enable_bus(1, bus_mask);
  803. bus_mask = cache_ll_l1_get_bus(1, irom_load_addr_aligned, irom_size);
  804. cache_ll_l1_enable_bus(1, bus_mask);
  805. #endif
  806. //----------------------Enable Cache----------------
  807. #if CONFIG_IDF_TARGET_ESP32
  808. // Application will need to do Cache_Flush(1) and Cache_Read_Enable(1)
  809. Cache_Read_Enable(0);
  810. #else
  811. cache_hal_enable(CACHE_TYPE_ALL);
  812. #endif
  813. ESP_LOGD(TAG, "start: 0x%08"PRIx32, entry_addr);
  814. bootloader_atexit();
  815. typedef void (*entry_t)(void) __attribute__((noreturn));
  816. entry_t entry = ((entry_t) entry_addr);
  817. // TODO: we have used quite a bit of stack at this point.
  818. // use "movsp" instruction to reset stack back to where ROM stack starts.
  819. (*entry)();
  820. }
  821. void bootloader_reset(void)
  822. {
  823. #ifdef BOOTLOADER_BUILD
  824. bootloader_atexit();
  825. esp_rom_delay_us(1000); /* Allow last byte to leave FIFO */
  826. esp_rom_software_reset_system();
  827. while (1) { } /* This line will never be reached, used to keep gcc happy */
  828. #else
  829. abort(); /* This function should really not be called from application code */
  830. #endif
  831. }
  832. void bootloader_atexit(void)
  833. {
  834. #ifdef BOOTLOADER_BUILD
  835. bootloader_console_deinit();
  836. #else
  837. abort();
  838. #endif
  839. }
  840. esp_err_t bootloader_sha256_hex_to_str(char *out_str, const uint8_t *in_array_hex, size_t len)
  841. {
  842. if (out_str == NULL || in_array_hex == NULL || len == 0) {
  843. return ESP_ERR_INVALID_ARG;
  844. }
  845. for (size_t i = 0; i < len; i++) {
  846. for (int shift = 0; shift < 2; shift++) {
  847. uint8_t nibble = (in_array_hex[i] >> (shift ? 0 : 4)) & 0x0F;
  848. if (nibble < 10) {
  849. out_str[i * 2 + shift] = '0' + nibble;
  850. } else {
  851. out_str[i * 2 + shift] = 'a' + nibble - 10;
  852. }
  853. }
  854. }
  855. return ESP_OK;
  856. }
  857. void bootloader_debug_buffer(const void *buffer, size_t length, const char *label)
  858. {
  859. #if CONFIG_BOOTLOADER_LOG_LEVEL >= 4
  860. const uint8_t *bytes = (const uint8_t *)buffer;
  861. const size_t output_len = MIN(length, 128);
  862. char hexbuf[128 * 2 + 1];
  863. bootloader_sha256_hex_to_str(hexbuf, bytes, output_len);
  864. hexbuf[output_len * 2] = '\0';
  865. ESP_LOGD(TAG, "%s: %s", label, hexbuf);
  866. #else
  867. (void) buffer;
  868. (void) length;
  869. (void) label;
  870. #endif
  871. }
  872. esp_err_t bootloader_sha256_flash_contents(uint32_t flash_offset, uint32_t len, uint8_t *digest)
  873. {
  874. if (digest == NULL) {
  875. return ESP_ERR_INVALID_ARG;
  876. }
  877. /* Handling firmware images larger than MMU capacity */
  878. uint32_t mmu_free_pages_count = bootloader_mmap_get_free_pages();
  879. bootloader_sha256_handle_t sha_handle = NULL;
  880. sha_handle = bootloader_sha256_start();
  881. if (sha_handle == NULL) {
  882. return ESP_ERR_NO_MEM;
  883. }
  884. while (len > 0) {
  885. uint32_t mmu_page_offset = ((flash_offset & MMAP_ALIGNED_MASK) != 0) ? 1 : 0; /* Skip 1st MMU Page if it is already populated */
  886. uint32_t partial_image_len = MIN(len, ((mmu_free_pages_count - mmu_page_offset) * SPI_FLASH_MMU_PAGE_SIZE)); /* Read the image that fits in the free MMU pages */
  887. const void * image = bootloader_mmap(flash_offset, partial_image_len);
  888. if (image == NULL) {
  889. bootloader_sha256_finish(sha_handle, NULL);
  890. return ESP_FAIL;
  891. }
  892. bootloader_sha256_data(sha_handle, image, partial_image_len);
  893. bootloader_munmap(image);
  894. flash_offset += partial_image_len;
  895. len -= partial_image_len;
  896. }
  897. bootloader_sha256_finish(sha_handle, digest);
  898. return ESP_OK;
  899. }