Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one link NASM program to libc via ld?

I have a following program for NASM (ArchLinux i686)

SECTION .data
LC1: db "library call", 0

SECTION .text
extern exit
extern printf

;global main
;main:
global _start
_start:
push    LC1
call    printf

push    0
call    exit

Which is assembled with command:

nasm -f elf libcall.asm

If to comment two lines with _start and uncomment two lines with main, then assemble and link with the command:

gcc libcall.o -o libcall

Then the program runs OK. But if to assemble the code with _start entry point and link with the command:

ld libcall.o -o libcall -lc

Then after launching the program in bash (via the command ./libcall) the following error message is returned:

bash: ./libcall: No such file or directory

Although the libcall file does exist. objdump shows the following:

[al libcall ]$ objdump -d libcall

libcall:     file format elf32-i386


Disassembly of section .plt:

08048190 <printf@plt-0x10>:
 8048190:   ff 35 78 92 04 08       pushl  0x8049278
 8048196:   ff 25 7c 92 04 08       jmp    *0x804927c
 804819c:   00 00                   add    %al,(%eax)
    ...

080481a0 <printf@plt>:
 80481a0:   ff 25 80 92 04 08       jmp    *0x8049280
 80481a6:   68 00 00 00 00          push   $0x0
 80481ab:   e9 e0 ff ff ff          jmp    8048190 <printf@plt-0x10>

080481b0 <exit@plt>:
 80481b0:   ff 25 84 92 04 08       jmp    *0x8049284
 80481b6:   68 08 00 00 00          push   $0x8
 80481bb:   e9 d0 ff ff ff          jmp    8048190 <printf@plt-0x10>

Disassembly of section .text:

080481c0 <_start>:
 80481c0:   68 88 92 04 08          push   $0x8049288
 80481c5:   e8 d6 ff ff ff          call   80481a0 <printf@plt>
 80481ca:   6a 00                   push   $0x0
 80481cc:   e8 df ff ff ff          call   80481b0 <exit@plt>

How the NASM assembly code should properly be linked with to libc via ld?

like image 889
Al Berger Avatar asked Feb 08 '16 16:02

Al Berger


1 Answers

There are some parts of libc/crt that come in object files that you also need to link. Additionally you need to specify some options such as the dynamic loader (aka. interpreter) to use (which is probably the reason for your issue.) Just use gcc to do right thing for you. If you are interested you can run with gcc -v and then you will see the horrible command line it uses to link. You have been warned ;)

PS: you should use the main entry point that you have commented out.

like image 189
Jester Avatar answered Sep 28 '22 19:09

Jester