1 /*
2  * Copyright (c) 2012-2014 Wind River Systems, Inc.
3  * Copyright (c) 2020 Arm Limited
4  * Copyright (c) 2021-2023 Nordic Semiconductor ASA
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 
19 #include <assert.h>
20 #include <zephyr/kernel.h>
21 #include <zephyr/devicetree.h>
22 #include <zephyr/drivers/gpio.h>
23 #include <zephyr/sys/__assert.h>
24 #include <zephyr/drivers/flash.h>
25 #include <zephyr/drivers/timer/system_timer.h>
26 #include <zephyr/usb/usb_device.h>
27 #include <soc.h>
28 #include <zephyr/linker/linker-defs.h>
29 
30 #if defined(CONFIG_BOOT_DISABLE_CACHES)
31 #include <zephyr/cache.h>
32 #endif
33 
34 #if defined(CONFIG_ARM)
35 #include <cmsis_core.h>
36 #endif
37 
38 #include "io/io.h"
39 #include "target.h"
40 
41 #include "bootutil/bootutil_log.h"
42 #include "bootutil/image.h"
43 #include "bootutil/bootutil.h"
44 #include "bootutil/fault_injection_hardening.h"
45 #include "bootutil/mcuboot_status.h"
46 #include "flash_map_backend/flash_map_backend.h"
47 
48 /* Check if Espressif target is supported */
49 #ifdef CONFIG_SOC_FAMILY_ESPRESSIF_ESP32
50 
51 #include <bootloader_init.h>
52 #include <esp_image_loader.h>
53 
54 #define IMAGE_INDEX_0   0
55 #define IMAGE_INDEX_1   1
56 
57 #define PRIMARY_SLOT    0
58 #define SECONDARY_SLOT  1
59 
60 #define IMAGE0_PRIMARY_START_ADDRESS \
61           DT_PROP_BY_IDX(DT_NODE_BY_FIXED_PARTITION_LABEL(image_0), reg, 0)
62 #define IMAGE0_PRIMARY_SIZE \
63           DT_PROP_BY_IDX(DT_NODE_BY_FIXED_PARTITION_LABEL(image_0), reg, 1)
64 
65 #define IMAGE1_PRIMARY_START_ADDRESS \
66           DT_PROP_BY_IDX(DT_NODE_BY_FIXED_PARTITION_LABEL(image_1), reg, 0)
67 #define IMAGE1_PRIMARY_SIZE \
68           DT_PROP_BY_IDX(DT_NODE_BY_FIXED_PARTITION_LABEL(image_1), reg, 1)
69 
70 #endif /* CONFIG_SOC_FAMILY_ESPRESSIF_ESP32 */
71 
72 #ifdef CONFIG_MCUBOOT_SERIAL
73 #include "boot_serial/boot_serial.h"
74 #include "serial_adapter/serial_adapter.h"
75 
76 const struct boot_uart_funcs boot_funcs = {
77     .read = console_read,
78     .write = console_write
79 };
80 #endif
81 
82 #if defined(CONFIG_BOOT_USB_DFU_WAIT) || defined(CONFIG_BOOT_USB_DFU_GPIO)
83 #include <zephyr/usb/class/usb_dfu.h>
84 #endif
85 
86 #if CONFIG_MCUBOOT_CLEANUP_ARM_CORE
87 #include <arm_cleanup.h>
88 #endif
89 
90 /* CONFIG_LOG_MINIMAL is the legacy Kconfig property,
91  * replaced by CONFIG_LOG_MODE_MINIMAL.
92  */
93 #if (defined(CONFIG_LOG_MODE_MINIMAL) || defined(CONFIG_LOG_MINIMAL))
94 #define ZEPHYR_LOG_MODE_MINIMAL 1
95 #endif
96 
97 /* CONFIG_LOG_IMMEDIATE is the legacy Kconfig property,
98  * replaced by CONFIG_LOG_MODE_IMMEDIATE.
99  */
100 #if (defined(CONFIG_LOG_MODE_IMMEDIATE) || defined(CONFIG_LOG_IMMEDIATE))
101 #define ZEPHYR_LOG_MODE_IMMEDIATE 1
102 #endif
103 
104 #if defined(CONFIG_LOG) && !defined(ZEPHYR_LOG_MODE_IMMEDIATE) && \
105     !defined(ZEPHYR_LOG_MODE_MINIMAL)
106 #ifdef CONFIG_LOG_PROCESS_THREAD
107 #warning "The log internal thread for log processing can't transfer the log"\
108          "well for MCUBoot."
109 #else
110 #include <zephyr/logging/log_ctrl.h>
111 
112 #define BOOT_LOG_PROCESSING_INTERVAL K_MSEC(30) /* [ms] */
113 
114 /* log are processing in custom routine */
115 K_THREAD_STACK_DEFINE(boot_log_stack, CONFIG_MCUBOOT_LOG_THREAD_STACK_SIZE);
116 struct k_thread boot_log_thread;
117 volatile bool boot_log_stop = false;
118 K_SEM_DEFINE(boot_log_sem, 1, 1);
119 
120 /* log processing need to be initalized by the application */
121 #define ZEPHYR_BOOT_LOG_START() zephyr_boot_log_start()
122 #define ZEPHYR_BOOT_LOG_STOP() zephyr_boot_log_stop()
123 #endif /* CONFIG_LOG_PROCESS_THREAD */
124 #else
125 /* synchronous log mode doesn't need to be initalized by the application */
126 #define ZEPHYR_BOOT_LOG_START() do { } while (false)
127 #define ZEPHYR_BOOT_LOG_STOP() do { } while (false)
128 #endif /* defined(CONFIG_LOG) && !defined(ZEPHYR_LOG_MODE_IMMEDIATE) && \
129         * !defined(ZEPHYR_LOG_MODE_MINIMAL)
130 	*/
131 
132 BOOT_LOG_MODULE_REGISTER(mcuboot);
133 
134 void os_heap_init(void);
135 
136 #if defined(CONFIG_ARM)
137 
138 #ifdef CONFIG_SW_VECTOR_RELAY
139 extern void *_vector_table_pointer;
140 #endif
141 
142 struct arm_vector_table {
143     uint32_t msp;
144     uint32_t reset;
145 };
146 
do_boot(struct boot_rsp * rsp)147 static void do_boot(struct boot_rsp *rsp)
148 {
149     struct arm_vector_table *vt;
150 
151     /* The beginning of the image is the ARM vector table, containing
152      * the initial stack pointer address and the reset vector
153      * consecutively. Manually set the stack pointer and jump into the
154      * reset vector
155      */
156 #ifdef CONFIG_BOOT_RAM_LOAD
157     /* Get ram address for image */
158     vt = (struct arm_vector_table *)(rsp->br_hdr->ih_load_addr + rsp->br_hdr->ih_hdr_size);
159 #else
160     int rc;
161     const struct flash_area *fap;
162     static uint32_t dst[2];
163 
164     /* Jump to flash image */
165     rc = flash_area_open(rsp->br_flash_dev_id, &fap);
166     assert(rc == 0);
167 
168     rc = flash_area_read(fap, rsp->br_hdr->ih_hdr_size, dst, sizeof(dst));
169     assert(rc == 0);
170 #ifndef CONFIG_ASSERT
171     /* Enter a lock up as asserts are disabled */
172     if (rc != 0) {
173         while (1);
174     }
175 #endif
176 
177     flash_area_close(fap);
178 
179     vt = (struct arm_vector_table *)dst;
180 #endif
181 
182     if (IS_ENABLED(CONFIG_SYSTEM_TIMER_HAS_DISABLE_SUPPORT)) {
183         sys_clock_disable();
184     }
185 
186 #ifdef CONFIG_USB_DEVICE_STACK
187     /* Disable the USB to prevent it from firing interrupts */
188     usb_disable();
189 #endif
190 #if CONFIG_MCUBOOT_CLEANUP_ARM_CORE
191     cleanup_arm_nvic(); /* cleanup NVIC registers */
192 
193 #if defined(CONFIG_BOOT_DISABLE_CACHES)
194     /* Flush and disable instruction/data caches before chain-loading the application */
195     (void)sys_cache_instr_flush_all();
196     (void)sys_cache_data_flush_all();
197     sys_cache_instr_disable();
198     sys_cache_data_disable();
199 #endif
200 
201 #if CONFIG_CPU_HAS_ARM_MPU || CONFIG_CPU_HAS_NXP_MPU
202     z_arm_clear_arm_mpu_config();
203 #endif
204 
205 #if defined(CONFIG_BUILTIN_STACK_GUARD) && \
206     defined(CONFIG_CPU_CORTEX_M_HAS_SPLIM)
207     /* Reset limit registers to avoid inflicting stack overflow on image
208      * being booted.
209      */
210     __set_PSPLIM(0);
211     __set_MSPLIM(0);
212 #endif
213 
214 #else
215     irq_lock();
216 #endif /* CONFIG_MCUBOOT_CLEANUP_ARM_CORE */
217 
218 #ifdef CONFIG_BOOT_INTR_VEC_RELOC
219 #if defined(CONFIG_SW_VECTOR_RELAY)
220     _vector_table_pointer = vt;
221 #ifdef CONFIG_CPU_CORTEX_M_HAS_VTOR
222     SCB->VTOR = (uint32_t)__vector_relay_table;
223 #endif
224 #elif defined(CONFIG_CPU_CORTEX_M_HAS_VTOR)
225     SCB->VTOR = (uint32_t)vt;
226 #endif /* CONFIG_SW_VECTOR_RELAY */
227 #else /* CONFIG_BOOT_INTR_VEC_RELOC */
228 #if defined(CONFIG_CPU_CORTEX_M_HAS_VTOR) && defined(CONFIG_SW_VECTOR_RELAY)
229     _vector_table_pointer = _vector_start;
230     SCB->VTOR = (uint32_t)__vector_relay_table;
231 #endif
232 #endif /* CONFIG_BOOT_INTR_VEC_RELOC */
233 
234     __set_MSP(vt->msp);
235 #if CONFIG_MCUBOOT_CLEANUP_ARM_CORE
236     __set_CONTROL(0x00); /* application will configures core on its own */
237     __ISB();
238 #endif
239     ((void (*)(void))vt->reset)();
240 }
241 
242 #elif defined(CONFIG_XTENSA) || defined(CONFIG_RISCV)
243 
244 #ifndef CONFIG_SOC_FAMILY_ESPRESSIF_ESP32
245 
246 #define SRAM_BASE_ADDRESS	0xBE030000
247 
copy_img_to_SRAM(int slot,unsigned int hdr_offset)248 static void copy_img_to_SRAM(int slot, unsigned int hdr_offset)
249 {
250     const struct flash_area *fap;
251     int area_id;
252     int rc;
253     unsigned char *dst = (unsigned char *)(SRAM_BASE_ADDRESS + hdr_offset);
254 
255     BOOT_LOG_INF("Copying image to SRAM");
256 
257     area_id = flash_area_id_from_image_slot(slot);
258     rc = flash_area_open(area_id, &fap);
259     if (rc != 0) {
260         BOOT_LOG_ERR("flash_area_open failed with %d\n", rc);
261         goto done;
262     }
263 
264     rc = flash_area_read(fap, hdr_offset, dst, fap->fa_size - hdr_offset);
265     if (rc != 0) {
266         BOOT_LOG_ERR("flash_area_read failed with %d\n", rc);
267         goto done;
268     }
269 
270 done:
271     flash_area_close(fap);
272 }
273 #endif /* !CONFIG_SOC_FAMILY_ESPRESSIF_ESP32 */
274 
275 /* Entry point (.ResetVector) is at the very beginning of the image.
276  * Simply copy the image to a suitable location and jump there.
277  */
do_boot(struct boot_rsp * rsp)278 static void do_boot(struct boot_rsp *rsp)
279 {
280 #ifndef CONFIG_SOC_FAMILY_ESPRESSIF_ESP32
281     void *start;
282 #endif /* CONFIG_SOC_FAMILY_ESPRESSIF_ESP32 */
283 
284     BOOT_LOG_INF("br_image_off = 0x%x\n", rsp->br_image_off);
285     BOOT_LOG_INF("ih_hdr_size = 0x%x\n", rsp->br_hdr->ih_hdr_size);
286 
287 #ifdef CONFIG_SOC_FAMILY_ESPRESSIF_ESP32
288     int slot = (rsp->br_image_off == IMAGE0_PRIMARY_START_ADDRESS) ?
289                 PRIMARY_SLOT : SECONDARY_SLOT;
290     /* Load memory segments and start from entry point */
291     start_cpu0_image(IMAGE_INDEX_0, slot, rsp->br_hdr->ih_hdr_size);
292 #else
293     /* Copy from the flash to HP SRAM */
294     copy_img_to_SRAM(0, rsp->br_hdr->ih_hdr_size);
295 
296     /* Jump to entry point */
297     start = (void *)(SRAM_BASE_ADDRESS + rsp->br_hdr->ih_hdr_size);
298     ((void (*)(void))start)();
299 #endif /* CONFIG_SOC_FAMILY_ESPRESSIF_ESP32 */
300 }
301 
302 #else
303 /* Default: Assume entry point is at the very beginning of the image. Simply
304  * lock interrupts and jump there. This is the right thing to do for X86 and
305  * possibly other platforms.
306  */
do_boot(struct boot_rsp * rsp)307 static void do_boot(struct boot_rsp *rsp)
308 {
309     void *start;
310 
311 #if defined(MCUBOOT_RAM_LOAD)
312     start = (void *)(rsp->br_hdr->ih_load_addr + rsp->br_hdr->ih_hdr_size);
313 #else
314     uintptr_t flash_base;
315     int rc;
316 
317     rc = flash_device_base(rsp->br_flash_dev_id, &flash_base);
318     assert(rc == 0);
319 
320     start = (void *)(flash_base + rsp->br_image_off +
321                      rsp->br_hdr->ih_hdr_size);
322 #endif
323 
324     /* Lock interrupts and dive into the entry point */
325     irq_lock();
326     ((void (*)(void))start)();
327 }
328 #endif
329 
330 #if defined(CONFIG_LOG) && !defined(ZEPHYR_LOG_MODE_IMMEDIATE) && \
331     !defined(CONFIG_LOG_PROCESS_THREAD) && !defined(ZEPHYR_LOG_MODE_MINIMAL)
332 /* The log internal thread for log processing can't transfer log well as has too
333  * low priority.
334  * Dedicated thread for log processing below uses highest application
335  * priority. This allows to transmit all logs without adding k_sleep/k_yield
336  * anywhere else int the code.
337  */
338 
339 /* most simple log processing theread */
boot_log_thread_func(void * dummy1,void * dummy2,void * dummy3)340 void boot_log_thread_func(void *dummy1, void *dummy2, void *dummy3)
341 {
342     (void)dummy1;
343     (void)dummy2;
344     (void)dummy3;
345 
346     log_init();
347 
348     while (1) {
349 #if defined(CONFIG_LOG1) || defined(CONFIG_LOG2)
350         /* support Zephyr legacy logging implementation before commit c5f2cde */
351         if (log_process(false) == false) {
352 #else
353         if (log_process() == false) {
354 #endif
355             if (boot_log_stop) {
356                 break;
357             }
358             k_sleep(BOOT_LOG_PROCESSING_INTERVAL);
359         }
360     }
361 
362     k_sem_give(&boot_log_sem);
363 }
364 
365 void zephyr_boot_log_start(void)
366 {
367     /* start logging thread */
368     k_thread_create(&boot_log_thread, boot_log_stack,
369                     K_THREAD_STACK_SIZEOF(boot_log_stack),
370                     boot_log_thread_func, NULL, NULL, NULL,
371                     K_HIGHEST_APPLICATION_THREAD_PRIO, 0,
372                     BOOT_LOG_PROCESSING_INTERVAL);
373 
374     k_thread_name_set(&boot_log_thread, "logging");
375 }
376 
377 void zephyr_boot_log_stop(void)
378 {
379     boot_log_stop = true;
380 
381     /* wait until log procesing thread expired
382      * This can be reworked using a thread_join() API once a such will be
383      * available in zephyr.
384      * see https://github.com/zephyrproject-rtos/zephyr/issues/21500
385      */
386     (void)k_sem_take(&boot_log_sem, K_FOREVER);
387 }
388 #endif /* defined(CONFIG_LOG) && !defined(ZEPHYR_LOG_MODE_IMMEDIATE) && \
389         * !defined(CONFIG_LOG_PROCESS_THREAD) && !defined(ZEPHYR_LOG_MODE_MINIMAL)
390         */
391 
392 #if defined(CONFIG_BOOT_SERIAL_ENTRANCE_GPIO) || defined(CONFIG_BOOT_SERIAL_PIN_RESET) \
393     || defined(CONFIG_BOOT_SERIAL_BOOT_MODE) || defined(CONFIG_BOOT_SERIAL_NO_APPLICATION)
394 static void boot_serial_enter()
395 {
396     int rc;
397 
398 #ifdef CONFIG_MCUBOOT_INDICATION_LED
399     io_led_set(1);
400 #endif
401 
402     mcuboot_status_change(MCUBOOT_STATUS_SERIAL_DFU_ENTERED);
403 
404     BOOT_LOG_INF("Enter the serial recovery mode");
405     rc = boot_console_init();
406     __ASSERT(rc == 0, "Error initializing boot console.\n");
407     boot_serial_start(&boot_funcs);
408     __ASSERT(0, "Bootloader serial process was terminated unexpectedly.\n");
409 }
410 #endif
411 
412 int main(void)
413 {
414     struct boot_rsp rsp;
415     int rc;
416     FIH_DECLARE(fih_rc, FIH_FAILURE);
417 
418     MCUBOOT_WATCHDOG_SETUP();
419     MCUBOOT_WATCHDOG_FEED();
420 
421 #if !defined(MCUBOOT_DIRECT_XIP)
422     BOOT_LOG_INF("Starting bootloader");
423 #else
424     BOOT_LOG_INF("Starting Direct-XIP bootloader");
425 #endif
426 
427 #ifdef CONFIG_MCUBOOT_INDICATION_LED
428     /* LED init */
429     io_led_init();
430 #endif
431 
432     os_heap_init();
433 
434     ZEPHYR_BOOT_LOG_START();
435 
436     (void)rc;
437 
438     mcuboot_status_change(MCUBOOT_STATUS_STARTUP);
439 
440 #ifdef CONFIG_BOOT_SERIAL_ENTRANCE_GPIO
441     if (io_detect_pin() &&
442             !io_boot_skip_serial_recovery()) {
443         boot_serial_enter();
444     }
445 #endif
446 
447 #ifdef CONFIG_BOOT_SERIAL_PIN_RESET
448     if (io_detect_pin_reset()) {
449         boot_serial_enter();
450     }
451 #endif
452 
453 #if defined(CONFIG_BOOT_USB_DFU_GPIO)
454     if (io_detect_pin()) {
455 #ifdef CONFIG_MCUBOOT_INDICATION_LED
456         io_led_set(1);
457 #endif
458 
459         mcuboot_status_change(MCUBOOT_STATUS_USB_DFU_ENTERED);
460 
461         rc = usb_enable(NULL);
462         if (rc) {
463             BOOT_LOG_ERR("Cannot enable USB");
464         } else {
465             BOOT_LOG_INF("Waiting for USB DFU");
466             wait_for_usb_dfu(K_FOREVER);
467             BOOT_LOG_INF("USB DFU wait time elapsed");
468         }
469     }
470 #elif defined(CONFIG_BOOT_USB_DFU_WAIT)
471     rc = usb_enable(NULL);
472     if (rc) {
473         BOOT_LOG_ERR("Cannot enable USB");
474     } else {
475         BOOT_LOG_INF("Waiting for USB DFU");
476 
477         mcuboot_status_change(MCUBOOT_STATUS_USB_DFU_WAITING);
478 
479         wait_for_usb_dfu(K_MSEC(CONFIG_BOOT_USB_DFU_WAIT_DELAY_MS));
480         BOOT_LOG_INF("USB DFU wait time elapsed");
481 
482         mcuboot_status_change(MCUBOOT_STATUS_USB_DFU_TIMED_OUT);
483     }
484 #endif
485 
486 #ifdef CONFIG_BOOT_SERIAL_WAIT_FOR_DFU
487     /* Initialize the boot console, so we can already fill up our buffers while
488      * waiting for the boot image check to finish. This image check, can take
489      * some time, so it's better to reuse thistime to already receive the
490      * initial mcumgr command(s) into our buffers
491      */
492     rc = boot_console_init();
493     int timeout_in_ms = CONFIG_BOOT_SERIAL_WAIT_FOR_DFU_TIMEOUT;
494     uint32_t start = k_uptime_get_32();
495 
496 #ifdef CONFIG_MCUBOOT_INDICATION_LED
497     io_led_set(1);
498 #endif
499 #endif
500 
501     FIH_CALL(boot_go, fih_rc, &rsp);
502 
503 #ifdef CONFIG_BOOT_SERIAL_BOOT_MODE
504     if (io_detect_boot_mode()) {
505         /* Boot mode to stay in bootloader, clear status and enter serial
506          * recovery mode
507          */
508         boot_serial_enter();
509     }
510 #endif
511 
512 #ifdef CONFIG_BOOT_SERIAL_WAIT_FOR_DFU
513     timeout_in_ms -= (k_uptime_get_32() - start);
514     if( timeout_in_ms <= 0 ) {
515         /* at least one check if time was expired */
516         timeout_in_ms = 1;
517     }
518     boot_serial_check_start(&boot_funcs,timeout_in_ms);
519 
520 #ifdef CONFIG_MCUBOOT_INDICATION_LED
521     io_led_set(0);
522 #endif
523 #endif
524 
525     if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
526         BOOT_LOG_ERR("Unable to find bootable image");
527 
528         mcuboot_status_change(MCUBOOT_STATUS_NO_BOOTABLE_IMAGE_FOUND);
529 
530 #ifdef CONFIG_BOOT_SERIAL_NO_APPLICATION
531         /* No bootable image and configuration set to remain in serial
532          * recovery mode
533          */
534         boot_serial_enter();
535 #elif defined(CONFIG_BOOT_USB_DFU_NO_APPLICATION)
536         rc = usb_enable(NULL);
537         if (rc && rc != -EALREADY) {
538             BOOT_LOG_ERR("Cannot enable USB");
539         } else {
540             BOOT_LOG_INF("Waiting for USB DFU");
541             wait_for_usb_dfu(K_FOREVER);
542         }
543 #endif
544 
545         FIH_PANIC;
546     }
547 
548 #ifdef CONFIG_BOOT_RAM_LOAD
549     BOOT_LOG_INF("Bootloader chainload address offset: 0x%x",
550                  rsp.br_hdr->ih_load_addr);
551 #else
552     BOOT_LOG_INF("Bootloader chainload address offset: 0x%x",
553                  rsp.br_image_off);
554 #endif
555 
556     BOOT_LOG_INF("Image version: v%d.%d.%d", rsp.br_hdr->ih_ver.iv_major,
557                                                     rsp.br_hdr->ih_ver.iv_minor,
558                                                     rsp.br_hdr->ih_ver.iv_revision);
559 
560 #if defined(MCUBOOT_DIRECT_XIP)
561     BOOT_LOG_INF("Jumping to the image slot");
562 #else
563     BOOT_LOG_INF("Jumping to the first image slot");
564 #endif
565 
566     mcuboot_status_change(MCUBOOT_STATUS_BOOTABLE_IMAGE_FOUND);
567 
568     ZEPHYR_BOOT_LOG_STOP();
569     do_boot(&rsp);
570 
571     mcuboot_status_change(MCUBOOT_STATUS_BOOT_FAILED);
572 
573     BOOT_LOG_ERR("Never should get here");
574     while (1)
575         ;
576 }
577