What's new

Emulating Call Stacks

MattMik

New member
Hello!

I'm about to begin programming a CHIP-8 emulator, and I pretty much understand everything I need to know, but I am a bit confused as how to program the stack. I would like to know if the following is correct. I am using C++, so I would create a 16 value array, and an integer for the stack pointer. When my emulator comes across a call to a subroutine, it would store the value of the PC in stack[stackpointer], and increment the stack pointer by one. It will jump to the address that the subroutine is located at, and when it comes across 0x00EE (return from a subroutine), it will store stack[stackpointer] + 1 in the PC, and decrement the stack pointer by one. Is this correct?

I also read that the subroutines are stored at the end of programs. If this is true, how does the emulator know not to execute the code in the subroutine? I have found no opcode to signal the beginning of a subroutine.

Thanks a ton!
~Matt
 

Exophase

Emulator Developer
You're close. The way're calling subroutines, in order to return from the subroutine you should do:

decrement stack pointer by one
pc = stack[stackpointer]

The emulator wouldn't know not to execute subroutines stored at the end of the program. Rather, the programs, by design, won't ever reach the subroutines except via the call instruction. That is, unless the program wanted to fall through into the subroutine. A running program must always have some code executing, so it'll be looping around to prevent itself from falling off the end.
 
OP
M

MattMik

New member
Ahh! Okay, thanks! Just one more question....

Shouldn't it be pc = stack[stackpointer] + 2? Wouldn't pc = stack[stackpointer] cause the emulator to reprocess the opcode that enters a subroutine? This would cause it to loop. Don't we want the opcode two bytes after the one entering the subroutine, allowing the program to continue?
 

MIO0

New member
I have never worked with Chip 8, but all microprocessors that I'm familiar with advance the program counter before saving it on the stack.
 

Top