bootloader_utility.c 33 KB

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