5 A Macro Crossassembler for the 6502/65C02/65816 CPUs
7 (C) Copyright 1998-2000 Ullrich von Bassewitz
40 ca65 is a replacement for the ra65 assembler that was part of the cc65 C
41 compiler developed by John R. Dunning. I had some problems with ra65 and
42 the copyright does not permit some things which I wanted to be possible,
43 so I decided to write a completely new assembler/linker/archiver suite for
44 the cc65 compiler. ca65 is part of this suite.
46 Some parts of the assembler (code generation and some routines for symbol
47 table handling) are taken from an older crossassembler named a816 written
48 by me a long time ago.
50 Here's a list of the design criteria, that were important for the
53 * The assembler must support macros. Macros are not essential, but they
54 make some things easier, especially when you use the assembler in the
55 backend of a compiler.
57 * The assembler must support the newer 65C02 and 65816 CPUs. I have been
58 thinking about a 65816 backend for the C compiler, and even my old
59 a816 assembler had support for these CPUs, so this wasn't really a
62 * The assembler must produce relocatable code. This necessary for the
63 compiler support, and it is more convenient.
65 * Conditional assembly must be supported. This is a must for bigger
66 projects written in assembler (like Elite128).
68 * The assembler must support segments, and it must support more than
69 three segments (this is the count, most other assemblers support).
70 Having more than one code segments helps developing code for systems
71 with a divided ROM area (like the C64).
73 * The linker must be able to resolve arbitrary expressions. Years ago I
74 spent half a day to convince Borlands Turbo Assembler to let me use
75 the size of a structure I had created. So I decided that this is a
76 must. The linker should be able to get things like
84 * True lexical nesting for symbols. This is very convenient for larger
87 * "Cheap" local symbols without lexical nesting for those quick, late
90 * I liked the idea of "options" as Anre Fachats .o65 format has it, so I
91 introduced the concept into the object file format use by the new cc65
94 * The assembler will be a one pass assembler. There was no real need for
95 this decision, but I've written several multipass assemblers, and it
96 started to get boring. A one pass assembler needs much more elaborated
97 data structures, and because of that it's much more fun:-)
99 * Non-GPLed code that may be used in any project without restrictions or
100 fear of "GPL infecting" other code.
107 The assembler accepts the following options:
109 ---------------------------------------------------------------------------
110 Usage: ca65 [options] file
112 -g Add debug info to object file
114 -i Ignore case of symbols
115 -l Create a listing if assembly was ok
116 -o name Name the output file
118 -v Increase verbosity
119 -D name[=value] Define a symbol
120 -I dir Set an include directory search path
121 -U Mark unresolved symbols as import
122 -V Print the assembler version
123 -W n Set warning level n
126 --auto-import Mark unresolved symbols as import
127 --cpu type Set cpu type
128 --debug-info Add debug info to object file
129 --help Help (this text)
130 --ignore-case Ignore case of symbols
131 --include-dir dir Set an include directory search path
132 --listing Create a listing if assembly was ok
133 --pagelength n Set the page length for the listing
134 --smart Enable smart mode
135 --verbose Increase verbosity
136 --version Print the assembler version
137 ---------------------------------------------------------------------------
139 Here is a description of all the command line options:
144 Set the default for the CPU type. The option takes a parameter, which
147 6502, 65C02, 65816 and sunplus
149 (the latter is not available in the freeware version).
155 When this option (or the equivalent control command .DEBUGINFO) is used,
156 the assembler will add a section to the object file that contains all
157 symbols (including local ones) together with the symbol values and
158 source file positions. The linker will put these additional symbols into
159 the VICE label file, so even local symbols can be seen in the VICE
166 Print the short option summary shown above.
172 This option makes the assembler case insensitive on identifiers and
173 labels. This option will override the default, but may itself be
174 overriden by the .CASE control command (see section 6).
180 Generate an assembler listing. The listing file will always have the
181 name of the main input file with the extension replaced by ".lst". This
182 may change in future versions.
187 The default output name is the name of the input file with the extension
188 replaced by ".o". If you don't like that, you may give another name with
189 the -o option. The output file will be placed in the same directory as
190 the source file, or, if -o is given, the full path in this name is used.
195 sets the length of a listing page in lines. See the .PAGELENGTH
196 directive for more information.
202 In smart mode (enabled by -s or the .SMART pseudo instruction) the
203 assembler will track usage of the REP and SEP instructions in 65816 mode
204 and update the operand sizes accordingly. If the operand of such an
205 instruction cannot be evaluated by the assembler (for example, because
206 the operand is an imported symbol), a warning is issued.
208 Beware: Since the assembler cannot trace the execution flow this may
209 lead to false results in some cases. If in doubt, use the .ixx and .axx
210 instructions to tell the assembler about the current settings. Smart
211 mode is off by default.
217 Increase the assembler verbosity. Usually only needed for debugging
218 purposes. You may use this option more than one time for even more
224 This option allows you to define symbols on the command line. Without a
225 value, the symbol is defined with the value zero. When giving a value,
226 you may use the '$' prefix for hexadecimal symbols. Please note that for
227 some operating systems, '$' has a special meaning, so you may have to
228 quote the expression.
234 Name a directory which is searched for include files. The option may be
235 used more than once to specify more than one directory to search. The
236 current directory is always searched first before considering any
237 additional directores.
243 Mark symbols that are not defined in the sources as imported symbols.
244 This should be used with care since it delays error messages about typos
245 and such until the linker is run. The compiler uses the equivalent of
246 this switch (.AUTOIMPORT, see control command section below) to enable
247 auto imported symbols for the runtime library. However, the compiler is
248 supposed to generate code that runs through the assembler without
249 problems, something which is not always true for assembler programmers.
255 Print the version number of the assembler. If you send any suggestions
256 or bugfixes, please include the version number.
261 Set the warning level for the assembler. Using -W2 the assembler will
262 even warn about such things like unused imported symbols. The default
263 warning level is 1, and it would probably be silly to set it to
271 The assembler accepts the standard 6502/65816 assembler syntax. One line
272 may contain a label (which is identified by a colon), and, in addition to
273 the label, an assembler mnemonic, a macro, or a control command (see
274 section 6 for supported control commands). Alternatively, the line may
275 contain a symbol definition using the '=' token. Everything after a
276 semicolon is handled as a comment (that is, it is ignored).
278 Here are some examples for valid input lines:
280 Label: ; A label and a comment
281 lda #$20 ; A 6502 instruction plus comment
282 L1: ldx #$20 ; Same with label
283 L2: .byte "Hello world" ; Label plus control command
284 mymac $20 ; Macro expansion
285 MySym = 3*L1 ; Symbol definition
286 MaSym = Label ; Another symbol
288 The assembler accepts all valid 6502 mnemonics when in 6502 mode (the
289 default). The assembler accepts all valid 65SC02 mnemonics when in 65SC02
290 mode (after a .PC02 command is found). The assembler accepts all valid
291 65816 mnemonics with a few exceptions after a .P816 command is found.
292 These exceptions are listed below.
294 In 65816 mode several aliases are accepted in addition to the official
297 BGE is an alias for BCS
298 BLT is an alias for BCC
299 CPA is an alias for CMP
300 DEA is an alias for DEC A
301 INA is an alias for INC A
302 SWA is an alias for XBA
303 TAD is an alias for TCD
304 TAS is an alias for TCS
305 TDA is an alias for TDC
306 TSA is an alias for TSC
309 Evaluation of banked expressions in 65816 mode differs slightly from the
312 Instead of accepting a 24 bit address (something that is difficult for
313 the assembler to determine and would have required one more special
314 .import command), the bank and the absolute address in that bank are
317 jsl 3.$1234 ; Call subroutine at $1234 in bank 3
319 For literal values, the assembler accepts the widely used number formats:
320 A preceeding '$' denotes a hex value, a preceeding '%' denotes a binary
321 value, and a bare number is interpeted as a decimal. There are currently
322 no octal values and no floats.
329 All expressions are evaluated with (at least) 32 bit precision. An
330 expression may contain constant values and any combination of internal and
331 external symbols. Expressions that cannot be evaluated at assembly time
332 are stored inside the object file for evaluation by the linker.
333 Expressions referencing imported symbols must always be evaluated by the
336 Sometimes, the assembler must know about the size of the value that is the
337 result of an expression. This is usually the case, if a decision has to be
338 made, to generate a zero page or an absolute memory references. In this
339 case, the assembler has to make some assumptions about the result of an
342 * If the result of an expression is constant, the actual value is
343 checked to see if it's a byte sized expression or not.
345 * If the expression is explicitly casted to a byte sized expression by
346 one of the '>'/'<' operators, it is a byte expression.
348 * If this is not the case, and the expression contains a symbol,
349 explicitly declared as zero page symbol (by one of the .importzp or
350 .exportzp instructions), then the whole expression is assumed to be
353 * If the expression contains symbols that are not defined, and these
354 symbols are local symbols, the enclosing scopes are searched for a
355 symbol with the same name. If one exists and this symbol is defined,
356 it's attributes are used to determine the result size.
358 * In all other cases the expression is assumed to be word sized.
360 Note: If the assembler is not able to evaluate the expression at assembly
361 time, the linker will evaluate it and check for range errors as soon as
367 In the context of a boolean expression, any non zero value is evaluated as
368 true, any other value to false. The result of a boolean expression is 1 if
369 it's true, and zero if it's false. There are boolean operators with extrem
370 low precedence with version 2.x (where x > 0). The .AND and .OR operators
371 are shortcut operators. That is, if the result of the expression is
372 already known, after evaluating the left hand side, the right hand side is
376 Available operators sorted by precedence:
378 Op Description Precedence
379 -------------------------------------------------------------------
380 .CONCAT Builtin function 0
381 .LEFT Builtin function 0
382 .MID Builtin function 0
383 .RIGHT Builtin function 0
384 .STRING Builtin function 0
386 * Builtin pseudo variable (r/o) 1
387 .BLANK Builtin function 1
388 .CONST Builtin function 1
389 .CPU Builtin pseudo variable (r/o) 1
390 .DEFINED Builtin function 1
391 .MATCH Builtin function 1
392 .TCOUNT Builtin function 1
393 .XMATCH Builtin function 1
394 .PARAMCOUNT Builtin pseudo variable (r/o) 1
395 .REFERENCED Builtin function 1
396 :: Global namespace override 1
399 ~ Unary bitwise not 1
400 .BITNOT Unary bitwise not 1
401 < Low byte operator 1
402 > High byte operator 1
406 .MOD Modulo operation 2
408 .BITAND Bitwise and 2
410 .BITXOR Bitwise xor 2
411 << Shift left operator 2
412 .SHL Shift left operator 2
413 >> Shift right operator 2
414 .SHR Shift right operator 2
421 = Compare operation (equal) 4
422 <> Compare operation (not equal) 4
423 < Compare operation (less) 4
424 > Compare operation (greater) 4
425 <= Compare operation (less or equal) 4
426 >= Compare operation (greater or equal) 4
439 To force a specific order of evaluation, braces may be used as usual.
441 Some of the pseudo variables mentioned above need some more explanation:
443 * This symbol is replaced by the value of the program
444 counter at start of the current instruction. Note, that
445 '*' yields a rvalue, that means, you cannot assign to it.
446 Use .ORG to set the program counter in sections with
451 5. Symbols and labels
452 ---------------------
454 The assembler allows you to use symbols instead of naked values to make
455 the source more readable. There are a lot of different ways to define and
456 use symbols and labels, giving a lot of flexibility.
460 Numeric constants are defined using the equal sign. After doing
464 may use the symbol "two" in every place where a number is expected,
465 and it is evaluated to the value 2 in this context. An example would be
472 A label is defined by writing the name of the label at the start of
473 the line (before any instruction mnemonic, macro or pseudo
474 directive), followed by a colon. This will declare a symbol with the
475 given name and the value of the current program counter.
478 - Local labels and symbols
480 Using the .PROC directive, it is possible to create regions of code
481 where the names of labels and symbols are local to this region. They
482 are not know outside and cannot be accessed from there. Such regions
483 may be nested like PROCEDUREs in Pascal.
485 See the description of the .PROC directive for more information.
489 Cheap local labels are defined like standard labels, but the name of
490 the label must begin with a special symbol (usually '@', but this can
491 be changed by the .LOCALCHAR directive).
493 Cheap local labels are visible only between two no cheap labels. As
494 soon as a standard symbol is encountered (this may also be a local
495 symbol if inside a region defined with the .PROC directive), the
496 cheap local symbol goes out of scope.
498 You may use cheap local labels as an easy way to reuse common label
499 names like "Loop". Here is an example:
501 Clear: lda #$00 ; Global label
503 @Loop: sta Mem,y ; Local label
507 Sub: ... ; New global label
508 bne @Loop ; ERROR: Unknown identifier!
512 If you really want to write messy code, there are also unnamed
513 labels. These labels do not have a name (you guessed that already,
514 didn't you?). A colon is used to mark the absence of the name.
516 Unnamed labels may be accessed by using the colon plus several minus
517 or plus characters as a label designator. Using the '-' characters
518 will create a back reference (use the n'th label backwards), using
519 '+' will create a forward reference (use the n'th label in forward
520 direction). An example will help to understand this:
540 As you can see from the example, unnamed labels will make even short
541 sections of code hard to understand, because you have to count labels
542 to find branch targets (this is the reason why I for my part do
543 prefer the "cheap" local labels). Nevertheless, unnamed labels are
544 convenient in some situations, so it's your decision.
546 - Using macros to define labels and constants
548 While there are drawbacks with this approach, it may be handy in some
549 situations. Using .DEFINE, it is possible to define symbols or
550 constants that may be used elsewhere. Since the macro facility works
551 on a very low level, there is no scoping. On the other side, you may
552 also define string constants this way (this is not possible with the
558 .DEFINE version "SOS V2.3"
560 four = two * two ; Ok
563 .PROC ; Start local scope
564 two = 3 ; Will give "2 = 3" - invalid!
568 If .DEBUGINFO is enabled (or -g is given on the command line), global,
569 local and cheap local labels are written to the object file and will be
570 available in the symbol file via the linker. Unnamed labels are not
571 written to the object file, because they don't have a name which would
572 allow to access them.
579 Here's a list of all control commands and a description, what they do:
584 Valid only in 65816 mode. Switch the accumulator to 16 bit.
586 Note: This command will not emit any code, it will tell the assembler to
587 create 16 bit operands for immediate accumulator adressing mode.
594 Valid only in 65816 mode. Switch the accumulator to 8 bit.
596 Note: This command will not emit any code, it will tell the assembler to
597 create 8 bit operands for immediate accu adressing mode.
604 Define word sized data. In 6502 mode, this is an alias for .WORD and
605 may be used for better readability if the data words are address values.
606 In 65816 mode, the address is forced to be 16 bit wide to fit into the
607 current segment. See also .FARADDR. The command must be followed by a
608 sequence of (not necessarily constant) expressions.
612 .addr $0D00, $AF13, _Clear
617 Align data to a given boundary. The command expects a constant integer
618 argument that must be a power of two, plus an optional second argument
619 in byte range. If there is a second argument, it is used as fill value,
620 otherwise the value defined in the linker configuration file is used
621 (the default for this value is zero).
623 Since alignment depends on the base address of the module, you must
624 give the same (or a greater) alignment for the segment when linking.
625 The linker will give you a warning, if you don't do that.
634 Define a string with a trailing zero.
638 Msg: .asciiz "Hello world"
640 This will put the string "Hello world" followed by a binary zero into
641 the current segment. There may be more strings separated by commas, but
642 the binary zero is only appended once (after the last one).
647 Is followd by a plus or a minus character. When switched on (using a
648 +), undefined symbols are automatically marked as import instead of
649 giving errors. When switched off (which is the default so this does not
650 make much sense), this does not happen and an error message is
651 displayed. The state of the autoimport flag is evaluated when the
652 complete source was translated, before outputing actual code, so it is
653 *not* possible to switch this feature on or off for separate sections of
654 code. The last setting is used for all symbols.
656 You should probably not use this switch because it delays error
657 messages about undefined symbols until the link stage. The cc65
658 compiler (which is supposed to produce correct assembler code in all
659 circumstances, something which is not true for most assembler
660 programmers) will insert this command to avoid importing each and every
661 routine from the runtime library.
665 .autoimport + ; Switch on auto import
670 Builtin function. The function evaluates its argument in braces and
671 yields "false" if the argument is non blank (there is an argument), and
672 "true" if there is no argument. As an example, the .IFBLANK statement
680 Switch to the BSS segment. The name of the BSS segment is always "BSS",
681 so this is a shortcut for
685 See also the .SEGMENT command.
690 Define byte sized data. Must be followed by a sequence of (byte ranged)
691 expressions or strings.
695 .byte "Hello world", $0D, $00
700 Switch on or off case sensitivity on identifiers. The default is off
701 (that is, identifiers are case sensitive), but may be changed by the
702 -i switch on the command line.
703 The command must be followed by a '+' or '-' character to switch the
704 option on or off respectively.
708 .case - ; Identifiers are not case sensitive
713 Switch to the CODE segment. The name of the CODE segment is always
714 "CODE", so this is a shortcut for
718 See also the .SEGMENT command.
723 Builtin function. The function allows to concatenate a list of string
724 constants separated by commas. The result is a string constant that
725 is the concatentation of all arguments. This function is most useful
726 in macros and when used together with the .STRING builtin function.
727 The function may be used in any case where a string constant is
732 .include .concat ("myheader", ".", "inc)
734 This is the same as the command
736 .include "myheader.inc"
741 Builtin function. The function evaluates its argument in braces and
742 yields "true" if the argument is a constant expression (that is, an
743 expression that yields a constant value at assembly time) and "false"
744 otherwise. As an example, the .IFCONST statement may be replaced by
751 Reading this pseudo variable will give a constant integer value that
752 tells which instruction set is currently enabled. Possible values are:
759 It may be used to replace the .IFPxx pseudo instructions or to construct
760 even more complex expressions.
764 .if (.cpu = 0) .or (.cpu = 1)
777 Switch to the DATA segment. The name of the DATA segment is always
778 "DATA", so this is a shortcut for
782 See also the .SEGMENT command.
787 Define word sized data with the hi and lo bytes swapped (use .WORD to
788 create word sized data in native 65XX format). Must be followed by a
789 sequence of (word ranged) expressions.
795 This will emit the bytes
799 into the current segment in that order.
804 Switch on or off debug info generation. The default is off (that is,
805 the object file will not contain debug infos), but may be changed by the
806 -g switch on the command line.
807 The command must be followed by a '+' or '-' character to switch the
808 option on or off respectively.
812 .debuginfo + ; Generate debug info
817 Start a define style macro definition. The command is followed by an
818 identifier (the macro name) and optionally by a list of formal arguments
820 See separate section about macros.
826 Builtin function. The function expects an identifier as argument in
827 braces. The argument is evaluated, and the function yields "true" if the
828 identifier is a symbol that is already defined somewhere in the source
829 file up to the current position. Otherwise the function yields false. As
830 an example, the .IFDEF statement may be replaced by
837 Define dword sized data (4 bytes) Must be followed by a sequence of
842 .dword $12344512, $12FA489
847 Conditional assembly: Reverse the current condition.
852 Conditional assembly: Reverse current condition and test a new one.
857 Forced end of assembly. Assembly stops at this point, even if the command
858 is read from an include file.
863 Conditional assembly: Close a .IF... or .ELSE branch.
869 End of macro definition (see separate section).
874 End of local lexical level (see .PROC).
879 Force an assembly error. The assembler will output an error message
880 preceeded by "User error" and will *not* produce an object file.
882 This command may be used to check for initial conditions that must be
883 set before assembling a source file.
892 .error "Must define foo or bar!"
899 Abort a macro expansion immidiately. This command is often useful in
900 recursive macros. See separate chapter about macros.
905 Make symbols accessible from other modules. Must be followed by a comma
906 separated list of symbols to export.
915 Make symbols accessible from other modules. Must be followed by a comma
916 separated list of symbols to export. The exported symbols are explicitly
917 marked as zero page symols.
926 Define far (24 bit) address data. The command must be followed by a
927 sequence of (not necessarily constant) expressions.
931 .faraddr DrawCircle, DrawRectangle, DrawHexagon
936 This directive may be used to enable one or more compatibility features
937 of the assembler. While the use of .FEATURE should be avoided when
938 possible, it may be useful when porting sources written for other
939 assemblers. There is no way to switch a feature off, once you have
944 will enable the feature until end of assembly is reached.
946 The following features are available:
950 The dollar sign may be used as an alias for the star (`*'), which
951 gives the value of the current PC in expressions.
952 Note: Assignment to the pseudo variable is not allowed.
954 labels_without_colons
956 Allow labels without a trailing colon. These labels are only accepted,
957 if they start at the beginning of a line (no leading white space).
961 Accept single quotes as well as double quotes as terminators for string
966 Accept the at character (`@') as a valid character in identifiers. The
967 at character is not allowed to start an identifier, even with this
970 dollar_in_identifiers
972 Accept the dollar sign (`$') as a valid character in identifiers. The
973 at character is not allowed to start an identifier, even with this
980 Insert an option string into the object file. There are two forms of
981 this command, one specifies the option by a keyword, the second
982 specifies it as a number. Since usage of the second one needs knowledge
983 of the internal encoding, its use is not recommended and I will only
984 describe the first form here.
986 The command is followed by one of the keywords
992 a comma and a string. The option is written into the object file
993 together with the string value. This is currently unidirectional and
994 there is no way to actually use these options once they are in the
999 .fileopt comment, "Code stolen from my brother"
1000 .fileopt compiler, "BASIC 2.0"
1001 .fopt author, "J. R. User"
1006 Declare symbols as global. Must be followed by a comma separated list
1007 of symbols to declare. Symbols from the list, that are defined somewhere
1008 in the source, are exported, all others are imported. An additional
1009 explicit .IMPORT or .EXPORT command for the same symbol is allowed.
1018 Declare symbols as global. Must be followed by a comma separated list
1019 of symbols to declare. Symbols from the list, that are defined
1020 somewhere in the source, are exported, all others are imported. An
1021 additional explicit .IMPORT or .EXPORT command for the same symbol is
1022 explicitly allowed. The symbols in the list are explicitly marked as
1032 Valid only in 65816 mode. Switch the index registers to 16 bit.
1034 Note: This command will not emit any code, it will tell the assembler to
1035 create 16 bit operands for immediate operands.
1044 Valid only in 65816 mode. Switch the index registers to 8 bit.
1046 Note: This command will not emit any code, it will tell the assembler to
1047 create 8 bit operands for immediate operands.
1056 Conditional assembly: Evalute an expression and switch assembler output
1057 on or off depending on the expression. The expression must be a constant
1058 expression, that is, all operands must be defined.
1060 A expression value of zero evaluates to FALSE, any other value evaluates
1066 Conditional assembly: Check if there are any remaining tokens in this
1067 line, and evaluate to FALSE if this is the case, and to TRUE otherwise.
1068 If the condition is not true, further lines are not assembled until
1069 an .ELSE, .ELSEIF or .ENDIF directive.
1071 This command is often used to check if a macro parameter was given.
1072 Since an empty macro parameter will evaluate to nothing, the condition
1073 will evaluate to FALSE if an empty parameter was given.
1092 Conditional assembly: Evaluate an expression and switch assembler output
1093 on or off depending on the constness of the expression.
1095 A const expression evaluates to to TRUE, a non const expression (one
1096 containing an imported or currently undefined symbol) evaluates to
1106 Conditional assembly: Check if a symbol is defined. Must be followed by
1107 a symbol name. The condition is true if the the given symbol is already
1108 defined, and false otherwise.
1117 Conditional assembly: Check if there are any remaining tokens in this
1118 line, and evaluate to TRUE if this is the case, and to FALSE otherwise.
1119 If the condition is not true, further lines are not assembled until
1120 an .ELSE, .ELSEIF or .ENDIF directive.
1122 This command is often used to check if a macro parameter was given.
1123 Since an empty macro parameter will evaluate to nothing, the condition
1124 will evaluate to FALSE if an empty parameter was given.
1142 Conditional assembly: Check if a symbol is defined. Must be followed by
1143 a symbol name. The condition is true if the the given symbol is not
1144 defined, and false otherwise.
1153 Conditional assembly: Check if a symbol is referenced. Must be followed
1154 by a symbol name. The condition is true if if the the given symbol was
1155 not referenced before, and false otherwise.
1164 Conditional assembly: Check if the assembler is currently in 6502 mode
1170 Conditional assembly: Check if the assembler is currently in 65816 mode
1171 (see .P816 command).
1176 Conditional assembly: Check if the assembler is currently in 65C02 mode
1177 (see .PC02 command).
1182 Conditional assembly: Check if a symbol is referenced. Must be followed
1183 by a symbol name. The condition is true if if the the given symbol was
1184 referenced before, and false otherwise.
1186 This command may be used to build subroutine libraries in include files
1187 (you may use separate object modules for this purpose too).
1191 .ifref ToHex ; If someone used this subroutine
1192 ToHex: tay ; Define subroutine
1204 Import a symbol from another module. The command is followed by a comma
1205 separated list of symbols to import.
1214 Import a symbol from another module. The command is followed by a comma
1215 separated list of symbols to import. The symbols are explicitly imported
1216 as zero page symbols (that is, symbols with values in byte range).
1225 Include a file as binary data. The command expects a string argument
1226 that is the name of a file to include literally in the current segment.
1230 .incbin "sprites.dat"
1235 Include another file. Include files may be nested up to a depth of 16.
1244 Builtin function. Extracts the left part of a given token list.
1248 .LEFT (<int expr>, <token list>)
1250 The first integer expression gives the number of tokens to extract from
1251 the token list. The second argument is the token list itself.
1255 To check in a macro if the given argument has a '#' as first token
1256 (immidiate addressing mode), use something like this:
1260 .if (.match (.left (1, arg), #))
1262 ; ldax called with immidiate operand
1269 See also the .MID and .RIGHT builtin functions.
1274 Switch on or off line continuations using the backslash character
1275 before a newline. The option is off by default.
1276 Note: Line continuations do not work in a comment. A backslash at the
1277 end of a comment is treated as part of the comment and does not trigger
1279 The command must be followed by a '+' or '-' character to switch the
1280 option on or off respectively.
1284 .linecont + ; Allow line continuations
1287 #$20 ; This is legal now
1292 Enable output to the listing. The command must be followed by a boolean
1293 switch ("on", "off", "+" or "-") and will enable or disable listing
1295 The option has no effect if the listing is not enabled by the command line
1296 switch -l. If -l is used, an internal counter is set to 1. Lines are output
1297 to the listing file, if the counter is greater than zero, and suppressed if
1298 the counter is zero. Each use of .LIST will increment or decrement the
1303 .list on ; Enable listing output
1308 Set, how many bytes are shown in the listing for one source line. The
1309 default is 12, so the listing will show only the first 12 bytes for any
1310 source line that generates more than 12 bytes of code or data.
1311 The directive needs an argument, which is either "unlimited", or an
1312 integer constant in the range 4..255.
1316 .listbytes unlimited ; List all bytes
1317 .listbytes 12 ; List the first 12 bytes
1318 .incbin "data.bin" ; Include large binary file
1323 This command may only be used inside a macro definition. It declares a
1324 list of identifiers as local to the macro expansion.
1326 A problem when using macros are labels: Since they don't change their
1327 name, you get a "duplicate symbol" error if the macro is expanded the
1328 second time. Labels declared with .LOCAL have their name mapped to an
1329 internal unique name (___ABCD__) with each macro invocation.
1331 Some other assemblers start a new lexical block inside a macro
1332 expansion. This has some drawbacks however, since that will not allow
1333 *any* symbol to be visible outside a macro, a feature that is sometimes
1334 useful. The .LOCAL command is in my eyes a better way to address the
1337 You get an error when using .LOCAL outside a macro.
1342 Defines the character that start "cheap" local labels. You may use one
1343 of '@' and '?' as start character. The default is '@'.
1345 Cheap local labels are labels that are visible only between two non
1346 cheap labels. This way you can reuse identifiers like "loop" without
1347 using explicit lexical nesting.
1353 Clear: lda #$00 ; Global label
1354 ?Loop: sta Mem,y ; Local label
1358 Sub: ... ; New global label
1359 bne ?Loop ; ERROR: Unknown identifier!
1364 Insert a predefined macro package. The command is followed by an
1365 identifier specifying the macro package to insert. Available macro
1368 generic Defines generic macros like add and sub.
1369 longbranch Defines conditional long jump macros.
1371 Including a macro package twice, or including a macro package that
1372 redefines already existing macros will lead to an error.
1376 .macpack longbranch ; Include macro package
1378 cmp #$20 ; Set condition codes
1379 jne Label ; Jump long on condition
1381 See separate section about macros packages.
1387 Start a classic macro definition. The command is followed by an identifier
1388 (the macro name) and optionally by a comma separated list of identifiers
1389 that are macro parameters.
1390 See separate section about macros.
1395 Builtin function. Matches two token lists against each other. This is
1396 most useful within macros, since macros are not stored as strings, but
1401 .MATCH(<token list #1>, <token list #2>)
1403 Both token list may contain arbitrary tokens with the exception of the
1404 terminator token (comma resp. right parenthesis) and
1409 Often a macro parameter is used for any of the token lists.
1411 Please note that the function does only compare tokens, not token
1412 attributes. So any number is equal to any other number, regardless of
1413 the actual value. The same is true for strings. If you need to compare
1414 tokens <em/and/ token attributes, use the .XMATCH function.
1418 Assume the macro ASR , that will shift right the accumulator by one,
1419 while honoring the sign bit. The builtin processor instructions will
1420 allow an optional "A" for accu addressing for instructions like ROL
1421 and ROR. We will use the .MATCH function to check for this and print
1422 and error for invalid calls.
1426 .if (.not .blank(arg)) .and (.not .match (arg, a))
1427 .error "Syntax error"
1430 cmp #$80 ; Bit 7 into carry
1431 lsr a ; Shit carry into bit 7
1435 The macro will only accept no arguments, or one argument that must
1436 be the reserved keyword "A".
1441 Builtin function. Takes a starting index, a count and a token list as
1442 arguments. Will return part of the token list.
1446 .MID (<int expr>, <int expr>, <token list>)
1448 The first integer expression gives the starting token in the list (the
1449 first token has index 0). The second integer expression gives the number
1450 of tokens to extract from the token list. The third argument is the
1455 To check in a macro if the given argument has a '#' as first token
1456 (immidiate addressing mode), use something like this:
1460 .if (.match (.mid (0, 1, arg), #))
1462 ; ldax called with immidiate operand
1469 See also the .LEFT and .RIGHT builtin functions.
1474 Start a section of absolute code. The command is followed by a constant
1475 expression that gives the new PC counter location for which the code is
1476 assembled. Use .RELOC to switch back to relocatable code.
1478 You may not switch segments while inside a section of absolute code.
1482 .org $7FF ; Emit code starting at $7FF
1487 Output a string to the console without producing an error. This command
1488 is similiar to .ERROR, however, it does not force an assembler error
1489 that prevents the creation of an object file.
1493 .out "This code was written by the codebuster(tm)"
1498 Enable the 6502 instruction set, disable 65C02 and 65816 instructions.
1499 This is the default if not overridden by the --cpu command line option.
1504 Enable the 65816 instruction set. This is a superset of the 65C02 and
1505 6502 instruction sets.
1511 Set the page length for the listing. Must be followed by an integer
1512 constant. The value may be "unlimited", or in the range 32 to 127. The
1513 statement has no effect if no listing is generated. The default value
1514 is -1 but may be overridden by the --pagelength command line option.
1515 Beware: Since the listing is generated after assembly is complete, you
1516 cannot use multiple line lengths with one source. Instead, the value
1517 set with the last .PAGELENGTH is used.
1521 .pagelength 66 ; Use 66 lines per listing page
1523 .pagelength unlimited ; Unlimited page length
1528 This builtin pseudo variable is only available in macros. It is replaced
1529 by the actual number of parameters that were given in the macro
1534 .macro foo arg1, arg2, arg3
1535 .if .paramcount <> 3
1536 .error "Too few parameters for macro foo"
1544 Enable the 65C02 instructions set. This instruction set includes all
1550 Start a nested lexical level. All new symbols from now on are in the
1551 local lexical level and are not accessible from outside. Symbols defined
1552 outside this local level may be accessed as long as their names are not
1553 used for new symbols inside the level. Symbols names in other lexical
1554 levels do not clash, so you may use the same names for identifiers. The
1555 lexical level ends when the .ENDPROC command is read. Lexical levels may
1556 be nested up to a depth of 16.
1558 The command may be followed by an identifier, in this case the
1559 identifier is declared in the outer level as a label having the value of
1560 the program counter at the start of the lexical level.
1562 Note: Macro names are always in the global level and in a separate name
1563 space. There is no special reason for this, it's just that I've never
1564 had any need for local macro definitions.
1568 .proc Clear ; Define Clear subroutine, start new level
1570 L1: sta Mem,y ; L1 is local and does not cause a
1571 ; duplicate symbol error if used in other
1574 bne L1 ; Reference local symbol
1576 .endproc ; Leave lexical level
1582 Builtin function. The function expects an identifier as argument in
1583 braces. The argument is evaluated, and the function yields "true" if the
1584 identifier is a symbol that has already been referenced somewhere in the
1585 source file up to the current position. Otherwise the function yields
1586 false. As an example, the .IFREF statement may be replaced by
1593 Switch back to relocatable mode. See the .ORG command.
1598 Reserve storage. The command is followed by one or two constant
1599 expressions. The first one is mandatory and defines, how many bytes of
1600 storage should be defined. The second, optional expression must by a
1601 constant byte value that will be used as value of the data. If there
1602 is no fill value given, the linker will use the value defined in the
1603 linker configuration file (default: zero).
1607 ; Reserve 12 bytes of memory with value $AA
1613 Builtin function. Extracts the right part of a given token list.
1617 .RIGHT (<int expr>, <token list>)
1619 The first integer expression gives the number of tokens to extract from
1620 the token list. The second argument is the token list itself.
1622 See also the .LEFT and .MID builtin functions.
1627 Switch to the RODATA segment. The name of the RODATA segment is always
1628 "RODATA", so this is a shortcut for
1632 The RODATA segment is a segment that is used by the compiler for
1633 readonly data like string constants. See also the .SEGMENT command.
1638 Switch to another segment. Code and data is always emitted into a
1639 segment, that is, a named section of data. The default segment is
1640 "CODE". There may be up to 254 different segments per object file
1641 (and up to 65534 per executable). There are shortcut commands for
1642 the most common segments ("CODE", "DATA" and "BSS").
1644 The command is followed by a string containing the segment name (there
1645 are some constraints for the name - as a rule of thumb use only those
1646 segment names that would also be valid identifiers). There may also be
1647 an optional attribute separated by a comma. Valid attributes are
1652 When specifying a segment for the first time, "absolute" is the
1653 default. For all other uses, the attribute specified the first time
1656 "absolute" means that this is a segment with absolute addressing. That
1657 is, the segment will reside somewhere in core memory outside the zero
1658 page. "zeropage" means the opposite: The segment will be placed in the
1659 zero page and direct (short) addressing is possible for data in this
1662 Beware: Only labels in a segment with the zeropage attribute are marked
1663 as reachable by short addressing. The `*' (PC counter) operator will
1664 work as in other segments and will create absolute variable values.
1668 .segment "ROM2" ; Switch to ROM2 segment
1669 .segment "ZP2", zeropage ; New direct segment
1670 .segment "ZP2" ; Ok, will use last attribute
1671 .segment "ZP2", absolute ; Error, redecl mismatch
1676 Switch on or off smart mode. The command must be followed by a '+' or
1677 '-' character to switch the option on or off respectively. The default
1678 is off (that is, the assembler doesn't try to be smart), but this
1679 default may be changed by the -s switch on the command line.
1681 In smart mode the assembler will track usage of the REP and SEP
1682 instructions in 65816 mode and update the operand sizes accordingly. If
1683 the operand of such an instruction cannot be evaluated by the assembler
1684 (for example, because the operand is an imported symbol), a warning is
1685 issued. Beware: Since the assembler cannot trace the execution flow this
1686 may lead to false results in some cases. If in doubt, use the .ixx and
1687 .axx instructions to tell the assembler about the current settings.
1692 .smart - ; Stop being smart
1697 Builtin function. The function accepts an argument in braces and
1698 converts this argument into a string constant. The argument may be an
1699 identifier, or a constant numeric value.
1700 Since you can use a string in the first place, the use of the function
1701 may not be obvious. However, it is useful in macros, or more complex
1706 ; Emulate other assemblers:
1708 .segment .string(name)
1714 Builtin function. The function accepts a token list in braces. The
1715 function result is the number of tokens given as argument.
1719 The ldax macro accepts the '#' token to denote immidiate addressing
1720 (as with the normal 6502 instructions). To translate it into two
1721 separate 8 bit load instructions, the '#' token has to get stripped
1725 .if (.match (.mid (0, 1, arg), #))
1726 ; ldax called with immidiate operand
1727 lda #<(.right (.tcount (arg)-1, arg))
1728 ldx #>(.right (.tcount (arg)-1, arg))
1737 Define word sized data. Must be followed by a sequence of (word ranged,
1738 but not necessarily constant) expressions.
1742 .word $0D00, $AF13, _Clear
1747 Switch to the ZEROPAGE segment and mark it as direct (zeropage) segment.
1748 The name of the ZEROPAGE segment is always "ZEROPAGE", so this is a
1751 .segment "ZEROPAGE", zeropage
1753 Because of the "zeropage" attribute, labels declared in this segment are
1754 addressed using direct addressing mode if possible. You MUST instruct
1755 the linker to place this segment somewhere in the address range 0..$FF
1756 otherwise you will get errors.
1763 Macros may be thought of as "parametrized super instructions". Macros are
1764 sequences of tokens that have a name. If that name is used in the source
1765 file, the macro is "expanded", that is, it is replaced by the tokens that
1766 were specified when the macro was defined.
1768 In it's simplest form, a macro does not have parameters. Here's an
1771 .macro asr ; Arithmetic shift right
1772 cmp #$80 ; Put bit 7 into carry
1773 ror ; Rotate right with carry
1776 The macro above consists of two real instructions, that are inserted into
1777 the code, whenever the macro is expanded. Macro expansion is simply done
1778 by using the name, like this:
1785 When using macro parameters, macros can be even more useful:
1797 When calling the macro, you may give a parameter, and each occurence of
1798 the name "addr" in the macro definition will be replaced by the given
1813 A macro may have more than one parameter, in this case, the parameters
1814 are separated by commas. You are free to give less parameters than the
1815 macro actually takes in the definition. You may also leave intermediate
1816 parameters empty. Empty parameters are replaced by empty space (that is,
1817 they are removed when the macro is exanded). If you have a look at our
1818 macro definition above, you will see, that replacing the "addr" parameter
1819 by nothing will lead to wrong code in most lines. To help you, writing
1820 macros with a variable parameter list, there are some control commands:
1822 .IFBLANK tests the rest of the line and returns true, if there are any
1823 tokens on the remainder of the line. Since empty parameters are replaced
1824 by nothing, this may be used to test if a given parameter is empty.
1825 .IFNBLANK tests the opposite.
1827 Look at this example:
1829 .macro ldaxy a, x, y
1841 This macro may be called as follows:
1843 ldaxy 1, 2, 3 ; Load all three registers
1845 ldaxy 1, , 3 ; Load only a and y
1847 ldaxy , , 3 ; Load y only
1849 There's another helper command for determining, which macro parameters are
1850 valid: .PARAMCOUNT. This command is replaced by the parameter count given,
1851 *including* intermediate empty macro parameters:
1853 ldaxy 1 ; .PARAMCOUNT = 1
1854 ldaxy 1,,3 ; .PARAMCOUNT = 3
1855 ldaxy 1,2 ; .PARAMCOUNT = 2
1856 ldaxy 1, ; .PARAMCOUNT = 2
1857 ldaxy 1,2,3 ; .PARAMCOUNT = 3
1859 Macros may be used recursively:
1861 .macro push r1, r2, r3
1869 There's also a special macro to help writing recursive macros: .EXITMACRO.
1870 This command will stop macro expansion immidiately:
1872 .macro push r1, r2, r3, r4, r5, r6, r7
1874 ; First parameter is empty
1880 push r2, r3, r4, r5, r6, r7
1883 When expanding this macro, the expansion will push all given parameters
1884 until an empty one is encountered. The macro may be called like this:
1886 push $20, $21, $32 ; Push 3 ZP locations
1887 push $21 ; Push one ZP location
1889 Now, with recursive macros, .IFBLANK and .PARAMCOUNT, what else do you need?
1890 Have a look at the inc16 macro above. Here is it again:
1902 If you have a closer look at the code, you will notice, that it could be
1903 written more efficiently, like this:
1915 But imagine what happens, if you use this macro twice? Since the label
1916 "Skip" has the same name both times, you get a "duplicate symbol" error.
1917 Without a way to circumvent this problem, macros are not as useful, as
1918 they could be. One solution is, to start a new lexical block inside the
1933 Now the label is local to the block and not visible outside. However,
1934 sometimes you want a label inside the macro to be visible outside. To make
1935 that possible, there's a new command that's only usable inside a macro
1936 definition: .LOCAL. .LOCAL declares one or more symbols as local to the
1937 macro expansion. The names of local variables are replaced by a unique
1938 name in each separate macro expansion. So we could also solve the problem
1939 above by using .LOCAL:
1942 .local Skip ; Make Skip a local symbol
1949 Skip: ; Not visible outside
1952 Starting with version 2.5 of the assembler, there is a second macro type
1953 available: C style macros using the .DEFINE directive. These macros are
1954 similar to the classic macro type speified above, but behaviour is
1955 sometimes different:
1957 * Macros defined with .DEFINE may not span more than a line. You may
1958 use line continuation (.LINECONT) to spread the definition over more
1959 than one line for increased readability, but the macro itself does
1960 not contain an end-of-line token.
1962 * Macros defined with .DEFINE share the name space with classic macros,
1963 but they are detected and replaced at the scanner level. While classic
1964 macros may be used in every place, where a mnemonic or other directive
1965 is allowed, .DEFINE style macros are allowed anywhere in a line. So
1966 they are more versatile in some situations.
1968 * .DEFINE style macros may take parameters. While classic macros may
1969 have empty parameters, this is not true for .DEFINE style macros. For
1970 this macro type, the number of actual parameters must match exactly
1971 the number of formal parameters.
1972 To make this possible, formal parameters are enclosed in braces when
1973 defining the macro. If there are no parameters, the empty braces may
1976 * Since .DEFINE style macros may not contain end-of-line tokens, there
1977 are things that cannot be done. They may not contain several processor
1978 instructions for example. So, while some things may be done with both
1979 macro types, each type has special usages. The types complement each
1982 Let's look at a few examples to make the advantages and disadvantages
1985 To emulate assemblers that use "EQU" instead of "=" you may use the
1990 foo EQU $1234 ; This is accepted now
1992 You may use the directive to define string constants used elsewhere:
1994 ; Define the version number
1995 .define VERSION "12.3a"
2000 Macros with parameters may also be useful:
2002 .define DEBUG(message) .out message
2004 DEBUG "Assembling include file #3"
2006 Note that, while formal parameters have to be placed in braces, this is
2007 not true for the actual parameters. Beware: Since the assembler cannot
2008 detect the end of one parameter, only the first token is used. If you
2009 don't like that, use classic macros instead:
2015 (This is an example where a problem can be solved with both macro types).
2022 Using the .macpack directive, predefined macro packages may be included
2023 with just one command. Available macro packages are:
2027 This macro package defines macros that are useful in almost any
2028 program. Currently, two macros are defined:
2043 This macro package defines long conditional jumps. They are named like
2044 the short counterpart but with the 'b' replaced by a 'j'. Here is a
2045 sample definition for the "jeq" macro, the other macros are built using
2049 .if .def(Target) .and ((*+2)-(Target) <= 127)
2057 All macros expand to a short branch, if the label is already defined
2058 (back jump) and is reachable with a short jump. Otherwise the macro
2059 expands to a conditional branch with the branch condition inverted,
2060 followed by an absolute jump to the actual branch target.
2062 The package defines the following macros:
2064 jeq, jne, jmi, jpl, jcs, jcc, jvs, jvc
2071 If you have problems using the assembler, if you find any bugs, or if
2072 you're doing something interesting with the assembler, I would be glad to
2073 hear from you. Feel free to contact me by email (uz@musoftware.de).
2080 ca65 (and all cc65 binutils) are (C) Copyright 1998-2000 Ullrich von
2081 Bassewitz. For usage of the binaries and/or sources the following
2082 conditions do apply:
2084 This software is provided 'as-is', without any expressed or implied
2085 warranty. In no event will the authors be held liable for any damages
2086 arising from the use of this software.
2088 Permission is granted to anyone to use this software for any purpose,
2089 including commercial applications, and to alter it and redistribute it
2090 freely, subject to the following restrictions:
2092 1. The origin of this software must not be misrepresented; you must not
2093 claim that you wrote the original software. If you use this software
2094 in a product, an acknowledgment in the product documentation would be
2095 appreciated but is not required.
2096 2. Altered source versions must be plainly marked as such, and must not
2097 be misrepresented as being the original software.
2098 3. This notice may not be removed or altered from any source