fixes for assembler - label addrs and DAT statements
[dcpu16] / vm-dcpu16.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <string.h>
5 #include <strings.h>
6 #include <signal.h>
7 #include <errno.h>
8 #include <assert.h>
9 #include <sysexits.h>
10
11 #include <readline/readline.h>
12
13 #include "dcpu16.h"
14 #include "common.h"
15 #include "display.h"
16
17 /*
18 * shell-like driver for dcpu16 core
19 * provides a basic interface to control a single emulation instance
20 *
21 * Justin Wind <justin.wind@gmail.com>
22 * 2012 04 10 - implementation started
23 * 2012 04 12 - cleanup, better shell loop
24 *
25 * TODO
26 * handle quotes in shell command parsing
27 * use readline/history.h, since we're using readline anyhow
28 * ncurses windowing or something, for future display capabilities
29 */
30
31 static const char * const src_id_ = "$Id$";
32
33 /* global invocation options */
34 struct options {
35 unsigned int verbose;
36 } opt_ = {
37 .verbose = 0,
38 };
39
40 /* global run state, first sigint caught will drop out of run loop and back into shell */
41 static volatile unsigned int running_ = 0;
42 static
43 void sigint_handler_(int sig) {
44 (void)sig;
45 running_ = 0;
46 }
47
48 #define VERBOSE_PRINTF(...) do { if (opt_.verbose) printf(__VA_ARGS__); } while (0)
49
50 static
51 void usage_(char *prog, unsigned int full) {
52 FILE *f = full ? stdout : stderr;
53 char *x = strrchr(prog, '/');
54
55 if (x && *(x + 1))
56 prog = x + 1;
57
58 if (full)
59 fprintf(f, "%s -- dcpu16 emulator core shell\n\n",
60 prog);
61
62 fprintf(f, "Usage: %s [-v] [file]\n",
63 prog);
64
65 if (full) {
66 fprintf(f, "\nOptions:\n"
67 "\t [file] -- ram image to load initially\n"
68 "\t -v -- displays slightly more information\n"
69 "\t -h -- this screen\n");
70
71 fprintf(f, "\n%78s\n", src_id_);
72 }
73 }
74
75
76 /* flense a buffer into a newly-allocated argument list */
77 static
78 int buf_tok_vect_(char ***v, int *c, char *buf) {
79 const char *sep = " \t";
80 const char *quot = "\"'`";
81 const size_t v_grow = 32;
82 size_t v_sz = 32;
83 char *st, *qt;
84
85 *c = 0;
86 *v = malloc(v_sz * sizeof **v);
87 if (*v == NULL) {
88 fprintf(stderr, "%s():%s\n", "malloc", strerror(errno));
89 return -1;
90 }
91
92 for ( (*v)[*c] = strqtok_r(buf, sep, '\\', quot, &qt, &st);
93 (*v)[*c];
94 (*v)[*c] = strqtok_r(NULL, sep, '\\', quot, &qt, &st)
95 ) {
96 (*c)++;
97
98 if ((size_t)(*c) == v_sz) {
99 void *tmp_ptr = realloc(*v, (v_sz + v_grow) * sizeof **v);
100 if (tmp_ptr == NULL) {
101 fprintf(stderr, "%s():%s\n", "realloc", strerror(errno));
102 free(*v);
103 *v = NULL;
104 return -1;
105 }
106 v_sz += v_grow;
107 }
108 }
109
110 return 0;
111 }
112
113 /*
114 resets the vm if addr is zero then
115 loads an image from filename into ram starting at addr
116 */
117 static
118 int file_load_(struct dcpu16 *vm, char *filename, DCPU16_WORD addr) {
119 FILE *f;
120 size_t r;
121
122 if (!addr)
123 dcpu16_reset(vm);
124
125 f = fopen(filename, "rb");
126 if (f == NULL) {
127 fprintf(stderr, "%s('%s'):%s\n", "fopen", filename, strerror(errno));
128 return -1;
129 }
130
131 r = fread(vm->ram + addr, sizeof(DCPU16_WORD), DCPU16_RAM - addr, f);
132 VERBOSE_PRINTF("read %zu words", r);
133 if (addr) VERBOSE_PRINTF(" starting at 0x%04x", addr);
134 VERBOSE_PRINTF("\n");
135
136 if (ferror(f))
137 fprintf(stderr, "%s('%s'):%s\n", "fread", filename, strerror(errno));
138
139 fclose(f);
140 return 0;
141 }
142
143 /*
144 Here follows the various commands the shell can execute.
145
146 At invocation, a command function will have already had its
147 number of arguments vetted, but will need command-specific
148 argument verifications done.
149
150 The arg_vector contains the command as the first entry, and
151 as such, arg_count will always be at least 1.
152 However, the args_min and args_max entries in struct command_
153 only refer to the counts of arguments, not the entries in the
154 argv.
155 */
156
157 struct command_ {
158 char *name;
159 int args_min;
160 int args_max;
161 int (*func)(struct dcpu16 *, int c, char **v);
162 void (*help)(FILE *f, unsigned int);
163 };
164
165 #define COMMAND_IMPL(x) static int command_##x##_(struct dcpu16 *vm, int arg_count, char **arg_vector)
166 #define COMMAND_HELP(x) static void command_##x##_help_(FILE *f, unsigned int summary)
167 #define COMMAND_ENTRY(x, y, z) { #x, y, z, command_##x##_, command_##x##_help_ }
168
169
170 COMMAND_IMPL(quit) {
171 (void)vm, (void)arg_count, (void)arg_vector;
172
173 return -1;
174 }
175 COMMAND_HELP(quit) {
176 fprintf(f, "\tquit\n");
177 if (summary) return;
178
179 fprintf(f, "Exits the emulator.\n");
180 }
181
182
183 COMMAND_IMPL(reset) {
184 (void)arg_count, (void)arg_vector;
185
186 dcpu16_reset(vm);
187 printf("initialized\n");
188 return 0;
189 }
190 COMMAND_HELP(reset) {
191 fprintf(f, "\treset\n");
192 if (summary) return;
193
194 fprintf(f, "Clears and reinitializes emulator.\n");
195 }
196
197
198 COMMAND_IMPL(load) {
199 int addr = 0;
200
201 if (arg_count > 2) {
202 addr = str_to_word(arg_vector[2]);
203 if (addr < 0) {
204 fprintf(stderr, "address '%s' is not a valid word: %s\n", arg_vector[2], strerror(errno));
205 return 0;
206 }
207 }
208
209 if (file_load_(vm, arg_vector[1], addr)) {
210 fprintf(stderr, "failed to load '%s'\n", arg_vector[1]);
211 return 0;
212 }
213 printf("loaded '%s'", arg_vector[1]);
214 if (addr) printf(" starting at 0x%04x", addr);
215 printf("\n");
216
217 return 0;
218 }
219 COMMAND_HELP(load) {
220 fprintf(f, "\tload file [addr]\n");
221 if (summary) return;
222
223 fprintf(f, "Load binary image from 'file' into ram.\n");
224 }
225
226
227 COMMAND_IMPL(dump) {
228 int addr[2];
229 int i;
230
231 for (i = 1; i < arg_count; i++) {
232 addr[i-1] = str_to_word(arg_vector[i]);
233 if (addr[i-1] < 0) {
234 fprintf(stderr, "address '%s' is not a valid word: %s\n", arg_vector[i], strerror(errno));
235 return 0;
236 }
237 }
238 if (arg_count < 2) addr[0] = vm->pc;
239 if (arg_count < 3) addr[1] = addr[0];
240
241 if (addr[1] < addr[0]) {
242 fprintf(stderr, "\t'addr_start' must be before addr_end\n");
243 return 0;
244 }
245
246 dcpu16_dump_ram(vm, addr[0], addr[1]);
247
248 return 0;
249 }
250 COMMAND_HELP(dump) {
251 fprintf(f, "\tdump [addr_start [addr_end]]\n");
252 if (summary) return;
253
254 fprintf(f, "Displays contents of ram from addr_start to addr_end.\n");
255 }
256
257
258 COMMAND_IMPL(disassemble) {
259 int addr[2];
260 int i;
261
262 for (i = 1; i < arg_count; i++) {
263 addr[i-1] = str_to_word(arg_vector[i]);
264 if (addr[i-1] < 0) {
265 fprintf(stderr, "address '%s' is not a valid word: %s\n", arg_vector[i], strerror(errno));
266 return 0;
267 }
268 }
269 if (arg_count < 2) addr[0] = vm->pc;
270 if (arg_count < 3) addr[1] = addr[0];
271
272 if (addr[1] < addr[0]) {
273 fprintf(stderr, "\t'addr_start' must be before addr_end\n");
274 return 0;
275 }
276
277 for (i = addr[0]; i <= addr[1]; /* */ ) {
278 printf("0x%04x: ", i);
279 i += dcpu16_disassemble_print(vm, i);
280 printf("\n");
281 }
282
283 return 0;
284 }
285 COMMAND_HELP(disassemble) {
286 fprintf(f, "\tdisassemble [addr_start [addr_end]]\n");
287 if (summary) return;
288
289 fprintf(f, "Displays contents of ram parsed into instructions.\n");
290 }
291
292
293 COMMAND_IMPL(step) {
294 unsigned long count = 1;
295 char *ep;
296
297 if (arg_count == 2) {
298 errno = 0;
299 count = strtoul(arg_vector[1], &ep, 0);
300 if (errno
301 || !(*arg_vector[0] && *ep == '\0') ) {
302 fprintf(stderr, "count '%s' is not a valid number: %s\n", arg_vector[1], strerror(errno));
303 return 0;
304 }
305
306 if (count <= 0) {
307 fprintf(stderr, "count must be positive\n");
308 return 0;
309 }
310 }
311
312 while (count--) {
313 dcpu16_disassemble_print(vm, vm->pc);
314 printf("\n");
315 dcpu16_step(vm);
316
317 if (count > 1 && opt_.verbose)
318 dcpu16_state_print(vm);
319 }
320
321 return 0;
322 }
323 COMMAND_HELP(step) {
324 fprintf(f, "\tstep [count]\n");
325 if (summary) return;
326
327 fprintf(f, "Executes the next instruction, or the next count instructions.\n");
328 }
329
330
331 COMMAND_IMPL(run) {
332 struct sigaction act;
333 (void)arg_count, (void)arg_vector;
334
335 running_ = 1;
336
337 memset(&act, 0, sizeof act);
338 act.sa_handler = sigint_handler_;
339 act.sa_flags = SA_RESETHAND;
340
341 if (sigaction(SIGINT, &act, NULL)) {
342 fprintf(stderr, "%s():%s\n", "sigaction", strerror(errno));
343 return -1;
344 }
345
346 while(running_) {
347 dcpu16_step(vm);
348 if (opt_.verbose > 1)
349 dcpu16_state_print(vm);
350 else if (opt_.verbose) {
351 dcpu16_disassemble_print(vm, vm->pc);
352 printf("\n");
353 }
354 }
355
356 printf("interrupted...\n");
357
358 return 0;
359 }
360 COMMAND_HELP(run) {
361 fprintf(f, "\trun\n");
362 if (summary) return;
363
364 fprintf(f, "Begins executing continuously.\n"
365 "May be interrupted with SIGINT.\n");
366 }
367
368 COMMAND_IMPL(display) {
369 (void)arg_count, (void)arg_vector;
370
371 static DPIX *pixbuf = NULL;
372
373 if (pixbuf) {
374 printf("display already enabled..\n");
375 return 0;
376 }
377
378 pixbuf = display_init_pixbuf();
379 if (pixbuf == NULL) {
380 fprintf(stderr, "failed to initialize display buffer\n");
381 return 0;
382 }
383
384 if (dcpu16_acct_add(vm, DCPU16_ACCT_EV_WRITE, display_fn, pixbuf)) {
385 fprintf(stderr, "failed to register display update callback\n");
386 return 0;
387 }
388
389 if (dcpu16_acct_add(vm, DCPU16_ACCT_EV_RESET, display_reset_fn, pixbuf)) {
390 fprintf(stderr, "failed to register display reset callback\n");
391 return 0;
392 }
393
394 /* init display as if reset occurred */
395 display_reset_fn(vm, DCPU16_ACCT_EV_RESET, 0, pixbuf);
396
397 return 0;
398 }
399 COMMAND_HELP(display) {
400 fprintf(f, "\tdisplay\n");
401 if (summary) return;
402
403 fprintf(f, "Begins updating a PNM of current display contents...\n"
404 "This is not a fully-baked feature...\n");
405 }
406
407 /* gather all these together into a searchable table */
408
409 /* help command gets some assistance in declarations */
410 COMMAND_IMPL(help);
411 COMMAND_HELP(help);
412
413 static struct command_ command_table_[] = {
414 COMMAND_ENTRY(help, 0, -1),
415 COMMAND_ENTRY(quit, 0, -1),
416 COMMAND_ENTRY(load, 1, 2),
417 COMMAND_ENTRY(dump, 0, 2),
418 COMMAND_ENTRY(disassemble, 0, 2),
419 COMMAND_ENTRY(step, 0, 1),
420 COMMAND_ENTRY(run, 0, 0),
421 COMMAND_ENTRY(reset, 0, 0),
422 COMMAND_ENTRY(display, 0, 0),
423 { NULL, 0, 0, NULL, NULL }
424 };
425
426 COMMAND_IMPL(help) {
427 struct command_ *c;
428 (void)vm;
429
430 if (arg_count == 2) {
431 for (c = command_table_; c->func; c++) {
432 if (strcasecmp(arg_vector[1], c->name) == 0) {
433 if (c->help)
434 c->help(stdout, 0);
435 break;
436 }
437 }
438 return 0;
439 }
440
441 for (c = command_table_; c->func; c++) {
442 if (c->help)
443 c->help(stdout, 1);
444 }
445 return 0;
446 }
447 COMMAND_HELP(help) {
448 fprintf(f, "\thelp [command]\n");
449 if (summary) return;
450
451 fprintf(f, "Displays a list of available commands, or detailed help on a specific command.\n");
452 }
453
454
455 int main(int argc, char **argv) {
456 const char prompt_fmt[] = "PC:%04x> ";
457 char prompt[32];
458 struct dcpu16 *vm;
459 char *line, *line_prev;
460 char **tok_v, **tok_v_prev;
461 int tok_c, tok_c_prev;
462 int c;
463
464 while ( (c = getopt(argc, argv, "hv")) != EOF) {
465 switch (c) {
466 case 'v':
467 opt_.verbose++;
468 break;
469
470 case 'h':
471 usage_(argv[0], 1);
472 exit(EX_OK);
473
474 default:
475 usage_(argv[0], 0);
476 exit(EX_USAGE);
477 }
478 }
479 if (opt_.verbose < 1) {
480 dcpu16_warn_cb_set(NULL);
481 dcpu16_trace_cb_set(NULL);
482 } else if (opt_.verbose < 2) {
483 dcpu16_trace_cb_set(NULL);
484 }
485 argc -= optind;
486 argv += optind;
487
488 if ((vm = dcpu16_new()) == NULL) {
489 fprintf(stderr, "could not allocate new dcpu16 instance\n");
490 exit(EX_UNAVAILABLE);
491 }
492
493 if (argc) {
494 if (file_load_(vm, *argv, 0)) {
495 fprintf(stderr, "couldn't load '%s'\n", *argv);
496 exit(EX_NOINPUT);
497 }
498 }
499
500 /* show state, read commands */
501 for (line = line_prev = NULL,
502 tok_v = tok_v_prev = NULL,
503 tok_c = tok_c_prev= 0,
504 snprintf(prompt, sizeof prompt, prompt_fmt, vm->pc),
505 dcpu16_state_print(vm);
506
507 (line = readline(prompt));
508
509 printf("\n"),
510 snprintf(prompt, sizeof prompt, prompt_fmt, vm->pc),
511 dcpu16_state_print(vm)) {
512 const char whitespace[] = " \t";
513 char *line_start;
514 struct command_ *c;
515 int r = 0;
516
517 /* skip whitespaces */
518 line_start = line + strspn(line, whitespace);
519
520 if (*line_start) {
521 /* a new command, remember previous for possible repetition */
522
523 /* turn new line into new arg array */
524 if (buf_tok_vect_(&tok_v, &tok_c, line_start)) {
525 fprintf(stderr, "failed to process command\n");
526 continue;
527 }
528
529 /* and keep track if it all for the next time around */
530 if (line_prev) free(line_prev);
531 line_prev = line;
532
533 if (tok_v_prev) free(tok_v_prev);
534 tok_v_prev = tok_v;
535 tok_c_prev = tok_c;
536 } else {
537 /* blank new command, but no prior command to repeat? ask again */
538 if (tok_v_prev == NULL || tok_v_prev[0] == NULL || *(tok_v_prev[0]) == '\0') {
539 free(line);
540 continue;
541 }
542
543 /* otherwise discard new line and promote prior */
544 free(line);
545 tok_v = tok_v_prev;
546 tok_c = tok_c_prev;
547 line = line_prev;
548 }
549
550 /* look up command */
551 for (c = command_table_; c->name; c++) {
552 if (strcasecmp(tok_v[0], c->name) == 0) {
553 if (c->args_min > tok_c - 1) {
554 fprintf(stderr, "%s: not enough arguments\n", c->name);
555 c->help(stderr, 1);
556 break;
557 }
558
559 if (c->args_max > 0
560 && tok_c - 1 > c->args_max) {
561 fprintf(stderr, "%s: too many arguments\n", c->name);
562 c->help(stderr, 1);
563 break;
564 }
565
566 r = c->func(vm, tok_c, tok_v);
567 break;
568 }
569 }
570 if (r)
571 break;
572
573 if (!c->func)
574 fprintf(stderr, "didn't recognize '%s'\n", tok_v[0]);
575 }
576
577 printf("\nfinished\n");
578
579 dcpu16_delete(&vm);
580
581 exit(EX_OK);
582 }