/*
 * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Apache-2.0
 */

/* TODO: [ESP32H4] IDF-12305 inherited from verification branch, need check */

#include "ld.common"

/* Default entry point */
ENTRY(call_start_cpu0);

SECTIONS
{

  .iram0.text :
  {
    _iram_start = ABSOLUTE(.);
    /* Vectors go to start of IRAM */
    ASSERT(ABSOLUTE(.) % 0x40 == 0, "vector address must be 64 byte aligned");
    KEEP(*(.exception_vectors_table.text));
    KEEP(*(.exception_vectors.text));

    /* Code marked as running out of IRAM */
    _iram_text_start = ABSOLUTE(.);

    mapping[iram0_text]

  } > sram_seg

  /* Marks the end of IRAM code segment */
  .iram0.text_end (NOLOAD) :
  {
    /* Align the end of code region as per PMP region granularity */
    . = ALIGN(_esp_pmp_align_size);

    ALIGNED_SYMBOL(4, _iram_text_end)
  } > sram_seg

  .iram0.data :
  {
    ALIGNED_SYMBOL(16, _iram_data_start)

    mapping[iram0_data]

    _iram_data_end = ABSOLUTE(.);
  } > sram_seg

  .iram0.bss (NOLOAD) :
  {
    ALIGNED_SYMBOL(16, _iram_bss_start)

    mapping[iram0_bss]

    _iram_bss_end = ABSOLUTE(.);
    ALIGNED_SYMBOL(16, _iram_end)
  } > sram_seg

  .dram0.data :
  {
    _data_start = ABSOLUTE(.);
    *(.gnu.linkonce.d.*)
    *(.data1)
    __global_pointer$ = . + 0x800;
    *(.sdata)
    *(.sdata.*)
    *(.gnu.linkonce.s.*)
    *(.gnu.linkonce.s2.*)
    *(.jcr)

    mapping[dram0_data]

    _data_end = ABSOLUTE(.);
  } > sram_seg

  /**
   * This section holds data that should not be initialized at power up.
   * The section located in Internal SRAM memory region. The macro _NOINIT
   * can be used as attribute to place data into this section.
   * See the "esp_attr.h" file for more information.
   */
  .noinit (NOLOAD):
  {
    ALIGNED_SYMBOL(4, _noinit_start)

    *(.noinit .noinit.*)

    ALIGNED_SYMBOL(4, _noinit_end)
  } > sram_seg

  /* Shared RAM */
  .dram0.bss (NOLOAD) :
  {
    ALIGNED_SYMBOL(8, _bss_start)

    /**
     * ldgen places all bss-related data to mapping[dram0_bss]
     * (See components/esp_system/app.lf).
     */
    mapping[dram0_bss]

    ALIGNED_SYMBOL(8, _bss_end)
  } > sram_seg

  ASSERT(((_bss_end - ORIGIN(sram_seg)) <= LENGTH(sram_seg)), "DRAM segment data does not fit.")

  .flash.text :
  {
    _stext = .;
    /**
     * Mark the start of flash.text.
     * This can be used by the MMU driver to maintain the virtual address.
     */
    _instruction_reserved_start = ABSOLUTE(.);
    _text_start = ABSOLUTE(.);

    mapping[flash_text]

    *(.stub)
    *(.gnu.linkonce.t.*)
    *(.gnu.warning)
    *(.irom0.text) /* catch stray ICACHE_RODATA_ATTR */

    /**
     * CPU will try to prefetch up to 16 bytes of of instructions.
     * This means that any configuration (e.g. MMU, PMS) must allow
     * safe access to up to 16 bytes after the last real instruction, add
     * dummy bytes to ensure this
     */
    . += _esp_flash_mmap_prefetch_pad_size;

    _text_end = ABSOLUTE(.);
    /**
     * Mark the flash.text end.
     * This can be used for MMU driver to maintain virtual address.
     */
    _instruction_reserved_end = ABSOLUTE(.);
    _etext = .;

    /**
     * Similar to _iram_start, this symbol goes here so it is
     * resolved by addr2line in preference to the first symbol in
     * the flash.text segment.
     */
    _flash_cache_start = ABSOLUTE(0);
  } > default_code_seg

  /**
   * Dummy section represents the .flash.text section but in default_rodata_seg.
   * Thus, it must have its alignment and (at least) its size.
   */
  .flash_rodata_dummy (NOLOAD):
  {
    _flash_rodata_dummy_start = .;

    . = ALIGN(ALIGNOF(.flash.text)) + SIZEOF(.flash.text);

    /* Add alignment of MMU page size + 0x20 bytes for the mapping header. */
    . = ALIGN(_esp_mmu_page_size) + 0x20;
  } > default_rodata_seg

  .flash.appdesc : ALIGN(0x10)
  {
    /**
     * Mark flash.rodata start.
     * This can be used for mmu driver to maintain virtual address
     */
    _rodata_reserved_start = ABSOLUTE(.);
    _rodata_start = ABSOLUTE(.);

    /* !DO NOT PUT ANYTHING BEFORE THIS! */

    /* Should be the first.  App version info. */
    *(.rodata_desc .rodata_desc.*)
    /* Should be the second. Custom app version info. */
    *(.rodata_custom_desc .rodata_custom_desc.*)

    /**
     * Create an empty gap within this section. Thanks to this, the end of this
     * section will match .flash.rodata's begin address. Thus, both sections
     * will be merged when creating the final bin image.
     */
    . = ALIGN(ALIGNOF(.flash.rodata));
  } > default_rodata_seg
  ASSERT_SECTIONS_GAP(.flash.appdesc, .flash.rodata)

  .flash.rodata : ALIGN(0x10)
  {
    _flash_rodata_start = ABSOLUTE(.);

    mapping[flash_rodata]

#if CONFIG_LIBC_PICOLIBC
    *(.got .got.plt) /* TODO: GCC-439 */
#endif
    *(.irom1.text) /* catch stray ICACHE_RODATA_ATTR */
    *(.gnu.linkonce.r.*)
    *(.rodata1)
    *(.gcc_except_table .gcc_except_table.*)
    *(.gnu.linkonce.e.*)
    /**
     * C++ constructor tables.
     *
     * Excluding crtbegin.o/crtend.o since IDF doesn't use the toolchain crt.
     *
     * RISC-V gcc is configured with --enable-initfini-array so it emits
     * .init_array section instead. But the init_priority sections will be
     * sorted for iteration in ascending order during startup.
     * The rest of the init_array sections is sorted for iteration in descending
     * order during startup, however. Hence a different section is generated for
     * the init_priority functions which is iterated in ascending order during
     * startup. The corresponding code can be found in startup.c.
     */
    ALIGNED_SYMBOL(4, __init_priority_array_start)
    KEEP (*(EXCLUDE_FILE (*crtend.* *crtbegin.*) .init_array.*))
    __init_priority_array_end = ABSOLUTE(.);

    ALIGNED_SYMBOL(4, __init_array_start)
    KEEP (*(EXCLUDE_FILE (*crtend.* *crtbegin.*) .init_array))
    __init_array_end = ABSOLUTE(.);

    /* Addresses of memory regions reserved via SOC_RESERVE_MEMORY_REGION() */
    ALIGNED_SYMBOL(4, soc_reserved_memory_region_start)
    KEEP (*(.reserved_memory_address))
    soc_reserved_memory_region_end = ABSOLUTE(.);

    /* System init functions registered via ESP_SYSTEM_INIT_FN */
    ALIGNED_SYMBOL(4, _esp_system_init_fn_array_start)
    KEEP (*(SORT_BY_INIT_PRIORITY(.esp_system_init_fn.*)))
    _esp_system_init_fn_array_end = ABSOLUTE(.);

    _rodata_end = ABSOLUTE(.);
    . = ALIGN(ALIGNOF(SECTION_AFTER_FLASH_RODATA));
  } > default_rodata_seg
  ASSERT_SECTIONS_GAP(.flash.rodata, SECTION_AFTER_FLASH_RODATA)

#if EH_FRAME_LINKING_ENABLED
  .eh_frame_hdr :
  {
    ALIGNED_SYMBOL(4, __eh_frame_hdr)

    KEEP (*(.eh_frame_hdr))

    __eh_frame_hdr_end = ABSOLUTE(.);

    . = ALIGN(ALIGNOF(.eh_frame));
  } > default_rodata_seg
  ASSERT_SECTIONS_GAP(.eh_frame_hdr, .eh_frame)

  .eh_frame :
  {
    ALIGNED_SYMBOL(4, __eh_frame)

    KEEP (*(.eh_frame))
    /**
     * As we are not linking with crtend.o, which includes the CIE terminator
     * (see __FRAME_END__ in libgcc sources), it is manually provided here.
     */
    LONG(0);

    __eh_frame_end = ABSOLUTE(.);

    . = ALIGN(ALIGNOF(.flash.tdata));
  } > default_rodata_seg
  ASSERT_SECTIONS_GAP(.eh_frame, .flash.tdata)
#endif // EH_FRAME_LINKING_ENABLED

  .flash.tdata :
  {
    /* Keep tdata and tbss sections contiguous (no gaps between them).
     * The TLS runtime code calculates offsets assuming these sections are
     * adjacent. Gaps would cause incorrect address calculations, leading
     * to accessing wrong memory.
     */
    /* tdata sections */
    _thread_local_data_start = ABSOLUTE(.);
#if CONFIG_LIBC_PICOLIBC
    _picolibc_reent_stub_start = ABSOLUTE(.);
    KEEP(*(.tdata.errno))
#if CONFIG_LIBC_PICOLIBC_NEWLIB_COMPATIBILITY
    /* Reproduce the public fields from struct _reent. */
    KEEP(*(.tdata.tls_stdin))
    KEEP(*(.tdata.tls_stdout))
    KEEP(*(.tdata.tls_stderr))
#endif // CONFIG_LIBC_PICOLIBC_NEWLIB_COMPATIBILITY
    _picolibc_reent_stub_end = ABSOLUTE(.);
#endif // CONFIG_LIBC_PICOLIBC
    *(.tdata .tdata.* .gnu.linkonce.td.*)
    . = ALIGN(ALIGNOF(.flash.tbss));
    _thread_local_data_end = ABSOLUTE(.);
  } > default_rodata_seg
  ASSERT_SECTIONS_GAP(.flash.tdata, .flash.tbss)
  ASSERT_PICOLIBC_REENT_STUB()

  .flash.tbss (NOLOAD) :
  {
    /* tbss sections */
    _thread_local_bss_start = ABSOLUTE(.);
    *(.tbss .tbss.* .gnu.linkonce.tb.*)
    *(.tcommon .tcommon.*)
    _thread_local_bss_end = ABSOLUTE(.);
  } > default_rodata_seg
  ASSERT(_thread_local_data_end == _thread_local_bss_start,
         "tdata and tbss must be contiguous.")

  /**
   * This section contains all the rodata that is not used
   * at runtime, helping to avoid an increase in binary size.
   */
  .flash.rodata_noload (NOLOAD) :
  {
    /**
     * This symbol marks the end of flash.rodata. It can be utilized by the MMU
     * driver to maintain the virtual address.
     * NOLOAD rodata may not be included in this section.
     */
    _rodata_reserved_end = .;

    mapping[rodata_noload]
  } > default_rodata_seg

  /* Marks the end of data, bss and possibly rodata */
  .dram0.heap_start (NOLOAD) :
  {
    ALIGNED_SYMBOL(16, _heap_start)
  } > sram_seg

#include "elf_misc.ld.in"
}

ASSERT(((_iram_end - ORIGIN(sram_seg)) <= LENGTH(sram_seg)),
          "IRAM0 segment data does not fit.")

ASSERT(((_heap_start - ORIGIN(sram_seg)) <= LENGTH(sram_seg)),
          "DRAM segment data does not fit.")
