/* "RAD0" version 1 image format, written by compilers from April to October * 2026. * * A 20-byte little-endian header, the magic "RAD0", the version 1 and the * sizes of the text, read-only data and read-write data sections, then the * bytes of the three sections in that order. Read-only data loads at * DATA_RO_OFFSET, text at the next word after it, and read-write data at * DATA_MEMORY_START. Execution starts at the first instruction. */ #include #include "hosted.h" #include "io.h" #include "riscv.h" #include "types.h" /* The ASCII bytes "RAD0" as a little-endian u32. */ #define RAD0_MAGIC 0x30444152U /* The only version of the format. */ #define RAD0_VERSION 1U /* Size of the header. */ #define RAD0_HEADER_SIZE 20U bool image_rad0_match(const u8 *header, size_t len) { return len >= sizeof(u32) && decode_u32_le(header) == RAD0_MAGIC; } struct hosted_image image_rad0_load( FILE *file, long file_size, u32 data_limit ) { u8 header[RAD0_HEADER_SIZE]; rewind(file); if (fread(header, 1, sizeof(header), file) != sizeof(header)) bail("truncated Radiance image header"); u32 version = decode_u32_le(&header[4]); if (version != RAD0_VERSION) bail("unsupported Radiance image version: %u", version); u32 program_bytes = decode_u32_le(&header[8]); u32 rodata_bytes = decode_u32_le(&header[12]); u32 data_bytes = decode_u32_le(&header[16]); if (program_bytes == 0 || program_bytes % sizeof(instr_t) != 0) bail("invalid text section size in Radiance image: %u", program_bytes); u64 image_size = (u64)RAD0_HEADER_SIZE + program_bytes + rodata_bytes + data_bytes; if (image_size != (u64)file_size) bail( "Radiance image size does not match header: file has %ld " "bytes, header requires %llu", file_size, (unsigned long long)image_size ); if ((u64)DATA_RO_OFFSET + rodata_bytes > DATA_MEMORY_START) bail("read-only data section exceeds available program memory"); u32 program_base = align(DATA_RO_OFFSET + rodata_bytes, WORD_SIZE); if ((u64)program_base + program_bytes > DATA_MEMORY_START) bail("text section exceeds available program memory"); if ((u64)DATA_MEMORY_START + data_bytes > data_limit) bail("read-write data section exceeds available data memory"); image_read(file, program_base, program_bytes, "text"); image_read(file, DATA_RO_OFFSET, rodata_bytes, "read-only data"); image_read(file, DATA_MEMORY_START, data_bytes, "read-write data"); return (struct hosted_image){ .code_base = program_base, .code_bytes = program_bytes, .data_bytes = data_bytes, }; }