2323#include <bootloader_flash.h>
2424#include <bootloader_random.h>
2525#include <bootloader_sha.h>
26+ #include "bootloader_util.h"
2627
2728static const char * TAG = "esp_image" ;
2829
@@ -42,6 +43,10 @@ static const char *TAG = "esp_image";
4243 (Means loaded code isn't executable until after the secure boot check.)
4344*/
4445static uint32_t ram_obfs_value [2 ];
46+
47+ /* Range of IRAM used by the loader, defined in ld script */
48+ extern int _loader_text_start ;
49+ extern int _loader_text_end ;
4550#endif
4651
4752/* Return true if load_addr is an address the bootloader should load into */
@@ -286,18 +291,41 @@ static esp_err_t process_segment(int index, uint32_t flash_addr, esp_image_segme
286291 (do_load )?"load" :(is_mapping )?"map" :"" );
287292 }
288293
294+
295+ #ifdef BOOTLOADER_BUILD
296+ /* Before loading segment, check it doesn't clobber bootloader RAM. */
289297 if (do_load ) {
290- /* Before loading segment, check it doesn't clobber bootloader RAM... */
291- uint32_t end_addr = load_addr + data_len ;
292- if ( end_addr < 0x40000000 ) {
298+ const intptr_t load_end = load_addr + data_len ;
299+ if ( load_end <= ( intptr_t ) SOC_DIRAM_DRAM_HIGH ) {
300+ /* Writing to DRAM */
293301 intptr_t sp = (intptr_t )get_sp ();
294- if (end_addr > sp - STACK_LOAD_HEADROOM ) {
295- ESP_LOGE (TAG , "Segment %d end address 0x%08x too high (bootloader stack 0x%08x liimit 0x%08x)" ,
296- index , end_addr , sp , sp - STACK_LOAD_HEADROOM );
302+ if (load_end > sp - STACK_LOAD_HEADROOM ) {
303+ /* Bootloader .data/.rodata/.bss is above the stack, so this
304+ * also checks that we aren't overwriting these segments.
305+ *
306+ * TODO: This assumes specific arrangement of sections we have
307+ * in the ESP32. Rewrite this in a generic way to support other
308+ * layouts.
309+ */
310+ ESP_LOGE (TAG , "Segment %d end address 0x%08x too high (bootloader stack 0x%08x limit 0x%08x)" ,
311+ index , load_end , sp , sp - STACK_LOAD_HEADROOM );
312+ return ESP_ERR_IMAGE_INVALID ;
313+ }
314+ } else {
315+ /* Writing to IRAM */
316+ const intptr_t loader_iram_start = (intptr_t ) & _loader_text_start ;
317+ const intptr_t loader_iram_end = (intptr_t ) & _loader_text_end ;
318+
319+ if (bootloader_util_regions_overlap (loader_iram_start , loader_iram_end ,
320+ load_addr , load_end )) {
321+ ESP_LOGE (TAG , "Segment %d (0x%08x-0x%08x) overlaps bootloader IRAM (0x%08x-0x%08x)" ,
322+ index , load_addr , load_end , loader_iram_start , loader_iram_end );
297323 return ESP_ERR_IMAGE_INVALID ;
298324 }
299325 }
300326 }
327+ #endif // BOOTLOADER_BUILD
328+
301329#ifndef BOOTLOADER_BUILD
302330 uint32_t free_page_count = spi_flash_mmap_get_free_pages (SPI_FLASH_MMAP_DATA );
303331 ESP_LOGD (TAG , "free data page_count 0x%08x" ,free_page_count );
0 commit comments