initial api changes to support hw_ devices as more-generic attachable modules
[dcpu16] / as-dcpu16.c
1 #include <stdlib.h>
2 #include <unistd.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <strings.h>
6 #include <errno.h>
7 #include <sysexits.h>
8 #include <assert.h>
9
10 #include "dcpu16.h"
11 #include "common.h"
12
13 /*
14 * quick and dirty assembler for dcpu16
15 *
16 * Justin Wind <justin.wind@gmail.com>
17 * 2012 04 07 - implementation started
18 * 2012 04 10 - functional
19 * 2012 04 16 - support dat statements
20 * 2012 05 05 - v1.7 revision started
21 * 2012 05 08 - v1.7 revision implemented
22 *
23 * TODO
24 * needs ability to specify location for code or data
25 * needs ability to specify label as relative to another label
26 * short labels not correctly computed
27 * in label struct, store index of instruction rather than ptr, ptrs for iteration in addr calculation are ugly
28 */
29
30 static const char * const src_id_ = "$Id$";
31
32 const char const out_filename_default_[] = "a.out";
33
34 /* global invocation options */
35 struct options {
36 unsigned int verbose;
37 unsigned int dryrun;
38 } opt_ = {
39 .verbose = 0,
40 .dryrun = 0,
41 };
42
43 #define DEBUG_PRINTF(...) do { if (opt_.verbose > 2) { printf("DEBUG: "); printf(__VA_ARGS__); } } while (0)
44 #define DEBUG_PRINTFQ(...) do { if (opt_.verbose > 2) printf(__VA_ARGS__); } while (0)
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 -- \n\n",
57 prog);
58
59 fprintf(f, "Usage: %s [-h] [-v] [-s] [-o file] file [file [...]]\n",
60 prog);
61
62 if (full) {
63 fprintf(f, "\nOptions:\n"
64 "\t-h -- this screen\n"
65 "\t-o <file> -- output to <file> [default: %s]\n"
66 "\t-s -- allow short labels in instruction words\n"
67 "\t-d -- dry run, print results, do not write to file\n"
68 "\t-v -- verbose output\n",
69 out_filename_default_);
70
71 fprintf(f, "\n%78s\n",
72 src_id_);
73 }
74 }
75
76 /* LSB-0 aaaaaabbbbbooooo */
77 #define OPCODE_BITS 5
78 #define OPERAND_B_BITS 5
79 #define OPERAND_A_BITS 6
80 #define N_BIT_MASK(__x__) ((1 << (__x__)) - 1)
81
82
83 /* instructions have operands */
84 struct operand_ {
85 struct operand_ *next;
86 char *operand; /* tokenized operand text */
87 };
88
89 /* keep an array of instructions as we read them in */
90 struct instruction_ {
91 size_t src_line;
92 char *label; /* set if a label points here */
93 char *opcode; /* tokenized instruction text */
94 struct operand_ *operands; /* list of operands */
95 unsigned int ready : 1; /* bytecode computed? */
96 unsigned int length; /* number of words of bytecode */
97 DCPU16_WORD instr_words[];
98 };
99
100 /* keep an array of labels, indexed back to their instruction locations */
101 struct label_ {
102 char *label; /* name of label */
103 struct instruction_ **instr; /* pointer into array of instructions */
104 unsigned int ready : 1; /* do we know where this label is yet? */
105 DCPU16_WORD addr;
106 };
107
108
109 /* locate and return the label entry matching name */
110 static
111 struct label_ *label_find_(struct dynamic_array *labels, char *name) {
112 size_t x;
113
114 for (x = 0; x < labels->entries; x++) {
115 struct label_ *l = (struct label_ *)DYNARRAY_ITEM(*labels, x);
116 if (strcmp(l->label, name) == 0)
117 return l;
118 }
119 return NULL;
120 }
121
122
123 /* if a label has a validly-calculated address, fetch it */
124 static
125 int label_addr_(struct dynamic_array *labels, char *name, DCPU16_WORD *addr) {
126 struct label_ *l;
127
128 if ( (l = label_find_(labels, name)) == NULL )
129 return -1;
130 if (! l->ready)
131 return -2;
132 *addr = l->addr;
133 return 0;
134 }
135
136
137 /* attempt to determine the addresses of all labels */
138 static
139 void label_addr_calculate_(struct dynamic_array *instructionps, struct dynamic_array *labels) {
140 size_t i;
141
142 /* idea: label1:label2 - calculated as offset between labels */
143
144 /* for each label.. */
145 for (i = 0; i < labels->entries; i++) {
146 struct label_ *l;
147 struct instruction_ **instr;
148 unsigned int word_count = 0;
149
150 l = (struct label_ *)DYNARRAY_ITEM(*labels, i);
151
152 DEBUG_PRINTFQ("%s: calculating address of label '%s'\n", __func__, l->label);
153
154 #if 0
155 force full resolution while debugging
156 /* if it's already calculated, great. */
157 if (l->ready)
158 continue;
159 #endif
160
161 /*
162 * starting at the instruction for this label,
163 * walk backwards through the list of instructions
164 * until we get to the start or a known prior label address.
165 * update our label with the freshly calculated addr
166 */
167
168 /* first fetch the instruction associated with the label we want to know about.. */
169 /* the addr of this instruction will be whatever follows all the preceding instructions */
170 /* so back up one before counting instruction lengths... */
171 instr = ((struct label_ *)DYNARRAY_ITEM(*labels, i))->instr;
172 /* is it the first one? */
173 if (instr == (struct instruction_ **)DYNARRAY_ITEM(*instructionps, 0))
174 break;
175
176 instr--;
177
178 while (instr >= (struct instruction_ **)DYNARRAY_ITEM(*instructionps, 0)) {
179 if ((*instr)->ready == 0)
180 DEBUG_PRINTF("%s: instr '%s' not ready\n", __func__, (*instr)->opcode);
181 word_count += (*instr)->length;
182
183 DEBUG_PRINTF("%s: instr '%s' takes '%u' bytes\n", __func__, (*instr)->opcode, (*instr)->length);
184
185 /* have we come across an instruction which a label points to?
186 it should already be calculated, so just add that on and be done */
187 if ((*instr)->label
188 && strcmp((*instr)->label, l->label)) {
189 DCPU16_WORD addr;
190
191 if (label_addr_(labels, (*instr)->label, &addr)) {
192 fprintf(stderr, "internal error: incomplete prior address for '%s' while calculating '%s'\n",
193 (*instr)->label,
194 l->label);
195 continue;
196 }
197
198 word_count += addr;
199 break;
200 }
201 instr--;
202 }
203 l->addr = word_count;
204 l->ready = 1;
205 DEBUG_PRINTF("label '%s' now has addr of 0x%04x\n", l->label, word_count);
206 }
207 }
208
209
210 /* generate the nibble for a given basic opcode */
211 static
212 int opcode_bits_(char *opcode) {
213 static struct {
214 char op[4];
215 char value;
216 } opcodes_lower_nibble[] = {
217 { "JSR", 0x00 },
218 { "INT", 0x00 },
219 { "IAG", 0x00 },
220 { "IAS", 0x00 },
221 { "RFI", 0x00 },
222 { "IAQ", 0x00 },
223 { "HWN", 0x00 },
224 { "HWQ", 0x00 },
225 { "HWI", 0x00 },
226 { "SET", 0x01 },
227 { "ADD", 0x02 },
228 { "SUB", 0x03 },
229 { "MUL", 0x04 },
230 { "MLI", 0x05 },
231 { "DIV", 0x06 },
232 { "DVI", 0x07 },
233 { "MOD", 0x08 },
234 { "MDI", 0x09 },
235 { "AND", 0x0a },
236 { "BOR", 0x0b },
237 { "XOR", 0x0c },
238 { "SHR", 0x0d },
239 { "ASR", 0x0e },
240 { "SHL", 0x0f },
241 { "IFB", 0x10 },
242 { "IFC", 0x11 },
243 { "IFE", 0x12 },
244 { "IFN", 0x13 },
245 { "IFG", 0x14 },
246 { "IFA", 0x15 },
247 { "IFL", 0x16 },
248 { "IFU", 0x17 },
249 { "ADX", 0x1a },
250 { "SBX", 0x1b },
251 { "STI", 0x1e },
252 { "SDI", 0x1f },
253 { "", 0x00 }
254 }, *o;
255
256 for (o = opcodes_lower_nibble; o->op[0]; o++) {
257 if (strcasecmp(o->op, opcode) == 0)
258 break;
259 }
260
261 if (o->op[0] == '\0') {
262 fprintf(stderr, "unknown instruction '%s'\n", opcode);
263 return -1;
264 }
265
266 return o->value;
267 }
268
269 /* generate the six bits for a given nbi opcode (aka first operand to opcode 0x00) */
270 static
271 int nbi_opcode_bits_(char *nbi_opcode) {
272 static struct {
273 char op[4];
274 char value;
275 } nbi_opcodes_bits[] = {
276 { " ", 0x00 }, /* reserved for future */
277 { "JSR", 0x01 },
278 { "INT", 0x08 },
279 { "IAG", 0x09 },
280 { "IAS", 0x0a },
281 { "RFI", 0x0b },
282 { "IAQ", 0x0c },
283 { "HWN", 0x10 },
284 { "HWQ", 0x11 },
285 { "HWI", 0x12 },
286 { "", 0x00 }
287 }, *o;
288
289 for (o = nbi_opcodes_bits; o->op[0]; o++) {
290 if (strcasecmp(o->op, nbi_opcode) == 0)
291 break;
292 }
293
294 if (o->op[0] == '\0') {
295 fprintf(stderr, "unknown nbi instruction '%s'\n", o->op);
296 return -1;
297 }
298
299 return o->value;
300 }
301
302 /* convert register character like 'x' to value like 0x03 */
303 static inline
304 unsigned int register_enumerate_(char r) {
305 const char regs[] = "AaBbCcXxYyZzIiJj";
306 const char *x = strchr(regs, r);
307
308 if (x)
309 return (x - regs)/2;
310
311 fprintf(stderr, "internal error, unknown register character 0x%02x\n", r);
312 return -1;
313 }
314
315 /* removes all occurences of chars from buf */
316 static inline
317 void buf_strip_chars_(char *buf, char *chars) {
318 char *s, *d;
319
320 for (s = d = buf; *s; s++, d++) {
321 while (*s && strchr(chars, *s)) {
322 s++;
323 }
324 if (!*s)
325 break;
326 *d = *s;
327 }
328 *d = *s;
329 }
330
331
332 /* value_bits_
333 * generate the six bits for a given operand string
334 * returns -1 if it could not parse the operand
335 * returns -2 if it could not parse the operand due to an unresolved label
336 * notes: nextword may be overwritten even if it's not used in final instruction
337 *
338 */
339 static
340 int value_bits_(struct dynamic_array *labels, const char *operand_orig, DCPU16_WORD *nextword, unsigned int *nextwordused, unsigned int allow_short_labels) {
341 static char *operand = NULL;
342 static size_t operand_sz = 0;
343
344 unsigned long l;
345 char *o, *ep;
346
347 /*
348 Our operand working buffer shouldn't ever need to be too big,
349 but DAT might blow that assumption.
350 */
351 if (operand_sz <= strlen(operand_orig)) {
352 void *tmp_ptr;
353 size_t new_sz = strlen(operand_orig);
354
355 if (new_sz < 256)
356 new_sz = 256;
357 new_sz += 256;
358
359 DEBUG_PRINTF("%s: allocating buffer of size %zu\n", __func__, new_sz);
360 tmp_ptr = realloc(operand, new_sz);
361 if (tmp_ptr == NULL) {
362 fprintf(stderr, "%s(%zu):%s\n", "realloc", new_sz, strerror(errno));
363 return -1;
364 }
365 operand = tmp_ptr;
366 operand_sz = new_sz;
367 }
368
369 o = strcpy(operand, operand_orig);
370
371 DEBUG_PRINTF("%s: operand '%s' ", __func__, operand); /* completed later */
372
373 /* this is a very stupid parser */
374
375 /* first, let's trim all whitespace out of string at once to make parsing easier */
376 buf_strip_chars_(operand, " \t\n");
377
378 /* single character might match a register */
379 if (strlen(operand) == 1
380 && strchr("AaBbCcXxYyZzIiJj", *operand)) {
381 DEBUG_PRINTFQ("is register %c\n", *operand);
382 return register_enumerate_(*operand);
383 }
384
385 /* easy matches */
386
387 /* push and pop now share the same operand value */
388 if (strcasecmp(operand, "POP") == 0
389 || strcasecmp(operand, "[SP++]") == 0) {
390 DEBUG_PRINTFQ("is POP\n");
391 return 0x18;
392 }
393 if (strcasecmp(operand, "PUSH") == 0
394 || strcasecmp(operand, "[--SP]") == 0) {
395 DEBUG_PRINTFQ("is PUSH\n");
396 return 0x18;
397 }
398
399 if (strcasecmp(operand, "PEEK") == 0
400 || strcasecmp(operand, "[SP]") == 0) {
401 DEBUG_PRINTFQ("is PEEK\n");
402 return 0x19;
403 }
404
405 /* this could be better, if we had a real token tree */
406 if (strncasecmp(operand, "PICK", 4) == 0) {
407 DEBUG_PRINTFQ("is PICK ");
408
409 errno = 0;
410 l = strtoul(operand + 4, &ep, 0);
411 if (errno == 0
412 && (*(operand + 4) && (*ep == '\0')) ) {
413 if (l > 0xffff) {
414 DEBUG_PRINTFQ("(out of range)\n");
415 fprintf(stderr, "constant invalid in operand '%s'\n", operand_orig);
416 return -1;
417 }
418 } else if (errno == ERANGE) {
419 DEBUG_PRINTFQ("(out of range)\n");
420 fprintf(stderr, "constant invalid in operand '%s'\n", operand_orig);
421 return -1;
422 }
423 *nextword = l & 0xffff;
424 *nextwordused += 1;
425 DEBUG_PRINTFQ("0x%04x\n", *nextword);
426 return 0x1a;
427 }
428
429 if (strcasecmp(operand, "SP") == 0) {
430 DEBUG_PRINTFQ("is register SP\n");
431 return 0x1b;
432 }
433 if (strcasecmp(operand, "PC") == 0) {
434 DEBUG_PRINTFQ("is register PC\n");
435 return 0x1c;
436 }
437 if (strcasecmp(operand, "EX") == 0) {
438 DEBUG_PRINTFQ("is register EX\n");
439 return 0x1d;
440 }
441
442 /* is the operand [bracketed]? */
443 if (operand[0] == '[' && operand[strlen(operand) - 1] == ']') {
444 /* eat the brackets */
445 operand[strlen(operand) - 1] = '\0';
446 operand++;
447
448 /* is it [register]? */
449 if (strlen(operand) == 1
450 && strchr("AaBbCcXxYyZzIiJj", *operand)) {
451 DEBUG_PRINTFQ("is dereferenced register %c\n", *operand);
452 return 0x08 | register_enumerate_(*operand);
453 }
454
455 /* is it [register+something]? */
456 if ( (ep = strchr(operand, '+')) ) {
457 char *reg;
458 char *constant;
459
460 DEBUG_PRINTFQ("is multipart.. ");
461
462 /* eat the plus */
463 *ep = '\0';
464 ep++;
465
466 /* figure out which one is which */
467 if ((strlen(ep) == 1 && strchr("AaBbCcXxYyZzIiJj", *ep))
468 || (strlen(ep) == 2 && strcasecmp(ep, "SP")) ) {
469 reg = ep;
470 constant = operand;
471 } else if ((strlen(operand) == 1 && strchr("AaBbCcXxYyZzIiJj", *operand))
472 || (strlen(operand) == 2 && strcasecmp(operand, "SP")) ) {
473 reg = operand;
474 constant = ep;
475 } else {
476 DEBUG_PRINTFQ("is unparsable\n");
477 fprintf(stderr, "couldn't parse operand '%s'\n", operand_orig);
478 return -1;
479 }
480
481 /* check if something is understandable as a value */
482 errno = 0;
483 l = strtoul(constant, &ep, 0);
484 if (errno == 0
485 && (*constant && (*ep == '\0')) ) {
486 /* string conversion went without issue */
487 /* validate it will fit in a word */
488 if (l > 0xffff) {
489 DEBUG_PRINTFQ("is out of range\n");
490 fprintf(stderr, "constant invalid in operand '%s'\n", operand_orig);
491 return -1;
492 }
493
494 /* seems fine */
495 *nextword = l & 0xffff;
496 *nextwordused += 1;
497
498 /* special case [SP+n]/PICK n */
499 if (strlen(reg) == 2) {
500 DEBUG_PRINTFQ("is PICK 0x%04x\n", *nextword);
501 return 0x1a;
502 }
503
504 DEBUG_PRINTFQ("is a dereferenced register (%c) + constant (%hu)\n", *reg, *nextword);
505 return 0x10 | register_enumerate_(*reg);
506 } else if (errno == ERANGE) {
507 fprintf(stderr, "%s('%s'):%s\n", "strtoul", constant, strerror(errno));
508 }
509
510 /* what? still here? assume it's a label, I guess */
511 /* try to populate nextword with label address */
512 if (label_addr_(labels, operand, nextword)) {
513 DEBUG_PRINTFQ("(deferred label resolution)\n");
514 *nextwordused += 1;
515 return -2;
516 }
517 DEBUG_PRINTFQ("is a dereferenced register (%c) + label\n", *reg);
518 *nextwordused += 1;
519 return 0x10 | register_enumerate_(*reg);
520 }
521
522 /* it must just be a dereferenced literal then */
523
524 errno = 0;
525 l = strtoul(operand, &ep, 0);
526 if (errno == 0
527 && (*operand && (*ep == '\0')) ) {
528 /* string conversion went without issue */
529 /* validate it will fit in a word */
530 if (l > 0xffff) {
531 DEBUG_PRINTFQ("is out of range\n");
532 fprintf(stderr, "constant invalid in operand '%s'\n", operand_orig);
533 return -1;
534 }
535
536 DEBUG_PRINTFQ("is a dereferenced literal value (%hu)\n", *nextword);
537 *nextword = l & 0xffff;
538 *nextwordused += 1;
539 return 0x1e;
540 } else if (errno) {
541 /* if number wasn't parsable, just fall through and assume it's a label */
542 }
543
544 /* not a number? try a label */
545 if (label_addr_(labels, operand, nextword)) {
546 DEBUG_PRINTFQ("(deferred label resolution)\n");
547 *nextwordused += 1;
548 return -2;
549 }
550 DEBUG_PRINTFQ("is a dereferenced label\n");
551 *nextwordused += 1;
552 return 0x1e;
553 }
554
555 /* left with a literal or a label, then */
556
557 errno = 0;
558 l = strtoul(operand, &ep, 0);
559 if (errno == 0
560 || (*operand && (*ep == '\0')) ) {
561 if (l > 0xffff) {
562 DEBUG_PRINTFQ("is out of range\n");
563 fprintf(stderr, "constant invalid in operand '%s'\n", operand_orig);
564 return -1;
565 }
566
567 DEBUG_PRINTFQ("is literal value (%lu)\n", l);
568 if (l < 0x1f) {
569 return l + 0x21;
570 }
571 if (l == 0xffff) {
572 return 0x20;
573 }
574
575 *nextword = l & 0xffff;
576 *nextwordused += 1;
577 return 0x1f;
578 }
579
580 /* try to populate nextword with label address */
581 if (label_addr_(labels, operand, nextword)) {
582 DEBUG_PRINTFQ("(deferred label resolution)\n");
583 /* assume non-small literal value */
584 *nextwordused += 1;
585 return -2;
586 }
587
588 DEBUG_PRINTFQ("is label '%s' (0x%02hx)\n", operand, *nextword);
589 if (allow_short_labels
590 && (*nextword < 0x1f) ) {
591 DEBUG_PRINTF("small value label win\n");
592 return (0x21 + *nextword) & N_BIT_MASK(OPERAND_A_BITS);
593 }
594 if (allow_short_labels
595 && (*nextword == 0xffff) ) {
596 DEBUG_PRINTF("small value label win\n");
597 return 0x20;
598 }
599
600 *nextwordused += 1;
601 return 0x1f;
602 }
603
604 /* prints an instruction's assembly */
605 static inline
606 int instruction_print_(struct instruction_ *i, unsigned int with_label) {
607 struct operand_ *o;
608 int r;
609
610 if (with_label)
611 r = printf("%-16s ", i->label ? i->label : "");
612
613 r = printf("%3s", i->opcode ? i->opcode : "");
614
615 for (o = i->operands; o; o = o->next)
616 r += printf(" %s%s", o->operand, o->next ? "," : "");
617
618 if (i->ready) {
619 DCPU16_WORD l;
620 printf(" [");
621 l = dcpu16_mnemonify_buf(i->instr_words);
622 printf("]");
623
624 if (i->length != l)
625 DEBUG_PRINTF("!!internal inconsistency!! i->length:%u l:%hu should match\n", i->length, l);
626 }
627 return r;
628 }
629
630 /* tokenize_line_
631 * Parses a zero-terminated line of input into a newly-allocated struct instruction_.
632 * [label] instruction [operand[,operand[,...]]]
633 * Does no validation of contents of any of these tokens, as of yet.
634 * does not clean up after itself if a malloc fails
635 */
636 static
637 int tokenize_line_(char *line, struct instruction_ **next_instr) {
638 const char const *whitespace = " \t\n";
639 const char const *quotes = "\"'`";
640 struct instruction_ *instr = NULL;
641 char *x, *st, *qt;
642 char *label, *opcode;
643 struct operand_ *operand_list = NULL;
644 struct operand_ **operand_tail = &operand_list;
645 size_t instr_words_needed = 0;
646
647 assert(line);
648 assert(next_instr);
649
650 *next_instr = NULL;
651
652 /* strip leading whitespace */
653 line += strspn(line, whitespace);
654 if (*line == '\0')
655 return 0;
656
657 /* set first bare ';' to '\0', thus isolating any comments */
658 /* here we only care about the side-effect of truncating the first separator character */
659 (void)strqtok_r(line, ";", '\\', quotes, &qt, &st);
660 /* we don't care if there was an unmatched quote at this point, let's see what happens */
661 if (*line == '\0')
662 return 0;
663
664 /* carve off the first token, determine if it is a label */
665 x = strqtok_r(line, whitespace, '\\', quotes, &qt, &st);
666 if (x == NULL || *x == '\0')
667 return 0;
668 if (qt) {
669 /* labels could contain an unmatched quote character, I guess? */
670 qt = NULL;
671 }
672
673 /* we have something, try to make sense of what it is */
674
675 #ifdef NON_SPEC_LABELS
676 /* I want my labels like 'label:' */
677 if ( *(x + strlen(line) - 1) == ':' ) {
678 *(x + strlen(line) - 1) = '\0';
679 DEBUG_PRINTF("label: %s\n", x);
680
681 label = x;
682
683 opcode = strqtok_r(NULL, whitespace, '\\', quotes, &qt, &st);
684 } else {
685 label = NULL;
686 opcode = x;
687 }
688 #endif /* NON_SPEC_LABELS */
689
690 /* spec gives example of labels as ':label' */
691 if (*x == ':') {
692 *x = '\0';
693 x++;
694 label = x;
695 opcode = strqtok_r(NULL, whitespace, '\\', quotes, &qt, &st);
696 } else {
697 label = NULL;
698 opcode = x;
699 }
700 /* opcodes shouldn't have quotes, so we'll ignore any unmatched quotes again */
701
702 if (opcode && *opcode) {
703 /* if we have an opcode, we'll need at least one word to compile instruction */
704 instr_words_needed++;
705
706 /* build a list of operands to hang off this instruction */
707 while ( (x = strqtok_r(NULL, ",", '\\', quotes, &qt, &st)) ) {
708 struct operand_ *new_operand;
709 char *y;
710
711 /* trim whitespaces */
712 x += strspn(x, whitespace);
713
714 if (*x) {
715 for (y = x + strlen(x) - 1; *y; y--) {
716 if (strchr(whitespace, *y)) {
717 *y = '\0';
718 }
719 }
720 }
721 /* nothing left? */
722 if (*x == '\0') {
723 fprintf(stderr, "null operand encountered\n");
724 return -1;
725 }
726
727 DEBUG_PRINTF("tokenized operand '%s'\n", x);
728
729 new_operand = malloc(sizeof *new_operand);
730 if (new_operand == NULL) {
731 fprintf(stderr, "%s():%s\n", "malloc", strerror(errno));
732 return -1;
733 }
734
735 new_operand->operand = strdup(x);
736 if (new_operand->operand == NULL) {
737 fprintf(stderr, "%s():%s\n", "strdup", strerror(errno));
738 return -1;
739 }
740
741 new_operand->next = NULL;
742
743 if (strchr(quotes, x[0])) {
744 /* if this is a quoted operand, assuming we are in a DAT statement, it will take up slightly less room than it is long */
745 instr_words_needed += strlen(x) - 1;
746 }
747 instr_words_needed++;
748
749 *operand_tail = new_operand;
750 operand_tail = &(*operand_tail)->next;
751 }
752 }
753
754 DEBUG_PRINTF("allocating new instruction with room for %zu bytes\n", instr_words_needed);
755
756 instr = calloc(1, (instr_words_needed * sizeof *instr->instr_words) + sizeof *instr);
757 if (instr == NULL) {
758 fprintf(stderr, "%s():%s\n", "malloc", strerror(errno));
759 return -1;
760 }
761
762 if (label) {
763 instr->label = strdup(label);
764 if (instr->label == NULL) {
765 fprintf(stderr, "%s():%s\n", "malloc", strerror(errno));
766 return -1;
767 }
768 } else {
769 label = NULL;
770 }
771
772 if (opcode) {
773 instr->opcode = strdup(opcode);
774 if (instr->opcode == NULL) {
775 fprintf(stderr, "%s():%s\n", "malloc", strerror(errno));
776 return -1;
777 }
778 } else {
779 opcode = NULL;
780 }
781
782 instr->operands = operand_list;
783
784 *next_instr = instr;
785
786 return 0;
787 }
788
789 /* try to generate bytecode for an instruction */
790 /* returns -1 on unrecoverable error */
791 static
792 int instr_assemble_(struct dynamic_array *labels, struct instruction_ *i, unsigned int allow_short_labels) {
793 unsigned int nwu = 0; /* number of words used */
794 unsigned int incomplete = 0;
795 int bits;
796 struct operand_ *o = i->operands;
797
798 if (opt_.verbose > 2) {
799 printf("%s: assembling %p ", __func__, (void *)i);
800 instruction_print_(i, 1);
801 printf("(line %zu)\n", i->src_line);
802 }
803
804 if (i->opcode == NULL) {
805 assert(i->label);
806 assert(i->operands == NULL);
807 /* just a label, move along */
808 i->length = 0;
809 i->ready = 1;
810 return 0;
811 }
812
813 /* special case DAT */
814 if (strncasecmp(i->opcode, "DAT", 3) == 0) {
815 DEBUG_PRINTF("processing DAT...\n");
816
817 i->length = 0;
818
819 for ( /* */ ; o; o = o->next) {
820 size_t j, dat_len;
821 char *x;
822 unsigned long l;
823
824 DEBUG_PRINTF("DAT operand:'%s' next:%p\n", o->operand, (void *)o->next);
825
826 /* is this a string? */
827 /* does it start with a quote, and end with the same quote? */
828 if ( (x = strchr("\"'`", o->operand[0])) ) {
829 dat_len = strlen(o->operand) - 1;
830 if (o->operand[dat_len] == *x) {
831 /* it is a string */
832 DEBUG_PRINTF("DAT string operand: %s\n", o->operand);
833
834 for (j = 0, x = o->operand + 1;
835 j < dat_len - 1;
836 j++, x++) {
837 i->instr_words[i->length] = *x;
838 i->length++;
839 }
840 /* Note that strings in DAT do not include their zero-terminators */
841 /* specify as 'DAT "string", 0' */
842 }
843 continue;
844 }
845
846 /* is this a number? */
847 char *ep;
848 errno = 0;
849 l = strtoul(o->operand, &ep, 0);
850 if (errno == 0
851 && (*o->operand && (*ep == '\0')) ) {
852 /* conversion succeeded */
853 if (l > 0xffff) {
854 fprintf(stderr, "value '%lu' out of range\n", l);
855 return -1;
856 }
857 i->instr_words[i->length] = l;
858 i->length++;
859 continue;
860 }
861
862 /* otherwise assume it's a label, even if we don't know what it is */
863 if (label_addr_(labels, o->operand, &i->instr_words[i->length])) {
864 DEBUG_PRINTF("(deferred label '%s' resolution)\n", o->operand);
865 incomplete = 1;
866 }
867 i->length++;
868 }
869
870 if (incomplete) {
871 DEBUG_PRINTF("pending label address\n");
872 } else {
873 i->ready = 1;
874 }
875
876 return 0;
877 } /* end of DAT */
878
879 /* start with opcode bits */
880 bits = opcode_bits_(i->opcode);
881 if (bits < 0) {
882 fprintf(stderr, "unrecognized instruction '%s%s", i->opcode, i->operands ? " " : "");
883 for (o = i->operands; o; o = o->next)
884 fprintf(stderr, " %s%s", o->operand, o->next ? "," : "");
885 fprintf(stderr, "'\n");
886 return -1;
887 }
888 i->instr_words[0] |= bits & N_BIT_MASK(OPCODE_BITS);
889
890 /* in rendered bytecode, all instructions have a and b operands; nbi instructions occupy 'b operand' bits. */
891 if ((bits & N_BIT_MASK(OPCODE_BITS)) == 0) {
892 bits = nbi_opcode_bits_(i->opcode);
893 if (bits < 0) {
894 fprintf(stderr, "INTERNAL ERROR: missing instruction in nbi opcode table\n");
895 exit(EX_SOFTWARE);
896 }
897 } else {
898 if (o == NULL) {
899 fprintf(stderr, "'%s' requires more operands\n", i->opcode);
900 return -1;
901 }
902 bits = value_bits_(labels, o->operand, i->instr_words + 1, &nwu, allow_short_labels);
903 if (bits == -1) {
904 fprintf(stderr, "couldn't assemble instruction\n");
905 return -1;
906 } else if (bits == -2) {
907 DEBUG_PRINTF("%s: assembly deferred: unresolved label\n", __func__);
908 /* keep going, but don't finalize until we can calculate label address */
909 incomplete = 1;
910 bits = 0;
911 }
912 o = o->next;
913 }
914 if (bits > N_BIT_MASK(OPERAND_B_BITS)) {
915 fprintf(stderr, "%s: internal error: operand '%s' generated out of range\n", __func__, "b");
916 return -1;
917 }
918 i->instr_words[0] |= (bits & N_BIT_MASK(OPERAND_B_BITS)) << OPCODE_BITS;
919
920 if (o == NULL) {
921 fprintf(stderr, "'%s' requires more operands\n", i->opcode);
922 return -1;
923 }
924
925 bits = value_bits_(labels, o->operand, i->instr_words + 1 + nwu, &nwu, allow_short_labels);
926 if (bits == -1) {
927 fprintf(stderr, "couldn't assemble instruction\n");
928 return -1;
929 } else if (bits == -2) {
930 DEBUG_PRINTF("%s: assembly deferred: unresolved label\n", __func__);
931 /* keep going, but don't finalize until we can calculate label address */
932 incomplete = 1;
933 bits = 0;
934 }
935 o = o->next;
936 if (bits > N_BIT_MASK(OPERAND_A_BITS)) {
937 fprintf(stderr, "%s: internal error: operand '%s' generated out of range\n", __func__, "a");
938 }
939 i->instr_words[0] |= (bits & N_BIT_MASK(OPERAND_A_BITS)) << (OPCODE_BITS + OPERAND_B_BITS);
940
941 if (o != NULL) {
942 fprintf(stderr, "too many operands\n");
943 return -1;
944 }
945
946 /* counting labels as words, we now know at least the maximum instruction length */
947
948 i->length = nwu + 1;
949
950 DEBUG_PRINTF("instruction words: [%u]", i->length);
951 for (bits = 0; bits <= (int)nwu; bits++)
952 DEBUG_PRINTFQ(" %04x", i->instr_words[bits]);
953
954 if (incomplete) {
955 DEBUG_PRINTFQ(" (preliminary)");
956 } else {
957 i->ready = 1;
958 }
959
960 DEBUG_PRINTFQ("\n");
961
962 return 0;
963 }
964
965 /* parse_stream_
966 * read lines from stream f
967 * break each line into parts, populate parts into structures
968 */
969 static
970 int parse_stream_(FILE *f, const char *src, struct dynamic_array *instructionps, struct dynamic_array *labels, unsigned int allow_short_labels) {
971 struct instruction_ *instr, **instr_list_entry;
972 unsigned int line = 0;
973 int retval = 0;
974 char buf[0x4000];
975
976 buf[sizeof buf - 1] = '\0';
977
978 while (fgets(buf, sizeof buf, f)) {
979 line++;
980
981 if (buf[sizeof buf - 1] != '\0') {
982 fprintf(stderr, "%s:%u:%s", src, line, "input line too long\n");
983 retval = -1;
984 break;
985 }
986
987 if (tokenize_line_(buf, &instr)) {
988 fprintf(stderr, "%s:%u:%s", src, line, "trouble tokenizing input\n");
989 retval = -1;
990 break;
991 }
992
993 if (instr) {
994 instr->src_line = line;
995 /* add to list of instructions */
996 instr_list_entry = dynarray_add(instructionps, &instr);
997 if (instr_list_entry == NULL) {
998 fprintf(stderr, "%s:%u:%s", src, line, "could not populate instruction list\n");
999 break;
1000 }
1001
1002 if (instr->label) {
1003 struct label_ new_label = {
1004 .label = instr->label,
1005 .instr = instr_list_entry,
1006 .ready = 0,
1007 .addr = 0,
1008 };
1009 if (label_find_(labels, instr->label)) {
1010 fprintf(stderr, "%s:%u:%s", src, line, "duplicate label\n");
1011 break;
1012 }
1013
1014 if (dynarray_add(labels, &new_label) == NULL) {
1015 fprintf(stderr, "%s:%u:%s", src, line, "could not populate label list\n");
1016 break;
1017 }
1018 label_addr_calculate_(instructionps, labels);
1019 }
1020
1021 if (instr_assemble_(labels, instr, allow_short_labels)) {
1022 fprintf(stderr, "%s:%u:%s", src, line, "could not assemble instruction\n");
1023 break;
1024 }
1025 }
1026 }
1027 if (ferror(f)) {
1028 fprintf(stderr, "%s():%s\n", "fgets", strerror(errno));
1029 return -1;
1030 }
1031 if (! feof(f)) {
1032 fprintf(stderr, "parsing aborted\n");
1033 return -1;
1034 }
1035
1036 return retval;
1037 }
1038
1039 /* assemble_check_
1040 * make a full pass over instruction list to resolve labels
1041 */
1042 static
1043 int assemble_check_(struct dynamic_array *instructionps, struct dynamic_array *labels, unsigned int allow_short_labels) {
1044 int retval = 0;
1045 size_t x;
1046
1047 /* fixing short labels .... */
1048 /* by here we have our list of instructions and their maximum instruction lengths */
1049 /* and we have a list of addresses, based on those maximum lengths */
1050 /* So, if doing short labels, all label addresses are now suspect, so recompute them all... */
1051 /* and reassemble.. */
1052 /* uh.. what else am I forgetting.. this method won't work for labels approaching the limit */
1053 /* of short form addresses, when there are more than the difference number of short form labels used previous to those addresses */
1054
1055 /* try this? keep another list of locations a label address is used */
1056 /* as we step forward, and recompute an address, back up to first occurence of address, make sure nothing else has changed */
1057
1058 DEBUG_PRINTF(" final pass of assembler...\n");
1059 for (x = 0; x < instructionps->entries; x++) {
1060 struct instruction_ **instrp = (struct instruction_ **)DYNARRAY_ITEM(*instructionps, x);
1061 retval = instr_assemble_(labels, *instrp, allow_short_labels);
1062 if (retval) {
1063 fprintf(stderr, "instruction %zu failed to assemble\n", x);
1064 return retval;
1065 }
1066 if (! (*instrp)->ready) {
1067 fprintf(stderr, "instruction not resolvable at line %lu\n", (*instrp)->src_line);
1068 return -1;
1069 }
1070 }
1071
1072 VERBOSE_PRINTF("%3s %6s %-32s %-4s\n", "", "_addr_", "_label_", "_instruction_");
1073 for (x = 0; x < labels->entries; x++) {
1074 struct label_ *l = (struct label_ *)DYNARRAY_ITEM(*labels, x);
1075 if (! l->ready)
1076 retval |= -1;
1077 if (opt_.verbose) {
1078 printf("%3s0x%04x %-32s ",
1079 l->ready ? "" : "*",
1080 l->addr,
1081 l->label);
1082 instruction_print_(*(l->instr), 0);
1083 printf("\n");
1084 }
1085 }
1086
1087 VERBOSE_PRINTF("\n");
1088
1089 if (retval)
1090 fprintf(stderr, "some labels could not be resolved\n");
1091
1092 return retval;
1093 }
1094
1095 /* output_
1096 * write assembled words to named file
1097 */
1098 static
1099 int output_(struct dynamic_array *instructionps, const char *filename) {
1100 FILE *of = NULL;
1101 struct instruction_ **instrp;
1102 size_t i, r, total_words = 0;
1103 size_t x;
1104
1105 if (! opt_.dryrun) {
1106 of = fopen(filename, "w");
1107 if (of == NULL) {
1108 fprintf(stderr, "%s('%s'):%s\n", "fopen", filename, strerror(errno));
1109 return -1;
1110 }
1111 }
1112
1113 for (i = 0; i < instructionps->entries; i++) {
1114 instrp = (struct instruction_ **)DYNARRAY_ITEM(*instructionps, i);
1115
1116 if (opt_.verbose) {
1117 int s;
1118 s = instruction_print_(*instrp, 1);
1119 printf("%*s;", (44 - s) > 0 ? (44 - s) : 0, "");
1120 for (x = 0; x < (*instrp)->length; x++) {
1121 printf(" %04x", (*instrp)->instr_words[x]);
1122 }
1123 printf("\n");
1124 }
1125
1126 if (of) {
1127 r = fwrite((*instrp)->instr_words, sizeof(DCPU16_WORD), (*instrp)->length, of);
1128 if (r < (*instrp)->length) {
1129 fprintf(stderr, "%s():%s\n", "fwrite", strerror(errno));
1130 return -1;
1131 }
1132 }
1133 total_words += (*instrp)->length;
1134 }
1135
1136 fprintf(stderr, "%s 0x%04zx instructions as 0x%04zx words\n",
1137 opt_.dryrun ? "assembled" : "wrote",
1138 i,
1139 total_words);
1140
1141 return 0;
1142 }
1143
1144 static struct dynamic_array *instructionps_;
1145 static struct dynamic_array *labels_;
1146
1147 int main(int argc, char *argv[]) {
1148 const char *out_filename = NULL;
1149 unsigned int allow_short_labels = 0;
1150 int c;
1151
1152 while ( (c = getopt(argc, argv, "dhsvo:")) != EOF ) {
1153 switch (c) {
1154 case 'd':
1155 opt_.dryrun++;
1156 break;
1157
1158 case 's':
1159 allow_short_labels++;
1160 break;
1161
1162 case 'o':
1163 if (out_filename) {
1164 fprintf(stderr, "Sorry, I can only write one file at a time.\n");
1165 exit(EX_CANTCREAT);
1166 }
1167 out_filename = optarg;
1168 break;
1169
1170 case 'v':
1171 opt_.verbose++;
1172 break;
1173
1174 case 'h':
1175 usage_(argv[0], 1);
1176 exit(EX_OK);
1177
1178 default:
1179 usage_(argv[0], 0);
1180 exit(EX_USAGE);
1181 }
1182 }
1183
1184 argc -= optind;
1185 argv += optind;
1186
1187 if (out_filename == NULL)
1188 out_filename = out_filename_default_;
1189
1190 /* init tables */
1191 instructionps_ = dynarray_new(sizeof (struct instruction_ *), 1024);
1192 labels_ = dynarray_new(sizeof(struct label_), 256);
1193 if (instructionps_ == NULL
1194 || labels_ == NULL) {
1195 fprintf(stderr, "failed to initialize\n");
1196 exit(EX_OSERR);
1197 }
1198
1199 /* if filenames were specified, parse them instead of stdin */
1200 if (argc) {
1201 while (argc) {
1202 char *filename = *argv;
1203 FILE *f = fopen(filename, "r");
1204
1205 argc--, argv++;
1206
1207 if (f == NULL) {
1208 fprintf(stderr, "%s('%s'):%s\n", "fopen", filename, strerror(errno));
1209 continue;
1210 }
1211
1212 VERBOSE_PRINTF("assembling '%s'...\n", filename);
1213 c = parse_stream_(f, filename, instructionps_, labels_, allow_short_labels);
1214 fclose(f);
1215 if (c)
1216 break;
1217 }
1218 } else {
1219 VERBOSE_PRINTF("assembling '%s'...\n", "stdin");
1220 c = parse_stream_(stdin, "-", instructionps_, labels_, allow_short_labels);
1221 }
1222 if (c) {
1223 fprintf(stderr, "could not parse input, aborting\n");
1224 exit(EX_DATAERR);
1225 }
1226
1227 if (assemble_check_(instructionps_, labels_, allow_short_labels)) {
1228 fprintf(stderr, "errors prevented assembly\n");
1229 exit(EX_DATAERR);
1230 }
1231
1232 if (output_(instructionps_, out_filename)) {
1233 fprintf(stderr, "failed to create output\n");
1234 exit(EX_OSERR);
1235 }
1236
1237 exit(EX_OK);
1238 }