Question

I wrote here is a simple code:

 printf.asm

 [EXTERN main]
 section .text
 global _start     
 _start:
       call main
       add esp, 8
       mov eax, 1
       xor ebx, ebx
       int 80h

and main.c

#include <stdio.h>

 int main()
 {
     char* str = "print from C :\\)";
     printf("%s", str);
 }

I compile code like this:

nasm -g -f elf printf.asm -o printf.o

gcc -c -o main.o main.c

ld -o printf printf.o main.o -lc -I/lib/ld-linux.so.2

And run:

./printf

On the terminal nothing printed. Why ?

when i doing linking with following command ld -Ttext 0x1000 -o printf printf.o main.o -lc -I/lib/ld-linux.so.2 , it displays "Killed" string. How to solve this problem ?

Code successfully earned just added a newline character in the printf function: printf("%s\n", str);. Thanks all, the problem is solved.

Was it helpful?

Solution 3

Mixed source with NASM-entrypoint works in this way (32-bit on my 64-bit-Linux):

printf.asm:

global _start
extern main
extern fflush

section .text
 _start:
    call main

    push 0                      ; fflush (stdout)
    call fflush
    add esp, 4

    mov ebx,0                   ; exit code, 0=normal
    mov eax,1                   ; exit command to kernel
    int 0x80                    ; interrupt 80 hex, call kernel

main.c

#include <stdio.h>

extern int main (void)
{
    char* str = "print from C :\\)\n";
    printf("%s", str);
    return 0;
}

build:

nasm -felf32 -oprintf.o printf.asm
gcc -c -m32 -omain.o main.c
ld -I/lib32/ld-linux.so.2 -lc -m elf_i386 -o printf printf.o main.o

I guess you can manage the changes for 32-bit-Linux :-)

OTHER TIPS

You are attempting to call main() without first executing the C startup code. You should not do that. Basically, the C startup initialises the stack and variable storage before jumping to main().

You can call assembly language code from main() as this allows the startup to do its thing first.

You are writing _start yourself which is a libc startup function .this is the reason you cannot link the code correctly.also you should not touch _start otherwise you will break libc. For running a code before main you may use ''attribute ((constructor))'' (it is a gcc feature and it's not available in other compilers).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top