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