diff --git a/README.md b/README.md index 5b4465e..d9c8c77 100644 --- a/README.md +++ b/README.md @@ -1 +1,12 @@ -# x65 6502 Macro Assembler in a single c++ file using the struse single file text parsing library. Supports most syntaxes. x65 was recently named Asm6502 but was renamed because Asm6502 is too generic, x65 has no particular meaning. Every assembler seems to add or change its own quirks to the 6502 syntax. This implementation aims to support all of them at once as long as there is no contradiction. To keep up with this trend x65 is adding the following features to the mix: * Full expression evaluation everywhere values are used: [Expressions](#expressions) * Basic relative sections and linking. * C style scoping within '{' and '}': [Scopes](#scopes) * Reassignment of labels. This means there is no error if you declare the same label twice, but on the other hand you can do things like label = label + 2. * [Local labels](#labels) can be defined in a number of ways, such as leading period (.label) or leading at-sign (@label) or terminating dollar sign (label$). * [Directives](#directives) support both with and without leading period. * Labels don't need to end with colon, but they can. * No indentation required for instructions, meaning that labels can't be mnemonics, macros or directives. * Conditional assembly with #if/#ifdef/#else etc. * As far as achievable, support the syntax of other 6502 assemblers (Merlin syntax now requires command line argument). In summary, if you are familiar with any 6502 assembler syntax you should feel at home with x65. If you're familiar with C programming expressions you should be familiar with '{', '}' scoping and complex expressions. There are no hard limits on binary size so if the address exceeds $ffff it will just wrap around to $0000. I'm not sure about the best way to handle that or if it really is a problem. There is a sublime package for coding/building in Sublime Text 3 in the *sublime* subfolder. ## Prerequisite x65.cpp requires struse.h which is a single file text parsing library that can be retrieved from https://github.com/Sakrac/struse. ### References * [6502 opcodes](http://www.6502.org/tutorials/6502opcodes.html) * [6502 opcode grid](http://www.llx.com/~nparker/a2/opcodes.html) * [Codebase64 CPU section](http://codebase64.org/doku.php?id=base:6502_6510_coding) ## Features * **Code** * **Comments** * **Labels** * **Directives** * **Macros** * **Expressions** ### Code Code is any valid mnemonic/opcode and addressing mode. At the moment only one opcode per line is assembled. ### Comments Comments are currently line based and both ';' and '//' are accepted as delimiters. ### Expressions Anywhere a number can be entered it can also be interpreted as a full expression, for example: ``` Get123: bytes Get1-*, Get2-*, Get3-* Get1: lda #1 rts Get2: lda #2 rts Get3: lda #3 rts ``` Would yield 3 bytes where the address of a label can be calculated by taking the address of the byte plus the value of the byte. ### Labels Labels come in two flavors: **Addresses** (PC based) or **Values** (Evaluated from an expression). An address label is simply placed somewhere in code and a value label is follwed by '**=**' and an expression. All labels are rewritable so it is fine to do things like NumInstance = NumInstance+1. Value assignments can be prefixed with '.const' or '.label' but is not required to be prefixed by anything. *Local labels* exist inbetween *global labels* and gets discarded whenever a new global label is added. The syntax for local labels are one of: prefix with period, at-sign, exclamation mark or suffix with $, as in: **.local** or **!local** or **@local** or **local$**. Both value labels and address labels can be local labels. ``` Function: ; global label ldx #32 .local_label ; local label dex bpl .local_label rts Next_Function: ; next global label, the local label above is now erased. rts ``` ### Directives Directives are assembler commands that control the code generation but that does not generate code by itself. Some assemblers prefix directives with a period (.org instead of org) so a leading period is accepted but not required for directives. * [**ORG**](#org) (same as **PC**): Set the current compiling address. * [**LOAD**](#load) Set the load address for binary formats that support it. * [**SECTION**](#section) Start a relative section * [**LINK**](#link) Link a relative section at this address * [**XDEF**](#xdef) Make a label available globally * [**INCOBJ**](#incobj) Include an object file (.o65) to this file * [**ALIGN**](#align) Align the address to a multiple by filling with 0s * [**MACRO**](#macro) Declare a macro * [**EVAL**](#eval) Log an expression during assembly. * [**BYTES**](#bytes) Insert comma separated bytes at this address (same as **BYTE** or **DC.B**) * [**WORDS**](#words) Insert comma separated 16 bit values at this address (same as **WORD** or **DC.W**) * [**TEXT**](#text) Insert text at this address * [**INCLUDE**](#include) Include another source file and assemble at this address * [**INCBIN**](#incbin) Include a binary file at this address * [**CONST**](#const) Assign a value to a label and make it constant (error if reassigned with other value) * [**LABEL**](#label) Decorative directive to assign an expression to a label * [**INCSYM**](#incsym) Include a symbol file with an optional set of wanted symbols. * [**POOL**](#pool) Add a label pool for temporary address labels * [**#IF / #ELSE / #IFDEF / #ELIF / #ENDIF**](#conditional) Conditional assembly * [**STRUCT**](#struct) Hierarchical data structures (dot separated sub structures) * [**REPT**](#rept) Repeat a scoped block of code a number of times. * [**INCDIR**](#incdir) Add a directory to look for binary and text include files in. * [**MERLIN**](#merlin) A variety of directives and label rules to support Merlin assembler sources **ORG** ``` org $2000 (or pc $2000) ``` Sets the current assembler address to this address **SECTION** ``` section Code Start: lda #Data sta $ff rts section BSS Data: byte 1,2,3,4 ``` Starts a relative section. Relative sections require a name and sections that share the same name will be linked sequentially. The labels will be evaluated at link time. **XDEF** Used in files assembled to object files to share a label globally. All labels that are not xdef'd are still processed but protected so that other objects can use the same label name without colliding. **XDEF ** must be specified before the label is defined, such as at the top of the file. **INCOBJ** Include an object file for linking into this file. **LINK** Link a set of relative sections (sharing the same name) at this address The following lines will place all sections named Code sequentially at location $1000, followed by all sections named BSS: ``` org $1000 link Code link BSS ``` There is currently object file support (use -obj argument to generate), currently doing a lot of testing to make sure it works as expected. At this time all labels from object files are globally visible causing potential confusion if two files share the same name labels and XDEF is intended to mark labels as global to protect file scope labels. **LOAD** ``` load $2000 ``` For c64 .prg files this prefixes the binary file with this address. **ALIGN** ``` align $100 ``` Add bytes of 0 up to the next address divisible by the alignment **MACRO** See the 'Macro' section below **EVAL** Example: ``` eval Current PC: * ``` Might yield the following in stdout: ``` Eval (15): Current PC : "*" = $2010 ``` When eval is encountered on a line print out "EVAL (\) \: \ = \" to stdout. This can be useful to see the size of things or debugging expressions. **BYTES** Adds the comma separated values on the current line to the assembled output, for example ``` RandomBytes: bytes NumRandomBytes { bytes 13,1,7,19,32 NumRandomBytes = * - ! } ``` **byte** or **dc.b** are also recognized. **WORDS** Adds comma separated 16 bit values similar to how **BYTES** work. **word** or **dc.w** are also recognized. **TEXT** Copies the string in quotes on the same line. The plan is to do a petscii conversion step. Use the modifier 'petscii' or 'petscii_shifted' to convert alphabetic characters to range. Example: ``` text petscii_shifted "This might work" ``` **INCLUDE** Include another source file. This should also work with .sym files to import labels from another build. The plan is for x65 to export .sym files as well. Example: ``` include "wizfx.s" ``` **INCBIN** Include binary data from a file, this inserts the binary data at the current address. Example: ``` incbin "wizfx.gfx" ``` **CONST** Prefix a label assignment with 'const' or '.const' to cause an error if the label gets reassigned. ``` const zpData = $fe ``` **LABEL** Decorative directive to assign an expression to a label, label assignments are followed by '=' and an expression. These two assignments do the same thing (with different values): ``` label zpDest = $fc zpDest = $fa ``` **INCSYM** Include a symbol file with an optional set of wanted symbols. Open a symbol file and extract a set of symbols, or all symbols if no set was specified. Local labels will be discarded if possible. ``` incsym Part1_Init, Part1_Update, Part1_Exit "part1.sym" ``` **POOL** Add a label pool for temporary address labels. This is similar to how stack frame variables are assigned in C. A label pool is a mini stack of addresses that can be assigned as temporary labels with a scope ('{' and '}'). This can be handy for large functions trying to minimize use of zero page addresses, the function can declare a range (or set of ranges) of available zero page addresses and labels can be assigned within a scope and be deleted on scope closure. The format of a label pool is: "pool start-end, start-end" and labels can then be allocated from that range by ' **STRUCT** Hierarchical data structures (dot separated sub structures) Structs helps define complex data types, there are two basic types to define struct members, and as long as a struct is declared it can be used as a member type of another struct. The result of a struct is that each member is an offset from the start of the data block in memory. Each substruct is referenced by separating the struct names with dots. Example: ``` struct MyStruct { byte count word pointer } struct TwoThings { MyStruct thing_one MyStruct thing_two } struct Mixed { word banana TwoThings things } Eval Mixed.things Eval Mixed.things.thing_two Eval Mixed.things.thing_two.pointer Eval Mixed.things.thing_one.count ``` results in the output: ``` EVAL(16): "Mixed.things" = $2 EVAL(27): "Mixed.things.thing_two" = $5 EVAL(28): "Mixed.things.thing_two.pointer" = $6 EVAL(29): "Mixed.things.thing_one.count" = $2 ``` **REPT** Repeat a scoped block of code a number of times. The syntax is rept \ { \ }. Example: ``` columns = 40 rows = 25 screen_col = $400 height_buf = $1000 rept columns { screen_addr = screen_col ldx height_buf dest = screen_addr remainder = 3 rept (rows+remainder)/4 { stx dest dest = dest + 4*40 } rept 3 { inx remainder = remainder-1 screen_addr = screen_addr + 40 dest = screen_addr rept (rows+remainder)/4 { stx dest dest = dest + 4*40 } } screen_col = screen_col+1 height_buf = height_buf+1 } ``` **INCDIR** Adds a folder to search for INCLUDE, INCBIN, etc. files in ###**MERLIN** A variety of directives and label rules to support Merlin assembler sources. Merlin syntax is supported in x65 since there is historic relevance and readily available publicly release source. * [Pinball Construction Set source](https://github.com/billbudge/PCS_AppleII) (Bill Budge) * [Prince of Persia source](https://github.com/jmechner/Prince-of-Persia-Apple-II) (Jordan Mechner) To enable Merlin 8.16 syntax use the '-merlin' command line argument. Where it causes no harm, Merlin directives are supported for non-merlin mode. *LABELS* ]label means mutable address label, also does not seem to invalidate local labels. :label is perfectly valid, currently treating as a local variable labels can include '?' Merlin labels are not allowed to include '.' as period means logical or in merlin, which also means that enums and structs are not supported when assembling with merlin syntax. *Expressions* Merlin may not process expressions (probably left to right, parenthesis not allowed) the same as x65 but given that it wouldn't be intuitive to read the code that way, there are probably very few cases where this would be an issue. **EJECT** An old assembler directive that does not affect the assembler but if printed would insert a page break at that point. **DS** Define section, followed by a number of bytes. If number is positive insert this amount of 0 bytes, if negative, reduce the current PC. **DUM**, **DEND** Dummy section, this will not write any opcodes or data to the binary output but all code and data will increment the PC addres up to the point of DEND. **PUT** A variation of **INCLUDE** that applies an oddball set of filename rules. These rules apply to **INCLUDE** as well just in case they make sense. **USR** In Merlin USR calls a function at a fixed address in memory, x65 safely avoids this. If there is a requirement for a user defined macro you've got the source code to do it in. ## Command Line Options Typical command line: ``` x65 [-DLabel] [-iIncDir] [-sym dest.sym] [-vice dest.vs] [-obj]/[-c64]/[-bin]/[-a2b] [-merlin] ``` **Usage** x65 [options] filename.s code.prg * -i\: Add include path (multiple allowed) * -D\[=\]: Define a label with an optional value (otherwise 1, multiple allowed) * -obj: x65 object file that can be loaded using INCOBJ and linked using LINK
* -bin: Raw binary * -c64: Include load address * -a2b: Apple II Dos 3.3 Binary Executable * -sym \: vice/kick asm symbol file * -vice \: export a vice symbol file * -merlin: Assembler syntax for Apple II Merlin 8.16 ## Expression syntax Expressions contain values, such as labels or raw numbers and operators including +, -, \*, /, & (and), | (or), ^ (eor), << (shift left), >> (shift right) similar to how expressions work in C. Parenthesis are supported for managing order of operations where C style precedence needs to be overrided. In addition there are some special characters supported: * \*: Current address (PC). This conflicts with the use of \* as multiply so multiply will be interpreted only after a value or right parenthesis * <: If less than is not follwed by another '<' in an expression this evaluates to the low byte of a value (and $ff) * >: If greater than is not followed by another '>' in an expression this evaluates to the high byte of a value (>>8) * !: Start of scope (use like an address label in expression) * %: First address after scope (use like an address label in expression) * $: Preceeds hexadecimal value * %: If immediately followed by '0' or '1' this is a binary value and not scope closure address Example: ``` lda #(((>SCREEN_MATRIX)&$3c)*4)+8 sta $d018 ``` ## Macros A macro can be defined by the using the directive macro and includes the line within the following scope: Example: ``` macro ShiftLeftA(Source) { rol Source rol A } ``` The macro will be instantiated anytime the macro name is encountered: ``` lda #0 ShiftLeftA($a0) ``` The parameter field is optional for both the macro declaration and instantiation, if there is a parameter in the declaration but not in the instantiation the parameter will be removed from the macro. If there are no parameters in the declaration the parenthesis can be omitted and will be slightly more efficient to assemble, as in: ``` .macro GetBit { asl bne % jsr GetByte } ``` Currently macros with parameters use search and replace without checking if the parameter is a whole word, the plan is to fix this. ## Scopes Scopes are lines inbetween '{' and '}' including macros. The purpose of scopes is to reduce the need for local labels and the scopes nest just like C code to support function level and loops and inner loop scoping. '!' is a label that is the first address of the scope and '%' the first address after the scope. This means you can write ``` { lda #0 ldx #8 { sta Label,x dex bpl ! } } ``` to construct a loop without adding a label. ##Examples Using scoping to avoid local labels ``` ; set zpTextPtr to a memory location with text ; return: y is the offset to the first space. ; (y==0 means either first is space or not found.) FindFirstSpace ldy #0 { lda (zpTextPtr),y cmp #$20 beq % ; found, exit iny bne ! ; not found, keep searching } rts ``` ### Development Status Currently the assembler is in an early revision and while features are tested individually it is fairly certain that untested combinations of features will indicate flaws and certain features are not in a complete state. **TODO** * Split object file non-xdef labels to keep from all labels being global (xdef) * Export full memory of fixed sections instead of a single section * Macro parameters should replace only whole words instead of any substring * Add 'import' directive as a catch-all include/incbin/etc. alternative * irp (indefinite repeat) **FIXED** * Object file format so sections can be saved for later linking * Added relative sections and relocatable references * Added Apple II Dos 3.3 Binary Executable output (-a2b) * Added more Merlin rules * Added directives from older assemblers * Added ENUM, sharing some functionality with STRUCT * Added INCDIR and command line options * [REPT](#rept) * fixed a flaw in expressions that ignored the next operator after raw hex values if no whitespace * expressions now handles high byte/low byte (\>, \<) as RPN tokens and not special cased. * structs * ifdef / if / elif / else / endif conditional code generation directives * Label Pools added * Bracket scoping closure ('}') cleans up local variables within that scope (better handling of local variables within macros). * Context stack cleanup * % in expressions is interpreted as binary value if immediately followed by 0 or 1 * Add a const directive for labels that shouldn't be allowed to change (currently ignoring const) * TEXT directive converts ascii to petscii (respect uppercase or lowercase petscii) (simplistic) Revisions: * 2015-10-16 XDEF and file protected symbols added for better recursive object file assembling * 2015-10-15 Object file reading, additional bugs debugged. * 2015-10-10 Relative Sections and Link support, adding -merlin command line to clean up code * 2015-10-06 Added ENUM and MERLIN / LISA assembler directives (EJECT, DUM, DEND, DS, DB, DFB, DDB, IF, ENDIF, etc.) * 2015-10-05 Added INCDIR, some command line options (-D, -i, -vice) * 2015-10-04 Added [REPT](#rept) directive * 2015-10-04 Added [STRUCT](#struct) directive, sorted functions by grouping a bit more, bug fixes * 2015-10-02 Cleanup hid an error (#else without #if), exit with nonzero if error was encountered * 2015-10-02 General cleanup, wrapping [conditional assembly](#conditional) in functions * 2015-10-01 Added [Label Pools](#pool) and conditional assembly * 2015-09-29 Moved Asm6502 out of Struse Samples. * 2015-09-28 First commit \ No newline at end of file +# x65 6502 Macro Assembler in a single c++ file using the struse single file text parsing library. Supports most syntaxes. x65 was recently named Asm6502 but was renamed because Asm6502 is too generic, x65 has no particular meaning. Every assembler seems to add or change its own quirks to the 6502 syntax. This implementation aims to support all of them at once as long as there is no contradiction. To keep up with this trend x65 is adding the following features to the mix: * Full expression evaluation everywhere values are used: [Expressions](#expressions) * Basic relative sections and linking. * C style scoping within '{' and '}': [Scopes](#scopes) * Reassignment of labels. This means there is no error if you declare the same label twice, but on the other hand you can do things like label = label + 2. * [Local labels](#labels) can be defined in a number of ways, such as leading period (.label) or leading at-sign (@label) or terminating dollar sign (label$). * [Directives](#directives) support both with and without leading period. * Labels don't need to end with colon, but they can. * No indentation required for instructions, meaning that labels can't be mnemonics, macros or directives. * Conditional assembly with #if/#ifdef/#else etc. * As far as achievable, support the syntax of other 6502 assemblers (Merlin syntax now requires command line argument). In summary, if you are familiar with any 6502 assembler syntax you should feel at home with x65. If you're familiar with C programming expressions you should be familiar with '{', '}' scoping and complex expressions. There are no hard limits on binary size so if the address exceeds $ffff it will just wrap around to $0000. I'm not sure about the best way to handle that or if it really is a problem. There is a sublime package for coding/building in Sublime Text 3 in the *sublime* subfolder. ## Prerequisite x65.cpp requires struse.h which is a single file text parsing library that can be retrieved from https://github.com/Sakrac/struse. ### References * [6502 opcodes](http://www.6502.org/tutorials/6502opcodes.html) * [6502 opcode grid](http://www.llx.com/~nparker/a2/opcodes.html) * [Codebase64 CPU section](http://codebase64.org/doku.php?id=base:6502_6510_coding) ## Command Line Options The command line options specifies the source file, the destination file and what type of file to generate, such as c64 or apple II dos 3.3 or binary or an x65 specific object file. You can also generate a disassembly listing with inline source code or dump the available set of opcodes as a source file. The command line can also set labels for conditional assembly to allow for distinguishing debug builds from shippable builds. Typical command line ([*] = optional): ``` x65 [-DLabel] [-iIncDir] (source.s) (dest.prg) [-lst[=file.lst]] [-opcodes[=file.s]] [-sym dest.sym] [-vice dest.vs] [-obj]/[-c64]/[-bin]/[-a2b] [-merlin] ``` **Usage** x65 filename.s code.prg [options] +* -i(path): Add include path +* -D(label)[=]: Define a label with an optional value (otherwise defined as 1) +* -obj (file.o65): generate object file for later linking +* -bin: Raw binary +* -c64: Include load address (default) +* -a2b: Apple II Dos 3.3 Binary +* -sym (file.sym): symbol file +* -lst / -lst=(file.lst): generate disassembly text from result (file or stdout) +* -opcodes / -opcodes=(file.s): dump all available opcodes (file or stdout) +* -vice (file.vs): export a vice symbol file + ## Features * **Code** * **Comments** * **Labels** * **Directives** * **Macros** * **Expressions** ### Code Code is any valid mnemonic/opcode and addressing mode. At the moment only one opcode per line is assembled. ### Comments Comments are currently line based and both ';' and '//' are accepted as delimiters. ### Expressions Anywhere a number can be entered it can also be interpreted as a full expression, for example: ``` Get123: bytes Get1-*, Get2-*, Get3-* Get1: lda #1 rts Get2: lda #2 rts Get3: lda #3 rts ``` Would yield 3 bytes where the address of a label can be calculated by taking the address of the byte plus the value of the byte. ### Labels Labels come in two flavors: **Addresses** (PC based) or **Values** (Evaluated from an expression). An address label is simply placed somewhere in code and a value label is follwed by '**=**' and an expression. All labels are rewritable so it is fine to do things like NumInstance = NumInstance+1. Value assignments can be prefixed with '.const' or '.label' but is not required to be prefixed by anything. *Local labels* exist inbetween *global labels* and gets discarded whenever a new global label is added. The syntax for local labels are one of: prefix with period, at-sign, exclamation mark or suffix with $, as in: **.local** or **!local** or **@local** or **local$**. Both value labels and address labels can be local labels. ``` Function: ; global label ldx #32 .local_label ; local label dex bpl .local_label rts Next_Function: ; next global label, the local label above is now erased. rts ``` ### Directives Directives are assembler commands that control the code generation but that does not generate code by itself. Some assemblers prefix directives with a period (.org instead of org) so a leading period is accepted but not required for directives. * [**ORG**](#org) (same as **PC**): Set the current compiling address. * [**LOAD**](#load) Set the load address for binary formats that support it. * [**SECTION**](#section) Start a relative section * [**LINK**](#link) Link a relative section at this address * [**XDEF**](#xdef) Make a label available globally * [**INCOBJ**](#incobj) Include an object file (.o65) to this file * [**ALIGN**](#align) Align the address to a multiple by filling with 0s * [**MACRO**](#macro) Declare a macro * [**EVAL**](#eval) Log an expression during assembly. * [**BYTES**](#bytes) Insert comma separated bytes at this address (same as **BYTE** or **DC.B**) * [**WORDS**](#words) Insert comma separated 16 bit values at this address (same as **WORD** or **DC.W**) * [**TEXT**](#text) Insert text at this address * [**INCLUDE**](#include) Include another source file and assemble at this address * [**INCBIN**](#incbin) Include a binary file at this address * [**CONST**](#const) Assign a value to a label and make it constant (error if reassigned with other value) * [**LABEL**](#label) Decorative directive to assign an expression to a label * [**INCSYM**](#incsym) Include a symbol file with an optional set of wanted symbols. * [**POOL**](#pool) Add a label pool for temporary address labels * [**#IF / #ELSE / #IFDEF / #ELIF / #ENDIF**](#conditional) Conditional assembly * [**STRUCT**](#struct) Hierarchical data structures (dot separated sub structures) * [**REPT**](#rept) Repeat a scoped block of code a number of times. * [**INCDIR**](#incdir) Add a directory to look for binary and text include files in. * [**MERLIN**](#merlin) A variety of directives and label rules to support Merlin assembler sources **ORG** ``` org $2000 (or pc $2000) ``` Sets the current assembler address to this address **SECTION** ``` section Code Start: lda #Data sta $ff rts section BSS Data: byte 1,2,3,4 ``` Starts a relative section. Relative sections require a name and sections that share the same name will be linked sequentially. The labels will be evaluated at link time. **XDEF** Used in files assembled to object files to share a label globally. All labels that are not xdef'd are still processed but protected so that other objects can use the same label name without colliding. **XDEF ** must be specified before the label is defined, such as at the top of the file. **INCOBJ** Include an object file for linking into this file. **LINK** Link a set of relative sections (sharing the same name) at this address The following lines will place all sections named Code sequentially at location $1000, followed by all sections named BSS: ``` org $1000 link Code link BSS ``` There is currently object file support (use -obj argument to generate), currently doing a lot of testing to make sure it works as expected. At this time all labels from object files are globally visible causing potential confusion if two files share the same name labels and XDEF is intended to mark labels as global to protect file scope labels. **LOAD** ``` load $2000 ``` For c64 .prg files this prefixes the binary file with this address. **ALIGN** ``` align $100 ``` Add bytes of 0 up to the next address divisible by the alignment **MACRO** See the 'Macro' section below **EVAL** Example: ``` eval Current PC: * ``` Might yield the following in stdout: ``` Eval (15): Current PC : "*" = $2010 ``` When eval is encountered on a line print out "EVAL (\) \: \ = \" to stdout. This can be useful to see the size of things or debugging expressions. **BYTES** Adds the comma separated values on the current line to the assembled output, for example ``` RandomBytes: bytes NumRandomBytes { bytes 13,1,7,19,32 NumRandomBytes = * - ! } ``` **byte** or **dc.b** are also recognized. **WORDS** Adds comma separated 16 bit values similar to how **BYTES** work. **word** or **dc.w** are also recognized. **TEXT** Copies the string in quotes on the same line. The plan is to do a petscii conversion step. Use the modifier 'petscii' or 'petscii_shifted' to convert alphabetic characters to range. Example: ``` text petscii_shifted "This might work" ``` **INCLUDE** Include another source file. This should also work with .sym files to import labels from another build. The plan is for x65 to export .sym files as well. Example: ``` include "wizfx.s" ``` **INCBIN** Include binary data from a file, this inserts the binary data at the current address. Example: ``` incbin "wizfx.gfx" ``` **CONST** Prefix a label assignment with 'const' or '.const' to cause an error if the label gets reassigned. ``` const zpData = $fe ``` **LABEL** Decorative directive to assign an expression to a label, label assignments are followed by '=' and an expression. These two assignments do the same thing (with different values): ``` label zpDest = $fc zpDest = $fa ``` **INCSYM** Include a symbol file with an optional set of wanted symbols. Open a symbol file and extract a set of symbols, or all symbols if no set was specified. Local labels will be discarded if possible. ``` incsym Part1_Init, Part1_Update, Part1_Exit "part1.sym" ``` **POOL** Add a label pool for temporary address labels. This is similar to how stack frame variables are assigned in C. A label pool is a mini stack of addresses that can be assigned as temporary labels with a scope ('{' and '}'). This can be handy for large functions trying to minimize use of zero page addresses, the function can declare a range (or set of ranges) of available zero page addresses and labels can be assigned within a scope and be deleted on scope closure. The format of a label pool is: "pool start-end, start-end" and labels can then be allocated from that range by ' **STRUCT** Hierarchical data structures (dot separated sub structures) Structs helps define complex data types, there are two basic types to define struct members, and as long as a struct is declared it can be used as a member type of another struct. The result of a struct is that each member is an offset from the start of the data block in memory. Each substruct is referenced by separating the struct names with dots. Example: ``` struct MyStruct { byte count word pointer } struct TwoThings { MyStruct thing_one MyStruct thing_two } struct Mixed { word banana TwoThings things } Eval Mixed.things Eval Mixed.things.thing_two Eval Mixed.things.thing_two.pointer Eval Mixed.things.thing_one.count ``` results in the output: ``` EVAL(16): "Mixed.things" = $2 EVAL(27): "Mixed.things.thing_two" = $5 EVAL(28): "Mixed.things.thing_two.pointer" = $6 EVAL(29): "Mixed.things.thing_one.count" = $2 ``` **REPT** Repeat a scoped block of code a number of times. The syntax is rept \ { \ }. Example: ``` columns = 40 rows = 25 screen_col = $400 height_buf = $1000 rept columns { screen_addr = screen_col ldx height_buf dest = screen_addr remainder = 3 rept (rows+remainder)/4 { stx dest dest = dest + 4*40 } rept 3 { inx remainder = remainder-1 screen_addr = screen_addr + 40 dest = screen_addr rept (rows+remainder)/4 { stx dest dest = dest + 4*40 } } screen_col = screen_col+1 height_buf = height_buf+1 } ``` **INCDIR** Adds a folder to search for INCLUDE, INCBIN, etc. files in ###**MERLIN** A variety of directives and label rules to support Merlin assembler sources. Merlin syntax is supported in x65 since there is historic relevance and readily available publicly release source. * [Pinball Construction Set source](https://github.com/billbudge/PCS_AppleII) (Bill Budge) * [Prince of Persia source](https://github.com/jmechner/Prince-of-Persia-Apple-II) (Jordan Mechner) To enable Merlin 8.16 syntax use the '-merlin' command line argument. Where it causes no harm, Merlin directives are supported for non-merlin mode. *LABELS* ]label means mutable address label, also does not seem to invalidate local labels. :label is perfectly valid, currently treating as a local variable labels can include '?' Merlin labels are not allowed to include '.' as period means logical or in merlin, which also means that enums and structs are not supported when assembling with merlin syntax. *Expressions* Merlin may not process expressions (probably left to right, parenthesis not allowed) the same as x65 but given that it wouldn't be intuitive to read the code that way, there are probably very few cases where this would be an issue. **EJECT** An old assembler directive that does not affect the assembler but if printed would insert a page break at that point. **DS** Define section, followed by a number of bytes. If number is positive insert this amount of 0 bytes, if negative, reduce the current PC. **DUM**, **DEND** Dummy section, this will not write any opcodes or data to the binary output but all code and data will increment the PC addres up to the point of DEND. **PUT** A variation of **INCLUDE** that applies an oddball set of filename rules. These rules apply to **INCLUDE** as well just in case they make sense. **USR** In Merlin USR calls a function at a fixed address in memory, x65 safely avoids this. If there is a requirement for a user defined macro you've got the source code to do it in. ## Expression syntax Expressions contain values, such as labels or raw numbers and operators including +, -, \*, /, & (and), | (or), ^ (eor), << (shift left), >> (shift right) similar to how expressions work in C. Parenthesis are supported for managing order of operations where C style precedence needs to be overrided. In addition there are some special characters supported: * \*: Current address (PC). This conflicts with the use of \* as multiply so multiply will be interpreted only after a value or right parenthesis * <: If less than is not follwed by another '<' in an expression this evaluates to the low byte of a value (and $ff) * >: If greater than is not followed by another '>' in an expression this evaluates to the high byte of a value (>>8) * !: Start of scope (use like an address label in expression) * %: First address after scope (use like an address label in expression) * $: Preceeds hexadecimal value * %: If immediately followed by '0' or '1' this is a binary value and not scope closure address Example: ``` lda #(((>SCREEN_MATRIX)&$3c)*4)+8 sta $d018 ``` ## Macros A macro can be defined by the using the directive macro and includes the line within the following scope: Example: ``` macro ShiftLeftA(Source) { rol Source rol A } ``` The macro will be instantiated anytime the macro name is encountered: ``` lda #0 ShiftLeftA($a0) ``` The parameter field is optional for both the macro declaration and instantiation, if there is a parameter in the declaration but not in the instantiation the parameter will be removed from the macro. If there are no parameters in the declaration the parenthesis can be omitted and will be slightly more efficient to assemble, as in: ``` .macro GetBit { asl bne % jsr GetByte } ``` Currently macros with parameters use search and replace without checking if the parameter is a whole word, the plan is to fix this. ## Scopes Scopes are lines inbetween '{' and '}' including macros. The purpose of scopes is to reduce the need for local labels and the scopes nest just like C code to support function level and loops and inner loop scoping. '!' is a label that is the first address of the scope and '%' the first address after the scope. This means you can write ``` { lda #0 ldx #8 { sta Label,x dex bpl ! } } ``` to construct a loop without adding a label. ##Examples Using scoping to avoid local labels ``` ; set zpTextPtr to a memory location with text ; return: y is the offset to the first space. ; (y==0 means either first is space or not found.) FindFirstSpace ldy #0 { lda (zpTextPtr),y cmp #$20 beq % ; found, exit iny bne ! ; not found, keep searching } rts ``` ### Development Status Currently the assembler is in an early revision and while features are tested individually it is fairly certain that untested combinations of features will indicate flaws and certain features are not in a complete state. **TODO** * Export full memory of fixed sections instead of a single section * Macro parameters should replace only whole words instead of any substring * Add 'import' directive as a catch-all include/incbin/etc. alternative * irp (indefinite repeat) **FIXED** * Option to source disasm output and option to dump all opcodes as a source file for tests * Object file format so sections can be saved for later linking * Added relative sections and relocatable references * Added Apple II Dos 3.3 Binary Executable output (-a2b) * Added more Merlin rules * Added directives from older assemblers * Added ENUM, sharing some functionality with STRUCT * Added INCDIR and command line options * [REPT](#rept) * fixed a flaw in expressions that ignored the next operator after raw hex values if no whitespace * expressions now handles high byte/low byte (\>, \<) as RPN tokens and not special cased. * structs * ifdef / if / elif / else / endif conditional code generation directives * Label Pools added * Bracket scoping closure ('}') cleans up local variables within that scope (better handling of local variables within macros). * Context stack cleanup * % in expressions is interpreted as binary value if immediately followed by 0 or 1 * Add a const directive for labels that shouldn't be allowed to change (currently ignoring const) * TEXT directive converts ascii to petscii (respect uppercase or lowercase petscii) (simplistic) Revisions: * 2015-10-18 Added list file output which is disassembly with inline source that generated the code. * 2015-10-16 XDEF and file protected symbols added for better recursive object file assembling * 2015-10-15 Object file reading, additional bugs debugged. * 2015-10-10 Relative Sections and Link support, adding -merlin command line to clean up code * 2015-10-06 Added ENUM and MERLIN / LISA assembler directives (EJECT, DUM, DEND, DS, DB, DFB, DDB, IF, ENDIF, etc.) * 2015-10-05 Added INCDIR, some command line options (-D, -i, -vice) * 2015-10-04 Added [REPT](#rept) directive * 2015-10-04 Added [STRUCT](#struct) directive, sorted functions by grouping a bit more, bug fixes * 2015-10-02 Cleanup hid an error (#else without #if), exit with nonzero if error was encountered * 2015-10-02 General cleanup, wrapping [conditional assembly](#conditional) in functions * 2015-10-01 Added [Label Pools](#pool) and conditional assembly * 2015-09-29 Moved Asm6502 out of Struse Samples. * 2015-09-28 First commit \ No newline at end of file diff --git a/x65.cpp b/x65.cpp index 848ec63..9617116 100644 --- a/x65.cpp +++ b/x65.cpp @@ -79,7 +79,7 @@ enum StatusCode { ERROR_EXPRESSION_OPERATION, ERROR_EXPRESSION_MISSING_VALUES, ERROR_INSTRUCTION_NOT_ZP, - ERROR_INVALID_ADDRESSING_MODE_FOR_BRANCH, + ERROR_INVALID_ADDRESSING_MODE, ERROR_BRANCH_OUT_OF_RANGE, ERROR_LABEL_MISPLACED_INTERNAL, ERROR_BAD_ADDRESSING_MODE, @@ -136,7 +136,7 @@ const char *aStatusStrings[STATUSCODE_COUNT] = { "Expression operation", "Expression missing values", "Instruction can not be zero page", - "Invalid addressing mode for branch instruction", + "Invalid addressing mode for instruction", "Branch out of range", "Internal label organization mishap", "Bad addressing mode", @@ -248,35 +248,125 @@ enum EvalOperator { // Opcode encoding typedef struct { unsigned int op_hash; - unsigned char group; // group # unsigned char index; // ground index unsigned char type; // mnemonic or } OP_ID; -// -// 6502 instruction encoding according to this page -// http://www.llx.com/~nparker/a2/opcodes.html -// decoded instruction: -// XXY10000 for branches -// AAABBBCC for CC=00, 01, 10 -// and some custom ops -// +enum AddrMode { + AMB_ZP_REL_X, // address mode bit index + AMB_ZP, + AMB_IMM, + AMB_ABS, + AMB_ZP_Y_REL, + AMB_ZP_X, + AMB_ABS_Y, + AMB_ABS_X, + AMB_REL, + AMB_ACC, + AMB_NON, + AMB_COUNT, -enum AddressingMode { - AM_REL_ZP_X, // 0 (zp,x) - AM_ZP, // 1 zp - AM_IMMEDIATE, // 2 #$hh - AM_ABSOLUTE, // 3 $hhhh - AM_REL_ZP_Y, // 4 (zp),y - AM_ZP_X, // 5 zp,x - AM_ABSOLUTE_Y, // 6 $hhhh,y - AM_ABSOLUTE_X, // 7 $hhhh,x - AM_RELATIVE, // 8 ($xxxx) - AM_ACCUMULATOR, // 9 A - AM_NONE, // 10 - AM_INVALID, // 11 + AMB_FLIPXY = AMB_COUNT, + AMB_BRANCH, + // address mode masks + AMM_NON = 1< base opcode -const unsigned char aMulAddGroup[][2] = { - { 0x20,0x00 }, - { 0x20,0x01 }, - { 0x20,0x02 }, - { 0x20,0x08 }, - { 0x20,0x10 }, - { 0x20,0x18 }, - { 0x20,0x20 }, - { 0x10,0x8a } -}; - -char aCC00Modes[] = { AM_IMMEDIATE, AM_ZP, AM_INVALID, AM_ABSOLUTE, AM_INVALID, AM_ZP_X, AM_INVALID, AM_ABSOLUTE_X }; -char aCC01Modes[] = { AM_REL_ZP_X, AM_ZP, AM_IMMEDIATE, AM_ABSOLUTE, AM_REL_ZP_Y, AM_ZP_X, AM_ABSOLUTE_X, AM_ABSOLUTE_Y }; -char aCC10Modes[] = { AM_IMMEDIATE, AM_ZP, AM_NONE, AM_ABSOLUTE, AM_INVALID, AM_ZP_X, AM_INVALID, AM_ABSOLUTE_X }; - -unsigned char CC00ModeAdd[] = { 0xff, 4, 0, 12, 0xff, 20, 0xff, 28 }; -unsigned char CC00Mask[] = { 0x0a, 0x08, 0x08, 0x2a, 0xae, 0x0e, 0x0e }; -unsigned char CC10ModeAdd[] = { 0xff, 4, 0, 12, 0xff, 20, 0xff, 28 }; -unsigned char CC10Mask[] = { 0xaa, 0xaa, 0xaa, 0xaa, 0x2a, 0xae, 0xaa, 0xaa }; - // hardtexted strings static const strref c_comment("//"); static const strref word_char_range("!0-9a-zA-Z_@$!#"); @@ -352,6 +386,19 @@ static const strref str_label("label"); static const strref str_const("const"); static const strref struct_byte("byte"); static const strref struct_word("word"); +static const char* aAddrModeFmt[] = { + "%s ($%02x,x)", + "%s $%02x", + "%s #$%02x", + "%s $%04x", + "%s ($%02x),y", + "%s $%02x,x", + "%s $%04x,y", + "%s $%04x,x", + "%s ($%04x)", + "%s A", + "%s " }; + // Binary search over an array of unsigned integers, may contain multiple instances of same key unsigned int FindLabelIndex(unsigned int hash, unsigned int *table, unsigned int count) @@ -459,7 +506,7 @@ public: }; // relocs are cheaper than full expressions and work with -// local labels for relative sections which would otherwise +// local labels for relative sections which could otherwise // be out of scope at link time. struct Reloc { @@ -480,6 +527,16 @@ struct Reloc { }; typedef std::vector relocList; +// For assembly listing this remembers the location of each line +struct ListLine { + int address; // start address of this line + int size; // number of bytes generated for this line + int line_offs; // offset into code + strref source_name; // source file index name + strref code; // line of code this represents +}; +typedef std::vector Listing; + // start of data section support // Default is a fixed address section at $1000 // Whenever org or dum with address is encountered => new section @@ -492,7 +549,6 @@ typedef struct Section { int load_address; // if assigned a load address int start_address; int address; // relative or absolute PC - bool address_assigned; // address is absolute if assigned // merged sections int merged_offset; // -1 if not merged @@ -505,6 +561,9 @@ typedef struct Section { // reloc data relocList *pRelocs; // link time resolve (not all sections need this) + Listing *pListing; // if list output + + bool address_assigned; // address is absolute if assigned bool dummySection; // true if section does not generate data, only labels void reset() { @@ -512,7 +571,10 @@ typedef struct Section { address_assigned = false; output = nullptr; curr = nullptr; dummySection = false; output_capacity = 0; merged_offset = -1; - if (pRelocs) delete pRelocs; pRelocs = nullptr; + if (pRelocs) delete pRelocs; + pRelocs = nullptr; + if (pListing) delete pListing; + pListing = nullptr; } void Cleanup() { if (output) free(output); reset(); } @@ -533,10 +595,11 @@ typedef struct Section { bool IsMergedSection() const { return merged_offset >= 0; } void AddReloc(int base, int offset, int section, Reloc::Type type = Reloc::WORD); - Section() : pRelocs(nullptr) { reset(); } - Section(strref _name, int _address) : pRelocs(nullptr) { reset(); name = _name; - start_address = load_address = address = _address; address_assigned = true; } - Section(strref _name) : pRelocs(nullptr) { reset(); name = _name; + Section() : pRelocs(nullptr), pListing(nullptr) { reset(); } + Section(strref _name, int _address) : pRelocs(nullptr), pListing(nullptr) + { reset(); name = _name; start_address = load_address = address = _address; + address_assigned = true; } + Section(strref _name) : pRelocs(nullptr), pListing(nullptr) { reset(); name = _name; start_address = load_address = address = 0; address_assigned = false; } ~Section() { reset(); } @@ -733,10 +796,17 @@ public: bool symbol_export, last_label_local; bool errorEncountered; + bool list_assembly; // Convert source to binary void Assemble(strref source, strref filename, bool obj_target); + // Generate assembler listing if requested + bool List(strref filename); + + // Generate source for all valid instructions + bool AllOpcodes(strref filename); + // Clean up memory allocations, reset assembler state void Cleanup(); @@ -808,9 +878,9 @@ public: // Assembler steps StatusCode ApplyDirective(AssemblerDirective dir, strref line, strref source_file); - AddressingMode GetAddressMode(strref line, bool flipXY, + AddrMode GetAddressMode(strref line, bool flipXY, StatusCode &error, strref &expression); - StatusCode AddOpcode(strref line, int group, int index, strref source_file); + StatusCode AddOpcode(strref line, int index, strref source_file); StatusCode BuildLine(OP_ID *pInstr, int numInstructions, strref line); StatusCode BuildSegment(OP_ID *pInstr, int numInstructions); @@ -866,6 +936,7 @@ void Asm::Cleanup() { symbol_export = false; last_label_local = false; errorEncountered = false; + list_assembly = false; } // Read in text data (main source, include, etc.) @@ -1078,6 +1149,7 @@ StatusCode Asm::LinkRelocs(int section_id, int section_address) return STATUS_OK; } +// Link sections with a specific name at this point StatusCode Asm::LinkSections(strref name) { if (CurrSection().IsRelativeSection()) return ERROR_LINKER_MUST_BE_IN_FIXED_ADDRESS_SECTION; @@ -1092,8 +1164,9 @@ StatusCode Asm::LinkSections(strref name) { // Get base addresses CheckOutputCapacity((int)s.size()); - int section_address = CurrSection().GetPC(); - unsigned char *section_out = CurrSection().curr; + Section &curr = CurrSection(); + int section_address = curr.GetPC(); + unsigned char *section_out = curr.curr; if (s.output) memcpy(section_out, s.output, s.size()); CurrSection().address += (int)s.size(); @@ -1110,6 +1183,22 @@ StatusCode Asm::LinkSections(strref name) { s.merged_section = SectionId(); s.merged_offset = (int)(section_out - CurrSection().output); + // Merge in the listing at this point + if (s.pListing) { + if (!curr.pListing) + curr.pListing = new Listing; + if ((curr.pListing->size() + s.pListing->size()) > curr.pListing->capacity()) + curr.pListing->reserve(curr.pListing->size() + s.pListing->size() + 256); + for (Listing::iterator si = s.pListing->begin(); si != s.pListing->end(); ++si) { + struct ListLine lst = *si; + lst.address += s.merged_offset; + curr.pListing->push_back(lst); + } + delete s.pListing; + s.pListing = nullptr; + } + + // All labels in this section can now be assigned LinkLabelsToAddress(section_id, section_address); @@ -1140,6 +1229,7 @@ void Section::CheckOutputCapacity(unsigned int addSize) { } } +// Add one byte to a section void Section::AddByte(int b) { if (!dummySection) { CheckOutputCapacity(1); @@ -1148,6 +1238,7 @@ void Section::AddByte(int b) { address++; } +// Add a 16 bit word to a section void Section::AddWord(int w) { if (!dummySection) { CheckOutputCapacity(2); @@ -1157,6 +1248,7 @@ void Section::AddWord(int w) { address += 2; } +// Add arbitrary length data to a section void Section::AddBin(unsigned const char *p, int size) { if (!dummySection) { CheckOutputCapacity(size); @@ -1166,6 +1258,7 @@ void Section::AddBin(unsigned const char *p, int size) { address += size; } +// Add a relocation marker to a section void Section::AddReloc(int base, int offset, int section, Reloc::Type type) { if (!pRelocs) @@ -2987,32 +3080,22 @@ int sortHashLookup(const void *A, const void *B) { return _A->op_hash > _B->op_hash ? 1 : -1; } -int BuildInstructionTable(OP_ID *pInstr, strref instr_text, int maxInstructions) +int BuildInstructionTable(OP_ID *pInstr, int maxInstructions) { // create an instruction table (mnemonic hash lookup) int numInstructions = 0; - char group_num = 0; - while (strref line = instr_text.next_line()) { - int index_num = 0; - while (line) { - strref mnemonic = line.split_token_trim(','); - if (mnemonic) { - OP_ID &op_hash = pInstr[numInstructions++]; - op_hash.op_hash = mnemonic.fnv1a_lower(); - op_hash.group = group_num; - op_hash.index = index_num; - op_hash.type = OT_MNEMONIC; - } - index_num++; - } - group_num++; + for (int i = 0; i < num_opcodes_6502; i++) { + OP_ID &op = pInstr[numInstructions++]; + op.op_hash = strref(opcodes_6502[i].instr).fnv1a_lower(); + op.index = i; + op.type = OT_MNEMONIC; } - + // add assembler directives for (int d=0; d=OPI_STX&&index<=OPI_LDX, error, expression); + AddrMode addrMode = GetAddressMode(line, + !!(opcodes_6502[index].modes & AMM_FLIPXY), error, expression); int value = 0; int target_section = -1; @@ -3107,7 +3189,7 @@ StatusCode Asm::AddOpcode(strref line, int group, int index, strref source_file) bool evalLater = false; if (expression) { struct EvalContext etx(CurrSection().GetPC(), scope_address[scope_depth], -1, - group==OPG_BRANCH ? SectionId() : -1); + !!(opcodes_6502[index].modes & AMM_BRA) ? SectionId() : -1); error = EvalExpression(expression, etx, value); if (error == STATUS_NOT_READY) { evalLater = true; @@ -3121,13 +3203,15 @@ StatusCode Asm::AddOpcode(strref line, int group, int index, strref source_file) } // check if address is in zero page range and should use a ZP mode instead of absolute - if (!evalLater && value>=0 && value<0x100 && group!=OPG_BRANCH && error != STATUS_RELATIVE_SECTION) { + if (!evalLater && value>=0 && value<0x100 && error != STATUS_RELATIVE_SECTION) { switch (addrMode) { - case AM_ABSOLUTE: - addrMode = AM_ZP; + case AMB_ABS: + if (opcodes_6502[index].modes & AMM_ZP) + addrMode = AMB_ZP; break; - case AM_ABSOLUTE_X: - addrMode = AM_ZP_X; + case AMB_ABS_X: + if (opcodes_6502[index].modes & AMM_ZP_X) + addrMode = AMB_ZP_X; break; default: break; @@ -3135,97 +3219,17 @@ StatusCode Asm::AddOpcode(strref line, int group, int index, strref source_file) } CODE_ARG codeArg = CA_NONE; - unsigned char opcode = base_opcode; - - // analyze addressing mode per mnemonic group - switch (group) { - case OPG_BRANCH: - if (addrMode != AM_ABSOLUTE) { - error = ERROR_INVALID_ADDRESSING_MODE_FOR_BRANCH; - break; - } + unsigned char opcode = opcodes_6502[index].aCodes[addrMode]; + + if (!(opcodes_6502[index].modes & (1 << addrMode))) + error = ERROR_INVALID_ADDRESSING_MODE; + else { + if (opcodes_6502[index].modes & AMM_BRANCH) codeArg = CA_BRANCH; - break; - - case OPG_SUBROUT: - if (index==OPI_JSR) { // jsr - if (addrMode != AM_ABSOLUTE) - error = ERROR_INVALID_ADDRESSING_MODE_FOR_BRANCH; - else - codeArg = CA_TWO_BYTES; - } - break; - case OPG_STACK: - case OPG_FLAG: - case OPG_TRANS: - codeArg = CA_NONE; - break; - case OPG_CC00: - // jump relative exception - if (addrMode==AM_RELATIVE && index==OPI_JMP) { - base_opcode += RELATIVE_JMP_DELTA; - addrMode = AM_ABSOLUTE; // the relative address is in an absolute location ;) - } - if (addrMode>7 || (CC00Mask[index]&(1<7 || (addrMode==AM_IMMEDIATE && index==OPI_STA)) - error = ERROR_BAD_ADDRESSING_MODE; - else { - opcode = base_opcode + addrMode*4; - switch (addrMode) { - case AM_ABSOLUTE: - case AM_ABSOLUTE_Y: - case AM_ABSOLUTE_X: - codeArg = CA_TWO_BYTES; - break; - default: - codeArg = CA_ONE_BYTE; - break; - } - } - break; - case OPG_CC10: { - if (addrMode == AM_NONE || addrMode == AM_ACCUMULATOR) { - if (index>=4) - error = ERROR_BAD_ADDRESSING_MODE; - else { - opcode = base_opcode + 8; - codeArg = CA_NONE; - } - } else { - if (addrMode>7 || (CC10Mask[index]&(1<size() == curr.pListing->capacity()) + curr.pListing->reserve(curr.pListing->size() + 256); + if (SectionId() == start_section) { + struct ListLine lst; + lst.address = start_address - curr.start_address; + lst.size = curr.address - start_address; + lst.code = contextStack.curr().source_file; + lst.source_name = contextStack.curr().source_name; + lst.line_offs = int(code_line.get() - lst.code.get()); + if (lst.size) + curr.pListing->push_back(lst); + } else { + struct ListLine lst; + lst.address = 0; + lst.size = curr.address - curr.start_address; + lst.code = contextStack.curr().source_file; + lst.source_name = contextStack.curr().source_name; + lst.line_offs = int(code_line.get() - lst.code.get()); + if (lst.size) + curr.pListing->push_back(lst); + } + } return error; } @@ -3460,11 +3491,156 @@ StatusCode Asm::BuildSegment(OP_ID *pInstr, int numInstructions) return error; } +// Produce the assembler listing +bool Asm::List(strref filename) +{ + FILE *f = stdout; + bool opened = false; + if (filename) { + f = fopen(strown<512>(filename).c_str(), "w"); + if (!f) + return false; + opened = true; + } + + // Build a disassembly lookup table + unsigned char mnemonic[256]; + unsigned char addrmode[256]; + memset(mnemonic, 255, sizeof(mnemonic)); + memset(addrmode, 255, sizeof(addrmode)); + for (int i = 0; i < num_opcodes_6502; i++) { + for (int j = 0; j < AMB_COUNT; j++) { + if (opcodes_6502[i].modes & (1 << j)) { + unsigned char op = opcodes_6502[i].aCodes[j]; + mnemonic[op] = i; + addrmode[op] = j; + } + } + } + + strref prev_src; + int prev_offs = 0; + for (std::vector
::iterator si = allSections.begin(); si != allSections.end(); ++si) { + if (!si->pListing) + continue; + for (Listing::iterator li = si->pListing->begin(); li != si->pListing->end(); ++li) { + strown<256> out; + const struct ListLine &lst = *li; + if (prev_src.fnv1a() != lst.source_name.fnv1a() || lst.line_offs < prev_offs) { + fprintf(f, STRREF_FMT "(%d):\n", STRREF_ARG(lst.source_name), lst.code.count_lines(lst.line_offs)); + prev_src = lst.source_name; + } + else { + strref prvline = lst.code.get_substr(prev_offs, lst.line_offs - prev_offs); + prvline.next_line(); + if (prvline.count_lines() < 5) { + while (strref space_line = prvline.line()) { + space_line.clip_trailing_whitespace(); + strown<128> line_fix(space_line); + for (strl_t pos = 0; pos < line_fix.len(); ++pos) { + if (line_fix[pos] == '\t') + line_fix.exchange(pos, 1, pos & 1 ? strref(" ") : strref(" ")); + } + out.append_to(' ', 30); + out.append(line_fix.get_strref()); + fprintf(f, STRREF_FMT "\n", STRREF_ARG(out)); + out.clear(); + } + } + else { + fprintf(f, STRREF_FMT "(%d):\n", STRREF_ARG(lst.source_name), lst.code.count_lines(lst.line_offs)); + } + } + + out.sprintf_append("$%04x ", lst.address + si->start_address); + int s = lst.size < 4 ? lst.size : 4; + if (si->output && si->output_capacity >= (lst.address + s)) { + for (int b = 0; b < s; ++b) + out.sprintf_append("%02x ", si->output[lst.address + b]); + } + else + s = 0; + out.append_to(' ', 18); + if (lst.size) { + unsigned char *buf = si->output + lst.address; + unsigned char op = mnemonic[*buf]; + unsigned char am = addrmode[*buf]; + if (op != 255 && am != 255) { + const char *fmt = aAddrModeFmt[am]; + if (opcodes_6502[op].modes & AMM_FLIPXY) { + if (am == AMB_ZP_X) fmt = "%s $%02x,y"; + else if (am == AMB_ABS_X) fmt = "%s $%04x,y"; + } + if (opcodes_6502[op].modes & AMM_BRANCH) + out.sprintf_append(fmt, opcodes_6502[op].instr, (char)buf[1] + lst.address + si->start_address + 2); + else if (am == AMB_NON || am == AMB_ACC) + out.sprintf_append(fmt, opcodes_6502[op].instr); + else if (am == AMB_ABS || am == AMB_ABS_X || am == AMB_ABS_Y || am == AMB_REL) + out.sprintf_append(fmt, opcodes_6502[op].instr, buf[1] | (buf[2] << 8)); + else + out.sprintf_append(fmt, opcodes_6502[op].instr, buf[1]); + } + } + out.append_to(' ', 30); + strref line = lst.code.get_skipped(lst.line_offs).get_line(); + line.clip_trailing_whitespace(); + strown<128> line_fix(line); + for (strl_t pos = 0; pos < line_fix.len(); ++pos) { + if (line_fix[pos] == '\t') + line_fix.exchange(pos, 1, pos & 1 ? strref(" ") : strref(" ")); + } + out.append(line_fix.get_strref()); + + fprintf(f, STRREF_FMT "\n", STRREF_ARG(out)); + prev_offs = lst.line_offs; + } + } + if (opened) + fclose(f); + return true; +} + +// Create a listing of all valid instructions and addressing modes +bool Asm::AllOpcodes(strref filename) +{ + FILE *f = stdout; + bool opened = false; + if (filename) { + f = fopen(strown<512>(filename).c_str(), "w"); + if (!f) + return false; + opened = true; + } + for (int i = 0; i < num_opcodes_6502; i++) { + for (int a = 0; a < AMB_COUNT; a++) { + if (opcodes_6502[i].modes & (1 << a)) { + const char *fmt = aAddrModeFmt[a]; + if (opcodes_6502[i].modes & AMM_BRANCH) + fprintf(f, "%s *+%d", opcodes_6502[i].instr, 5); + else { + if (opcodes_6502[i].modes & AMM_FLIPXY) { + if (a == AMB_ZP_X) fmt = "%s $%02x,y"; + else if (a == AMB_ABS_X) fmt = "%s $%04x,y"; + } + if (a==AMB_ABS || a==AMB_ABS_X || a==AMB_ABS_Y || a==AMB_REL) + fprintf(f, fmt, opcodes_6502[i].instr, 0x2120); + else + fprintf(f, fmt, opcodes_6502[i].instr, 0x21, 0x20, 0x1f); + } + fputs("\n", f); + } + } + } + if (opened) + fclose(f); + return true; +} + // create an instruction table (mnemonic hash lookup + directives) void Asm::Assemble(strref source, strref filename, bool obj_target) { OP_ID *pInstr = new OP_ID[256]; - int numInstructions = BuildInstructionTable(pInstr, strref(aInstr, strl_t(sizeof(aInstr)-1)), 256); + int numInstructions = BuildInstructionTable(pInstr, 256); StatusCode error = STATUS_OK; contextStack.push(filename, source, source); @@ -3502,6 +3678,10 @@ void Asm::Assemble(strref source, strref filename, bool obj_target) } } } + // dump the listing from each section + if (list_assembly) { + List(nullptr); + } } @@ -3678,10 +3858,10 @@ StatusCode Asm::WriteObjectFile(strref filename) l.section = lo.section; l.mapIndex = lo.mapIndex; l.flags = - (lo.constant ? ObjFileLabel::OFL_CNST : 0) | - (lo.pc_relative ? ObjFileLabel::OFL_ADDR : 0) | - (lo.evaluated ? ObjFileLabel::OFL_EVAL : 0) | - (lo.external ? ObjFileLabel::OFL_XDEF : 0); + (lo.constant ? ObjFileLabel::OFL_CNST : 0) | + (lo.pc_relative ? ObjFileLabel::OFL_ADDR : 0) | + (lo.evaluated ? ObjFileLabel::OFL_EVAL : 0) | + (lo.external ? ObjFileLabel::OFL_XDEF : 0); } } @@ -3697,10 +3877,10 @@ StatusCode Asm::WriteObjectFile(strref filename) l.section = lo.section; l.mapIndex = lo.mapIndex; l.flags = - (lo.constant ? ObjFileLabel::OFL_CNST : 0) | - (lo.pc_relative ? ObjFileLabel::OFL_ADDR : 0) | - (lo.evaluated ? ObjFileLabel::OFL_EVAL : 0) | - file_index; + (lo.constant ? ObjFileLabel::OFL_CNST : 0) | + (lo.pc_relative ? ObjFileLabel::OFL_ADDR : 0) | + (lo.evaluated ? ObjFileLabel::OFL_EVAL : 0) | + file_index; } file_index++; } @@ -3910,15 +4090,19 @@ StatusCode Asm::ReadObjectFile(strref filename) int main(int argc, char **argv) { + const strref listing("lst"); + const strref allinstr("opcodes"); int return_value = 0; bool load_header = true; bool size_header = false; bool info = false; + bool gen_allinstr = false; Asm assembler; const char *source_filename = nullptr, *obj_out_file = nullptr; const char *binary_out_name = nullptr; - const char *sym_file=nullptr, *vs_file=nullptr; + const char *sym_file = nullptr, *vs_file = nullptr; + strref list_file, allinstr_file; for (int a=1; a: Add include path\n * -D