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