bootloader_utility.c 39 KB

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