Sunday, December 27, 2009

Throw it on the Stack

Today, I implemented a stack. It's primitive, but it has all the moving parts of a call stack.

Some code:

; A call stack
;
;
;


AREA HEAP, NOINIT, READWRITE, ALIGN=3

Heap_Size EQU 0x500 ; Size of heap. 0x500, from my earlier project
Stack_Size EQU 0x400 ; Size of stack. 0x400
Manager_Offset EQU 0x100 ; Size of ordinary heap. Manager lives on top of it.

Heap_Memory SPACE Heap_Size ; Allocate memroy for the heap.
Stack_Memory SPACE Stack_Size ; Allocate memory for the stack.


Heap_Manager EQU (Heap_Memory + Manager_Offset)

AREA HelloWorld, CODE, READONLY ;
EXPORT mystart ; Export this code to the project


; Test code to see if the stack works as expected.

;
mystart
LDR sp, =Stack_Memory ; Set stack memory. This points to the base of the stack.
ADD sp, sp, #Stack_Size ; Because this is a decrementing stack, we need to point to the top of the stack.

MOV R4, #0xA ; Load test values into registers
MOV R7, #0xA
MOV R9, #0xA
MOV R10, #0xA
MOV R11, #0xA

STMFD sp!, {R4, R7, R9-R11, R14} ; Push test values and Link Register (R14) onto stack

MOV R4, #0xb ; Overwrite test values in registers
MOV R7, #0xb
MOV R9, #0xb
MOV R10, #0xb
MOV R11, #0xb

LDMFD sp!, {R4, R7, R9-R11, R14} ; Pop test values off stack.

stop
BAL stop ; gives me a loop to be caught in

END ; end.


When I ran this in debug mode, it loaded the test values into registers, then saved the registers into memory in the stack. After making whatever changes to the registers (in what would be the body of the subroutine), the code pops the values from the stack.

As expected, the final values in the test registers were all 0xA.

The only thing that didn't go as expected was that when the STMFD command was executed, all the test registers were set to 0x0. I don't know if this is part of the language specification, the hardware, or something the simulator does.

No comments:

Post a Comment