summaryrefslogtreecommitdiff
path: root/misc/sims/z80sim/src/main.c
blob: 9312b7509a4787b41a7d9820273eccb84c90fee0 (plain) (blame)
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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#include <errno.h>

#include "Z80.h"

/* This is the simulated z80 16-bit address space */

static unsigned char memory[65536];

/* This is the simulatin execution context */

static Z80 gR;

/* Command line options */

static int gtrace = 0;
static const char *gfilename = NULL;

/* Name:        RdZ80 and WrZ80
 * Description: These functions are called when access to RAM occurs.
 *              They allow to control memory access.
 */

void WrZ80(register word Addr, register byte Value)
{
	memory[Addr] = Value;
}

byte RdZ80(register word Addr)
{
	return memory[Addr];
}

/* Name:        InZ80 and OutZ80
 * Description: Z80 emulation calls these functions to read/write from
 *              I/O ports. There can be 65536 I/O ports, but only first
 *              256 are usually used.
 */

void OutZ80(register word Port,register byte Value)
{
	/* We recognize only one port, 0xbe, which is mapped to stdout */

	if ((Port & 0x00ff) == 0xbe)
	{
		putchar(Value);
		fflush(stdout);
	}
}

byte InZ80(register word Port)
{
	/* We recognize only one port, 0xbe, which is mapped to stdin */

	if ((Port & 0x00ff) == 0xbe)
	{
		return getchar();
	}
	return 0;
}

/* Name:        PatchZ80
 * Description: Z80 emulation calls this function when it encounters a
 *              special patch command (ED FE) provided for user needs.
 *              For example, it can be called to emulate BIOS calls,
 *              such as disk and tape access. Replace it with an empty
 *              macro for no patching.
 */

void PatchZ80(register Z80 *R)
{
}

/* Name:        LoopZ80
 * Description: Z80 emulation calls this function periodically to check
 *              if the system hardware requires any interrupts. This
 *              function must return an address of the interrupt vector
 *              (0x0038, 0x0066, etc.) or INT_NONE for no interrupt.
 *               Return INT_QUIT to exit the emulation loop.
 */

word LoopZ80(register Z80 *R)
{
	return INT_NONE;
}

/* Name:        JumpZ80
 * Description: Z80 emulation calls this function when it executes a
 *              JP, JR, CALL, RST, or RET. You can use JumpZ80() to
 *              trap these opcodes and switch memory layout.
 */

#ifdef JUMPZ80
void JumpZ80(word PC)
{
	if (gtrace)
	{
		printf("PC: %04X [%02X] HL: %04X SP: %04X [%04X, %04X, ...]\n",
			gR.PC.W, memory[gR.PC.W], gR.HL.W, gR.SP.W,
			((int)memory[gR.SP.W]   | ((int)memory[gR.SP.W+1]) << 8),
			((int)memory[gR.SP.W+2] | ((int)memory[gR.SP.W+3]) << 8));
	}
}
#endif

/* Intel hex code based largely on code taken from the PJRC website.
 * Licensing requires the following:
 *
 * Author:  Paul Stoffregen
 * Contact: paul@ece.orst.edu
 */

/* Name:        parse_hex
 * Description: Parse one line from an Intel hex file
 */

