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
25 TOKEN exprbuf[128]; // Expression buffer
26 SYM * symbolPtr[1000000]; // Symbol pointers table
27 static long unused; // For supressing 'write' warnings
28 char buffer[256]; // Scratch buffer for messages
31 // Directive handler table
42 (void *)d_init, // 9 init
44 (void *)d_goto, // 11 goto
45 (void *)d_dc, // 12 dc
46 (void *)d_ds, // 13 ds
47 d_undmac, // 14 undefmac
50 (void *)d_dcb, // 17 dcb
54 d_incbin, // 21 .incbin //load
55 d_unimpl, // 22 disable
56 d_unimpl, // 23 enable
58 d_regbank0, // 25 .regbank0
59 d_regbank1, // 26 .regbank1
61 d_assert, // 28 assert
63 d_unimpl, // 30* endif
66 d_include, // 33 include
68 d_unimpl, // 35* macro
69 ExitMacro, // 36* exitm
75 d_dphrase, // 42 struct
78 d_subttl, // 45 subttl
82 d_noclear, // 49 .noclear
83 d_equrundef, // 50 .equrundef/.regundef
84 d_ccundef, // 51 .ccundef
86 d_cstruct, // 53 .cstruct
87 d_jpad, // 54 .jpad (deprecated)
88 d_nojpad, // 55 .nojpad (deprecated)
89 d_gpumain, // 56 .gpumain (deprecated)
90 d_prgflags, // 57 .prgflags
96 // .error - Abort compilation, printing an error message
98 int d_error(char *str)
101 return error("error directive encountered - aborting assembling");
107 return error(string[tok[1]]);
110 return error("error directive encountered - aborting assembling");
117 // .warn - Just display a warning on screen
119 int d_warn(char *str)
122 return warn("WARNING WARNING WARNING");
128 return warn(string[tok[1]]);
131 return warn("WARNING WARNING WARNING");
145 return error(".org permitted only in gpu/dsp section");
149 if (abs_expr(&address) == ERROR)
151 error("cannot determine org'd address");
157 //printf("ORG: address = $%08X...\n", orgaddr);
168 char prntstr[LNSIZ]; // String for PRINT directive
169 char format[LNSIZ]; // Format for PRINT directive
170 int formatting = 0; // Formatting on/off
171 int wordlong = 0; // WORD = 0, LONG = 1
172 int outtype = 0; // 0:hex, 1:decimal, 2:unsigned
174 VALUE eval; // Expression value
175 WORD eattr; // Expression attributes
176 SYM * esym; // External symbol involved in expr.
177 TOKEN r_expr[EXPRSIZE];
184 sprintf(prntstr, "%s", string[tok[1]]);
185 printf("%s", prntstr);
188 unused = write(list_fd, prntstr, (LONG)strlen(prntstr));
195 if (tok[1] != SYMBOL)
198 // strcpy(prntstr, (char *)tok[2]);
199 strcpy(prntstr, string[tok[2]]);
203 case 'l': case 'L': wordlong = 1; break;
204 case 'w': case 'W': wordlong = 0; break;
205 case 'x': case 'X': outtype = 0; break;
206 case 'd': case 'D': outtype = 1; break;
207 case 'u': case 'U': outtype = 2; break;
209 error("unknown print format flag");
219 if (expr(r_expr, &eval, &eattr, &esym) != OK)
225 case 0: strcpy(format, "%X"); break;
226 case 1: strcpy(format, "%d" ); break;
227 case 2: strcpy(format, "%u" ); break;
231 sprintf(prntstr, format, eval);
233 sprintf(prntstr, format, eval & 0xFFFF);
235 printf("%s", prntstr);
238 unused = write(list_fd, prntstr, (LONG)strlen(prntstr));
254 error("illegal print token");
260 // Undefine an equated condition code
266 // Check that we are in a RISC section
269 error(".ccundef must be defined in .gpu/.dsp section");
275 error("syntax error; expected symbol");
279 ccname = lookup(string[tok[1]], LABEL, 0);
281 // Make sure symbol is a valid ccdef
282 if (!ccname || !(ccname->sattre & EQUATEDCC))
284 error("invalid equated condition name specified");
288 ccname->sattre |= UNDEF_CC;
295 // Undefine an equated register
297 int d_equrundef(void)
301 // Check that we are in a RISC section
303 return error(".equrundef/.regundef must be defined in .gpu/.dsp section");
307 // Skip preceeding or seperating commas (if any)
311 // Check we are dealing with a symbol
313 return error("syntax error; expected symbol");
315 // Lookup and undef if equated register
316 regname = lookup(string[tok[1]], LABEL, 0);
318 if (regname && (regname->sattre & EQUATEDREG))
320 // Reset the attributes of this symbol...
322 regname->sattre &= ~(EQUATEDREG | BANK_0 | BANK_1);
323 regname->sattre |= UNDEF_EQUR;
326 // Skip over symbol token and address
335 // Do not allow use of the CLR.L opcode
339 warn("CLR.L opcode ignored...");
345 // Include binary file
351 long pos, size, bytesRead;
356 // Check to see if we're in BSS, and, if so, throw an error
359 errors("cannot include binary file \"%s\" in BSS section", string[tok[1]]);
365 error("syntax error; string missing");
369 // Attempt to open the include file in the current directory, then (if that
370 // failed) try list of include files passed in the enviroment string or by
372 if ((fd = open(string[tok[1]], _OPEN_INC)) < 0)
374 for(i=0; nthpath("RMACPATH", i, buf1)!=0; i++)
378 // Append path char if necessary
379 if (fd > 0 && buf1[fd - 1] != SLASHCHAR)
380 strcat(buf1, SLASHSTRING);
382 strcat(buf1, string[tok[1]]);
384 if ((fd = open(buf1, _OPEN_INC)) >= 0)
388 return errors("cannot open: \"%s\"", string[tok[1]]);
393 size = lseek(fd, 0L, SEEK_END);
394 pos = lseek(fd, 0L, SEEK_SET);
397 DEBUG { printf("INCBIN: File '%s' is %li bytes.\n", string[tok[1]], size); }
399 char * fileBuffer = (char *)malloc(size);
400 bytesRead = read(fd, fileBuffer, size);
402 if (bytesRead != size)
404 sprintf(msg, "was only able to read %li bytes from binary file (%s, %li bytes)", bytesRead, string[tok[1]], size);
409 memcpy(chptr, fileBuffer, size);
424 // Set RISC register banks
428 // Set active register bank zero
436 // Set active register bank one
443 // Helper function, to cut down on mistakes & typing
445 static inline void SkipBytes(unsigned bytesToSkip)
450 if ((scattr & SBSS) == 0)
452 chcheck(bytesToSkip);
453 D_ZEROFILL(bytesToSkip);
460 orgaddr += bytesToSkip;
466 // Adjust location to an EVEN value
470 unsigned skip = (rgpu || rdsp ? orgaddr : sloc) & 0x01;
474 if ((scattr & SBSS) == 0)
493 // Adjust location to a LONG value
497 unsigned lower2Bits = (rgpu || rdsp ? orgaddr : sloc) & 0x03;
498 unsigned bytesToSkip = (0x04 - lower2Bits) & 0x03;
499 SkipBytes(bytesToSkip);
506 // Adjust location to a PHRASE value
508 // N.B.: We have to handle the GPU/DSP cases separately because you can embed
509 // RISC code in the middle of a regular 68K section. Also note that all
510 // of the alignment pseudo-ops will have to be fixed this way.
512 // This *must* behave differently when in a RISC section, as following sloc
513 // (instead of orgaddr) will fuck things up royally. Note that we do it this
514 // way because you can embed RISC code in a 68K section, and have the origin
515 // pointing to a different alignment in the RISC section than the 68K section.
519 unsigned lower3Bits = (rgpu || rdsp ? orgaddr : sloc) & 0x07;
520 unsigned bytesToSkip = (0x08 - lower3Bits) & 0x07;
521 SkipBytes(bytesToSkip);
528 // Adjust location to a DPHRASE value
532 unsigned lower4Bits = (rgpu || rdsp ? orgaddr : sloc) & 0x0F;
533 unsigned bytesToSkip = (0x10 - lower4Bits) & 0x0F;
534 SkipBytes(bytesToSkip);
541 // Adjust location to a QPHRASE value
545 unsigned lower5Bits = (rgpu || rdsp ? orgaddr : sloc) & 0x1F;
546 unsigned bytesToSkip = (0x20 - lower5Bits) & 0x1F;
547 SkipBytes(bytesToSkip);
554 // Do auto-even. This must be called ONLY if 'sloc' is odd.
556 // This is made hairy because, if there was a label on the line, we also have
557 // to adjust its value. This won't work with more than one label on the line,
558 // which is OK since multiple labels are only allowed in AS68 kludge mode, and
559 // the C compiler is VERY paranoid and uses ".even" whenever it can
561 // N.B.: This probably needs the same fixes as above...
566 sloc++; // Bump BSS section
568 D_byte(0); // Deposit 0.b in non-BSS
570 if (lab_sym != NULL) // Bump label if we have to
576 // Unimplemened directive error
580 return error("unimplemented directive");
585 // Return absolute (not TDB) and defined expression or return an error
587 int abs_expr(VALUE * a_eval)
591 if (expr(exprbuf, a_eval, &eattr, NULL) < 0)
594 if (!(eattr & DEFINED))
595 return error(undef_error);
598 return error(rel_error);
605 // Hand symbols in a symbol-list to a function (kind of like mapcar...)
607 int symlist(int(* func)())
609 const char * em = "symbol list syntax";
616 if ((*func)(string[tok[1]]) != OK)
635 // .include "filename"
645 if (*tok == STRING) // Leave strings ALONE
647 else if (*tok == SYMBOL) // Try to append ".s" to symbols
649 strcpy(buf, string[*++tok]);
653 else // Punt if no STRING or SYMBOL
654 return error("missing filename");
656 // Make sure the user didn't try anything like:
657 // .include equates.s
659 return error("extra stuff after filename -- enclose it in quotes");
661 // Attempt to open the include file in the current directory, then (if that
662 // failed) try list of include files passed in the enviroment string or by
664 if ((j = open(fn, 0)) < 0)
666 for(i=0; nthpath("RMACPATH", i, buf1)!=0; i++)
670 // Append path char if necessary
671 if (j > 0 && buf1[j - 1] != SLASHCHAR)
672 strcat(buf1, SLASHSTRING);
676 if ((j = open(buf1, 0)) >= 0)
680 return errors("cannot open: \"%s\"", fn);
690 // .assert expression [, expression...]
697 for(; expr(exprbuf, &eval, &eattr, NULL)==OK; ++tok)
699 if (!(eattr & DEFINED))
700 return error("forward or undefined .assert");
703 return error("assert failure");
715 // .globl symbol [, symbol] <<<cannot make local symbols global>>>
722 return error("cannot .globl local symbol");
724 if ((sy = lookup(p, LABEL, 0)) == NULL)
726 sy = NewSymbol(p, LABEL, 0);
729 //printf("glob1: Making global symbol: attr=%04X, eattr=%08X, %s\n", sy->sattr, sy->sattre, sy->sname);
746 // .prgflags expression
753 return error("PRGFLAGS requires value");
754 else if (abs_expr(&eval) == OK)
761 return error("PRGFLAGS requires value");
777 else if (abs_expr(&eval) != OK)
792 return error("directive forbidden in gpu/dsp mode");
807 return error("directive forbidden in gpu/dsp mode");
822 return error("directive forbidden in gpu/dsp mode");
835 // .ds[.size] expression
839 DEBUG { printf("Directive: .ds.[size] = %u, sloc = $%X\n", siz, sloc); }
843 // This gets kind of stupid. This directive is disallowed in normal 68000
844 // mode ("for your own good!"), but is permitted for 6502 and Alcyon-
845 // compatibility modes. For obvious reasons, no auto-even is done in 8-bit
847 if (as68_flag == 0 && (scattr & SBSS) == 0)
848 return error(".ds permitted only in BSS");
850 if ((siz != SIZB) && (sloc & 1)) // Automatic .even
853 if (abs_expr(&eval) != OK)
856 // Check to see if the value being passed in is negative (who the hell does
857 // that?--nobody does; it's the code gremlins, or rum, that does it)
859 return error("negative sizes not allowed");
861 // In non-TDB section (BSS, ABS and M6502) just advance the location
862 // counter appropriately. In TDB sections, deposit (possibly large) chunks
863 // of zeroed memory....
869 just_bss = 1; // No data deposited (8-bit CPU mode)
873 dep_block(eval, siz, (VALUE)0, (WORD)(DEFINED | ABS), NULL);
882 // dc.b, dc.w / dc, dc.l, dc.i
890 if ((scattr & SBSS) != 0)
891 return error("illegal initialization of section");
893 // Do an auto_even if it's not BYTE sized (hmm, should we be doing this???)
894 if ((siz != SIZB) && (sloc & 1))
897 // Check to see if we're trying to set LONGS on a non 32-bit aligned
898 // address in a GPU or DSP section, in their local RAM
899 if ((siz == SIZL) && (orgaddr & 0x03)
900 && ((rgpu && (orgaddr >= 0xF03000) && (orgaddr <= 0xF03FFFF))
901 || (rdsp && (orgaddr >= 0xF1B000) && (orgaddr <= 0xF1CFFFF))))
902 warn("depositing LONGs on a non-long address in local RAM");
906 // dc.b 'string' [,] ...
907 if (siz == SIZB && *tok == STRING && (tok[2] == ',' || tok[2] == EOL))
909 uint32_t i = strlen(string[tok[1]]);
911 if ((challoc - ch_size) < i)
914 for(p=string[tok[1]]; *p!=EOS; p++)
921 int movei = 0; // MOVEI flag for dc.i
933 if (expr(exprbuf, &eval, &eattr, &esym) != OK)
936 uint16_t tdb = eattr & TDB;
937 uint16_t defined = eattr & DEFINED;
939 if ((challoc - ch_size) < 4)
947 AddFixup(FU_BYTE | FU_SEXT, sloc, exprbuf);
952 if (eval + 0x100 >= 0x200)
954 sprintf(buffer, "%s (value = $%X)", range_error, eval);
955 return error(buffer);
959 return error("non-absolute byte value");
969 AddFixup(FU_WORD | FU_SEXT, sloc, exprbuf);
974 if (eval + 0x10000 >= 0x20000)
975 return error(range_error);
978 MarkRelocatable(cursect, sloc, tdb, MWORD, NULL);
980 // Deposit 68000 or 6502 (byte-reversed) word
989 AddFixup(FU_LONG | FU_MOVEI, sloc, exprbuf);
991 AddFixup(FU_LONG, sloc, exprbuf);
998 MarkRelocatable(cursect, sloc, tdb, MLONG, NULL);
1001 eval = WORDSWAP32(eval);
1019 // dcb[.siz] expr1,expr2 - Make 'expr1' copies of 'expr2'
1026 DEBUG { printf("dcb: section is %s%s%s (scattr=$%X)\n", (cursect & TEXT ? "TEXT" : ""), (cursect & DATA ? " DATA" : ""), (cursect & BSS ? "BSS" : ""), scattr); }
1028 if ((scattr & SBSS) != 0)
1029 return error("illegal initialization of section");
1031 if (abs_expr(&evalc) != OK)
1035 return error("missing comma");
1037 if (expr(exprbuf, &eval, &eattr, NULL) < 0)
1040 if ((siz != SIZB) && (sloc & 1))
1043 dep_block(evalc, siz, eval, eattr, exprbuf);
1049 // Generalized initialization directive
1051 // .init[.siz] [#count,] expression [.size] , ...
1053 // The size suffix on the ".init" directive becomes the default size of the
1054 // objects to deposit. If an item is preceeded with a sharp (immediate) sign
1055 // and an expression, it specifies a repeat count. The value to be deposited
1056 // may be followed by a size suffix, which overrides the default size.
1058 int d_init(WORD def_siz)
1065 if ((scattr & SBSS) != 0)
1066 return error(".init not permitted in BSS or ABS");
1069 return error("directive forbidden in gpu/dsp mode");
1073 // Get repeat count (defaults to 1)
1078 if (abs_expr(&count) != OK)
1082 return error(comma_error);
1087 // Evaluate expression to deposit
1088 if (expr(exprbuf, &eval, &eattr, NULL) < 0)
1091 switch ((int)*tok++)
1092 { // Determine size of object to deposit
1093 case DOTB: siz = SIZB; break;
1094 case DOTW: siz = SIZB; break;
1095 case DOTL: siz = SIZL; break;
1102 dep_block(count, siz, eval, eattr, exprbuf);
1112 return error(comma_error);
1119 // Deposit 'count' values of size 'siz' in the current (non-BSS) segment
1121 int dep_block(VALUE count, WORD siz, VALUE eval, WORD eattr, TOKEN * exprbuf)
1126 tdb = (WORD)(eattr & TDB);
1127 defined = (WORD)(eattr & DEFINED);
1131 if ((challoc - ch_size) < 4)
1139 AddFixup(FU_BYTE | FU_SEXT, sloc, exprbuf);
1145 return error("non-absolute byte value");
1147 if (eval + 0x100 >= 0x200)
1148 return error(range_error);
1158 AddFixup(FU_WORD | FU_SEXT, sloc, exprbuf);
1164 MarkRelocatable(cursect, sloc, tdb, MWORD, NULL);
1166 if (eval + 0x10000 >= 0x20000)
1167 return error(range_error);
1169 // Deposit 68000 or 6502 (byte-reversed) word
1177 AddFixup(FU_LONG, sloc, exprbuf);
1183 MarkRelocatable(cursect, sloc, tdb, MLONG, NULL);
1197 // .comm symbol, size
1206 return error("missing symbol");
1211 if (*p == '.') // Cannot .comm a local symbol
1212 return error(locgl_error);
1214 if ((sym = lookup(p, LABEL, 0)) == NULL)
1215 sym = NewSymbol(p, LABEL, 0);
1218 if (sym->sattr & DEFINED)
1219 return error(".comm symbol already defined");
1222 sym->sattr = GLOBAL | COMMON | BSS;
1225 return error(comma_error);
1227 if (abs_expr(&eval) != OK) // Parse size of common region
1230 sym->svalue = eval; // Install common symbol's size
1237 // .list - Turn listing on
1249 // .nlist - Turn listing off
1261 // .68000 - Back to 68000 TEXT segment
1266 // Switching from gpu/dsp sections should reset any ORG'd Address
1270 SwitchSection(TEXT);
1276 // .gpu - Switch to GPU assembler
1280 if ((cursect != TEXT) && (cursect != DATA))
1282 error(".gpu can only be used in the TEXT or DATA segments");
1286 // If previous section was dsp or 68000 then we need to reset ORG'd Addresses
1289 //printf("Resetting ORG...\n");
1293 //else printf("NOT resetting ORG!\n");
1295 rgpu = 1; // Set GPU assembly
1296 rdsp = 0; // Unset DSP assembly
1297 regbank = BANK_N; // Set no default register bank
1303 // .dsp - Switch to DSP assembler
1307 if ((cursect != TEXT) && (cursect != DATA))
1309 error(".dsp can only be used in the TEXT or DATA segments");
1313 // If previous section was gpu or 68000 then we need to reset ORG'd Addresses
1320 rdsp = 1; // Set DSP assembly
1321 rgpu = 0; // Unset GPU assembly
1322 regbank = BANK_N; // Set no default register bank
1328 // .cargs [#offset], symbol[.size], ...
1330 // Lists of registers may also be mentioned; they just take up space. Good for
1331 // "documentation" purposes:
1333 // .cargs a6, .arg1, .arg2, .arg3...
1335 // Symbols thus created are ABS and EQUATED.
1339 VALUE eval = 4; // Default to 4 if no offset specified (to account for
1348 return error("directive forbidden in gpu/dsp mode");
1354 if (abs_expr(&eval) != OK)
1357 // Eat the comma, if it's there
1368 // Set env to either local (dot prefixed) or global scope
1369 env = (*p == '.' ? curenv : 0);
1370 symbol = lookup(p, LABEL, env);
1374 symbol = NewSymbol(p, LABEL, env);
1377 else if (symbol->sattr & DEFINED)
1378 return errors("multiply-defined label '%s'", p);
1380 // Put symbol in "order of definition" list
1381 AddToSymbolDeclarationList(symbol);
1383 symbol->sattr |= (ABS | DEFINED | EQUATED);
1384 symbol->svalue = eval;
1387 // What this does is eat any dot suffixes attached to a symbol. If
1388 // it's a .L, it adds 4 to eval; if it's .W or .B, it adds 2. If
1389 // there is no dot suffix, it assumes a size of 2.
1401 else if (*tok >= KW_D0 && *tok <= KW_A7)
1403 if (reglist(&rlist) < 0)
1406 for(i=0; i<16; i++, rlist>>=1)
1429 return error(".cargs syntax");
1433 // Eat commas in between each argument, if they exist
1441 // .cstruct [#offset], symbol[.size], ...
1443 // Lists of registers may also be mentioned; they just take up space. Good for
1444 // "documentation" purposes:
1446 // .cstruct a6, .arg1, .arg2, .arg3...
1448 // Symbols thus created are ABS and EQUATED. Note that this is for
1449 // compatibility with VBCC and the Remover's library. Thanks to GroovyBee for
1454 VALUE eval = 0; // Default, if no offset specified, is zero
1462 return error("directive forbidden in gpu/dsp mode");
1468 if (abs_expr(&eval) != OK)
1471 // Eat the comma, if it's there
1480 symbolName = string[tok[1]];
1482 // Set env to either local (dot prefixed) or global scope
1483 env = (symbolName[0] == '.' ? curenv : 0);
1484 symbol = lookup(symbolName, LABEL, env);
1486 // If the symbol wasn't found, then define it. Otherwise, throw an
1490 symbol = NewSymbol(symbolName, LABEL, env);
1493 else if (symbol->sattr & DEFINED)
1494 return errors("multiply-defined label '%s'", symbolName);
1496 // Put symbol in "order of definition" list
1497 AddToSymbolDeclarationList(symbol);
1501 // Adjust label start address if it's a word or a long, as a byte
1502 // label might have left us on an odd address.
1507 eval += eval & 0x01;
1510 symbol->sattr |= (ABS | DEFINED | EQUATED);
1511 symbol->svalue = eval;
1513 // Check for dot suffixes and adjust space accordingly (longs and
1514 // words on an odd boundary get bumped to the next word aligned
1515 // address). If no suffix, then throw an error.
1528 return error("Symbol missing dot suffix in .cstruct construct");
1533 else if (*tok >= KW_D0 && *tok <= KW_A7)
1535 if (reglist(&rlist) < 0)
1538 for(i=0; i<16; i++, rlist>>=1)
1561 return error(".cstruct syntax");
1565 // Eat commas in between each argument, if they exist
1573 // Undefine a macro - .undefmac macname [, macname...]
1575 int undmac1(char * p)
1577 SYM * symbol = lookup(p, MACRO, 0);
1579 // If the macro symbol exists, cause it to disappear
1581 symbol->stype = (BYTE)SY_UNDEF;
1596 warn("JPAD directive is deprecated/non-functional");
1603 warn("NOJPAD directive is deprecated/non-functional");
1610 return error("What the hell? Do you think we adhere to the Goof standard?");
1615 // .opt - turn a specific (or all) optimisation on or off
1624 char * tmpstr = string[*tok++];
1626 if (ParseOptimization(tmpstr) != OK)
1629 sprintf(temperr, "unknown optimization flag '%s'", tmpstr);
1630 return error(temperr);
1634 return error(".opt directive needs every switch enclosed inside quotation marks");