Adam Sh
Adam Sh

Reputation: 8577

Assembly - How 0x80 with ecx=esp work?

I have the next code:

Doit: mov eax, 4 ; for write system call
      push Dword, 0x44434241
      mov ebx, 1
      mov ecx, esp
      mov edx, 4
      int 0x80
      add esp, 4
      ret

As I check, It's print "ABCD", but why? AS I understood it, on the stack we have the next picture:

Low --- 0x41 0x42 0x43 0x44 -- esp,

i.e esp is point to 0x44. When we call 0x80. it should print "DCBA". What I missed?

Upvotes: 0

Views: 532

Answers (2)

user1233508
user1233508

Reputation:

Your stack picture is wrong. Because x86 is a little-endian architecture, ESP is equal to the address of the least-significant byte in the pushed value, or 0x41.

From Intel's priceless Architecture Developer's Manual:

When an item is pushed onto the stack, the processor decrements the ESP register, then writes the item at the new top of stack.

Upvotes: 2

Brett Hale
Brett Hale

Reputation: 22308

This is just an endianness issue. You are simply pushing a 32-bit value onto the stack, which will be at the address ESP. x86 is little-endian, and stores the least-significant byte first:

ESP + 0 (0x41), ESP + 1 (0x42), ESP + 2 (0x43), ESP + 3 (0x44). When accessed as an array of bytes however, it starts at ESP and increments through memory.

There's nothing wrong with your use of the stack, it's just misunderstanding of word / dword / qword storage vs. byte access.

Upvotes: 0

Related Questions