static int parse_hex(const char *hex, unsigned char *binary, int *addr, int *nbytes, int *code)
{
	const char *ptr;
	int accum;
	int chksum;
	int len;
	
	*nbytes = 0;

	/* Each valid hex begins with a colon */

	ptr = hex;
	if (*hex != ':')
	{
		return 0;
	}
	ptr++;

	/* The minimun size is ':'(1) + (0) + addr(4) + type(2) + data(2) + chechksum(2) = 11 */

	if (strlen(hex) < 11)
	{
		return 0;
	}

	/* Get the length byte */

	if (!sscanf(ptr, "%02x", &len))
	{
		return 0;
	}
	ptr += 2;

	/* Now verify the length is ':'(1) + l2*len + addr(4) + type(2) + data(2) + chechksum(2) */

	if (strlen(hex) < (11 + (2*len)))
	{
		return 0;
	}

	/* Get the address */

	if (!sscanf(ptr, "%04x", addr))
	{
		return 0;
	}
	ptr += 4;

	/* Get the code byte */

	if (!sscanf(ptr, "%02x", code))
	{
		return 0;
	}
	ptr += 2;

	/* Copy the data and calculate the chechksum */

	accum = len + (*addr >> 8) + *addr + *code;
	while (*nbytes < len)
	{
		int tmp;

		/* Get the next data byte */

		if (!sscanf(ptr, "%02x", &tmp))
		{
			return 0;
		}
		ptr += 2;

		/* Transfer the data to the user binary */

		binary[*nbytes] = tmp;

		/* Update the accum */

		accum += binary[*nbytes];
		(*nbytes)++;
	}

	/* Get the checksum */

	if (!sscanf(ptr, "%02x", &chksum))
	{
		return 0;
	}

	/* Verify the checksum */

	if (((accum + chksum) & 0xff) != 0)
	{
		return 0;
	}
	return 1;
}

/* Name:        load_file
 * Description: Read an entire Intel hex file into (simulated) z80 memory
 */

int load_file(const char *filename)
{
	char hex[1000];
	FILE *stream;
	unsigned char binary[256];
	int i;
	int total = 0;
	int lineno = 1;
	int minaddr = 65536;
	int maxaddr = 0;
	int addr;
	int nbytes;
	int status;

	/* Open the ascii hex file */

	stream = fopen(filename, "r");
	if (stream == NULL)
	{
		printf("ERROR: Failed to open file '%s' for reading: %s\n", filename, strerror(errno));
		return 0;
	}

	/* Loop until every line has been read */

	while (!feof(stream) && !ferror(stream))
	{
		/* Read the next line from the Intel hex file */

		hex[0] = '\0';
		fgets(hex, 1000, stream);

		/* Remove any trailing CR/LF */

		if (hex[strlen(hex)-1] == '\n')
		{
			hex[strlen(hex)-1] = '\0';
		}

		if (hex[strlen(hex)-1] == '\r')
		{
			hex[strlen(hex)-1] = '\0';
		}

		/* Parse the hex line */

		if (parse_hex(hex, binary, &addr, &nbytes, &status))
		{
			/* Valid data? */

			if (status == 0)
			{
				/* Yes.. move it into the z80 memory image */

				for (i = 0; i <= (nbytes-1); i++)
				{
					memory[addr] = binary[i];
					total++;

					/* Keep track of the highest and lowest addresses written */

					if (addr < minaddr)
					{
						minaddr = addr;
					}

					if (addr > maxaddr)
					{
						maxaddr = addr;
					}
					addr++;
				}
			}

			/* End of file? */

			else if (status == 1)
			{
				fclose(stream);
				printf("Loaded %d bytes between %04x to %04x\n", total, minaddr, maxaddr);
				return 1;
			}
			else if (status != 2)  /* begin of file */
			{
				printf("ERROR: Unrecognized status=%d at line=%d\n", status, lineno);
				return 0;
			}
		}
		else
		{
			printf("ERROR: Failed to parse %s at line: %d\n", filename, lineno);
			return 0;
		}
		lineno++;
	}
	printf("ERROR: No end of file marker encountered in %s\n", filename);
	return 0;
}

/* Name:        sighandler
 * Description: Catch program termination via control-C
 */

