cleaned up verbosity in vm-dcpu16.c
[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 -- displays slightly more information\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
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 dcpu16_disassemble_print(vm, vm->pc);
335 printf("\n");
336 dcpu16_step(vm);
337
338 if (count > 1 && opt_.verbose)
339 dcpu16_state_print(vm);
340 }
341
342 return 0;
343 }
344 COMMAND_HELP(step) {
345 fprintf(f, "\tstep [count]\n");
346 if (summary) return;
347
348 fprintf(f, "Executes the next instruction, or the next count instructions.\n");
349 }
350
351
352 COMMAND_IMPL(run) {
353 sig_t osig;
354 (void)arg_count, (void)arg_vector;
355
356 running_ = 1;
357
358 /* install our new interrupt signal handler */
359 if ( (osig = signal(SIGINT, sigint_handler_)) == SIG_ERR ) {
360 fprintf(stderr, "%s():%s\n", "signal", strerror(errno));
361 return -1;
362 }
363
364 while(running_) {
365 dcpu16_step(vm);
366 if (opt_.verbose > 1)
367 dcpu16_state_print(vm);
368 else if (opt_.verbose) {
369 dcpu16_disassemble_print(vm, vm->pc);
370 printf("\n");
371 }
372 }
373
374 /* restore the old interrupt signal handler */
375 if (signal(SIGINT, osig) == SIG_ERR) {
376 fprintf(stderr, "%s():%s\n", "signal", strerror(errno));
377 return -1;
378 }
379
380 printf("interrupted...\n");
381
382 return 0;
383 }
384 COMMAND_HELP(run) {
385 fprintf(f, "\trun\n");
386 if (summary) return;
387
388 fprintf(f, "Begins executing continuously.\n"
389 "May be interrupted with SIGINT.\n");
390 }
391
392 /* gather all these together into a searchable table */
393
394 /* help command gets some assistance in declarations */
395 COMMAND_IMPL(help);
396 COMMAND_HELP(help);
397
398 static struct command_ command_table_[] = {
399 COMMAND_ENTRY(help, 0, -1),
400 COMMAND_ENTRY(quit, 0, -1),
401 COMMAND_ENTRY(load, 1, 2),
402 COMMAND_ENTRY(dump, 0, 2),
403 COMMAND_ENTRY(disassemble, 0, 2),
404 COMMAND_ENTRY(step, 0, 1),
405 COMMAND_ENTRY(run, 0, 0),
406 COMMAND_ENTRY(reset, 0, 0),
407 { NULL, 0, 0, NULL, NULL }
408 };
409
410 COMMAND_IMPL(help) {
411 struct command_ *c;
412 (void)vm;
413
414 if (arg_count == 2) {
415 for (c = command_table_; c->func; c++) {
416 if (strcasecmp(arg_vector[1], c->name) == 0) {
417 if (c->help)
418 c->help(stdout, 0);
419 break;
420 }
421 }
422 return 0;
423 }
424
425 for (c = command_table_; c->func; c++) {
426 if (c->help)
427 c->help(stdout, 1);
428 }
429 return 0;
430 }
431 COMMAND_HELP(help) {
432 fprintf(f, "\thelp [command]\n");
433 if (summary) return;
434
435 fprintf(f, "Displays a list of available commands, or detailed help on a specific command.\n");
436 }
437
438
439 int main(int argc, char **argv) {
440 const char prompt_fmt[] = "PC:%04x> ";
441 char prompt[32];
442 struct dcpu16 *vm;
443 char *line, *line_prev;
444 char **tok_v, **tok_v_prev;
445 int tok_c, tok_c_prev;
446 int c;
447
448 while ( (c = getopt(argc, argv, "hv")) != EOF) {
449 switch (c) {
450 case 'v':
451 opt_.verbose++;
452 break;
453
454 case 'h':
455 usage_(argv[0], 1);
456 exit(EX_OK);
457
458 default:
459 usage_(argv[0], 0);
460 exit(EX_USAGE);
461 }
462 }
463 if (opt_.verbose < 1) {
464 dcpu16_warn_cb_set(NULL);
465 dcpu16_trace_cb_set(NULL);
466 } else if (opt_.verbose < 2) {
467 dcpu16_trace_cb_set(NULL);
468 }
469 argc -= optind;
470 argv += optind;
471
472 if ((vm = dcpu16_new()) == NULL) {
473 fprintf(stderr, "could not allocate new dcpu16 instance\n");
474 exit(EX_UNAVAILABLE);
475 }
476
477 if (argc) {
478 if (file_load_(vm, *argv, 0)) {
479 fprintf(stderr, "couldn't load '%s'\n", *argv);
480 exit(EX_NOINPUT);
481 }
482 }
483
484 /* show state, read commands */
485 for (line = line_prev = NULL,
486 tok_v = tok_v_prev = NULL,
487 tok_c = tok_c_prev= 0,
488 snprintf(prompt, sizeof prompt, prompt_fmt, vm->pc),
489 dcpu16_state_print(vm);
490
491 (line = readline(prompt));
492
493 printf("\n"),
494 snprintf(prompt, sizeof prompt, prompt_fmt, vm->pc),
495 dcpu16_state_print(vm)) {
496 const char whitespace[] = " \t";
497 char *line_start;
498 struct command_ *c;
499 int r = 0;
500
501 /* skip whitespaces */
502 line_start = line + strspn(line, whitespace);
503
504 if (*line_start) {
505 /* a new command, remember previous for possible repetition */
506
507 /* turn new line into new arg array */
508 if (buf_tok_vect_(&tok_v, &tok_c, line_start)) {
509 fprintf(stderr, "failed to process command\n");
510 continue;
511 }
512
513 /* and keep track if it all for the next time around */
514 if (line_prev) free(line_prev);
515 line_prev = line;
516
517 if (tok_v_prev) free(tok_v_prev);
518 tok_v_prev = tok_v;
519 tok_c_prev = tok_c;
520 } else {
521 /* blank new command, but no prior command to repeat? ask again */
522 if (tok_v_prev == NULL || tok_v_prev[0] == NULL || *(tok_v_prev[0]) == '\0') {
523 free(line);
524 continue;
525 }
526
527 /* otherwise discard new line and promote prior */
528 free(line);
529 tok_v = tok_v_prev;
530 tok_c = tok_c_prev;
531 line = line_prev;
532 }
533
534 /* look up command */
535 for (c = command_table_; c->name; c++) {
536 if (strcasecmp(tok_v[0], c->name) == 0) {
537 if (c->args_min > tok_c - 1) {
538 fprintf(stderr, "%s: not enough arguments\n", c->name);
539 c->help(stderr, 1);
540 break;
541 }
542
543 if (c->args_max > 0
544 && tok_c - 1 > c->args_max) {
545 fprintf(stderr, "%s: too many arguments\n", c->name);
546 c->help(stderr, 1);
547 break;
548 }
549
550 r = c->func(vm, tok_c, tok_v);
551 break;
552 }
553 }
554 if (r)
555 break;
556
557 if (!c->func)
558 fprintf(stderr, "didn't recognize '%s'\n", tok_v[0]);
559 }
560
561 printf("\nfinished\n");
562
563 dcpu16_delete(&vm);
564
565 exit(EX_OK);
566 }