2 // RMAC - Reboot's Macro Assembler for the Atari Jaguar Console System
3 // DIRECT.C - Directive Handling
4 // Copyright (C) 199x Landon Dyer, 2017 Reboot and Friends
5 // RMAC derived from MADMAC v1.07 Written by Landon Dyer, 1986
6 // Source utilised with the kind permission of Landon Dyer
26 TOKEN exprbuf[128]; // Expression buffer
27 SYM * symbolPtr[1000000]; // Symbol pointers table
28 static long unused; // For supressing 'write' warnings
29 char buffer[256]; // Scratch buffer for messages
31 // Function prototypes
59 int d_equrundef(void);
70 // Directive handler table
81 (void *)d_init, // 9 init
83 (void *)d_goto, // 11 goto
84 (void *)d_dc, // 12 dc
85 (void *)d_ds, // 13 ds
86 d_undmac, // 14 undefmac
89 (void *)d_dcb, // 17 dcb
93 d_incbin, // 21 .incbin //load
94 d_unimpl, // 22 disable
95 d_unimpl, // 23 enable
97 d_regbank0, // 25 .regbank0
98 d_regbank1, // 26 .regbank1
100 d_assert, // 28 assert
102 d_unimpl, // 30* endif
103 d_unimpl, // 31* endc
105 d_include, // 33 include
107 d_unimpl, // 35* macro
108 ExitMacro, // 36* exitm
109 d_unimpl, // 37* endm
113 d_phrase, // 41* endr
114 d_dphrase, // 42 struct
115 d_qphrase, // 43 ends
117 d_subttl, // 45 subttl
121 d_noclear, // 49 .noclear
122 d_equrundef, // 50 .equrundef/.regundef
123 d_ccundef, // 51 .ccundef
124 d_print, // 52 .print
125 d_cstruct, // 53 .cstruct
126 d_jpad, // 54 .jpad (deprecated)
127 d_nojpad, // 55 .nojpad (deprecated)
128 d_gpumain, // 56 .gpumain (deprecated)
129 d_prgflags, // 57 .prgflags
135 // .error - Abort compilation, printing an error message
137 int d_error(char *str)
140 return error("error directive encountered - aborting assembling");
146 return error(string[tok[1]]);
149 return error("error directive encountered - aborting assembling");
156 // .warn - Just display a warning on screen
158 int d_warn(char *str)
161 return warn("WARNING WARNING WARNING");
167 return warn(string[tok[1]]);
170 return warn("WARNING WARNING WARNING");
183 if (!rgpu && !rdsp && !m6502)
184 return error(".org permitted only in gpu/dsp and 6502 sections");
186 if (abs_expr(&address) == ERROR)
188 error("cannot determine org'd address");
199 // 6502. We also kludge `lsloc' so the listing generator doesn't try
200 // to spew out megabytes.
201 if (address > 0xFFFF)
202 return error(range_error);
204 if (sloc != currentorg[0])
206 currentorg[1] = sloc;
210 currentorg[0] = address;
212 lsloc = sloc = address;
213 chptr = scode->chptr + address;
228 char prntstr[LNSIZ]; // String for PRINT directive
229 char format[LNSIZ]; // Format for PRINT directive
230 int formatting = 0; // Formatting on/off
231 int wordlong = 0; // WORD = 0, LONG = 1
232 int outtype = 0; // 0:hex, 1:decimal, 2:unsigned
234 VALUE eval; // Expression value
235 WORD eattr; // Expression attributes
236 SYM * esym; // External symbol involved in expr.
237 TOKEN r_expr[EXPRSIZE];
244 sprintf(prntstr, "%s", string[tok[1]]);
245 printf("%s", prntstr);
248 unused = write(list_fd, prntstr, (LONG)strlen(prntstr));
255 if (tok[1] != SYMBOL)
258 // strcpy(prntstr, (char *)tok[2]);
259 strcpy(prntstr, string[tok[2]]);
263 case 'l': case 'L': wordlong = 1; break;
264 case 'w': case 'W': wordlong = 0; break;
265 case 'x': case 'X': outtype = 0; break;
266 case 'd': case 'D': outtype = 1; break;
267 case 'u': case 'U': outtype = 2; break;
269 error("unknown print format flag");
279 if (expr(r_expr, &eval, &eattr, &esym) != OK)
285 case 0: strcpy(format, "%X"); break;
286 case 1: strcpy(format, "%d" ); break;
287 case 2: strcpy(format, "%u" ); break;
291 sprintf(prntstr, format, eval);
293 sprintf(prntstr, format, eval & 0xFFFF);
295 printf("%s", prntstr);
298 unused = write(list_fd, prntstr, (LONG)strlen(prntstr));
314 error("illegal print token");
320 // Undefine an equated condition code
326 // Check that we are in a RISC section
329 error(".ccundef must be defined in .gpu/.dsp section");
335 error("syntax error; expected symbol");
339 ccname = lookup(string[tok[1]], LABEL, 0);
341 // Make sure symbol is a valid ccdef
342 if (!ccname || !(ccname->sattre & EQUATEDCC))
344 error("invalid equated condition name specified");
348 ccname->sattre |= UNDEF_CC;
355 // Undefine an equated register
357 int d_equrundef(void)
361 // Check that we are in a RISC section
363 return error(".equrundef/.regundef must be defined in .gpu/.dsp section");
367 // Skip preceeding or seperating commas (if any)
371 // Check we are dealing with a symbol
373 return error("syntax error; expected symbol");
375 // Lookup and undef if equated register
376 regname = lookup(string[tok[1]], LABEL, 0);
378 if (regname && (regname->sattre & EQUATEDREG))
380 // Reset the attributes of this symbol...
382 regname->sattre &= ~(EQUATEDREG | BANK_0 | BANK_1);
383 regname->sattre |= UNDEF_EQUR;
386 // Skip over symbol token and address
395 // Do not allow use of the CLR.L opcode
399 warn("CLR.L opcode ignored...");
405 // Include binary file
411 long pos, size, bytesRead;
416 // Check to see if we're in BSS, and, if so, throw an error
419 errors("cannot include binary file \"%s\" in BSS section", string[tok[1]]);
425 error("syntax error; string missing");
429 // Attempt to open the include file in the current directory, then (if that
430 // failed) try list of include files passed in the enviroment string or by
432 if ((fd = open(string[tok[1]], _OPEN_INC)) < 0)
434 for(i=0; nthpath("RMACPATH", i, buf1)!=0; i++)
438 // Append path char if necessary
439 if (fd > 0 && buf1[fd - 1] != SLASHCHAR)
440 strcat(buf1, SLASHSTRING);
442 strcat(buf1, string[tok[1]]);
444 if ((fd = open(buf1, _OPEN_INC)) >= 0)
448 return errors("cannot open: \"%s\"", string[tok[1]]);
453 size = lseek(fd, 0L, SEEK_END);
454 pos = lseek(fd, 0L, SEEK_SET);
457 DEBUG { printf("INCBIN: File '%s' is %li bytes.\n", string[tok[1]], size); }
459 char * fileBuffer = (char *)malloc(size);
460 bytesRead = read(fd, fileBuffer, size);
462 if (bytesRead != size)
464 sprintf(msg, "was only able to read %li bytes from binary file (%s, %li bytes)", bytesRead, string[tok[1]], size);
469 memcpy(chptr, fileBuffer, size);
484 // Set RISC register banks
488 // Set active register bank zero
496 // Set active register bank one
503 // Helper function, to cut down on mistakes & typing
505 static inline void SkipBytes(unsigned bytesToSkip)
510 if ((scattr & SBSS) == 0)
512 chcheck(bytesToSkip);
513 D_ZEROFILL(bytesToSkip);
520 orgaddr += bytesToSkip;
526 // Adjust location to an EVEN value
531 return error(in_6502mode);
533 unsigned skip = (rgpu || rdsp ? orgaddr : sloc) & 0x01;
537 if ((scattr & SBSS) == 0)
556 // Adjust location to a LONG value
560 unsigned lower2Bits = (rgpu || rdsp ? orgaddr : sloc) & 0x03;
561 unsigned bytesToSkip = (0x04 - lower2Bits) & 0x03;
562 SkipBytes(bytesToSkip);
569 // Adjust location to a PHRASE value
571 // N.B.: We have to handle the GPU/DSP cases separately because you can embed
572 // RISC code in the middle of a regular 68K section. Also note that all
573 // of the alignment pseudo-ops will have to be fixed this way.
575 // This *must* behave differently when in a RISC section, as following sloc
576 // (instead of orgaddr) will fuck things up royally. Note that we do it this
577 // way because you can embed RISC code in a 68K section, and have the origin
578 // pointing to a different alignment in the RISC section than the 68K section.
582 unsigned lower3Bits = (rgpu || rdsp ? orgaddr : sloc) & 0x07;
583 unsigned bytesToSkip = (0x08 - lower3Bits) & 0x07;
584 SkipBytes(bytesToSkip);
591 // Adjust location to a DPHRASE value
595 unsigned lower4Bits = (rgpu || rdsp ? orgaddr : sloc) & 0x0F;
596 unsigned bytesToSkip = (0x10 - lower4Bits) & 0x0F;
597 SkipBytes(bytesToSkip);
604 // Adjust location to a QPHRASE value
608 unsigned lower5Bits = (rgpu || rdsp ? orgaddr : sloc) & 0x1F;
609 unsigned bytesToSkip = (0x20 - lower5Bits) & 0x1F;
610 SkipBytes(bytesToSkip);
617 // Do auto-even. This must be called ONLY if 'sloc' is odd.
619 // This is made hairy because, if there was a label on the line, we also have
620 // to adjust its value. This won't work with more than one label on the line,
621 // which is OK since multiple labels are only allowed in AS68 kludge mode, and
622 // the C compiler is VERY paranoid and uses ".even" whenever it can
624 // N.B.: This probably needs the same fixes as above...
628 if (cursect != M6502)
631 sloc++; // Bump BSS section
633 D_byte(0); // Deposit 0.b in non-BSS
635 if (lab_sym != NULL) // Bump label if we have to
642 // Unimplemened directive error
646 return error("unimplemented directive");
651 // Return absolute (not TDB) and defined expression or return an error
653 int abs_expr(VALUE * a_eval)
657 if (expr(exprbuf, a_eval, &eattr, NULL) < 0)
660 if (!(eattr & DEFINED))
661 return error(undef_error);
664 return error(rel_error);
671 // Hand symbols in a symbol-list to a function (kind of like mapcar...)
673 int symlist(int(* func)())
675 const char * em = "symbol list syntax";
682 if ((*func)(string[tok[1]]) != OK)
701 // .include "filename"
711 if (*tok == STRING) // Leave strings ALONE
713 else if (*tok == SYMBOL) // Try to append ".s" to symbols
715 strcpy(buf, string[*++tok]);
719 else // Punt if no STRING or SYMBOL
720 return error("missing filename");
722 // Make sure the user didn't try anything like:
723 // .include equates.s
725 return error("extra stuff after filename -- enclose it in quotes");
727 // Attempt to open the include file in the current directory, then (if that
728 // failed) try list of include files passed in the enviroment string or by
730 if ((j = open(fn, 0)) < 0)
732 for(i=0; nthpath("RMACPATH", i, buf1)!=0; i++)
736 // Append path char if necessary
737 if (j > 0 && buf1[j - 1] != SLASHCHAR)
738 strcat(buf1, SLASHSTRING);
742 if ((j = open(buf1, 0)) >= 0)
746 return errors("cannot open: \"%s\"", fn);
756 // .assert expression [, expression...]
763 for(; expr(exprbuf, &eval, &eattr, NULL)==OK; ++tok)
765 if (!(eattr & DEFINED))
766 return error("forward or undefined .assert");
769 return error("assert failure");
781 // .globl symbol [, symbol] <<<cannot make local symbols global>>>
788 return error("cannot .globl local symbol");
790 if ((sy = lookup(p, LABEL, 0)) == NULL)
792 sy = NewSymbol(p, LABEL, 0);
795 //printf("glob1: Making global symbol: attr=%04X, eattr=%08X, %s\n", sy->sattr, sy->sattre, sy->sname);
807 return error(in_6502mode);
815 // .prgflags expression
822 return error("PRGFLAGS requires value");
823 else if (abs_expr(&eval) == OK)
830 return error("PRGFLAGS requires value");
843 return error(in_6502mode);
849 else if (abs_expr(&eval) != OK)
864 return error("directive forbidden in gpu/dsp mode");
866 return error(in_6502mode);
881 return error("directive forbidden in gpu/dsp mode");
883 return error(in_6502mode);
898 return error("directive forbidden in gpu/dsp mode");
900 return error(in_6502mode);
913 // .ds[.size] expression
917 DEBUG { printf("Directive: .ds.[size] = %u, sloc = $%X\n", siz, sloc); }
921 if (cursect != M6502)
923 if ((siz != SIZB) && (sloc & 1)) // Automatic .even
927 if (abs_expr(&eval) != OK)
930 // Check to see if the value being passed in is negative (who the hell does
931 // that?--nobody does; it's the code gremlins, or rum, that does it)
933 return error("negative sizes not allowed");
935 // In non-TDB section (BSS, ABS and M6502) just advance the location
936 // counter appropriately. In TDB sections, deposit (possibly large) chunks
937 // of zeroed memory....
938 if ((scattr & SBSS) || cursect == M6502)
944 if (cursect == M6502)
947 just_bss = 1; // No data deposited (8-bit CPU mode)
951 dep_block(eval, siz, (VALUE)0, (WORD)(DEFINED | ABS), NULL);
960 // dc.b, dc.w / dc, dc.l, dc.i
968 if ((scattr & SBSS) != 0)
969 return error("illegal initialization of section");
971 // Do an auto_even if it's not BYTE sized (hmm, should we be doing this???)
972 if (cursect != M6502 && (siz != SIZB) && (sloc & 1))
975 // Check to see if we're trying to set LONGS on a non 32-bit aligned
976 // address in a GPU or DSP section, in their local RAM
977 if ((siz == SIZL) && (orgaddr & 0x03)
978 && ((rgpu && (orgaddr >= 0xF03000) && (orgaddr <= 0xF03FFFF))
979 || (rdsp && (orgaddr >= 0xF1B000) && (orgaddr <= 0xF1CFFFF))))
980 warn("depositing LONGs on a non-long address in local RAM");
984 // dc.b 'string' [,] ...
985 if (siz == SIZB && *tok == STRING && (tok[2] == ',' || tok[2] == EOL))
987 uint32_t i = strlen(string[tok[1]]);
989 if ((challoc - ch_size) < i)
992 for(p=string[tok[1]]; *p!=EOS; p++)
999 int movei = 0; // MOVEI flag for dc.i
1008 // dc.x <expression>
1011 if (expr(exprbuf, &eval, &eattr, &esym) != OK)
1014 uint16_t tdb = eattr & TDB;
1015 uint16_t defined = eattr & DEFINED;
1017 if ((challoc - ch_size) < 4)
1025 AddFixup(FU_BYTE | FU_SEXT, sloc, exprbuf);
1030 if (eval + 0x100 >= 0x200)
1032 sprintf(buffer, "%s (value = $%X)", range_error, eval);
1033 return error(buffer);
1037 return error("non-absolute byte value");
1047 AddFixup(FU_WORD | FU_SEXT, sloc, exprbuf);
1052 if (eval + 0x10000 >= 0x20000)
1053 return error(range_error);
1056 MarkRelocatable(cursect, sloc, tdb, MWORD, NULL);
1058 // Deposit 68000 or 6502 (byte-reversed) word
1059 if (cursect != M6502)
1068 return error(in_6502mode);
1073 AddFixup(FU_LONG | FU_MOVEI, sloc, exprbuf);
1075 AddFixup(FU_LONG, sloc, exprbuf);
1082 MarkRelocatable(cursect, sloc, tdb, MLONG, NULL);
1085 eval = WORDSWAP32(eval);
1103 // dcb[.siz] expr1,expr2 - Make 'expr1' copies of 'expr2'
1110 DEBUG { printf("dcb: section is %s%s%s (scattr=$%X)\n", (cursect & TEXT ? "TEXT" : ""), (cursect & DATA ? " DATA" : ""), (cursect & BSS ? "BSS" : ""), scattr); }
1112 if ((scattr & SBSS) != 0)
1113 return error("illegal initialization of section");
1115 if (abs_expr(&evalc) != OK)
1119 return error("missing comma");
1121 if (expr(exprbuf, &eval, &eattr, NULL) < 0)
1124 if (cursect != M6502 && (siz != SIZB) && (sloc & 1))
1127 dep_block(evalc, siz, eval, eattr, exprbuf);
1133 // Generalized initialization directive
1135 // .init[.siz] [#count,] expression [.size] , ...
1137 // The size suffix on the ".init" directive becomes the default size of the
1138 // objects to deposit. If an item is preceeded with a sharp (immediate) sign
1139 // and an expression, it specifies a repeat count. The value to be deposited
1140 // may be followed by a size suffix, which overrides the default size.
1142 int d_init(WORD def_siz)
1149 if ((scattr & SBSS) != 0)
1150 return error(".init not permitted in BSS or ABS");
1153 return error("directive forbidden in gpu/dsp mode");
1157 // Get repeat count (defaults to 1)
1162 if (abs_expr(&count) != OK)
1166 return error(comma_error);
1171 // Evaluate expression to deposit
1172 if (expr(exprbuf, &eval, &eattr, NULL) < 0)
1175 switch ((int)*tok++)
1176 { // Determine size of object to deposit
1177 case DOTB: siz = SIZB; break;
1178 case DOTW: siz = SIZB; break;
1179 case DOTL: siz = SIZL; break;
1186 dep_block(count, siz, eval, eattr, exprbuf);
1196 return error(comma_error);
1203 // Deposit 'count' values of size 'siz' in the current (non-BSS) segment
1205 int dep_block(VALUE count, WORD siz, VALUE eval, WORD eattr, TOKEN * exprbuf)
1210 tdb = (WORD)(eattr & TDB);
1211 defined = (WORD)(eattr & DEFINED);
1215 if ((challoc - ch_size) < 4)
1223 AddFixup(FU_BYTE | FU_SEXT, sloc, exprbuf);
1229 return error("non-absolute byte value");
1231 if (eval + 0x100 >= 0x200)
1232 return error(range_error);
1242 AddFixup(FU_WORD | FU_SEXT, sloc, exprbuf);
1248 MarkRelocatable(cursect, sloc, tdb, MWORD, NULL);
1250 if (eval + 0x10000 >= 0x20000)
1251 return error(range_error);
1253 // Deposit 68000 or 6502 (byte-reversed) word
1254 if (cursect != M6502)
1264 return error(in_6502mode);
1268 AddFixup(FU_LONG, sloc, exprbuf);
1274 MarkRelocatable(cursect, sloc, tdb, MLONG, NULL);
1288 // .comm symbol, size
1297 return error(in_6502mode);
1300 return error("missing symbol");
1305 if (*p == '.') // Cannot .comm a local symbol
1306 return error(locgl_error);
1308 if ((sym = lookup(p, LABEL, 0)) == NULL)
1309 sym = NewSymbol(p, LABEL, 0);
1312 if (sym->sattr & DEFINED)
1313 return error(".comm symbol already defined");
1316 sym->sattr = GLOBAL | COMMON | BSS;
1319 return error(comma_error);
1321 if (abs_expr(&eval) != OK) // Parse size of common region
1324 sym->svalue = eval; // Install common symbol's size
1331 // .list - Turn listing on
1343 // .nlist - Turn listing off
1355 // .68000 - Back to 68000 TEXT segment
1360 // Switching from gpu/dsp sections should reset any ORG'd Address
1364 SwitchSection(TEXT);
1370 // .gpu - Switch to GPU assembler
1374 if ((cursect != TEXT) && (cursect != DATA))
1376 error(".gpu can only be used in the TEXT or DATA segments");
1380 // If previous section was dsp or 68000 then we need to reset ORG'd Addresses
1383 //printf("Resetting ORG...\n");
1387 //else printf("NOT resetting ORG!\n");
1389 rgpu = 1; // Set GPU assembly
1390 rdsp = 0; // Unset DSP assembly
1391 regbank = BANK_N; // Set no default register bank
1397 // .dsp - Switch to DSP assembler
1401 if ((cursect != TEXT) && (cursect != DATA))
1403 error(".dsp can only be used in the TEXT or DATA segments");
1407 // If previous section was gpu or 68000 then we need to reset ORG'd Addresses
1414 rdsp = 1; // Set DSP assembly
1415 rgpu = 0; // Unset GPU assembly
1416 regbank = BANK_N; // Set no default register bank
1422 // .cargs [#offset], symbol[.size], ...
1424 // Lists of registers may also be mentioned; they just take up space. Good for
1425 // "documentation" purposes:
1427 // .cargs a6, .arg1, .arg2, .arg3...
1429 // Symbols thus created are ABS and EQUATED.
1433 VALUE eval = 4; // Default to 4 if no offset specified (to account for
1442 return error("directive forbidden in gpu/dsp mode");
1448 if (abs_expr(&eval) != OK)
1451 // Eat the comma, if it's there
1462 // Set env to either local (dot prefixed) or global scope
1463 env = (*p == '.' ? curenv : 0);
1464 symbol = lookup(p, LABEL, env);
1468 symbol = NewSymbol(p, LABEL, env);
1471 else if (symbol->sattr & DEFINED)
1472 return errors("multiply-defined label '%s'", p);
1474 // Put symbol in "order of definition" list
1475 AddToSymbolDeclarationList(symbol);
1477 symbol->sattr |= (ABS | DEFINED | EQUATED);
1478 symbol->svalue = eval;
1481 // What this does is eat any dot suffixes attached to a symbol. If
1482 // it's a .L, it adds 4 to eval; if it's .W or .B, it adds 2. If
1483 // there is no dot suffix, it assumes a size of 2.
1495 else if (*tok >= KW_D0 && *tok <= KW_A7)
1497 if (reglist(&rlist) < 0)
1500 for(i=0; i<16; i++, rlist>>=1)
1523 return error(".cargs syntax");
1527 // Eat commas in between each argument, if they exist
1535 // .cstruct [#offset], symbol[.size], ...
1537 // Lists of registers may also be mentioned; they just take up space. Good for
1538 // "documentation" purposes:
1540 // .cstruct a6, .arg1, .arg2, .arg3...
1542 // Symbols thus created are ABS and EQUATED. Note that this is for
1543 // compatibility with VBCC and the Remover's library. Thanks to GroovyBee for
1548 VALUE eval = 0; // Default, if no offset specified, is zero
1556 return error("directive forbidden in gpu/dsp mode");
1562 if (abs_expr(&eval) != OK)
1565 // Eat the comma, if it's there
1574 symbolName = string[tok[1]];
1576 // Set env to either local (dot prefixed) or global scope
1577 env = (symbolName[0] == '.' ? curenv : 0);
1578 symbol = lookup(symbolName, LABEL, env);
1580 // If the symbol wasn't found, then define it. Otherwise, throw an
1584 symbol = NewSymbol(symbolName, LABEL, env);
1587 else if (symbol->sattr & DEFINED)
1588 return errors("multiply-defined label '%s'", symbolName);
1590 // Put symbol in "order of definition" list
1591 AddToSymbolDeclarationList(symbol);
1595 // Adjust label start address if it's a word or a long, as a byte
1596 // label might have left us on an odd address.
1601 eval += eval & 0x01;
1604 symbol->sattr |= (ABS | DEFINED | EQUATED);
1605 symbol->svalue = eval;
1607 // Check for dot suffixes and adjust space accordingly (longs and
1608 // words on an odd boundary get bumped to the next word aligned
1609 // address). If no suffix, then throw an error.
1622 return error("Symbol missing dot suffix in .cstruct construct");
1627 else if (*tok >= KW_D0 && *tok <= KW_A7)
1629 if (reglist(&rlist) < 0)
1632 for(i=0; i<16; i++, rlist>>=1)
1655 return error(".cstruct syntax");
1659 // Eat commas in between each argument, if they exist
1667 // Undefine a macro - .undefmac macname [, macname...]
1669 int undmac1(char * p)
1671 SYM * symbol = lookup(p, MACRO, 0);
1673 // If the macro symbol exists, cause it to disappear
1675 symbol->stype = (BYTE)SY_UNDEF;
1690 warn("JPAD directive is deprecated/non-functional");
1697 warn("NOJPAD directive is deprecated/non-functional");
1704 return error("What the hell? Do you think we adhere to the Goof standard?");
1709 // .opt - turn a specific (or all) optimisation on or off
1718 char * tmpstr = string[*tok++];
1720 if (ParseOptimization(tmpstr) != OK)
1723 sprintf(temperr, "unknown optimization flag '%s'", tmpstr);
1724 return error(temperr);
1728 return error(".opt directive needs every switch enclosed inside quotation marks");