id
int64
1
722k
file_path
stringlengths
8
177
funcs
stringlengths
1
35.8M
901
./cc65/src/common/hashfunc.c
/*****************************************************************************/ /* */ /* hashfunc.c */ /* */ /* Hash functions */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "hashfunc.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned HashInt (unsigned V) /* Return a hash value for the given integer. The function uses Robert * Jenkins' 32 bit integer hash function taken from * http://www.concentric.net/~ttwang/tech/inthash.htm * For 16 bit integers, the function may be suboptimal. */ { V = (V + 0x7ed55d16) + (V << 12); V = (V ^ 0xc761c23c) ^ (V >> 19); V = (V + 0x165667b1) + (V << 5); V = (V + 0xd3a2646c) ^ (V << 9); V = (V + 0xfd7046c5) + (V << 3); V = (V ^ 0xb55a4f09) ^ (V >> 16); return V; } unsigned HashStr (const char* S) /* Return a hash value for the given string */ { unsigned L, H; /* Do the hash */ H = L = 0; while (*S) { H = ((H << 3) ^ ((unsigned char) *S++)) + L++; } return H; } unsigned HashBuf (const StrBuf* S) /* Return a hash value for the given string buffer */ { unsigned I, L, H; /* Do the hash */ H = L = 0; for (I = 0; I < SB_GetLen (S); ++I) { H = ((H << 3) ^ ((unsigned char) SB_AtUnchecked (S, I))) + L++; } return H; }
902
./cc65/src/common/abend.c
/*****************************************************************************/ /* */ /* abend.c */ /* */ /* Abnormal program end */ /* */ /* */ /* */ /* (C) 2000 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include "cmdline.h" #include "abend.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void AbEnd (const char* Format, ...) /* Print a message preceeded by the program name and terminate the program * with an error exit code. */ { va_list ap; /* Print the program name */ fprintf (stderr, "%s: ", ProgName); /* Format the given message and print it */ va_start (ap, Format); vfprintf (stderr, Format, ap); va_end (ap); /* Add a newline */ fprintf (stderr, "\n"); /* Terminate the program */ exit (EXIT_FAILURE); }
903
./cc65/src/common/alignment.c
/*****************************************************************************/ /* */ /* alignment.c */ /* */ /* Address aligment */ /* */ /* */ /* */ /* (C) 2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* 70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "alignment.h" #include "check.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* To factorize an alignment, we will use the following prime table. It lists * all primes up to 256, which means we're able to factorize alignments up to * 0x10000. This is checked in the code. */ static const unsigned char Primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 }; #define PRIME_COUNT (sizeof (Primes) / sizeof (Primes[0])) #define LAST_PRIME ((unsigned long)Primes[PRIME_COUNT-1]) /* A number together with its prime factors */ typedef struct FactorizedNumber FactorizedNumber; struct FactorizedNumber { unsigned long Value; /* The actual number */ unsigned long Remainder; /* Remaining prime */ unsigned char Powers[PRIME_COUNT]; /* Powers of the factors */ }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void Initialize (FactorizedNumber* F, unsigned long Value) /* Initialize a FactorizedNumber structure */ { unsigned I; F->Value = Value; F->Remainder = 1; for (I = 0; I < PRIME_COUNT; ++I) { F->Powers[I] = 0; } } static void Factorize (unsigned long Value, FactorizedNumber* F) /* Factorize a value between 1 and 0x10000 that is in F */ { unsigned I; /* Initialize F */ Initialize (F, Value); /* If the value is 1 we're already done */ if (Value == 1) { return; } /* Be sure we can factorize */ CHECK (Value <= MAX_ALIGNMENT && Value != 0); /* Handle factor 2 separately for speed */ while ((Value & 0x01UL) == 0UL) { ++F->Powers[0]; Value >>= 1; } /* Factorize. */ I = 1; /* Skip 2 because it was handled above */ while (Value > 1) { unsigned long Tmp = Value / Primes[I]; if (Tmp * Primes[I] == Value) { /* This is a factor */ ++F->Powers[I]; Value = Tmp; } else { /* This is not a factor, try next one */ if (++I >= PRIME_COUNT) { break; } } } /* If something is left, it must be a remaining prime */ F->Remainder = Value; } unsigned long LeastCommonMultiple (unsigned long Left, unsigned long Right) /* Calculate the least common multiple of two numbers and return * the result. */ { unsigned I; FactorizedNumber L, R; unsigned long Res; /* Factorize the two numbers */ Factorize (Left, &L); Factorize (Right, &R); /* Generate the result from the factors. * Some thoughts on range problems: Since the largest numbers we can * factorize are 2^16 (0x10000), the only numbers that could produce an * overflow when using 32 bits are exactly these. But the LCM for 2^16 * and 2^16 is 2^16 so this will never happen and we're safe. */ Res = L.Remainder * R.Remainder; for (I = 0; I < PRIME_COUNT; ++I) { unsigned P = (L.Powers[I] > R.Powers[I])? L.Powers[I] : R.Powers[I]; while (P--) { Res *= Primes[I]; } } /* Return the calculated lcm */ return Res; } unsigned long AlignAddr (unsigned long Addr, unsigned long Alignment) /* Align an address to the given alignment */ { return ((Addr + Alignment - 1) / Alignment) * Alignment; } unsigned long AlignCount (unsigned long Addr, unsigned long Alignment) /* Calculate how many bytes must be inserted to align Addr to Alignment */ { return AlignAddr (Addr, Alignment) - Addr; }
904
./cc65/src/common/filetype.c
/*****************************************************************************/ /* */ /* filetype.c */ /* */ /* Determine the type of a file */ /* */ /* */ /* */ /* (C) 2003-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> /* common */ #include "fileid.h" #include "filetype.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ static const FileId TypeTable[] = { /* Upper case stuff for obsolete operating systems */ { "A", FILETYPE_LIB }, { "A65", FILETYPE_ASM }, { "ASM", FILETYPE_ASM }, { "C", FILETYPE_C }, { "EMD", FILETYPE_O65 }, { "GRC", FILETYPE_GR }, { "JOY", FILETYPE_O65 }, { "LIB", FILETYPE_LIB }, { "MOU", FILETYPE_O65 }, { "O", FILETYPE_OBJ }, { "O65", FILETYPE_O65 }, { "OBJ", FILETYPE_OBJ }, { "S", FILETYPE_ASM }, { "SER", FILETYPE_O65 }, { "TGI", FILETYPE_O65 }, { "a", FILETYPE_LIB }, { "a65", FILETYPE_ASM }, { "asm", FILETYPE_ASM }, { "c", FILETYPE_C }, { "emd", FILETYPE_O65 }, { "grc", FILETYPE_GR }, { "joy", FILETYPE_O65 }, { "lib", FILETYPE_LIB }, { "mou", FILETYPE_O65 }, { "o", FILETYPE_OBJ }, { "o65", FILETYPE_O65 }, { "obj", FILETYPE_OBJ }, { "s", FILETYPE_ASM }, { "ser", FILETYPE_O65 }, { "tgi", FILETYPE_O65 }, }; #define FILETYPE_COUNT (sizeof (TypeTable) / sizeof (TypeTable[0])) /*****************************************************************************/ /* Code */ /*****************************************************************************/ FILETYPE GetFileType (const char* Name) /* Determine the type of the given file by looking at the name. If the file * type could not be determined, the function returns FILETYPE_UNKOWN. */ { /* Search for a table entry */ const FileId* F = GetFileId (Name, TypeTable, FILETYPE_COUNT); /* Return the result */ return F? F->Id : FILETYPE_UNKNOWN; }
905
./cc65/src/common/cpu.c
/*****************************************************************************/ /* */ /* cpu.c */ /* */ /* CPU specifications */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "addrsize.h" #include "check.h" #include "cpu.h" #include "strutil.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* CPU used */ cpu_t CPU = CPU_UNKNOWN; /* Table with target names */ const char* CPUNames[CPU_COUNT] = { "none", "6502", "6502X", "65SC02", "65C02", "65816", "sunplus", "sweet16", "huc6280", "m740", }; /* Tables with CPU instruction sets */ const unsigned CPUIsets[CPU_COUNT] = { CPU_ISET_NONE, CPU_ISET_6502, CPU_ISET_6502 | CPU_ISET_6502X, CPU_ISET_6502 | CPU_ISET_65SC02, CPU_ISET_6502 | CPU_ISET_65SC02 | CPU_ISET_65C02, CPU_ISET_6502 | CPU_ISET_65SC02 | CPU_ISET_65C02 | CPU_ISET_65816, CPU_ISET_SUNPLUS, CPU_ISET_SWEET16, CPU_ISET_6502 | CPU_ISET_65SC02 | CPU_ISET_65C02 | CPU_ISET_HUC6280, CPU_ISET_6502 | CPU_ISET_M740, }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ int ValidAddrSizeForCPU (unsigned char AddrSize) /* Check if the given address size is valid for the current CPU */ { switch (AddrSize) { case ADDR_SIZE_DEFAULT: /* Always supported */ return 1; case ADDR_SIZE_ZP: /* Not supported by None and Sweet16 */ return (CPU != CPU_NONE && CPU != CPU_SWEET16); case ADDR_SIZE_ABS: /* Not supported by None */ return (CPU != CPU_NONE); case ADDR_SIZE_FAR: /* Only supported by 65816 */ return (CPU == CPU_65816); case ADDR_SIZE_LONG: /* Not supported by any CPU */ return 0; default: FAIL ("Invalid address size"); /* NOTREACHED */ return 0; } } cpu_t FindCPU (const char* Name) /* Find a CPU by name and return the target id. CPU_UNKNOWN is returned if * the given name is no valid target. */ { unsigned I; /* Check all CPU names */ for (I = 0; I < CPU_COUNT; ++I) { if (StrCaseCmp (CPUNames [I], Name) == 0) { return (cpu_t)I; } } /* Not found */ return CPU_UNKNOWN; }
906
./cc65/src/common/chartype.c
/*****************************************************************************/ /* */ /* chartype.c */ /* */ /* Character classification functions */ /* */ /* */ /* */ /* (C) 2000-2004 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include "chartype.h" /* This module contains replacements for functions in ctype.h besides other * functions. There is a problem with using ctype.h directly: * The parameter must have a value of "unsigned char" or EOF. * So on platforms where a char is signed, this may give problems or at * least warnings. The wrapper functions below will have an "char" parameter * but handle it correctly. They will NOT work for EOF, but this is not a * problem, since EOF is always handled separately. */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ int IsAlpha (char C) /* Check for a letter */ { return (C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z'); } int IsAlNum (char C) /* Check for letter or digit */ { return (C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z') || (C >= '0' && C <= '9'); } int IsAscii (char C) /* Check for an ASCII character */ { return (C & ~0x7F) == 0; } int IsBlank (char C) /* Check for a space or tab */ { return (C == ' ' || C == '\t'); } int IsSpace (char C) /* Check for any white space characters */ { return (C == ' ' || C == '\n' || C == '\r' || C == '\t' || C == '\v' || C == '\f'); } int IsDigit (char C) /* Check for a digit */ { return (C >= '0' && C <= '9'); } int IsLower (char C) /* Check for a lower case char */ { return (C >= 'a' && C <= 'z'); } int IsUpper (char C) /* Check for upper case characters */ { return (C >= 'A' && C <= 'Z'); } int IsBDigit (char C) /* Check for binary digits (0/1) */ { return (C == '0' || C == '1'); } int IsODigit (char C) /* Check for octal digits (0..7) */ { return (C >= '0' && C <= '7'); } int IsXDigit (char C) /* Check for hexadecimal digits */ { return (C >= 'a' && C <= 'f') || (C >= 'A' && C <= 'F') || (C >= '0' && C <= '9'); } int IsQuote (char C) /* Check for a single or double quote */ { return (C == '"' || C == '\''); }
907
./cc65/src/common/cmdline.c
/*****************************************************************************/ /* */ /* cmdline.c */ /* */ /* Helper functions for command line parsing */ /* */ /* */ /* */ /* (C) 2000-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <errno.h> /* common */ #include "abend.h" #include "chartype.h" #include "fname.h" #include "xmalloc.h" #include "cmdline.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Program name - is set after call to InitCmdLine */ const char* ProgName; /* The program argument vector */ char** ArgVec = 0; unsigned ArgCount = 0; /* Struct to pass the command line */ typedef struct { char** Vec; /* The argument vector */ unsigned Count; /* Actual number of arguments */ unsigned Size; /* Number of argument allocated */ } CmdLine; /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static void NewCmdLine (CmdLine* L) /* Initialize a CmdLine struct */ { /* Initialize the struct */ L->Size = 8; L->Count = 0; L->Vec = xmalloc (L->Size * sizeof (L->Vec[0])); } static void AddArg (CmdLine* L, char* Arg) /* Add one argument to the list */ { if (L->Size <= L->Count) { /* No space left, reallocate */ unsigned NewSize = L->Size * 2; char** NewVec = xmalloc (NewSize * sizeof (L->Vec[0])); memcpy (NewVec, L->Vec, L->Count * sizeof (L->Vec[0])); xfree (L->Vec); L->Vec = NewVec; L->Size = NewSize; } /* We have space left, add a copy of the argument */ L->Vec[L->Count++] = Arg; } static void ExpandFile (CmdLine* L, const char* Name) /* Add the contents of a file to the command line. Each line is a separate * argument with leading and trailing whitespace removed. */ { char Buf [256]; /* Try to open the file for reading */ FILE* F = fopen (Name, "r"); if (F == 0) { AbEnd ("Cannot open \"%s\": %s", Name, strerror (errno)); } /* File is open, read all lines */ while (fgets (Buf, sizeof (Buf), F) != 0) { /* Get a pointer to the buffer */ const char* B = Buf; /* Skip trailing whitespace (this will also kill the newline that is * appended by fgets(). */ unsigned Len = strlen (Buf); while (Len > 0 && IsSpace (Buf [Len-1])) { --Len; } Buf [Len] = '\0'; /* Skip leading spaces */ while (IsSpace (*B)) { ++B; } /* Skip empty lines to work around problems with some editors */ if (*B == '\0') { continue; } /* Add anything not empty to the command line */ AddArg (L, xstrdup (B)); } /* Close the file, ignore errors here since we had the file open for * reading only. */ (void) fclose (F); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ void InitCmdLine (int* aArgCount, char** aArgVec[], const char* aProgName) /* Initialize command line parsing. aArgVec is the argument array terminated by * a NULL pointer (as usual), ArgCount is the number of valid arguments in the * array. Both arguments are remembered in static storage. */ { CmdLine L; int I; /* Get the program name from argv[0] but strip a path */ if (*(aArgVec)[0] == 0) { /* Use the default name given */ ProgName = aProgName; } else { /* Strip a path */ ProgName = FindName ((*aArgVec)[0]); if (ProgName[0] == '\0') { /* Use the default */ ProgName = aProgName; } } /* Make a CmdLine struct */ NewCmdLine (&L); /* Walk over the parameters and add them to the CmdLine struct. Add a * special handling for arguments preceeded by the '@' sign - these are * actually files containing arguments. */ for (I = 0; I < *aArgCount; ++I) { /* Get the next argument */ char* Arg = (*aArgVec)[I]; /* Is this a file argument? */ if (Arg && Arg[0] == '@') { /* Expand the file */ ExpandFile (&L, Arg+1); } else { /* No file, just add a copy */ AddArg (&L, Arg); } } /* Store the new argument list in a safe place... */ ArgCount = L.Count; ArgVec = L.Vec; /* ...and pass back the changed data also */ *aArgCount = L.Count; *aArgVec = L.Vec; } void UnknownOption (const char* Opt) /* Print an error about an unknown option and die. */ { AbEnd ("Unknown option: %s", Opt); } void NeedArg (const char* Opt) /* Print an error about a missing option argument and exit. */ { AbEnd ("Option requires an argument: %s", Opt); } void InvArg (const char* Opt, const char* Arg) /* Print an error about an invalid option argument and exit. */ { AbEnd ("Invalid argument for %s: `%s'", Opt, Arg); } void InvDef (const char* Def) /* Print an error about an invalid definition and die */ { AbEnd ("Invalid definition: `%s'", Def); } const char* GetArg (unsigned* ArgNum, unsigned Len) /* Get an argument for a short option. The argument may be appended to the * option itself or may be separate. Len is the length of the option string. */ { const char* Arg = ArgVec[*ArgNum]; if (Arg[Len] != '\0') { /* Argument appended */ return Arg + Len; } else { /* Separate argument */ Arg = ArgVec[*ArgNum + 1]; if (Arg == 0) { /* End of arguments */ NeedArg (ArgVec[*ArgNum]); } ++(*ArgNum); return Arg; } } void LongOption (unsigned* ArgNum, const LongOpt* OptTab, unsigned OptCount) /* Handle a long command line option */ { /* Get the option and the argument (which may be zero) */ const char* Opt = ArgVec[*ArgNum]; /* Search the table for a match */ while (OptCount) { if (strcmp (Opt, OptTab->Option) == 0) { /* Found, call the function */ if (OptTab->ArgCount > 0) { /* We need an argument, check if we have one */ const char* Arg = ArgVec[++(*ArgNum)]; if (Arg == 0) { NeedArg (Opt); } OptTab->Func (Opt, Arg); } else { OptTab->Func (Opt, 0); } /* Done */ return; } /* Next table entry */ --OptCount; ++OptTab; } /* Invalid option */ UnknownOption (Opt); }
908
./cc65/src/common/debugflag.c
/*****************************************************************************/ /* */ /* debugflag.c */ /* */ /* Global debug flag */ /* */ /* */ /* */ /* (C) 2002 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "debugflag.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ unsigned char Debug = 0; /* Debug mode */
909
./cc65/src/common/fileid.c
/*****************************************************************************/ /* */ /* fileid.c */ /* */ /* Determine the id of a file type by extension */ /* */ /* */ /* */ /* (C) 2003-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> /* common */ #include "fileid.h" #include "fname.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ int CompareFileId (const void* Key, const void* Id) /* Compare function used when calling bsearch with a table of FileIds */ { return strcmp (Key, ((const FileId*) Id)->Ext); } const FileId* GetFileId (const char* Name, const FileId* Table, unsigned Count) /* Determine the id of the given file by looking at file extension of the name. * The table passed to the function must be sorted alphabetically. If the * extension is found, a pointer to the matching table entry is returned. If * no matching table entry was found, the function returns NULL. */ { /* Determine the file type by the extension */ const char* Ext = FindExt (Name); /* Do we have an extension? */ if (Ext == 0) { return 0; } /* Search for a table entry and return it */ return bsearch (Ext+1, Table, Count, sizeof (FileId), CompareFileId); }
910
./cc65/src/common/tgttrans.c
/*****************************************************************************/ /* */ /* tgttrans.c */ /* */ /* Character set translation */ /* */ /* */ /* */ /* (C) 2000-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "check.h" #include "target.h" #include "tgttrans.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Translation table actually used. Default is no translation */ static unsigned char Tab[256] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F, 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F, 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F, 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF, }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ void TgtTranslateInit (void) /* Initialize the translation tables */ { /* Copy the translation for the selected target */ memcpy (Tab, GetTargetProperties (Target)->CharMap, sizeof (Tab)); } int TgtTranslateChar (int C) /* Translate one character from the source character set into the target * system character set. */ { /* Translate */ return Tab[C & 0xFF]; } void TgtTranslateBuf (void* Buf, unsigned Len) /* Translate a buffer of the given length from the source character set into * the target system character set. */ { /* Translate */ unsigned char* B = (unsigned char*)Buf; while (Len--) { *B = Tab[*B]; ++B; } } void TgtTranslateStrBuf (StrBuf* Buf) /* Translate a string buffer from the source character set into the target * system character set. */ { TgtTranslateBuf (SB_GetBuf (Buf), SB_GetLen (Buf)); } void TgtTranslateSet (unsigned Index, unsigned char C) /* Set the translation code for the given character */ { CHECK (Index > 0 && Index < sizeof (Tab)); Tab[Index] = C; }
911
./cc65/src/common/gentype.c
/*****************************************************************************/ /* */ /* gentype.c */ /* */ /* Generic data type encoding */ /* */ /* */ /* */ /* (C) 2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" #include "gentype.h" #include "strbuf.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void GT_AddArray (StrBuf* Type, unsigned ArraySize) /* Add an array with the given size to the type string in Type. This will * NOT add the element type! */ { unsigned SizeBytes; /* Remember the current position */ unsigned Pos = SB_GetLen (Type); /* Add a dummy array token */ SB_AppendChar (Type, GT_TYPE_ARRAY); /* Add the size. */ SizeBytes = 0; do { SB_AppendChar (Type, ArraySize & 0xFF); ArraySize >>= 8; ++SizeBytes; } while (ArraySize); /* Write the correct array token */ SB_GetBuf (Type)[Pos] = GT_ARRAY (SizeBytes); } unsigned GT_GetElementCount (StrBuf* Type) /* Retrieve the element count of an array stored in Type at the current index * position. Note: Index must point to the array token itself, since the size * of the element count is encoded there. The index position will get moved * past the array. */ { /* Get the number of bytes for the element count */ unsigned SizeBytes = GT_GET_SIZE (SB_Get (Type)); /* Read the size */ unsigned Size = 0; const char* Buf = SB_GetConstBuf (Type) + SB_GetLen (Type); while (SizeBytes--) { Size <<= 8; Size |= Buf[SizeBytes]; } /* Return it */ return Size; } const char* GT_AsString (const StrBuf* Type, StrBuf* String) /* Convert the type into a readable representation. The target string buffer * will be zero terminated and a pointer to the contents are returned. */ { static const char HexTab[16] = "0123456789ABCDEF"; unsigned I; /* Convert Type into readable hex. String will have twice then length * plus a terminator. */ SB_Realloc (String, 2 * SB_GetLen (Type) + 1); SB_Clear (String); for (I = 0; I < SB_GetLen (Type); ++I) { unsigned char C = SB_AtUnchecked (Type, I); SB_AppendChar (String, HexTab[(C & 0xF0) >> 4]); SB_AppendChar (String, HexTab[(C & 0x0F) >> 0]); } /* Terminate the string so it can be used with string functions */ SB_Terminate (String); /* Return the contents of String */ return SB_GetConstBuf (String); }
912
./cc65/src/common/addrsize.c
/*****************************************************************************/ /* */ /* addrsize.c */ /* */ /* Address size definitions */ /* */ /* */ /* */ /* (C) 2003-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "addrsize.h" #include "strutil.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ const char* AddrSizeToStr (unsigned char AddrSize) /* Return the name for an address size specifier */ { switch (AddrSize) { case ADDR_SIZE_DEFAULT: return "default"; case ADDR_SIZE_ZP: return "zeropage"; case ADDR_SIZE_ABS: return "absolute"; case ADDR_SIZE_FAR: return "far"; case ADDR_SIZE_LONG: return "long"; default: return "unknown"; } } unsigned char AddrSizeFromStr (const char* Str) /* Return the address size for a given string. Returns ADDR_SIZE_INVALID if * the string cannot be mapped to an address size. */ { static const struct { const char* Name; unsigned char AddrSize; } AddrSizeTable[] = { { "abs", ADDR_SIZE_ABS }, { "absolute", ADDR_SIZE_ABS }, { "default", ADDR_SIZE_DEFAULT }, { "direct", ADDR_SIZE_ZP }, { "dword", ADDR_SIZE_LONG }, { "far", ADDR_SIZE_FAR }, { "long", ADDR_SIZE_LONG }, { "near", ADDR_SIZE_ABS }, { "zeropage", ADDR_SIZE_ZP }, { "zp", ADDR_SIZE_ZP }, }; unsigned I; for (I = 0; I < sizeof (AddrSizeTable) / sizeof (AddrSizeTable[0]); ++I) { if (StrCaseCmp (Str, AddrSizeTable[I].Name) == 0) { /* Found */ return AddrSizeTable[I].AddrSize; } } /* Not found */ return ADDR_SIZE_INVALID; }
913
./cc65/src/common/filetime.c
/*****************************************************************************/ /* */ /* filetime.c */ /* */ /* Replacement for buggy Microsoft code */ /* */ /* */ /* */ /* (C) 2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* This module works around bugs in the time conversion code supplied by * Microsoft. The problem described here: * http://www.codeproject.com/KB/datetime/dstbugs.aspx * is also true when setting file times via utime(), so we need a * replacement */ #if defined(__WATCOMC__) && defined(__NT__) #define BUGGY_OS 1 #include <errno.h> #include <windows.h> #else #if defined(__WATCOMC__) || defined(_MSC_VER) || defined(__MINGW32__) /* The Windows compilers have the file in the wrong directory */ # include <sys/utime.h> #else # include <sys/types.h> /* FreeBSD needs this */ # include <utime.h> #endif #endif /* common */ #include "filetime.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ #if defined(BUGGY_OS) static FILETIME* UnixTimeToFileTime (time_t T, FILETIME* FT) /* Calculate a FILETIME value from a time_t. FILETIME contains a 64 bit * value with point zero at 1600-01-01 00:00:00 and counting 100ns intervals. * time_t is in seconds since 1970-01-01 00:00:00. */ { /* Offset between 1600-01-01 and the Epoch in seconds. Watcom C has no * way to express a number > 32 bit (known to me) but is able to do * calculations with 64 bit integers, so we need to do it this way. */ static const ULARGE_INTEGER Offs = { 0xB6109100UL, 0x00000020UL }; ULARGE_INTEGER V; V.QuadPart = ((unsigned __int64) T + Offs.QuadPart) * 10000000U; FT->dwLowDateTime = V.LowPart; FT->dwHighDateTime = V.HighPart; return FT; } int SetFileTimes (const char* Path, time_t T) /* Set the time of last modification and the time of last access of a file to * the given time T. This calls utime() for system where it works, and applies * workarounds for all others (which in fact means "WINDOWS"). */ { HANDLE H; FILETIME FileTime; int Error = EACCES; /* Assume an error */ /* Open the file */ H = CreateFile (Path, GENERIC_WRITE, FILE_SHARE_READ, 0, /* Security attributes */ OPEN_EXISTING, 0, /* File flags */ 0); /* Template file */ if (H != INVALID_HANDLE_VALUE) { /* Set access and modification time */ UnixTimeToFileTime (T, &FileTime); if (SetFileTime (H, 0, &FileTime, &FileTime)) { /* Done */ Error = 0; } /* Close the handle */ (void) CloseHandle (H); } /* Return the error code */ return Error; } #else int SetFileTimes (const char* Path, time_t T) /* Set the time of last modification and the time of last access of a file to * the given time T. This calls utime() for system where it works, and applies * workarounds for all others (which in fact means "WINDOWS"). */ { struct utimbuf U; /* Set access and modification time */ U.actime = T; U.modtime = T; return utime (Path, &U); } #endif
914
./cc65/src/common/strstack.c
/*****************************************************************************/ /* */ /* strstack.c */ /* */ /* String stack used for program settings */ /* */ /* */ /* */ /* (C) 2004 Ullrich von Bassewitz */ /* R÷merstra▀e 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" #include "strstack.h" #include "xmalloc.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ const char* SS_Get (const StrStack* S) /* Get the value on top of a string stack */ { CHECK (S->Count > 0); return S->Stack[S->Count-1]; } void SS_Set (StrStack* S, const char* Val) /* Set the value on top of a string stack */ { CHECK (S->Count > 0); xfree (S->Stack[S->Count-1]); S->Stack[S->Count-1] = xstrdup (Val); } void SS_Drop (StrStack* S) /* Drop a value from a string stack */ { CHECK (S->Count > 1); xfree (S->Stack[--S->Count]); } void SS_Push (StrStack* S, const char* Val) /* Push a value onto a string stack */ { CHECK (S->Count < sizeof (S->Stack) / sizeof (S->Stack[0])); S->Stack[S->Count++] = xstrdup (Val); }
915
./cc65/src/common/filepos.c
/*****************************************************************************/ /* */ /* filepos.c */ /* */ /* File position data structure */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "filepos.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void InitFilePos (FilePos* P) /* Initialize the file position (set all fields to zero) */ { P->Line = 0; P->Col = 0; P->Name = 0; } int CompareFilePos (const FilePos* P1, const FilePos* P2) /* Compare two file positions. Return zero if both are equal, return a value * > 0 if P1 is greater and P2, and a value < 0 if P1 is less than P2. The * compare rates file index over line over column. */ { if (P1->Name > P2->Name) { return 1; } else if (P1->Name < P2->Name) { return -1; } else if (P1->Line > P2->Line) { return 1; } else if (P1->Line < P2->Line) { return -1; } else if (P1->Col > P2->Col) { return 1; } else if (P1->Col < P2->Col) { return -1; } else { return 0; } }
916
./cc65/src/common/mmodel.c
/*****************************************************************************/ /* */ /* mmodel.c */ /* */ /* Memory model definitions */ /* */ /* */ /* */ /* (C) 2003 Ullrich von Bassewitz */ /* R÷merstra▀e 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "addrsize.h" #include "mmodel.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Memory model in use */ mmodel_t MemoryModel = MMODEL_UNKNOWN; /* Table with memory model names */ static const char* MemoryModelNames[MMODEL_COUNT] = { "near", "far", "huge", }; /* Address sizes for the segments */ unsigned char CodeAddrSize = ADDR_SIZE_ABS; unsigned char DataAddrSize = ADDR_SIZE_ABS; unsigned char ZpAddrSize = ADDR_SIZE_ZP; /*****************************************************************************/ /* Code */ /*****************************************************************************/ mmodel_t FindMemoryModel (const char* Name) /* Find a memory model by name. Return MMODEL_UNKNOWN for an unknown name. */ { unsigned I; /* Check all CPU names */ for (I = 0; I < MMODEL_COUNT; ++I) { if (strcmp (MemoryModelNames[I], Name) == 0) { return (mmodel_t)I; } } /* Not found */ return MMODEL_UNKNOWN; } void SetMemoryModel (mmodel_t Model) /* Set the memory model updating the MemoryModel variables and the address * sizes for the segments. */ { /* Remember the memory model */ MemoryModel = Model; /* Set the address sizes for the segments */ switch (MemoryModel) { case MMODEL_NEAR: /* Code: near, data: near */ CodeAddrSize = ADDR_SIZE_ABS; DataAddrSize = ADDR_SIZE_ABS; break; case MMODEL_FAR: /* Code: far, data: near */ CodeAddrSize = ADDR_SIZE_FAR; DataAddrSize = ADDR_SIZE_ABS; break; case MMODEL_HUGE: /* Code: far, data: far */ CodeAddrSize = ADDR_SIZE_FAR; DataAddrSize = ADDR_SIZE_FAR; break; default: break; } /* Zeropage is always zeropage */ ZpAddrSize = ADDR_SIZE_ZP; }
917
./cc65/src/common/strpool.c
/*****************************************************************************/ /* */ /* strpool.c */ /* */ /* A string pool */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* A string pool is used to store identifiers and other strings. Each string * stored in the pool has a unique id, which may be used to access the string * in the pool. Identical strings are stored only once in the pool and have * identical ids. This means that instead of comparing strings, just the * string pool ids must be compared. */ #include <string.h> /* common */ #include "coll.h" #include "hashfunc.h" #include "hashtab.h" #include "strbuf.h" #include "strpool.h" #include "xmalloc.h" /*****************************************************************************/ /* Forwards */ /*****************************************************************************/ static unsigned HT_GenHash (const void* Key); /* Generate the hash over a key. */ static const void* HT_GetKey (const void* Entry); /* Given a pointer to the user entry data, return a pointer to the key */ static int HT_Compare (const void* Key1, const void* Key2); /* Compare two keys. The function must return a value less than zero if * Key1 is smaller than Key2, zero if both are equal, and a value greater * than zero if Key1 is greater then Key2. */ /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* A string pool entry */ struct StringPoolEntry { HashNode Node; /* Node for the hash table */ unsigned Id; /* The numeric string id */ StrBuf Buf; /* The string itself */ }; /* A string pool */ struct StringPool { Collection Entries; /* Entries sorted by number */ unsigned TotalSize; /* Total size of all string data */ HashTable Tab; /* Hash table */ }; /* Hash table functions */ static const HashFunctions HashFunc = { HT_GenHash, HT_GetKey, HT_Compare }; /*****************************************************************************/ /* struct StringPoolEntry */ /*****************************************************************************/ static StringPoolEntry* NewStringPoolEntry (const StrBuf* S, unsigned Id) /* Create a new string pool entry and return it. */ { /* Allocate memory */ StringPoolEntry* E = xmalloc (sizeof (StringPoolEntry)); /* Initialize the fields */ InitHashNode (&E->Node); E->Id = Id; SB_Init (&E->Buf); SB_Copy (&E->Buf, S); /* Always zero terminate the string */ SB_Terminate (&E->Buf); /* Return the new entry */ return E; } /*****************************************************************************/ /* Hash table functions */ /*****************************************************************************/ static unsigned HT_GenHash (const void* Key) /* Generate the hash over a key. */ { return HashBuf (Key); } static const void* HT_GetKey (const void* Entry) /* Given a pointer to the user entry data, return a pointer to the index */ { return &((const StringPoolEntry*) Entry)->Buf; } static int HT_Compare (const void* Key1, const void* Key2) /* Compare two keys. The function must return a value less than zero if * Key1 is smaller than Key2, zero if both are equal, and a value greater * than zero if Key1 is greater then Key2. */ { return SB_Compare (Key1, Key2); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ StringPool* NewStringPool (unsigned HashSlots) /* Allocate, initialize and return a new string pool */ { /* Allocate memory */ StringPool* P = xmalloc (sizeof (*P)); /* Initialize the fields */ P->Entries = EmptyCollection; P->TotalSize = 0; InitHashTable (&P->Tab, HashSlots, &HashFunc); /* Return a pointer to the new pool */ return P; } void FreeStringPool (StringPool* P) /* Free a string pool */ { unsigned I; /* Free all entries and clear the entry collection */ for (I = 0; I < CollCount (&P->Entries); ++I) { /* Get a pointer to the entry */ StringPoolEntry* E = CollAtUnchecked (&P->Entries, I); /* Free string buffer memory */ SB_Done (&E->Buf); /* Free the memory for the entry itself */ xfree (E); } CollDeleteAll (&P->Entries); /* Free the hash table */ DoneHashTable (&P->Tab); /* Free the string pool itself */ xfree (P); } const StrBuf* SP_Get (const StringPool* P, unsigned Index) /* Return a string from the pool. Index must exist, otherwise FAIL is called. */ { /* Get the collection entry */ const StringPoolEntry* E = CollConstAt (&P->Entries, Index); /* Return the string from the entry */ return &E->Buf; } unsigned SP_Add (StringPool* P, const StrBuf* S) /* Add a string buffer to the buffer and return the index. If the string does * already exist in the pool, SP_AddBuf will just return the index of the * existing string. */ { /* Search for a matching entry in the hash table */ StringPoolEntry* E = HT_Find (&P->Tab, S); /* Did we find it? */ if (E == 0) { /* We didn't find the entry, so create a new one */ E = NewStringPoolEntry (S, CollCount (&P->Entries)); /* Insert the new entry into the entries collection */ CollAppend (&P->Entries, E); /* Insert the new entry into the hash table */ HT_Insert (&P->Tab, E); /* Add up the string size */ P->TotalSize += SB_GetLen (&E->Buf); } /* Return the id of the entry */ return E->Id; } unsigned SP_AddStr (StringPool* P, const char* S) /* Add a string to the buffer and return the index. If the string does already * exist in the pool, SP_Add will just return the index of the existing string. */ { unsigned Id; /* First make a string buffer, then add it. This is some overhead, but the * routine will probably go. */ StrBuf Buf; Id = SP_Add (P, SB_InitFromString (&Buf, S)); /* Return the id of the new entry */ return Id; } unsigned SP_GetCount (const StringPool* P) /* Return the number of strings in the pool */ { return CollCount (&P->Entries); }
918
./cc65/src/common/intstack.c
/*****************************************************************************/ /* */ /* intstack.c */ /* */ /* Integer stack used for program settings */ /* */ /* */ /* */ /* (C) 2004-2010, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" #include "intstack.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ long IS_Get (const IntStack* S) /* Get the value on top of an int stack */ { PRECONDITION (S->Count > 0); return S->Stack[S->Count-1]; } void IS_Set (IntStack* S, long Val) /* Set the value on top of an int stack */ { PRECONDITION (S->Count > 0); S->Stack[S->Count-1] = Val; } void IS_Drop (IntStack* S) /* Drop a value from an int stack */ { PRECONDITION (S->Count > 0); --S->Count; } void IS_Push (IntStack* S, long Val) /* Push a value onto an int stack */ { PRECONDITION (S->Count < sizeof (S->Stack) / sizeof (S->Stack[0])); S->Stack[S->Count++] = Val; } long IS_Pop (IntStack* S) /* Pop a value from an int stack */ { PRECONDITION (S->Count > 0); return S->Stack[--S->Count]; }
919
./cc65/src/common/coll.c
/*****************************************************************************/ /* */ /* coll.c */ /* */ /* Collection (dynamic array) */ /* */ /* */ /* */ /* (C) 2000-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> /* common */ #include "check.h" #include "xmalloc.h" /* cc65 */ #include "coll.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* An empty collection */ const Collection EmptyCollection = STATIC_COLLECTION_INITIALIZER; /*****************************************************************************/ /* Code */ /*****************************************************************************/ Collection* InitCollection (Collection* C) /* Initialize a collection and return it. */ { /* Intialize the fields. */ C->Count = 0; C->Size = 0; C->Items = 0; /* Return the new struct */ return C; } void DoneCollection (Collection* C) /* Free the data for a collection. This will not free the data contained in * the collection. */ { /* Free the pointer array */ xfree (C->Items); } Collection* NewCollection (void) /* Create and return a new collection with the given initial size */ { /* Allocate memory, intialize the collection and return it */ return InitCollection (xmalloc (sizeof (Collection))); } void FreeCollection (Collection* C) /* Free a collection */ { /* Free the data */ DoneCollection (C); /* Free the structure itself */ xfree (C); } void CollGrow (Collection* C, unsigned Size) /* Grow the collection C so it is able to hold Size items without a resize * being necessary. This can be called for performance reasons if the number * of items to be placed in the collection is known in advance. */ { void** NewItems; /* Ignore the call if the collection is already large enough */ if (Size <= C->Size) { return; } /* Grow the collection */ C->Size = Size; NewItems = xmalloc (C->Size * sizeof (void*)); memcpy (NewItems, C->Items, C->Count * sizeof (void*)); xfree (C->Items); C->Items = NewItems; } void CollInsert (Collection* C, void* Item, unsigned Index) /* Insert the data at the given position in the collection */ { /* Check for invalid indices */ PRECONDITION (Index <= C->Count); /* Grow the array if necessary */ if (C->Count >= C->Size) { /* Must grow */ CollGrow (C, (C->Size == 0)? 4 : C->Size * 2); } /* Move the existing elements if needed */ if (C->Count != Index) { memmove (C->Items+Index+1, C->Items+Index, (C->Count-Index) * sizeof (void*)); } ++C->Count; /* Store the new item */ C->Items[Index] = Item; } #if !defined(HAVE_INLINE) void CollAppend (Collection* C, void* Item) /* Append an item to the end of the collection */ { /* Insert the item at the end of the current list */ CollInsert (C, Item, C->Count); } #endif #if !defined(HAVE_INLINE) void* CollAt (const Collection* C, unsigned Index) /* Return the item at the given index */ { /* Check the index */ PRECONDITION (Index < C->Count); /* Return the element */ return C->Items[Index]; } #endif #if !defined(HAVE_INLINE) const void* CollConstAt (const Collection* C, unsigned Index) /* Return the item at the given index */ { /* Check the index */ PRECONDITION (Index < C->Count); /* Return the element */ return C->Items[Index]; } #endif #if !defined(HAVE_INLINE) void* CollLast (Collection* C) /* Return the last item in a collection */ { /* We must have at least one entry */ PRECONDITION (C->Count > 0); /* Return the element */ return C->Items[C->Count-1]; } #endif #if !defined(HAVE_INLINE) const void* CollConstLast (const Collection* C) /* Return the last item in a collection */ { /* We must have at least one entry */ PRECONDITION (C->Count > 0); /* Return the element */ return C->Items[C->Count-1]; } #endif #if !defined(HAVE_INLINE) void* CollPop (Collection* C) /* Remove the last segment from the stack and return it. Calls FAIL if the * collection is empty. */ { /* We must have at least one entry */ PRECONDITION (C->Count > 0); /* Return the element */ return C->Items[--C->Count]; } #endif int CollIndex (Collection* C, const void* Item) /* Return the index of the given item in the collection. Return -1 if the * item was not found in the collection. */ { /* Linear search */ unsigned I; for (I = 0; I < C->Count; ++I) { if (Item == C->Items[I]) { /* Found */ return (int)I; } } /* Not found */ return -1; } void CollDelete (Collection* C, unsigned Index) /* Remove the item with the given index from the collection. This will not * free the item itself, just the pointer. All items with higher indices * will get moved to a lower position. */ { /* Check the index */ PRECONDITION (Index < C->Count); /* Remove the item pointer */ --C->Count; memmove (C->Items+Index, C->Items+Index+1, (C->Count-Index) * sizeof (void*)); } void CollDeleteItem (Collection* C, const void* Item) /* Delete the item pointer from the collection. The item must be in the * collection, otherwise FAIL will be called. */ { /* Get the index of the entry */ int Index = CollIndex (C, Item); CHECK (Index >= 0); /* Delete the item with this index */ --C->Count; memmove (C->Items+Index, C->Items+Index+1, (C->Count-Index) * sizeof (void*)); } #if !defined(HAVE_INLINE) void CollReplace (Collection* C, void* Item, unsigned Index) /* Replace the item at the given position. The old item will not be freed, * just the pointer will get replaced. */ { /* Check the index */ PRECONDITION (Index < C->Count); /* Replace the item pointer */ C->Items[Index] = Item; } #endif void CollReplaceExpand (Collection* C, void* Item, unsigned Index) /* If Index is a valid index for the collection, replace the item at this * position by the one passed. If the collection is too small, expand it, * filling unused pointers with NULL, then add the new item at the given * position. */ { if (Index < C->Count) { /* Collection is already large enough */ C->Items[Index] = Item; } else { /* Must expand the collection */ unsigned Size = C->Size; if (Size == 0) { Size = 4; } while (Index >= Size) { Size *= 2; } CollGrow (C, Size); /* Fill up unused slots with NULL */ while (C->Count < Index) { C->Items[C->Count++] = 0; } /* Fill in the item */ C->Items[C->Count++] = Item; } } void CollMove (Collection* C, unsigned OldIndex, unsigned NewIndex) /* Move an item from one position in the collection to another. OldIndex * is the current position of the item, NewIndex is the new index after * the function has done it's work. Existing entries with indices NewIndex * and up are moved one position upwards. */ { /* Get the item and remove it from the collection */ void* Item = CollAt (C, OldIndex); CollDelete (C, OldIndex); /* Correct NewIndex if needed */ if (NewIndex >= OldIndex) { /* Position has changed with removal */ --NewIndex; } /* Now insert it at the new position */ CollInsert (C, Item, NewIndex); } void CollMoveMultiple (Collection* C, unsigned Start, unsigned Count, unsigned Target) /* Move a range of items from one position to another. Start is the index * of the first item to move, Count is the number of items and Target is * the index of the target item. The item with the index Start will later * have the index Target. All items with indices Target and above are moved * to higher indices. */ { void** TmpItems; unsigned Bytes; /* Check the range */ PRECONDITION (Start < C->Count && Start + Count <= C->Count && Target <= C->Count); /* Check for trivial parameters */ if (Count == 0 || Start == Target) { return; } /* Calculate the raw memory space used by the items to move */ Bytes = Count * sizeof (void*); /* Allocate temporary storage for the items */ TmpItems = xmalloc (Bytes); /* Copy the items we have to move to the temporary storage */ memcpy (TmpItems, C->Items + Start, Bytes); /* Check if the range has to be moved upwards or downwards. Move the * existing items to their final location, so that the space needed * for the items now in temporary storage is unoccupied. */ if (Target < Start) { /* Move downwards */ unsigned BytesToMove = (Start - Target) * sizeof (void*); memmove (C->Items+Target+Count, C->Items+Target, BytesToMove); } else if (Target < Start + Count) { /* Target is inside range */ FAIL ("Not supported"); } else { /* Move upwards */ unsigned ItemsToMove = (Target - Start - Count); unsigned BytesToMove = ItemsToMove * sizeof (void*); memmove (C->Items+Start, C->Items+Target-ItemsToMove, BytesToMove); /* Adjust the target index */ Target -= Count; } /* Move the old items to their final location */ memcpy (C->Items + Target, TmpItems, Bytes); /* Delete the temporary item space */ xfree (TmpItems); } static void QuickSort (Collection* C, int Lo, int Hi, int (*Compare) (void*, const void*, const void*), void* Data) /* Internal recursive sort function. */ { /* Get a pointer to the items */ void** Items = C->Items; /* Quicksort */ while (Hi > Lo) { int I = Lo + 1; int J = Hi; while (I <= J) { while (I <= J && Compare (Data, Items[Lo], Items[I]) >= 0) { ++I; } while (I <= J && Compare (Data, Items[Lo], Items[J]) < 0) { --J; } if (I <= J) { /* Swap I and J */ void* Tmp = Items[I]; Items[I] = Items[J]; Items[J] = Tmp; ++I; --J; } } if (J != Lo) { /* Swap J and Lo */ void* Tmp = Items[J]; Items[J] = Items[Lo]; Items[Lo] = Tmp; } if (J > (Hi + Lo) / 2) { QuickSort (C, J + 1, Hi, Compare, Data); Hi = J - 1; } else { QuickSort (C, Lo, J - 1, Compare, Data); Lo = J + 1; } } } void CollTransfer (Collection* Dest, const Collection* Source) /* Transfer all items from Source to Dest. Anything already in Dest is left * untouched. The items in Source are not changed and are therefore in both * Collections on return. */ { /* Be sure there's enough room in Dest */ CollGrow (Dest, Dest->Count + Source->Count); /* Copy the items */ memcpy (Dest->Items + Dest->Count, Source->Items, Source->Count * sizeof (Source->Items[0])); /* Bump the counter */ Dest->Count += Source->Count; } void CollSort (Collection* C, int (*Compare) (void*, const void*, const void*), void* Data) /* Sort the collection using the given compare function. The data pointer is * passed as *first* element to the compare function, it's not used by the * sort function itself. The other two pointer passed to the Compare function * are pointers to objects. */ { if (C->Count > 1) { QuickSort (C, 0, C->Count-1, Compare, Data); } }
920
./cc65/src/ca65/symtab.c
/*****************************************************************************/ /* */ /* symtab.c */ /* */ /* Symbol table for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "addrsize.h" #include "check.h" #include "hashfunc.h" #include "mmodel.h" #include "scopedefs.h" #include "symdefs.h" #include "xmalloc.h" /* ca65 */ #include "dbginfo.h" #include "error.h" #include "expr.h" #include "global.h" #include "objfile.h" #include "scanner.h" #include "segment.h" #include "sizeof.h" #include "span.h" #include "spool.h" #include "studyexpr.h" #include "symtab.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Combined symbol entry flags used within this module */ #define SF_UNDEFMASK (SF_REFERENCED | SF_DEFINED | SF_IMPORT) #define SF_UNDEFVAL (SF_REFERENCED) /* Symbol tables */ SymTable* CurrentScope = 0; /* Pointer to current symbol table */ SymTable* RootScope = 0; /* Root symbol table */ static SymTable* LastScope = 0; /* Pointer to last scope in list */ static unsigned ScopeCount = 0; /* Number of scopes */ /* Symbol table variables */ static unsigned ImportCount = 0; /* Counter for import symbols */ static unsigned ExportCount = 0; /* Counter for export symbols */ /*****************************************************************************/ /* Internally used functions */ /*****************************************************************************/ static int IsDbgSym (const SymEntry* S) /* Return true if this is a debug symbol */ { if ((S->Flags & (SF_DEFINED | SF_UNUSED)) == SF_DEFINED) { /* Defined symbols are debug symbols if they aren't sizes */ return !IsSizeOfSymbol (S); } else { /* Others are debug symbols if they're referenced imports */ return ((S->Flags & SF_REFIMP) == SF_REFIMP); } } static unsigned ScopeTableSize (unsigned Level) /* Get the size of a table for the given lexical level */ { switch (Level) { case 0: return 213; case 1: return 53; default: return 29; } } static SymTable* NewSymTable (SymTable* Parent, const StrBuf* Name) /* Allocate a symbol table on the heap and return it */ { /* Determine the lexical level and the number of table slots */ unsigned Level = Parent? Parent->Level + 1 : 0; unsigned Slots = ScopeTableSize (Level); /* Allocate memory */ SymTable* S = xmalloc (sizeof (SymTable) + (Slots-1) * sizeof (SymEntry*)); /* Set variables and clear hash table entries */ S->Next = 0; S->Left = 0; S->Right = 0; S->Childs = 0; S->Label = 0; S->Spans = AUTO_COLLECTION_INITIALIZER; S->Id = ScopeCount++; S->Flags = ST_NONE; S->AddrSize = ADDR_SIZE_DEFAULT; S->Type = SCOPE_UNDEF; S->Level = Level; S->TableSlots = Slots; S->TableEntries = 0; S->Parent = Parent; S->Name = GetStrBufId (Name); while (Slots--) { S->Table[Slots] = 0; } /* Insert the symbol table into the list of all symbol tables */ if (RootScope == 0) { RootScope = S; } else { LastScope->Next = S; } LastScope = S; /* Insert the symbol table into the child tree of the parent */ if (Parent) { SymTable* T = Parent->Childs; if (T == 0) { /* First entry */ Parent->Childs = S; } else { while (1) { /* Choose next entry */ int Cmp = SB_Compare (Name, GetStrBuf (T->Name)); if (Cmp < 0) { if (T->Left) { T = T->Left; } else { T->Left = S; break; } } else if (Cmp > 0) { if (T->Right) { T = T->Right; } else { T->Right = S; break; } } else { /* Duplicate scope name */ Internal ("Duplicate scope name: `%m%p'", Name); } } } } /* Return the prepared struct */ return S; } /*****************************************************************************/ /* Code */ /*****************************************************************************/ void SymEnterLevel (const StrBuf* ScopeName, unsigned char Type, unsigned char AddrSize, SymEntry* ScopeLabel) /* Enter a new lexical level */ { /* Map a default address size to something real */ if (AddrSize == ADDR_SIZE_DEFAULT) { /* Use the segment address size */ AddrSize = GetCurrentSegAddrSize (); } /* If we have a current scope, search for the given name and create a * new one if it doesn't exist. If this is the root scope, just create it. */ if (CurrentScope) { /* Search for the scope, create a new one */ CurrentScope = SymFindScope (CurrentScope, ScopeName, SYM_ALLOC_NEW); /* Check if the scope has been defined before */ if (CurrentScope->Flags & ST_DEFINED) { Error ("Duplicate scope `%m%p'", ScopeName); } } else { CurrentScope = RootScope = NewSymTable (0, ScopeName); } /* Mark the scope as defined and set type, address size and owner symbol */ CurrentScope->Flags |= ST_DEFINED; CurrentScope->AddrSize = AddrSize; CurrentScope->Type = Type; CurrentScope->Label = ScopeLabel; /* If this is a scope that allows to emit data into segments, add spans * for all currently existing segments. Doing this for just a few scope * types is not really necessary but an optimization, because it does not * allocate memory for useless data (unhandled types here don't occupy * space in any segment). */ if (CurrentScope->Type <= SCOPE_HAS_DATA) { OpenSpanList (&CurrentScope->Spans); } } void SymLeaveLevel (void) /* Leave the current lexical level */ { /* If this is a scope that allows to emit data into segments, close the * open the spans. */ if (CurrentScope->Type <= SCOPE_HAS_DATA) { CloseSpanList (&CurrentScope->Spans); } /* If we have spans, the first one is the segment that was active, when the * scope was opened. Set the size of the scope to the number of data bytes * emitted into this segment. If we have an owner symbol set the size of * this symbol, too. */ if (CollCount (&CurrentScope->Spans) > 0) { const Span* S = CollAtUnchecked (&CurrentScope->Spans, 0); unsigned long Size = GetSpanSize (S); DefSizeOfScope (CurrentScope, Size); if (CurrentScope->Label) { DefSizeOfSymbol (CurrentScope->Label, Size); } } /* Mark the scope as closed */ CurrentScope->Flags |= ST_CLOSED; /* Leave the scope */ CurrentScope = CurrentScope->Parent; } SymTable* SymFindScope (SymTable* Parent, const StrBuf* Name, SymFindAction Action) /* Find a scope in the given enclosing scope */ { SymTable** T = &Parent->Childs; while (*T) { int Cmp = SB_Compare (Name, GetStrBuf ((*T)->Name)); if (Cmp < 0) { T = &(*T)->Left; } else if (Cmp > 0) { T = &(*T)->Right; } else { /* Found the scope */ return *T; } } /* Create a new scope if requested and we didn't find one */ if (*T == 0 && (Action & SYM_ALLOC_NEW) != 0) { *T = NewSymTable (Parent, Name); } /* Return the scope */ return *T; } SymTable* SymFindAnyScope (SymTable* Parent, const StrBuf* Name) /* Find a scope in the given or any of its parent scopes. The function will * never create a new symbol, since this can only be done in one specific * scope. */ { SymTable* Scope; do { /* Search in the current table */ Scope = SymFindScope (Parent, Name, SYM_FIND_EXISTING); if (Scope == 0) { /* Not found, search in the parent scope, if we have one */ Parent = Parent->Parent; } } while (Scope == 0 && Parent != 0); return Scope; } SymEntry* SymFindLocal (SymEntry* Parent, const StrBuf* Name, SymFindAction Action) /* Find a cheap local symbol. If Action contains SYM_ALLOC_NEW and the entry is * not found, create a new one. Return the entry found, or the new entry * created, or - in case Action is SYM_FIND_EXISTING - return 0. */ { SymEntry* S; int Cmp; /* Local symbol, get the table */ if (!Parent) { /* No last global, so there's no local table */ Error ("No preceeding global symbol"); if (Action & SYM_ALLOC_NEW) { return NewSymEntry (Name, SF_LOCAL); } else { return 0; } } /* Search for the symbol if we have a table */ Cmp = SymSearchTree (Parent->Locals, Name, &S); /* If we found an entry, return it */ if (Cmp == 0) { return S; } if (Action & SYM_ALLOC_NEW) { /* Otherwise create a new entry, insert and return it */ SymEntry* N = NewSymEntry (Name, SF_LOCAL); N->Sym.Entry = Parent; if (S == 0) { Parent->Locals = N; } else if (Cmp < 0) { S->Left = N; } else { S->Right = N; } return N; } /* We did not find the entry and AllocNew is false. */ return 0; } SymEntry* SymFind (SymTable* Scope, const StrBuf* Name, SymFindAction Action) /* Find a new symbol table entry in the given table. If Action contains * SYM_ALLOC_NEW and the entry is not found, create a new one. Return the * entry found, or the new entry created, or - in case Action is * SYM_FIND_EXISTING - return 0. */ { SymEntry* S; /* Global symbol: Get the hash value for the name */ unsigned Hash = HashBuf (Name) % Scope->TableSlots; /* Search for the entry */ int Cmp = SymSearchTree (Scope->Table[Hash], Name, &S); /* If we found an entry, return it */ if (Cmp == 0) { if ((Action & SYM_CHECK_ONLY) == 0 && SymTabIsClosed (Scope)) { S->Flags |= SF_FIXED; } return S; } if (Action & SYM_ALLOC_NEW) { /* Otherwise create a new entry, insert and return it. If the scope is * already closed, mark the symbol as fixed so it won't be resolved * by a symbol in the enclosing scopes later. */ SymEntry* N = NewSymEntry (Name, SF_NONE); if (SymTabIsClosed (Scope)) { N->Flags |= SF_FIXED; } N->Sym.Tab = Scope; if (S == 0) { Scope->Table[Hash] = N; } else if (Cmp < 0) { S->Left = N; } else { S->Right = N; } ++Scope->TableEntries; return N; } /* We did not find the entry and AllocNew is false. */ return 0; } SymEntry* SymFindAny (SymTable* Scope, const StrBuf* Name) /* Find a symbol in the given or any of its parent scopes. The function will * never create a new symbol, since this can only be done in one specific * scope. */ { /* Generate the name hash */ unsigned Hash = HashBuf (Name); /* Search for the symbol */ SymEntry* Sym; do { /* Search in the current table. Ignore entries flagged with SF_UNUSED, * because for such symbols there is a real entry in one of the parent * scopes. */ if (SymSearchTree (Scope->Table[Hash % Scope->TableSlots], Name, &Sym) == 0) { if (Sym->Flags & SF_UNUSED) { Sym = 0; } else { /* Found, return it */ break; } } else { Sym = 0; } /* Not found, search in the parent scope, if we have one */ Scope = Scope->Parent; } while (Sym == 0 && Scope != 0); /* Return the result */ return Sym; } static void SymCheckUndefined (SymEntry* S) /* Handle an undefined symbol */ { /* Undefined symbol. It may be... * * - An undefined symbol in a nested lexical level. If the symbol is not * fixed to this level, search for the symbol in the higher levels and * make the entry a trampoline entry if we find one. * * - If the symbol is not found, it is a real undefined symbol. If the * AutoImport flag is set, make it an import. If the AutoImport flag is * not set, it's an error. */ SymEntry* Sym = 0; if ((S->Flags & SF_FIXED) == 0) { SymTable* Tab = GetSymParentScope (S); while (Tab) { Sym = SymFind (Tab, GetStrBuf (S->Name), SYM_FIND_EXISTING | SYM_CHECK_ONLY); if (Sym && (Sym->Flags & (SF_DEFINED | SF_IMPORT)) != 0) { /* We've found a symbol in a higher level that is * either defined in the source, or an import. */ break; } /* No matching symbol found in this level. Look further */ Tab = Tab->Parent; } } if (Sym) { /* We found the symbol in a higher level. Transfer the flags and * address size from the local symbol to that in the higher level * and check for problems. */ if (S->Flags & SF_EXPORT) { if (Sym->Flags & SF_IMPORT) { /* The symbol is already marked as import */ LIError (&S->RefLines, "Symbol `%s' is already an import", GetString (Sym->Name)); } if (Sym->Flags & SF_EXPORT) { /* The symbol is already marked as an export. */ if (Sym->AddrSize > S->ExportSize) { /* We're exporting a symbol smaller than it actually is */ LIWarning (&S->DefLines, 1, "Symbol `%m%p' is %s but exported %s", GetSymName (Sym), AddrSizeToStr (Sym->AddrSize), AddrSizeToStr (S->ExportSize)); } } else { /* Mark the symbol as an export */ Sym->Flags |= SF_EXPORT; Sym->ExportSize = S->ExportSize; if (Sym->ExportSize == ADDR_SIZE_DEFAULT) { /* Use the actual size of the symbol */ Sym->ExportSize = Sym->AddrSize; } if (Sym->AddrSize > Sym->ExportSize) { /* We're exporting a symbol smaller than it actually is */ LIWarning (&S->DefLines, 1, "Symbol `%m%p' is %s but exported %s", GetSymName (Sym), AddrSizeToStr (Sym->AddrSize), AddrSizeToStr (Sym->ExportSize)); } } } if (S->Flags & SF_REFERENCED) { /* Mark as referenced and move the line info */ Sym->Flags |= SF_REFERENCED; CollTransfer (&Sym->RefLines, &S->RefLines); CollDeleteAll (&S->RefLines); } /* Transfer all expression references */ SymTransferExprRefs (S, Sym); /* Mark the symbol as unused removing all other flags */ S->Flags = SF_UNUSED; } else { /* The symbol is definitely undefined */ if (S->Flags & SF_EXPORT) { /* We will not auto-import an export */ LIError (&S->RefLines, "Exported symbol `%m%p' was never defined", GetSymName (S)); } else { if (AutoImport) { /* Mark as import, will be indexed later */ S->Flags |= SF_IMPORT; /* Use the address size for code */ S->AddrSize = CodeAddrSize; /* Mark point of import */ GetFullLineInfo (&S->DefLines); } else { /* Error */ LIError (&S->RefLines, "Symbol `%m%p' is undefined", GetSymName (S)); } } } } void SymCheck (void) /* Run through all symbols and check for anomalies and errors */ { SymEntry* S; /* Check for open scopes */ if (CurrentScope->Parent != 0) { Error ("Local scope was not closed"); } /* First pass: Walk through all symbols, checking for undefined's and * changing them to trampoline symbols or make them imports. */ S = SymList; while (S) { /* If the symbol is marked as global, mark it as export, if it is * already defined, otherwise mark it as import. */ if (S->Flags & SF_GLOBAL) { if (S->Flags & SF_DEFINED) { SymExportFromGlobal (S); } else { SymImportFromGlobal (S); } } /* Handle undefined symbols */ if ((S->Flags & SF_UNDEFMASK) == SF_UNDEFVAL) { /* This is an undefined symbol. Handle it. */ SymCheckUndefined (S); } /* Next symbol */ S = S->List; } /* Second pass: Walk again through the symbols. Count exports and imports * and set address sizes where this has not happened before. Ignore * undefined's, since we handled them in the last pass, and ignore unused * symbols, since we handled them in the last pass, too. */ S = SymList; while (S) { if ((S->Flags & SF_UNUSED) == 0 && (S->Flags & SF_UNDEFMASK) != SF_UNDEFVAL) { /* Check for defined symbols that were never referenced */ if (IsSizeOfSymbol (S)) { /* Remove line infos, we don't need them any longer */ ReleaseFullLineInfo (&S->DefLines); ReleaseFullLineInfo (&S->RefLines); } else if ((S->Flags & SF_DEFINED) != 0 && (S->Flags & SF_REFERENCED) == 0) { LIWarning (&S->DefLines, 2, "Symbol `%m%p' is defined but never used", GetSymName (S)); } /* Assign an index to all imports */ if (S->Flags & SF_IMPORT) { if ((S->Flags & (SF_REFERENCED | SF_FORCED)) == SF_NONE) { /* Imported symbol is not referenced */ LIWarning (&S->DefLines, 2, "Symbol `%m%p' is imported but never used", GetSymName (S)); } else { /* Give the import an id, count imports */ S->ImportId = ImportCount++; } } /* Count exports, assign the export ID */ if (S->Flags & SF_EXPORT) { S->ExportId = ExportCount++; } /* If the symbol is defined but has an unknown address size, * recalculate it. */ if (SymHasExpr (S) && S->AddrSize == ADDR_SIZE_DEFAULT) { ExprDesc ED; ED_Init (&ED); StudyExpr (S->Expr, &ED); S->AddrSize = ED.AddrSize; if (SymIsExport (S)) { if (S->ExportSize == ADDR_SIZE_DEFAULT) { /* Use the real export size */ S->ExportSize = S->AddrSize; } else if (S->AddrSize > S->ExportSize) { /* We're exporting a symbol smaller than it actually is */ LIWarning (&S->DefLines, 1, "Symbol `%m%p' is %s but exported %s", GetSymName (S), AddrSizeToStr (S->AddrSize), AddrSizeToStr (S->ExportSize)); } } ED_Done (&ED); } /* If the address size of the symbol was guessed, check the guess * against the actual address size and print a warning if the two * differ. */ if (S->AddrSize != ADDR_SIZE_DEFAULT) { /* Do we have data for this address size? */ if (S->AddrSize <= sizeof (S->GuessedUse) / sizeof (S->GuessedUse[0])) { /* Get the file position where the symbol was used */ const FilePos* P = S->GuessedUse[S->AddrSize - 1]; if (P) { PWarning (P, 0, "Didn't use %s addressing for `%m%p'", AddrSizeToStr (S->AddrSize), GetSymName (S)); } } } } /* Next symbol */ S = S->List; } } void SymDump (FILE* F) /* Dump the symbol table */ { SymEntry* S = SymList; while (S) { /* Ignore unused symbols */ if ((S->Flags & SF_UNUSED) != 0) { fprintf (F, "%m%-24p %s %s %s %s %s\n", GetSymName (S), (S->Flags & SF_DEFINED)? "DEF" : "---", (S->Flags & SF_REFERENCED)? "REF" : "---", (S->Flags & SF_IMPORT)? "IMP" : "---", (S->Flags & SF_EXPORT)? "EXP" : "---", AddrSizeToStr (S->AddrSize)); } /* Next symbol */ S = S->List; } } void WriteImports (void) /* Write the imports list to the object file */ { SymEntry* S; /* Tell the object file module that we're about to start the imports */ ObjStartImports (); /* Write the import count to the list */ ObjWriteVar (ImportCount); /* Walk throught list and write all valid imports to the file. An import * is considered valid, if it is either referenced, or the forced bit is * set. Otherwise, the import is ignored (no need to link in something * that isn't used). */ S = SymList; while (S) { if ((S->Flags & (SF_UNUSED | SF_IMPORT)) == SF_IMPORT && (S->Flags & (SF_REFERENCED | SF_FORCED)) != 0) { ObjWrite8 (S->AddrSize); ObjWriteVar (S->Name); WriteLineInfo (&S->DefLines); WriteLineInfo (&S->RefLines); } S = S->List; } /* Done writing imports */ ObjEndImports (); } void WriteExports (void) /* Write the exports list to the object file */ { SymEntry* S; unsigned Type; /* Tell the object file module that we're about to start the exports */ ObjStartExports (); /* Write the export count to the list */ ObjWriteVar (ExportCount); /* Walk throught list and write all exports to the file */ S = SymList; while (S) { if ((S->Flags & (SF_UNUSED | SF_EXPORT)) == SF_EXPORT) { /* Get the expression bits and the value */ long ConstVal; unsigned SymFlags = GetSymInfoFlags (S, &ConstVal); /* Check if this symbol has a size. If so, remember it in the * flags. */ long Size; SymEntry* SizeSym = FindSizeOfSymbol (S); if (SizeSym != 0 && SymIsConst (SizeSym, &Size)) { SymFlags |= SYM_SIZE; } /* Count the number of ConDes types */ for (Type = 0; Type < CD_TYPE_COUNT; ++Type) { if (S->ConDesPrio[Type] != CD_PRIO_NONE) { SYM_INC_CONDES_COUNT (SymFlags); } } /* Write the type and the export size */ ObjWriteVar (SymFlags); ObjWrite8 (S->ExportSize); /* Write any ConDes declarations */ if (SYM_GET_CONDES_COUNT (SymFlags) > 0) { for (Type = 0; Type < CD_TYPE_COUNT; ++Type) { unsigned char Prio = S->ConDesPrio[Type]; if (Prio != CD_PRIO_NONE) { ObjWrite8 (CD_BUILD (Type, Prio)); } } } /* Write the name */ ObjWriteVar (S->Name); /* Write the value */ if (SYM_IS_CONST (SymFlags)) { /* Constant value */ ObjWrite32 (ConstVal); } else { /* Expression involved */ WriteExpr (S->Expr); } /* If the symbol has a size, write it to the file */ if (SYM_HAS_SIZE (SymFlags)) { ObjWriteVar (Size); } /* Write the line infos */ WriteLineInfo (&S->DefLines); WriteLineInfo (&S->RefLines); } S = S->List; } /* Done writing exports */ ObjEndExports (); } void WriteDbgSyms (void) /* Write a list of all symbols to the object file */ { unsigned Count; SymEntry* S; /* Tell the object file module that we're about to start the debug info */ ObjStartDbgSyms (); /* Check if debug info is requested */ if (DbgSyms) { /* Walk through the list, give each symbol an id and count them */ Count = 0; S = SymList; while (S) { if (IsDbgSym (S)) { S->DebugSymId = Count++; } S = S->List; } /* Write the symbol count to the list */ ObjWriteVar (Count); /* Walk through list and write all symbols to the file. Ignore size * symbols. */ S = SymList; while (S) { if (IsDbgSym (S)) { /* Get the expression bits and the value */ long ConstVal; unsigned SymFlags = GetSymInfoFlags (S, &ConstVal); /* Check if this symbol has a size. If so, remember it in the * flags. */ long Size; SymEntry* SizeSym = FindSizeOfSymbol (S); if (SizeSym != 0 && SymIsConst (SizeSym, &Size)) { SymFlags |= SYM_SIZE; } /* Write the type */ ObjWriteVar (SymFlags); /* Write the address size */ ObjWrite8 (S->AddrSize); /* Write the id of the parent. For normal symbols, this is a * scope (symbol table), for cheap locals, it's a symbol. */ if (SYM_IS_STD (SymFlags)) { ObjWriteVar (S->Sym.Tab->Id); } else { ObjWriteVar (S->Sym.Entry->DebugSymId); } /* Write the name */ ObjWriteVar (S->Name); /* Write the value */ if (SYM_IS_CONST (SymFlags)) { /* Constant value */ ObjWrite32 (ConstVal); } else { /* Expression involved */ WriteExpr (S->Expr); } /* If the symbol has a size, write it to the file */ if (SYM_HAS_SIZE (SymFlags)) { ObjWriteVar (Size); } /* If the symbol is an im- or export, write out the ids */ if (SYM_IS_IMPORT (SymFlags)) { ObjWriteVar (GetSymImportId (S)); } if (SYM_IS_EXPORT (SymFlags)) { ObjWriteVar (GetSymExportId (S)); } /* Write the line infos */ WriteLineInfo (&S->DefLines); WriteLineInfo (&S->RefLines); } S = S->List; } } else { /* No debug symbols */ ObjWriteVar (0); } /* Write the high level symbols */ WriteHLLDbgSyms (); /* Done writing debug symbols */ ObjEndDbgSyms (); } void WriteScopes (void) /* Write the scope table to the object file */ { /* Tell the object file module that we're about to start the scopes */ ObjStartScopes (); /* We will write scopes only if debug symbols are requested */ if (DbgSyms) { /* Get head of list */ SymTable* S = RootScope; /* Write the scope count to the file */ ObjWriteVar (ScopeCount); /* Walk through all scopes and write them to the file */ while (S) { /* Flags for this scope */ unsigned Flags = 0; /* Check if this scope has a size. If so, remember it in the * flags. */ long Size; SymEntry* SizeSym = FindSizeOfScope (S); if (SizeSym != 0 && SymIsConst (SizeSym, &Size)) { Flags |= SCOPE_SIZE; } /* Check if the scope has a label */ if (S->Label) { Flags |= SCOPE_LABELED; } /* Scope must be defined */ CHECK (S->Type != SCOPE_UNDEF); /* Id of parent scope */ if (S->Parent) { ObjWriteVar (S->Parent->Id); } else { ObjWriteVar (0); } /* Lexical level */ ObjWriteVar (S->Level); /* Scope flags */ ObjWriteVar (Flags); /* Type of scope */ ObjWriteVar (S->Type); /* Name of the scope */ ObjWriteVar (S->Name); /* If the scope has a size, write it to the file */ if (SCOPE_HAS_SIZE (Flags)) { ObjWriteVar (Size); } /* If the scope has a label, write its id to the file */ if (SCOPE_HAS_LABEL (Flags)) { ObjWriteVar (S->Label->DebugSymId); } /* Spans for this scope */ WriteSpanList (&S->Spans); /* Next scope */ S = S->Next; } } else { /* No debug info requested */ ObjWriteVar (0); } /* Done writing the scopes */ ObjEndScopes (); }
921
./cc65/src/ca65/options.c
/*****************************************************************************/ /* */ /* options.c */ /* */ /* Object file options for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2008, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "optdefs.h" #include "xmalloc.h" /* ca65 */ #include "error.h" #include "objfile.h" #include "options.h" #include "spool.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Option list */ static Option* OptRoot = 0; static Option* OptLast = 0; static unsigned OptCount = 0; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static Option* NewOption (unsigned char Type, unsigned long Val) /* Create a new option, insert it into the list and return it */ { Option* Opt; /* Allocate memory */ Opt = xmalloc (sizeof (*Opt)); /* Initialize fields */ Opt->Next = 0; Opt->Type = Type; Opt->Val = Val; /* Insert it into the list */ if (OptRoot == 0) { OptRoot = Opt; } else { OptLast->Next = Opt; } OptLast = Opt; /* One more option now */ ++OptCount; /* Return the new struct */ return Opt; } void OptStr (unsigned char Type, const StrBuf* Text) /* Add a string option */ { NewOption (Type, GetStrBufId (Text)); } void OptComment (const StrBuf* Comment) /* Add a comment */ { NewOption (OPT_COMMENT, GetStrBufId (Comment)); } void OptAuthor (const StrBuf* Author) /* Add an author statement */ { NewOption (OPT_AUTHOR, GetStrBufId (Author)); } void OptTranslator (const StrBuf* Translator) /* Add a translator option */ { NewOption (OPT_TRANSLATOR, GetStrBufId (Translator)); } void OptCompiler (const StrBuf* Compiler) /* Add a compiler option */ { NewOption (OPT_COMPILER, GetStrBufId (Compiler)); } void OptOS (const StrBuf* OS) /* Add an operating system option */ { NewOption (OPT_OS, GetStrBufId (OS)); } void OptDateTime (unsigned long DateTime) /* Add a date/time option */ { NewOption (OPT_DATETIME, DateTime); } void WriteOptions (void) /* Write the options to the object file */ { Option* O; /* Tell the object file module that we're about to start the options */ ObjStartOptions (); /* Write the option count */ ObjWriteVar (OptCount); /* Walk through the list and write the options */ O = OptRoot; while (O) { /* Write the type of the option, then the value */ ObjWrite8 (O->Type); ObjWriteVar (O->Val); /* Next option */ O = O->Next; } /* Done writing options */ ObjEndOptions (); }
922
./cc65/src/ca65/objcode.c
/*****************************************************************************/ /* */ /* objcode.c */ /* */ /* Objectcode management for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> #include <errno.h> /* cc65 */ #include "error.h" #include "fragment.h" #include "objcode.h" #include "segment.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void Emit0 (unsigned char OPC) /* Emit an instruction with a zero sized operand */ { Fragment* F = GenFragment (FRAG_LITERAL, 1); F->V.Data[0] = OPC; } void Emit1 (unsigned char OPC, ExprNode* Value) /* Emit an instruction with an one byte argument */ { long V; Fragment* F; if (IsEasyConst (Value, &V)) { /* Must be in byte range */ if (!IsByteRange (V)) { Error ("Range error (%ld not in [0..255])", V); } /* Create a literal fragment */ F = GenFragment (FRAG_LITERAL, 2); F->V.Data[0] = OPC; F->V.Data[1] = (unsigned char) V; FreeExpr (Value); } else { /* Emit the opcode */ Emit0 (OPC); /* Emit the argument as an expression */ F = GenFragment (FRAG_EXPR, 1); F->V.Expr = Value; } } void Emit2 (unsigned char OPC, ExprNode* Value) /* Emit an instruction with a two byte argument */ { long V; Fragment* F; if (IsEasyConst (Value, &V)) { /* Must be in byte range */ if (!IsWordRange (V)) { Error ("Range error (%ld not in [0..65535])", V); } /* Create a literal fragment */ F = GenFragment (FRAG_LITERAL, 3); F->V.Data[0] = OPC; F->V.Data[1] = (unsigned char) V; F->V.Data[2] = (unsigned char) (V >> 8); FreeExpr (Value); } else { /* Emit the opcode */ Emit0 (OPC); /* Emit the argument as an expression */ F = GenFragment (FRAG_EXPR, 2); F->V.Expr = Value; } } void Emit3 (unsigned char OPC, ExprNode* Expr) /* Emit an instruction with a three byte argument */ { Emit0 (OPC); EmitFarAddr (Expr); } void EmitSigned (ExprNode* Expr, unsigned Size) /* Emit a signed expression with the given size */ { Fragment* F = GenFragment (FRAG_SEXPR, Size); F->V.Expr = Expr; } void EmitPCRel (unsigned char OPC, ExprNode* Expr, unsigned Size) /* Emit an opcode with a PC relative argument of one or two bytes */ { Emit0 (OPC); EmitSigned (Expr, Size); } void EmitData (const void* D, unsigned Size) /* Emit data into the current segment */ { /* Make a useful pointer from Data */ const unsigned char* Data = D; /* Create lots of fragments for the data */ while (Size) { Fragment* F; /* Determine the length of the next fragment */ unsigned Len = Size; if (Len > sizeof (F->V.Data)) { Len = sizeof (F->V.Data); } /* Create a new fragment */ F = GenFragment (FRAG_LITERAL, Len); /* Copy the data */ memcpy (F->V.Data, Data, Len); /* Next chunk */ Data += Len; Size -= Len; } } void EmitStrBuf (const StrBuf* Data) /* Emit a string into the current segment */ { /* Use EmitData to output the data */ EmitData (SB_GetConstBuf (Data), SB_GetLen (Data)); } void EmitByte (ExprNode* Expr) /* Emit one byte */ { long V; Fragment* F; if (IsEasyConst (Expr, &V)) { /* Must be in byte range */ if (!IsByteRange (V)) { Error ("Range error (%ld not in [0..255])", V); } /* Create a literal fragment */ F = GenFragment (FRAG_LITERAL, 1); F->V.Data[0] = (unsigned char) V; FreeExpr (Expr); } else { /* Emit the argument as an expression */ F = GenFragment (FRAG_EXPR, 1); F->V.Expr = Expr; } } void EmitWord (ExprNode* Expr) /* Emit one word */ { long V; Fragment* F; if (IsEasyConst (Expr, &V)) { /* Must be in byte range */ if (!IsWordRange (V)) { Error ("Range error (%ld not in [0..65535])", V); } /* Create a literal fragment */ F = GenFragment (FRAG_LITERAL, 2); F->V.Data[0] = (unsigned char) V; F->V.Data[1] = (unsigned char) (V >> 8); FreeExpr (Expr); } else { /* Emit the argument as an expression */ Fragment* F = GenFragment (FRAG_EXPR, 2); F->V.Expr = Expr; } } void EmitFarAddr (ExprNode* Expr) /* Emit a 24 bit expression */ { /* Create a new fragment */ Fragment* F = GenFragment (FRAG_EXPR, 3); /* Set the data */ F->V.Expr = Expr; } void EmitDWord (ExprNode* Expr) /* Emit one dword */ { /* Create a new fragment */ Fragment* F = GenFragment (FRAG_EXPR, 4); /* Set the data */ F->V.Expr = Expr; } void EmitFill (unsigned long Count) /* Emit Count fill bytes */ { while (Count) { /* Calculate the size of the next chunk */ unsigned Chunk = (Count > 0xFFFF)? 0xFFFF : (unsigned) Count; Count -= Chunk; /* Emit one chunk */ GenFragment (FRAG_FILL, Chunk); } }
923
./cc65/src/ca65/struct.c
/*****************************************************************************/ /* */ /* struct.c */ /* */ /* .STRUCT/.UNION commands */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "addrsize.h" #include "scopedefs.h" /* ca65 */ #include "condasm.h" #include "error.h" #include "expr.h" #include "macro.h" #include "nexttok.h" #include "scanner.h" #include "sizeof.h" #include "symbol.h" #include "symtab.h" #include "struct.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ enum { STRUCT, UNION }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static long Member (long AllocSize) /* Read one struct member and return its size */ { long Multiplicator; /* A multiplicator may follow */ if (CurTok.Tok != TOK_SEP) { Multiplicator = ConstExpression (); if (Multiplicator <= 0) { ErrorSkip ("Range error"); Multiplicator = 1; } AllocSize *= Multiplicator; } /* Check the size for a reasonable value */ if (AllocSize >= 0x10000) { ErrorSkip ("Range error"); } /* Return the size */ return AllocSize; } static long DoStructInternal (long Offs, unsigned Type) /* Handle the .STRUCT command */ { long Size = 0; /* Outside of other structs, we need a name. Inside another struct or * union, the struct may be anonymous, in which case no new lexical level * is started. */ int Anon = (CurTok.Tok != TOK_IDENT); if (!Anon) { /* Enter a new scope, then skip the name */ SymEnterLevel (&CurTok.SVal, SCOPE_STRUCT, ADDR_SIZE_ABS, 0); NextTok (); /* Start at zero offset in the new scope */ Offs = 0; } /* Test for end of line */ ConsumeSep (); /* Read until end of struct */ while (CurTok.Tok != TOK_ENDSTRUCT && CurTok.Tok != TOK_ENDUNION && CurTok.Tok != TOK_EOF) { long MemberSize; SymTable* Struct; SymEntry* Sym; /* Allow empty and comment lines */ if (CurTok.Tok == TOK_SEP) { NextTok (); continue; } /* The format is "[identifier] storage-allocator [, multiplicator]" */ Sym = 0; if (CurTok.Tok == TOK_IDENT) { /* Beware: An identifier may also be a macro, in which case we have * to start over. */ Macro* M = FindMacro (&CurTok.SVal); if (M) { MacExpandStart (M); continue; } /* We have an identifier, generate a symbol */ Sym = SymFind (CurrentScope, &CurTok.SVal, SYM_ALLOC_NEW); /* Assign the symbol the offset of the current member */ SymDef (Sym, GenLiteralExpr (Offs), ADDR_SIZE_DEFAULT, SF_NONE); /* Skip the member name */ NextTok (); } /* Read storage allocators */ MemberSize = 0; /* In case of errors, use zero */ switch (CurTok.Tok) { case TOK_BYTE: NextTok (); MemberSize = Member (1); break; case TOK_DBYT: case TOK_WORD: case TOK_ADDR: NextTok (); MemberSize = Member (2); break; case TOK_FARADDR: NextTok (); MemberSize = Member (3); break; case TOK_DWORD: NextTok (); MemberSize = Member (4); break; case TOK_RES: NextTok (); if (CurTok.Tok == TOK_SEP) { ErrorSkip ("Size is missing"); } else { MemberSize = Member (1); } break; case TOK_TAG: NextTok (); Struct = ParseScopedSymTable (); if (Struct == 0) { ErrorSkip ("Unknown struct/union"); } else if (GetSymTabType (Struct) != SCOPE_STRUCT) { ErrorSkip ("Not a struct/union"); } else { SymEntry* SizeSym = GetSizeOfScope (Struct); if (!SymIsDef (SizeSym) || !SymIsConst (SizeSym, &MemberSize)) { ErrorSkip ("Size of struct/union is unknown"); } } MemberSize = Member (MemberSize); break; case TOK_STRUCT: NextTok (); MemberSize = DoStructInternal (Offs, STRUCT); break; case TOK_UNION: NextTok (); MemberSize = DoStructInternal (Offs, UNION); break; default: if (!CheckConditionals ()) { /* Not a conditional directive */ ErrorSkip ("Invalid storage allocator in struct/union"); } } /* Assign the size to the member if it has a name */ if (Sym) { DefSizeOfSymbol (Sym, MemberSize); } /* Next member */ if (Type == STRUCT) { /* Struct */ Offs += MemberSize; Size += MemberSize; } else { /* Union */ if (MemberSize > Size) { Size = MemberSize; } } /* Expect end of line */ ConsumeSep (); } /* If this is not a anon struct, enter a special symbol named ".size" * into the symbol table of the struct that holds the size of the * struct. Since the symbol starts with a dot, it cannot be accessed * by user code. * Leave the struct scope level. */ if (!Anon) { /* Add a symbol */ SymEntry* SizeSym = GetSizeOfScope (CurrentScope); SymDef (SizeSym, GenLiteralExpr (Size), ADDR_SIZE_DEFAULT, SF_NONE); /* Close the struct scope */ SymLeaveLevel (); } /* End of struct/union definition */ if (Type == STRUCT) { Consume (TOK_ENDSTRUCT, "`.ENDSTRUCT' expected"); } else { Consume (TOK_ENDUNION, "`.ENDUNION' expected"); } /* Return the size of the struct */ return Size; } long GetStructSize (SymTable* Struct) /* Get the size of a struct or union */ { SymEntry* SizeSym = FindSizeOfScope (Struct); if (SizeSym == 0) { Error ("Size of struct/union is unknown"); return 0; } else { return GetSymVal (SizeSym); } } void DoStruct (void) /* Handle the .STRUCT command */ { DoStructInternal (0, STRUCT); } void DoUnion (void) /* Handle the .UNION command */ { DoStructInternal (0, UNION); }
924
./cc65/src/ca65/lineinfo.c
/*****************************************************************************/ /* */ /* lineinfo.c */ /* */ /* Source file line info structure */ /* */ /* */ /* */ /* (C) 2001-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* 70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> /* common */ #include "coll.h" #include "hashfunc.h" #include "xmalloc.h" /* ca65 */ #include "filetab.h" #include "global.h" #include "lineinfo.h" #include "objfile.h" #include "scanner.h" #include "span.h" /*****************************************************************************/ /* Forwards */ /*****************************************************************************/ static unsigned HT_GenHash (const void* Key); /* Generate the hash over a key. */ static const void* HT_GetKey (const void* Entry); /* Given a pointer to the user entry data, return a pointer to the key */ static int HT_Compare (const void* Key1, const void* Key2); /* Compare two keys. The function must return a value less than zero if * Key1 is smaller than Key2, zero if both are equal, and a value greater * than zero if Key1 is greater then Key2. */ /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Structure that holds the key for a line info */ typedef struct LineInfoKey LineInfoKey; struct LineInfoKey { FilePos Pos; /* File position */ unsigned Type; /* Type/count of line info */ }; /* Structure that holds line info */ struct LineInfo { HashNode Node; /* Hash table node */ unsigned Id; /* Index */ LineInfoKey Key; /* Key for this line info */ unsigned RefCount; /* Reference counter */ Collection Spans; /* Segment spans for this line info */ Collection OpenSpans; /* List of currently open spans */ }; /* Collection containing all line infos */ static Collection LineInfoList = STATIC_COLLECTION_INITIALIZER; /* Collection with currently active line infos */ static Collection CurLineInfo = STATIC_COLLECTION_INITIALIZER; /* Hash table functions */ static const HashFunctions HashFunc = { HT_GenHash, HT_GetKey, HT_Compare }; /* Line info hash table */ static HashTable LineInfoTab = STATIC_HASHTABLE_INITIALIZER (1051, &HashFunc); /* The current assembler input line */ static LineInfo* AsmLineInfo = 0; /*****************************************************************************/ /* Hash table functions */ /*****************************************************************************/ static unsigned HT_GenHash (const void* Key) /* Generate the hash over a key. */ { /* Key is a LineInfoKey pointer */ const LineInfoKey* K = Key; /* Hash over a combination of type, file and line */ return HashInt ((K->Type << 21) ^ (K->Pos.Name << 14) ^ K->Pos.Line); } static const void* HT_GetKey (const void* Entry) /* Given a pointer to the user entry data, return a pointer to the key */ { return &((const LineInfo*)Entry)->Key; } static int HT_Compare (const void* Key1, const void* Key2) /* Compare two keys. The function must return a value less than zero if * Key1 is smaller than Key2, zero if both are equal, and a value greater * than zero if Key1 is greater then Key2. */ { /* Convert both parameters to FileInfoKey pointers */ const LineInfoKey* K1 = Key1; const LineInfoKey* K2 = Key2; /* Compare line number, then file and type */ int Res = (int)K2->Pos.Line - (int)K1->Pos.Line; if (Res == 0) { Res = (int)K2->Pos.Name - (int)K1->Pos.Name; if (Res == 0) { Res = (int)K2->Type - (int)K1->Type; } } /* Done */ return Res; } /*****************************************************************************/ /* struct LineInfo */ /*****************************************************************************/ static LineInfo* NewLineInfo (const LineInfoKey* Key) /* Create and return a new line info. Usage will be zero. */ { /* Allocate memory */ LineInfo* LI = xmalloc (sizeof (LineInfo)); /* Initialize the fields */ InitHashNode (&LI->Node); LI->Id = ~0U; LI->Key = *Key; LI->RefCount = 0; InitCollection (&LI->Spans); InitCollection (&LI->OpenSpans); /* Add it to the hash table, so we will find it if necessary */ HT_Insert (&LineInfoTab, LI); /* Return the new struct */ return LI; } static void FreeLineInfo (LineInfo* LI) /* Free a LineInfo structure */ { /* Free the Spans collection. It is supposed to be empty */ CHECK (CollCount (&LI->Spans) == 0); DoneCollection (&LI->Spans); DoneCollection (&LI->OpenSpans); /* Free the structure itself */ xfree (LI); } static int CheckLineInfo (void* Entry, void* Data attribute ((unused))) /* Called from HT_Walk. Remembers used line infos and assigns them an id */ { /* Entry is actually a line info */ LineInfo* LI = Entry; /* The entry is used if there are spans or the ref counter is non zero */ if (LI->RefCount > 0 || CollCount (&LI->Spans) > 0) { LI->Id = CollCount (&LineInfoList); CollAppend (&LineInfoList, LI); return 0; /* Keep the entry */ } else { FreeLineInfo (LI); return 1; /* Remove entry from table */ } } /*****************************************************************************/ /* Code */ /*****************************************************************************/ #if 0 static void DumpLineInfos (const char* Title, const Collection* C) /* Dump line infos from the given collection */ { unsigned I; fprintf (stderr, "%s:\n", Title); for (I = 0; I < CollCount (C); ++I) { const LineInfo* LI = CollConstAt (C, I); const char* Type; switch (GetLineInfoType (LI)) { case LI_TYPE_ASM: Type = "ASM"; break; case LI_TYPE_EXT: Type = "EXT"; break; case LI_TYPE_MACRO: Type = "MACRO"; break; case LI_TYPE_MACPARAM: Type = "MACPARAM"; break; default: Type = "unknown"; break; } fprintf (stderr, "%2u: %-8s %2u %-16s %u/%u\n", I, Type, LI->Key.Pos.Name, SB_GetConstBuf (GetFileName (LI->Key.Pos.Name)), LI->Key.Pos.Line, LI->Key.Pos.Col); } } #endif void InitLineInfo (void) /* Initialize the line infos */ { static const FilePos DefaultPos = STATIC_FILEPOS_INITIALIZER; /* Increase the initial count of the line info collection */ CollGrow (&LineInfoList, 200); /* Create a LineInfo for the default source. This is necessary to allow * error message to be generated without any input file open. */ AsmLineInfo = StartLine (&DefaultPos, LI_TYPE_ASM, 0); } void DoneLineInfo (void) /* Close down line infos */ { /* Close all current line infos */ unsigned Count = CollCount (&CurLineInfo); while (Count) { EndLine (CollAt (&CurLineInfo, --Count)); } /* Walk over the entries in the hash table and sort them into used and * unused ones. Add the used ones to the line info list and assign them * an id. */ HT_Walk (&LineInfoTab, CheckLineInfo, 0); } void EndLine (LineInfo* LI) /* End a line that is tracked by the given LineInfo structure */ { /* Close the spans for the line */ CloseSpanList (&LI->OpenSpans); /* Move the spans to the list of all spans for this line, then clear the * list of open spans. */ CollTransfer (&LI->Spans, &LI->OpenSpans); CollDeleteAll (&LI->OpenSpans); /* Line info is no longer active - remove it from the list of current * line infos. */ CollDeleteItem (&CurLineInfo, LI); } LineInfo* StartLine (const FilePos* Pos, unsigned Type, unsigned Count) /* Start line info for a new line */ { LineInfoKey Key; LineInfo* LI; /* Prepare the key struct */ Key.Pos = *Pos; Key.Type = LI_MAKE_TYPE (Type, Count); /* Try to find a line info with this position and type in the hash table. * If so, reuse it. Otherwise create a new one. */ LI = HT_Find (&LineInfoTab, &Key); if (LI == 0) { /* Allocate a new LineInfo */ LI = NewLineInfo (&Key); } /* Open the spans for this line info */ OpenSpanList (&LI->OpenSpans); /* Add the line info to the list of current line infos */ CollAppend (&CurLineInfo, LI); /* Return the new info */ return LI; } void NewAsmLine (void) /* Start a new assembler input line. Use this function when generating new * line of LI_TYPE_ASM. It will check if line and/or file have actually * changed, end the old and start the new line as necessary. */ { /* Check if we can reuse the old line */ if (AsmLineInfo) { if (AsmLineInfo->Key.Pos.Line == CurTok.Pos.Line && AsmLineInfo->Key.Pos.Name == CurTok.Pos.Name) { /* We do already have line info for this line */ return; } /* Line has changed -> end the old line */ EndLine (AsmLineInfo); } /* Start a new line using the current line info */ AsmLineInfo = StartLine (&CurTok.Pos, LI_TYPE_ASM, 0); } LineInfo* GetAsmLineInfo (void) /* Return the line info for the current assembler file. The function will * bump the reference counter before returning the line info. */ { ++AsmLineInfo->RefCount; return AsmLineInfo; } void ReleaseLineInfo (LineInfo* LI) /* Decrease the reference count for a line info */ { /* Decrease the reference counter */ CHECK (LI->RefCount > 0); ++LI->RefCount; } void GetFullLineInfo (Collection* LineInfos) /* Return full line infos, that is line infos for currently active Slots. The * infos will be added to the given collection, existing entries will be left * intact. The reference count of all added entries will be increased. */ { unsigned I; /* Bum the reference counter for all active line infos */ for (I = 0; I < CollCount (&CurLineInfo); ++I) { ++((LineInfo*)CollAt (&CurLineInfo, I))->RefCount; } /* Copy all line infos over */ CollTransfer (LineInfos, &CurLineInfo); } void ReleaseFullLineInfo (Collection* LineInfos) /* Decrease the reference count for a collection full of LineInfos, then clear * the collection. */ { unsigned I; /* Walk over all entries */ for (I = 0; I < CollCount (LineInfos); ++I) { /* Release the the line info */ ReleaseLineInfo (CollAt (LineInfos, I)); } /* Delete all entries */ CollDeleteAll (LineInfos); } const FilePos* GetSourcePos (const LineInfo* LI) /* Return the source file position from the given line info */ { return &LI->Key.Pos; } unsigned GetLineInfoType (const LineInfo* LI) /* Return the type of a line info */ { return LI_GET_TYPE (LI->Key.Type); } void WriteLineInfo (const Collection* LineInfos) /* Write a list of line infos to the object file. */ { unsigned I; /* Write the count */ ObjWriteVar (CollCount (LineInfos)); /* Write the line info indices */ for (I = 0; I < CollCount (LineInfos); ++I) { /* Get a pointer to the line info */ const LineInfo* LI = CollConstAt (LineInfos, I); /* Safety */ CHECK (LI->Id != ~0U); /* Write the index to the file */ ObjWriteVar (LI->Id); } } void WriteLineInfos (void) /* Write a list of all line infos to the object file. */ { unsigned I; /* Tell the object file module that we're about to write line infos */ ObjStartLineInfos (); /* Write the line info count to the list */ ObjWriteVar (CollCount (&LineInfoList)); /* Walk over the list and write all line infos */ for (I = 0; I < CollCount (&LineInfoList); ++I) { /* Get a pointer to this line info */ LineInfo* LI = CollAt (&LineInfoList, I); /* Write the source file position */ ObjWritePos (&LI->Key.Pos); /* Write the type and count of the line info */ ObjWriteVar (LI->Key.Type); /* Write the ids of the spans for this line */ WriteSpanList (&LI->Spans); } /* End of line infos */ ObjEndLineInfos (); }
925
./cc65/src/ca65/segment.c
/*****************************************************************************/ /* */ /* segment.c */ /* */ /* Segments for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> #include <errno.h> /* common */ #include "addrsize.h" #include "alignment.h" #include "coll.h" #include "mmodel.h" #include "segdefs.h" #include "segnames.h" #include "xmalloc.h" /* cc65 */ #include "error.h" #include "fragment.h" #include "global.h" #include "lineinfo.h" #include "listing.h" #include "objcode.h" #include "objfile.h" #include "segment.h" #include "span.h" #include "spool.h" #include "studyexpr.h" #include "symtab.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* If OrgPerSeg is false, all segments share the RelocMode flag and a PC * used when in absolute mode. OrgPerSeg may be set by .feature org_per_seg */ static int RelocMode = 1; static unsigned long AbsPC = 0; /* PC if in absolute mode */ /* Definitions for predefined segments */ SegDef NullSegDef = STATIC_SEGDEF_INITIALIZER (SEGNAME_NULL, ADDR_SIZE_ABS); SegDef ZeropageSegDef = STATIC_SEGDEF_INITIALIZER (SEGNAME_ZEROPAGE, ADDR_SIZE_ZP); SegDef DataSegDef = STATIC_SEGDEF_INITIALIZER (SEGNAME_DATA, ADDR_SIZE_ABS); SegDef BssSegDef = STATIC_SEGDEF_INITIALIZER (SEGNAME_BSS, ADDR_SIZE_ABS); SegDef RODataSegDef = STATIC_SEGDEF_INITIALIZER (SEGNAME_RODATA, ADDR_SIZE_ABS); SegDef CodeSegDef = STATIC_SEGDEF_INITIALIZER (SEGNAME_CODE, ADDR_SIZE_ABS); /* Collection containing all segments */ Collection SegmentList = STATIC_COLLECTION_INITIALIZER; /* Currently active segment */ Segment* ActiveSeg; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static Segment* NewSegFromDef (SegDef* Def) /* Create a new segment from a segment definition. Used only internally, no * checks. */ { /* Create a new segment */ Segment* S = xmalloc (sizeof (*S)); /* Initialize it */ S->Root = 0; S->Last = 0; S->FragCount = 0; S->Num = CollCount (&SegmentList); S->Flags = SEG_FLAG_NONE; S->Align = 1; S->RelocMode = 1; S->PC = 0; S->AbsPC = 0; S->Def = Def; /* Insert it into the segment list */ CollAppend (&SegmentList, S); /* And return it... */ return S; } static Segment* NewSegment (const char* Name, unsigned char AddrSize) /* Create a new segment, insert it into the global list and return it */ { /* Check for too many segments */ if (CollCount (&SegmentList) >= 256) { Fatal ("Too many segments"); } /* Check the segment name for invalid names */ if (!ValidSegName (Name)) { Error ("Illegal segment name: `%s'", Name); } /* Create a new segment and return it */ return NewSegFromDef (NewSegDef (Name, AddrSize)); } Fragment* GenFragment (unsigned char Type, unsigned short Len) /* Generate a new fragment, add it to the current segment and return it. */ { /* Create the new fragment */ Fragment* F = NewFragment (Type, Len); /* Insert the fragment into the current segment */ if (ActiveSeg->Root) { ActiveSeg->Last->Next = F; ActiveSeg->Last = F; } else { ActiveSeg->Root = ActiveSeg->Last = F; } ++ActiveSeg->FragCount; /* Add this fragment to the current listing line */ if (LineCur) { if (LineCur->FragList == 0) { LineCur->FragList = F; } else { LineCur->FragLast->LineList = F; } LineCur->FragLast = F; } /* Increment the program counter */ ActiveSeg->PC += F->Len; if (OrgPerSeg) { /* Relocatable mode is switched per segment */ if (!ActiveSeg->RelocMode) { ActiveSeg->AbsPC += F->Len; } } else { /* Relocatable mode is switched globally */ if (!RelocMode) { AbsPC += F->Len; } } /* Return the fragment */ return F; } void UseSeg (const SegDef* D) /* Use the segment with the given name */ { unsigned I; for (I = 0; I < CollCount (&SegmentList); ++I) { Segment* Seg = CollAtUnchecked (&SegmentList, I); if (strcmp (Seg->Def->Name, D->Name) == 0) { /* We found this segment. Check if the type is identical */ if (D->AddrSize != ADDR_SIZE_DEFAULT && Seg->Def->AddrSize != D->AddrSize) { Error ("Segment attribute mismatch"); /* Use the new attribute to avoid errors */ Seg->Def->AddrSize = D->AddrSize; } ActiveSeg = Seg; return; } } /* Segment is not in list, create a new one */ if (D->AddrSize == ADDR_SIZE_DEFAULT) { ActiveSeg = NewSegment (D->Name, ADDR_SIZE_ABS); } else { ActiveSeg = NewSegment (D->Name, D->AddrSize); } } unsigned long GetPC (void) /* Get the program counter of the current segment */ { if (OrgPerSeg) { /* Relocatable mode is switched per segment */ return ActiveSeg->RelocMode? ActiveSeg->PC : ActiveSeg->AbsPC; } else { /* Relocatable mode is switched globally */ return RelocMode? ActiveSeg->PC : AbsPC; } } void EnterAbsoluteMode (unsigned long PC) /* Enter absolute (non relocatable mode). Depending on the OrgPerSeg flag, * this will either switch the mode globally or for the current segment. */ { if (OrgPerSeg) { /* Relocatable mode is switched per segment */ ActiveSeg->RelocMode = 0; ActiveSeg->AbsPC = PC; } else { /* Relocatable mode is switched globally */ RelocMode = 0; AbsPC = PC; } } int GetRelocMode (void) /* Return true if we're currently in relocatable mode */ { if (OrgPerSeg) { /* Relocatable mode is switched per segment */ return ActiveSeg->RelocMode; } else { /* Relocatable mode is switched globally */ return RelocMode; } } void EnterRelocMode (void) /* Enter relocatable mode. Depending on the OrgPerSeg flag, this will either * switch the mode globally or for the current segment. */ { if (OrgPerSeg) { /* Relocatable mode is switched per segment */ ActiveSeg->RelocMode = 1; } else { /* Relocatable mode is switched globally */ RelocMode = 1; } } void SegAlign (unsigned long Alignment, int FillVal) /* Align the PC segment to Alignment. If FillVal is -1, emit fill fragments * (the actual fill value will be determined by the linker), otherwise use * the given value. */ { unsigned char Data [4]; unsigned long CombinedAlignment; unsigned long Count; /* The segment must have the combined alignment of all separate alignments * in the source. Calculate this alignment and check it for sanity. */ CombinedAlignment = LeastCommonMultiple (ActiveSeg->Align, Alignment); if (CombinedAlignment > MAX_ALIGNMENT) { Error ("Combined alignment for active segment is %lu which exceeds %lu", CombinedAlignment, MAX_ALIGNMENT); /* Avoid creating large fills for an object file that is thrown away * later. */ Count = 1; } else { ActiveSeg->Align = CombinedAlignment; /* Output a warning for larger alignments if not suppressed */ if (CombinedAlignment > LARGE_ALIGNMENT && !LargeAlignment) { Warning (0, "Combined alignment is suspiciously large (%lu)", CombinedAlignment); } /* Calculate the number of fill bytes */ Count = AlignCount (ActiveSeg->PC, Alignment); } /* Emit the data or a fill fragment */ if (FillVal != -1) { /* User defined fill value */ memset (Data, FillVal, sizeof (Data)); while (Count) { if (Count > sizeof (Data)) { EmitData (Data, sizeof (Data)); Count -= sizeof (Data); } else { EmitData (Data, Count); Count = 0; } } } else { /* Linker defined fill value */ EmitFill (Count); } } unsigned char GetSegAddrSize (unsigned SegNum) /* Return the address size of the segment with the given number */ { /* Is there such a segment? */ if (SegNum >= CollCount (&SegmentList)) { FAIL ("Invalid segment number"); } /* Return the address size */ return ((Segment*) CollAtUnchecked (&SegmentList, SegNum))->Def->AddrSize; } void SegDone (void) /* Check the segments for range and other errors. Do cleanup. */ { static const unsigned long U_Hi[4] = { 0x000000FFUL, 0x0000FFFFUL, 0x00FFFFFFUL, 0xFFFFFFFFUL }; static const long S_Hi[4] = { 0x0000007FL, 0x00007FFFL, 0x007FFFFFL, 0x7FFFFFFFL }; unsigned I; for (I = 0; I < CollCount (&SegmentList); ++I) { Segment* S = CollAtUnchecked (&SegmentList, I); Fragment* F = S->Root; while (F) { if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) { /* We have an expression, study it */ ExprDesc ED; ED_Init (&ED); StudyExpr (F->V.Expr, &ED); /* Check if the expression is constant */ if (ED_IsConst (&ED)) { unsigned J; /* The expression is constant. Check for range errors. */ CHECK (F->Len <= 4); if (F->Type == FRAG_SEXPR) { long Hi = S_Hi[F->Len-1]; long Lo = ~Hi; if (ED.Val > Hi || ED.Val < Lo) { LIError (&F->LI, "Range error (%ld not in [%ld..%ld])", ED.Val, Lo, Hi); } } else { if (((unsigned long)ED.Val) > U_Hi[F->Len-1]) { LIError (&F->LI, "Range error (%lu not in [0..%lu])", (unsigned long)ED.Val, U_Hi[F->Len-1]); } } /* We don't need the expression tree any longer */ FreeExpr (F->V.Expr); /* Convert the fragment into a literal fragment */ for (J = 0; J < F->Len; ++J) { F->V.Data[J] = ED.Val & 0xFF; ED.Val >>= 8; } F->Type = FRAG_LITERAL; } else if (RelaxChecks == 0) { /* We cannot evaluate the expression now, leave the job for * the linker. However, we can check if the address size * matches the fragment size. Mismatches are errors in * most situations. */ if ((F->Len == 1 && ED.AddrSize > ADDR_SIZE_ZP) || (F->Len == 2 && ED.AddrSize > ADDR_SIZE_ABS) || (F->Len == 3 && ED.AddrSize > ADDR_SIZE_FAR)) { LIError (&F->LI, "Range error"); } } /* Release memory allocated for the expression decriptor */ ED_Done (&ED); } F = F->Next; } } } void SegDump (void) /* Dump the contents of all segments */ { unsigned I; unsigned X = 0; printf ("\n"); for (I = 0; I < CollCount (&SegmentList); ++I) { Segment* S = CollAtUnchecked (&SegmentList, I); unsigned I; Fragment* F; int State = -1; printf ("New segment: %s", S->Def->Name); F = S->Root; while (F) { if (F->Type == FRAG_LITERAL) { if (State != 0) { printf ("\n Literal:"); X = 15; State = 0; } for (I = 0; I < F->Len; ++I) { printf (" %02X", F->V.Data [I]); X += 3; } } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) { State = 1; printf ("\n Expression (%u): ", F->Len); DumpExpr (F->V.Expr, SymResolve); } else if (F->Type == FRAG_FILL) { State = 1; printf ("\n Fill bytes (%u)", F->Len); } else { Internal ("Unknown fragment type: %u", F->Type); } if (X > 65) { State = -1; } F = F->Next; } printf ("\n End PC = $%04X\n", (unsigned)(S->PC & 0xFFFF)); } printf ("\n"); } void SegInit (void) /* Initialize segments */ { /* Create the predefined segments. Code segment is active */ ActiveSeg = NewSegFromDef (&CodeSegDef); NewSegFromDef (&RODataSegDef); NewSegFromDef (&BssSegDef); NewSegFromDef (&DataSegDef); NewSegFromDef (&ZeropageSegDef); NewSegFromDef (&NullSegDef); } void SetSegmentSizes (void) /* Set the default segment sizes according to the memory model */ { /* Initialize segment sizes. The segment definitions do already contain * the correct values for the default case (near), so we must only change * things that should be different. */ switch (MemoryModel) { case MMODEL_NEAR: break; case MMODEL_FAR: CodeSegDef.AddrSize = ADDR_SIZE_FAR; break; case MMODEL_HUGE: CodeSegDef.AddrSize = ADDR_SIZE_FAR; DataSegDef.AddrSize = ADDR_SIZE_FAR; BssSegDef.AddrSize = ADDR_SIZE_FAR; RODataSegDef.AddrSize = ADDR_SIZE_FAR; break; default: Internal ("Invalid memory model: %d", MemoryModel); } } static void WriteOneSeg (Segment* Seg) /* Write one segment to the object file */ { Fragment* Frag; unsigned long DataSize; unsigned long EndPos; /* Remember the file position, then write a dummy for the size of the * following data */ unsigned long SizePos = ObjGetFilePos (); ObjWrite32 (0); /* Write the segment data */ ObjWriteVar (GetStringId (Seg->Def->Name)); /* Name of the segment */ ObjWriteVar (Seg->Flags); /* Segment flags */ ObjWriteVar (Seg->PC); /* Size */ ObjWriteVar (Seg->Align); /* Segment alignment */ ObjWrite8 (Seg->Def->AddrSize); /* Address size of the segment */ ObjWriteVar (Seg->FragCount); /* Number of fragments */ /* Now walk through the fragment list for this segment and write the * fragments. */ Frag = Seg->Root; while (Frag) { /* Write data depending on the type */ switch (Frag->Type) { case FRAG_LITERAL: ObjWrite8 (FRAG_LITERAL); ObjWriteVar (Frag->Len); ObjWriteData (Frag->V.Data, Frag->Len); break; case FRAG_EXPR: switch (Frag->Len) { case 1: ObjWrite8 (FRAG_EXPR8); break; case 2: ObjWrite8 (FRAG_EXPR16); break; case 3: ObjWrite8 (FRAG_EXPR24); break; case 4: ObjWrite8 (FRAG_EXPR32); break; default: Internal ("Invalid fragment size: %u", Frag->Len); } WriteExpr (Frag->V.Expr); break; case FRAG_SEXPR: switch (Frag->Len) { case 1: ObjWrite8 (FRAG_SEXPR8); break; case 2: ObjWrite8 (FRAG_SEXPR16); break; case 3: ObjWrite8 (FRAG_SEXPR24); break; case 4: ObjWrite8 (FRAG_SEXPR32); break; default: Internal ("Invalid fragment size: %u", Frag->Len); } WriteExpr (Frag->V.Expr); break; case FRAG_FILL: ObjWrite8 (FRAG_FILL); ObjWriteVar (Frag->Len); break; default: Internal ("Invalid fragment type: %u", Frag->Type); } /* Write the line infos for this fragment */ WriteLineInfo (&Frag->LI); /* Next fragment */ Frag = Frag->Next; } /* Calculate the size of the data, seek back and write it */ EndPos = ObjGetFilePos (); /* Remember where we are */ DataSize = EndPos - SizePos - 4; /* Don't count size itself */ ObjSetFilePos (SizePos); /* Seek back to the size */ ObjWrite32 (DataSize); /* Write the size */ ObjSetFilePos (EndPos); /* Seek back to the end */ } void WriteSegments (void) /* Write the segment data to the object file */ { unsigned I; /* Tell the object file module that we're about to start the seg list */ ObjStartSegments (); /* First thing is segment count */ ObjWriteVar (CollCount (&SegmentList)); /* Now walk through all segments and write them to the object file */ for (I = 0; I < CollCount (&SegmentList); ++I) { /* Write one segment */ WriteOneSeg (CollAtUnchecked (&SegmentList, I)); } /* Done writing segments */ ObjEndSegments (); }
926
./cc65/src/ca65/ulabel.c
/*****************************************************************************/ /* */ /* ulabel.c */ /* */ /* Unnamed labels for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 2000-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" #include "coll.h" #include "xmalloc.h" /* ca65 */ #include "error.h" #include "expr.h" #include "lineinfo.h" #include "scanner.h" #include "ulabel.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Struct that describes an unnamed label */ typedef struct ULabel ULabel; struct ULabel { Collection LineInfos; /* Position of the label in the source */ ExprNode* Val; /* The label value - may be NULL */ unsigned Ref; /* Number of references */ }; /* List management */ static Collection ULabList = STATIC_COLLECTION_INITIALIZER; static unsigned ULabDefCount = 0; /* Number of defined labels */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ static ULabel* NewULabel (ExprNode* Val) /* Create a new ULabel and insert it into the collection. The created label * structure is returned. */ { /* Allocate memory for the ULabel structure */ ULabel* L = xmalloc (sizeof (ULabel)); /* Initialize the fields */ L->LineInfos = EmptyCollection; GetFullLineInfo (&L->LineInfos); L->Val = Val; L->Ref = 0; /* Insert the label into the collection */ CollAppend (&ULabList, L); /* Return the created label */ return L; } ExprNode* ULabRef (int Which) /* Get an unnamed label. If Which is negative, it is a backreference (a * reference to an already defined label), and the function will return a * segment relative expression. If Which is positive, it is a forward ref, * and the function will return a expression node for an unnamed label that * must be resolved later. */ { int Index; ULabel* L; /* Which can never be 0 */ PRECONDITION (Which != 0); /* Get the index of the referenced label */ if (Which > 0) { --Which; } Index = (int) ULabDefCount + Which; /* We cannot have negative label indices */ if (Index < 0) { /* Label does not exist */ Error ("Undefined label"); /* We must return something valid */ return GenCurrentPC(); } /* Check if the label exists. If not, generate enough forward labels. */ if (Index < (int) CollCount (&ULabList)) { /* The label exists, get it. */ L = CollAtUnchecked (&ULabList, Index); } else { /* Generate new, undefined labels */ while (Index >= (int) CollCount (&ULabList)) { L = NewULabel (0); } } /* Mark the label as referenced */ ++L->Ref; /* If the label is already defined, return its value, otherwise return * just a reference. */ if (L->Val) { return CloneExpr (L->Val); } else { return GenULabelExpr (Index); } } void ULabDef (void) /* Define an unnamed label at the current PC */ { if (ULabDefCount < CollCount (&ULabList)) { /* We did already have a forward reference to this label, so has * already been generated, but doesn't have a value. Use the current * PC for the label value. */ ULabel* L = CollAtUnchecked (&ULabList, ULabDefCount); CHECK (L->Val == 0); L->Val = GenCurrentPC (); ReleaseFullLineInfo (&L->LineInfos); GetFullLineInfo (&L->LineInfos); } else { /* There is no such label, create it */ NewULabel (GenCurrentPC ()); } /* We have one more defined label */ ++ULabDefCount; } int ULabCanResolve (void) /* Return true if we can resolve arbitrary ULabels. */ { /* We can resolve labels if we don't have any undefineds */ return (ULabDefCount == CollCount (&ULabList)); } ExprNode* ULabResolve (unsigned Index) /* Return a valid expression for the unnamed label with the given index. This * is used to resolve unnamed labels when assembly is done, so it is an error * if a label is still undefined in this phase. */ { /* Get the label and check that it is defined */ ULabel* L = CollAt (&ULabList, Index); CHECK (L->Val != 0); /* Return the label value */ return CloneExpr (L->Val); } void ULabDone (void) /* Run through all unnamed labels, check for anomalies and errors and do * necessary cleanups. */ { /* Check if there are undefined labels */ unsigned I = ULabDefCount; while (I < CollCount (&ULabList)) { ULabel* L = CollAtUnchecked (&ULabList, I); LIError (&L->LineInfos, "Undefined label"); ++I; } /* Walk over all labels and emit a warning if any unreferenced ones * are found. Remove line infos because they're no longer needed. */ for (I = 0; I < CollCount (&ULabList); ++I) { ULabel* L = CollAtUnchecked (&ULabList, I); if (L->Ref == 0) { LIWarning (&L->LineInfos, 1, "No reference to unnamed label"); } ReleaseFullLineInfo (&L->LineInfos); } }
927
./cc65/src/ca65/token.c
/*****************************************************************************/ /* */ /* token.c */ /* */ /* Token list for the ca65 macro assembler */ /* */ /* */ /* */ /* (C) 2007-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* ca65 */ #include "token.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ int TokHasSVal (token_t Tok) /* Return true if the given token has an attached SVal */ { return (Tok == TOK_IDENT || Tok == TOK_LOCAL_IDENT || Tok == TOK_STRCON); } int TokHasIVal (token_t Tok) /* Return true if the given token has an attached IVal */ { return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_REG); } void CopyToken (Token* Dst, const Token* Src) /* Copy a token from Src to Dst. The current value of Dst.SVal is free'd, * so Dst must be initialized. */ { /* Copy the fields */ Dst->Tok = Src->Tok; Dst->WS = Src->WS; Dst->IVal = Src->IVal; SB_Copy (&Dst->SVal, &Src->SVal); Dst->Pos = Src->Pos; }
928
./cc65/src/ca65/filetab.c
/*****************************************************************************/ /* */ /* filetab.h */ /* */ /* Input file table for ca65 */ /* */ /* */ /* */ /* (C) 2000-2008 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <errno.h> /* common */ #include "check.h" #include "coll.h" #include "hashtab.h" #include "xmalloc.h" /* ca65 */ #include "error.h" #include "filetab.h" #include "global.h" #include "objfile.h" #include "spool.h" /*****************************************************************************/ /* Forwards */ /*****************************************************************************/ static unsigned HT_GenHash (const void* Key); /* Generate the hash over a key. */ static const void* HT_GetKey (const void* Entry); /* Given a pointer to the user entry data, return a pointer to the key. */ static int HT_Compare (const void* Key1, const void* Key2); /* Compare two keys. The function must return a value less than zero if * Key1 is smaller than Key2, zero if both are equal, and a value greater * than zero if Key1 is greater then Key2. */ /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Number of entries in the table and the mask to generate the hash */ #define HASHTAB_MASK 0x1F #define HASHTAB_COUNT (HASHTAB_MASK + 1) /* An entry in the file table */ typedef struct FileEntry FileEntry; struct FileEntry { HashNode Node; unsigned Name; /* File name */ unsigned Index; /* Index of entry */ FileType Type; /* Type of file */ unsigned long Size; /* Size of file */ unsigned long MTime; /* Time of last modification */ }; /* Array of all entries, listed by index */ static Collection FileTab = STATIC_COLLECTION_INITIALIZER; /* Hash table functions */ static const HashFunctions HashFunc = { HT_GenHash, HT_GetKey, HT_Compare }; /* Hash table, hashed by name */ static HashTable HashTab = STATIC_HASHTABLE_INITIALIZER (HASHTAB_COUNT, &HashFunc); /*****************************************************************************/ /* Hash table functions */ /*****************************************************************************/ static unsigned HT_GenHash (const void* Key) /* Generate the hash over a key. */ { return (*(const unsigned*)Key & HASHTAB_MASK); } static const void* HT_GetKey (const void* Entry) /* Given a pointer to the user entry data, return a pointer to the index */ { return &((FileEntry*) Entry)->Name; } static int HT_Compare (const void* Key1, const void* Key2) /* Compare two keys. The function must return a value less than zero if * Key1 is smaller than Key2, zero if both are equal, and a value greater * than zero if Key1 is greater then Key2. */ { return (int)*(const unsigned*)Key1 - (int)*(const unsigned*)Key2; } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static FileEntry* NewFileEntry (unsigned Name, FileType Type, unsigned long Size, unsigned long MTime) /* Create a new FileEntry, insert it into the tables and return it */ { /* Allocate memory for the entry */ FileEntry* F = xmalloc (sizeof (FileEntry)); /* Initialize the fields */ InitHashNode (&F->Node); F->Name = Name; F->Index = CollCount (&FileTab) + 1; /* First file has index #1 */ F->Type = Type; F->Size = Size; F->MTime = MTime; /* Insert the file into the file table */ CollAppend (&FileTab, F); /* Insert the entry into the hash table */ HT_Insert (&HashTab, F); /* Return the new entry */ return F; } const StrBuf* GetFileName (unsigned Name) /* Get the name of a file where the name index is known */ { static const StrBuf ErrorMsg = LIT_STRBUF_INITIALIZER ("(outside file scope)"); const FileEntry* F; if (Name == 0) { /* Name was defined outside any file scope, use the name of the first * file instead. Errors are then reported with a file position of * line zero in the first file. */ if (CollCount (&FileTab) == 0) { /* No files defined until now */ return &ErrorMsg; } else { F = CollConstAt (&FileTab, 0); } } else { F = CollConstAt (&FileTab, Name-1); } return GetStrBuf (F->Name); } unsigned GetFileIndex (const StrBuf* Name) /* Return the file index for the given file name. */ { /* Get the string pool index from the name */ unsigned NameIdx = GetStrBufId (Name); /* Search in the hash table for the name */ const FileEntry* F = HT_Find (&HashTab, &NameIdx); /* If we don't have this index, print a diagnostic and use the main file */ if (F == 0) { Error ("File name `%m%p' not found in file table", Name); return 0; } else { return F->Index; } } unsigned AddFile (const StrBuf* Name, FileType Type, unsigned long Size, unsigned long MTime) /* Add a new file to the list of input files. Return the index of the file in * the table. */ { /* Create a new file entry and insert it into the tables */ FileEntry* F = NewFileEntry (GetStrBufId (Name), Type, Size, MTime); /* Return the index */ return F->Index; } void WriteFiles (void) /* Write the list of input files to the object file */ { unsigned I; /* Tell the obj file module that we're about to start the file list */ ObjStartFiles (); /* Write the file count */ ObjWriteVar (CollCount (&FileTab)); /* Write the file data */ for (I = 0; I < CollCount (&FileTab); ++I) { /* Get a pointer to the entry */ const FileEntry* F = CollConstAt (&FileTab, I); /* Write the fields */ ObjWriteVar (F->Name); ObjWrite32 (F->MTime); ObjWriteVar (F->Size); } /* Done writing files */ ObjEndFiles (); } static void WriteDep (FILE* F, FileType Types) /* Helper function. Writes all file names that match Types to the output */ { unsigned I; /* Loop over all files */ for (I = 0; I < CollCount (&FileTab); ++I) { const StrBuf* Filename; /* Get the next input file */ const FileEntry* E = (const FileEntry*) CollAt (&FileTab, I); /* Ignore it if it is not of the correct type */ if ((E->Type & Types) == 0) { continue; } /* If this is not the first file, add a space */ if (I > 0) { fputc (' ', F); } /* Print the dependency */ Filename = GetStrBuf (E->Name); fprintf (F, "%*s", SB_GetLen (Filename), SB_GetConstBuf (Filename)); } } static void CreateDepFile (const char* Name, FileType Types) /* Create a dependency file with the given name and place dependencies for * all files with the given types there. */ { /* Open the file */ FILE* F = fopen (Name, "w"); if (F == 0) { Fatal ("Cannot open dependency file `%s': %s", Name, strerror (errno)); } /* Print the output file followed by a tab char */ fprintf (F, "%s:\t", OutFile); /* Write out the dependencies for the output file */ WriteDep (F, Types); fputs ("\n\n", F); /* Write out a phony dependency for the included files */ WriteDep (F, Types); fputs (":\n\n", F); /* Close the file, check for errors */ if (fclose (F) != 0) { remove (Name); Fatal ("Cannot write to dependeny file (disk full?)"); } } void CreateDependencies (void) /* Create dependency files requested by the user */ { if (SB_NotEmpty (&DepName)) { CreateDepFile (SB_GetConstBuf (&DepName), FT_MAIN | FT_INCLUDE | FT_BINARY); } if (SB_NotEmpty (&FullDepName)) { CreateDepFile (SB_GetConstBuf (&FullDepName), FT_MAIN | FT_INCLUDE | FT_BINARY | FT_DBGINFO); } }
929
./cc65/src/ca65/error.c
/*****************************************************************************/ /* */ /* error.c */ /* */ /* Error handling for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> /* common */ #include "strbuf.h" /* ca65 */ #include "error.h" #include "filetab.h" #include "lineinfo.h" #include "nexttok.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Warning level */ unsigned WarnLevel = 1; /* Statistics */ unsigned ErrorCount = 0; unsigned WarningCount = 0; /* Maximum number of additional notifications */ #define MAX_NOTES 8 /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static void VPrintMsg (const FilePos* Pos, const char* Desc, const char* Format, va_list ap) /* Format and output an error/warning message. */ { StrBuf S = STATIC_STRBUF_INITIALIZER; /* Format the actual message */ StrBuf Msg = STATIC_STRBUF_INITIALIZER; SB_VPrintf (&Msg, Format, ap); SB_Terminate (&Msg); /* Format the message header */ SB_Printf (&S, "%s(%u): %s: ", SB_GetConstBuf (GetFileName (Pos->Name)), Pos->Line, Desc); /* Append the message to the message header */ SB_Append (&S, &Msg); /* Delete the formatted message */ SB_Done (&Msg); /* Add a new line and terminate the generated full message */ SB_AppendChar (&S, '\n'); SB_Terminate (&S); /* Output the full message */ fputs (SB_GetConstBuf (&S), stderr); /* Delete the buffer for the full message */ SB_Done (&S); } static void PrintMsg (const FilePos* Pos, const char* Desc, const char* Format, ...) /* Format and output an error/warning message. */ { va_list ap; va_start (ap, Format); VPrintMsg (Pos, Desc, Format, ap); va_end (ap); } static void AddNotifications (const Collection* LineInfos) /* Output additional notifications for an error or warning */ { unsigned I; unsigned Output; unsigned Skipped; /* The basic line info is always in slot zero. It has been used to * output the actual error or warning. The following slots may contain * more information. Check them and print additional notifications if * they're present, but limit the number to a reasonable value. */ for (I = 1, Output = 0, Skipped = 0; I < CollCount (LineInfos); ++I) { /* Get next line info */ const LineInfo* LI = CollConstAt (LineInfos, I); /* Check the type and output an appropriate note */ const char* Msg; switch (GetLineInfoType (LI)) { case LI_TYPE_ASM: Msg = "Expanded from here"; break; case LI_TYPE_EXT: Msg = "Assembler code generated from this line"; break; case LI_TYPE_MACRO: Msg = "Macro was defined here"; break; case LI_TYPE_MACPARAM: Msg = "Macro parameter came from here"; break; default: /* No output */ Msg = 0; break; } /* Output until an upper limit of messages is reached */ if (Msg) { if (Output < MAX_NOTES) { PrintMsg (GetSourcePos (LI), "Note", "%s", Msg); ++Output; } else { ++Skipped; } } } /* Add a note if we have more stuff that we won't output */ if (Skipped > 0) { const LineInfo* LI = CollConstAt (LineInfos, 0); PrintMsg (GetSourcePos (LI), "Note", "Dropping %u additional line infos", Skipped); } } /*****************************************************************************/ /* Warnings */ /*****************************************************************************/ static void WarningMsg (const Collection* LineInfos, const char* Format, va_list ap) /* Print warning message. */ { /* The first entry in the collection is that of the actual source pos */ const LineInfo* LI = CollConstAt (LineInfos, 0); /* Output a warning for this position */ VPrintMsg (GetSourcePos (LI), "Warning", Format, ap); /* Add additional notifications if necessary */ AddNotifications (LineInfos); /* Count warnings */ ++WarningCount; } void Warning (unsigned Level, const char* Format, ...) /* Print warning message. */ { if (Level <= WarnLevel) { va_list ap; Collection LineInfos = STATIC_COLLECTION_INITIALIZER; /* Get line infos for the current position */ GetFullLineInfo (&LineInfos); /* Output the message */ va_start (ap, Format); WarningMsg (&LineInfos, Format, ap); va_end (ap); /* Free the line info list */ ReleaseFullLineInfo (&LineInfos); DoneCollection (&LineInfos); } } void PWarning (const FilePos* Pos, unsigned Level, const char* Format, ...) /* Print warning message giving an explicit file and position. */ { if (Level <= WarnLevel) { va_list ap; va_start (ap, Format); VPrintMsg (Pos, "Warning", Format, ap); va_end (ap); /* Count warnings */ ++WarningCount; } } void LIWarning (const Collection* LineInfos, unsigned Level, const char* Format, ...) /* Print warning message using the given line infos */ { if (Level <= WarnLevel) { /* Output the message */ va_list ap; va_start (ap, Format); WarningMsg (LineInfos, Format, ap); va_end (ap); } } /*****************************************************************************/ /* Errors */ /*****************************************************************************/ void ErrorMsg (const Collection* LineInfos, const char* Format, va_list ap) /* Print an error message */ { /* The first entry in the collection is that of the actual source pos */ const LineInfo* LI = CollConstAt (LineInfos, 0); /* Output an error for this position */ VPrintMsg (GetSourcePos (LI), "Error", Format, ap); /* Add additional notifications if necessary */ AddNotifications (LineInfos); /* Count errors */ ++ErrorCount; } void Error (const char* Format, ...) /* Print an error message */ { va_list ap; Collection LineInfos = STATIC_COLLECTION_INITIALIZER; /* Get line infos for the current position */ GetFullLineInfo (&LineInfos); /* Output the message */ va_start (ap, Format); ErrorMsg (&LineInfos, Format, ap); va_end (ap); /* Free the line info list */ ReleaseFullLineInfo (&LineInfos); DoneCollection (&LineInfos); } void PError (const FilePos* Pos, const char* Format, ...) /* Print an error message giving an explicit file and position. */ { va_list ap; va_start (ap, Format); VPrintMsg (Pos, "Error", Format, ap); va_end (ap); /* Count errors */ ++ErrorCount; } void LIError (const Collection* LineInfos, const char* Format, ...) /* Print an error message using the given line infos. */ { /* Output an error for this position */ va_list ap; va_start (ap, Format); ErrorMsg (LineInfos, Format, ap); va_end (ap); } void ErrorSkip (const char* Format, ...) /* Print an error message and skip the rest of the line */ { va_list ap; Collection LineInfos = STATIC_COLLECTION_INITIALIZER; /* Get line infos for the current position */ GetFullLineInfo (&LineInfos); /* Output the message */ va_start (ap, Format); ErrorMsg (&LineInfos, Format, ap); va_end (ap); /* Free the line info list */ ReleaseFullLineInfo (&LineInfos); DoneCollection (&LineInfos); /* Skip tokens until we reach the end of the line */ SkipUntilSep (); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ void Fatal (const char* Format, ...) /* Print a message about a fatal error and die */ { va_list ap; StrBuf S = STATIC_STRBUF_INITIALIZER; va_start (ap, Format); SB_VPrintf (&S, Format, ap); SB_Terminate (&S); va_end (ap); fprintf (stderr, "Fatal error: %s\n", SB_GetConstBuf (&S)); SB_Done (&S); /* And die... */ exit (EXIT_FAILURE); } void Internal (const char* Format, ...) /* Print a message about an internal assembler error and die. */ { va_list ap; StrBuf S = STATIC_STRBUF_INITIALIZER; va_start (ap, Format); SB_VPrintf (&S, Format, ap); SB_Terminate (&S); va_end (ap); fprintf (stderr, "Internal assembler error: %s\n", SB_GetConstBuf (&S)); SB_Done (&S); exit (EXIT_FAILURE); }
930
./cc65/src/ca65/fragment.c
/*****************************************************************************/ /* */ /* fragment.c */ /* */ /* Data fragments for the ca65 crossassembler */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "xmalloc.h" /* ca65 */ #include "fragment.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ Fragment* NewFragment (unsigned char Type, unsigned short Len) /* Create, initialize and return a new fragment. The fragment will be inserted * into the current segment. */ { /* Create a new fragment */ Fragment* F = xmalloc (sizeof (*F)); /* Initialize it */ F->Next = 0; F->LineList = 0; F->LI = EmptyCollection; GetFullLineInfo (&F->LI); F->Len = Len; F->Type = Type; /* And return it */ return F; }
931
./cc65/src/ca65/expr.c
/*****************************************************************************/ /* */ /* expr.c */ /* */ /* Expression evaluation for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> #include <time.h> /* common */ #include "check.h" #include "cpu.h" #include "exprdefs.h" #include "print.h" #include "shift.h" #include "segdefs.h" #include "strbuf.h" #include "tgttrans.h" #include "version.h" #include "xmalloc.h" /* ca65 */ #include "error.h" #include "expr.h" #include "global.h" #include "instr.h" #include "nexttok.h" #include "objfile.h" #include "segment.h" #include "sizeof.h" #include "studyexpr.h" #include "symbol.h" #include "symtab.h" #include "toklist.h" #include "ulabel.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Since all expressions are first packed into expression trees, and each * expression tree node is allocated on the heap, we add some type of special * purpose memory allocation here: Instead of freeing the nodes, we save some * number of freed nodes for later and remember them in a single linked list * using the Left link. */ #define MAX_FREE_NODES 64 static ExprNode* FreeExprNodes = 0; static unsigned FreeNodeCount = 0; /*****************************************************************************/ /* Helpers */ /*****************************************************************************/ static ExprNode* NewExprNode (unsigned Op) /* Create a new expression node */ { ExprNode* N; /* Do we have some nodes in the list already? */ if (FreeNodeCount) { /* Use first node from list */ N = FreeExprNodes; FreeExprNodes = N->Left; --FreeNodeCount; } else { /* Allocate fresh memory */ N = xmalloc (sizeof (ExprNode)); } N->Op = Op; N->Left = N->Right = 0; N->Obj = 0; return N; } static void FreeExprNode (ExprNode* E) /* Free a node */ { if (E) { if (E->Op == EXPR_SYMBOL) { /* Remove the symbol reference */ SymDelExprRef (E->V.Sym, E); } /* Place the symbol into the free nodes list if possible */ if (FreeNodeCount < MAX_FREE_NODES) { /* Remember this node for later */ E->Left = FreeExprNodes; FreeExprNodes = E; ++FreeNodeCount; } else { /* Free the memory */ xfree (E); } } } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static ExprNode* Expr0 (void); int IsByteRange (long Val) /* Return true if this is a byte value */ { return (Val & ~0xFFL) == 0; } int IsWordRange (long Val) /* Return true if this is a word value */ { return (Val & ~0xFFFFL) == 0; } int IsFarRange (long Val) /* Return true if this is a far (24 bit) value */ { return (Val & ~0xFFFFFFL) == 0; } int IsEasyConst (const ExprNode* E, long* Val) /* Do some light checking if the given node is a constant. Don't care if E is * a complex expression. If E is a constant, return true and place its value * into Val, provided that Val is not NULL. */ { /* Resolve symbols, follow symbol chains */ while (E->Op == EXPR_SYMBOL) { E = SymResolve (E->V.Sym); if (E == 0) { /* Could not resolve */ return 0; } } /* Symbols resolved, check for a literal */ if (E->Op == EXPR_LITERAL) { if (Val) { *Val = E->V.IVal; } return 1; } /* Not found to be a const according to our tests */ return 0; } static ExprNode* LoByte (ExprNode* Operand) /* Return the low byte of the given expression */ { ExprNode* Expr; long Val; /* Special handling for const expressions */ if (IsEasyConst (Operand, &Val)) { FreeExpr (Operand); Expr = GenLiteralExpr (Val & 0xFF); } else { /* Extract byte #0 */ Expr = NewExprNode (EXPR_BYTE0); Expr->Left = Operand; } return Expr; } static ExprNode* HiByte (ExprNode* Operand) /* Return the high byte of the given expression */ { ExprNode* Expr; long Val; /* Special handling for const expressions */ if (IsEasyConst (Operand, &Val)) { FreeExpr (Operand); Expr = GenLiteralExpr ((Val >> 8) & 0xFF); } else { /* Extract byte #1 */ Expr = NewExprNode (EXPR_BYTE1); Expr->Left = Operand; } return Expr; } static ExprNode* Bank (ExprNode* Operand) /* Return the bank of the given segmented expression */ { /* Generate the bank expression */ ExprNode* Expr = NewExprNode (EXPR_BANK); Expr->Left = Operand; /* Return the result */ return Expr; } static ExprNode* BankByte (ExprNode* Operand) /* Return the bank byte of the given expression */ { ExprNode* Expr; long Val; /* Special handling for const expressions */ if (IsEasyConst (Operand, &Val)) { FreeExpr (Operand); Expr = GenLiteralExpr ((Val >> 16) & 0xFF); } else { /* Extract byte #2 */ Expr = NewExprNode (EXPR_BYTE2); Expr->Left = Operand; } return Expr; } static ExprNode* LoWord (ExprNode* Operand) /* Return the low word of the given expression */ { ExprNode* Expr; long Val; /* Special handling for const expressions */ if (IsEasyConst (Operand, &Val)) { FreeExpr (Operand); Expr = GenLiteralExpr (Val & 0xFFFF); } else { /* Extract word #0 */ Expr = NewExprNode (EXPR_WORD0); Expr->Left = Operand; } return Expr; } static ExprNode* HiWord (ExprNode* Operand) /* Return the high word of the given expression */ { ExprNode* Expr; long Val; /* Special handling for const expressions */ if (IsEasyConst (Operand, &Val)) { FreeExpr (Operand); Expr = GenLiteralExpr ((Val >> 16) & 0xFFFF); } else { /* Extract word #1 */ Expr = NewExprNode (EXPR_WORD1); Expr->Left = Operand; } return Expr; } static ExprNode* Symbol (SymEntry* S) /* Reference a symbol and return an expression for it */ { if (S == 0) { /* Some weird error happened before */ return GenLiteralExpr (0); } else { /* Mark the symbol as referenced */ SymRef (S); /* If the symbol is a variable, return just its value, otherwise * return a reference to the symbol. */ if (SymIsVar (S)) { return CloneExpr (GetSymExpr (S)); } else { /* Create symbol node */ return GenSymExpr (S); } } } ExprNode* FuncBank (void) /* Handle the .BANK builtin function */ { return Bank (Expression ()); } ExprNode* FuncBankByte (void) /* Handle the .BANKBYTE builtin function */ { return BankByte (Expression ()); } static ExprNode* FuncBlank (void) /* Handle the .BLANK builtin function */ { /* We have a list of tokens that ends with the closing paren. Skip * the tokens, and count them. Allow optionally curly braces. */ token_t Term = GetTokListTerm (TOK_RPAREN); unsigned Count = 0; while (CurTok.Tok != Term) { /* Check for end of line or end of input. Since the calling function * will check for the closing paren, we don't need to print an error * here, just bail out. */ if (TokIsSep (CurTok.Tok)) { break; } /* One more token */ ++Count; /* Skip the token */ NextTok (); } /* If the list was enclosed in curly braces, skip the closing brace */ if (Term == TOK_RCURLY && CurTok.Tok == TOK_RCURLY) { NextTok (); } /* Return true if the list was empty */ return GenLiteralExpr (Count == 0); } static ExprNode* FuncConst (void) /* Handle the .CONST builtin function */ { /* Read an expression */ ExprNode* Expr = Expression (); /* Check the constness of the expression */ ExprNode* Result = GenLiteralExpr (IsConstExpr (Expr, 0)); /* Free the expression */ FreeExpr (Expr); /* Done */ return Result; } static ExprNode* FuncDefined (void) /* Handle the .DEFINED builtin function */ { /* Parse the symbol name and search for the symbol */ SymEntry* Sym = ParseAnySymName (SYM_FIND_EXISTING); /* Check if the symbol is defined */ return GenLiteralExpr (Sym != 0 && SymIsDef (Sym)); } ExprNode* FuncHiByte (void) /* Handle the .HIBYTE builtin function */ { return HiByte (Expression ()); } static ExprNode* FuncHiWord (void) /* Handle the .HIWORD builtin function */ { return HiWord (Expression ()); } ExprNode* FuncLoByte (void) /* Handle the .LOBYTE builtin function */ { return LoByte (Expression ()); } static ExprNode* FuncLoWord (void) /* Handle the .LOWORD builtin function */ { return LoWord (Expression ()); } static ExprNode* DoMatch (enum TC EqualityLevel) /* Handle the .MATCH and .XMATCH builtin functions */ { int Result; TokNode* Root = 0; TokNode* Last = 0; TokNode* Node; /* A list of tokens follows. Read this list and remember it building a * single linked list of tokens including attributes. The list is * either enclosed in curly braces, or terminated by a comma. */ token_t Term = GetTokListTerm (TOK_COMMA); while (CurTok.Tok != Term) { /* We may not end-of-line of end-of-file here */ if (TokIsSep (CurTok.Tok)) { Error ("Unexpected end of line"); return GenLiteral0 (); } /* Get a node with this token */ Node = NewTokNode (); /* Insert the node into the list */ if (Last == 0) { Root = Node; } else { Last->Next = Node; } Last = Node; /* Skip the token */ NextTok (); } /* Skip the terminator token*/ NextTok (); /* If the token list was enclosed in curly braces, we expect a comma */ if (Term == TOK_RCURLY) { ConsumeComma (); } /* Read the second list which is optionally enclosed in curly braces and * terminated by the right parenthesis. Compare each token against the * one in the first list. */ Term = GetTokListTerm (TOK_RPAREN); Result = 1; Node = Root; while (CurTok.Tok != Term) { /* We may not end-of-line of end-of-file here */ if (TokIsSep (CurTok.Tok)) { Error ("Unexpected end of line"); return GenLiteral0 (); } /* Compare the tokens if the result is not already known */ if (Result != 0) { if (Node == 0) { /* The second list is larger than the first one */ Result = 0; } else if (TokCmp (Node) < EqualityLevel) { /* Tokens do not match */ Result = 0; } } /* Next token in first list */ if (Node) { Node = Node->Next; } /* Next token in current list */ NextTok (); } /* If the token list was enclosed in curly braces, eat the closing brace */ if (Term == TOK_RCURLY) { NextTok (); } /* Check if there are remaining tokens in the first list */ if (Node != 0) { Result = 0; } /* Free the token list */ while (Root) { Node = Root; Root = Root->Next; FreeTokNode (Node); } /* Done, return the result */ return GenLiteralExpr (Result); } static ExprNode* FuncMatch (void) /* Handle the .MATCH function */ { return DoMatch (tcSameToken); } static ExprNode* FuncMax (void) /* Handle the .MAX function */ { ExprNode* Left; ExprNode* Right; ExprNode* Expr; long LeftVal, RightVal; /* Two arguments to the pseudo function */ Left = Expression (); ConsumeComma (); Right = Expression (); /* Check if we can evaluate the value immediately */ if (IsEasyConst (Left, &LeftVal) && IsEasyConst (Right, &RightVal)) { FreeExpr (Left); FreeExpr (Right); Expr = GenLiteralExpr ((LeftVal > RightVal)? LeftVal : RightVal); } else { /* Make an expression node */ Expr = NewExprNode (EXPR_MAX); Expr->Left = Left; Expr->Right = Right; } return Expr; } static ExprNode* FuncMin (void) /* Handle the .MIN function */ { ExprNode* Left; ExprNode* Right; ExprNode* Expr; long LeftVal, RightVal; /* Two arguments to the pseudo function */ Left = Expression (); ConsumeComma (); Right = Expression (); /* Check if we can evaluate the value immediately */ if (IsEasyConst (Left, &LeftVal) && IsEasyConst (Right, &RightVal)) { FreeExpr (Left); FreeExpr (Right); Expr = GenLiteralExpr ((LeftVal < RightVal)? LeftVal : RightVal); } else { /* Make an expression node */ Expr = NewExprNode (EXPR_MIN); Expr->Left = Left; Expr->Right = Right; } return Expr; } static ExprNode* FuncReferenced (void) /* Handle the .REFERENCED builtin function */ { /* Parse the symbol name and search for the symbol */ SymEntry* Sym = ParseAnySymName (SYM_FIND_EXISTING); /* Check if the symbol is referenced */ return GenLiteralExpr (Sym != 0 && SymIsRef (Sym)); } static ExprNode* FuncSizeOf (void) /* Handle the .SIZEOF function */ { StrBuf ScopeName = STATIC_STRBUF_INITIALIZER; StrBuf Name = STATIC_STRBUF_INITIALIZER; SymTable* Scope; SymEntry* Sym; SymEntry* SizeSym; long Size; int NoScope; /* Assume an error */ SizeSym = 0; /* Check for a cheap local which needs special handling */ if (CurTok.Tok == TOK_LOCAL_IDENT) { /* Cheap local symbol */ Sym = SymFindLocal (SymLast, &CurTok.SVal, SYM_FIND_EXISTING); if (Sym == 0) { Error ("Unknown symbol or scope: `%m%p'", &CurTok.SVal); } else { SizeSym = GetSizeOfSymbol (Sym); } /* Remember and skip SVal, terminate ScopeName so it is empty */ SB_Copy (&Name, &CurTok.SVal); NextTok (); SB_Terminate (&ScopeName); } else { /* Parse the scope and the name */ SymTable* ParentScope = ParseScopedIdent (&Name, &ScopeName); /* Check if the parent scope is valid */ if (ParentScope == 0) { /* No such scope */ SB_Done (&ScopeName); SB_Done (&Name); return GenLiteral0 (); } /* If ScopeName is empty, no explicit scope was specified. We have to * search upper scope levels in this case. */ NoScope = SB_IsEmpty (&ScopeName); /* First search for a scope with the given name */ if (NoScope) { Scope = SymFindAnyScope (ParentScope, &Name); } else { Scope = SymFindScope (ParentScope, &Name, SYM_FIND_EXISTING); } /* If we did find a scope with the name, read the symbol defining the * size, otherwise search for a symbol entry with the name and scope. */ if (Scope) { /* Yep, it's a scope */ SizeSym = GetSizeOfScope (Scope); } else { if (NoScope) { Sym = SymFindAny (ParentScope, &Name); } else { Sym = SymFind (ParentScope, &Name, SYM_FIND_EXISTING); } /* If we found the symbol retrieve the size, otherwise complain */ if (Sym) { SizeSym = GetSizeOfSymbol (Sym); } else { Error ("Unknown symbol or scope: `%m%p%m%p'", &ScopeName, &Name); } } } /* Check if we have a size */ if (SizeSym == 0 || !SymIsConst (SizeSym, &Size)) { Error ("Size of `%m%p%m%p' is unknown", &ScopeName, &Name); Size = 0; } /* Free the string buffers */ SB_Done (&ScopeName); SB_Done (&Name); /* Return the size */ return GenLiteralExpr (Size); } static ExprNode* FuncStrAt (void) /* Handle the .STRAT function */ { StrBuf Str = STATIC_STRBUF_INITIALIZER; long Index; unsigned char C = 0; /* String constant expected */ if (CurTok.Tok != TOK_STRCON) { Error ("String constant expected"); NextTok (); goto ExitPoint; } /* Remember the string and skip it */ SB_Copy (&Str, &CurTok.SVal); NextTok (); /* Comma must follow */ ConsumeComma (); /* Expression expected */ Index = ConstExpression (); /* Must be a valid index */ if (Index >= (long) SB_GetLen (&Str)) { Error ("Range error"); goto ExitPoint; } /* Get the char, handle as unsigned. Be sure to translate it into * the target character set. */ C = TgtTranslateChar (SB_At (&Str, (unsigned)Index)); ExitPoint: /* Free string buffer memory */ SB_Done (&Str); /* Return the char expression */ return GenLiteralExpr (C); } static ExprNode* FuncStrLen (void) /* Handle the .STRLEN function */ { int Len; /* String constant expected */ if (CurTok.Tok != TOK_STRCON) { Error ("String constant expected"); /* Smart error recovery */ if (CurTok.Tok != TOK_RPAREN) { NextTok (); } Len = 0; } else { /* Get the length of the string */ Len = SB_GetLen (&CurTok.SVal); /* Skip the string */ NextTok (); } /* Return the length */ return GenLiteralExpr (Len); } static ExprNode* FuncTCount (void) /* Handle the .TCOUNT function */ { /* We have a list of tokens that ends with the closing paren. Skip * the tokens, and count them. Allow optionally curly braces. */ token_t Term = GetTokListTerm (TOK_RPAREN); int Count = 0; while (CurTok.Tok != Term) { /* Check for end of line or end of input. Since the calling function * will check for the closing paren, we don't need to print an error * here, just bail out. */ if (TokIsSep (CurTok.Tok)) { break; } /* One more token */ ++Count; /* Skip the token */ NextTok (); } /* If the list was enclosed in curly braces, skip the closing brace */ if (Term == TOK_RCURLY && CurTok.Tok == TOK_RCURLY) { NextTok (); } /* Return the number of tokens */ return GenLiteralExpr (Count); } static ExprNode* FuncXMatch (void) /* Handle the .XMATCH function */ { return DoMatch (tcIdentical); } static ExprNode* Function (ExprNode* (*F) (void)) /* Handle builtin functions */ { ExprNode* E; /* Skip the keyword */ NextTok (); /* Expression must be enclosed in braces */ if (CurTok.Tok != TOK_LPAREN) { Error ("'(' expected"); SkipUntilSep (); return GenLiteral0 (); } NextTok (); /* Call the function itself */ E = F (); /* Closing brace must follow */ ConsumeRParen (); /* Return the result of the actual function */ return E; } static ExprNode* Factor (void) { ExprNode* L; ExprNode* N; long Val; switch (CurTok.Tok) { case TOK_INTCON: N = GenLiteralExpr (CurTok.IVal); NextTok (); break; case TOK_CHARCON: N = GenLiteralExpr (TgtTranslateChar (CurTok.IVal)); NextTok (); break; case TOK_NAMESPACE: case TOK_IDENT: case TOK_LOCAL_IDENT: N = Symbol (ParseAnySymName (SYM_ALLOC_NEW)); break; case TOK_ULABEL: N = ULabRef (CurTok.IVal); NextTok (); break; case TOK_PLUS: NextTok (); N = Factor (); break; case TOK_MINUS: NextTok (); L = Factor (); if (IsEasyConst (L, &Val)) { FreeExpr (L); N = GenLiteralExpr (-Val); } else { N = NewExprNode (EXPR_UNARY_MINUS); N->Left = L; } break; case TOK_NOT: NextTok (); L = Factor (); if (IsEasyConst (L, &Val)) { FreeExpr (L); N = GenLiteralExpr (~Val); } else { N = NewExprNode (EXPR_NOT); N->Left = L; } break; case TOK_STAR: case TOK_PC: NextTok (); N = GenCurrentPC (); break; case TOK_LT: NextTok (); N = LoByte (Factor ()); break; case TOK_GT: NextTok (); N = HiByte (Factor ()); break; case TOK_XOR: /* ^ means the bank byte of an expression */ NextTok (); N = BankByte (Factor ()); break; case TOK_LPAREN: NextTok (); N = Expr0 (); ConsumeRParen (); break; case TOK_BANK: N = Function (FuncBank); break; case TOK_BANKBYTE: N = Function (FuncBankByte); break; case TOK_BLANK: N = Function (FuncBlank); break; case TOK_CONST: N = Function (FuncConst); break; case TOK_CPU: N = GenLiteralExpr (CPUIsets[CPU]); NextTok (); break; case TOK_DEFINED: N = Function (FuncDefined); break; case TOK_HIBYTE: N = Function (FuncHiByte); break; case TOK_HIWORD: N = Function (FuncHiWord); break; case TOK_LOBYTE: N = Function (FuncLoByte); break; case TOK_LOWORD: N = Function (FuncLoWord); break; case TOK_MATCH: N = Function (FuncMatch); break; case TOK_MAX: N = Function (FuncMax); break; case TOK_MIN: N = Function (FuncMin); break; case TOK_REFERENCED: N = Function (FuncReferenced); break; case TOK_SIZEOF: N = Function (FuncSizeOf); break; case TOK_STRAT: N = Function (FuncStrAt); break; case TOK_STRLEN: N = Function (FuncStrLen); break; case TOK_TCOUNT: N = Function (FuncTCount); break; case TOK_TIME: N = GenLiteralExpr ((long) time (0)); NextTok (); break; case TOK_VERSION: N = GenLiteralExpr (GetVersionAsNumber ()); NextTok (); break; case TOK_XMATCH: N = Function (FuncXMatch); break; default: if (LooseCharTerm && CurTok.Tok == TOK_STRCON && SB_GetLen (&CurTok.SVal) == 1) { /* A character constant */ N = GenLiteralExpr (TgtTranslateChar (SB_At (&CurTok.SVal, 0))); } else { N = GenLiteral0 (); /* Dummy */ Error ("Syntax error"); } NextTok (); break; } return N; } static ExprNode* Term (void) { /* Read left hand side */ ExprNode* Root = Factor (); /* Handle multiplicative operations */ while (CurTok.Tok == TOK_MUL || CurTok.Tok == TOK_DIV || CurTok.Tok == TOK_MOD || CurTok.Tok == TOK_AND || CurTok.Tok == TOK_XOR || CurTok.Tok == TOK_SHL || CurTok.Tok == TOK_SHR) { long LVal, RVal, Val; ExprNode* Left; ExprNode* Right; /* Remember the token and skip it */ token_t T = CurTok.Tok; NextTok (); /* Move root to left side and read the right side */ Left = Root; Right = Factor (); /* If both expressions are constant, we can evaluate the term */ if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) { switch (T) { case TOK_MUL: Val = LVal * RVal; break; case TOK_DIV: if (RVal == 0) { Error ("Division by zero"); Val = 1; } else { Val = LVal / RVal; } break; case TOK_MOD: if (RVal == 0) { Error ("Modulo operation with zero"); Val = 1; } else { Val = LVal % RVal; } break; case TOK_AND: Val = LVal & RVal; break; case TOK_XOR: Val = LVal ^ RVal; break; case TOK_SHL: Val = shl_l (LVal, RVal); break; case TOK_SHR: Val = shr_l (LVal, RVal); break; default: Internal ("Invalid token"); } /* Generate a literal expression and delete the old left and * right sides. */ FreeExpr (Left); FreeExpr (Right); Root = GenLiteralExpr (Val); } else { /* Generate an expression tree */ unsigned char Op; switch (T) { case TOK_MUL: Op = EXPR_MUL; break; case TOK_DIV: Op = EXPR_DIV; break; case TOK_MOD: Op = EXPR_MOD; break; case TOK_AND: Op = EXPR_AND; break; case TOK_XOR: Op = EXPR_XOR; break; case TOK_SHL: Op = EXPR_SHL; break; case TOK_SHR: Op = EXPR_SHR; break; default: Internal ("Invalid token"); } Root = NewExprNode (Op); Root->Left = Left; Root->Right = Right; } } /* Return the expression tree we've created */ return Root; } static ExprNode* SimpleExpr (void) { /* Read left hand side */ ExprNode* Root = Term (); /* Handle additive operations */ while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS || CurTok.Tok == TOK_OR) { long LVal, RVal, Val; ExprNode* Left; ExprNode* Right; /* Remember the token and skip it */ token_t T = CurTok.Tok; NextTok (); /* Move root to left side and read the right side */ Left = Root; Right = Term (); /* If both expressions are constant, we can evaluate the term */ if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) { switch (T) { case TOK_PLUS: Val = LVal + RVal; break; case TOK_MINUS: Val = LVal - RVal; break; case TOK_OR: Val = LVal | RVal; break; default: Internal ("Invalid token"); } /* Generate a literal expression and delete the old left and * right sides. */ FreeExpr (Left); FreeExpr (Right); Root = GenLiteralExpr (Val); } else { /* Generate an expression tree */ unsigned char Op; switch (T) { case TOK_PLUS: Op = EXPR_PLUS; break; case TOK_MINUS: Op = EXPR_MINUS; break; case TOK_OR: Op = EXPR_OR; break; default: Internal ("Invalid token"); } Root = NewExprNode (Op); Root->Left = Left; Root->Right = Right; } } /* Return the expression tree we've created */ return Root; } static ExprNode* BoolExpr (void) /* Evaluate a boolean expression */ { /* Read left hand side */ ExprNode* Root = SimpleExpr (); /* Handle booleans */ while (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_NE || CurTok.Tok == TOK_LT || CurTok.Tok == TOK_GT || CurTok.Tok == TOK_LE || CurTok.Tok == TOK_GE) { long LVal, RVal, Val; ExprNode* Left; ExprNode* Right; /* Remember the token and skip it */ token_t T = CurTok.Tok; NextTok (); /* Move root to left side and read the right side */ Left = Root; Right = SimpleExpr (); /* If both expressions are constant, we can evaluate the term */ if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) { switch (T) { case TOK_EQ: Val = (LVal == RVal); break; case TOK_NE: Val = (LVal != RVal); break; case TOK_LT: Val = (LVal < RVal); break; case TOK_GT: Val = (LVal > RVal); break; case TOK_LE: Val = (LVal <= RVal); break; case TOK_GE: Val = (LVal >= RVal); break; default: Internal ("Invalid token"); } /* Generate a literal expression and delete the old left and * right sides. */ FreeExpr (Left); FreeExpr (Right); Root = GenLiteralExpr (Val); } else { /* Generate an expression tree */ unsigned char Op; switch (T) { case TOK_EQ: Op = EXPR_EQ; break; case TOK_NE: Op = EXPR_NE; break; case TOK_LT: Op = EXPR_LT; break; case TOK_GT: Op = EXPR_GT; break; case TOK_LE: Op = EXPR_LE; break; case TOK_GE: Op = EXPR_GE; break; default: Internal ("Invalid token"); } Root = NewExprNode (Op); Root->Left = Left; Root->Right = Right; } } /* Return the expression tree we've created */ return Root; } static ExprNode* Expr2 (void) /* Boolean operators: AND and XOR */ { /* Read left hand side */ ExprNode* Root = BoolExpr (); /* Handle booleans */ while (CurTok.Tok == TOK_BOOLAND || CurTok.Tok == TOK_BOOLXOR) { long LVal, RVal, Val; ExprNode* Left; ExprNode* Right; /* Remember the token and skip it */ token_t T = CurTok.Tok; NextTok (); /* Move root to left side and read the right side */ Left = Root; Right = BoolExpr (); /* If both expressions are constant, we can evaluate the term */ if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) { switch (T) { case TOK_BOOLAND: Val = ((LVal != 0) && (RVal != 0)); break; case TOK_BOOLXOR: Val = ((LVal != 0) ^ (RVal != 0)); break; default: Internal ("Invalid token"); } /* Generate a literal expression and delete the old left and * right sides. */ FreeExpr (Left); FreeExpr (Right); Root = GenLiteralExpr (Val); } else { /* Generate an expression tree */ unsigned char Op; switch (T) { case TOK_BOOLAND: Op = EXPR_BOOLAND; break; case TOK_BOOLXOR: Op = EXPR_BOOLXOR; break; default: Internal ("Invalid token"); } Root = NewExprNode (Op); Root->Left = Left; Root->Right = Right; } } /* Return the expression tree we've created */ return Root; } static ExprNode* Expr1 (void) /* Boolean operators: OR */ { /* Read left hand side */ ExprNode* Root = Expr2 (); /* Handle booleans */ while (CurTok.Tok == TOK_BOOLOR) { long LVal, RVal, Val; ExprNode* Left; ExprNode* Right; /* Remember the token and skip it */ token_t T = CurTok.Tok; NextTok (); /* Move root to left side and read the right side */ Left = Root; Right = Expr2 (); /* If both expressions are constant, we can evaluate the term */ if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) { switch (T) { case TOK_BOOLOR: Val = ((LVal != 0) || (RVal != 0)); break; default: Internal ("Invalid token"); } /* Generate a literal expression and delete the old left and * right sides. */ FreeExpr (Left); FreeExpr (Right); Root = GenLiteralExpr (Val); } else { /* Generate an expression tree */ unsigned char Op; switch (T) { case TOK_BOOLOR: Op = EXPR_BOOLOR; break; default: Internal ("Invalid token"); } Root = NewExprNode (Op); Root->Left = Left; Root->Right = Right; } } /* Return the expression tree we've created */ return Root; } static ExprNode* Expr0 (void) /* Boolean operators: NOT */ { ExprNode* Root; /* Handle booleans */ if (CurTok.Tok == TOK_BOOLNOT) { long Val; ExprNode* Left; /* Skip the operator token */ NextTok (); /* Read the argument */ Left = Expr0 (); /* If the argument is const, evaluate it directly */ if (IsEasyConst (Left, &Val)) { FreeExpr (Left); Root = GenLiteralExpr (!Val); } else { Root = NewExprNode (EXPR_BOOLNOT); Root->Left = Left; } } else { /* Read left hand side */ Root = Expr1 (); } /* Return the expression tree we've created */ return Root; } ExprNode* Expression (void) /* Evaluate an expression, build the expression tree on the heap and return * a pointer to the root of the tree. */ { return Expr0 (); } long ConstExpression (void) /* Parse an expression. Check if the expression is const, and print an error * message if not. Return the value of the expression, or a dummy, if it is * not constant. */ { long Val; /* Read the expression */ ExprNode* Expr = Expression (); /* Study the expression */ ExprDesc D; ED_Init (&D); StudyExpr (Expr, &D); /* Check if the expression is constant */ if (ED_IsConst (&D)) { Val = D.Val; } else { Error ("Constant expression expected"); Val = 0; } /* Free the expression tree and allocated memory for D */ FreeExpr (Expr); ED_Done (&D); /* Return the value */ return Val; } void FreeExpr (ExprNode* Root) /* Free the expression, Root is pointing to. */ { if (Root) { FreeExpr (Root->Left); FreeExpr (Root->Right); FreeExprNode (Root); } } ExprNode* SimplifyExpr (ExprNode* Expr, const ExprDesc* D) /* Try to simplify the given expression tree */ { if (Expr->Op != EXPR_LITERAL && ED_IsConst (D)) { /* No external references */ FreeExpr (Expr); Expr = GenLiteralExpr (D->Val); } return Expr; } ExprNode* GenLiteralExpr (long Val) /* Return an expression tree that encodes the given literal value */ { ExprNode* Expr = NewExprNode (EXPR_LITERAL); Expr->V.IVal = Val; return Expr; } ExprNode* GenLiteral0 (void) /* Return an expression tree that encodes the the number zero */ { return GenLiteralExpr (0); } ExprNode* GenSymExpr (SymEntry* Sym) /* Return an expression node that encodes the given symbol */ { ExprNode* Expr = NewExprNode (EXPR_SYMBOL); Expr->V.Sym = Sym; SymAddExprRef (Sym, Expr); return Expr; } static ExprNode* GenSectionExpr (unsigned SecNum) /* Return an expression node for the given section */ { ExprNode* Expr = NewExprNode (EXPR_SECTION); Expr->V.SecNum = SecNum; return Expr; } static ExprNode* GenBankExpr (unsigned SecNum) /* Return an expression node for the given bank */ { ExprNode* Expr = NewExprNode (EXPR_BANK); Expr->V.SecNum = SecNum; return Expr; } ExprNode* GenAddExpr (ExprNode* Left, ExprNode* Right) /* Generate an addition from the two operands */ { long Val; if (IsEasyConst (Left, &Val) && Val == 0) { FreeExpr (Left); return Right; } else if (IsEasyConst (Right, &Val) && Val == 0) { FreeExpr (Right); return Left; } else { ExprNode* Root = NewExprNode (EXPR_PLUS); Root->Left = Left; Root->Right = Right; return Root; } } ExprNode* GenCurrentPC (void) /* Return the current program counter as expression */ { ExprNode* Root; if (GetRelocMode ()) { /* Create SegmentBase + Offset */ Root = GenAddExpr (GenSectionExpr (GetCurrentSegNum ()), GenLiteralExpr (GetPC ())); } else { /* Absolute mode, just return PC value */ Root = GenLiteralExpr (GetPC ()); } return Root; } ExprNode* GenSwapExpr (ExprNode* Expr) /* Return an extended expression with lo and hi bytes swapped */ { ExprNode* N = NewExprNode (EXPR_SWAP); N->Left = Expr; return N; } ExprNode* GenBranchExpr (unsigned Offs) /* Return an expression that encodes the difference between current PC plus * offset and the target expression (that is, Expression() - (*+Offs) ). */ { ExprNode* N; ExprNode* Root; long Val; /* Read Expression() */ N = Expression (); /* If the expression is a cheap constant, generate a simpler tree */ if (IsEasyConst (N, &Val)) { /* Free the constant expression tree */ FreeExpr (N); /* Generate the final expression: * Val - (* + Offs) * Val - ((Seg + PC) + Offs) * Val - Seg - PC - Offs * (Val - PC - Offs) - Seg */ Root = GenLiteralExpr (Val - GetPC () - Offs); if (GetRelocMode ()) { N = Root; Root = NewExprNode (EXPR_MINUS); Root->Left = N; Root->Right = GenSectionExpr (GetCurrentSegNum ()); } } else { /* Generate the expression: * N - (* + Offs) * N - ((Seg + PC) + Offs) * N - Seg - PC - Offs * N - (PC + Offs) - Seg */ Root = NewExprNode (EXPR_MINUS); Root->Left = N; Root->Right = GenLiteralExpr (GetPC () + Offs); if (GetRelocMode ()) { N = Root; Root = NewExprNode (EXPR_MINUS); Root->Left = N; Root->Right = GenSectionExpr (GetCurrentSegNum ()); } } /* Return the result */ return Root; } ExprNode* GenULabelExpr (unsigned Num) /* Return an expression for an unnamed label with the given index */ { ExprNode* Node = NewExprNode (EXPR_ULABEL); Node->V.IVal = Num; /* Return the new node */ return Node; } ExprNode* GenByteExpr (ExprNode* Expr) /* Force the given expression into a byte and return the result */ { /* Use the low byte operator to force the expression into byte size */ return LoByte (Expr); } ExprNode* GenWordExpr (ExprNode* Expr) /* Force the given expression into a word and return the result. */ { /* Use the low byte operator to force the expression into word size */ return LoWord (Expr); } ExprNode* GenFarAddrExpr (ExprNode* Expr) /* Force the given expression into a far address and return the result. */ { long Val; /* Special handling for const expressions */ if (IsEasyConst (Expr, &Val)) { FreeExpr (Expr); Expr = GenLiteralExpr (Val & 0xFFFFFF); } else { ExprNode* Operand = Expr; Expr = NewExprNode (EXPR_FARADDR); Expr->Left = Operand; } return Expr; } ExprNode* GenDWordExpr (ExprNode* Expr) /* Force the given expression into a dword and return the result. */ { long Val; /* Special handling for const expressions */ if (IsEasyConst (Expr, &Val)) { FreeExpr (Expr); Expr = GenLiteralExpr (Val & 0xFFFFFFFF); } else { ExprNode* Operand = Expr; Expr = NewExprNode (EXPR_DWORD); Expr->Left = Operand; } return Expr; } ExprNode* GenNE (ExprNode* Expr, long Val) /* Generate an expression that compares Expr and Val for inequality */ { /* Generate a compare node */ ExprNode* Root = NewExprNode (EXPR_NE); Root->Left = Expr; Root->Right = GenLiteralExpr (Val); /* Return the result */ return Root; } int IsConstExpr (ExprNode* Expr, long* Val) /* Return true if the given expression is a constant expression, that is, one * with no references to external symbols. If Val is not NULL and the * expression is constant, the constant value is stored here. */ { int IsConst; /* Study the expression */ ExprDesc D; ED_Init (&D); StudyExpr (Expr, &D); /* Check if the expression is constant */ IsConst = ED_IsConst (&D); if (IsConst && Val != 0) { *Val = D.Val; } /* Delete allocated memory and return the result */ ED_Done (&D); return IsConst; } ExprNode* CloneExpr (ExprNode* Expr) /* Clone the given expression tree. The function will simply clone symbol * nodes, it will not resolve them. */ { ExprNode* Clone; /* Accept NULL pointers */ if (Expr == 0) { return 0; } /* Clone the node */ switch (Expr->Op) { case EXPR_LITERAL: Clone = GenLiteralExpr (Expr->V.IVal); break; case EXPR_ULABEL: Clone = GenULabelExpr (Expr->V.IVal); break; case EXPR_SYMBOL: Clone = GenSymExpr (Expr->V.Sym); break; case EXPR_SECTION: Clone = GenSectionExpr (Expr->V.SecNum); break; case EXPR_BANK: Clone = GenBankExpr (Expr->V.SecNum); break; default: /* Generate a new node */ Clone = NewExprNode (Expr->Op); /* Clone the tree nodes */ Clone->Left = CloneExpr (Expr->Left); Clone->Right = CloneExpr (Expr->Right); break; } /* Done */ return Clone; } void WriteExpr (ExprNode* Expr) /* Write the given expression to the object file */ { /* Null expressions are encoded by a type byte of zero */ if (Expr == 0) { ObjWrite8 (EXPR_NULL); return; } /* If the is a leafnode, write the expression attribute, otherwise * write the expression operands. */ switch (Expr->Op) { case EXPR_LITERAL: ObjWrite8 (EXPR_LITERAL); ObjWrite32 (Expr->V.IVal); break; case EXPR_SYMBOL: if (SymIsImport (Expr->V.Sym)) { ObjWrite8 (EXPR_SYMBOL); ObjWriteVar (GetSymImportId (Expr->V.Sym)); } else { WriteExpr (GetSymExpr (Expr->V.Sym)); } break; case EXPR_SECTION: ObjWrite8 (EXPR_SECTION); ObjWriteVar (Expr->V.SecNum); break; case EXPR_ULABEL: WriteExpr (ULabResolve (Expr->V.IVal)); break; default: /* Not a leaf node */ ObjWrite8 (Expr->Op); WriteExpr (Expr->Left); WriteExpr (Expr->Right); break; } } void ExprGuessedAddrSize (const ExprNode* Expr, unsigned char AddrSize) /* Mark the address size of the given expression tree as guessed. The address * size passed as argument is the one NOT used, because the actual address * size wasn't known. Example: Zero page addressing was not used because symbol * is undefined, and absolute addressing was available. * This function will actually parse the expression tree for undefined symbols, * and mark these symbols accordingly. */ { /* Accept NULL expressions */ if (Expr == 0) { return; } /* Check the type code */ switch (EXPR_NODETYPE (Expr->Op)) { case EXPR_LEAFNODE: if (Expr->Op == EXPR_SYMBOL) { if (!SymIsDef (Expr->V.Sym)) { /* Symbol is undefined, mark it */ SymGuessedAddrSize (Expr->V.Sym, AddrSize); } } return; case EXPR_BINARYNODE: ExprGuessedAddrSize (Expr->Right, AddrSize); /* FALLTHROUGH */ case EXPR_UNARYNODE: ExprGuessedAddrSize (Expr->Left, AddrSize); break; } } ExprNode* MakeBoundedExpr (ExprNode* Expr, unsigned Size) /* Force the given expression into a specific size of ForceRange is true */ { if (ForceRange) { switch (Size) { case 1: Expr = GenByteExpr (Expr); break; case 2: Expr = GenWordExpr (Expr); break; case 3: Expr = GenFarAddrExpr (Expr); break; case 4: Expr = GenDWordExpr (Expr); break; default: Internal ("Invalid size in BoundedExpr: %u", Size); } } return Expr; } ExprNode* BoundedExpr (ExprNode* (*ExprFunc) (void), unsigned Size) /* Parse an expression and force it within a given size if ForceRange is true */ { return MakeBoundedExpr (ExprFunc (), Size); }
932
./cc65/src/ca65/instr.c
/*****************************************************************************/ /* */ /* instr.c */ /* */ /* Instruction encoding for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> #include <ctype.h> /* common */ #include "addrsize.h" #include "attrib.h" #include "bitops.h" #include "check.h" #include "mmodel.h" /* ca65 */ #include "asserts.h" #include "ea.h" #include "ea65.h" #include "easw16.h" #include "error.h" #include "expr.h" #include "global.h" #include "instr.h" #include "nexttok.h" #include "objcode.h" #include "spool.h" #include "studyexpr.h" #include "symtab.h" /*****************************************************************************/ /* Forwards */ /*****************************************************************************/ static void PutPCRel8 (const InsDesc* Ins); /* Handle branches with a 8 bit distance */ static void PutPCRel16 (const InsDesc* Ins); /* Handle branches with an 16 bit distance and PER */ static void PutBlockMove (const InsDesc* Ins); /* Handle the blockmove instructions (65816) */ static void PutBlockTransfer (const InsDesc* Ins); /* Handle the block transfer instructions (HuC6280) */ static void PutBitBranch (const InsDesc* Ins); /* Handle 65C02 branch on bit condition */ static void PutREP (const InsDesc* Ins); /* Emit a REP instruction, track register sizes */ static void PutSEP (const InsDesc* Ins); /* Emit a SEP instruction (65816), track register sizes */ static void PutTAMn (const InsDesc* Ins); /* Emit a TAMn instruction (HuC6280). Since this is a two byte instruction with * implicit addressing mode, the opcode byte in the table is actually the * second operand byte. The TAM instruction is the more generic form, it takes * an immediate argument. */ static void PutTMA (const InsDesc* Ins); /* Emit a TMA instruction (HuC6280) with an immediate argument. Only one bit * in the argument byte may be set. */ static void PutTMAn (const InsDesc* Ins); /* Emit a TMAn instruction (HuC6280). Since this is a two byte instruction with * implicit addressing mode, the opcode byte in the table is actually the * second operand byte. The TAM instruction is the more generic form, it takes * an immediate argument. */ static void PutTST (const InsDesc* Ins); /* Emit a TST instruction (HuC6280). */ static void PutJMP (const InsDesc* Ins); /* Handle the jump instruction for the 6502. Problem is that these chips have * a bug: If the address crosses a page, the upper byte gets not corrected and * the instruction will fail. The PutJmp function will add a linker assertion * to check for this case and is otherwise identical to PutAll. */ static void PutRTS (const InsDesc* Ins attribute ((unused))); /* Handle the RTS instruction for the 816. In smart mode emit a RTL opcode if * the enclosing scope is FAR. */ static void PutAll (const InsDesc* Ins); /* Handle all other instructions */ static void PutSweet16 (const InsDesc* Ins); /* Handle a generic sweet16 instruction */ static void PutSweet16Branch (const InsDesc* Ins); /* Handle a sweet16 branch instruction */ /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Empty instruction table */ static const struct { unsigned Count; } InsTabNone = { 0 }; /* Instruction table for the 6502 */ static const struct { unsigned Count; InsDesc Ins[56]; } InsTab6502 = { sizeof (InsTab6502.Ins) / sizeof (InsTab6502.Ins[0]), { { "ADC", 0x080A26C, 0x60, 0, PutAll }, { "AND", 0x080A26C, 0x20, 0, PutAll }, { "ASL", 0x000006e, 0x02, 1, PutAll }, { "BCC", 0x0020000, 0x90, 0, PutPCRel8 }, { "BCS", 0x0020000, 0xb0, 0, PutPCRel8 }, { "BEQ", 0x0020000, 0xf0, 0, PutPCRel8 }, { "BIT", 0x000000C, 0x00, 2, PutAll }, { "BMI", 0x0020000, 0x30, 0, PutPCRel8 }, { "BNE", 0x0020000, 0xd0, 0, PutPCRel8 }, { "BPL", 0x0020000, 0x10, 0, PutPCRel8 }, { "BRK", 0x0000001, 0x00, 0, PutAll }, { "BVC", 0x0020000, 0x50, 0, PutPCRel8 }, { "BVS", 0x0020000, 0x70, 0, PutPCRel8 }, { "CLC", 0x0000001, 0x18, 0, PutAll }, { "CLD", 0x0000001, 0xd8, 0, PutAll }, { "CLI", 0x0000001, 0x58, 0, PutAll }, { "CLV", 0x0000001, 0xb8, 0, PutAll }, { "CMP", 0x080A26C, 0xc0, 0, PutAll }, { "CPX", 0x080000C, 0xe0, 1, PutAll }, { "CPY", 0x080000C, 0xc0, 1, PutAll }, { "DEC", 0x000006C, 0x00, 3, PutAll }, { "DEX", 0x0000001, 0xca, 0, PutAll }, { "DEY", 0x0000001, 0x88, 0, PutAll }, { "EOR", 0x080A26C, 0x40, 0, PutAll }, { "INC", 0x000006c, 0x00, 4, PutAll }, { "INX", 0x0000001, 0xe8, 0, PutAll }, { "INY", 0x0000001, 0xc8, 0, PutAll }, { "JMP", 0x0000808, 0x4c, 6, PutJMP }, { "JSR", 0x0000008, 0x20, 7, PutAll }, { "LDA", 0x080A26C, 0xa0, 0, PutAll }, { "LDX", 0x080030C, 0xa2, 1, PutAll }, { "LDY", 0x080006C, 0xa0, 1, PutAll }, { "LSR", 0x000006F, 0x42, 1, PutAll }, { "NOP", 0x0000001, 0xea, 0, PutAll }, { "ORA", 0x080A26C, 0x00, 0, PutAll }, { "PHA", 0x0000001, 0x48, 0, PutAll }, { "PHP", 0x0000001, 0x08, 0, PutAll }, { "PLA", 0x0000001, 0x68, 0, PutAll }, { "PLP", 0x0000001, 0x28, 0, PutAll }, { "ROL", 0x000006F, 0x22, 1, PutAll }, { "ROR", 0x000006F, 0x62, 1, PutAll }, { "RTI", 0x0000001, 0x40, 0, PutAll }, { "RTS", 0x0000001, 0x60, 0, PutAll }, { "SBC", 0x080A26C, 0xe0, 0, PutAll }, { "SEC", 0x0000001, 0x38, 0, PutAll }, { "SED", 0x0000001, 0xf8, 0, PutAll }, { "SEI", 0x0000001, 0x78, 0, PutAll }, { "STA", 0x000A26C, 0x80, 0, PutAll }, { "STX", 0x000010c, 0x82, 1, PutAll }, { "STY", 0x000002c, 0x80, 1, PutAll }, { "TAX", 0x0000001, 0xaa, 0, PutAll }, { "TAY", 0x0000001, 0xa8, 0, PutAll }, { "TSX", 0x0000001, 0xba, 0, PutAll }, { "TXA", 0x0000001, 0x8a, 0, PutAll }, { "TXS", 0x0000001, 0x9a, 0, PutAll }, { "TYA", 0x0000001, 0x98, 0, PutAll } } }; /* Instruction table for the 6502 with illegal instructions */ static const struct { unsigned Count; InsDesc Ins[70]; } InsTab6502X = { sizeof (InsTab6502X.Ins) / sizeof (InsTab6502X.Ins[0]), { { "ADC", 0x080A26C, 0x60, 0, PutAll }, { "ALR", 0x0800000, 0x4B, 0, PutAll }, /* X */ { "ANC", 0x0800000, 0x0B, 0, PutAll }, /* X */ { "AND", 0x080A26C, 0x20, 0, PutAll }, { "ARR", 0x0800000, 0x6B, 0, PutAll }, /* X */ { "ASL", 0x000006e, 0x02, 1, PutAll }, { "AXS", 0x0800000, 0xCB, 0, PutAll }, /* X */ { "BCC", 0x0020000, 0x90, 0, PutPCRel8 }, { "BCS", 0x0020000, 0xb0, 0, PutPCRel8 }, { "BEQ", 0x0020000, 0xf0, 0, PutPCRel8 }, { "BIT", 0x000000C, 0x00, 2, PutAll }, { "BMI", 0x0020000, 0x30, 0, PutPCRel8 }, { "BNE", 0x0020000, 0xd0, 0, PutPCRel8 }, { "BPL", 0x0020000, 0x10, 0, PutPCRel8 }, { "BRK", 0x0000001, 0x00, 0, PutAll }, { "BVC", 0x0020000, 0x50, 0, PutPCRel8 }, { "BVS", 0x0020000, 0x70, 0, PutPCRel8 }, { "CLC", 0x0000001, 0x18, 0, PutAll }, { "CLD", 0x0000001, 0xd8, 0, PutAll }, { "CLI", 0x0000001, 0x58, 0, PutAll }, { "CLV", 0x0000001, 0xb8, 0, PutAll }, { "CMP", 0x080A26C, 0xc0, 0, PutAll }, { "CPX", 0x080000C, 0xe0, 1, PutAll }, { "CPY", 0x080000C, 0xc0, 1, PutAll }, { "DCP", 0x000A26C, 0xC3, 0, PutAll }, /* X */ { "DEC", 0x000006C, 0x00, 3, PutAll }, { "DEX", 0x0000001, 0xca, 0, PutAll }, { "DEY", 0x0000001, 0x88, 0, PutAll }, { "EOR", 0x080A26C, 0x40, 0, PutAll }, { "INC", 0x000006c, 0x00, 4, PutAll }, { "INX", 0x0000001, 0xe8, 0, PutAll }, { "INY", 0x0000001, 0xc8, 0, PutAll }, { "ISC", 0x000A26C, 0xE3, 0, PutAll }, /* X */ { "JAM", 0x0000001, 0x02, 0, PutAll }, /* X */ { "JMP", 0x0000808, 0x4c, 6, PutJMP }, { "JSR", 0x0000008, 0x20, 7, PutAll }, { "LAS", 0x0000200, 0xBB, 0, PutAll }, /* X */ { "LAX", 0x000A30C, 0xA3, 1, PutAll }, /* X */ { "LDA", 0x080A26C, 0xa0, 0, PutAll }, { "LDX", 0x080030C, 0xa2, 1, PutAll }, { "LDY", 0x080006C, 0xa0, 1, PutAll }, { "LSR", 0x000006F, 0x42, 1, PutAll }, { "NOP", 0x0000001, 0xea, 0, PutAll }, { "ORA", 0x080A26C, 0x00, 0, PutAll }, { "PHA", 0x0000001, 0x48, 0, PutAll }, { "PHP", 0x0000001, 0x08, 0, PutAll }, { "PLA", 0x0000001, 0x68, 0, PutAll }, { "PLP", 0x0000001, 0x28, 0, PutAll }, { "RLA", 0x000A26C, 0x23, 0, PutAll }, /* X */ { "ROL", 0x000006F, 0x22, 1, PutAll }, { "ROR", 0x000006F, 0x62, 1, PutAll }, { "RRA", 0x000A26C, 0x63, 0, PutAll }, /* X */ { "RTI", 0x0000001, 0x40, 0, PutAll }, { "RTS", 0x0000001, 0x60, 0, PutAll }, { "SAX", 0x000810C, 0x83, 1, PutAll }, /* X */ { "SBC", 0x080A26C, 0xe0, 0, PutAll }, { "SEC", 0x0000001, 0x38, 0, PutAll }, { "SED", 0x0000001, 0xf8, 0, PutAll }, { "SEI", 0x0000001, 0x78, 0, PutAll }, { "SLO", 0x000A26C, 0x03, 0, PutAll }, /* X */ { "SRE", 0x000A26C, 0x43, 0, PutAll }, /* X */ { "STA", 0x000A26C, 0x80, 0, PutAll }, { "STX", 0x000010c, 0x82, 1, PutAll }, { "STY", 0x000002c, 0x80, 1, PutAll }, { "TAX", 0x0000001, 0xaa, 0, PutAll }, { "TAY", 0x0000001, 0xa8, 0, PutAll }, { "TSX", 0x0000001, 0xba, 0, PutAll }, { "TXA", 0x0000001, 0x8a, 0, PutAll }, { "TXS", 0x0000001, 0x9a, 0, PutAll }, { "TYA", 0x0000001, 0x98, 0, PutAll } } }; /* Instruction table for the 65SC02 */ static const struct { unsigned Count; InsDesc Ins[66]; } InsTab65SC02 = { sizeof (InsTab65SC02.Ins) / sizeof (InsTab65SC02.Ins[0]), { { "ADC", 0x080A66C, 0x60, 0, PutAll }, { "AND", 0x080A66C, 0x20, 0, PutAll }, { "ASL", 0x000006e, 0x02, 1, PutAll }, { "BCC", 0x0020000, 0x90, 0, PutPCRel8 }, { "BCS", 0x0020000, 0xb0, 0, PutPCRel8 }, { "BEQ", 0x0020000, 0xf0, 0, PutPCRel8 }, { "BIT", 0x0A0006C, 0x00, 2, PutAll }, { "BMI", 0x0020000, 0x30, 0, PutPCRel8 }, { "BNE", 0x0020000, 0xd0, 0, PutPCRel8 }, { "BPL", 0x0020000, 0x10, 0, PutPCRel8 }, { "BRA", 0x0020000, 0x80, 0, PutPCRel8 }, { "BRK", 0x0000001, 0x00, 0, PutAll }, { "BVC", 0x0020000, 0x50, 0, PutPCRel8 }, { "BVS", 0x0020000, 0x70, 0, PutPCRel8 }, { "CLC", 0x0000001, 0x18, 0, PutAll }, { "CLD", 0x0000001, 0xd8, 0, PutAll }, { "CLI", 0x0000001, 0x58, 0, PutAll }, { "CLV", 0x0000001, 0xb8, 0, PutAll }, { "CMP", 0x080A66C, 0xc0, 0, PutAll }, { "CPX", 0x080000C, 0xe0, 1, PutAll }, { "CPY", 0x080000C, 0xc0, 1, PutAll }, { "DEA", 0x0000001, 0x00, 3, PutAll }, /* == DEC */ { "DEC", 0x000006F, 0x00, 3, PutAll }, { "DEX", 0x0000001, 0xca, 0, PutAll }, { "DEY", 0x0000001, 0x88, 0, PutAll }, { "EOR", 0x080A66C, 0x40, 0, PutAll }, { "INA", 0x0000001, 0x00, 4, PutAll }, /* == INC */ { "INC", 0x000006f, 0x00, 4, PutAll }, { "INX", 0x0000001, 0xe8, 0, PutAll }, { "INY", 0x0000001, 0xc8, 0, PutAll }, { "JMP", 0x0010808, 0x4c, 6, PutAll }, { "JSR", 0x0000008, 0x20, 7, PutAll }, { "LDA", 0x080A66C, 0xa0, 0, PutAll }, { "LDX", 0x080030C, 0xa2, 1, PutAll }, { "LDY", 0x080006C, 0xa0, 1, PutAll }, { "LSR", 0x000006F, 0x42, 1, PutAll }, { "NOP", 0x0000001, 0xea, 0, PutAll }, { "ORA", 0x080A66C, 0x00, 0, PutAll }, { "PHA", 0x0000001, 0x48, 0, PutAll }, { "PHP", 0x0000001, 0x08, 0, PutAll }, { "PHX", 0x0000001, 0xda, 0, PutAll }, { "PHY", 0x0000001, 0x5a, 0, PutAll }, { "PLA", 0x0000001, 0x68, 0, PutAll }, { "PLP", 0x0000001, 0x28, 0, PutAll }, { "PLX", 0x0000001, 0xfa, 0, PutAll }, { "PLY", 0x0000001, 0x7a, 0, PutAll }, { "ROL", 0x000006F, 0x22, 1, PutAll }, { "ROR", 0x000006F, 0x62, 1, PutAll }, { "RTI", 0x0000001, 0x40, 0, PutAll }, { "RTS", 0x0000001, 0x60, 0, PutAll }, { "SBC", 0x080A66C, 0xe0, 0, PutAll }, { "SEC", 0x0000001, 0x38, 0, PutAll }, { "SED", 0x0000001, 0xf8, 0, PutAll }, { "SEI", 0x0000001, 0x78, 0, PutAll }, { "STA", 0x000A66C, 0x80, 0, PutAll }, { "STX", 0x000010c, 0x82, 1, PutAll }, { "STY", 0x000002c, 0x80, 1, PutAll }, { "STZ", 0x000006c, 0x04, 5, PutAll }, { "TAX", 0x0000001, 0xaa, 0, PutAll }, { "TAY", 0x0000001, 0xa8, 0, PutAll }, { "TRB", 0x000000c, 0x10, 1, PutAll }, { "TSB", 0x000000c, 0x00, 1, PutAll }, { "TSX", 0x0000001, 0xba, 0, PutAll }, { "TXA", 0x0000001, 0x8a, 0, PutAll }, { "TXS", 0x0000001, 0x9a, 0, PutAll }, { "TYA", 0x0000001, 0x98, 0, PutAll } } }; /* Instruction table for the 65C02 */ static const struct { unsigned Count; InsDesc Ins[98]; } InsTab65C02 = { sizeof (InsTab65C02.Ins) / sizeof (InsTab65C02.Ins[0]), { { "ADC", 0x080A66C, 0x60, 0, PutAll }, { "AND", 0x080A66C, 0x20, 0, PutAll }, { "ASL", 0x000006e, 0x02, 1, PutAll }, { "BBR0", 0x0000000, 0x0F, 0, PutBitBranch }, { "BBR1", 0x0000000, 0x1F, 0, PutBitBranch }, { "BBR2", 0x0000000, 0x2F, 0, PutBitBranch }, { "BBR3", 0x0000000, 0x3F, 0, PutBitBranch }, { "BBR4", 0x0000000, 0x4F, 0, PutBitBranch }, { "BBR5", 0x0000000, 0x5F, 0, PutBitBranch }, { "BBR6", 0x0000000, 0x6F, 0, PutBitBranch }, { "BBR7", 0x0000000, 0x7F, 0, PutBitBranch }, { "BBS0", 0x0000000, 0x8F, 0, PutBitBranch }, { "BBS1", 0x0000000, 0x9F, 0, PutBitBranch }, { "BBS2", 0x0000000, 0xAF, 0, PutBitBranch }, { "BBS3", 0x0000000, 0xBF, 0, PutBitBranch }, { "BBS4", 0x0000000, 0xCF, 0, PutBitBranch }, { "BBS5", 0x0000000, 0xDF, 0, PutBitBranch }, { "BBS6", 0x0000000, 0xEF, 0, PutBitBranch }, { "BBS7", 0x0000000, 0xFF, 0, PutBitBranch }, { "BCC", 0x0020000, 0x90, 0, PutPCRel8 }, { "BCS", 0x0020000, 0xb0, 0, PutPCRel8 }, { "BEQ", 0x0020000, 0xf0, 0, PutPCRel8 }, { "BIT", 0x0A0006C, 0x00, 2, PutAll }, { "BMI", 0x0020000, 0x30, 0, PutPCRel8 }, { "BNE", 0x0020000, 0xd0, 0, PutPCRel8 }, { "BPL", 0x0020000, 0x10, 0, PutPCRel8 }, { "BRA", 0x0020000, 0x80, 0, PutPCRel8 }, { "BRK", 0x0000001, 0x00, 0, PutAll }, { "BVC", 0x0020000, 0x50, 0, PutPCRel8 }, { "BVS", 0x0020000, 0x70, 0, PutPCRel8 }, { "CLC", 0x0000001, 0x18, 0, PutAll }, { "CLD", 0x0000001, 0xd8, 0, PutAll }, { "CLI", 0x0000001, 0x58, 0, PutAll }, { "CLV", 0x0000001, 0xb8, 0, PutAll }, { "CMP", 0x080A66C, 0xc0, 0, PutAll }, { "CPX", 0x080000C, 0xe0, 1, PutAll }, { "CPY", 0x080000C, 0xc0, 1, PutAll }, { "DEA", 0x0000001, 0x00, 3, PutAll }, /* == DEC */ { "DEC", 0x000006F, 0x00, 3, PutAll }, { "DEX", 0x0000001, 0xca, 0, PutAll }, { "DEY", 0x0000001, 0x88, 0, PutAll }, { "EOR", 0x080A66C, 0x40, 0, PutAll }, { "INA", 0x0000001, 0x00, 4, PutAll }, /* == INC */ { "INC", 0x000006f, 0x00, 4, PutAll }, { "INX", 0x0000001, 0xe8, 0, PutAll }, { "INY", 0x0000001, 0xc8, 0, PutAll }, { "JMP", 0x0010808, 0x4c, 6, PutAll }, { "JSR", 0x0000008, 0x20, 7, PutAll }, { "LDA", 0x080A66C, 0xa0, 0, PutAll }, { "LDX", 0x080030C, 0xa2, 1, PutAll }, { "LDY", 0x080006C, 0xa0, 1, PutAll }, { "LSR", 0x000006F, 0x42, 1, PutAll }, { "NOP", 0x0000001, 0xea, 0, PutAll }, { "ORA", 0x080A66C, 0x00, 0, PutAll }, { "PHA", 0x0000001, 0x48, 0, PutAll }, { "PHP", 0x0000001, 0x08, 0, PutAll }, { "PHX", 0x0000001, 0xda, 0, PutAll }, { "PHY", 0x0000001, 0x5a, 0, PutAll }, { "PLA", 0x0000001, 0x68, 0, PutAll }, { "PLP", 0x0000001, 0x28, 0, PutAll }, { "PLX", 0x0000001, 0xfa, 0, PutAll }, { "PLY", 0x0000001, 0x7a, 0, PutAll }, { "RMB0", 0x0000004, 0x07, 1, PutAll }, { "RMB1", 0x0000004, 0x17, 1, PutAll }, { "RMB2", 0x0000004, 0x27, 1, PutAll }, { "RMB3", 0x0000004, 0x37, 1, PutAll }, { "RMB4", 0x0000004, 0x47, 1, PutAll }, { "RMB5", 0x0000004, 0x57, 1, PutAll }, { "RMB6", 0x0000004, 0x67, 1, PutAll }, { "RMB7", 0x0000004, 0x77, 1, PutAll }, { "ROL", 0x000006F, 0x22, 1, PutAll }, { "ROR", 0x000006F, 0x62, 1, PutAll }, { "RTI", 0x0000001, 0x40, 0, PutAll }, { "RTS", 0x0000001, 0x60, 0, PutAll }, { "SBC", 0x080A66C, 0xe0, 0, PutAll }, { "SEC", 0x0000001, 0x38, 0, PutAll }, { "SED", 0x0000001, 0xf8, 0, PutAll }, { "SEI", 0x0000001, 0x78, 0, PutAll }, { "SMB0", 0x0000004, 0x87, 1, PutAll }, { "SMB1", 0x0000004, 0x97, 1, PutAll }, { "SMB2", 0x0000004, 0xA7, 1, PutAll }, { "SMB3", 0x0000004, 0xB7, 1, PutAll }, { "SMB4", 0x0000004, 0xC7, 1, PutAll }, { "SMB5", 0x0000004, 0xD7, 1, PutAll }, { "SMB6", 0x0000004, 0xE7, 1, PutAll }, { "SMB7", 0x0000004, 0xF7, 1, PutAll }, { "STA", 0x000A66C, 0x80, 0, PutAll }, { "STX", 0x000010c, 0x82, 1, PutAll }, { "STY", 0x000002c, 0x80, 1, PutAll }, { "STZ", 0x000006c, 0x04, 5, PutAll }, { "TAX", 0x0000001, 0xaa, 0, PutAll }, { "TAY", 0x0000001, 0xa8, 0, PutAll }, { "TRB", 0x000000c, 0x10, 1, PutAll }, { "TSB", 0x000000c, 0x00, 1, PutAll }, { "TSX", 0x0000001, 0xba, 0, PutAll }, { "TXA", 0x0000001, 0x8a, 0, PutAll }, { "TXS", 0x0000001, 0x9a, 0, PutAll }, { "TYA", 0x0000001, 0x98, 0, PutAll } } }; /* Instruction table for the 65816 */ static const struct { unsigned Count; InsDesc Ins[99]; } InsTab65816 = { sizeof (InsTab65816.Ins) / sizeof (InsTab65816.Ins[0]), { { "ADC", 0x0b8f6fc, 0x60, 0, PutAll }, { "AND", 0x0b8f6fc, 0x20, 0, PutAll }, { "ASL", 0x000006e, 0x02, 1, PutAll }, { "BCC", 0x0020000, 0x90, 0, PutPCRel8 }, { "BCS", 0x0020000, 0xb0, 0, PutPCRel8 }, { "BEQ", 0x0020000, 0xf0, 0, PutPCRel8 }, { "BIT", 0x0a0006c, 0x00, 2, PutAll }, { "BMI", 0x0020000, 0x30, 0, PutPCRel8 }, { "BNE", 0x0020000, 0xd0, 0, PutPCRel8 }, { "BPL", 0x0020000, 0x10, 0, PutPCRel8 }, { "BRA", 0x0020000, 0x80, 0, PutPCRel8 }, { "BRK", 0x0000001, 0x00, 0, PutAll }, { "BRL", 0x0040000, 0x82, 0, PutPCRel16 }, { "BVC", 0x0020000, 0x50, 0, PutPCRel8 }, { "BVS", 0x0020000, 0x70, 0, PutPCRel8 }, { "CLC", 0x0000001, 0x18, 0, PutAll }, { "CLD", 0x0000001, 0xd8, 0, PutAll }, { "CLI", 0x0000001, 0x58, 0, PutAll }, { "CLV", 0x0000001, 0xb8, 0, PutAll }, { "CMP", 0x0b8f6fc, 0xc0, 0, PutAll }, { "COP", 0x0000004, 0x02, 6, PutAll }, { "CPA", 0x0b8f6fc, 0xc0, 0, PutAll }, /* == CMP */ { "CPX", 0x0c0000c, 0xe0, 1, PutAll }, { "CPY", 0x0c0000c, 0xc0, 1, PutAll }, { "DEA", 0x0000001, 0x00, 3, PutAll }, /* == DEC */ { "DEC", 0x000006F, 0x00, 3, PutAll }, { "DEX", 0x0000001, 0xca, 0, PutAll }, { "DEY", 0x0000001, 0x88, 0, PutAll }, { "EOR", 0x0b8f6fc, 0x40, 0, PutAll }, { "INA", 0x0000001, 0x00, 4, PutAll }, /* == INC */ { "INC", 0x000006F, 0x00, 4, PutAll }, { "INX", 0x0000001, 0xe8, 0, PutAll }, { "INY", 0x0000001, 0xc8, 0, PutAll }, { "JML", 0x0000810, 0x5c, 1, PutAll }, { "JMP", 0x0010818, 0x4c, 6, PutAll }, { "JSL", 0x0000010, 0x20, 7, PutAll }, { "JSR", 0x0010018, 0x20, 7, PutAll }, { "LDA", 0x0b8f6fc, 0xa0, 0, PutAll }, { "LDX", 0x0c0030c, 0xa2, 1, PutAll }, { "LDY", 0x0c0006c, 0xa0, 1, PutAll }, { "LSR", 0x000006F, 0x42, 1, PutAll }, { "MVN", 0x1000000, 0x54, 0, PutBlockMove }, { "MVP", 0x1000000, 0x44, 0, PutBlockMove }, { "NOP", 0x0000001, 0xea, 0, PutAll }, { "ORA", 0x0b8f6fc, 0x00, 0, PutAll }, { "PEA", 0x0000008, 0xf4, 6, PutAll }, { "PEI", 0x0000400, 0xd4, 1, PutAll }, { "PER", 0x0040000, 0x62, 0, PutPCRel16 }, { "PHA", 0x0000001, 0x48, 0, PutAll }, { "PHB", 0x0000001, 0x8b, 0, PutAll }, { "PHD", 0x0000001, 0x0b, 0, PutAll }, { "PHK", 0x0000001, 0x4b, 0, PutAll }, { "PHP", 0x0000001, 0x08, 0, PutAll }, { "PHX", 0x0000001, 0xda, 0, PutAll }, { "PHY", 0x0000001, 0x5a, 0, PutAll }, { "PLA", 0x0000001, 0x68, 0, PutAll }, { "PLB", 0x0000001, 0xab, 0, PutAll }, { "PLD", 0x0000001, 0x2b, 0, PutAll }, { "PLP", 0x0000001, 0x28, 0, PutAll }, { "PLX", 0x0000001, 0xfa, 0, PutAll }, { "PLY", 0x0000001, 0x7a, 0, PutAll }, { "REP", 0x0800000, 0xc2, 1, PutREP }, { "ROL", 0x000006F, 0x22, 1, PutAll }, { "ROR", 0x000006F, 0x62, 1, PutAll }, { "RTI", 0x0000001, 0x40, 0, PutAll }, { "RTL", 0x0000001, 0x6b, 0, PutAll }, { "RTS", 0x0000001, 0x60, 0, PutRTS }, { "SBC", 0x0b8f6fc, 0xe0, 0, PutAll }, { "SEC", 0x0000001, 0x38, 0, PutAll }, { "SED", 0x0000001, 0xf8, 0, PutAll }, { "SEI", 0x0000001, 0x78, 0, PutAll }, { "SEP", 0x0800000, 0xe2, 1, PutSEP }, { "STA", 0x018f6fc, 0x80, 0, PutAll }, { "STP", 0x0000001, 0xdb, 0, PutAll }, { "STX", 0x000010c, 0x82, 1, PutAll }, { "STY", 0x000002c, 0x80, 1, PutAll }, { "STZ", 0x000006c, 0x04, 5, PutAll }, { "SWA", 0x0000001, 0xeb, 0, PutAll }, /* == XBA */ { "TAD", 0x0000001, 0x5b, 0, PutAll }, /* == TCD */ { "TAS", 0x0000001, 0x1b, 0, PutAll }, /* == TCS */ { "TAX", 0x0000001, 0xaa, 0, PutAll }, { "TAY", 0x0000001, 0xa8, 0, PutAll }, { "TCD", 0x0000001, 0x5b, 0, PutAll }, { "TCS", 0x0000001, 0x1b, 0, PutAll }, { "TDA", 0x0000001, 0x7b, 0, PutAll }, /* == TDC */ { "TDC", 0x0000001, 0x7b, 0, PutAll }, { "TRB", 0x000000c, 0x10, 1, PutAll }, { "TSA", 0x0000001, 0x3b, 0, PutAll }, /* == TSC */ { "TSB", 0x000000c, 0x00, 1, PutAll }, { "TSC", 0x0000001, 0x3b, 0, PutAll }, { "TSX", 0x0000001, 0xba, 0, PutAll }, { "TXA", 0x0000001, 0x8a, 0, PutAll }, { "TXS", 0x0000001, 0x9a, 0, PutAll }, { "TXY", 0x0000001, 0x9b, 0, PutAll }, { "TYA", 0x0000001, 0x98, 0, PutAll }, { "TYX", 0x0000001, 0xbb, 0, PutAll }, { "WAI", 0x0000001, 0xcb, 0, PutAll }, { "XBA", 0x0000001, 0xeb, 0, PutAll }, { "XCE", 0x0000001, 0xfb, 0, PutAll } } }; #ifdef SUNPLUS /* Table for the SUNPLUS CPU */ #include "sunplus.inc" #endif /* Instruction table for the SWEET16 pseudo CPU */ static const struct { unsigned Count; InsDesc Ins[26]; } InsTabSweet16 = { sizeof (InsTabSweet16.Ins) / sizeof (InsTabSweet16.Ins[0]), { { "ADD", AMSW16_REG, 0xA0, 0, PutSweet16 }, { "BC", AMSW16_BRA, 0x03, 0, PutSweet16Branch }, { "BK", AMSW16_IMP, 0x0A, 0, PutSweet16 }, { "BM", AMSW16_BRA, 0x05, 0, PutSweet16Branch }, { "BM1", AMSW16_BRA, 0x08, 0, PutSweet16Branch }, { "BNC", AMSW16_BRA, 0x02, 0, PutSweet16Branch }, { "BNM1", AMSW16_BRA, 0x09, 0, PutSweet16Branch }, { "BNZ", AMSW16_BRA, 0x07, 0, PutSweet16Branch }, { "BP", AMSW16_BRA, 0x04, 0, PutSweet16Branch }, { "BR", AMSW16_BRA, 0x01, 0, PutSweet16Branch }, { "BS", AMSW16_BRA, 0x0B, 0, PutSweet16Branch }, { "BZ", AMSW16_BRA, 0x06, 0, PutSweet16Branch }, { "CPR", AMSW16_REG, 0xD0, 0, PutSweet16 }, { "DCR", AMSW16_REG, 0xF0, 0, PutSweet16 }, { "INR", AMSW16_REG, 0xE0, 0, PutSweet16 }, { "LD", AMSW16_REG | AMSW16_IND, 0x00, 1, PutSweet16 }, { "LDD", AMSW16_IND, 0x60, 0, PutSweet16 }, { "POP", AMSW16_IND, 0x80, 0, PutSweet16 }, { "POPD", AMSW16_IND, 0xC0, 0, PutSweet16 }, { "RS", AMSW16_IMP, 0x0B, 0, PutSweet16 }, { "RTN", AMSW16_IMP, 0x00, 0, PutSweet16 }, { "SET", AMSW16_IMM, 0x10, 0, PutSweet16 }, { "ST", AMSW16_REG | AMSW16_IND, 0x10, 1, PutSweet16 }, { "STD", AMSW16_IND, 0x70, 0, PutSweet16 }, { "STP", AMSW16_IND, 0x90, 0, PutSweet16 }, { "SUB", AMSW16_REG, 0xB0, 0, PutSweet16 }, } }; /* Instruction table for the HuC6280 (the CPU used in the PC engine) */ static const struct { unsigned Count; InsDesc Ins[135]; } InsTabHuC6280 = { sizeof (InsTabHuC6280.Ins) / sizeof (InsTabHuC6280.Ins[0]), { { "ADC", 0x080A66C, 0x60, 0, PutAll }, { "AND", 0x080A66C, 0x20, 0, PutAll }, { "ASL", 0x000006e, 0x02, 1, PutAll }, { "BBR0", 0x0000000, 0x0F, 0, PutBitBranch }, { "BBR1", 0x0000000, 0x1F, 0, PutBitBranch }, { "BBR2", 0x0000000, 0x2F, 0, PutBitBranch }, { "BBR3", 0x0000000, 0x3F, 0, PutBitBranch }, { "BBR4", 0x0000000, 0x4F, 0, PutBitBranch }, { "BBR5", 0x0000000, 0x5F, 0, PutBitBranch }, { "BBR6", 0x0000000, 0x6F, 0, PutBitBranch }, { "BBR7", 0x0000000, 0x7F, 0, PutBitBranch }, { "BBS0", 0x0000000, 0x8F, 0, PutBitBranch }, { "BBS1", 0x0000000, 0x9F, 0, PutBitBranch }, { "BBS2", 0x0000000, 0xAF, 0, PutBitBranch }, { "BBS3", 0x0000000, 0xBF, 0, PutBitBranch }, { "BBS4", 0x0000000, 0xCF, 0, PutBitBranch }, { "BBS5", 0x0000000, 0xDF, 0, PutBitBranch }, { "BBS6", 0x0000000, 0xEF, 0, PutBitBranch }, { "BBS7", 0x0000000, 0xFF, 0, PutBitBranch }, { "BCC", 0x0020000, 0x90, 0, PutPCRel8 }, { "BCS", 0x0020000, 0xb0, 0, PutPCRel8 }, { "BEQ", 0x0020000, 0xf0, 0, PutPCRel8 }, { "BIT", 0x0A0006C, 0x00, 2, PutAll }, { "BMI", 0x0020000, 0x30, 0, PutPCRel8 }, { "BNE", 0x0020000, 0xd0, 0, PutPCRel8 }, { "BPL", 0x0020000, 0x10, 0, PutPCRel8 }, { "BRA", 0x0020000, 0x80, 0, PutPCRel8 }, { "BRK", 0x0000001, 0x00, 0, PutAll }, { "BSR", 0x0020000, 0x44, 0, PutPCRel8 }, { "BVC", 0x0020000, 0x50, 0, PutPCRel8 }, { "BVS", 0x0020000, 0x70, 0, PutPCRel8 }, { "CLA", 0x0000001, 0x62, 0, PutAll }, { "CLC", 0x0000001, 0x18, 0, PutAll }, { "CLD", 0x0000001, 0xd8, 0, PutAll }, { "CLI", 0x0000001, 0x58, 0, PutAll }, { "CLV", 0x0000001, 0xb8, 0, PutAll }, { "CLX", 0x0000001, 0x82, 0, PutAll }, { "CLY", 0x0000001, 0xc2, 0, PutAll }, { "CMP", 0x080A66C, 0xc0, 0, PutAll }, { "CPX", 0x080000C, 0xe0, 1, PutAll }, { "CPY", 0x080000C, 0xc0, 1, PutAll }, { "CSH", 0x0000001, 0xd4, 0, PutAll }, { "CSL", 0x0000001, 0x54, 0, PutAll }, { "DEA", 0x0000001, 0x00, 3, PutAll }, /* == DEC */ { "DEC", 0x000006F, 0x00, 3, PutAll }, { "DEX", 0x0000001, 0xca, 0, PutAll }, { "DEY", 0x0000001, 0x88, 0, PutAll }, { "EOR", 0x080A66C, 0x40, 0, PutAll }, { "INA", 0x0000001, 0x00, 4, PutAll }, /* == INC */ { "INC", 0x000006f, 0x00, 4, PutAll }, { "INX", 0x0000001, 0xe8, 0, PutAll }, { "INY", 0x0000001, 0xc8, 0, PutAll }, { "JMP", 0x0010808, 0x4c, 6, PutAll }, { "JSR", 0x0000008, 0x20, 7, PutAll }, { "LDA", 0x080A66C, 0xa0, 0, PutAll }, { "LDX", 0x080030C, 0xa2, 1, PutAll }, { "LDY", 0x080006C, 0xa0, 1, PutAll }, { "LSR", 0x000006F, 0x42, 1, PutAll }, { "NOP", 0x0000001, 0xea, 0, PutAll }, { "ORA", 0x080A66C, 0x00, 0, PutAll }, { "PHA", 0x0000001, 0x48, 0, PutAll }, { "PHP", 0x0000001, 0x08, 0, PutAll }, { "PHX", 0x0000001, 0xda, 0, PutAll }, { "PHY", 0x0000001, 0x5a, 0, PutAll }, { "PLA", 0x0000001, 0x68, 0, PutAll }, { "PLP", 0x0000001, 0x28, 0, PutAll }, { "PLX", 0x0000001, 0xfa, 0, PutAll }, { "PLY", 0x0000001, 0x7a, 0, PutAll }, { "RMB0", 0x0000004, 0x07, 1, PutAll }, { "RMB1", 0x0000004, 0x17, 1, PutAll }, { "RMB2", 0x0000004, 0x27, 1, PutAll }, { "RMB3", 0x0000004, 0x37, 1, PutAll }, { "RMB4", 0x0000004, 0x47, 1, PutAll }, { "RMB5", 0x0000004, 0x57, 1, PutAll }, { "RMB6", 0x0000004, 0x67, 1, PutAll }, { "RMB7", 0x0000004, 0x77, 1, PutAll }, { "ROL", 0x000006F, 0x22, 1, PutAll }, { "ROR", 0x000006F, 0x62, 1, PutAll }, { "RTI", 0x0000001, 0x40, 0, PutAll }, { "RTS", 0x0000001, 0x60, 0, PutAll }, { "SBC", 0x080A66C, 0xe0, 0, PutAll }, { "SAX", 0x0000001, 0x22, 0, PutAll }, { "SAY", 0x0000001, 0x42, 0, PutAll }, { "SEC", 0x0000001, 0x38, 0, PutAll }, { "SED", 0x0000001, 0xf8, 0, PutAll }, { "SEI", 0x0000001, 0x78, 0, PutAll }, { "SET", 0x0000001, 0xf4, 0, PutAll }, { "SMB0", 0x0000004, 0x87, 1, PutAll }, { "SMB1", 0x0000004, 0x97, 1, PutAll }, { "SMB2", 0x0000004, 0xA7, 1, PutAll }, { "SMB3", 0x0000004, 0xB7, 1, PutAll }, { "SMB4", 0x0000004, 0xC7, 1, PutAll }, { "SMB5", 0x0000004, 0xD7, 1, PutAll }, { "SMB6", 0x0000004, 0xE7, 1, PutAll }, { "SMB7", 0x0000004, 0xF7, 1, PutAll }, { "ST0", 0x0800000, 0x03, 1, PutAll }, { "ST1", 0x0800000, 0x13, 1, PutAll }, { "ST2", 0x0800000, 0x23, 1, PutAll }, { "STA", 0x000A66C, 0x80, 0, PutAll }, { "STX", 0x000010c, 0x82, 1, PutAll }, { "STY", 0x000002c, 0x80, 1, PutAll }, { "STZ", 0x000006c, 0x04, 5, PutAll }, { "SXY", 0x0000001, 0x02, 0, PutAll }, { "TAI", 0x2000000, 0xf3, 0, PutBlockTransfer }, { "TAM", 0x0800000, 0x53, 1, PutAll }, { "TAM0", 0x0000001, 0x01, 0, PutTAMn}, { "TAM1", 0x0000001, 0x02, 0, PutTAMn}, { "TAM2", 0x0000001, 0x04, 0, PutTAMn}, { "TAM3", 0x0000001, 0x08, 0, PutTAMn}, { "TAM4", 0x0000001, 0x10, 0, PutTAMn}, { "TAM5", 0x0000001, 0x20, 0, PutTAMn}, { "TAM6", 0x0000001, 0x40, 0, PutTAMn}, { "TAM7", 0x0000001, 0x80, 0, PutTAMn}, { "TAX", 0x0000001, 0xaa, 0, PutAll }, { "TAY", 0x0000001, 0xa8, 0, PutAll }, { "TDD", 0x2000000, 0xc3, 0, PutBlockTransfer }, { "TIA", 0x2000000, 0xe3, 0, PutBlockTransfer }, { "TII", 0x2000000, 0x73, 0, PutBlockTransfer }, { "TIN", 0x2000000, 0xD3, 0, PutBlockTransfer }, { "TMA", 0x0800000, 0x43, 1, PutTMA }, { "TMA0", 0x0000001, 0x01, 0, PutTMAn}, { "TMA1", 0x0000001, 0x02, 0, PutTMAn}, { "TMA2", 0x0000001, 0x04, 0, PutTMAn}, { "TMA3", 0x0000001, 0x08, 0, PutTMAn}, { "TMA4", 0x0000001, 0x10, 0, PutTMAn}, { "TMA5", 0x0000001, 0x20, 0, PutTMAn}, { "TMA6", 0x0000001, 0x40, 0, PutTMAn}, { "TMA7", 0x0000001, 0x80, 0, PutTMAn}, { "TRB", 0x000000c, 0x10, 1, PutAll }, { "TSB", 0x000000c, 0x00, 1, PutAll }, { "TST", 0x000006c, 0x83, 9, PutTST }, { "TSX", 0x0000001, 0xba, 0, PutAll }, { "TXA", 0x0000001, 0x8a, 0, PutAll }, { "TXS", 0x0000001, 0x9a, 0, PutAll }, { "TYA", 0x0000001, 0x98, 0, PutAll } } }; /* An array with instruction tables */ static const InsTable* InsTabs[CPU_COUNT] = { (const InsTable*) &InsTabNone, (const InsTable*) &InsTab6502, (const InsTable*) &InsTab6502X, (const InsTable*) &InsTab65SC02, (const InsTable*) &InsTab65C02, (const InsTable*) &InsTab65816, #ifdef SUNPLUS (const InsTable*) &InsTabSunPlus, #else 0, #endif (const InsTable*) &InsTabSweet16, (const InsTable*) &InsTabHuC6280, 0, /* Mitsubishi 740 */ }; const InsTable* InsTab = (const InsTable*) &InsTab6502; /* Table to build the effective 65xx opcode from a base opcode and an * addressing mode. */ static unsigned char EATab[10][AM65I_COUNT] = { { /* Table 0 */ 0x00, 0x00, 0x05, 0x0D, 0x0F, 0x15, 0x1D, 0x1F, 0x00, 0x19, 0x12, 0x00, 0x07, 0x11, 0x17, 0x01, 0x00, 0x00, 0x00, 0x03, 0x13, 0x09, 0x00, 0x09, 0x00, 0x00 }, { /* Table 1 */ 0x08, 0x08, 0x04, 0x0C, 0x00, 0x14, 0x1C, 0x00, 0x14, 0x1C, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* Table 2 */ 0x00, 0x00, 0x24, 0x2C, 0x0F, 0x34, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x89, 0x00, 0x00, 0x00, 0x00 }, { /* Table 3 */ 0x3A, 0x3A, 0xC6, 0xCE, 0x00, 0xD6, 0xDE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* Table 4 */ 0x1A, 0x1A, 0xE6, 0xEE, 0x00, 0xF6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* Table 5 */ 0x00, 0x00, 0x60, 0x98, 0x00, 0x70, 0x9E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* Table 6 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* Table 7 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { /* Table 8 */ 0x00, 0x40, 0x01, 0x41, 0x00, 0x09, 0x49, 0x00, 0x00, 0x00, 0x00, 0x51, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00 }, { /* Table 9 */ 0x00, 0x00, 0x00, 0x10, 0x00, 0x20, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, }; /* Table to build the effective SWEET16 opcode from a base opcode and an * addressing mode. */ static unsigned char Sweet16EATab[2][AMSW16I_COUNT] = { { /* Table 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, }, { /* Table 1 */ 0x00, 0x00, 0x00, 0x40, 0x20, }, }; /* Table that encodes the additional bytes for each 65xx instruction */ unsigned char ExtBytes[AM65I_COUNT] = { 0, /* Implicit */ 0, /* Accu */ 1, /* Direct */ 2, /* Absolute */ 3, /* Absolute long */ 1, /* Direct,X */ 2, /* Absolute,X */ 3, /* Absolute long,X */ 1, /* Direct,Y */ 2, /* Absolute,Y */ 1, /* (Direct) */ 2, /* (Absolute) */ 1, /* [Direct] */ 1, /* (Direct),Y */ 1, /* [Direct],Y */ 1, /* (Direct,X) */ 2, /* (Absolute,X) */ 1, /* Relative short */ 2, /* Relative long */ 1, /* r,s */ 1, /* (r,s),y */ 1, /* Immidiate accu */ 1, /* Immidiate index */ 1, /* Immidiate byte */ 2, /* Blockmove (65816) */ 7, /* Block transfer (HuC6280) */ }; /* Table that encodes the additional bytes for each SWEET16 instruction */ static unsigned char Sweet16ExtBytes[AMSW16I_COUNT] = { 0, /* AMSW16_IMP */ 1, /* AMSW16_BRA */ 2, /* AMSW16_IMM */ 0, /* AMSW16_IND */ 0, /* AMSW16_REG */ }; /*****************************************************************************/ /* Handler functions for 6502 derivates */ /*****************************************************************************/ static int EvalEA (const InsDesc* Ins, EffAddr* A) /* Evaluate the effective address. All fields in A will be valid after calling * this function. The function returns true on success and false on errors. */ { /* Get the set of possible addressing modes */ GetEA (A); /* From the possible addressing modes, remove the ones that are invalid * for this instruction or CPU. */ A->AddrModeSet &= Ins->AddrMode; /* If we have an expression, check it and remove any addressing modes that * are too small for the expression size. Since we have to study the * expression anyway, do also replace it by a simpler one if possible. */ if (A->Expr) { ExprDesc ED; ED_Init (&ED); /* Study the expression */ StudyExpr (A->Expr, &ED); /* Simplify it if possible */ A->Expr = SimplifyExpr (A->Expr, &ED); if (ED.AddrSize == ADDR_SIZE_DEFAULT) { /* We don't know how big the expression is. If the instruction * allows just one addressing mode, assume this as address size * for the expression. Otherwise assume the default address size * for data. */ if ((A->AddrModeSet & ~AM65_ALL_ZP) == 0) { ED.AddrSize = ADDR_SIZE_ZP; } else if ((A->AddrModeSet & ~AM65_ALL_ABS) == 0) { ED.AddrSize = ADDR_SIZE_ABS; } else if ((A->AddrModeSet & ~AM65_ALL_FAR) == 0) { ED.AddrSize = ADDR_SIZE_FAR; } else { ED.AddrSize = DataAddrSize; /* If the default address size of the data segment is unequal * to zero page addressing, but zero page addressing is * allowed by the instruction, mark all symbols in the * expression tree. This mark will be checked at end of * assembly, and a warning is issued, if a zero page symbol * was guessed wrong here. */ if (ED.AddrSize > ADDR_SIZE_ZP && (A->AddrModeSet & AM65_SET_ZP)) { ExprGuessedAddrSize (A->Expr, ADDR_SIZE_ZP); } } } /* Check the size */ switch (ED.AddrSize) { case ADDR_SIZE_ABS: A->AddrModeSet &= ~AM65_SET_ZP; break; case ADDR_SIZE_FAR: A->AddrModeSet &= ~(AM65_SET_ZP | AM65_SET_ABS); break; } /* Free any resource associated with the expression desc */ ED_Done (&ED); } /* Check if we have any adressing modes left */ if (A->AddrModeSet == 0) { Error ("Illegal addressing mode"); return 0; } A->AddrMode = BitFind (A->AddrModeSet); A->AddrModeBit = (0x01UL << A->AddrMode); /* If the instruction has a one byte operand and immediate addressing is * allowed but not used, check for an operand expression in the form * <label or >label, where label is a far or absolute label. If found, * emit a warning. This warning protects against a typo, where the '#' * for the immediate operand is omitted. */ if (A->Expr && (Ins->AddrMode & AM65_ALL_IMM) && (A->AddrModeSet & (AM65_DIR | AM65_ABS | AM65_ABS_LONG)) && ExtBytes[A->AddrMode] == 1) { /* Found, check the expression */ ExprNode* Left = A->Expr->Left; if ((A->Expr->Op == EXPR_BYTE0 || A->Expr->Op == EXPR_BYTE1) && Left->Op == EXPR_SYMBOL && GetSymAddrSize (Left->V.Sym) != ADDR_SIZE_ZP) { /* Output a warning */ Warning (1, "Suspicious address expression"); } } /* Build the opcode */ A->Opcode = Ins->BaseCode | EATab[Ins->ExtCode][A->AddrMode]; /* If feature force_range is active, and we have immediate addressing mode, * limit the expression to the maximum possible value. */ if (A->AddrMode == AM65I_IMM_ACCU || A->AddrMode == AM65I_IMM_INDEX || A->AddrMode == AM65I_IMM_IMPLICIT) { if (ForceRange && A->Expr) { A->Expr = MakeBoundedExpr (A->Expr, ExtBytes[A->AddrMode]); } } /* Success */ return 1; } static void EmitCode (EffAddr* A) /* Output code for the data in A */ { /* Check how many extension bytes are needed and output the instruction */ switch (ExtBytes[A->AddrMode]) { case 0: Emit0 (A->Opcode); break; case 1: Emit1 (A->Opcode, A->Expr); break; case 2: if (CPU == CPU_65816 && (A->AddrModeBit & (AM65_ABS | AM65_ABS_X | AM65_ABS_Y))) { /* This is a 16 bit mode that uses an address. If in 65816, * mode, force this address into 16 bit range to allow * addressing inside a 64K segment. */ Emit2 (A->Opcode, GenWordExpr (A->Expr)); } else { Emit2 (A->Opcode, A->Expr); } break; case 3: /* Far argument */ Emit3 (A->Opcode, A->Expr); break; default: Internal ("Invalid operand byte count: %u", ExtBytes[A->AddrMode]); } } static long PutImmed8 (const InsDesc* Ins) /* Parse and emit an immediate 8 bit instruction. Return the value of the * operand if it's available and const. */ { EffAddr A; long Val = -1; /* Evaluate the addressing mode */ if (EvalEA (Ins, &A) == 0) { /* An error occurred */ return -1L; } /* If we have an expression and it's const, get it's value */ if (A.Expr) { (void) IsConstExpr (A.Expr, &Val); } /* Check how many extension bytes are needed and output the instruction */ switch (ExtBytes[A.AddrMode]) { case 1: Emit1 (A.Opcode, A.Expr); break; default: Internal ("Invalid operand byte count: %u", ExtBytes[A.AddrMode]); } /* Return the expression value */ return Val; } static void PutPCRel8 (const InsDesc* Ins) /* Handle branches with a 8 bit distance */ { EmitPCRel (Ins->BaseCode, GenBranchExpr (2), 1); } static void PutPCRel16 (const InsDesc* Ins) /* Handle branches with an 16 bit distance and PER */ { EmitPCRel (Ins->BaseCode, GenBranchExpr (3), 2); } static void PutBlockMove (const InsDesc* Ins) /* Handle the blockmove instructions (65816) */ { Emit0 (Ins->BaseCode); EmitByte (Expression ()); ConsumeComma (); EmitByte (Expression ()); } static void PutBlockTransfer (const InsDesc* Ins) /* Handle the block transfer instructions (HuC6280) */ { Emit0 (Ins->BaseCode); EmitWord (Expression ()); ConsumeComma (); EmitWord (Expression ()); ConsumeComma (); EmitWord (Expression ()); } static void PutBitBranch (const InsDesc* Ins) /* Handle 65C02 branch on bit condition */ { Emit0 (Ins->BaseCode); EmitByte (Expression ()); ConsumeComma (); EmitSigned (GenBranchExpr (1), 1); } static void PutREP (const InsDesc* Ins) /* Emit a REP instruction, track register sizes */ { /* Use the generic handler */ long Val = PutImmed8 (Ins); /* We track the status only for the 816 CPU and in smart mode */ if (CPU == CPU_65816 && SmartMode) { /* Check the range for Val. */ if (Val < 0) { /* We had an error */ Warning (1, "Cannot track processor status byte"); } else { if (Val & 0x10) { /* Index registers to 16 bit */ ExtBytes[AM65I_IMM_INDEX] = 2; } if (Val & 0x20) { /* Accu to 16 bit */ ExtBytes[AM65I_IMM_ACCU] = 2; } } } } static void PutSEP (const InsDesc* Ins) /* Emit a SEP instruction (65816), track register sizes */ { /* Use the generic handler */ long Val = PutImmed8 (Ins); /* We track the status only for the 816 CPU and in smart mode */ if (CPU == CPU_65816 && SmartMode) { /* Check the range for Val. */ if (Val < 0) { /* We had an error */ Warning (1, "Cannot track processor status byte"); } else { if (Val & 0x10) { /* Index registers to 8 bit */ ExtBytes[AM65I_IMM_INDEX] = 1; } if (Val & 0x20) { /* Accu to 8 bit */ ExtBytes[AM65I_IMM_ACCU] = 1; } } } } static void PutTAMn (const InsDesc* Ins) /* Emit a TAMn instruction (HuC6280). Since this is a two byte instruction with * implicit addressing mode, the opcode byte in the table is actually the * second operand byte. The TAM instruction is the more generic form, it takes * an immediate argument. */ { /* Emit the TAM opcode itself */ Emit0 (0x53); /* Emit the argument, which is the opcode from the table */ Emit0 (Ins->BaseCode); } static void PutTMA (const InsDesc* Ins) /* Emit a TMA instruction (HuC6280) with an immediate argument. Only one bit * in the argument byte may be set. */ { /* Use the generic handler */ long Val = PutImmed8 (Ins); /* Check the range for Val. */ if (Val < 0) { /* We had an error */ Warning (1, "Cannot check argument of TMA instruction"); } else { /* Make sure just one bit is set */ if ((Val & (Val - 1)) != 0) { Error ("Argument to TAM must be a power of two"); } } } static void PutTMAn (const InsDesc* Ins) /* Emit a TMAn instruction (HuC6280). Since this is a two byte instruction with * implicit addressing mode, the opcode byte in the table is actually the * second operand byte. The TAM instruction is the more generic form, it takes * an immediate argument. */ { /* Emit the TMA opcode itself */ Emit0 (0x43); /* Emit the argument, which is the opcode from the table */ Emit0 (Ins->BaseCode); } static void PutTST (const InsDesc* Ins) /* Emit a TST instruction (HuC6280). */ { ExprNode* Arg1; EffAddr A; /* The first argument is always an immediate byte */ if (CurTok.Tok != TOK_HASH) { ErrorSkip ("Invalid addressing mode"); return; } NextTok (); Arg1 = Expression (); /* Second argument follows */ ConsumeComma (); /* For the second argument, we use the standard function */ if (EvalEA (Ins, &A)) { /* No error, output code */ Emit1 (A.Opcode, Arg1); /* Check how many extension bytes are needed and output the instruction */ switch (ExtBytes[A.AddrMode]) { case 1: EmitByte (A.Expr); break; case 2: EmitWord (A.Expr); break; } } } static void PutJMP (const InsDesc* Ins) /* Handle the jump instruction for the 6502. Problem is that these chips have * a bug: If the address crosses a page, the upper byte gets not corrected and * the instruction will fail. The PutJmp function will add a linker assertion * to check for this case and is otherwise identical to PutAll. */ { EffAddr A; /* Evaluate the addressing mode used */ if (EvalEA (Ins, &A)) { /* Check for indirect addressing */ if (A.AddrModeBit & AM65_ABS_IND) { /* Compare the low byte of the expression to 0xFF to check for * a page cross. Be sure to use a copy of the expression otherwise * things will go weird later. */ ExprNode* E = GenNE (GenByteExpr (CloneExpr (A.Expr)), 0xFF); /* Generate the message */ unsigned Msg = GetStringId ("\"jmp (abs)\" across page border"); /* Generate the assertion */ AddAssertion (E, ASSERT_ACT_WARN, Msg); } /* No error, output code */ EmitCode (&A); } } static void PutRTS (const InsDesc* Ins attribute ((unused))) /* Handle the RTS instruction for the 816. In smart mode emit a RTL opcode if * the enclosing scope is FAR. */ { if (SmartMode && CurrentScope->AddrSize == ADDR_SIZE_FAR) { Emit0 (0x6B); /* RTL */ } else { Emit0 (0x60); /* RTS */ } } static void PutAll (const InsDesc* Ins) /* Handle all other instructions */ { EffAddr A; /* Evaluate the addressing mode used */ if (EvalEA (Ins, &A)) { /* No error, output code */ EmitCode (&A); } } /*****************************************************************************/ /* Handler functions for SWEET16 */ /*****************************************************************************/ static void PutSweet16 (const InsDesc* Ins) /* Handle a generic sweet16 instruction */ { EffAddr A; /* Evaluate the addressing mode used */ GetSweet16EA (&A); /* From the possible addressing modes, remove the ones that are invalid * for this instruction or CPU. */ A.AddrModeSet &= Ins->AddrMode; /* Check if we have any adressing modes left */ if (A.AddrModeSet == 0) { Error ("Illegal addressing mode"); return; } A.AddrMode = BitFind (A.AddrModeSet); A.AddrModeBit = (0x01UL << A.AddrMode); /* Build the opcode */ A.Opcode = Ins->BaseCode | Sweet16EATab[Ins->ExtCode][A.AddrMode] | A.Reg; /* Check how many extension bytes are needed and output the instruction */ switch (Sweet16ExtBytes[A.AddrMode]) { case 0: Emit0 (A.Opcode); break; case 1: Emit1 (A.Opcode, A.Expr); break; case 2: Emit2 (A.Opcode, A.Expr); break; default: Internal ("Invalid operand byte count: %u", Sweet16ExtBytes[A.AddrMode]); } } static void PutSweet16Branch (const InsDesc* Ins) /* Handle a sweet16 branch instruction */ { EmitPCRel (Ins->BaseCode, GenBranchExpr (2), 1); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static int CmpName (const void* Key, const void* Instr) /* Compare function for bsearch */ { return strcmp ((const char*)Key, ((const InsDesc*) Instr)->Mnemonic); } void SetCPU (cpu_t NewCPU) /* Set a new CPU */ { /* Make sure the parameter is correct */ CHECK (NewCPU < CPU_COUNT); /* Check if we have support for the new CPU, if so, use it */ if (NewCPU != CPU_UNKNOWN && InsTabs[NewCPU]) { CPU = NewCPU; InsTab = InsTabs[CPU]; } else { Error ("CPU not supported"); } } cpu_t GetCPU (void) /* Return the current CPU */ { return CPU; } int FindInstruction (const StrBuf* Ident) /* Check if Ident is a valid mnemonic. If so, return the index in the * instruction table. If not, return -1. */ { unsigned I; const InsDesc* ID; char Key[sizeof (ID->Mnemonic)]; /* Shortcut for the "none" CPU: If there are no instructions to search * for, bail out early. */ if (InsTab->Count == 0) { /* Not found */ return -1; } /* Make a copy, and uppercase that copy */ I = 0; while (I < SB_GetLen (Ident)) { /* If the identifier is longer than the longest mnemonic, it cannot * be one. */ if (I >= sizeof (Key) - 1) { /* Not found, no need for further action */ return -1; } Key[I] = toupper ((unsigned char)SB_AtUnchecked (Ident, I)); ++I; } Key[I] = '\0'; /* Search for the key */ ID = bsearch (Key, InsTab->Ins, InsTab->Count, sizeof (InsDesc), CmpName); if (ID == 0) { /* Not found */ return -1; } else { /* Found, return the entry */ return ID - InsTab->Ins; } } void HandleInstruction (unsigned Index) /* Handle the mnemonic with the given index */ { /* Safety check */ PRECONDITION (Index < InsTab->Count); /* Skip the mnemonic token */ NextTok (); /* Call the handler */ InsTab->Ins[Index].Emit (&InsTab->Ins[Index]); }
933
./cc65/src/ca65/istack.c
/*****************************************************************************/ /* */ /* istack.c */ /* */ /* Input stack for the scanner */ /* */ /* */ /* */ /* (C) 2000-2003 Ullrich von Bassewitz */ /* R÷merstra▀e 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" #include "xmalloc.h" /* ca65 */ #include "error.h" #include "istack.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Size of the stack (== maximum nested macro or repeat count) */ #define ISTACK_MAX 256 /* Structure holding a stack element */ typedef struct IElement IElement; struct IElement { IElement* Next; /* Next stack element */ int (*Func)(void*); /* Function called for input */ void* Data; /* User data given as argument */ const char* Desc; /* Description */ }; /* The stack */ static IElement* IStack = 0; /* Input stack pointer */ static unsigned ICount = 0; /* Number of items on the stack */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ void PushInput (int (*Func) (void*), void* Data, const char* Desc) /* Push an input function onto the input stack */ { IElement* E; /* Check for a stack overflow */ if (ICount > ISTACK_MAX) { Fatal ("Maximum input stack nesting exceeded"); } /* Create a new stack element */ E = xmalloc (sizeof (*E)); /* Initialize it */ E->Func = Func; E->Data = Data; E->Desc = Desc; /* Push it */ E->Next = IStack; IStack = E; } void PopInput (void) /* Pop the current input function from the input stack */ { IElement* E; /* We cannot pop from an empty stack */ PRECONDITION (IStack != 0); /* Remember the last element */ E = IStack; /* Pop it */ IStack = IStack->Next; /* And delete it */ xfree (E); } int InputFromStack (void) /* Try to get input from the input stack. Return true if we had such input, * return false otherwise. */ { /* Repeatedly call the TOS routine until we have a token or if run out of * routines. */ while (IStack) { if (IStack->Func (IStack->Data) != 0) { /* We have a token */ return 1; } } /* Nothing is on the stack */ return 0; } int HavePushedInput (void) /* Return true if we have stacked input available, return false if not */ { return (IStack != 0); } void CheckInputStack (void) /* Called from the scanner before closing an input file. Will check for any * stuff on the input stack. */ { if (IStack) { Error ("Open %s", IStack->Desc); } }
934
./cc65/src/ca65/sizeof.c
/*****************************************************************************/ /* */ /* sizeof.c */ /* */ /* Handle sizes of types and data */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewit */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "addrsize.h" /* ca65 */ #include "expr.h" #include "sizeof.h" #include "symtab.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* The name of the symbol used to encode the size. The name of this entry is * choosen so that it cannot be accessed by the user. */ static const StrBuf SizeEntryName = LIT_STRBUF_INITIALIZER (".size"); /*****************************************************************************/ /* Code */ /*****************************************************************************/ int IsSizeOfSymbol (const SymEntry* Sym) /* Return true if the given symbol is the one that encodes the size of some * entity. Sym may also be a NULL pointer in which case false is returned. */ { return (Sym != 0 && SB_Compare (GetSymName (Sym), &SizeEntryName) == 0); } SymEntry* FindSizeOfScope (SymTable* Scope) /* Get the size of a scope. The function returns the symbol table entry that * encodes the size or NULL if there is no such entry. */ { return SymFind (Scope, &SizeEntryName, SYM_FIND_EXISTING); } SymEntry* FindSizeOfSymbol (SymEntry* Sym) /* Get the size of a symbol table entry. The function returns the symbol table * entry that encodes the size of the symbol or NULL if there is no such entry. */ { return SymFindLocal (Sym, &SizeEntryName, SYM_FIND_EXISTING); } SymEntry* GetSizeOfScope (SymTable* Scope) /* Get the size of a scope. The function returns the symbol table entry that * encodes the size, and will create a new entry if it does not exist. */ { return SymFind (Scope, &SizeEntryName, SYM_ALLOC_NEW); } SymEntry* GetSizeOfSymbol (SymEntry* Sym) /* Get the size of a symbol table entry. The function returns the symbol table * entry that encodes the size of the symbol and will create a new one if it * does not exist. */ { return SymFindLocal (Sym, &SizeEntryName, SYM_ALLOC_NEW); } SymEntry* DefSizeOfScope (SymTable* Scope, long Size) /* Define the size of a scope and return the size symbol */ { SymEntry* SizeSym = GetSizeOfScope (Scope); SymDef (SizeSym, GenLiteralExpr (Size), ADDR_SIZE_DEFAULT, SF_NONE); return SizeSym; } SymEntry* DefSizeOfSymbol (SymEntry* Sym, long Size) /* Define the size of a symbol and return the size symbol */ { SymEntry* SizeSym = GetSizeOfSymbol (Sym); SymDef (SizeSym, GenLiteralExpr (Size), ADDR_SIZE_DEFAULT, SF_NONE); return SizeSym; }
935
./cc65/src/ca65/feature.c
/*****************************************************************************/ /* */ /* feature.c */ /* */ /* Subroutines for the emulation features */ /* */ /* */ /* */ /* (C) 2000-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* ca65 */ #include "global.h" #include "feature.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Names of the features */ static const char* FeatureKeys[FEAT_COUNT] = { "dollar_is_pc", "labels_without_colons", "loose_string_term", "loose_char_term", "at_in_identifiers", "dollar_in_identifiers", "leading_dot_in_identifiers", "org_per_seg", "pc_assignment", "missing_char_term", "ubiquitous_idents", "c_comments", "force_range", "underline_in_numbers", }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ feature_t FindFeature (const StrBuf* Key) /* Find the feature in a table and return the corresponding enum value. If the * feature is invalid, return FEAT_UNKNOWN. */ { feature_t F; /* This is not time critical, so do a linear search */ for (F = (feature_t) 0; F < FEAT_COUNT; ++F) { if (SB_CompareStr (Key, FeatureKeys[F]) == 0) { /* Found, index is enum value */ return F; } } /* Not found */ return FEAT_UNKNOWN; } feature_t SetFeature (const StrBuf* Key) /* Find the feature and set the corresponding flag if the feature is known. * In any case, return the feature found. An invalid Key will return * FEAT_UNKNOWN. */ { /* Map the string to an enum value */ feature_t Feature = FindFeature (Key); /* Set the flags */ switch (Feature) { case FEAT_DOLLAR_IS_PC: DollarIsPC = 1; break; case FEAT_LABELS_WITHOUT_COLONS: NoColonLabels = 1; break; case FEAT_LOOSE_STRING_TERM: LooseStringTerm = 1; break; case FEAT_LOOSE_CHAR_TERM: LooseCharTerm = 1; break; case FEAT_AT_IN_IDENTIFIERS: AtInIdents = 1; break; case FEAT_DOLLAR_IN_IDENTIFIERS: DollarInIdents = 1; break; case FEAT_LEADING_DOT_IN_IDENTIFIERS: LeadingDotInIdents= 1; break; case FEAT_ORG_PER_SEG: OrgPerSeg = 1; break; case FEAT_PC_ASSIGNMENT: PCAssignment = 1; break; case FEAT_MISSING_CHAR_TERM: MissingCharTerm = 1; break; case FEAT_UBIQUITOUS_IDENTS: UbiquitousIdents = 1; break; case FEAT_C_COMMENTS: CComments = 1; break; case FEAT_FORCE_RANGE: ForceRange = 1; break; case FEAT_UNDERLINE_IN_NUMBERS: UnderlineInNumbers= 1; break; default: /* Keep gcc silent */ break; } /* Return the value found */ return Feature; }
936
./cc65/src/ca65/studyexpr.c
/*****************************************************************************/ /* */ /* studyexpr.c */ /* */ /* Study an expression tree */ /* */ /* */ /* */ /* (C) 2003-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "check.h" #include "debugflag.h" #include "shift.h" #include "xmalloc.h" /* ca65 */ #include "error.h" #include "segment.h" #include "studyexpr.h" #include "symtab.h" #include "ulabel.h" /*****************************************************************************/ /* struct ExprDesc */ /*****************************************************************************/ ExprDesc* ED_Init (ExprDesc* ED) /* Initialize an ExprDesc structure for use with StudyExpr */ { ED->Flags = ED_OK; ED->AddrSize = ADDR_SIZE_DEFAULT; ED->Val = 0; ED->SymCount = 0; ED->SymLimit = 0; ED->SymRef = 0; ED->SecCount = 0; ED->SecLimit = 0; ED->SecRef = 0; return ED; } void ED_Done (ExprDesc* ED) /* Delete allocated memory for an ExprDesc. */ { xfree (ED->SymRef); xfree (ED->SecRef); } int ED_IsConst (const ExprDesc* D) /* Return true if the expression is constant */ { unsigned I; if (D->Flags & ED_TOO_COMPLEX) { return 0; } for (I = 0; I < D->SymCount; ++I) { if (D->SymRef[I].Count != 0) { return 0; } } for (I = 0; I < D->SecCount; ++I) { if (D->SecRef[I].Count != 0) { return 0; } } return 1; } static int ED_IsValid (const ExprDesc* D) /* Return true if the expression is valid, that is, neither the ERROR nor the * TOO_COMPLEX flags are set. */ { return ((D->Flags & (ED_ERROR | ED_TOO_COMPLEX)) == 0); } static int ED_HasError (const ExprDesc* D) /* Return true if the expression has an error. */ { return ((D->Flags & ED_ERROR) != 0); } static void ED_Invalidate (ExprDesc* D) /* Set the TOO_COMPLEX flag for D */ { D->Flags |= ED_TOO_COMPLEX; } static void ED_SetError (ExprDesc* D) /* Set the TOO_COMPLEX and ERROR flags for D */ { D->Flags |= (ED_ERROR | ED_TOO_COMPLEX); } static void ED_UpdateAddrSize (ExprDesc* ED, unsigned char AddrSize) /* Update the address size of the expression */ { if (ED_IsValid (ED)) { /* ADDR_SIZE_DEFAULT may get overridden */ if (ED->AddrSize == ADDR_SIZE_DEFAULT || AddrSize > ED->AddrSize) { ED->AddrSize = AddrSize; } } else { /* ADDR_SIZE_DEFAULT takes precedence */ if (ED->AddrSize != ADDR_SIZE_DEFAULT) { if (AddrSize == ADDR_SIZE_DEFAULT || AddrSize > ED->AddrSize) { ED->AddrSize = AddrSize; } } } } static void ED_MergeAddrSize (ExprDesc* ED, const ExprDesc* Right) /* Merge the address sizes of two expressions into ED */ { if (ED->AddrSize == ADDR_SIZE_DEFAULT) { /* If ED is valid, ADDR_SIZE_DEFAULT gets always overridden, otherwise * it takes precedence over anything else. */ if (ED_IsValid (ED)) { ED->AddrSize = Right->AddrSize; } } else if (Right->AddrSize == ADDR_SIZE_DEFAULT) { /* If Right is valid, ADDR_SIZE_DEFAULT gets always overridden, * otherwise it takes precedence over anything else. */ if (!ED_IsValid (Right)) { ED->AddrSize = Right->AddrSize; } } else { /* Neither ED nor Right has a default address size, use the larger of * the two. */ if (Right->AddrSize > ED->AddrSize) { ED->AddrSize = Right->AddrSize; } } } static ED_SymRef* ED_FindSymRef (ExprDesc* ED, SymEntry* Sym) /* Find a symbol reference and return it. Return NULL if the reference does * not exist. */ { unsigned I; ED_SymRef* SymRef; for (I = 0, SymRef = ED->SymRef; I < ED->SymCount; ++I, ++SymRef) { if (SymRef->Ref == Sym) { return SymRef; } } return 0; } static ED_SecRef* ED_FindSecRef (ExprDesc* ED, unsigned Sec) /* Find a section reference and return it. Return NULL if the reference does * not exist. */ { unsigned I; ED_SecRef* SecRef; for (I = 0, SecRef = ED->SecRef; I < ED->SecCount; ++I, ++SecRef) { if (SecRef->Ref == Sec) { return SecRef; } } return 0; } static ED_SymRef* ED_AllocSymRef (ExprDesc* ED, SymEntry* Sym) /* Allocate a new symbol reference and return it. The count of the new * reference will be set to zero, and the reference itself to Sym. */ { ED_SymRef* SymRef; /* Make sure we have enough SymRef slots */ if (ED->SymCount >= ED->SymLimit) { ED->SymLimit *= 2; if (ED->SymLimit == 0) { ED->SymLimit = 2; } ED->SymRef = xrealloc (ED->SymRef, ED->SymLimit * sizeof (ED->SymRef[0])); } /* Allocate a new slot */ SymRef = ED->SymRef + ED->SymCount++; /* Initialize the new struct and return it */ SymRef->Count = 0; SymRef->Ref = Sym; return SymRef; } static ED_SecRef* ED_AllocSecRef (ExprDesc* ED, unsigned Sec) /* Allocate a new section reference and return it. The count of the new * reference will be set to zero, and the reference itself to Sec. */ { ED_SecRef* SecRef; /* Make sure we have enough SecRef slots */ if (ED->SecCount >= ED->SecLimit) { ED->SecLimit *= 2; if (ED->SecLimit == 0) { ED->SecLimit = 2; } ED->SecRef = xrealloc (ED->SecRef, ED->SecLimit * sizeof (ED->SecRef[0])); } /* Allocate a new slot */ SecRef = ED->SecRef + ED->SecCount++; /* Initialize the new struct and return it */ SecRef->Count = 0; SecRef->Ref = Sec; return SecRef; } static ED_SymRef* ED_GetSymRef (ExprDesc* ED, SymEntry* Sym) /* Get a symbol reference and return it. If the symbol reference does not * exist, a new one is created and returned. */ { ED_SymRef* SymRef = ED_FindSymRef (ED, Sym); if (SymRef == 0) { SymRef = ED_AllocSymRef (ED, Sym); } return SymRef; } static ED_SecRef* ED_GetSecRef (ExprDesc* ED, unsigned Sec) /* Get a section reference and return it. If the section reference does not * exist, a new one is created and returned. */ { ED_SecRef* SecRef = ED_FindSecRef (ED, Sec); if (SecRef == 0) { SecRef = ED_AllocSecRef (ED, Sec); } return SecRef; } static void ED_MergeSymRefs (ExprDesc* ED, const ExprDesc* New) /* Merge the symbol references from New into ED */ { unsigned I; for (I = 0; I < New->SymCount; ++I) { /* Get a pointer to the SymRef entry */ const ED_SymRef* NewRef = New->SymRef + I; /* Get the corresponding entry in ED */ ED_SymRef* SymRef = ED_GetSymRef (ED, NewRef->Ref); /* Sum up the references */ SymRef->Count += NewRef->Count; } } static void ED_MergeSecRefs (ExprDesc* ED, const ExprDesc* New) /* Merge the section references from New into ED */ { unsigned I; for (I = 0; I < New->SecCount; ++I) { /* Get a pointer to the SymRef entry */ const ED_SecRef* NewRef = New->SecRef + I; /* Get the corresponding entry in ED */ ED_SecRef* SecRef = ED_GetSecRef (ED, NewRef->Ref); /* Sum up the references */ SecRef->Count += NewRef->Count; } } static void ED_MergeRefs (ExprDesc* ED, const ExprDesc* New) /* Merge all references from New into ED */ { ED_MergeSymRefs (ED, New); ED_MergeSecRefs (ED, New); } static void ED_NegRefs (ExprDesc* D) /* Negate the references in ED */ { unsigned I; for (I = 0; I < D->SymCount; ++I) { D->SymRef[I].Count = -D->SymRef[I].Count; } for (I = 0; I < D->SecCount; ++I) { D->SecRef[I].Count = -D->SecRef[I].Count; } } static void ED_Add (ExprDesc* ED, const ExprDesc* Right) /* Calculate ED = ED + Right, update address size in ED */ { ED->Val += Right->Val; ED_MergeRefs (ED, Right); ED_MergeAddrSize (ED, Right); } static void ED_Sub (ExprDesc* ED, const ExprDesc* Right) /* Calculate ED = ED - Right, update address size in ED */ { ExprDesc D = *Right; /* Temporary */ ED_NegRefs (&D); ED->Val -= Right->Val; ED_MergeRefs (ED, &D); /* Merge negatives */ ED_MergeAddrSize (ED, Right); } static void ED_Mul (ExprDesc* ED, const ExprDesc* Right) /* Calculate ED = ED * Right, update address size in ED */ { unsigned I; ED->Val *= Right->Val; for (I = 0; I < ED->SymCount; ++I) { ED->SymRef[I].Count *= Right->Val; } for (I = 0; I < ED->SecCount; ++I) { ED->SecRef[I].Count *= Right->Val; } ED_MergeAddrSize (ED, Right); } static void ED_Neg (ExprDesc* D) /* Negate an expression */ { D->Val = -D->Val; ED_NegRefs (D); } static void ED_Move (ExprDesc* From, ExprDesc* To) /* Move the data from one ExprDesc to another. Old data is freed, and From * is prepared to that ED_Done may be called safely. */ { /* Delete old data */ ED_Done (To); /* Move the data */ *To = *From; /* Cleanup From */ ED_Init (From); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void StudyExprInternal (ExprNode* Expr, ExprDesc* D); /* Study an expression tree and place the contents into D */ static unsigned char GetConstAddrSize (long Val) /* Get the address size of a constant */ { if ((Val & ~0xFFL) == 0) { return ADDR_SIZE_ZP; } else if ((Val & ~0xFFFFL) == 0) { return ADDR_SIZE_ABS; } else if ((Val & ~0xFFFFFFL) == 0) { return ADDR_SIZE_FAR; } else { return ADDR_SIZE_LONG; } } static void StudyBinaryExpr (ExprNode* Expr, ExprDesc* D) /* Study a binary expression subtree. This is a helper function for StudyExpr * used for operations that succeed when both operands are known and constant. * It evaluates the two subtrees and checks if they are constant. If they * aren't constant, it will set the TOO_COMPLEX flag, and merge references. * Otherwise the first value is returned in D->Val, the second one in D->Right, * so the actual operation can be done by the caller. */ { ExprDesc Right; /* Study the left side of the expression */ StudyExprInternal (Expr->Left, D); /* Study the right side of the expression */ ED_Init (&Right); StudyExprInternal (Expr->Right, &Right); /* Check if we can handle the operation */ if (ED_IsConst (D) && ED_IsConst (&Right)) { /* Remember the constant value from Right */ D->Right = Right.Val; } else { /* Cannot evaluate */ ED_Invalidate (D); /* Merge references and update address size */ ED_MergeRefs (D, &Right); ED_MergeAddrSize (D, &Right); } /* Cleanup Right */ ED_Done (&Right); } static void StudyLiteral (ExprNode* Expr, ExprDesc* D) /* Study a literal expression node */ { /* This one is easy */ D->Val = Expr->V.IVal; D->AddrSize = GetConstAddrSize (D->Val); } static void StudySymbol (ExprNode* Expr, ExprDesc* D) /* Study a symbol expression node */ { /* Get the symbol from the expression */ SymEntry* Sym = Expr->V.Sym; /* If the symbol is defined somewhere, it has an expression associated. * In this case, just study the expression associated with the symbol, * but mark the symbol so if we encounter it twice, we know that we have * a circular reference. */ if (SymHasExpr (Sym)) { if (SymHasUserMark (Sym)) { LIError (&Sym->DefLines, "Circular reference in definition of symbol `%m%p'", GetSymName (Sym)); ED_SetError (D); } else { unsigned char AddrSize; /* Mark the symbol and study its associated expression */ SymMarkUser (Sym); StudyExprInternal (GetSymExpr (Sym), D); SymUnmarkUser (Sym); /* If requested and if the expression is valid, dump it */ if (Debug > 0 && !ED_HasError (D)) { DumpExpr (Expr, SymResolve); } /* If the symbol has an explicit address size, use it. This may * lead to range errors later (maybe even in the linker stage), if * the user lied about the address size, but for now we trust him. */ AddrSize = GetSymAddrSize (Sym); if (AddrSize != ADDR_SIZE_DEFAULT) { D->AddrSize = AddrSize; } } } else if (SymIsImport (Sym)) { /* The symbol is an import. Track the symbols used and update the * address size. */ ED_SymRef* SymRef = ED_GetSymRef (D, Sym); ++SymRef->Count; ED_UpdateAddrSize (D, GetSymAddrSize (Sym)); } else { unsigned char AddrSize; SymTable* Parent; /* The symbol is undefined. Track symbol usage but set the "too * complex" flag, since we cannot evaluate the final result. */ ED_SymRef* SymRef = ED_GetSymRef (D, Sym); ++SymRef->Count; ED_Invalidate (D); /* Since the symbol may be a forward, and we may need a statement * about the address size, check higher lexical levels for a symbol * with the same name and use its address size if we find such a * symbol which is defined. */ AddrSize = GetSymAddrSize (Sym); Parent = GetSymParentScope (Sym); if (AddrSize == ADDR_SIZE_DEFAULT && Parent != 0) { SymEntry* H = SymFindAny (Parent, GetSymName (Sym)); if (H) { AddrSize = GetSymAddrSize (H); if (AddrSize != ADDR_SIZE_DEFAULT) { D->AddrSize = AddrSize; } } } else { D->AddrSize = AddrSize; } } } static void StudySection (ExprNode* Expr, ExprDesc* D) /* Study a section expression node */ { /* Get the section reference */ ED_SecRef* SecRef = ED_GetSecRef (D, Expr->V.SecNum); /* Update the data and the address size */ ++SecRef->Count; ED_UpdateAddrSize (D, GetSegAddrSize (SecRef->Ref)); } static void StudyULabel (ExprNode* Expr, ExprDesc* D) /* Study an unnamed label expression node */ { /* If we can resolve the label, study the expression associated with it, * otherwise mark the expression as too complex to evaluate. */ if (ULabCanResolve ()) { /* We can resolve the label */ StudyExprInternal (ULabResolve (Expr->V.IVal), D); } else { ED_Invalidate (D); } } static void StudyPlus (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_PLUS binary expression node */ { ExprDesc Right; /* Study the left side of the expression */ StudyExprInternal (Expr->Left, D); /* Study the right side of the expression */ ED_Init (&Right); StudyExprInternal (Expr->Right, &Right); /* Check if we can handle the operation */ if (ED_IsValid (D) && ED_IsValid (&Right)) { /* Add both */ ED_Add (D, &Right); } else { /* Cannot evaluate */ ED_Invalidate (D); /* Merge references and update address size */ ED_MergeRefs (D, &Right); ED_MergeAddrSize (D, &Right); } /* Done */ ED_Done (&Right); } static void StudyMinus (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_MINUS binary expression node */ { ExprDesc Right; /* Study the left side of the expression */ StudyExprInternal (Expr->Left, D); /* Study the right side of the expression */ ED_Init (&Right); StudyExprInternal (Expr->Right, &Right); /* Check if we can handle the operation */ if (ED_IsValid (D) && ED_IsValid (&Right)) { /* Subtract both */ ED_Sub (D, &Right); } else { /* Cannot evaluate */ ED_Invalidate (D); /* Merge references and update address size */ ED_MergeRefs (D, &Right); ED_MergeAddrSize (D, &Right); } /* Done */ ED_Done (&Right); } static void StudyMul (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_MUL binary expression node */ { ExprDesc Right; /* Study the left side of the expression */ StudyExprInternal (Expr->Left, D); /* Study the right side of the expression */ ED_Init (&Right); StudyExprInternal (Expr->Right, &Right); /* We can handle the operation if at least one of both operands is const * and the other one is valid. */ if (ED_IsConst (D) && ED_IsValid (&Right)) { /* Multiplicate both, result goes into Right */ ED_Mul (&Right, D); /* Move result into D */ ED_Move (&Right, D); } else if (ED_IsConst (&Right) && ED_IsValid (D)) { /* Multiplicate both */ ED_Mul (D, &Right); } else { /* Cannot handle this operation */ ED_Invalidate (D); } /* If we could not handle the op, merge references and update address size */ if (!ED_IsValid (D)) { ED_MergeRefs (D, &Right); ED_MergeAddrSize (D, &Right); } /* Done */ ED_Done (&Right); } static void StudyDiv (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_DIV binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { if (D->Right == 0) { Error ("Division by zero"); ED_SetError (D); } else { D->Val /= D->Right; } } } static void StudyMod (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_MOD binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { if (D->Right == 0) { Error ("Modulo operation with zero"); ED_SetError (D); } else { D->Val %= D->Right; } } } static void StudyOr (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_OR binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val |= D->Right; } } static void StudyXor (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_XOR binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val ^= D->Right; } } static void StudyAnd (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_AND binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val &= D->Right; } } static void StudyShl (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_SHL binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val = shl_l (D->Val, D->Right); } } static void StudyShr (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_SHR binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val = shr_l (D->Val, D->Right); } } static void StudyEQ (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_EQ binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val = (D->Val == D->Right); } /* In any case, the result is 0 or 1 */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyNE (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_NE binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val = (D->Val != D->Right); } /* In any case, the result is 0 or 1 */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyLT (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_LT binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val = (D->Val < D->Right); } /* In any case, the result is 0 or 1 */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyGT (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_GT binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val = (D->Val > D->Right); } /* In any case, the result is 0 or 1 */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyLE (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_LE binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val = (D->Val <= D->Right); } /* In any case, the result is 0 or 1 */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyGE (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_GE binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val = (D->Val >= D->Right); } /* In any case, the result is 0 or 1 */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyBoolAnd (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_BOOLAND binary expression node */ { StudyExprInternal (Expr->Left, D); if (ED_IsConst (D)) { if (D->Val != 0) { /* Shortcut op */ ED_Done (D); ED_Init (D); StudyExprInternal (Expr->Right, D); if (ED_IsConst (D)) { D->Val = (D->Val != 0); } else { ED_Invalidate (D); } } } else { ED_Invalidate (D); } /* In any case, the result is 0 or 1 */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyBoolOr (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_BOOLOR binary expression node */ { StudyExprInternal (Expr->Left, D); if (ED_IsConst (D)) { if (D->Val == 0) { /* Shortcut op */ ED_Done (D); ED_Init (D); StudyExprInternal (Expr->Right, D); if (ED_IsConst (D)) { D->Val = (D->Val != 0); } else { ED_Invalidate (D); } } else { D->Val = 1; } } else { ED_Invalidate (D); } /* In any case, the result is 0 or 1 */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyBoolXor (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_BOOLXOR binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val = (D->Val != 0) ^ (D->Right != 0); } /* In any case, the result is 0 or 1 */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyMax (ExprNode* Expr, ExprDesc* D) /* Study an MAX binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val = (D->Val > D->Right)? D->Val : D->Right; } } static void StudyMin (ExprNode* Expr, ExprDesc* D) /* Study an MIN binary expression node */ { /* Use helper function */ StudyBinaryExpr (Expr, D); /* If the result is valid, apply the operation */ if (ED_IsValid (D)) { D->Val = (D->Val < D->Right)? D->Val : D->Right; } } static void StudyUnaryMinus (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_UNARY_MINUS expression node */ { /* Study the expression */ StudyExprInternal (Expr->Left, D); /* If it is valid, negate it */ if (ED_IsValid (D)) { ED_Neg (D); } } static void StudyNot (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_NOT expression node */ { /* Study the expression */ StudyExprInternal (Expr->Left, D); /* We can handle only const expressions */ if (ED_IsConst (D)) { D->Val = ~D->Val; } else { ED_Invalidate (D); } } static void StudySwap (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_SWAP expression node */ { /* Study the expression */ StudyExprInternal (Expr->Left, D); /* We can handle only const expressions */ if (ED_IsConst (D)) { D->Val = (D->Val & ~0xFFFFUL) | ((D->Val >> 8) & 0xFF) | ((D->Val << 8) & 0xFF00); } else { ED_Invalidate (D); } } static void StudyBoolNot (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_BOOLNOT expression node */ { /* Study the expression */ StudyExprInternal (Expr->Left, D); /* We can handle only const expressions */ if (ED_IsConst (D)) { D->Val = (D->Val == 0); } else { ED_Invalidate (D); } /* In any case, the result is 0 or 1 */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyBank (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_BANK expression node */ { /* Study the expression extracting section references */ StudyExprInternal (Expr->Left, D); /* The expression is always linker evaluated, so invalidate it */ ED_Invalidate (D); } static void StudyByte0 (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_BYTE0 expression node */ { /* Study the expression */ StudyExprInternal (Expr->Left, D); /* We can handle only const expressions */ if (ED_IsConst (D)) { D->Val = (D->Val & 0xFF); } else { ED_Invalidate (D); } /* In any case, the result is a zero page expression */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyByte1 (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_BYTE1 expression node */ { /* Study the expression */ StudyExprInternal (Expr->Left, D); /* We can handle only const expressions */ if (ED_IsConst (D)) { D->Val = (D->Val >> 8) & 0xFF; } else { ED_Invalidate (D); } /* In any case, the result is a zero page expression */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyByte2 (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_BYTE2 expression node */ { /* Study the expression */ StudyExprInternal (Expr->Left, D); /* We can handle only const expressions */ if (ED_IsConst (D)) { D->Val = (D->Val >> 16) & 0xFF; } else { ED_Invalidate (D); } /* In any case, the result is a zero page expression */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyByte3 (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_BYTE3 expression node */ { /* Study the expression */ StudyExprInternal (Expr->Left, D); /* We can handle only const expressions */ if (ED_IsConst (D)) { D->Val = (D->Val >> 24) & 0xFF; } else { ED_Invalidate (D); } /* In any case, the result is a zero page expression */ D->AddrSize = ADDR_SIZE_ZP; } static void StudyWord0 (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_WORD0 expression node */ { /* Study the expression */ StudyExprInternal (Expr->Left, D); /* We can handle only const expressions */ if (ED_IsConst (D)) { D->Val &= 0xFFFFL; } else { ED_Invalidate (D); } /* In any case, the result is an absolute expression */ D->AddrSize = ADDR_SIZE_ABS; } static void StudyWord1 (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_WORD1 expression node */ { /* Study the expression */ StudyExprInternal (Expr->Left, D); /* We can handle only const expressions */ if (ED_IsConst (D)) { D->Val = (D->Val >> 16) & 0xFFFFL; } else { ED_Invalidate (D); } /* In any case, the result is an absolute expression */ D->AddrSize = ADDR_SIZE_ABS; } static void StudyFarAddr (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_FARADDR expression node */ { /* Study the expression */ StudyExprInternal (Expr->Left, D); /* We can handle only const expressions */ if (ED_IsConst (D)) { D->Val &= 0xFFFFFFL; } else { ED_Invalidate (D); } /* In any case, the result is a far address */ D->AddrSize = ADDR_SIZE_FAR; } static void StudyDWord (ExprNode* Expr, ExprDesc* D) /* Study an EXPR_DWORD expression node */ { /* Study the expression */ StudyExprInternal (Expr->Left, D); /* We can handle only const expressions */ if (ED_IsConst (D)) { D->Val &= 0xFFFFFFFFL; } else { ED_Invalidate (D); } /* In any case, the result is a long expression */ D->AddrSize = ADDR_SIZE_LONG; } static void StudyExprInternal (ExprNode* Expr, ExprDesc* D) /* Study an expression tree and place the contents into D */ { /* Study this expression node */ switch (Expr->Op) { case EXPR_LITERAL: StudyLiteral (Expr, D); break; case EXPR_SYMBOL: StudySymbol (Expr, D); break; case EXPR_SECTION: StudySection (Expr, D); break; case EXPR_ULABEL: StudyULabel (Expr, D); break; case EXPR_PLUS: StudyPlus (Expr, D); break; case EXPR_MINUS: StudyMinus (Expr, D); break; case EXPR_MUL: StudyMul (Expr, D); break; case EXPR_DIV: StudyDiv (Expr, D); break; case EXPR_MOD: StudyMod (Expr, D); break; case EXPR_OR: StudyOr (Expr, D); break; case EXPR_XOR: StudyXor (Expr, D); break; case EXPR_AND: StudyAnd (Expr, D); break; case EXPR_SHL: StudyShl (Expr, D); break; case EXPR_SHR: StudyShr (Expr, D); break; case EXPR_EQ: StudyEQ (Expr, D); break; case EXPR_NE: StudyNE (Expr, D); break; case EXPR_LT: StudyLT (Expr, D); break; case EXPR_GT: StudyGT (Expr, D); break; case EXPR_LE: StudyLE (Expr, D); break; case EXPR_GE: StudyGE (Expr, D); break; case EXPR_BOOLAND: StudyBoolAnd (Expr, D); break; case EXPR_BOOLOR: StudyBoolOr (Expr, D); break; case EXPR_BOOLXOR: StudyBoolXor (Expr, D); break; case EXPR_MAX: StudyMax (Expr, D); break; case EXPR_MIN: StudyMin (Expr, D); break; case EXPR_UNARY_MINUS: StudyUnaryMinus (Expr, D); break; case EXPR_NOT: StudyNot (Expr, D); break; case EXPR_SWAP: StudySwap (Expr, D); break; case EXPR_BOOLNOT: StudyBoolNot (Expr, D); break; case EXPR_BANK: StudyBank (Expr, D); break; case EXPR_BYTE0: StudyByte0 (Expr, D); break; case EXPR_BYTE1: StudyByte1 (Expr, D); break; case EXPR_BYTE2: StudyByte2 (Expr, D); break; case EXPR_BYTE3: StudyByte3 (Expr, D); break; case EXPR_WORD0: StudyWord0 (Expr, D); break; case EXPR_WORD1: StudyWord1 (Expr, D); break; case EXPR_FARADDR: StudyFarAddr (Expr, D); break; case EXPR_DWORD: StudyDWord (Expr, D); break; default: Internal ("Unknown Op type: %u", Expr->Op); break; } } void StudyExpr (ExprNode* Expr, ExprDesc* D) /* Study an expression tree and place the contents into D */ { unsigned I, J; /* Call the internal function */ StudyExprInternal (Expr, D); /* Remove symbol references with count zero */ I = J = 0; while (I < D->SymCount) { if (D->SymRef[I].Count == 0) { /* Delete the entry */ --D->SymCount; memmove (D->SymRef + I, D->SymRef + I + 1, (D->SymCount - I) * sizeof (D->SymRef[0])); } else { /* Next entry */ ++I; } } /* Remove section references with count zero */ I = 0; while (I < D->SecCount) { if (D->SecRef[I].Count == 0) { /* Delete the entry */ --D->SecCount; memmove (D->SecRef + I, D->SecRef + I + 1, (D->SecCount - I) * sizeof (D->SecRef[0])); } else { /* Next entry */ ++I; } } /* If we don't have an address size, assign one if the expression is a * constant. */ if (D->AddrSize == ADDR_SIZE_DEFAULT && ED_IsConst (D)) { D->AddrSize = GetConstAddrSize (D->Val); } /* If the expression is valid, throw away the address size and recalculate * it using the data we have. This is more exact than the on-the-fly * calculation done when evaluating the tree, because symbols may have * been removed from the expression, and the final numeric value is now * known. */ if (ED_IsValid (D)) { unsigned char AddrSize; /* If there are symbols or sections, use the largest one. If the * expression resolves to a const, use the address size of the value. */ if (D->SymCount > 0 || D->SecCount > 0) { D->AddrSize = ADDR_SIZE_DEFAULT; for (I = 0; I < D->SymCount; ++I) { const SymEntry* Sym = D->SymRef[I].Ref; AddrSize = GetSymAddrSize (Sym); if (AddrSize > D->AddrSize) { D->AddrSize = AddrSize; } } for (I = 0; I < D->SecCount; ++I) { unsigned SegNum = D->SecRef[0].Ref; AddrSize = GetSegAddrSize (SegNum); if (AddrSize > D->AddrSize) { D->AddrSize = AddrSize; } } } else { AddrSize = GetConstAddrSize (D->Val); if (AddrSize > D->AddrSize) { D->AddrSize = AddrSize; } } } #if 0 /* Debug code */ printf ("StudyExpr: "); DumpExpr (Expr, SymResolve); printf ("Value: %08lX\n", D->Val); if (!ED_IsValid (D)) { printf ("Invalid: %s\n", AddrSizeToStr (D->AddrSize)); } else { printf ("Valid: %s\n", AddrSizeToStr (D->AddrSize)); } printf ("%u symbols:\n", D->SymCount); printf ("%u sections:\n", D->SecCount); #endif }
937
./cc65/src/ca65/toklist.c
/*****************************************************************************/ /* */ /* toklist.c */ /* */ /* Token list for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "check.h" #include "xmalloc.h" /* ca65 */ #include "error.h" #include "istack.h" #include "lineinfo.h" #include "nexttok.h" #include "scanner.h" #include "toklist.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Number of currently pushed token lists */ static unsigned PushCounter = 0; /*****************************************************************************/ /* Code */ /*****************************************************************************/ TokNode* NewTokNode (void) /* Create and return a token node with the current token value */ { /* Allocate memory */ TokNode* N = xmalloc (sizeof (TokNode)); /* Initialize the token contents */ N->Next = 0; SB_Init (&N->T.SVal); CopyToken (&N->T, &CurTok); /* Return the node */ return N; } void FreeTokNode (TokNode* N) /* Free the given token node */ { SB_Done (&N->T.SVal); xfree (N); } void TokSet (TokNode* N) /* Set the scanner token from the given token node. */ { /* Set the values */ CopyToken (&CurTok, &N->T); SB_Terminate (&CurTok.SVal); } enum TC TokCmp (const TokNode* N) /* Compare the token given as parameter against the current token */ { if (N->T.Tok != CurTok.Tok) { /* Different token */ return tcDifferent; } /* If the token has string attribute, check it */ if (TokHasSVal (N->T.Tok)) { if (SB_Compare (&CurTok.SVal, &N->T.SVal) != 0) { return tcSameToken; } } else if (TokHasIVal (N->T.Tok)) { if (N->T.IVal != CurTok.IVal) { return tcSameToken; } } /* Tokens are identical */ return tcIdentical; } TokList* NewTokList (void) /* Create a new, empty token list */ { /* Allocate memory for the list structure */ TokList* T = xmalloc (sizeof (TokList)); /* Initialize the fields */ T->Next = 0; T->Root = 0; T->Last = 0; T->RepCount = 0; T->RepMax = 1; T->Count = 0; T->Check = 0; T->Data = 0; T->LI = 0; /* Return the new list */ return T; } void FreeTokList (TokList* List) /* Delete the token list including all token nodes */ { /* Free the token list */ TokNode* T = List->Root; while (T) { TokNode* Tmp = T; T = T->Next; FreeTokNode (Tmp); } /* Free associated line info */ if (List->LI) { EndLine (List->LI); } /* If we have associated data, free it */ if (List->Data) { xfree (List->Data); } /* Free the list structure itself */ xfree (List); } enum token_t GetTokListTerm (enum token_t Term) /* Determine if the following token list is enclosed in curly braces. This is * the case if the next token is the opening brace. If so, skip it and return * a closing brace, otherwise return Term. */ { if (CurTok.Tok == TOK_LCURLY) { NextTok (); return TOK_RCURLY; } else { return Term; } } void AddCurTok (TokList* List) /* Add the current token to the token list */ { /* Create a token node with the current token value */ TokNode* T = NewTokNode (); /* Insert the node into the list */ if (List->Root == 0) { List->Root = T; } else { List->Last->Next = T; } List->Last = T; /* Count nodes */ List->Count++; } static int ReplayTokList (void* List) /* Function that gets the next token from a token list and sets it. This * function may be used together with the PushInput function from the istack * module. */ { /* Cast the generic pointer to an actual list */ TokList* L = List; /* If there are no more tokens, decrement the repeat counter. If it goes * zero, delete the list and remove the function from the stack. */ if (L->Last == 0) { if (++L->RepCount >= L->RepMax) { /* Done with this list */ FreeTokList (L); --PushCounter; PopInput (); return 0; } else { /* Replay one more time */ L->Last = L->Root; } } /* Set the next token from the list */ TokSet (L->Last); /* Set the line info for the new token */ if (L->LI) { EndLine (L->LI); } L->LI = StartLine (&CurTok.Pos, LI_TYPE_ASM, PushCounter); /* If a check function is defined, call it, so it may look at the token * just set and changed it as apropriate. */ if (L->Check) { L->Check (L); } /* Set the pointer to the next token */ L->Last = L->Last->Next; /* We have a token */ return 1; } void PushTokList (TokList* List, const char* Desc) /* Push a token list to be used as input for InputFromStack. This includes * several initializations needed in the token list structure, so don't use * PushInput directly. */ { /* If the list is empty, just delete it and bail out */ if (List->Count == 0) { FreeTokList (List); return; } /* Reset the last pointer to the first element */ List->Last = List->Root; /* Insert the list specifying our input function */ ++PushCounter; PushInput (ReplayTokList, List, Desc); }
938
./cc65/src/ca65/symentry.c
/*****************************************************************************/ /* */ /* symentry.c */ /* */ /* Symbol table entry for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "addrsize.h" #include "symdefs.h" #include "xmalloc.h" /* ca65 */ #include "error.h" #include "expr.h" #include "global.h" #include "scanner.h" #include "segment.h" #include "spool.h" #include "studyexpr.h" /* ### */ #include "symentry.h" #include "symtab.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* List of all symbol table entries */ SymEntry* SymList = 0; /* Pointer to last defined symbol */ SymEntry* SymLast = 0; /*****************************************************************************/ /* Code */ /*****************************************************************************/ SymEntry* NewSymEntry (const StrBuf* Name, unsigned Flags) /* Allocate a symbol table entry, initialize and return it */ { unsigned I; /* Allocate memory */ SymEntry* S = xmalloc (sizeof (SymEntry)); /* Initialize the entry */ S->Left = 0; S->Right = 0; S->Locals = 0; S->Sym.Tab = 0; S->DefLines = EmptyCollection; S->RefLines = EmptyCollection; for (I = 0; I < sizeof (S->GuessedUse) / sizeof (S->GuessedUse[0]); ++I) { S->GuessedUse[I] = 0; } S->HLLSym = 0; S->Flags = Flags; S->DebugSymId = ~0U; S->ImportId = ~0U; S->ExportId = ~0U; S->Expr = 0; S->ExprRefs = AUTO_COLLECTION_INITIALIZER; S->ExportSize = ADDR_SIZE_DEFAULT; S->AddrSize = ADDR_SIZE_DEFAULT; memset (S->ConDesPrio, 0, sizeof (S->ConDesPrio)); S->Name = GetStrBufId (Name); /* Insert it into the list of all entries */ S->List = SymList; SymList = S; /* Return the initialized entry */ return S; } int SymSearchTree (SymEntry* T, const StrBuf* Name, SymEntry** E) /* Search in the given tree for a name. If we find the symbol, the function * will return 0 and put the entry pointer into E. If we did not find the * symbol, and the tree is empty, E is set to NULL. If the tree is not empty, * E will be set to the last entry, and the result of the function is <0 if * the entry should be inserted on the left side, and >0 if it should get * inserted on the right side. */ { /* Is there a tree? */ if (T == 0) { *E = 0; return 1; } /* We have a table, search it */ while (1) { /* Get the symbol name */ const StrBuf* SymName = GetStrBuf (T->Name); /* Choose next entry */ int Cmp = SB_Compare (Name, SymName); if (Cmp < 0 && T->Left) { T = T->Left; } else if (Cmp > 0 && T->Right) { T = T->Right; } else { /* Found or end of search, return the result */ *E = T; return Cmp; } } } void SymTransferExprRefs (SymEntry* From, SymEntry* To) /* Transfer all expression references from one symbol to another. */ { unsigned I; for (I = 0; I < CollCount (&From->ExprRefs); ++I) { /* Get the expression node */ ExprNode* E = CollAtUnchecked (&From->ExprRefs, I); /* Safety */ CHECK (E->Op == EXPR_SYMBOL && E->V.Sym == From); /* Replace the symbol reference */ E->V.Sym = To; /* Add the expression reference */ SymAddExprRef (To, E); } /* Remove all symbol references from the old symbol */ CollDeleteAll (&From->ExprRefs); } static void SymReplaceExprRefs (SymEntry* S) /* Replace the references to this symbol by a copy of the symbol expression */ { unsigned I; long Val; /* Check if the expression is const and get its value */ int IsConst = IsConstExpr (S->Expr, &Val); CHECK (IsConst); /* Loop over all references */ for (I = 0; I < CollCount (&S->ExprRefs); ++I) { /* Get the expression node */ ExprNode* E = CollAtUnchecked (&S->ExprRefs, I); /* Safety */ CHECK (E->Op == EXPR_SYMBOL && E->V.Sym == S); /* We cannot touch the root node, since there are pointers to it. * Replace it by a literal node. */ E->Op = EXPR_LITERAL; E->V.IVal = Val; } /* Remove all symbol references from the symbol */ CollDeleteAll (&S->ExprRefs); } void SymDef (SymEntry* S, ExprNode* Expr, unsigned char AddrSize, unsigned Flags) /* Define a new symbol */ { if (S->Flags & SF_IMPORT) { /* Defined symbol is marked as imported external symbol */ Error ("Symbol `%m%p' is already an import", GetSymName (S)); return; } if ((Flags & SF_VAR) != 0 && (S->Flags & (SF_EXPORT | SF_GLOBAL))) { /* Variable symbols cannot be exports or globals */ Error ("Var symbol `%m%p' cannot be an export or global symbol", GetSymName (S)); return; } if (S->Flags & SF_DEFINED) { /* Multiple definition. In case of a variable, this is legal. */ if ((S->Flags & SF_VAR) == 0) { Error ("Symbol `%m%p' is already defined", GetSymName (S)); S->Flags |= SF_MULTDEF; return; } else { /* Redefinition must also be a variable symbol */ if ((Flags & SF_VAR) == 0) { Error ("Symbol `%m%p' is already different kind", GetSymName (S)); return; } /* Delete the current symbol expression, since it will get * replaced */ FreeExpr (S->Expr); S->Expr = 0; } } /* Map a default address size to a real value */ if (AddrSize == ADDR_SIZE_DEFAULT) { /* ### Must go! Delay address size calculation until end of assembly! */ ExprDesc ED; ED_Init (&ED); StudyExpr (Expr, &ED); AddrSize = ED.AddrSize; ED_Done (&ED); } /* Set the symbol value */ S->Expr = Expr; /* In case of a variable symbol, walk over all expressions containing * this symbol and replace the (sub-)expression by the literal value of * the tree. Be sure to replace the expression node in place, since there * may be pointers to it. */ if (Flags & SF_VAR) { SymReplaceExprRefs (S); } /* If the symbol is marked as global, export it. Address size is checked * below. */ if (S->Flags & SF_GLOBAL) { S->Flags = (S->Flags & ~SF_GLOBAL) | SF_EXPORT; ReleaseFullLineInfo (&S->DefLines); } /* Mark the symbol as defined and use the given address size */ S->Flags |= (SF_DEFINED | Flags); S->AddrSize = AddrSize; /* Remember the line info of the symbol definition */ GetFullLineInfo (&S->DefLines); /* If the symbol is exported, check the address sizes */ if (S->Flags & SF_EXPORT) { if (S->ExportSize == ADDR_SIZE_DEFAULT) { /* Use the real size of the symbol */ S->ExportSize = S->AddrSize; } else if (S->AddrSize > S->ExportSize) { /* We're exporting a symbol smaller than it actually is */ Warning (1, "Symbol `%m%p' is %s but exported %s", GetSymName (S), AddrSizeToStr (S->AddrSize), AddrSizeToStr (S->ExportSize)); } } /* If this is not a local symbol, remember it as the last global one */ if ((S->Flags & SF_LOCAL) == 0) { SymLast = S; } } void SymRef (SymEntry* S) /* Mark the given symbol as referenced */ { /* Mark the symbol as referenced */ S->Flags |= SF_REFERENCED; /* Remember the current location */ CollAppend (&S->RefLines, GetAsmLineInfo ()); } void SymImport (SymEntry* S, unsigned char AddrSize, unsigned Flags) /* Mark the given symbol as an imported symbol */ { if (S->Flags & SF_DEFINED) { Error ("Symbol `%m%p' is already defined", GetSymName (S)); S->Flags |= SF_MULTDEF; return; } if (S->Flags & SF_EXPORT) { /* The symbol is already marked as exported symbol */ Error ("Cannot import exported symbol `%m%p'", GetSymName (S)); return; } /* If no address size is given, use the address size of the enclosing * segment. */ if (AddrSize == ADDR_SIZE_DEFAULT) { AddrSize = GetCurrentSegAddrSize (); } /* If the symbol is marked as import or global, check the address size, * then do silently remove the global flag. */ if (S->Flags & SF_IMPORT) { if ((Flags & SF_FORCED) != (S->Flags & SF_FORCED)) { Error ("Redeclaration mismatch for symbol `%m%p'", GetSymName (S)); } if (AddrSize != S->AddrSize) { Error ("Address size mismatch for symbol `%m%p'", GetSymName (S)); } } if (S->Flags & SF_GLOBAL) { S->Flags &= ~SF_GLOBAL; if (AddrSize != S->AddrSize) { Error ("Address size mismatch for symbol `%m%p'", GetSymName (S)); } } /* Set the symbol data */ S->Flags |= (SF_IMPORT | Flags); S->AddrSize = AddrSize; /* Mark the position of the import as the position of the definition. * Please note: In case of multiple .global or .import statements, the line * infos add up. */ GetFullLineInfo (&S->DefLines); } void SymExport (SymEntry* S, unsigned char AddrSize, unsigned Flags) /* Mark the given symbol as an exported symbol */ { /* Check if it's ok to export the symbol */ if (S->Flags & SF_IMPORT) { /* The symbol is already marked as imported external symbol */ Error ("Symbol `%m%p' is already an import", GetSymName (S)); return; } if (S->Flags & SF_VAR) { /* Variable symbols cannot be exported */ Error ("Var symbol `%m%p' cannot be exported", GetSymName (S)); return; } /* If the symbol was marked as global before, remove the global flag and * proceed, but check the address size. */ if (S->Flags & SF_GLOBAL) { if (AddrSize != S->ExportSize) { Error ("Address size mismatch for symbol `%m%p'", GetSymName (S)); } S->Flags &= ~SF_GLOBAL; /* .GLOBAL remembers line infos in case an .IMPORT follows. We have * to remove these here. */ ReleaseFullLineInfo (&S->DefLines); } /* If the symbol was already marked as an export, but wasn't defined * before, the address sizes in both definitions must match. */ if ((S->Flags & (SF_EXPORT|SF_DEFINED)) == SF_EXPORT) { if (S->ExportSize != AddrSize) { Error ("Address size mismatch for symbol `%m%p'", GetSymName (S)); } } S->ExportSize = AddrSize; /* If the symbol is already defined, check symbol size against the * exported size. */ if (S->Flags & SF_DEFINED) { if (S->ExportSize == ADDR_SIZE_DEFAULT) { /* No export size given, use the real size of the symbol */ S->ExportSize = S->AddrSize; } else if (S->AddrSize > S->ExportSize) { /* We're exporting a symbol smaller than it actually is */ Warning (1, "Symbol `%m%p' is %s but exported %s", GetSymName (S), AddrSizeToStr (S->AddrSize), AddrSizeToStr (S->ExportSize)); } } /* Set the symbol data */ S->Flags |= (SF_EXPORT | SF_REFERENCED | Flags); /* Remember line info for this reference */ CollAppend (&S->RefLines, GetAsmLineInfo ()); } void SymGlobal (SymEntry* S, unsigned char AddrSize, unsigned Flags) /* Mark the given symbol as a global symbol, that is, as a symbol that is * either imported or exported. */ { if (S->Flags & SF_VAR) { /* Variable symbols cannot be exported or imported */ Error ("Var symbol `%m%p' cannot be made global", GetSymName (S)); return; } /* If the symbol is already marked as import, the address size must match. * Apart from that, ignore the global declaration. */ if (S->Flags & SF_IMPORT) { if (AddrSize == ADDR_SIZE_DEFAULT) { /* Use the size of the current segment */ AddrSize = GetCurrentSegAddrSize (); } if (AddrSize != S->AddrSize) { Error ("Address size mismatch for symbol `%m%p'", GetSymName (S)); } return; } /* If the symbol is already an export: If it is not defined, the address * sizes must match. */ if (S->Flags & SF_EXPORT) { if ((S->Flags & SF_DEFINED) == 0) { /* Symbol is undefined */ if (AddrSize != S->ExportSize) { Error ("Address size mismatch for symbol `%m%p'", GetSymName (S)); } } else if (AddrSize != ADDR_SIZE_DEFAULT) { /* Symbol is defined and address size given */ if (AddrSize != S->ExportSize) { Error ("Address size mismatch for symbol `%m%p'", GetSymName (S)); } } return; } /* If the symbol is already marked as global, the address size must match. * Use the ExportSize here, since it contains the actual address size * passed to this function. */ if (S->Flags & SF_GLOBAL) { if (AddrSize != S->ExportSize) { Error ("Address size mismatch for symbol `%m%p'", GetSymName (S)); } return; } /* If we come here, the symbol was neither declared as export, import or * global before. Check if it is already defined, in which case it will * become an export. If it is not defined, mark it as global and remember * the given address sizes. */ if (S->Flags & SF_DEFINED) { /* The symbol is defined, export it */ S->ExportSize = AddrSize; if (S->ExportSize == ADDR_SIZE_DEFAULT) { /* No export size given, use the real size of the symbol */ S->ExportSize = S->AddrSize; } else if (S->AddrSize > S->ExportSize) { /* We're exporting a symbol smaller than it actually is */ Warning (1, "Symbol `%m%p' is %s but exported %s", GetSymName (S), AddrSizeToStr (S->AddrSize), AddrSizeToStr (S->ExportSize)); } S->Flags |= (SF_EXPORT | Flags); } else { /* Since we don't know if the symbol will get exported or imported, * remember two different address sizes: One for an import in AddrSize, * and the other one for an export in ExportSize. */ S->AddrSize = AddrSize; if (S->AddrSize == ADDR_SIZE_DEFAULT) { /* Use the size of the current segment */ S->AddrSize = GetCurrentSegAddrSize (); } S->ExportSize = AddrSize; S->Flags |= (SF_GLOBAL | Flags); /* Remember the current location as location of definition in case * an .IMPORT follows later. */ GetFullLineInfo (&S->DefLines); } } void SymConDes (SymEntry* S, unsigned char AddrSize, unsigned Type, unsigned Prio) /* Mark the given symbol as a module constructor/destructor. This will also * mark the symbol as an export. Initializers may never be zero page symbols. */ { /* Check the parameters */ #if (CD_TYPE_MIN != 0) CHECK (Type >= CD_TYPE_MIN && Type <= CD_TYPE_MAX); #else CHECK (Type <= CD_TYPE_MAX); #endif CHECK (Prio >= CD_PRIO_MIN && Prio <= CD_PRIO_MAX); /* Check for errors */ if (S->Flags & SF_IMPORT) { /* The symbol is already marked as imported external symbol */ Error ("Symbol `%m%p' is already an import", GetSymName (S)); return; } if (S->Flags & SF_VAR) { /* Variable symbols cannot be exported or imported */ Error ("Var symbol `%m%p' cannot be exported", GetSymName (S)); return; } /* If the symbol was already marked as an export or global, check if * this was done specifiying the same address size. In case of a global * declaration, silently remove the global flag. */ if (S->Flags & (SF_EXPORT | SF_GLOBAL)) { if (S->ExportSize != AddrSize) { Error ("Address size mismatch for symbol `%m%p'", GetSymName (S)); } S->Flags &= ~SF_GLOBAL; } S->ExportSize = AddrSize; /* If the symbol is already defined, check symbol size against the * exported size. */ if (S->Flags & SF_DEFINED) { if (S->ExportSize == ADDR_SIZE_DEFAULT) { /* Use the real size of the symbol */ S->ExportSize = S->AddrSize; } else if (S->AddrSize != S->ExportSize) { Error ("Address size mismatch for symbol `%m%p'", GetSymName (S)); } } /* If the symbol was already declared as a condes, check if the new * priority value is the same as the old one. */ if (S->ConDesPrio[Type] != CD_PRIO_NONE) { if (S->ConDesPrio[Type] != Prio) { Error ("Redeclaration mismatch for symbol `%m%p'", GetSymName (S)); } } S->ConDesPrio[Type] = Prio; /* Set the symbol data */ S->Flags |= (SF_EXPORT | SF_REFERENCED); /* In case we have no line info for the definition, record it now */ if (CollCount (&S->DefLines) == 0) { GetFullLineInfo (&S->DefLines); } } void SymGuessedAddrSize (SymEntry* Sym, unsigned char AddrSize) /* Mark the address size of the given symbol as guessed. The address size * passed as argument is the one NOT used, because the actual address size * wasn't known. Example: Zero page addressing was not used because symbol * is undefined, and absolute addressing was available. */ { /* We must have a valid address size passed */ PRECONDITION (AddrSize != ADDR_SIZE_DEFAULT); /* We do not support all address sizes currently */ if (AddrSize > sizeof (Sym->GuessedUse) / sizeof (Sym->GuessedUse[0])) { return; } /* We can only remember one such occurance */ if (Sym->GuessedUse[AddrSize-1]) { return; } /* Ok, remember the file position */ Sym->GuessedUse[AddrSize-1] = xdup (&CurTok.Pos, sizeof (CurTok.Pos)); } void SymExportFromGlobal (SymEntry* S) /* Called at the end of assembly. Converts a global symbol that is defined * into an export. */ { /* Remove the global flag and make the symbol an export */ S->Flags &= ~SF_GLOBAL; S->Flags |= SF_EXPORT; } void SymImportFromGlobal (SymEntry* S) /* Called at the end of assembly. Converts a global symbol that is undefined * into an import. */ { /* Remove the global flag and make it an import */ S->Flags &= ~SF_GLOBAL; S->Flags |= SF_IMPORT; } int SymIsConst (const SymEntry* S, long* Val) /* Return true if the given symbol has a constant value. If Val is not NULL * and the symbol has a constant value, store it's value there. */ { /* Check for constness */ return (SymHasExpr (S) && IsConstExpr (S->Expr, Val)); } SymTable* GetSymParentScope (SymEntry* S) /* Get the parent scope of the symbol (not the one it is defined in). Return * NULL if the symbol is a cheap local, or defined on global level. */ { if ((S->Flags & SF_LOCAL) != 0) { /* This is a cheap local symbol */ return 0; } else if (S->Sym.Tab == 0) { /* Symbol not in a table. This may happen if there have been errors * before. Return NULL in this case to avoid further errors. */ return 0; } else { /* This is a global symbol */ return S->Sym.Tab->Parent; } } struct ExprNode* GetSymExpr (SymEntry* S) /* Get the expression for a non-const symbol */ { PRECONDITION (S != 0 && SymHasExpr (S)); return S->Expr; } const struct ExprNode* SymResolve (const SymEntry* S) /* Helper function for DumpExpr. Resolves a symbol into an expression or return * NULL. Do not call in other contexts! */ { return SymHasExpr (S)? S->Expr : 0; } long GetSymVal (SymEntry* S) /* Return the value of a symbol assuming it's constant. FAIL will be called * in case the symbol is undefined or not constant. */ { long Val; CHECK (S != 0 && SymHasExpr (S) && IsConstExpr (GetSymExpr (S), &Val)); return Val; } unsigned GetSymImportId (const SymEntry* S) /* Return the import id for the given symbol */ { PRECONDITION (S != 0 && (S->Flags & SF_IMPORT) && S->ImportId != ~0U); return S->ImportId; } unsigned GetSymExportId (const SymEntry* S) /* Return the export id for the given symbol */ { PRECONDITION (S != 0 && (S->Flags & SF_EXPORT) && S->ExportId != ~0U); return S->ExportId; } unsigned GetSymInfoFlags (const SymEntry* S, long* ConstVal) /* Return a set of flags used when writing symbol information into a file. * If the SYM_CONST bit is set, ConstVal will contain the constant value * of the symbol. The result does not include the condes count. * See common/symdefs.h for more information. */ { /* Setup info flags */ unsigned Flags = 0; Flags |= SymIsConst (S, ConstVal)? SYM_CONST : SYM_EXPR; Flags |= (S->Flags & SF_LABEL)? SYM_LABEL : SYM_EQUATE; Flags |= (S->Flags & SF_LOCAL)? SYM_CHEAP_LOCAL : SYM_STD; if (S->Flags & SF_EXPORT) { Flags |= SYM_EXPORT; } if (S->Flags & SF_IMPORT) { Flags |= SYM_IMPORT; } /* Return the result */ return Flags; }
939
./cc65/src/ca65/ea65.c
/*****************************************************************************/ /* */ /* ea65.c */ /* */ /* 65XX effective address parsing for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* ca65 */ #include "ea.h" #include "ea65.h" #include "error.h" #include "expr.h" #include "instr.h" #include "nexttok.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void GetEA (EffAddr* A) /* Parse an effective address, return the result in A */ { unsigned long Restrictions; /* Clear the output struct */ A->AddrModeSet = 0; A->Expr = 0; /* Handle an addressing size override */ switch (CurTok.Tok) { case TOK_OVERRIDE_ZP: Restrictions = AM65_DIR | AM65_DIR_X | AM65_DIR_Y; NextTok (); break; case TOK_OVERRIDE_ABS: Restrictions = AM65_ABS | AM65_ABS_X | AM65_ABS_Y; NextTok (); break; case TOK_OVERRIDE_FAR: Restrictions = AM65_ABS_LONG | AM65_ABS_LONG_X; NextTok (); break; default: Restrictions = ~0UL; /* None */ break; } /* Parse the effective address */ if (TokIsSep (CurTok.Tok)) { A->AddrModeSet = AM65_IMPLICIT; } else if (CurTok.Tok == TOK_HASH) { /* #val */ NextTok (); A->Expr = Expression (); A->AddrModeSet = AM65_ALL_IMM; } else if (CurTok.Tok == TOK_A) { NextTok (); A->AddrModeSet = AM65_ACCU; } else if (CurTok.Tok == TOK_LBRACK) { /* [dir] or [dir],y */ NextTok (); A->Expr = Expression (); Consume (TOK_RBRACK, "']' expected"); if (CurTok.Tok == TOK_COMMA) { /* [dir],y */ NextTok (); Consume (TOK_Y, "`Y' expected"); A->AddrModeSet = AM65_DIR_IND_LONG_Y; } else { /* [dir] */ A->AddrModeSet = AM65_DIR_IND_LONG; } } else if (CurTok.Tok == TOK_LPAREN) { /* One of the indirect modes */ NextTok (); A->Expr = Expression (); if (CurTok.Tok == TOK_COMMA) { /* (expr,X) or (rel,S),y */ NextTok (); if (CurTok.Tok == TOK_X) { /* (adr,x) */ NextTok (); A->AddrModeSet = AM65_ABS_X_IND | AM65_DIR_X_IND; ConsumeRParen (); } else if (CurTok.Tok == TOK_S) { /* (rel,s),y */ NextTok (); A->AddrModeSet = AM65_STACK_REL_IND_Y; ConsumeRParen (); ConsumeComma (); Consume (TOK_Y, "`Y' expected"); } else { Error ("Syntax error"); } } else { /* (adr) or (adr),y */ ConsumeRParen (); if (CurTok.Tok == TOK_COMMA) { /* (adr),y */ NextTok (); Consume (TOK_Y, "`Y' expected"); A->AddrModeSet = AM65_DIR_IND_Y; } else { /* (adr) */ A->AddrModeSet = AM65_ABS_IND | AM65_DIR_IND; } } } else { /* Remaining stuff: * * adr * adr,x * adr,y * adr,s */ A->Expr = Expression (); if (CurTok.Tok == TOK_COMMA) { NextTok (); switch (CurTok.Tok) { case TOK_X: A->AddrModeSet = AM65_ABS_LONG_X | AM65_ABS_X | AM65_DIR_X; NextTok (); break; case TOK_Y: A->AddrModeSet = AM65_ABS_Y | AM65_DIR_Y; NextTok (); break; case TOK_S: A->AddrModeSet = AM65_STACK_REL; NextTok (); break; default: Error ("Syntax error"); } } else { A->AddrModeSet = AM65_ABS_LONG | AM65_ABS | AM65_DIR; } } /* Apply addressing mode overrides */ A->AddrModeSet &= Restrictions; }
940
./cc65/src/ca65/condasm.c
/*****************************************************************************/ /* */ /* condasm.c */ /* */ /* Conditional assembly support for ca65 */ /* */ /* */ /* */ /* (C) 2000-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* ca65 */ #include "error.h" #include "expr.h" #include "instr.h" #include "lineinfo.h" #include "nexttok.h" #include "symbol.h" #include "symtab.h" #include "condasm.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Maximum count of nested .ifs */ #define MAX_IFS 256 /* Set of bitmapped flags for the if descriptor */ enum { ifNone = 0x0000, /* No flag */ ifCond = 0x0001, /* IF condition was true */ ifParentCond= 0x0002, /* IF condition of parent */ ifElse = 0x0004, /* We had a .ELSE branch */ ifNeedTerm = 0x0008, /* Need .ENDIF termination */ }; /* The overall .IF condition */ int IfCond = 1; /*****************************************************************************/ /* struct IfDesc */ /*****************************************************************************/ /* One .IF descriptor */ typedef struct IfDesc IfDesc; struct IfDesc { unsigned Flags; /* Bitmapped flags, see above */ Collection LineInfos; /* File position of the .IF */ const char* Name; /* Name of the directive */ }; /* The .IF stack */ static IfDesc IfStack [MAX_IFS]; static unsigned IfCount = 0; static IfDesc* GetCurrentIf (void) /* Return the current .IF descriptor */ { if (IfCount == 0) { return 0; } else { return &IfStack[IfCount-1]; } } static int GetOverallIfCond (void) /* Get the overall condition based on all conditions on the stack. */ { /* Since the last entry contains the overall condition of the parent, we * must check it in combination of the current condition. If there is no * last entry, the overall condition is true. */ return (IfCount == 0) || ((IfStack[IfCount-1].Flags & (ifCond | ifParentCond)) == (ifCond | ifParentCond)); } static void CalcOverallIfCond (void) /* Caclulate the overall condition based on all conditions on the stack. */ { IfCond = GetOverallIfCond (); } static void SetIfCond (IfDesc* ID, int C) /* Set the .IF condition */ { if (C) { ID->Flags |= ifCond; } else { ID->Flags &= ~ifCond; } } static void ElseClause (IfDesc* ID, const char* Directive) /* Enter an .ELSE clause */ { /* Check if we have an open .IF - otherwise .ELSE is not allowed */ if (ID == 0) { Error ("Unexpected %s", Directive); return; } /* Check for a duplicate else, then remember that we had one */ if (ID->Flags & ifElse) { /* We already had a .ELSE ! */ Error ("Duplicate .ELSE"); } ID->Flags |= ifElse; /* Condition is inverted now */ ID->Flags ^= ifCond; } static IfDesc* AllocIf (const char* Directive, int NeedTerm) /* Alloc a new element from the .IF stack */ { IfDesc* ID; /* Check for stack overflow */ if (IfCount >= MAX_IFS) { Fatal ("Too many nested .IFs"); } /* Get the next element */ ID = &IfStack[IfCount]; /* Initialize elements */ ID->Flags = NeedTerm? ifNeedTerm : ifNone; if (GetOverallIfCond ()) { /* The parents .IF condition is true */ ID->Flags |= ifParentCond; } ID->LineInfos = EmptyCollection; GetFullLineInfo (&ID->LineInfos); ID->Name = Directive; /* One more slot allocated */ ++IfCount; /* Return the result */ return ID; } static void FreeIf (void) /* Free all .IF descriptors until we reach one with the NeedTerm bit set */ { int Done; do { IfDesc* ID = GetCurrentIf(); if (ID == 0) { Error (" Unexpected .ENDIF"); Done = 1; } else { Done = (ID->Flags & ifNeedTerm) != 0; ReleaseFullLineInfo (&ID->LineInfos); DoneCollection (&ID->LineInfos); --IfCount; } } while (!Done); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ void DoConditionals (void) /* Catch all for conditional directives */ { IfDesc* D; do { switch (CurTok.Tok) { case TOK_ELSE: D = GetCurrentIf (); /* Allow an .ELSE */ ElseClause (D, ".ELSE"); /* Remember the data for the .ELSE */ if (D) { ReleaseFullLineInfo (&D->LineInfos); GetFullLineInfo (&D->LineInfos); D->Name = ".ELSE"; } /* Calculate the new overall condition */ CalcOverallIfCond (); /* Skip .ELSE */ NextTok (); ExpectSep (); break; case TOK_ELSEIF: D = GetCurrentIf (); /* Handle as if there was an .ELSE first */ ElseClause (D, ".ELSEIF"); /* Calculate the new overall if condition */ CalcOverallIfCond (); /* Allocate and prepare a new descriptor */ D = AllocIf (".ELSEIF", 0); NextTok (); /* Ignore the new condition if we are inside a false .ELSE * branch. This way we won't get any errors about undefined * symbols or similar... */ if (IfCond) { SetIfCond (D, ConstExpression ()); ExpectSep (); } /* Get the new overall condition */ CalcOverallIfCond (); break; case TOK_ENDIF: /* We're done with this .IF.. - remove the descriptor(s) */ FreeIf (); /* Be sure not to read the next token until the .IF stack * has been cleanup up, since we may be at end of file. */ NextTok (); ExpectSep (); /* Get the new overall condition */ CalcOverallIfCond (); break; case TOK_IF: D = AllocIf (".IF", 1); NextTok (); if (IfCond) { SetIfCond (D, ConstExpression ()); ExpectSep (); } CalcOverallIfCond (); break; case TOK_IFBLANK: D = AllocIf (".IFBLANK", 1); NextTok (); if (IfCond) { if (TokIsSep (CurTok.Tok)) { SetIfCond (D, 1); } else { SetIfCond (D, 0); SkipUntilSep (); } } CalcOverallIfCond (); break; case TOK_IFCONST: D = AllocIf (".IFCONST", 1); NextTok (); if (IfCond) { ExprNode* Expr = Expression(); SetIfCond (D, IsConstExpr (Expr, 0)); FreeExpr (Expr); ExpectSep (); } CalcOverallIfCond (); break; case TOK_IFDEF: D = AllocIf (".IFDEF", 1); NextTok (); if (IfCond) { SymEntry* Sym = ParseAnySymName (SYM_FIND_EXISTING); SetIfCond (D, Sym != 0 && SymIsDef (Sym)); } CalcOverallIfCond (); break; case TOK_IFNBLANK: D = AllocIf (".IFNBLANK", 1); NextTok (); if (IfCond) { if (TokIsSep (CurTok.Tok)) { SetIfCond (D, 0); } else { SetIfCond (D, 1); SkipUntilSep (); } } CalcOverallIfCond (); break; case TOK_IFNCONST: D = AllocIf (".IFNCONST", 1); NextTok (); if (IfCond) { ExprNode* Expr = Expression(); SetIfCond (D, !IsConstExpr (Expr, 0)); FreeExpr (Expr); ExpectSep (); } CalcOverallIfCond (); break; case TOK_IFNDEF: D = AllocIf (".IFNDEF", 1); NextTok (); if (IfCond) { SymEntry* Sym = ParseAnySymName (SYM_FIND_EXISTING); SetIfCond (D, Sym == 0 || !SymIsDef (Sym)); ExpectSep (); } CalcOverallIfCond (); break; case TOK_IFNREF: D = AllocIf (".IFNREF", 1); NextTok (); if (IfCond) { SymEntry* Sym = ParseAnySymName (SYM_FIND_EXISTING); SetIfCond (D, Sym == 0 || !SymIsRef (Sym)); ExpectSep (); } CalcOverallIfCond (); break; case TOK_IFP02: D = AllocIf (".IFP02", 1); NextTok (); if (IfCond) { SetIfCond (D, GetCPU() == CPU_6502); } ExpectSep (); CalcOverallIfCond (); break; case TOK_IFP816: D = AllocIf (".IFP816", 1); NextTok (); if (IfCond) { SetIfCond (D, GetCPU() == CPU_65816); } ExpectSep (); CalcOverallIfCond (); break; case TOK_IFPC02: D = AllocIf (".IFPC02", 1); NextTok (); if (IfCond) { SetIfCond (D, GetCPU() == CPU_65C02); } ExpectSep (); CalcOverallIfCond (); break; case TOK_IFPSC02: D = AllocIf (".IFPSC02", 1); NextTok (); if (IfCond) { SetIfCond (D, GetCPU() == CPU_65SC02); } ExpectSep (); CalcOverallIfCond (); break; case TOK_IFREF: D = AllocIf (".IFREF", 1); NextTok (); if (IfCond) { SymEntry* Sym = ParseAnySymName (SYM_FIND_EXISTING); SetIfCond (D, Sym != 0 && SymIsRef (Sym)); ExpectSep (); } CalcOverallIfCond (); break; default: /* Skip tokens */ NextTok (); } } while (IfCond == 0 && CurTok.Tok != TOK_EOF); } int CheckConditionals (void) /* Check if the current token is one that starts a conditional directive, and * call DoConditionals if so. Return true if a conditional directive was found, * return false otherwise. */ { switch (CurTok.Tok) { case TOK_ELSE: case TOK_ELSEIF: case TOK_ENDIF: case TOK_IF: case TOK_IFBLANK: case TOK_IFCONST: case TOK_IFDEF: case TOK_IFNBLANK: case TOK_IFNCONST: case TOK_IFNDEF: case TOK_IFNREF: case TOK_IFP02: case TOK_IFP816: case TOK_IFPC02: case TOK_IFPSC02: case TOK_IFREF: DoConditionals (); return 1; default: return 0; } } void CheckOpenIfs (void) /* Called from the scanner before closing an input file. Will check for any * open .ifs in this file. */ { const LineInfo* LI; while (1) { /* Get the current file number and check if the topmost entry on the * .IF stack was inserted with this file number */ IfDesc* D = GetCurrentIf (); if (D == 0) { /* There are no open .IFs */ break; } LI = CollConstAt (&D->LineInfos, 0); if (GetSourcePos (LI)->Name != CurTok.Pos.Name) { /* The .if is from another file, bail out */ break; } /* Start of .if is in the file we're about to leave */ LIError (&D->LineInfos, "Conditional assembly branch was never closed"); FreeIf (); } /* Calculate the new overall .IF condition */ CalcOverallIfCond (); } unsigned GetIfStack (void) /* Get the current .IF stack pointer */ { return IfCount; } void CleanupIfStack (unsigned SP) /* Cleanup the .IF stack, remove anything above the given stack pointer */ { while (IfCount > SP) { FreeIf (); } /* Calculate the new overall .IF condition */ CalcOverallIfCond (); }
941
./cc65/src/ca65/main.c
/* */ /* main.c */ /* */ /* Main program for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> /* common */ #include "addrsize.h" #include "chartype.h" #include "cmdline.h" #include "debugflag.h" #include "mmodel.h" #include "print.h" #include "scopedefs.h" #include "strbuf.h" #include "target.h" #include "tgttrans.h" #include "version.h" /* ca65 */ #include "abend.h" #include "asserts.h" #include "dbginfo.h" #include "error.h" #include "expr.h" #include "feature.h" #include "filetab.h" #include "global.h" #include "incpath.h" #include "instr.h" #include "istack.h" #include "lineinfo.h" #include "listing.h" #include "macro.h" #include "nexttok.h" #include "objfile.h" #include "options.h" #include "pseudo.h" #include "scanner.h" #include "segment.h" #include "sizeof.h" #include "span.h" #include "spool.h" #include "symbol.h" #include "symtab.h" #include "ulabel.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void Usage (void) /* Print usage information and exit */ { printf ("Usage: %s [options] file\n" "Short options:\n" " -D name[=value]\t\tDefine a symbol\n" " -I dir\t\t\tSet an include directory search path\n" " -U\t\t\t\tMark unresolved symbols as import\n" " -V\t\t\t\tPrint the assembler version\n" " -W n\t\t\t\tSet warning level n\n" " -d\t\t\t\tDebug mode\n" " -g\t\t\t\tAdd debug info to object file\n" " -h\t\t\t\tHelp (this text)\n" " -i\t\t\t\tIgnore case of symbols\n" " -l name\t\t\tCreate a listing file if assembly was ok\n" " -mm model\t\t\tSet the memory model\n" " -o name\t\t\tName the output file\n" " -s\t\t\t\tEnable smart mode\n" " -t sys\t\t\tSet the target system\n" " -v\t\t\t\tIncrease verbosity\n" "\n" "Long options:\n" " --auto-import\t\t\tMark unresolved symbols as import\n" " --bin-include-dir dir\t\tSet a search path for binary includes\n" " --cpu type\t\t\tSet cpu type\n" " --create-dep name\t\tCreate a make dependency file\n" " --create-full-dep name\tCreate a full make dependency file\n" " --debug\t\t\tDebug mode\n" " --debug-info\t\t\tAdd debug info to object file\n" " --feature name\t\tSet an emulation feature\n" " --help\t\t\tHelp (this text)\n" " --ignore-case\t\t\tIgnore case of symbols\n" " --include-dir dir\t\tSet an include directory search path\n" " --large-alignment\t\tDon't warn about large alignments\n" " --listing name\t\tCreate a listing file if assembly was ok\n" " --list-bytes n\t\tMaximum number of bytes per listing line\n" " --macpack-dir dir\t\tSet a macro package directory\n" " --memory-model model\t\tSet the memory model\n" " --pagelength n\t\tSet the page length for the listing\n" " --relax-checks\t\tRelax some checks (see docs)\n" " --smart\t\t\tEnable smart mode\n" " --target sys\t\t\tSet the target system\n" " --verbose\t\t\tIncrease verbosity\n" " --version\t\t\tPrint the assembler version\n", ProgName); } static void SetOptions (void) /* Set the option for the translator */ { StrBuf Buf = STATIC_STRBUF_INITIALIZER; /* Set the translator */ SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ()); OptTranslator (&Buf); /* Set date and time */ OptDateTime ((unsigned long) time(0)); /* Release memory for the string */ SB_Done (&Buf); } static void NewSymbol (const char* SymName, long Val) /* Define a symbol with a fixed numeric value in the current scope */ { ExprNode* Expr; SymEntry* Sym; /* Convert the name to a string buffer */ StrBuf SymBuf = STATIC_STRBUF_INITIALIZER; SB_CopyStr (&SymBuf, SymName); /* Search for the symbol, allocate a new one if it doesn't exist */ Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW); /* Check if have already a symbol with this name */ if (SymIsDef (Sym)) { AbEnd ("`%s' is already defined", SymName); } /* Generate an expression for the symbol */ Expr = GenLiteralExpr (Val); /* Mark the symbol as defined */ SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE); /* Free string buffer memory */ SB_Done (&SymBuf); } static void CBMSystem (const char* Sys) /* Define a CBM system */ { NewSymbol ("__CBM__", 1); NewSymbol (Sys, 1); } static void SetSys (const char* Sys) /* Define a target system */ { switch (Target = FindTarget (Sys)) { case TGT_NONE: break; case TGT_MODULE: AbEnd ("Cannot use `module' as a target for the assembler"); break; case TGT_ATARI: NewSymbol ("__ATARI__", 1); break; case TGT_ATARIXL: NewSymbol ("__ATARI__", 1); NewSymbol ("__ATARIXL__", 1); break; case TGT_C16: CBMSystem ("__C16__"); break; case TGT_C64: CBMSystem ("__C64__"); break; case TGT_VIC20: CBMSystem ("__VIC20__"); break; case TGT_C128: CBMSystem ("__C128__"); break; case TGT_PLUS4: CBMSystem ("__PLUS4__"); break; case TGT_CBM510: CBMSystem ("__CBM510__"); break; case TGT_CBM610: CBMSystem ("__CBM610__"); break; case TGT_PET: CBMSystem ("__PET__"); break; case TGT_BBC: NewSymbol ("__BBC__", 1); break; case TGT_APPLE2: NewSymbol ("__APPLE2__", 1); break; case TGT_APPLE2ENH: NewSymbol ("__APPLE2__", 1); NewSymbol ("__APPLE2ENH__", 1); break; case TGT_GEOS_CBM: /* Do not handle as a CBM system */ NewSymbol ("__GEOS__", 1); NewSymbol ("__GEOS_CBM__", 1); break; case TGT_GEOS_APPLE: NewSymbol ("__GEOS__", 1); NewSymbol ("__GEOS_APPLE__", 1); break; case TGT_LUNIX: NewSymbol ("__LUNIX__", 1); break; case TGT_ATMOS: NewSymbol ("__ATMOS__", 1); break; case TGT_NES: NewSymbol ("__NES__", 1); break; case TGT_SUPERVISION: NewSymbol ("__SUPERVISION__", 1); break; case TGT_LYNX: NewSymbol ("__LYNX__", 1); break; case TGT_SIM6502: NewSymbol ("__SIM6502__", 1); break; case TGT_SIM65C02: NewSymbol ("__SIM65C02__", 1); break; default: AbEnd ("Invalid target name: `%s'", Sys); } /* Initialize the translation tables for the target system */ TgtTranslateInit (); } static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name) /* Handle an option that remembers a file name for later */ { /* Cannot have the option twice */ if (SB_NotEmpty (Name)) { AbEnd ("Cannot use option `%s' twice", Opt); } /* Remember the file name for later */ SB_CopyStr (Name, Arg); SB_Terminate (Name); } static void DefineSymbol (const char* Def) /* Define a symbol from the command line */ { const char* P; long Val; StrBuf SymName = AUTO_STRBUF_INITIALIZER; /* The symbol must start with a character or underline */ if (!IsIdStart (Def [0])) { InvDef (Def); } P = Def; /* Copy the symbol, checking the rest */ while (IsIdChar (*P)) { SB_AppendChar (&SymName, *P++); } SB_Terminate (&SymName); /* Do we have a value given? */ if (*P != '=') { if (*P != '\0') { InvDef (Def); } Val = 0; } else { /* We have a value */ ++P; if (*P == '$') { ++P; if (sscanf (P, "%lx", &Val) != 1) { InvDef (Def); } } else { if (sscanf (P, "%li", &Val) != 1) { InvDef (Def); } } } /* Define the new symbol */ NewSymbol (SB_GetConstBuf (&SymName), Val); /* Release string memory */ SB_Done (&SymName); } static void OptAutoImport (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Mark unresolved symbols as imported */ { AutoImport = 1; } static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg) /* Add an include search path for binaries */ { AddSearchPath (BinSearchPath, Arg); } static void OptCPU (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --cpu option */ { cpu_t CPU = FindCPU (Arg); if (CPU == CPU_UNKNOWN) { AbEnd ("Invalid CPU: `%s'", Arg); } else { SetCPU (CPU); } } static void OptCreateDep (const char* Opt, const char* Arg) /* Handle the --create-dep option */ { FileNameOption (Opt, Arg, &DepName); } static void OptCreateFullDep (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --create-full-dep option */ { FileNameOption (Opt, Arg, &FullDepName); } static void OptDebug (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Compiler debug mode */ { ++Debug; } static void OptDebugInfo (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Add debug info to the object file */ { DbgSyms = 1; } static void OptFeature (const char* Opt attribute ((unused)), const char* Arg) /* Set an emulation feature */ { /* Make a string buffer from Arg */ StrBuf Feature; /* Set the feature, check for errors */ if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) { AbEnd ("Illegal emulation feature: `%s'", Arg); } } static void OptHelp (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Print usage information and exit */ { Usage (); exit (EXIT_SUCCESS); } static void OptIgnoreCase (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Ignore case on symbols */ { IgnoreCase = 1; } static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg) /* Add an include search path */ { AddSearchPath (IncSearchPath, Arg); } static void OptLargeAlignment (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Don't warn about large alignments */ { LargeAlignment = 1; } static void OptListBytes (const char* Opt, const char* Arg) /* Set the maximum number of bytes per listing line */ { unsigned Num; char Check; /* Convert the argument to a number */ if (sscanf (Arg, "%u%c", &Num, &Check) != 1) { InvArg (Opt, Arg); } /* Check the bounds */ if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) { AbEnd ("Argument for option `%s' is out of range", Opt); } /* Use the value */ SetListBytes (Num); } static void OptListing (const char* Opt, const char* Arg) /* Create a listing file */ { /* Since the meaning of -l and --listing has changed, print an error if * the filename is empty or begins with the option char. */ if (Arg == 0 || *Arg == '\0' || *Arg == '-') { Fatal ("The meaning of `%s' has changed. It does now " "expect a file name as argument.", Opt); } /* Get the file name */ FileNameOption (Opt, Arg, &ListingName); } static void OptMemoryModel (const char* Opt, const char* Arg) /* Set the memory model */ { mmodel_t M; /* Check the current memory model */ if (MemoryModel != MMODEL_UNKNOWN) { AbEnd ("Cannot use option `%s' twice", Opt); } /* Translate the memory model name and check it */ M = FindMemoryModel (Arg); if (M == MMODEL_UNKNOWN) { AbEnd ("Unknown memory model: %s", Arg); } else if (M == MMODEL_HUGE) { AbEnd ("Unsupported memory model: %s", Arg); } /* Set the memory model */ SetMemoryModel (M); } static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --pagelength option */ { int Len = atoi (Arg); if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) { AbEnd ("Invalid page length: %d", Len); } PageLength = Len; } static void OptRelaxChecks (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Handle the --relax-checks options */ { RelaxChecks = 1; } static void OptSmart (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Handle the -s/--smart options */ { SmartMode = 1; } static void OptTarget (const char* Opt attribute ((unused)), const char* Arg) /* Set the target system */ { SetSys (Arg); } static void OptVerbose (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Increase verbosity */ { ++Verbosity; } static void OptVersion (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Print the assembler version */ { fprintf (stderr, "ca65 V%s\n", GetVersionAsString ()); } static void DoPCAssign (void) /* Start absolute code */ { long PC = ConstExpression (); if (PC < 0 || PC > 0xFFFFFF) { Error ("Range error"); } else { EnterAbsoluteMode (PC); } } static void OneLine (void) /* Assemble one line */ { Segment* Seg = 0; unsigned long PC = 0; SymEntry* Sym = 0; Macro* Mac = 0; int Instr = -1; /* Initialize the new listing line if we are actually reading from file * and not from internally pushed input. */ if (!HavePushedInput ()) { InitListingLine (); } /* Single colon means unnamed label */ if (CurTok.Tok == TOK_COLON) { ULabDef (); NextTok (); } /* If the first token on the line is an identifier, check for a macro or * an instruction. */ if (CurTok.Tok == TOK_IDENT) { if (!UbiquitousIdents) { /* Macros and symbols cannot use instruction names */ Instr = FindInstruction (&CurTok.SVal); if (Instr < 0) { Mac = FindMacro (&CurTok.SVal); } } else { /* Macros and symbols may use the names of instructions */ Mac = FindMacro (&CurTok.SVal); } } /* Handle an identifier. This may be a cheap local symbol, or a fully * scoped identifier which may start with a namespace token (for global * namespace) */ if (CurTok.Tok == TOK_LOCAL_IDENT || CurTok.Tok == TOK_NAMESPACE || (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) { /* Did we have whitespace before the ident? */ int HadWS = CurTok.WS; /* Generate the symbol table entry, then skip the name */ Sym = ParseAnySymName (SYM_ALLOC_NEW); /* If a colon follows, this is a label definition. If there * is no colon, it's an assignment. */ if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) { /* Determine the symbol flags from the assignment token */ unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE; /* Skip the '=' */ NextTok (); /* Define the symbol with the expression following the '=' */ SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags); /* Don't allow anything after a symbol definition */ ConsumeSep (); return; } else if (CurTok.Tok == TOK_SET) { ExprNode* Expr; /* .SET defines variables (= redefinable symbols) */ NextTok (); /* Read the assignment expression, which must be constant */ Expr = GenLiteralExpr (ConstExpression ()); /* Define the symbol with the constant expression following * the '=' */ SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR); /* Don't allow anything after a symbol definition */ ConsumeSep (); return; } else { /* A label. Remember the current segment, so we can later * determine the size of the data stored under the label. */ Seg = ActiveSeg; PC = GetPC (); /* Define the label */ SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL); /* Skip the colon. If NoColonLabels is enabled, allow labels * without a colon if there is no whitespace before the * identifier. */ if (CurTok.Tok != TOK_COLON) { if (HadWS || !NoColonLabels) { Error ("`:' expected"); /* Try some smart error recovery */ if (CurTok.Tok == TOK_NAMESPACE) { NextTok (); } } } else { /* Skip the colon */ NextTok (); } /* If we come here, a new identifier may be waiting, which may * be a macro or instruction. */ if (CurTok.Tok == TOK_IDENT) { if (!UbiquitousIdents) { /* Macros and symbols cannot use instruction names */ Instr = FindInstruction (&CurTok.SVal); if (Instr < 0) { Mac = FindMacro (&CurTok.SVal); } } else { /* Macros and symbols may use the names of instructions */ Mac = FindMacro (&CurTok.SVal); } } } } /* We've handled a possible label, now handle the remainder of the line */ if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) { /* A control command */ HandlePseudo (); } else if (Mac != 0) { /* A macro expansion */ MacExpandStart (Mac); } else if (Instr >= 0 || (UbiquitousIdents && ((Instr = FindInstruction (&CurTok.SVal)) >= 0))) { /* A mnemonic - assemble one instruction */ HandleInstruction (Instr); } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) { NextTok (); if (CurTok.Tok != TOK_EQ) { Error ("`=' expected"); SkipUntilSep (); } else { /* Skip the equal sign */ NextTok (); /* Enter absolute mode */ DoPCAssign (); } } /* If we have defined a label, remember its size. Sym is also set by * a symbol assignment, but in this case Done is false, so we don't * come here. */ if (Sym) { unsigned long Size; if (Seg == ActiveSeg) { /* Same segment */ Size = GetPC () - PC; } else { /* The line has switched the segment */ Size = 0; } DefSizeOfSymbol (Sym, Size); } /* Line separator must come here */ ConsumeSep (); } static void Assemble (void) /* Start the ball rolling ... */ { /* Prime the pump */ NextTok (); /* Assemble lines until end of file */ while (CurTok.Tok != TOK_EOF) { OneLine (); } } static void CreateObjFile (void) /* Create the object file */ { /* Open the object, write the header */ ObjOpen (); /* Write the object file options */ WriteOptions (); /* Write the list of input files */ WriteFiles (); /* Write the segment data to the file */ WriteSegments (); /* Write the import list */ WriteImports (); /* Write the export list */ WriteExports (); /* Write debug symbols if requested */ WriteDbgSyms (); /* Write the scopes if requested */ WriteScopes (); /* Write line infos if requested */ WriteLineInfos (); /* Write the string pool */ WriteStrPool (); /* Write the assertions */ WriteAssertions (); /* Write the spans */ WriteSpans (); /* Write an updated header and close the file */ ObjClose (); } int main (int argc, char* argv []) /* Assembler main program */ { /* Program long options */ static const LongOpt OptTab[] = { { "--auto-import", 0, OptAutoImport }, { "--bin-include-dir", 1, OptBinIncludeDir }, { "--cpu", 1, OptCPU }, { "--create-dep", 1, OptCreateDep }, { "--create-full-dep", 1, OptCreateFullDep }, { "--debug", 0, OptDebug }, { "--debug-info", 0, OptDebugInfo }, { "--feature", 1, OptFeature }, { "--help", 0, OptHelp }, { "--ignore-case", 0, OptIgnoreCase }, { "--include-dir", 1, OptIncludeDir }, { "--large-alignment", 0, OptLargeAlignment }, { "--list-bytes", 1, OptListBytes }, { "--listing", 1, OptListing }, { "--memory-model", 1, OptMemoryModel }, { "--pagelength", 1, OptPageLength }, { "--relax-checks", 0, OptRelaxChecks }, { "--smart", 0, OptSmart }, { "--target", 1, OptTarget }, { "--verbose", 0, OptVerbose }, { "--version", 0, OptVersion }, }; /* Name of the global name space */ static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER; unsigned I; /* Initialize the cmdline module */ InitCmdLine (&argc, &argv, "ca65"); /* Initialize the string pool */ InitStrPool (); /* Initialize the include search paths */ InitIncludePaths (); /* Create the predefined segments */ SegInit (); /* Enter the base lexical level. We must do that here, since we may * define symbols using -D. */ SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0); /* Initialize the line infos. Must be done here, since we need line infos * for symbol definitions. */ InitLineInfo (); /* Check the parameters */ I = 1; while (I < ArgCount) { /* Get the argument */ const char* Arg = ArgVec [I]; /* Check for an option */ if (Arg[0] == '-') { switch (Arg[1]) { case '-': LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0])); break; case 'd': OptDebug (Arg, 0); break; case 'g': OptDebugInfo (Arg, 0); break; case 'h': OptHelp (Arg, 0); break; case 'i': OptIgnoreCase (Arg, 0); break; case 'l': OptListing (Arg, GetArg (&I, 2)); break; case 'm': if (Arg[2] == 'm') { OptMemoryModel (Arg, GetArg (&I, 3)); } else { UnknownOption (Arg); } break; case 'o': OutFile = GetArg (&I, 2); break; case 's': OptSmart (Arg, 0); break; case 't': OptTarget (Arg, GetArg (&I, 2)); break; case 'v': OptVerbose (Arg, 0); break; case 'D': DefineSymbol (GetArg (&I, 2)); break; case 'I': OptIncludeDir (Arg, GetArg (&I, 2)); break; case 'U': OptAutoImport (Arg, 0); break; case 'V': OptVersion (Arg, 0); break; case 'W': WarnLevel = atoi (GetArg (&I, 2)); break; default: UnknownOption (Arg); break; } } else { /* Filename. Check if we already had one */ if (InFile) { fprintf (stderr, "%s: Don't know what to do with `%s'\n", ProgName, Arg); exit (EXIT_FAILURE); } else { InFile = Arg; } } /* Next argument */ ++I; } /* Do we have an input file? */ if (InFile == 0) { fprintf (stderr, "%s: No input files\n", ProgName); exit (EXIT_FAILURE); } /* Add the default include search paths. */ FinishIncludePaths (); /* If no CPU given, use the default CPU for the target */ if (GetCPU () == CPU_UNKNOWN) { if (Target != TGT_UNKNOWN) { SetCPU (GetTargetProperties (Target)->DefaultCPU); } else { SetCPU (CPU_6502); } } /* If no memory model was given, use the default */ if (MemoryModel == MMODEL_UNKNOWN) { SetMemoryModel (MMODEL_NEAR); } /* Set the default segment sizes according to the memory model */ SetSegmentSizes (); /* Initialize the scanner, open the input file */ InitScanner (InFile); /* Define the default options */ SetOptions (); /* Assemble the input */ Assemble (); /* If we didn't have any errors, check the pseudo insn stacks */ if (ErrorCount == 0) { CheckPseudo (); } /* If we didn't have any errors, check and cleanup the unnamed labels */ if (ErrorCount == 0) { ULabDone (); } /* If we didn't have any errors, check the symbol table */ if (ErrorCount == 0) { SymCheck (); } /* If we didn't have any errors, check the hll debug symbols */ if (ErrorCount == 0) { DbgInfoCheck (); } /* If we didn't have any errors, close the file scope lexical level */ if (ErrorCount == 0) { SymLeaveLevel (); } /* If we didn't have any errors, check and resolve the segment data */ if (ErrorCount == 0) { SegDone (); } /* If we didn't have any errors, check the assertions */ if (ErrorCount == 0) { CheckAssertions (); } /* Dump the data */ if (Verbosity >= 2) { SymDump (stdout); SegDump (); } /* If we didn't have an errors, finish off the line infos */ DoneLineInfo (); /* If we didn't have any errors, create the object, listing and * dependency files */ if (ErrorCount == 0) { CreateObjFile (); if (SB_GetLen (&ListingName) > 0) { CreateListing (); } CreateDependencies (); } /* Close the input file */ DoneScanner (); /* Return an apropriate exit code */ return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE; }
942
./cc65/src/ca65/easw16.c
/*****************************************************************************/ /* */ /* easw16.c */ /* */ /* SWEET16 effective address parsing for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 2004-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* ca65 */ #include "ea.h" #include "ea65.h" #include "error.h" #include "expr.h" #include "instr.h" #include "nexttok.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static long RegNum () /* Try to read a register number specified not as a register (Rx) but as a * numeric value between 0 and 15. Return the register number or -1 on * failure. */ { long Val; ExprNode* Expr = Expression (); if (!IsConstExpr (Expr, &Val) || Val < 0 || Val > 15) { /* Invalid register */ Val = -1L; } /* Free the expression and return the register number */ FreeExpr (Expr); return Val; } void GetSweet16EA (EffAddr* A) /* Parse an effective address, return the result in A */ { long Reg; /* Clear the output struct */ A->AddrModeSet = 0; A->Expr = 0; A->Reg = 0; /* Parse the effective address */ if (TokIsSep (CurTok.Tok)) { A->AddrModeSet = AMSW16_IMP; } else if (CurTok.Tok == TOK_AT) { /* @reg or @regnumber */ A->AddrModeSet = AMSW16_IND; NextTok (); if (CurTok.Tok == TOK_REG) { A->Reg = (unsigned) CurTok.IVal; NextTok (); } else if ((Reg = RegNum ()) >= 0) { /* Register number */ A->Reg = (unsigned) Reg; } else { ErrorSkip ("Register or register number expected"); A->Reg = 0; } } else if (CurTok.Tok == TOK_REG) { A->Reg = (unsigned) CurTok.IVal; NextTok (); if (CurTok.Tok == TOK_COMMA) { /* Rx, constant */ NextTok (); A->Expr = Expression (); A->AddrModeSet = AMSW16_IMM; } else { A->AddrModeSet = AMSW16_REG; } } else { /* OPC ea or: OPC regnum, constant */ A->Expr = Expression (); A->AddrModeSet = AMSW16_BRA; /* If the value is a constant between 0 and 15, it may also be a * register number. */ if (IsConstExpr (A->Expr, &Reg) && Reg >= 0 && Reg <= 15) { FreeExpr (A->Expr); A->Reg = (unsigned) Reg; /* If a comma follows, it is: OPC Rx, constant */ if (CurTok.Tok == TOK_COMMA) { NextTok (); A->Expr = Expression (); A->AddrModeSet = AMSW16_IMM; } else { A->Expr = 0; A->AddrModeSet |= AMSW16_REG; } } } }
943
./cc65/src/ca65/global.c
/*****************************************************************************/ /* */ /* global.c */ /* */ /* Global variables for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "addrsize.h" /* ca65 */ #include "global.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* File names */ const char* InFile = 0; /* Name of input file */ const char* OutFile = 0; /* Name of output file */ StrBuf ListingName = STATIC_STRBUF_INITIALIZER; /* Name of listing file */ StrBuf DepName = STATIC_STRBUF_INITIALIZER; /* Dependency file */ StrBuf FullDepName = STATIC_STRBUF_INITIALIZER; /* Full dependency file */ /* Default extensions */ const char ObjExt[] = ".o";/* Default object extension */ char LocalStart = '@'; /* This char starts local symbols */ unsigned char IgnoreCase = 0; /* Ignore case on identifiers? */ unsigned char AutoImport = 0; /* Mark unresolveds as import */ unsigned char SmartMode = 0; /* Smart mode */ unsigned char DbgSyms = 0; /* Add debug symbols */ unsigned char LineCont = 0; /* Allow line continuation */ unsigned char LargeAlignment = 0; /* Don't warn about large alignments */ unsigned char RelaxChecks = 0; /* Relax a few assembler checks */ /* Emulation features */ unsigned char DollarIsPC = 0; /* Allow the $ symbol as current PC */ unsigned char NoColonLabels = 0; /* Allow labels without a colon */ unsigned char LooseStringTerm = 0; /* Allow ' as string terminator */ unsigned char LooseCharTerm = 0; /* Allow " for char constants */ unsigned char AtInIdents = 0; /* Allow '@' in identifiers */ unsigned char DollarInIdents = 0; /* Allow '$' in identifiers */ unsigned char LeadingDotInIdents = 0; /* Allow '.' to start an identifier */ unsigned char PCAssignment = 0; /* Allow "* = $XXX" or "$ = $XXX" */ unsigned char MissingCharTerm = 0; /* Allow lda #'a (no closing term) */ unsigned char UbiquitousIdents = 0; /* Allow ubiquitous identifiers */ unsigned char OrgPerSeg = 0; /* Make .org local to current seg */ unsigned char CComments = 0; /* Allow C like comments */ unsigned char ForceRange = 0; /* Force values into expected range */ unsigned char UnderlineInNumbers = 0; /* Allow underlines in numbers */
944
./cc65/src/ca65/scanner.c
/*****************************************************************************/ /* */ /* scanner.c */ /* */ /* The scanner for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> /* common */ #include "addrsize.h" #include "attrib.h" #include "chartype.h" #include "check.h" #include "filestat.h" #include "fname.h" #include "xmalloc.h" /* ca65 */ #include "condasm.h" #include "error.h" #include "filetab.h" #include "global.h" #include "incpath.h" #include "instr.h" #include "istack.h" #include "listing.h" #include "macro.h" #include "toklist.h" #include "scanner.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Current input token incl. attributes */ Token CurTok = STATIC_TOKEN_INITIALIZER; /* Struct to handle include files. */ typedef struct InputFile InputFile; struct InputFile { FILE* F; /* Input file descriptor */ FilePos Pos; /* Position in file */ token_t Tok; /* Last token */ int C; /* Last character */ StrBuf Line; /* The current input line */ int IncSearchPath; /* True if we've added a search path */ int BinSearchPath; /* True if we've added a search path */ InputFile* Next; /* Linked list of input files */ }; /* Struct to handle textual input data */ typedef struct InputData InputData; struct InputData { char* Text; /* Pointer to the text data */ const char* Pos; /* Pointer to current position */ int Malloced; /* Memory was malloced */ token_t Tok; /* Last token */ int C; /* Last character */ InputData* Next; /* Linked list of input data */ }; /* Input source: Either file or data */ typedef struct CharSource CharSource; /* Set of input functions */ typedef struct CharSourceFunctions CharSourceFunctions; struct CharSourceFunctions { void (*MarkStart) (CharSource*); /* Mark the start pos of a token */ void (*NextChar) (CharSource*); /* Read next char from input */ void (*Done) (CharSource*); /* Close input source */ }; /* Input source: Either file or data */ struct CharSource { CharSource* Next; /* Linked list of char sources */ token_t Tok; /* Last token */ int C; /* Last character */ const CharSourceFunctions* Func; /* Pointer to function table */ union { InputFile File; /* File data */ InputData Data; /* Textual data */ } V; }; /* Current input variables */ static CharSource* Source = 0; /* Current char source */ static unsigned FCount = 0; /* Count of input files */ static int C = 0; /* Current input character */ /* Force end of assembly */ int ForcedEnd = 0; /* List of dot keywords with the corresponding tokens */ struct DotKeyword { const char* Key; /* MUST be first field */ token_t Tok; } DotKeywords [] = { { ".A16", TOK_A16 }, { ".A8", TOK_A8 }, { ".ADDR", TOK_ADDR }, { ".ALIGN", TOK_ALIGN }, { ".AND", TOK_BOOLAND }, { ".ASCIIZ", TOK_ASCIIZ }, { ".ASSERT", TOK_ASSERT }, { ".AUTOIMPORT", TOK_AUTOIMPORT }, { ".BANK", TOK_BANK }, { ".BANKBYTE", TOK_BANKBYTE }, { ".BANKBYTES", TOK_BANKBYTES }, { ".BITAND", TOK_AND }, { ".BITNOT", TOK_NOT }, { ".BITOR", TOK_OR }, { ".BITXOR", TOK_XOR }, { ".BLANK", TOK_BLANK }, { ".BSS", TOK_BSS }, { ".BYT", TOK_BYTE }, { ".BYTE", TOK_BYTE }, { ".CASE", TOK_CASE }, { ".CHARMAP", TOK_CHARMAP }, { ".CODE", TOK_CODE }, { ".CONCAT", TOK_CONCAT }, { ".CONDES", TOK_CONDES }, { ".CONST", TOK_CONST }, { ".CONSTRUCTOR", TOK_CONSTRUCTOR }, { ".CPU", TOK_CPU }, { ".DATA", TOK_DATA }, { ".DBG", TOK_DBG }, { ".DBYT", TOK_DBYT }, { ".DEBUGINFO", TOK_DEBUGINFO }, { ".DEF", TOK_DEFINED }, { ".DEFINE", TOK_DEFINE }, { ".DEFINED", TOK_DEFINED }, { ".DELMAC", TOK_DELMAC }, { ".DELMACRO", TOK_DELMAC }, { ".DESTRUCTOR", TOK_DESTRUCTOR }, { ".DWORD", TOK_DWORD }, { ".ELSE", TOK_ELSE }, { ".ELSEIF", TOK_ELSEIF }, { ".END", TOK_END }, { ".ENDENUM", TOK_ENDENUM }, { ".ENDIF", TOK_ENDIF }, { ".ENDMAC", TOK_ENDMACRO }, { ".ENDMACRO", TOK_ENDMACRO }, { ".ENDPROC", TOK_ENDPROC }, { ".ENDREP", TOK_ENDREP }, { ".ENDREPEAT", TOK_ENDREP }, { ".ENDSCOPE", TOK_ENDSCOPE }, { ".ENDSTRUCT", TOK_ENDSTRUCT }, { ".ENDUNION", TOK_ENDUNION }, { ".ENUM", TOK_ENUM }, { ".ERROR", TOK_ERROR }, { ".EXITMAC", TOK_EXITMACRO }, { ".EXITMACRO", TOK_EXITMACRO }, { ".EXPORT", TOK_EXPORT }, { ".EXPORTZP", TOK_EXPORTZP }, { ".FARADDR", TOK_FARADDR }, { ".FATAL", TOK_FATAL }, { ".FEATURE", TOK_FEATURE }, { ".FILEOPT", TOK_FILEOPT }, { ".FOPT", TOK_FILEOPT }, { ".FORCEIMPORT", TOK_FORCEIMPORT }, { ".FORCEWORD", TOK_FORCEWORD }, { ".GLOBAL", TOK_GLOBAL }, { ".GLOBALZP", TOK_GLOBALZP }, { ".HIBYTE", TOK_HIBYTE }, { ".HIBYTES", TOK_HIBYTES }, { ".HIWORD", TOK_HIWORD }, { ".I16", TOK_I16 }, { ".I8", TOK_I8 }, { ".IDENT", TOK_MAKEIDENT }, { ".IF", TOK_IF }, { ".IFBLANK", TOK_IFBLANK }, { ".IFCONST", TOK_IFCONST }, { ".IFDEF", TOK_IFDEF }, { ".IFNBLANK", TOK_IFNBLANK }, { ".IFNCONST", TOK_IFNCONST }, { ".IFNDEF", TOK_IFNDEF }, { ".IFNREF", TOK_IFNREF }, { ".IFP02", TOK_IFP02 }, { ".IFP816", TOK_IFP816 }, { ".IFPC02", TOK_IFPC02 }, { ".IFPSC02", TOK_IFPSC02 }, { ".IFREF", TOK_IFREF }, { ".IMPORT", TOK_IMPORT }, { ".IMPORTZP", TOK_IMPORTZP }, { ".INCBIN", TOK_INCBIN }, { ".INCLUDE", TOK_INCLUDE }, { ".INTERRUPTOR", TOK_INTERRUPTOR }, { ".LEFT", TOK_LEFT }, { ".LINECONT", TOK_LINECONT }, { ".LIST", TOK_LIST }, { ".LISTBYTES", TOK_LISTBYTES }, { ".LOBYTE", TOK_LOBYTE }, { ".LOBYTES", TOK_LOBYTES }, { ".LOCAL", TOK_LOCAL }, { ".LOCALCHAR", TOK_LOCALCHAR }, { ".LOWORD", TOK_LOWORD }, { ".MAC", TOK_MACRO }, { ".MACPACK", TOK_MACPACK }, { ".MACRO", TOK_MACRO }, { ".MATCH", TOK_MATCH }, { ".MAX", TOK_MAX }, { ".MID", TOK_MID }, { ".MIN", TOK_MIN }, { ".MOD", TOK_MOD }, { ".NOT", TOK_BOOLNOT }, { ".NULL", TOK_NULL }, { ".OR", TOK_BOOLOR }, { ".ORG", TOK_ORG }, { ".OUT", TOK_OUT }, { ".P02", TOK_P02 }, { ".P816", TOK_P816 }, { ".PAGELEN", TOK_PAGELENGTH }, { ".PAGELENGTH", TOK_PAGELENGTH }, { ".PARAMCOUNT", TOK_PARAMCOUNT }, { ".PC02", TOK_PC02 }, { ".POPCPU", TOK_POPCPU }, { ".POPSEG", TOK_POPSEG }, { ".PROC", TOK_PROC }, { ".PSC02", TOK_PSC02 }, { ".PUSHCPU", TOK_PUSHCPU }, { ".PUSHSEG", TOK_PUSHSEG }, { ".REF", TOK_REFERENCED }, { ".REFERENCED", TOK_REFERENCED }, { ".RELOC", TOK_RELOC }, { ".REPEAT", TOK_REPEAT }, { ".RES", TOK_RES }, { ".RIGHT", TOK_RIGHT }, { ".RODATA", TOK_RODATA }, { ".SCOPE", TOK_SCOPE }, { ".SEGMENT", TOK_SEGMENT }, { ".SET", TOK_SET }, { ".SETCPU", TOK_SETCPU }, { ".SHL", TOK_SHL }, { ".SHR", TOK_SHR }, { ".SIZEOF", TOK_SIZEOF }, { ".SMART", TOK_SMART }, { ".SPRINTF", TOK_SPRINTF }, { ".STRAT", TOK_STRAT }, { ".STRING", TOK_STRING }, { ".STRLEN", TOK_STRLEN }, { ".STRUCT", TOK_STRUCT }, { ".SUNPLUS", TOK_SUNPLUS }, { ".TAG", TOK_TAG }, { ".TCOUNT", TOK_TCOUNT }, { ".TIME", TOK_TIME }, { ".UNDEF", TOK_UNDEF }, { ".UNDEFINE", TOK_UNDEF }, { ".UNION", TOK_UNION }, { ".VERSION", TOK_VERSION }, { ".WARNING", TOK_WARNING }, { ".WORD", TOK_WORD }, { ".XMATCH", TOK_XMATCH }, { ".XOR", TOK_BOOLXOR }, { ".ZEROPAGE", TOK_ZEROPAGE }, }; /*****************************************************************************/ /* CharSource functions */ /*****************************************************************************/ static void UseCharSource (CharSource* S) /* Initialize a new input source and start to use it. */ { /* Remember the current input char and token */ S->Tok = CurTok.Tok; S->C = C; /* Use the new input source */ S->Next = Source; Source = S; /* Read the first character from the new file */ S->Func->NextChar (S); /* Setup the next token so it will be skipped on the next call to * NextRawTok(). */ CurTok.Tok = TOK_SEP; } static void DoneCharSource (void) /* Close the top level character source */ { CharSource* S; /* First, call the type specific function */ Source->Func->Done (Source); /* Restore the old token */ CurTok.Tok = Source->Tok; C = Source->C; /* Remember the last stacked input source */ S = Source->Next; /* Delete the top level one ... */ xfree (Source); /* ... and use the one before */ Source = S; } /*****************************************************************************/ /* InputFile functions */ /*****************************************************************************/ static void IFMarkStart (CharSource* S) /* Mark the start of the next token */ { CurTok.Pos = S->V.File.Pos; } static void IFNextChar (CharSource* S) /* Read the next character from the input file */ { /* Check for end of line, read the next line if needed */ while (SB_GetIndex (&S->V.File.Line) >= SB_GetLen (&S->V.File.Line)) { unsigned Len; /* End of current line reached, read next line */ SB_Clear (&S->V.File.Line); while (1) { int N = fgetc (S->V.File.F); if (N == EOF) { /* End of file. Accept files without a newline at the end */ if (SB_NotEmpty (&S->V.File.Line)) { break; } /* No more data - add an empty line to the listing. This * is a small hack needed to keep the PC output in sync. */ NewListingLine (&EmptyStrBuf, S->V.File.Pos.Name, FCount); C = EOF; return; /* Check for end of line */ } else if (N == '\n') { /* End of line */ break; /* Collect other stuff */ } else { /* Append data to line */ SB_AppendChar (&S->V.File.Line, N); } } /* If we come here, we have a new input line. To avoid problems * with strange line terminators, remove all whitespace from the * end of the line, the add a single newline. */ Len = SB_GetLen (&S->V.File.Line); while (Len > 0 && IsSpace (SB_AtUnchecked (&S->V.File.Line, Len-1))) { --Len; } SB_Drop (&S->V.File.Line, SB_GetLen (&S->V.File.Line) - Len); SB_AppendChar (&S->V.File.Line, '\n'); /* Terminate the string buffer */ SB_Terminate (&S->V.File.Line); /* One more line */ S->V.File.Pos.Line++; /* Remember the new line for the listing */ NewListingLine (&S->V.File.Line, S->V.File.Pos.Name, FCount); } /* Set the column pointer */ S->V.File.Pos.Col = SB_GetIndex (&S->V.File.Line); /* Return the next character from the buffer */ C = SB_Get (&S->V.File.Line); } void IFDone (CharSource* S) /* Close the current input file */ { /* We're at the end of an include file. Check if we have any * open .IFs, or any open token lists in this file. This * enforcement is artificial, using conditionals that start * in one file and end in another are uncommon, and don't * allowing these things will help finding errors. */ CheckOpenIfs (); /* If we've added search paths for this file, remove them */ if (S->V.File.IncSearchPath) { PopSearchPath (IncSearchPath); } if (S->V.File.BinSearchPath) { PopSearchPath (BinSearchPath); } /* Free the line buffer */ SB_Done (&S->V.File.Line); /* Close the input file and decrement the file count. We will ignore * errors here, since we were just reading from the file. */ (void) fclose (S->V.File.F); --FCount; } /* Set of input file handling functions */ static const CharSourceFunctions IFFunc = { IFMarkStart, IFNextChar, IFDone }; int NewInputFile (const char* Name) /* Open a new input file. Returns true if the file could be successfully opened * and false otherwise. */ { int RetCode = 0; /* Return code. Assume an error. */ char* PathName = 0; FILE* F; struct stat Buf; StrBuf NameBuf; /* No need to initialize */ StrBuf Path = AUTO_STRBUF_INITIALIZER; unsigned FileIdx; CharSource* S; /* If this is the main file, just try to open it. If it's an include file, * search for it using the include path list. */ if (FCount == 0) { /* Main file */ F = fopen (Name, "r"); if (F == 0) { Fatal ("Cannot open input file `%s': %s", Name, strerror (errno)); } } else { /* We are on include level. Search for the file in the include * directories. */ PathName = SearchFile (IncSearchPath, Name); if (PathName == 0 || (F = fopen (PathName, "r")) == 0) { /* Not found or cannot open, print an error and bail out */ Error ("Cannot open include file `%s': %s", Name, strerror (errno)); goto ExitPoint; } /* Use the path name from now on */ Name = PathName; } /* Stat the file and remember the values. There a race condition here, * since we cannot use fileno() (non standard identifier in standard * header file), and therefore not fstat. When using stat with the * file name, there's a risk that the file was deleted and recreated * while it was open. Since mtime and size are only used to check * if a file has changed in the debugger, we will ignore this problem * here. */ if (FileStat (Name, &Buf) != 0) { Fatal ("Cannot stat input file `%s': %s", Name, strerror (errno)); } /* Add the file to the input file table and remember the index */ FileIdx = AddFile (SB_InitFromString (&NameBuf, Name), (FCount == 0)? FT_MAIN : FT_INCLUDE, Buf.st_size, (unsigned long) Buf.st_mtime); /* Create a new input source variable and initialize it */ S = xmalloc (sizeof (*S)); S->Func = &IFFunc; S->V.File.F = F; S->V.File.Pos.Line = 0; S->V.File.Pos.Col = 0; S->V.File.Pos.Name = FileIdx; SB_Init (&S->V.File.Line); /* Push the path for this file onto the include search lists */ SB_CopyBuf (&Path, Name, FindName (Name) - Name); SB_Terminate (&Path); S->V.File.IncSearchPath = PushSearchPath (IncSearchPath, SB_GetConstBuf (&Path)); S->V.File.BinSearchPath = PushSearchPath (BinSearchPath, SB_GetConstBuf (&Path)); SB_Done (&Path); /* Count active input files */ ++FCount; /* Use this input source */ UseCharSource (S); /* File successfully opened */ RetCode = 1; ExitPoint: /* Free an allocated name buffer */ xfree (PathName); /* Return the success code */ return RetCode; } /*****************************************************************************/ /* InputData functions */ /*****************************************************************************/ static void IDMarkStart (CharSource* S attribute ((unused))) /* Mark the start of the next token */ { /* Nothing to do here */ } static void IDNextChar (CharSource* S) /* Read the next character from the input text */ { C = *S->V.Data.Pos++; if (C == '\0') { /* End of input data */ --S->V.Data.Pos; C = EOF; } } void IDDone (CharSource* S) /* Close the current input data */ { /* Cleanup the current stuff */ if (S->V.Data.Malloced) { xfree (S->V.Data.Text); } } /* Set of input data handling functions */ static const CharSourceFunctions IDFunc = { IDMarkStart, IDNextChar, IDDone }; void NewInputData (char* Text, int Malloced) /* Add a chunk of input data to the input stream */ { CharSource* S; /* Create a new input source variable and initialize it */ S = xmalloc (sizeof (*S)); S->Func = &IDFunc; S->V.Data.Text = Text; S->V.Data.Pos = Text; S->V.Data.Malloced = Malloced; /* Use this input source */ UseCharSource (S); } /*****************************************************************************/ /* Character classification functions */ /*****************************************************************************/ int IsIdChar (int C) /* Return true if the character is a valid character for an identifier */ { return IsAlNum (C) || (C == '_') || (C == '@' && AtInIdents) || (C == '$' && DollarInIdents); } int IsIdStart (int C) /* Return true if the character may start an identifier */ { return IsAlpha (C) || C == '_'; } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static unsigned DigitVal (unsigned char C) /* Convert a digit into it's numerical representation */ { if (IsDigit (C)) { return C - '0'; } else { return toupper (C) - 'A' + 10; } } static void NextChar (void) /* Read the next character from the input file */ { Source->Func->NextChar (Source); } void LocaseSVal (void) /* Make SVal lower case */ { SB_ToLower (&CurTok.SVal); } void UpcaseSVal (void) /* Make SVal upper case */ { SB_ToUpper (&CurTok.SVal); } static int CmpDotKeyword (const void* K1, const void* K2) /* Compare function for the dot keyword search */ { return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key); } static token_t FindDotKeyword (void) /* Find the dot keyword in SVal. Return the corresponding token if found, * return TOK_NONE if not found. */ { struct DotKeyword K; struct DotKeyword* R; /* Initialize K */ K.Key = SB_GetConstBuf (&CurTok.SVal); K.Tok = 0; /* If we aren't in ignore case mode, we have to uppercase the keyword */ if (!IgnoreCase) { UpcaseSVal (); } /* Search for the keyword */ R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]), sizeof (DotKeywords [0]), CmpDotKeyword); if (R != 0) { return R->Tok; } else { return TOK_NONE; } } static void ReadIdent (void) /* Read an identifier from the current input position into Ident. Filling SVal * starts at the current position with the next character in C. It is assumed * that any characters already filled in are ok, and the character in C is * checked. */ { /* Read the identifier */ do { SB_AppendChar (&CurTok.SVal, C); NextChar (); } while (IsIdChar (C)); SB_Terminate (&CurTok.SVal); /* If we should ignore case, convert the identifier to upper case */ if (IgnoreCase) { UpcaseSVal (); } } static void ReadStringConst (int StringTerm) /* Read a string constant into SVal. */ { /* Skip the leading string terminator */ NextChar (); /* Read the string */ while (1) { if (C == StringTerm) { break; } if (C == '\n' || C == EOF) { Error ("Newline in string constant"); break; } /* Append the char to the string */ SB_AppendChar (&CurTok.SVal, C); /* Skip the character */ NextChar (); } /* Skip the trailing terminator */ NextChar (); /* Terminate the string */ SB_Terminate (&CurTok.SVal); } static int Sweet16Reg (const StrBuf* Id) /* Check if the given identifier is a sweet16 register. Return -1 if this is * not the case, return the register number otherwise. */ { unsigned RegNum; char Check; if (SB_GetLen (Id) < 2) { return -1; } if (toupper (SB_AtUnchecked (Id, 0)) != 'R') { return -1; } if (!IsDigit (SB_AtUnchecked (Id, 1))) { return -1; } if (sscanf (SB_GetConstBuf (Id)+1, "%u%c", &RegNum, &Check) != 1 || RegNum > 15) { /* Invalid register */ return -1; } /* The register number is valid */ return (int) RegNum; } void NextRawTok (void) /* Read the next raw token from the input stream */ { Macro* M; /* If we've a forced end of assembly, don't read further */ if (ForcedEnd) { CurTok.Tok = TOK_EOF; return; } Restart: /* Check if we have tokens from another input source */ if (InputFromStack ()) { if (CurTok.Tok == TOK_IDENT && (M = FindDefine (&CurTok.SVal)) != 0) { /* This is a define style macro - expand it */ MacExpandStart (M); goto Restart; } return; } Again: /* Skip whitespace, remember if we had some */ if ((CurTok.WS = IsBlank (C)) != 0) { do { NextChar (); } while (IsBlank (C)); } /* Mark the file position of the next token */ Source->Func->MarkStart (Source); /* Clear the string attribute */ SB_Clear (&CurTok.SVal); /* Generate line info for the current token */ NewAsmLine (); /* Hex number or PC symbol? */ if (C == '$') { NextChar (); /* Hex digit must follow or DollarIsPC must be enabled */ if (!IsXDigit (C)) { if (DollarIsPC) { CurTok.Tok = TOK_PC; return; } else { Error ("Hexadecimal digit expected"); } } /* Read the number */ CurTok.IVal = 0; while (1) { if (UnderlineInNumbers && C == '_') { while (C == '_') { NextChar (); } if (!IsXDigit (C)) { Error ("Number may not end with underline"); } } if (IsXDigit (C)) { if (CurTok.IVal & 0xF0000000) { Error ("Overflow in hexadecimal number"); CurTok.IVal = 0; } CurTok.IVal = (CurTok.IVal << 4) + DigitVal (C); NextChar (); } else { break; } } /* This is an integer constant */ CurTok.Tok = TOK_INTCON; return; } /* Binary number? */ if (C == '%') { NextChar (); /* 0 or 1 must follow */ if (!IsBDigit (C)) { Error ("Binary digit expected"); } /* Read the number */ CurTok.IVal = 0; while (1) { if (UnderlineInNumbers && C == '_') { while (C == '_') { NextChar (); } if (!IsBDigit (C)) { Error ("Number may not end with underline"); } } if (IsBDigit (C)) { if (CurTok.IVal & 0x80000000) { Error ("Overflow in binary number"); CurTok.IVal = 0; } CurTok.IVal = (CurTok.IVal << 1) + DigitVal (C); NextChar (); } else { break; } } /* This is an integer constant */ CurTok.Tok = TOK_INTCON; return; } /* Number? */ if (IsDigit (C)) { char Buf[16]; unsigned Digits; unsigned Base; unsigned I; long Max; unsigned DVal; /* Ignore leading zeros */ while (C == '0') { NextChar (); } /* Read the number into Buf counting the digits */ Digits = 0; while (1) { if (UnderlineInNumbers && C == '_') { while (C == '_') { NextChar (); } if (!IsXDigit (C)) { Error ("Number may not end with underline"); } } if (IsXDigit (C)) { /* Buf is big enough to allow any decimal and hex number to * overflow, so ignore excess digits here, they will be detected * when we convert the value. */ if (Digits < sizeof (Buf)) { Buf[Digits++] = C; } NextChar (); } else { break; } } /* Allow zilog/intel style hex numbers with a 'h' suffix */ if (C == 'h' || C == 'H') { NextChar (); Base = 16; Max = 0xFFFFFFFFUL / 16; } else { Base = 10; Max = 0xFFFFFFFFUL / 10; } /* Convert the number using the given base */ CurTok.IVal = 0; for (I = 0; I < Digits; ++I) { if (CurTok.IVal > Max) { Error ("Number out of range"); CurTok.IVal = 0; break; } DVal = DigitVal (Buf[I]); if (DVal > Base) { Error ("Invalid digits in number"); CurTok.IVal = 0; break; } CurTok.IVal = (CurTok.IVal * Base) + DVal; } /* This is an integer constant */ CurTok.Tok = TOK_INTCON; return; } /* Control command? */ if (C == '.') { /* Remember and skip the dot */ NextChar (); /* Check if it's just a dot */ if (!IsIdStart (C)) { /* Just a dot */ CurTok.Tok = TOK_DOT; } else { /* Read the remainder of the identifier */ SB_AppendChar (&CurTok.SVal, '.'); ReadIdent (); /* Dot keyword, search for it */ CurTok.Tok = FindDotKeyword (); if (CurTok.Tok == TOK_NONE) { /* Not found */ if (!LeadingDotInIdents) { /* Invalid pseudo instruction */ Error ("`%m%p' is not a recognized control command", &CurTok.SVal); goto Again; } /* An identifier with a dot. Check if it's a define style * macro. */ if ((M = FindDefine (&CurTok.SVal)) != 0) { /* This is a define style macro - expand it */ MacExpandStart (M); goto Restart; } /* Just an identifier with a dot */ CurTok.Tok = TOK_IDENT; } } return; } /* Indirect op for sweet16 cpu. Must check this before checking for local * symbols, because these may also use the '@' symbol. */ if (CPU == CPU_SWEET16 && C == '@') { NextChar (); CurTok.Tok = TOK_AT; return; } /* Local symbol? */ if (C == LocalStart) { /* Read the identifier. */ ReadIdent (); /* Start character alone is not enough */ if (SB_GetLen (&CurTok.SVal) == 1) { Error ("Invalid cheap local symbol"); goto Again; } /* A local identifier */ CurTok.Tok = TOK_LOCAL_IDENT; return; } /* Identifier or keyword? */ if (IsIdStart (C)) { /* Read the identifier */ ReadIdent (); /* Check for special names. Bail out if we have identified the type of * the token. Go on if the token is an identifier. */ if (SB_GetLen (&CurTok.SVal) == 1) { switch (toupper (SB_AtUnchecked (&CurTok.SVal, 0))) { case 'A': if (C == ':') { NextChar (); CurTok.Tok = TOK_OVERRIDE_ABS; } else { CurTok.Tok = TOK_A; } return; case 'F': if (C == ':') { NextChar (); CurTok.Tok = TOK_OVERRIDE_FAR; return; } break; case 'S': if (CPU == CPU_65816) { CurTok.Tok = TOK_S; return; } break; case 'X': CurTok.Tok = TOK_X; return; case 'Y': CurTok.Tok = TOK_Y; return; case 'Z': if (C == ':') { NextChar (); CurTok.Tok = TOK_OVERRIDE_ZP; return; } break; default: break; } } else if (CPU == CPU_SWEET16 && (CurTok.IVal = Sweet16Reg (&CurTok.SVal)) >= 0) { /* A sweet16 register number in sweet16 mode */ CurTok.Tok = TOK_REG; return; } /* Check for define style macro */ if ((M = FindDefine (&CurTok.SVal)) != 0) { /* Macro - expand it */ MacExpandStart (M); goto Restart; } else { /* An identifier */ CurTok.Tok = TOK_IDENT; } return; } /* Ok, let's do the switch */ CharAgain: switch (C) { case '+': NextChar (); CurTok.Tok = TOK_PLUS; return; case '-': NextChar (); CurTok.Tok = TOK_MINUS; return; case '/': NextChar (); if (C != '*') { CurTok.Tok = TOK_DIV; } else if (CComments) { /* Remember the position, then skip the '*' */ Collection LineInfos = STATIC_COLLECTION_INITIALIZER; GetFullLineInfo (&LineInfos); NextChar (); do { while (C != '*') { if (C == EOF) { LIError (&LineInfos, "Unterminated comment"); ReleaseFullLineInfo (&LineInfos); DoneCollection (&LineInfos); goto CharAgain; } NextChar (); } NextChar (); } while (C != '/'); NextChar (); ReleaseFullLineInfo (&LineInfos); DoneCollection (&LineInfos); goto Again; } return; case '*': NextChar (); CurTok.Tok = TOK_MUL; return; case '^': NextChar (); CurTok.Tok = TOK_XOR; return; case '&': NextChar (); if (C == '&') { NextChar (); CurTok.Tok = TOK_BOOLAND; } else { CurTok.Tok = TOK_AND; } return; case '|': NextChar (); if (C == '|') { NextChar (); CurTok.Tok = TOK_BOOLOR; } else { CurTok.Tok = TOK_OR; } return; case ':': NextChar (); switch (C) { case ':': NextChar (); CurTok.Tok = TOK_NAMESPACE; break; case '-': CurTok.IVal = 0; do { --CurTok.IVal; NextChar (); } while (C == '-'); CurTok.Tok = TOK_ULABEL; break; case '+': CurTok.IVal = 0; do { ++CurTok.IVal; NextChar (); } while (C == '+'); CurTok.Tok = TOK_ULABEL; break; case '=': NextChar (); CurTok.Tok = TOK_ASSIGN; break; default: CurTok.Tok = TOK_COLON; break; } return; case ',': NextChar (); CurTok.Tok = TOK_COMMA; return; case ';': NextChar (); while (C != '\n' && C != EOF) { NextChar (); } goto CharAgain; case '#': NextChar (); CurTok.Tok = TOK_HASH; return; case '(': NextChar (); CurTok.Tok = TOK_LPAREN; return; case ')': NextChar (); CurTok.Tok = TOK_RPAREN; return; case '[': NextChar (); CurTok.Tok = TOK_LBRACK; return; case ']': NextChar (); CurTok.Tok = TOK_RBRACK; return; case '{': NextChar (); CurTok.Tok = TOK_LCURLY; return; case '}': NextChar (); CurTok.Tok = TOK_RCURLY; return; case '<': NextChar (); if (C == '=') { NextChar (); CurTok.Tok = TOK_LE; } else if (C == '<') { NextChar (); CurTok.Tok = TOK_SHL; } else if (C == '>') { NextChar (); CurTok.Tok = TOK_NE; } else { CurTok.Tok = TOK_LT; } return; case '=': NextChar (); CurTok.Tok = TOK_EQ; return; case '!': NextChar (); CurTok.Tok = TOK_BOOLNOT; return; case '>': NextChar (); if (C == '=') { NextChar (); CurTok.Tok = TOK_GE; } else if (C == '>') { NextChar (); CurTok.Tok = TOK_SHR; } else { CurTok.Tok = TOK_GT; } return; case '~': NextChar (); CurTok.Tok = TOK_NOT; return; case '\'': /* Hack: If we allow ' as terminating character for strings, read * the following stuff as a string, and check for a one character * string later. */ if (LooseStringTerm) { ReadStringConst ('\''); if (SB_GetLen (&CurTok.SVal) == 1) { CurTok.IVal = SB_AtUnchecked (&CurTok.SVal, 0); CurTok.Tok = TOK_CHARCON; } else { CurTok.Tok = TOK_STRCON; } } else { /* Always a character constant */ NextChar (); if (C == EOF || IsControl (C)) { Error ("Illegal character constant"); goto CharAgain; } CurTok.IVal = C; CurTok.Tok = TOK_CHARCON; NextChar (); if (C != '\'') { if (!MissingCharTerm) { Error ("Illegal character constant"); } } else { NextChar (); } } return; case '\"': ReadStringConst ('\"'); CurTok.Tok = TOK_STRCON; return; case '\\': /* Line continuation? */ if (LineCont) { NextChar (); if (C == '\n') { /* Handle as white space */ NextChar (); C = ' '; goto Again; } } break; case '\n': NextChar (); CurTok.Tok = TOK_SEP; return; case EOF: CheckInputStack (); /* In case of the main file, do not close it, but return EOF. */ if (Source && Source->Next) { DoneCharSource (); goto Again; } else { CurTok.Tok = TOK_EOF; } return; } /* If we go here, we could not identify the current character. Skip it * and try again. */ Error ("Invalid input character: 0x%02X", C & 0xFF); NextChar (); goto Again; } int GetSubKey (const char** Keys, unsigned Count) /* Search for a subkey in a table of keywords. The current token must be an * identifier and all keys must be in upper case. The identifier will be * uppercased in the process. The function returns the index of the keyword, * or -1 if the keyword was not found. */ { unsigned I; /* Must have an identifier */ PRECONDITION (CurTok.Tok == TOK_IDENT); /* If we aren't in ignore case mode, we have to uppercase the identifier */ if (!IgnoreCase) { UpcaseSVal (); } /* Do a linear search (a binary search is not worth the effort) */ for (I = 0; I < Count; ++I) { if (SB_CompareStr (&CurTok.SVal, Keys [I]) == 0) { /* Found it */ return I; } } /* Not found */ return -1; } unsigned char ParseAddrSize (void) /* Check if the next token is a keyword that denotes an address size specifier. * If so, return the corresponding address size constant, otherwise output an * error message and return ADDR_SIZE_DEFAULT. */ { unsigned char AddrSize; /* Check for an identifier */ if (CurTok.Tok != TOK_IDENT) { Error ("Address size specifier expected"); return ADDR_SIZE_DEFAULT; } /* Convert the attribute */ AddrSize = AddrSizeFromStr (SB_GetConstBuf (&CurTok.SVal)); if (AddrSize == ADDR_SIZE_INVALID) { Error ("Address size specifier expected"); AddrSize = ADDR_SIZE_DEFAULT; } /* Done */ return AddrSize; } void InitScanner (const char* InFile) /* Initialize the scanner, open the given input file */ { /* Open the input file */ NewInputFile (InFile); } void DoneScanner (void) /* Release scanner resources */ { DoneCharSource (); }
945
./cc65/src/ca65/anonname.c
/*****************************************************************************/ /* */ /* anonname.c */ /* */ /* Create names for anonymous scopes/variables/types */ /* */ /* */ /* */ /* (C) 2000-2008 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> /* ca65 */ #include "anonname.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ static const char AnonTag[] = "$anon"; /*****************************************************************************/ /* Code */ /*****************************************************************************/ StrBuf* AnonName (StrBuf* Buf, const char* Spec) /* Get a name for an anonymous scope, variable or type. Size is the size of * the buffer passed to the function, Spec will be used as part of the * identifier if given. A pointer to the buffer is returned. */ { static unsigned ACount = 0; SB_Printf (Buf, "%s-%s-%04X", AnonTag, Spec, ++ACount); return Buf; } int IsAnonName (const StrBuf* Name) /* Check if the given symbol name is that of an anonymous symbol */ { if (SB_GetLen (Name) < sizeof (AnonTag) - 1) { /* Too short */ return 0; } return (strncmp (SB_GetConstBuf (Name), AnonTag, sizeof (AnonTag) - 1) == 0); }
946
./cc65/src/ca65/segdef.c
/*****************************************************************************/ /* */ /* segdef.c */ /* */ /* Segment definitions for the ca65 assembler */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "xmalloc.h" /* ca65 */ #include "segdef.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ SegDef* NewSegDef (const char* Name, unsigned char AddrSize) /* Create a new segment definition and return it */ { /* Allocate memory */ SegDef* D = xmalloc (sizeof (SegDef)); /* Initialize it */ D->Name = xstrdup (Name); D->AddrSize = AddrSize; /* Return the result */ return D; } void FreeSegDef (SegDef* D) /* Free a segment definition */ { xfree (D->Name); xfree (D); } SegDef* DupSegDef (const SegDef* Def) /* Duplicate a segment definition and return it */ { return NewSegDef (Def->Name, Def->AddrSize); }
947
./cc65/src/ca65/repeat.c
/*****************************************************************************/ /* */ /* repeat.c */ /* */ /* Handle the .REPEAT pseudo instruction */ /* */ /* */ /* */ /* (C) 2000-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "xmalloc.h" /* ca65 */ #include "error.h" #include "expr.h" #include "nexttok.h" #include "toklist.h" #include "repeat.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static TokList* CollectRepeatTokens (void) /* Collect all tokens inside the .REPEAT body in a token list and return * this list. In case of errors, NULL is returned. */ { /* Create the token list */ TokList* List = NewTokList (); /* Read the token list */ unsigned Repeats = 0; while (Repeats != 0 || CurTok.Tok != TOK_ENDREP) { /* Check for end of input */ if (CurTok.Tok == TOK_EOF) { Error ("Unexpected end of file"); FreeTokList (List); return 0; } /* Collect all tokens in the list */ AddCurTok (List); /* Check for and count nested .REPEATs */ if (CurTok.Tok == TOK_REPEAT) { ++Repeats; } else if (CurTok.Tok == TOK_ENDREP) { --Repeats; } /* Get the next token */ NextTok (); } /* Eat the closing .ENDREP */ NextTok (); /* Return the list of collected tokens */ return List; } static void RepeatTokenCheck (TokList* L) /* Called each time a token from a repeat token list is set. Is used to check * for and replace identifiers that are the repeat counter. */ { if (CurTok.Tok == TOK_IDENT && L->Data != 0 && SB_CompareStr (&CurTok.SVal, L->Data) == 0) { /* Must replace by the repeat counter */ CurTok.Tok = TOK_INTCON; CurTok.IVal = L->RepCount; } } void ParseRepeat (void) /* Parse and handle the .REPEAT statement */ { char* Name; TokList* List; /* Repeat count follows */ long RepCount = ConstExpression (); if (RepCount < 0) { Error ("Range error"); RepCount = 0; } /* Optional there is a comma and a counter variable */ Name = 0; if (CurTok.Tok == TOK_COMMA) { /* Skip the comma */ NextTok (); /* Check for an identifier */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Identifier expected"); } else { /* Remember the name and skip it */ SB_Terminate (&CurTok.SVal); Name = xstrdup (SB_GetConstBuf (&CurTok.SVal)); NextTok (); } } /* Switch to raw token mode, then skip the separator */ EnterRawTokenMode (); ConsumeSep (); /* Read the token list */ List = CollectRepeatTokens (); /* If we had an error, bail out */ if (List == 0) { xfree (Name); goto Done; } /* Update the token list for replay */ List->RepMax = (unsigned) RepCount; List->Data = Name; List->Check = RepeatTokenCheck; /* If the list is empty, or repeat count zero, there is nothing * to repeat. */ if (List->Count == 0 || RepCount == 0) { FreeTokList (List); goto Done; } /* Read input from the repeat descriptor */ PushTokList (List, ".REPEAT"); Done: /* Switch out of raw token mode */ LeaveRawTokenMode (); }
948
./cc65/src/ca65/incpath.c
/*****************************************************************************/ /* */ /* incpath.c */ /* */ /* Include path handling for the ca65 macro assembler */ /* */ /* */ /* */ /* (C) 2000-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* ca65 */ #include "incpath.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ SearchPath* IncSearchPath; /* Standard include path */ SearchPath* BinSearchPath; /* Binary include path */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ void InitIncludePaths (void) /* Initialize the include path search list */ { /* Create the search path lists */ IncSearchPath = NewSearchPath (); BinSearchPath = NewSearchPath (); } void FinishIncludePaths (void) /* Finish creating the include path search list. */ { /* Add specific paths from the environment */ AddSearchPathFromEnv (IncSearchPath, "CA65_INC"); /* Add paths relative to a main directory defined in an env. var. */ AddSubSearchPathFromEnv (IncSearchPath, "CC65_HOME", "asminc"); /* Add some compiled-in search paths if defined at compile time. */ #ifdef CA65_INC AddSearchPath (IncSearchPath, STRINGIZE (CA65_INC)); #endif /* Add paths relative to the parent directory of the Windows binary. */ AddSubSearchPathFromWinBin (IncSearchPath, "asminc"); }
949
./cc65/src/ca65/spool.c
/*****************************************************************************/ /* */ /* spool.c */ /* */ /* Id and message pool for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* ca65 */ #include "objfile.h" #include "spool.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ StringPool* StrPool = 0; /*****************************************************************************/ /* Code */ /*****************************************************************************/ void WriteStrPool (void) /* Write the string pool to the object file */ { unsigned I; /* Get the number of strings in the string pool */ unsigned Count = SP_GetCount (StrPool); /* Tell the object file module that we're about to start the string pool */ ObjStartStrPool (); /* Write the string count to the list */ ObjWriteVar (Count); /* Write the strings in id order */ for (I = 0; I < Count; ++I) { ObjWriteBuf (SP_Get (StrPool, I)); } /* Done writing the string pool */ ObjEndStrPool (); } void InitStrPool (void) /* Initialize the string pool */ { /* Create a string pool */ StrPool = NewStringPool (1103); /* Insert an empty string. It will have string id 0 */ SP_AddStr (StrPool, ""); }
950
./cc65/src/ca65/enum.c
/*****************************************************************************/ /* */ /* enum.c */ /* */ /* .ENUM command */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "addrsize.h" #include "scopedefs.h" /* ca65 */ #include "condasm.h" #include "enum.h" #include "error.h" #include "expr.h" #include "macro.h" #include "nexttok.h" #include "scanner.h" #include "symbol.h" #include "symtab.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void DoEnum (void) /* Handle the .ENUM command */ { /* Start at zero */ long Offs = 0; ExprNode* BaseExpr = GenLiteral0 (); /* Check for a name */ int Anon = (CurTok.Tok != TOK_IDENT); if (!Anon) { /* Enter a new scope, then skip the name */ SymEnterLevel (&CurTok.SVal, SCOPE_ENUM, ADDR_SIZE_ABS, 0); NextTok (); } /* Test for end of line */ ConsumeSep (); /* Read until end of struct */ while (CurTok.Tok != TOK_ENDENUM && CurTok.Tok != TOK_EOF) { Macro* M; SymEntry* Sym; ExprNode* EnumExpr; /* Skip empty lines */ if (CurTok.Tok == TOK_SEP) { NextTok (); continue; } /* The format is "identifier [ = value ]" */ if (CurTok.Tok != TOK_IDENT) { /* Maybe it's a conditional? */ if (!CheckConditionals ()) { ErrorSkip ("Identifier expected"); } continue; } /* We have an identifier. Is it a macro? */ if ((M = FindMacro (&CurTok.SVal)) != 0) { MacExpandStart (M); continue; } /* We have an identifier, generate a symbol */ Sym = SymFind (CurrentScope, &CurTok.SVal, SYM_ALLOC_NEW); /* Skip the member name */ NextTok (); /* Check for an assignment */ if (CurTok.Tok == TOK_EQ) { /* Skip the equal sign */ NextTok (); /* Read the new expression */ EnumExpr = Expression (); /* Reset the base expression and the offset */ FreeExpr (BaseExpr); BaseExpr = CloneExpr (EnumExpr); Offs = 0; } else { /* No assignment, use last value + 1 */ EnumExpr = GenAddExpr (CloneExpr (BaseExpr), GenLiteralExpr (Offs)); } /* Assign the value to the enum member */ SymDef (Sym, EnumExpr, ADDR_SIZE_DEFAULT, SF_NONE); /* Increment the offset for the next member */ ++Offs; /* Expect end of line */ ConsumeSep (); } /* If this is not an anon enum, leave its scope */ if (!Anon) { /* Close the enum scope */ SymLeaveLevel (); } /* End of enum definition */ Consume (TOK_ENDENUM, "`.ENDENUM' expected"); /* Free the base expression */ FreeExpr (BaseExpr); }
951
./cc65/src/ca65/listing.c
/*****************************************************************************/ /* */ /* listing.c */ /* */ /* Listing support for the ca65 crossassembler */ /* */ /* */ /* */ /* (C) 2000-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <errno.h> /* common */ #include "check.h" #include "fname.h" #include "fragdefs.h" #include "strbuf.h" #include "version.h" #include "xmalloc.h" /* ca65 */ #include "error.h" #include "filetab.h" #include "global.h" #include "listing.h" #include "segment.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Single linked list of lines */ ListLine* LineList = 0; /* List of listing lines */ ListLine* LineCur = 0; /* Current listing line */ ListLine* LineLast = 0; /* Last (current) listing line */ /* Page and other formatting */ int PageLength = -1; /* Length of a listing page */ static unsigned PageNumber = 1; /* Current listing page number */ static int PageLines = 0; /* Current line on page */ static unsigned ListBytes = 12; /* Number of bytes to list for one line */ /* Switch the listing on/off */ static int ListingEnabled = 1; /* Enabled if > 0 */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ void NewListingLine (const StrBuf* Line, unsigned char File, unsigned char Depth) /* Create a new ListLine struct and insert it */ { /* Store only if listing is enabled */ if (SB_GetLen (&ListingName) > 0) { ListLine* L; /* Get the length of the line */ unsigned Len = SB_GetLen (Line); /* Ignore trailing newlines */ while (Len > 0 && SB_AtUnchecked (Line, Len-1) == '\n') { --Len; } /* Allocate memory */ L = xmalloc (sizeof (ListLine) + Len); /* Initialize the fields. */ L->Next = 0; L->FragList = 0; L->FragLast = 0; L->PC = GetPC (); L->Reloc = GetRelocMode (); L->File = File; L->Depth = Depth; L->Output = (ListingEnabled > 0); L->ListBytes = (unsigned char) ListBytes; memcpy (L->Line, SB_GetConstBuf (Line), Len); L->Line[Len] = '\0'; /* Insert the line into the list of lines */ if (LineList == 0) { LineList = L; } else { LineLast->Next = L; } LineLast = L; } } void EnableListing (void) /* Enable output of lines to the listing */ { if (SB_GetLen (&ListingName) > 0) { /* If we're about to enable the listing, do this for the current line * also, so we will see the source line that did this. */ if (ListingEnabled++ == 0) { LineCur->Output = 1; } } } void DisableListing (void) /* Disable output of lines to the listing */ { if (SB_GetLen (&ListingName) > 0) { if (ListingEnabled == 0) { /* Cannot switch the listing off once more */ Error ("Counter underflow"); } else { --ListingEnabled; } } } void SetListBytes (int Bytes) /* Set the maximum number of bytes listed for one line */ { if (Bytes < 0) { Bytes = 0; /* Encode "unlimited" as zero */ } ListBytes = Bytes; } void InitListingLine (void) /* Initialize the current listing line */ { if (SB_GetLen (&ListingName) > 0) { /* Make the last loaded line the current line */ /* ###### This code is a hack! We really need to do it right * as soon as we know, how:-( */ if (LineCur && LineCur->Next && LineCur->Next != LineLast) { ListLine* L = LineCur; do { L = L->Next; /* Set the values for this line */ CHECK (L != 0); L->PC = GetPC (); L->Reloc = GetRelocMode (); L->Output = (ListingEnabled > 0); L->ListBytes = (unsigned char) ListBytes; } while (L->Next != LineLast); } LineCur = LineLast; /* Set the values for this line */ CHECK (LineCur != 0); LineCur->PC = GetPC (); LineCur->Reloc = GetRelocMode (); LineCur->Output = (ListingEnabled > 0); LineCur->ListBytes = (unsigned char) ListBytes; } } static char* AddHex (char* S, unsigned Val) /* Add a hex byte in ASCII to the given string and return the new pointer */ { static const char HexTab [16] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' }; *S++ = HexTab [(Val >> 4) & 0x0F]; *S++ = HexTab [Val & 0x0F]; return S; } static void PrintPageHeader (FILE* F, const ListLine* L) /* Print the header for a new page. It is assumed that the given line is the * last line of the previous page. */ { /* Gte a pointer to the current input file */ const StrBuf* CurFile = GetFileName (L->File); /* Print the header on the new page */ fprintf (F, "ca65 V%s\n" "Main file : %s\n" "Current file: %.*s\n" "\n", GetVersionAsString (), InFile, (int) SB_GetLen (CurFile), SB_GetConstBuf (CurFile)); /* Count pages, reset lines */ ++PageNumber; PageLines = 4; } static void PrintLine (FILE* F, const char* Header, const char* Line, const ListLine* L) /* Print one line to the listing file, adding a newline and counting lines */ { /* Print the given line */ fprintf (F, "%s%s\n", Header, Line); /* Increment the current line */ ++PageLines; /* Switch to a new page if needed. Do not switch, if the current line is * the last one, to avoid pages that consist of just the header. */ if (PageLength > 0 && PageLines >= PageLength && L->Next != 0) { /* Do a formfeed */ putc ('\f', F); /* Print the header on the new page */ PrintPageHeader (F, L); } } static char* AddMult (char* S, char C, unsigned Count) /* Add multiple instances of character C to S, return updated S. */ { memset (S, C, Count); return S + Count; } static char* MakeLineHeader (char* H, const ListLine* L) /* Prepare the line header */ { char Mode; char Depth; /* Setup the PC mode */ Mode = (L->Reloc)? 'r' : ' '; /* Set up the include depth */ Depth = (L->Depth < 10)? L->Depth + '0' : '+'; /* Format the line */ sprintf (H, "%06lX%c %c", L->PC, Mode, Depth); memset (H+9, ' ', LINE_HEADER_LEN-9); /* Return the buffer */ return H; } void CreateListing (void) /* Create the listing */ { FILE* F; Fragment* Frag; ListLine* L; char HeaderBuf [LINE_HEADER_LEN+1]; /* Open the real listing file */ F = fopen (SB_GetConstBuf (&ListingName), "w"); if (F == 0) { Fatal ("Cannot open listing file `%s': %s", SB_GetConstBuf (&ListingName), strerror (errno)); } /* Reset variables, print the header for the first page */ PageNumber = 0; PrintPageHeader (F, LineList); /* Terminate the header buffer. The last byte will never get overwritten */ HeaderBuf [LINE_HEADER_LEN] = '\0'; /* Walk through all listing lines */ L = LineList; while (L) { char* Buf; char* B; unsigned Count; unsigned I; char* Line; /* If we should not output this line, go to the next */ if (L->Output == 0) { L = L->Next; continue; } /* If we don't have a fragment list for this line, things are easy */ if (L->FragList == 0) { PrintLine (F, MakeLineHeader (HeaderBuf, L), L->Line, L); L = L->Next; continue; } /* Count the number of bytes in the complete fragment list */ Count = 0; Frag = L->FragList; while (Frag) { Count += Frag->Len; Frag = Frag->LineList; } /* Allocate memory for the given number of bytes */ Buf = xmalloc (Count*2+1); /* Copy an ASCII representation of the bytes into the buffer */ B = Buf; Frag = L->FragList; while (Frag) { /* Write data depending on the type */ switch (Frag->Type) { case FRAG_LITERAL: for (I = 0; I < Frag->Len; ++I) { B = AddHex (B, Frag->V.Data[I]); } break; case FRAG_EXPR: case FRAG_SEXPR: B = AddMult (B, 'r', Frag->Len*2); break; case FRAG_FILL: B = AddMult (B, 'x', Frag->Len*2); break; default: Internal ("Invalid fragment type: %u", Frag->Type); } /* Next fragment */ Frag = Frag->LineList; } /* Limit the number of bytes actually printed */ if (L->ListBytes != 0) { /* Not unlimited */ if (Count > L->ListBytes) { Count = L->ListBytes; } } /* Output the data. The format of a listing line is: * * PPPPPPm I 11 22 33 44 * * where * * PPPPPP is the PC * m is the mode ('r' or empty) * I is the include level * 11 .. are code or data bytes */ Line = L->Line; B = Buf; while (Count) { unsigned Chunk; char* P; /* Prepare the line header */ MakeLineHeader (HeaderBuf, L); /* Get the number of bytes for the next line */ Chunk = Count; if (Chunk > 4) { Chunk = 4; } Count -= Chunk; /* Increment the program counter. Since we don't need the PC stored * in the LineList object for anything else, just increment this * variable. */ L->PC += Chunk; /* Copy the bytes into the line */ P = HeaderBuf + 11; for (I = 0; I < Chunk; ++I) { *P++ = *B++; *P++ = *B++; *P++ = ' '; } /* Output this line */ PrintLine (F, HeaderBuf, Line, L); /* Don't output a line twice */ Line = ""; } /* Delete the temporary buffer */ xfree (Buf); /* Next line */ L = L->Next; } /* Close the listing file */ (void) fclose (F); }
952
./cc65/src/ca65/span.c
/*****************************************************************************/ /* */ /* span.c */ /* */ /* A span of data within a segment */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "hashfunc.h" #include "hashtab.h" #include "xmalloc.h" /* ca65 */ #include "global.h" #include "objfile.h" #include "segment.h" #include "span.h" #include "spool.h" /*****************************************************************************/ /* Forwards */ /*****************************************************************************/ static unsigned HT_GenHash (const void* Key); /* Generate the hash over a key. */ static const void* HT_GetKey (const void* Entry); /* Given a pointer to the user entry data, return a pointer to the key */ static int HT_Compare (const void* Key1, const void* Key2); /* Compare two keys. The function must return a value less than zero if * Key1 is smaller than Key2, zero if both are equal, and a value greater * than zero if Key1 is greater then Key2. */ /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Hash table functions */ static const HashFunctions HashFunc = { HT_GenHash, HT_GetKey, HT_Compare }; /* Span hash table */ static HashTable SpanTab = STATIC_HASHTABLE_INITIALIZER (1051, &HashFunc); /*****************************************************************************/ /* Hash table functions */ /*****************************************************************************/ static unsigned HT_GenHash (const void* Key) /* Generate the hash over a key. */ { /* Key is a Span pointer */ const Span* S = Key; /* Hash over a combination of segment number, start and end */ return HashInt ((S->Seg->Num << 28) ^ (S->Start << 14) ^ S->End); } static const void* HT_GetKey (const void* Entry) /* Given a pointer to the user entry data, return a pointer to the key */ { return Entry; } static int HT_Compare (const void* Key1, const void* Key2) /* Compare two keys. The function must return a value less than zero if * Key1 is smaller than Key2, zero if both are equal, and a value greater * than zero if Key1 is greater then Key2. */ { /* Convert both parameters to Span pointers */ const Span* S1 = Key1; const Span* S2 = Key2; /* Compare segment number, then start and end */ int Res = (int)S2->Seg->Num - (int)S1->Seg->Num; if (Res == 0) { Res = (int)S2->Start - (int)S1->Start; if (Res == 0) { Res = (int)S2->End - (int)S1->End; } } /* Done */ return Res; } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static Span* NewSpan (Segment* Seg, unsigned long Start, unsigned long End) /* Create a new span. The segment is set to Seg, Start and End are set to the * current PC of the segment. */ { /* Allocate memory */ Span* S = xmalloc (sizeof (Span)); /* Initialize the struct */ InitHashNode (&S->Node); S->Id = ~0U; S->Seg = Seg; S->Start = Start; S->End = End; S->Type = EMPTY_STRING_ID; /* Return the new struct */ return S; } static void FreeSpan (Span* S) /* Free a span */ { xfree (S); } static Span* MergeSpan (Span* S) /* Check if we have a span with the same data as S already. If so, free S and * return the already existing one. If not, remember S and return it. */ { /* Check if we have such a span already. If so use the existing * one and free the one from the collection. If not, add the one to * the hash table and return it. */ Span* E = HT_Find (&SpanTab, S); if (E) { /* If S has a type and E not, move the type */ if (S->Type != EMPTY_STRING_ID) { CHECK (E->Type == EMPTY_STRING_ID); E->Type = S->Type; } /* Free S and return E */ FreeSpan (S); return E; } else { /* Assign the id, insert S, then return it */ S->Id = HT_GetCount (&SpanTab); HT_Insert (&SpanTab, S); return S; } } void SetSpanType (Span* S, const StrBuf* Type) /* Set the generic type of the span to Type */ { /* Ignore the call if we won't generate debug infos */ if (DbgSyms) { S->Type = GetStrBufId (Type); } } Span* OpenSpan (void) /* Open a span for the active segment and return it. */ { return NewSpan (ActiveSeg, ActiveSeg->PC, ActiveSeg->PC); } Span* CloseSpan (Span* S) /* Close the given span. Be sure to replace the passed span by the one * returned, since the span will get deleted if it is empty or may be * replaced if a duplicate exists. */ { /* Set the end offset */ if (S->Start == S->Seg->PC) { /* Span is empty */ FreeSpan (S); return 0; } else { /* Span is not empty */ S->End = S->Seg->PC; /* Check if we have such a span already. If so use the existing * one and free the one from the collection. If not, add the one to * the hash table and return it. */ return MergeSpan (S); } } void OpenSpanList (Collection* Spans) /* Open a list of spans for all existing segments to the given collection of * spans. The currently active segment will be inserted first with all others * following. */ { unsigned I; /* Grow the Spans collection as necessary */ CollGrow (Spans, CollCount (&SegmentList)); /* Add the currently active segment */ CollAppend (Spans, NewSpan (ActiveSeg, ActiveSeg->PC, ActiveSeg->PC)); /* Walk through the segment list and add all other segments */ for (I = 0; I < CollCount (&SegmentList); ++I) { Segment* Seg = CollAtUnchecked (&SegmentList, I); /* Be sure to skip the active segment, since it was already added */ if (Seg != ActiveSeg) { CollAppend (Spans, NewSpan (Seg, Seg->PC, Seg->PC)); } } } void CloseSpanList (Collection* Spans) /* Close a list of spans. This will add new segments to the list, mark the end * of existing ones, and remove empty spans from the list. */ { unsigned I, J; /* Have new segments been added while the span list was open? */ for (I = CollCount (Spans); I < CollCount (&SegmentList); ++I) { /* Add new spans if not empty */ Segment* S = CollAtUnchecked (&SegmentList, I); if (S->PC == 0) { /* Segment is empty */ continue; } CollAppend (Spans, NewSpan (S, 0, S->PC)); } /* Walk over the spans, close open, remove empty ones */ for (I = 0, J = 0; I < CollCount (Spans); ++I) { /* Get the next span */ Span* S = CollAtUnchecked (Spans, I); /* Set the end offset */ if (S->Start == S->Seg->PC) { /* Span is empty */ FreeSpan (S); } else { /* Span is not empty */ S->End = S->Seg->PC; /* Merge duplicate spans, then insert it at the new position */ CollReplace (Spans, MergeSpan (S), J++); } } /* New Count is now in J */ Spans->Count = J; } void WriteSpanList (const Collection* Spans) /* Write a list of spans to the output file */ { unsigned I; /* We only write spans if debug info is enabled */ if (DbgSyms == 0) { /* Number of spans is zero */ ObjWriteVar (0); } else { /* Write the number of spans */ ObjWriteVar (CollCount (Spans)); /* Write the spans */ for (I = 0; I < CollCount (Spans); ++I) { /* Write the id of the next span */ ObjWriteVar (((const Span*)CollConstAt (Spans, I))->Id); } } } static int CollectSpans (void* Entry, void* Data) /* Collect all spans in a collection sorted by id */ { /* Cast the pointers to real objects */ Span* S = Entry; Collection* C = Data; /* Place the entry into the collection */ CollReplaceExpand (C, S, S->Id); /* Keep the span */ return 0; } void WriteSpans (void) /* Write all spans to the object file */ { /* Tell the object file module that we're about to start the spans */ ObjStartSpans (); /* We will write scopes only if debug symbols are requested */ if (DbgSyms) { unsigned I; /* We must first collect all items in a collection sorted by id */ Collection SpanList = STATIC_COLLECTION_INITIALIZER; CollGrow (&SpanList, HT_GetCount (&SpanTab)); /* Walk over the hash table and fill the span list */ HT_Walk (&SpanTab, CollectSpans, &SpanList); /* Write the span count to the file */ ObjWriteVar (CollCount (&SpanList)); /* Write all spans */ for (I = 0; I < CollCount (&SpanList); ++I) { /* Get the span and check it */ const Span* S = CollAtUnchecked (&SpanList, I); CHECK (S->End > S->Start); /* Write data for the span We will write the size instead of the * end offset to save some bytes, since most spans are expected * to be rather small. */ ObjWriteVar (S->Seg->Num); ObjWriteVar (S->Start); ObjWriteVar (S->End - S->Start); ObjWriteVar (S->Type); } /* Free the collection with the spans */ DoneCollection (&SpanList); } else { /* No debug info requested */ ObjWriteVar (0); } /* Done writing the spans */ ObjEndSpans (); }
953
./cc65/src/ca65/pseudo.c
/*****************************************************************************/ /* */ /* pseudo.c */ /* */ /* Pseudo instructions for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> /* common */ #include "alignment.h" #include "assertion.h" #include "bitops.h" #include "cddefs.h" #include "coll.h" #include "filestat.h" #include "gentype.h" #include "intstack.h" #include "scopedefs.h" #include "symdefs.h" #include "tgttrans.h" #include "xmalloc.h" /* ca65 */ #include "anonname.h" #include "asserts.h" #include "condasm.h" #include "dbginfo.h" #include "enum.h" #include "error.h" #include "expr.h" #include "feature.h" #include "filetab.h" #include "global.h" #include "incpath.h" #include "instr.h" #include "listing.h" #include "macro.h" #include "nexttok.h" #include "objcode.h" #include "options.h" #include "pseudo.h" #include "repeat.h" #include "segment.h" #include "sizeof.h" #include "span.h" #include "spool.h" #include "struct.h" #include "symbol.h" #include "symtab.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Keyword we're about to handle */ static StrBuf Keyword = STATIC_STRBUF_INITIALIZER; /* CPU stack */ static IntStack CPUStack = STATIC_INTSTACK_INITIALIZER; /* Segment stack */ #define MAX_PUSHED_SEGMENTS 16 static Collection SegStack = STATIC_COLLECTION_INITIALIZER; /*****************************************************************************/ /* Forwards */ /*****************************************************************************/ static void DoUnexpected (void); /* Got an unexpected keyword */ static void DoInvalid (void); /* Handle a token that is invalid here, since it should have been handled on * a much lower level of the expression hierarchy. Getting this sort of token * means that the lower level code has bugs. * This function differs to DoUnexpected in that the latter may be triggered * by the user by using keywords in the wrong location. DoUnexpected is not * an error in the assembler itself, while DoInvalid is. */ /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static unsigned char OptionalAddrSize (void) /* If a colon follows, parse an optional address size spec and return it. * Otherwise return ADDR_SIZE_DEFAULT. */ { unsigned AddrSize = ADDR_SIZE_DEFAULT; if (CurTok.Tok == TOK_COLON) { NextTok (); AddrSize = ParseAddrSize (); if (!ValidAddrSizeForCPU (AddrSize)) { /* Print an error and reset to default */ Error ("Invalid address size specification for current CPU"); AddrSize = ADDR_SIZE_DEFAULT; } NextTok (); } return AddrSize; } static void SetBoolOption (unsigned char* Flag) /* Read a on/off/+/- option and set flag accordingly */ { static const char* Keys[] = { "OFF", "ON", }; if (CurTok.Tok == TOK_PLUS) { *Flag = 1; NextTok (); } else if (CurTok.Tok == TOK_MINUS) { *Flag = 0; NextTok (); } else if (CurTok.Tok == TOK_IDENT) { /* Map the keyword to a number */ switch (GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]))) { case 0: *Flag = 0; NextTok (); break; case 1: *Flag = 1; NextTok (); break; default: ErrorSkip ("`on' or `off' expected"); break; } } else if (TokIsSep (CurTok.Tok)) { /* Without anything assume switch on */ *Flag = 1; } else { ErrorSkip ("`on' or `off' expected"); } } static void ExportWithAssign (SymEntry* Sym, unsigned char AddrSize, unsigned Flags) /* Allow to assign the value of an export in an .export statement */ { /* The name and optional address size spec may be followed by an assignment * or equal token. */ if (CurTok.Tok == TOK_ASSIGN || CurTok.Tok == TOK_EQ) { /* Assignment means the symbol is a label */ if (CurTok.Tok == TOK_ASSIGN) { Flags |= SF_LABEL; } /* Skip the assignment token */ NextTok (); /* Define the symbol with the expression following the '=' */ SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags); } /* Now export the symbol */ SymExport (Sym, AddrSize, Flags); } static void ExportImport (void (*Func) (SymEntry*, unsigned char, unsigned), unsigned char DefAddrSize, unsigned Flags) /* Export or import symbols */ { SymEntry* Sym; unsigned char AddrSize; while (1) { /* We need an identifier here */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Identifier expected"); return; } /* Find the symbol table entry, allocate a new one if necessary */ Sym = SymFind (CurrentScope, &CurTok.SVal, SYM_ALLOC_NEW); /* Skip the name */ NextTok (); /* Get an optional address size */ AddrSize = OptionalAddrSize (); if (AddrSize == ADDR_SIZE_DEFAULT) { AddrSize = DefAddrSize; } /* Call the actual import/export function */ Func (Sym, AddrSize, Flags); /* More symbols? */ if (CurTok.Tok == TOK_COMMA) { NextTok (); } else { break; } } } static long IntArg (long Min, long Max) /* Read an integer argument and check a range. Accept the token "unlimited" * and return -1 in this case. */ { if (CurTok.Tok == TOK_IDENT && SB_CompareStr (&CurTok.SVal, "unlimited") == 0) { NextTok (); return -1; } else { long Val = ConstExpression (); if (Val < Min || Val > Max) { Error ("Range error"); Val = Min; } return Val; } } static void ConDes (const StrBuf* Name, unsigned Type) /* Parse remaining line for constructor/destructor of the remaining type */ { long Prio; /* Find the symbol table entry, allocate a new one if necessary */ SymEntry* Sym = SymFind (CurrentScope, Name, SYM_ALLOC_NEW); /* Optional constructor priority */ if (CurTok.Tok == TOK_COMMA) { /* Priority value follows */ NextTok (); Prio = ConstExpression (); if (Prio < CD_PRIO_MIN || Prio > CD_PRIO_MAX) { /* Value out of range */ Error ("Range error"); return; } } else { /* Use the default priority value */ Prio = CD_PRIO_DEF; } /* Define the symbol */ SymConDes (Sym, ADDR_SIZE_DEFAULT, Type, (unsigned) Prio); } static StrBuf* GenArrayType (StrBuf* Type, unsigned SpanSize, const char* ElementType, unsigned ElementTypeLen) /* Create an array (or single data) of the given type. SpanSize is the size * of the span, ElementType is a string that encodes the element data type. * The function returns Type. */ { /* Get the size of the element type */ unsigned ElementSize = GT_GET_SIZE (ElementType[0]); /* Get the number of array elements */ unsigned ElementCount = SpanSize / ElementSize; /* The span size must be divideable by the element size */ CHECK ((SpanSize % ElementSize) == 0); /* Encode the array */ GT_AddArray (Type, ElementCount); SB_AppendBuf (Type, ElementType, ElementTypeLen); /* Return the pointer to the created array type */ return Type; } /*****************************************************************************/ /* Handler functions */ /*****************************************************************************/ static void DoA16 (void) /* Switch the accu to 16 bit mode (assembler only) */ { if (GetCPU() != CPU_65816) { Error ("Command is only valid in 65816 mode"); } else { /* Immidiate mode has two extension bytes */ ExtBytes [AM65I_IMM_ACCU] = 2; } } static void DoA8 (void) /* Switch the accu to 8 bit mode (assembler only) */ { if (GetCPU() != CPU_65816) { Error ("Command is only valid in 65816 mode"); } else { /* Immidiate mode has one extension byte */ ExtBytes [AM65I_IMM_ACCU] = 1; } } static void DoAddr (void) /* Define addresses */ { /* Element type for the generated array */ static const char EType[2] = { GT_PTR, GT_VOID }; /* Record type information */ Span* S = OpenSpan (); StrBuf Type = STATIC_STRBUF_INITIALIZER; /* Parse arguments */ while (1) { ExprNode* Expr = Expression (); if (GetCPU () == CPU_65816 || ForceRange) { /* Do a range check */ Expr = GenWordExpr (Expr); } EmitWord (Expr); if (CurTok.Tok != TOK_COMMA) { break; } else { NextTok (); } } /* Close the span, then add type information to it */ S = CloseSpan (S); SetSpanType (S, GenArrayType (&Type, GetSpanSize (S), EType, sizeof (EType))); /* Free the strings */ SB_Done (&Type); } static void DoAlign (void) /* Align the PC to some boundary */ { long FillVal; long Alignment; /* Read the alignment value */ Alignment = ConstExpression (); if (Alignment <= 0 || (unsigned long) Alignment > MAX_ALIGNMENT) { ErrorSkip ("Range error"); return; } /* Optional value follows */ if (CurTok.Tok == TOK_COMMA) { NextTok (); FillVal = ConstExpression (); /* We need a byte value here */ if (!IsByteRange (FillVal)) { ErrorSkip ("Range error"); return; } } else { FillVal = -1; } /* Generate the alignment */ SegAlign (Alignment, (int) FillVal); } static void DoASCIIZ (void) /* Define text with a zero terminator */ { while (1) { /* Must have a string constant */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); return; } /* Translate into target charset and emit */ TgtTranslateStrBuf (&CurTok.SVal); EmitStrBuf (&CurTok.SVal); NextTok (); if (CurTok.Tok == TOK_COMMA) { NextTok (); } else { break; } } Emit0 (0); } static void DoAssert (void) /* Add an assertion */ { static const char* ActionTab [] = { "WARN", "WARNING", "ERROR", "LDWARN", "LDWARNING", "LDERROR", }; AssertAction Action; unsigned Msg; /* First we have the expression that has to evaluated */ ExprNode* Expr = Expression (); ConsumeComma (); /* Action follows */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Identifier expected"); return; } switch (GetSubKey (ActionTab, sizeof (ActionTab) / sizeof (ActionTab[0]))) { case 0: case 1: /* Warning */ Action = ASSERT_ACT_WARN; break; case 2: /* Error */ Action = ASSERT_ACT_ERROR; break; case 3: case 4: /* Linker warning */ Action = ASSERT_ACT_LDWARN; break; case 5: /* Linker error */ Action = ASSERT_ACT_LDERROR; break; default: Error ("Illegal assert action specifier"); /* Use lderror - there won't be an .o file anyway */ Action = ASSERT_ACT_LDERROR; break; } NextTok (); /* We can have an optional message. If no message is present, use * "Assertion failed". */ if (CurTok.Tok == TOK_COMMA) { /* Skip the comma */ NextTok (); /* Read the message */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); return; } /* Translate the message into a string id. We can then skip the input * string. */ Msg = GetStrBufId (&CurTok.SVal); NextTok (); } else { /* Use "Assertion failed" */ Msg = GetStringId ("Assertion failed"); } /* Remember the assertion */ AddAssertion (Expr, (AssertAction) Action, Msg); } static void DoAutoImport (void) /* Mark unresolved symbols as imported */ { SetBoolOption (&AutoImport); } static void DoBankBytes (void) /* Define bytes, extracting the bank byte from each expression in the list */ { while (1) { EmitByte (FuncBankByte ()); if (CurTok.Tok != TOK_COMMA) { break; } else { NextTok (); } } } static void DoBss (void) /* Switch to the BSS segment */ { UseSeg (&BssSegDef); } static void DoByte (void) /* Define bytes */ { /* Element type for the generated array */ static const char EType[1] = { GT_BYTE }; /* Record type information */ Span* S = OpenSpan (); StrBuf Type = STATIC_STRBUF_INITIALIZER; /* Parse arguments */ while (1) { if (CurTok.Tok == TOK_STRCON) { /* A string, translate into target charset and emit */ TgtTranslateStrBuf (&CurTok.SVal); EmitStrBuf (&CurTok.SVal); NextTok (); } else { EmitByte (BoundedExpr (Expression, 1)); } if (CurTok.Tok != TOK_COMMA) { break; } else { NextTok (); /* Do smart handling of dangling comma */ if (CurTok.Tok == TOK_SEP) { Error ("Unexpected end of line"); break; } } } /* Close the span, then add type information to it */ S = CloseSpan (S); SetSpanType (S, GenArrayType (&Type, GetSpanSize (S), EType, sizeof (EType))); /* Free the type string */ SB_Done (&Type); } static void DoCase (void) /* Switch the IgnoreCase option */ { SetBoolOption (&IgnoreCase); IgnoreCase = !IgnoreCase; } static void DoCharMap (void) /* Allow custome character mappings */ { long Index; long Code; /* Read the index as numerical value */ Index = ConstExpression (); if (Index <= 0 || Index > 255) { /* Value out of range */ ErrorSkip ("Range error"); return; } /* Comma follows */ ConsumeComma (); /* Read the character code */ Code = ConstExpression (); if (Code < 0 || Code > 255) { /* Value out of range */ ErrorSkip ("Range error"); return; } /* Set the character translation */ TgtTranslateSet ((unsigned) Index, (unsigned char) Code); } static void DoCode (void) /* Switch to the code segment */ { UseSeg (&CodeSegDef); } static void DoConDes (void) /* Export a symbol as constructor/destructor */ { static const char* Keys[] = { "CONSTRUCTOR", "DESTRUCTOR", "INTERRUPTOR", }; StrBuf Name = STATIC_STRBUF_INITIALIZER; long Type; /* Symbol name follows */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Identifier expected"); return; } SB_Copy (&Name, &CurTok.SVal); NextTok (); /* Type follows. May be encoded as identifier or numerical */ ConsumeComma (); if (CurTok.Tok == TOK_IDENT) { /* Map the following keyword to a number, then skip it */ Type = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0])); NextTok (); /* Check if we got a valid keyword */ if (Type < 0) { ErrorSkip ("Syntax error"); goto ExitPoint; } } else { /* Read the type as numerical value */ Type = ConstExpression (); if (Type < CD_TYPE_MIN || Type > CD_TYPE_MAX) { /* Value out of range */ ErrorSkip ("Range error"); goto ExitPoint; } } /* Parse the remainder of the line and export the symbol */ ConDes (&Name, (unsigned) Type); ExitPoint: /* Free string memory */ SB_Done (&Name); } static void DoConstructor (void) /* Export a symbol as constructor */ { StrBuf Name = STATIC_STRBUF_INITIALIZER; /* Symbol name follows */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Identifier expected"); return; } SB_Copy (&Name, &CurTok.SVal); NextTok (); /* Parse the remainder of the line and export the symbol */ ConDes (&Name, CD_TYPE_CON); /* Free string memory */ SB_Done (&Name); } static void DoData (void) /* Switch to the data segment */ { UseSeg (&DataSegDef); } static void DoDbg (void) /* Add debug information from high level code */ { static const char* Keys[] = { "FILE", "FUNC", "LINE", "SYM", }; int Key; /* We expect a subkey */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Identifier expected"); return; } /* Map the following keyword to a number */ Key = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0])); /* Skip the subkey */ NextTok (); /* Check the key and dispatch to a handler */ switch (Key) { case 0: DbgInfoFile (); break; case 1: DbgInfoFunc (); break; case 2: DbgInfoLine (); break; case 3: DbgInfoSym (); break; default: ErrorSkip ("Syntax error"); break; } } static void DoDByt (void) /* Output double bytes */ { /* Element type for the generated array */ static const char EType[1] = { GT_DBYTE }; /* Record type information */ Span* S = OpenSpan (); StrBuf Type = STATIC_STRBUF_INITIALIZER; /* Parse arguments */ while (1) { EmitWord (GenSwapExpr (BoundedExpr (Expression, 2))); if (CurTok.Tok != TOK_COMMA) { break; } else { NextTok (); } } /* Close the span, then add type information to it */ S = CloseSpan (S); SetSpanType (S, GenArrayType (&Type, GetSpanSize (S), EType, sizeof (EType))); /* Free the type string */ SB_Done (&Type); } static void DoDebugInfo (void) /* Switch debug info on or off */ { SetBoolOption (&DbgSyms); } static void DoDefine (void) /* Define a one line macro */ { MacDef (MAC_STYLE_DEFINE); } static void DoDelMac (void) /* Delete a classic macro */ { /* We expect an identifier */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Identifier expected"); } else { MacUndef (&CurTok.SVal, MAC_STYLE_CLASSIC); NextTok (); } } static void DoDestructor (void) /* Export a symbol as destructor */ { StrBuf Name = STATIC_STRBUF_INITIALIZER; /* Symbol name follows */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Identifier expected"); return; } SB_Copy (&Name, &CurTok.SVal); NextTok (); /* Parse the remainder of the line and export the symbol */ ConDes (&Name, CD_TYPE_DES); /* Free string memory */ SB_Done (&Name); } static void DoDWord (void) /* Define dwords */ { while (1) { EmitDWord (BoundedExpr (Expression, 4)); if (CurTok.Tok != TOK_COMMA) { break; } else { NextTok (); } } } static void DoEnd (void) /* End of assembly */ { ForcedEnd = 1; NextTok (); } static void DoEndProc (void) /* Leave a lexical level */ { if (CurrentScope->Type != SCOPE_SCOPE || CurrentScope->Label == 0) { /* No local scope */ ErrorSkip ("No open .PROC"); } else { SymLeaveLevel (); } } static void DoEndScope (void) /* Leave a lexical level */ { if (CurrentScope->Type != SCOPE_SCOPE || CurrentScope->Label != 0) { /* No local scope */ ErrorSkip ("No open .SCOPE"); } else { SymLeaveLevel (); } } static void DoError (void) /* User error */ { if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); } else { Error ("User error: %m%p", &CurTok.SVal); SkipUntilSep (); } } static void DoExitMacro (void) /* Exit a macro expansion */ { if (!InMacExpansion ()) { /* We aren't expanding a macro currently */ DoUnexpected (); } else { MacAbort (); } } static void DoExport (void) /* Export a symbol */ { ExportImport (ExportWithAssign, ADDR_SIZE_DEFAULT, SF_NONE); } static void DoExportZP (void) /* Export a zeropage symbol */ { ExportImport (ExportWithAssign, ADDR_SIZE_ZP, SF_NONE); } static void DoFarAddr (void) /* Define far addresses (24 bit) */ { /* Element type for the generated array */ static const char EType[2] = { GT_FAR_PTR, GT_VOID }; /* Record type information */ Span* S = OpenSpan (); StrBuf Type = STATIC_STRBUF_INITIALIZER; /* Parse arguments */ while (1) { EmitFarAddr (BoundedExpr (Expression, 3)); if (CurTok.Tok != TOK_COMMA) { break; } else { NextTok (); } } /* Close the span, then add type information to it */ S = CloseSpan (S); SetSpanType (S, GenArrayType (&Type, GetSpanSize (S), EType, sizeof (EType))); /* Free the type string */ SB_Done (&Type); } static void DoFatal (void) /* Fatal user error */ { if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); } else { Fatal ("User error: %m%p", &CurTok.SVal); SkipUntilSep (); } } static void DoFeature (void) /* Switch the Feature option */ { /* Allow a list of comma separated keywords */ while (1) { /* We expect an identifier */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Identifier expected"); return; } /* Make the string attribute lower case */ LocaseSVal (); /* Set the feature and check for errors */ if (SetFeature (&CurTok.SVal) == FEAT_UNKNOWN) { /* Not found */ ErrorSkip ("Invalid feature: `%m%p'", &CurTok.SVal); return; } else { /* Skip the keyword */ NextTok (); } /* Allow more than one keyword */ if (CurTok.Tok == TOK_COMMA) { NextTok (); } else { break; } } } static void DoFileOpt (void) /* Insert a file option */ { long OptNum; /* The option type may be given as a keyword or as a number. */ if (CurTok.Tok == TOK_IDENT) { /* Option given as keyword */ static const char* Keys [] = { "AUTHOR", "COMMENT", "COMPILER" }; /* Map the option to a number */ OptNum = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0])); if (OptNum < 0) { /* Not found */ ErrorSkip ("File option keyword expected"); return; } /* Skip the keyword */ NextTok (); /* Must be followed by a comma */ ConsumeComma (); /* We accept only string options for now */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); return; } /* Insert the option */ switch (OptNum) { case 0: /* Author */ OptAuthor (&CurTok.SVal); break; case 1: /* Comment */ OptComment (&CurTok.SVal); break; case 2: /* Compiler */ OptCompiler (&CurTok.SVal); break; default: Internal ("Invalid OptNum: %ld", OptNum); } /* Done */ NextTok (); } else { /* Option given as number */ OptNum = ConstExpression (); if (!IsByteRange (OptNum)) { ErrorSkip ("Range error"); return; } /* Must be followed by a comma */ ConsumeComma (); /* We accept only string options for now */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); return; } /* Insert the option */ OptStr ((unsigned char) OptNum, &CurTok.SVal); /* Done */ NextTok (); } } static void DoForceImport (void) /* Do a forced import on a symbol */ { ExportImport (SymImport, ADDR_SIZE_DEFAULT, SF_FORCED); } static void DoGlobal (void) /* Declare a global symbol */ { ExportImport (SymGlobal, ADDR_SIZE_DEFAULT, SF_NONE); } static void DoGlobalZP (void) /* Declare a global zeropage symbol */ { ExportImport (SymGlobal, ADDR_SIZE_ZP, SF_NONE); } static void DoHiBytes (void) /* Define bytes, extracting the hi byte from each expression in the list */ { while (1) { EmitByte (FuncHiByte ()); if (CurTok.Tok != TOK_COMMA) { break; } else { NextTok (); } } } static void DoI16 (void) /* Switch the index registers to 16 bit mode (assembler only) */ { if (GetCPU() != CPU_65816) { Error ("Command is only valid in 65816 mode"); } else { /* Immidiate mode has two extension bytes */ ExtBytes [AM65I_IMM_INDEX] = 2; } } static void DoI8 (void) /* Switch the index registers to 16 bit mode (assembler only) */ { if (GetCPU() != CPU_65816) { Error ("Command is only valid in 65816 mode"); } else { /* Immidiate mode has one extension byte */ ExtBytes [AM65I_IMM_INDEX] = 1; } } static void DoImport (void) /* Import a symbol */ { ExportImport (SymImport, ADDR_SIZE_DEFAULT, SF_NONE); } static void DoImportZP (void) /* Import a zero page symbol */ { ExportImport (SymImport, ADDR_SIZE_ZP, SF_NONE); } static void DoIncBin (void) /* Include a binary file */ { StrBuf Name = STATIC_STRBUF_INITIALIZER; struct stat StatBuf; long Start = 0L; long Count = -1L; long Size; FILE* F; /* Name must follow */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); return; } SB_Copy (&Name, &CurTok.SVal); SB_Terminate (&Name); NextTok (); /* A starting offset may follow */ if (CurTok.Tok == TOK_COMMA) { NextTok (); Start = ConstExpression (); /* And a length may follow */ if (CurTok.Tok == TOK_COMMA) { NextTok (); Count = ConstExpression (); } } /* Try to open the file */ F = fopen (SB_GetConstBuf (&Name), "rb"); if (F == 0) { /* Search for the file in the binary include directory */ char* PathName = SearchFile (BinSearchPath, SB_GetConstBuf (&Name)); if (PathName == 0 || (F = fopen (PathName, "rb")) == 0) { /* Not found or cannot open, print an error and bail out */ ErrorSkip ("Cannot open include file `%m%p': %s", &Name, strerror (errno)); xfree (PathName); goto ExitPoint; } /* Remember the new file name */ SB_CopyStr (&Name, PathName); /* Free the allocated memory */ xfree (PathName); } /* Get the size of the file */ fseek (F, 0, SEEK_END); Size = ftell (F); /* Stat the file and remember the values. There a race condition here, * since we cannot use fileno() (non standard identifier in standard * header file), and therefore not fstat. When using stat with the * file name, there's a risk that the file was deleted and recreated * while it was open. Since mtime and size are only used to check * if a file has changed in the debugger, we will ignore this problem * here. */ SB_Terminate (&Name); if (FileStat (SB_GetConstBuf (&Name), &StatBuf) != 0) { Fatal ("Cannot stat input file `%m%p': %s", &Name, strerror (errno)); } /* Add the file to the input file table */ AddFile (&Name, FT_BINARY, Size, (unsigned long) StatBuf.st_mtime); /* If a count was not given, calculate it now */ if (Count < 0) { Count = Size - Start; if (Count < 0) { /* Nothing to read - flag this as a range error */ ErrorSkip ("Range error"); goto Done; } } else { /* Count was given, check if it is valid */ if (Start + Count > Size) { ErrorSkip ("Range error"); goto Done; } } /* Seek to the start position */ fseek (F, Start, SEEK_SET); /* Read chunks and insert them into the output */ while (Count > 0) { unsigned char Buf [1024]; /* Calculate the number of bytes to read */ size_t BytesToRead = (Count > (long)sizeof(Buf))? sizeof(Buf) : (size_t) Count; /* Read chunk */ size_t BytesRead = fread (Buf, 1, BytesToRead, F); if (BytesToRead != BytesRead) { /* Some sort of error */ ErrorSkip ("Cannot read from include file `%m%p': %s", &Name, strerror (errno)); break; } /* Insert it into the output */ EmitData (Buf, BytesRead); /* Keep the counters current */ Count -= BytesRead; } Done: /* Close the file, ignore errors since it's r/o */ (void) fclose (F); ExitPoint: /* Free string memory */ SB_Done (&Name); } static void DoInclude (void) /* Include another file */ { /* Name must follow */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); } else { SB_Terminate (&CurTok.SVal); if (NewInputFile (SB_GetConstBuf (&CurTok.SVal)) == 0) { /* Error opening the file, skip remainder of line */ SkipUntilSep (); } } } static void DoInterruptor (void) /* Export a symbol as interruptor */ { StrBuf Name = STATIC_STRBUF_INITIALIZER; /* Symbol name follows */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Identifier expected"); return; } SB_Copy (&Name, &CurTok.SVal); NextTok (); /* Parse the remainder of the line and export the symbol */ ConDes (&Name, CD_TYPE_INT); /* Free string memory */ SB_Done (&Name); } static void DoInvalid (void) /* Handle a token that is invalid here, since it should have been handled on * a much lower level of the expression hierarchy. Getting this sort of token * means that the lower level code has bugs. * This function differs to DoUnexpected in that the latter may be triggered * by the user by using keywords in the wrong location. DoUnexpected is not * an error in the assembler itself, while DoInvalid is. */ { Internal ("Unexpected token: %m%p", &Keyword); } static void DoLineCont (void) /* Switch the use of line continuations */ { SetBoolOption (&LineCont); } static void DoList (void) /* Enable/disable the listing */ { /* Get the setting */ unsigned char List; SetBoolOption (&List); /* Manage the counter */ if (List) { EnableListing (); } else { DisableListing (); } } static void DoLoBytes (void) /* Define bytes, extracting the lo byte from each expression in the list */ { while (1) { EmitByte (FuncLoByte ()); if (CurTok.Tok != TOK_COMMA) { break; } else { NextTok (); } } } static void DoListBytes (void) /* Set maximum number of bytes to list for one line */ { SetListBytes (IntArg (MIN_LIST_BYTES, MAX_LIST_BYTES)); } static void DoLocalChar (void) /* Define the character that starts local labels */ { if (CurTok.Tok != TOK_CHARCON) { ErrorSkip ("Character constant expected"); } else { if (CurTok.IVal != '@' && CurTok.IVal != '?') { Error ("Invalid start character for locals"); } else { LocalStart = (char) CurTok.IVal; } NextTok (); } } static void DoMacPack (void) /* Insert a macro package */ { /* We expect an identifier */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Identifier expected"); } else { SB_AppendStr (&CurTok.SVal, ".mac"); SB_Terminate (&CurTok.SVal); if (NewInputFile (SB_GetConstBuf (&CurTok.SVal)) == 0) { /* Error opening the file, skip remainder of line */ SkipUntilSep (); } } } static void DoMacro (void) /* Start a macro definition */ { MacDef (MAC_STYLE_CLASSIC); } static void DoNull (void) /* Switch to the NULL segment */ { UseSeg (&NullSegDef); } static void DoOrg (void) /* Start absolute code */ { long PC = ConstExpression (); if (PC < 0 || PC > 0xFFFFFF) { Error ("Range error"); return; } EnterAbsoluteMode (PC); } static void DoOut (void) /* Output a string */ { if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); } else { /* Output the string and be sure to flush the output to keep it in * sync with any error messages if the output is redirected to a file. */ printf ("%.*s\n", (int) SB_GetLen (&CurTok.SVal), SB_GetConstBuf (&CurTok.SVal)); fflush (stdout); NextTok (); } } static void DoP02 (void) /* Switch to 6502 CPU */ { SetCPU (CPU_6502); } static void DoPC02 (void) /* Switch to 65C02 CPU */ { SetCPU (CPU_65C02); } static void DoP816 (void) /* Switch to 65816 CPU */ { SetCPU (CPU_65816); } static void DoPageLength (void) /* Set the page length for the listing */ { PageLength = IntArg (MIN_PAGE_LEN, MAX_PAGE_LEN); } static void DoPopCPU (void) /* Pop an old CPU setting from the CPU stack */ { /* Must have a CPU on the stack */ if (IS_IsEmpty (&CPUStack)) { ErrorSkip ("CPU stack is empty"); return; } /* Set the CPU to the value popped from stack */ SetCPU (IS_Pop (&CPUStack)); } static void DoPopSeg (void) /* Pop an old segment from the segment stack */ { SegDef* Def; /* Must have a segment on the stack */ if (CollCount (&SegStack) == 0) { ErrorSkip ("Segment stack is empty"); return; } /* Pop the last element */ Def = CollPop (&SegStack); /* Restore this segment */ UseSeg (Def); /* Delete the segment definition */ FreeSegDef (Def); } static void DoProc (void) /* Start a new lexical scope */ { StrBuf Name = STATIC_STRBUF_INITIALIZER; unsigned char AddrSize; SymEntry* Sym = 0; if (CurTok.Tok == TOK_IDENT) { /* The new scope has a name. Remember it. */ SB_Copy (&Name, &CurTok.SVal); /* Search for the symbol, generate a new one if needed */ Sym = SymFind (CurrentScope, &Name, SYM_ALLOC_NEW); /* Skip the scope name */ NextTok (); /* Read an optional address size specifier */ AddrSize = OptionalAddrSize (); /* Mark the symbol as defined */ SymDef (Sym, GenCurrentPC (), AddrSize, SF_LABEL); } else { /* A .PROC statement without a name */ Warning (1, "Unnamed .PROCs are deprecated, please use .SCOPE"); AnonName (&Name, "PROC"); AddrSize = ADDR_SIZE_DEFAULT; } /* Enter a new scope */ SymEnterLevel (&Name, SCOPE_SCOPE, AddrSize, Sym); /* Free memory for Name */ SB_Done (&Name); } static void DoPSC02 (void) /* Switch to 65SC02 CPU */ { SetCPU (CPU_65SC02); } static void DoPushCPU (void) /* Push the current CPU setting onto the CPU stack */ { /* Can only push a limited size of segments */ if (IS_IsFull (&CPUStack)) { ErrorSkip ("CPU stack overflow"); return; } /* Get the current segment and push it */ IS_Push (&CPUStack, GetCPU ()); } static void DoPushSeg (void) /* Push the current segment onto the segment stack */ { /* Can only push a limited size of segments */ if (CollCount (&SegStack) >= MAX_PUSHED_SEGMENTS) { ErrorSkip ("Segment stack overflow"); return; } /* Get the current segment and push it */ CollAppend (&SegStack, DupSegDef (GetCurrentSegDef ())); } static void DoReloc (void) /* Enter relocatable mode */ { EnterRelocMode (); } static void DoRepeat (void) /* Repeat some instruction block */ { ParseRepeat (); } static void DoRes (void) /* Reserve some number of storage bytes */ { long Count; long Val; Count = ConstExpression (); if (Count > 0xFFFF || Count < 0) { ErrorSkip ("Range error"); return; } if (CurTok.Tok == TOK_COMMA) { NextTok (); Val = ConstExpression (); /* We need a byte value here */ if (!IsByteRange (Val)) { ErrorSkip ("Range error"); return; } /* Emit constant values */ while (Count--) { Emit0 ((unsigned char) Val); } } else { /* Emit fill fragments */ EmitFill (Count); } } static void DoROData (void) /* Switch to the r/o data segment */ { UseSeg (&RODataSegDef); } static void DoScope (void) /* Start a local scope */ { StrBuf Name = STATIC_STRBUF_INITIALIZER; unsigned char AddrSize; if (CurTok.Tok == TOK_IDENT) { /* The new scope has a name. Remember and skip it. */ SB_Copy (&Name, &CurTok.SVal); NextTok (); } else { /* An unnamed scope */ AnonName (&Name, "SCOPE"); } /* Read an optional address size specifier */ AddrSize = OptionalAddrSize (); /* Enter the new scope */ SymEnterLevel (&Name, SCOPE_SCOPE, AddrSize, 0); /* Free memory for Name */ SB_Done (&Name); } static void DoSegment (void) /* Switch to another segment */ { StrBuf Name = STATIC_STRBUF_INITIALIZER; SegDef Def; if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); } else { /* Save the name of the segment and skip it */ SB_Copy (&Name, &CurTok.SVal); NextTok (); /* Use the name for the segment definition */ SB_Terminate (&Name); Def.Name = SB_GetBuf (&Name); /* Check for an optional address size modifier */ Def.AddrSize = OptionalAddrSize (); /* Set the segment */ UseSeg (&Def); } /* Free memory for Name */ SB_Done (&Name); } static void DoSetCPU (void) /* Switch the CPU instruction set */ { /* We expect an identifier */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); } else { cpu_t CPU; /* Try to find the CPU */ SB_Terminate (&CurTok.SVal); CPU = FindCPU (SB_GetConstBuf (&CurTok.SVal)); /* Switch to the new CPU */ SetCPU (CPU); /* Skip the identifier. If the CPU switch was successful, the scanner * will treat the input now correctly for the new CPU. */ NextTok (); } } static void DoSmart (void) /* Smart mode on/off */ { SetBoolOption (&SmartMode); } static void DoSunPlus (void) /* Switch to the SUNPLUS CPU */ { SetCPU (CPU_SUNPLUS); } static void DoTag (void) /* Allocate space for a struct */ { SymEntry* SizeSym; long Size; /* Read the struct name */ SymTable* Struct = ParseScopedSymTable (); /* Check the supposed struct */ if (Struct == 0) { ErrorSkip ("Unknown struct"); return; } if (GetSymTabType (Struct) != SCOPE_STRUCT) { ErrorSkip ("Not a struct"); return; } /* Get the symbol that defines the size of the struct */ SizeSym = GetSizeOfScope (Struct); /* Check if it does exist and if its value is known */ if (SizeSym == 0 || !SymIsConst (SizeSym, &Size)) { ErrorSkip ("Size of struct/union is unknown"); return; } /* Optional multiplicator may follow */ if (CurTok.Tok == TOK_COMMA) { long Multiplicator; NextTok (); Multiplicator = ConstExpression (); /* Multiplicator must make sense */ if (Multiplicator <= 0) { ErrorSkip ("Range error"); return; } Size *= Multiplicator; } /* Emit fill fragments */ EmitFill (Size); } static void DoUnDef (void) /* Undefine a define style macro */ { /* The function is called with the .UNDEF token in place, because we need * to disable .define macro expansions before reading the next token. * Otherwise the name of the macro would be expanded, so we would never * see it. */ DisableDefineStyleMacros (); NextTok (); EnableDefineStyleMacros (); /* We expect an identifier */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Identifier expected"); } else { MacUndef (&CurTok.SVal, MAC_STYLE_DEFINE); NextTok (); } } static void DoUnexpected (void) /* Got an unexpected keyword */ { Error ("Unexpected `%m%p'", &Keyword); SkipUntilSep (); } static void DoWarning (void) /* User warning */ { if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); } else { Warning (0, "User warning: %m%p", &CurTok.SVal); SkipUntilSep (); } } static void DoWord (void) /* Define words */ { /* Element type for the generated array */ static const char EType[1] = { GT_WORD }; /* Record type information */ Span* S = OpenSpan (); StrBuf Type = STATIC_STRBUF_INITIALIZER; /* Parse arguments */ while (1) { EmitWord (BoundedExpr (Expression, 2)); if (CurTok.Tok != TOK_COMMA) { break; } else { NextTok (); } } /* Close the span, then add type information to it */ S = CloseSpan (S); SetSpanType (S, GenArrayType (&Type, GetSpanSize (S), EType, sizeof (EType))); /* Free the type string */ SB_Done (&Type); } static void DoZeropage (void) /* Switch to the zeropage segment */ { UseSeg (&ZeropageSegDef); } /*****************************************************************************/ /* Table data */ /*****************************************************************************/ /* Control commands flags */ enum { ccNone = 0x0000, /* No special flags */ ccKeepToken = 0x0001 /* Do not skip the current token */ }; /* Control command table */ typedef struct CtrlDesc CtrlDesc; struct CtrlDesc { unsigned Flags; /* Flags for this directive */ void (*Handler) (void); /* Command handler */ }; #define PSEUDO_COUNT (sizeof (CtrlCmdTab) / sizeof (CtrlCmdTab [0])) static CtrlDesc CtrlCmdTab [] = { { ccNone, DoA16 }, { ccNone, DoA8 }, { ccNone, DoAddr }, /* .ADDR */ { ccNone, DoAlign }, { ccNone, DoASCIIZ }, { ccNone, DoAssert }, { ccNone, DoAutoImport }, { ccNone, DoUnexpected }, /* .BANK */ { ccNone, DoUnexpected }, /* .BANKBYTE */ { ccNone, DoBankBytes }, { ccNone, DoUnexpected }, /* .BLANK */ { ccNone, DoBss }, { ccNone, DoByte }, { ccNone, DoCase }, { ccNone, DoCharMap }, { ccNone, DoCode }, { ccNone, DoUnexpected, }, /* .CONCAT */ { ccNone, DoConDes }, { ccNone, DoUnexpected }, /* .CONST */ { ccNone, DoConstructor }, { ccNone, DoUnexpected }, /* .CPU */ { ccNone, DoData }, { ccNone, DoDbg, }, { ccNone, DoDByt }, { ccNone, DoDebugInfo }, { ccNone, DoDefine }, { ccNone, DoUnexpected }, /* .DEFINED */ { ccNone, DoDelMac }, { ccNone, DoDestructor }, { ccNone, DoDWord }, { ccKeepToken, DoConditionals }, /* .ELSE */ { ccKeepToken, DoConditionals }, /* .ELSEIF */ { ccKeepToken, DoEnd }, { ccNone, DoUnexpected }, /* .ENDENUM */ { ccKeepToken, DoConditionals }, /* .ENDIF */ { ccNone, DoUnexpected }, /* .ENDMACRO */ { ccNone, DoEndProc }, { ccNone, DoUnexpected }, /* .ENDREPEAT */ { ccNone, DoEndScope }, { ccNone, DoUnexpected }, /* .ENDSTRUCT */ { ccNone, DoUnexpected }, /* .ENDUNION */ { ccNone, DoEnum }, { ccNone, DoError }, { ccNone, DoExitMacro }, { ccNone, DoExport }, { ccNone, DoExportZP }, { ccNone, DoFarAddr }, { ccNone, DoFatal }, { ccNone, DoFeature }, { ccNone, DoFileOpt }, { ccNone, DoForceImport }, { ccNone, DoUnexpected }, /* .FORCEWORD */ { ccNone, DoGlobal }, { ccNone, DoGlobalZP }, { ccNone, DoUnexpected }, /* .HIBYTE */ { ccNone, DoHiBytes }, { ccNone, DoUnexpected }, /* .HIWORD */ { ccNone, DoI16 }, { ccNone, DoI8 }, { ccNone, DoUnexpected }, /* .IDENT */ { ccKeepToken, DoConditionals }, /* .IF */ { ccKeepToken, DoConditionals }, /* .IFBLANK */ { ccKeepToken, DoConditionals }, /* .IFCONST */ { ccKeepToken, DoConditionals }, /* .IFDEF */ { ccKeepToken, DoConditionals }, /* .IFNBLANK */ { ccKeepToken, DoConditionals }, /* .IFNCONST */ { ccKeepToken, DoConditionals }, /* .IFNDEF */ { ccKeepToken, DoConditionals }, /* .IFNREF */ { ccKeepToken, DoConditionals }, /* .IFP02 */ { ccKeepToken, DoConditionals }, /* .IFP816 */ { ccKeepToken, DoConditionals }, /* .IFPC02 */ { ccKeepToken, DoConditionals }, /* .IFPSC02 */ { ccKeepToken, DoConditionals }, /* .IFREF */ { ccNone, DoImport }, { ccNone, DoImportZP }, { ccNone, DoIncBin }, { ccNone, DoInclude }, { ccNone, DoInterruptor }, { ccNone, DoInvalid }, /* .LEFT */ { ccNone, DoLineCont }, { ccNone, DoList }, { ccNone, DoListBytes }, { ccNone, DoUnexpected }, /* .LOBYTE */ { ccNone, DoLoBytes }, { ccNone, DoUnexpected }, /* .LOCAL */ { ccNone, DoLocalChar }, { ccNone, DoUnexpected }, /* .LOWORD */ { ccNone, DoMacPack }, { ccNone, DoMacro }, { ccNone, DoUnexpected }, /* .MATCH */ { ccNone, DoUnexpected }, /* .MAX */ { ccNone, DoInvalid }, /* .MID */ { ccNone, DoUnexpected }, /* .MIN */ { ccNone, DoNull }, { ccNone, DoOrg }, { ccNone, DoOut }, { ccNone, DoP02 }, { ccNone, DoP816 }, { ccNone, DoPageLength }, { ccNone, DoUnexpected }, /* .PARAMCOUNT */ { ccNone, DoPC02 }, { ccNone, DoPopCPU }, { ccNone, DoPopSeg }, { ccNone, DoProc }, { ccNone, DoPSC02 }, { ccNone, DoPushCPU }, { ccNone, DoPushSeg }, { ccNone, DoUnexpected }, /* .REFERENCED */ { ccNone, DoReloc }, { ccNone, DoRepeat }, { ccNone, DoRes }, { ccNone, DoInvalid }, /* .RIGHT */ { ccNone, DoROData }, { ccNone, DoScope }, { ccNone, DoSegment }, { ccNone, DoUnexpected }, /* .SET */ { ccNone, DoSetCPU }, { ccNone, DoUnexpected }, /* .SIZEOF */ { ccNone, DoSmart }, { ccNone, DoUnexpected }, /* .SPRINTF */ { ccNone, DoUnexpected }, /* .STRAT */ { ccNone, DoUnexpected }, /* .STRING */ { ccNone, DoUnexpected }, /* .STRLEN */ { ccNone, DoStruct }, { ccNone, DoSunPlus }, { ccNone, DoTag }, { ccNone, DoUnexpected }, /* .TCOUNT */ { ccNone, DoUnexpected }, /* .TIME */ { ccKeepToken, DoUnDef }, { ccNone, DoUnion }, { ccNone, DoUnexpected }, /* .VERSION */ { ccNone, DoWarning }, { ccNone, DoWord }, { ccNone, DoUnexpected }, /* .XMATCH */ { ccNone, DoZeropage }, }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ void HandlePseudo (void) /* Handle a pseudo instruction */ { CtrlDesc* D; /* Calculate the index into the table */ unsigned Index = CurTok.Tok - TOK_FIRSTPSEUDO; /* Safety check */ if (PSEUDO_COUNT != (TOK_LASTPSEUDO - TOK_FIRSTPSEUDO + 1)) { Internal ("Pseudo mismatch: PSEUDO_COUNT = %u, actual count = %u\n", (unsigned) PSEUDO_COUNT, TOK_LASTPSEUDO - TOK_FIRSTPSEUDO + 1); } CHECK (Index < PSEUDO_COUNT); /* Get the pseudo intruction descriptor */ D = &CtrlCmdTab [Index]; /* Remember the instruction, then skip it if needed */ if ((D->Flags & ccKeepToken) == 0) { SB_Copy (&Keyword, &CurTok.SVal); NextTok (); } /* Call the handler */ D->Handler (); } void CheckPseudo (void) /* Check if the stacks are empty at end of assembly */ { if (CollCount (&SegStack) != 0) { Warning (1, "Segment stack is not empty"); } if (!IS_IsEmpty (&CPUStack)) { Warning (1, "CPU stack is not empty"); } }
954
./cc65/src/ca65/nexttok.c
/*****************************************************************************/ /* */ /* nexttok.c */ /* */ /* Get next token and handle token level functions */ /* */ /* */ /* */ /* (C) 2000-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> /* common */ #include "chartype.h" #include "check.h" #include "strbuf.h" /* ca65 */ #include "condasm.h" #include "error.h" #include "expr.h" #include "global.h" #include "scanner.h" #include "toklist.h" #include "nexttok.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ static unsigned RawMode = 0; /* Raw token mode flag/counter */ /*****************************************************************************/ /* Error handling */ /*****************************************************************************/ static int LookAtStrCon (void) /* Make sure the next token is a string constant. If not, print an error * messages skip the remainder of the line and return false. Otherwise return * true. */ { if (CurTok.Tok != TOK_STRCON) { Error ("String constant expected"); SkipUntilSep (); return 0; } else { return 1; } } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static TokList* CollectTokens (unsigned Start, unsigned Count) /* Read a list of tokens that is optionally enclosed in curly braces and * terminated by a right paren. For all tokens starting at the one with index * Start, and ending at (Start+Count-1), place them into a token list, and * return this token list. */ { /* Create the token list */ TokList* List = NewTokList (); /* Determine if the list is enclosed in curly braces. */ token_t Term = GetTokListTerm (TOK_RPAREN); /* Read the token list */ unsigned Current = 0; while (CurTok.Tok != Term) { /* Check for end of line or end of input */ if (TokIsSep (CurTok.Tok)) { Error ("Unexpected end of line"); return List; } /* Collect tokens in the given range */ if (Current >= Start && Current < Start+Count) { /* Add the current token to the list */ AddCurTok (List); } /* Get the next token */ ++Current; NextTok (); } /* Eat the terminator token */ NextTok (); /* If the list was enclosed in curly braces, we do expect now a right paren */ if (Term == TOK_RCURLY) { ConsumeRParen (); } /* Return the list of collected tokens */ return List; } static void FuncConcat (void) /* Handle the .CONCAT function */ { StrBuf Buf = STATIC_STRBUF_INITIALIZER; /* Skip it */ NextTok (); /* Left paren expected */ ConsumeLParen (); /* Concatenate any number of strings */ while (1) { /* Next token must be a string */ if (!LookAtStrCon ()) { SB_Done (&Buf); return; } /* Append the string */ SB_Append (&Buf, &CurTok.SVal); /* Skip the string token */ NextTok (); /* Comma means another argument */ if (CurTok.Tok == TOK_COMMA) { NextTok (); } else { /* Done */ break; } } /* We expect a closing parenthesis, but will not skip it but replace it * by the string token just created. */ if (CurTok.Tok != TOK_RPAREN) { Error ("`)' expected"); } else { CurTok.Tok = TOK_STRCON; SB_Copy (&CurTok.SVal, &Buf); SB_Terminate (&CurTok.SVal); } /* Free the string buffer */ SB_Done (&Buf); } static void NoIdent (void) /* Print an error message and skip the remainder of the line */ { Error ("Argument of .IDENT is not a valid identifier"); SkipUntilSep (); } static void FuncIdent (void) /* Handle the .IDENT function */ { StrBuf Buf = STATIC_STRBUF_INITIALIZER; token_t Id; unsigned I; /* Skip it */ NextTok (); /* Left paren expected */ ConsumeLParen (); /* The function expects a string argument */ if (!LookAtStrCon ()) { return; } /* Check that the string contains a valid identifier. While doing so, * determine if it is a cheap local, or global one. */ SB_Reset (&CurTok.SVal); /* Check for a cheap local symbol */ if (SB_Peek (&CurTok.SVal) == LocalStart) { SB_Skip (&CurTok.SVal); Id = TOK_LOCAL_IDENT; } else { Id = TOK_IDENT; } /* Next character must be a valid identifier start */ if (!IsIdStart (SB_Get (&CurTok.SVal))) { NoIdent (); return; } for (I = SB_GetIndex (&CurTok.SVal); I < SB_GetLen (&CurTok.SVal); ++I) { if (!IsIdChar (SB_AtUnchecked (&CurTok.SVal, I))) { NoIdent (); return; } } if (IgnoreCase) { UpcaseSVal (); } /* If anything is ok, save and skip the string. Check that the next token * is a right paren, then replace the token by an identifier token. */ SB_Copy (&Buf, &CurTok.SVal); NextTok (); if (CurTok.Tok != TOK_RPAREN) { Error ("`)' expected"); } else { CurTok.Tok = Id; SB_Copy (&CurTok.SVal, &Buf); SB_Terminate (&CurTok.SVal); } /* Free buffer memory */ SB_Done (&Buf); } static void FuncLeft (void) /* Handle the .LEFT function */ { long Count; TokList* List; /* Skip it */ NextTok (); /* Left paren expected */ ConsumeLParen (); /* Count argument. Correct negative counts to zero. */ Count = ConstExpression (); if (Count < 0) { Count = 0; } ConsumeComma (); /* Read the token list */ List = CollectTokens (0, (unsigned) Count); /* Since we want to insert the list before the now current token, we have * to save the current token in some way and then skip it. To do this, we * will add the current token at the end of the token list (so the list * will never be empty), push the token list, and then skip the current * token. This will replace the current token by the first token from the * list (which will be the old current token in case the list was empty). */ AddCurTok (List); /* Insert it into the scanner feed */ PushTokList (List, ".LEFT"); /* Skip the current token */ NextTok (); } static void FuncMid (void) /* Handle the .MID function */ { long Start; long Count; TokList* List; /* Skip it */ NextTok (); /* Left paren expected */ ConsumeLParen (); /* Start argument. Since the start argument can get negative with * expressions like ".tcount(arg)-2", we correct it to zero silently. */ Start = ConstExpression (); if (Start < 0 || Start > 100) { Start = 0; } ConsumeComma (); /* Count argument. Similar as above, we will accept negative counts and * correct them to zero silently. */ Count = ConstExpression (); if (Count < 0) { Count = 0; } ConsumeComma (); /* Read the token list */ List = CollectTokens ((unsigned) Start, (unsigned) Count); /* Since we want to insert the list before the now current token, we have * to save the current token in some way and then skip it. To do this, we * will add the current token at the end of the token list (so the list * will never be empty), push the token list, and then skip the current * token. This will replace the current token by the first token from the * list (which will be the old current token in case the list was empty). */ AddCurTok (List); /* Insert it into the scanner feed */ PushTokList (List, ".MID"); /* Skip the current token */ NextTok (); } static void FuncRight (void) /* Handle the .RIGHT function */ { long Count; TokList* List; /* Skip it */ NextTok (); /* Left paren expected */ ConsumeLParen (); /* Count argument. Correct negative counts to zero. */ Count = ConstExpression (); if (Count < 0) { Count = 0; } ConsumeComma (); /* Read the complete token list */ List = CollectTokens (0, 9999); /* Delete tokens from the list until Count tokens are remaining */ while (List->Count > (unsigned) Count) { /* Get the first node */ TokNode* T = List->Root; /* Remove it from the list */ List->Root = List->Root->Next; /* Free the node */ FreeTokNode (T); /* Corrent the token counter */ List->Count--; } /* Since we want to insert the list before the now current token, we have * to save the current token in some way and then skip it. To do this, we * will add the current token at the end of the token list (so the list * will never be empty), push the token list, and then skip the current * token. This will replace the current token by the first token from the * list (which will be the old current token in case the list was empty). */ AddCurTok (List); /* Insert it into the scanner feed */ PushTokList (List, ".RIGHT"); /* Skip the current token */ NextTok (); } static void InvalidFormatString (void) /* Print an error message and skip the remainder of the line */ { Error ("Invalid format string"); SkipUntilSep (); } static void FuncSPrintF (void) /* Handle the .SPRINTF function */ { StrBuf Format = STATIC_STRBUF_INITIALIZER; /* User supplied format */ StrBuf R = STATIC_STRBUF_INITIALIZER; /* Result string */ StrBuf F1 = STATIC_STRBUF_INITIALIZER; /* One format spec from F */ StrBuf R1 = STATIC_STRBUF_INITIALIZER; /* One result */ char C; int Done; long IVal; /* Integer value */ /* Skip the .SPRINTF token */ NextTok (); /* Left paren expected */ ConsumeLParen (); /* First argument is a format string. Remember and skip it */ if (!LookAtStrCon ()) { return; } SB_Copy (&Format, &CurTok.SVal); NextTok (); /* Walk over the format string, generating the function result in R */ while (1) { /* Get the next char from the format string and check for EOS */ if (SB_Peek (&Format) == '\0') { break; } /* Check for a format specifier */ if (SB_Peek (&Format) != '%') { /* No format specifier, just copy */ SB_AppendChar (&R, SB_Get (&Format)); continue; } SB_Skip (&Format); if (SB_Peek (&Format) == '%') { /* %% */ SB_AppendChar (&R, '%'); SB_Skip (&Format); continue; } if (SB_Peek (&Format) == '\0') { InvalidFormatString (); break; } /* Since a format specifier follows, we do expect anotehr argument for * the .sprintf function. */ ConsumeComma (); /* We will copy the format spec into F1 checking for the things we * support, and later use xsprintf to do the actual formatting. This * is easier than adding another printf implementation... */ SB_Clear (&F1); SB_AppendChar (&F1, '%'); /* Check for flags */ Done = 0; while ((C = SB_Peek (&Format)) != '\0' && !Done) { switch (C) { case '-': /* FALLTHROUGH */ case '+': /* FALLTHROUGH */ case ' ': /* FALLTHROUGH */ case '#': /* FALLTHROUGH */ case '0': SB_AppendChar (&F1, SB_Get (&Format)); break; default: Done = 1; break; } } /* We do only support a numerical width field */ while (IsDigit (SB_Peek (&Format))) { SB_AppendChar (&F1, SB_Get (&Format)); } /* Precision - only positive numerical fields supported */ if (SB_Peek (&Format) == '.') { SB_AppendChar (&F1, SB_Get (&Format)); while (IsDigit (SB_Peek (&Format))) { SB_AppendChar (&F1, SB_Get (&Format)); } } /* Length modifiers aren't supported, so read the conversion specs */ switch (SB_Peek (&Format)) { case 'd': case 'i': case 'o': case 'u': case 'X': case 'x': /* Our ints are actually longs, so we use the 'l' modifier when * calling xsprintf later. Terminate the format string. */ SB_AppendChar (&F1, 'l'); SB_AppendChar (&F1, SB_Get (&Format)); SB_Terminate (&F1); /* The argument must be a constant expression */ IVal = ConstExpression (); /* Format this argument according to the spec */ SB_Printf (&R1, SB_GetConstBuf (&F1), IVal); /* Append the formatted argument to the result */ SB_Append (&R, &R1); break; case 's': /* Add the format spec and terminate the format */ SB_AppendChar (&F1, SB_Get (&Format)); SB_Terminate (&F1); /* The argument must be a string constant */ if (!LookAtStrCon ()) { /* Make it one */ SB_CopyStr (&CurTok.SVal, "**undefined**"); } /* Format this argument according to the spec */ SB_Printf (&R1, SB_GetConstBuf (&F1), SB_GetConstBuf (&CurTok.SVal)); /* Skip the string constant */ NextTok (); /* Append the formatted argument to the result */ SB_Append (&R, &R1); break; case 'c': /* Add the format spec and terminate the format */ SB_AppendChar (&F1, SB_Get (&Format)); SB_Terminate (&F1); /* The argument must be a constant expression */ IVal = ConstExpression (); /* Check for a valid character range */ if (IVal <= 0 || IVal > 255) { Error ("Char argument out of range"); IVal = ' '; } /* Format this argument according to the spec. Be sure to pass * an int as the char value. */ SB_Printf (&R1, SB_GetConstBuf (&F1), (int) IVal); /* Append the formatted argument to the result */ SB_Append (&R, &R1); break; default: Error ("Invalid format string"); SB_Skip (&Format); break; } } /* Terminate the result string */ SB_Terminate (&R); /* We expect a closing parenthesis, but will not skip it but replace it * by the string token just created. */ if (CurTok.Tok != TOK_RPAREN) { Error ("`)' expected"); } else { CurTok.Tok = TOK_STRCON; SB_Copy (&CurTok.SVal, &R); SB_Terminate (&CurTok.SVal); } /* Delete the string buffers */ SB_Done (&Format); SB_Done (&R); SB_Done (&F1); SB_Done (&R1); } static void FuncString (void) /* Handle the .STRING function */ { StrBuf Buf = STATIC_STRBUF_INITIALIZER; /* Skip it */ NextTok (); /* Left paren expected */ ConsumeLParen (); /* Accept identifiers or numeric expressions */ if (CurTok.Tok == TOK_LOCAL_IDENT) { /* Save the identifier, then skip it */ SB_Copy (&Buf, &CurTok.SVal); NextTok (); } else if (CurTok.Tok == TOK_NAMESPACE || CurTok.Tok == TOK_IDENT) { /* Parse a fully qualified symbol name. We cannot use * ParseScopedSymName here since the name may be invalid. */ int NameSpace; do { NameSpace = (CurTok.Tok == TOK_NAMESPACE); if (NameSpace) { SB_AppendStr (&Buf, "::"); } else { SB_Append (&Buf, &CurTok.SVal); } NextTok (); } while ((NameSpace != 0 && CurTok.Tok == TOK_IDENT) || (NameSpace == 0 && CurTok.Tok == TOK_NAMESPACE)); } else { /* Numeric expression */ long Val = ConstExpression (); SB_Printf (&Buf, "%ld", Val); } /* We expect a closing parenthesis, but will not skip it but replace it * by the string token just created. */ if (CurTok.Tok != TOK_RPAREN) { Error ("`)' expected"); } else { CurTok.Tok = TOK_STRCON; SB_Copy (&CurTok.SVal, &Buf); SB_Terminate (&CurTok.SVal); } /* Free string memory */ SB_Done (&Buf); } void NextTok (void) /* Get next token and handle token level functions */ { /* Get the next raw token */ NextRawTok (); /* In raw mode, or when output is suppressed via conditional assembly, * pass the token unchanged. */ if (RawMode == 0 && IfCond) { /* Execute token handling functions */ switch (CurTok.Tok) { case TOK_CONCAT: FuncConcat (); break; case TOK_LEFT: FuncLeft (); break; case TOK_MAKEIDENT: FuncIdent (); break; case TOK_MID: FuncMid (); break; case TOK_RIGHT: FuncRight (); break; case TOK_SPRINTF: FuncSPrintF (); break; case TOK_STRING: FuncString (); break; default: /* Quiet down gcc */ break; } } } void Consume (token_t Expected, const char* ErrMsg) /* Consume Expected, print an error if we don't find it */ { if (CurTok.Tok == Expected) { NextTok (); } else { Error ("%s", ErrMsg); } } void ConsumeSep (void) /* Consume a separator token */ { /* We expect a separator token */ ExpectSep (); /* If we are at end of line, skip it */ if (CurTok.Tok == TOK_SEP) { NextTok (); } } void ConsumeLParen (void) /* Consume a left paren */ { Consume (TOK_LPAREN, "`(' expected"); } void ConsumeRParen (void) /* Consume a right paren */ { Consume (TOK_RPAREN, "`)' expected"); } void ConsumeComma (void) /* Consume a comma */ { Consume (TOK_COMMA, "`,' expected"); } void SkipUntilSep (void) /* Skip tokens until we reach a line separator or end of file */ { while (!TokIsSep (CurTok.Tok)) { NextTok (); } } void ExpectSep (void) /* Check if we've reached a line separator, and output an error if not. Do * not skip the line separator. */ { if (!TokIsSep (CurTok.Tok)) { ErrorSkip ("Unexpected trailing garbage characters"); } } void EnterRawTokenMode (void) /* Enter raw token mode. In raw mode, token handling functions are not * executed, but the function tokens are passed untouched to the upper * layer. Raw token mode is used when storing macro tokens for later * use. * Calls to EnterRawTokenMode and LeaveRawTokenMode may be nested. */ { ++RawMode; } void LeaveRawTokenMode (void) /* Leave raw token mode. */ { PRECONDITION (RawMode > 0); --RawMode; }
955
./cc65/src/ca65/macro.c
/*****************************************************************************/ /* */ /* macro.c */ /* */ /* Macros for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> /* common */ #include "check.h" #include "hashfunc.h" #include "hashtab.h" #include "xmalloc.h" /* ca65 */ #include "condasm.h" #include "error.h" #include "global.h" #include "instr.h" #include "istack.h" #include "lineinfo.h" #include "nexttok.h" #include "pseudo.h" #include "toklist.h" #include "macro.h" /*****************************************************************************/ /* Forwards */ /*****************************************************************************/ static unsigned HT_GenHash (const void* Key); /* Generate the hash over a key. */ static const void* HT_GetKey (const void* Entry); /* Given a pointer to the user entry data, return a pointer to the key */ static int HT_Compare (const void* Key1, const void* Key2); /* Compare two keys. The function must return a value less than zero if * Key1 is smaller than Key2, zero if both are equal, and a value greater * than zero if Key1 is greater then Key2. */ /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Struct that describes an identifer (macro param, local list) */ typedef struct IdDesc IdDesc; struct IdDesc { IdDesc* Next; /* Linked list */ StrBuf Id; /* Identifier, dynamically allocated */ }; /* Struct that describes a macro definition */ struct Macro { HashNode Node; /* Hash list node */ Macro* List; /* List of all macros */ unsigned LocalCount; /* Count of local symbols */ IdDesc* Locals; /* List of local symbols */ unsigned ParamCount; /* Parameter count of macro */ IdDesc* Params; /* Identifiers of macro parameters */ unsigned TokCount; /* Number of tokens for this macro */ TokNode* TokRoot; /* Root of token list */ TokNode* TokLast; /* Pointer to last token in list */ StrBuf Name; /* Macro name, dynamically allocated */ unsigned Expansions; /* Number of active macro expansions */ unsigned char Style; /* Macro style */ unsigned char Incomplete; /* Macro is currently built */ }; /* Hash table functions */ static const HashFunctions HashFunc = { HT_GenHash, HT_GetKey, HT_Compare }; /* Macro hash table */ static HashTable MacroTab = STATIC_HASHTABLE_INITIALIZER (117, &HashFunc); /* Structs that holds data for a macro expansion */ typedef struct MacExp MacExp; struct MacExp { MacExp* Next; /* Pointer to next expansion */ Macro* M; /* Which macro do we expand? */ unsigned IfSP; /* .IF stack pointer at start of expansion */ TokNode* Exp; /* Pointer to current token */ TokNode* Final; /* Pointer to final token */ unsigned MacExpansions; /* Number of active macro expansions */ unsigned LocalStart; /* Start of counter for local symbol names */ unsigned ParamCount; /* Number of actual parameters */ TokNode** Params; /* List of actual parameters */ TokNode* ParamExp; /* Node for expanding parameters */ LineInfo* LI; /* Line info for the expansion */ LineInfo* ParamLI; /* Line info for parameter expansion */ }; /* Maximum number of nested macro expansions */ #define MAX_MACEXPANSIONS 256U /* Number of active macro expansions */ static unsigned MacExpansions = 0; /* Flag if a macro expansion should get aborted */ static int DoMacAbort = 0; /* Counter to create local names for symbols */ static unsigned LocalName = 0; /* Define style macros disabled if != 0 */ static unsigned DisableDefines = 0; /*****************************************************************************/ /* Hash table functions */ /*****************************************************************************/ static unsigned HT_GenHash (const void* Key) /* Generate the hash over a key. */ { return HashBuf (Key); } static const void* HT_GetKey (const void* Entry) /* Given a pointer to the user entry data, return a pointer to the index */ { return &((Macro*) Entry)->Name; } static int HT_Compare (const void* Key1, const void* Key2) /* Compare two keys. The function must return a value less than zero if * Key1 is smaller than Key2, zero if both are equal, and a value greater * than zero if Key1 is greater then Key2. */ { return SB_Compare (Key1, Key2); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static IdDesc* NewIdDesc (const StrBuf* Id) /* Create a new IdDesc, initialize and return it */ { /* Allocate memory */ IdDesc* ID = xmalloc (sizeof (IdDesc)); /* Initialize the struct */ ID->Next = 0; SB_Init (&ID->Id); SB_Copy (&ID->Id, Id); /* Return the new struct */ return ID; } static void FreeIdDesc (IdDesc* ID) /* Free an IdDesc */ { /* Free the name */ SB_Done (&ID->Id); /* Free the structure itself */ xfree (ID); } static void FreeIdDescList (IdDesc* ID) /* Free a complete list of IdDesc structures */ { while (ID) { IdDesc* This = ID; ID = ID->Next; FreeIdDesc (This); } } static Macro* NewMacro (const StrBuf* Name, unsigned char Style) /* Generate a new macro entry, initialize and return it */ { /* Allocate memory */ Macro* M = xmalloc (sizeof (Macro)); /* Initialize the macro struct */ InitHashNode (&M->Node); M->LocalCount = 0; M->Locals = 0; M->ParamCount = 0; M->Params = 0; M->TokCount = 0; M->TokRoot = 0; M->TokLast = 0; SB_Init (&M->Name); SB_Copy (&M->Name, Name); M->Expansions = 0; M->Style = Style; M->Incomplete = 1; /* Insert the macro into the hash table */ HT_Insert (&MacroTab, &M->Node); /* Return the new macro struct */ return M; } static void FreeMacro (Macro* M) /* Free a macro entry which has already been removed from the macro table. */ { TokNode* T; /* Free locals */ FreeIdDescList (M->Locals); /* Free identifiers of parameters */ FreeIdDescList (M->Params); /* Free the token list for the macro */ while ((T = M->TokRoot) != 0) { M->TokRoot = T->Next; FreeTokNode (T); } /* Free the macro name */ SB_Done (&M->Name); /* Free the macro structure itself */ xfree (M); } static MacExp* NewMacExp (Macro* M) /* Create a new expansion structure for the given macro */ { unsigned I; /* Allocate memory */ MacExp* E = xmalloc (sizeof (MacExp)); /* Initialize the data */ E->M = M; E->IfSP = GetIfStack (); E->Exp = M->TokRoot; E->Final = 0; E->MacExpansions = ++MacExpansions; /* One macro expansion more */ E->LocalStart = LocalName; LocalName += M->LocalCount; E->ParamCount = 0; E->Params = xmalloc (M->ParamCount * sizeof (TokNode*)); for (I = 0; I < M->ParamCount; ++I) { E->Params[I] = 0; } E->ParamExp = 0; E->LI = 0; E->ParamLI = 0; /* Mark the macro as expanding */ ++M->Expansions; /* Return the new macro expansion */ return E; } static void FreeMacExp (MacExp* E) /* Remove and free the current macro expansion */ { unsigned I; /* One macro expansion less */ --MacExpansions; /* No longer expanding this macro */ --E->M->Expansions; /* Free the parameter lists */ for (I = 0; I < E->ParamCount; ++I) { /* Free one parameter list */ TokNode* N = E->Params[I]; while (N) { TokNode* P = N->Next; FreeTokNode (N); N = P; } } xfree (E->Params); /* Free the additional line info */ if (E->ParamLI) { EndLine (E->ParamLI); } if (E->LI) { EndLine (E->LI); } /* Free the final token if we have one */ if (E->Final) { FreeTokNode (E->Final); } /* Free the structure itself */ xfree (E); } static void MacSkipDef (unsigned Style) /* Skip a macro definition */ { if (Style == MAC_STYLE_CLASSIC) { /* Skip tokens until we reach the final .endmacro */ while (CurTok.Tok != TOK_ENDMACRO && CurTok.Tok != TOK_EOF) { NextTok (); } if (CurTok.Tok != TOK_EOF) { SkipUntilSep (); } else { Error ("`.ENDMACRO' expected"); } } else { /* Skip until end of line */ SkipUntilSep (); } } void MacDef (unsigned Style) /* Parse a macro definition */ { Macro* M; TokNode* N; int HaveParams; /* We expect a macro name here */ if (CurTok.Tok != TOK_IDENT) { Error ("Identifier expected"); MacSkipDef (Style); return; } else if (!UbiquitousIdents && FindInstruction (&CurTok.SVal) >= 0) { /* The identifier is a name of a 6502 instruction, which is not * allowed if not explicitly enabled. */ Error ("Cannot use an instruction as macro name"); MacSkipDef (Style); return; } /* Did we already define that macro? */ if (HT_Find (&MacroTab, &CurTok.SVal) != 0) { /* Macro is already defined */ Error ("A macro named `%m%p' is already defined", &CurTok.SVal); /* Skip tokens until we reach the final .endmacro */ MacSkipDef (Style); return; } /* Define the macro */ M = NewMacro (&CurTok.SVal, Style); /* Switch to raw token mode and skip the macro name */ EnterRawTokenMode (); NextTok (); /* If we have a DEFINE style macro, we may have parameters in braces, * otherwise we may have parameters without braces. */ if (Style == MAC_STYLE_CLASSIC) { HaveParams = 1; } else { if (CurTok.Tok == TOK_LPAREN) { HaveParams = 1; NextTok (); } else { HaveParams = 0; } } /* Parse the parameter list */ if (HaveParams) { while (CurTok.Tok == TOK_IDENT) { /* Create a struct holding the identifier */ IdDesc* I = NewIdDesc (&CurTok.SVal); /* Insert the struct into the list, checking for duplicate idents */ if (M->ParamCount == 0) { M->Params = I; } else { IdDesc* List = M->Params; while (1) { if (SB_Compare (&List->Id, &CurTok.SVal) == 0) { Error ("Duplicate symbol `%m%p'", &CurTok.SVal); } if (List->Next == 0) { break; } else { List = List->Next; } } List->Next = I; } ++M->ParamCount; /* Skip the name */ NextTok (); /* Maybe there are more params... */ if (CurTok.Tok == TOK_COMMA) { NextTok (); } else { break; } } } /* For class macros, we expect a separator token, for define style macros, * we expect the closing paren. */ if (Style == MAC_STYLE_CLASSIC) { ConsumeSep (); } else if (HaveParams) { ConsumeRParen (); } /* Preparse the macro body. We will read the tokens until we reach end of * file, or a .endmacro (or end of line for DEFINE style macros) and store * them into an token list internal to the macro. For classic macros, there * the .LOCAL command is detected and removed at this time. */ while (1) { /* Check for end of macro */ if (Style == MAC_STYLE_CLASSIC) { /* In classic macros, only .endmacro is allowed */ if (CurTok.Tok == TOK_ENDMACRO) { /* Done */ break; } /* May not have end of file in a macro definition */ if (CurTok.Tok == TOK_EOF) { Error ("`.ENDMACRO' expected"); goto Done; } } else { /* Accept a newline or end of file for new style macros */ if (TokIsSep (CurTok.Tok)) { break; } } /* Check for a .LOCAL declaration */ if (CurTok.Tok == TOK_LOCAL && Style == MAC_STYLE_CLASSIC) { while (1) { IdDesc* I; /* Skip .local or comma */ NextTok (); /* Need an identifer */ if (CurTok.Tok != TOK_IDENT && CurTok.Tok != TOK_LOCAL_IDENT) { Error ("Identifier expected"); SkipUntilSep (); break; } /* Put the identifier into the locals list and skip it */ I = NewIdDesc (&CurTok.SVal); I->Next = M->Locals; M->Locals = I; ++M->LocalCount; NextTok (); /* Check for end of list */ if (CurTok.Tok != TOK_COMMA) { break; } } /* We need end of line after the locals */ ConsumeSep (); continue; } /* Create a token node for the current token */ N = NewTokNode (); /* If the token is an identifier, check if it is a local parameter */ if (CurTok.Tok == TOK_IDENT) { unsigned Count = 0; IdDesc* I = M->Params; while (I) { if (SB_Compare (&I->Id, &CurTok.SVal) == 0) { /* Local param name, replace it */ N->T.Tok = TOK_MACPARAM; N->T.IVal = Count; break; } ++Count; I = I->Next; } } /* Insert the new token in the list */ if (M->TokCount == 0) { /* First token */ M->TokRoot = M->TokLast = N; } else { /* We have already tokens */ M->TokLast->Next = N; M->TokLast = N; } ++M->TokCount; /* Read the next token */ NextTok (); } /* Skip the .endmacro for a classic macro */ if (Style == MAC_STYLE_CLASSIC) { NextTok (); } /* Reset the Incomplete flag now that parsing is done */ M->Incomplete = 0; Done: /* Switch out of raw token mode */ LeaveRawTokenMode (); } void MacUndef (const StrBuf* Name, unsigned char Style) /* Undefine the macro with the given name and style. A style mismatch is * treated as if the macro didn't exist. */ { /* Search for the macro */ Macro* M = HT_Find (&MacroTab, Name); /* Don't let the user kid with us */ if (M == 0 || M->Style != Style) { Error ("No such macro: %m%p", Name); return; } if (M->Expansions > 0) { Error ("Cannot delete a macro that is currently expanded"); return; } /* Remove the macro from the macro table */ HT_Remove (&MacroTab, M); /* Free the macro structure */ FreeMacro (M); } static int MacExpand (void* Data) /* If we're currently expanding a macro, set the the scanner token and * attribute to the next value and return true. If we are not expanding * a macro, return false. */ { /* Cast the Data pointer to the actual data structure */ MacExp* Mac = (MacExp*) Data; /* Check if we should abort this macro */ if (DoMacAbort) { /* Reset the flag */ DoMacAbort = 0; /* Abort any open .IF statements in this macro expansion */ CleanupIfStack (Mac->IfSP); /* Terminate macro expansion */ goto MacEnd; } /* We're expanding a macro. Check if we are expanding one of the * macro parameters. */ ExpandParam: if (Mac->ParamExp) { /* Ok, use token from parameter list */ TokSet (Mac->ParamExp); /* Create new line info for this parameter token */ if (Mac->ParamLI) { EndLine (Mac->ParamLI); } Mac->ParamLI = StartLine (&CurTok.Pos, LI_TYPE_MACPARAM, Mac->MacExpansions); /* Set pointer to next token */ Mac->ParamExp = Mac->ParamExp->Next; /* Done */ return 1; } else if (Mac->ParamLI) { /* There's still line info open from the parameter expansion - end it */ EndLine (Mac->ParamLI); Mac->ParamLI = 0; } /* We're not expanding macro parameters. Check if we have tokens left from * the macro itself. */ if (Mac->Exp) { /* Use next macro token */ TokSet (Mac->Exp); /* Create new line info for this token */ if (Mac->LI) { EndLine (Mac->LI); } Mac->LI = StartLine (&CurTok.Pos, LI_TYPE_MACRO, Mac->MacExpansions); /* Set pointer to next token */ Mac->Exp = Mac->Exp->Next; /* Is it a request for actual parameter count? */ if (CurTok.Tok == TOK_PARAMCOUNT) { CurTok.Tok = TOK_INTCON; CurTok.IVal = Mac->ParamCount; return 1; } /* Is it the name of a macro parameter? */ if (CurTok.Tok == TOK_MACPARAM) { /* Start to expand the parameter token list */ Mac->ParamExp = Mac->Params[CurTok.IVal]; /* Go back and expand the parameter */ goto ExpandParam; } /* If it's an identifier, it may in fact be a local symbol */ if ((CurTok.Tok == TOK_IDENT || CurTok.Tok == TOK_LOCAL_IDENT) && Mac->M->LocalCount) { /* Search for the local symbol in the list */ unsigned Index = 0; IdDesc* I = Mac->M->Locals; while (I) { if (SB_Compare (&CurTok.SVal, &I->Id) == 0) { /* This is in fact a local symbol, change the name. Be sure * to generate a local label name if the original name was * a local label, and also generate a name that cannot be * generated by a user. */ if (SB_At (&I->Id, 0) == LocalStart) { /* Must generate a local symbol */ SB_Printf (&CurTok.SVal, "%cLOCAL-MACRO_SYMBOL-%04X", LocalStart, Mac->LocalStart + Index); } else { /* Global symbol */ SB_Printf (&CurTok.SVal, "LOCAL-MACRO_SYMBOL-%04X", Mac->LocalStart + Index); } break; } /* Next symbol */ ++Index; I = I->Next; } /* Done */ return 1; } /* The token was successfully set */ return 1; } /* No more macro tokens. Do we have a final token? */ if (Mac->Final) { /* Set the final token and remove it */ TokSet (Mac->Final); FreeTokNode (Mac->Final); Mac->Final = 0; /* Problem: When a .define style macro is expanded within the call * of a classic one, the latter may be terminated and removed while * the expansion of the .define style macro is still active. Because * line info slots are "stacked", this runs into a CHECK FAILED. For * now, we will fix that by removing the .define style macro expansion * immediately, once the final token is placed. The better solution * would probably be to not require AllocLineInfoSlot/FreeLineInfoSlot * to be called in FIFO order, but this is a bigger change. */ /* End of macro expansion and pop the input function */ FreeMacExp (Mac); PopInput (); /* The token was successfully set */ return 1; } MacEnd: /* End of macro expansion */ FreeMacExp (Mac); /* Pop the input function */ PopInput (); /* No token available */ return 0; } static void StartExpClassic (MacExp* E) /* Start expanding a classic macro */ { token_t Term; /* Skip the macro name */ NextTok (); /* Read the actual parameters */ while (!TokIsSep (CurTok.Tok)) { TokNode* Last; /* Check for maximum parameter count */ if (E->ParamCount >= E->M->ParamCount) { ErrorSkip ("Too many macro parameters"); break; } /* The macro may optionally be enclosed in curly braces */ Term = GetTokListTerm (TOK_COMMA); /* Read tokens for one parameter, accept empty params */ Last = 0; while (CurTok.Tok != Term && CurTok.Tok != TOK_SEP) { TokNode* T; /* Check for end of file */ if (CurTok.Tok == TOK_EOF) { Error ("Unexpected end of file"); FreeMacExp (E); return; } /* Get the next token in a node */ T = NewTokNode (); /* Insert it into the list */ if (Last == 0) { E->Params [E->ParamCount] = T; } else { Last->Next = T; } Last = T; /* And skip it... */ NextTok (); } /* One parameter more */ ++E->ParamCount; /* If the macro argument was enclosed in curly braces, end-of-line * is an error. Skip the closing curly brace. */ if (Term == TOK_RCURLY) { if (CurTok.Tok == TOK_SEP) { Error ("End of line encountered within macro argument"); break; } NextTok (); } /* Check for a comma */ if (CurTok.Tok == TOK_COMMA) { NextTok (); } else { break; } } /* We must be at end of line now, otherwise something is wrong */ ExpectSep (); /* Insert a new token input function */ PushInput (MacExpand, E, ".MACRO"); } static void StartExpDefine (MacExp* E) /* Start expanding a DEFINE style macro */ { /* A define style macro must be called with as many actual parameters * as there are formal ones. Get the parameter count. */ unsigned Count = E->M->ParamCount; /* Skip the current token */ NextTok (); /* Read the actual parameters */ while (Count--) { TokNode* Last; /* The macro may optionally be enclosed in curly braces */ token_t Term = GetTokListTerm (TOK_COMMA); /* Check if there is really a parameter */ if (TokIsSep (CurTok.Tok) || CurTok.Tok == Term) { ErrorSkip ("Macro parameter #%u is empty", E->ParamCount+1); FreeMacExp (E); return; } /* Read tokens for one parameter */ Last = 0; do { TokNode* T; /* Get the next token in a node */ T = NewTokNode (); /* Insert it into the list */ if (Last == 0) { E->Params [E->ParamCount] = T; } else { Last->Next = T; } Last = T; /* And skip it... */ NextTok (); } while (CurTok.Tok != Term && !TokIsSep (CurTok.Tok)); /* One parameter more */ ++E->ParamCount; /* If the macro argument was enclosed in curly braces, end-of-line * is an error. Skip the closing curly brace. */ if (Term == TOK_RCURLY) { if (TokIsSep (CurTok.Tok)) { Error ("End of line encountered within macro argument"); break; } NextTok (); } /* Check for a comma */ if (Count > 0) { if (CurTok.Tok == TOK_COMMA) { NextTok (); } else { Error ("`,' expected"); } } } /* Macro expansion will overwrite the current token. This is a problem * for define style macros since these are called from the scanner level. * To avoid it, remember the current token and re-insert it, once macro * expansion is done. */ E->Final = NewTokNode (); /* Insert a new token input function */ PushInput (MacExpand, E, ".DEFINE"); } void MacExpandStart (Macro* M) /* Start expanding a macro */ { MacExp* E; /* Check the argument */ PRECONDITION (M && (M->Style != MAC_STYLE_DEFINE || DisableDefines == 0)); /* We cannot expand an incomplete macro */ if (M->Incomplete) { Error ("Cannot expand an incomplete macro"); return; } /* Don't allow too many nested macro expansions - otherwise it is possible * to force an endless loop and assembler crash. */ if (MacExpansions >= MAX_MACEXPANSIONS) { Error ("Too many nested macro expansions"); return; } /* Create a structure holding expansion data */ E = NewMacExp (M); /* Call the apropriate subroutine */ switch (M->Style) { case MAC_STYLE_CLASSIC: StartExpClassic (E); break; case MAC_STYLE_DEFINE: StartExpDefine (E); break; default: Internal ("Invalid macro style: %d", M->Style); } } void MacAbort (void) /* Abort the current macro expansion */ { /* Must have an expansion */ CHECK (MacExpansions > 0); /* Set a flag so macro expansion will terminate on the next call */ DoMacAbort = 1; } Macro* FindMacro (const StrBuf* Name) /* Try to find the macro with the given name and return it. If no macro with * this name was found, return NULL. */ { Macro* M = HT_Find (&MacroTab, Name); return (M != 0 && M->Style == MAC_STYLE_CLASSIC)? M : 0; } Macro* FindDefine (const StrBuf* Name) /* Try to find the define style macro with the given name and return it. If no * such macro was found, return NULL. */ { Macro* M; /* Never if disabled */ if (DisableDefines) { return 0; } /* Check if we have such a macro */ M = HT_Find (&MacroTab, Name); return (M != 0 && M->Style == MAC_STYLE_DEFINE)? M : 0; } int InMacExpansion (void) /* Return true if we're currently expanding a macro */ { return (MacExpansions > 0); } void DisableDefineStyleMacros (void) /* Disable define style macros until EnableDefineStyleMacros is called */ { ++DisableDefines; } void EnableDefineStyleMacros (void) /* Re-enable define style macros previously disabled with * DisableDefineStyleMacros. */ { PRECONDITION (DisableDefines > 0); --DisableDefines; }
956
./cc65/src/ca65/symbol.c
/*****************************************************************************/ /* */ /* symbol.c */ /* */ /* Parse a symbol name and search for it */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "strbuf.h" /* ca65 */ #include "error.h" #include "nexttok.h" #include "scanner.h" #include "symbol.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ SymTable* ParseScopedIdent (StrBuf* Name, StrBuf* FullName) /* Parse a (possibly scoped) identifer. The scope of the name must exist and * is returned as function result, while the last part (the identifier) which * may be either a symbol or a scope depending on the context is returned in * Name. FullName is a string buffer that is used to store the full name of * the identifier including the scope. It is used internally and may be used * by the caller for error messages or similar. */ { SymTable* Scope; /* Clear both passed string buffers */ SB_Clear (Name); SB_Clear (FullName); /* Get the starting table */ if (CurTok.Tok == TOK_NAMESPACE) { /* Start from the root scope */ Scope = RootScope; } else if (CurTok.Tok == TOK_IDENT) { /* Remember the name and skip it */ SB_Copy (Name, &CurTok.SVal); NextTok (); /* If no namespace symbol follows, we're already done */ if (CurTok.Tok != TOK_NAMESPACE) { SB_Terminate (FullName); return CurrentScope; } /* Pass the scope back to the caller */ SB_Append (FullName, Name); /* The scope must exist, so search for it starting with the current * scope. */ Scope = SymFindAnyScope (CurrentScope, Name); if (Scope == 0) { /* Scope not found */ SB_Terminate (FullName); Error ("No such scope: `%m%p'", FullName); return 0; } } else { /* Invalid token */ Error ("Identifier expected"); return 0; } /* Skip the namespace token that follows */ SB_AppendStr (FullName, "::"); NextTok (); /* Resolve scopes. */ while (1) { /* Next token must be an identifier. */ if (CurTok.Tok != TOK_IDENT) { Error ("Identifier expected"); return 0; } /* Remember and skip the identifier */ SB_Copy (Name, &CurTok.SVal); NextTok (); /* If a namespace token follows, we search for another scope, otherwise * the name is a symbol and we're done. */ if (CurTok.Tok != TOK_NAMESPACE) { /* Symbol */ return Scope; } /* Pass the scope back to the caller */ SB_Append (FullName, Name); /* Search for the child scope */ Scope = SymFindScope (Scope, Name, SYM_FIND_EXISTING); if (Scope == 0) { /* Scope not found */ Error ("No such scope: `%m%p'", FullName); return 0; } /* Skip the namespace token that follows */ SB_AppendStr (FullName, "::"); NextTok (); } } SymEntry* ParseScopedSymName (SymFindAction Action) /* Parse a (possibly scoped) symbol name, search for it in the symbol table * and return the symbol table entry. */ { StrBuf ScopeName = STATIC_STRBUF_INITIALIZER; StrBuf Ident = STATIC_STRBUF_INITIALIZER; int NoScope; SymEntry* Sym; /* Parse the scoped symbol name */ SymTable* Scope = ParseScopedIdent (&Ident, &ScopeName); /* If ScopeName is empty, no scope was specified */ NoScope = SB_IsEmpty (&ScopeName); /* We don't need ScopeName any longer */ SB_Done (&ScopeName); /* Check if the scope is valid. Errors have already been diagnosed by * the routine, so just exit. */ if (Scope) { /* Search for the symbol and return it. If no scope was specified, * search also in the upper levels. */ if (NoScope && (Action & SYM_ALLOC_NEW) == 0) { Sym = SymFindAny (Scope, &Ident); } else { Sym = SymFind (Scope, &Ident, Action); } } else { /* No scope ==> no symbol. To avoid errors in the calling routine that * may not expect NULL to be returned if Action contains SYM_ALLOC_NEW, * create a new symbol. */ if (Action & SYM_ALLOC_NEW) { Sym = NewSymEntry (&Ident, SF_NONE); } else { Sym = 0; } } /* Deallocate memory for ident */ SB_Done (&Ident); /* Return the symbol found */ return Sym; } SymTable* ParseScopedSymTable (void) /* Parse a (possibly scoped) symbol table (scope) name, search for it in the * symbol space and return the symbol table struct. */ { StrBuf ScopeName = STATIC_STRBUF_INITIALIZER; StrBuf Name = STATIC_STRBUF_INITIALIZER; int NoScope; /* Parse the scoped symbol name */ SymTable* Scope = ParseScopedIdent (&Name, &ScopeName); /* If ScopeName is empty, no scope was specified */ NoScope = SB_IsEmpty (&ScopeName); /* We don't need FullName any longer */ SB_Done (&ScopeName); /* If we got no error, search for the child scope withint the enclosing one. * Beware: If no explicit parent scope was specified, search in all upper * levels. */ if (Scope) { /* Search for the last scope */ if (NoScope) { Scope = SymFindAnyScope (Scope, &Name); } else { Scope = SymFindScope (Scope, &Name, SYM_FIND_EXISTING); } } /* Free memory for name */ SB_Done (&Name); /* Return the scope found */ return Scope; } SymEntry* ParseAnySymName (SymFindAction Action) /* Parse a cheap local symbol or a a (possibly scoped) symbol name, search * for it in the symbol table and return the symbol table entry. */ { SymEntry* Sym; /* Distinguish cheap locals and other symbols */ if (CurTok.Tok == TOK_LOCAL_IDENT) { Sym = SymFindLocal (SymLast, &CurTok.SVal, Action); NextTok (); } else { Sym = ParseScopedSymName (Action); } /* Return the symbol found */ return Sym; }
957
./cc65/src/ca65/objfile.c
/*****************************************************************************/ /* */ /* objfile.c */ /* */ /* Object file writing routines for the ca65 macroassembler */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> /* common */ #include "fname.h" #include "objdefs.h" /* ca65 */ #include "global.h" #include "error.h" #include "objfile.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* File descriptor */ static FILE* F = 0; /* Default extension */ #define OBJ_EXT ".o" /* Header structure */ static ObjHeader Header = { OBJ_MAGIC, /* 32: Magic number */ OBJ_VERSION, /* 16: Version number */ 0, /* 16: flags */ 0, /* 32: Offset to option table */ 0, /* 32: Size of options */ 0, /* 32: Offset to file table */ 0, /* 32: Size of files */ 0, /* 32: Offset to segment table */ 0, /* 32: Size of segment table */ 0, /* 32: Offset to import list */ 0, /* 32: Size of import list */ 0, /* 32: Offset to export list */ 0, /* 32: Size of export list */ 0, /* 32: Offset to list of debug symbols */ 0, /* 32: Size of debug symbols */ 0, /* 32: Offset to list of line infos */ 0, /* 32: Size of line infos */ 0, /* 32: Offset to string pool */ 0, /* 32: Size of string pool */ 0, /* 32: Offset to assertion table */ 0, /* 32: Size of assertion table */ 0, /* 32: Offset into scope table */ 0, /* 32: Size of scope table */ 0, /* 32: Offset into span table */ 0, /* 32: Size of span table */ }; /*****************************************************************************/ /* Internally used functions */ /*****************************************************************************/ static void ObjWriteError (void) /* Called on a write error. Will try to close and remove the file, then * print a fatal error. */ { /* Remember the error */ int Error = errno; /* Force a close of the file, ignoring errors */ fclose (F); /* Try to remove the file, also ignoring errors */ remove (OutFile); /* Now abort with a fatal error */ Fatal ("Cannot write to output file `%s': %s", OutFile, strerror (Error)); } static void ObjWriteHeader (void) /* Write the object file header to the current file position */ { ObjWrite32 (Header.Magic); ObjWrite16 (Header.Version); ObjWrite16 (Header.Flags); ObjWrite32 (Header.OptionOffs); ObjWrite32 (Header.OptionSize); ObjWrite32 (Header.FileOffs); ObjWrite32 (Header.FileSize); ObjWrite32 (Header.SegOffs); ObjWrite32 (Header.SegSize); ObjWrite32 (Header.ImportOffs); ObjWrite32 (Header.ImportSize); ObjWrite32 (Header.ExportOffs); ObjWrite32 (Header.ExportSize); ObjWrite32 (Header.DbgSymOffs); ObjWrite32 (Header.DbgSymSize); ObjWrite32 (Header.LineInfoOffs); ObjWrite32 (Header.LineInfoSize); ObjWrite32 (Header.StrPoolOffs); ObjWrite32 (Header.StrPoolSize); ObjWrite32 (Header.AssertOffs); ObjWrite32 (Header.AssertSize); ObjWrite32 (Header.ScopeOffs); ObjWrite32 (Header.ScopeSize); ObjWrite32 (Header.SpanOffs); ObjWrite32 (Header.SpanSize); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ void ObjOpen (void) /* Open the object file for writing, write a dummy header */ { /* Do we have a name for the output file? */ if (OutFile == 0) { /* We don't have an output name explicitly given, construct one from * the name of the input file. */ OutFile = MakeFilename (InFile, OBJ_EXT); } /* Create the output file */ F = fopen (OutFile, "w+b"); if (F == 0) { Fatal ("Cannot open output file `%s': %s", OutFile, strerror (errno)); } /* Write a dummy header */ ObjWriteHeader (); } void ObjClose (void) /* Write an update header and close the object file. */ { /* Go back to the beginning */ if (fseek (F, 0, SEEK_SET) != 0) { ObjWriteError (); } /* If we have debug infos, set the flag in the header */ if (DbgSyms) { Header.Flags |= OBJ_FLAGS_DBGINFO; } /* Write the updated header */ ObjWriteHeader (); /* Close the file */ if (fclose (F) != 0) { ObjWriteError (); } } unsigned long ObjGetFilePos (void) /* Get the current file position */ { long Pos = ftell (F); if (Pos < 0) { ObjWriteError (); } return Pos; } void ObjSetFilePos (unsigned long Pos) /* Set the file position */ { if (fseek (F, Pos, SEEK_SET) != 0) { ObjWriteError (); } } void ObjWrite8 (unsigned V) /* Write an 8 bit value to the file */ { if (putc (V, F) == EOF) { ObjWriteError (); } } void ObjWrite16 (unsigned V) /* Write a 16 bit value to the file */ { ObjWrite8 (V); ObjWrite8 (V >> 8); } void ObjWrite24 (unsigned long V) /* Write a 24 bit value to the file */ { ObjWrite8 (V); ObjWrite8 (V >> 8); ObjWrite8 (V >> 16); } void ObjWrite32 (unsigned long V) /* Write a 32 bit value to the file */ { ObjWrite8 (V); ObjWrite8 (V >> 8); ObjWrite8 (V >> 16); ObjWrite8 (V >> 24); } void ObjWriteVar (unsigned long V) /* Write a variable sized value to the file in special encoding */ { /* We will write the value to the file in 7 bit chunks. If the 8th bit * is clear, we're done, if it is set, another chunk follows. This will * allow us to encode smaller values with less bytes, at the expense of * needing 5 bytes if a 32 bit value is written to file. */ do { unsigned char C = (V & 0x7F); V >>= 7; if (V) { C |= 0x80; } ObjWrite8 (C); } while (V != 0); } void ObjWriteStr (const char* S) /* Write a string to the object file */ { unsigned Len = strlen (S); /* Write the string with the length preceeded (this is easier for * the reading routine than the C format since the length is known in * advance). */ ObjWriteVar (Len); ObjWriteData (S, Len); } void ObjWriteBuf (const StrBuf* S) /* Write a string to the object file */ { /* Write the string with the length preceeded (this is easier for * the reading routine than the C format since the length is known in * advance). */ ObjWriteVar (SB_GetLen (S)); ObjWriteData (SB_GetConstBuf (S), SB_GetLen (S)); } void ObjWriteData (const void* Data, unsigned Size) /* Write literal data to the file */ { if (fwrite (Data, 1, Size, F) != Size) { ObjWriteError (); } } void ObjWritePos (const FilePos* Pos) /* Write a file position to the object file */ { /* Write the data entries */ ObjWriteVar (Pos->Line); ObjWriteVar (Pos->Col); if (Pos->Name == 0) { /* Position is outside file scope, use the main file instead */ ObjWriteVar (0); } else { ObjWriteVar (Pos->Name - 1); } } void ObjStartOptions (void) /* Mark the start of the option section */ { Header.OptionOffs = ftell (F); } void ObjEndOptions (void) /* Mark the end of the option section */ { Header.OptionSize = ftell (F) - Header.OptionOffs; } void ObjStartFiles (void) /* Mark the start of the files section */ { Header.FileOffs = ftell (F); } void ObjEndFiles (void) /* Mark the end of the files section */ { Header.FileSize = ftell (F) - Header.FileOffs; } void ObjStartSegments (void) /* Mark the start of the segment section */ { Header.SegOffs = ftell (F); } void ObjEndSegments (void) /* Mark the end of the segment section */ { Header.SegSize = ftell (F) - Header.SegOffs; } void ObjStartImports (void) /* Mark the start of the import section */ { Header.ImportOffs = ftell (F); } void ObjEndImports (void) /* Mark the end of the import section */ { Header.ImportSize = ftell (F) - Header.ImportOffs; } void ObjStartExports (void) /* Mark the start of the export section */ { Header.ExportOffs = ftell (F); } void ObjEndExports (void) /* Mark the end of the export section */ { Header.ExportSize = ftell (F) - Header.ExportOffs; } void ObjStartDbgSyms (void) /* Mark the start of the debug symbol section */ { Header.DbgSymOffs = ftell (F); } void ObjEndDbgSyms (void) /* Mark the end of the debug symbol section */ { Header.DbgSymSize = ftell (F) - Header.DbgSymOffs; } void ObjStartLineInfos (void) /* Mark the start of the line info section */ { Header.LineInfoOffs = ftell (F); } void ObjEndLineInfos (void) /* Mark the end of the line info section */ { Header.LineInfoSize = ftell (F) - Header.LineInfoOffs; } void ObjStartStrPool (void) /* Mark the start of the string pool section */ { Header.StrPoolOffs = ftell (F); } void ObjEndStrPool (void) /* Mark the end of the string pool section */ { Header.StrPoolSize = ftell (F) - Header.StrPoolOffs; } void ObjStartAssertions (void) /* Mark the start of the assertion table */ { Header.AssertOffs = ftell (F); } void ObjEndAssertions (void) /* Mark the end of the assertion table */ { Header.AssertSize = ftell (F) - Header.AssertOffs; } void ObjStartScopes (void) /* Mark the start of the scope table */ { Header.ScopeOffs = ftell (F); } void ObjEndScopes (void) /* Mark the end of the scope table */ { Header.ScopeSize = ftell (F) - Header.ScopeOffs; } void ObjStartSpans (void) /* Mark the start of the span table */ { Header.SpanOffs = ftell (F); } void ObjEndSpans (void) /* Mark the end of the span table */ { Header.SpanSize = ftell (F) - Header.SpanOffs; }
958
./cc65/src/ca65/dbginfo.c
/*****************************************************************************/ /* */ /* dbginfo.c */ /* */ /* Handle the .dbg commands */ /* */ /* */ /* */ /* (C) 2000-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "chartype.h" #include "coll.h" #include "filepos.h" #include "hlldbgsym.h" #include "scopedefs.h" #include "strbuf.h" /* ca65 */ #include "dbginfo.h" #include "error.h" #include "expr.h" #include "filetab.h" #include "global.h" #include "lineinfo.h" #include "objfile.h" #include "nexttok.h" #include "symentry.h" #include "symtab.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Structure used for a high level language function or symbol */ typedef struct HLLDbgSym HLLDbgSym; struct HLLDbgSym { unsigned Flags; /* See above */ unsigned Name; /* String id of name */ unsigned AsmName; /* String id of asm symbol name */ SymEntry* Sym; /* The assembler symbol */ int Offs; /* Offset if any */ unsigned Type; /* String id of type */ SymTable* Scope; /* Parent scope */ unsigned FuncId; /* Id of hll function if any */ FilePos Pos; /* Position of statement */ }; /* The current line info */ static LineInfo* CurLineInfo = 0; /* List of high level language debug symbols */ static Collection HLLDbgSyms = STATIC_COLLECTION_INITIALIZER; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static HLLDbgSym* NewHLLDbgSym (unsigned Flags, unsigned Name, unsigned Type) /* Allocate and return a new HLLDbgSym structure */ { /* Allocate memory */ HLLDbgSym* S = xmalloc (sizeof (*S)); /* Initialize the fields as necessary */ S->Flags = Flags; S->Name = Name; S->AsmName = EMPTY_STRING_ID; S->Sym = 0; S->Offs = 0; S->Type = Type; S->Scope = CurrentScope; S->FuncId = ~0U; S->Pos = CurTok.Pos; /* Return the result */ return S; } static unsigned HexValue (char C) /* Convert the ascii representation of a hex nibble into the hex nibble */ { if (isdigit (C)) { return C - '0'; } else if (islower (C)) { return C - 'a' + 10; } else { return C - 'A' + 10; } } static int ValidateType (StrBuf* Type) /* Check if the given type is valid and if so, return a string id for it. If * the type isn't valid, return -1. Type is overwritten when checking. */ { unsigned I; const char* A; char* B; /* The length must not be zero and divideable by two */ unsigned Length = SB_GetLen (Type); if (Length < 2 || (Length & 0x01) != 0) { ErrorSkip ("Type value has invalid length"); return -1; } /* The string must consist completely of hex digit chars */ A = SB_GetConstBuf (Type); for (I = 0; I < Length; ++I) { if (!IsXDigit (A[I])) { ErrorSkip ("Type value contains invalid characters"); return -1; } } /* Convert the type to binary */ B = SB_GetBuf (Type); while (A < SB_GetConstBuf (Type) + Length) { /* Since we know, there are only hex digits, there can't be any errors */ *B++ = (HexValue (A[0]) << 4) | HexValue (A[1]); A += 2; } Type->Len = (Length /= 2); /* Allocate the type and return it */ return GetStrBufId (Type); } void DbgInfoFile (void) /* Parse and handle FILE subcommand of the .dbg pseudo instruction */ { StrBuf Name = STATIC_STRBUF_INITIALIZER; unsigned long Size; unsigned long MTime; /* Parameters are separated by a comma */ ConsumeComma (); /* Name */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); return; } SB_Copy (&Name, &CurTok.SVal); NextTok (); /* Comma expected */ ConsumeComma (); /* Size */ Size = ConstExpression (); /* Comma expected */ ConsumeComma (); /* MTime */ MTime = ConstExpression (); /* Insert the file into the table */ AddFile (&Name, FT_DBGINFO, Size, MTime); /* Free memory used for Name */ SB_Done (&Name); } void DbgInfoFunc (void) /* Parse and handle func subcommand of the .dbg pseudo instruction */ { static const char* StorageKeys[] = { "EXTERN", "STATIC", }; unsigned Name; int Type; unsigned AsmName; unsigned Flags; HLLDbgSym* S; /* Parameters are separated by a comma */ ConsumeComma (); /* Name */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); return; } Name = GetStrBufId (&CurTok.SVal); NextTok (); /* Comma expected */ ConsumeComma (); /* Type */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); return; } Type = ValidateType (&CurTok.SVal); if (Type < 0) { return; } NextTok (); /* Comma expected */ ConsumeComma (); /* The storage class follows */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Storage class specifier expected"); return; } switch (GetSubKey (StorageKeys, sizeof (StorageKeys)/sizeof (StorageKeys[0]))) { case 0: Flags = HLL_TYPE_FUNC | HLL_SC_EXTERN; break; case 1: Flags = HLL_TYPE_FUNC | HLL_SC_STATIC; break; default: ErrorSkip ("Storage class specifier expected"); return; } NextTok (); /* Comma expected */ ConsumeComma (); /* Assembler name follows */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); return; } AsmName = GetStrBufId (&CurTok.SVal); NextTok (); /* There may only be one function per scope */ if (CurrentScope == RootScope) { ErrorSkip ("Functions may not be used in the root scope"); return; } else if (CurrentScope->Type != SCOPE_SCOPE || CurrentScope->Label == 0) { ErrorSkip ("Functions can only be tagged to .PROC scopes"); return; } else if (CurrentScope->Label->HLLSym != 0) { ErrorSkip ("Only one HLL symbol per asm symbol is allowed"); return; } else if (CurrentScope->Label->Name != AsmName) { ErrorSkip ("Scope label and asm name for function must match"); return; } /* Add the function */ S = NewHLLDbgSym (Flags, Name, Type); S->Sym = CurrentScope->Label; CurrentScope->Label->HLLSym = S; CollAppend (&HLLDbgSyms, S); } void DbgInfoLine (void) /* Parse and handle LINE subcommand of the .dbg pseudo instruction */ { long Line; FilePos Pos = STATIC_FILEPOS_INITIALIZER; /* Any new line info terminates the last one */ if (CurLineInfo) { EndLine (CurLineInfo); CurLineInfo = 0; } /* If a parameters follow, this is actual line info. If no parameters * follow, the last line info is terminated. */ if (CurTok.Tok == TOK_SEP) { return; } /* Parameters are separated by a comma */ ConsumeComma (); /* The name of the file follows */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); return; } /* Get the index in the file table for the name */ Pos.Name = GetFileIndex (&CurTok.SVal); /* Skip the name */ NextTok (); /* Comma expected */ ConsumeComma (); /* Line number */ Line = ConstExpression (); if (Line < 0) { ErrorSkip ("Line number is out of valid range"); return; } Pos.Line = Line; /* Generate a new external line info */ CurLineInfo = StartLine (&Pos, LI_TYPE_EXT, 0); } void DbgInfoSym (void) /* Parse and handle SYM subcommand of the .dbg pseudo instruction */ { static const char* StorageKeys[] = { "AUTO", "EXTERN", "REGISTER", "STATIC", }; unsigned Name; int Type; unsigned AsmName = EMPTY_STRING_ID; unsigned Flags; int Offs = 0; HLLDbgSym* S; /* Parameters are separated by a comma */ ConsumeComma (); /* Name */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); return; } Name = GetStrBufId (&CurTok.SVal); NextTok (); /* Comma expected */ ConsumeComma (); /* Type */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); return; } Type = ValidateType (&CurTok.SVal); if (Type < 0) { return; } NextTok (); /* Comma expected */ ConsumeComma (); /* The storage class follows */ if (CurTok.Tok != TOK_IDENT) { ErrorSkip ("Storage class specifier expected"); return; } switch (GetSubKey (StorageKeys, sizeof (StorageKeys)/sizeof (StorageKeys[0]))) { case 0: Flags = HLL_SC_AUTO; break; case 1: Flags = HLL_SC_EXTERN; break; case 2: Flags = HLL_SC_REG; break; case 3: Flags = HLL_SC_STATIC; break; default: ErrorSkip ("Storage class specifier expected"); return; } /* Skip the storage class token and the following comma */ NextTok (); ConsumeComma (); /* The next tokens depend on the storage class */ if (Flags == HLL_SC_AUTO) { /* Auto: Stack offset follows */ Offs = ConstExpression (); } else { /* Register, extern or static: Assembler name follows */ if (CurTok.Tok != TOK_STRCON) { ErrorSkip ("String constant expected"); return; } AsmName = GetStrBufId (&CurTok.SVal); NextTok (); /* For register, an offset follows */ if (Flags == HLL_SC_REG) { ConsumeComma (); Offs = ConstExpression (); } } /* Add the function */ S = NewHLLDbgSym (Flags | HLL_TYPE_SYM, Name, Type); S->AsmName = AsmName; S->Offs = Offs; CollAppend (&HLLDbgSyms, S); } void DbgInfoCheck (void) /* Do checks on all hll debug info symbols when assembly is complete */ { /* When parsing the debug statements for HLL symbols, we have already * tagged the functions to their asm counterparts. This wasn't done for * C symbols, since we will allow forward declarations. So we have to * resolve the normal C symbols now. */ unsigned I; for (I = 0; I < CollCount (&HLLDbgSyms); ++I) { /* Get the next symbol */ HLLDbgSym* S = CollAtUnchecked (&HLLDbgSyms, I); /* Ignore functions and auto symbols, because the later live on the * stack and don't have corresponding asm symbols. */ if (HLL_IS_FUNC (S->Flags) || HLL_GET_SC (S->Flags) == HLL_SC_AUTO) { continue; } /* Safety */ CHECK (S->Sym == 0 && S->Scope != 0); /* Search for the symbol name */ S->Sym = SymFindAny (S->Scope, GetStrBuf (S->AsmName)); if (S->Sym == 0) { PError (&S->Pos, "Assembler symbol `%s' not found", GetString (S->AsmName)); } else { /* Set the backlink */ S->Sym->HLLSym = S; } } } void WriteHLLDbgSyms (void) /* Write a list of all high level language symbols to the object file. */ { unsigned I; /* Only if debug info is enabled */ if (DbgSyms) { /* Write the symbol count to the list */ ObjWriteVar (CollCount (&HLLDbgSyms)); /* Walk through list and write all symbols to the file. */ for (I = 0; I < CollCount (&HLLDbgSyms); ++I) { /* Get the next symbol */ HLLDbgSym* S = CollAtUnchecked (&HLLDbgSyms, I); /* Get the type of the symbol */ unsigned SC = HLL_GET_SC (S->Flags); /* Remember if the symbol has debug info attached * ### This should go into DbgInfoCheck */ if (S->Sym && S->Sym->DebugSymId != ~0U) { S->Flags |= HLL_DATA_SYM; } /* Write the symbol data */ ObjWriteVar (S->Flags); ObjWriteVar (S->Name); if (HLL_HAS_SYM (S->Flags)) { ObjWriteVar (S->Sym->DebugSymId); } if (SC == HLL_SC_AUTO || SC == HLL_SC_REG) { ObjWriteVar (S->Offs); } ObjWriteVar (S->Type); ObjWriteVar (S->Scope->Id); } } else { /* Write a count of zero */ ObjWriteVar (0); } }
959
./cc65/src/ca65/asserts.c
/*****************************************************************************/ /* */ /* asserts.c */ /* */ /* Linker assertions for the ca65 crossassembler */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "coll.h" #include "xmalloc.h" /* ca65 */ #include "asserts.h" #include "error.h" #include "expr.h" #include "lineinfo.h" #include "objfile.h" #include "spool.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* An assertion entry */ typedef struct Assertion Assertion; struct Assertion { ExprNode* Expr; /* Expression to evaluate */ AssertAction Action; /* Action to take */ unsigned Msg; /* Message to print (if any) */ Collection LI; /* Line infos for the assertion */ }; /* Collection with all assertions for a module */ static Collection Assertions = STATIC_COLLECTION_INITIALIZER; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static Assertion* NewAssertion (ExprNode* Expr, AssertAction Action, unsigned Msg) /* Create a new Assertion struct and return it */ { /* Allocate memory */ Assertion* A = xmalloc (sizeof (Assertion)); /* Initialize the fields */ A->Expr = Expr; A->Action = Action; A->Msg = Msg; A->LI = EmptyCollection; GetFullLineInfo (&A->LI); /* Return the new struct */ return A; } void AddAssertion (ExprNode* Expr, AssertAction Action, unsigned Msg) /* Add an assertion to the assertion table */ { /* Add an assertion object to the table */ CollAppend (&Assertions, NewAssertion (Expr, Action, Msg)); } void CheckAssertions (void) /* Check all assertions and evaluate the ones we can evaluate here. */ { unsigned I; /* Get the number of assertions */ unsigned Count = CollCount (&Assertions); /* Check the assertions */ for (I = 0; I < Count; ++I) { long Val; /* Get the next assertion */ Assertion* A = CollAtUnchecked (&Assertions, I); /* Ignore it, if it should only be evaluated by the linker */ if (!AssertAtAsmTime (A->Action)) { continue; } /* Can we evaluate the expression? */ if (IsConstExpr (A->Expr, &Val) && Val == 0) { /* Apply the action */ const char* Msg = GetString (A->Msg); switch (A->Action) { case ASSERT_ACT_WARN: LIWarning (&A->LI, 0, "%s", Msg); break; case ASSERT_ACT_ERROR: LIError (&A->LI, "%s", Msg); break; default: Internal ("Illegal assert action specifier"); break; } } } } void WriteAssertions (void) /* Write the assertion table to the object file */ { unsigned I; /* Get the number of assertions */ unsigned Count = CollCount (&Assertions); /* Tell the object file module that we're about to start the assertions */ ObjStartAssertions (); /* Write the string count to the list */ ObjWriteVar (Count); /* Write the assertions */ for (I = 0; I < Count; ++I) { /* Get the next assertion */ Assertion* A = CollAtUnchecked (&Assertions, I); /* Write it to the file */ WriteExpr (A->Expr); ObjWriteVar ((unsigned) A->Action); ObjWriteVar (A->Msg); WriteLineInfo (&A->LI); } /* Done writing the assertions */ ObjEndAssertions (); }
960
./cc65/src/co65/convert.c
/*****************************************************************************/ /* */ /* convert.c */ /* */ /* Actual conversion routines for the co65 object file converter */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <errno.h> /* common */ #include "debugflag.h" #include "print.h" #include "version.h" #include "xmalloc.h" #include "xsprintf.h" /* co65 */ #include "error.h" #include "global.h" #include "model.h" #include "o65.h" #include "convert.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void PrintO65Stats (const O65Data* D) /* Print information about the O65 file if --verbose is given */ { Print (stdout, 1, "Size of text segment: %5lu\n", D->Header.tlen); Print (stdout, 1, "Size of data segment: %5lu\n", D->Header.dlen); Print (stdout, 1, "Size of bss segment: %5lu\n", D->Header.blen); Print (stdout, 1, "Size of zeropage segment: %5lu\n", D->Header.zlen); Print (stdout, 1, "Number of imports: %5u\n", CollCount (&D->Imports)); Print (stdout, 1, "Number of exports: %5u\n", CollCount (&D->Exports)); Print (stdout, 1, "Number of text segment relocations: %5u\n", CollCount (&D->TextReloc)); Print (stdout, 1, "Number of data segment relocations: %5u\n", CollCount (&D->DataReloc)); } static void SetupSegLabels (FILE* F) /* Setup the segment label names */ { if (BssLabel) { fprintf (F, ".export\t\t%s\n", BssLabel); } else { BssLabel = xstrdup ("BSS"); } if (CodeLabel) { fprintf (F, ".export\t\t%s\n", CodeLabel); } else { CodeLabel = xstrdup ("CODE"); } if (DataLabel) { fprintf (F, ".export\t\t%s\n", DataLabel); } else { DataLabel = xstrdup ("DATA"); } if (ZeropageLabel) { fprintf (F, ".export\t\t%s\n", ZeropageLabel); } else { ZeropageLabel = xstrdup ("ZEROPAGE"); } } static const char* LabelPlusOffs (const char* Label, long Offs) /* Generate "Label+xxx" in a static buffer and return a pointer to the buffer */ { static char Buf[256]; xsprintf (Buf, sizeof (Buf), "%s%+ld", Label, Offs); return Buf; } static const char* RelocExpr (const O65Data* D, unsigned char SegID, unsigned long Val, const O65Reloc* R) /* Generate the segment relative relocation expression. R is only used if the * expression contains am import, and may be NULL if this is an error (which * is then flagged). */ { const O65Import* Import; switch (SegID) { case O65_SEGID_UNDEF: if (R) { if (R->SymIdx >= CollCount (&D->Imports)) { Error ("Import index out of range (input file corrupt)"); } Import = CollConstAt (&D->Imports, R->SymIdx); return LabelPlusOffs (Import->Name, Val); } else { Error ("Relocation references an import which is not allowed here"); return 0; } break; case O65_SEGID_TEXT: return LabelPlusOffs (CodeLabel, Val - D->Header.tbase); case O65_SEGID_DATA: return LabelPlusOffs (DataLabel, Val - D->Header.dbase); case O65_SEGID_BSS: return LabelPlusOffs (BssLabel, Val - D->Header.bbase); case O65_SEGID_ZP: return LabelPlusOffs (ZeropageLabel, Val - D->Header.zbase); case O65_SEGID_ABS: return LabelPlusOffs ("", Val); default: Internal ("Cannot handle this segment reference in reloc entry"); } /* NOTREACHED */ return 0; } static void ConvertImports (FILE* F, const O65Data* D) /* Convert the imports */ { unsigned I; if (CollCount (&D->Imports) > 0) { for (I = 0; I < CollCount (&D->Imports); ++I) { /* Get the next import */ const O65Import* Import = CollConstAt (&D->Imports, I); /* Import it by name */ fprintf (F, ".import\t%s\n", Import->Name); } fprintf (F, "\n"); } } static void ConvertExports (FILE* F, const O65Data* D) /* Convert the exports */ { unsigned I; if (CollCount (&D->Exports) > 0) { for (I = 0; I < CollCount (&D->Exports); ++I) { /* Get the next import */ const O65Export* Export = CollConstAt (&D->Exports, I); /* First define it */ fprintf (F, "%s = %s\n", Export->Name, RelocExpr (D, Export->SegID, Export->Val, 0)); /* Then export it by name */ fprintf (F, ".export\t%s\n", Export->Name); } fprintf (F, "\n"); } } static void ConvertSeg (FILE* F, const O65Data* D, const Collection* Relocs, const unsigned char* Data, unsigned long Size) /* Convert one segment */ { const O65Reloc* R; unsigned RIdx; unsigned long Byte; /* Get the pointer to the first relocation entry if there are any */ R = (CollCount (Relocs) > 0)? CollConstAt (Relocs, 0) : 0; /* Initialize for the loop */ RIdx = 0; Byte = 0; /* Walk over the segment data */ while (Byte < Size) { if (R && R->Offs == Byte) { /* We've reached an entry that must be relocated */ unsigned long Val; switch (R->Type) { case O65_RTYPE_WORD: if (Byte >= Size - 1) { Error ("Found WORD relocation, but not enough bytes left"); } else { Val = (Data[Byte+1] << 8) + Data[Byte]; Byte += 2; fprintf (F, "\t.word\t%s\n", RelocExpr (D, R->SegID, Val, R)); } break; case O65_RTYPE_HIGH: Val = (Data[Byte++] << 8) + R->Val; fprintf (F, "\t.byte\t>(%s)\n", RelocExpr (D, R->SegID, Val, R)); break; case O65_RTYPE_LOW: Val = Data[Byte++]; fprintf (F, "\t.byte\t<(%s)\n", RelocExpr (D, R->SegID, Val, R)); break; case O65_RTYPE_SEGADDR: if (Byte >= Size - 2) { Error ("Found SEGADDR relocation, but not enough bytes left"); } else { Val = (((unsigned long) Data[Byte+2]) << 16) + (((unsigned long) Data[Byte+1]) << 8) + (((unsigned long) Data[Byte+0]) << 0) + R->Val; Byte += 3; fprintf (F, "\t.faraddr\t%s\n", RelocExpr (D, R->SegID, Val, R)); } break; case O65_RTYPE_SEG: /* FALLTHROUGH for now */ default: Internal ("Cannot handle relocation type %d at %lu", R->Type, Byte); } /* Get the next relocation entry */ if (++RIdx < CollCount (Relocs)) { R = CollConstAt (Relocs, RIdx); } else { R = 0; } } else { /* Just a constant value */ fprintf (F, "\t.byte\t$%02X\n", Data[Byte++]); } } fprintf (F, "\n"); } static void ConvertCodeSeg (FILE* F, const O65Data* D) /* Do code segment conversion */ { /* Header */ fprintf (F, ";\n; CODE SEGMENT\n;\n" ".segment\t\"%s\"\n" "%s:\n", CodeSeg, CodeLabel); /* Segment data */ ConvertSeg (F, D, &D->TextReloc, D->Text, D->Header.tlen); } static void ConvertDataSeg (FILE* F, const O65Data* D) /* Do data segment conversion */ { /* Header */ fprintf (F, ";\n; DATA SEGMENT\n;\n" ".segment\t\"%s\"\n" "%s:\n", DataSeg, DataLabel); /* Segment data */ ConvertSeg (F, D, &D->DataReloc, D->Data, D->Header.dlen); } static void ConvertBssSeg (FILE* F, const O65Data* D) /* Do bss segment conversion */ { /* Header */ fprintf (F, ";\n; BSS SEGMENT\n;\n" ".segment\t\"%s\"\n" "%s:\n", BssSeg, BssLabel); /* Segment data */ fprintf (F, "\t.res\t%lu\n", D->Header.blen); fprintf (F, "\n"); } static void ConvertZeropageSeg (FILE* F, const O65Data* D) /* Do zeropage segment conversion */ { /* Header */ fprintf (F, ";\n; ZEROPAGE SEGMENT\n;\n"); if (Model == O65_MODEL_CC65_MODULE) { /* o65 files of type cc65-module are linked together with a definition * file for the zero page, but the zero page is not allocated in the * module itself, but the locations are mapped to the zp locations of * the main file. */ fprintf (F, ".import\t__ZP_START__\t\t; Linker generated symbol\n"); fprintf (F, "%s = __ZP_START__\n", ZeropageLabel); } else { /* Header */ fprintf (F, ".segment\t\"%s\": zeropage\n%s:\n", ZeropageSeg, ZeropageLabel); /* Segment data */ fprintf (F, "\t.res\t%lu\n", D->Header.zlen); } fprintf (F, "\n"); } void Convert (const O65Data* D) /* Convert the o65 file in D using the given output file. */ { FILE* F; unsigned I; char* Author = 0; /* For now, we do only accept o65 files generated by the ld65 linker which * have a specific format. */ if (!Debug && D->Header.mode != O65_MODE_CC65) { Error ("Cannot convert o65 files of this type"); } /* Output statistics */ PrintO65Stats (D); /* Walk through the options and print them if verbose mode is enabled. * Check for a os=cc65 option and bail out if we didn't find one (for * now - later we switch to special handling). */ for (I = 0; I < CollCount (&D->Options); ++I) { /* Get the next option */ const O65Option* O = CollConstAt (&D->Options, I); /* Check the type of the option */ switch (O->Type) { case O65_OPT_FILENAME: Print (stdout, 1, "O65 filename option: `%s'\n", GetO65OptionText (O)); break; case O65_OPT_OS: if (O->Len == 2) { Warning ("Operating system option without data found"); } else { Print (stdout, 1, "O65 operating system option: `%s'\n", GetO65OSName (O->Data[0])); switch (O->Data[0]) { case O65_OS_CC65_MODULE: if (Model != O65_MODEL_NONE && Model != O65_MODEL_CC65_MODULE) { Warning ("Wrong o65 model for input file specified"); } else { Model = O65_MODEL_CC65_MODULE; } break; } } break; case O65_OPT_ASM: Print (stdout, 1, "O65 assembler option: `%s'\n", GetO65OptionText (O)); break; case O65_OPT_AUTHOR: if (Author) { xfree (Author); } Author = xstrdup (GetO65OptionText (O)); Print (stdout, 1, "O65 author option: `%s'\n", Author); break; case O65_OPT_TIMESTAMP: Print (stdout, 1, "O65 timestamp option: `%s'\n", GetO65OptionText (O)); break; default: Warning ("Found unknown option, type %d, length %d", O->Type, O->Len); break; } } /* If we shouldn't generate output, we're done here */ if (NoOutput) { return; } /* Open the output file */ F = fopen (OutputName, "w"); if (F == 0) { Error ("Cannot open `%s': %s", OutputName, strerror (errno)); } /* Create a header */ fprintf (F, ";\n; File generated by co65 v %s using model `%s'\n;\n", GetVersionAsString (), GetModelName (Model)); /* Select the CPU */ if ((D->Header.mode & O65_CPU_MASK) == O65_CPU_65816) { fprintf (F, ".p816\n"); } /* Object file options */ fprintf (F, ".fopt\t\tcompiler,\"co65 v %s\"\n", GetVersionAsString ()); if (Author) { fprintf (F, ".fopt\t\tauthor, \"%s\"\n", Author); xfree (Author); Author = 0; } /* Several other assembler options */ fprintf (F, ".case\t\ton\n"); fprintf (F, ".debuginfo\t%s\n", (DebugInfo != 0)? "on" : "off"); /* Setup/export the segment labels */ SetupSegLabels (F); /* End of header */ fprintf (F, "\n"); /* Imported identifiers */ ConvertImports (F, D); /* Exported identifiers */ ConvertExports (F, D); /* Code segment */ ConvertCodeSeg (F, D); /* Data segment */ ConvertDataSeg (F, D); /* BSS segment */ ConvertBssSeg (F, D); /* Zero page segment */ ConvertZeropageSeg (F, D); /* End of data */ fprintf (F, ".end\n"); fclose (F); }
961
./cc65/src/co65/error.c
/*****************************************************************************/ /* */ /* error.c */ /* */ /* Error handling for the co65 object file converter */ /* */ /* */ /* */ /* (C) 1998-2003 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> /* common */ #include "cmdline.h" /* co65 */ #include "error.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void Warning (const char* Format, ...) /* Print a warning message */ { va_list ap; va_start (ap, Format); fprintf (stderr, "%s: Warning: ", ProgName); vfprintf (stderr, Format, ap); putc ('\n', stderr); va_end (ap); } void Error (const char* Format, ...) /* Print an error message and die */ { va_list ap; va_start (ap, Format); fprintf (stderr, "%s: Error: ", ProgName); vfprintf (stderr, Format, ap); putc ('\n', stderr); va_end (ap); exit (EXIT_FAILURE); } void Internal (const char* Format, ...) /* Print an internal error message and die */ { va_list ap; va_start (ap, Format); fprintf (stderr, "%s: Internal error: ", ProgName); vfprintf (stderr, Format, ap); putc ('\n', stderr); va_end (ap); exit (EXIT_FAILURE); }
962
./cc65/src/co65/o65.c
/*****************************************************************************/ /* */ /* o65.h */ /* */ /* Definitions and code for the o65 file format */ /* */ /* */ /* */ /* (C) 2002-2004 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <errno.h> /* common */ #include "chartype.h" #include "xmalloc.h" /* co65 */ #include "error.h" #include "fileio.h" #include "o65.h" /*****************************************************************************/ /* struct O65Data */ /*****************************************************************************/ static O65Data* NewO65Data (void) /* Create, initialize and return a new O65Data struct */ { /* Allocate memory */ O65Data* D = xmalloc (sizeof (O65Data)); /* Initialize the fields as needed */ D->Options = AUTO_COLLECTION_INITIALIZER; D->Text = 0; D->Data = 0; D->TextReloc = AUTO_COLLECTION_INITIALIZER; D->DataReloc = AUTO_COLLECTION_INITIALIZER; D->Imports = AUTO_COLLECTION_INITIALIZER; D->Exports = AUTO_COLLECTION_INITIALIZER; /* Return the new struct */ return D; } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static unsigned long ReadO65Size (FILE* F, const O65Header* H) /* Read a size variable (16 or 32 bit, depending on the mode word in the * header) from the o65 file. */ { unsigned long Size = 0; /* Initialize to avoid warnings */ switch (H->mode & O65_SIZE_MASK) { case O65_SIZE_32BIT: Size = Read32 (F); break; case O65_SIZE_16BIT: Size = Read16 (F); break; default: Internal ("Invalid size field value in o65 header"); } return Size; } static void ReadO65Header (FILE* F, O65Header* H) /* Read an o65 header from the given file. The function will call Error if * something is wrong. */ { static const char Magic[3] = { O65_MAGIC_0, O65_MAGIC_1, O65_MAGIC_2 /* "o65" */ }; /* Read the marker and check it */ ReadData (F, H->marker, sizeof (H->marker)); if (H->marker[0] != O65_MARKER_0 || H->marker[1] != O65_MARKER_1) { Error ("Not an o65 object file: Invalid marker %02X %02X", H->marker[0], H->marker[1]); } /* Read the magic and check it */ ReadData (F, H->magic, sizeof (H->magic)); if (memcmp (H->magic, Magic, sizeof (H->magic)) != 0) { Error ("Not an o65 object file: Invalid magic %02X %02X %02X", H->magic[0], H->magic[1], H->magic[2]); } /* Read the version number and check it */ H->version = Read8 (F); if (H->version != O65_VERSION) { Error ("Invalid o65 version number: %02X", H->version); } /* Read the mode word */ H->mode = Read16 (F); /* Read the remainder of the header */ H->tbase = ReadO65Size (F, H); H->tlen = ReadO65Size (F, H); H->dbase = ReadO65Size (F, H); H->dlen = ReadO65Size (F, H); H->bbase = ReadO65Size (F, H); H->blen = ReadO65Size (F, H); H->zbase = ReadO65Size (F, H); H->zlen = ReadO65Size (F, H); H->stack = ReadO65Size (F, H); } static O65Option* ReadO65Option (FILE* F) /* Read the next O65 option from the given file. The option is stored into a * dynamically allocated O65Option struct which is returned. On end of options, * NULL is returned. On error, Error is called which terminates the program. */ { O65Option* O; /* Read the length of the option and bail out on end of options */ unsigned char Len = Read8 (F); if (Len == 0) { return 0; } if (Len < 2) { Error ("Found option with length < 2 (input file corrupt)"); } Len -= 2; /* Allocate a new O65Option structure of the needed size */ O = xmalloc (sizeof (*O) - sizeof (O->Data) + Len); /* Assign the length and read the remaining option data */ O->Len = Len; O->Type = Read8 (F); ReadData (F, O->Data, Len); /* Return the new struct */ return O; } static O65Import* ReadO65Import (FILE* F) /* Read an o65 import from the file */ { O65Import* I; /* Allow identifiers up to 511 bytes */ char Buf[512]; /* Read the identifier */ unsigned Len = 0; char C; do { C = Read8 (F); if (Len >= sizeof (Buf)) { Error ("Imported identifier exceeds maximum size (%u)", (unsigned) sizeof (Buf)); } Buf[Len++] = C; } while (C != '\0'); /* Allocate an import structure and initialize it */ I = xmalloc (sizeof (*I) - sizeof (I->Name) + Len); memcpy (I->Name, Buf, Len); /* Return the new struct */ return I; } static void ReadO65RelocInfo (FILE* F, const O65Data* D, Collection* Reloc) /* Read relocation data for one segment */ { /* Relocation starts at (start address - 1) */ unsigned long Offs = (unsigned long) -1L; while (1) { O65Reloc* R; /* Read the next relocation offset */ unsigned char C = Read8 (F); if (C == 0) { /* End of relocation table */ break; } /* Create a new relocation entry */ R = xmalloc (sizeof (*R)); /* Handle overflow bytes */ while (C == 0xFF) { Offs += 0xFE; C = Read8 (F); } /* Calculate the final offset */ R->Offs = (Offs += C); /* Read typebyte and segment id */ C = Read8 (F); R->Type = (C & O65_RTYPE_MASK); R->SegID = (C & O65_SEGID_MASK); /* Read an additional relocation value if there is one */ R->SymIdx = (R->SegID == O65_SEGID_UNDEF)? ReadO65Size (F, &D->Header) : 0; switch (R->Type) { case O65_RTYPE_HIGH: if ((D->Header.mode & O65_RELOC_MASK) == O65_RELOC_BYTE) { /* Low byte follows */ R->Val = Read8 (F); } else { /* Low byte is zero */ R->Val = 0; } break; case O65_RTYPE_SEG: /* Low 16 byte of the segment address follow */ R->Val = Read16 (F); break; default: R->Val = 0; break; } /* Insert this relocation entry into the collection */ CollAppend (Reloc, R); } } static O65Export* ReadO65Export (FILE* F, const O65Header* H) /* Read an o65 export from the file */ { O65Export* E; /* Allow identifiers up to 511 bytes */ char Buf[512]; /* Read the identifier */ unsigned Len = 0; char C; do { C = Read8 (F); if (Len >= sizeof (Buf)) { Error ("Exported identifier exceeds maximum size (%u)", (unsigned) sizeof (Buf)); } Buf[Len++] = C; } while (C != '\0'); /* Allocate an export structure and initialize it */ E = xmalloc (sizeof (*E) - sizeof (E->Name) + Len); memcpy (E->Name, Buf, Len); E->SegID = Read8 (F); E->Val = ReadO65Size (F, H); /* Return the new struct */ return E; } static O65Data* ReadO65Data (FILE* F) /* Read a complete o65 file into dynamically allocated memory and return the * created O65Data struct. */ { unsigned long Count; O65Option* O; /* Create the struct we're going to return */ O65Data* D = NewO65Data (); /* Read the header */ ReadO65Header (F, &D->Header); /* Read the options */ while ((O = ReadO65Option (F)) != 0) { CollAppend (&D->Options, O); } /* Allocate space for the text segment and read it */ D->Text = xmalloc (D->Header.tlen); ReadData (F, D->Text, D->Header.tlen); /* Allocate space for the data segment and read it */ D->Data = xmalloc (D->Header.dlen); ReadData (F, D->Data, D->Header.dlen); /* Read the undefined references list */ Count = ReadO65Size (F, &D->Header); while (Count--) { CollAppend (&D->Imports, ReadO65Import (F)); } /* Read the relocation tables for text and data segment */ ReadO65RelocInfo (F, D, &D->TextReloc); ReadO65RelocInfo (F, D, &D->DataReloc); /* Read the exported globals list */ Count = ReadO65Size (F, &D->Header); while (Count--) { CollAppend (&D->Exports, ReadO65Export (F, &D->Header)); } /* Return the o65 data read from the file */ return D; } O65Data* ReadO65File (const char* Name) /* Read a complete o65 file into dynamically allocated memory and return the * created O65Data struct. */ { O65Data* D; /* Open the o65 input file */ FILE* F = fopen (Name, "rb"); if (F == 0) { Error ("Cannot open `%s': %s", Name, strerror (errno)); } /* Read the file data */ D = ReadO65Data (F); /* Close the input file. Ignore errors since we were only reading */ fclose (F); /* Return the data read */ return D; } const char* GetO65OSName (unsigned char OS) /* Return the name of the operating system given by OS */ { switch (OS) { case O65_OS_OSA65: return "OS/A65"; case O65_OS_LUNIX: return "Lunix"; case O65_OS_CC65_MODULE: return "cc65 module"; default: return "unknown"; } } const char* GetO65OptionText (const O65Option* O) /* Return the data of the given option as a readable text. The function returns * a pointer to a static buffer that is reused on the next call, so if in doubt, * make a copy (and no, the function is not thread safe). */ { static char Buf[256]; unsigned I, J; /* Get the length of the text */ unsigned Len = 0; while (Len < O->Len && O->Data[Len] != '\0') { ++Len; } /* Copy into the buffer converting non readable characters */ I = J = 0; while (I < sizeof (Buf) - 1 && J < Len) { if (!IsControl (O->Data[J])) { Buf[I++] = O->Data[J]; } else { Buf[I++] = '\\'; if (I >= sizeof (Buf) - 4) { --I; break; } switch (O->Data[J]) { case '\t': Buf[I++] = 't'; break; case '\b': Buf[I++] = 'b'; break; case '\n': Buf[I++] = 'n'; break; case '\r': Buf[I++] = 'r'; break; case '\v': Buf[I++] = 'v'; break; default: sprintf (Buf + I, "x%02X", O->Data[J]); I += 3; break; } } ++J; } /* Terminate the string and return it */ Buf[I] = '\0'; return Buf; }
963
./cc65/src/co65/main.c
/*****************************************************************************/ /* */ /* main.c */ /* */ /* Main program for the co65 object file converter */ /* */ /* */ /* */ /* (C) 2003-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <time.h> /* common */ #include "chartype.h" #include "cmdline.h" #include "debugflag.h" #include "fname.h" #include "print.h" #include "segnames.h" #include "version.h" #include "xmalloc.h" #include "xsprintf.h" /* co65 */ #include "convert.h" #include "error.h" #include "global.h" #include "model.h" #include "o65.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void Usage (void) /* Print usage information and exit */ { printf ("Usage: %s [options] file\n" "Short options:\n" " -V\t\t\tPrint the version number\n" " -g\t\t\tAdd debug info to object file\n" " -h\t\t\tHelp (this text)\n" " -m model\t\tOverride the o65 model\n" " -n\t\t\tDon't generate an output file\n" " -o name\t\tName the output file\n" " -v\t\t\tIncrease verbosity\n" "\n" "Long options:\n" " --bss-label name\tDefine and export a BSS segment label\n" " --bss-name seg\tSet the name of the BSS segment\n" " --code-label name\tDefine and export a CODE segment label\n" " --code-name seg\tSet the name of the CODE segment\n" " --data-label name\tDefine and export a DATA segment label\n" " --data-name seg\tSet the name of the DATA segment\n" " --debug-info\t\tAdd debug info to object file\n" " --help\t\tHelp (this text)\n" " --no-output\t\tDon't generate an output file\n" " --o65-model model\tOverride the o65 model\n" " --verbose\t\tIncrease verbosity\n" " --version\t\tPrint the version number\n" " --zeropage-label name\tDefine and export a ZEROPAGE segment label\n" " --zeropage-name seg\tSet the name of the ZEROPAGE segment\n", ProgName); } static void CheckLabelName (const char* Label) /* Check if the given label is a valid label name */ { const char* L = Label; if (strlen (L) < 256 && (IsAlpha (*L) || *L== '_')) { while (*++L) { if (!IsAlNum (*L) && *L != '_') { break; } } } if (*L) { Error ("Label name `%s' is invalid", Label); } } static void CheckSegName (const char* Seg) /* Abort if the given name is not a valid segment name */ { /* Print an error and abort if the name is not ok */ if (!ValidSegName (Seg)) { Error ("Segment name `%s' is invalid", Seg); } } static void OptBssLabel (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --bss-label option */ { /* Check for a label name */ CheckLabelName (Arg); /* Set the label */ BssLabel = xstrdup (Arg); } static void OptBssName (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --bss-name option */ { /* Check for a valid name */ CheckSegName (Arg); /* Set the name */ BssSeg = xstrdup (Arg); } static void OptCodeLabel (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --code-label option */ { /* Check for a label name */ CheckLabelName (Arg); /* Set the label */ CodeLabel = xstrdup (Arg); } static void OptCodeName (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --code-name option */ { /* Check for a valid name */ CheckSegName (Arg); /* Set the name */ CodeSeg = xstrdup (Arg); } static void OptDataLabel (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --data-label option */ { /* Check for a label name */ CheckLabelName (Arg); /* Set the label */ DataLabel = xstrdup (Arg); } static void OptDataName (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --data-name option */ { /* Check for a valid name */ CheckSegName (Arg); /* Set the name */ DataSeg = xstrdup (Arg); } static void OptDebug (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Enable debugging code */ { ++Debug; } static void OptDebugInfo (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Add debug info to the object file */ { DebugInfo = 1; } static void OptHelp (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Print usage information and exit */ { Usage (); exit (EXIT_SUCCESS); } static void OptNoOutput (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Handle the --no-output option */ { NoOutput = 1; } static void OptO65Model (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --o65-model option */ { /* Search for the model name */ Model = FindModel (Arg); if (Model == O65_MODEL_INVALID) { Error ("Unknown o65 model `%s'", Arg); } } static void OptVerbose (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Increase verbosity */ { ++Verbosity; } static void OptVersion (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Print the assembler version */ { fprintf (stderr, "co65 V%s\n", GetVersionAsString ()); } static void OptZeropageLabel (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --zeropage-label option */ { /* Check for a label name */ CheckLabelName (Arg); /* Set the label */ ZeropageLabel = xstrdup (Arg); } static void OptZeropageName (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --zeropage-name option */ { /* Check for a valid name */ CheckSegName (Arg); /* Set the name */ ZeropageSeg = xstrdup (Arg); } static void DoConversion (void) /* Do file conversion */ { /* Read the o65 file into memory */ O65Data* D = ReadO65File (InputName); /* Do the conversion */ Convert (D); /* Free the o65 module data */ /* ### */ } int main (int argc, char* argv []) /* Converter main program */ { /* Program long options */ static const LongOpt OptTab[] = { { "--bss-label", 1, OptBssLabel }, { "--bss-name", 1, OptBssName }, { "--code-label", 1, OptCodeLabel }, { "--code-name", 1, OptCodeName }, { "--data-label", 1, OptDataLabel }, { "--data-name", 1, OptDataName }, { "--debug", 0, OptDebug }, { "--debug-info", 0, OptDebugInfo }, { "--help", 0, OptHelp }, { "--no-output", 0, OptNoOutput }, { "--o65-model", 1, OptO65Model }, { "--verbose", 0, OptVerbose }, { "--version", 0, OptVersion }, { "--zeropage-label", 1, OptZeropageLabel }, { "--zeropage-name", 1, OptZeropageName }, }; unsigned I; /* Initialize the cmdline module */ InitCmdLine (&argc, &argv, "co65"); /* Check the parameters */ I = 1; while (I < ArgCount) { /* Get the argument */ const char* Arg = ArgVec [I]; /* Check for an option */ if (Arg [0] == '-') { switch (Arg [1]) { case '-': LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0])); break; case 'g': OptDebugInfo (Arg, 0); break; case 'h': OptHelp (Arg, 0); break; case 'm': OptO65Model (Arg, GetArg (&I, 2)); break; case 'n': OptNoOutput (Arg, 0); break; case 'o': OutputName = GetArg (&I, 2); break; case 'v': OptVerbose (Arg, 0); break; case 'V': OptVersion (Arg, 0); break; default: UnknownOption (Arg); break; } } else { /* Filename. Check if we already had one */ if (InputName) { Error ("Don't know what to do with `%s'", Arg); } else { InputName = Arg; } } /* Next argument */ ++I; } /* Do we have an input file? */ if (InputName == 0) { Error ("No input file"); } /* Generate the name of the output file if none was specified */ if (OutputName == 0) { OutputName = MakeFilename (InputName, AsmExt); } /* Do the conversion */ DoConversion (); /* Return an apropriate exit code */ return EXIT_SUCCESS; }
964
./cc65/src/co65/global.c
/*****************************************************************************/ /* */ /* global.c */ /* */ /* Global variables for the co65 object file converter */ /* */ /* */ /* */ /* (C) 2003 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "segnames.h" /* co65 */ #include "global.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* File names */ const char* InputName = 0; /* Name of input file */ const char* OutputName = 0; /* Name of output file */ /* Default extensions */ const char AsmExt[] = ".s"; /* Default assembler extension */ /* Segment names */ const char* CodeSeg = SEGNAME_CODE; /* Name of the code segment */ const char* DataSeg = SEGNAME_DATA; /* Name of the data segment */ const char* BssSeg = SEGNAME_BSS; /* Name of the bss segment */ const char* ZeropageSeg = SEGNAME_ZEROPAGE; /* Name of the zeropage segment */ /* Labels */ const char* CodeLabel = 0; /* Label for the code segment */ const char* DataLabel = 0; /* Label for the data segment */ const char* BssLabel = 0; /* Label for the bss segment */ const char* ZeropageLabel = 0; /* Label for the zeropage segment */ /* Flags */ unsigned char DebugInfo = 0; /* Enable debug info */ unsigned char NoOutput = 0; /* Suppress the actual conversion */
965
./cc65/src/co65/model.c
/*****************************************************************************/ /* */ /* model.c */ /* */ /* o65 model definitions for the co65 object file converter */ /* */ /* */ /* */ /* (C) 2003 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "strutil.h" /* co65 */ #include "error.h" #include "model.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Current model */ O65Model Model = O65_MODEL_NONE; /* Name table */ static const char* NameTable[O65_MODEL_COUNT] = { "none", "os/a65", "lunix", "cc65-module" }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ const char* GetModelName (O65Model M) /* Map the model to its name. */ { if (M < 0 || M >= O65_MODEL_COUNT) { Internal ("O65 Model %d not found", M); } return NameTable[M]; } O65Model FindModel (const char* ModelName) /* Map a model name to its identifier. Return O65_MODEL_INVALID if the name * could not be found. Case is ignored when comparing names. */ { O65Model M; for (M = O65_MODEL_NONE; M < O65_MODEL_COUNT; ++M) { if (StrCaseCmp (ModelName, NameTable[M]) == 0) { return M; } } return O65_MODEL_INVALID; }
966
./cc65/src/co65/fileio.c
/*****************************************************************************/ /* */ /* fileio.c */ /* */ /* Binary file I/O for the co65 object file converter */ /* */ /* */ /* */ /* (C) 1998-2003 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "xmalloc.h" /* ld65 */ #include "error.h" #include "fileio.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned Read8 (FILE* F) /* Read an 8 bit value from the file */ { int C = getc (F); if (C == EOF) { Error ("Read error (file corrupt?)"); } return C; } unsigned Read16 (FILE* F) /* Read a 16 bit value from the file */ { unsigned Lo = Read8 (F); unsigned Hi = Read8 (F); return (Hi << 8) | Lo; } unsigned long Read24 (FILE* F) /* Read a 24 bit value from the file */ { unsigned long Lo = Read16 (F); unsigned long Hi = Read8 (F); return (Hi << 16) | Lo; } unsigned long Read32 (FILE* F) /* Read a 32 bit value from the file */ { unsigned long Lo = Read16 (F); unsigned long Hi = Read16 (F); return (Hi << 16) | Lo; } void* ReadData (FILE* F, void* Data, unsigned Size) /* Read data from the file */ { /* Explicitly allow reading zero bytes */ if (Size > 0) { if (fread (Data, 1, Size, F) != Size) { Error ("Read error (file corrupt?)"); } } return Data; }
967
./cc65/src/da65/opc6502x.c
/*****************************************************************************/ /* */ /* opc6502.c */ /* */ /* 6502 opcode description table with NMOS illegals */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* da65 */ #include "handler.h" #include "opc6502x.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Descriptions for all opcodes. Base table from opc6502.c with illegal * opcodes from http://www.oxyron.de/html/opcodes02.html */ const OpcDesc OpcTable_6502X[256] = { { "brk", 1, flNone, OH_Implicit }, /* $00 */ { "ora", 2, flUseLabel, OH_DirectXIndirect }, /* $01 */ { "kil", 1, flNone, OH_Implicit }, /* $02 */ { "slo", 2, flUseLabel, OH_DirectXIndirect }, /* $03 */ { "nop", 2, flUseLabel, OH_Direct }, /* $04 */ { "ora", 2, flUseLabel, OH_Direct }, /* $05 */ { "asl", 2, flUseLabel, OH_Direct }, /* $06 */ { "slo", 2, flUseLabel, OH_Direct }, /* $07 */ { "php", 1, flNone, OH_Implicit }, /* $08 */ { "ora", 2, flNone, OH_Immediate }, /* $09 */ { "asl", 1, flNone, OH_Accumulator }, /* $0a */ { "anc", 2, flNone, OH_Immediate }, /* $0b */ { "nop", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0c */ { "ora", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0d */ { "asl", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0e */ { "slo", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0f */ { "bpl", 2, flLabel, OH_Relative }, /* $10 */ { "ora", 2, flUseLabel, OH_DirectIndirectY }, /* $11 */ { "kil", 1, flNone, OH_Implicit }, /* $12 */ { "slo", 2, flUseLabel, OH_DirectIndirectY }, /* $13 */ { "nop", 2, flUseLabel, OH_DirectX }, /* $14 */ { "ora", 2, flUseLabel, OH_DirectX }, /* $15 */ { "asl", 2, flUseLabel, OH_DirectX }, /* $16 */ { "slo", 2, flUseLabel, OH_DirectX }, /* $17 */ { "clc", 1, flNone, OH_Implicit }, /* $18 */ { "ora", 3, flUseLabel, OH_AbsoluteY }, /* $19 */ { "nop", 1, flNone, OH_Implicit }, /* $1a */ { "slo", 3, flUseLabel, OH_AbsoluteY }, /* $1b */ { "nop", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1c */ { "ora", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1d */ { "asl", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1e */ { "slo", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1f */ { "jsr", 3, flLabel, OH_Absolute }, /* $20 */ { "and", 2, flUseLabel, OH_DirectXIndirect }, /* $21 */ { "kil", 1, flNone, OH_Implicit, }, /* $22 */ { "rla", 2, flUseLabel, OH_DirectXIndirect }, /* $23 */ { "bit", 2, flUseLabel, OH_Direct }, /* $24 */ { "and", 2, flUseLabel, OH_Direct }, /* $25 */ { "rol", 2, flUseLabel, OH_Direct }, /* $26 */ { "rla", 2, flUseLabel, OH_Direct }, /* $27 */ { "plp", 1, flNone, OH_Implicit }, /* $28 */ { "and", 2, flNone, OH_Immediate }, /* $29 */ { "rol", 1, flNone, OH_Accumulator }, /* $2a */ { "anc", 2, flNone, OH_Immediate }, /* $2b */ { "bit", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2c */ { "and", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2d */ { "rol", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2e */ { "rla", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2f */ { "bmi", 2, flLabel, OH_Relative }, /* $30 */ { "and", 2, flUseLabel, OH_DirectIndirectY }, /* $31 */ { "kil", 1, flNone, OH_Implicit }, /* $32 */ { "rla", 2, flUseLabel, OH_DirectIndirectY }, /* $33 */ { "nop", 2, flUseLabel, OH_DirectX }, /* $34 */ { "and", 2, flUseLabel, OH_DirectX }, /* $35 */ { "rol", 2, flUseLabel, OH_DirectX }, /* $36 */ { "rla", 2, flUseLabel, OH_DirectX }, /* $37 */ { "sec", 1, flNone, OH_Implicit }, /* $38 */ { "and", 3, flUseLabel, OH_AbsoluteY }, /* $39 */ { "nop", 1, flNone, OH_Implicit }, /* $3a */ { "rla", 3, flUseLabel, OH_AbsoluteY }, /* $3b */ { "nop", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3c */ { "and", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3d */ { "rol", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3e */ { "rla", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3f */ { "rti", 1, flNone, OH_Rts }, /* $40 */ { "eor", 2, flUseLabel, OH_DirectXIndirect }, /* $41 */ { "kil", 1, flNone, OH_Implicit }, /* $42 */ { "sre", 2, flUseLabel, OH_DirectXIndirect }, /* $43 */ { "nop", 2, flUseLabel, OH_Direct }, /* $44 */ { "eor", 2, flUseLabel, OH_Direct }, /* $45 */ { "lsr", 2, flUseLabel, OH_Direct }, /* $46 */ { "sre", 2, flUseLabel, OH_Direct }, /* $47 */ { "pha", 1, flNone, OH_Implicit }, /* $48 */ { "eor", 2, flNone, OH_Immediate }, /* $49 */ { "lsr", 1, flNone, OH_Accumulator }, /* $4a */ { "alr", 2, flNone, OH_Immediate }, /* $4b */ { "jmp", 3, flLabel, OH_JmpAbsolute }, /* $4c */ { "eor", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4e */ { "sre", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4f */ { "bvc", 2, flLabel, OH_Relative }, /* $50 */ { "eor", 2, flUseLabel, OH_DirectIndirectY }, /* $51 */ { "kil", 1, flNone, OH_Implicit }, /* $52 */ { "sre", 2, flUseLabel, OH_DirectIndirectY }, /* $53 */ { "nop", 2, flUseLabel, OH_DirectX }, /* $54 */ { "eor", 2, flUseLabel, OH_DirectX }, /* $55 */ { "lsr", 2, flUseLabel, OH_DirectX }, /* $56 */ { "sre", 2, flUseLabel, OH_DirectX }, /* $57 */ { "cli", 1, flNone, OH_Implicit }, /* $58 */ { "eor", 3, flUseLabel, OH_AbsoluteY }, /* $59 */ { "nop", 1, flNone, OH_Implicit }, /* $5a */ { "sre", 3, flUseLabel, OH_AbsoluteY }, /* $5b */ { "nop", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5c */ { "eor", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5e */ { "sre", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5f */ { "rts", 1, flNone, OH_Rts }, /* $60 */ { "adc", 2, flUseLabel, OH_DirectXIndirect }, /* $61 */ { "kil", 1, flNone, OH_Implicit }, /* $62 */ { "rra", 2, flUseLabel, OH_DirectXIndirect }, /* $63 */ { "nop", 2, flUseLabel, OH_Direct }, /* $64 */ { "adc", 2, flUseLabel, OH_Direct }, /* $65 */ { "ror", 2, flUseLabel, OH_Direct }, /* $66 */ { "rra", 2, flUseLabel, OH_Direct }, /* $67 */ { "pla", 1, flNone, OH_Implicit }, /* $68 */ { "adc", 2, flNone, OH_Immediate }, /* $69 */ { "ror", 1, flNone, OH_Accumulator }, /* $6a */ { "arr", 2, flNone, OH_Immediate }, /* $6b */ { "jmp", 3, flLabel, OH_JmpAbsoluteIndirect }, /* $6c */ { "adc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6d */ { "ror", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6e */ { "rra", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6f */ { "bvs", 2, flLabel, OH_Relative }, /* $70 */ { "adc", 2, flUseLabel, OH_DirectIndirectY }, /* $71 */ { "kil", 1, flNone, OH_Implicit }, /* $72 */ { "rra", 2, flUseLabel, OH_DirectIndirectY }, /* $73 */ { "nop", 2, flUseLabel, OH_DirectX }, /* $74 */ { "adc", 2, flUseLabel, OH_DirectX }, /* $75 */ { "ror", 2, flUseLabel, OH_DirectX }, /* $76 */ { "rra", 2, flUseLabel, OH_DirectX }, /* $77 */ { "sei", 1, flNone, OH_Implicit }, /* $78 */ { "adc", 3, flUseLabel, OH_AbsoluteY }, /* $79 */ { "nop", 1, flNone, OH_Implicit }, /* $7a */ { "rra", 3, flUseLabel, OH_AbsoluteY }, /* $7b */ { "nop", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7c */ { "adc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7d */ { "ror", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7e */ { "rra", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7f */ { "nop", 2, flNone, OH_Immediate }, /* $80 */ { "sta", 2, flUseLabel, OH_DirectXIndirect }, /* $81 */ { "nop", 2, flNone, OH_Immediate }, /* $82 */ { "sax", 2, flUseLabel, OH_DirectXIndirect }, /* $83 */ { "sty", 2, flUseLabel, OH_Direct }, /* $84 */ { "sta", 2, flUseLabel, OH_Direct }, /* $85 */ { "stx", 2, flUseLabel, OH_Direct }, /* $86 */ { "sax", 2, flUseLabel, OH_Direct }, /* $87 */ { "dey", 1, flNone, OH_Implicit }, /* $88 */ { "nop", 2, flNone, OH_Immediate }, /* $89 */ { "txa", 1, flNone, OH_Implicit }, /* $8a */ { "xaa", 2, flNone, OH_Immediate }, /* $8b */ { "sty", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8c */ { "sta", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8d */ { "stx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8e */ { "sax", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8f */ { "bcc", 2, flLabel, OH_Relative }, /* $90 */ { "sta", 2, flUseLabel, OH_DirectIndirectY }, /* $91 */ { "kil", 1, flNone, OH_Implicit }, /* $92 */ { "ahx", 2, flUseLabel, OH_DirectIndirectY }, /* $93 */ { "sty", 2, flUseLabel, OH_DirectX }, /* $94 */ { "sta", 2, flUseLabel, OH_DirectX }, /* $95 */ { "stx", 2, flUseLabel, OH_DirectY }, /* $96 */ { "sax", 2, flUseLabel, OH_DirectY }, /* $97 */ { "tya", 1, flNone, OH_Implicit }, /* $98 */ { "sta", 3, flUseLabel, OH_AbsoluteY }, /* $99 */ { "txs", 1, flNone, OH_Implicit }, /* $9a */ { "tas", 3, flUseLabel, OH_AbsoluteY }, /* $9b */ { "shy", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $9c */ { "sta", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $9d */ { "shx", 3, flUseLabel, OH_AbsoluteY }, /* $9e */ { "ahx", 3, flUseLabel, OH_AbsoluteY }, /* $9f */ { "ldy", 2, flNone, OH_Immediate }, /* $a0 */ { "lda", 2, flUseLabel, OH_DirectXIndirect }, /* $a1 */ { "ldx", 2, flNone, OH_Immediate }, /* $a2 */ { "lax", 2, flUseLabel, OH_DirectXIndirect }, /* $a3 */ { "ldy", 2, flUseLabel, OH_Direct }, /* $a4 */ { "lda", 2, flUseLabel, OH_Direct }, /* $a5 */ { "ldx", 2, flUseLabel, OH_Direct }, /* $a6 */ { "lax", 2, flUseLabel, OH_Direct }, /* $a7 */ { "tay", 1, flNone, OH_Implicit }, /* $a8 */ { "lda", 2, flNone, OH_Immediate }, /* $a9 */ { "tax", 1, flNone, OH_Implicit }, /* $aa */ { "lax", 2, flNone, OH_Immediate }, /* $ab */ { "ldy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ac */ { "lda", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ad */ { "ldx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ae */ { "lax", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $af */ { "bcs", 2, flLabel, OH_Relative }, /* $b0 */ { "lda", 2, flUseLabel, OH_DirectIndirectY }, /* $b1 */ { "kil", 1, flNone, OH_Implicit }, /* $b2 */ { "lax", 2, flUseLabel, OH_DirectIndirectY }, /* $b3 */ { "ldy", 2, flUseLabel, OH_DirectX }, /* $b4 */ { "lda", 2, flUseLabel, OH_DirectX }, /* $b5 */ { "ldx", 2, flUseLabel, OH_DirectY }, /* $b6 */ { "lax", 2, flUseLabel, OH_DirectY }, /* $b7 */ { "clv", 1, flNone, OH_Implicit }, /* $b8 */ { "lda", 3, flUseLabel, OH_AbsoluteY }, /* $b9 */ { "tsx", 1, flNone, OH_Implicit }, /* $ba */ { "las", 3, flUseLabel, OH_AbsoluteY }, /* $bb */ { "ldy", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bc */ { "lda", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bd */ { "ldx", 3, flUseLabel|flAbsOverride, OH_AbsoluteY }, /* $be */ { "lax", 3, flUseLabel|flAbsOverride, OH_AbsoluteY }, /* $bf */ { "cpy", 2, flNone, OH_Immediate }, /* $c0 */ { "cmp", 2, flUseLabel, OH_DirectXIndirect }, /* $c1 */ { "nop", 2, flNone, OH_Immediate }, /* $c2 */ { "dcp", 2, flUseLabel, OH_DirectXIndirect }, /* $c3 */ { "cpy", 2, flUseLabel, OH_Direct }, /* $c4 */ { "cmp", 2, flUseLabel, OH_Direct }, /* $c5 */ { "dec", 2, flUseLabel, OH_Direct }, /* $c6 */ { "dcp", 2, flUseLabel, OH_Direct }, /* $c7 */ { "iny", 1, flNone, OH_Implicit }, /* $c8 */ { "cmp", 2, flNone, OH_Immediate }, /* $c9 */ { "dex", 1, flNone, OH_Implicit }, /* $ca */ { "axs", 2, flNone, OH_Immediate }, /* $cb */ { "cpy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cd */ { "dec", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ce */ { "dcp", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cf */ { "bne", 2, flLabel, OH_Relative }, /* $d0 */ { "cmp", 2, flUseLabel, OH_DirectIndirectY }, /* $d1 */ { "kil", 1, flNone, OH_Implicit }, /* $d2 */ { "dcp", 2, flUseLabel, OH_DirectIndirectY }, /* $d3 */ { "nop", 2, flUseLabel, OH_DirectX }, /* $d4 */ { "cmp", 2, flUseLabel, OH_DirectX }, /* $d5 */ { "dec", 2, flUseLabel, OH_DirectX }, /* $d6 */ { "dcp", 2, flUseLabel, OH_DirectX }, /* $d7 */ { "cld", 1, flNone, OH_Implicit }, /* $d8 */ { "cmp", 3, flUseLabel, OH_AbsoluteY }, /* $d9 */ { "nop", 1, flNone, OH_Implicit }, /* $da */ { "dcp", 3, flUseLabel, OH_AbsoluteY }, /* $db */ { "nop", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $dc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $dd */ { "dec", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $de */ { "dcp", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $df */ { "cpx", 2, flNone, OH_Immediate }, /* $e0 */ { "sbc", 2, flUseLabel, OH_DirectXIndirect }, /* $e1 */ { "nop", 2, flNone, OH_Immediate }, /* $e2 */ { "isc", 2, flUseLabel, OH_DirectXIndirect }, /* $e3 */ { "cpx", 2, flUseLabel, OH_Direct }, /* $e4 */ { "sbc", 2, flUseLabel, OH_Direct }, /* $e5 */ { "inc", 2, flUseLabel, OH_Direct }, /* $e6 */ { "isc", 2, flUseLabel, OH_Direct }, /* $e7 */ { "inx", 1, flNone, OH_Implicit }, /* $e8 */ { "sbc", 2, flNone, OH_Immediate }, /* $e9 */ { "nop", 1, flNone, OH_Implicit }, /* $ea */ { "sbc", 2, flNone, OH_Immediate }, /* $eb */ { "cpx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ec */ { "sbc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ed */ { "inc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ee */ { "isc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ef */ { "beq", 2, flLabel, OH_Relative }, /* $f0 */ { "sbc", 2, flUseLabel, OH_DirectIndirectY }, /* $f1 */ { "kil", 1, flNone, OH_Implicit }, /* $f2 */ { "isc", 2, flUseLabel, OH_DirectIndirectY }, /* $f3 */ { "nop", 2, flUseLabel, OH_DirectX }, /* $f4 */ { "sbc", 2, flUseLabel, OH_DirectX }, /* $f5 */ { "inc", 2, flUseLabel, OH_DirectX }, /* $f6 */ { "isc", 2, flUseLabel, OH_DirectX }, /* $f7 */ { "sed", 1, flNone, OH_Implicit }, /* $f8 */ { "sbc", 3, flUseLabel, OH_AbsoluteY }, /* $f9 */ { "nop", 1, flNone, OH_Implicit }, /* $fa */ { "isc", 3, flUseLabel, OH_AbsoluteY }, /* $fb */ { "nop", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fc */ { "sbc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fd */ { "inc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fe */ { "isc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $ff */ };
968
./cc65/src/da65/opctable.c
/*****************************************************************************/ /* */ /* opctable.c */ /* */ /* Disassembler opcode description table */ /* */ /* */ /* */ /* (C) 2000-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* da65 */ #include "error.h" #include "opc6502.h" #include "opc6502x.h" #include "opc65816.h" #include "opc65c02.h" #include "opc65sc02.h" #include "opchuc6280.h" #include "opcm740.h" #include "opctable.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Descriptions for all opcodes */ const OpcDesc* OpcTable = OpcTable_6502; /*****************************************************************************/ /* Code */ /*****************************************************************************/ void SetOpcTable (cpu_t CPU) /* Set the correct opcode table for the given CPU */ { switch (CPU) { case CPU_6502: OpcTable = OpcTable_6502; break; case CPU_6502X: OpcTable = OpcTable_6502X; break; case CPU_65SC02: OpcTable = OpcTable_65SC02; break; case CPU_65C02: OpcTable = OpcTable_65C02; break; case CPU_HUC6280: OpcTable = OpcTable_HuC6280; break; case CPU_M740: OpcTable = OpcTable_M740; break; default: Error ("Unsupported CPU"); } }
969
./cc65/src/da65/segment.c
/*****************************************************************************/ /* */ /* segment.c */ /* */ /* Segment handling for da65 */ /* */ /* */ /* */ /* (C) 2007 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "addrsize.h" #include "xmalloc.h" /* da65 */ #include "attrtab.h" #include "segment.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Hash definitions */ #define HASH_SIZE 53 /* Segment definition */ typedef struct Segment Segment; struct Segment { Segment* NextStart; /* Pointer to next segment */ Segment* NextEnd; /* Pointer to next segment */ unsigned long Start; unsigned long End; unsigned AddrSize; char Name[1]; /* Name, dynamically allocated */ }; /* Tables containing the segments. A segment is inserted using it's hash * value. Collision is done by single linked lists. */ static Segment* StartTab[HASH_SIZE]; /* Table containing segment starts */ static Segment* EndTab[HASH_SIZE]; /* Table containing segment ends */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ void AddAbsSegment (unsigned Start, unsigned End, const char* Name) /* Add an absolute segment to the segment table */ { /* Get the length of the name */ unsigned Len = strlen (Name); /* Create a new segment */ Segment* S = xmalloc (sizeof (Segment) + Len); /* Fill in the data */ S->Start = Start; S->End = End; S->AddrSize = ADDR_SIZE_ABS; memcpy (S->Name, Name, Len + 1); /* Insert the segment into the hash tables */ S->NextStart = StartTab[Start % HASH_SIZE]; StartTab[Start % HASH_SIZE] = S; S->NextEnd = EndTab[End % HASH_SIZE]; EndTab[End % HASH_SIZE] = S; /* Mark start and end of the segment */ MarkAddr (Start, atSegmentChange); MarkAddr (End, atSegmentChange); /* Mark the addresses within the segment */ MarkRange (Start, End, atSegment); }
970
./cc65/src/da65/asminc.c
/*****************************************************************************/ /* */ /* asminc.c */ /* */ /* Read an assembler include file containing symbols */ /* */ /* */ /* */ /* (C) 2005-2008 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <errno.h> /* common */ #include "chartype.h" #include "strbuf.h" /* da65 */ #include "asminc.h" #include "comments.h" #include "error.h" #include "labels.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static char* SkipWhitespace (char* L) /* Ignore white space in L */ { while (IsBlank (*L)) { ++L; } return L; } unsigned DigitVal (unsigned char C) /* Return the value of the given digit */ { if (IsDigit (C)) { return C - '0'; } else { return tolower (C) - 'a' + 10; } } void AsmInc (const char* Filename, char CommentStart, int IgnoreUnknown) /* Read an assembler include file */ { char Buf[1024]; char* L; const char* Comment; unsigned Line; unsigned Len; long Val; unsigned DVal; int Sign; unsigned Base; unsigned Digits; StrBuf Ident = STATIC_STRBUF_INITIALIZER; /* Try to open the file for reading */ FILE* F = fopen (Filename, "r"); if (F == 0) { Error ("Cannot open asm include file \"%s\": %s", Filename, strerror (errno)); } /* Read line by line, check for NAME = VALUE lines */ Line = 0; while ((L = fgets (Buf, sizeof (Buf), F)) != 0) { /* One more line read */ ++Line; /* Ignore leading white space */ while (IsBlank (*L)) { ++L; } /* Remove trailing whitespace */ Len = strlen (L); while (Len > 0 && IsSpace (L[Len-1])) { --Len; } L[Len] = '\0'; /* If the line is empty or starts with a comment char, ignore it */ if (*L == '\0' || *L == CommentStart) { continue; } /* Read an identifier */ SB_Clear (&Ident); if (IsAlpha (*L) || *L == '_') { SB_AppendChar (&Ident, *L++); while (IsAlNum (*L) || *L == '_') { SB_AppendChar (&Ident, *L++); } SB_Terminate (&Ident); } else { if (!IgnoreUnknown) { Error ("%s(%u): Syntax error", Filename, Line); } continue; } /* Ignore white space */ L = SkipWhitespace (L); /* Check for := or = */ if (*L == '=') { ++L; } else if (*L == ':' && *++L == '=') { ++L; } else { if (!IgnoreUnknown) { Error ("%s(%u): Missing `='", Filename, Line); } continue; } /* Allow white space once again */ L = SkipWhitespace (L); /* A number follows. Read the sign. */ if (*L == '-') { Sign = -1; ++L; } else { Sign = 1; if (*L == '+') { ++L; } } /* Determine the base of the number. Allow $ and % as prefixes for * hex and binary numbers respectively. */ if (*L == '$') { Base = 16; ++L; } else if (*L == '%') { Base = 2; ++L; } else { Base = 10; } /* Decode the number */ Digits = 0; Val = 0; while (IsXDigit (*L) && (DVal = DigitVal (*L)) < Base) { Val = (Val * Base) + DVal; ++Digits; ++L; } /* Must have at least one digit */ if (Digits == 0) { if (!IgnoreUnknown) { Error ("%s(%u): Error in number format", Filename, Line); } continue; } /* Skip whitespace again */ L = SkipWhitespace (L); /* Check for a comment */ if (*L == CommentStart) { Comment = SkipWhitespace (L+1); if (*Comment == '\0') { Comment = 0; } } else { Comment = 0; } /* Check for a comment character or end of line */ if (*L != CommentStart && *L != '\0') { if (!IgnoreUnknown) { Error ("%s(%u): Trailing garbage", Filename, Line); } continue; } /* Apply the sign */ Val *= Sign; /* Define the symbol and the comment */ AddExtLabel (Val, SB_GetConstBuf (&Ident)); SetComment (Val, Comment); } /* Delete the string buffer contents */ SB_Done (&Ident); /* Close the include file ignoring errors (we were just reading). */ (void) fclose (F); }
971
./cc65/src/da65/data.c
/*****************************************************************************/ /* */ /* data.c */ /* */ /* Data output routines */ /* */ /* */ /* */ /* (C) 2000-2007 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* da65 */ #include "attrtab.h" #include "code.h" #include "error.h" #include "global.h" #include "labels.h" #include "output.h" #include "data.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static unsigned GetSpan (attr_t Style) /* Get the number of bytes for a given style */ { /* Get the number of bytes still available */ unsigned RemainingBytes = GetRemainingBytes (); /* Count how many bytes are available. This number is limited by the * number of remaining bytes, a label, a segment change, or the end of * the given Style attribute. */ unsigned Count = 1; while (Count < RemainingBytes) { attr_t Attr; if (MustDefLabel(PC+Count)) { break; } Attr = GetAttr (PC+Count); if ((Attr & atStyleMask) != Style) { break; } if ((Attr & atSegmentChange)) { break; } ++Count; } /* Return the number of bytes */ return Count; } static unsigned DoTable (attr_t Style, unsigned MemberSize, void (*TableFunc) (unsigned)) /* Output a table of bytes */ { unsigned BytesLeft; /* Count how many bytes may be output. */ unsigned Count = GetSpan (Style); /* If the count is less than the member size, print a row of Count data * bytes. We assume here that there is no member with a size that is less * than BytesPerLine. */ if (Count < MemberSize) { DataByteLine (Count); PC += Count; return Count; } /* Make Count an even number of multiples of MemberSize */ Count &= ~(MemberSize-1); /* Output as many data bytes lines as needed */ BytesLeft = Count; while (BytesLeft > 0) { /* Calculate the number of bytes for the next line */ unsigned Chunk = (BytesLeft > BytesPerLine)? BytesPerLine : BytesLeft; /* Output a line with these bytes */ TableFunc (Chunk); /* Next line */ BytesLeft -= Chunk; PC += Chunk; } /* If the next line is not the same style, add a separator */ if (CodeLeft() && GetStyleAttr (PC) != Style) { SeparatorLine (); } /* Return the number of bytes output */ return Count; } unsigned ByteTable (void) /* Output a table of bytes */ { /* Call the low level function */ return DoTable (atByteTab, 1, DataByteLine); } unsigned DByteTable (void) /* Output a table of dbytes */ { /* Call the low level function */ return DoTable (atDByteTab, 2, DataDByteLine); } unsigned WordTable (void) /* Output a table of words */ { /* Call the low level function */ return DoTable (atWordTab, 2, DataWordLine); } unsigned DWordTable (void) /* Output a table of double words */ { /* Call the low level function */ return DoTable (atDWordTab, 4, DataDWordLine); } unsigned AddrTable (void) /* Output a table of addresses */ { unsigned long BytesLeft = GetRemainingBytes (); unsigned long Start = PC; /* Loop while table bytes left and we don't need to create a label at the * current position. */ while (BytesLeft && GetStyleAttr (PC) == atAddrTab) { unsigned Addr; /* If just one byte is left, define it and bail out */ if (BytesLeft == 1 || GetStyleAttr (PC+1) != atAddrTab) { DataByteLine (1); ++PC; break; } /* More than one byte left. Define a forward label if necessary */ ForwardLabel (1); /* Now get the address from the PC */ Addr = GetCodeWord (PC); /* In pass 1, define a label, in pass 2 output the line */ if (Pass == 1) { if (!HaveLabel (Addr)) { AddIntLabel (Addr); } } else { const char* Label = GetLabel (Addr, PC); if (Label == 0) { /* OOPS! Should not happen */ Internal ("OOPS - Label for address 0x%06X disappeard!", Addr); } Indent (MCol); Output (".addr"); Indent (ACol); Output ("%s", Label); LineComment (PC, 2); LineFeed (); } /* Next table entry */ PC += 2; BytesLeft -= 2; /* If we must define a label here, bail out */ if (BytesLeft && MustDefLabel (PC)) { break; } } /* If the next line is not an address table line, add a separator */ if (CodeLeft() && GetStyleAttr (PC) != atAddrTab) { SeparatorLine (); } /* Return the number of bytes output */ return PC - Start; } unsigned RtsTable (void) /* Output a table of RTS addresses (address - 1) */ { unsigned long BytesLeft = GetRemainingBytes (); unsigned long Start = PC; /* Loop while table bytes left and we don't need to create a label at the * current position. */ while (BytesLeft && GetStyleAttr (PC) == atRtsTab) { unsigned Addr; /* If just one byte is left, define it and bail out */ if (BytesLeft == 1 || GetStyleAttr (PC+1) != atRtsTab) { DataByteLine (1); ++PC; break; } /* More than one byte left. Define a forward label if necessary */ ForwardLabel (1); /* Now get the address from the PC */ Addr = (GetCodeWord (PC) + 1) & 0xFFFF; /* In pass 1, define a label, in pass 2 output the line */ if (Pass == 1) { if (!HaveLabel (Addr)) { AddIntLabel (Addr); } } else { const char* Label = GetLabel (Addr, PC); if (Label == 0) { /* OOPS! Should not happen */ Internal ("OOPS - Label for address 0x%06X disappeard!", Addr); } Indent (MCol); Output (".word"); Indent (ACol); Output ("%s-1", Label); LineComment (PC, 2); LineFeed (); } /* Next table entry */ PC += 2; BytesLeft -= 2; /* If we must define a label here, bail out */ if (BytesLeft && MustDefLabel (PC)) { break; } } /* If the next line is not a return address table line, add a separator */ if (CodeLeft() && GetStyleAttr (PC) != atRtsTab) { SeparatorLine (); } /* Return the number of bytes output */ return PC - Start; } unsigned TextTable (void) /* Output a table of text messages */ { /* Count how many bytes may be output. */ unsigned ByteCount = GetSpan (atTextTab); /* Output as many data bytes lines as needed. */ unsigned BytesLeft = ByteCount; while (BytesLeft > 0) { unsigned I; /* Count the number of characters that can be output as such */ unsigned Count = 0; while (Count < BytesLeft && Count < BytesPerLine*4-1) { unsigned char C = GetCodeByte (PC + Count); if (C >= 0x20 && C <= 0x7E && C != '\"') { ++Count; } else { break; } } /* If we have text, output it */ if (Count > 0) { unsigned CBytes; Indent (MCol); Output (".byte"); Indent (ACol); Output ("\""); for (I = 0; I < Count; ++I) { Output ("%c", GetCodeByte (PC+I)); } Output ("\""); CBytes = Count; while (CBytes > 0) { unsigned Chunk = CBytes; if (Chunk > BytesPerLine) { Chunk = BytesPerLine; } LineComment (PC, Chunk); LineFeed (); CBytes -= Chunk; PC += Chunk; } BytesLeft -= Count; } /* Count the number of bytes that must be output as bytes */ Count = 0; while (Count < BytesLeft && Count < BytesPerLine) { unsigned char C = GetCodeByte (PC + Count); if (C < 0x20 || C > 0x7E || C == '\"') { ++Count; } else { break; } } /* If we have raw output bytes, print them */ if (Count > 0) { DataByteLine (Count); PC += Count; BytesLeft -= Count; } } /* If the next line is not a byte table line, add a separator */ if (CodeLeft() && GetStyleAttr (PC) != atTextTab) { SeparatorLine (); } /* Return the number of bytes output */ return ByteCount; }
972
./cc65/src/da65/infofile.c
/*****************************************************************************/ /* */ /* infofile.h */ /* */ /* Disassembler info file handling */ /* */ /* */ /* */ /* (C) 2000-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <limits.h> #if defined(_MSC_VER) /* Microsoft compiler */ # include <io.h> #else /* Anyone else */ # include <unistd.h> #endif /* common */ #include "cpu.h" #include "xmalloc.h" /* da65 */ #include "asminc.h" #include "attrtab.h" #include "comments.h" #include "error.h" #include "global.h" #include "infofile.h" #include "labels.h" #include "opctable.h" #include "scanner.h" #include "segment.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void AddAttr (const char* Name, unsigned* Set, unsigned Attr) /* Add an attribute to the set and check that it is not given twice */ { if (*Set & Attr) { /* Attribute is already in the set */ InfoError ("%s given twice", Name); } *Set |= Attr; } static void AsmIncSection (void) /* Parse a asminc section */ { static const IdentTok LabelDefs[] = { { "COMMENTSTART", INFOTOK_COMMENTSTART }, { "FILE", INFOTOK_FILE }, { "IGNOREUNKNOWN", INFOTOK_IGNOREUNKNOWN }, }; /* Locals - initialize to avoid gcc warnings */ char* Name = 0; int CommentStart = EOF; int IgnoreUnknown = -1; /* Skip the token */ InfoNextTok (); /* Expect the opening curly brace */ InfoConsumeLCurly (); /* Look for section tokens */ while (InfoTok != INFOTOK_RCURLY) { /* Convert to special token */ InfoSpecialToken (LabelDefs, ENTRY_COUNT (LabelDefs), "Asminc directive"); /* Look at the token */ switch (InfoTok) { case INFOTOK_COMMENTSTART: InfoNextTok (); if (CommentStart != EOF) { InfoError ("Commentstart already given"); } InfoAssureChar (); CommentStart = (char) InfoIVal; InfoNextTok (); break; case INFOTOK_FILE: InfoNextTok (); if (Name) { InfoError ("File name already given"); } InfoAssureStr (); if (InfoSVal[0] == '\0') { InfoError ("File name may not be empty"); } Name = xstrdup (InfoSVal); InfoNextTok (); break; case INFOTOK_IGNOREUNKNOWN: InfoNextTok (); if (IgnoreUnknown != -1) { InfoError ("Ignoreunknown already specified"); } InfoBoolToken (); IgnoreUnknown = (InfoTok != INFOTOK_FALSE); InfoNextTok (); break; default: Internal ("Unexpected token: %u", InfoTok); } /* Directive is followed by a semicolon */ InfoConsumeSemi (); } /* Check for the necessary data and assume defaults */ if (Name == 0) { InfoError ("File name is missing"); } if (CommentStart == EOF) { CommentStart = ';'; } if (IgnoreUnknown == -1) { IgnoreUnknown = 0; } /* Open the file and read the symbol definitions */ AsmInc (Name, CommentStart, IgnoreUnknown); /* Delete the dynamically allocated memory for Name */ xfree (Name); /* Consume the closing brace */ InfoConsumeRCurly (); } static void GlobalSection (void) /* Parse a global section */ { static const IdentTok GlobalDefs[] = { { "ARGUMENTCOL", INFOTOK_ARGUMENT_COLUMN }, { "ARGUMENTCOLUMN", INFOTOK_ARGUMENT_COLUMN }, { "COMMENTCOL", INFOTOK_COMMENT_COLUMN }, { "COMMENTCOLUMN", INFOTOK_COMMENT_COLUMN }, { "COMMENTS", INFOTOK_COMMENTS }, { "CPU", INFOTOK_CPU }, { "HEXOFFS", INFOTOK_HEXOFFS }, { "INPUTNAME", INFOTOK_INPUTNAME }, { "INPUTOFFS", INFOTOK_INPUTOFFS }, { "INPUTSIZE", INFOTOK_INPUTSIZE }, { "LABELBREAK", INFOTOK_LABELBREAK }, { "MNEMONICCOL", INFOTOK_MNEMONIC_COLUMN }, { "MNEMONICCOLUMN", INFOTOK_MNEMONIC_COLUMN }, { "NEWLINEAFTERJMP", INFOTOK_NL_AFTER_JMP }, { "NEWLINEAFTERRTS", INFOTOK_NL_AFTER_RTS }, { "OUTPUTNAME", INFOTOK_OUTPUTNAME }, { "PAGELENGTH", INFOTOK_PAGELENGTH }, { "STARTADDR", INFOTOK_STARTADDR }, { "TEXTCOL", INFOTOK_TEXT_COLUMN }, { "TEXTCOLUMN", INFOTOK_TEXT_COLUMN }, }; /* Skip the token */ InfoNextTok (); /* Expect the opening curly brace */ InfoConsumeLCurly (); /* Look for section tokens */ while (InfoTok != INFOTOK_RCURLY) { /* Convert to special token */ InfoSpecialToken (GlobalDefs, ENTRY_COUNT (GlobalDefs), "Global directive"); /* Look at the token */ switch (InfoTok) { case INFOTOK_ARGUMENT_COLUMN: InfoNextTok (); InfoAssureInt (); InfoRangeCheck (MIN_ACOL, MAX_ACOL); ACol = InfoIVal; InfoNextTok (); break; case INFOTOK_COMMENT_COLUMN: InfoNextTok (); InfoAssureInt (); InfoRangeCheck (MIN_CCOL, MAX_CCOL); CCol = InfoIVal; InfoNextTok (); break; case INFOTOK_COMMENTS: InfoNextTok (); InfoAssureInt (); InfoRangeCheck (MIN_COMMENTS, MAX_COMMENTS); Comments = InfoIVal; InfoNextTok (); break; case INFOTOK_CPU: InfoNextTok (); InfoAssureStr (); if (CPU != CPU_UNKNOWN) { InfoError ("CPU already specified"); } CPU = FindCPU (InfoSVal); SetOpcTable (CPU); InfoNextTok (); break; case INFOTOK_HEXOFFS: InfoNextTok (); InfoBoolToken (); switch (InfoTok) { case INFOTOK_FALSE: UseHexOffs = 0; break; case INFOTOK_TRUE: UseHexOffs = 1; break; } InfoNextTok (); break; case INFOTOK_INPUTNAME: InfoNextTok (); InfoAssureStr (); if (InFile) { InfoError ("Input file name already given"); } InFile = xstrdup (InfoSVal); InfoNextTok (); break; case INFOTOK_INPUTOFFS: InfoNextTok (); InfoAssureInt (); InputOffs = InfoIVal; InfoNextTok (); break; case INFOTOK_INPUTSIZE: InfoNextTok (); InfoAssureInt (); InfoRangeCheck (1, 0x10000); InputSize = InfoIVal; InfoNextTok (); break; case INFOTOK_LABELBREAK: InfoNextTok (); InfoAssureInt (); InfoRangeCheck (0, UCHAR_MAX); LBreak = (unsigned char) InfoIVal; InfoNextTok (); break; case INFOTOK_MNEMONIC_COLUMN: InfoNextTok (); InfoAssureInt (); InfoRangeCheck (MIN_MCOL, MAX_MCOL); MCol = InfoIVal; InfoNextTok (); break; case INFOTOK_NL_AFTER_JMP: InfoNextTok (); if (NewlineAfterJMP != -1) { InfoError ("NLAfterJMP already specified"); } InfoBoolToken (); NewlineAfterJMP = (InfoTok != INFOTOK_FALSE); InfoNextTok (); break; case INFOTOK_NL_AFTER_RTS: InfoNextTok (); InfoBoolToken (); if (NewlineAfterRTS != -1) { InfoError ("NLAfterRTS already specified"); } NewlineAfterRTS = (InfoTok != INFOTOK_FALSE); InfoNextTok (); break; case INFOTOK_OUTPUTNAME: InfoNextTok (); InfoAssureStr (); if (OutFile) { InfoError ("Output file name already given"); } OutFile = xstrdup (InfoSVal); InfoNextTok (); break; case INFOTOK_PAGELENGTH: InfoNextTok (); InfoAssureInt (); if (InfoIVal != 0) { InfoRangeCheck (MIN_PAGE_LEN, MAX_PAGE_LEN); } PageLength = InfoIVal; InfoNextTok (); break; case INFOTOK_STARTADDR: InfoNextTok (); InfoAssureInt (); InfoRangeCheck (0x0000, 0xFFFF); StartAddr = InfoIVal; InfoNextTok (); break; case INFOTOK_TEXT_COLUMN: InfoNextTok (); InfoAssureInt (); InfoRangeCheck (MIN_TCOL, MAX_TCOL); TCol = InfoIVal; InfoNextTok (); break; default: Internal ("Unexpected token: %u", InfoTok); } /* Directive is followed by a semicolon */ InfoConsumeSemi (); } /* Consume the closing brace */ InfoConsumeRCurly (); } static void LabelSection (void) /* Parse a label section */ { static const IdentTok LabelDefs[] = { { "COMMENT", INFOTOK_COMMENT }, { "ADDR", INFOTOK_ADDR }, { "NAME", INFOTOK_NAME }, { "SIZE", INFOTOK_SIZE }, }; /* Locals - initialize to avoid gcc warnings */ char* Name = 0; char* Comment = 0; long Value = -1; long Size = -1; /* Skip the token */ InfoNextTok (); /* Expect the opening curly brace */ InfoConsumeLCurly (); /* Look for section tokens */ while (InfoTok != INFOTOK_RCURLY) { /* Convert to special token */ InfoSpecialToken (LabelDefs, ENTRY_COUNT (LabelDefs), "Label attribute"); /* Look at the token */ switch (InfoTok) { case INFOTOK_ADDR: InfoNextTok (); if (Value >= 0) { InfoError ("Value already given"); } InfoAssureInt (); InfoRangeCheck (0, 0xFFFF); Value = InfoIVal; InfoNextTok (); break; case INFOTOK_COMMENT: InfoNextTok (); if (Comment) { InfoError ("Comment already given"); } InfoAssureStr (); if (InfoSVal[0] == '\0') { InfoError ("Comment may not be empty"); } Comment = xstrdup (InfoSVal); InfoNextTok (); break; case INFOTOK_NAME: InfoNextTok (); if (Name) { InfoError ("Name already given"); } InfoAssureStr (); Name = xstrdup (InfoSVal); InfoNextTok (); break; case INFOTOK_SIZE: InfoNextTok (); if (Size >= 0) { InfoError ("Size already given"); } InfoAssureInt (); InfoRangeCheck (1, 0x10000); Size = InfoIVal; InfoNextTok (); break; default: Internal ("Unexpected token: %u", InfoTok); } /* Directive is followed by a semicolon */ InfoConsumeSemi (); } /* Did we get the necessary data */ if (Name == 0) { InfoError ("Label name is missing"); } if (Name[0] == '\0' && Size > 1) { InfoError ("Unnamed labels must not have a size > 1"); } if (Value < 0) { InfoError ("Label value is missing"); } if (Size < 0) { /* Use default */ Size = 1; } if (Value + Size > 0x10000) { InfoError ("Invalid size (address out of range)"); } if (HaveLabel ((unsigned) Value)) { InfoError ("Label for address $%04lX already defined", Value); } /* Define the label(s) */ if (Name[0] == '\0') { /* Size has already beed checked */ AddUnnamedLabel (Value); } else { AddExtLabelRange ((unsigned) Value, Name, Size); } /* Define the comment */ if (Comment) { SetComment (Value, Comment); } /* Delete the dynamically allocated memory for Name and Comment */ xfree (Name); xfree (Comment); /* Consume the closing brace */ InfoConsumeRCurly (); } static void RangeSection (void) /* Parse a range section */ { static const IdentTok RangeDefs[] = { { "COMMENT", INFOTOK_COMMENT }, { "END", INFOTOK_END }, { "NAME", INFOTOK_NAME }, { "START", INFOTOK_START }, { "TYPE", INFOTOK_TYPE }, }; static const IdentTok TypeDefs[] = { { "ADDRTABLE", INFOTOK_ADDRTAB }, { "BYTETABLE", INFOTOK_BYTETAB }, { "CODE", INFOTOK_CODE }, { "DBYTETABLE", INFOTOK_DBYTETAB }, { "DWORDTABLE", INFOTOK_DWORDTAB }, { "RTSTABLE", INFOTOK_RTSTAB }, { "SKIP", INFOTOK_SKIP }, { "TEXTTABLE", INFOTOK_TEXTTAB }, { "WORDTABLE", INFOTOK_WORDTAB }, }; /* Which values did we get? */ enum { tNone = 0x00, tStart = 0x01, tEnd = 0x02, tType = 0x04, tName = 0x08, tComment= 0x10, tNeeded = (tStart | tEnd | tType) }; unsigned Attributes = tNone; /* Locals - initialize to avoid gcc warnings */ unsigned Start = 0; unsigned End = 0; unsigned char Type = 0; char* Name = 0; char* Comment = 0; unsigned MemberSize = 0; /* Skip the token */ InfoNextTok (); /* Expect the opening curly brace */ InfoConsumeLCurly (); /* Look for section tokens */ while (InfoTok != INFOTOK_RCURLY) { /* Convert to special token */ InfoSpecialToken (RangeDefs, ENTRY_COUNT (RangeDefs), "Range attribute"); /* Look at the token */ switch (InfoTok) { case INFOTOK_COMMENT: AddAttr ("COMMENT", &Attributes, tComment); InfoNextTok (); InfoAssureStr (); if (InfoSVal[0] == '\0') { InfoError ("Comment may not be empty"); } Comment = xstrdup (InfoSVal); Attributes |= tComment; InfoNextTok (); break; case INFOTOK_END: AddAttr ("END", &Attributes, tEnd); InfoNextTok (); InfoAssureInt (); InfoRangeCheck (0x0000, 0xFFFF); End = InfoIVal; InfoNextTok (); break; case INFOTOK_NAME: AddAttr ("NAME", &Attributes, tName); InfoNextTok (); InfoAssureStr (); if (InfoSVal[0] == '\0') { InfoError ("Name may not be empty"); } Name = xstrdup (InfoSVal); Attributes |= tName; InfoNextTok (); break; case INFOTOK_START: AddAttr ("START", &Attributes, tStart); InfoNextTok (); InfoAssureInt (); InfoRangeCheck (0x0000, 0xFFFF); Start = InfoIVal; InfoNextTok (); break; case INFOTOK_TYPE: AddAttr ("TYPE", &Attributes, tType); InfoNextTok (); InfoSpecialToken (TypeDefs, ENTRY_COUNT (TypeDefs), "TYPE"); switch (InfoTok) { case INFOTOK_ADDRTAB: Type = atAddrTab; MemberSize = 2; break; case INFOTOK_BYTETAB: Type = atByteTab; MemberSize = 1; break; case INFOTOK_CODE: Type = atCode; MemberSize = 1; break; case INFOTOK_DBYTETAB: Type = atDByteTab; MemberSize = 2; break; case INFOTOK_DWORDTAB: Type = atDWordTab; MemberSize = 4; break; case INFOTOK_RTSTAB: Type = atRtsTab; MemberSize = 2; break; case INFOTOK_SKIP: Type = atSkip; MemberSize = 1; break; case INFOTOK_TEXTTAB: Type = atTextTab; MemberSize = 1; break; case INFOTOK_WORDTAB: Type = atWordTab; MemberSize = 2; break; } InfoNextTok (); break; default: Internal ("Unexpected token: %u", InfoTok); } /* Directive is followed by a semicolon */ InfoConsumeSemi (); } /* Did we get all required values? */ if ((Attributes & tNeeded) != tNeeded) { InfoError ("Required values missing from this section"); } /* Start must be less than end */ if (Start > End) { InfoError ("Start value must not be greater than end value"); } /* Check the granularity */ if (((End - Start + 1) % MemberSize) != 0) { InfoError ("Type of range needs a granularity of %u", MemberSize); } /* Set the range */ MarkRange (Start, End, Type); /* Do we have a label? */ if (Attributes & tName) { /* Define a label for the table */ AddExtLabel (Start, Name); /* Set the comment if we have one */ if (Comment) { SetComment (Start, Comment); } /* Delete name and comment */ xfree (Name); xfree (Comment); } /* Consume the closing brace */ InfoConsumeRCurly (); } static void SegmentSection (void) /* Parse a segment section */ { static const IdentTok LabelDefs[] = { { "END", INFOTOK_END }, { "NAME", INFOTOK_NAME }, { "START", INFOTOK_START }, }; /* Locals - initialize to avoid gcc warnings */ long End = -1; long Start = -1; char* Name = 0; /* Skip the token */ InfoNextTok (); /* Expect the opening curly brace */ InfoConsumeLCurly (); /* Look for section tokens */ while (InfoTok != INFOTOK_RCURLY) { /* Convert to special token */ InfoSpecialToken (LabelDefs, ENTRY_COUNT (LabelDefs), "Segment attribute"); /* Look at the token */ switch (InfoTok) { case INFOTOK_END: InfoNextTok (); if (End >= 0) { InfoError ("Value already given"); } InfoAssureInt (); InfoRangeCheck (0, 0xFFFF); End = InfoIVal; InfoNextTok (); break; case INFOTOK_NAME: InfoNextTok (); if (Name) { InfoError ("Name already given"); } InfoAssureStr (); Name = xstrdup (InfoSVal); InfoNextTok (); break; case INFOTOK_START: InfoNextTok (); if (Start >= 0) { InfoError ("Value already given"); } InfoAssureInt (); InfoRangeCheck (0, 0xFFFF); Start = InfoIVal; InfoNextTok (); break; default: Internal ("Unexpected token: %u", InfoTok); } /* Directive is followed by a semicolon */ InfoConsumeSemi (); } /* Did we get the necessary data, and is it correct? */ if (Name == 0 || Name[0] == '\0') { InfoError ("Segment name is missing"); } if (End < 0) { InfoError ("End address is missing"); } if (Start < 0) { InfoError ("Start address is missing"); } if (Start == End) { InfoError ("Segment is empty"); } if (Start > End) { InfoError ("Start address of segment is greater than end address"); } /* Check that segments do not overlap */ if (SegmentDefined ((unsigned) Start, (unsigned) End)) { InfoError ("Segments cannot overlap"); } /* Remember the segment data */ AddAbsSegment ((unsigned) Start, (unsigned) End, Name); /* Delete the dynamically allocated memory for Name */ xfree (Name); /* Consume the closing brace */ InfoConsumeRCurly (); } static void InfoParse (void) /* Parse the config file */ { static const IdentTok Globals[] = { { "ASMINC", INFOTOK_ASMINC }, { "GLOBAL", INFOTOK_GLOBAL }, { "LABEL", INFOTOK_LABEL }, { "RANGE", INFOTOK_RANGE }, { "SEGMENT", INFOTOK_SEGMENT }, }; while (InfoTok != INFOTOK_EOF) { /* Convert an identifier into a token */ InfoSpecialToken (Globals, ENTRY_COUNT (Globals), "Config directive"); /* Check the token */ switch (InfoTok) { case INFOTOK_ASMINC: AsmIncSection (); break; case INFOTOK_GLOBAL: GlobalSection (); break; case INFOTOK_LABEL: LabelSection (); break; case INFOTOK_RANGE: RangeSection (); break; case INFOTOK_SEGMENT: SegmentSection (); break; default: Internal ("Unexpected token: %u", InfoTok); } /* Semicolon expected */ InfoConsumeSemi (); } } void ReadInfoFile (void) /* Read the info file */ { /* Check if we have a info file given */ if (InfoAvail()) { /* Open the config file */ InfoOpenInput (); /* Parse the config file */ InfoParse (); /* Close the file */ InfoCloseInput (); } }
973
./cc65/src/da65/error.c
/*****************************************************************************/ /* */ /* error.c */ /* */ /* Error handling */ /* */ /* */ /* */ /* (C) 2000 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> /* da65 */ #include "error.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void Warning (const char* Format, ...) /* Print a warning message */ { va_list ap; va_start (ap, Format); fprintf (stderr, "Warning: "); vfprintf (stderr, Format, ap); putc ('\n', stderr); va_end (ap); } void Error (const char* Format, ...) /* Print an error message and die */ { va_list ap; va_start (ap, Format); fprintf (stderr, "Error: "); vfprintf (stderr, Format, ap); putc ('\n', stderr); va_end (ap); exit (EXIT_FAILURE); } void Internal (const char* Format, ...) /* Print an internal error message and die */ { va_list ap; va_start (ap, Format); fprintf (stderr, "Internal error: "); vfprintf (stderr, Format, ap); putc ('\n', stderr); va_end (ap); exit (EXIT_FAILURE); }
974
./cc65/src/da65/output.c
/*****************************************************************************/ /* */ /* output.c */ /* */ /* Disassembler output routines */ /* */ /* */ /* */ /* (C) 2000-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdarg.h> #include <string.h> #include <ctype.h> #include <errno.h> /* common */ #include "addrsize.h" #include "cpu.h" #include "version.h" /* da65 */ #include "code.h" #include "error.h" #include "global.h" #include "output.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ static FILE* F = 0; /* Output stream */ static unsigned Col = 1; /* Current column */ static unsigned Line = 0; /* Current line on page */ static unsigned Page = 1; /* Current output page */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void PageHeader (void) /* Print a page header */ { fprintf (F, "; da65 V%s\n" "; Created: %s\n" "; Input file: %s\n" "; Page: %u\n\n", GetVersionAsString (), Now, InFile, Page); } void OpenOutput (const char* Name) /* Open the given file for output */ { /* If we have a name given, open the output file, otherwise use stdout */ if (Name != 0) { F = fopen (Name, "w"); if (F == 0) { Error ("Cannot open `%s': %s", Name, strerror (errno)); } } else { F = stdout; } /* Output the header and initialize stuff */ PageHeader (); Line = 5; Col = 1; } void CloseOutput (void) /* Close the output file */ { if (F != stdout && fclose (F) != 0) { Error ("Error closing output file: %s", strerror (errno)); } } void Output (const char* Format, ...) /* Write to the output file */ { if (Pass == PassCount) { va_list ap; va_start (ap, Format); Col += vfprintf (F, Format, ap); va_end (ap); } } void Indent (unsigned N) /* Make sure the current line column is at position N (zero based) */ { if (Pass == PassCount) { while (Col < N) { fputc (' ', F); ++Col; } } } void LineFeed (void) /* Add a linefeed to the output file */ { if (Pass == PassCount) { fputc ('\n', F); if (PageLength > 0 && ++Line >= PageLength) { if (FormFeeds) { fputc ('\f', F); } ++Page; PageHeader (); Line = 5; } Col = 1; } } void DefLabel (const char* Name) /* Define a label with the given name */ { Output ("%s:", Name); /* If the label is longer than the configured maximum, or if it runs into * the opcode column, start a new line. */ if (Col > LBreak+2 || Col > MCol) { LineFeed (); } } void DefForward (const char* Name, const char* Comment, unsigned Offs) /* Define a label as "* + x", where x is the offset relative to the * current PC. */ { if (Pass == PassCount) { /* Flush existing output if necessary */ if (Col > 1) { LineFeed (); } /* Output the forward definition */ Output ("%s", Name); Indent (ACol); if (UseHexOffs) { Output (":= * + $%04X", Offs); } else { Output (":= * + %u", Offs); } if (Comment) { Indent (CCol); Output ("; %s", Comment); } LineFeed (); } } void DefConst (const char* Name, const char* Comment, unsigned Addr) /* Define an address constant */ { if (Pass == PassCount) { Output ("%s", Name); Indent (ACol); Output (":= $%04X", Addr); if (Comment) { Indent (CCol); Output ("; %s", Comment); } LineFeed (); } } void StartSegment (const char* Name, unsigned AddrSize) /* Start a segment */ { if (Pass == PassCount) { Output (".segment"); Indent (ACol); if (AddrSize == ADDR_SIZE_DEFAULT) { Output ("\"%s\"", Name); } else { Output ("\"%s\": %s", Name, AddrSizeToStr (AddrSize)); } LineFeed (); } } void DataByteLine (unsigned ByteCount) /* Output a line with bytes */ { unsigned I; Indent (MCol); Output (".byte"); Indent (ACol); for (I = 0; I < ByteCount; ++I) { if (I > 0) { Output (",$%02X", CodeBuf[PC+I]); } else { Output ("$%02X", CodeBuf[PC+I]); } } LineComment (PC, ByteCount); LineFeed (); } void DataDByteLine (unsigned ByteCount) /* Output a line with dbytes */ { unsigned I; Indent (MCol); Output (".dbyt"); Indent (ACol); for (I = 0; I < ByteCount; I += 2) { if (I > 0) { Output (",$%04X", GetCodeDByte (PC+I)); } else { Output ("$%04X", GetCodeDByte (PC+I)); } } LineComment (PC, ByteCount); LineFeed (); } void DataWordLine (unsigned ByteCount) /* Output a line with words */ { unsigned I; Indent (MCol); Output (".word"); Indent (ACol); for (I = 0; I < ByteCount; I += 2) { if (I > 0) { Output (",$%04X", GetCodeWord (PC+I)); } else { Output ("$%04X", GetCodeWord (PC+I)); } } LineComment (PC, ByteCount); LineFeed (); } void DataDWordLine (unsigned ByteCount) /* Output a line with dwords */ { unsigned I; Indent (MCol); Output (".dword"); Indent (ACol); for (I = 0; I < ByteCount; I += 4) { if (I > 0) { Output (",$%08lX", GetCodeDWord (PC+I)); } else { Output ("$%08lX", GetCodeDWord (PC+I)); } } LineComment (PC, ByteCount); LineFeed (); } void SeparatorLine (void) /* Print a separator line */ { if (Pass == PassCount && Comments >= 1) { Output ("; ----------------------------------------------------------------------------"); LineFeed (); } } void UserComment (const char* Comment) /* Output a comment line */ { Output ("; %s", Comment); LineFeed (); } void LineComment (unsigned PC, unsigned Count) /* Add a line comment with the PC and data bytes */ { unsigned I; if (Pass == PassCount && Comments >= 2) { Indent (CCol); Output ("; %04X", PC); if (Comments >= 3) { for (I = 0; I < Count; ++I) { Output (" %02X", CodeBuf [PC+I]); } if (Comments >= 4) { Indent (TCol); for (I = 0; I < Count; ++I) { unsigned char C = CodeBuf [PC+I]; if (!isprint (C)) { C = '.'; } Output ("%c", C); } } } } } void OutputSettings (void) /* Output CPU and other settings */ { LineFeed (); Indent (MCol); Output (".setcpu"); Indent (ACol); Output ("\"%s\"", CPUNames[CPU]); LineFeed (); LineFeed (); }
975
./cc65/src/da65/attrtab.c
/*****************************************************************************/ /* */ /* attrtab.c */ /* */ /* Disassembler attribute table */ /* */ /* */ /* */ /* (C) 2000-2006 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* da65 */ #include "error.h" #include "attrtab.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Attribute table */ static unsigned short AttrTab[0x10000]; /*****************************************************************************/ /* Code */ /*****************************************************************************/ void AddrCheck (unsigned Addr) /* Check if the given address has a valid range */ { if (Addr >= 0x10000) { Error ("Address out of range: %08X", Addr); } } int SegmentDefined (unsigned Start, unsigned End) /* Return true if the atSegment bit is set somewhere in the given range */ { while (Start <= End) { if (AttrTab[Start++] & atSegment) { return 1; } } return 0; } int HaveSegmentChange (unsigned Addr) /* Return true if the segment change attribute is set for the given address */ { /* Check the given address */ AddrCheck (Addr); /* Return the attribute */ return (AttrTab[Addr] & atSegmentChange) != 0; } unsigned GetGranularity (attr_t Style) /* Get the granularity for the given style */ { switch (Style) { case atDefault: return 1; case atCode: return 1; case atIllegal: return 1; case atByteTab: return 1; case atDByteTab: return 2; case atWordTab: return 2; case atDWordTab: return 4; case atAddrTab: return 2; case atRtsTab: return 2; case atTextTab: return 1; case atSkip: default: Internal ("GetGraularity called for style = %d", Style); return 0; } } void MarkRange (unsigned Start, unsigned End, attr_t Attr) /* Mark a range with the given attribute */ { /* Do it easy here... */ while (Start <= End) { MarkAddr (Start++, Attr); } } void MarkAddr (unsigned Addr, attr_t Attr) /* Mark an address with an attribute */ { /* Check the given address */ AddrCheck (Addr); /* We must not have more than one style bit */ if (Attr & atStyleMask) { if (AttrTab[Addr] & atStyleMask) { Error ("Duplicate style for address %04X", Addr); } } /* Set the style */ AttrTab[Addr] |= Attr; } attr_t GetAttr (unsigned Addr) /* Return the attribute for the given address */ { /* Check the given address */ AddrCheck (Addr); /* Return the attribute */ return AttrTab[Addr]; } attr_t GetStyleAttr (unsigned Addr) /* Return the style attribute for the given address */ { /* Check the given address */ AddrCheck (Addr); /* Return the attribute */ return (AttrTab[Addr] & atStyleMask); } attr_t GetLabelAttr (unsigned Addr) /* Return the label attribute for the given address */ { /* Check the given address */ AddrCheck (Addr); /* Return the attribute */ return (AttrTab[Addr] & atLabelMask); }
976
./cc65/src/da65/opchuc6280.c
/*****************************************************************************/ /* */ /* opchuc6280.c */ /* */ /* HuC6280 opcode description table */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* da65 */ #include "handler.h" #include "opchuc6280.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Descriptions for all opcodes */ const OpcDesc OpcTable_HuC6280[256] = { { "brk", 1, flNone, OH_Implicit }, /* $00 */ { "ora", 2, flUseLabel, OH_DirectXIndirect }, /* $01 */ { "sxy", 1, flNone, OH_Implicit, }, /* $02 */ { "st0", 2, flNone, OH_Immediate, }, /* $03 */ { "tsb", 2, flUseLabel, OH_Direct }, /* $04 */ { "ora", 2, flUseLabel, OH_Direct }, /* $05 */ { "asl", 2, flUseLabel, OH_Direct }, /* $06 */ { "rmb0", 1, flUseLabel, OH_Direct, }, /* $07 */ { "php", 1, flNone, OH_Implicit }, /* $08 */ { "ora", 2, flNone, OH_Immediate }, /* $09 */ { "asl", 1, flNone, OH_Accumulator }, /* $0a */ { "", 1, flIllegal, OH_Illegal, }, /* $0b */ { "tsb", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0c */ { "ora", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0d */ { "asl", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0e */ { "bbr0", 3, flUseLabel, OH_BitBranch }, /* $0f */ { "bpl", 2, flLabel, OH_Relative }, /* $10 */ { "ora", 2, flUseLabel, OH_DirectIndirectY }, /* $11 */ { "ora", 2, flUseLabel, OH_DirectIndirect }, /* $12 */ { "st1", 2, flNone, OH_Immediate, }, /* $13 */ { "trb", 2, flUseLabel, OH_Direct }, /* $14 */ { "ora", 2, flUseLabel, OH_DirectX }, /* $15 */ { "asl", 2, flUseLabel, OH_DirectX }, /* $16 */ { "rmb1", 1, flUseLabel, OH_Direct, }, /* $17 */ { "clc", 1, flNone, OH_Implicit }, /* $18 */ { "ora", 3, flUseLabel, OH_AbsoluteY }, /* $19 */ { "inc", 1, flNone, OH_Accumulator }, /* $1a */ { "", 1, flIllegal, OH_Illegal, }, /* $1b */ { "trb", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $1c */ { "ora", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1d */ { "asl", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1e */ { "bbr1", 3, flUseLabel, OH_BitBranch }, /* $1f */ { "jsr", 3, flLabel, OH_Absolute }, /* $20 */ { "and", 2, flUseLabel, OH_DirectXIndirect }, /* $21 */ { "sax", 1, flNone, OH_Implicit, }, /* $22 */ { "st2", 2, flNone, OH_Immediate, }, /* $23 */ { "bit", 2, flUseLabel, OH_Direct }, /* $24 */ { "and", 2, flUseLabel, OH_Direct }, /* $25 */ { "rol", 2, flUseLabel, OH_Direct }, /* $26 */ { "rmb2", 1, flUseLabel, OH_Direct, }, /* $27 */ { "plp", 1, flNone, OH_Implicit }, /* $28 */ { "and", 2, flNone, OH_Immediate }, /* $29 */ { "rol", 1, flNone, OH_Accumulator }, /* $2a */ { "", 1, flIllegal, OH_Illegal, }, /* $2b */ { "bit", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2c */ { "and", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2d */ { "rol", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2e */ { "bbr2", 3, flUseLabel, OH_BitBranch }, /* $2f */ { "bmi", 2, flLabel, OH_Relative }, /* $30 */ { "and", 2, flUseLabel, OH_DirectIndirectY }, /* $31 */ { "and", 2, flUseLabel, OH_DirectIndirect, }, /* $32 */ { "", 1, flIllegal, OH_Illegal, }, /* $33 */ { "bit", 2, flUseLabel, OH_DirectX }, /* $34 */ { "and", 2, flUseLabel, OH_DirectX }, /* $35 */ { "rol", 2, flUseLabel, OH_DirectX }, /* $36 */ { "rmb3", 1, flUseLabel, OH_Direct, }, /* $37 */ { "sec", 1, flNone, OH_Implicit }, /* $38 */ { "and", 3, flUseLabel, OH_AbsoluteY }, /* $39 */ { "dec", 1, flNone, OH_Accumulator }, /* $3a */ { "", 1, flIllegal, OH_Illegal, }, /* $3b */ { "bit", 3, flUseLabel, OH_AbsoluteX }, /* $3c */ { "and", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3d */ { "rol", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3e */ { "bbr3", 3, flUseLabel, OH_BitBranch }, /* $3f */ { "rti", 1, flNone, OH_Rts }, /* $40 */ { "eor", 2, flUseLabel, OH_DirectXIndirect }, /* $41 */ { "say", 1, flNone, OH_Implicit, }, /* $42 */ { "tmai", 2, flNone, OH_Immediate, }, /* $43 */ { "bsr", 2, flLabel, OH_Relative, }, /* $44 */ { "eor", 2, flUseLabel, OH_Direct }, /* $45 */ { "lsr", 2, flUseLabel, OH_Direct }, /* $46 */ { "rmb4", 1, flUseLabel, OH_Direct, }, /* $47 */ { "pha", 1, flNone, OH_Implicit }, /* $48 */ { "eor", 2, flNone, OH_Immediate }, /* $49 */ { "lsr", 1, flNone, OH_Accumulator }, /* $4a */ { "", 1, flIllegal, OH_Illegal, }, /* $4b */ { "jmp", 3, flLabel, OH_JmpAbsolute }, /* $4c */ { "eor", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4e */ { "bbr4", 3, flUseLabel, OH_BitBranch }, /* $4f */ { "bvc", 2, flLabel, OH_Relative }, /* $50 */ { "eor", 2, flUseLabel, OH_DirectIndirectY }, /* $51 */ { "eor", 2, flUseLabel, OH_DirectIndirect }, /* $52 */ { "tami", 2, flNone, OH_Immediate, }, /* $53 */ { "csl", 1, flNone, OH_Implicit, }, /* $54 */ { "eor", 2, flUseLabel, OH_DirectX }, /* $55 */ { "lsr", 2, flUseLabel, OH_DirectX }, /* $56 */ { "rmb5", 1, flUseLabel, OH_Direct, }, /* $57 */ { "cli", 1, flNone, OH_Implicit }, /* $58 */ { "eor", 3, flUseLabel, OH_AbsoluteY }, /* $59 */ { "phy", 1, flNone, OH_Implicit }, /* $5a */ { "", 1, flIllegal, OH_Illegal, }, /* $5b */ { "", 1, flIllegal, OH_Illegal, }, /* $5c */ { "eor", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5e */ { "bbr5", 3, flUseLabel, OH_BitBranch }, /* $5f */ { "rts", 1, flNone, OH_Rts }, /* $60 */ { "adc", 2, flUseLabel, OH_DirectXIndirect }, /* $61 */ { "cla", 1, flNone, OH_Implicit, }, /* $62 */ { "", 1, flIllegal, OH_Illegal, }, /* $63 */ { "stz", 2, flUseLabel, OH_Direct }, /* $64 */ { "adc", 2, flUseLabel, OH_Direct }, /* $65 */ { "ror", 2, flUseLabel, OH_Direct }, /* $66 */ { "rmb6", 1, flUseLabel, OH_Direct, }, /* $67 */ { "pla", 1, flNone, OH_Implicit }, /* $68 */ { "adc", 2, flNone, OH_Immediate }, /* $69 */ { "ror", 1, flNone, OH_Accumulator }, /* $6a */ { "", 1, flIllegal, OH_Illegal, }, /* $6b */ { "jmp", 3, flLabel, OH_JmpAbsoluteIndirect }, /* $6c */ { "adc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6d */ { "ror", 3, flUseLabel, OH_Absolute }, /* $6e */ { "bbr6", 3, flUseLabel, OH_BitBranch }, /* $6f */ { "bvs", 2, flLabel, OH_Relative }, /* $70 */ { "adc", 2, flUseLabel, OH_DirectIndirectY }, /* $71 */ { "adc", 2, flUseLabel, OH_DirectIndirect, }, /* $72 */ { "tii", 7, flNone, OH_BlockMove, }, /* $73 */ { "stz", 2, flUseLabel, OH_DirectX }, /* $74 */ { "adc", 2, flUseLabel, OH_DirectX }, /* $75 */ { "ror", 2, flUseLabel, OH_DirectX }, /* $76 */ { "rmb7", 1, flUseLabel, OH_Direct, }, /* $77 */ { "sei", 1, flNone, OH_Implicit }, /* $78 */ { "adc", 3, flUseLabel, OH_AbsoluteY }, /* $79 */ { "ply", 1, flNone, OH_Implicit }, /* $7a */ { "", 1, flIllegal, OH_Illegal, }, /* $7b */ { "jmp", 3, flLabel, OH_AbsoluteXIndirect }, /* $7c */ { "adc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7d */ { "ror", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7e */ { "bbr7", 3, flUseLabel, OH_BitBranch }, /* $7f */ { "bra", 2, flLabel, OH_Relative }, /* $80 */ { "sta", 2, flUseLabel, OH_DirectXIndirect }, /* $81 */ { "clx", 1, flNone, OH_Implicit, }, /* $82 */ { "tst", 3, flNone, OH_ImmediateDirect, }, /* $83 */ { "sty", 2, flUseLabel, OH_Direct }, /* $84 */ { "sta", 2, flUseLabel, OH_Direct }, /* $85 */ { "stx", 2, flUseLabel, OH_Direct }, /* $86 */ { "smb0", 1, flUseLabel, OH_Direct, }, /* $87 */ { "dey", 1, flNone, OH_Implicit }, /* $88 */ { "bit", 2, flNone, OH_Immediate }, /* $89 */ { "txa", 1, flNone, OH_Implicit }, /* $8a */ { "", 1, flIllegal, OH_Illegal, }, /* $8b */ { "sty", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8c */ { "sta", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8d */ { "stx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8e */ { "bbs0", 3, flUseLabel, OH_BitBranch }, /* $8f */ { "bcc", 2, flLabel, OH_Relative }, /* $90 */ { "sta", 2, flUseLabel, OH_DirectIndirectY }, /* $91 */ { "sta", 2, flUseLabel, OH_DirectIndirect }, /* $92 */ { "tst", 4, flNone, OH_ImmediateAbsolute, }, /* $93 */ { "sty", 2, flUseLabel, OH_DirectX }, /* $94 */ { "sta", 2, flUseLabel, OH_DirectX }, /* $95 */ { "stx", 2, flUseLabel, OH_DirectY }, /* $96 */ { "smb1", 1, flUseLabel, OH_Direct, }, /* $97 */ { "tya", 1, flNone, OH_Implicit }, /* $98 */ { "sta", 3, flUseLabel, OH_AbsoluteY }, /* $99 */ { "txs", 1, flNone, OH_Implicit }, /* $9a */ { "", 1, flIllegal, OH_Illegal, }, /* $9b */ { "stz", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $9c */ { "sta", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $9d */ { "stz", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $9e */ { "bbs1", 3, flUseLabel, OH_BitBranch }, /* $9f */ { "ldy", 2, flNone, OH_Immediate }, /* $a0 */ { "lda", 2, flUseLabel, OH_DirectXIndirect }, /* $a1 */ { "ldx", 2, flNone, OH_Immediate }, /* $a2 */ { "tst", 3, flNone, OH_ImmediateDirectX, }, /* $a3 */ { "ldy", 2, flUseLabel, OH_Direct }, /* $a4 */ { "lda", 2, flUseLabel, OH_Direct }, /* $a5 */ { "ldx", 2, flUseLabel, OH_Direct }, /* $a6 */ { "smb2", 1, flUseLabel, OH_Direct, }, /* $a7 */ { "tay", 1, flNone, OH_Implicit }, /* $a8 */ { "lda", 2, flNone, OH_Immediate }, /* $a9 */ { "tax", 1, flNone, OH_Implicit }, /* $aa */ { "", 1, flIllegal, OH_Illegal, }, /* $ab */ { "ldy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ac */ { "lda", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ad */ { "ldx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ae */ { "bbs2", 3, flUseLabel, OH_BitBranch }, /* $af */ { "bcs", 2, flLabel, OH_Relative }, /* $b0 */ { "lda", 2, flUseLabel, OH_DirectIndirectY }, /* $b1 */ { "lda", 2, flUseLabel, OH_DirectIndirect }, /* $b2 */ { "tst", 4, flNone, OH_ImmediateAbsoluteX, }, /* $b3 */ { "ldy", 2, flUseLabel, OH_DirectX }, /* $b4 */ { "lda", 2, flUseLabel, OH_DirectX }, /* $b5 */ { "ldx", 2, flUseLabel, OH_DirectY }, /* $b6 */ { "smb3", 1, flUseLabel, OH_Direct, }, /* $b7 */ { "clv", 1, flNone, OH_Implicit }, /* $b8 */ { "lda", 3, flUseLabel, OH_AbsoluteY }, /* $b9 */ { "tsx", 1, flNone, OH_Implicit }, /* $ba */ { "", 1, flIllegal, OH_Illegal, }, /* $bb */ { "ldy", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bc */ { "lda", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bd */ { "ldx", 3, flUseLabel|flAbsOverride, OH_AbsoluteY }, /* $be */ { "bbs3", 3, flUseLabel, OH_BitBranch }, /* $bf */ { "cpy", 2, flNone, OH_Immediate }, /* $c0 */ { "cmp", 2, flUseLabel, OH_DirectXIndirect }, /* $c1 */ { "cly", 1, flNone, OH_Implicit, }, /* $c2 */ { "tdd", 7, flNone, OH_BlockMove, }, /* $c3 */ { "cpy", 2, flUseLabel, OH_Direct }, /* $c4 */ { "cmp", 2, flUseLabel, OH_Direct }, /* $c5 */ { "dec", 2, flUseLabel, OH_Direct }, /* $c6 */ { "smb4", 1, flUseLabel, OH_Direct, }, /* $c7 */ { "iny", 1, flNone, OH_Implicit }, /* $c8 */ { "cmp", 2, flNone, OH_Immediate }, /* $c9 */ { "dex", 1, flNone, OH_Implicit }, /* $ca */ { "", 1, flIllegal, OH_Illegal, }, /* $cb */ { "cpy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cd */ { "dec", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ce */ { "bbs4", 3, flUseLabel, OH_BitBranch }, /* $cf */ { "bne", 2, flLabel, OH_Relative }, /* $d0 */ { "cmp", 2, flUseLabel, OH_DirectIndirectY }, /* $d1 */ { "cmp", 2, flUseLabel, OH_DirectIndirect }, /* $d2 */ { "tin", 7, flNone, OH_BlockMove, }, /* $d3 */ { "csh", 1, flNone, OH_Implicit, }, /* $d4 */ { "cmp", 2, flUseLabel, OH_DirectX }, /* $d5 */ { "dec", 2, flUseLabel, OH_DirectX }, /* $d6 */ { "smb5", 1, flUseLabel, OH_Direct, }, /* $d7 */ { "cld", 1, flNone, OH_Implicit }, /* $d8 */ { "cmp", 3, flUseLabel, OH_AbsoluteY }, /* $d9 */ { "phx", 1, flNone, OH_Implicit }, /* $da */ { "", 1, flIllegal, OH_Illegal, }, /* $db */ { "", 1, flIllegal, OH_Illegal, }, /* $dc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $dd */ { "dec", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $de */ { "bbs5", 3, flUseLabel, OH_BitBranch }, /* $df */ { "cpx", 2, flNone, OH_Immediate }, /* $e0 */ { "sbc", 2, flUseLabel, OH_DirectXIndirect }, /* $e1 */ { "", 1, flIllegal, OH_Illegal, }, /* $e2 */ { "tia", 7, flNone, OH_BlockMove, }, /* $e3 */ { "cpx", 2, flUseLabel, OH_Direct }, /* $e4 */ { "sbc", 2, flUseLabel, OH_Direct }, /* $e5 */ { "inc", 2, flUseLabel, OH_Direct }, /* $e6 */ { "smb6", 1, flUseLabel, OH_Direct, }, /* $e7 */ { "inx", 1, flNone, OH_Implicit }, /* $e8 */ { "sbc", 2, flNone, OH_Immediate }, /* $e9 */ { "nop", 1, flNone, OH_Implicit }, /* $ea */ { "", 1, flIllegal, OH_Illegal, }, /* $eb */ { "cpx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ec */ { "sbc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ed */ { "inc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ee */ { "bbs6", 3, flUseLabel, OH_BitBranch }, /* $ef */ { "beq", 2, flLabel, OH_Relative }, /* $f0 */ { "sbc", 2, flUseLabel, OH_DirectIndirectY }, /* $f1 */ { "sbc", 2, flUseLabel, OH_DirectIndirect }, /* $f2 */ { "tai", 7, flNone, OH_BlockMove, }, /* $f3 */ { "set", 1, flNone, OH_Implicit, }, /* $f4 */ { "sbc", 2, flUseLabel, OH_DirectX }, /* $f5 */ { "inc", 2, flUseLabel, OH_DirectX }, /* $f6 */ { "smb7", 1, flUseLabel, OH_Direct, }, /* $f7 */ { "sed", 1, flNone, OH_Implicit }, /* $f8 */ { "sbc", 3, flUseLabel, OH_AbsoluteY }, /* $f9 */ { "plx", 1, flNone, OH_Implicit }, /* $fa */ { "", 1, flIllegal, OH_Illegal, }, /* $fb */ { "", 1, flIllegal, OH_Illegal, }, /* $fc */ { "sbc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fd */ { "inc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fe */ { "bbs7", 3, flUseLabel, OH_BitBranch }, /* $ff */ };
977
./cc65/src/da65/labels.c
/*****************************************************************************/ /* */ /* labels.c */ /* */ /* Label management for da65 */ /* */ /* */ /* */ /* (C) 2006-2007 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> /* common */ #include "xmalloc.h" #include "xsprintf.h" /* da65 */ #include "attrtab.h" #include "code.h" #include "comments.h" #include "error.h" #include "global.h" #include "labels.h" #include "output.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Symbol table */ static const char* SymTab[0x10000]; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static const char* MakeLabelName (unsigned Addr) /* Make the default label name from the given address and return it in a * static buffer. */ { static char LabelBuf [32]; xsprintf (LabelBuf, sizeof (LabelBuf), "L%04X", Addr); return LabelBuf; } static void AddLabel (unsigned Addr, attr_t Attr, const char* Name) /* Add a label */ { /* Get an existing label attribute */ attr_t ExistingAttr = GetLabelAttr (Addr); /* Must not have two symbols for one address */ if (ExistingAttr != atNoLabel) { /* Allow redefinition if identical. Beware: Unnamed labels don't * have a name (you guessed that, didn't you?). */ if (ExistingAttr == Attr && ((Name == 0 && SymTab[Addr] == 0) || strcmp (SymTab[Addr], Name) == 0)) { return; } Error ("Duplicate label for address $%04X: %s/%s", Addr, SymTab[Addr], Name); } /* Create a new label (xstrdup will return NULL if input NULL) */ SymTab[Addr] = xstrdup (Name); /* Remember the attribute */ MarkAddr (Addr, Attr); } void AddIntLabel (unsigned Addr) /* Add an internal label using the address to generate the name. */ { AddLabel (Addr, atIntLabel, MakeLabelName (Addr)); } void AddExtLabel (unsigned Addr, const char* Name) /* Add an external label */ { AddLabel (Addr, atExtLabel, Name); } void AddUnnamedLabel (unsigned Addr) /* Add an unnamed label */ { AddLabel (Addr, atUnnamedLabel, 0); } void AddDepLabel (unsigned Addr, attr_t Attr, const char* BaseName, unsigned Offs) /* Add a dependent label at the given address using "basename+Offs" as the new * name. */ { /* Allocate memory for the dependent label name */ unsigned NameLen = strlen (BaseName); char* DepName = xmalloc (NameLen + 7); /* "+$ABCD\0" */ /* Create the new name in the buffer */ if (UseHexOffs) { sprintf (DepName, "%s+$%02X", BaseName, Offs); } else { sprintf (DepName, "%s+%u", BaseName, Offs); } /* Define the labels */ AddLabel (Addr, Attr | atDepLabel, DepName); /* Free the name buffer */ xfree (DepName); } static void AddLabelRange (unsigned Addr, attr_t Attr, const char* Name, unsigned Count) /* Add a label for a range. The first entry gets the label "Name" while the * others get "Name+offs". */ { /* Define the label */ AddLabel (Addr, Attr, Name); /* Define dependent labels if necessary */ if (Count > 1) { unsigned Offs; /* Setup the format string */ const char* Format = UseHexOffs? "$%02X" : "%u"; /* Allocate memory for the dependent label names */ unsigned NameLen = strlen (Name); char* DepName = xmalloc (NameLen + 7); /* "+$ABCD" */ char* DepOffs = DepName + NameLen + 1; /* Copy the original name into the buffer */ memcpy (DepName, Name, NameLen); DepName[NameLen] = '+'; /* Define the labels */ for (Offs = 1; Offs < Count; ++Offs) { sprintf (DepOffs, Format, Offs); AddLabel (Addr + Offs, Attr | atDepLabel, DepName); } /* Free the name buffer */ xfree (DepName); } } void AddIntLabelRange (unsigned Addr, const char* Name, unsigned Count) /* Add an internal label for a range. The first entry gets the label "Name" * while the others get "Name+offs". */ { /* Define the label range */ AddLabelRange (Addr, atIntLabel, Name, Count); } void AddExtLabelRange (unsigned Addr, const char* Name, unsigned Count) /* Add an external label for a range. The first entry gets the label "Name" * while the others get "Name+offs". */ { /* Define the label range */ AddLabelRange (Addr, atExtLabel, Name, Count); } int HaveLabel (unsigned Addr) /* Check if there is a label for the given address */ { /* Check for a label */ return (GetLabelAttr (Addr) != atNoLabel); } int MustDefLabel (unsigned Addr) /* Return true if we must define a label for this address, that is, if there * is a label at this address, and it is an external or internal label. */ { /* Get the label attribute */ attr_t A = GetLabelAttr (Addr); /* Check for an internal, external, or unnamed label */ return (A == atExtLabel || A == atIntLabel || A == atUnnamedLabel); } const char* GetLabelName (unsigned Addr) /* Return the label name for an address */ { /* Get the label attribute */ attr_t A = GetLabelAttr (Addr); /* Special case unnamed labels, because these don't have a named stored in * the symbol table to save space. */ if (A == atUnnamedLabel) { return ""; } else { /* Return the label if any */ return SymTab[Addr]; } } const char* GetLabel (unsigned Addr, unsigned RefFrom) /* Return the label name for an address, as it is used in a label reference. * RefFrom is the address the label is referenced from. This is needed in case * of unnamed labels, to determine the name. */ { static const char* FwdLabels[] = { ":+", ":++", ":+++", ":++++", ":+++++", ":++++++", ":+++++++", ":++++++++", ":+++++++++", ":++++++++++" }; static const char* BackLabels[] = { ":-", ":--", ":---", ":----", ":-----", ":------", ":-------", ":--------", ":---------", ":----------" }; /* Get the label attribute */ attr_t A = GetLabelAttr (Addr); /* Special case unnamed labels, because these don't have a named stored in * the symbol table to save space. */ if (A == atUnnamedLabel) { unsigned Count = 0; /* Search forward or backward depending in which direction the label * is. */ if (Addr <= RefFrom) { /* Search backwards */ unsigned I = RefFrom; while (Addr < I) { --I; A = GetLabelAttr (I); if (A == atUnnamedLabel) { ++Count; if (Count >= sizeof (BackLabels) / sizeof (BackLabels[0])) { Error ("Too many unnamed labels between label at " "$%04X and reference at $%04X", Addr, RefFrom); } } } /* Return the label name */ return BackLabels[Count-1]; } else { /* Search forwards */ unsigned I = RefFrom; while (Addr > I) { ++I; A = GetLabelAttr (I); if (A == atUnnamedLabel) { ++Count; if (Count >= sizeof (FwdLabels) / sizeof (FwdLabels[0])) { Error ("Too many unnamed labels between label at " "$%04X and reference at $%04X", Addr, RefFrom); } } } /* Return the label name */ return FwdLabels[Count-1]; } } else { /* Return the label if any */ return SymTab[Addr]; } } void ForwardLabel (unsigned Offs) /* If necessary, output a forward label, one that is within the next few * bytes and is therefore output as "label = * + x". */ { /* Calculate the actual address */ unsigned long Addr = PC + Offs; /* Get the type of the label */ attr_t A = GetLabelAttr (Addr); /* If there is no label, or just a dependent one, bail out */ if (A == atNoLabel || (A & atDepLabel) != 0) { return; } /* An unnamed label cannot be output as a forward declaration, so this is * an error. */ if (A == atUnnamedLabel) { Error ("Cannot define unnamed label at address $%04lX", Addr); } /* Output the label */ DefForward (GetLabelName (Addr), GetComment (Addr), Offs); } static void DefOutOfRangeLabel (unsigned long Addr) /* Define one label that is outside code range. */ { switch (GetLabelAttr (Addr)) { case atIntLabel: case atExtLabel: DefConst (SymTab[Addr], GetComment (Addr), Addr); break; case atUnnamedLabel: Error ("Cannot define unnamed label at address $%04lX", Addr); break; default: break; } } void DefOutOfRangeLabels (void) /* Output any labels that are out of the loaded code range */ { unsigned long Addr; SeparatorLine (); /* Low range */ Addr = 0; while (Addr < CodeStart) { DefOutOfRangeLabel (Addr++); } /* Skip areas in code range */ while (Addr <= CodeEnd) { if (GetStyleAttr (Addr) == atSkip) { DefOutOfRangeLabel (Addr); } ++Addr; } /* High range */ while (Addr < 0x10000) { DefOutOfRangeLabel (Addr++); } SeparatorLine (); }
978
./cc65/src/da65/opc6502.c
/*****************************************************************************/ /* */ /* opc6502.c */ /* */ /* 6502 opcode description table */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* da65 */ #include "handler.h" #include "opc6502.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Descriptions for all opcodes */ const OpcDesc OpcTable_6502[256] = { { "brk", 1, flNone, OH_Implicit }, /* $00 */ { "ora", 2, flUseLabel, OH_DirectXIndirect }, /* $01 */ { "", 1, flIllegal, OH_Illegal, }, /* $02 */ { "", 1, flIllegal, OH_Illegal, }, /* $03 */ { "", 1, flIllegal, OH_Illegal, }, /* $04 */ { "ora", 2, flUseLabel, OH_Direct }, /* $05 */ { "asl", 2, flUseLabel, OH_Direct }, /* $06 */ { "", 1, flIllegal, OH_Illegal, }, /* $07 */ { "php", 1, flNone, OH_Implicit }, /* $08 */ { "ora", 2, flNone, OH_Immediate }, /* $09 */ { "asl", 1, flNone, OH_Accumulator }, /* $0a */ { "", 1, flIllegal, OH_Illegal, }, /* $0b */ { "", 1, flIllegal, OH_Illegal, }, /* $0c */ { "ora", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0d */ { "asl", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0e */ { "", 1, flIllegal, OH_Illegal, }, /* $0f */ { "bpl", 2, flLabel, OH_Relative }, /* $10 */ { "ora", 2, flUseLabel, OH_DirectIndirectY }, /* $11 */ { "", 1, flIllegal, OH_Illegal, }, /* $12 */ { "", 1, flIllegal, OH_Illegal, }, /* $13 */ { "", 1, flIllegal, OH_Illegal, }, /* $14 */ { "ora", 2, flUseLabel, OH_DirectX }, /* $15 */ { "asl", 2, flUseLabel, OH_DirectX }, /* $16 */ { "", 1, flIllegal, OH_Illegal, }, /* $17 */ { "clc", 1, flNone, OH_Implicit }, /* $18 */ { "ora", 3, flUseLabel, OH_AbsoluteY }, /* $19 */ { "", 1, flIllegal, OH_Illegal, }, /* $1a */ { "", 1, flIllegal, OH_Illegal, }, /* $1b */ { "", 1, flIllegal, OH_Illegal, }, /* $1c */ { "ora", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1d */ { "asl", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1e */ { "", 1, flIllegal, OH_Illegal, }, /* $1f */ { "jsr", 3, flLabel, OH_Absolute }, /* $20 */ { "and", 2, flUseLabel, OH_DirectXIndirect }, /* $21 */ { "", 1, flIllegal, OH_Illegal, }, /* $22 */ { "", 1, flIllegal, OH_Illegal, }, /* $23 */ { "bit", 2, flUseLabel, OH_Direct }, /* $24 */ { "and", 2, flUseLabel, OH_Direct }, /* $25 */ { "rol", 2, flUseLabel, OH_Direct }, /* $26 */ { "", 1, flIllegal, OH_Illegal, }, /* $27 */ { "plp", 1, flNone, OH_Implicit }, /* $28 */ { "and", 2, flNone, OH_Immediate }, /* $29 */ { "rol", 1, flNone, OH_Accumulator }, /* $2a */ { "", 1, flIllegal, OH_Illegal, }, /* $2b */ { "bit", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2c */ { "and", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2d */ { "rol", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2e */ { "", 1, flIllegal, OH_Illegal, }, /* $2f */ { "bmi", 2, flLabel, OH_Relative }, /* $30 */ { "and", 2, flUseLabel, OH_DirectIndirectY }, /* $31 */ { "", 1, flIllegal, OH_Illegal, }, /* $32 */ { "", 1, flIllegal, OH_Illegal, }, /* $33 */ { "", 1, flIllegal, OH_Illegal, }, /* $34 */ { "and", 2, flUseLabel, OH_DirectX }, /* $35 */ { "rol", 2, flUseLabel, OH_DirectX }, /* $36 */ { "", 1, flIllegal, OH_Illegal, }, /* $37 */ { "sec", 1, flNone, OH_Implicit }, /* $38 */ { "and", 3, flUseLabel, OH_AbsoluteY }, /* $39 */ { "", 1, flIllegal, OH_Illegal, }, /* $3a */ { "", 1, flIllegal, OH_Illegal, }, /* $3b */ { "", 1, flIllegal, OH_Illegal, }, /* $3c */ { "and", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3d */ { "rol", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3e */ { "", 1, flIllegal, OH_Illegal, }, /* $3f */ { "rti", 1, flNone, OH_Rts }, /* $40 */ { "eor", 2, flUseLabel, OH_DirectXIndirect }, /* $41 */ { "", 1, flIllegal, OH_Illegal, }, /* $42 */ { "", 1, flIllegal, OH_Illegal, }, /* $43 */ { "", 1, flIllegal, OH_Illegal, }, /* $44 */ { "eor", 2, flUseLabel, OH_Direct }, /* $45 */ { "lsr", 2, flUseLabel, OH_Direct }, /* $46 */ { "", 1, flIllegal, OH_Illegal, }, /* $47 */ { "pha", 1, flNone, OH_Implicit }, /* $48 */ { "eor", 2, flNone, OH_Immediate }, /* $49 */ { "lsr", 1, flNone, OH_Accumulator }, /* $4a */ { "", 1, flIllegal, OH_Illegal, }, /* $4b */ { "jmp", 3, flLabel, OH_JmpAbsolute }, /* $4c */ { "eor", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4e */ { "", 1, flIllegal, OH_Illegal, }, /* $4f */ { "bvc", 2, flLabel, OH_Relative }, /* $50 */ { "eor", 2, flUseLabel, OH_DirectIndirectY }, /* $51 */ { "", 1, flIllegal, OH_Illegal, }, /* $52 */ { "", 1, flIllegal, OH_Illegal, }, /* $53 */ { "", 1, flIllegal, OH_Illegal, }, /* $54 */ { "eor", 2, flUseLabel, OH_DirectX }, /* $55 */ { "lsr", 2, flUseLabel, OH_DirectX }, /* $56 */ { "", 1, flIllegal, OH_Illegal, }, /* $57 */ { "cli", 1, flNone, OH_Implicit }, /* $58 */ { "eor", 3, flUseLabel, OH_AbsoluteY }, /* $59 */ { "", 1, flIllegal, OH_Illegal, }, /* $5a */ { "", 1, flIllegal, OH_Illegal, }, /* $5b */ { "", 1, flIllegal, OH_Illegal, }, /* $5c */ { "eor", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5e */ { "", 1, flIllegal, OH_Illegal, }, /* $5f */ { "rts", 1, flNone, OH_Rts }, /* $60 */ { "adc", 2, flUseLabel, OH_DirectXIndirect }, /* $61 */ { "", 1, flIllegal, OH_Illegal, }, /* $62 */ { "", 1, flIllegal, OH_Illegal, }, /* $63 */ { "", 1, flIllegal, OH_Illegal, }, /* $64 */ { "adc", 2, flUseLabel, OH_Direct }, /* $65 */ { "ror", 2, flUseLabel, OH_Direct }, /* $66 */ { "", 1, flIllegal, OH_Illegal, }, /* $67 */ { "pla", 1, flNone, OH_Implicit }, /* $68 */ { "adc", 2, flNone, OH_Immediate }, /* $69 */ { "ror", 1, flNone, OH_Accumulator }, /* $6a */ { "", 1, flIllegal, OH_Illegal, }, /* $6b */ { "jmp", 3, flLabel, OH_JmpAbsoluteIndirect }, /* $6c */ { "adc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6d */ { "ror", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6e */ { "", 1, flIllegal, OH_Illegal, }, /* $6f */ { "bvs", 2, flLabel, OH_Relative }, /* $70 */ { "adc", 2, flUseLabel, OH_DirectIndirectY }, /* $71 */ { "", 1, flIllegal, OH_Illegal, }, /* $72 */ { "", 1, flIllegal, OH_Illegal, }, /* $73 */ { "", 1, flIllegal, OH_Illegal, }, /* $74 */ { "adc", 2, flUseLabel, OH_DirectX }, /* $75 */ { "ror", 2, flUseLabel, OH_DirectX }, /* $76 */ { "", 1, flIllegal, OH_Illegal, }, /* $77 */ { "sei", 1, flNone, OH_Implicit }, /* $78 */ { "adc", 3, flUseLabel, OH_AbsoluteY }, /* $79 */ { "", 1, flIllegal, OH_Illegal, }, /* $7a */ { "", 1, flIllegal, OH_Illegal, }, /* $7b */ { "", 1, flIllegal, OH_Illegal, }, /* $7c */ { "adc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7d */ { "ror", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7e */ { "", 1, flIllegal, OH_Illegal, }, /* $7f */ { "", 1, flIllegal, OH_Illegal, }, /* $80 */ { "sta", 2, flUseLabel, OH_DirectXIndirect }, /* $81 */ { "", 1, flIllegal, OH_Illegal, }, /* $82 */ { "", 1, flIllegal, OH_Illegal, }, /* $83 */ { "sty", 2, flUseLabel, OH_Direct }, /* $84 */ { "sta", 2, flUseLabel, OH_Direct }, /* $85 */ { "stx", 2, flUseLabel, OH_Direct }, /* $86 */ { "", 1, flIllegal, OH_Illegal, }, /* $87 */ { "dey", 1, flNone, OH_Implicit }, /* $88 */ { "", 1, flIllegal, OH_Illegal, }, /* $89 */ { "txa", 1, flNone, OH_Implicit }, /* $8a */ { "", 1, flIllegal, OH_Illegal, }, /* $8b */ { "sty", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8c */ { "sta", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8d */ { "stx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8e */ { "", 1, flIllegal, OH_Illegal, }, /* $8f */ { "bcc", 2, flLabel, OH_Relative }, /* $90 */ { "sta", 2, flUseLabel, OH_DirectIndirectY }, /* $91 */ { "", 1, flIllegal, OH_Illegal, }, /* $92 */ { "", 1, flIllegal, OH_Illegal, }, /* $93 */ { "sty", 2, flUseLabel, OH_DirectX }, /* $94 */ { "sta", 2, flUseLabel, OH_DirectX }, /* $95 */ { "stx", 2, flUseLabel, OH_DirectY }, /* $96 */ { "", 1, flIllegal, OH_Illegal, }, /* $97 */ { "tya", 1, flNone, OH_Implicit }, /* $98 */ { "sta", 3, flUseLabel, OH_AbsoluteY }, /* $99 */ { "txs", 1, flNone, OH_Implicit }, /* $9a */ { "", 1, flIllegal, OH_Illegal, }, /* $9b */ { "", 1, flIllegal, OH_Illegal, }, /* $9c */ { "sta", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $9d */ { "", 1, flIllegal, OH_Illegal, }, /* $9e */ { "", 1, flIllegal, OH_Illegal, }, /* $9f */ { "ldy", 2, flNone, OH_Immediate }, /* $a0 */ { "lda", 2, flUseLabel, OH_DirectXIndirect }, /* $a1 */ { "ldx", 2, flNone, OH_Immediate }, /* $a2 */ { "", 1, flIllegal, OH_Illegal, }, /* $a3 */ { "ldy", 2, flUseLabel, OH_Direct }, /* $a4 */ { "lda", 2, flUseLabel, OH_Direct }, /* $a5 */ { "ldx", 2, flUseLabel, OH_Direct }, /* $a6 */ { "", 1, flIllegal, OH_Illegal, }, /* $a7 */ { "tay", 1, flNone, OH_Implicit }, /* $a8 */ { "lda", 2, flNone, OH_Immediate }, /* $a9 */ { "tax", 1, flNone, OH_Implicit }, /* $aa */ { "", 1, flIllegal, OH_Illegal, }, /* $ab */ { "ldy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ac */ { "lda", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ad */ { "ldx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ae */ { "", 1, flIllegal, OH_Illegal, }, /* $af */ { "bcs", 2, flLabel, OH_Relative }, /* $b0 */ { "lda", 2, flUseLabel, OH_DirectIndirectY }, /* $b1 */ { "", 1, flIllegal, OH_Illegal, }, /* $b2 */ { "", 1, flIllegal, OH_Illegal, }, /* $b3 */ { "ldy", 2, flUseLabel, OH_DirectX }, /* $b4 */ { "lda", 2, flUseLabel, OH_DirectX }, /* $b5 */ { "ldx", 2, flUseLabel, OH_DirectY }, /* $b6 */ { "", 1, flIllegal, OH_Illegal, }, /* $b7 */ { "clv", 1, flNone, OH_Implicit }, /* $b8 */ { "lda", 3, flUseLabel, OH_AbsoluteY }, /* $b9 */ { "tsx", 1, flNone, OH_Implicit }, /* $ba */ { "", 1, flIllegal, OH_Illegal, }, /* $bb */ { "ldy", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bc */ { "lda", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bd */ { "ldx", 3, flUseLabel|flAbsOverride, OH_AbsoluteY }, /* $be */ { "", 1, flIllegal, OH_Illegal, }, /* $bf */ { "cpy", 2, flNone, OH_Immediate }, /* $c0 */ { "cmp", 2, flUseLabel, OH_DirectXIndirect }, /* $c1 */ { "", 1, flIllegal, OH_Illegal, }, /* $c2 */ { "", 1, flIllegal, OH_Illegal, }, /* $c3 */ { "cpy", 2, flUseLabel, OH_Direct }, /* $c4 */ { "cmp", 2, flUseLabel, OH_Direct }, /* $c5 */ { "dec", 2, flUseLabel, OH_Direct }, /* $c6 */ { "", 1, flIllegal, OH_Illegal, }, /* $c7 */ { "iny", 1, flNone, OH_Implicit }, /* $c8 */ { "cmp", 2, flNone, OH_Immediate }, /* $c9 */ { "dex", 1, flNone, OH_Implicit }, /* $ca */ { "", 1, flIllegal, OH_Illegal, }, /* $cb */ { "cpy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cd */ { "dec", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ce */ { "", 1, flIllegal, OH_Illegal, }, /* $cf */ { "bne", 2, flLabel, OH_Relative }, /* $d0 */ { "cmp", 2, flUseLabel, OH_DirectIndirectY }, /* $d1 */ { "", 1, flIllegal, OH_Illegal, }, /* $d2 */ { "", 1, flIllegal, OH_Illegal, }, /* $d3 */ { "", 1, flIllegal, OH_Illegal, }, /* $d4 */ { "cmp", 2, flUseLabel, OH_DirectX }, /* $d5 */ { "dec", 2, flUseLabel, OH_DirectX }, /* $d6 */ { "", 1, flIllegal, OH_Illegal, }, /* $d7 */ { "cld", 1, flNone, OH_Implicit }, /* $d8 */ { "cmp", 3, flUseLabel, OH_AbsoluteY }, /* $d9 */ { "", 1, flIllegal, OH_Illegal, }, /* $da */ { "", 1, flIllegal, OH_Illegal, }, /* $db */ { "", 1, flIllegal, OH_Illegal, }, /* $dc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $dd */ { "dec", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $de */ { "", 1, flIllegal, OH_Illegal, }, /* $df */ { "cpx", 2, flNone, OH_Immediate }, /* $e0 */ { "sbc", 2, flUseLabel, OH_DirectXIndirect }, /* $e1 */ { "", 1, flIllegal, OH_Illegal, }, /* $e2 */ { "", 1, flIllegal, OH_Illegal, }, /* $e3 */ { "cpx", 2, flUseLabel, OH_Direct }, /* $e4 */ { "sbc", 2, flUseLabel, OH_Direct }, /* $e5 */ { "inc", 2, flUseLabel, OH_Direct }, /* $e6 */ { "", 1, flIllegal, OH_Illegal, }, /* $e7 */ { "inx", 1, flNone, OH_Implicit }, /* $e8 */ { "sbc", 2, flNone, OH_Immediate }, /* $e9 */ { "nop", 1, flNone, OH_Implicit }, /* $ea */ { "", 1, flIllegal, OH_Illegal, }, /* $eb */ { "cpx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ec */ { "sbc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ed */ { "inc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ee */ { "", 1, flIllegal, OH_Illegal, }, /* $ef */ { "beq", 2, flLabel, OH_Relative }, /* $f0 */ { "sbc", 2, flUseLabel, OH_DirectIndirectY }, /* $f1 */ { "", 1, flIllegal, OH_Illegal, }, /* $f2 */ { "", 1, flIllegal, OH_Illegal, }, /* $f3 */ { "", 1, flIllegal, OH_Illegal, }, /* $f4 */ { "sbc", 2, flUseLabel, OH_DirectX }, /* $f5 */ { "inc", 2, flUseLabel, OH_DirectX }, /* $f6 */ { "", 1, flIllegal, OH_Illegal, }, /* $f7 */ { "sed", 1, flNone, OH_Implicit }, /* $f8 */ { "sbc", 3, flUseLabel, OH_AbsoluteY }, /* $f9 */ { "", 1, flIllegal, OH_Illegal, }, /* $fa */ { "", 1, flIllegal, OH_Illegal, }, /* $fb */ { "", 1, flIllegal, OH_Illegal, }, /* $fc */ { "sbc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fd */ { "inc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fe */ { "", 1, flIllegal, OH_Illegal, }, /* $ff */ };
979
./cc65/src/da65/main.c
/*****************************************************************************/ /* */ /* main.c */ /* */ /* Main program for the da65 disassembler */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <limits.h> #include <time.h> /* common */ #include "abend.h" #include "cmdline.h" #include "cpu.h" #include "fname.h" #include "print.h" #include "version.h" /* da65 */ #include "attrtab.h" #include "code.h" #include "comments.h" #include "data.h" #include "error.h" #include "global.h" #include "infofile.h" #include "labels.h" #include "opctable.h" #include "output.h" #include "scanner.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void Usage (void) /* Print usage information and exit */ { printf ("Usage: %s [options] [inputfile]\n" "Short options:\n" " -g\t\t\tAdd debug info to object file\n" " -h\t\t\tHelp (this text)\n" " -i name\t\tSpecify an info file\n" " -o name\t\tName the output file\n" " -v\t\t\tIncrease verbosity\n" " -F\t\t\tAdd formfeeds to the output\n" " -S addr\t\tSet the start/load address\n" " -V\t\t\tPrint the disassembler version\n" "\n" "Long options:\n" " --argument-column n\tSpecify argument start column\n" " --comment-column n\tSpecify comment start column\n" " --comments n\t\tSet the comment level for the output\n" " --cpu type\t\tSet cpu type\n" " --debug-info\t\tAdd debug info to object file\n" " --formfeeds\t\tAdd formfeeds to the output\n" " --help\t\tHelp (this text)\n" " --hexoffs\t\tUse hexadecimal label offsets\n" " --info name\t\tSpecify an info file\n" " --label-break n\tAdd newline if label exceeds length n\n" " --mnemonic-column n\tSpecify mnemonic start column\n" " --pagelength n\tSet the page length for the listing\n" " --start-addr addr\tSet the start/load address\n" " --text-column n\tSpecify text start column\n" " --verbose\t\tIncrease verbosity\n" " --version\t\tPrint the disassembler version\n", ProgName); } static void RangeCheck (const char* Opt, unsigned long Val, unsigned long Min, unsigned long Max) /* Do a range check for the given option and abort if there's a range * error. */ { if (Val < Min || Val > Max) { Error ("Argument for %s outside valid range (%ld-%ld)", Opt, Min, Max); } } static unsigned long CvtNumber (const char* Arg, const char* Number) /* Convert a number from a string. Allow '$' and '0x' prefixes for hex * numbers. */ { unsigned long Val; int Converted; char BoundsCheck; /* Convert */ if (*Number == '$') { ++Number; Converted = sscanf (Number, "%lx%c", &Val, &BoundsCheck); } else { Converted = sscanf (Number, "%li%c", (long*)&Val, &BoundsCheck); } /* Check if we do really have a number */ if (Converted != 1) { Error ("Invalid number given in argument: %s\n", Arg); } /* Return the result */ return Val; } static void OptArgumentColumn (const char* Opt, const char* Arg) /* Handle the --argument-column option */ { /* Convert the argument to a number */ unsigned long Val = CvtNumber (Opt, Arg); /* Check for a valid range */ RangeCheck (Opt, Val, MIN_ACOL, MAX_ACOL); /* Use the value */ ACol = (unsigned char) Val; } static void OptBytesPerLine (const char* Opt, const char* Arg) /* Handle the --bytes-per-line option */ { /* Convert the argument to a number */ unsigned long Val = CvtNumber (Opt, Arg); /* Check for a valid range */ RangeCheck (Opt, Val, MIN_BYTESPERLINE, MAX_BYTESPERLINE); /* Use the value */ BytesPerLine = (unsigned char) Val; } static void OptCommentColumn (const char* Opt, const char* Arg) /* Handle the --comment-column option */ { /* Convert the argument to a number */ unsigned long Val = CvtNumber (Opt, Arg); /* Check for a valid range */ RangeCheck (Opt, Val, MIN_CCOL, MAX_CCOL); /* Use the value */ CCol = (unsigned char) Val; } static void OptComments (const char* Opt, const char* Arg) /* Handle the --comments option */ { /* Convert the argument to a number */ unsigned long Val = CvtNumber (Opt, Arg); /* Check for a valid range */ RangeCheck (Opt, Val, MIN_COMMENTS, MAX_COMMENTS); /* Use the value */ Comments = (unsigned char) Val; } static void OptCPU (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --cpu option */ { /* Find the CPU from the given name */ CPU = FindCPU (Arg); SetOpcTable (CPU); } static void OptDebugInfo (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Add debug info to the object file */ { DebugInfo = 1; } static void OptFormFeeds (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Add form feeds to the output */ { FormFeeds = 1; } static void OptHelp (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Print usage information and exit */ { Usage (); exit (EXIT_SUCCESS); } static void OptHexOffs (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Handle the --hexoffs option */ { UseHexOffs = 1; } static void OptInfo (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --info option */ { InfoSetName (Arg); } static void OptLabelBreak (const char* Opt, const char* Arg) /* Handle the --label-break option */ { /* Convert the argument to a number */ unsigned long Val = CvtNumber (Opt, Arg); /* Check for a valid range */ RangeCheck (Opt, Val, MIN_LABELBREAK, MAX_LABELBREAK); /* Use the value */ LBreak = (unsigned char) Val; } static void OptMnemonicColumn (const char* Opt, const char* Arg) /* Handle the --mnemonic-column option */ { /* Convert the argument to a number */ unsigned long Val = CvtNumber (Opt, Arg); /* Check for a valid range */ RangeCheck (Opt, Val, MIN_MCOL, MAX_MCOL); /* Use the value */ MCol = (unsigned char) Val; } static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --pagelength option */ { int Len = atoi (Arg); if (Len != 0) { RangeCheck (Opt, Len, MIN_PAGE_LEN, MAX_PAGE_LEN); } PageLength = Len; } static void OptStartAddr (const char* Opt, const char* Arg) /* Set the default start address */ { StartAddr = CvtNumber (Opt, Arg); } static void OptTextColumn (const char* Opt, const char* Arg) /* Handle the --text-column option */ { /* Convert the argument to a number */ unsigned long Val = CvtNumber (Opt, Arg); /* Check for a valid range */ RangeCheck (Opt, Val, MIN_TCOL, MAX_TCOL); /* Use the value */ TCol = (unsigned char) Val; } static void OptVerbose (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Increase verbosity */ { ++Verbosity; } static void OptVersion (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Print the disassembler version */ { fprintf (stderr, "da65 V%s\n", GetVersionAsString ()); } static void OneOpcode (unsigned RemainingBytes) /* Disassemble one opcode */ { /* Get the opcode from the current address */ unsigned char OPC = GetCodeByte (PC); /* Get the opcode description for the opcode byte */ const OpcDesc* D = &OpcTable[OPC]; /* Get the output style for the current PC */ attr_t Style = GetStyleAttr (PC); /* If we have a label at this address, output the label and an attached * comment, provided that we aren't in a skip area. */ if (Style != atSkip && MustDefLabel (PC)) { const char* Comment = GetComment (PC); if (Comment) { UserComment (Comment); } DefLabel (GetLabelName (PC)); } /* Check... * - ...if we have enough bytes remaining for the code at this address. * - ...if the current instruction is valid for the given CPU. * - ...if there is no label somewhere between the instruction bytes. * If any of these conditions is false, switch to data mode. */ if (Style == atDefault) { if (D->Size > RemainingBytes) { Style = atIllegal; MarkAddr (PC, Style); } else if (D->Flags & flIllegal) { Style = atIllegal; MarkAddr (PC, Style); } else { unsigned I; for (I = 1; I < D->Size; ++I) { if (HaveLabel (PC+I) || HaveSegmentChange (PC+I)) { Style = atIllegal; MarkAddr (PC, Style); break; } } } } /* Disassemble the line */ switch (Style) { case atDefault: D->Handler (D); PC += D->Size; break; case atCode: /* Beware: If we don't have enough bytes left to disassemble the * following insn, fall through to byte mode. */ if (D->Size <= RemainingBytes) { /* Output labels within the next insn */ unsigned I; for (I = 1; I < D->Size; ++I) { ForwardLabel (I); } /* Output the insn */ D->Handler (D); PC += D->Size; break; } /* FALLTHROUGH */ case atByteTab: ByteTable (); break; case atDByteTab: DByteTable (); break; case atWordTab: WordTable (); break; case atDWordTab: DWordTable (); break; case atAddrTab: AddrTable (); break; case atRtsTab: RtsTable (); break; case atTextTab: TextTable (); break; case atSkip: ++PC; break; default: DataByteLine (1); ++PC; break; } } static void OnePass (void) /* Make one pass through the code */ { unsigned Count; /* Disassemble until nothing left */ while ((Count = GetRemainingBytes()) > 0) { OneOpcode (Count); } } static void Disassemble (void) /* Disassemble the code */ { /* Pass 1 */ Pass = 1; OnePass (); Output ("---------------------------"); LineFeed (); /* Pass 2 */ Pass = 2; ResetCode (); OutputSettings (); DefOutOfRangeLabels (); OnePass (); } int main (int argc, char* argv []) /* Assembler main program */ { /* Program long options */ static const LongOpt OptTab[] = { { "--argument-column", 1, OptArgumentColumn }, { "--bytes-per-line", 1, OptBytesPerLine }, { "--comment-column", 1, OptCommentColumn }, { "--comments", 1, OptComments }, { "--cpu", 1, OptCPU }, { "--debug-info", 0, OptDebugInfo }, { "--formfeeds", 0, OptFormFeeds }, { "--help", 0, OptHelp }, { "--hexoffs", 0, OptHexOffs }, { "--info", 1, OptInfo }, { "--label-break", 1, OptLabelBreak }, { "--mnemonic-column", 1, OptMnemonicColumn }, { "--pagelength", 1, OptPageLength }, { "--start-addr", 1, OptStartAddr }, { "--text-column", 1, OptTextColumn }, { "--verbose", 0, OptVerbose }, { "--version", 0, OptVersion }, }; unsigned I; time_t T; /* Initialize the cmdline module */ InitCmdLine (&argc, &argv, "da65"); /* Check the parameters */ I = 1; while (I < ArgCount) { /* Get the argument */ const char* Arg = ArgVec[I]; /* Check for an option */ if (Arg [0] == '-') { switch (Arg [1]) { case '-': LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0])); break; case 'g': OptDebugInfo (Arg, 0); break; case 'h': OptHelp (Arg, 0); break; case 'i': OptInfo (Arg, GetArg (&I, 2)); break; case 'o': OutFile = GetArg (&I, 2); break; case 'v': OptVerbose (Arg, 0); break; case 'S': OptStartAddr (Arg, GetArg (&I, 2)); break; case 'V': OptVersion (Arg, 0); break; default: UnknownOption (Arg); break; } } else { /* Filename. Check if we already had one */ if (InFile) { fprintf (stderr, "%s: Don't know what to do with `%s'\n", ProgName, Arg); exit (EXIT_FAILURE); } else { InFile = Arg; } } /* Next argument */ ++I; } /* Try to read the info file */ ReadInfoFile (); /* Must have an input file */ if (InFile == 0) { AbEnd ("No input file"); } /* Check the formatting options for reasonable values. Note: We will not * really check that they make sense, just that they aren't complete * garbage. */ if (MCol >= ACol) { AbEnd ("mnemonic-column value must be smaller than argument-column value"); } if (ACol >= CCol) { AbEnd ("argument-column value must be smaller than comment-column value"); } if (CCol >= TCol) { AbEnd ("comment-column value must be smaller than text-column value"); } /* If no CPU given, use the default CPU */ if (CPU == CPU_UNKNOWN) { CPU = CPU_6502; } /* Get the current time and convert it to string so it can be used in * the output page headers. */ T = time (0); strftime (Now, sizeof (Now), "%Y-%m-%d %H:%M:%S", localtime (&T)); /* Load the input file */ LoadCode (); /* Open the output file */ OpenOutput (OutFile); /* Disassemble the code */ Disassemble (); /* Close the output file */ CloseOutput (); /* Done */ return EXIT_SUCCESS; }
980
./cc65/src/da65/comments.c
/*****************************************************************************/ /* */ /* comments.c */ /* */ /* Comment management for da65 */ /* */ /* */ /* */ /* (C) 2006 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "xmalloc.h" /* da65 */ #include "attrtab.h" #include "comments.h" #include "error.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Comment table */ static const char* CommentTab[0x10000]; /*****************************************************************************/ /* Code */ /*****************************************************************************/ void SetComment (unsigned Addr, const char* Comment) /* Set a comment for the given address */ { /* Check the given address */ AddrCheck (Addr); /* If we do already have a comment, warn and ignore the new one */ if (CommentTab[Addr]) { Warning ("Duplicate comment for address $%04X", Addr); } else { CommentTab[Addr] = xstrdup (Comment); } } const char* GetComment (unsigned Addr) /* Return the comment for an address */ { /* Check the given address */ AddrCheck (Addr); /* Return the label if any */ return CommentTab[Addr]; }
981
./cc65/src/da65/global.c
/*****************************************************************************/ /* */ /* global.c */ /* */ /* Global variables for the da65 disassembler */ /* */ /* */ /* */ /* (C) 2000-2006 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include "global.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* File names */ const char* InFile = 0; /* Name of input file */ const char* OutFile = 0; /* Name of output file */ /* Default extensions */ const char OutExt[] = ".dis"; /* Output file extension */ const char CfgExt[] = ".cfg"; /* Config file extension */ /* Flags and other command line stuff */ unsigned char DebugInfo = 0; /* Add debug info to the object file */ unsigned char FormFeeds = 0; /* Add form feeds to the output? */ unsigned char UseHexOffs = 0; /* Use hexadecimal label offsets */ unsigned char PassCount = 2; /* How many passed do we do? */ signed char NewlineAfterJMP = -1; /* Add a newline after a JMP insn? */ signed char NewlineAfterRTS = -1; /* Add a newline after a RTS insn? */ long StartAddr = -1L; /* Start/load address of the program */ long InputOffs = -1L; /* Offset into input file */ long InputSize = -1L; /* Number of bytes to read from input */ /* Stuff needed by many routines */ unsigned Pass = 0; /* Disassembler pass */ char Now[128]; /* Current time as string */ /* Comments */ unsigned Comments = 0; /* Add which comments to the output? */ /* Page formatting */ unsigned PageLength = 0; /* Length of a listing page */ unsigned LBreak = 7; /* Linefeed if labels exceed this limit */ unsigned MCol = 9; /* Mnemonic column */ unsigned ACol = 17; /* Argument column */ unsigned CCol = 49; /* Comment column */ unsigned TCol = 81; /* Text bytes column */ unsigned BytesPerLine = 8; /* Max. number of data bytes per line */
982
./cc65/src/da65/opcm740.c
/*****************************************************************************/ /* */ /* opcm740.c */ /* */ /* Mitsubishi 740 series opcode description table */ /* */ /* A contribution from Chris Baird */ /* EMail: cjb@brushtail.apana.org.au */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* da65 */ #include "handler.h" #include "opcm740.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Descriptions for all opcodes */ const OpcDesc OpcTable_M740[256] = { { "brk", 1, flNone, OH_Implicit }, /* $00 */ { "ora", 2, flUseLabel, OH_DirectXIndirect }, /* $01 */ { "jsr", 2, flLabel, OH_JmpDirectIndirect }, /* $02 */ { "bbs", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $03 */ { "", 1, flIllegal, OH_Illegal }, /* $04 */ { "ora", 2, flUseLabel, OH_Direct }, /* $05 */ { "asl", 2, flUseLabel, OH_Direct }, /* $06 */ { "bbs", 3, flUseLabel, OH_ZeroPageBit }, /* $07 */ { "php", 1, flNone, OH_Implicit }, /* $08 */ { "ora", 2, flNone, OH_Immediate }, /* $09 */ { "asl", 1, flNone, OH_Accumulator }, /* $0a */ { "seb", 1, flNone, OH_AccumulatorBit }, /* $0b */ { "", 1, flIllegal, OH_Illegal, }, /* $0c */ { "ora", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0d */ { "asl", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0e */ { "seb", 2, flUseLabel, OH_ZeroPageBit }, /* $0f */ { "bpl", 2, flLabel, OH_Relative }, /* $10 */ { "ora", 2, flUseLabel, OH_DirectIndirectY }, /* $11 */ { "clt", 1, flNone, OH_Implicit }, /* $12 */ { "bbc", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $13 */ { "", 1, flIllegal, OH_Illegal }, /* $14 */ { "ora", 2, flUseLabel, OH_DirectX }, /* $15 */ { "asl", 2, flUseLabel, OH_DirectX }, /* $16 */ { "bbc", 3, flUseLabel, OH_ZeroPageBit }, /* $17 */ { "clc", 1, flNone, OH_Implicit }, /* $18 */ { "ora", 3, flUseLabel, OH_AbsoluteY }, /* $19 */ { "dec", 1, flNone, OH_Accumulator }, /* $1a */ { "clb", 1, flNone, OH_AccumulatorBit }, /* $1b */ { "", 1, flIllegal, OH_Illegal }, /* $1c */ { "ora", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1d */ { "asl", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1e */ { "clb", 2, flUseLabel, OH_ZeroPageBit }, /* $1f */ { "jsr", 3, flLabel, OH_Absolute }, /* $20 */ { "and", 2, flUseLabel, OH_DirectXIndirect }, /* $21 */ { "jsr", 2, flLabel, OH_SpecialPage }, /* $22 */ { "bbs", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $23 */ { "bit", 2, flUseLabel, OH_Direct }, /* $24 */ { "and", 2, flUseLabel, OH_Direct }, /* $25 */ { "rol", 2, flUseLabel, OH_Direct }, /* $26 */ { "bbs", 3, flUseLabel, OH_ZeroPageBit }, /* $27 */ { "plp", 1, flNone, OH_Implicit }, /* $28 */ { "and", 2, flNone, OH_Immediate }, /* $29 */ { "rol", 1, flNone, OH_Accumulator }, /* $2a */ { "seb", 1, flNone, OH_AccumulatorBit }, /* $2b */ { "bit", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2c */ { "and", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2d */ { "rol", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2e */ { "seb", 2, flUseLabel, OH_ZeroPageBit }, /* $2f */ { "bmi", 2, flLabel, OH_Relative }, /* $30 */ { "and", 2, flUseLabel, OH_DirectIndirectY }, /* $31 */ { "set", 1, flNone, OH_Implicit }, /* $32 */ { "bbc", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $33 */ { "", 1, flIllegal, OH_Illegal }, /* $34 */ { "and", 2, flUseLabel, OH_DirectX }, /* $35 */ { "rol", 2, flUseLabel, OH_DirectX }, /* $36 */ { "bbc", 3, flUseLabel, OH_ZeroPageBit }, /* $37 */ { "sec", 1, flNone, OH_Implicit }, /* $38 */ { "and", 3, flUseLabel, OH_AbsoluteY }, /* $39 */ { "inc", 1, flNone, OH_Accumulator }, /* $3a */ { "clb", 1, flNone, OH_AccumulatorBit }, /* $3b */ { "ldm", 3, flLabel, OH_DirectImmediate }, /* $3c */ { "and", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3d */ { "rol", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3e */ { "clb", 2, flUseLabel, OH_ZeroPageBit }, /* $3f */ { "rti", 1, flNone, OH_Rts }, /* $40 */ { "eor", 2, flUseLabel, OH_DirectXIndirect }, /* $41 */ { "stp", 1, flNone, OH_Implicit }, /* $42 */ { "bbs", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $43 */ { "com", 2, flUseLabel, OH_Direct }, /* $44 */ { "eor", 2, flUseLabel, OH_Direct }, /* $45 */ { "lsr", 2, flUseLabel, OH_Direct }, /* $46 */ { "bbs", 3, flUseLabel, OH_ZeroPageBit }, /* $47 */ { "pha", 1, flNone, OH_Implicit }, /* $48 */ { "eor", 2, flNone, OH_Immediate }, /* $49 */ { "lsr", 1, flNone, OH_Accumulator }, /* $4a */ { "seb", 1, flNone, OH_AccumulatorBit }, /* $4b */ { "jmp", 3, flLabel, OH_JmpAbsolute }, /* $4c */ { "eor", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4e */ { "seb", 2, flUseLabel, OH_ZeroPageBit }, /* $4f */ { "bvc", 2, flLabel, OH_Relative }, /* $50 */ { "eor", 2, flUseLabel, OH_DirectIndirectY }, /* $51 */ { "", 1, flIllegal, OH_Illegal }, /* $52 */ { "bbc", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $53 */ { "", 1, flIllegal, OH_Illegal }, /* $54 */ { "eor", 2, flUseLabel, OH_DirectX }, /* $55 */ { "lsr", 2, flUseLabel, OH_DirectX }, /* $56 */ { "bbc", 3, flUseLabel, OH_ZeroPageBit }, /* $57 */ { "cli", 1, flNone, OH_Implicit }, /* $58 */ { "eor", 3, flUseLabel, OH_AbsoluteY }, /* $59 */ { "", 1, flIllegal, OH_Illegal }, /* $5a */ { "clb", 1, flNone, OH_AccumulatorBit }, /* $5b */ { "", 1, flIllegal, OH_Illegal }, /* $5c */ { "eor", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5e */ { "clb", 2, flUseLabel, OH_ZeroPageBit }, /* $5f */ { "rts", 1, flNone, OH_Rts }, /* $60 */ { "adc", 2, flUseLabel, OH_DirectXIndirect }, /* $61 */ { "mul", 2, flUseLabel, OH_DirectX }, /* $62 */ { "bbs", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $63 */ { "tst", 2, flUseLabel, OH_Direct }, /* $64 */ { "adc", 2, flUseLabel, OH_Direct }, /* $65 */ { "ror", 2, flUseLabel, OH_Direct }, /* $66 */ { "bbs", 3, flUseLabel, OH_ZeroPageBit }, /* $67 */ { "pla", 1, flNone, OH_Implicit }, /* $68 */ { "adc", 2, flNone, OH_Immediate }, /* $69 */ { "ror", 1, flNone, OH_Accumulator }, /* $6a */ { "seb", 1, flNone, OH_AccumulatorBit }, /* $6b */ { "jmp", 3, flLabel, OH_JmpAbsoluteIndirect }, /* $6c */ { "adc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6d */ { "ror", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6e */ { "seb", 2, flUseLabel, OH_ZeroPageBit }, /* $6f */ { "bvs", 2, flLabel, OH_Relative }, /* $70 */ { "adc", 2, flUseLabel, OH_DirectIndirectY }, /* $71 */ { "", 1, flIllegal, OH_Illegal }, /* $72 */ { "bbc", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $73 */ { "", 1, flIllegal, OH_Illegal }, /* $74 */ { "adc", 2, flUseLabel, OH_DirectX }, /* $75 */ { "ror", 2, flUseLabel, OH_DirectX }, /* $76 */ { "bbc", 3, flUseLabel, OH_ZeroPageBit }, /* $77 */ { "sei", 1, flNone, OH_Implicit }, /* $78 */ { "adc", 3, flUseLabel, OH_AbsoluteY }, /* $79 */ { "", 1, flIllegal, OH_Illegal }, /* $7a */ { "clb", 1, flNone, OH_AccumulatorBit }, /* $7b */ { "", 1, flIllegal, OH_Illegal }, /* $7c */ { "adc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7d */ { "ror", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7e */ { "clb", 2, flUseLabel, OH_ZeroPageBit }, /* $7f */ { "bra", 2, flLabel, OH_Relative }, /* $80 */ { "sta", 2, flUseLabel, OH_DirectXIndirect }, /* $81 */ { "rrf", 2, flLabel, OH_Direct }, /* $82 */ { "bbs", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $83 */ { "sty", 2, flUseLabel, OH_Direct }, /* $84 */ { "sta", 2, flUseLabel, OH_Direct }, /* $85 */ { "stx", 2, flUseLabel, OH_Direct }, /* $86 */ { "bbs", 3, flUseLabel, OH_ZeroPageBit }, /* $87 */ { "dey", 1, flNone, OH_Implicit }, /* $88 */ { "", 1, flIllegal, OH_Illegal }, /* $89 */ { "txa", 1, flNone, OH_Implicit }, /* $8a */ { "seb", 1, flNone, OH_AccumulatorBit }, /* $8b */ { "sty", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8c */ { "sta", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8d */ { "stx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8e */ { "seb", 2, flUseLabel, OH_ZeroPageBit }, /* $8f */ { "bcc", 2, flLabel, OH_Relative }, /* $90 */ { "sta", 2, flUseLabel, OH_DirectIndirectY }, /* $91 */ { "", 1, flIllegal, OH_Illegal }, /* $92 */ { "bbc", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $93 */ { "sty", 2, flUseLabel, OH_DirectX }, /* $94 */ { "sta", 2, flUseLabel, OH_DirectX }, /* $95 */ { "stx", 2, flUseLabel, OH_DirectY }, /* $96 */ { "bbc", 3, flUseLabel, OH_ZeroPageBit }, /* $97 */ { "tya", 1, flNone, OH_Implicit }, /* $98 */ { "sta", 3, flUseLabel, OH_AbsoluteY }, /* $99 */ { "txs", 1, flNone, OH_Implicit }, /* $9a */ { "clb", 1, flNone, OH_AccumulatorBit }, /* $9b */ { "", 1, flIllegal, OH_Illegal }, /* $9c */ { "sta", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $9d */ { "", 1, flIllegal, OH_Illegal }, /* $9e */ { "clb", 2, flUseLabel, OH_ZeroPageBit }, /* $9f */ { "ldy", 2, flNone, OH_Immediate }, /* $a0 */ { "lda", 2, flUseLabel, OH_DirectXIndirect }, /* $a1 */ { "ldx", 2, flNone, OH_Immediate }, /* $a2 */ { "bbs", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $a3 */ { "ldy", 2, flUseLabel, OH_Direct }, /* $a4 */ { "lda", 2, flUseLabel, OH_Direct }, /* $a5 */ { "ldx", 2, flUseLabel, OH_Direct }, /* $a6 */ { "bbs", 3, flUseLabel, OH_ZeroPageBit }, /* $a7 */ { "tay", 1, flNone, OH_Implicit }, /* $a8 */ { "lda", 2, flNone, OH_Immediate }, /* $a9 */ { "tax", 1, flNone, OH_Implicit }, /* $aa */ { "seb", 1, flNone, OH_AccumulatorBit }, /* $ab */ { "ldy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ac */ { "lda", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ad */ { "ldx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ae */ { "seb", 2, flUseLabel, OH_ZeroPageBit }, /* $af */ { "bcs", 2, flLabel, OH_Relative }, /* $b0 */ { "lda", 2, flUseLabel, OH_DirectIndirectY }, /* $b1 */ { "jmp", 2, flLabel, OH_JmpDirectIndirect }, /* $b2 */ { "bbc", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $b3 */ { "ldy", 2, flUseLabel, OH_DirectX }, /* $b4 */ { "lda", 2, flUseLabel, OH_DirectX }, /* $b5 */ { "ldx", 2, flUseLabel, OH_DirectY }, /* $b6 */ { "bbc", 3, flUseLabel, OH_ZeroPageBit }, /* $b7 */ { "clv", 1, flNone, OH_Implicit }, /* $b8 */ { "lda", 3, flUseLabel, OH_AbsoluteY }, /* $b9 */ { "tsx", 1, flNone, OH_Implicit }, /* $ba */ { "clb", 1, flNone, OH_AccumulatorBit }, /* $bb */ { "ldy", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bc */ { "lda", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bd */ { "ldx", 3, flUseLabel|flAbsOverride, OH_AbsoluteY }, /* $be */ { "clb", 2, flUseLabel, OH_ZeroPageBit }, /* $bf */ { "cpy", 2, flNone, OH_Immediate }, /* $c0 */ { "cmp", 2, flUseLabel, OH_DirectXIndirect }, /* $c1 */ { "wit", 1, flNone, OH_Implicit, }, /* $c2 */ { "bbs", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $c3 */ { "cpy", 2, flUseLabel, OH_Direct }, /* $c4 */ { "cmp", 2, flUseLabel, OH_Direct }, /* $c5 */ { "dec", 2, flUseLabel, OH_Direct }, /* $c6 */ { "bbs", 3, flUseLabel, OH_ZeroPageBit }, /* $c7 */ { "iny", 1, flNone, OH_Implicit }, /* $c8 */ { "cmp", 2, flNone, OH_Immediate }, /* $c9 */ { "dex", 1, flNone, OH_Implicit }, /* $ca */ { "seb", 1, flNone, OH_AccumulatorBit }, /* $cb */ { "cpy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cd */ { "dec", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ce */ { "seb", 2, flUseLabel, OH_ZeroPageBit }, /* $cf */ { "bne", 2, flLabel, OH_Relative }, /* $d0 */ { "cmp", 2, flUseLabel, OH_DirectIndirectY }, /* $d1 */ { "", 1, flIllegal, OH_Illegal }, /* $d2 */ { "bbc", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $d3 */ { "", 1, flIllegal, OH_Illegal }, /* $d4 */ { "cmp", 2, flUseLabel, OH_DirectX }, /* $d5 */ { "dec", 2, flUseLabel, OH_DirectX }, /* $d6 */ { "bbc", 3, flUseLabel, OH_ZeroPageBit }, /* $d7 */ { "cld", 1, flNone, OH_Implicit }, /* $d8 */ { "cmp", 3, flUseLabel, OH_AbsoluteY }, /* $d9 */ { "", 1, flIllegal, OH_Illegal }, /* $da */ { "clb", 1, flNone, OH_AccumulatorBit }, /* $db */ { "", 1, flIllegal, OH_Illegal }, /* $dc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $dd */ { "dec", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $de */ { "clb", 2, flUseLabel, OH_ZeroPageBit }, /* $df */ { "cpx", 2, flNone, OH_Immediate }, /* $e0 */ { "sbc", 2, flUseLabel, OH_DirectXIndirect }, /* $e1 */ { "div", 2, flUseLabel, OH_DirectX }, /* $e2 */ { "bbs", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $e3 */ { "cpx", 2, flUseLabel, OH_Direct }, /* $e4 */ { "sbc", 2, flUseLabel, OH_Direct }, /* $e5 */ { "inc", 2, flUseLabel, OH_Direct }, /* $e6 */ { "bbs", 3, flUseLabel, OH_ZeroPageBit }, /* $e7 */ { "inx", 1, flNone, OH_Implicit }, /* $e8 */ { "sbc", 2, flNone, OH_Immediate }, /* $e9 */ { "nop", 1, flNone, OH_Implicit }, /* $ea */ { "seb", 1, flNone, OH_AccumulatorBit }, /* $eb */ { "cpx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ec */ { "sbc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ed */ { "inc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ee */ { "seb", 2, flUseLabel, OH_ZeroPageBit }, /* $ef */ { "beq", 2, flLabel, OH_Relative }, /* $f0 */ { "sbc", 2, flUseLabel, OH_DirectIndirectY }, /* $f1 */ { "", 1, flIllegal, OH_Illegal }, /* $f2 */ { "bbc", 2, flUseLabel, OH_AccumulatorBitBranch }, /* $f3 */ { "", 1, flIllegal, OH_Illegal }, /* $f4 */ { "sbc", 2, flUseLabel, OH_DirectX }, /* $f5 */ { "inc", 2, flUseLabel, OH_DirectX }, /* $f6 */ { "bbc", 3, flUseLabel, OH_ZeroPageBit }, /* $f7 */ { "sed", 1, flNone, OH_Implicit }, /* $f8 */ { "sbc", 3, flUseLabel, OH_AbsoluteY }, /* $f9 */ { "", 1, flIllegal, OH_Illegal }, /* $fa */ { "clb", 1, flNone, OH_AccumulatorBit }, /* $fb */ { "", 1, flIllegal, OH_Illegal }, /* $fc */ { "sbc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fd */ { "inc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fe */ { "clb", 2, flUseLabel, OH_ZeroPageBit }, /* $ff */ };
983
./cc65/src/da65/scanner.c
/*****************************************************************************/ /* */ /* scanner.c */ /* */ /* Configuration file scanner for the da65 disassembler */ /* */ /* */ /* */ /* (C) 2000-2005 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdarg.h> #include <stdio.h> #include <string.h> #include <errno.h> /* common */ #include "chartype.h" #include "xsprintf.h" /* ld65 */ #include "global.h" #include "error.h" #include "scanner.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Current token and attributes */ unsigned InfoTok; char InfoSVal [CFG_MAX_IDENT_LEN+1]; long InfoIVal; /* Error location */ unsigned InfoErrorLine; unsigned InfoErrorCol; /* Input sources for the configuration */ static const char* InfoFile = 0; /* Other input stuff */ static int C = ' '; static unsigned InputLine = 1; static unsigned InputCol = 0; static FILE* InputFile = 0; /*****************************************************************************/ /* Error handling */ /*****************************************************************************/ void InfoWarning (const char* Format, ...) /* Print a warning message adding file name and line number of the config file */ { char Buf [512]; va_list ap; va_start (ap, Format); xvsprintf (Buf, sizeof (Buf), Format, ap); va_end (ap); Warning ("%s(%u): %s", InfoFile, InfoErrorLine, Buf); } void InfoError (const char* Format, ...) /* Print an error message adding file name and line number of the config file */ { char Buf [512]; va_list ap; va_start (ap, Format); xvsprintf (Buf, sizeof (Buf), Format, ap); va_end (ap); Error ("%s(%u): %s", InfoFile, InfoErrorLine, Buf); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void NextChar (void) /* Read the next character from the input file */ { /* Read from the file */ C = getc (InputFile); /* Count columns */ if (C != EOF) { ++InputCol; } /* Count lines */ if (C == '\n') { ++InputLine; InputCol = 0; } } static unsigned DigitVal (int C) /* Return the value for a numeric digit */ { if (IsDigit (C)) { return C - '0'; } else { return toupper (C) - 'A' + 10; } } void InfoNextTok (void) /* Read the next token from the input stream */ { unsigned I; int Esc; Again: /* Skip whitespace */ while (IsSpace (C)) { NextChar (); } /* Remember the current position */ InfoErrorLine = InputLine; InfoErrorCol = InputCol; /* Identifier? */ if (C == '_' || IsAlpha (C)) { /* Read the identifier */ I = 0; while (C == '_' || IsAlNum (C)) { if (I < CFG_MAX_IDENT_LEN) { InfoSVal [I++] = C; } NextChar (); } InfoSVal [I] = '\0'; InfoTok = INFOTOK_IDENT; return; } /* Hex number? */ if (C == '$') { NextChar (); if (!IsXDigit (C)) { InfoError ("Hex digit expected"); } InfoIVal = 0; while (IsXDigit (C)) { InfoIVal = InfoIVal * 16 + DigitVal (C); NextChar (); } InfoTok = INFOTOK_INTCON; return; } /* Decimal number? */ if (IsDigit (C)) { InfoIVal = 0; while (IsDigit (C)) { InfoIVal = InfoIVal * 10 + DigitVal (C); NextChar (); } InfoTok = INFOTOK_INTCON; return; } /* Other characters */ switch (C) { case '{': NextChar (); InfoTok = INFOTOK_LCURLY; break; case '}': NextChar (); InfoTok = INFOTOK_RCURLY; break; case ';': NextChar (); InfoTok = INFOTOK_SEMI; break; case '.': NextChar (); InfoTok = INFOTOK_DOT; break; case ',': NextChar (); InfoTok = INFOTOK_COMMA; break; case '=': NextChar (); InfoTok = INFOTOK_EQ; break; case ':': NextChar (); InfoTok = INFOTOK_COLON; break; case '\"': NextChar (); I = 0; while (C != '\"') { Esc = (C == '\\'); if (Esc) { NextChar (); } if (C == EOF || C == '\n') { InfoError ("Unterminated string"); } if (Esc) { switch (C) { case '\"': C = '\"'; break; case '\'': C = '\''; break; default: InfoError ("Invalid escape char: %c", C); } } if (I < CFG_MAX_IDENT_LEN) { InfoSVal [I++] = C; } NextChar (); } NextChar (); InfoSVal [I] = '\0'; InfoTok = INFOTOK_STRCON; break; case '\'': NextChar (); if (C == EOF || IsControl (C)) { InfoError ("Invalid character constant"); } InfoIVal = C; NextChar (); if (C != '\'') { InfoError ("Unterminated character constant"); } NextChar (); InfoTok = INFOTOK_CHARCON; break; case '#': /* Comment */ while (C != '\n' && C != EOF) { NextChar (); } if (C != EOF) { goto Again; } InfoTok = INFOTOK_EOF; break; case EOF: InfoTok = INFOTOK_EOF; break; default: InfoError ("Invalid character `%c'", C); } } void InfoConsume (unsigned T, const char* Msg) /* Skip a token, print an error message if not found */ { if (InfoTok != T) { InfoError (Msg); } InfoNextTok (); } void InfoConsumeLCurly (void) /* Consume a left curly brace */ { InfoConsume (INFOTOK_LCURLY, "`{' expected"); } void InfoConsumeRCurly (void) /* Consume a right curly brace */ { InfoConsume (INFOTOK_RCURLY, "`}' expected"); } void InfoConsumeSemi (void) /* Consume a semicolon */ { InfoConsume (INFOTOK_SEMI, "`;' expected"); } void InfoConsumeColon (void) /* Consume a colon */ { InfoConsume (INFOTOK_COLON, "`:' expected"); } void InfoOptionalComma (void) /* Consume a comma if there is one */ { if (InfoTok == INFOTOK_COMMA) { InfoNextTok (); } } void InfoOptionalAssign (void) /* Consume an equal sign if there is one */ { if (InfoTok == INFOTOK_EQ) { InfoNextTok (); } } void InfoAssureInt (void) /* Make sure the next token is an integer */ { if (InfoTok != INFOTOK_INTCON) { InfoError ("Integer constant expected"); } } void InfoAssureStr (void) /* Make sure the next token is a string constant */ { if (InfoTok != INFOTOK_STRCON) { InfoError ("String constant expected"); } } void InfoAssureChar (void) /* Make sure the next token is a char constant */ { if (InfoTok != INFOTOK_STRCON) { InfoError ("Character constant expected"); } } void InfoAssureIdent (void) /* Make sure the next token is an identifier */ { if (InfoTok != INFOTOK_IDENT) { InfoError ("Identifier expected"); } } void InfoRangeCheck (long Lo, long Hi) /* Check the range of InfoIVal */ { if (InfoIVal < Lo || InfoIVal > Hi) { InfoError ("Range error"); } } void InfoSpecialToken (const IdentTok* Table, unsigned Size, const char* Name) /* Map an identifier to one of the special tokens in the table */ { unsigned I; /* We need an identifier */ if (InfoTok == INFOTOK_IDENT) { /* Make it upper case */ I = 0; while (InfoSVal [I]) { InfoSVal [I] = toupper (InfoSVal [I]); ++I; } /* Linear search */ for (I = 0; I < Size; ++I) { if (strcmp (InfoSVal, Table [I].Ident) == 0) { InfoTok = Table [I].Tok; return; } } } /* Not found or no identifier */ InfoError ("%s expected", Name); } void InfoBoolToken (void) /* Map an identifier or integer to a boolean token */ { static const IdentTok Booleans [] = { { "YES", INFOTOK_TRUE }, { "NO", INFOTOK_FALSE }, { "TRUE", INFOTOK_TRUE }, { "FALSE", INFOTOK_FALSE }, { "ON", INFOTOK_TRUE }, { "OFF", INFOTOK_FALSE }, }; /* If we have an identifier, map it to a boolean token */ if (InfoTok == INFOTOK_IDENT) { InfoSpecialToken (Booleans, ENTRY_COUNT (Booleans), "Boolean"); } else { /* We expected an integer here */ if (InfoTok != INFOTOK_INTCON) { InfoError ("Boolean value expected"); } InfoTok = (InfoIVal == 0)? INFOTOK_FALSE : INFOTOK_TRUE; } } void InfoSetName (const char* Name) /* Set a name for a config file */ { InfoFile = Name; } const char* InfoGetName (void) /* Get the name of the config file */ { return InfoFile? InfoFile : ""; } int InfoAvail () /* Return true if we have an info file given */ { return (InfoFile != 0); } void InfoOpenInput (void) /* Open the input file */ { /* Open the file */ InputFile = fopen (InfoFile, "r"); if (InputFile == 0) { Error ("Cannot open `%s': %s", InfoFile, strerror (errno)); } /* Initialize variables */ C = ' '; InputLine = 1; InputCol = 0; /* Start the ball rolling ... */ InfoNextTok (); } void InfoCloseInput (void) /* Close the input file if we have one */ { /* Close the input file if we had one */ if (InputFile) { (void) fclose (InputFile); InputFile = 0; } }
984
./cc65/src/da65/opc65816.c
/*****************************************************************************/ /* */ /* opc65816.c */ /* */ /* 65816 opcode description table */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* da65 */ #include "handler.h" #include "opc65816.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Descriptions for all opcodes */ const OpcDesc OpcTable_65816[256] = { { "brk", 1, flNone, OH_Implicit }, /* $00 */ { "ora", 2, flUseLabel, OH_DirectXIndirect }, /* $01 */ { "cop", 2, flNone, OH_Implicit }, /* $02 */ { "ora", 2, flNone, OH_StackRelative }, /* $03 */ { "tsb", 2, flUseLabel, OH_Direct }, /* $04 */ { "ora", 2, flUseLabel, OH_Direct }, /* $05 */ { "asl", 2, flUseLabel, OH_Direct }, /* $06 */ { "ora", 2, flUseLabel, OH_DirectIndirectLong }, /* $07 */ { "php", 1, flNone, OH_Implicit }, /* $08 */ { "ora", 2, flNone, OH_Immediate }, /* $09 */ { "asl", 1, flNone, OH_Accumulator }, /* $0a */ { "phd", 1, flNone, OH_Implicit }, /* $0b */ { "tsb", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0c */ { "ora", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0d */ { "asl", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0e */ { "ora", 4, flUseLabel, OH_AbsoluteLong }, /* $0f */ { "bpl", 2, flLabel, OH_Relative }, /* $10 */ { "ora", 2, flUseLabel, OH_DirectIndirectY }, /* $11 */ { "ora", 2, flUseLabel, OH_DirectIndirect }, /* $12 */ { "ora", 2, flNone, OH_StackRelativeIndirectY}, /* $13 */ { "trb", 2, flUseLabel, OH_Direct }, /* $14 */ { "ora", 2, flUseLabel, OH_DirectX }, /* $15 */ { "asl", 2, flUseLabel, OH_DirectX }, /* $16 */ { "ora", 2, flUseLabel, OH_DirectIndirectLongY }, /* $17 */ { "clc", 1, flNone, OH_Implicit }, /* $18 */ { "ora", 3, flUseLabel, OH_AbsoluteY }, /* $19 */ { "inc", 1, flNone, OH_Accumulator }, /* $1a */ { "tcs", 1, flNone, OH_Implicit }, /* $1b */ { "trb", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $1c */ { "ora", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1d */ { "asl", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1e */ { "ora", 4, flUseLabel, OH_AbsoluteLongX }, /* $1f */ { "jsr", 3, flLabel, OH_Absolute }, /* $20 */ { "and", 2, flUseLabel, OH_DirectXIndirect }, /* $21 */ { "jsl", 3, flLabel, OH_AbsoluteLong }, /* $22 */ { "and", 2, flNone, OH_StackRelative }, /* $23 */ { "bit", 2, flUseLabel, OH_Direct }, /* $24 */ { "and", 2, flUseLabel, OH_Direct }, /* $25 */ { "rol", 2, flUseLabel, OH_Direct }, /* $26 */ { "and", 2, flUseLabel, OH_DirectIndirectLong }, /* $27 */ { "plp", 1, flNone, OH_Implicit }, /* $28 */ { "and", 2, flNone, OH_Immediate }, /* $29 */ { "rol", 1, flNone, OH_Accumulator }, /* $2a */ { "pld", 1, flNone, OH_Implicit }, /* $2b */ { "bit", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2c */ { "and", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2d */ { "rol", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2e */ { "and", 4, flUseLabel, OH_AbsoluteLong }, /* $2f */ { "bmi", 2, flLabel, OH_Relative }, /* $30 */ { "and", 2, flUseLabel, OH_DirectIndirectY }, /* $31 */ { "and", 2, flUseLabel, OH_DirectIndirect }, /* $32 */ { "and", 2, flNone, OH_StackRelativeIndirectY}, /* $33 */ { "bit", 2, flUseLabel, OH_DirectX }, /* $34 */ { "and", 2, flUseLabel, OH_DirectX }, /* $35 */ { "rol", 2, flUseLabel, OH_DirectX }, /* $36 */ { "and", 2, flUseLabel, OH_DirectIndirectLongY }, /* $37 */ { "sec", 1, flNone, OH_Implicit }, /* $38 */ { "and", 3, flUseLabel, OH_AbsoluteY }, /* $39 */ { "dec", 1, flNone, OH_Accumulator }, /* $3a */ { "tsc", 1, flNone, OH_Implicit }, /* $3b */ { "bit", 3, flUseLabel, OH_AbsoluteX }, /* $3c */ { "and", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3d */ { "rol", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3e */ { "and", 4, flUseLabel, OH_AbsoluteLongX }, /* $3f */ { "rti", 1, flNone, OH_Rts }, /* $40 */ { "eor", 2, flUseLabel, OH_DirectXIndirect }, /* $41 */ { "wdm", 2, flNone, OH_Implicit }, /* $42 */ { "eor", 2, flNone, OH_StackRelative }, /* $43 */ { "mvp", 3, flNone, OH_BlockMove }, /* $44 */ { "eor", 2, flUseLabel, OH_Direct }, /* $45 */ { "lsr", 2, flUseLabel, OH_Direct }, /* $46 */ { "eor", 2, flUseLabel, OH_DirectIndirectLong }, /* $47 */ { "pha", 1, flNone, OH_Implicit }, /* $48 */ { "eor", 2, flNone, OH_Immediate }, /* $49 */ { "lsr", 1, flNone, OH_Accumulator }, /* $4a */ { "phk", 1, flNone, OH_Implicit }, /* $4b */ { "jmp", 3, flLabel, OH_JmpAbsolute }, /* $4c */ { "eor", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4e */ { "eor", 4, flUseLabel, OH_AbsoluteLong }, /* $4f */ { "bvc", 2, flLabel, OH_Relative }, /* $50 */ { "eor", 2, flUseLabel, OH_DirectIndirectY }, /* $51 */ { "eor", 2, flUseLabel, OH_DirectIndirect }, /* $52 */ { "eor", 2, flNone, OH_StackRelativeIndirectY}, /* $53 */ { "mvn", 3, flNone, OH_BlockMove }, /* $54 */ { "eor", 2, flUseLabel, OH_DirectX }, /* $55 */ { "lsr", 2, flUseLabel, OH_DirectX }, /* $56 */ { "eor", 2, flUseLabel, OH_DirectIndirectLongY }, /* $57 */ { "cli", 1, flNone, OH_Implicit }, /* $58 */ { "eor", 3, flUseLabel, OH_AbsoluteY }, /* $59 */ { "phy", 1, flNone, OH_Implicit }, /* $5a */ { "tcd", 1, flNone, OH_Implicit }, /* $5b */ { "jml", 4, flLabel, OH_AbsoluteLong }, /* $5c */ { "eor", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5e */ { "eor", 4, flUseLabel, OH_AbsoluteLongX }, /* $5f */ { "rts", 1, flNone, OH_Rts }, /* $60 */ { "adc", 2, flUseLabel, OH_DirectXIndirect }, /* $61 */ { "per", 3, flLabel, OH_RelativeLong }, /* $62 */ { "adc", 2, flNone, OH_StackRelative }, /* $63 */ { "stz", 2, flUseLabel, OH_Direct }, /* $64 */ { "adc", 2, flUseLabel, OH_Direct }, /* $65 */ { "ror", 2, flUseLabel, OH_Direct }, /* $66 */ { "adc", 2, flUseLabel, OH_DirectIndirectLong }, /* $67 */ { "pla", 1, flNone, OH_Implicit }, /* $68 */ { "adc", 2, flNone, OH_Immediate }, /* $69 */ { "ror", 1, flNone, OH_Accumulator }, /* $6a */ { "rtl", 1, flNone, OH_Implicit }, /* $6b */ { "jmp", 3, flLabel, OH_JmpAbsoluteIndirect }, /* $6c */ { "adc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6d */ { "ror", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6e */ { "adc", 4, flUseLabel, OH_AbsoluteLong }, /* $6f */ { "bvs", 2, flLabel, OH_Relative }, /* $70 */ { "adc", 2, flUseLabel, OH_DirectIndirectY }, /* $71 */ { "adc", 2, flUseLabel, OH_DirectIndirect }, /* $72 */ { "adc", 2, flNone, OH_StackRelativeIndirectY}, /* $73 */ { "stz", 2, flUseLabel, OH_DirectX }, /* $74 */ { "adc", 2, flUseLabel, OH_DirectX }, /* $75 */ { "ror", 2, flUseLabel, OH_DirectX }, /* $76 */ { "adc", 2, flUseLabel, OH_DirectIndirectLongY }, /* $77 */ { "sei", 1, flNone, OH_Implicit }, /* $78 */ { "adc", 3, flUseLabel, OH_AbsoluteY }, /* $79 */ { "ply", 1, flNone, OH_Implicit }, /* $7a */ { "tdc", 1, flNone, OH_Implicit }, /* $7b */ { "jmp", 3, flLabel, OH_AbsoluteXIndirect }, /* $7c */ { "adc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7d */ { "ror", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7e */ { "adc", 4, flUseLabel, OH_AbsoluteLongX }, /* $7f */ { "bra", 2, flLabel, OH_Relative }, /* $80 */ { "sta", 2, flUseLabel, OH_DirectXIndirect }, /* $81 */ { "brl", 3, flLabel, OH_RelativeLong }, /* $82 */ { "sta", 2, flNone, OH_StackRelative }, /* $83 */ { "sty", 2, flUseLabel, OH_Direct }, /* $84 */ { "sta", 2, flUseLabel, OH_Direct }, /* $85 */ { "stx", 2, flUseLabel, OH_Direct }, /* $86 */ { "sta", 2, flUseLabel, OH_DirectIndirectLong }, /* $87 */ { "dey", 1, flNone, OH_Implicit }, /* $88 */ { "bit", 2, flNone, OH_Immediate }, /* $89 */ { "txa", 1, flNone, OH_Implicit }, /* $8a */ { "phb", 1, flNone, OH_Implicit }, /* $8b */ { "sty", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8c */ { "sta", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8d */ { "stx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8e */ { "sta", 4, flUseLabel, OH_AbsoluteLong }, /* $8f */ { "bcc", 2, flLabel, OH_Relative }, /* $90 */ { "sta", 2, flUseLabel, OH_DirectIndirectY }, /* $91 */ { "sta", 2, flUseLabel, OH_DirectIndirect }, /* $92 */ { "sta", 2, flNone, OH_StackRelativeIndirectY}, /* $93 */ { "sty", 2, flUseLabel, OH_DirectX }, /* $94 */ { "sta", 2, flUseLabel, OH_DirectX }, /* $95 */ { "stx", 2, flUseLabel, OH_DirectY }, /* $96 */ { "sta", 2, flUseLabel, OH_DirectIndirectLongY }, /* $97 */ { "tya", 1, flNone, OH_Implicit }, /* $98 */ { "sta", 3, flUseLabel, OH_AbsoluteY }, /* $99 */ { "txs", 1, flNone, OH_Implicit }, /* $9a */ { "txy", 1, flNone, OH_Implicit }, /* $9b */ { "stz", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $9c */ { "sta", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $9d */ { "stz", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $9e */ { "sta", 4, flUseLabel, OH_AbsoluteLongX }, /* $9f */ { "ldy", 2, flNone, OH_Immediate }, /* $a0 */ { "lda", 2, flUseLabel, OH_DirectXIndirect }, /* $a1 */ { "ldx", 2, flNone, OH_Immediate }, /* $a2 */ { "lda", 2, flNone, OH_StackRelative }, /* $a3 */ { "ldy", 2, flUseLabel, OH_Direct }, /* $a4 */ { "lda", 2, flUseLabel, OH_Direct }, /* $a5 */ { "ldx", 2, flUseLabel, OH_Direct }, /* $a6 */ { "lda", 2, flUseLabel, OH_DirectIndirectLong }, /* $a7 */ { "tay", 1, flNone, OH_Implicit }, /* $a8 */ { "lda", 2, flNone, OH_Immediate }, /* $a9 */ { "tax", 1, flNone, OH_Implicit }, /* $aa */ { "plb", 1, flNone, OH_Implicit }, /* $ab */ { "ldy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ac */ { "lda", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ad */ { "ldx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ae */ { "lda", 4, flUseLabel, OH_AbsoluteLong }, /* $af */ { "bcs", 2, flLabel, OH_Relative }, /* $b0 */ { "lda", 2, flUseLabel, OH_DirectIndirectY }, /* $b1 */ { "lda", 2, flUseLabel, OH_DirectIndirect }, /* $b2 */ { "lda", 2, flNone, OH_StackRelativeIndirectY}, /* $b3 */ { "ldy", 2, flUseLabel, OH_DirectX }, /* $b4 */ { "lda", 2, flUseLabel, OH_DirectX }, /* $b5 */ { "ldx", 2, flUseLabel, OH_DirectY }, /* $b6 */ { "lda", 2, flUseLabel, OH_DirectIndirectLongY }, /* $b7 */ { "clv", 1, flNone, OH_Implicit }, /* $b8 */ { "lda", 3, flUseLabel, OH_AbsoluteY }, /* $b9 */ { "tsx", 1, flNone, OH_Implicit }, /* $ba */ { "tyx", 1, flNone, OH_Implicit }, /* $bb */ { "ldy", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bc */ { "lda", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bd */ { "ldx", 3, flUseLabel|flAbsOverride, OH_AbsoluteY }, /* $be */ { "lda", 4, flUseLabel, OH_AbsoluteLongX }, /* $bf */ { "cpy", 2, flNone, OH_Immediate }, /* $c0 */ { "cmp", 2, flUseLabel, OH_DirectXIndirect }, /* $c1 */ { "rep", 2, flNone, OH_Immediate }, /* $c2 */ { "cmp", 2, flNone, OH_StackRelative }, /* $c3 */ { "cpy", 2, flUseLabel, OH_Direct }, /* $c4 */ { "cmp", 2, flUseLabel, OH_Direct }, /* $c5 */ { "dec", 2, flUseLabel, OH_Direct }, /* $c6 */ { "cmp", 2, flUseLabel, OH_DirectIndirectLong }, /* $c7 */ { "iny", 1, flNone, OH_Implicit }, /* $c8 */ { "cmp", 2, flNone, OH_Immediate }, /* $c9 */ { "dex", 1, flNone, OH_Implicit }, /* $ca */ { "wai", 1, flNone, OH_Implicit }, /* $cb */ { "cpy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cd */ { "dec", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ce */ { "cmp", 4, flUseLabel, OH_AbsoluteLong }, /* $cf */ { "bne", 2, flLabel, OH_Relative }, /* $d0 */ { "cmp", 2, flUseLabel, OH_DirectIndirectY }, /* $d1 */ { "cmp", 2, flUseLabel, OH_DirectIndirect }, /* $d2 */ { "cmp", 2, flNone, OH_StackRelativeIndirectY}, /* $d3 */ { "pei", 2, flUseLabel, OH_Direct }, /* $d4 */ { "cmp", 2, flUseLabel, OH_DirectX }, /* $d5 */ { "dec", 2, flUseLabel, OH_DirectX }, /* $d6 */ { "cmp", 2, flUseLabel, OH_DirectIndirectLongY }, /* $d7 */ { "cld", 1, flNone, OH_Implicit }, /* $d8 */ { "cmp", 3, flUseLabel, OH_AbsoluteY }, /* $d9 */ { "phx", 1, flNone, OH_Implicit }, /* $da */ { "stp", 1, flNone, OH_Implicit }, /* $db */ { "jml", 3, flLabel, OH_AbsoluteIndirect }, /* $dc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $dd */ { "dec", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $de */ { "cmp", 4, flUseLabel, OH_AbsoluteLongX }, /* $df */ { "cpx", 2, flNone, OH_Immediate }, /* $e0 */ { "sbc", 2, flUseLabel, OH_DirectXIndirect }, /* $e1 */ { "sep", 2, flNone, OH_Immediate }, /* $e2 */ { "sbc", 2, flNone, OH_StackRelative }, /* $e3 */ { "cpx", 2, flUseLabel, OH_Direct }, /* $e4 */ { "sbc", 2, flUseLabel, OH_Direct }, /* $e5 */ { "inc", 2, flUseLabel, OH_Direct }, /* $e6 */ { "sbc", 2, flUseLabel, OH_DirectIndirectLong }, /* $e7 */ { "inx", 1, flNone, OH_Implicit }, /* $e8 */ { "sbc", 2, flNone, OH_Immediate }, /* $e9 */ { "nop", 1, flNone, OH_Implicit }, /* $ea */ { "xba", 1, flNone, OH_Implicit }, /* $eb */ { "cpx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ec */ { "sbc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ed */ { "inc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ee */ { "sbc", 4, flUseLabel, OH_AbsoluteLong }, /* $ef */ { "beq", 2, flLabel, OH_Relative }, /* $f0 */ { "sbc", 2, flUseLabel, OH_DirectIndirectY }, /* $f1 */ { "sbc", 2, flUseLabel, OH_DirectIndirect }, /* $f2 */ { "sbc", 2, flNone, OH_StackRelativeIndirectY}, /* $f3 */ { "pea", 3, flUseLabel, OH_Absolute }, /* $f4 */ { "sbc", 2, flUseLabel, OH_DirectX }, /* $f5 */ { "inc", 2, flUseLabel, OH_DirectX }, /* $f6 */ { "sbc", 2, flUseLabel, OH_DirectIndirectLongY }, /* $f7 */ { "sed", 1, flNone, OH_Implicit }, /* $f8 */ { "sbc", 3, flUseLabel, OH_AbsoluteY }, /* $f9 */ { "plx", 1, flNone, OH_Implicit }, /* $fa */ { "xce", 1, flNone, OH_Implicit }, /* $fb */ { "jsr", 3, flLabel, OH_AbsoluteXIndirect }, /* $fc */ { "sbc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fd */ { "inc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fe */ { "sbc", 4, flUseLabel, OH_AbsoluteLongX }, /* $ff */ };
985
./cc65/src/da65/handler.c
/*****************************************************************************/ /* */ /* handler.c */ /* */ /* Opcode handler functions for the disassembler */ /* */ /* */ /* */ /* (C) 2000-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdarg.h> /* common */ #include "xsprintf.h" /* da65 */ #include "attrtab.h" #include "code.h" #include "error.h" #include "global.h" #include "handler.h" #include "labels.h" #include "opctable.h" #include "output.h" /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static void Mnemonic (const char* M) /* Indent and output a mnemonic */ { Indent (MCol); Output ("%s", M); } static void OneLine (const OpcDesc* D, const char* Arg, ...) attribute ((format(printf, 2, 3))); static void OneLine (const OpcDesc* D, const char* Arg, ...) /* Output one line with the given mnemonic and argument */ { char Buf [256]; va_list ap; /* Mnemonic */ Mnemonic (D->Mnemo); /* Argument */ va_start (ap, Arg); xvsprintf (Buf, sizeof (Buf), Arg, ap); va_end (ap); Indent (ACol); Output ("%s", Buf); /* Add the code stuff as comment */ LineComment (PC, D->Size); /* End the line */ LineFeed (); } static const char* GetAbsOverride (unsigned Flags, unsigned Addr) /* If the instruction requires an abs override modifier, return the necessary * string, otherwise return the empty string. */ { if ((Flags & flAbsOverride) != 0 && Addr < 0x100) { return "a:"; } else { return ""; } } static const char* GetAddrArg (unsigned Flags, unsigned Addr) /* Return an address argument - a label if we have one, or the address itself */ { const char* Label = 0; if (Flags & flUseLabel) { Label = GetLabel (Addr, PC); } if (Label) { return Label; } else { static char Buf [32]; if (Addr < 0x100) { xsprintf (Buf, sizeof (Buf), "$%02X", Addr); } else { xsprintf (Buf, sizeof (Buf), "$%04X", Addr); } return Buf; } } static void GenerateLabel (unsigned Flags, unsigned Addr) /* Generate a label in pass one if requested */ { /* Generate labels in pass #1, and only if we don't have a label already */ if (Pass == 1 && !HaveLabel (Addr) && /* Check if we must create a label */ ((Flags & flGenLabel) != 0 || ((Flags & flUseLabel) != 0 && Addr >= CodeStart && Addr <= CodeEnd))) { /* As a special case, handle ranges with tables or similar. Within * such a range with a granularity > 1, do only generate dependent * labels for all addresses but the first one. Be sure to generate * a label for the start of the range, however. */ attr_t Style = GetStyleAttr (Addr); unsigned Granularity = GetGranularity (Style); if (Granularity == 1) { /* Just add the label */ AddIntLabel (Addr); } else { /* THIS CODE IS A MESS AND WILL FAIL ON SEVERAL CONDITIONS! ### */ /* Search for the start of the range or the last non dependent * label in the range. */ unsigned Offs; attr_t LabelAttr; unsigned LabelAddr = Addr; while (LabelAddr > CodeStart) { if (Style != GetStyleAttr (LabelAddr-1)) { /* End of range reached */ break; } --LabelAddr; LabelAttr = GetLabelAttr (LabelAddr); if ((LabelAttr & (atIntLabel|atExtLabel)) != 0) { /* The address has an internal or external label */ break; } } /* If the proposed label address doesn't have a label, define one */ if ((GetLabelAttr (LabelAddr) & (atIntLabel|atExtLabel)) == 0) { AddIntLabel (LabelAddr); } /* Create the label */ Offs = Addr - LabelAddr; if (Offs == 0) { AddIntLabel (Addr); } else { AddDepLabel (Addr, atIntLabel, GetLabelName (LabelAddr), Offs); } } } } /*****************************************************************************/ /* Code */ /*****************************************************************************/ void OH_Illegal (const OpcDesc* D attribute ((unused))) { DataByteLine (1); } void OH_Accumulator (const OpcDesc* D) { OneLine (D, "a"); } void OH_Implicit (const OpcDesc* D) { Mnemonic (D->Mnemo); LineComment (PC, D->Size); LineFeed (); } void OH_Immediate (const OpcDesc* D) { OneLine (D, "#$%02X", GetCodeByte (PC+1)); } void OH_Direct (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeByte (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "%s", GetAddrArg (D->Flags, Addr)); } void OH_DirectX (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeByte (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "%s,x", GetAddrArg (D->Flags, Addr)); } void OH_DirectY (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeByte (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "%s,y", GetAddrArg (D->Flags, Addr)); } void OH_Absolute (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeWord (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "%s%s", GetAbsOverride (D->Flags, Addr), GetAddrArg (D->Flags, Addr)); } void OH_AbsoluteX (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeWord (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "%s%s,x", GetAbsOverride (D->Flags, Addr), GetAddrArg (D->Flags, Addr)); } void OH_AbsoluteY (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeWord (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "%s%s,y", GetAbsOverride (D->Flags, Addr), GetAddrArg (D->Flags, Addr)); } void OH_AbsoluteLong (const OpcDesc* D attribute ((unused))) { Error ("Not implemented"); } void OH_AbsoluteLongX (const OpcDesc* D attribute ((unused))) { Error ("Not implemented"); } void OH_Relative (const OpcDesc* D) { /* Get the operand */ signed char Offs = GetCodeByte (PC+1); /* Calculate the target address */ unsigned Addr = (((int) PC+2) + Offs) & 0xFFFF; /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "%s", GetAddrArg (D->Flags, Addr)); } void OH_RelativeLong (const OpcDesc* D attribute ((unused))) { Error ("Not implemented"); } void OH_DirectIndirect (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeByte (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "(%s)", GetAddrArg (D->Flags, Addr)); } void OH_DirectIndirectY (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeByte (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "(%s),y", GetAddrArg (D->Flags, Addr)); } void OH_DirectXIndirect (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeByte (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "(%s,x)", GetAddrArg (D->Flags, Addr)); } void OH_AbsoluteIndirect (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeWord (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "(%s)", GetAddrArg (D->Flags, Addr)); } void OH_BitBranch (const OpcDesc* D) { /* Get the operands */ unsigned char TestAddr = GetCodeByte (PC+1); signed char BranchOffs = GetCodeByte (PC+2); /* Calculate the target address for the branch */ unsigned BranchAddr = (((int) PC+3) + BranchOffs) & 0xFFFF; /* Generate labels in pass 1. The bit branch codes are special in that * they don't really match the remainder of the 6502 instruction set (they * are a Rockwell addon), so we must pass additional flags as direct * value to the second GenerateLabel call. */ GenerateLabel (D->Flags, TestAddr); GenerateLabel (flLabel, BranchAddr); /* Output the line */ OneLine (D, "%s,%s", GetAddrArg (D->Flags, TestAddr), GetAddrArg (flLabel, BranchAddr)); } void OH_ImmediateDirect (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeByte (PC+2); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "#$%02X,%s", GetCodeByte (PC+1), GetAddrArg (D->Flags, Addr)); } void OH_ImmediateDirectX (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeByte (PC+2); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "#$%02X,%s,x", GetCodeByte (PC+1), GetAddrArg (D->Flags, Addr)); } void OH_ImmediateAbsolute (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeWord (PC+2); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "#$%02X,%s%s", GetCodeByte (PC+1), GetAbsOverride (D->Flags, Addr), GetAddrArg (D->Flags, Addr)); } void OH_ImmediateAbsoluteX (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeWord (PC+2); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "#$%02X,%s%s,x", GetCodeByte (PC+1), GetAbsOverride (D->Flags, Addr), GetAddrArg (D->Flags, Addr)); } void OH_StackRelative (const OpcDesc* D attribute ((unused))) { Error ("Not implemented"); } void OH_DirectIndirectLongX (const OpcDesc* D attribute ((unused))) { Error ("Not implemented"); } void OH_StackRelativeIndirectY (const OpcDesc* D attribute ((unused))) { Error ("Not implemented"); } void OH_DirectIndirectLong (const OpcDesc* D attribute ((unused))) { Error ("Not implemented"); } void OH_DirectIndirectLongY (const OpcDesc* D attribute ((unused))) { Error ("Not implemented"); } void OH_BlockMove (const OpcDesc* D attribute ((unused))) { /* Get source operand */ unsigned Src = GetCodeWord (PC+1); /* Get destination operand */ unsigned Dst = GetCodeWord (PC+3); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Src); GenerateLabel (D->Flags, Dst); /* Output the line */ OneLine (D, "%s%s,%s%s,#$%02X", GetAbsOverride (D->Flags, Src), GetAddrArg (D->Flags, Src), GetAbsOverride (D->Flags, Dst), GetAddrArg (D->Flags, Dst), GetCodeWord (PC+5)); } void OH_AbsoluteXIndirect (const OpcDesc* D attribute ((unused))) { /* Get the operand */ unsigned Addr = GetCodeWord (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "(%s,x)", GetAddrArg (D->Flags, Addr)); } void OH_DirectImmediate (const OpcDesc* D) { /* Get the operand */ unsigned Addr = GetCodeByte (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "%s, #$%02X", GetAddrArg (D->Flags, Addr), GetCodeByte (PC+2)); } void OH_ZeroPageBit (const OpcDesc* D) { unsigned Bit = GetCodeByte (PC) >> 5; unsigned Addr = GetCodeByte (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* Output the line */ OneLine (D, "%01X,%s", Bit, GetAddrArg (D->Flags, Addr)); } void OH_AccumulatorBit (const OpcDesc* D) { unsigned Bit = GetCodeByte (PC) >> 5; /* Output the line */ OneLine (D, "%01X,a", Bit); } void OH_AccumulatorBitBranch (const OpcDesc* D) { unsigned Bit = GetCodeByte (PC) >> 5; signed char BranchOffs = GetCodeByte (PC+1); /* Calculate the target address for the branch */ unsigned BranchAddr = (((int) PC+3) + BranchOffs) & 0xFFFF; /* Generate labels in pass 1 */ GenerateLabel (flLabel, BranchAddr); /* Output the line */ OneLine (D, "%01X,a,%s", Bit, GetAddrArg (flLabel, BranchAddr)); } void OH_JmpDirectIndirect (const OpcDesc* D) { OH_DirectIndirect (D); if (NewlineAfterJMP) { LineFeed (); } SeparatorLine (); } void OH_SpecialPage (const OpcDesc* D) { /* Get the operand */ unsigned Addr = 0xFF00 + GetCodeByte (PC+1); /* Generate a label in pass 1 */ GenerateLabel (D->Flags, Addr); /* OneLine (D, "$FF%02X", (CodeByte (PC+1)); */ OneLine (D, "%s", GetAddrArg (D->Flags, Addr)); } void OH_Rts (const OpcDesc* D) { OH_Implicit (D); if (NewlineAfterRTS) { LineFeed (); } SeparatorLine(); } void OH_JmpAbsolute (const OpcDesc* D) { OH_Absolute (D); if (NewlineAfterJMP) { LineFeed (); } SeparatorLine (); } void OH_JmpAbsoluteIndirect (const OpcDesc* D) { OH_AbsoluteIndirect (D); if (NewlineAfterJMP) { LineFeed (); } SeparatorLine (); }
986
./cc65/src/da65/code.c
/*****************************************************************************/ /* */ /* code.c */ /* */ /* Binary code management */ /* */ /* */ /* */ /* (C) 2000-2003 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <errno.h> /* common */ #include "check.h" /* da65 */ #include "code.h" #include "error.h" #include "global.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ unsigned char CodeBuf [0x10000]; /* Code buffer */ unsigned long CodeStart; /* Start address */ unsigned long CodeEnd; /* End address */ unsigned long PC; /* Current PC */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ void LoadCode (void) /* Load the code from the given file */ { long Count, MaxCount, Size; FILE* F; PRECONDITION (StartAddr < 0x10000); /* Open the file */ F = fopen (InFile, "rb"); if (F == 0) { Error ("Cannot open `%s': %s", InFile, strerror (errno)); } /* Seek to the end to get the size of the file */ if (fseek (F, 0, SEEK_END) != 0) { Error ("Cannot seek on file `%s': %s", InFile, strerror (errno)); } Size = ftell (F); /* The input offset must be smaller than the size */ if (InputOffs >= 0) { if (InputOffs >= Size) { Error ("Input offset is greater than file size"); } } else { /* Use a zero offset */ InputOffs = 0; } /* Seek to the input offset and correct size to contain the remainder of * the file. */ if (fseek (F, InputOffs, SEEK_SET) != 0) { Error ("Cannot seek on file `%s': %s", InFile, strerror (errno)); } Size -= InputOffs; /* Limit the size to the maximum input size if one is given */ if (InputSize >= 0) { if (InputSize > Size) { Error ("Input size is greater than what is available"); } Size = InputSize; } /* If the start address was not given, set it so that the code loads to * 0x10000 - Size. This is a reasonable default assuming that the file * is a ROM that contains the hardware vectors at $FFFA. */ if (StartAddr < 0) { if (Size > 0x10000) { StartAddr = 0; } else { StartAddr = 0x10000 - Size; } } /* Calculate the maximum code size */ MaxCount = 0x10000 - StartAddr; /* Check if the size is larger than what we can read */ if (Size == 0) { Error ("Nothing to read from input file `%s'", InFile); } if (Size > MaxCount) { Warning ("File `%s' is too large, ignoring %ld bytes", InFile, Size - MaxCount); } else if (MaxCount > Size) { MaxCount = (unsigned) Size; } /* Read from the file and remember the number of bytes read */ Count = fread (CodeBuf + StartAddr, 1, MaxCount, F); if (ferror (F) || Count != MaxCount) { Error ("Error reading from `%s': %s", InFile, strerror (errno)); } /* Close the file */ fclose (F); /* Set the buffer variables */ CodeStart = PC = StartAddr; CodeEnd = CodeStart + Count - 1; /* CodeEnd is inclusive */ } unsigned char GetCodeByte (unsigned Addr) /* Get a byte from the given address */ { PRECONDITION (Addr <= CodeEnd); return CodeBuf [Addr]; } unsigned GetCodeDByte (unsigned Addr) /* Get a dbyte from the given address */ { unsigned Lo = GetCodeByte (Addr); unsigned Hi = GetCodeByte (Addr+1); return (Lo <<8) | Hi; } unsigned GetCodeWord (unsigned Addr) /* Get a word from the given address */ { unsigned Lo = GetCodeByte (Addr); unsigned Hi = GetCodeByte (Addr+1); return Lo | (Hi << 8); } unsigned long GetCodeDWord (unsigned Addr) /* Get a dword from the given address */ { unsigned long Lo = GetCodeWord (Addr); unsigned long Hi = GetCodeWord (Addr+2); return Lo | (Hi << 16); } unsigned GetRemainingBytes (void) /* Return the number of remaining code bytes */ { if (CodeEnd >= PC) { return (CodeEnd - PC + 1); } else { return 0; } } int CodeLeft (void) /* Return true if there are code bytes left */ { return (PC <= CodeEnd); } void ResetCode (void) /* Reset the code input to start over for the next pass */ { PC = CodeStart; }
987
./cc65/src/da65/opc65c02.c
/*****************************************************************************/ /* */ /* opc65c02.c */ /* */ /* 65C02 opcode description table */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* da65 */ #include "handler.h" #include "opc65c02.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Descriptions for all opcodes */ const OpcDesc OpcTable_65C02[256] = { { "brk", 1, flNone, OH_Implicit }, /* $00 */ { "ora", 2, flUseLabel, OH_DirectXIndirect }, /* $01 */ { "", 1, flIllegal, OH_Illegal, }, /* $02 */ { "", 1, flIllegal, OH_Illegal, }, /* $03 */ { "tsb", 2, flUseLabel, OH_Direct }, /* $04 */ { "ora", 2, flUseLabel, OH_Direct }, /* $05 */ { "asl", 2, flUseLabel, OH_Direct }, /* $06 */ { "rmb0", 2, flUseLabel, OH_Direct, }, /* $07 */ { "php", 1, flNone, OH_Implicit }, /* $08 */ { "ora", 2, flNone, OH_Immediate }, /* $09 */ { "asl", 1, flNone, OH_Accumulator }, /* $0a */ { "", 1, flIllegal, OH_Illegal, }, /* $0b */ { "tsb", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0c */ { "ora", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0d */ { "asl", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0e */ { "bbr0", 3, flUseLabel, OH_BitBranch }, /* $0f */ { "bpl", 2, flLabel, OH_Relative }, /* $10 */ { "ora", 2, flUseLabel, OH_DirectIndirectY }, /* $11 */ { "ora", 2, flUseLabel, OH_DirectIndirect }, /* $12 */ { "", 1, flIllegal, OH_Illegal, }, /* $13 */ { "trb", 2, flUseLabel, OH_Direct }, /* $14 */ { "ora", 2, flUseLabel, OH_DirectX }, /* $15 */ { "asl", 2, flUseLabel, OH_DirectX }, /* $16 */ { "rmb1", 2, flUseLabel, OH_Direct, }, /* $17 */ { "clc", 1, flNone, OH_Implicit }, /* $18 */ { "ora", 3, flUseLabel, OH_AbsoluteY }, /* $19 */ { "inc", 1, flNone, OH_Accumulator }, /* $1a */ { "", 1, flIllegal, OH_Illegal, }, /* $1b */ { "trb", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $1c */ { "ora", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1d */ { "asl", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1e */ { "bbr1", 3, flUseLabel, OH_BitBranch }, /* $1f */ { "jsr", 3, flLabel, OH_Absolute }, /* $20 */ { "and", 2, flUseLabel, OH_DirectXIndirect }, /* $21 */ { "", 1, flIllegal, OH_Illegal, }, /* $22 */ { "", 1, flIllegal, OH_Illegal, }, /* $23 */ { "bit", 2, flUseLabel, OH_Direct }, /* $24 */ { "and", 2, flUseLabel, OH_Direct }, /* $25 */ { "rol", 2, flUseLabel, OH_Direct }, /* $26 */ { "rmb2", 2, flUseLabel, OH_Direct, }, /* $27 */ { "plp", 1, flNone, OH_Implicit }, /* $28 */ { "and", 2, flNone, OH_Immediate }, /* $29 */ { "rol", 1, flNone, OH_Accumulator }, /* $2a */ { "", 1, flIllegal, OH_Illegal, }, /* $2b */ { "bit", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2c */ { "and", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2d */ { "rol", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2e */ { "bbr2", 3, flUseLabel, OH_BitBranch }, /* $2f */ { "bmi", 2, flLabel, OH_Relative }, /* $30 */ { "and", 2, flUseLabel, OH_DirectIndirectY }, /* $31 */ { "and", 2, flUseLabel, OH_DirectIndirect, }, /* $32 */ { "", 1, flIllegal, OH_Illegal, }, /* $33 */ { "bit", 2, flUseLabel, OH_DirectX }, /* $34 */ { "and", 2, flUseLabel, OH_DirectX }, /* $35 */ { "rol", 2, flUseLabel, OH_DirectX }, /* $36 */ { "rmb3", 2, flUseLabel, OH_Direct, }, /* $37 */ { "sec", 1, flNone, OH_Implicit }, /* $38 */ { "and", 3, flUseLabel, OH_AbsoluteY }, /* $39 */ { "dec", 1, flNone, OH_Accumulator }, /* $3a */ { "", 1, flIllegal, OH_Illegal, }, /* $3b */ { "bit", 3, flUseLabel, OH_AbsoluteX }, /* $3c */ { "and", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3d */ { "rol", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3e */ { "bbr3", 3, flUseLabel, OH_BitBranch }, /* $3f */ { "rti", 1, flNone, OH_Rts }, /* $40 */ { "eor", 2, flUseLabel, OH_DirectXIndirect }, /* $41 */ { "", 1, flIllegal, OH_Illegal, }, /* $42 */ { "", 1, flIllegal, OH_Illegal, }, /* $43 */ { "", 1, flIllegal, OH_Illegal, }, /* $44 */ { "eor", 2, flUseLabel, OH_Direct }, /* $45 */ { "lsr", 2, flUseLabel, OH_Direct }, /* $46 */ { "rmb4", 2, flUseLabel, OH_Direct, }, /* $47 */ { "pha", 1, flNone, OH_Implicit }, /* $48 */ { "eor", 2, flNone, OH_Immediate }, /* $49 */ { "lsr", 1, flNone, OH_Accumulator }, /* $4a */ { "", 1, flIllegal, OH_Illegal, }, /* $4b */ { "jmp", 3, flLabel, OH_JmpAbsolute }, /* $4c */ { "eor", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4e */ { "bbr4", 3, flUseLabel, OH_BitBranch }, /* $4f */ { "bvc", 2, flLabel, OH_Relative }, /* $50 */ { "eor", 2, flUseLabel, OH_DirectIndirectY }, /* $51 */ { "eor", 2, flUseLabel, OH_DirectIndirect }, /* $52 */ { "", 1, flIllegal, OH_Illegal, }, /* $53 */ { "", 1, flIllegal, OH_Illegal, }, /* $54 */ { "eor", 2, flUseLabel, OH_DirectX }, /* $55 */ { "lsr", 2, flUseLabel, OH_DirectX }, /* $56 */ { "rmb5", 2, flUseLabel, OH_Direct, }, /* $57 */ { "cli", 1, flNone, OH_Implicit }, /* $58 */ { "eor", 3, flUseLabel, OH_AbsoluteY }, /* $59 */ { "phy", 1, flNone, OH_Implicit }, /* $5a */ { "", 1, flIllegal, OH_Illegal, }, /* $5b */ { "", 1, flIllegal, OH_Illegal, }, /* $5c */ { "eor", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5e */ { "bbr5", 3, flUseLabel, OH_BitBranch }, /* $5f */ { "rts", 1, flNone, OH_Rts }, /* $60 */ { "adc", 2, flUseLabel, OH_DirectXIndirect }, /* $61 */ { "", 1, flIllegal, OH_Illegal, }, /* $62 */ { "", 1, flIllegal, OH_Illegal, }, /* $63 */ { "stz", 2, flUseLabel, OH_Direct }, /* $64 */ { "adc", 2, flUseLabel, OH_Direct }, /* $65 */ { "ror", 2, flUseLabel, OH_Direct }, /* $66 */ { "rmb6", 2, flUseLabel, OH_Direct, }, /* $67 */ { "pla", 1, flNone, OH_Implicit }, /* $68 */ { "adc", 2, flNone, OH_Immediate }, /* $69 */ { "ror", 1, flNone, OH_Accumulator }, /* $6a */ { "", 1, flIllegal, OH_Illegal, }, /* $6b */ { "jmp", 3, flLabel, OH_JmpAbsoluteIndirect }, /* $6c */ { "adc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6d */ { "ror", 3, flUseLabel, OH_Absolute }, /* $6e */ { "bbr6", 3, flUseLabel, OH_BitBranch }, /* $6f */ { "bvs", 2, flLabel, OH_Relative }, /* $70 */ { "adc", 2, flUseLabel, OH_DirectIndirectY }, /* $71 */ { "adc", 2, flUseLabel, OH_DirectIndirect, }, /* $72 */ { "", 1, flIllegal, OH_Illegal, }, /* $73 */ { "stz", 2, flUseLabel, OH_DirectX }, /* $74 */ { "adc", 2, flUseLabel, OH_DirectX }, /* $75 */ { "ror", 2, flUseLabel, OH_DirectX }, /* $76 */ { "rmb7", 2, flUseLabel, OH_Direct, }, /* $77 */ { "sei", 1, flNone, OH_Implicit }, /* $78 */ { "adc", 3, flUseLabel, OH_AbsoluteY }, /* $79 */ { "ply", 1, flNone, OH_Implicit }, /* $7a */ { "", 1, flIllegal, OH_Illegal, }, /* $7b */ { "jmp", 3, flLabel, OH_AbsoluteXIndirect }, /* $7c */ { "adc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7d */ { "ror", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7e */ { "bbr7", 3, flUseLabel, OH_BitBranch }, /* $7f */ { "bra", 2, flLabel, OH_Relative }, /* $80 */ { "sta", 2, flUseLabel, OH_DirectXIndirect }, /* $81 */ { "", 1, flIllegal, OH_Illegal, }, /* $82 */ { "", 1, flIllegal, OH_Illegal, }, /* $83 */ { "sty", 2, flUseLabel, OH_Direct }, /* $84 */ { "sta", 2, flUseLabel, OH_Direct }, /* $85 */ { "stx", 2, flUseLabel, OH_Direct }, /* $86 */ { "smb0", 2, flUseLabel, OH_Direct, }, /* $87 */ { "dey", 1, flNone, OH_Implicit }, /* $88 */ { "bit", 2, flNone, OH_Immediate }, /* $89 */ { "txa", 1, flNone, OH_Implicit }, /* $8a */ { "", 1, flIllegal, OH_Illegal, }, /* $8b */ { "sty", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8c */ { "sta", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8d */ { "stx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8e */ { "bbs0", 3, flUseLabel, OH_BitBranch }, /* $8f */ { "bcc", 2, flLabel, OH_Relative }, /* $90 */ { "sta", 2, flUseLabel, OH_DirectIndirectY }, /* $91 */ { "sta", 2, flUseLabel, OH_DirectIndirect }, /* $92 */ { "", 1, flIllegal, OH_Illegal, }, /* $93 */ { "sty", 2, flUseLabel, OH_DirectX }, /* $94 */ { "sta", 2, flUseLabel, OH_DirectX }, /* $95 */ { "stx", 2, flUseLabel, OH_DirectY }, /* $96 */ { "smb1", 2, flUseLabel, OH_Direct, }, /* $97 */ { "tya", 1, flNone, OH_Implicit }, /* $98 */ { "sta", 3, flUseLabel, OH_AbsoluteY }, /* $99 */ { "txs", 1, flNone, OH_Implicit }, /* $9a */ { "", 1, flIllegal, OH_Illegal, }, /* $9b */ { "stz", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $9c */ { "sta", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $9d */ { "stz", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $9e */ { "bbs1", 3, flUseLabel, OH_BitBranch }, /* $9f */ { "ldy", 2, flNone, OH_Immediate }, /* $a0 */ { "lda", 2, flUseLabel, OH_DirectXIndirect }, /* $a1 */ { "ldx", 2, flNone, OH_Immediate }, /* $a2 */ { "", 1, flIllegal, OH_Illegal, }, /* $a3 */ { "ldy", 2, flUseLabel, OH_Direct }, /* $a4 */ { "lda", 2, flUseLabel, OH_Direct }, /* $a5 */ { "ldx", 2, flUseLabel, OH_Direct }, /* $a6 */ { "smb2", 2, flUseLabel, OH_Direct, }, /* $a7 */ { "tay", 1, flNone, OH_Implicit }, /* $a8 */ { "lda", 2, flNone, OH_Immediate }, /* $a9 */ { "tax", 1, flNone, OH_Implicit }, /* $aa */ { "", 1, flIllegal, OH_Illegal, }, /* $ab */ { "ldy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ac */ { "lda", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ad */ { "ldx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ae */ { "bbs2", 3, flUseLabel, OH_BitBranch }, /* $af */ { "bcs", 2, flLabel, OH_Relative }, /* $b0 */ { "lda", 2, flUseLabel, OH_DirectIndirectY }, /* $b1 */ { "lda", 2, flUseLabel, OH_DirectIndirect }, /* $b2 */ { "", 1, flIllegal, OH_Illegal, }, /* $b3 */ { "ldy", 2, flUseLabel, OH_DirectX }, /* $b4 */ { "lda", 2, flUseLabel, OH_DirectX }, /* $b5 */ { "ldx", 2, flUseLabel, OH_DirectY }, /* $b6 */ { "smb3", 2, flUseLabel, OH_Direct, }, /* $b7 */ { "clv", 1, flNone, OH_Implicit }, /* $b8 */ { "lda", 3, flUseLabel, OH_AbsoluteY }, /* $b9 */ { "tsx", 1, flNone, OH_Implicit }, /* $ba */ { "", 1, flIllegal, OH_Illegal, }, /* $bb */ { "ldy", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bc */ { "lda", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bd */ { "ldx", 3, flUseLabel|flAbsOverride, OH_AbsoluteY }, /* $be */ { "bbs3", 3, flUseLabel, OH_BitBranch }, /* $bf */ { "cpy", 2, flNone, OH_Immediate }, /* $c0 */ { "cmp", 2, flUseLabel, OH_DirectXIndirect }, /* $c1 */ { "", 1, flIllegal, OH_Illegal, }, /* $c2 */ { "", 1, flIllegal, OH_Illegal, }, /* $c3 */ { "cpy", 2, flUseLabel, OH_Direct }, /* $c4 */ { "cmp", 2, flUseLabel, OH_Direct }, /* $c5 */ { "dec", 2, flUseLabel, OH_Direct }, /* $c6 */ { "smb4", 2, flUseLabel, OH_Direct, }, /* $c7 */ { "iny", 1, flNone, OH_Implicit }, /* $c8 */ { "cmp", 2, flNone, OH_Immediate }, /* $c9 */ { "dex", 1, flNone, OH_Implicit }, /* $ca */ { "", 1, flIllegal, OH_Illegal, }, /* $cb */ { "cpy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cd */ { "dec", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ce */ { "bbs4", 3, flUseLabel, OH_BitBranch }, /* $cf */ { "bne", 2, flLabel, OH_Relative }, /* $d0 */ { "cmp", 2, flUseLabel, OH_DirectIndirectY }, /* $d1 */ { "cmp", 2, flUseLabel, OH_DirectIndirect }, /* $d2 */ { "", 1, flIllegal, OH_Illegal, }, /* $d3 */ { "", 1, flIllegal, OH_Illegal, }, /* $d4 */ { "cmp", 2, flUseLabel, OH_DirectX }, /* $d5 */ { "dec", 2, flUseLabel, OH_DirectX }, /* $d6 */ { "smb5", 2, flUseLabel, OH_Direct, }, /* $d7 */ { "cld", 1, flNone, OH_Implicit }, /* $d8 */ { "cmp", 3, flUseLabel, OH_AbsoluteY }, /* $d9 */ { "phx", 1, flNone, OH_Implicit }, /* $da */ { "", 1, flIllegal, OH_Illegal, }, /* $db */ { "", 1, flIllegal, OH_Illegal, }, /* $dc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $dd */ { "dec", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $de */ { "bbs5", 3, flUseLabel, OH_BitBranch }, /* $df */ { "cpx", 2, flNone, OH_Immediate }, /* $e0 */ { "sbc", 2, flUseLabel, OH_DirectXIndirect }, /* $e1 */ { "", 1, flIllegal, OH_Illegal, }, /* $e2 */ { "", 1, flIllegal, OH_Illegal, }, /* $e3 */ { "cpx", 2, flUseLabel, OH_Direct }, /* $e4 */ { "sbc", 2, flUseLabel, OH_Direct }, /* $e5 */ { "inc", 2, flUseLabel, OH_Direct }, /* $e6 */ { "smb6", 2, flUseLabel, OH_Direct, }, /* $e7 */ { "inx", 1, flNone, OH_Implicit }, /* $e8 */ { "sbc", 2, flNone, OH_Immediate }, /* $e9 */ { "nop", 1, flNone, OH_Implicit }, /* $ea */ { "", 1, flIllegal, OH_Illegal, }, /* $eb */ { "cpx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ec */ { "sbc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ed */ { "inc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ee */ { "bbs6", 3, flUseLabel, OH_BitBranch }, /* $ef */ { "beq", 2, flLabel, OH_Relative }, /* $f0 */ { "sbc", 2, flUseLabel, OH_DirectIndirectY }, /* $f1 */ { "sbc", 2, flUseLabel, OH_DirectIndirect }, /* $f2 */ { "", 1, flIllegal, OH_Illegal, }, /* $f3 */ { "", 1, flIllegal, OH_Illegal, }, /* $f4 */ { "sbc", 2, flUseLabel, OH_DirectX }, /* $f5 */ { "inc", 2, flUseLabel, OH_DirectX }, /* $f6 */ { "smb7", 2, flUseLabel, OH_Direct, }, /* $f7 */ { "sed", 1, flNone, OH_Implicit }, /* $f8 */ { "sbc", 3, flUseLabel, OH_AbsoluteY }, /* $f9 */ { "plx", 1, flNone, OH_Implicit }, /* $fa */ { "", 1, flIllegal, OH_Illegal, }, /* $fb */ { "", 1, flIllegal, OH_Illegal, }, /* $fc */ { "sbc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fd */ { "inc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fe */ { "bbs7", 3, flUseLabel, OH_BitBranch }, /* $ff */ };
988
./cc65/src/da65/opc65sc02.c
/*****************************************************************************/ /* */ /* opc65sc02.c */ /* */ /* 65SC02 opcode description table */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* da65 */ #include "handler.h" #include "opc65sc02.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Descriptions for all opcodes */ const OpcDesc OpcTable_65SC02[256] = { { "brk", 1, flNone, OH_Implicit }, /* $00 */ { "ora", 2, flUseLabel, OH_DirectXIndirect }, /* $01 */ { "", 1, flIllegal, OH_Illegal, }, /* $02 */ { "", 1, flIllegal, OH_Illegal, }, /* $03 */ { "tsb", 2, flUseLabel, OH_Direct }, /* $04 */ { "ora", 2, flUseLabel, OH_Direct }, /* $05 */ { "asl", 2, flUseLabel, OH_Direct }, /* $06 */ { "", 1, flIllegal, OH_Illegal, }, /* $07 */ { "php", 1, flNone, OH_Implicit }, /* $08 */ { "ora", 2, flNone, OH_Immediate }, /* $09 */ { "asl", 1, flNone, OH_Accumulator }, /* $0a */ { "", 1, flIllegal, OH_Illegal, }, /* $0b */ { "tsb", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0c */ { "ora", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0d */ { "asl", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0e */ { "", 1, flIllegal, OH_Illegal, }, /* $0f */ { "bpl", 2, flLabel, OH_Relative }, /* $10 */ { "ora", 2, flUseLabel, OH_DirectIndirectY }, /* $11 */ { "ora", 2, flUseLabel, OH_DirectIndirect }, /* $12 */ { "", 1, flIllegal, OH_Illegal, }, /* $13 */ { "trb", 2, flUseLabel, OH_Direct }, /* $14 */ { "ora", 2, flUseLabel, OH_DirectX }, /* $15 */ { "asl", 2, flUseLabel, OH_DirectX }, /* $16 */ { "", 1, flIllegal, OH_Illegal, }, /* $17 */ { "clc", 1, flNone, OH_Implicit }, /* $18 */ { "ora", 3, flUseLabel, OH_AbsoluteY }, /* $19 */ { "inc", 1, flNone, OH_Accumulator }, /* $1a */ { "", 1, flIllegal, OH_Illegal, }, /* $1b */ { "trb", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $1c */ { "ora", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1d */ { "asl", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1e */ { "", 1, flIllegal, OH_Illegal, }, /* $1f */ { "jsr", 3, flLabel, OH_Absolute }, /* $20 */ { "and", 2, flUseLabel, OH_DirectXIndirect }, /* $21 */ { "", 1, flIllegal, OH_Illegal, }, /* $22 */ { "", 1, flIllegal, OH_Illegal, }, /* $23 */ { "bit", 2, flUseLabel, OH_Direct }, /* $24 */ { "and", 2, flUseLabel, OH_Direct }, /* $25 */ { "rol", 2, flUseLabel, OH_Direct }, /* $26 */ { "", 1, flIllegal, OH_Illegal, }, /* $27 */ { "plp", 1, flNone, OH_Implicit }, /* $28 */ { "and", 2, flNone, OH_Immediate }, /* $29 */ { "rol", 1, flNone, OH_Accumulator }, /* $2a */ { "", 1, flIllegal, OH_Illegal, }, /* $2b */ { "bit", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2c */ { "and", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2d */ { "rol", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2e */ { "", 1, flIllegal, OH_Illegal, }, /* $2f */ { "bmi", 2, flLabel, OH_Relative }, /* $30 */ { "and", 2, flUseLabel, OH_DirectIndirectY }, /* $31 */ { "and", 2, flUseLabel, OH_DirectIndirect, }, /* $32 */ { "", 1, flIllegal, OH_Illegal, }, /* $33 */ { "bit", 2, flUseLabel, OH_DirectX }, /* $34 */ { "and", 2, flUseLabel, OH_DirectX }, /* $35 */ { "rol", 2, flUseLabel, OH_DirectX }, /* $36 */ { "", 1, flIllegal, OH_Illegal, }, /* $37 */ { "sec", 1, flNone, OH_Implicit }, /* $38 */ { "and", 3, flUseLabel, OH_AbsoluteY }, /* $39 */ { "dec", 1, flNone, OH_Accumulator }, /* $3a */ { "", 1, flIllegal, OH_Illegal, }, /* $3b */ { "bit", 3, flUseLabel, OH_AbsoluteX }, /* $3c */ { "and", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3d */ { "rol", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3e */ { "", 1, flIllegal, OH_Illegal, }, /* $3f */ { "rti", 1, flNone, OH_Rts }, /* $40 */ { "eor", 2, flUseLabel, OH_DirectXIndirect }, /* $41 */ { "", 1, flIllegal, OH_Illegal, }, /* $42 */ { "", 1, flIllegal, OH_Illegal, }, /* $43 */ { "", 1, flIllegal, OH_Illegal, }, /* $44 */ { "eor", 2, flUseLabel, OH_Direct }, /* $45 */ { "lsr", 2, flUseLabel, OH_Direct }, /* $46 */ { "", 1, flIllegal, OH_Illegal, }, /* $47 */ { "pha", 1, flNone, OH_Implicit }, /* $48 */ { "eor", 2, flNone, OH_Immediate }, /* $49 */ { "lsr", 1, flNone, OH_Accumulator }, /* $4a */ { "", 1, flIllegal, OH_Illegal, }, /* $4b */ { "jmp", 3, flLabel, OH_JmpAbsolute }, /* $4c */ { "eor", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4e */ { "", 1, flIllegal, OH_Illegal, }, /* $4f */ { "bvc", 2, flLabel, OH_Relative }, /* $50 */ { "eor", 2, flUseLabel, OH_DirectIndirectY }, /* $51 */ { "eor", 2, flUseLabel, OH_DirectIndirect }, /* $52 */ { "", 1, flIllegal, OH_Illegal, }, /* $53 */ { "", 1, flIllegal, OH_Illegal, }, /* $54 */ { "eor", 2, flUseLabel, OH_DirectX }, /* $55 */ { "lsr", 2, flUseLabel, OH_DirectX }, /* $56 */ { "", 1, flIllegal, OH_Illegal, }, /* $57 */ { "cli", 1, flNone, OH_Implicit }, /* $58 */ { "eor", 3, flUseLabel, OH_AbsoluteY }, /* $59 */ { "phy", 1, flNone, OH_Implicit }, /* $5a */ { "", 1, flIllegal, OH_Illegal, }, /* $5b */ { "", 1, flIllegal, OH_Illegal, }, /* $5c */ { "eor", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5d */ { "lsr", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5e */ { "", 1, flIllegal, OH_Illegal, }, /* $5f */ { "rts", 1, flNone, OH_Rts }, /* $60 */ { "adc", 2, flUseLabel, OH_DirectXIndirect }, /* $61 */ { "", 1, flIllegal, OH_Illegal, }, /* $62 */ { "", 1, flIllegal, OH_Illegal, }, /* $63 */ { "stz", 2, flUseLabel, OH_Direct }, /* $64 */ { "adc", 2, flUseLabel, OH_Direct }, /* $65 */ { "ror", 2, flUseLabel, OH_Direct }, /* $66 */ { "", 1, flIllegal, OH_Illegal, }, /* $67 */ { "pla", 1, flNone, OH_Implicit }, /* $68 */ { "adc", 2, flNone, OH_Immediate }, /* $69 */ { "ror", 1, flNone, OH_Accumulator }, /* $6a */ { "", 1, flIllegal, OH_Illegal, }, /* $6b */ { "jmp", 3, flLabel, OH_JmpAbsoluteIndirect }, /* $6c */ { "adc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6d */ { "ror", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6e */ { "", 1, flIllegal, OH_Illegal, }, /* $6f */ { "bvs", 2, flLabel, OH_Relative }, /* $70 */ { "adc", 2, flUseLabel, OH_DirectIndirectY }, /* $71 */ { "adc", 2, flUseLabel, OH_DirectIndirect, }, /* $72 */ { "", 1, flIllegal, OH_Illegal, }, /* $73 */ { "stz", 2, flUseLabel, OH_DirectX }, /* $74 */ { "adc", 2, flUseLabel, OH_DirectX }, /* $75 */ { "ror", 2, flUseLabel, OH_DirectX }, /* $76 */ { "", 1, flIllegal, OH_Illegal, }, /* $77 */ { "sei", 1, flNone, OH_Implicit }, /* $78 */ { "adc", 3, flUseLabel, OH_AbsoluteY }, /* $79 */ { "ply", 1, flNone, OH_Implicit }, /* $7a */ { "", 1, flIllegal, OH_Illegal, }, /* $7b */ { "jmp", 3, flLabel, OH_AbsoluteXIndirect }, /* $7c */ { "adc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7d */ { "ror", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7e */ { "", 1, flIllegal, OH_Illegal, }, /* $7f */ { "bra", 2, flLabel, OH_Relative }, /* $80 */ { "sta", 2, flUseLabel, OH_DirectXIndirect }, /* $81 */ { "", 1, flIllegal, OH_Illegal, }, /* $82 */ { "", 1, flIllegal, OH_Illegal, }, /* $83 */ { "sty", 2, flUseLabel, OH_Direct }, /* $84 */ { "sta", 2, flUseLabel, OH_Direct }, /* $85 */ { "stx", 2, flUseLabel, OH_Direct }, /* $86 */ { "", 1, flIllegal, OH_Illegal, }, /* $87 */ { "dey", 1, flNone, OH_Implicit }, /* $88 */ { "bit", 2, flNone, OH_Immediate }, /* $89 */ { "txa", 1, flNone, OH_Implicit }, /* $8a */ { "", 1, flIllegal, OH_Illegal, }, /* $8b */ { "sty", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8c */ { "sta", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8d */ { "stx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8e */ { "", 1, flIllegal, OH_Illegal, }, /* $8f */ { "bcc", 2, flLabel, OH_Relative }, /* $90 */ { "sta", 2, flUseLabel, OH_DirectIndirectY }, /* $91 */ { "sta", 2, flUseLabel, OH_DirectIndirect }, /* $92 */ { "", 1, flIllegal, OH_Illegal, }, /* $93 */ { "sty", 2, flUseLabel, OH_DirectX }, /* $94 */ { "sta", 2, flUseLabel, OH_DirectX }, /* $95 */ { "stx", 2, flUseLabel, OH_DirectY }, /* $96 */ { "", 1, flIllegal, OH_Illegal, }, /* $97 */ { "tya", 1, flNone, OH_Implicit }, /* $98 */ { "sta", 3, flUseLabel, OH_AbsoluteY }, /* $99 */ { "txs", 1, flNone, OH_Implicit }, /* $9a */ { "", 1, flIllegal, OH_Illegal, }, /* $9b */ { "stz", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $9c */ { "sta", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $9d */ { "stz", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $9e */ { "", 1, flIllegal, OH_Illegal, }, /* $9f */ { "ldy", 2, flNone, OH_Immediate }, /* $a0 */ { "lda", 2, flUseLabel, OH_DirectXIndirect }, /* $a1 */ { "ldx", 2, flNone, OH_Immediate }, /* $a2 */ { "", 1, flIllegal, OH_Illegal, }, /* $a3 */ { "ldy", 2, flUseLabel, OH_Direct }, /* $a4 */ { "lda", 2, flUseLabel, OH_Direct }, /* $a5 */ { "ldx", 2, flUseLabel, OH_Direct }, /* $a6 */ { "", 1, flIllegal, OH_Illegal, }, /* $a7 */ { "tay", 1, flNone, OH_Implicit }, /* $a8 */ { "lda", 2, flNone, OH_Immediate }, /* $a9 */ { "tax", 1, flNone, OH_Implicit }, /* $aa */ { "", 1, flIllegal, OH_Illegal, }, /* $ab */ { "ldy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ac */ { "lda", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ad */ { "ldx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ae */ { "", 1, flIllegal, OH_Illegal, }, /* $af */ { "bcs", 2, flLabel, OH_Relative }, /* $b0 */ { "lda", 2, flUseLabel, OH_DirectIndirectY }, /* $b1 */ { "lda", 2, flUseLabel, OH_DirectIndirect }, /* $b2 */ { "", 1, flIllegal, OH_Illegal, }, /* $b3 */ { "ldy", 2, flUseLabel, OH_DirectX }, /* $b4 */ { "lda", 2, flUseLabel, OH_DirectX }, /* $b5 */ { "ldx", 2, flUseLabel, OH_DirectY }, /* $b6 */ { "", 1, flIllegal, OH_Illegal, }, /* $b7 */ { "clv", 1, flNone, OH_Implicit }, /* $b8 */ { "lda", 3, flUseLabel, OH_AbsoluteY }, /* $b9 */ { "tsx", 1, flNone, OH_Implicit }, /* $ba */ { "", 1, flIllegal, OH_Illegal, }, /* $bb */ { "ldy", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bc */ { "lda", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bd */ { "ldx", 3, flUseLabel|flAbsOverride, OH_AbsoluteY }, /* $be */ { "", 1, flIllegal, OH_Illegal, }, /* $bf */ { "cpy", 2, flNone, OH_Immediate }, /* $c0 */ { "cmp", 2, flUseLabel, OH_DirectXIndirect }, /* $c1 */ { "", 1, flIllegal, OH_Illegal, }, /* $c2 */ { "", 1, flIllegal, OH_Illegal, }, /* $c3 */ { "cpy", 2, flUseLabel, OH_Direct }, /* $c4 */ { "cmp", 2, flUseLabel, OH_Direct }, /* $c5 */ { "dec", 2, flUseLabel, OH_Direct }, /* $c6 */ { "", 1, flIllegal, OH_Illegal, }, /* $c7 */ { "iny", 1, flNone, OH_Implicit }, /* $c8 */ { "cmp", 2, flNone, OH_Immediate }, /* $c9 */ { "dex", 1, flNone, OH_Implicit }, /* $ca */ { "", 1, flIllegal, OH_Illegal, }, /* $cb */ { "cpy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cd */ { "dec", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ce */ { "", 1, flIllegal, OH_Illegal, }, /* $cf */ { "bne", 2, flLabel, OH_Relative }, /* $d0 */ { "cmp", 2, flUseLabel, OH_DirectIndirectY }, /* $d1 */ { "cmp", 2, flUseLabel, OH_DirectIndirect }, /* $d2 */ { "", 1, flIllegal, OH_Illegal, }, /* $d3 */ { "", 1, flIllegal, OH_Illegal, }, /* $d4 */ { "cmp", 2, flUseLabel, OH_DirectX }, /* $d5 */ { "dec", 2, flUseLabel, OH_DirectX }, /* $d6 */ { "", 1, flIllegal, OH_Illegal, }, /* $d7 */ { "cld", 1, flNone, OH_Implicit }, /* $d8 */ { "cmp", 3, flUseLabel, OH_AbsoluteY }, /* $d9 */ { "phx", 1, flNone, OH_Implicit }, /* $da */ { "", 1, flIllegal, OH_Illegal, }, /* $db */ { "", 1, flIllegal, OH_Illegal, }, /* $dc */ { "cmp", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $dd */ { "dec", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $de */ { "", 1, flIllegal, OH_Illegal, }, /* $df */ { "cpx", 2, flNone, OH_Immediate }, /* $e0 */ { "sbc", 2, flUseLabel, OH_DirectXIndirect }, /* $e1 */ { "", 1, flIllegal, OH_Illegal, }, /* $e2 */ { "", 1, flIllegal, OH_Illegal, }, /* $e3 */ { "cpx", 2, flUseLabel, OH_Direct }, /* $e4 */ { "sbc", 2, flUseLabel, OH_Direct }, /* $e5 */ { "inc", 2, flUseLabel, OH_Direct }, /* $e6 */ { "", 1, flIllegal, OH_Illegal, }, /* $e7 */ { "inx", 1, flNone, OH_Implicit }, /* $e8 */ { "sbc", 2, flNone, OH_Immediate }, /* $e9 */ { "nop", 1, flNone, OH_Implicit }, /* $ea */ { "", 1, flIllegal, OH_Illegal, }, /* $eb */ { "cpx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ec */ { "sbc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ed */ { "inc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ee */ { "", 1, flIllegal, OH_Illegal, }, /* $ef */ { "beq", 2, flLabel, OH_Relative }, /* $f0 */ { "sbc", 2, flUseLabel, OH_DirectIndirectY }, /* $f1 */ { "sbc", 2, flUseLabel, OH_DirectIndirect }, /* $f2 */ { "", 1, flIllegal, OH_Illegal, }, /* $f3 */ { "", 1, flIllegal, OH_Illegal, }, /* $f4 */ { "sbc", 2, flUseLabel, OH_DirectX }, /* $f5 */ { "inc", 2, flUseLabel, OH_DirectX }, /* $f6 */ { "", 1, flIllegal, OH_Illegal, }, /* $f7 */ { "sed", 1, flNone, OH_Implicit }, /* $f8 */ { "sbc", 3, flUseLabel, OH_AbsoluteY }, /* $f9 */ { "plx", 1, flNone, OH_Implicit }, /* $fa */ { "", 1, flIllegal, OH_Illegal, }, /* $fb */ { "", 1, flIllegal, OH_Illegal, }, /* $fc */ { "sbc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fd */ { "inc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fe */ { "", 1, flIllegal, OH_Illegal, }, /* $ff */ };
989
./cc65/src/ld65/segments.c
/*****************************************************************************/ /* */ /* segments.c */ /* */ /* Segment handling for the ld65 linker */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> /* common */ #include "addrsize.h" #include "alignment.h" #include "check.h" #include "coll.h" #include "exprdefs.h" #include "fragdefs.h" #include "hashfunc.h" #include "print.h" #include "segdefs.h" #include "symdefs.h" #include "xmalloc.h" /* ld65 */ #include "error.h" #include "expr.h" #include "fileio.h" #include "fragment.h" #include "global.h" #include "lineinfo.h" #include "segments.h" #include "spool.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Hash table */ #define HASHTAB_MASK 0x3FU #define HASHTAB_SIZE (HASHTAB_MASK + 1) static Segment* HashTab[HASHTAB_SIZE]; /* List of all segments */ static Collection SegmentList = STATIC_COLLECTION_INITIALIZER; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static Segment* NewSegment (unsigned Name, unsigned char AddrSize) /* Create a new segment and initialize it */ { unsigned Hash; /* Allocate memory */ Segment* S = xmalloc (sizeof (Segment)); /* Initialize the fields */ S->Name = Name; S->Next = 0; S->Flags = SEG_FLAG_NONE; S->Sections = EmptyCollection; S->MemArea = 0; S->PC = 0; S->Size = 0; S->OutputName = 0; S->OutputOffs = 0; S->Alignment = 1; S->FillVal = 0; S->AddrSize = AddrSize; S->ReadOnly = 0; S->Dumped = 0; /* Insert the segment into the segment list and assign the segment id */ S->Id = CollCount (&SegmentList); CollAppend (&SegmentList, S); /* Insert the segment into the segment hash list */ Hash = (S->Name & HASHTAB_MASK); S->Next = HashTab[Hash]; HashTab[Hash] = S; /* Return the new entry */ return S; } Segment* GetSegment (unsigned Name, unsigned char AddrSize, const char* ObjName) /* Search for a segment and return an existing one. If the segment does not * exist, create a new one and return that. ObjName is only used for the error * message and may be NULL if the segment is linker generated. */ { /* Try to locate the segment in the table */ Segment* S = SegFind (Name); /* If we don't have that segment already, allocate it using the type of * the first section. */ if (S == 0) { /* Create a new segment */ S = NewSegment (Name, AddrSize); } else { /* Check if the existing segment has the requested address size */ if (S->AddrSize != AddrSize) { /* Allow an empty object name */ if (ObjName == 0) { ObjName = "[linker generated]"; } Error ("Module `%s': Type mismatch for segment `%s'", ObjName, GetString (Name)); } } /* Return the segment */ return S; } Section* NewSection (Segment* Seg, unsigned long Alignment, unsigned char AddrSize) /* Create a new section for the given segment */ { /* Allocate memory */ Section* S = xmalloc (sizeof (Section)); /* Initialize the data */ S->Next = 0; S->Seg = Seg; S->Obj = 0; S->FragRoot = 0; S->FragLast = 0; S->Size = 0; S->Alignment= Alignment; S->AddrSize = AddrSize; /* Calculate the alignment bytes needed for the section */ S->Fill = AlignCount (Seg->Size, S->Alignment); /* Adjust the segment size and set the section offset */ Seg->Size += S->Fill; S->Offs = Seg->Size; /* Current size is offset */ /* Insert the section into the segment */ CollAppend (&Seg->Sections, S); /* Return the struct */ return S; } Section* ReadSection (FILE* F, ObjData* O) /* Read a section from a file */ { unsigned Name; unsigned Size; unsigned long Alignment; unsigned char Type; unsigned FragCount; Segment* S; Section* Sec; /* Read the segment data */ (void) Read32 (F); /* File size of data */ Name = MakeGlobalStringId (O, ReadVar (F)); /* Segment name */ ReadVar (F); /* Segment flags (currently unused) */ Size = ReadVar (F); /* Size of data */ Alignment = ReadVar (F); /* Alignment */ Type = Read8 (F); /* Segment type */ FragCount = ReadVar (F); /* Number of fragments */ /* Print some data */ Print (stdout, 2, "Module `%s': Found segment `%s', size = %u, alignment = %lu, type = %u\n", GetObjFileName (O), GetString (Name), Size, Alignment, Type); /* Get the segment for this section */ S = GetSegment (Name, Type, GetObjFileName (O)); /* Allocate the section we will return later */ Sec = NewSection (S, Alignment, Type); /* Remember the object file this section was from */ Sec->Obj = O; /* Set up the combined segment alignment */ if (Sec->Alignment > 1) { Alignment = LeastCommonMultiple (S->Alignment, Sec->Alignment); if (Alignment > MAX_ALIGNMENT) { Error ("Combined alignment for segment `%s' is %lu which exceeds " "%lu. Last module requiring alignment was `%s'.", GetString (Name), Alignment, MAX_ALIGNMENT, GetObjFileName (O)); } else if (Alignment >= LARGE_ALIGNMENT) { Warning ("Combined alignment for segment `%s' is suspiciously " "large (%lu). Last module requiring alignment was `%s'.", GetString (Name), Alignment, GetObjFileName (O)); } S->Alignment = Alignment; } /* Start reading fragments from the file and insert them into the section . */ while (FragCount--) { Fragment* Frag; /* Read the fragment type */ unsigned char Type = Read8 (F); /* Extract the check mask from the type */ unsigned char Bytes = Type & FRAG_BYTEMASK; Type &= FRAG_TYPEMASK; /* Handle the different fragment types */ switch (Type) { case FRAG_LITERAL: Frag = NewFragment (Type, ReadVar (F), Sec); ReadData (F, Frag->LitBuf, Frag->Size); break; case FRAG_EXPR: case FRAG_SEXPR: Frag = NewFragment (Type, Bytes, Sec); Frag->Expr = ReadExpr (F, O); break; case FRAG_FILL: /* Will allocate memory, but we don't care... */ Frag = NewFragment (Type, ReadVar (F), Sec); break; default: Error ("Unknown fragment type in module `%s', segment `%s': %02X", GetObjFileName (O), GetString (S->Name), Type); /* NOTREACHED */ return 0; } /* Read the line infos into the list of the fragment */ ReadLineInfoList (F, O, &Frag->LineInfos); /* Remember the module we had this fragment from */ Frag->Obj = O; } /* Return the section */ return Sec; } Segment* SegFind (unsigned Name) /* Return the given segment or NULL if not found. */ { Segment* S = HashTab[Name & HASHTAB_MASK]; while (S) { if (Name == S->Name) { /* Found */ break; } S = S->Next; } /* Not found */ return S; } int IsBSSType (Segment* S) /* Check if the given segment is a BSS style segment, that is, it does not * contain non-zero data. */ { /* Loop over all sections */ unsigned I; for (I = 0; I < CollCount (&S->Sections); ++I) { /* Get the next section */ Section* Sec = CollAtUnchecked (&S->Sections, I); /* Loop over all fragments */ Fragment* F = Sec->FragRoot; while (F) { if (F->Type == FRAG_LITERAL) { unsigned char* Data = F->LitBuf; unsigned long Count = F->Size; while (Count--) { if (*Data++ != 0) { return 0; } } } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) { if (GetExprVal (F->Expr) != 0) { return 0; } } F = F->Next; } } return 1; } void SegDump (void) /* Dump the segments and it's contents */ { unsigned I, J; unsigned long Count; unsigned char* Data; for (I = 0; I < CollCount (&SegmentList); ++I) { Segment* Seg = CollAtUnchecked (&SegmentList, I); printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size); for (J = 0; J < CollCount (&Seg->Sections); ++J) { Section* S = CollAtUnchecked (&Seg->Sections, J); unsigned J; Fragment* F = S->FragRoot; printf (" Section:\n"); while (F) { switch (F->Type) { case FRAG_LITERAL: printf (" Literal (%u bytes):", F->Size); Count = F->Size; Data = F->LitBuf; J = 100; while (Count--) { if (J > 75) { printf ("\n "); J = 3; } printf (" %02X", *Data++); J += 3; } printf ("\n"); break; case FRAG_EXPR: printf (" Expression (%u bytes):\n", F->Size); printf (" "); DumpExpr (F->Expr, 0); break; case FRAG_SEXPR: printf (" Signed expression (%u bytes):\n", F->Size); printf (" "); DumpExpr (F->Expr, 0); break; case FRAG_FILL: printf (" Empty space (%u bytes)\n", F->Size); break; default: Internal ("Invalid fragment type: %02X", F->Type); } F = F->Next; } } } } unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size) /* Write a supposedly constant expression to the target file. Do a range * check and return one of the SEG_EXPR_xxx codes. */ { static const unsigned long U_Hi[4] = { 0x000000FFUL, 0x0000FFFFUL, 0x00FFFFFFUL, 0xFFFFFFFFUL }; static const long S_Hi[4] = { 0x0000007FL, 0x00007FFFL, 0x007FFFFFL, 0x7FFFFFFFL }; static const long S_Lo[4] = { ~0x0000007FL, ~0x00007FFFL, ~0x007FFFFFL, ~0x7FFFFFFFL }; /* Get the expression value */ long Val = GetExprVal (E); /* Check the size */ CHECK (Size >= 1 && Size <= 4); /* Check for a range error */ if (Signed) { if (Val > S_Hi[Size-1] || Val < S_Lo[Size-1]) { /* Range error */ return SEG_EXPR_RANGE_ERROR; } } else { if (((unsigned long)Val) > U_Hi[Size-1]) { /* Range error */ return SEG_EXPR_RANGE_ERROR; } } /* Write the value to the file */ WriteVal (F, Val, Size); /* Success */ return SEG_EXPR_OK; } void SegWrite (const char* TgtName, FILE* Tgt, Segment* S, SegWriteFunc F, void* Data) /* Write the data from the given segment to a file. For expressions, F is * called (see description of SegWriteFunc above). */ { unsigned I; int Sign; unsigned long Offs = 0; /* Remember the output file and offset for the segment */ S->OutputName = TgtName; S->OutputOffs = (unsigned long) ftell (Tgt); /* Loop over all sections in this segment */ for (I = 0; I < CollCount (&S->Sections); ++I) { Section* Sec = CollAtUnchecked (&S->Sections, I); Fragment* Frag; unsigned char FillVal; /* Output were this section is from */ Print (stdout, 2, " Section from \"%s\"\n", GetObjFileName (Sec->Obj)); /* If we have fill bytes, write them now. Beware: If this is the * first section, the fill value is not considered part of the segment * and therefore taken from the memory area. */ FillVal = (I == 0)? S->MemArea->FillVal : S->FillVal; Print (stdout, 2, " Filling 0x%lx bytes with 0x%02x\n", Sec->Fill, FillVal); WriteMult (Tgt, FillVal, Sec->Fill); Offs += Sec->Fill; /* Loop over all fragments in this section */ Frag = Sec->FragRoot; while (Frag) { /* Output fragment data */ switch (Frag->Type) { case FRAG_LITERAL: WriteData (Tgt, Frag->LitBuf, Frag->Size); break; case FRAG_EXPR: case FRAG_SEXPR: Sign = (Frag->Type == FRAG_SEXPR); /* Call the users function and evaluate the result */ switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) { case SEG_EXPR_OK: break; case SEG_EXPR_RANGE_ERROR: Error ("Range error in module `%s', line %u", GetFragmentSourceName (Frag), GetFragmentSourceLine (Frag)); break; case SEG_EXPR_TOO_COMPLEX: Error ("Expression too complex in module `%s', line %u", GetFragmentSourceName (Frag), GetFragmentSourceLine (Frag)); break; case SEG_EXPR_INVALID: Error ("Invalid expression in module `%s', line %u", GetFragmentSourceName (Frag), GetFragmentSourceLine (Frag)); break; default: Internal ("Invalid return code from SegWriteFunc"); } break; case FRAG_FILL: WriteMult (Tgt, S->FillVal, Frag->Size); break; default: Internal ("Invalid fragment type: %02X", Frag->Type); } /* Update the offset */ Print (stdout, 2, " Fragment with 0x%x bytes\n", Frag->Size); Offs += Frag->Size; /* Next fragment */ Frag = Frag->Next; } } } unsigned SegmentCount (void) /* Return the total number of segments */ { return CollCount (&SegmentList); } static int CmpSegStart (const void* K1, const void* K2) /* Compare function for qsort */ { /* Get the real segment pointers */ const Segment* S1 = *(const Segment**)K1; const Segment* S2 = *(const Segment**)K2; /* Compare the start addresses */ if (S1->PC > S2->PC) { return 1; } else if (S1->PC < S2->PC) { return -1; } else { /* Sort segments with equal starts by name */ return strcmp (GetString (S1->Name), GetString (S2->Name)); } } void PrintSegmentMap (FILE* F) /* Print a segment map to the given file */ { /* Allocate memory for the segment pool */ Segment** SegPool = xmalloc (CollCount (&SegmentList) * sizeof (Segment*)); /* Copy the segment pointers */ unsigned I; for (I = 0; I < CollCount (&SegmentList); ++I) { SegPool[I] = CollAtUnchecked (&SegmentList, I); } /* Sort the array by increasing start addresses */ qsort (SegPool, CollCount (&SegmentList), sizeof (Segment*), CmpSegStart); /* Print a header */ fprintf (F, "Name Start End Size Align\n" "----------------------------------------------------\n"); /* Print the segments */ for (I = 0; I < CollCount (&SegmentList); ++I) { /* Get a pointer to the segment */ Segment* S = SegPool[I]; /* Print empty segments only if explicitly requested */ if (VerboseMap || S->Size > 0) { /* Print the segment data */ long End = S->PC + S->Size; if (S->Size > 0) { /* Point to last element addressed */ --End; } fprintf (F, "%-20s %06lX %06lX %06lX %05lX\n", GetString (S->Name), S->PC, End, S->Size, S->Alignment); } } /* Free the segment pool */ xfree (SegPool); } void PrintDbgSegments (FILE* F) /* Output the segments to the debug file */ { /* Walk over all segments */ unsigned I; for (I = 0; I < CollCount (&SegmentList); ++I) { /* Get the next segment */ const Segment* S = CollAtUnchecked (&SegmentList, I); /* Print the segment data */ fprintf (F, "seg\tid=%u,name=\"%s\",start=0x%06lX,size=0x%04lX,addrsize=%s,type=%s", S->Id, GetString (S->Name), S->PC, S->Size, AddrSizeToStr (S->AddrSize), S->ReadOnly? "ro" : "rw"); if (S->OutputName) { fprintf (F, ",oname=\"%s\",ooffs=%lu", S->OutputName, S->OutputOffs); } fputc ('\n', F); } } void CheckSegments (void) /* Walk through the segment list and check if there are segments that were * not written to the output file. Output an error if this is the case. */ { unsigned I; for (I = 0; I < CollCount (&SegmentList); ++I) { /* Get the next segment */ const Segment* S = CollAtUnchecked (&SegmentList, I); /* Check it */ if (S->Size > 0 && S->Dumped == 0) { Error ("Missing memory area assignment for segment `%s'", GetString (S->Name)); } } }
990
./cc65/src/ld65/lineinfo.c
/*****************************************************************************/ /* */ /* lineinfo.h */ /* */ /* Source file line info structure */ /* */ /* */ /* */ /* (C) 2001-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" #include "lidefs.h" #include "xmalloc.h" /* ld65 */ #include "error.h" #include "fileinfo.h" #include "fileio.h" #include "lineinfo.h" #include "objdata.h" #include "segments.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static LineInfo* NewLineInfo (void) /* Create and return a new LineInfo struct with mostly empty fields */ { /* Allocate memory */ LineInfo* LI = xmalloc (sizeof (LineInfo)); /* Initialize the fields */ LI->Id = ~0U; LI->File = 0; LI->Type = LI_MAKE_TYPE (LI_TYPE_ASM, 0); LI->Pos.Name = INVALID_STRING_ID; LI->Pos.Line = 0; LI->Pos.Col = 0; LI->Spans = 0; /* Return the new struct */ return LI; } void FreeLineInfo (LineInfo* LI) /* Free a LineInfo structure. */ { /* Free the span list */ xfree (LI->Spans); /* Free the structure itself */ xfree (LI); } LineInfo* DupLineInfo (const LineInfo* LI) /* Creates a duplicate of a line info structure */ { /* Allocate memory */ LineInfo* New = xmalloc (sizeof (LineInfo)); /* Copy the fields (leave id invalid) */ New->Id = LI->Id; New->File = LI->File; New->Type = LI->Type; New->Pos = LI->Pos; New->Spans = DupSpanList (LI->Spans); /* Return the copy */ return New; } LineInfo* GenLineInfo (const FilePos* Pos) /* Generate a new (internally used) line info with the given information */ { /* Create a new LineInfo struct */ LineInfo* LI = NewLineInfo (); /* Initialize the fields in the new LineInfo */ LI->Pos = *Pos; /* Return the struct read */ return LI; } LineInfo* ReadLineInfo (FILE* F, ObjData* O) /* Read a line info from a file and return it */ { /* Create a new LineInfo struct */ LineInfo* LI = NewLineInfo (); /* Read/fill the fields in the new LineInfo */ LI->Pos.Line = ReadVar (F); LI->Pos.Col = ReadVar (F); LI->File = CollAt (&O->Files, ReadVar (F)); LI->Pos.Name = LI->File->Name; LI->Type = ReadVar (F); LI->Spans = ReadSpanList (F); /* Return the struct read */ return LI; } void ReadLineInfoList (FILE* F, ObjData* O, Collection* LineInfos) /* Read a list of line infos stored as a list of indices in the object file, * make real line infos from them and place them into the passed collection. */ { /* Read the number of line info indices that follow */ unsigned LineInfoCount = ReadVar (F); /* Grow the collection as needed */ CollGrow (LineInfos, LineInfoCount); /* Read the line infos and resolve them */ while (LineInfoCount--) { /* Read an index */ unsigned LineInfoIndex = ReadVar (F); /* The line info index was written by the assembler and must * therefore be part of the line infos read from the object file. */ if (LineInfoIndex >= CollCount (&O->LineInfos)) { Internal ("Invalid line info index %u in module `%s' - max is %u", LineInfoIndex, GetObjFileName (O), CollCount (&O->LineInfos)); } /* Add the line info to the collection */ CollAppend (LineInfos, CollAt (&O->LineInfos, LineInfoIndex)); } } const LineInfo* GetAsmLineInfo (const Collection* LineInfos) /* Find a line info of type LI_TYPE_ASM and count zero in the given collection * and return it. Return NULL if no such line info was found. */ { unsigned I; /* Search for a line info of LI_TYPE_ASM */ for (I = 0; I < CollCount (LineInfos); ++I) { const LineInfo* LI = CollConstAt (LineInfos, I); if (LI->Type == LI_MAKE_TYPE (LI_TYPE_ASM, 0)) { return LI; } } /* Not found */ return 0; } unsigned LineInfoCount (void) /* Return the total number of line infos */ { /* Walk over all object files */ unsigned I; unsigned Count = 0; for (I = 0; I < CollCount (&ObjDataList); ++I) { /* Get this object file */ const ObjData* O = CollAtUnchecked (&ObjDataList, I); /* Count spans */ Count += CollCount (&O->LineInfos); } return Count; } void AssignLineInfoIds (void) /* Assign the ids to the line infos */ { unsigned I, J; /* Walk over all line infos */ unsigned Id = 0; for (I = 0; I < CollCount (&ObjDataList); ++I) { /* Get the object file */ ObjData* O = CollAtUnchecked (&ObjDataList, I); /* Output the line infos */ for (J = 0; J < CollCount (&O->LineInfos); ++J) { /* Get this line info */ LineInfo* LI = CollAtUnchecked (&O->LineInfos, J); /* Assign the id */ LI->Id = Id++; } } } void PrintDbgLineInfo (FILE* F) /* Output the line infos to a debug info file */ { unsigned I, J; /* Print line infos from all modules we have linked into the output file */ for (I = 0; I < CollCount (&ObjDataList); ++I) { /* Get the object file */ const ObjData* O = CollAtUnchecked (&ObjDataList, I); /* Output the line infos */ for (J = 0; J < CollCount (&O->LineInfos); ++J) { /* Get this line info */ const LineInfo* LI = CollConstAt (&O->LineInfos, J); /* Get the line info type and count */ unsigned Type = LI_GET_TYPE (LI->Type); unsigned Count = LI_GET_COUNT (LI->Type); /* Print the start of the line */ fprintf (F, "line\tid=%u,file=%u,line=%u", LI->Id, LI->File->Id, GetSourceLine (LI)); /* Print type if not LI_TYPE_ASM and count if not zero */ if (Type != LI_TYPE_ASM) { fprintf (F, ",type=%u", Type); } if (Count != 0) { fprintf (F, ",count=%u", Count); } /* Add spans if the line info has it */ PrintDbgSpanList (F, O, LI->Spans); /* Terminate line */ fputc ('\n', F); } } }
991
./cc65/src/ld65/filepath.c
/*****************************************************************************/ /* */ /* filepath.c */ /* */ /* File search path handling for ld65 */ /* */ /* */ /* */ /* (C) 2003-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* ld65 */ #include "filepath.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ SearchPath* LibSearchPath; /* Library path */ SearchPath* ObjSearchPath; /* Object file path */ SearchPath* CfgSearchPath; /* Config file path */ SearchPath* LibDefaultPath; /* Default Library path */ SearchPath* ObjDefaultPath; /* Default Object file path */ SearchPath* CfgDefaultPath; /* Default Config file path */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ void InitSearchPaths (void) /* Initialize the path search list */ { /* Create the search path lists */ LibSearchPath = NewSearchPath (); ObjSearchPath = NewSearchPath (); CfgSearchPath = NewSearchPath (); LibDefaultPath = NewSearchPath (); ObjDefaultPath = NewSearchPath (); CfgDefaultPath = NewSearchPath (); /* Always search all stuff in the current directory */ AddSearchPath (LibSearchPath, ""); AddSearchPath (ObjSearchPath, ""); AddSearchPath (CfgSearchPath, ""); /* Add specific paths from the environment. */ AddSearchPathFromEnv (LibDefaultPath, "LD65_LIB"); AddSearchPathFromEnv (ObjDefaultPath, "LD65_OBJ"); AddSearchPathFromEnv (CfgDefaultPath, "LD65_CFG"); /* Add paths relative to a main directory defined in an env. var. */ AddSubSearchPathFromEnv (LibDefaultPath, "CC65_HOME", "lib"); AddSubSearchPathFromEnv (ObjDefaultPath, "CC65_HOME", "lib"); AddSubSearchPathFromEnv (CfgDefaultPath, "CC65_HOME", "cfg"); /* Add some compiled-in search paths if defined at compile time. */ #if defined(LD65_LIB) AddSearchPath (LibDefaultPath, STRINGIZE (LD65_LIB)); #endif #if defined(LD65_OBJ) AddSearchPath (ObjDefaultPath, STRINGIZE (LD65_OBJ)); #endif #if defined(LD65_CFG) AddSearchPath (CfgDefaultPath, STRINGIZE (LD65_CFG)); #endif /* Add paths relative to the parent directory of the Windows binary. */ AddSubSearchPathFromWinBin (LibDefaultPath, "lib"); AddSubSearchPathFromWinBin (ObjDefaultPath, "lib"); AddSubSearchPathFromWinBin (CfgDefaultPath, "cfg"); }
992
./cc65/src/ld65/error.c
/*****************************************************************************/ /* */ /* error.c */ /* */ /* Error handling for the ld65 linker */ /* */ /* */ /* */ /* (C) 1998-2008 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> /* common */ #include "cmdline.h" #include "strbuf.h" /* ld65 */ #include "error.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void Warning (const char* Format, ...) /* Print a warning message */ { StrBuf S = STATIC_STRBUF_INITIALIZER; va_list ap; va_start (ap, Format); SB_VPrintf (&S, Format, ap); va_end (ap); SB_Terminate (&S); fprintf (stderr, "%s: Warning: %s\n", ProgName, SB_GetConstBuf (&S)); SB_Done (&S); } void Error (const char* Format, ...) /* Print an error message and die */ { StrBuf S = STATIC_STRBUF_INITIALIZER; va_list ap; va_start (ap, Format); SB_VPrintf (&S, Format, ap); va_end (ap); SB_Terminate (&S); fprintf (stderr, "%s: Error: %s\n", ProgName, SB_GetConstBuf (&S)); SB_Done (&S); exit (EXIT_FAILURE); } void Internal (const char* Format, ...) /* Print an internal error message and die */ { StrBuf S = STATIC_STRBUF_INITIALIZER; va_list ap; va_start (ap, Format); SB_VPrintf (&S, Format, ap); va_end (ap); SB_Terminate (&S); fprintf (stderr, "%s: Internal Error: %s\n", ProgName, SB_GetConstBuf (&S)); SB_Done (&S); exit (EXIT_FAILURE); }
993
./cc65/src/ld65/fragment.c
/*****************************************************************************/ /* */ /* fragment.c */ /* */ /* Code/data fragment routines */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "fragdefs.h" #include "xmalloc.h" /* ld65 */ #include "error.h" #include "fragment.h" #include "objdata.h" #include "segments.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ Fragment* NewFragment (unsigned char Type, unsigned Size, Section* S) /* Create a new fragment and insert it into the section S */ { Fragment* F; /* Calculate the size of the memory block. LitBuf is only needed if the * fragment contains literal data. */ unsigned FragSize = sizeof (Fragment) - 1; if (Type == FRAG_LITERAL) { FragSize += Size; } /* Allocate memory */ F = xmalloc (FragSize); /* Initialize the data */ F->Next = 0; F->Obj = 0; F->Sec = S; F->Size = Size; F->Expr = 0; F->LineInfos = EmptyCollection; F->Type = Type; /* Insert the code fragment into the section */ if (S->FragRoot == 0) { /* First fragment */ S->FragRoot = F; } else { S->FragLast->Next = F; } S->FragLast = F; /* Increment the size of the section by the size of the fragment */ S->Size += Size; /* Increment the size of the segment that contains the section */ S->Seg->Size += Size; /* Return the new fragment */ return F; }
994
./cc65/src/ld65/expr.c
/*****************************************************************************/ /* */ /* expr.c */ /* */ /* Expression evaluation for the ld65 linker */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" #include "exprdefs.h" #include "xmalloc.h" /* ld65 */ #include "global.h" #include "error.h" #include "fileio.h" #include "memarea.h" #include "segments.h" #include "expr.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ ExprNode* NewExprNode (ObjData* O, unsigned char Op) /* Create a new expression node */ { /* Allocate fresh memory */ ExprNode* N = xmalloc (sizeof (ExprNode)); N->Op = Op; N->Left = 0; N->Right = 0; N->Obj = O; N->V.IVal = 0; return N; } static void FreeExprNode (ExprNode* E) /* Free a node */ { /* Free the memory */ xfree (E); } void FreeExpr (ExprNode* Root) /* Free the expression, Root is pointing to. */ { if (Root) { FreeExpr (Root->Left); FreeExpr (Root->Right); FreeExprNode (Root); } } int IsConstExpr (ExprNode* Root) /* Return true if the given expression is a constant expression, that is, one * with no references to external symbols. */ { int Const; Export* E; Section* S; MemoryArea* M; if (EXPR_IS_LEAF (Root->Op)) { switch (Root->Op) { case EXPR_LITERAL: return 1; case EXPR_SYMBOL: /* Get the referenced export */ E = GetExprExport (Root); /* If this export has a mark set, we've already encountered it. * This means that the export is used to define it's own value, * which in turn means, that we have a circular reference. */ if (ExportHasMark (E)) { CircularRefError (E); Const = 0; } else { MarkExport (E); Const = IsConstExport (E); UnmarkExport (E); } return Const; case EXPR_SECTION: /* A section expression is const if the segment it is in is * not relocatable and already placed. */ S = GetExprSection (Root); M = S->Seg->MemArea; return M != 0 && (M->Flags & MF_PLACED) != 0 && !M->Relocatable; case EXPR_SEGMENT: /* A segment is const if it is not relocatable and placed */ M = Root->V.Seg->MemArea; return M != 0 && (M->Flags & MF_PLACED) != 0 && !M->Relocatable; case EXPR_MEMAREA: /* A memory area is const if it is not relocatable and placed */ return !Root->V.Mem->Relocatable && (Root->V.Mem->Flags & MF_PLACED); default: /* Anything else is not const */ return 0; } } else if (EXPR_IS_UNARY (Root->Op)) { SegExprDesc D; /* Special handling for the BANK pseudo function */ switch (Root->Op) { case EXPR_BANK: /* Get segment references for the expression */ GetSegExprVal (Root->Left, &D); /* The expression is const if the expression contains exactly * one segment that is assigned to a memory area which has a * bank attribute that is constant. */ return (D.TooComplex == 0 && D.Seg != 0 && D.Seg->MemArea != 0 && D.Seg->MemArea->BankExpr != 0 && IsConstExpr (D.Seg->MemArea->BankExpr)); default: /* All others handled normal */ return IsConstExpr (Root->Left); } } else { /* We must handle shortcut boolean expressions here */ switch (Root->Op) { case EXPR_BOOLAND: if (IsConstExpr (Root->Left)) { /* lhs is const, if it is zero, don't eval right */ if (GetExprVal (Root->Left) == 0) { return 1; } else { return IsConstExpr (Root->Right); } } else { /* lhs not const --> tree not const */ return 0; } break; case EXPR_BOOLOR: if (IsConstExpr (Root->Left)) { /* lhs is const, if it is not zero, don't eval right */ if (GetExprVal (Root->Left) != 0) { return 1; } else { return IsConstExpr (Root->Right); } } else { /* lhs not const --> tree not const */ return 0; } break; default: /* All others are handled normal */ return IsConstExpr (Root->Left) && IsConstExpr (Root->Right); } } } Import* GetExprImport (ExprNode* Expr) /* Get the import data structure for a symbol expression node */ { /* Check that this is really a symbol */ PRECONDITION (Expr->Op == EXPR_SYMBOL); /* If we have an object file, get the import from it, otherwise * (internally generated expressions), get the import from the * import pointer. */ if (Expr->Obj) { /* Return the Import */ return GetObjImport (Expr->Obj, Expr->V.ImpNum); } else { return Expr->V.Imp; } } Export* GetExprExport (ExprNode* Expr) /* Get the exported symbol for a symbol expression node */ { /* Check that this is really a symbol */ PRECONDITION (Expr->Op == EXPR_SYMBOL); /* Return the export for an import*/ return GetExprImport (Expr)->Exp; } Section* GetExprSection (ExprNode* Expr) /* Get the segment for a section expression node */ { /* Check that this is really a section node */ PRECONDITION (Expr->Op == EXPR_SECTION); /* If we have an object file, get the section from it, otherwise * (internally generated expressions), get the section from the * section pointer. */ if (Expr->Obj) { /* Return the export */ return CollAt (&Expr->Obj->Sections, Expr->V.SecNum); } else { return Expr->V.Sec; } } long GetExprVal (ExprNode* Expr) /* Get the value of a constant expression */ { long Right; long Left; long Val; Section* S; Export* E; SegExprDesc D; switch (Expr->Op) { case EXPR_LITERAL: return Expr->V.IVal; case EXPR_SYMBOL: /* Get the referenced export */ E = GetExprExport (Expr); /* If this export has a mark set, we've already encountered it. * This means that the export is used to define it's own value, * which in turn means, that we have a circular reference. */ if (ExportHasMark (E)) { CircularRefError (E); Val = 0; } else { MarkExport (E); Val = GetExportVal (E); UnmarkExport (E); } return Val; case EXPR_SECTION: S = GetExprSection (Expr); return S->Offs + S->Seg->PC; case EXPR_SEGMENT: return Expr->V.Seg->PC; case EXPR_MEMAREA: return Expr->V.Mem->Start; case EXPR_PLUS: return GetExprVal (Expr->Left) + GetExprVal (Expr->Right); case EXPR_MINUS: return GetExprVal (Expr->Left) - GetExprVal (Expr->Right); case EXPR_MUL: return GetExprVal (Expr->Left) * GetExprVal (Expr->Right); case EXPR_DIV: Left = GetExprVal (Expr->Left); Right = GetExprVal (Expr->Right); if (Right == 0) { Error ("Division by zero"); } return Left / Right; case EXPR_MOD: Left = GetExprVal (Expr->Left); Right = GetExprVal (Expr->Right); if (Right == 0) { Error ("Modulo operation with zero"); } return Left % Right; case EXPR_OR: return GetExprVal (Expr->Left) | GetExprVal (Expr->Right); case EXPR_XOR: return GetExprVal (Expr->Left) ^ GetExprVal (Expr->Right); case EXPR_AND: return GetExprVal (Expr->Left) & GetExprVal (Expr->Right); case EXPR_SHL: return GetExprVal (Expr->Left) << GetExprVal (Expr->Right); case EXPR_SHR: return GetExprVal (Expr->Left) >> GetExprVal (Expr->Right); case EXPR_EQ: return (GetExprVal (Expr->Left) == GetExprVal (Expr->Right)); case EXPR_NE: return (GetExprVal (Expr->Left) != GetExprVal (Expr->Right)); case EXPR_LT: return (GetExprVal (Expr->Left) < GetExprVal (Expr->Right)); case EXPR_GT: return (GetExprVal (Expr->Left) > GetExprVal (Expr->Right)); case EXPR_LE: return (GetExprVal (Expr->Left) <= GetExprVal (Expr->Right)); case EXPR_GE: return (GetExprVal (Expr->Left) >= GetExprVal (Expr->Right)); case EXPR_BOOLAND: return GetExprVal (Expr->Left) && GetExprVal (Expr->Right); case EXPR_BOOLOR: return GetExprVal (Expr->Left) || GetExprVal (Expr->Right); case EXPR_BOOLXOR: return (GetExprVal (Expr->Left) != 0) ^ (GetExprVal (Expr->Right) != 0); case EXPR_MAX: Left = GetExprVal (Expr->Left); Right = GetExprVal (Expr->Right); return (Left > Right)? Left : Right; case EXPR_MIN: Left = GetExprVal (Expr->Left); Right = GetExprVal (Expr->Right); return (Left < Right)? Left : Right; case EXPR_UNARY_MINUS: return -GetExprVal (Expr->Left); case EXPR_NOT: return ~GetExprVal (Expr->Left); case EXPR_SWAP: Left = GetExprVal (Expr->Left); return ((Left >> 8) & 0x00FF) | ((Left << 8) & 0xFF00); case EXPR_BOOLNOT: return !GetExprVal (Expr->Left); case EXPR_BANK: GetSegExprVal (Expr->Left, &D); if (D.TooComplex || D.Seg == 0) { Error ("Argument for .BANK is not segment relative or too complex"); } if (D.Seg->MemArea == 0) { Error ("Segment `%s' is referenced by .BANK but " "not assigned to a memory area", GetString (D.Seg->Name)); } if (D.Seg->MemArea->BankExpr == 0) { Error ("Memory area `%s' is referenced by .BANK but " "has no BANK attribute", GetString (D.Seg->MemArea->Name)); } return GetExprVal (D.Seg->MemArea->BankExpr); case EXPR_BYTE0: return GetExprVal (Expr->Left) & 0xFF; case EXPR_BYTE1: return (GetExprVal (Expr->Left) >> 8) & 0xFF; case EXPR_BYTE2: return (GetExprVal (Expr->Left) >> 16) & 0xFF; case EXPR_BYTE3: return (GetExprVal (Expr->Left) >> 24) & 0xFF; case EXPR_WORD0: return GetExprVal (Expr->Left) & 0xFFFF; case EXPR_WORD1: return (GetExprVal (Expr->Left) >> 16) & 0xFFFF; case EXPR_FARADDR: return GetExprVal (Expr->Left) & 0xFFFFFF; case EXPR_DWORD: return GetExprVal (Expr->Left) & 0xFFFFFFFF; default: Internal ("Unknown expression Op type: %u", Expr->Op); /* NOTREACHED */ return 0; } } static void GetSegExprValInternal (ExprNode* Expr, SegExprDesc* D, int Sign) /* Check if the given expression consists of a segment reference and only * constant values, additions and subtractions. If anything else is found, * set D->TooComplex to true. * Internal, recursive routine. */ { Export* E; switch (Expr->Op) { case EXPR_LITERAL: D->Val += (Sign * Expr->V.IVal); break; case EXPR_SYMBOL: /* Get the referenced export */ E = GetExprExport (Expr); /* If this export has a mark set, we've already encountered it. * This means that the export is used to define it's own value, * which in turn means, that we have a circular reference. */ if (ExportHasMark (E)) { CircularRefError (E); } else { MarkExport (E); GetSegExprValInternal (E->Expr, D, Sign); UnmarkExport (E); } break; case EXPR_SECTION: if (D->Seg) { /* We cannot handle more than one segment reference in o65 */ D->TooComplex = 1; } else { /* Get the section from the expression */ Section* S = GetExprSection (Expr); /* Remember the segment reference */ D->Seg = S->Seg; /* Add the offset of the section to the constant value */ D->Val += Sign * (S->Offs + D->Seg->PC); } break; case EXPR_SEGMENT: if (D->Seg) { /* We cannot handle more than one segment reference in o65 */ D->TooComplex = 1; } else { /* Remember the segment reference */ D->Seg = Expr->V.Seg; /* Add the offset of the segment to the constant value */ D->Val += (Sign * D->Seg->PC); } break; case EXPR_PLUS: GetSegExprValInternal (Expr->Left, D, Sign); GetSegExprValInternal (Expr->Right, D, Sign); break; case EXPR_MINUS: GetSegExprValInternal (Expr->Left, D, Sign); GetSegExprValInternal (Expr->Right, D, -Sign); break; default: /* Expression contains illegal operators */ D->TooComplex = 1; break; } } void GetSegExprVal (ExprNode* Expr, SegExprDesc* D) /* Check if the given expression consists of a segment reference and only * constant values, additions and subtractions. If anything else is found, * set D->TooComplex to true. The function will initialize D. */ { /* Initialize the given structure */ D->Val = 0; D->TooComplex = 0; D->Seg = 0; /* Call our recursive calculation routine */ GetSegExprValInternal (Expr, D, 1); } ExprNode* LiteralExpr (long Val, ObjData* O) /* Return an expression tree that encodes the given literal value */ { ExprNode* Expr = NewExprNode (O, EXPR_LITERAL); Expr->V.IVal = Val; return Expr; } ExprNode* MemoryExpr (MemoryArea* Mem, long Offs, ObjData* O) /* Return an expression tree that encodes an offset into a memory area */ { ExprNode* Root; ExprNode* Expr = NewExprNode (O, EXPR_MEMAREA); Expr->V.Mem = Mem; if (Offs != 0) { Root = NewExprNode (O, EXPR_PLUS); Root->Left = Expr; Root->Right = LiteralExpr (Offs, O); } else { Root = Expr; } return Root; } ExprNode* SegmentExpr (Segment* Seg, long Offs, ObjData* O) /* Return an expression tree that encodes an offset into a segment */ { ExprNode* Root; ExprNode* Expr = NewExprNode (O, EXPR_SEGMENT); Expr->V.Seg = Seg; if (Offs != 0) { Root = NewExprNode (O, EXPR_PLUS); Root->Left = Expr; Root->Right = LiteralExpr (Offs, O); } else { Root = Expr; } return Root; } ExprNode* SectionExpr (Section* Sec, long Offs, ObjData* O) /* Return an expression tree that encodes an offset into a section */ { ExprNode* Root; ExprNode* Expr = NewExprNode (O, EXPR_SECTION); Expr->V.Sec = Sec; if (Offs != 0) { Root = NewExprNode (O, EXPR_PLUS); Root->Left = Expr; Root->Right = LiteralExpr (Offs, O); } else { Root = Expr; } return Root; } ExprNode* ReadExpr (FILE* F, ObjData* O) /* Read an expression from the given file */ { ExprNode* Expr; /* Read the node tag and handle NULL nodes */ unsigned char Op = Read8 (F); if (Op == EXPR_NULL) { return 0; } /* Create a new node */ Expr = NewExprNode (O, Op); /* Check the tag and handle the different expression types */ if (EXPR_IS_LEAF (Op)) { switch (Op) { case EXPR_LITERAL: Expr->V.IVal = Read32Signed (F); break; case EXPR_SYMBOL: /* Read the import number */ Expr->V.ImpNum = ReadVar (F); break; case EXPR_SECTION: /* Read the section number */ Expr->V.SecNum = ReadVar (F); break; default: Error ("Invalid expression op: %02X", Op); } } else { /* Not a leaf node */ Expr->Left = ReadExpr (F, O); Expr->Right = ReadExpr (F, O); } /* Return the tree */ return Expr; } int EqualExpr (ExprNode* E1, ExprNode* E2) /* Check if two expressions are identical. */ { /* If one pointer is NULL, both must be NULL */ if ((E1 == 0) ^ (E2 == 0)) { return 0; } if (E1 == 0) { return 1; } /* Both pointers not NULL, check OP */ if (E1->Op != E2->Op) { return 0; } /* OPs are identical, check data for leafs, or subtrees */ switch (E1->Op) { case EXPR_LITERAL: /* Value must be identical */ return (E1->V.IVal == E2->V.IVal); case EXPR_SYMBOL: /* Import must be identical */ return (GetExprImport (E1) == GetExprImport (E2)); case EXPR_SECTION: /* Section must be identical */ return (GetExprSection (E1) == GetExprSection (E2)); case EXPR_SEGMENT: /* Segment must be identical */ return (E1->V.Seg == E2->V.Seg); case EXPR_MEMAREA: /* Memory area must be identical */ return (E1->V.Mem == E2->V.Mem); default: /* Not a leaf node */ return EqualExpr (E1->Left, E2->Left) && EqualExpr (E1->Right, E2->Right); } }
995
./cc65/src/ld65/o65.c
/*****************************************************************************/ /* */ /* o65.c */ /* */ /* Module to handle the o65 binary format */ /* */ /* */ /* */ /* (C) 1999-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <limits.h> #include <errno.h> #include <time.h> /* common */ #include "chartype.h" #include "check.h" #include "fname.h" #include "print.h" #include "version.h" #include "xmalloc.h" /* ld65 */ #include "error.h" #include "exports.h" #include "expr.h" #include "fileio.h" #include "global.h" #include "lineinfo.h" #include "memarea.h" #include "o65.h" #include "spool.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Header mode bits */ #define MF_CPU_65816 0x8000 /* Executable is for 65816 */ #define MF_CPU_6502 0x0000 /* Executable is for the 6502 */ #define MF_CPU_MASK 0x8000 /* Mask to extract CPU type */ #define MF_RELOC_PAGE 0x4000 /* Page wise relocation */ #define MF_RELOC_BYTE 0x0000 /* Byte wise relocation */ #define MF_RELOC_MASK 0x4000 /* Mask to extract relocation type */ #define MF_SIZE_32BIT 0x2000 /* All size words are 32bit */ #define MF_SIZE_16BIT 0x0000 /* All size words are 16bit */ #define MF_SIZE_MASK 0x2000 /* Mask to extract size */ #define MF_FTYPE_OBJ 0x1000 /* Object file */ #define MF_FTYPE_EXE 0x0000 /* Executable file */ #define MF_FTYPE_MASK 0x1000 /* Mask to extract type */ #define MF_ADDR_SIMPLE 0x0800 /* Simple addressing */ #define MF_ADDR_DEFAULT 0x0000 /* Default addressing */ #define MF_ADDR_MASK 0x0800 /* Mask to extract addressing */ #define MF_ALIGN_1 0x0000 /* Bytewise alignment */ #define MF_ALIGN_2 0x0001 /* Align words */ #define MF_ALIGN_4 0x0002 /* Align longwords */ #define MF_ALIGN_256 0x0003 /* Align pages (256 bytes) */ #define MF_ALIGN_MASK 0x0003 /* Mask to extract alignment */ /* The four o65 segment types. Note: These values are identical to the values * needed for the segmentID in the o65 spec. */ #define O65SEG_UNDEF 0x00 #define O65SEG_ABS 0x01 #define O65SEG_TEXT 0x02 #define O65SEG_DATA 0x03 #define O65SEG_BSS 0x04 #define O65SEG_ZP 0x05 /* Relocation type codes for the o65 format */ #define O65RELOC_WORD 0x80 #define O65RELOC_HIGH 0x40 #define O65RELOC_LOW 0x20 #define O65RELOC_SEGADR 0xC0 #define O65RELOC_SEG 0xA0 #define O65RELOC_MASK 0xE0 /* O65 executable file header */ typedef struct O65Header O65Header; struct O65Header { unsigned Version; /* Version number for o65 format */ unsigned Mode; /* Mode word */ unsigned long TextBase; /* Base address of text segment */ unsigned long TextSize; /* Size of text segment */ unsigned long DataBase; /* Base of data segment */ unsigned long DataSize; /* Size of data segment */ unsigned long BssBase; /* Base of bss segment */ unsigned long BssSize; /* Size of bss segment */ unsigned long ZPBase; /* Base of zeropage segment */ unsigned long ZPSize; /* Size of zeropage segment */ unsigned long StackSize; /* Requested stack size */ }; /* An o65 option */ typedef struct O65Option O65Option; struct O65Option { O65Option* Next; /* Next in option list */ unsigned char Type; /* Type of option */ unsigned char Len; /* Data length */ unsigned char Data [1]; /* Data, dynamically allocated */ }; /* A o65 relocation table */ typedef struct O65RelocTab O65RelocTab; struct O65RelocTab { unsigned Size; /* Size of the table */ unsigned Fill; /* Amount used */ unsigned char* Buf; /* Buffer, dynamically allocated */ }; /* Structure describing the format */ struct O65Desc { O65Header Header; /* File header */ O65Option* Options; /* List of file options */ ExtSymTab* Exports; /* Table with exported symbols */ ExtSymTab* Imports; /* Table with imported symbols */ unsigned Undef; /* Count of undefined symbols */ FILE* F; /* The file we're writing to */ const char* Filename; /* Name of the output file */ O65RelocTab* TextReloc; /* Relocation table for text segment */ O65RelocTab* DataReloc; /* Relocation table for data segment */ unsigned TextCount; /* Number of segments assigned to .text */ SegDesc** TextSeg; /* Array of text segments */ unsigned DataCount; /* Number of segments assigned to .data */ SegDesc** DataSeg; /* Array of data segments */ unsigned BssCount; /* Number of segments assigned to .bss */ SegDesc** BssSeg; /* Array of bss segments */ unsigned ZPCount; /* Number of segments assigned to .zp */ SegDesc** ZPSeg; /* Array of zp segments */ /* Temporary data for writing segments */ unsigned long SegSize; O65RelocTab* CurReloc; long LastOffs; }; /* Structure for parsing expression trees */ typedef struct ExprDesc ExprDesc; struct ExprDesc { O65Desc* D; /* File format descriptor */ long Val; /* The offset value */ int TooComplex; /* Expression too complex */ MemoryArea* MemRef; /* Memory reference if any */ Segment* SegRef; /* Segment reference if any */ Section* SecRef; /* Section reference if any */ ExtSym* ExtRef; /* External reference if any */ }; /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static ExprDesc* InitExprDesc (ExprDesc* ED, O65Desc* D) /* Initialize an ExprDesc structure for use with O65ParseExpr */ { ED->D = D; ED->Val = 0; ED->TooComplex = 0; ED->MemRef = 0; ED->SegRef = 0; ED->SecRef = 0; ED->ExtRef = 0; return ED; } static void WriteSize (const O65Desc* D, unsigned long Val) /* Write a "size" word to the file */ { switch (D->Header.Mode & MF_SIZE_MASK) { case MF_SIZE_16BIT: Write16 (D->F, (unsigned) Val); break; case MF_SIZE_32BIT: Write32 (D->F, Val); break; default: Internal ("Invalid size in header: %04X", D->Header.Mode); } } static unsigned O65SegType (const SegDesc* S) /* Map our own segment types into something o65 compatible */ { /* Check the segment type. Readonly segments are assign to the o65 * text segment, writeable segments that contain data are assigned * to data, bss and zp segments are handled respectively. * Beware: Zeropage segments have the SF_BSS flag set, so be sure * to check SF_ZP first. */ if (S->Flags & SF_RO) { return O65SEG_TEXT; } else if (S->Flags & SF_ZP) { return O65SEG_ZP; } else if (S->Flags & SF_BSS) { return O65SEG_BSS; } else { return O65SEG_DATA; } } static void CvtMemoryToSegment (ExprDesc* ED) /* Convert a memory area into a segment by searching the list of run segments * in this memory area and assigning the nearest one. */ { /* Get the memory area from the expression */ MemoryArea* M = ED->MemRef; /* Remember the "nearest" segment and its offset */ Segment* Nearest = 0; unsigned long Offs = ULONG_MAX; /* Walk over all segments */ unsigned I; for (I = 0; I < CollCount (&M->SegList); ++I) { /* Get the segment and check if it's a run segment */ SegDesc* S = CollAtUnchecked (&M->SegList, I); if (S->Run == M) { unsigned long O; /* Get the segment from the segment descriptor */ Segment* Seg = S->Seg; /* Check the PC. */ if ((long) Seg->PC <= ED->Val && (O = (ED->Val - Seg->PC)) < Offs) { /* This is the nearest segment for now */ Offs = O; Nearest = Seg; /* If we found an exact match, don't look further */ if (Offs == 0) { break; } } } } /* If we found a segment, use it and adjust the offset */ if (Nearest) { ED->SegRef = Nearest; ED->MemRef = 0; ED->Val -= Nearest->PC; } } static const SegDesc* FindSeg (SegDesc** const List, unsigned Count, const Segment* S) /* Search for a segment in the given list of segment descriptors and return * the descriptor for a segment if we found it, and NULL if not. */ { unsigned I; for (I = 0; I < Count; ++I) { if (List[I]->Seg == S) { /* Found */ return List[I]; } } /* Not found */ return 0; } static const SegDesc* O65FindSeg (const O65Desc* D, const Segment* S) /* Search for a segment in the segment lists and return it's segment descriptor */ { const SegDesc* SD; if ((SD = FindSeg (D->TextSeg, D->TextCount, S)) != 0) { return SD; } if ((SD = FindSeg (D->DataSeg, D->DataCount, S)) != 0) { return SD; } if ((SD = FindSeg (D->BssSeg, D->BssCount, S)) != 0) { return SD; } if ((SD = FindSeg (D->ZPSeg, D->ZPCount, S)) != 0) { return SD; } /* Not found */ return 0; } /*****************************************************************************/ /* Expression handling */ /*****************************************************************************/ static void O65ParseExpr (ExprNode* Expr, ExprDesc* D, int Sign) /* Extract and evaluate all constant factors in an subtree that has only * additions and subtractions. If anything other than additions and * subtractions are found, D->TooComplex is set to true. */ { Export* E; switch (Expr->Op) { case EXPR_LITERAL: D->Val += (Sign * Expr->V.IVal); break; case EXPR_SYMBOL: /* Get the referenced Export */ E = GetExprExport (Expr); /* If this export has a mark set, we've already encountered it. * This means that the export is used to define it's own value, * which in turn means, that we have a circular reference. */ if (ExportHasMark (E)) { CircularRefError (E); } else if (E->Expr == 0) { /* Dummy export, must be an o65 imported symbol */ ExtSym* S = O65GetImport (D->D, E->Name); CHECK (S != 0); if (D->ExtRef) { /* We cannot have more than one external reference in o65 */ D->TooComplex = 1; } else { /* Remember the external reference */ D->ExtRef = S; } } else { MarkExport (E); O65ParseExpr (E->Expr, D, Sign); UnmarkExport (E); } break; case EXPR_SECTION: if (D->SecRef) { /* We cannot handle more than one segment reference in o65 */ D->TooComplex = 1; } else { /* Remember the segment reference */ D->SecRef = GetExprSection (Expr); /* Add the offset of the section to the constant value */ D->Val += Sign * (D->SecRef->Offs + D->SecRef->Seg->PC); } break; case EXPR_SEGMENT: if (D->SegRef) { /* We cannot handle more than one segment reference in o65 */ D->TooComplex = 1; } else { /* Remember the segment reference */ D->SegRef = Expr->V.Seg; /* Add the offset of the segment to the constant value */ D->Val += (Sign * D->SegRef->PC); } break; case EXPR_MEMAREA: if (D->MemRef) { /* We cannot handle more than one memory reference in o65 */ D->TooComplex = 1; } else { /* Remember the memory area reference */ D->MemRef = Expr->V.Mem; /* Add the start address of the memory area to the constant * value */ D->Val += (Sign * D->MemRef->Start); } break; case EXPR_PLUS: O65ParseExpr (Expr->Left, D, Sign); O65ParseExpr (Expr->Right, D, Sign); break; case EXPR_MINUS: O65ParseExpr (Expr->Left, D, Sign); O65ParseExpr (Expr->Right, D, -Sign); break; default: /* Expression contains illegal operators */ D->TooComplex = 1; break; } } /*****************************************************************************/ /* Relocation tables */ /*****************************************************************************/ static O65RelocTab* NewO65RelocTab (void) /* Create a new relocation table */ { /* Allocate a new structure */ O65RelocTab* R = xmalloc (sizeof (O65RelocTab)); /* Initialize the data */ R->Size = 0; R->Fill = 0; R->Buf = 0; /* Return the created struct */ return R; } static void FreeO65RelocTab (O65RelocTab* R) /* Free a relocation table */ { xfree (R->Buf); xfree (R); } static void O65RelocPutByte (O65RelocTab* R, unsigned B) /* Put the byte into the relocation table */ { /* Do we have enough space in the buffer? */ if (R->Fill == R->Size) { /* We need to grow the buffer */ if (R->Size) { R->Size *= 2; } else { R->Size = 1024; /* Initial size */ } R->Buf = xrealloc (R->Buf, R->Size); } /* Put the byte into the buffer */ R->Buf [R->Fill++] = (unsigned char) B; } static void O65RelocPutWord (O65RelocTab* R, unsigned W) /* Put a word into the relocation table */ { O65RelocPutByte (R, W); O65RelocPutByte (R, W >> 8); } static void O65WriteReloc (O65RelocTab* R, FILE* F) /* Write the relocation table to the given file */ { WriteData (F, R->Buf, R->Fill); } /*****************************************************************************/ /* Option handling */ /*****************************************************************************/ static O65Option* NewO65Option (unsigned Type, const void* Data, unsigned DataLen) /* Allocate and initialize a new option struct */ { O65Option* O; /* Check the length */ CHECK (DataLen <= 253); /* Allocate memory */ O = xmalloc (sizeof (O65Option) - 1 + DataLen); /* Initialize the structure */ O->Next = 0; O->Type = Type; O->Len = DataLen; memcpy (O->Data, Data, DataLen); /* Return the created struct */ return O; } static void FreeO65Option (O65Option* O) /* Free an O65Option struct */ { xfree (O); } /*****************************************************************************/ /* Subroutines to write o65 sections */ /*****************************************************************************/ static void O65WriteHeader (O65Desc* D) /* Write the header of the executable to the given file */ { static unsigned char Trailer [5] = { 0x01, 0x00, 0x6F, 0x36, 0x35 }; O65Option* O; /* Write the fixed header */ WriteData (D->F, Trailer, sizeof (Trailer)); Write8 (D->F, D->Header.Version); Write16 (D->F, D->Header.Mode); WriteSize (D, D->Header.TextBase); WriteSize (D, D->Header.TextSize); WriteSize (D, D->Header.DataBase); WriteSize (D, D->Header.DataSize); WriteSize (D, D->Header.BssBase); WriteSize (D, D->Header.BssSize); WriteSize (D, D->Header.ZPBase); WriteSize (D, D->Header.ZPSize); WriteSize (D, D->Header.StackSize); /* Write the options */ O = D->Options; while (O) { Write8 (D->F, O->Len + 2); /* Account for len and type bytes */ Write8 (D->F, O->Type); if (O->Len) { WriteData (D->F, O->Data, O->Len); } O = O->Next; } /* Write the end-of-options byte */ Write8 (D->F, 0); } static unsigned O65WriteExpr (ExprNode* E, int Signed, unsigned Size, unsigned long Offs, void* Data) /* Called from SegWrite for an expression. Evaluate the expression, check the * range and write the expression value to the file, update the relocation * table. */ { long Diff; unsigned RefCount; long BinVal; ExprNode* Expr; ExprDesc ED; unsigned char RelocType; /* Cast the Data pointer to its real type, an O65Desc */ O65Desc* D = (O65Desc*) Data; /* Check for a constant expression */ if (IsConstExpr (E)) { /* Write out the constant expression */ return SegWriteConstExpr (((O65Desc*)Data)->F, E, Signed, Size); } /* We have a relocatable expression that needs a relocation table entry. * Calculate the number of bytes between this entry and the last one, and * setup all necessary intermediate bytes in the relocation table. */ Offs += D->SegSize; /* Calulate full offset */ Diff = ((long) Offs) - D->LastOffs; while (Diff > 0xFE) { O65RelocPutByte (D->CurReloc, 0xFF); Diff -= 0xFE; } O65RelocPutByte (D->CurReloc, (unsigned char) Diff); /* Remember this offset for the next time */ D->LastOffs = Offs; /* Determine the expression to relocate */ Expr = E; if (E->Op == EXPR_BYTE0 || E->Op == EXPR_BYTE1 || E->Op == EXPR_BYTE2 || E->Op == EXPR_BYTE3 || E->Op == EXPR_WORD0 || E->Op == EXPR_WORD1 || E->Op == EXPR_FARADDR || E->Op == EXPR_DWORD) { /* Use the real expression */ Expr = E->Left; } /* Recursively collect information about this expression */ O65ParseExpr (Expr, InitExprDesc (&ED, D), 1); /* We cannot handle more than one external reference */ RefCount = (ED.MemRef != 0) + (ED.SegRef != 0) + (ED.SecRef != 0) + (ED.ExtRef != 0); if (RefCount > 1) { ED.TooComplex = 1; } /* If we have a memory area reference, we need to convert it into a * segment reference. If we cannot do that, we cannot handle the * expression. */ if (ED.MemRef) { CvtMemoryToSegment (&ED); if (ED.SegRef == 0) { return SEG_EXPR_TOO_COMPLEX; } } /* Bail out if we cannot handle the expression */ if (ED.TooComplex) { return SEG_EXPR_TOO_COMPLEX; } /* Safety: Check that we have exactly one reference */ CHECK (RefCount == 1); /* Write out the offset that goes into the segment. */ BinVal = ED.Val; switch (E->Op) { case EXPR_BYTE0: BinVal &= 0xFF; break; case EXPR_BYTE1: BinVal = (BinVal >> 8) & 0xFF; break; case EXPR_BYTE2: BinVal = (BinVal >> 16) & 0xFF; break; case EXPR_BYTE3: BinVal = (BinVal >> 24) & 0xFF; break; case EXPR_WORD0: BinVal &= 0xFFFF; break; case EXPR_WORD1: BinVal = (BinVal >> 16) & 0xFFFF; break; case EXPR_FARADDR: BinVal &= 0xFFFFFFUL; break; case EXPR_DWORD: BinVal &= 0xFFFFFFFFUL; break; } WriteVal (D->F, BinVal, Size); /* Determine the actual type of relocation entry needed from the * information gathered about the expression. */ if (E->Op == EXPR_BYTE0) { RelocType = O65RELOC_LOW; } else if (E->Op == EXPR_BYTE1) { RelocType = O65RELOC_HIGH; } else if (E->Op == EXPR_BYTE2) { RelocType = O65RELOC_SEG; } else { switch (Size) { case 1: RelocType = O65RELOC_LOW; break; case 2: RelocType = O65RELOC_WORD; break; case 3: RelocType = O65RELOC_SEGADR; break; case 4: /* 4 byte expression not supported by o65 */ return SEG_EXPR_TOO_COMPLEX; default: Internal ("O65WriteExpr: Invalid expression size: %u", Size); RelocType = 0; /* Avoid gcc warnings */ } } /* Determine which segment we're referencing */ if (ED.SegRef || ED.SecRef) { const SegDesc* Seg; /* Segment or section reference. */ if (ED.SecRef) { /* Get segment from section */ ED.SegRef = ED.SecRef->Seg; } /* Search for the segment and map it to it's o65 segmentID */ Seg = O65FindSeg (D, ED.SegRef); if (Seg == 0) { /* For some reason, we didn't find this segment in the list of * segments written to the o65 file. */ return SEG_EXPR_INVALID; } RelocType |= O65SegType (Seg); O65RelocPutByte (D->CurReloc, RelocType); /* Output additional data if needed */ switch (RelocType & O65RELOC_MASK) { case O65RELOC_HIGH: O65RelocPutByte (D->CurReloc, ED.Val & 0xFF); break; case O65RELOC_SEG: O65RelocPutWord (D->CurReloc, ED.Val & 0xFFFF); break; } } else if (ED.ExtRef) { /* Imported symbol */ RelocType |= O65SEG_UNDEF; O65RelocPutByte (D->CurReloc, RelocType); /* Put the number of the imported symbol into the table */ O65RelocPutWord (D->CurReloc, ExtSymNum (ED.ExtRef)); } else { /* OOPS - something bad happened */ Internal ("External reference not handled"); } /* Success */ return SEG_EXPR_OK; } static void O65WriteSeg (O65Desc* D, SegDesc** Seg, unsigned Count, int DoWrite) /* Write one segment to the o65 output file */ { SegDesc* S; unsigned I; /* Initialize variables */ D->SegSize = 0; D->LastOffs = -1; /* Write out all segments */ for (I = 0; I < Count; ++I) { /* Get the segment from the list node */ S = Seg [I]; /* Keep the user happy */ Print (stdout, 1, " Writing `%s'\n", GetString (S->Name)); /* Write this segment */ if (DoWrite) { SegWrite (D->Filename, D->F, S->Seg, O65WriteExpr, D); } /* Mark the segment as dumped */ S->Seg->Dumped = 1; /* Calculate the total size */ D->SegSize += S->Seg->Size; } /* Terminate the relocation table for this segment */ if (D->CurReloc) { O65RelocPutByte (D->CurReloc, 0); } /* Check the size of the segment for overflow */ if ((D->Header.Mode & MF_SIZE_MASK) == MF_SIZE_16BIT && D->SegSize > 0xFFFF) { Error ("Segment overflow in file `%s'", D->Filename); } } static void O65WriteTextSeg (O65Desc* D) /* Write the code segment to the o65 output file */ { /* Initialize variables */ D->CurReloc = D->TextReloc; /* Dump all text segments */ O65WriteSeg (D, D->TextSeg, D->TextCount, 1); /* Set the size of the segment */ D->Header.TextSize = D->SegSize; } static void O65WriteDataSeg (O65Desc* D) /* Write the data segment to the o65 output file */ { /* Initialize variables */ D->CurReloc = D->DataReloc; /* Dump all data segments */ O65WriteSeg (D, D->DataSeg, D->DataCount, 1); /* Set the size of the segment */ D->Header.DataSize = D->SegSize; } static void O65WriteBssSeg (O65Desc* D) /* "Write" the bss segments to the o65 output file. This will only update * the relevant header fields. */ { /* Initialize variables */ D->CurReloc = 0; /* Dump all bss segments */ O65WriteSeg (D, D->BssSeg, D->BssCount, 0); /* Set the size of the segment */ D->Header.BssSize = D->SegSize; } static void O65WriteZPSeg (O65Desc* D) /* "Write" the zeropage segments to the o65 output file. This will only update * the relevant header fields. */ { /* Initialize variables */ D->CurReloc = 0; /* Dump all zp segments */ O65WriteSeg (D, D->ZPSeg, D->ZPCount, 0); /* Set the size of the segment */ D->Header.ZPSize = D->SegSize; } static void O65WriteImports (O65Desc* D) /* Write the list of imported symbols to the O65 file */ { const ExtSym* S; /* Write the number of imports */ WriteSize (D, ExtSymCount (D->Imports)); /* Write out the symbol names, zero terminated */ S = ExtSymList (D->Imports); while (S) { /* Get the name */ const char* Name = GetString (ExtSymName (S)); /* And write it to the output file */ WriteData (D->F, Name, strlen (Name) + 1); /* Next symbol */ S = ExtSymNext (S); } } static void O65WriteTextReloc (O65Desc* D) /* Write the relocation for the text segment to the output file */ { O65WriteReloc (D->TextReloc, D->F); } static void O65WriteDataReloc (O65Desc* D) /* Write the relocation for the data segment to the output file */ { O65WriteReloc (D->DataReloc, D->F); } static void O65WriteExports (O65Desc* D) /* Write the list of exports */ { const ExtSym* S; /* Write the number of exports */ WriteSize (D, ExtSymCount (D->Exports)); /* Write out the symbol information */ S = ExtSymList (D->Exports); while (S) { ExprNode* Expr; unsigned char SegmentID; ExprDesc ED; /* Get the name */ unsigned NameIdx = ExtSymName (S); const char* Name = GetString (NameIdx); /* Get the export for this symbol. We've checked before that this * export does really exist, so if it is unresolved, or if we don't * find it, there is an error in the linker code. */ Export* E = FindExport (NameIdx); if (E == 0 || IsUnresolvedExport (E)) { Internal ("Unresolved export `%s' found in O65WriteExports", Name); } /* Get the expression for the symbol */ Expr = E->Expr; /* Recursively collect information about this expression */ O65ParseExpr (Expr, InitExprDesc (&ED, D), 1); /* We cannot handle expressions with imported symbols, or expressions * with more than one segment reference here */ if (ED.ExtRef != 0 || (ED.SegRef != 0 && ED.SecRef != 0)) { ED.TooComplex = 1; } /* Bail out if we cannot handle the expression */ if (ED.TooComplex) { Error ("Expression for symbol `%s' is too complex", Name); } /* Determine the segment id for the expression */ if (ED.SegRef != 0 || ED.SecRef != 0) { const SegDesc* Seg; /* Segment or section reference */ if (ED.SecRef != 0) { ED.SegRef = ED.SecRef->Seg; /* Get segment from section */ } /* Search for the segment and map it to it's o65 segmentID */ Seg = O65FindSeg (D, ED.SegRef); if (Seg == 0) { /* For some reason, we didn't find this segment in the list of * segments written to the o65 file. */ Error ("Segment for symbol `%s' is undefined", Name); } SegmentID = O65SegType (Seg); } else { /* Absolute value */ SegmentID = O65SEG_ABS; } /* Write the name to the output file */ WriteData (D->F, Name, strlen (Name) + 1); /* Output the segment id followed by the literal value */ Write8 (D->F, SegmentID); WriteSize (D, ED.Val); /* Next symbol */ S = ExtSymNext (S); } } /*****************************************************************************/ /* Public code */ /*****************************************************************************/ O65Desc* NewO65Desc (void) /* Create, initialize and return a new O65 descriptor struct */ { /* Allocate a new structure */ O65Desc* D = xmalloc (sizeof (O65Desc)); /* Initialize the header */ D->Header.Version = 0; D->Header.Mode = 0; D->Header.TextBase = 0; D->Header.TextSize = 0; D->Header.DataBase = 0; D->Header.DataSize = 0; D->Header.BssBase = 0; D->Header.BssSize = 0; D->Header.ZPBase = 0; D->Header.ZPSize = 0; D->Header.StackSize = 0; /* Let OS choose a good value */ /* Initialize other data */ D->Options = 0; D->Exports = NewExtSymTab (); D->Imports = NewExtSymTab (); D->Undef = 0; D->F = 0; D->Filename = 0; D->TextReloc = NewO65RelocTab (); D->DataReloc = NewO65RelocTab (); D->TextCount = 0; D->TextSeg = 0; D->DataCount = 0; D->DataSeg = 0; D->BssCount = 0; D->BssSeg = 0; D->ZPCount = 0; D->ZPSeg = 0; /* Return the created struct */ return D; } void FreeO65Desc (O65Desc* D) /* Delete the descriptor struct with cleanup */ { /* Free the segment arrays */ xfree (D->ZPSeg); xfree (D->BssSeg); xfree (D->DataSeg); xfree (D->TextSeg); /* Free the relocation tables */ FreeO65RelocTab (D->DataReloc); FreeO65RelocTab (D->TextReloc); /* Free the option list */ while (D->Options) { O65Option* O = D->Options; D->Options = D->Options->Next; FreeO65Option (O); } /* Free the external symbol tables */ FreeExtSymTab (D->Exports); FreeExtSymTab (D->Imports); /* Free the struct itself */ xfree (D); } void O65Set6502 (O65Desc* D) /* Enable 6502 mode */ { D->Header.Mode = (D->Header.Mode & ~MF_CPU_MASK) | MF_CPU_6502; } void O65Set65816 (O65Desc* D) /* Enable 816 mode */ { D->Header.Mode = (D->Header.Mode & ~MF_CPU_MASK) | MF_CPU_65816; } void O65SetSmallModel (O65Desc* D) /* Enable a small memory model executable */ { D->Header.Mode = (D->Header.Mode & ~MF_SIZE_MASK) | MF_SIZE_16BIT; } void O65SetLargeModel (O65Desc* D) /* Enable a large memory model executable */ { D->Header.Mode = (D->Header.Mode & ~MF_SIZE_MASK) | MF_SIZE_32BIT; } void O65SetAlignment (O65Desc* D, unsigned Alignment) /* Set the executable alignment */ { /* Remove all alignment bits from the mode word */ D->Header.Mode &= ~MF_ALIGN_MASK; /* Set the alignment bits */ switch (Alignment) { case 1: D->Header.Mode |= MF_ALIGN_1; break; case 2: D->Header.Mode |= MF_ALIGN_2; break; case 4: D->Header.Mode |= MF_ALIGN_4; break; case 256: D->Header.Mode |= MF_ALIGN_256; break; default: Error ("Invalid alignment for O65 format: %u", Alignment); } } void O65SetOption (O65Desc* D, unsigned Type, const void* Data, unsigned DataLen) /* Set an o65 header option */ { /* Create a new option structure */ O65Option* O = NewO65Option (Type, Data, DataLen); /* Insert it into the linked list */ O->Next = D->Options; D->Options = O; } void O65SetOS (O65Desc* D, unsigned OS, unsigned Version, unsigned Id) /* Set an option describing the target operating system */ { /* Setup the option data */ unsigned char Opt[4]; Opt[0] = OS; Opt[1] = Version; /* Write the correct option length */ switch (OS) { case O65OS_CC65: /* Set the 16 bit id */ Opt[2] = (unsigned char) Id; Opt[3] = (unsigned char) (Id >> 8); O65SetOption (D, O65OPT_OS, Opt, 4); break; default: /* No id for OS/A65, Lunix, and unknown OSes */ O65SetOption (D, O65OPT_OS, Opt, 2); break; } } ExtSym* O65GetImport (O65Desc* D, unsigned Ident) /* Return the imported symbol or NULL if not found */ { /* Retrieve the symbol from the table */ return GetExtSym (D->Imports, Ident); } void O65SetImport (O65Desc* D, unsigned Ident) /* Set an imported identifier */ { /* Insert the entry into the table */ NewExtSym (D->Imports, Ident); } ExtSym* O65GetExport (O65Desc* D, unsigned Ident) /* Return the exported symbol or NULL if not found */ { /* Retrieve the symbol from the table */ return GetExtSym (D->Exports, Ident); } void O65SetExport (O65Desc* D, unsigned Ident) /* Set an exported identifier */ { /* Get the export for this symbol and check if it does exist and is * a resolved symbol. */ Export* E = FindExport (Ident); if (E == 0 || IsUnresolvedExport (E)) { Error ("Unresolved export: `%s'", GetString (Ident)); } /* Insert the entry into the table */ NewExtSym (D->Exports, Ident); } static void O65SetupSegments (O65Desc* D, File* F) /* Setup segment assignments */ { unsigned I; unsigned TextIdx, DataIdx, BssIdx, ZPIdx; /* Initialize the counters */ D->TextCount = 0; D->DataCount = 0; D->BssCount = 0; D->ZPCount = 0; /* Walk over the memory list */ for (I = 0; I < CollCount (&F->MemoryAreas); ++I) { /* Get this entry */ MemoryArea* M = CollAtUnchecked (&F->MemoryAreas, I); /* Walk through the segment list and count the segment types */ unsigned J; for (J = 0; J < CollCount (&M->SegList); ++J) { /* Get the segment */ SegDesc* S = CollAtUnchecked (&M->SegList, J); /* Check the segment type. */ switch (O65SegType (S)) { case O65SEG_TEXT: D->TextCount++; break; case O65SEG_DATA: D->DataCount++; break; case O65SEG_BSS: D->BssCount++; break; case O65SEG_ZP: D->ZPCount++; break; default: Internal ("Invalid return from O65SegType"); } } } /* Allocate memory according to the numbers */ D->TextSeg = xmalloc (D->TextCount * sizeof (SegDesc*)); D->DataSeg = xmalloc (D->DataCount * sizeof (SegDesc*)); D->BssSeg = xmalloc (D->BssCount * sizeof (SegDesc*)); D->ZPSeg = xmalloc (D->ZPCount * sizeof (SegDesc*)); /* Walk again through the list and setup the segment arrays */ TextIdx = DataIdx = BssIdx = ZPIdx = 0; for (I = 0; I < CollCount (&F->MemoryAreas); ++I) { /* Get this entry */ MemoryArea* M = CollAtUnchecked (&F->MemoryAreas, I); /* Walk over the segment list and check the segment types */ unsigned J; for (J = 0; J < CollCount (&M->SegList); ++J) { /* Get the segment */ SegDesc* S = CollAtUnchecked (&M->SegList, J); /* Check the segment type. */ switch (O65SegType (S)) { case O65SEG_TEXT: D->TextSeg [TextIdx++] = S; break; case O65SEG_DATA: D->DataSeg [DataIdx++] = S; break; case O65SEG_BSS: D->BssSeg [BssIdx++] = S; break; case O65SEG_ZP: D->ZPSeg [ZPIdx++] = S; break; default: Internal ("Invalid return from O65SegType"); } } } } static int O65Unresolved (unsigned Name, void* D) /* Called if an unresolved symbol is encountered */ { /* Check if the symbol is an imported o65 symbol */ if (O65GetImport (D, Name) != 0) { /* This is an external symbol, relax... */ return 1; } else { /* This is actually an unresolved external. Bump the counter */ ((O65Desc*) D)->Undef++; return 0; } } static void O65SetupHeader (O65Desc* D) /* Set additional stuff in the header */ { /* Set the base addresses of the segments */ if (D->TextCount > 0) { SegDesc* FirstSeg = D->TextSeg [0]; D->Header.TextBase = FirstSeg->Seg->PC; } if (D->DataCount > 0) { SegDesc* FirstSeg = D->DataSeg [0]; D->Header.DataBase = FirstSeg->Seg->PC; } if (D->BssCount > 0) { SegDesc* FirstSeg = D->BssSeg [0]; D->Header.BssBase = FirstSeg->Seg->PC; } if (D->ZPCount > 0) { SegDesc* FirstSeg = D->ZPSeg [0]; D->Header.ZPBase = FirstSeg->Seg->PC; } /* If we have byte wise relocation and an alignment of 1, we can set * the "simple addressing" bit in the header. */ if ((D->Header.Mode & MF_RELOC_MASK) == MF_RELOC_BYTE && (D->Header.Mode & MF_ALIGN_MASK) == MF_ALIGN_1) { D->Header.Mode = (D->Header.Mode & ~MF_ADDR_MASK) | MF_ADDR_SIMPLE; } } void O65WriteTarget (O65Desc* D, File* F) /* Write an o65 output file */ { char OptBuf [256]; /* Buffer for option strings */ unsigned OptLen; time_t T; const char* Name; /* Place the filename in the control structure */ D->Filename = GetString (F->Name); /* Check for unresolved symbols. The function O65Unresolved is called * if we get an unresolved symbol. */ D->Undef = 0; /* Reset the counter */ CheckUnresolvedImports (O65Unresolved, D); if (D->Undef > 0) { /* We had unresolved symbols, cannot create output file */ Error ("%u unresolved external(s) found - cannot create output file", D->Undef); } /* Setup the segment arrays */ O65SetupSegments (D, F); /* Setup additional stuff in the header */ O65SetupHeader (D); /* Open the file */ D->F = fopen (D->Filename, "wb"); if (D->F == 0) { Error ("Cannot open `%s': %s", D->Filename, strerror (errno)); } /* Keep the user happy */ Print (stdout, 1, "Opened `%s'...\n", D->Filename); /* Define some more options: A timestamp, the linker version and the * filename */ T = time (0); strcpy (OptBuf, ctime (&T)); OptLen = strlen (OptBuf); while (OptLen > 0 && IsControl (OptBuf[OptLen-1])) { --OptLen; } OptBuf[OptLen] = '\0'; O65SetOption (D, O65OPT_TIMESTAMP, OptBuf, OptLen + 1); sprintf (OptBuf, "ld65 V%s", GetVersionAsString ()); O65SetOption (D, O65OPT_ASM, OptBuf, strlen (OptBuf) + 1); Name = FindName (D->Filename); O65SetOption (D, O65OPT_FILENAME, Name, strlen (Name) + 1); /* Write the header */ O65WriteHeader (D); /* Write the text segment */ O65WriteTextSeg (D); /* Write the data segment */ O65WriteDataSeg (D); /* "Write" the bss segments */ O65WriteBssSeg (D); /* "Write" the zeropage segments */ O65WriteZPSeg (D); /* Write the undefined references list */ O65WriteImports (D); /* Write the text segment relocation table */ O65WriteTextReloc (D); /* Write the data segment relocation table */ O65WriteDataReloc (D); /* Write the list of exports */ O65WriteExports (D); /* Seek back to the start and write the updated header */ fseek (D->F, 0, SEEK_SET); O65WriteHeader (D); /* Close the file */ if (fclose (D->F) != 0) { Error ("Cannot write to `%s': %s", D->Filename, strerror (errno)); } /* Reset the file and filename */ D->F = 0; D->Filename = 0; }
996
./cc65/src/ld65/config.c
/*****************************************************************************/ /* */ /* config.c */ /* */ /* Target configuration file for the ld65 linker */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* With contributions from: */ /* */ /* - "David M. Lloyd" <david.lloyd@redhat.com> */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> /* common */ #include "addrsize.h" #include "bitops.h" #include "check.h" #include "print.h" #include "segdefs.h" #include "target.h" #include "xmalloc.h" #include "xsprintf.h" /* ld65 */ #include "alignment.h" #include "bin.h" #include "binfmt.h" #include "cfgexpr.h" #include "condes.h" #include "config.h" #include "error.h" #include "exports.h" #include "expr.h" #include "global.h" #include "memarea.h" #include "o65.h" #include "objdata.h" #include "scanner.h" #include "spool.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Remember which sections we had encountered */ static enum { SE_NONE = 0x0000, SE_MEMORY = 0x0001, SE_SEGMENTS = 0x0002, SE_FEATURES = 0x0004, SE_FILES = 0x0008, SE_FORMATS = 0x0010, SE_SYMBOLS = 0x0020 } SectionsEncountered = SE_NONE; /* File list */ static Collection FileList = STATIC_COLLECTION_INITIALIZER; /* Memory list */ static Collection MemoryAreas = STATIC_COLLECTION_INITIALIZER; /* Memory attributes */ #define MA_START 0x0001 #define MA_SIZE 0x0002 #define MA_TYPE 0x0004 #define MA_FILE 0x0008 #define MA_DEFINE 0x0010 #define MA_FILL 0x0020 #define MA_FILLVAL 0x0040 #define MA_BANK 0x0080 /* Segment list */ static Collection SegDescList = STATIC_COLLECTION_INITIALIZER; /* Segment attributes */ #define SA_TYPE 0x0001 #define SA_LOAD 0x0002 #define SA_RUN 0x0004 #define SA_ALIGN 0x0008 #define SA_ALIGN_LOAD 0x0010 #define SA_DEFINE 0x0020 #define SA_OFFSET 0x0040 #define SA_START 0x0080 #define SA_OPTIONAL 0x0100 #define SA_FILLVAL 0x0200 /* Symbol types used in the CfgSymbol structure */ typedef enum { CfgSymExport, /* Not really used in struct CfgSymbol */ CfgSymImport, /* Dito */ CfgSymWeak, /* Like export but weak */ CfgSymO65Export, /* An o65 export */ CfgSymO65Import, /* An o65 import */ } CfgSymType; /* Symbol structure. It is used for o65 imports and exports, but also for * symbols from the SYMBOLS sections (symbols defined in the config file or * forced imports). */ typedef struct CfgSymbol CfgSymbol; struct CfgSymbol { CfgSymType Type; /* Type of symbol */ LineInfo* LI; /* Config file position */ unsigned Name; /* Symbol name */ ExprNode* Value; /* Symbol value if any */ unsigned AddrSize; /* Address size of symbol */ }; /* Collections with symbols */ static Collection CfgSymbols = STATIC_COLLECTION_INITIALIZER; /* Descriptor holding information about the binary formats */ static BinDesc* BinFmtDesc = 0; static O65Desc* O65FmtDesc = 0; /*****************************************************************************/ /* Forwards */ /*****************************************************************************/ static File* NewFile (unsigned Name); /* Create a new file descriptor and insert it into the list */ /*****************************************************************************/ /* List management */ /*****************************************************************************/ static File* FindFile (unsigned Name) /* Find a file with a given name. */ { unsigned I; for (I = 0; I < CollCount (&FileList); ++I) { File* F = CollAtUnchecked (&FileList, I); if (F->Name == Name) { return F; } } return 0; } static File* GetFile (unsigned Name) /* Get a file entry with the given name. Create a new one if needed. */ { File* F = FindFile (Name); if (F == 0) { /* Create a new one */ F = NewFile (Name); } return F; } static void FileInsert (File* F, MemoryArea* M) /* Insert the memory area into the files list */ { M->F = F; CollAppend (&F->MemoryAreas, M); } static MemoryArea* CfgFindMemory (unsigned Name) /* Find the memory are with the given name. Return NULL if not found */ { unsigned I; for (I = 0; I < CollCount (&MemoryAreas); ++I) { MemoryArea* M = CollAtUnchecked (&MemoryAreas, I); if (M->Name == Name) { return M; } } return 0; } static MemoryArea* CfgGetMemory (unsigned Name) /* Find the memory are with the given name. Print an error on an invalid name */ { MemoryArea* M = CfgFindMemory (Name); if (M == 0) { CfgError (&CfgErrorPos, "Invalid memory area `%s'", GetString (Name)); } return M; } static SegDesc* CfgFindSegDesc (unsigned Name) /* Find the segment descriptor with the given name, return NULL if not found. */ { unsigned I; for (I = 0; I < CollCount (&SegDescList); ++I) { SegDesc* S = CollAtUnchecked (&SegDescList, I); if (S->Name == Name) { /* Found */ return S; } } /* Not found */ return 0; } static void MemoryInsert (MemoryArea* M, SegDesc* S) /* Insert the segment descriptor into the memory area list */ { /* Insert the segment into the segment list of the memory area */ CollAppend (&M->SegList, S); } /*****************************************************************************/ /* Constructors/Destructors */ /*****************************************************************************/ static CfgSymbol* NewCfgSymbol (CfgSymType Type, unsigned Name) /* Create a new CfgSymbol structure with the given type and name. The * current config file position is recorded in the returned struct. The * created struct is inserted into the CfgSymbols collection and returned. */ { /* Allocate memory */ CfgSymbol* Sym = xmalloc (sizeof (CfgSymbol)); /* Initialize the fields */ Sym->Type = Type; Sym->LI = GenLineInfo (&CfgErrorPos); Sym->Name = Name; Sym->Value = 0; Sym->AddrSize = ADDR_SIZE_INVALID; /* Insert the symbol into the collection */ CollAppend (&CfgSymbols, Sym); /* Return the initialized struct */ return Sym; } static File* NewFile (unsigned Name) /* Create a new file descriptor and insert it into the list */ { /* Allocate memory */ File* F = xmalloc (sizeof (File)); /* Initialize the fields */ F->Name = Name; F->Flags = 0; F->Format = BINFMT_DEFAULT; F->Size = 0; InitCollection (&F->MemoryAreas); /* Insert the struct into the list */ CollAppend (&FileList, F); /* ...and return it */ return F; } static MemoryArea* CreateMemoryArea (const FilePos* Pos, unsigned Name) /* Create a new memory area and insert it into the list */ { /* Check for duplicate names */ MemoryArea* M = CfgFindMemory (Name); if (M) { CfgError (&CfgErrorPos, "Memory area `%s' defined twice", GetString (Name)); } /* Create a new memory area */ M = NewMemoryArea (Pos, Name); /* Insert the struct into the list ... */ CollAppend (&MemoryAreas, M); /* ...and return it */ return M; } static SegDesc* NewSegDesc (unsigned Name) /* Create a segment descriptor and insert it into the list */ { /* Check for duplicate names */ SegDesc* S = CfgFindSegDesc (Name); if (S) { CfgError (&CfgErrorPos, "Segment `%s' defined twice", GetString (Name)); } /* Allocate memory */ S = xmalloc (sizeof (SegDesc)); /* Initialize the fields */ S->Name = Name; S->LI = GenLineInfo (&CfgErrorPos); S->Seg = 0; S->Attr = 0; S->Flags = 0; S->FillVal = 0; S->RunAlignment = 1; S->LoadAlignment = 1; /* Insert the struct into the list ... */ CollAppend (&SegDescList, S); /* ...and return it */ return S; } static void FreeSegDesc (SegDesc* S) /* Free a segment descriptor */ { FreeLineInfo (S->LI); xfree (S); } /*****************************************************************************/ /* Config file parsing */ /*****************************************************************************/ static void FlagAttr (unsigned* Flags, unsigned Mask, const char* Name) /* Check if the item is already defined. Print an error if so. If not, set * the marker that we have a definition now. */ { if (*Flags & Mask) { CfgError (&CfgErrorPos, "%s is already defined", Name); } *Flags |= Mask; } static void AttrCheck (unsigned Attr, unsigned Mask, const char* Name) /* Check that a mandatory attribute was given */ { if ((Attr & Mask) == 0) { CfgError (&CfgErrorPos, "%s attribute is missing", Name); } } static void ParseMemory (void) /* Parse a MEMORY section */ { static const IdentTok Attributes [] = { { "BANK", CFGTOK_BANK }, { "DEFINE", CFGTOK_DEFINE }, { "FILE", CFGTOK_FILE }, { "FILL", CFGTOK_FILL }, { "FILLVAL", CFGTOK_FILLVAL }, { "SIZE", CFGTOK_SIZE }, { "START", CFGTOK_START }, { "TYPE", CFGTOK_TYPE }, }; static const IdentTok Types [] = { { "RO", CFGTOK_RO }, { "RW", CFGTOK_RW }, }; while (CfgTok == CFGTOK_IDENT) { /* Create a new entry on the heap */ MemoryArea* M = CreateMemoryArea (&CfgErrorPos, GetStrBufId (&CfgSVal)); /* Skip the name and the following colon */ CfgNextTok (); CfgConsumeColon (); /* Read the attributes */ while (CfgTok == CFGTOK_IDENT) { /* Map the identifier to a token */ cfgtok_t AttrTok; CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute"); AttrTok = CfgTok; /* An optional assignment follows */ CfgNextTok (); CfgOptionalAssign (); /* Check which attribute was given */ switch (AttrTok) { case CFGTOK_BANK: FlagAttr (&M->Attr, MA_BANK, "BANK"); M->BankExpr = CfgExpr (); break; case CFGTOK_DEFINE: FlagAttr (&M->Attr, MA_DEFINE, "DEFINE"); /* Map the token to a boolean */ CfgBoolToken (); if (CfgTok == CFGTOK_TRUE) { M->Flags |= MF_DEFINE; } CfgNextTok (); break; case CFGTOK_FILE: FlagAttr (&M->Attr, MA_FILE, "FILE"); CfgAssureStr (); /* Get the file entry and insert the memory area */ FileInsert (GetFile (GetStrBufId (&CfgSVal)), M); CfgNextTok (); break; case CFGTOK_FILL: FlagAttr (&M->Attr, MA_FILL, "FILL"); /* Map the token to a boolean */ CfgBoolToken (); if (CfgTok == CFGTOK_TRUE) { M->Flags |= MF_FILL; } CfgNextTok (); break; case CFGTOK_FILLVAL: FlagAttr (&M->Attr, MA_FILLVAL, "FILLVAL"); M->FillVal = (unsigned char) CfgCheckedConstExpr (0, 0xFF); break; case CFGTOK_SIZE: FlagAttr (&M->Attr, MA_SIZE, "SIZE"); M->SizeExpr = CfgExpr (); break; case CFGTOK_START: FlagAttr (&M->Attr, MA_START, "START"); M->StartExpr = CfgExpr (); break; case CFGTOK_TYPE: FlagAttr (&M->Attr, MA_TYPE, "TYPE"); CfgSpecialToken (Types, ENTRY_COUNT (Types), "TYPE"); if (CfgTok == CFGTOK_RO) { M->Flags |= MF_RO; } CfgNextTok (); break; default: FAIL ("Unexpected attribute token"); } /* Skip an optional comma */ CfgOptionalComma (); } /* Skip the semicolon */ CfgConsumeSemi (); /* Check for mandatory parameters */ AttrCheck (M->Attr, MA_START, "START"); AttrCheck (M->Attr, MA_SIZE, "SIZE"); /* If we don't have a file name for output given, use the default * file name. */ if ((M->Attr & MA_FILE) == 0) { FileInsert (GetFile (GetStringId (OutputName)), M); OutputNameUsed = 1; } } /* Remember we had this section */ SectionsEncountered |= SE_MEMORY; } static void ParseFiles (void) /* Parse a FILES section */ { static const IdentTok Attributes [] = { { "FORMAT", CFGTOK_FORMAT }, }; static const IdentTok Formats [] = { { "O65", CFGTOK_O65 }, { "BIN", CFGTOK_BIN }, { "BINARY", CFGTOK_BIN }, }; /* The MEMORY section must preceed the FILES section */ if ((SectionsEncountered & SE_MEMORY) == 0) { CfgError (&CfgErrorPos, "MEMORY must precede FILES"); } /* Parse all files */ while (CfgTok != CFGTOK_RCURLY) { File* F; /* We expect a string value here */ CfgAssureStr (); /* Search for the file, it must exist */ F = FindFile (GetStrBufId (&CfgSVal)); if (F == 0) { CfgError (&CfgErrorPos, "File `%s' not found in MEMORY section", SB_GetConstBuf (&CfgSVal)); } /* Skip the token and the following colon */ CfgNextTok (); CfgConsumeColon (); /* Read the attributes */ while (CfgTok == CFGTOK_IDENT) { /* Map the identifier to a token */ cfgtok_t AttrTok; CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute"); AttrTok = CfgTok; /* An optional assignment follows */ CfgNextTok (); CfgOptionalAssign (); /* Check which attribute was given */ switch (AttrTok) { case CFGTOK_FORMAT: if (F->Format != BINFMT_DEFAULT) { /* We've set the format already! */ CfgError (&CfgErrorPos, "Cannot set a file format twice"); } /* Read the format token */ CfgSpecialToken (Formats, ENTRY_COUNT (Formats), "Format"); switch (CfgTok) { case CFGTOK_BIN: F->Format = BINFMT_BINARY; break; case CFGTOK_O65: F->Format = BINFMT_O65; break; default: Error ("Unexpected format token"); } break; default: FAIL ("Unexpected attribute token"); } /* Skip the attribute value and an optional comma */ CfgNextTok (); CfgOptionalComma (); } /* Skip the semicolon */ CfgConsumeSemi (); } /* Remember we had this section */ SectionsEncountered |= SE_FILES; } static void ParseSegments (void) /* Parse a SEGMENTS section */ { static const IdentTok Attributes [] = { { "ALIGN", CFGTOK_ALIGN }, { "ALIGN_LOAD", CFGTOK_ALIGN_LOAD }, { "DEFINE", CFGTOK_DEFINE }, { "FILLVAL", CFGTOK_FILLVAL }, { "LOAD", CFGTOK_LOAD }, { "OFFSET", CFGTOK_OFFSET }, { "OPTIONAL", CFGTOK_OPTIONAL }, { "RUN", CFGTOK_RUN }, { "START", CFGTOK_START }, { "TYPE", CFGTOK_TYPE }, }; static const IdentTok Types [] = { { "RO", CFGTOK_RO }, { "RW", CFGTOK_RW }, { "BSS", CFGTOK_BSS }, { "ZP", CFGTOK_ZP }, }; unsigned Count; /* The MEMORY section must preceed the SEGMENTS section */ if ((SectionsEncountered & SE_MEMORY) == 0) { CfgError (&CfgErrorPos, "MEMORY must precede SEGMENTS"); } while (CfgTok == CFGTOK_IDENT) { SegDesc* S; /* Create a new entry on the heap */ S = NewSegDesc (GetStrBufId (&CfgSVal)); /* Skip the name and the following colon */ CfgNextTok (); CfgConsumeColon (); /* Read the attributes */ while (CfgTok == CFGTOK_IDENT) { /* Map the identifier to a token */ cfgtok_t AttrTok; CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute"); AttrTok = CfgTok; /* An optional assignment follows */ CfgNextTok (); CfgOptionalAssign (); /* Check which attribute was given */ switch (AttrTok) { case CFGTOK_ALIGN: FlagAttr (&S->Attr, SA_ALIGN, "ALIGN"); S->RunAlignment = (unsigned) CfgCheckedConstExpr (1, MAX_ALIGNMENT); S->Flags |= SF_ALIGN; break; case CFGTOK_ALIGN_LOAD: FlagAttr (&S->Attr, SA_ALIGN_LOAD, "ALIGN_LOAD"); S->LoadAlignment = (unsigned) CfgCheckedConstExpr (1, MAX_ALIGNMENT); S->Flags |= SF_ALIGN_LOAD; break; case CFGTOK_DEFINE: FlagAttr (&S->Attr, SA_DEFINE, "DEFINE"); /* Map the token to a boolean */ CfgBoolToken (); if (CfgTok == CFGTOK_TRUE) { S->Flags |= SF_DEFINE; } CfgNextTok (); break; case CFGTOK_FILLVAL: FlagAttr (&S->Attr, SA_FILLVAL, "FILLVAL"); S->FillVal = (unsigned char) CfgCheckedConstExpr (0, 0xFF); S->Flags |= SF_FILLVAL; break; case CFGTOK_LOAD: FlagAttr (&S->Attr, SA_LOAD, "LOAD"); S->Load = CfgGetMemory (GetStrBufId (&CfgSVal)); CfgNextTok (); break; case CFGTOK_OFFSET: FlagAttr (&S->Attr, SA_OFFSET, "OFFSET"); S->Addr = CfgCheckedConstExpr (1, 0x1000000); S->Flags |= SF_OFFSET; break; case CFGTOK_OPTIONAL: FlagAttr (&S->Attr, SA_OPTIONAL, "OPTIONAL"); CfgBoolToken (); if (CfgTok == CFGTOK_TRUE) { S->Flags |= SF_OPTIONAL; } CfgNextTok (); break; case CFGTOK_RUN: FlagAttr (&S->Attr, SA_RUN, "RUN"); S->Run = CfgGetMemory (GetStrBufId (&CfgSVal)); CfgNextTok (); break; case CFGTOK_START: FlagAttr (&S->Attr, SA_START, "START"); S->Addr = CfgCheckedConstExpr (1, 0x1000000); S->Flags |= SF_START; break; case CFGTOK_TYPE: FlagAttr (&S->Attr, SA_TYPE, "TYPE"); CfgSpecialToken (Types, ENTRY_COUNT (Types), "Type"); switch (CfgTok) { case CFGTOK_RO: S->Flags |= SF_RO; break; case CFGTOK_RW: /* Default */ break; case CFGTOK_BSS: S->Flags |= SF_BSS; break; case CFGTOK_ZP: S->Flags |= (SF_BSS | SF_ZP); break; default: Internal ("Unexpected token: %d", CfgTok); } CfgNextTok (); break; default: FAIL ("Unexpected attribute token"); } /* Skip an optional comma */ CfgOptionalComma (); } /* Check for mandatory parameters */ AttrCheck (S->Attr, SA_LOAD, "LOAD"); /* Set defaults for stuff not given */ if ((S->Attr & SA_RUN) == 0) { S->Attr |= SA_RUN; S->Run = S->Load; } /* An attribute of ALIGN_LOAD doesn't make sense if there are no * separate run and load memory areas. */ if ((S->Flags & SF_ALIGN_LOAD) != 0 && (S->Load == S->Run)) { CfgWarning (&CfgErrorPos, "ALIGN_LOAD attribute specified, but no separate " "LOAD and RUN memory areas assigned"); /* Remove the flag */ S->Flags &= ~SF_ALIGN_LOAD; } /* If the segment is marked as BSS style, it may not have separate * load and run memory areas, because it's is never written to disk. */ if ((S->Flags & SF_BSS) != 0 && (S->Load != S->Run)) { CfgWarning (&CfgErrorPos, "Segment with type `bss' has both LOAD and RUN " "memory areas assigned"); } /* Don't allow read/write data to be put into a readonly area */ if ((S->Flags & SF_RO) == 0) { if (S->Run->Flags & MF_RO) { CfgError (&CfgErrorPos, "Cannot put r/w segment `%s' in r/o memory area `%s'", GetString (S->Name), GetString (S->Run->Name)); } } /* Only one of ALIGN, START and OFFSET may be used */ Count = ((S->Flags & SF_ALIGN) != 0) + ((S->Flags & SF_OFFSET) != 0) + ((S->Flags & SF_START) != 0); if (Count > 1) { CfgError (&CfgErrorPos, "Only one of ALIGN, START, OFFSET may be used"); } /* Skip the semicolon */ CfgConsumeSemi (); } /* Remember we had this section */ SectionsEncountered |= SE_SEGMENTS; } static void ParseO65 (void) /* Parse the o65 format section */ { static const IdentTok Attributes [] = { { "EXPORT", CFGTOK_EXPORT }, { "IMPORT", CFGTOK_IMPORT }, { "TYPE", CFGTOK_TYPE }, { "OS", CFGTOK_OS }, { "ID", CFGTOK_ID }, { "VERSION", CFGTOK_VERSION }, }; static const IdentTok Types [] = { { "SMALL", CFGTOK_SMALL }, { "LARGE", CFGTOK_LARGE }, }; static const IdentTok OperatingSystems [] = { { "LUNIX", CFGTOK_LUNIX }, { "OSA65", CFGTOK_OSA65 }, { "CC65", CFGTOK_CC65 }, { "OPENCBM", CFGTOK_OPENCBM }, }; /* Bitmask to remember the attributes we got already */ enum { atNone = 0x0000, atOS = 0x0001, atOSVersion = 0x0002, atType = 0x0004, atImport = 0x0008, atExport = 0x0010, atID = 0x0020, atVersion = 0x0040 }; unsigned AttrFlags = atNone; /* Remember the attributes read */ unsigned OS = 0; /* Initialize to keep gcc happy */ unsigned Version = 0; /* Read the attributes */ while (CfgTok == CFGTOK_IDENT) { /* Map the identifier to a token */ cfgtok_t AttrTok; CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute"); AttrTok = CfgTok; /* An optional assignment follows */ CfgNextTok (); CfgOptionalAssign (); /* Check which attribute was given */ switch (AttrTok) { case CFGTOK_EXPORT: /* Remember we had this token (maybe more than once) */ AttrFlags |= atExport; /* We expect an identifier */ CfgAssureIdent (); /* Remember it as an export for later */ NewCfgSymbol (CfgSymO65Export, GetStrBufId (&CfgSVal)); /* Eat the identifier token */ CfgNextTok (); break; case CFGTOK_IMPORT: /* Remember we had this token (maybe more than once) */ AttrFlags |= atImport; /* We expect an identifier */ CfgAssureIdent (); /* Remember it as an import for later */ NewCfgSymbol (CfgSymO65Import, GetStrBufId (&CfgSVal)); /* Eat the identifier token */ CfgNextTok (); break; case CFGTOK_TYPE: /* Cannot have this attribute twice */ FlagAttr (&AttrFlags, atType, "TYPE"); /* Get the type of the executable */ CfgSpecialToken (Types, ENTRY_COUNT (Types), "Type"); switch (CfgTok) { case CFGTOK_SMALL: O65SetSmallModel (O65FmtDesc); break; case CFGTOK_LARGE: O65SetLargeModel (O65FmtDesc); break; default: CfgError (&CfgErrorPos, "Unexpected type token"); } /* Eat the attribute token */ CfgNextTok (); break; case CFGTOK_OS: /* Cannot use this attribute twice */ FlagAttr (&AttrFlags, atOS, "OS"); /* Get the operating system. It may be specified as name or * as a number in the range 1..255. */ if (CfgTok == CFGTOK_INTCON) { CfgRangeCheck (O65OS_MIN, O65OS_MAX); OS = (unsigned) CfgIVal; } else { CfgSpecialToken (OperatingSystems, ENTRY_COUNT (OperatingSystems), "OS type"); switch (CfgTok) { case CFGTOK_LUNIX: OS = O65OS_LUNIX; break; case CFGTOK_OSA65: OS = O65OS_OSA65; break; case CFGTOK_CC65: OS = O65OS_CC65; break; case CFGTOK_OPENCBM: OS = O65OS_OPENCBM; break; default: CfgError (&CfgErrorPos, "Unexpected OS token"); } } CfgNextTok (); break; case CFGTOK_ID: /* Cannot have this attribute twice */ FlagAttr (&AttrFlags, atID, "ID"); /* We're expecting a number in the 0..$FFFF range*/ ModuleId = (unsigned) CfgCheckedConstExpr (0, 0xFFFF); break; case CFGTOK_VERSION: /* Cannot have this attribute twice */ FlagAttr (&AttrFlags, atVersion, "VERSION"); /* We're expecting a number in byte range */ Version = (unsigned) CfgCheckedConstExpr (0, 0xFF); break; default: FAIL ("Unexpected attribute token"); } /* Skip an optional comma */ CfgOptionalComma (); } /* Check if we have all mandatory attributes */ AttrCheck (AttrFlags, atOS, "OS"); /* Check for attributes that may not be combined */ if (OS == O65OS_CC65) { if ((AttrFlags & (atImport | atExport)) != 0 && ModuleId < 0x8000) { CfgError (&CfgErrorPos, "OS type CC65 may not have imports or exports for ids < $8000"); } } else { if (AttrFlags & atID) { CfgError (&CfgErrorPos, "Operating system does not support the ID attribute"); } } /* Set the O65 operating system to use */ O65SetOS (O65FmtDesc, OS, Version, ModuleId); } static void ParseFormats (void) /* Parse a target format section */ { static const IdentTok Formats [] = { { "O65", CFGTOK_O65 }, { "BIN", CFGTOK_BIN }, { "BINARY", CFGTOK_BIN }, }; while (CfgTok == CFGTOK_IDENT) { /* Map the identifier to a token */ cfgtok_t FormatTok; CfgSpecialToken (Formats, ENTRY_COUNT (Formats), "Format"); FormatTok = CfgTok; /* Skip the name and the following colon */ CfgNextTok (); CfgConsumeColon (); /* Parse the format options */ switch (FormatTok) { case CFGTOK_O65: ParseO65 (); break; case CFGTOK_BIN: /* No attribibutes available */ break; default: Error ("Unexpected format token"); } /* Skip the semicolon */ CfgConsumeSemi (); } /* Remember we had this section */ SectionsEncountered |= SE_FORMATS; } static void ParseConDes (void) /* Parse the CONDES feature */ { static const IdentTok Attributes [] = { { "COUNT", CFGTOK_COUNT }, { "IMPORT", CFGTOK_IMPORT }, { "LABEL", CFGTOK_LABEL }, { "ORDER", CFGTOK_ORDER }, { "SEGMENT", CFGTOK_SEGMENT }, { "TYPE", CFGTOK_TYPE }, }; static const IdentTok Types [] = { { "CONSTRUCTOR", CFGTOK_CONSTRUCTOR }, { "DESTRUCTOR", CFGTOK_DESTRUCTOR }, { "INTERRUPTOR", CFGTOK_INTERRUPTOR }, }; static const IdentTok Orders [] = { { "DECREASING", CFGTOK_DECREASING }, { "INCREASING", CFGTOK_INCREASING }, }; /* Attribute values. */ unsigned Count = INVALID_STRING_ID; unsigned Label = INVALID_STRING_ID; unsigned SegName = INVALID_STRING_ID; ConDesImport Import; /* Initialize to avoid gcc warnings: */ int Type = -1; ConDesOrder Order = cdIncreasing; /* Bitmask to remember the attributes we got already */ enum { atNone = 0x0000, atCount = 0x0001, atImport = 0x0002, atLabel = 0x0004, atOrder = 0x0008, atSegName = 0x0010, atType = 0x0020, }; unsigned AttrFlags = atNone; /* Parse the attributes */ while (1) { /* Map the identifier to a token */ cfgtok_t AttrTok; CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute"); AttrTok = CfgTok; /* An optional assignment follows */ CfgNextTok (); CfgOptionalAssign (); /* Check which attribute was given */ switch (AttrTok) { case CFGTOK_COUNT: /* Don't allow this twice */ FlagAttr (&AttrFlags, atCount, "COUNT"); /* We expect an identifier */ CfgAssureIdent (); /* Remember the value for later */ Count = GetStrBufId (&CfgSVal); break; case CFGTOK_IMPORT: /* Don't allow this twice */ FlagAttr (&AttrFlags, atImport, "IMPORT"); /* We expect an identifier */ CfgAssureIdent (); /* Remember value and position for later */ Import.Name = GetStrBufId (&CfgSVal); Import.Pos = CfgErrorPos; Import.AddrSize = ADDR_SIZE_ABS; break; case CFGTOK_LABEL: /* Don't allow this twice */ FlagAttr (&AttrFlags, atLabel, "LABEL"); /* We expect an identifier */ CfgAssureIdent (); /* Remember the value for later */ Label = GetStrBufId (&CfgSVal); break; case CFGTOK_ORDER: /* Don't allow this twice */ FlagAttr (&AttrFlags, atOrder, "ORDER"); CfgSpecialToken (Orders, ENTRY_COUNT (Orders), "Order"); switch (CfgTok) { case CFGTOK_DECREASING: Order = cdDecreasing; break; case CFGTOK_INCREASING: Order = cdIncreasing; break; default: FAIL ("Unexpected order token"); } break; case CFGTOK_SEGMENT: /* Don't allow this twice */ FlagAttr (&AttrFlags, atSegName, "SEGMENT"); /* We expect an identifier */ CfgAssureIdent (); /* Remember the value for later */ SegName = GetStrBufId (&CfgSVal); break; case CFGTOK_TYPE: /* Don't allow this twice */ FlagAttr (&AttrFlags, atType, "TYPE"); /* The type may be given as id or numerical */ if (CfgTok == CFGTOK_INTCON) { CfgRangeCheck (CD_TYPE_MIN, CD_TYPE_MAX); Type = (int) CfgIVal; } else { CfgSpecialToken (Types, ENTRY_COUNT (Types), "Type"); switch (CfgTok) { case CFGTOK_CONSTRUCTOR: Type = CD_TYPE_CON; break; case CFGTOK_DESTRUCTOR: Type = CD_TYPE_DES; break; case CFGTOK_INTERRUPTOR: Type = CD_TYPE_INT; break; default: FAIL ("Unexpected type token"); } } break; default: FAIL ("Unexpected attribute token"); } /* Skip the attribute value */ CfgNextTok (); /* Semicolon ends the ConDes decl, otherwise accept an optional comma */ if (CfgTok == CFGTOK_SEMI) { break; } else if (CfgTok == CFGTOK_COMMA) { CfgNextTok (); } } /* Check if we have all mandatory attributes */ AttrCheck (AttrFlags, atSegName, "SEGMENT"); AttrCheck (AttrFlags, atLabel, "LABEL"); AttrCheck (AttrFlags, atType, "TYPE"); /* Check if the condes has already attributes defined */ if (ConDesHasSegName(Type) || ConDesHasLabel(Type)) { CfgError (&CfgErrorPos, "CONDES attributes for type %d are already defined", Type); } /* Define the attributes */ ConDesSetSegName (Type, SegName); ConDesSetLabel (Type, Label); if (AttrFlags & atCount) { ConDesSetCountSym (Type, Count); } if (AttrFlags & atImport) { ConDesSetImport (Type, &Import); } if (AttrFlags & atOrder) { ConDesSetOrder (Type, Order); } } static void ParseStartAddress (void) /* Parse the STARTADDRESS feature */ { static const IdentTok Attributes [] = { { "DEFAULT", CFGTOK_DEFAULT }, }; /* Attribute values. */ unsigned long DefStartAddr = 0; /* Bitmask to remember the attributes we got already */ enum { atNone = 0x0000, atDefault = 0x0001 }; unsigned AttrFlags = atNone; /* Parse the attributes */ while (1) { /* Map the identifier to a token */ cfgtok_t AttrTok; CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute"); AttrTok = CfgTok; /* An optional assignment follows */ CfgNextTok (); CfgOptionalAssign (); /* Check which attribute was given */ switch (AttrTok) { case CFGTOK_DEFAULT: /* Don't allow this twice */ FlagAttr (&AttrFlags, atDefault, "DEFAULT"); /* We expect a numeric expression */ DefStartAddr = CfgCheckedConstExpr (0, 0xFFFFFF); break; default: FAIL ("Unexpected attribute token"); } /* Semicolon ends the ConDes decl, otherwise accept an optional comma */ if (CfgTok == CFGTOK_SEMI) { break; } else if (CfgTok == CFGTOK_COMMA) { CfgNextTok (); } } /* Check if we have all mandatory attributes */ AttrCheck (AttrFlags, atDefault, "DEFAULT"); /* If no start address was given on the command line, use the one given * here */ if (!HaveStartAddr) { StartAddr = DefStartAddr; } } static void ParseFeatures (void) /* Parse a features section */ { static const IdentTok Features [] = { { "CONDES", CFGTOK_CONDES }, { "STARTADDRESS", CFGTOK_STARTADDRESS }, }; while (CfgTok == CFGTOK_IDENT) { /* Map the identifier to a token */ cfgtok_t FeatureTok; CfgSpecialToken (Features, ENTRY_COUNT (Features), "Feature"); FeatureTok = CfgTok; /* Skip the name and the following colon */ CfgNextTok (); CfgConsumeColon (); /* Parse the format options */ switch (FeatureTok) { case CFGTOK_CONDES: ParseConDes (); break; case CFGTOK_STARTADDRESS: ParseStartAddress (); break; default: FAIL ("Unexpected feature token"); } /* Skip the semicolon */ CfgConsumeSemi (); } /* Remember we had this section */ SectionsEncountered |= SE_FEATURES; } static void ParseSymbols (void) /* Parse a symbols section */ { static const IdentTok Attributes[] = { { "ADDRSIZE", CFGTOK_ADDRSIZE }, { "TYPE", CFGTOK_TYPE }, { "VALUE", CFGTOK_VALUE }, }; static const IdentTok AddrSizes [] = { { "ABS", CFGTOK_ABS }, { "ABSOLUTE", CFGTOK_ABS }, { "DIRECT", CFGTOK_ZP }, { "DWORD", CFGTOK_LONG }, { "FAR", CFGTOK_FAR }, { "LONG", CFGTOK_LONG }, { "NEAR", CFGTOK_ABS }, { "ZEROPAGE", CFGTOK_ZP }, { "ZP", CFGTOK_ZP }, }; static const IdentTok Types [] = { { "EXPORT", CFGTOK_EXPORT }, { "IMPORT", CFGTOK_IMPORT }, { "WEAK", CFGTOK_WEAK }, }; while (CfgTok == CFGTOK_IDENT) { /* Bitmask to remember the attributes we got already */ enum { atNone = 0x0000, atAddrSize = 0x0001, atType = 0x0002, atValue = 0x0004, }; unsigned AttrFlags = atNone; ExprNode* Value = 0; CfgSymType Type = CfgSymExport; unsigned char AddrSize = ADDR_SIZE_ABS; Import* Imp; Export* Exp; CfgSymbol* Sym; /* Remember the name */ unsigned Name = GetStrBufId (&CfgSVal); CfgNextTok (); /* New syntax - skip the colon */ CfgNextTok (); /* Parse the attributes */ while (1) { /* Map the identifier to a token */ cfgtok_t AttrTok; CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute"); AttrTok = CfgTok; /* Skip the attribute name */ CfgNextTok (); /* An optional assignment follows */ CfgOptionalAssign (); /* Check which attribute was given */ switch (AttrTok) { case CFGTOK_ADDRSIZE: /* Don't allow this twice */ FlagAttr (&AttrFlags, atAddrSize, "ADDRSIZE"); /* Map the type to a token */ CfgSpecialToken (AddrSizes, ENTRY_COUNT (AddrSizes), "AddrSize"); switch (CfgTok) { case CFGTOK_ABS: AddrSize = ADDR_SIZE_ABS; break; case CFGTOK_FAR: AddrSize = ADDR_SIZE_FAR; break; case CFGTOK_LONG: AddrSize = ADDR_SIZE_LONG; break; case CFGTOK_ZP: AddrSize = ADDR_SIZE_ZP; break; default: Internal ("Unexpected token: %d", CfgTok); } CfgNextTok (); break; case CFGTOK_TYPE: /* Don't allow this twice */ FlagAttr (&AttrFlags, atType, "TYPE"); /* Map the type to a token */ CfgSpecialToken (Types, ENTRY_COUNT (Types), "Type"); switch (CfgTok) { case CFGTOK_EXPORT: Type = CfgSymExport; break; case CFGTOK_IMPORT: Type = CfgSymImport; break; case CFGTOK_WEAK: Type = CfgSymWeak; break; default: Internal ("Unexpected token: %d", CfgTok); } CfgNextTok (); break; case CFGTOK_VALUE: /* Don't allow this twice */ FlagAttr (&AttrFlags, atValue, "VALUE"); /* Value is an expression */ Value = CfgExpr (); break; default: FAIL ("Unexpected attribute token"); } /* Semicolon ends the decl, otherwise accept an optional comma */ if (CfgTok == CFGTOK_SEMI) { break; } else if (CfgTok == CFGTOK_COMMA) { CfgNextTok (); } } /* We must have a type */ AttrCheck (AttrFlags, atType, "TYPE"); /* Further actions depend on the type */ switch (Type) { case CfgSymExport: /* We must have a value */ AttrCheck (AttrFlags, atValue, "VALUE"); /* Create the export */ Exp = CreateExprExport (Name, Value, AddrSize); CollAppend (&Exp->DefLines, GenLineInfo (&CfgErrorPos)); break; case CfgSymImport: /* An import must not have a value */ if (AttrFlags & atValue) { CfgError (&CfgErrorPos, "Imports must not have a value"); } /* Generate the import */ Imp = InsertImport (GenImport (Name, AddrSize)); /* Remember the file position */ CollAppend (&Imp->RefLines, GenLineInfo (&CfgErrorPos)); break; case CfgSymWeak: /* We must have a value */ AttrCheck (AttrFlags, atValue, "VALUE"); /* Remember the symbol for later */ Sym = NewCfgSymbol (CfgSymWeak, Name); Sym->Value = Value; Sym->AddrSize = AddrSize; break; default: Internal ("Unexpected symbol type %d", Type); } /* Skip the semicolon */ CfgConsumeSemi (); } /* Remember we had this section */ SectionsEncountered |= SE_SYMBOLS; } static void ParseConfig (void) /* Parse the config file */ { static const IdentTok BlockNames [] = { { "MEMORY", CFGTOK_MEMORY }, { "FILES", CFGTOK_FILES }, { "SEGMENTS", CFGTOK_SEGMENTS }, { "FORMATS", CFGTOK_FORMATS }, { "FEATURES", CFGTOK_FEATURES }, { "SYMBOLS", CFGTOK_SYMBOLS }, }; cfgtok_t BlockTok; do { /* Read the block ident */ CfgSpecialToken (BlockNames, ENTRY_COUNT (BlockNames), "Block identifier"); BlockTok = CfgTok; CfgNextTok (); /* Expected a curly brace */ CfgConsume (CFGTOK_LCURLY, "`{' expected"); /* Read the block */ switch (BlockTok) { case CFGTOK_MEMORY: ParseMemory (); break; case CFGTOK_FILES: ParseFiles (); break; case CFGTOK_SEGMENTS: ParseSegments (); break; case CFGTOK_FORMATS: ParseFormats (); break; case CFGTOK_FEATURES: ParseFeatures (); break; case CFGTOK_SYMBOLS: ParseSymbols (); break; default: FAIL ("Unexpected block token"); } /* Skip closing brace */ CfgConsume (CFGTOK_RCURLY, "`}' expected"); } while (CfgTok != CFGTOK_EOF); } void CfgRead (void) /* Read the configuration */ { /* Create the descriptors for the binary formats */ BinFmtDesc = NewBinDesc (); O65FmtDesc = NewO65Desc (); /* If we have a config name given, open the file, otherwise we will read * from a buffer. */ CfgOpenInput (); /* Parse the file */ ParseConfig (); /* Close the input file */ CfgCloseInput (); } /*****************************************************************************/ /* Config file processing */ /*****************************************************************************/ static void ProcessSegments (void) /* Process the SEGMENTS section */ { unsigned I; /* Walk over the list of segment descriptors */ I = 0; while (I < CollCount (&SegDescList)) { /* Get the next segment descriptor */ SegDesc* S = CollAtUnchecked (&SegDescList, I); /* Search for the actual segment in the input files. The function may * return NULL (no such segment), this is checked later. */ S->Seg = SegFind (S->Name); /* If the segment is marked as BSS style, and if the segment exists * in any of the object file, check that there's no initialized data * in the segment. */ if ((S->Flags & SF_BSS) != 0 && S->Seg != 0 && !IsBSSType (S->Seg)) { CfgWarning (GetSourcePos (S->LI), "Segment `%s' with type `bss' contains initialized data", GetString (S->Name)); } /* If this segment does exist in any of the object files, insert the * segment into the load/run memory areas. Otherwise print a warning * and discard it, because the segment pointer in the descriptor is * invalid. */ if (S->Seg != 0) { /* Insert the segment into the memory area list */ MemoryInsert (S->Run, S); if (S->Load != S->Run) { /* We have separate RUN and LOAD areas */ MemoryInsert (S->Load, S); } /* Use the fill value from the config */ S->Seg->FillVal = S->FillVal; /* Process the next segment descriptor in the next run */ ++I; } else { /* Print a warning if the segment is not optional */ if ((S->Flags & SF_OPTIONAL) == 0) { CfgWarning (&CfgErrorPos, "Segment `%s' does not exist", GetString (S->Name)); } /* Discard the descriptor and remove it from the collection */ FreeSegDesc (S); CollDelete (&SegDescList, I); } } } static void ProcessSymbols (void) /* Process the SYMBOLS section */ { Export* E; /* Walk over all symbols */ unsigned I; for (I = 0; I < CollCount (&CfgSymbols); ++I) { /* Get the next symbol */ CfgSymbol* Sym = CollAtUnchecked (&CfgSymbols, I); /* Check what it is. */ switch (Sym->Type) { case CfgSymO65Export: /* Check if the export symbol is also defined as an import. */ if (O65GetImport (O65FmtDesc, Sym->Name) != 0) { CfgError ( GetSourcePos (Sym->LI), "Exported o65 symbol `%s' cannot also be an o65 import", GetString (Sym->Name) ); } /* Check if we have this symbol defined already. The entry * routine will check this also, but we get a more verbose * error message when checking it here. */ if (O65GetExport (O65FmtDesc, Sym->Name) != 0) { CfgError ( GetSourcePos (Sym->LI), "Duplicate exported o65 symbol: `%s'", GetString (Sym->Name) ); } /* Insert the symbol into the table */ O65SetExport (O65FmtDesc, Sym->Name); break; case CfgSymO65Import: /* Check if the import symbol is also defined as an export. */ if (O65GetExport (O65FmtDesc, Sym->Name) != 0) { CfgError ( GetSourcePos (Sym->LI), "Imported o65 symbol `%s' cannot also be an o65 export", GetString (Sym->Name) ); } /* Check if we have this symbol defined already. The entry * routine will check this also, but we get a more verbose * error message when checking it here. */ if (O65GetImport (O65FmtDesc, Sym->Name) != 0) { CfgError ( GetSourcePos (Sym->LI), "Duplicate imported o65 symbol: `%s'", GetString (Sym->Name) ); } /* Insert the symbol into the table */ O65SetImport (O65FmtDesc, Sym->Name); break; case CfgSymWeak: /* If the symbol is not defined until now, define it */ if ((E = FindExport (Sym->Name)) == 0 || IsUnresolvedExport (E)) { /* The symbol is undefined, generate an export */ E = CreateExprExport (Sym->Name, Sym->Value, Sym->AddrSize); CollAppend (&E->DefLines, Sym->LI); } break; default: Internal ("Unexpected symbol type %d", Sym->Type); break; } } } static void CreateRunDefines (SegDesc* S, unsigned long SegAddr) /* Create the defines for a RUN segment */ { Export* E; StrBuf Buf = STATIC_STRBUF_INITIALIZER; /* Define the run address of the segment */ SB_Printf (&Buf, "__%s_RUN__", GetString (S->Name)); E = CreateMemoryExport (GetStrBufId (&Buf), S->Run, SegAddr - S->Run->Start); CollAppend (&E->DefLines, S->LI); /* Define the size of the segment */ SB_Printf (&Buf, "__%s_SIZE__", GetString (S->Name)); E = CreateConstExport (GetStrBufId (&Buf), S->Seg->Size); CollAppend (&E->DefLines, S->LI); S->Flags |= SF_RUN_DEF; SB_Done (&Buf); } static void CreateLoadDefines (SegDesc* S, unsigned long SegAddr) /* Create the defines for a LOAD segment */ { Export* E; StrBuf Buf = STATIC_STRBUF_INITIALIZER; /* Define the load address of the segment */ SB_Printf (&Buf, "__%s_LOAD__", GetString (S->Name)); E = CreateMemoryExport (GetStrBufId (&Buf), S->Load, SegAddr - S->Load->Start); CollAppend (&E->DefLines, S->LI); S->Flags |= SF_LOAD_DEF; SB_Done (&Buf); } unsigned CfgProcess (void) /* Process the config file after reading in object files and libraries. This * includes postprocessing of the config file data but also assigning segments * and defining segment/memory area related symbols. The function will return * the number of memory area overflows (so zero means anything went ok). * In case of overflows, a short mapfile can be generated later, to ease the * task of rearranging segments for the user. */ { unsigned Overflows = 0; unsigned I; /* Postprocess symbols. We must do that first, since weak symbols are * defined here, which may be needed later. */ ProcessSymbols (); /* Postprocess segments */ ProcessSegments (); /* Walk through each of the memory sections. Add up the sizes and check * for an overflow of the section. Assign the start addresses of the * segments while doing this. */ for (I = 0; I < CollCount (&MemoryAreas); ++I) { unsigned J; unsigned long Addr; /* Get the next memory area */ MemoryArea* M = CollAtUnchecked (&MemoryAreas, I); /* Remember the offset in the output file */ M->FileOffs = M->F->Size; /* Remember if this is a relocatable memory area */ M->Relocatable = RelocatableBinFmt (M->F->Format); /* Resolve the start address expression, remember the start address * and mark the memory area as placed. */ if (!IsConstExpr (M->StartExpr)) { CfgError (GetSourcePos (M->LI), "Start address of memory area `%s' is not constant", GetString (M->Name)); } Addr = M->Start = GetExprVal (M->StartExpr); M->Flags |= MF_PLACED; /* If requested, define the symbol for the start of the memory area. * Doing it here means that the expression for the size of the area * may reference this symbol. */ if (M->Flags & MF_DEFINE) { Export* E; StrBuf Buf = STATIC_STRBUF_INITIALIZER; /* Define the start of the memory area */ SB_Printf (&Buf, "__%s_START__", GetString (M->Name)); E = CreateMemoryExport (GetStrBufId (&Buf), M, 0); CollAppend (&E->DefLines, M->LI); SB_Done (&Buf); } /* Resolve the size expression */ if (!IsConstExpr (M->SizeExpr)) { CfgError (GetSourcePos (M->LI), "Size of memory area `%s' is not constant", GetString (M->Name)); } M->Size = GetExprVal (M->SizeExpr); /* Walk through the segments in this memory area */ for (J = 0; J < CollCount (&M->SegList); ++J) { /* Get the segment */ SegDesc* S = CollAtUnchecked (&M->SegList, J); /* Remember the start address before handling this segment */ unsigned long StartAddr = Addr; /* Some actions depend on wether this is the load or run memory * area. */ if (S->Run == M) { /* This is the run (and maybe load) memory area. Handle * alignment and explict start address and offset. */ if (S->Flags & SF_ALIGN) { /* Align the address */ unsigned long NewAddr = AlignAddr (Addr, S->RunAlignment); /* If the first segment placed in the memory area needs * fill bytes for the alignment, emit a warning, since * this is somewhat suspicious. */ if (M->FillLevel == 0 && NewAddr > Addr) { CfgWarning (GetSourcePos (S->LI), "First segment in memory area `%s' does " "already need fill bytes for alignment", GetString (M->Name)); } /* Use the aligned address */ Addr = NewAddr; } else if (S->Flags & (SF_OFFSET | SF_START)) { /* Give the segment a fixed starting address */ unsigned long NewAddr = S->Addr; if (S->Flags & SF_OFFSET) { /* An offset was given, no address, make an address */ NewAddr += M->Start; } if (Addr > NewAddr) { /* Offset already too large */ if (S->Flags & SF_OFFSET) { CfgError (GetSourcePos (M->LI), "Offset too small in `%s', segment `%s'", GetString (M->Name), GetString (S->Name)); } else { CfgError (GetSourcePos (M->LI), "Start address too low in `%s', segment `%s'", GetString (M->Name), GetString (S->Name)); } } Addr = NewAddr; } /* Set the start address of this segment, set the readonly flag * in the segment and and remember if the segment is in a * relocatable file or not. */ S->Seg->PC = Addr; S->Seg->ReadOnly = (S->Flags & SF_RO) != 0; /* Remember the run memory for this segment, which is also a * flag that the segment has been placed. */ S->Seg->MemArea = M; } else if (S->Load == M) { /* This is the load memory area, *and* run and load are * different (because of the "else" above). Handle alignment. */ if (S->Flags & SF_ALIGN_LOAD) { /* Align the address */ Addr = AlignAddr (Addr, S->LoadAlignment); } } /* If this is the load memory area and the segment doesn't have a * fill value defined, use the one from the memory area. */ if (S->Load == M && (S->Flags & SF_FILLVAL) == 0) { S->Seg->FillVal = M->FillVal; } /* Increment the fill level of the memory area and check for an * overflow. */ M->FillLevel = Addr + S->Seg->Size - M->Start; if (M->FillLevel > M->Size && (M->Flags & MF_OVERFLOW) == 0) { ++Overflows; M->Flags |= MF_OVERFLOW; CfgWarning (GetSourcePos (M->LI), "Memory area overflow in `%s', segment `%s' (%lu bytes)", GetString (M->Name), GetString (S->Name), M->FillLevel - M->Size); } /* If requested, define symbols for the start and size of the * segment. */ if (S->Flags & SF_DEFINE) { if (S->Run == M && (S->Flags & SF_RUN_DEF) == 0) { CreateRunDefines (S, Addr); } if (S->Load == M && (S->Flags & SF_LOAD_DEF) == 0) { CreateLoadDefines (S, Addr); } } /* Calculate the new address */ Addr += S->Seg->Size; /* If this segment goes out to the file, increase the file size */ if ((S->Flags & SF_BSS) == 0 && S->Load == M) { M->F->Size += Addr - StartAddr; } } /* If requested, define symbols for start, size and offset of the * memory area */ if (M->Flags & MF_DEFINE) { Export* E; StrBuf Buf = STATIC_STRBUF_INITIALIZER; /* Define the size of the memory area */ SB_Printf (&Buf, "__%s_SIZE__", GetString (M->Name)); E = CreateConstExport (GetStrBufId (&Buf), M->Size); CollAppend (&E->DefLines, M->LI); /* Define the fill level of the memory area */ SB_Printf (&Buf, "__%s_LAST__", GetString (M->Name)); E = CreateMemoryExport (GetStrBufId (&Buf), M, M->FillLevel); CollAppend (&E->DefLines, M->LI); /* Define the file offset of the memory area. This isn't of much * use for relocatable output files. */ if (!M->Relocatable) { SB_Printf (&Buf, "__%s_FILEOFFS__", GetString (M->Name)); E = CreateConstExport (GetStrBufId (&Buf), M->FileOffs); CollAppend (&E->DefLines, M->LI); } /* Throw away the string buffer */ SB_Done (&Buf); } /* If we didn't have an overflow and are requested to fill the memory * area, acount for that in the file size. */ if ((M->Flags & MF_OVERFLOW) == 0 && (M->Flags & MF_FILL) != 0) { M->F->Size += (M->Size - M->FillLevel); } } /* Return the number of memory area overflows */ return Overflows; } void CfgWriteTarget (void) /* Write the target file(s) */ { unsigned I; /* Walk through the files list */ for (I = 0; I < CollCount (&FileList); ++I) { /* Get this entry */ File* F = CollAtUnchecked (&FileList, I); /* We don't need to look at files with no memory areas */ if (CollCount (&F->MemoryAreas) > 0) { /* Is there an output file? */ if (SB_GetLen (GetStrBuf (F->Name)) > 0) { /* Assign a proper binary format */ if (F->Format == BINFMT_DEFAULT) { F->Format = DefaultBinFmt; } /* Call the apropriate routine for the binary format */ switch (F->Format) { case BINFMT_BINARY: BinWriteTarget (BinFmtDesc, F); break; case BINFMT_O65: O65WriteTarget (O65FmtDesc, F); break; default: Internal ("Invalid binary format: %u", F->Format); } } else { /* No output file. Walk through the list and mark all segments * loading into these memory areas in this file as dumped. */ unsigned J; for (J = 0; J < CollCount (&F->MemoryAreas); ++J) { unsigned K; /* Get this entry */ MemoryArea* M = CollAtUnchecked (&F->MemoryAreas, J); /* Debugging */ Print (stdout, 2, "Skipping `%s'...\n", GetString (M->Name)); /* Walk throught the segments */ for (K = 0; K < CollCount (&M->SegList); ++K) { SegDesc* S = CollAtUnchecked (&M->SegList, K); if (S->Load == M) { /* Load area - mark the segment as dumped */ S->Seg->Dumped = 1; } } } } } } }
997
./cc65/src/ld65/mapfile.c
/*****************************************************************************/ /* */ /* mapfile.c */ /* */ /* Map file creation for the ld65 linker */ /* */ /* */ /* */ /* (C) 1998-2010, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <errno.h> /* ld65 */ #include "config.h" #include "dbgsyms.h" #include "exports.h" #include "global.h" #include "error.h" #include "library.h" #include "mapfile.h" #include "objdata.h" #include "segments.h" #include "spool.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void CreateMapFile (int ShortMap) /* Create a map file. If ShortMap is true, only the segment lists are * generated, not the import/export lists. */ { unsigned I; /* Open the map file */ FILE* F = fopen (MapFileName, "w"); if (F == 0) { Error ("Cannot create map file `%s': %s", MapFileName, strerror (errno)); } /* Write a modules list */ fprintf (F, "Modules list:\n" "-------------\n"); for (I = 0; I < CollCount (&ObjDataList); ++I) { unsigned J; /* Get the object file */ const ObjData* O = CollConstAt (&ObjDataList, I); /* Output the data */ if (O->Lib) { /* The file is from a library */ fprintf (F, "%s(%s):\n", GetLibFileName (O->Lib), GetObjFileName (O)); } else { fprintf (F, "%s:\n", GetObjFileName (O)); } for (J = 0; J < CollCount (&O->Sections); ++J) { const Section* S = CollConstAt (&O->Sections, J); /* Don't include zero sized sections if not explicitly * requested */ if (VerboseMap || S->Size > 0) { fprintf (F, " %-17s Offs=%06lX Size=%06lX " "Align=%05lX Fill=%04lX\n", GetString (S->Seg->Name), S->Offs, S->Size, S->Alignment, S->Fill); } } } /* Write the segment list */ fprintf (F, "\n\n" "Segment list:\n" "-------------\n"); PrintSegmentMap (F); /* The remainder is not written for short map files */ if (!ShortMap) { /* Write the exports list */ fprintf (F, "\n\n" "Exports list:\n" "-------------\n"); PrintExportMap (F); /* Write the imports list */ fprintf (F, "\n\n" "Imports list:\n" "-------------\n"); PrintImportMap (F); } /* Close the file */ if (fclose (F) != 0) { Error ("Error closing map file `%s': %s", MapFileName, strerror (errno)); } } void CreateLabelFile (void) /* Create a label file */ { /* Open the label file */ FILE* F = fopen (LabelFileName, "w"); if (F == 0) { Error ("Cannot create label file `%s': %s", LabelFileName, strerror (errno)); } /* Print the labels for the export symbols */ PrintExportLabels (F); /* Output the labels */ PrintDbgSymLabels (F); /* Close the file */ if (fclose (F) != 0) { Error ("Error closing label file `%s': %s", LabelFileName, strerror (errno)); } }
998
./cc65/src/ld65/condes.c
/*****************************************************************************/ /* */ /* condes.c */ /* */ /* Module constructor/destructor support */ /* */ /* */ /* */ /* (C) 2000-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "addrsize.h" #include "check.h" #include "coll.h" #include "filepos.h" #include "fragdefs.h" #include "xmalloc.h" /* ld65 */ #include "condes.h" #include "exports.h" #include "fragment.h" #include "segments.h" #include "spool.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Struct describing one condes type */ typedef struct ConDesDesc ConDesDesc; struct ConDesDesc { Collection ExpList; /* List of exported symbols */ unsigned SegName; /* Name of segment the table is in */ unsigned Label; /* Name of table label */ unsigned CountSym; /* Name of symbol for entry count */ unsigned char Order; /* Table order (increasing/decreasing) */ ConDesImport Import; /* Forced import if any */ }; /* Array for all types */ static ConDesDesc ConDes[CD_TYPE_COUNT] = { { STATIC_COLLECTION_INITIALIZER, INVALID_STRING_ID, INVALID_STRING_ID, INVALID_STRING_ID, cdIncreasing, { INVALID_STRING_ID, STATIC_FILEPOS_INITIALIZER, ADDR_SIZE_DEFAULT }, },{ STATIC_COLLECTION_INITIALIZER, INVALID_STRING_ID, INVALID_STRING_ID, INVALID_STRING_ID, cdIncreasing, { INVALID_STRING_ID, STATIC_FILEPOS_INITIALIZER, ADDR_SIZE_DEFAULT }, },{ STATIC_COLLECTION_INITIALIZER, INVALID_STRING_ID, INVALID_STRING_ID, INVALID_STRING_ID, cdIncreasing, { INVALID_STRING_ID, STATIC_FILEPOS_INITIALIZER, ADDR_SIZE_DEFAULT }, },{ STATIC_COLLECTION_INITIALIZER, INVALID_STRING_ID, INVALID_STRING_ID, INVALID_STRING_ID, cdIncreasing, { INVALID_STRING_ID, STATIC_FILEPOS_INITIALIZER, ADDR_SIZE_DEFAULT }, },{ STATIC_COLLECTION_INITIALIZER, INVALID_STRING_ID, INVALID_STRING_ID, INVALID_STRING_ID, cdIncreasing, { INVALID_STRING_ID, STATIC_FILEPOS_INITIALIZER, ADDR_SIZE_DEFAULT }, },{ STATIC_COLLECTION_INITIALIZER, INVALID_STRING_ID, INVALID_STRING_ID, INVALID_STRING_ID, cdIncreasing, { INVALID_STRING_ID, STATIC_FILEPOS_INITIALIZER, ADDR_SIZE_DEFAULT }, },{ STATIC_COLLECTION_INITIALIZER, INVALID_STRING_ID, INVALID_STRING_ID, INVALID_STRING_ID, cdIncreasing, { INVALID_STRING_ID, STATIC_FILEPOS_INITIALIZER, ADDR_SIZE_DEFAULT }, }, }; /*****************************************************************************/ /* Internally used function to create the condes tables */ /*****************************************************************************/ static int ConDesCompare (void* Data, const void* E1, const void* E2) /* Compare function to sort the exports */ { int Cmp; /* Data is actually a pointer to a ConDesDesc from the table, E1 and * E2 are exports from the collection. Get the condes type and cast * the void pointers to object pointers. */ ConDesDesc* CD = ((ConDesDesc*) Data); int Type = CD - ConDes; const Export* Exp1 = (const Export*) E1; const Export* Exp2 = (const Export*) E2; /* Get the priorities of the two exports */ unsigned Prio1 = Exp1->ConDes[Type]; unsigned Prio2 = Exp2->ConDes[Type]; /* Compare the priorities for this condes type */ if (Prio1 < Prio2) { Cmp = -1; } else if (Prio1 > Prio2) { Cmp = 1; } else { /* Use the name in this case */ Cmp = SB_Compare (GetStrBuf (Exp1->Name), GetStrBuf (Exp2->Name)); } /* Reverse the result for decreasing order */ if (CD->Order == cdIncreasing) { return Cmp; } else { return -Cmp; } } static void ConDesCreateOne (ConDesDesc* CD) /* Create one table if requested */ { Segment* Seg; /* Segment for table */ Section* Sec; /* Section for table */ unsigned Count; /* Number of exports */ unsigned I; /* Check if this table has a segment and table label defined. If not, * creation was not requested in the config file - ignore it. */ if (CD->SegName == INVALID_STRING_ID || CD->Label == INVALID_STRING_ID) { return; } /* Check if there is an import for the table label. If not, there is no * reference to the table and we would just waste memory creating the * table. */ if (!IsUnresolved (CD->Label)) { return; } /* Sort the collection of exports according to priority */ CollSort (&CD->ExpList, ConDesCompare, CD); /* Get the segment for the table, create it if needed */ Seg = GetSegment (CD->SegName, ADDR_SIZE_ABS, 0); /* Create a new section for the table */ Sec = NewSection (Seg, 1, ADDR_SIZE_ABS); /* Walk over the exports and create a fragment for each one. We will use * the exported expression without copying it, since it's cheap and there * is currently no place where it gets changed (hope this will not hunt * me later...). */ Count = CollCount (&CD->ExpList); for (I = 0; I < Count; ++I) { /* Get the export */ Export* E = CollAt (&CD->ExpList, I); /* Create the fragment */ Fragment* F = NewFragment (FRAG_EXPR, 2, Sec); /* Set the expression pointer */ F->Expr = E->Expr; } /* Define the table start as an export, offset into section is zero * (the section only contains the table). */ CreateSectionExport (CD->Label, Sec, 0); /* If we have a CountSym name given AND if it is referenced, define it * with the number of elements in the table. */ if (CD->CountSym) { CreateConstExport (CD->CountSym, Count); } } /*****************************************************************************/ /* Code */ /*****************************************************************************/ void ConDesAddExport (struct Export* E) /* Add the given export to the list of constructors/destructor */ { unsigned Type; /* Insert the export into all tables for which declarations exist */ for (Type = 0; Type < CD_TYPE_COUNT; ++Type) { unsigned Prio = E->ConDes[Type]; if (Prio != CD_PRIO_NONE) { CollAppend (&ConDes[Type].ExpList, E); } } } void ConDesSetSegName (unsigned Type, unsigned SegName) /* Set the segment name where the table should go */ { /* Check the parameters */ PRECONDITION (Type <= CD_TYPE_MAX && SegName != 0); /* Setting the segment name twice is bad */ CHECK (ConDes[Type].SegName == INVALID_STRING_ID); /* Set the name */ ConDes[Type].SegName = SegName; } const ConDesImport* ConDesGetImport (unsigned Type) /* Get the forced import for the given ConDes type. Returns NULL if there is * no forced import for this type. */ { const ConDesImport* Import; /* Check the parameters */ PRECONDITION (Type <= CD_TYPE_MAX); /* Return the import */ Import = &ConDes[Type].Import; return (Import->Name != INVALID_STRING_ID)? Import : 0; } void ConDesSetImport (unsigned Type, const ConDesImport* Import) /* Set the forced import for the given ConDes type */ { /* Check the parameters */ PRECONDITION (Type <= CD_TYPE_MAX && Import != 0); /* Setting the import twice is bad */ CHECK (ConDes[Type].Import.Name == INVALID_STRING_ID); /* Set the import and its position */ ConDes[Type].Import = *Import; } void ConDesSetLabel (unsigned Type, unsigned Name) /* Set the label for the given ConDes type */ { /* Check the parameters */ PRECONDITION (Type <= CD_TYPE_MAX && Name != 0); /* Setting the label twice is bad */ CHECK (ConDes[Type].Label == INVALID_STRING_ID); /* Set the name */ ConDes[Type].Label = Name; } void ConDesSetCountSym (unsigned Type, unsigned Name) /* Set the name for the given ConDes count symbol */ { /* Check the parameters */ PRECONDITION (Type <= CD_TYPE_MAX && Name != 0); /* Setting the symbol twice is bad */ CHECK (ConDes[Type].CountSym == INVALID_STRING_ID); /* Set the name */ ConDes[Type].CountSym = Name; } void ConDesSetOrder (unsigned Type, ConDesOrder Order) /* Set the sorting oder for the given ConDes table */ { /* Check the parameters */ PRECONDITION (Type <= CD_TYPE_MAX); /* Set the order */ ConDes[Type].Order = Order; } int ConDesHasSegName (unsigned Type) /* Return true if a segment name is already defined for this ConDes type */ { /* Check the parameters */ PRECONDITION (Type <= CD_TYPE_MAX); return (ConDes[Type].SegName != INVALID_STRING_ID); } int ConDesHasLabel (unsigned Type) /* Return true if a label is already defined for this ConDes type */ { /* Check the parameters */ PRECONDITION (Type <= CD_TYPE_MAX); return (ConDes[Type].Label != INVALID_STRING_ID); } void ConDesCreate (void) /* Create the condes tables if requested */ { unsigned Type; /* Walk over the descriptor array and create a table for each entry */ for (Type = 0; Type < CD_TYPE_COUNT; ++Type) { ConDesCreateOne (ConDes + Type); } } void ConDesDump (void) /* Dump ConDes data to stdout for debugging */ { unsigned Type; for (Type = 0; Type < CD_TYPE_COUNT; ++Type) { Collection* ExpList = &ConDes[Type].ExpList; printf ("CONDES(%u): %u symbols\n", Type, CollCount (ExpList)); } }
999
./cc65/src/ld65/dbgsyms.c
/*****************************************************************************/ /* */ /* dbgsyms.c */ /* */ /* Debug symbol handling for the ld65 linker */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "addrsize.h" #include "attrib.h" #include "check.h" #include "hlldbgsym.h" #include "symdefs.h" #include "xmalloc.h" /* ld65 */ #include "dbgsyms.h" #include "error.h" #include "exports.h" #include "expr.h" #include "fileio.h" #include "global.h" #include "lineinfo.h" #include "objdata.h" #include "spool.h" #include "tpool.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Definition of the debug symbol structure */ struct DbgSym { unsigned Id; /* Id of debug symbol */ DbgSym* Next; /* Pool linear list link */ ObjData* Obj; /* Object file that exports the name */ Collection DefLines; /* Line infos for definition */ Collection RefLines; /* Line infos for references */ ExprNode* Expr; /* Expression (0 if not def'd) */ unsigned Size; /* Symbol size if any */ unsigned OwnerId; /* Id of parent/owner */ unsigned ImportId; /* Id of import if this is one */ unsigned Name; /* Name */ unsigned short Type; /* Type of symbol */ unsigned short AddrSize; /* Address size of symbol */ }; /* Structure used for a high level language function or symbol */ typedef struct HLLDbgSym HLLDbgSym; struct HLLDbgSym { unsigned Flags; /* See above */ unsigned Name; /* String id of name */ DbgSym* Sym; /* Assembler symbol */ int Offs; /* Offset if any */ unsigned Type; /* String id of type */ unsigned ScopeId; /* Parent scope */ }; /* We will collect all debug symbols in the following array and remove * duplicates before outputing them into a label file. */ static DbgSym* DbgSymPool[256]; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static DbgSym* NewDbgSym (unsigned Id, unsigned Type, unsigned char AddrSize, ObjData* O) /* Create a new DbgSym and return it */ { /* Allocate memory */ DbgSym* D = xmalloc (sizeof (DbgSym)); /* Initialize the fields */ D->Id = Id; D->Next = 0; D->Obj = O; D->DefLines = EmptyCollection; D->RefLines = EmptyCollection; D->Expr = 0; D->Size = 0; D->OwnerId = ~0U; D->ImportId = ~0U; D->Name = 0; D->Type = Type; D->AddrSize = AddrSize; /* Return the new entry */ return D; } static HLLDbgSym* NewHLLDbgSym (void) /* Create a new HLLDbgSym and return it */ { /* Allocate memory and return it */ return xmalloc (sizeof (HLLDbgSym)); } static DbgSym* GetDbgSym (DbgSym* D, long Val) /* Check if we find the same debug symbol in the table. If we find it, return * a pointer to the other occurrence, if we didn't find it, return NULL. */ { /* Create the hash. We hash over the symbol value */ unsigned Hash = ((Val >> 24) & 0xFF) ^ ((Val >> 16) & 0xFF) ^ ((Val >> 8) & 0xFF) ^ ((Val >> 0) & 0xFF); /* Check for this symbol */ DbgSym* Sym = DbgSymPool[Hash]; while (Sym) { /* Is this symbol identical? */ if (Sym->Name == D->Name && EqualExpr (Sym->Expr, D->Expr)) { /* Found */ return Sym; } /* Next symbol */ Sym = Sym->Next; } /* This is the first symbol of it's kind */ return 0; } static void InsertDbgSym (DbgSym* D, long Val) /* Insert the symbol into the hashed symbol pool */ { /* Create the hash. We hash over the symbol value */ unsigned Hash = ((Val >> 24) & 0xFF) ^ ((Val >> 16) & 0xFF) ^ ((Val >> 8) & 0xFF) ^ ((Val >> 0) & 0xFF); /* Insert the symbol */ D->Next = DbgSymPool [Hash]; DbgSymPool [Hash] = D; } DbgSym* ReadDbgSym (FILE* F, ObjData* O, unsigned Id) /* Read a debug symbol from a file, insert and return it */ { /* Read the type and address size */ unsigned Type = ReadVar (F); unsigned char AddrSize = Read8 (F); /* Create a new debug symbol */ DbgSym* D = NewDbgSym (Id, Type, AddrSize, O); /* Read the id of the owner scope/symbol */ D->OwnerId = ReadVar (F); /* Read and assign the name */ D->Name = MakeGlobalStringId (O, ReadVar (F)); /* Read the value */ if (SYM_IS_EXPR (D->Type)) { D->Expr = ReadExpr (F, O); } else { D->Expr = LiteralExpr (Read32 (F), O); } /* Read the size */ if (SYM_HAS_SIZE (D->Type)) { D->Size = ReadVar (F); } /* If this is an import, the file contains its id */ if (SYM_IS_IMPORT (D->Type)) { D->ImportId = ReadVar (F); } /* If its an exports, there's also the export id, but we don't remember * it but use it to let the export point back to us. */ if (SYM_IS_EXPORT (D->Type)) { /* Get the export from the export id, then set the our id */ GetObjExport (O, ReadVar (F))->DbgSymId = Id; } /* Last is the list of line infos for this symbol */ ReadLineInfoList (F, O, &D->DefLines); ReadLineInfoList (F, O, &D->RefLines); /* Return the new DbgSym */ return D; } HLLDbgSym* ReadHLLDbgSym (FILE* F, ObjData* O, unsigned Id attribute ((unused))) /* Read a hll debug symbol from a file, insert and return it */ { unsigned SC; /* Create a new HLLDbgSym */ HLLDbgSym* S = NewHLLDbgSym (); /* Read the data */ S->Flags = ReadVar (F); SC = HLL_GET_SC (S->Flags); S->Name = MakeGlobalStringId (O, ReadVar (F)); if (HLL_HAS_SYM (S->Flags)) { S->Sym = GetObjDbgSym (O, ReadVar (F)); } else { /* Auto variables aren't attached to asm symbols */ S->Sym = 0; } if (SC == HLL_SC_AUTO || SC == HLL_SC_REG) { S->Offs = ReadVar (F); } else { S->Offs = 0; } S->Type = GetTypeId (GetObjString (O, ReadVar (F))); S->ScopeId = ReadVar (F); /* Return the (now initialized) hll debug symbol */ return S; } static void ClearDbgSymTable (void) /* Clear the debug symbol table */ { unsigned I; for (I = 0; I < sizeof (DbgSymPool) / sizeof (DbgSymPool[0]); ++I) { DbgSym* Sym = DbgSymPool[I]; DbgSymPool[I] = 0; while (Sym) { DbgSym* NextSym = Sym->Next; Sym->Next = 0; Sym = NextSym; } } } static long GetDbgSymVal (const DbgSym* D) /* Get the value of this symbol */ { CHECK (D->Expr != 0); return GetExprVal (D->Expr); } static void PrintLineInfo (FILE* F, const Collection* LineInfos, const char* Format) /* Output an attribute with line infos */ { if (CollCount (LineInfos) > 0) { unsigned I; const LineInfo* LI = CollConstAt (LineInfos, 0); fprintf (F, Format, LI->Id); for (I = 1; I < CollCount (LineInfos); ++I) { LI = CollConstAt (LineInfos, I); fprintf (F, "+%u", LI->Id); } } } unsigned DbgSymCount (void) /* Return the total number of debug symbols */ { /* Walk over all object files */ unsigned I; unsigned Count = 0; for (I = 0; I < CollCount (&ObjDataList); ++I) { /* Get this object file */ const ObjData* O = CollAtUnchecked (&ObjDataList, I); /* Count debug symbols */ Count += CollCount (&O->DbgSyms); } return Count; } unsigned HLLDbgSymCount (void) /* Return the total number of high level language debug symbols */ { /* Walk over all object files */ unsigned I; unsigned Count = 0; for (I = 0; I < CollCount (&ObjDataList); ++I) { /* Get this object file */ const ObjData* O = CollAtUnchecked (&ObjDataList, I); /* Count debug symbols */ Count += CollCount (&O->HLLDbgSyms); } return Count; } void PrintDbgSyms (FILE* F) /* Print the debug symbols in a debug file */ { unsigned I, J; for (I = 0; I < CollCount (&ObjDataList); ++I) { /* Get the object file */ ObjData* O = CollAtUnchecked (&ObjDataList, I); /* Walk through all debug symbols in this module */ for (J = 0; J < CollCount (&O->DbgSyms); ++J) { /* Get the next debug symbol */ const DbgSym* S = CollConstAt (&O->DbgSyms, J); /* Emit the base data for the entry */ fprintf (F, "sym\tid=%u,name=\"%s\",addrsize=%s", O->SymBaseId + J, GetString (S->Name), AddrSizeToStr ((unsigned char) S->AddrSize)); /* Emit the size only if we know it */ if (S->Size != 0) { fprintf (F, ",size=%u", S->Size); } /* For cheap local symbols, add the owner symbol, for others, * add the owner scope. */ if (SYM_IS_STD (S->Type)) { fprintf (F, ",scope=%u", O->ScopeBaseId + S->OwnerId); } else { fprintf (F, ",parent=%u", O->SymBaseId + S->OwnerId); } /* Output line infos */ PrintLineInfo (F, &S->DefLines, ",def=%u"); PrintLineInfo (F, &S->RefLines, ",ref=%u"); /* If this is an import, output the id of the matching export. * If this is not an import, output its value and - if we have * it - the segment. */ if (SYM_IS_IMPORT (S->Type)) { /* Get the import */ const Import* Imp = GetObjImport (O, S->ImportId); /* Get the export from the import */ const Export* Exp = Imp->Exp; /* Output the type */ fputs (",type=imp", F); /* If this is not a linker generated symbol, and the module * that contains the export has debug info, output the debug * symbol id for the export */ if (Exp->Obj && OBJ_HAS_DBGINFO (Exp->Obj->Header.Flags)) { fprintf (F, ",exp=%u", Exp->Obj->SymBaseId + Exp->DbgSymId); } } else { SegExprDesc D; /* Get the symbol value */ long Val = GetDbgSymVal (S); /* Output it */ fprintf (F, ",val=0x%lX", Val); /* Check for a segmented expression and add the segment id to * the debug info if we have one. */ GetSegExprVal (S->Expr, &D); if (!D.TooComplex && D.Seg != 0) { fprintf (F, ",seg=%u", D.Seg->Id); } /* Output the type */ fprintf (F, ",type=%s", SYM_IS_LABEL (S->Type)? "lab" : "equ"); } /* Terminate the output line */ fputc ('\n', F); } } } void PrintHLLDbgSyms (FILE* F) /* Print the high level language debug symbols in a debug file */ { unsigned I, J; for (I = 0; I < CollCount (&ObjDataList); ++I) { /* Get the object file */ ObjData* O = CollAtUnchecked (&ObjDataList, I); /* Walk through all hll debug symbols in this module */ for (J = 0; J < CollCount (&O->HLLDbgSyms); ++J) { /* Get the next debug symbol */ const HLLDbgSym* S = CollConstAt (&O->HLLDbgSyms, J); /* Get the storage class */ unsigned SC = HLL_GET_SC (S->Flags); /* Output the base info */ fprintf (F, "csym\tid=%u,name=\"%s\",scope=%u,type=%u,sc=", O->HLLSymBaseId + J, GetString (S->Name), O->ScopeBaseId + S->ScopeId, S->Type); switch (SC) { case HLL_SC_AUTO: fputs ("auto", F); break; case HLL_SC_REG: fputs ("reg", F); break; case HLL_SC_STATIC: fputs ("static", F); break; case HLL_SC_EXTERN: fputs ("ext", F); break; default: Error ("Invalid storage class %u for hll symbol", SC); break; } /* Output the offset if it is not zero */ if (S->Offs) { fprintf (F, ",offs=%d", S->Offs); } /* For non auto symbols output the debug symbol id of the asm sym */ if (HLL_HAS_SYM (S->Flags)) { fprintf (F, ",sym=%u", O->SymBaseId + S->Sym->Id); } /* Terminate the output line */ fputc ('\n', F); } } } void PrintDbgSymLabels (FILE* F) /* Print the debug symbols in a VICE label file */ { unsigned I, J; /* Clear the symbol table */ ClearDbgSymTable (); /* Create labels from all modules we have linked into the output file */ for (I = 0; I < CollCount (&ObjDataList); ++I) { /* Get the object file */ ObjData* O = CollAtUnchecked (&ObjDataList, I); /* Walk through all debug symbols in this module */ for (J = 0; J < CollCount (&O->DbgSyms); ++J) { long Val; /* Get the next debug symbol */ DbgSym* D = CollAt (&O->DbgSyms, J); /* Emit this symbol only if it is a label (ignore equates and imports) */ if (SYM_IS_EQUATE (D->Type) || SYM_IS_IMPORT (D->Type)) { continue; } /* Get the symbol value */ Val = GetDbgSymVal (D); /* Lookup this symbol in the table. If it is found in the table, it was * already written to the file, so don't emit it twice. If it is not in * the table, insert and output it. */ if (GetDbgSym (D, Val) == 0) { /* Emit the VICE label line */ fprintf (F, "al %06lX .%s\n", Val, GetString (D->Name)); /* Insert the symbol into the table */ InsertDbgSym (D, Val); } } } }
1,000
./cc65/src/ld65/tpool.c
/*****************************************************************************/ /* */ /* tpool.c */ /* */ /* Pool for generic types */ /* */ /* */ /* */ /* (C) 2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "gentype.h" /* ld65 */ #include "tpool.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* The string pool we're using */ StringPool* TypePool = 0; /*****************************************************************************/ /* Code */ /*****************************************************************************/ void PrintDbgTypes (FILE* F) /* Output the types to a debug info file */ { StrBuf Type = STATIC_STRBUF_INITIALIZER; /* Get the number of strings in the type pool */ unsigned Count = SP_GetCount (TypePool); /* Output all of them */ unsigned Id; for (Id = 0; Id < Count; ++Id) { /* Output it */ fprintf (F, "type\tid=%u,val=\"%s\"\n", Id, GT_AsString (SP_Get (TypePool, Id), &Type)); } /* Free the memory for the temporary string */ SB_Done (&Type); } void InitTypePool (void) /* Initialize the type pool */ { /* Allocate a type pool */ TypePool = NewStringPool (137); }