bootloader_utility.c 36 KB

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