bootloader_utility.c 34 KB

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