image_raw.c 2.6 KiB raw
1
/* Headerless image format, written by compilers from February to April 2026.
2
 *
3
 * The image file holds only the code. Its read-only and read-write data are in
4
 * the optional sidecar files `<image>.ro.data` and `<image>.rw.data`, which the
5
 * compiler leaves out when a section is empty. Read-only data loads at
6
 * DATA_RO_OFFSET, code at the next word after it, and read-write data at
7
 * DATA_MEMORY_START. Execution starts at the first instruction.
8
 *
9
 * An image without the magic of another format is taken to be headerless. */
10
#include <limits.h>
11
#include <stdio.h>
12
13
#include "hosted.h"
14
#include "io.h"
15
#include "riscv.h"
16
#include "types.h"
17
18
#ifndef PATH_MAX
19
#define PATH_MAX 4096
20
#endif
21
22
/* Load the sidecar file `<path>.<suffix>` at `offset`, which must end at or
23
 * before `limit`, and return its size. A missing sidecar is empty. */
24
static u32 load_sidecar(
25
    const char *path, const char *suffix, u32 offset, u32 limit
26
) {
27
    char sidecar[PATH_MAX];
28
    if (snprintf(sidecar, sizeof(sidecar), "%s.%s", path, suffix) >=
29
        (int)sizeof(sidecar))
30
        bail("image path too long: '%s'", path);
31
32
    FILE *file = fopen(sidecar, "rb");
33
    if (!file)
34
        return 0;
35
    if (fseek(file, 0, SEEK_END) != 0) {
36
        fclose(file);
37
        bail("failed to seek '%s'", sidecar);
38
    }
39
    long size = ftell(file);
40
    if (size < 0 || fseek(file, 0, SEEK_SET) != 0) {
41
        fclose(file);
42
        bail("failed to determine the size of '%s'", sidecar);
43
    }
44
    if ((u64)offset + (u64)size > limit) {
45
        fclose(file);
46
        bail(
47
            "%s section too large: %ld bytes, at most %u bytes",
48
            suffix,
49
            size,
50
            limit - offset
51
        );
52
    }
53
    image_read(file, offset, (u32)size, suffix);
54
    fclose(file);
55
    return (u32)size;
56
}
57
58
struct hosted_image image_raw_load(
59
    FILE *file, long file_size, const char *path, u32 data_limit
60
) {
61
    if (file_size % sizeof(instr_t) != 0)
62
        bail("unrecognized Radiance image: '%s'", path);
63
64
    u32 rodata_bytes =
65
        load_sidecar(path, "ro.data", DATA_RO_OFFSET, DATA_MEMORY_START);
66
    u32 program_base = align(DATA_RO_OFFSET + rodata_bytes, WORD_SIZE);
67
    if ((u64)program_base + (u64)file_size > DATA_MEMORY_START)
68
        bail("text section exceeds available program memory");
69
70
    rewind(file);
71
    image_read(file, program_base, (u32)file_size, "text");
72
    u32 data_bytes =
73
        load_sidecar(path, "rw.data", DATA_MEMORY_START, data_limit);
74
75
    return (struct hosted_image){
76
        .code_base  = program_base,
77
        .code_bytes = (u32)file_size,
78
        .data_bytes = data_bytes,
79
    };
80
}