Relocatable Machine Code in BASIC Strings

Atari BASIC screen showing a generated line 2000 L$= followed by a long string of graphics characters, the message LINE 2000 HOLDS AN EXACT COPY, and THIS CODE RUNS ANYWHERE printed near the bottom

Thousands of Atari BASIC programs carried their machine code in string variables. A string is a block of bytes that BASIC stores and saves with the program, and ADR() tells you where it is. The catch is that BASIC moves strings around, so the code inside them must run correctly at whatever address it lands on. This guide covers writing such position-independent 6502 code and getting it into a string. The basic USR calling convention is in Calling Machine Language from Atari BASIC with USR. This guide goes further.

What you'll learn: what makes 6502 code relocatable, how to get around missing relative JMP and JSR instructions, how a routine finds its own address (including a trick built into Atari BASIC's USR), how to load code from DATA into a string, and how to turn it into a literal "..." string despite the two bytes that can't appear in one.

What you need: Atari BASIC and an assembler (MADS is used here) to produce the bytes. Both test programs were run in an emulator.

1. Why strings move

Atari BASIC keeps its string and array area directly above the tokenized program. Adding or editing a program line moves everything above it, and so does loading a different version of the program. The address of M$ is only known at the moment you ask for it. That's why the call is always written USR(ADR(M$),…), which evaluates ADR every time. The generator in section 6 adds a program line while it runs, so its own strings move halfway through. The code doesn't mind.

2. The rules for position-independent 6502 code

A routine runs at any address if no instruction depends on where the routine itself lives. In practice:

  • Branches are fine. BNE, BCC, BPL and the rest store a signed offset from the next instruction (−128 to +127 bytes), not an address.
  • JMP and JSR to your own labels are not. Both contain an absolute address.
  • No absolute references to your own data. LDA TABLE,X or STA COUNTER hard-codes an address inside the routine. The same goes for self-modifying code.
  • Fixed system addresses are fine. Page zero, OS shadow registers, hardware registers and ROM entry points such as CIOV ($E456) never move, so STA $D01A or JSR $E456 are allowed.

Some workarounds for the missing relative jumps:

  • Forced branches. If you know the state of a flag, a conditional branch acts like a JMP: CLC followed by BCC, or a BNE after loading a non-zero value. The example below uses BCS after an addition that has just set carry.
  • Branch chains. For a target more than 127 bytes away, branch to an intermediate branch that sits out of the program flow. Andy Barton's Machine Language Stringer (Antic, July 1989) shows the pattern.
  • Computed jumps. Once you know your own address (next section), add a label's offset to it and jump through a page-zero pointer with JMP (ptr), or push the address minus one and execute RTS. CIO dispatches to device handlers with that same RTS trick.
  • Fixed subroutines. If a routine really needs JSR, put that subroutine somewhere fixed, such as page 6, and keep only the relocatable part in the string.

3. Finding your own address

To read a table or message stored inside the string, the routine needs its own address at run time. There are two reliable ways.

Pass it in. X=USR(ADR(M$),ADR(M$)) hands the routine its address as a normal argument, which it pulls off the stack like any other. This works in any BASIC.

Read it from FR0. In Atari BASIC this costs nothing. The USR code in the BASIC ROM (XPUSR in The Atari BASIC Source Book) converts the address argument to an integer in FR0 ($D4/$D5, 212/213), pushes the other arguments and the count on the stack, and then calls the routine with JMP (FR0). So on entry, $D4/$D5 still hold the routine's own address. This is also why USR returns the routine's address if you store nothing in FR0. Other BASICs may not work this way. If you're writing for more than one, pass the address in.

Once you have the base address, add an offset to make a page-zero pointer, then use (zp),Y addressing to reach anything inside the routine. Locations $CB–$D1 (203–209) are free page-zero bytes under Atari BASIC.

4. A relocatable routine

This routine copies a message stored inside itself onto the GRAPHICS 0 screen at a row you choose: X=USR(ADR(M$),ROW).

