aboutsummaryrefslogtreecommitdiffstats
path: root/sysload.c
blob: d4c1d08634bcff539b3900cb918137169c4ecfdb (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
/*
 * Load a file into memory. The syntax is:
 *
 * [[memspace][@address][,format],]filename
 *
 * If "format" is unspecified, this code will automatically try to detect
 * one of Intel Hex, S-records, or binary.
 *
 * The memory spaces supported are:
 *
 * null  - discard
 * rom	 - BASIC, DOS, option ROM, printer ROM, etc.
 *         loads into both rom40 and rom80 space for the first 16K (ABC80 only)
 * rom40 - 40-character BASIC ROM
 * rom80 - 80-character BASIC ROM
 * ram   - regular working memory; includes paged-out memory
 *         (ABC80 > 32K, ABC802 etc.)
 * vram  - text video memory
 * cpu   - memory as seen by CPU
 *
 * Not yet implemented:
 *    sram  - auxiliary SRAM for ABC80 128K+
 *    fg/hr - high res graphics memory
 */

#include "compiler.h"
#include "sysload.h"
#include "hostfile.h"

/* Namespace definition */
struct load_data {
    const char *name;		/* memspace name */
    const char *dump_name;	/* name when dumping to a file */
    const struct load_data *next;
    load_op load_op;
    dump_op dump_op;
    void *buf;
    uint32_t mask;
    uint32_t limit;
};

/* No operations will ever be called when limit == 0 */
static struct load_data memspace_null =
{ "null", "null", NULL, NULL, NULL, NULL, 0, 0 };
static const struct load_data *memspaces = &memspace_null;

static inline uint32_t
write_byte(const struct load_data *ws, uint32_t addr, uint8_t val)
{
    if (likely(addr < ws->limit)) {
	addr &= ws->mask;
	if (!ws->load_op) {
	    uint8_t *p = ws->buf;
	    p[addr] = val;
	} else {
	    ws->load_op(ws->buf, addr, val);
	}
    }
    return addr + 1;
}

static uint32_t load_data(const struct load_data *ws, uint32_t addr,
			   const uint8_t *data, unsigned int len)
{
    while (len--)
	addr = write_byte(ws, addr, *data++);
    return addr;
}

/*
 * Return the hex value of a single character, or negative if invalid.
 * The hex digit must be upper case or considered invalid.
 */
static inline int hexval(int c)
{
    if (c <= '9')
	return c - '0';
    if (c < 'A')
	return -1;
    if (c <= 'F')
	return c - 'A' + 10;
    return -1;
}

static inline bool is_eoln(int c)
{
    return c == '\n' || c == '\r';
}

static inline bool is_eof(int c)
{
    return c == EOF || c == ('Z' & 0x1f);
}

static inline bool is_white(int c)
{
    return (c >= '\a' && c <= '\r') || c == 0x7f || c == 0xff;
}

static int load_ihex(FILE *file, const struct load_data *ws, uint32_t offset)
{

    int c;
    int hval = 0;
    int bytes = 0;
    int left = 0;
    int lpos = 0;
    uint8_t ldata[255+5];	/* Record data including metadata */
    uint8_t *p = NULL;
    uint8_t csum = 0;
    uint32_t baseaddr = 0;

    rewind(file);

    while (1) {
	if (ferror(file))
	    return -1;

	c = fgetc(file);

	/* End of line/end of file? */
	if (is_eoln(c) || is_eof(c)) {
	    if (lpos > 0) {
		unsigned int len = ldata[0];
		uint32_t laddr = (ldata[1] << 8) + ldata[2];
		uint8_t ltype = ldata[3];

		if (csum)
		    return -1;	/* Invalid checksum */

		if (left)
		    return -1;	/* Truncated record */

		switch (ltype) {
		case 0:		/* Data */
		{
		    uint32_t addr = laddr + baseaddr;
		    load_data(ws, addr + offset, ldata+4, len);
		    bytes += len;
		    break;
		}

		case 1:		/* End of file */
		    return (len == 0) ? bytes : -1;

		case 2:		/* Segment address */
		    if (len != 2)
			return -1;
		    baseaddr = laddr << 4;
		    break;

		case 4:		/* Linear address */
		    if (len != 2)
			return -1;
		    baseaddr = laddr << 16;
		    break;

		case 3:		/* Start address CS:IP */
		case 5:		/* Start address linear */
		    if (len != 4)
			return -1;
		    /* Otherwise ignore */
		    break;

		default:	/* Unknown record type */
		    return -1;
		}
	    }

	    if (is_eof(c))
		return bytes;	/* Done! */

	    lpos = 0;
	    continue;
	}

	/* Whitespace or similar? */
	if (is_white(c))
	    continue;

	/* All other control characters -> invalid, even in apparent comment */
	if (c < ' ')
	    return -1;

	/* Skip this line (comment?) */
	if (lpos < 0)
	    continue;

	/* Seems line a comment? */
	if (c == ';' || c == '#') {
	    lpos = -1;
	    continue;
	}

	if (!lpos) {
	    if (c != ':')
		return -1;	/* Invalid */
	    hval = 0;
	    left = 5;		/* Length of header+checksum in bytes */
	    csum = 0;
	    p = ldata;
	} else {
	    int hdig = hexval(c);

	    if (hdig < 0)
		return hdig;	/* Invalid */

	    hval = (hval << 4) + hdig;

	    if (lpos & 1)
		continue;	/* Middle of a byte */

	    if (!left)
		return -1;	/* Overrun */

	    *p++ = hval;
	    csum += hval;
	    left--;
	    if (lpos == 2)
		left += hval; /* Add data length to bytes needed */
	    hval = 0;
	}
	lpos++;
    }
}

static int load_srec(FILE *file, const struct load_data *ws, uint32_t offset)
{
    int c;
    int hval = 0;
    int bytes = 0;
    int left = 0;
    int lpos = 0;
    uint8_t ldata[255+7];	/* Record data including metadata */
    uint8_t *p = NULL;
    uint8_t csum = 0;

    rewind(file);

    while (1) {
	if (ferror(file))
	    return -1;

	c = fgetc(file);

	/* End of line/end of file? */
	if (is_eoln(c) || is_eof(c)) {
	    if (lpos > 0) {
		static const int addrlen[10] =
		    { 2, 2, 3, 4, 2, 2, 3, 4, 3, 4 };
		unsigned int ltype = p[0];
		int len = p[1];
		int alen = addrlen[p[0]];
		uint32_t addr = 0;
		const uint8_t *dp;

		if (left)
		    return -1;	/* Truncated record */

		len -= alen + 1; /* Count data bytes only */
		if (len < 0) {
		    /* Record too short: need minimum address + checksum */
		    return -1;
		}

		/* Note: type is not included in the checksum */
		if (csum - ltype != 0xff)
		    return -1;	/* Invalid checksum */

		dp = ldata+2;	/* Address field */
		addr = 0;
		while (alen--)
		    addr = (addr << 8) + *dp++;

		switch (ldata[0]) {
		case 0:
		case 4:
		case 5:
		case 6:
		    /* Ignore record */
		    break;
		case 1:
		case 2:
		case 3:
		    /* Data record */
		    load_data(ws, addr + offset, dp, len);
		    bytes += len;
		    break;
		case 7:
		case 8:
		case 9:
		    /* Start of program, also end of file */
		    return bytes;
		}
	    }

	    if (is_eof(c))
		return bytes;	/* Done! */

	    lpos = 0;
	    continue;
	}

	/* Whitespace or similar? */
	if (is_white(c))
	    continue;

	/* All other control characters -> invalid, even in apparent comment */
	if (c < ' ')
	    return -1;

	/* Skip this line (comment?) */
	if (lpos < 0)
	    continue;

	/* Seems line a comment? */
	if (c == ';' || c == '#') {
	    lpos = -1;
	    continue;
	}

	if (!lpos) {
	    if (c != 'S')
		return -1;	/* Invalid */
	    hval = 0;
	    left = 2;		/* Type and byte count */
	    csum = 0;
	    p = ldata;
	} else {
	    int hdig = hexval(c);

	    if (hdig < 0)
		return hdig;	/* Invalid */

	    hval = (hval << 4) + hdig;

	    /*
	     * The ! here is correct. The first "byte" is the type,
	     * which has only one digit.
	     */
	    if (!(lpos & 1))
		continue;	/* Middle of a byte */

	    if (!left)
		return -1;	/* Overrun */

	    *p++ = hval;
	    csum += hval;
	    left--;
	    if (lpos == 3)
		left += hval;	/* Add byte count for rest of record */

	    hval = 0;
	}
	lpos++;
    }
}

static int load_bin(FILE *file, const struct load_data *ws, uint32_t addr)
{
    int c;
    int bytes = 0;

    rewind(file);

    while (1) {
	if (ferror(file))
	    return -1;
	c = fgetc(file);
	if (c == EOF)
	    return bytes;
	addr = write_byte(ws, addr, c);
	bytes++;
    }
}

void sysload_add_memspace(const char *name, load_op load_op, dump_op dump_op,
			  void *buf, uint32_t mask, uint32_t limit)
{
    struct load_data *ws;

    ws = calloc(1, sizeof *ws);
    if (!ws)
	return;

    ws->name = name;
    ws->dump_name = !strcmp(name, "cpu") ? "mem" : name; /* Historic */
    ws->load_op = load_op;
    ws->dump_op = dump_op;
    ws->buf = buf;
    ws->mask = mask;
    ws->limit = limit;
    ws->next = memspaces;
    memspaces = ws;
}

static const struct load_data *get_memspace(const char *name, size_t len)
{
    const struct load_data *ws;

    for (ws = memspaces; ws; ws = ws->next) {
	if (!strncmp(ws->name, name, len) && !ws->name[len])
	    return ws;
    }
    return NULL;
}

typedef int (*load_func)(FILE *file, const struct load_data *ws, uint32_t addr);

struct file_format {
    const char *name;
    load_func loader;
};

static const struct file_format file_formats[] =
{
    { "ihex", load_ihex },
    { "srec", load_srec },
    { "bin",  load_bin },
    { "any",  NULL }
};

/* Iterates through the loaders until one succeeds */
static int load_any(FILE *file, const struct load_data *ws, uint32_t addr)
{
    const struct file_format *fmt;
    int bytes = -1;

    for (fmt = file_formats; fmt->loader; fmt++) {
	/* Validate the file contents by loading to null */
	if (fmt->loader(file, &memspace_null, addr) < 0)
	    continue;

	bytes = fmt->loader(file, ws, addr);
	if (bytes >= 0)
	    break;
    }
    return bytes;
}

int load_sysfile(const char *filespec)
{
    FILE *f;
    const char *p = filespec;
    const char *comma;
    const struct load_data *ws;
    load_func loader = NULL;
    uint32_t addr = 0;
    int rv;

    ws = get_memspace("cpu", 3);

    while ((comma = strchr(p, ','))) {
	const struct load_data *wms;
	const struct file_format *fmt;
	size_t len = comma-p;
	const char *at = strchr(p, '@');

	if (at && at < comma) {
	    char *ep;
	    addr = strtoul(at+1, &ep, 0);
	    if (ep != comma)
		return -1;
	    len = at-p;
	}

	wms = get_memspace(p, len);
	if (wms) {
	    ws = wms;
	    goto next;
	}

	fmt = file_formats;
	do {
	    if (!strncmp(fmt->name, p, len) && !fmt->name[len]) {
		loader = fmt->loader;
		goto next;
	    }
	} while ((fmt++)->loader);

	/* Doesn't match anything, assume it is actually the filename */
	break;

    next:
	p = comma+1;
	continue;
    }

    if (!ws)
	return -1;		/* No memspace, and "cpu" undefined */

    f = fopen(p, "rb");
    if (!f) {
	fprintf(stderr, "Can't open file: %s: %s\n",
		p, strerror(errno));
	return -1;
    }

    if (!loader)
	rv = load_any(f, ws, addr);
    else
	rv = loader(f, ws, addr);

    fclose(f);

    return rv;
}


/*
 * Dump an arbitrary memory namespace space to a file
 */
const char *memdump_path;

void dump_memory(const char *namespace)
{
    const struct load_data *ws;
    struct host_file *hf;
    struct dump_data dd;
    uint32_t addr, limit;

    ws = get_memspace(namespace, strlen(namespace));
    if (!ws)
	return;			/* Nothing to dump */

    limit = ws->limit & ws->mask;
    if (!limit)
	return;			/* Empty namespace */

    hf = dump_file(HF_BINARY, memdump_path, ws->dump_name, ".bin");
    if (!hf)
        return;

    if (!ws->dump_op) {
	fwrite(ws->buf, 1, ws->limit, hf->f);
    } else {
	addr = 0;
	while (addr < limit) {
	    dd = ws->dump_op(ws->buf, addr);
	    fwrite(dd.data, 1, dd.len, hf->f);
	    addr += dd.len;
	}
    }

    if (!ferror(hf->f))
        keep_file(hf);          /* It's good */

    close_file(&hf);
}