How to compile an assembly whose entry point is not the main one in gcc?

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

I compile with -nostdlib :

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

What is wrong here?

BTW, is it possible to make entry points with names other than main and _start ?

+4
source share
2 answers

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

The reason your segfaults program is because, since you are not using the standard library, there is nowhere to go back to ( retq ). Instead, call exit using the correct syscall (in this case it is 60, which is placed in rax , the first (and only) parameter is placed in 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 make system calls on x86_64

+5
source

You can set an 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, this is not the entry point to your compiled application, although this is a function that will be called from the entry point. The entry point itself, if you are compiling C or C ++ code, is defined somehow like Start.S deep in the glibc source tree and is platform dependent. If you program direct assembly, I don’t know what is actually happening.

+1
source

All Articles