!pr2
!lm12
!rm75
Run-Anywhere Subroutine Calls...........Bob Sander-Cederlof

Bob Nacon (author of Amper-Magic) called yesterday and told me about his new way to call subroutines in programs that will be loaded anywhere in memory without relocation or reassembly.  He does this a lot inside Amper-Magic, and you might want to do it yourself sometime.

Instead of JSR <subroutine name>, put the following three lines whenever you call a subroutine:
!lm17

CLV
JSR $FF58
BVC <subroutine name>
!lm12

The byte at $FF58 in the monitor ROM is always $60, an RTS instruction.  Since this is used by most Apple interface boards, Apple has guaranteed that it will always be $60.  The JSR to a guaranteed RTS instruction seems silly, doesn't it?  Not quite, because it does put two bytes on the stack, and then pop them off again.  But we can get them back later, inside the called subroutine, like this:
!lm17

TSX    GET STACK POINTER
DEX
DEX
TXS    REVISED STACK POINTER
!lm12

Now the subroutine we called has a return address to go to, just as though we had used JSR <subroutine name>!  The only problem is that if we execute an RTS, we will re-execute the BVC <subroutine name> and be in a loop.  Unless....

Unless we set overflow, so the BVC falls through.  But there is no SEV opcode in the 6502, so what do we do?  $FF58 to the rescue again!  Here is how we end the subroutine:
!lm17

BIT $FF58    SET OVERFLOW
RTS
!lm12

The BIT instruction copies bit 7 of $FF58 into the Carry Status bit, and bit 6 into the Overflow Status bit.  This, in other words, (since $FF58 has $60 in it) clears carry and sets overflow.  If you want carry to be set as a return flag, you can insert SEC between the BIT and RTS lines.

I thank Bob Nacon for this technique, and he thanks Roger Wagner for putting him on the trail to its discovery.  Roger writes the monthly column in Softalk Magazine called "Assembly Lines"; the December, 1981, issue covered writing run-anywhere programs.  If you haven't got Roger's book yet, called "Assembly Lines: The Book", it is currently the best book for beginners that I know of.  The regular price is $19.95+$2 shipping, but I sell them for $18+$2 shipping.