; relocatable USR routine: X=USR(ADR(M$),ROW)
FR0    = $D4            ; Atari BASIC leaves the routine's address here
SRC    = $CB            ; $CB-$CE: free page-zero bytes
DST    = $CD
SAVMSC = $58

        org $0600       ; any address: the code never refers to itself
start   pla             ; argument count (1)
        pla             ; row, high byte (ignored)
        pla             ; row, low byte
        tax
        lda FR0         ; SRC = own address + offset of the text
        clc
        adc #msg-start
        sta SRC
        lda FR0+1
        adc #0
        sta SRC+1
        lda SAVMSC      ; DST = screen memory
        sta DST
        lda SAVMSC+1
        sta DST+1
row     dex             ; add 40 bytes per row
        bmi copy
        lda DST
        clc
        adc #40
        sta DST
        bcc row
        inc DST+1
        bcs row         ; carry is still set: always taken
copy    ldy #msgend-msg-1
cl      lda (SRC),y
        sta (DST),y
        dey
        bpl cl
        rts             ; FR0 untouched: USR returns our address
msg     dta d'THIS CODE RUNS ANYWHERE'
msgend

The only references to its own labels are differences such as msg-start and msgend-msg-1, which the assembler turns into constants that don't depend on where the code is loaded. The org line is only there to keep the assembler happy. The routine is 74 bytes: 51 bytes of code and a 23-byte message stored as screen codes (d'...' in MADS), so it can be copied straight into screen memory. SAVMSC ($58/$59, 88/89) holds the address of the screen.

5. Loading it from DATA, and proving it moves

The safest way to fill a string is a READ loop. Every byte value from 0 to 255 is allowed, because the bytes never pass through the program editor.

10 DIM M$(74),N$(100)
20 FOR I=1 TO 74:READ B:M$(I,I)=CHR$(B):NEXT I
30 GRAPHICS 0
40 A=USR(ADR(M$),3)
50 N$="XXXXXXXXXXXXXXXXXXXXXXXXXX":N$(27)=M$
60 B=USR(ADR(N$)+26,6)
70 POSITION 2,9:PRINT "M$ IS AT ";ADR(M$);", USR GAVE ";A
80 PRINT "COPY IS AT ";ADR(N$)+26;", USR GAVE ";B
1000 DATA 104,104,104,170,165,212,24,105,51,133,203,165,213
1010 DATA 105,0,133,204,165,88,133,205,165,89,133,206,202
1020 DATA 48,13,165,205,24,105,40,133,205,144,244,230,206
1030 DATA 176,240,160,22,177,203,145,205,136,16,249,96,52
1040 DATA 40,41,51,0,35,47,36,37,0,50,53,46,51
1050 DATA 0,33,46,57,55,40,37,50,37

Line 50 copies the routine into the middle of another string, 26 bytes in, and line 60 calls the copy there. Both calls print the message, on rows 3 and 6. In the run shown here the two copies were at 2683 and 2783, and each USR call returned its own address. That shows the code doesn't care where it runs, and it confirms the FR0 trick: neither call stores anything in FR0.

The M$(I,I)=CHR$(B) form matters. It puts one byte at position I and makes the string at least I characters long, which is how a string gets built up from DATA.

6. From DATA to a string literal

DATA costs memory and time: each value is stored as text in the program, and READ is slow. The more compact form puts the bytes straight into the program as a literal, M$="..." or even X=USR(ADR("..."),3). Two byte values can't appear in a literal:

  • 34, the quotation mark, which ends the string.
  • 155, ATASCII RETURN (EOL), which ends the program line.

There are three ways around them. Avoid the bytes when you write the code: 34 is $22 and 155 is $9B, so check immediate values, page-zero addresses and offsets. A different free page-zero location or a different constant usually does it. Patch them after the literal: Machine Language Stringer generated an extra line such as M$(72,72)=CHR$(155) for each problem byte. Or build the string in pieces with CHR$(34).

