Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why using external c function in nasm breaks this code?

I've encountered a problem when using an external c function for debugging my nasm program.

%macro pint 1
  pushad
  push %1
  call printint
  popad
%endmacro

section .text
      extern printint
      global main
   main:
      mov eax, 3
      pint eax
      dec eax
      pint eax

      mov eax,1
      mov ebx,0
      int 0x80

while printint is defined like this:

 void printint(int a) { 
   printf("%d\n",a);
 }

the output I'm getting is 3 from the first print (as expected) and a random number from the 2nd print. I was told that printf() might change cpu register values without restoring them, so i thought saving all registers on the stack before calling printf would prevent any registers from changing but apparently it doesn't.
can anyone explains why the weird output and how can i fix it ?

Thanks.

like image 716
yurib Avatar asked Dec 25 '10 18:12

yurib


1 Answers

printint() is probably using the cdecl calling convention. Under that convention, it's the caller's responsibility to remove the pushed parameters from the stack.

You should write:

%macro pint 1
    pushad
    push %1
    call printint
    add esp, 4  ; Clean pushed parameter.
    popad
%endmacro
like image 122
Frédéric Hamidi Avatar answered Sep 27 '22 16:09

Frédéric Hamidi