14 * quick and dirty assembler for dcpu16
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
22 * needs ability to specify location for code or data
23 * needs ability to specify label as relative to another label
24 * short labels not correctly computed
25 * in label struct, store index of instruction rather than ptr, ptrs for iteration in addr calculation are ugly
28 static const char * const src_id_
= "$Id$";
30 const char const out_filename_default_
[] = "a.out";
32 /* global invocation options */
41 #define DEBUG_PRINTF(...) do { if (opt_.verbose > 2) { printf("DEBUG: "); printf(__VA_ARGS__); } } while (0)
42 #define DEBUG_PRINTFQ(...) do { if (opt_.verbose > 2) printf(__VA_ARGS__); } while (0)
43 #define VERBOSE_PRINTF(...) do { if (opt_.verbose) printf(__VA_ARGS__); } while (0)
46 void usage_(char *prog
, unsigned int full
) {
47 FILE *f
= full
? stdout
: stderr
;
48 char *x
= strrchr(prog
, '/');
54 fprintf(f
, "%s -- \n\n",
57 fprintf(f
, "Usage: %s [-h] [-v] [-s] [-o file] file [file [...]]\n",
61 fprintf(f
, "\nOptions:\n"
62 "\t-h -- this screen\n"
63 "\t-o <file> -- output to <file> [default: %s]\n"
64 "\t-s -- allow short labels in instruction words\n"
65 "\t-d -- dry run, print results, do not write to file\n"
66 "\t-v -- verbose output\n",
67 out_filename_default_
);
69 fprintf(f
, "\n%78s\n",
75 /* instructions have operands */
77 struct operand_
*next
;
78 char *operand
; /* tokenized operand text */
81 /* keep an array of instructions as we read them in */
84 char *label
; /* set if a label points here */
85 char *opcode
; /* tokenized instruction text */
86 struct operand_
*operands
; /* list of operands */
87 unsigned int ready
: 1; /* bytecode computed? */
88 unsigned int length
; /* number of words of bytecode */
89 DCPU16_WORD instr_words
[];
92 /* keep an array of labels, indexed back to their instruction locations */
94 char *label
; /* name of label */
95 struct instruction_
**instr
; /* pointer into array of instructions */
96 unsigned int ready
: 1; /* do we know where this label is yet? */
101 /* locate and return the label entry matching name */
103 struct label_
*label_find_(struct dynamic_array
*labels
, char *name
) {
106 for (x
= 0; x
< labels
->entries
; x
++) {
107 struct label_
*l
= (struct label_
*)DYNARRAY_ITEM(*labels
, x
);
108 if (strcmp(l
->label
, name
) == 0)
115 /* if a label has a validly-calculated address, fetch it */
117 int label_addr_(struct dynamic_array
*labels
, char *name
, DCPU16_WORD
*addr
) {
120 if ( (l
= label_find_(labels
, name
)) == NULL
)
129 /* attempt to determine the addresses of all labels */
131 void label_addr_calculate_(struct dynamic_array
*instructionps
, struct dynamic_array
*labels
) {
134 /* idea: label1:label2 - calculated as offset between labels */
136 /* for each label.. */
137 for (i
= 0; i
< labels
->entries
; i
++) {
139 struct instruction_
**instr
;
140 unsigned int word_count
= 0;
142 l
= (struct label_
*)DYNARRAY_ITEM(*labels
, i
);
144 DEBUG_PRINTFQ("%s: calculating address of label '%s'\n", __func__
, l
->label
);
147 force full resolution
while debugging
148 /* if it's already calculated, great. */
154 * starting at the instruction for this label,
155 * walk backwards through the list of instructions
156 * until we get to the start or a known prior label address.
157 * update our label with the freshly calculated addr
160 /* first fetch the instruction associated with the label we want to know about.. */
161 /* the addr of this instruction will be whatever follows all the preceding instructions */
162 /* so back up one before counting instruction lengths... */
163 instr
= ((struct label_
*)DYNARRAY_ITEM(*labels
, i
))->instr
;
164 /* is it the first one? */
165 if (instr
== (struct instruction_
**)DYNARRAY_ITEM(*instructionps
, 0))
170 while (instr
>= (struct instruction_
**)DYNARRAY_ITEM(*instructionps
, 0)) {
171 if ((*instr
)->ready
== 0)
172 DEBUG_PRINTF("%s: instr '%s' not ready\n", __func__
, (*instr
)->opcode
);
173 word_count
+= (*instr
)->length
;
175 DEBUG_PRINTF("%s: instr '%s' takes '%u' bytes\n", __func__
, (*instr
)->opcode
, (*instr
)->length
);
177 /* have we come across an instruction which a label points to?
178 it should already be calculated, so just add that on and be done */
180 && strcmp((*instr
)->label
, l
->label
)) {
183 if (label_addr_(labels
, (*instr
)->label
, &addr
)) {
184 fprintf(stderr
, "internal error: incomplete prior address for '%s' while calculating '%s'\n",
195 l
->addr
= word_count
;
197 DEBUG_PRINTF("label '%s' now has addr of 0x%04x\n", l
->label
, word_count
);
202 /* generate the nibble for a given basic opcode */
204 int opcode_bits_(char *opcode
) {
208 } opcodes_lower_nibble
[] = {
210 /* { "future nbi instruction", 0x00 }, */
229 for (o
= opcodes_lower_nibble
; o
->op
[0]; o
++) {
230 if (strcasecmp(o
->op
, opcode
) == 0)
234 if (o
->op
[0] == '\0') {
235 fprintf(stderr
, "unknown instruction '%s'\n", opcode
);
242 /* generate the six bits for a given nbi opcode (aka first operand to opcode 0x00) */
244 int nbi_opcode_bits_(char *nbi_opcode
) {
248 } nbi_opcodes_bits
[] = {
249 { " ", 0x00 }, /* reserved for future */
254 for (o
= nbi_opcodes_bits
; o
->op
[0]; o
++) {
255 if (strcasecmp(o
->op
, nbi_opcode
) == 0)
259 if (o
->op
[0] == '\0') {
260 fprintf(stderr
, "unknown nbi instruction '%s'\n", o
->op
);
267 /* convert register character like 'x' to value like 0x03 */
269 unsigned int register_enumerate_(char r
) {
270 const char regs
[] = "AaBbCcXxYyZzIiJj";
271 const char *x
= strchr(regs
, r
);
276 fprintf(stderr
, "internal error, unknown register character 0x%02x\n", r
);
280 /* removes all occurences of chars from buf */
282 void buf_strip_chars_(char *buf
, char *chars
) {
285 for (s
= d
= buf
; *s
; s
++, d
++) {
286 while (*s
&& strchr(chars
, *s
)) {
298 * generate the six bits for a given operand string
299 * returns -1 if it could not parse the operand
300 * returns -2 if it could not parse the operand due to an unresolved label
301 * notes: nextword may be overwritten even if it's not used in final instruction
304 int value_bits_(struct dynamic_array
*labels
, const char *operand_orig
, DCPU16_WORD
*nextword
, unsigned int *nextwordused
, unsigned int allow_short_labels
) {
305 static char *operand
= NULL
;
306 static size_t operand_sz
= 0;
312 Our operand working buffer shouldn't ever need to be too big,
313 but DAT might blow that assumption.
315 if (operand_sz
<= strlen(operand_orig
)) {
317 size_t new_sz
= strlen(operand_orig
);
323 DEBUG_PRINTF("%s: allocating buffer of size %zu\n", __func__
, new_sz
);
324 tmp_ptr
= realloc(operand
, new_sz
);
325 if (tmp_ptr
== NULL
) {
326 fprintf(stderr
, "%s(%zu):%s\n", "realloc", new_sz
, strerror(errno
));
333 o
= strcpy(operand
, operand_orig
);
335 DEBUG_PRINTF("%s: operand '%s' ", __func__
, operand
); /* completed later */
337 /* this is a very stupid parser */
339 /* first, let's trim all whitespace out of string at once to make parsing easier */
340 buf_strip_chars_(operand
, " \t\n");
342 /* single character might match a register */
343 if (strlen(operand
) == 1
344 && strchr("AaBbCcXxYyZzIiJj", *operand
)) {
345 DEBUG_PRINTFQ("is register %c\n", *operand
);
346 return register_enumerate_(*operand
);
350 if (strcasecmp(operand
, "POP") == 0) {
351 DEBUG_PRINTFQ("is POP\n");
354 if (strcasecmp(operand
, "PUSH") == 0) {
355 DEBUG_PRINTFQ("is PUSH\n");
358 if (strcasecmp(operand
, "PEEK") == 0) {
359 DEBUG_PRINTFQ("is PEEK\n");
362 if (strcasecmp(operand
, "SP") == 0) {
363 DEBUG_PRINTFQ("is register SP\n");
366 if (strcasecmp(operand
, "PC") == 0) {
367 DEBUG_PRINTFQ("is register PC\n");
370 if (strcasecmp(operand
, "O") == 0) {
371 DEBUG_PRINTFQ("is register O\n");
375 /* is the operand [bracketed]? */
376 if (operand
[0] == '[' && operand
[strlen(operand
) - 1] == ']') {
377 /* eat the brackets */
378 operand
[strlen(operand
) - 1] = '\0';
381 /* is it [register]? */
382 if (strlen(operand
) == 1
383 && strchr("AaBbCcXxYyZzIiJj", *operand
)) {
384 DEBUG_PRINTFQ("is dereferenced register %c\n", *operand
);
385 return 0x08 | register_enumerate_(*operand
);
388 /* is it [register+something]? */
389 if ( (ep
= strchr(operand
, '+')) ) {
393 DEBUG_PRINTFQ("is multipart.. ");
399 /* figure out which one is which */
401 && strchr("AaBbCcXxYyZzIiJj", *ep
)) {
404 } else if (strlen(operand
) == 1
405 && strchr("AaBbCcXxYyZzIiJj", *operand
) ) {
409 DEBUG_PRINTFQ("is unparsable\n");
410 fprintf(stderr
, "couldn't parse operand '%s'\n", operand_orig
);
414 /* check if something is understandable as a value */
416 l
= strtoul(constant
, &ep
, 0);
418 && (*constant
&& (*ep
== '\0')) ) {
419 /* string conversion went without issue */
420 /* validate it will fit in a word */
422 DEBUG_PRINTFQ("is out of range\n");
423 fprintf(stderr
, "constant invalid in operand '%s'\n", operand_orig
);
428 *nextword
= l
& 0xffff;
430 DEBUG_PRINTFQ("is a dereferenced register (%c) + constant (%hu)\n", *reg
, *nextword
);
431 return 0x10 | register_enumerate_(*reg
);
432 } else if (errno
== ERANGE
) {
434 oh
, right
, labels fall through
435 DEBUG_PRINTFQ("is out of range\n");
436 fprintf(stderr
, "trouble with operand '%s': %s\n", operand_orig
, strerror(errno
));
441 /* what? still here? assume it's a label, I guess */
442 /* try to populate nextword with label address */
443 if (label_addr_(labels
, operand
, nextword
)) {
444 DEBUG_PRINTFQ("(deferred label resolution)\n");
448 DEBUG_PRINTFQ("is a dereferenced register (%c) + label\n", *reg
);
450 return 0x10 | register_enumerate_(*reg
);
453 /* it must just be a dereferenced literal then */
456 l
= strtoul(operand
, &ep
, 0);
458 && (*operand
&& (*ep
== '\0')) ) {
459 /* string conversion went without issue */
460 /* validate it will fit in a word */
462 DEBUG_PRINTFQ("is out of range\n");
463 fprintf(stderr
, "constant invalid in operand '%s'\n", operand_orig
);
467 DEBUG_PRINTFQ("is a dereferenced literal value (%hu)\n", *nextword
);
468 *nextword
= l
& 0xffff;
472 DEBUG_PRINTFQ("is out of range\n");
473 fprintf(stderr
, "trouble with operand '%s': %s\n", operand_orig
, strerror(errno
));
476 /* not a number? try a label */
477 if (label_addr_(labels
, operand
, nextword
)) {
478 DEBUG_PRINTFQ("(deferred label resolution)\n");
482 DEBUG_PRINTFQ("is a dereferenced label\n");
487 /* left with a literal or a label, then */
490 l
= strtoul(operand
, &ep
, 0);
492 || (*operand
&& (*ep
== '\0')) ) {
494 DEBUG_PRINTFQ("is out of range\n");
495 fprintf(stderr
, "constant invalid in operand '%s'\n", operand_orig
);
499 DEBUG_PRINTFQ("is literal value (%lu)\n", l
);
504 *nextword
= l
& 0xffff;
509 /* try to populate nextword with label address */
510 if (label_addr_(labels
, operand
, nextword
)) {
511 DEBUG_PRINTFQ("(deferred label resolution)\n");
512 /* assume non-small literal value */
517 DEBUG_PRINTFQ("is label '%s' (0x%02hx)\n", operand
, *nextword
);
518 if (*nextword
< 0x20 && allow_short_labels
) {
519 DEBUG_PRINTF("small value label win\n");
520 return (0x20 + *nextword
) & 0x3f;
527 /* prints an instruction's assembly */
529 int instruction_print_(struct instruction_
*i
, unsigned int with_label
) {
534 r
= printf("%-16s ", i
->label
? i
->label
: "");
536 r
= printf("%3s", i
->opcode
? i
->opcode
: "");
538 for (o
= i
->operands
; o
; o
= o
->next
)
539 r
+= printf(" %s%s", o
->operand
, o
->next
? "," : "");
545 * Parses a zero-terminated line of input into a newly-allocated struct instruction_.
546 * [label] instruction [operand[,operand[,...]]]
547 * Does no validation of contents of any of these tokens, as of yet.
548 * does not clean up after itself if a malloc fails
551 int tokenize_line_(char *line
, struct instruction_
**next_instr
) {
552 const char const *whitespace
= " \t\n";
553 const char const *quotes
= "\"'`";
554 struct instruction_
*instr
= NULL
;
556 char *label
, *opcode
;
557 struct operand_
*operand_list
= NULL
;
558 struct operand_
**operand_tail
= &operand_list
;
559 size_t instr_words_needed
= 0;
566 /* strip leading whitespace */
567 line
+= strspn(line
, whitespace
);
571 /* set first bare ';' to '\0', thus isolating any comments */
572 /* here we only care about the side-effect of truncating the first separator character */
573 (void)strqtok_r(line
, ";", '\\', quotes
, &qt
, &st
);
574 /* we don't care if there was an unmatched quote at this point, let's see what happens */
578 /* carve off the first token, determine if it is a label */
579 x
= strqtok_r(line
, whitespace
, '\\', quotes
, &qt
, &st
);
580 if (x
== NULL
|| *x
== '\0')
583 /* labels could contain an unmatched quote character, I guess? */
587 /* we have something, try to make sense of what it is */
589 #ifdef NON_SPEC_LABELS
590 /* I want my labels like 'label:' */
591 if ( *(x
+ strlen(line
) - 1) == ':' ) {
592 *(x
+ strlen(line
) - 1) = '\0';
593 DEBUG_PRINTF("label: %s\n", x
);
597 opcode
= strqtok_r(NULL
, whitespace
, '\\', quotes
, &qt
, &st
);
602 #endif /* NON_SPEC_LABELS */
604 /* spec gives example of labels as ':label' */
609 opcode
= strqtok_r(NULL
, whitespace
, '\\', quotes
, &qt
, &st
);
614 /* opcodes shouldn't have quotes, so we'll ignore any unmatched quotes again */
616 if (opcode
&& *opcode
) {
617 /* if we have an opcode, we'll need at least one word to compile instruction */
618 instr_words_needed
++;
620 /* build a list of operands to hang off this instruction */
621 while ( (x
= strqtok_r(NULL
, ",", '\\', quotes
, &qt
, &st
)) ) {
622 struct operand_
*new_operand
;
625 /* trim whitespaces */
626 x
+= strspn(x
, whitespace
);
629 for (y
= x
+ strlen(x
) - 1; *y
; y
--) {
630 if (strchr(whitespace
, *y
)) {
637 fprintf(stderr
, "null operand encountered\n");
641 DEBUG_PRINTF("tokenized operand '%s'\n", x
);
643 new_operand
= malloc(sizeof *new_operand
);
644 if (new_operand
== NULL
) {
645 fprintf(stderr
, "%s():%s\n", "malloc", strerror(errno
));
649 new_operand
->operand
= strdup(x
);
650 if (new_operand
->operand
== NULL
) {
651 fprintf(stderr
, "%s():%s\n", "strdup", strerror(errno
));
655 new_operand
->next
= NULL
;
657 if (strchr(quotes
, x
[0])) {
658 /* if this is a quoted operand, assuming we are in a DAT statement, it will take up slightly less room than it is long */
659 instr_words_needed
+= strlen(x
) - 1;
661 instr_words_needed
++;
663 *operand_tail
= new_operand
;
664 operand_tail
= &(*operand_tail
)->next
;
668 DEBUG_PRINTF("allocating new instruction with room for %zu bytes\n", instr_words_needed
);
670 instr
= calloc(1, (instr_words_needed
* sizeof *instr
->instr_words
) + sizeof *instr
);
672 fprintf(stderr
, "%s():%s\n", "malloc", strerror(errno
));
677 instr
->label
= strdup(label
);
678 if (instr
->label
== NULL
) {
679 fprintf(stderr
, "%s():%s\n", "malloc", strerror(errno
));
687 instr
->opcode
= strdup(opcode
);
688 if (instr
->opcode
== NULL
) {
689 fprintf(stderr
, "%s():%s\n", "malloc", strerror(errno
));
696 instr
->operands
= operand_list
;
703 /* try to generate bytecode for an instruction */
704 /* returns -1 on unrecoverable error */
706 int instr_assemble_(struct dynamic_array
*labels
, struct instruction_
*i
, unsigned int allow_short_labels
) {
707 unsigned int nwu
= 0; /* number of words used */
708 unsigned int incomplete
= 0;
710 struct operand_
*o
= i
->operands
;
712 if (opt_
.verbose
> 2) {
713 printf("%s: assembling %p ", __func__
, i
);
714 instruction_print_(i
, 1);
715 printf("(line %zu)\n", i
->src_line
);
719 while debugging
, always reassemble
721 /* already assembled, nothing to do */
726 if (i
->opcode
== NULL
) {
728 assert(i
->operands
== NULL
);
729 /* just a label, move along */
735 /* special case DAT */
736 if (strncasecmp(i
->opcode
, "DAT", 3) == 0) {
737 DEBUG_PRINTF("processing DAT...\n");
741 for ( /* */ ; o
; o
= o
->next
) {
746 DEBUG_PRINTF("DAT operand:'%s' next:%p\n", o
->operand
, o
->next
);
748 /* is this a string? */
749 /* does it start with a quote, and end with the same quote? */
750 if ( (x
= strchr("\"'`", o
->operand
[0])) ) {
751 dat_len
= strlen(o
->operand
) - 1;
752 if (o
->operand
[dat_len
] == *x
) {
754 DEBUG_PRINTF("DAT string operand: %s\n", o
->operand
);
756 for (j
= 0, x
= o
->operand
+ 1;
759 i
->instr_words
[i
->length
] = *x
;
762 /* Note that strings in DAT do not include their zero-terminators */
763 /* specify as 'DAT "string", 0' */
768 /* is this a number? */
771 l
= strtoul(o
->operand
, &ep
, 0);
773 && (*o
->operand
&& (*ep
== '\0')) ) {
774 /* conversion succeeded */
776 fprintf(stderr
, "value '%lu' out of range\n", l
);
779 i
->instr_words
[i
->length
] = l
;
784 /* otherwise assume it's a label, even if we don't know what it is */
785 if (label_addr_(labels
, o
->operand
, &i
->instr_words
[i
->length
])) {
786 DEBUG_PRINTF("(deferred label '%s' resolution)\n", o
->operand
);
793 DEBUG_PRINTF("pending label address\n");
801 /* start with opcode bits */
802 bits
= opcode_bits_(i
->opcode
);
804 fprintf(stderr
, "unrecognized instruction '%s%s", i
->opcode
, i
->operands
? " " : "");
805 for (o
= i
->operands
; o
; o
= o
->next
)
806 fprintf(stderr
, " %s%s", o
->operand
, o
->next
? "," : "");
807 fprintf(stderr
, "'\n");
810 i
->instr_words
[0] |= 0x0f & bits
;
812 /* in rendered bytecode, all instructions have two operands; nbi instructions take 'first operand' bits. */
813 if ((bits
& 0x0f) == 0) {
814 bits
= nbi_opcode_bits_(i
->opcode
);
816 fprintf(stderr
, "INTERNAL ERROR: missing instruction in nbi opcode table\n");
821 fprintf(stderr
, "'%s' requires more operands\n", i
->opcode
);
824 bits
= value_bits_(labels
, o
->operand
, i
->instr_words
+ 1, &nwu
, allow_short_labels
);
826 fprintf(stderr
, "couldn't assemble instruction\n");
828 } else if (bits
== -2) {
829 DEBUG_PRINTF("%s: assembly deferred: unresolved label\n", __func__
);
830 /* keep going, but don't finalize until we can calculate label address */
836 i
->instr_words
[0] |= (bits
& 0x3f) << 4;
839 fprintf(stderr
, "'%s' requires more operands\n", i
->opcode
);
843 bits
= value_bits_(labels
, o
->operand
, i
->instr_words
+ 1 + nwu
, &nwu
, allow_short_labels
);
845 fprintf(stderr
, "couldn't assemble instruction\n");
847 } else if (bits
== -2) {
848 DEBUG_PRINTF("%s: assembly deferred: unresolved label\n", __func__
);
849 /* keep going, but don't finalize until we can calculate label address */
854 i
->instr_words
[0] |= (bits
& 0x3f) << 10;
857 fprintf(stderr
, "too many operands\n");
861 /* counting labels as words, we now know at least the maximum instruction length */
865 DEBUG_PRINTF("instruction words: [%u]", i
->length
);
866 for (bits
= 0; bits
<= (int)nwu
; bits
++)
867 DEBUG_PRINTFQ(" %04x", i
->instr_words
[bits
]);
870 DEBUG_PRINTFQ(" (preliminary)");
881 * read lines from stream f
882 * break each line into parts, populate parts into structures
885 int parse_stream_(FILE *f
, const char *src
, struct dynamic_array
*instructionps
, struct dynamic_array
*labels
, unsigned int allow_short_labels
) {
886 struct instruction_
*instr
, **instr_list_entry
;
887 unsigned int line
= 0;
891 buf
[sizeof buf
- 1] = '\0';
893 while (fgets(buf
, sizeof buf
, f
)) {
896 if (buf
[sizeof buf
- 1] != '\0') {
897 fprintf(stderr
, "%s:%u:%s", src
, line
, "input line too long\n");
902 if (tokenize_line_(buf
, &instr
)) {
903 fprintf(stderr
, "%s:%u:%s", src
, line
, "trouble tokenizing input\n");
909 instr
->src_line
= line
;
910 /* add to list of instructions */
911 instr_list_entry
= dynarray_add(instructionps
, &instr
);
912 if (instr_list_entry
== NULL
) {
913 fprintf(stderr
, "%s:%u:%s", src
, line
, "could not populate instruction list\n");
918 struct label_ new_label
= {
919 .label
= instr
->label
,
920 .instr
= instr_list_entry
,
924 if (label_find_(labels
, instr
->label
)) {
925 fprintf(stderr
, "%s:%u:%s", src
, line
, "duplicate label\n");
929 if (dynarray_add(labels
, &new_label
) == NULL
) {
930 fprintf(stderr
, "%s:%u:%s", src
, line
, "could not populate label list\n");
933 label_addr_calculate_(instructionps
, labels
);
936 if (instr_assemble_(labels
, instr
, allow_short_labels
)) {
937 fprintf(stderr
, "%s:%u:%s", src
, line
, "could not assemble instruction\n");
943 fprintf(stderr
, "%s():%s\n", "fgets", strerror(errno
));
947 fprintf(stderr
, "parsing aborted\n");
955 * make a full pass over instruction list to resolve labels
958 int assemble_check_(struct dynamic_array
*instructionps
, struct dynamic_array
*labels
, unsigned int allow_short_labels
) {
962 /* fixing short labels .... */
963 /* by here we have our list of instructions and their maximum instruction lengths */
964 /* and we have a list of addresses, based on those maximum lengths */
965 /* So, if doing short labels, all label addresses are now suspect, so recompute them all... */
966 /* and reassemble.. */
967 /* uh.. what else am I forgetting.. this method won't work for labels approaching the limit */
968 /* of short form addresses, when there are more than the difference number of short form labels used previous to those addresses */
970 /* try this? keep another list of locations a label address is used */
971 /* as we step forward, and recompute an address, back up to first occurence of address, make sure nothing else has changed */
973 DEBUG_PRINTF(" final pass of assembler...\n");
974 for (x
= 0; x
< instructionps
->entries
; x
++) {
975 struct instruction_
**instrp
= (struct instruction_
**)DYNARRAY_ITEM(*instructionps
, x
);
976 retval
= instr_assemble_(labels
, *instrp
, allow_short_labels
);
978 fprintf(stderr
, "instruction %zu failed to assemble\n", x
);
981 if (! (*instrp
)->ready
) {
982 fprintf(stderr
, "instruction not resolvable\n");
987 VERBOSE_PRINTF("%3s %6s %-32s %-4s\n", "", "_addr_", "_label_", "_instruction_");
988 for (x
= 0; x
< labels
->entries
; x
++) {
989 struct label_
*l
= (struct label_
*)DYNARRAY_ITEM(*labels
, x
);
993 printf("%3s0x%04x %-32s ",
997 instruction_print_(*(l
->instr
), 0);
1002 VERBOSE_PRINTF("\n");
1005 fprintf(stderr
, "some labels could not be resolved\n");
1011 * write assembled words to named file
1014 int output_(struct dynamic_array
*instructionps
, const char *filename
) {
1016 struct instruction_
**instrp
;
1017 size_t i
, r
, total_words
= 0;
1020 if (! opt_
.dryrun
) {
1021 of
= fopen(filename
, "w");
1023 fprintf(stderr
, "%s('%s'):%s\n", "fopen", filename
, strerror(errno
));
1028 for (i
= 0; i
< instructionps
->entries
; i
++) {
1029 instrp
= (struct instruction_
**)DYNARRAY_ITEM(*instructionps
, i
);
1033 s
= instruction_print_(*instrp
, 1);
1034 printf("%*s;", (44 - s
) > 0 ? (44 - s
) : 0, "");
1035 for (x
= 0; x
< (*instrp
)->length
; x
++) {
1036 printf(" %04x", (*instrp
)->instr_words
[x
]);
1042 r
= fwrite((*instrp
)->instr_words
, sizeof(DCPU16_WORD
), (*instrp
)->length
, of
);
1043 if (r
< (*instrp
)->length
) {
1044 fprintf(stderr
, "%s():%s\n", "fwrite", strerror(errno
));
1048 total_words
+= (*instrp
)->length
;
1051 fprintf(stderr
, "%s 0x%04zx instructions as 0x%04zx words\n",
1052 opt_
.dryrun
? "assembled" : "wrote",
1059 static struct dynamic_array
*instructionps_
;
1060 static struct dynamic_array
*labels_
;
1062 int main(int argc
, char *argv
[]) {
1063 const char *out_filename
= NULL
;
1064 unsigned int allow_short_labels
= 0;
1067 while ( (c
= getopt(argc
, argv
, "dhsvo:")) != EOF
) {
1074 allow_short_labels
++;
1079 fprintf(stderr
, "Sorry, I can only write one file at a time.\n");
1082 out_filename
= optarg
;
1102 if (out_filename
== NULL
)
1103 out_filename
= out_filename_default_
;
1106 instructionps_
= dynarray_new(sizeof (struct instruction_
*), 1024);
1107 labels_
= dynarray_new(sizeof(struct label_
), 256);
1108 if (instructionps_
== NULL
1109 || labels_
== NULL
) {
1110 fprintf(stderr
, "failed to initialize\n");
1114 /* if filenames were specified, parse them instead of stdin */
1117 char *filename
= *argv
;
1118 FILE *f
= fopen(filename
, "r");
1123 fprintf(stderr
, "%s('%s'):%s\n", "fopen", filename
, strerror(errno
));
1127 VERBOSE_PRINTF("assembling '%s'...\n", filename
);
1128 c
= parse_stream_(f
, filename
, instructionps_
, labels_
, allow_short_labels
);
1134 VERBOSE_PRINTF("assembling '%s'...\n", "stdin");
1135 c
= parse_stream_(stdin
, "-", instructionps_
, labels_
, allow_short_labels
);
1138 fprintf(stderr
, "could not parse input, aborting\n");
1142 if (assemble_check_(instructionps_
, labels_
, allow_short_labels
)) {
1143 fprintf(stderr
, "errors prevented assembly\n");
1147 if (output_(instructionps_
, out_filename
)) {
1148 fprintf(stderr
, "failed to create output\n");