image_rad0.c 2.7 KiB raw
1
/* "RAD0" version 1 image format, written by compilers from April to October
2
 * 2026.
3
 *
4
 * A 20-byte little-endian header, the magic "RAD0", the version 1 and the
5
 * sizes of the text, read-only data and read-write data sections, then the
6
 * bytes of the three sections in that order. Read-only data loads at
7
 * DATA_RO_OFFSET, text at the next word after it, and read-write data at
8
 * DATA_MEMORY_START. Execution starts at the first instruction. */
9
#include <stdio.h>
10
11
#include "hosted.h"
12
#include "io.h"
13
#include "riscv.h"
14
#include "types.h"
15
16
/* The ASCII bytes "RAD0" as a little-endian u32. */
17
#define RAD0_MAGIC       0x30444152U
18
/* The only version of the format. */
19
#define RAD0_VERSION     1U
20
/* Size of the header. */
21
#define RAD0_HEADER_SIZE 20U
22
23
bool image_rad0_match(const u8 *header, size_t len) {
24
    return len >= sizeof(u32) && decode_u32_le(header) == RAD0_MAGIC;
25
}
26
27
struct hosted_image image_rad0_load(
28
    FILE *file, long file_size, u32 data_limit
29
) {
30
    u8 header[RAD0_HEADER_SIZE];
31
    rewind(file);
32
    if (fread(header, 1, sizeof(header), file) != sizeof(header))
33
        bail("truncated Radiance image header");
34
35
    u32 version = decode_u32_le(&header[4]);
36
    if (version != RAD0_VERSION)
37
        bail("unsupported Radiance image version: %u", version);
38
39
    u32 program_bytes = decode_u32_le(&header[8]);
40
    u32 rodata_bytes  = decode_u32_le(&header[12]);
41
    u32 data_bytes    = decode_u32_le(&header[16]);
42
    if (program_bytes == 0 || program_bytes % sizeof(instr_t) != 0)
43
        bail("invalid text section size in Radiance image: %u", program_bytes);
44
45
    u64 image_size =
46
        (u64)RAD0_HEADER_SIZE + program_bytes + rodata_bytes + data_bytes;
47
    if (image_size != (u64)file_size)
48
        bail(
49
            "Radiance image size does not match header: file has %ld "
50
            "bytes, header requires %llu",
51
            file_size,
52
            (unsigned long long)image_size
53
        );
54
    if ((u64)DATA_RO_OFFSET + rodata_bytes > DATA_MEMORY_START)
55
        bail("read-only data section exceeds available program memory");
56
57
    u32 program_base = align(DATA_RO_OFFSET + rodata_bytes, WORD_SIZE);
58
    if ((u64)program_base + program_bytes > DATA_MEMORY_START)
59
        bail("text section exceeds available program memory");
60
    if ((u64)DATA_MEMORY_START + data_bytes > data_limit)
61
        bail("read-write data section exceeds available data memory");
62
63
    image_read(file, program_base, program_bytes, "text");
64
    image_read(file, DATA_RO_OFFSET, rodata_bytes, "read-only data");
65
    image_read(file, DATA_MEMORY_START, data_bytes, "read-write data");
66
67
    return (struct hosted_image){
68
        .code_base  = program_base,
69
        .code_bytes = program_bytes,
70
        .data_bytes = data_bytes,
71
    };
72
}