cmake_minimum_required(VERSION 3.14)

add_subdirectory(../MEM_TEST_bsp MEM_TEST_bsp)

include(../MEM_TEST_bsp/toolchain.cmake)

project(MEM_TEST)

enable_language(ASM)
enable_language(C)
enable_language(CXX)

add_executable(MEM_TEST.elf)

target_sources(MEM_TEST.elf
    PRIVATE
        main.c
        mem_verify.c
)

target_include_directories(MEM_TEST.elf
    PRIVATE
    PUBLIC
)

target_link_libraries(MEM_TEST.elf
    PRIVATE
        -T "${BspLinkerScript}" -nostdlib
        "${ExtraArchiveLibraries}"
        -Wl,--start-group "${BspLibraryName}" -lc -lstdc++ -lgcc -lm -Wl,--end-group
)

# Create objdump from ELF.
set(objdump MEM_TEST.elf.objdump)
add_custom_command(
    OUTPUT "${objdump}"
    DEPENDS MEM_TEST.elf
    COMMAND "${ToolchainObjdump}" "${ToolchainObjdumpFlags}" MEM_TEST.elf >
            "${objdump}"
    COMMENT "Creating ${objdump}."
    VERBATIM
)
add_custom_target(create-objdump ALL DEPENDS "${objdump}")

# Report space free for stack + heap. Note that the file below is never created
# so the report is always output on build.
set(stack_report_file MEM_TEST.elf.stack_report)
add_custom_command(
    OUTPUT "${stack_report_file}"
    DEPENDS MEM_TEST.elf
    COMMAND niosv-stack-report -p "${ToolchainPrefix}" MEM_TEST.elf
    COMMENT "Reporting memory available for stack + heap in MEM_TEST.elf."
    VERBATIM
)
add_custom_target(niosv-stack-report ALL DEPENDS "${stack_report_file}")

# Generate HEX file(s) from MEM_TEST.elf using elf2hex tool.
# Note : If ECC Full is enabled, width of 39 is set for NiosV TCM. Otherwise, 32.
add_custom_command(
    OUTPUT "intel_onchip_memory.hex"
    DEPENDS MEM_TEST.elf
    COMMAND elf2hex MEM_TEST.elf -o intel_onchip_memory.hex -b 0x60000000 -w 32 -e 0x6007FFFF -r 4
    COMMENT "Creating intel_onchip_memory.hex."
    VERBATIM
)
add_custom_target(create-hex ALL DEPENDS "intel_onchip_memory.hex")
