bootloader_utility.c 34 KB

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