/* Kernel link layout — higher half.
 *
 * The kernel is linked to *run* in the higher half (virtual base
 * 0xFFFF_FFFF_8000_0000, matching danos.kernel_virt_base and build.zig's
 * image_base) but is *loaded* low. Each section's load address (LMA) is its
 * virtual address minus KERNEL_VIRT_BASE via AT(), so the ELF's p_paddr lands
 * at a low physical address (.text at 1 MiB) that the loader can allocate and
 * copy into. The loader maps p_vaddr (high) -> p_paddr (low) in its bootstrap
 * tables and jumps to the high entry; the kernel then builds its own tables
 * with the physmap and abandons the identity map. Requires LLD (build.zig pins
 * it) — the self-hosted linker ignores PHDRS/AT()/section order.
 */

KERNEL_VIRT_BASE = 0xFFFFFFFF80000000;

ENTRY(_start)

/* One loadable segment per permission set, so the loader can map .text as R+X,
 * .rodata as R, and .data/.bss as R+W. FLAGS bits: 1=X, 2=W, 4=R. */
PHDRS {
    text   PT_LOAD FLAGS(5); /* R + X */
    rodata PT_LOAD FLAGS(4); /* R     */
    data   PT_LOAD FLAGS(6); /* R + W */
}

SECTIONS {
    .text ALIGN(4K) : AT(ADDR(.text) - KERNEL_VIRT_BASE) {
        *(.text .text.*)
    } :text

    .rodata ALIGN(4K) : AT(ADDR(.rodata) - KERNEL_VIRT_BASE) {
        *(.rodata .rodata.*)
    } :rodata

    .data ALIGN(4K) : AT(ADDR(.data) - KERNEL_VIRT_BASE) {
        *(.data .data.*)
    } :data

    /* .bss occupies memory but not file space. The loader zeroes it via the
     * gap between each PT_LOAD segment's file size and memory size, so no
     * boundary symbols are needed here. */
    .bss ALIGN(4K) : AT(ADDR(.bss) - KERNEL_VIRT_BASE) {
        *(.bss .bss.*)
        *(COMMON)
    } :data

    /DISCARD/ : {
        *(.comment)
        *(.note .note.*)
        *(.eh_frame .eh_frame_hdr)
    }
}
