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