removed checks for setting literal operands
[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
16 /*
17 * shell-like driver for dcpu16 core
18 * provides a basic interface to control a single emulation instance
19 *
20 * Justin Wind <justin.wind@gmail.com>
21 * 2012 04 10 - implementation started
22 * 2012 04 12 - cleanup, better shell loop
23 *
24 * TODO
25 * handle quotes in shell command parsing
26 * use readline/history.h, since we're using readline anyhow
27 * ncurses windowing or something, for future display capabilities
28 */
29
30 static const char * const src_id_ = "$Id$";
31
32 /* global invocation options */
33 struct options {
34 unsigned int verbose;
35 } opt_ = {
36 .verbose = 0,
37 };
38
39 /* global run state, first sigint caught will drop out of run loop and back into shell */
40 static volatile unsigned int running_ = 0;
41 static
42 void sigint_handler_(int sig) {
43 (void)sig;
44 running_ = 0;
45 }
46
47 #define VERBOSE_PRINTF(...) do { if (opt_.verbose) printf(__VA_ARGS__); } while (0)
48
49 static
50 void usage_(char *prog, unsigned int full) {
51 FILE *f = full ? stdout : stderr;
52 char *x = strrchr(prog, '/');
53
54 if (x && *(x + 1))
55 prog = x + 1;
56
57 if (full)
58 fprintf(f, "%s -- dcpu16 emulator core shell\n\n",
59 prog);
60
61 fprintf(f, "Usage: %s [-v] [file]\n",
62 prog);
63
64 if (full) {
65 fprintf(f, "\nOptions:\n"
66 "\t [file] -- ram image to load initially\n"
67 "\t -v -- displays slightly more information\n"
68 "\t -h -- this screen\n");
69
70 fprintf(f, "\n%78s\n", src_id_);
71 }
72 }
73
74
75 /* flense a buffer into a newly-allocated argument list */
76 static
77 int buf_tok_vect_(char ***v, int *c, char *buf) {
78 const char *sep = " \t";
79 const char *quot = "\"'`";
80 const size_t v_grow = 32;
81 size_t v_sz = 32;
82 char *st, *qt;
83
84 *c = 0;
85 *v = malloc(v_sz * sizeof **v);
86 if (*v == NULL) {
87 fprintf(stderr, "%s():%s\n", "malloc", strerror(errno));
88 return -1;
89 }
90
91 for ( (*v)[*c] = strqtok_r(buf, sep, '\\', quot, &qt, &st);
92 (*v)[*c];
93 (*v)[*c] = strqtok_r(NULL, sep, '\\', quot, &qt, &st)
94 ) {
95 (*c)++;
96
97 if ((size_t)(*c) == v_sz) {
98 void *tmp_ptr = realloc(*v, (v_sz + v_grow) * sizeof **v);
99 if (tmp_ptr == NULL) {
100 fprintf(stderr, "%s():%s\n", "realloc", strerror(errno));
101 free(*v);
102 *v = NULL;
103 return -1;
104 }
105 v_sz += v_grow;
106 }
107 }
108
109 return 0;
110 }
111
112 /*
113 resets the vm if addr is zero then
114 loads an image from filename into ram starting at addr
115 */
116 static
117 int file_load_(struct dcpu16 *vm, char *filename, DCPU16_WORD addr) {
118 FILE *f;
119 size_t r;
120
121 if (!addr)
122 dcpu16_reset(vm);
123
124 f = fopen(filename, "rb");
125 if (f == NULL) {
126 fprintf(stderr, "%s('%s'):%s\n", "fopen", filename, strerror(errno));
127 return -1;
128 }
129
130 r = fread(vm->ram + addr, sizeof(DCPU16_WORD), DCPU16_RAM - addr, f);
131 VERBOSE_PRINTF("read %zu words", r);
132 if (addr) VERBOSE_PRINTF(" starting at 0x%04x", addr);
133 VERBOSE_PRINTF("\n");
134
135 if (ferror(f))
136 fprintf(stderr, "%s('%s'):%s\n", "fread", filename, strerror(errno));
137
138 fclose(f);
139 return 0;
140 }
141
142 /*
143 Here follows the various commands the shell can execute.
144
145 At invocation, a command function will have already had its
146 number of arguments vetted, but will need command-specific
147 argument verifications done.
148
149 The arg_vector contains the command as the first entry, and
150 as such, arg_count will always be at least 1.
151 However, the args_min and args_max entries in struct command_
152 only refer to the counts of arguments, not the entries in the
153 argv.
154 */
155
156 struct command_ {
157 char *name;
158 int args_min;
159 int args_max;
160 int (*func)(struct dcpu16 *, int c, char **v);
161 void (*help)(FILE *f, unsigned int);
162 };
163
164 #define COMMAND_IMPL(x) static int command_##x##_(struct dcpu16 *vm, int arg_count, char **arg_vector)
165 #define COMMAND_HELP(x) static void command_##x##_help_(FILE *f, unsigned int summary)
166 #define COMMAND_ENTRY(x, y, z) { #x, y, z, command_##x##_, command_##x##_help_ }
167
168
169 COMMAND_IMPL(quit) {
170 (void)vm, (void)arg_count, (void)arg_vector;
171
172 return -1;
173 }
174 COMMAND_HELP(quit) {
175 fprintf(f, "\tquit\n");
176 if (summary) return;
177
178 fprintf(f, "Exits the emulator.\n");
179 }
180
181
182 COMMAND_IMPL(reset) {
183 (void)arg_count, (void)arg_vector;
184
185 dcpu16_reset(vm);
186 printf("initialized\n");
187 return 0;
188 }
189 COMMAND_HELP(reset) {
190 fprintf(f, "\treset\n");
191 if (summary) return;
192
193 fprintf(f, "Clears and reinitializes emulator.\n");
194 }
195
196
197 COMMAND_IMPL(load) {
198 int addr = 0;
199
200 if (arg_count > 2) {
201 addr = str_to_word(arg_vector[2]);
202 if (addr < 0) {
203 fprintf(stderr, "address '%s' is not a valid word: %s\n", arg_vector[2], strerror(errno));
204 return 0;
205 }
206 }
207
208 if (file_load_(vm, arg_vector[1], addr)) {
209 fprintf(stderr, "failed to load '%s'\n", arg_vector[1]);
210 return 0;
211 }
212 printf("loaded '%s'", arg_vector[1]);
213 if (addr) printf(" starting at 0x%04x", addr);
214 printf("\n");
215
216 return 0;
217 }
218 COMMAND_HELP(load) {
219 fprintf(f, "\tload file [addr]\n");
220 if (summary) return;
221
222 fprintf(f, "Load binary image from 'file' into ram.\n");
223 }
224
225
226 COMMAND_IMPL(dump) {
227 int addr[2];
228 int i;
229
230 for (i = 1; i < arg_count; i++) {
231 addr[i-1] = str_to_word(arg_vector[i]);
232 if (addr[i-1] < 0) {
233 fprintf(stderr, "address '%s' is not a valid word: %s\n", arg_vector[i], strerror(errno));
234 return 0;
235 }
236 }
237 if (arg_count < 2) addr[0] = vm->pc;
238 if (arg_count < 3) addr[1] = addr[0];
239
240 if (addr[1] < addr[0]) {
241 fprintf(stderr, "\t'addr_start' must be before addr_end\n");
242 return 0;
243 }
244
245 dcpu16_dump_ram(vm, addr[0], addr[1]);
246
247 return 0;
248 }
249 COMMAND_HELP(dump) {
250 fprintf(f, "\tdump [addr_start [addr_end]]\n");
251 if (summary) return;
252
253 fprintf(f, "Displays contents of ram from addr_start to addr_end.\n");
254 }
255
256
257 COMMAND_IMPL(disassemble) {
258 int addr[2];
259 int i;
260
261 for (i = 1; i < arg_count; i++) {
262 addr[i-1] = str_to_word(arg_vector[i]);
263 if (addr[i-1] < 0) {
264 fprintf(stderr, "address '%s' is not a valid word: %s\n", arg_vector[i], strerror(errno));
265 return 0;
266 }
267 }
268 if (arg_count < 2) addr[0] = vm->pc;
269 if (arg_count < 3) addr[1] = addr[0];
270
271 if (addr[1] < addr[0]) {
272 fprintf(stderr, "\t'addr_start' must be before addr_end\n");
273 return 0;
274 }
275
276 for (i = addr[0]; i <= addr[1]; /* */ ) {
277 printf("0x%04x: ", i);
278 i += dcpu16_disassemble_print(vm, i);
279 printf("\n");
280 }
281
282 return 0;
283 }
284 COMMAND_HELP(disassemble) {
285 fprintf(f, "\tdisassemble [addr_start [addr_end]]\n");
286 if (summary) return;
287
288 fprintf(f, "Displays contents of ram parsed into instructions.\n");
289 }
290
291
292 COMMAND_IMPL(step) {
293 unsigned long count = 1;
294 char *ep;
295
296 if (arg_count == 2) {
297 errno = 0;
298 count = strtoul(arg_vector[1], &ep, 0);
299 if (errno
300 || !(*arg_vector[0] && *ep == '\0') ) {
301 fprintf(stderr, "count '%s' is not a valid number: %s\n", arg_vector[1], strerror(errno));
302 return 0;
303 }
304
305 if (count <= 0) {
306 fprintf(stderr, "count must be positive\n");
307 return 0;
308 }
309 }
310
311 while (count--) {
312 dcpu16_disassemble_print(vm, vm->pc);
313 printf("\n");
314 dcpu16_step(vm);
315
316 if (count > 1 && opt_.verbose)
317 dcpu16_state_print(vm);
318 }
319
320 return 0;
321 }
322 COMMAND_HELP(step) {
323 fprintf(f, "\tstep [count]\n");
324 if (summary) return;
325
326 fprintf(f, "Executes the next instruction, or the next count instructions.\n");
327 }
328
329
330 COMMAND_IMPL(run) {
331 struct sigaction act;
332 (void)arg_count, (void)arg_vector;
333
334 running_ = 1;
335
336 memset(&act, 0, sizeof act);
337 act.sa_handler = sigint_handler_;
338 act.sa_flags = SA_RESETHAND;
339
340 if (sigaction(SIGINT, &act, NULL)) {
341 fprintf(stderr, "%s():%s\n", "sigaction", strerror(errno));
342 return -1;
343 }
344
345 while(running_) {
346 dcpu16_step(vm);
347 if (opt_.verbose > 1)
348 dcpu16_state_print(vm);
349 else if (opt_.verbose) {
350 dcpu16_disassemble_print(vm, vm->pc);
351 printf("\n");
352 }
353 }
354
355 printf("interrupted...\n");
356
357 return 0;
358 }
359 COMMAND_HELP(run) {
360 fprintf(f, "\trun\n");
361 if (summary) return;
362
363 fprintf(f, "Begins executing continuously.\n"
364 "May be interrupted with SIGINT.\n");
365 }
366
367 /* gather all these together into a searchable table */
368
369 /* help command gets some assistance in declarations */
370 COMMAND_IMPL(help);
371 COMMAND_HELP(help);
372
373 static struct command_ command_table_[] = {
374 COMMAND_ENTRY(help, 0, -1),
375 COMMAND_ENTRY(quit, 0, -1),
376 COMMAND_ENTRY(load, 1, 2),
377 COMMAND_ENTRY(dump, 0, 2),
378 COMMAND_ENTRY(disassemble, 0, 2),
379 COMMAND_ENTRY(step, 0, 1),
380 COMMAND_ENTRY(run, 0, 0),
381 COMMAND_ENTRY(reset, 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 detailed 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 dcpu16 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 }