executing assembly code in c

15,056

Solution 1

The ability to do this is compiler-specific. Gcc allows this using its asm keyword extension, while Visual studio implements a different extension.

Note that, beside the obvious problem with non-portability to other architectures, including any inline assembly can reduce performance because the compiler is unable to analyze the assembly to determine whether it's side-effect-free, safe for inlining, whether it accesses global resources, and so on.

Solution 2

Another method if e.g. using gcc, is to first compile some very trivial function without optimizations:

int foo(int a, int b) {
  return a+(b<<3);
}

with gcc -S foo.c

and use the foo.s as template. One can later compile and link those files with gcc main.c foo.s (and be sure to delete the foo.c file / rename foo.s to something else)

From that particular function one can observe, where the compiler puts the result and in which addresses or registers the compiler puts the first and second arguments.

It's slightly faster approach than learning asm-templates with read,write, clobber lists.

Solution 3

You really need to "put" asm source in Nasm syntax "in" your C source program? Fergedit. lcc maybe... If you want to "execute" your asm program from your C program...

    global getbrk
    section .text
    getbrk:
        push ebx ; C likes it saved
        mov eax, 45 ; __NR_brk
        xor ebx, ebx ; get current break
        int 80h
        pop ebx
        ret

assemble nasm -f elf getbrk.asm, put sp=getbrk(); in your C file, compile gcc -m32 -O3 -o myprog myprog.c getbrk.o

Or just sp=sbrk(0); in your C program and skip the asm... won't be any more portable than doing it with int 80h. (but what fun would that be?) :)

Solution 4

void function(void){

   void *sp
   __asm__ volatile(
   "movl $0x2d, %%eax;"
   "movl $0, %%ebx;"
   "int $0x80"
   :"=a"(sp)
   :
   :"%ebx"
   );

   fprintf(stderr, "system break: %p\n",sp);
   }

This is my answer :)

Share:
15,056
Weigel Gram
Author by

Weigel Gram

Updated on June 25, 2022

Comments

  • Weigel Gram
    Weigel Gram almost 2 years

    I want to know if there is a way of calling in a .c assembly code? I want to put this code in my .c file

    The assembly code i want to execute in .c file to return the address

    1. mov eax, 0x2d
    2. mov ebx, 0
    3. int 0x80
    

    I know the answer is put eax.

    This is the part of .c file:

    1. void function(void)
    2. {
    3. void *sp;
    4. sp = eax;
    5. fprintf(stderr, "system break:   %p\n", sp);
    6. }
    

    How can I do it?