Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 517
Je Rog Avatar asked Jul 03 '11 15:07

Je Rog


2 Answers

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

like image 151
user786653 Avatar answered Nov 15 '22 06:11

user786653


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.

like image 35
Justin Aquadro Avatar answered Nov 15 '22 07:11

Justin Aquadro