The excerpt below is
from the July 1982 issue of Apple Assembly Lines. I understand what the code is doing but I can't figure out the context. That is, when would you need to use this particular call & return method?
TIA... Cheerful regards, Mike
Quote:
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:
CLV
JSR $FF58
BVC <subroutine name>
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:
TSX GET STACK POINTER
DEX
DEX
TXS REVISED STACK POINTER
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:
BIT $FF58 SET OVERFLOW
RTS
The BIT instruction copies bit 7 of $FF58 into the N-status bit, and bit 6 into the Overflow status bit. This, in other words (since $FF58 has $60 in it) clears N and sets Overflow. BIT does not affect Carry Status in any way. BIT also sets or clears the Z-status bit, according to the value of the logical product of the A-register and the addressed byte. If you want Z and/or N to be flags to the calling program, you will have to modify them after the BIT instruction.
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.