clinuxassemblyx86

Is it possible to convert C to asm without link libc on Linux?


Test platform is on Linux 32 bit. (But certain solution on windows 32 bit is also welcome)

Here is a c code snippet:

int a = 0;
printf("%d\n", a);

And if I use gcc to generate assembly code

gcc -S test.c

Then I will get:

      movl    $0, 28(%esp)
      movl    28(%esp), %eax
      movl    %eax, 4(%esp)
      movl    $.LC0, (%esp)
      call    printf
      leave
      ret

And this assembly code needs linking to libc to work(because of the call printf)

My question is :

Is it possible to convert C to asm with only explicit using system call automatically, without using libc?

Like this:

    pop ecx        
    add ecx,host_msg-host_reloc
    mov eax,4
    mov ebx,1
     mov edx,host_msg_len
    int 80h
    mov eax,1
     xor ebx,ebx
     int 80h

Directly call the int 80h software interrupt.

Is it possible? If so, is there any tool on this issue?

Thank you!


Solution

  • Not from that source code. A call to printf() cannot be converted by the compiler to a call to the write system call - the printf() library function contains a significant amount of logic which is not present in the system call (such as processing the format string and converting integer and floating-point numbers to strings).

    It is possible to generate system calls directly, but only by using inline assembly. For instance, to generate a call to _exit(0) (not quite the same as exit()!), you would write:

    #include <asm/unistd.h>
    ...
    int retval;
    asm("int $0x80" : "=a" (retval) : "a" (__NR_exit_group), "b" (0) : "memory");
    

    For more information on GCC inline assembly, particularly on the constraints I'm using here to map variables to registers, please read the GCC Inline Assembly HOWTO. It's rather old, but still perfectly relevant.

    Note that doing this is not recommended. The exact calling conventions for system calls (e.g, which registers are used for the call number and arguments, how errors are returned, etc) are different on different architectures, operating systems, and even between 32-bit and 64-bit x86. Writing code this way will make it very difficult to maintain.