Search code examples
stack6502

Why does the 6502 read from the stack before writing it?


I am building a W65C02S based computer for fun, and I try to build basically all the tools myself. Including the assembler (yes, I know they exist, I just want to make everything from scratch myself, for fun).

When working on the JSR opcode (absolute addressing mode), I find that before it puts the program counter on the stack, it reads one byte off the stack first (program counter is set to 80 2e at this point, the stack pointer is 01b6):

READ  address:   80 2e   data:   20   JSR   ; Read the opcode
READ  address:   80 2f   data:   14   14    ; Read the LO byte of operand
READ  address:   01 b6   data:   74   't'   ; Read the stack (why?!)
WRITE address:   01 b6   data:   80   ---   ; Write HI byte of PC
WRITE address:   01 b5   data:   30   '0'   ; Write LO byte of PC
READ  address:   80 30   data:   80   80    ; Read HI byte of operand
READ  address:   80 14   data:   8d   STA   ; Read opcode at `80 14` (the JSR operand)

It works OK, but what it the reason it reads from the stack first?

(Update: to explain the table. This was from my own tool. I am using an Arduino to look at the data and address buses to see what is happening there. It is a hardware CPU running only my own code.)


Solution

  • I am by no means a 6502 expert, but I do have a conjecture. Someone with more 6502 experience can correct me if I'm wrong here...

    Your output is, among other things, just indicating what's on the bus on each clock cycle. I believe the initial "stack read" you are seeing isn't really a read at all, but simply the CPU asserting the stack address onto the address bus during that clock cycle with the RWB (read/write bit) high (so as not to write to the stack unintentionally) but not for the purpose of actually reading the contents of the stack at that address at that time into an internal register. With a stable address on the address bus, on the next cycle, the CPU presents the data to be written on the data lines and lowers the RWB signal to write the value to the stack at that address.