void sighandler(int signo)
{
	sigset_t set;
	char command[80];
	int i;
	int j;

	sigemptyset(&set);
	sigaddset(&set, SIGINT);
	sigprocmask(SIG_UNBLOCK, &set, NULL);
	signal(SIGINT, SIG_DFL);

	printf("AF:%04X HL:%04X DE:%04X BC:%04X PC:%04X SP:%04X IX:%04X IY:%04X I:%02X\n",
		gR.AF.W, gR.HL.W, gR.DE.W, gR.BC.W, gR.PC.W, gR.SP.W, gR.IX.W, gR.IY.W, gR.I);

	printf("AT PC: [%02X]  AT SP: [%04X]  %s: %s\n",
		RdZ80(gR.PC.W), RdZ80(gR.SP.W) + RdZ80(gR.SP.W+1) * 256,
		gR.IFF & 0x04? "IM2" : gR.IFF & 0x02? "IM1" : "IM0",
		gR.IFF & 0x01? "EI" : "DI");

	for (;;)
	{
		printf("\n[Command,'?']-> ");
		fflush(stdout);
		fflush(stdin);

		fgets(command, 50, stdin);

		switch(command[0])
		{
		case 'H':
		case 'h':
		case '?':
			puts("\n***** Built-in Z80 Debugger Commands *****");
			puts("m <addr>   : Memory dump at addr");
			puts("?,h        : Show this help text");
			puts("q          : Exit Z80 emulation");
			break;

		case 'M':
		case 'm':
			{
				unsigned short addr;

				if (strlen(command) > 1)
				{
					sscanf(command+1, "%hX", &addr);
				}
				else
				{
					addr = gR.PC.W;
				}

				puts("");
				for (j = 0; j < 16; j++)
				{
					printf("%04X: ",addr);
					for (i = 0; i < 16; i++, addr++)
					{
						printf("%02X ", memory[addr]);
					}
					printf(" | ");
					addr -= 16;
					for (i = 0; i < 16; i++, addr++)
					{
						putchar(isprint(memory[addr])? memory[addr]:'.');
					}
					puts("");
				}
			}
			break;

		case 'Q':
		case 'q':
			exit(0);
		}
	}
	exit(0);
}

static void show_usage(const char *progname, int exitcode)
{
	fprintf(stderr, "\nUSAGE: %s [OPTIONS] <Intel-Hex-File>\n", progname);
	fprintf(stderr, "\nWhere [OPTIONS] include:\n");
	fprintf(stderr, "\n\t-t\tEnable trace output\n");
	fprintf(stderr, "\t-h\tShow this message\n");
	exit(exitcode);
}

static void parse_commandline(int argc, char **argv)
{
	int opt;

	while ((opt = getopt(argc, argv, ":th")) != -1)
	{
		switch (opt)
		{
		case 't':
			gtrace++;
			break;
		case 'h':
			show_usage(argv[0], 0);
			break;
		case '?':
			fprintf(stderr, "ERROR: Unrecognized option: %c\n", optopt);
			show_usage(argv[0], 1);
			break;
		case ':':
			fprintf(stderr, "ERROR: Missing argument to option: %c\n", optopt);
			show_usage(argv[0], 1);
			break;
		}
	}

	if (optind >= argc)
	{
		fprintf(stderr, "ERROR: Missing filename argument\n");
		show_usage(argv[0], 1);
	}

	gfilename = argv[optind];
	optind++;

	if (optind < argc)
	{
		fprintf(stderr, "ERROR: Extra stuff on command line after filename\n");
		show_usage(argv[0], 1);
	}
}

/* Name:        main
 * Description: Program entry point
 */

int main(int argc, char **argv, char **envp)
{
	/* Parse the command line options */

	parse_commandline(argc, argv);

	/* Set all simulated z80 memory to a known value and load the Intel hex file */

	memset(memory, 0, 65536);
	load_file(gfilename);

	/* Configure the simulation */

	memset(&gR, 0, sizeof(Z80));
	gR.IPeriod    = 10000; /* 100Hz at 10MHz */
	gR.IAutoReset = 1;

	/* Set up to catch SIGINT (control-C from console) */

	(void)signal(SIGINT, sighandler);

	/* Then start the simulation */

	RunZ80(&gR);
	return 0;
}