Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the output binary of ld can not be executed?

(I am using Ubuntu 18.04 x86-64)

These are the two source files of my program:

//main.c
#include "stdio.h"
int sum(int *a, int n);

int array[2] = {1, 2};

int main()
{
        int val = sum(array,2);
        printf("%d\n", val);
        return 0;
}
//sum.c
int sum(int *a, int n)
{
        int i = 0,s =0;
        for(;i<n;i++)
                s+=a[i];
        return s;
}

I generated the executable by the following steps:

# preprocessing
gcc -E main.c -o main.i 
gcc -E sum.c -o sum.i

# compilation
gcc -Og -S main.i -o main.s 
gcc -Og -S sum.i -o sum.s

# assembling
as main.s -o main.o
as sum.s -o sum.o

# linking
ld -o prog sum.o main.o -lc --entry main

But prog can not be run:

$ ./prog
-bash: ./prog: No such file or directory
$ file ./prog
prog: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib/ld6, not stripped
$ stat prog
  File: prog
  Size: 6424        Blocks: 16         IO Block: 4096   regular file
Device: 801h/2049d  Inode: 3153139     Links: 1
Access: (0777/-rwxrwxrwx)  Uid: ( 1000/       u)   Gid: ( 1000/       u)
Access: 2021-01-22 17:41:02.516854257 +0800
Modify: 2021-01-22 17:31:02.969230783 +0800
Change: 2021-01-22 17:40:57.432364965 +0800
 Birth: -

I wonder what went wrong that prevents me from executing the file.

like image 771
Name Null Avatar asked Nov 19 '25 00:11

Name Null


1 Answers

If you run ldd prog you will see /lib/ld64.so.1 => /lib64/ld-linux-x86-64.so.2. The loader /lib/ld64.so.1 does not exists and you get a No such file or directory error. If you add --dynamic-linker=/lib64/ld-linux-x86-64.so.2 to your linking options the program can be executed. Also see this answer.

Edit:

You can see the arguments used by gcc by executing gcc -v main.c sum.c -o program. I used that output for finding the missing linking arguments. When linking with ld -o prog sum.o main.o -lc --dynamic-linker=/lib64/ld-linux-x86-64.so.2 /usr/lib/gcc/x86_64-linux-gnu/8/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/8/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/8/crtbeginS.o -lc /usr/lib/gcc/x86_64-linux-gnu/8/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/8/../../../x86_64-linux-gnu/crtn.o there was no segmentation anymore.

like image 56
Antonio Avatar answered Nov 21 '25 12:11

Antonio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!