summaryrefslogtreecommitdiff
path: root/misc/kassemble.c
blob: a818cc50f9ab156cb385c968f8e4a311830c109e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <errno.h>

int main(int argc, char **argv) {
    if (argc != 4) {
        fprintf(stderr, "usage: %s <in> <out> <image_size>\n", argv[0]);
        return 1;
    }

    const char *in_path  = argv[1];
    const char *out_path = argv[2];
    char *end;
    errno = 0;
    unsigned long long size = strtoull(argv[3], &end, 16);
    if (errno || *end != '\0') {
        fprintf(stderr, "bad size: %s, invalid chars: %s\n", argv[3], end);
        return 1;
    }

    FILE *in = fopen(in_path, "rb");
    if (!in) { perror("fopen in"); return 1; }

    FILE *out = fopen(out_path, "wb");
    if (!out) { perror("fopen out"); fclose(in); return 1; }

    /* Copy in -> out */
    unsigned char buf[65536];
    size_t n;
    while ((n = fread(buf, 1, sizeof buf, in)) > 0) {
        if (fwrite(buf, 1, n, out) != n) { perror("fwrite"); return 1; }
    }
    if (ferror(in)) { perror("fread"); return 1; }

    /* Write size as u64 little-endian at offset 16 */
    unsigned char le[8];
    for (int i = 0; i < 8; i++)
        le[i] = (unsigned char)(size >> (8 * i));

    if (fseek(out, 16, SEEK_SET) != 0) { perror("fseek"); return 1; }
    if (fwrite(le, 1, 8, out) != 8)    { perror("fwrite size"); return 1; }

    fclose(in);
    if (fclose(out) != 0) { perror("fclose out"); return 1; }
    return 0;
}