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

自古美人都是妖i 提交于 2020-01-14 12:55:51

问题


.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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/6563663/how-to-compile-assembly-whose-entry-point-is-not-main-with-gcc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!