bootloader_utility.c 39 KB

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