load("@prelude//platforms:defs.bzl", "host_configuration")

export_file(
    name = "linker-script-riscv64",
    src = "linkers/riscv64-unknown-qemu.ld",
)

_DEPS = [
    "//sys/loader-api:loader-api",
    "//lib/abort:abort",
    "//lib/mem-core:mem-core",
    "//lib/arrayvec:arrayvec",
    "//lib/fdt:fdt",
    "//lib/spin:spin",
    # third-party dependencies
    "//third-party:log",
    "//third-party:cfg-if",
    "//third-party:lock_api",
] + select({
    # `loader-common` is bare-metal-only, and the host-side `frame-alloc-tests`
    # reuses `_DEPS`; riding the riscv64 loader branch (next to `riscv`) keeps it out
    # of the host build, where it would be incompatible and is unused anyway.
    "prelude//cpu/constraints:riscv64": [
        "//sys/loader-common:loader-common",
        "//lib/riscv:riscv",
    ],
    "DEFAULT": [],
})

_RUSTC_FLAGS = [
    "-Clink-arg=-T",
    "-Clink-arg=$(location :linker-script-riscv64)",
]

rust_binary(
    name = "loader-flat",
    srcs = glob(["src/**/*.rs"]),
    crate_root = "src/main.rs",
    rustc_flags = _RUSTC_FLAGS,
    deps = _DEPS,
    env = {
        "KERNEL": "$(location //sys/kernel:kernel)",
        "KERNEL_DEBUGINFO": "$(location //sys/kernel:kernel[debuginfo])"
    },
    target_compatible_with = ["prelude//cpu/constraints:riscv64"],
    incoming_transition = "//build:loader",
    visibility = ["PUBLIC"],
    tests = [":frame-alloc-tests"],
)

# on-target selftests build of the loader & kernel
rust_binary(
    name = "loader-flat-tests",
    srcs = glob(["src/**/*.rs"]),
    crate_root = "src/main.rs",
    rustc_flags = _RUSTC_FLAGS,
    deps = _DEPS,
    env = {
        "KERNEL": "$(location //sys/kernel:kernel-tests)",
        "KERNEL_DEBUGINFO": "$(location //sys/kernel:kernel-tests[debuginfo])"
    },
    target_compatible_with = ["prelude//cpu/constraints:riscv64"],
    incoming_transition = "//build:loader",
    visibility = ["PUBLIC"],
)

# Host-side unit/property tests for the bump frame allocator.
rust_test(
    name = "frame-alloc-tests",
    srcs = ["src/frame_alloc.rs"],
    crate_root = "src/frame_alloc.rs",
    crate = "frame_alloc",
    deps = _DEPS + [
        "//lib/mem-testkit:mem-testkit",
        "//third-party:parking_lot",
        "//third-party:proptest",
        "//lib/human-bytes:human-bytes",
        "//third-party:test-log",
        "//third-party:tracing-subscriber",
    ],
    env = {
        "PROPTEST_DISABLE_FAILURE_PERSISTENCE": "true",
    },
    target_compatible_with = [host_configuration.os, host_configuration.cpu],
    visibility = ["PUBLIC"],
)
