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