support png output, buffered file writing
[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 static const char * const display_filename_default_ =
369 #ifdef HAVE_LIBPNG
370 "dcpu16-display.png"
371 #else /* HAVE_LIBPNG */
372 "dcpu16-display.pnm"
373 #endif /* HAVE_LIBPNG */
374 ;
375 COMMAND_IMPL(display) {
376 static DCPU16_DISPLAY *display = NULL;
377 const char *filename = display_filename_default_;
378
379 if (arg_count == 2) {
380 filename = arg_vector[1];
381 }
382
383 if (display) {
384 printf("display already enabled..\n");
385 return 0;
386 }
387
388 display = display_new(filename);
389
390 if (display == NULL) {
391 fprintf(stderr, "failed to initialize display buffer\n");
392 return 0;
393 }
394
395 if (dcpu16_acct_add(vm, DCPU16_ACCT_EV_WRITE, display_fn, display)) {
396 fprintf(stderr, "failed to register display update callback\n");
397 return 0;
398 }
399
400 if (dcpu16_acct_add(vm, DCPU16_ACCT_EV_RESET, display_reset_fn, display)) {
401 fprintf(stderr, "failed to register display reset callback\n");
402 return 0;
403 }
404
405 if (dcpu16_acct_add(vm, DCPU16_ACCT_EV_CYCLE, display_cycle_fn, display)) {
406 fprintf(stderr, "failed to register display cycle callback\n");
407 return 0;
408 }
409
410 /* init display as if reset occurred */
411 display_reset_fn(vm, DCPU16_ACCT_EV_RESET, 0, display);
412
413 return 0;
414 }
415 COMMAND_HELP(display) {
416 fprintf(f, "\tdisplay [file]\n");
417 if (summary) return;
418
419 fprintf(f, "Attaches display interface, begins updating an image file of display contents...\n"
420 "Image filename may be specified, defaults to '%s'\n",
421 display_filename_default_
422 );
423 }
424
425 /* gather all these together into a searchable table */
426
427 /* help command gets some assistance in declarations */
428 COMMAND_IMPL(help);
429 COMMAND_HELP(help);
430
431 static struct command_ command_table_[] = {
432 COMMAND_ENTRY(help, 0, -1),
433 COMMAND_ENTRY(quit, 0, -1),
434 COMMAND_ENTRY(load, 1, 2),
435 COMMAND_ENTRY(dump, 0, 2),
436 COMMAND_ENTRY(disassemble, 0, 2),
437 COMMAND_ENTRY(step, 0, 1),
438 COMMAND_ENTRY(run, 0, 0),
439 COMMAND_ENTRY(reset, 0, 0),
440 COMMAND_ENTRY(display, 0, 1),
441 { NULL, 0, 0, NULL, NULL }
442 };
443
444 COMMAND_IMPL(help) {
445 struct command_ *c;
446 (void)vm;
447
448 if (arg_count == 2) {
449 for (c = command_table_; c->func; c++) {
450 if (strcasecmp(arg_vector[1], c->name) == 0) {
451 if (c->help)
452 c->help(stdout, 0);
453 break;
454 }
455 }
456 return 0;
457 }
458
459 for (c = command_table_; c->func; c++) {
460 if (c->help)
461 c->help(stdout, 1);
462 }
463 return 0;
464 }
465 COMMAND_HELP(help) {
466 fprintf(f, "\thelp [command]\n");
467 if (summary) return;
468
469 fprintf(f, "Displays a list of available commands, or detailed help on a specific command.\n");
470 }
471
472
473 int main(int argc, char **argv) {
474 const char prompt_fmt[] = "PC:%04x> ";
475 char prompt[32];
476 struct dcpu16 *vm;
477 char *line, *line_prev;
478 char **tok_v, **tok_v_prev;
479 int tok_c, tok_c_prev;
480 int c;
481
482 while ( (c = getopt(argc, argv, "hv")) != EOF) {
483 switch (c) {
484 case 'v':
485 opt_.verbose++;
486 break;
487
488 case 'h':
489 usage_(argv[0], 1);
490 exit(EX_OK);
491
492 default:
493 usage_(argv[0], 0);
494 exit(EX_USAGE);
495 }
496 }
497 if (opt_.verbose < 1) {
498 dcpu16_warn_cb_set(NULL);
499 dcpu16_trace_cb_set(NULL);
500 } else if (opt_.verbose < 2) {
501 dcpu16_trace_cb_set(NULL);
502 }
503 argc -= optind;
504 argv += optind;
505
506 if ((vm = dcpu16_new()) == NULL) {
507 fprintf(stderr, "could not allocate new dcpu16 instance\n");
508 exit(EX_UNAVAILABLE);
509 }
510
511 if (argc) {
512 if (file_load_(vm, *argv, 0)) {
513 fprintf(stderr, "couldn't load '%s'\n", *argv);
514 exit(EX_NOINPUT);
515 }
516 }
517
518 /* show state, read commands */
519 for (line = line_prev = NULL,
520 tok_v = tok_v_prev = NULL,
521 tok_c = tok_c_prev= 0,
522 snprintf(prompt, sizeof prompt, prompt_fmt, vm->pc),
523 dcpu16_state_print(vm);
524
525 (line = readline(prompt));
526
527 printf("\n"),
528 snprintf(prompt, sizeof prompt, prompt_fmt, vm->pc),
529 dcpu16_state_print(vm)) {
530 const char whitespace[] = " \t";
531 char *line_start;
532 struct command_ *c;
533 int r = 0;
534
535 /* skip whitespaces */
536 line_start = line + strspn(line, whitespace);
537
538 if (*line_start) {
539 /* a new command, remember previous for possible repetition */
540
541 /* turn new line into new arg array */
542 if (buf_tok_vect_(&tok_v, &tok_c, line_start)) {
543 fprintf(stderr, "failed to process command\n");
544 continue;
545 }
546
547 /* and keep track if it all for the next time around */
548 if (line_prev) free(line_prev);
549 line_prev = line;
550
551 if (tok_v_prev) free(tok_v_prev);
552 tok_v_prev = tok_v;
553 tok_c_prev = tok_c;
554 } else {
555 /* blank new command, but no prior command to repeat? ask again */
556 if (tok_v_prev == NULL || tok_v_prev[0] == NULL || *(tok_v_prev[0]) == '\0') {
557 free(line);
558 continue;
559 }
560
561 /* otherwise discard new line and promote prior */
562 free(line);
563 tok_v = tok_v_prev;
564 tok_c = tok_c_prev;
565 line = line_prev;
566 }
567
568 /* look up command */
569 for (c = command_table_; c->name; c++) {
570 if (strcasecmp(tok_v[0], c->name) == 0) {
571 if (c->args_min > tok_c - 1) {
572 fprintf(stderr, "%s: not enough arguments\n", c->name);
573 c->help(stderr, 1);
574 break;
575 }
576
577 if (c->args_max > 0
578 && tok_c - 1 > c->args_max) {
579 fprintf(stderr, "%s: too many arguments\n", c->name);
580 c->help(stderr, 1);
581 break;
582 }
583
584 r = c->func(vm, tok_c, tok_v);
585 break;
586 }
587 }
588 if (r)
589 break;
590
591 if (!c->func)
592 fprintf(stderr, "didn't recognize '%s'\n", tok_v[0]);
593 }
594
595 printf("\nfinished\n");
596
597 dcpu16_delete(&vm);
598
599 exit(EX_OK);
600 }