Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C and assembly __asm doesn't work

Tags:

c

gcc

assembly

I found this piece of code to put the stack pointer into EAX register(It should be the register used by "return" in C)

#include <stdio.h>
unsigned long get_sp(){
    unsigned long stp;
    __asm{
        mov
        eax, esp
        }
}

void main(void){
printf("\n0x%x", get_sp());
}

I tried it with Geany but it doesn't works!! Then I follow the compiler log and I changed the code in this way:

#include <stdio.h>

unsigned long get_sp(void);

int main(void){
printf("\n0x%ld", get_sp());
return 0;
}


unsigned long get_sp(void){
    unsigned long stp;
    __asm{
        mov eax, esp
    }
}

this time I have no problems with the main but the other function is a tragedy!!! It doesn't recognize __asm. unknown type name 'mov'.... unused variable 'eax'... It seems like it wants __asm() instead of __asm{}, like a normal call of a function. Somebody can help me? PS I have debian 64....it can have some problems with the 64 architecture??

like image 470
nicanz Avatar asked Oct 19 '22 09:10

nicanz


1 Answers

The correct GCC code would be

__attribute__((noinline,noclone))
unsigned long get_sp(void) {
  unsigned long stp;
  asm(
    // For x86_64: "movq %%rsp, %0"
    "movl %%esp, %0"
    : "=r"(stp)
  );
  return stp;
}
like image 194
yugr Avatar answered Oct 22 '22 00:10

yugr