Je Rog
Je Rog

Reputation: 6031

How to compile assembly whose entry point is not main with gcc?

.text
    .globl _start
_start:
     pushq %rbp
     movq %rsp,%rbp
     movq $2, %rax
     leaveq
     retq

I'm compiling with -nostdlib:

[root@ test]# gcc -nostdlib -Wall minimal.S &&./a.out 
Segmentation fault

What's wrong here?

BTW,is it possible to make the entry point other names than main and _start?

Upvotes: 5

Views: 5663

Answers (2)

Justin Aquadro
Justin Aquadro

Reputation: 2310

You can set the entry point by passing an option to the linker

http://sca.uwaterloo.ca/coldfire/gcc-doc/docs/ld_24.html

To do this with gcc, you would do something like...

gcc all_my_other_gcc_commands -Wl,-e,start_symbol

main is different, it is not the entry point to your compiled application, although it is the function that will be called from the entry point. The entry point itself, if you're compiling C or C++ code, is defined in something like Start.S deep in the source tree of glibc, and is platform-dependent. If you're programming straight assembly, I don't know what actually goes on.

Upvotes: 1

user786653
user786653

Reputation: 30480

As @jaquadro mentions, you can specify the entry point on the command line to the linker (or use a link script): gcc -Wall -Wextra -nostdlib -Wl,-eMyEntry minimal.S && ./a.out

The reason your program segfaults is, that since you're not using the standard library there is nowhere to return back to (retq). Instead call exit using the correct syscall (in this case it is 60, which is put into rax, the first (and only) parameter is put into rdi.

Example:

.text
.globl MyEntry
MyEntry:
    # Use Syscall 60 (exit) to exit with error code 42
    movq $60, %rax
    movq $42, %rdi
    syscall

Related question on how to perform syscalls on x86_64

Upvotes: 6

Related Questions