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
24 TOKEN exprbuf[128]; // Expression buffer
25 SYM * symbolPtr[1000000]; // Symbol pointers table
26 static long unused; // For supressing 'write' warnings
27 char buffer[256]; // Scratch buffer for messages
30 // Directive handler table
41 (void *)d_init, // 9 init
43 (void *)d_goto, // 11 goto
44 (void *)d_dc, // 12 dc
45 (void *)d_ds, // 13 ds
46 d_undmac, // 14 undefmac
49 (void *)d_dcb, // 17 dcb
53 d_incbin, // 21 .incbin //load
54 d_unimpl, // 22 disable
55 d_unimpl, // 23 enable
57 d_regbank0, // 25 .regbank0
58 d_regbank1, // 26 .regbank1
60 d_assert, // 28 assert
62 d_unimpl, // 30* endif
65 d_include, // 33 include
67 d_unimpl, // 35* macro
68 ExitMacro, // 36* exitm
74 d_dphrase, // 42 struct
77 d_subttl, // 45 subttl
81 d_noclear, // 49 .noclear
82 d_equrundef, // 50 .equrundef/.regundef
83 d_ccundef, // 51 .ccundef
85 d_cstruct, // 53 .cstruct
86 d_jpad, // 54 .jpad (deprecated)
87 d_nojpad, // 55 .nojpad (deprecated)
88 d_gpumain, // 56 .gpumain (deprecated)
89 d_prgflags, // 57 .prgflags
95 // .error - Abort compilation, printing an error message
97 int d_error(char *str)
100 return error("error directive encountered - aborting assembling");
106 return error(string[tok[1]]);
109 return error("error directive encountered - aborting assembling");
116 // .warn - Just display a warning on screen
118 int d_warn(char *str)
121 return warn("WARNING WARNING WARNING");
127 return warn(string[tok[1]]);
130 return warn("WARNING WARNING WARNING");
143 if (!rgpu && !rdsp && !m6502)
144 return error(".org permitted only in gpu/dsp and 6502 sections");
150 if (abs_expr(&address) == ERROR)
152 error("cannot determine org'd address");
158 //printf("ORG: address = $%08X...\n", orgaddr);
165 // We also kludge `lsloc' so the listing generator doesn't
166 // try to spew out megabytes.
169 //if (m6502 == 0) return error(".org permitted only in .6502 section");
170 if (abs_expr(&eval) < 0) return 0;
171 if (eval >= 0x10000L) return error(range_error);
173 if (sloc != currentorg[0])
175 currentorg[1] = sloc;
179 currentorg[0] = eval;
182 chptr = scode->chptr + eval;
196 char prntstr[LNSIZ]; // String for PRINT directive
197 char format[LNSIZ]; // Format for PRINT directive
198 int formatting = 0; // Formatting on/off
199 int wordlong = 0; // WORD = 0, LONG = 1
200 int outtype = 0; // 0:hex, 1:decimal, 2:unsigned
202 VALUE eval; // Expression value
203 WORD eattr; // Expression attributes
204 SYM * esym; // External symbol involved in expr.
205 TOKEN r_expr[EXPRSIZE];
212 sprintf(prntstr, "%s", string[tok[1]]);
213 printf("%s", prntstr);
216 unused = write(list_fd, prntstr, (LONG)strlen(prntstr));
223 if (tok[1] != SYMBOL)
226 // strcpy(prntstr, (char *)tok[2]);
227 strcpy(prntstr, string[tok[2]]);
231 case 'l': case 'L': wordlong = 1; break;
232 case 'w': case 'W': wordlong = 0; break;
233 case 'x': case 'X': outtype = 0; break;
234 case 'd': case 'D': outtype = 1; break;
235 case 'u': case 'U': outtype = 2; break;
237 error("unknown print format flag");
247 if (expr(r_expr, &eval, &eattr, &esym) != OK)
253 case 0: strcpy(format, "%X"); break;
254 case 1: strcpy(format, "%d" ); break;
255 case 2: strcpy(format, "%u" ); break;
259 sprintf(prntstr, format, eval);
261 sprintf(prntstr, format, eval & 0xFFFF);
263 printf("%s", prntstr);
266 unused = write(list_fd, prntstr, (LONG)strlen(prntstr));
282 error("illegal print token");
288 // Undefine an equated condition code
294 // Check that we are in a RISC section
297 error(".ccundef must be defined in .gpu/.dsp section");
303 error("syntax error; expected symbol");
307 ccname = lookup(string[tok[1]], LABEL, 0);
309 // Make sure symbol is a valid ccdef
310 if (!ccname || !(ccname->sattre & EQUATEDCC))
312 error("invalid equated condition name specified");
316 ccname->sattre |= UNDEF_CC;
323 // Undefine an equated register
325 int d_equrundef(void)
329 // Check that we are in a RISC section
331 return error(".equrundef/.regundef must be defined in .gpu/.dsp section");
335 // Skip preceeding or seperating commas (if any)
339 // Check we are dealing with a symbol
341 return error("syntax error; expected symbol");
343 // Lookup and undef if equated register
344 regname = lookup(string[tok[1]], LABEL, 0);
346 if (regname && (regname->sattre & EQUATEDREG))
348 // Reset the attributes of this symbol...
350 regname->sattre &= ~(EQUATEDREG | BANK_0 | BANK_1);
351 regname->sattre |= UNDEF_EQUR;
354 // Skip over symbol token and address
363 // Do not allow use of the CLR.L opcode
367 warn("CLR.L opcode ignored...");
373 // Include binary file
379 long pos, size, bytesRead;
384 // Check to see if we're in BSS, and, if so, throw an error
387 errors("cannot include binary file \"%s\" in BSS section", string[tok[1]]);
393 error("syntax error; string missing");
397 // Attempt to open the include file in the current directory, then (if that
398 // failed) try list of include files passed in the enviroment string or by
400 if ((fd = open(string[tok[1]], _OPEN_INC)) < 0)
402 for(i=0; nthpath("RMACPATH", i, buf1)!=0; i++)
406 // Append path char if necessary
407 if (fd > 0 && buf1[fd - 1] != SLASHCHAR)
408 strcat(buf1, SLASHSTRING);
410 strcat(buf1, string[tok[1]]);
412 if ((fd = open(buf1, _OPEN_INC)) >= 0)
416 return errors("cannot open: \"%s\"", string[tok[1]]);
421 size = lseek(fd, 0L, SEEK_END);
422 pos = lseek(fd, 0L, SEEK_SET);
425 DEBUG { printf("INCBIN: File '%s' is %li bytes.\n", string[tok[1]], size); }
427 char * fileBuffer = (char *)malloc(size);
428 bytesRead = read(fd, fileBuffer, size);
430 if (bytesRead != size)
432 sprintf(msg, "was only able to read %li bytes from binary file (%s, %li bytes)", bytesRead, string[tok[1]], size);
437 memcpy(chptr, fileBuffer, size);
452 // Set RISC register banks
456 // Set active register bank zero
464 // Set active register bank one
471 // Helper function, to cut down on mistakes & typing
473 static inline void SkipBytes(unsigned bytesToSkip)
478 if ((scattr & SBSS) == 0)
480 chcheck(bytesToSkip);
481 D_ZEROFILL(bytesToSkip);
488 orgaddr += bytesToSkip;
494 // Adjust location to an EVEN value
499 return error(in_6502mode);
501 unsigned skip = (rgpu || rdsp ? orgaddr : sloc) & 0x01;
505 if ((scattr & SBSS) == 0)
524 // Adjust location to a LONG value
528 unsigned lower2Bits = (rgpu || rdsp ? orgaddr : sloc) & 0x03;
529 unsigned bytesToSkip = (0x04 - lower2Bits) & 0x03;
530 SkipBytes(bytesToSkip);
537 // Adjust location to a PHRASE value
539 // N.B.: We have to handle the GPU/DSP cases separately because you can embed
540 // RISC code in the middle of a regular 68K section. Also note that all
541 // of the alignment pseudo-ops will have to be fixed this way.
543 // This *must* behave differently when in a RISC section, as following sloc
544 // (instead of orgaddr) will fuck things up royally. Note that we do it this
545 // way because you can embed RISC code in a 68K section, and have the origin
546 // pointing to a different alignment in the RISC section than the 68K section.
550 unsigned lower3Bits = (rgpu || rdsp ? orgaddr : sloc) & 0x07;
551 unsigned bytesToSkip = (0x08 - lower3Bits) & 0x07;
552 SkipBytes(bytesToSkip);
559 // Adjust location to a DPHRASE value
563 unsigned lower4Bits = (rgpu || rdsp ? orgaddr : sloc) & 0x0F;
564 unsigned bytesToSkip = (0x10 - lower4Bits) & 0x0F;
565 SkipBytes(bytesToSkip);
572 // Adjust location to a QPHRASE value
576 unsigned lower5Bits = (rgpu || rdsp ? orgaddr : sloc) & 0x1F;
577 unsigned bytesToSkip = (0x20 - lower5Bits) & 0x1F;
578 SkipBytes(bytesToSkip);
585 // Do auto-even. This must be called ONLY if 'sloc' is odd.
587 // This is made hairy because, if there was a label on the line, we also have
588 // to adjust its value. This won't work with more than one label on the line,
589 // which is OK since multiple labels are only allowed in AS68 kludge mode, and
590 // the C compiler is VERY paranoid and uses ".even" whenever it can
592 // N.B.: This probably needs the same fixes as above...
596 if (cursect != M6502)
599 sloc++; // Bump BSS section
601 D_byte(0); // Deposit 0.b in non-BSS
603 if (lab_sym != NULL) // Bump label if we have to
610 // Unimplemened directive error
614 return error("unimplemented directive");
619 // Return absolute (not TDB) and defined expression or return an error
621 int abs_expr(VALUE * a_eval)
625 if (expr(exprbuf, a_eval, &eattr, NULL) < 0)
628 if (!(eattr & DEFINED))
629 return error(undef_error);
632 return error(rel_error);
639 // Hand symbols in a symbol-list to a function (kind of like mapcar...)
641 int symlist(int(* func)())
643 const char * em = "symbol list syntax";
650 if ((*func)(string[tok[1]]) != OK)
669 // .include "filename"
679 if (*tok == STRING) // Leave strings ALONE
681 else if (*tok == SYMBOL) // Try to append ".s" to symbols
683 strcpy(buf, string[*++tok]);
687 else // Punt if no STRING or SYMBOL
688 return error("missing filename");
690 // Make sure the user didn't try anything like:
691 // .include equates.s
693 return error("extra stuff after filename -- enclose it in quotes");
695 // Attempt to open the include file in the current directory, then (if that
696 // failed) try list of include files passed in the enviroment string or by
698 if ((j = open(fn, 0)) < 0)
700 for(i=0; nthpath("RMACPATH", i, buf1)!=0; i++)
704 // Append path char if necessary
705 if (j > 0 && buf1[j - 1] != SLASHCHAR)
706 strcat(buf1, SLASHSTRING);
710 if ((j = open(buf1, 0)) >= 0)
714 return errors("cannot open: \"%s\"", fn);
724 // .assert expression [, expression...]
731 for(; expr(exprbuf, &eval, &eattr, NULL)==OK; ++tok)
733 if (!(eattr & DEFINED))
734 return error("forward or undefined .assert");
737 return error("assert failure");
749 // .globl symbol [, symbol] <<<cannot make local symbols global>>>
756 return error("cannot .globl local symbol");
758 if ((sy = lookup(p, LABEL, 0)) == NULL)
760 sy = NewSymbol(p, LABEL, 0);
763 //printf("glob1: Making global symbol: attr=%04X, eattr=%08X, %s\n", sy->sattr, sy->sattre, sy->sname);
775 return error(in_6502mode);
783 // .prgflags expression
790 return error("PRGFLAGS requires value");
791 else if (abs_expr(&eval) == OK)
798 return error("PRGFLAGS requires value");
811 return error(in_6502mode);
817 else if (abs_expr(&eval) != OK)
832 return error("directive forbidden in gpu/dsp mode");
834 return error(in_6502mode);
849 return error("directive forbidden in gpu/dsp mode");
851 return error(in_6502mode);
866 return error("directive forbidden in gpu/dsp mode");
868 return error(in_6502mode);
881 // .ds[.size] expression
885 DEBUG { printf("Directive: .ds.[size] = %u, sloc = $%X\n", siz, sloc); }
889 if (cursect != M6502)
891 if ((siz != SIZB) && (sloc & 1)) // Automatic .even
895 if (abs_expr(&eval) != OK)
898 // Check to see if the value being passed in is negative (who the hell does
899 // that?--nobody does; it's the code gremlins, or rum, that does it)
901 return error("negative sizes not allowed");
903 // In non-TDB section (BSS, ABS and M6502) just advance the location
904 // counter appropriately. In TDB sections, deposit (possibly large) chunks
905 // of zeroed memory....
906 if ((scattr & SBSS) || cursect == M6502)
911 if (cursect == M6502) chptr += eval;
912 just_bss = 1; // No data deposited (8-bit CPU mode)
916 dep_block(eval, siz, (VALUE)0, (WORD)(DEFINED | ABS), NULL);
925 // dc.b, dc.w / dc, dc.l, dc.i
933 if ((scattr & SBSS) != 0)
934 return error("illegal initialization of section");
936 // Do an auto_even if it's not BYTE sized (hmm, should we be doing this???)
937 if (cursect != M6502 && (siz != SIZB) && (sloc & 1))
940 // Check to see if we're trying to set LONGS on a non 32-bit aligned
941 // address in a GPU or DSP section, in their local RAM
942 if ((siz == SIZL) && (orgaddr & 0x03)
943 && ((rgpu && (orgaddr >= 0xF03000) && (orgaddr <= 0xF03FFFF))
944 || (rdsp && (orgaddr >= 0xF1B000) && (orgaddr <= 0xF1CFFFF))))
945 warn("depositing LONGs on a non-long address in local RAM");
949 // dc.b 'string' [,] ...
950 if (siz == SIZB && *tok == STRING && (tok[2] == ',' || tok[2] == EOL))
952 uint32_t i = strlen(string[tok[1]]);
954 if ((challoc - ch_size) < i)
957 for(p=string[tok[1]]; *p!=EOS; p++)
964 int movei = 0; // MOVEI flag for dc.i
976 if (expr(exprbuf, &eval, &eattr, &esym) != OK)
979 uint16_t tdb = eattr & TDB;
980 uint16_t defined = eattr & DEFINED;
982 if ((challoc - ch_size) < 4)
990 AddFixup(FU_BYTE | FU_SEXT, sloc, exprbuf);
995 if (eval + 0x100 >= 0x200)
997 sprintf(buffer, "%s (value = $%X)", range_error, eval);
998 return error(buffer);
1002 return error("non-absolute byte value");
1012 AddFixup(FU_WORD | FU_SEXT, sloc, exprbuf);
1017 if (eval + 0x10000 >= 0x20000)
1018 return error(range_error);
1021 MarkRelocatable(cursect, sloc, tdb, MWORD, NULL);
1023 // Deposit 68000 or 6502 (byte-reversed) word
1024 if (cursect != M6502)
1038 return error(in_6502mode);
1043 AddFixup(FU_LONG | FU_MOVEI, sloc, exprbuf);
1045 AddFixup(FU_LONG, sloc, exprbuf);
1052 MarkRelocatable(cursect, sloc, tdb, MLONG, NULL);
1055 eval = WORDSWAP32(eval);
1073 // dcb[.siz] expr1,expr2 - Make 'expr1' copies of 'expr2'
1080 DEBUG { printf("dcb: section is %s%s%s (scattr=$%X)\n", (cursect & TEXT ? "TEXT" : ""), (cursect & DATA ? " DATA" : ""), (cursect & BSS ? "BSS" : ""), scattr); }
1082 if ((scattr & SBSS) != 0)
1083 return error("illegal initialization of section");
1085 if (abs_expr(&evalc) != OK)
1089 return error("missing comma");
1091 if (expr(exprbuf, &eval, &eattr, NULL) < 0)
1094 if (cursect != M6502 && (siz != SIZB) && (sloc & 1))
1097 dep_block(evalc, siz, eval, eattr, exprbuf);
1103 // Generalized initialization directive
1105 // .init[.siz] [#count,] expression [.size] , ...
1107 // The size suffix on the ".init" directive becomes the default size of the
1108 // objects to deposit. If an item is preceeded with a sharp (immediate) sign
1109 // and an expression, it specifies a repeat count. The value to be deposited
1110 // may be followed by a size suffix, which overrides the default size.
1112 int d_init(WORD def_siz)
1119 if ((scattr & SBSS) != 0)
1120 return error(".init not permitted in BSS or ABS");
1123 return error("directive forbidden in gpu/dsp mode");
1127 // Get repeat count (defaults to 1)
1132 if (abs_expr(&count) != OK)
1136 return error(comma_error);
1141 // Evaluate expression to deposit
1142 if (expr(exprbuf, &eval, &eattr, NULL) < 0)
1145 switch ((int)*tok++)
1146 { // Determine size of object to deposit
1147 case DOTB: siz = SIZB; break;
1148 case DOTW: siz = SIZB; break;
1149 case DOTL: siz = SIZL; break;
1156 dep_block(count, siz, eval, eattr, exprbuf);
1166 return error(comma_error);
1173 // Deposit 'count' values of size 'siz' in the current (non-BSS) segment
1175 int dep_block(VALUE count, WORD siz, VALUE eval, WORD eattr, TOKEN * exprbuf)
1180 tdb = (WORD)(eattr & TDB);
1181 defined = (WORD)(eattr & DEFINED);
1185 if ((challoc - ch_size) < 4)
1193 AddFixup(FU_BYTE | FU_SEXT, sloc, exprbuf);
1199 return error("non-absolute byte value");
1201 if (eval + 0x100 >= 0x200)
1202 return error(range_error);
1212 AddFixup(FU_WORD | FU_SEXT, sloc, exprbuf);
1218 MarkRelocatable(cursect, sloc, tdb, MWORD, NULL);
1220 if (eval + 0x10000 >= 0x20000)
1221 return error(range_error);
1223 // Deposit 68000 or 6502 (byte-reversed) word
1224 if (cursect != M6502)
1238 return error(in_6502mode);
1242 AddFixup(FU_LONG, sloc, exprbuf);
1248 MarkRelocatable(cursect, sloc, tdb, MLONG, NULL);
1262 // .comm symbol, size
1271 return error(in_6502mode);
1274 return error("missing symbol");
1279 if (*p == '.') // Cannot .comm a local symbol
1280 return error(locgl_error);
1282 if ((sym = lookup(p, LABEL, 0)) == NULL)
1283 sym = NewSymbol(p, LABEL, 0);
1286 if (sym->sattr & DEFINED)
1287 return error(".comm symbol already defined");
1290 sym->sattr = GLOBAL | COMMON | BSS;
1293 return error(comma_error);
1295 if (abs_expr(&eval) != OK) // Parse size of common region
1298 sym->svalue = eval; // Install common symbol's size
1305 // .list - Turn listing on
1317 // .nlist - Turn listing off
1329 // .68000 - Back to 68000 TEXT segment
1334 // Switching from gpu/dsp sections should reset any ORG'd Address
1338 SwitchSection(TEXT);
1344 // .gpu - Switch to GPU assembler
1348 if ((cursect != TEXT) && (cursect != DATA))
1350 error(".gpu can only be used in the TEXT or DATA segments");
1354 // If previous section was dsp or 68000 then we need to reset ORG'd Addresses
1357 //printf("Resetting ORG...\n");
1361 //else printf("NOT resetting ORG!\n");
1363 rgpu = 1; // Set GPU assembly
1364 rdsp = 0; // Unset DSP assembly
1365 regbank = BANK_N; // Set no default register bank
1371 // .dsp - Switch to DSP assembler
1375 if ((cursect != TEXT) && (cursect != DATA))
1377 error(".dsp can only be used in the TEXT or DATA segments");
1381 // If previous section was gpu or 68000 then we need to reset ORG'd Addresses
1388 rdsp = 1; // Set DSP assembly
1389 rgpu = 0; // Unset GPU assembly
1390 regbank = BANK_N; // Set no default register bank
1396 // .cargs [#offset], symbol[.size], ...
1398 // Lists of registers may also be mentioned; they just take up space. Good for
1399 // "documentation" purposes:
1401 // .cargs a6, .arg1, .arg2, .arg3...
1403 // Symbols thus created are ABS and EQUATED.
1407 VALUE eval = 4; // Default to 4 if no offset specified (to account for
1416 return error("directive forbidden in gpu/dsp mode");
1422 if (abs_expr(&eval) != OK)
1425 // Eat the comma, if it's there
1436 // Set env to either local (dot prefixed) or global scope
1437 env = (*p == '.' ? curenv : 0);
1438 symbol = lookup(p, LABEL, env);
1442 symbol = NewSymbol(p, LABEL, env);
1445 else if (symbol->sattr & DEFINED)
1446 return errors("multiply-defined label '%s'", p);
1448 // Put symbol in "order of definition" list
1449 AddToSymbolDeclarationList(symbol);
1451 symbol->sattr |= (ABS | DEFINED | EQUATED);
1452 symbol->svalue = eval;
1455 // What this does is eat any dot suffixes attached to a symbol. If
1456 // it's a .L, it adds 4 to eval; if it's .W or .B, it adds 2. If
1457 // there is no dot suffix, it assumes a size of 2.
1469 else if (*tok >= KW_D0 && *tok <= KW_A7)
1471 if (reglist(&rlist) < 0)
1474 for(i=0; i<16; i++, rlist>>=1)
1497 return error(".cargs syntax");
1501 // Eat commas in between each argument, if they exist
1509 // .cstruct [#offset], symbol[.size], ...
1511 // Lists of registers may also be mentioned; they just take up space. Good for
1512 // "documentation" purposes:
1514 // .cstruct a6, .arg1, .arg2, .arg3...
1516 // Symbols thus created are ABS and EQUATED. Note that this is for
1517 // compatibility with VBCC and the Remover's library. Thanks to GroovyBee for
1522 VALUE eval = 0; // Default, if no offset specified, is zero
1530 return error("directive forbidden in gpu/dsp mode");
1536 if (abs_expr(&eval) != OK)
1539 // Eat the comma, if it's there
1548 symbolName = string[tok[1]];
1550 // Set env to either local (dot prefixed) or global scope
1551 env = (symbolName[0] == '.' ? curenv : 0);
1552 symbol = lookup(symbolName, LABEL, env);
1554 // If the symbol wasn't found, then define it. Otherwise, throw an
1558 symbol = NewSymbol(symbolName, LABEL, env);
1561 else if (symbol->sattr & DEFINED)
1562 return errors("multiply-defined label '%s'", symbolName);
1564 // Put symbol in "order of definition" list
1565 AddToSymbolDeclarationList(symbol);
1569 // Adjust label start address if it's a word or a long, as a byte
1570 // label might have left us on an odd address.
1575 eval += eval & 0x01;
1578 symbol->sattr |= (ABS | DEFINED | EQUATED);
1579 symbol->svalue = eval;
1581 // Check for dot suffixes and adjust space accordingly (longs and
1582 // words on an odd boundary get bumped to the next word aligned
1583 // address). If no suffix, then throw an error.
1596 return error("Symbol missing dot suffix in .cstruct construct");
1601 else if (*tok >= KW_D0 && *tok <= KW_A7)
1603 if (reglist(&rlist) < 0)
1606 for(i=0; i<16; i++, rlist>>=1)
1629 return error(".cstruct syntax");
1633 // Eat commas in between each argument, if they exist
1641 // Undefine a macro - .undefmac macname [, macname...]
1643 int undmac1(char * p)
1645 SYM * symbol = lookup(p, MACRO, 0);
1647 // If the macro symbol exists, cause it to disappear
1649 symbol->stype = (BYTE)SY_UNDEF;
1664 warn("JPAD directive is deprecated/non-functional");
1671 warn("NOJPAD directive is deprecated/non-functional");
1678 return error("What the hell? Do you think we adhere to the Goof standard?");
1683 // .opt - turn a specific (or all) optimisation on or off
1692 char * tmpstr = string[*tok++];
1694 if (ParseOptimization(tmpstr) != OK)
1697 sprintf(temperr, "unknown optimization flag '%s'", tmpstr);
1698 return error(temperr);
1702 return error(".opt directive needs every switch enclosed inside quotation marks");