Reputation: 1179
I'm trying to do a two stack sort in assembly. I understand for the first stack you use the system stack; however have no idea how one would implement the second stack.
Upvotes: 4
Views: 1098
Reputation: 173
Load everything into the stack and use pointers?
Mov eax,[point1-4] (top of stack down)
mov ebx,[point2-4] (limit of point 1 down)
you usually decrement by 4 because items are stored as dwords
if you mess with the stack start off by storing esp to a DW[stackstore]
mov dword [stak],esp
and return the stored value to esp at the end of your routine
mov esp,[stak]
ret
The stack can be a bit funny and crash a routine unless you keep your foot firmly on its throat
Upvotes: 0
Reputation: 39905
To solve this problem, you need to answer three questions: What operations do I need, what does each operation do, and how can I do that?
A stack has two operations: Push and pop.
Let's model our implementation after the system stack. Then this question becomes "what do the push
and pop
instructions do?". The push
instruction decrements the stack pointer and stores its argument at the location it now points to. The pop
instruction reads the value the stack pointer points to, increments the stack pointer, and returns the read value.
Pushing was two steps: Decrementing the stack pointer and storing a value. There are already instructions for just this purpose. The push
instruction uses esp
as the stack pointer, but since we are writing our own, we can use whatever we want. We will use edx
, and assume the value to store is in eax
(we are storing 4 bytes).
sub edx, 4 ; Decrement the stack pointer one position (4 bytes)
mov dword [edx], eax ; Store the value at the new location
Popping was three steps: Getting the value, incrementing the stack, and returning the value. We will return the value simply by leaving it in eax
.
mov eax, dword [edx] ; Load the value off of the stack
add edx, 4 ; Increment the stack pointer one position (4 bytes)
; Leave the result in eax to return it
Now that we have implementations for both operations, we can use them how we like. Perhaps we want to wrap them in a function by adding code to read the arguments into the registers (if needed) before, and a return after. Or, maybe we just want to insert these directly where we need them, changing registers to suit our needs.
Upvotes: 4