/* Headerless image format, written by compilers from February to April 2026. * * The image file holds only the code. Its read-only and read-write data are in * the optional sidecar files `.ro.data` and `.rw.data`, which the * compiler leaves out when a section is empty. Read-only data loads at * DATA_RO_OFFSET, code at the next word after it, and read-write data at * DATA_MEMORY_START. Execution starts at the first instruction. * * An image without the magic of another format is taken to be headerless. */ #include #include #include "hosted.h" #include "io.h" #include "riscv.h" #include "types.h" #ifndef PATH_MAX #define PATH_MAX 4096 #endif /* Load the sidecar file `.` at `offset`, which must end at or * before `limit`, and return its size. A missing sidecar is empty. */ static u32 load_sidecar( const char *path, const char *suffix, u32 offset, u32 limit ) { char sidecar[PATH_MAX]; if (snprintf(sidecar, sizeof(sidecar), "%s.%s", path, suffix) >= (int)sizeof(sidecar)) bail("image path too long: '%s'", path); FILE *file = fopen(sidecar, "rb"); if (!file) return 0; if (fseek(file, 0, SEEK_END) != 0) { fclose(file); bail("failed to seek '%s'", sidecar); } long size = ftell(file); if (size < 0 || fseek(file, 0, SEEK_SET) != 0) { fclose(file); bail("failed to determine the size of '%s'", sidecar); } if ((u64)offset + (u64)size > limit) { fclose(file); bail( "%s section too large: %ld bytes, at most %u bytes", suffix, size, limit - offset ); } image_read(file, offset, (u32)size, suffix); fclose(file); return (u32)size; } struct hosted_image image_raw_load( FILE *file, long file_size, const char *path, u32 data_limit ) { if (file_size % sizeof(instr_t) != 0) bail("unrecognized Radiance image: '%s'", path); u32 rodata_bytes = load_sidecar(path, "ro.data", DATA_RO_OFFSET, DATA_MEMORY_START); u32 program_base = align(DATA_RO_OFFSET + rodata_bytes, WORD_SIZE); if ((u64)program_base + (u64)file_size > DATA_MEMORY_START) bail("text section exceeds available program memory"); rewind(file); image_read(file, program_base, (u32)file_size, "text"); u32 data_bytes = load_sidecar(path, "rw.data", DATA_MEMORY_START, data_limit); return (struct hosted_image){ .code_base = program_base, .code_bytes = (u32)file_size, .data_bytes = data_bytes, }; }