1 /*****************************************************************************/
5 /* Pseudo instructions for the ca65 macroassembler */
9 /* (C) 1998-2011, Ullrich von Bassewitz */
10 /* Roemerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
15 /* This software is provided 'as-is', without any expressed or implied */
16 /* warranty. In no event will the authors be held liable for any damages */
17 /* arising from the use of this software. */
19 /* Permission is granted to anyone to use this software for any purpose, */
20 /* including commercial applications, and to alter it and redistribute it */
21 /* freely, subject to the following restrictions: */
23 /* 1. The origin of this software must not be misrepresented; you must not */
24 /* claim that you wrote the original software. If you use this software */
25 /* in a product, an acknowledgment in the product documentation would be */
26 /* appreciated but is not required. */
27 /* 2. Altered source versions must be plainly marked as such, and must not */
28 /* be misrepresented as being the original software. */
29 /* 3. This notice may not be removed or altered from any source */
32 /*****************************************************************************/
41 #include <sys/types.h> /* EMX needs this */
45 #include "assertion.h"
51 #include "scopedefs.h"
87 /*****************************************************************************/
89 /*****************************************************************************/
93 /* Keyword we're about to handle */
94 static StrBuf Keyword = STATIC_STRBUF_INITIALIZER;
97 static IntStack CPUStack = STATIC_INTSTACK_INITIALIZER;
100 #define MAX_PUSHED_SEGMENTS 16
101 static Collection SegStack = STATIC_COLLECTION_INITIALIZER;
105 /*****************************************************************************/
107 /*****************************************************************************/
111 static void DoUnexpected (void);
112 /* Got an unexpected keyword */
114 static void DoInvalid (void);
115 /* Handle a token that is invalid here, since it should have been handled on
116 * a much lower level of the expression hierarchy. Getting this sort of token
117 * means that the lower level code has bugs.
118 * This function differs to DoUnexpected in that the latter may be triggered
119 * by the user by using keywords in the wrong location. DoUnexpected is not
120 * an error in the assembler itself, while DoInvalid is.
125 /*****************************************************************************/
126 /* Helper functions */
127 /*****************************************************************************/
131 static unsigned char OptionalAddrSize (void)
132 /* If a colon follows, parse an optional address size spec and return it.
133 * Otherwise return ADDR_SIZE_DEFAULT.
136 unsigned AddrSize = ADDR_SIZE_DEFAULT;
137 if (CurTok.Tok == TOK_COLON) {
139 AddrSize = ParseAddrSize ();
140 if (!ValidAddrSizeForCPU (AddrSize)) {
141 /* Print an error and reset to default */
142 Error ("Invalid address size specification for current CPU");
143 AddrSize = ADDR_SIZE_DEFAULT;
152 static void SetBoolOption (unsigned char* Flag)
153 /* Read a on/off/+/- option and set flag accordingly */
155 static const char* Keys[] = {
160 if (CurTok.Tok == TOK_PLUS) {
163 } else if (CurTok.Tok == TOK_MINUS) {
166 } else if (CurTok.Tok == TOK_IDENT) {
167 /* Map the keyword to a number */
168 switch (GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]))) {
169 case 0: *Flag = 0; NextTok (); break;
170 case 1: *Flag = 1; NextTok (); break;
171 default: ErrorSkip ("`on' or `off' expected"); break;
173 } else if (TokIsSep (CurTok.Tok)) {
174 /* Without anything assume switch on */
177 ErrorSkip ("`on' or `off' expected");
183 static void ExportWithAssign (SymEntry* Sym, unsigned char AddrSize, unsigned Flags)
184 /* Allow to assign the value of an export in an .export statement */
186 /* The name and optional address size spec may be followed by an assignment
189 if (CurTok.Tok == TOK_ASSIGN || CurTok.Tok == TOK_EQ) {
191 /* Assignment means the symbol is a label */
192 if (CurTok.Tok == TOK_ASSIGN) {
196 /* Skip the assignment token */
199 /* Define the symbol with the expression following the '=' */
200 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
204 /* Now export the symbol */
205 SymExport (Sym, AddrSize, Flags);
210 static void ExportImport (void (*Func) (SymEntry*, unsigned char, unsigned),
211 unsigned char DefAddrSize, unsigned Flags)
212 /* Export or import symbols */
215 unsigned char AddrSize;
219 /* We need an identifier here */
220 if (CurTok.Tok != TOK_IDENT) {
221 ErrorSkip ("Identifier expected");
225 /* Find the symbol table entry, allocate a new one if necessary */
226 Sym = SymFind (CurrentScope, &CurTok.SVal, SYM_ALLOC_NEW);
231 /* Get an optional address size */
232 AddrSize = OptionalAddrSize ();
233 if (AddrSize == ADDR_SIZE_DEFAULT) {
234 AddrSize = DefAddrSize;
237 /* Call the actual import/export function */
238 Func (Sym, AddrSize, Flags);
241 if (CurTok.Tok == TOK_COMMA) {
251 static long IntArg (long Min, long Max)
252 /* Read an integer argument and check a range. Accept the token "unlimited"
253 * and return -1 in this case.
256 if (CurTok.Tok == TOK_IDENT && SB_CompareStr (&CurTok.SVal, "unlimited") == 0) {
260 long Val = ConstExpression ();
261 if (Val < Min || Val > Max) {
262 Error ("Range error");
271 static void ConDes (const StrBuf* Name, unsigned Type)
272 /* Parse remaining line for constructor/destructor of the remaining type */
277 /* Find the symbol table entry, allocate a new one if necessary */
278 SymEntry* Sym = SymFind (CurrentScope, Name, SYM_ALLOC_NEW);
280 /* Optional constructor priority */
281 if (CurTok.Tok == TOK_COMMA) {
282 /* Priority value follows */
284 Prio = ConstExpression ();
285 if (Prio < CD_PRIO_MIN || Prio > CD_PRIO_MAX) {
286 /* Value out of range */
287 Error ("Range error");
291 /* Use the default priority value */
295 /* Define the symbol */
296 SymConDes (Sym, ADDR_SIZE_DEFAULT, Type, (unsigned) Prio);
301 static StrBuf* GenArrayType (StrBuf* Type, unsigned SpanSize,
302 const char* ElementType,
303 unsigned ElementTypeLen)
304 /* Create an array (or single data) of the given type. SpanSize is the size
305 * of the span, ElementType is a string that encodes the element data type.
306 * The function returns Type.
309 /* Get the size of the element type */
310 unsigned ElementSize = GT_GET_SIZE (ElementType[0]);
312 /* Get the number of array elements */
313 unsigned ElementCount = SpanSize / ElementSize;
315 /* The span size must be divideable by the element size */
316 CHECK ((SpanSize % ElementSize) == 0);
318 /* Encode the array */
319 GT_AddArray (Type, ElementCount);
320 SB_AppendBuf (Type, ElementType, ElementTypeLen);
322 /* Return the pointer to the created array type */
328 /*****************************************************************************/
329 /* Handler functions */
330 /*****************************************************************************/
334 static void DoA16 (void)
335 /* Switch the accu to 16 bit mode (assembler only) */
337 if (GetCPU() != CPU_65816) {
338 Error ("Command is only valid in 65816 mode");
340 /* Immidiate mode has two extension bytes */
341 ExtBytes [AM65I_IMM_ACCU] = 2;
347 static void DoA8 (void)
348 /* Switch the accu to 8 bit mode (assembler only) */
350 if (GetCPU() != CPU_65816) {
351 Error ("Command is only valid in 65816 mode");
353 /* Immidiate mode has one extension byte */
354 ExtBytes [AM65I_IMM_ACCU] = 1;
360 static void DoAddr (void)
361 /* Define addresses */
363 /* Element type for the generated array */
364 static const char EType[2] = { GT_PTR, GT_VOID };
366 /* Record type information */
367 Span* S = OpenSpan ();
368 StrBuf Type = STATIC_STRBUF_INITIALIZER;
370 /* Parse arguments */
372 if (GetCPU() == CPU_65816) {
373 EmitWord (GenWordExpr (Expression ()));
375 /* Do a range check */
376 EmitWord (Expression ());
378 if (CurTok.Tok != TOK_COMMA) {
385 /* Close the span, then add type information to it */
387 SetSpanType (S, GenArrayType (&Type, GetSpanSize (S), EType, sizeof (EType)));
389 /* Free the strings */
395 static void DoAlign (void)
396 /* Align the PC to some boundary */
402 /* Read the alignment value */
403 Align = ConstExpression ();
404 if (Align <= 0 || Align > 0x10000) {
405 ErrorSkip ("Range error");
409 /* Optional value follows */
410 if (CurTok.Tok == TOK_COMMA) {
412 Val = ConstExpression ();
413 /* We need a byte value here */
414 if (!IsByteRange (Val)) {
415 ErrorSkip ("Range error");
422 /* Check if the alignment is a power of two */
423 Bit = BitFind (Align);
424 if (Align != (0x01L << Bit)) {
425 Error ("Alignment value must be a power of 2");
427 SegAlign (Bit, (int) Val);
433 static void DoASCIIZ (void)
434 /* Define text with a zero terminator */
437 /* Must have a string constant */
438 if (CurTok.Tok != TOK_STRCON) {
439 ErrorSkip ("String constant expected");
443 /* Translate into target charset and emit */
444 TgtTranslateStrBuf (&CurTok.SVal);
445 EmitStrBuf (&CurTok.SVal);
447 if (CurTok.Tok == TOK_COMMA) {
458 static void DoAssert (void)
459 /* Add an assertion */
461 static const char* ActionTab [] = {
464 "LDWARN", "LDWARNING",
471 /* First we have the expression that has to evaluated */
472 ExprNode* Expr = Expression ();
476 if (CurTok.Tok != TOK_IDENT) {
477 ErrorSkip ("Identifier expected");
480 switch (GetSubKey (ActionTab, sizeof (ActionTab) / sizeof (ActionTab[0]))) {
485 Action = ASSERT_ACT_WARN;
490 Action = ASSERT_ACT_ERROR;
496 Action = ASSERT_ACT_LDWARN;
501 Action = ASSERT_ACT_LDERROR;
505 Error ("Illegal assert action specifier");
506 /* Use lderror - there won't be an .o file anyway */
507 Action = ASSERT_ACT_LDERROR;
513 /* We can have an optional message. If no message is present, use
514 * "Assertion failed".
516 if (CurTok.Tok == TOK_COMMA) {
521 /* Read the message */
522 if (CurTok.Tok != TOK_STRCON) {
523 ErrorSkip ("String constant expected");
527 /* Translate the message into a string id. We can then skip the input
530 Msg = GetStrBufId (&CurTok.SVal);
535 /* Use "Assertion failed" */
536 Msg = GetStringId ("Assertion failed");
540 /* Remember the assertion */
541 AddAssertion (Expr, (AssertAction) Action, Msg);
546 static void DoAutoImport (void)
547 /* Mark unresolved symbols as imported */
549 SetBoolOption (&AutoImport);
553 static void DoBankBytes (void)
554 /* Define bytes, extracting the bank byte from each expression in the list */
557 EmitByte (FuncBankByte ());
558 if (CurTok.Tok != TOK_COMMA) {
568 static void DoBss (void)
569 /* Switch to the BSS segment */
576 static void DoByte (void)
579 /* Element type for the generated array */
580 static const char EType[1] = { GT_BYTE };
582 /* Record type information */
583 Span* S = OpenSpan ();
584 StrBuf Type = STATIC_STRBUF_INITIALIZER;
586 /* Parse arguments */
588 if (CurTok.Tok == TOK_STRCON) {
589 /* A string, translate into target charset and emit */
590 TgtTranslateStrBuf (&CurTok.SVal);
591 EmitStrBuf (&CurTok.SVal);
594 EmitByte (Expression ());
596 if (CurTok.Tok != TOK_COMMA) {
600 /* Do smart handling of dangling comma */
601 if (CurTok.Tok == TOK_SEP) {
602 Error ("Unexpected end of line");
608 /* Close the span, then add type information to it */
610 SetSpanType (S, GenArrayType (&Type, GetSpanSize (S), EType, sizeof (EType)));
612 /* Free the type string */
618 static void DoCase (void)
619 /* Switch the IgnoreCase option */
621 SetBoolOption (&IgnoreCase);
622 IgnoreCase = !IgnoreCase;
627 static void DoCharMap (void)
628 /* Allow custome character mappings */
633 /* Read the index as numerical value */
634 Index = ConstExpression ();
635 if (Index < 0 || Index > 255) {
636 /* Value out of range */
637 ErrorSkip ("Range error");
644 /* Read the character code */
645 Code = ConstExpression ();
646 if (Code < 0 || Code > 255) {
647 /* Value out of range */
648 ErrorSkip ("Range error");
652 /* Set the character translation */
653 TgtTranslateSet ((unsigned) Index, (unsigned char) Code);
658 static void DoCode (void)
659 /* Switch to the code segment */
661 UseSeg (&CodeSegDef);
666 static void DoConDes (void)
667 /* Export a symbol as constructor/destructor */
669 static const char* Keys[] = {
674 StrBuf Name = STATIC_STRBUF_INITIALIZER;
677 /* Symbol name follows */
678 if (CurTok.Tok != TOK_IDENT) {
679 ErrorSkip ("Identifier expected");
682 SB_Copy (&Name, &CurTok.SVal);
685 /* Type follows. May be encoded as identifier or numerical */
687 if (CurTok.Tok == TOK_IDENT) {
689 /* Map the following keyword to a number, then skip it */
690 Type = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
693 /* Check if we got a valid keyword */
695 ErrorSkip ("Syntax error");
701 /* Read the type as numerical value */
702 Type = ConstExpression ();
703 if (Type < CD_TYPE_MIN || Type > CD_TYPE_MAX) {
704 /* Value out of range */
705 ErrorSkip ("Range error");
711 /* Parse the remainder of the line and export the symbol */
712 ConDes (&Name, (unsigned) Type);
715 /* Free string memory */
721 static void DoConstructor (void)
722 /* Export a symbol as constructor */
724 StrBuf Name = STATIC_STRBUF_INITIALIZER;
726 /* Symbol name follows */
727 if (CurTok.Tok != TOK_IDENT) {
728 ErrorSkip ("Identifier expected");
731 SB_Copy (&Name, &CurTok.SVal);
734 /* Parse the remainder of the line and export the symbol */
735 ConDes (&Name, CD_TYPE_CON);
737 /* Free string memory */
743 static void DoData (void)
744 /* Switch to the data segment */
746 UseSeg (&DataSegDef);
751 static void DoDbg (void)
752 /* Add debug information from high level code */
754 static const char* Keys[] = {
763 /* We expect a subkey */
764 if (CurTok.Tok != TOK_IDENT) {
765 ErrorSkip ("Identifier expected");
769 /* Map the following keyword to a number */
770 Key = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
772 /* Skip the subkey */
775 /* Check the key and dispatch to a handler */
777 case 0: DbgInfoFile (); break;
778 case 1: DbgInfoFunc (); break;
779 case 2: DbgInfoLine (); break;
780 case 3: DbgInfoSym (); break;
781 default: ErrorSkip ("Syntax error"); break;
787 static void DoDByt (void)
788 /* Output double bytes */
790 /* Element type for the generated array */
791 static const char EType[1] = { GT_DBYTE };
793 /* Record type information */
794 Span* S = OpenSpan ();
795 StrBuf Type = STATIC_STRBUF_INITIALIZER;
797 /* Parse arguments */
799 EmitWord (GenSwapExpr (Expression ()));
800 if (CurTok.Tok != TOK_COMMA) {
807 /* Close the span, then add type information to it */
809 SetSpanType (S, GenArrayType (&Type, GetSpanSize (S), EType, sizeof (EType)));
811 /* Free the type string */
817 static void DoDebugInfo (void)
818 /* Switch debug info on or off */
820 SetBoolOption (&DbgSyms);
825 static void DoDefine (void)
826 /* Define a one line macro */
828 MacDef (MAC_STYLE_DEFINE);
833 static void DoDelMac (void)
834 /* Delete a classic macro */
836 /* We expect an identifier */
837 if (CurTok.Tok != TOK_IDENT) {
838 ErrorSkip ("Identifier expected");
840 MacUndef (&CurTok.SVal, MAC_STYLE_CLASSIC);
847 static void DoDestructor (void)
848 /* Export a symbol as destructor */
850 StrBuf Name = STATIC_STRBUF_INITIALIZER;
852 /* Symbol name follows */
853 if (CurTok.Tok != TOK_IDENT) {
854 ErrorSkip ("Identifier expected");
857 SB_Copy (&Name, &CurTok.SVal);
860 /* Parse the remainder of the line and export the symbol */
861 ConDes (&Name, CD_TYPE_DES);
863 /* Free string memory */
869 static void DoDWord (void)
873 EmitDWord (Expression ());
874 if (CurTok.Tok != TOK_COMMA) {
884 static void DoEnd (void)
885 /* End of assembly */
893 static void DoEndProc (void)
894 /* Leave a lexical level */
896 if (CurrentScope->Type != SCOPE_SCOPE || CurrentScope->Label == 0) {
898 ErrorSkip ("No open .PROC");
906 static void DoEndScope (void)
907 /* Leave a lexical level */
909 if (CurrentScope->Type != SCOPE_SCOPE || CurrentScope->Label != 0) {
911 ErrorSkip ("No open .SCOPE");
919 static void DoError (void)
922 if (CurTok.Tok != TOK_STRCON) {
923 ErrorSkip ("String constant expected");
925 Error ("User error: %m%p", &CurTok.SVal);
932 static void DoExitMacro (void)
933 /* Exit a macro expansion */
935 if (!InMacExpansion ()) {
936 /* We aren't expanding a macro currently */
945 static void DoExport (void)
946 /* Export a symbol */
948 ExportImport (ExportWithAssign, ADDR_SIZE_DEFAULT, SF_NONE);
953 static void DoExportZP (void)
954 /* Export a zeropage symbol */
956 ExportImport (ExportWithAssign, ADDR_SIZE_ZP, SF_NONE);
961 static void DoFarAddr (void)
962 /* Define far addresses (24 bit) */
964 /* Element type for the generated array */
965 static const char EType[2] = { GT_FAR_PTR, GT_VOID };
967 /* Record type information */
968 Span* S = OpenSpan ();
969 StrBuf Type = STATIC_STRBUF_INITIALIZER;
971 /* Parse arguments */
973 EmitFarAddr (Expression ());
974 if (CurTok.Tok != TOK_COMMA) {
981 /* Close the span, then add type information to it */
983 SetSpanType (S, GenArrayType (&Type, GetSpanSize (S), EType, sizeof (EType)));
985 /* Free the type string */
991 static void DoFatal (void)
992 /* Fatal user error */
994 if (CurTok.Tok != TOK_STRCON) {
995 ErrorSkip ("String constant expected");
997 Fatal ("User error: %m%p", &CurTok.SVal);
1004 static void DoFeature (void)
1005 /* Switch the Feature option */
1007 /* Allow a list of comma separated keywords */
1010 /* We expect an identifier */
1011 if (CurTok.Tok != TOK_IDENT) {
1012 ErrorSkip ("Identifier expected");
1016 /* Make the string attribute lower case */
1019 /* Set the feature and check for errors */
1020 if (SetFeature (&CurTok.SVal) == FEAT_UNKNOWN) {
1022 ErrorSkip ("Invalid feature: `%m%p'", &CurTok.SVal);
1025 /* Skip the keyword */
1029 /* Allow more than one keyword */
1030 if (CurTok.Tok == TOK_COMMA) {
1040 static void DoFileOpt (void)
1041 /* Insert a file option */
1045 /* The option type may be given as a keyword or as a number. */
1046 if (CurTok.Tok == TOK_IDENT) {
1048 /* Option given as keyword */
1049 static const char* Keys [] = {
1050 "AUTHOR", "COMMENT", "COMPILER"
1053 /* Map the option to a number */
1054 OptNum = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
1057 ErrorSkip ("File option keyword expected");
1061 /* Skip the keyword */
1064 /* Must be followed by a comma */
1067 /* We accept only string options for now */
1068 if (CurTok.Tok != TOK_STRCON) {
1069 ErrorSkip ("String constant expected");
1073 /* Insert the option */
1078 OptAuthor (&CurTok.SVal);
1083 OptComment (&CurTok.SVal);
1088 OptCompiler (&CurTok.SVal);
1092 Internal ("Invalid OptNum: %ld", OptNum);
1101 /* Option given as number */
1102 OptNum = ConstExpression ();
1103 if (!IsByteRange (OptNum)) {
1104 ErrorSkip ("Range error");
1108 /* Must be followed by a comma */
1111 /* We accept only string options for now */
1112 if (CurTok.Tok != TOK_STRCON) {
1113 ErrorSkip ("String constant expected");
1117 /* Insert the option */
1118 OptStr ((unsigned char) OptNum, &CurTok.SVal);
1127 static void DoForceImport (void)
1128 /* Do a forced import on a symbol */
1130 ExportImport (SymImport, ADDR_SIZE_DEFAULT, SF_FORCED);
1135 static void DoGlobal (void)
1136 /* Declare a global symbol */
1138 ExportImport (SymGlobal, ADDR_SIZE_DEFAULT, SF_NONE);
1143 static void DoGlobalZP (void)
1144 /* Declare a global zeropage symbol */
1146 ExportImport (SymGlobal, ADDR_SIZE_ZP, SF_NONE);
1150 static void DoHiBytes (void)
1151 /* Define bytes, extracting the hi byte from each expression in the list */
1154 EmitByte (FuncHiByte ());
1155 if (CurTok.Tok != TOK_COMMA) {
1165 static void DoI16 (void)
1166 /* Switch the index registers to 16 bit mode (assembler only) */
1168 if (GetCPU() != CPU_65816) {
1169 Error ("Command is only valid in 65816 mode");
1171 /* Immidiate mode has two extension bytes */
1172 ExtBytes [AM65I_IMM_INDEX] = 2;
1178 static void DoI8 (void)
1179 /* Switch the index registers to 16 bit mode (assembler only) */
1181 if (GetCPU() != CPU_65816) {
1182 Error ("Command is only valid in 65816 mode");
1184 /* Immidiate mode has one extension byte */
1185 ExtBytes [AM65I_IMM_INDEX] = 1;
1191 static void DoImport (void)
1192 /* Import a symbol */
1194 ExportImport (SymImport, ADDR_SIZE_DEFAULT, SF_NONE);
1199 static void DoImportZP (void)
1200 /* Import a zero page symbol */
1202 ExportImport (SymImport, ADDR_SIZE_ZP, SF_NONE);
1207 static void DoIncBin (void)
1208 /* Include a binary file */
1210 StrBuf Name = STATIC_STRBUF_INITIALIZER;
1211 struct stat StatBuf;
1217 /* Name must follow */
1218 if (CurTok.Tok != TOK_STRCON) {
1219 ErrorSkip ("String constant expected");
1222 SB_Copy (&Name, &CurTok.SVal);
1223 SB_Terminate (&Name);
1226 /* A starting offset may follow */
1227 if (CurTok.Tok == TOK_COMMA) {
1229 Start = ConstExpression ();
1231 /* And a length may follow */
1232 if (CurTok.Tok == TOK_COMMA) {
1234 Count = ConstExpression ();
1239 /* Try to open the file */
1240 F = fopen (SB_GetConstBuf (&Name), "rb");
1243 /* Search for the file in the binary include directory */
1244 char* PathName = SearchFile (BinSearchPath, SB_GetConstBuf (&Name));
1245 if (PathName == 0 || (F = fopen (PathName, "rb")) == 0) {
1246 /* Not found or cannot open, print an error and bail out */
1247 ErrorSkip ("Cannot open include file `%m%p': %s", &Name, strerror (errno));
1252 /* Remember the new file name */
1253 SB_CopyStr (&Name, PathName);
1255 /* Free the allocated memory */
1259 /* Get the size of the file */
1260 fseek (F, 0, SEEK_END);
1263 /* Stat the file and remember the values. There a race condition here,
1264 * since we cannot use fileno() (non standard identifier in standard
1265 * header file), and therefore not fstat. When using stat with the
1266 * file name, there's a risk that the file was deleted and recreated
1267 * while it was open. Since mtime and size are only used to check
1268 * if a file has changed in the debugger, we will ignore this problem
1271 SB_Terminate (&Name);
1272 if (stat (SB_GetConstBuf (&Name), &StatBuf) != 0) {
1273 Fatal ("Cannot stat input file `%m%p': %s", &Name, strerror (errno));
1276 /* Add the file to the input file table */
1277 AddFile (&Name, FT_BINARY, Size, StatBuf.st_mtime);
1279 /* If a count was not given, calculate it now */
1281 Count = Size - Start;
1283 /* Nothing to read - flag this as a range error */
1284 ErrorSkip ("Range error");
1288 /* Count was given, check if it is valid */
1289 if (Start + Count > Size) {
1290 ErrorSkip ("Range error");
1295 /* Seek to the start position */
1296 fseek (F, Start, SEEK_SET);
1298 /* Read chunks and insert them into the output */
1301 unsigned char Buf [1024];
1303 /* Calculate the number of bytes to read */
1304 size_t BytesToRead = (Count > (long)sizeof(Buf))? sizeof(Buf) : (size_t) Count;
1307 size_t BytesRead = fread (Buf, 1, BytesToRead, F);
1308 if (BytesToRead != BytesRead) {
1309 /* Some sort of error */
1310 ErrorSkip ("Cannot read from include file `%m%p': %s",
1311 &Name, strerror (errno));
1315 /* Insert it into the output */
1316 EmitData (Buf, BytesRead);
1318 /* Keep the counters current */
1323 /* Close the file, ignore errors since it's r/o */
1327 /* Free string memory */
1333 static void DoInclude (void)
1334 /* Include another file */
1336 /* Name must follow */
1337 if (CurTok.Tok != TOK_STRCON) {
1338 ErrorSkip ("String constant expected");
1340 SB_Terminate (&CurTok.SVal);
1341 if (NewInputFile (SB_GetConstBuf (&CurTok.SVal)) == 0) {
1342 /* Error opening the file, skip remainder of line */
1350 static void DoInterruptor (void)
1351 /* Export a symbol as interruptor */
1353 StrBuf Name = STATIC_STRBUF_INITIALIZER;
1355 /* Symbol name follows */
1356 if (CurTok.Tok != TOK_IDENT) {
1357 ErrorSkip ("Identifier expected");
1360 SB_Copy (&Name, &CurTok.SVal);
1363 /* Parse the remainder of the line and export the symbol */
1364 ConDes (&Name, CD_TYPE_INT);
1366 /* Free string memory */
1372 static void DoInvalid (void)
1373 /* Handle a token that is invalid here, since it should have been handled on
1374 * a much lower level of the expression hierarchy. Getting this sort of token
1375 * means that the lower level code has bugs.
1376 * This function differs to DoUnexpected in that the latter may be triggered
1377 * by the user by using keywords in the wrong location. DoUnexpected is not
1378 * an error in the assembler itself, while DoInvalid is.
1381 Internal ("Unexpected token: %m%p", &Keyword);
1386 static void DoLineCont (void)
1387 /* Switch the use of line continuations */
1389 SetBoolOption (&LineCont);
1394 static void DoList (void)
1395 /* Enable/disable the listing */
1397 /* Get the setting */
1399 SetBoolOption (&List);
1401 /* Manage the counter */
1411 static void DoLoBytes (void)
1412 /* Define bytes, extracting the lo byte from each expression in the list */
1415 EmitByte (FuncLoByte ());
1416 if (CurTok.Tok != TOK_COMMA) {
1425 static void DoListBytes (void)
1426 /* Set maximum number of bytes to list for one line */
1428 SetListBytes (IntArg (MIN_LIST_BYTES, MAX_LIST_BYTES));
1433 static void DoLocalChar (void)
1434 /* Define the character that starts local labels */
1436 if (CurTok.Tok != TOK_CHARCON) {
1437 ErrorSkip ("Character constant expected");
1439 if (CurTok.IVal != '@' && CurTok.IVal != '?') {
1440 Error ("Invalid start character for locals");
1442 LocalStart = (char) CurTok.IVal;
1450 static void DoMacPack (void)
1451 /* Insert a macro package */
1455 /* We expect an identifier */
1456 if (CurTok.Tok != TOK_IDENT) {
1457 ErrorSkip ("Identifier expected");
1461 /* Search for the macro package name */
1463 Package = MacPackFind (&CurTok.SVal);
1466 ErrorSkip ("Invalid macro package");
1470 /* Insert the package. If this fails, skip the remainder of the line to
1471 * avoid additional error messages.
1473 if (MacPackInsert (Package) == 0) {
1480 static void DoMacro (void)
1481 /* Start a macro definition */
1483 MacDef (MAC_STYLE_CLASSIC);
1488 static void DoNull (void)
1489 /* Switch to the NULL segment */
1491 UseSeg (&NullSegDef);
1496 static void DoOrg (void)
1497 /* Start absolute code */
1499 long PC = ConstExpression ();
1500 if (PC < 0 || PC > 0xFFFFFF) {
1501 Error ("Range error");
1504 EnterAbsoluteMode (PC);
1509 static void DoOut (void)
1510 /* Output a string */
1512 if (CurTok.Tok != TOK_STRCON) {
1513 ErrorSkip ("String constant expected");
1515 /* Output the string and be sure to flush the output to keep it in
1516 * sync with any error messages if the output is redirected to a file.
1519 (int) SB_GetLen (&CurTok.SVal),
1520 SB_GetConstBuf (&CurTok.SVal));
1528 static void DoP02 (void)
1529 /* Switch to 6502 CPU */
1536 static void DoPC02 (void)
1537 /* Switch to 65C02 CPU */
1544 static void DoP816 (void)
1545 /* Switch to 65816 CPU */
1552 static void DoPageLength (void)
1553 /* Set the page length for the listing */
1555 PageLength = IntArg (MIN_PAGE_LEN, MAX_PAGE_LEN);
1560 static void DoPopCPU (void)
1561 /* Pop an old CPU setting from the CPU stack */
1563 /* Must have a CPU on the stack */
1564 if (IS_IsEmpty (&CPUStack)) {
1565 ErrorSkip ("CPU stack is empty");
1569 /* Set the CPU to the value popped from stack */
1570 SetCPU (IS_Pop (&CPUStack));
1575 static void DoPopSeg (void)
1576 /* Pop an old segment from the segment stack */
1580 /* Must have a segment on the stack */
1581 if (CollCount (&SegStack) == 0) {
1582 ErrorSkip ("Segment stack is empty");
1586 /* Pop the last element */
1587 Def = CollPop (&SegStack);
1589 /* Restore this segment */
1592 /* Delete the segment definition */
1598 static void DoProc (void)
1599 /* Start a new lexical scope */
1601 StrBuf Name = STATIC_STRBUF_INITIALIZER;
1602 unsigned char AddrSize;
1606 if (CurTok.Tok == TOK_IDENT) {
1608 /* The new scope has a name. Remember it. */
1609 SB_Copy (&Name, &CurTok.SVal);
1611 /* Search for the symbol, generate a new one if needed */
1612 Sym = SymFind (CurrentScope, &Name, SYM_ALLOC_NEW);
1614 /* Skip the scope name */
1617 /* Read an optional address size specifier */
1618 AddrSize = OptionalAddrSize ();
1620 /* Mark the symbol as defined */
1621 SymDef (Sym, GenCurrentPC (), AddrSize, SF_LABEL);
1625 /* A .PROC statement without a name */
1626 Warning (1, "Unnamed .PROCs are deprecated, please use .SCOPE");
1627 AnonName (&Name, "PROC");
1628 AddrSize = ADDR_SIZE_DEFAULT;
1632 /* Enter a new scope */
1633 SymEnterLevel (&Name, SCOPE_SCOPE, AddrSize, Sym);
1635 /* Free memory for Name */
1641 static void DoPSC02 (void)
1642 /* Switch to 65SC02 CPU */
1644 SetCPU (CPU_65SC02);
1649 static void DoPushCPU (void)
1650 /* Push the current CPU setting onto the CPU stack */
1652 /* Can only push a limited size of segments */
1653 if (IS_IsFull (&CPUStack)) {
1654 ErrorSkip ("CPU stack overflow");
1658 /* Get the current segment and push it */
1659 IS_Push (&CPUStack, GetCPU ());
1664 static void DoPushSeg (void)
1665 /* Push the current segment onto the segment stack */
1667 /* Can only push a limited size of segments */
1668 if (CollCount (&SegStack) >= MAX_PUSHED_SEGMENTS) {
1669 ErrorSkip ("Segment stack overflow");
1673 /* Get the current segment and push it */
1674 CollAppend (&SegStack, DupSegDef (GetCurrentSegDef ()));
1679 static void DoReloc (void)
1680 /* Enter relocatable mode */
1687 static void DoRepeat (void)
1688 /* Repeat some instruction block */
1695 static void DoRes (void)
1696 /* Reserve some number of storage bytes */
1701 Count = ConstExpression ();
1702 if (Count > 0xFFFF || Count < 0) {
1703 ErrorSkip ("Range error");
1706 if (CurTok.Tok == TOK_COMMA) {
1708 Val = ConstExpression ();
1709 /* We need a byte value here */
1710 if (!IsByteRange (Val)) {
1711 ErrorSkip ("Range error");
1715 /* Emit constant values */
1717 Emit0 ((unsigned char) Val);
1721 /* Emit fill fragments */
1728 static void DoROData (void)
1729 /* Switch to the r/o data segment */
1731 UseSeg (&RODataSegDef);
1736 static void DoScope (void)
1737 /* Start a local scope */
1739 StrBuf Name = STATIC_STRBUF_INITIALIZER;
1740 unsigned char AddrSize;
1743 if (CurTok.Tok == TOK_IDENT) {
1745 /* The new scope has a name. Remember and skip it. */
1746 SB_Copy (&Name, &CurTok.SVal);
1751 /* An unnamed scope */
1752 AnonName (&Name, "SCOPE");
1756 /* Read an optional address size specifier */
1757 AddrSize = OptionalAddrSize ();
1759 /* Enter the new scope */
1760 SymEnterLevel (&Name, SCOPE_SCOPE, AddrSize, 0);
1762 /* Free memory for Name */
1768 static void DoSegment (void)
1769 /* Switch to another segment */
1771 StrBuf Name = STATIC_STRBUF_INITIALIZER;
1774 if (CurTok.Tok != TOK_STRCON) {
1775 ErrorSkip ("String constant expected");
1778 /* Save the name of the segment and skip it */
1779 SB_Copy (&Name, &CurTok.SVal);
1782 /* Use the name for the segment definition */
1783 SB_Terminate (&Name);
1784 Def.Name = SB_GetBuf (&Name);
1786 /* Check for an optional address size modifier */
1787 Def.AddrSize = OptionalAddrSize ();
1789 /* Set the segment */
1793 /* Free memory for Name */
1799 static void DoSetCPU (void)
1800 /* Switch the CPU instruction set */
1802 /* We expect an identifier */
1803 if (CurTok.Tok != TOK_STRCON) {
1804 ErrorSkip ("String constant expected");
1808 /* Try to find the CPU */
1809 SB_Terminate (&CurTok.SVal);
1810 CPU = FindCPU (SB_GetConstBuf (&CurTok.SVal));
1812 /* Switch to the new CPU */
1815 /* Skip the identifier. If the CPU switch was successful, the scanner
1816 * will treat the input now correctly for the new CPU.
1824 static void DoSmart (void)
1825 /* Smart mode on/off */
1827 SetBoolOption (&SmartMode);
1832 static void DoSunPlus (void)
1833 /* Switch to the SUNPLUS CPU */
1835 SetCPU (CPU_SUNPLUS);
1840 static void DoTag (void)
1841 /* Allocate space for a struct */
1846 /* Read the struct name */
1847 SymTable* Struct = ParseScopedSymTable ();
1849 /* Check the supposed struct */
1851 ErrorSkip ("Unknown struct");
1854 if (GetSymTabType (Struct) != SCOPE_STRUCT) {
1855 ErrorSkip ("Not a struct");
1859 /* Get the symbol that defines the size of the struct */
1860 SizeSym = GetSizeOfScope (Struct);
1862 /* Check if it does exist and if its value is known */
1863 if (SizeSym == 0 || !SymIsConst (SizeSym, &Size)) {
1864 ErrorSkip ("Size of struct/union is unknown");
1868 /* Optional multiplicator may follow */
1869 if (CurTok.Tok == TOK_COMMA) {
1872 Multiplicator = ConstExpression ();
1873 /* Multiplicator must make sense */
1874 if (Multiplicator <= 0) {
1875 ErrorSkip ("Range error");
1878 Size *= Multiplicator;
1881 /* Emit fill fragments */
1887 static void DoUnDef (void)
1888 /* Undefine a define style macro */
1890 /* The function is called with the .UNDEF token in place, because we need
1891 * to disable .define macro expansions before reading the next token.
1892 * Otherwise the name of the macro would be expanded, so we would never
1895 DisableDefineStyleMacros ();
1897 EnableDefineStyleMacros ();
1899 /* We expect an identifier */
1900 if (CurTok.Tok != TOK_IDENT) {
1901 ErrorSkip ("Identifier expected");
1903 MacUndef (&CurTok.SVal, MAC_STYLE_DEFINE);
1910 static void DoUnexpected (void)
1911 /* Got an unexpected keyword */
1913 Error ("Unexpected `%m%p'", &Keyword);
1919 static void DoWarning (void)
1922 if (CurTok.Tok != TOK_STRCON) {
1923 ErrorSkip ("String constant expected");
1925 Warning (0, "User warning: %m%p", &CurTok.SVal);
1932 static void DoWord (void)
1935 /* Element type for the generated array */
1936 static const char EType[1] = { GT_WORD };
1938 /* Record type information */
1939 Span* S = OpenSpan ();
1940 StrBuf Type = STATIC_STRBUF_INITIALIZER;
1942 /* Parse arguments */
1944 EmitWord (Expression ());
1945 if (CurTok.Tok != TOK_COMMA) {
1952 /* Close the span, then add type information to it */
1954 SetSpanType (S, GenArrayType (&Type, GetSpanSize (S), EType, sizeof (EType)));
1956 /* Free the type string */
1962 static void DoZeropage (void)
1963 /* Switch to the zeropage segment */
1965 UseSeg (&ZeropageSegDef);
1970 /*****************************************************************************/
1972 /*****************************************************************************/
1976 /* Control commands flags */
1978 ccNone = 0x0000, /* No special flags */
1979 ccKeepToken = 0x0001 /* Do not skip the current token */
1982 /* Control command table */
1983 typedef struct CtrlDesc CtrlDesc;
1985 unsigned Flags; /* Flags for this directive */
1986 void (*Handler) (void); /* Command handler */
1989 #define PSEUDO_COUNT (sizeof (CtrlCmdTab) / sizeof (CtrlCmdTab [0]))
1990 static CtrlDesc CtrlCmdTab [] = {
1993 { ccNone, DoAddr }, /* .ADDR */
1994 { ccNone, DoAlign },
1995 { ccNone, DoASCIIZ },
1996 { ccNone, DoAssert },
1997 { ccNone, DoAutoImport },
1998 { ccNone, DoUnexpected }, /* .BANKBYTE */
1999 { ccNone, DoBankBytes },
2000 { ccNone, DoUnexpected }, /* .BLANK */
2004 { ccNone, DoCharMap },
2006 { ccNone, DoUnexpected, }, /* .CONCAT */
2007 { ccNone, DoConDes },
2008 { ccNone, DoUnexpected }, /* .CONST */
2009 { ccNone, DoConstructor },
2010 { ccNone, DoUnexpected }, /* .CPU */
2014 { ccNone, DoDebugInfo },
2015 { ccNone, DoDefine },
2016 { ccNone, DoUnexpected }, /* .DEFINED */
2017 { ccNone, DoDelMac },
2018 { ccNone, DoDestructor },
2019 { ccNone, DoDWord },
2020 { ccKeepToken, DoConditionals }, /* .ELSE */
2021 { ccKeepToken, DoConditionals }, /* .ELSEIF */
2022 { ccKeepToken, DoEnd },
2023 { ccNone, DoUnexpected }, /* .ENDENUM */
2024 { ccKeepToken, DoConditionals }, /* .ENDIF */
2025 { ccNone, DoUnexpected }, /* .ENDMACRO */
2026 { ccNone, DoEndProc },
2027 { ccNone, DoUnexpected }, /* .ENDREPEAT */
2028 { ccNone, DoEndScope },
2029 { ccNone, DoUnexpected }, /* .ENDSTRUCT */
2030 { ccNone, DoUnexpected }, /* .ENDUNION */
2032 { ccNone, DoError },
2033 { ccNone, DoExitMacro },
2034 { ccNone, DoExport },
2035 { ccNone, DoExportZP },
2036 { ccNone, DoFarAddr },
2037 { ccNone, DoFatal },
2038 { ccNone, DoFeature },
2039 { ccNone, DoFileOpt },
2040 { ccNone, DoForceImport },
2041 { ccNone, DoUnexpected }, /* .FORCEWORD */
2042 { ccNone, DoGlobal },
2043 { ccNone, DoGlobalZP },
2044 { ccNone, DoUnexpected }, /* .HIBYTE */
2045 { ccNone, DoHiBytes },
2046 { ccNone, DoUnexpected }, /* .HIWORD */
2049 { ccNone, DoUnexpected }, /* .IDENT */
2050 { ccKeepToken, DoConditionals }, /* .IF */
2051 { ccKeepToken, DoConditionals }, /* .IFBLANK */
2052 { ccKeepToken, DoConditionals }, /* .IFCONST */
2053 { ccKeepToken, DoConditionals }, /* .IFDEF */
2054 { ccKeepToken, DoConditionals }, /* .IFNBLANK */
2055 { ccKeepToken, DoConditionals }, /* .IFNCONST */
2056 { ccKeepToken, DoConditionals }, /* .IFNDEF */
2057 { ccKeepToken, DoConditionals }, /* .IFNREF */
2058 { ccKeepToken, DoConditionals }, /* .IFP02 */
2059 { ccKeepToken, DoConditionals }, /* .IFP816 */
2060 { ccKeepToken, DoConditionals }, /* .IFPC02 */
2061 { ccKeepToken, DoConditionals }, /* .IFPSC02 */
2062 { ccKeepToken, DoConditionals }, /* .IFREF */
2063 { ccNone, DoImport },
2064 { ccNone, DoImportZP },
2065 { ccNone, DoIncBin },
2066 { ccNone, DoInclude },
2067 { ccNone, DoInterruptor },
2068 { ccNone, DoInvalid }, /* .LEFT */
2069 { ccNone, DoLineCont },
2071 { ccNone, DoListBytes },
2072 { ccNone, DoUnexpected }, /* .LOBYTE */
2073 { ccNone, DoLoBytes },
2074 { ccNone, DoUnexpected }, /* .LOCAL */
2075 { ccNone, DoLocalChar },
2076 { ccNone, DoUnexpected }, /* .LOWORD */
2077 { ccNone, DoMacPack },
2078 { ccNone, DoMacro },
2079 { ccNone, DoUnexpected }, /* .MATCH */
2080 { ccNone, DoUnexpected }, /* .MAX */
2081 { ccNone, DoInvalid }, /* .MID */
2082 { ccNone, DoUnexpected }, /* .MIN */
2088 { ccNone, DoPageLength },
2089 { ccNone, DoUnexpected }, /* .PARAMCOUNT */
2091 { ccNone, DoPopCPU },
2092 { ccNone, DoPopSeg },
2094 { ccNone, DoPSC02 },
2095 { ccNone, DoPushCPU },
2096 { ccNone, DoPushSeg },
2097 { ccNone, DoUnexpected }, /* .REFERENCED */
2098 { ccNone, DoReloc },
2099 { ccNone, DoRepeat },
2101 { ccNone, DoInvalid }, /* .RIGHT */
2102 { ccNone, DoROData },
2103 { ccNone, DoScope },
2104 { ccNone, DoSegment },
2105 { ccNone, DoUnexpected }, /* .SET */
2106 { ccNone, DoSetCPU },
2107 { ccNone, DoUnexpected }, /* .SIZEOF */
2108 { ccNone, DoSmart },
2109 { ccNone, DoUnexpected }, /* .SPRINTF */
2110 { ccNone, DoUnexpected }, /* .STRAT */
2111 { ccNone, DoUnexpected }, /* .STRING */
2112 { ccNone, DoUnexpected }, /* .STRLEN */
2113 { ccNone, DoStruct },
2114 { ccNone, DoSunPlus },
2116 { ccNone, DoUnexpected }, /* .TCOUNT */
2117 { ccNone, DoUnexpected }, /* .TIME */
2118 { ccKeepToken, DoUnDef },
2119 { ccNone, DoUnion },
2120 { ccNone, DoUnexpected }, /* .VERSION */
2121 { ccNone, DoWarning },
2123 { ccNone, DoUnexpected }, /* .XMATCH */
2124 { ccNone, DoZeropage },
2129 /*****************************************************************************/
2131 /*****************************************************************************/
2135 void HandlePseudo (void)
2136 /* Handle a pseudo instruction */
2140 /* Calculate the index into the table */
2141 unsigned Index = CurTok.Tok - TOK_FIRSTPSEUDO;
2144 if (PSEUDO_COUNT != (TOK_LASTPSEUDO - TOK_FIRSTPSEUDO + 1)) {
2145 Internal ("Pseudo mismatch: PSEUDO_COUNT = %u, actual count = %u\n",
2146 (unsigned) PSEUDO_COUNT, TOK_LASTPSEUDO - TOK_FIRSTPSEUDO + 1);
2148 CHECK (Index < PSEUDO_COUNT);
2150 /* Get the pseudo intruction descriptor */
2151 D = &CtrlCmdTab [Index];
2153 /* Remember the instruction, then skip it if needed */
2154 if ((D->Flags & ccKeepToken) == 0) {
2155 SB_Copy (&Keyword, &CurTok.SVal);
2159 /* Call the handler */
2165 void CheckPseudo (void)
2166 /* Check if the stacks are empty at end of assembly */
2168 if (CollCount (&SegStack) != 0) {
2169 Warning (1, "Segment stack is not empty");
2171 if (!IS_IsEmpty (&CPUStack)) {
2172 Warning (1, "CPU stack is not empty");