Jjack
Jjack

Reputation: 1358

x86 32 Bit Assembly question

I am currently in the process of learning assembly and I was playing around with if statements. My current code is as follows.

write:
mov eax, 0x4     
sub esp, 4       
int 0x80         

main:
    ; The message has already been pushed to the stack
mov eax, 4
inc eax
cmp eax, 5
je write  

If I put the ret at the end of write: then I get a bus error 10 and if I do not I get an infinite loop resulting in a segmentation error. What should I do to make this work?

Upvotes: 4

Views: 355

Answers (2)

Sparafusile
Sparafusile

Reputation: 4966

Try this instead. No need to call a procedure in your example.

main:  ; The message has already been pushed to the stack
  mov eax, 4
  inc eax
  cmp eax, 5
  jne dontwrite   ; Skip Write

  ; Write
  mov eax, 0x4
  sub esp, 4
  int 0x80

dontwrite:
       ; the rest of the program goes here

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 225242

Use the call instruction instead of je to get into write. ret expects the return address to be on the stack, but it won't get pushed if you use a jump to get there! You're going to have to put esp back to whatever it was when you entered the function, too. Here's a best-guess example based on your code:

write:
  mov eax, 0x4
  sub esp, 4       
  int 0x80
  add esp, 4
  ret

main:  ; The message has already been pushed to the stack
  mov eax, 4
  inc eax
  cmp eax, 5
  jne dontwrite  ; skip calling 'write' if eax != 5
  call write
dontwrite:
       ; the rest of the program goes here

Upvotes: 1

Related Questions