I've read nearly every thread discussing the bootstrap code and for some reason I am just not getting it.
I will use this one as reference:
http://nand2tetris-questions-and-answers-forum.32033.n3.nabble.com/Bootstrap-Code-vs-Initialization-td4028658.htmlThe bootstrap code(starting at ROM[0]) should do this:
Set SP to 256
call Sys.init
Fair enough. SP is easy.
Next, let's call Sys.init. Well this is just like calling any other function right?
We have to abide by these rules:
push return-address // (Using the label declared below)
push LCL // Save LCL of the calling function
push ARG // Save ARG of the calling function
push THIS // Save THIS of the calling function
push THAT // Save THAT of the calling function
ARG = SP-n-5 // Reposition ARG (n = number of args.)
LCL = SP // Reposition LCL
goto f // Transfer control
(return-address) // Declare a label for the return-address
So the return address is generated by the assembler. In my case, it maps to 48. But we don't care. Sys.init should never return(right?).
So RAM[256] = 48.
Is this alright?
If I run the VM emulator, the stack looks much differently than mine.
The VM emulator does not show
call Sys.init, only
funciton Sys.init.
So if we observe the state of RAM before
funciton Sys.init runs, I notice that their RAM[SP] = 256.
That's fine. But their RAM[256] = 0 while mine is RAM[256] = 48. That's different than what I have.
At this point, I am thinking maybe it doesn't matter and the VM emulator defaults the return address to 0.
Let's move on. Next let's push LCL, ARG, THIS, THAT, ARG=SP-n-5, LCL=SP
My RAM looks like this now:
0 261
1 261
2 256
3 0
4 0
Now goto Sys.init.
At this point, my RAM should match the VM emulator. But it does not. The VM emulator(before function Sys.init runs) is:
0 256
1 0
2 0
3 0
4 0
Apparently, call sys.init does not behave like a normal call.
So am I missing some type of initialization? I noticed in the thread I linked to, he said he initialized some values. But, the book doesn't mention that. The book says initialize SP to 256 and then call Sys.init.
Does call Sys.init not act like a normal call?
I am sure I am missing something dumb. Thanks for the advice.