Typing graphics characters from a listing is error-prone, so let the program write the line for you. The editor's forced-read mode makes the screen editor take its next input from the screen instead of the keyboard. You print a program line and a CONT on the screen, switch on forced read by poking 13 into IOCB 0's AUX1 (location 842), and stop. BASIC then "types" the line into itself and continues. Add these lines to the loader above, replacing lines 30–80:

10 DIM M$(74),L$(74)
20 FOR I=1 TO 74:READ B:M$(I,I)=CHR$(B):NEXT I
100 GRAPHICS 0:POSITION 2,6
110 PRINT "2000 L$=";CHR$(34);
120 FOR I=1 TO LEN(M$):C=ASC(M$(I,I))
130 IF C=34 OR C=155 THEN PRINT :PRINT "BYTE ";I;" CANNOT BE IN A LITERAL":END
140 IF C>26 AND C<32 OR C>124 AND C<128 OR C>154 AND C<160 OR C>252 THEN PRINT CHR$(27);
150 PRINT CHR$(C);:NEXT I
160 PRINT CHR$(34);":RETURN"
170 PRINT :PRINT "CONT"
180 POSITION 2,0:POKE 842,13:STOP
190 POKE 842,12
200 GOSUB 2000:IF L$=M$ THEN PRINT "LINE 2000 HOLDS AN EXACT COPY"
210 X=USR(ADR(L$),20)
220 END

Line 140 handles the second problem with literals. When the bytes are printed, the screen editor carries out the control codes instead of displaying them: 27–31 (ESC and the cursor moves), 125–127 (clear, backspace, tab), 155–159 (EOL, delete and insert line, tab set and clear) and 253–255 (bell, delete and insert character). Printing an ESC (27) first makes the editor show the next character as a glyph. Run on a test string containing several of those codes, the generator produced a line holding an exact copy.

When you RUN it, line 2000 appears on screen as a two-line string of graphics characters ending in :RETURN, and the program confirms the copy and calls it from the new literal (the screenshot). The generated line is printed a few rows down because the STOP message is also on the screen. Depending on the BASIC, the editor may read that message back as input and print an error, which does no harm. Afterwards, delete the generator and DATA lines (or use LIST "D:CODE.LST",2000 and ENTER it into your own program). The routine is then part of the program text itself and loads with it.

Troubleshooting

  • Works in page 6, crashes in a string: there's a JMP, JSR or absolute reference to your own code or data. Check the assembler listing for any operand that falls inside the routine's address range.
  • Works until you edit the program: you saved ADR(M$) in a variable once instead of evaluating it at each call.
  • Garbage instead of the message: the offset arithmetic is wrong, or a stray STA into FR0 before you read it. Read $D4/$D5 first.
  • Generated line is truncated or the screen scrolls oddly: a control code was printed without its ESC. Check line 140's ranges.
  • "BYTE n CANNOT BE IN A LITERAL": change the code so it avoids 34 and 155, or patch those positions after the literal.
  • Forced read never stops: line 190 (POKE 842,12) didn't run, so the editor keeps reading the screen. Press RESET.

Further reading

  • Andy Barton, "Machine Language Stringer", Antic, July 1989: a BASIC utility that converts object files into string-literal lines and patches 34 and 155 separately.
  • The Atari BASIC Source Book by Bill Wilkinson, Kathleen O'Brien and Paul Laughton (COMPUTE! Books, 1983): the USR implementation, the string and array area, and why strings move.
  • Mark Chasin, Assembly Language Programming for the Atari Computers, chapter 7, "Locating Machine Language Programs in Memory": relocatable versus fixed routines.
  • Atari BASIC Faster and Better by Carl Evans (IJG, 1983): relocatable USR routines loaded into strings, and moving them between memory areas.
  • On this site: Calling Machine Language from Atari BASIC with USR, Page 6: The Atari's 256 Bytes of Safe Memory and Atari BASIC String Tricks.

Credits