Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing function with inline assembly C

I've got a function whose inner code I want to convert into assembly (for various reasons):

int foo(int x, int y, int z);

I generated the assembly code using:

clang -S -mllvm --x86-asm-syntax=intel foo.c

The assembly output: foo.s starts off with something like:

_foo:                               ## @foo
    .cfi_startproc
## BB#0:
    push    RBP
Ltmp2:
    .cfi_def_cfa_offset 16
...

I assume this is the corresponding assembly code for that function. My question is, what part of the assembly output should I copy into the C code (I'm trying to use inline assembly) so that the function would work? The code should look like:

int foo(int x, int y, int z) {
   __asm__("..."); // <-- What goes inside?
}

Thanks

like image 205
Peter Avatar asked Nov 11 '22 07:11

Peter


1 Answers

You have to see the disassembly of that function and write the __asm__. For example below code

int foo(int x, int y, int z) {
x = y+z; return x; }

will yeild a disassembly of following :

int foo(int x, int y, int z) {
  push        ebp  
  mov         ebp,esp 
  sub         esp,0C0h 
  push        ebx  
  push        esi  
  push        edi  
  lea         edi,[ebp-0C0h] 
  mov         ecx,30h 
  mov         eax,0CCCCCCCCh 
  rep stos    dword ptr es:[edi] 

  x = y+z;
  mov         eax,dword ptr [y] 
  add         eax,dword ptr [z] 
  mov         dword ptr [x],eax 

  return x;
  mov         eax,dword ptr [x] 
}

so you have to add below for statement x= y+z,

 mov         eax,dword ptr [y] 
 add         eax,dword ptr [z] 
 mov         dword ptr [x],eax 
like image 73
Balu Avatar answered Nov 15 '22 10:11

Balu