Feeds:
Posts
Comments

Archive for December 27th, 2018

You can call C function from assembly but you can’t compile the object file with ‘ld’ command. You have to use ‘GCC’. If you want to use ‘GCC’ then you have to change the ‘_start’ with ‘main’.
Mostly, you will use:

section .text
global _start
_start:

But, if you use ‘gcc’ then you have to change it to become:

section .text
global _main
main:

Let’s try.
Type the codes below and save it to ‘hello.asm’.

1 extern printf
2
3 section .text
4 global main
5
6 main:
7 push ebp
8 mov ebp,esp
9
10 push msg ;move msg to stack
11 call printf ;call printf
12
13 mov esp,ebp
14 pop ebp
15 ret
16
17 section .data
18 msg db 'Hello, world.',0xA
19

Assemble it with ‘nasm’ to get the object file.

$ nasm -f elf32 hello.asm -o hello.o

Then compile it with gcc.

$ gcc hello.o -o hello
$ ./hello
Hello, world.
$

Type the code below and save it to ‘hello2.asm’.

1 extern printf
2
3 section .text
4 global main
5
6 main:
7 sub esp,4 ;allocate 4 byte in stack
8
9 lea eax,[mystring]
10 mov [esp],eax ; pointer to string
11
12 call printf ; call printf
13
14 add esp,4
15
16 ret
17
18 section .data
19 mystring db 'Hello World',0xA
20

Assemble the code to get the object code.

$ nasm -f elf32 hello2.asm -o hello2.o

Compile the object code with gcc

$ gcc hello2.o -o hello2
$ ./hello2
Hello World
$

 

Read Full Post »