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