Segmentation Fault on simple ASM code

拈花ヽ惹草 提交于 2019-12-25 12:22:11

问题


For my Question when I tried to create a example of NASM under ubuntu 64-bit version and execute it after assembled and linked into ELF. It return error messages as below when I execute

NASM -f elf64 -o firstasm.o firstasm.asm ld -o firstasm firstasm.o firstasm

Segmentation fault (core dumped)

My NASM code would be below where I tried to perform simple write() and exit() function

section .data ;Data segment

msg db "This line is test", 0x0a 

section .text ;text segment
global _start  ;Default entry point for ELF linking

_start:

; SYSCALL : write (1,msg,14)
xor rax,rax
xor rbx,rbx
xor rcx,rcx
xor rdx,rdx
mov rax,64 ; make a syscall write 4
mov rbx,1 ; put 1 into rbx and also stdout is 1
mov rcx,msg ;put address of string in rcx
mov rdx,19 ; put length of string into rdx
int 0x80   ; call kernel to made syscall

; SYSCALL : exit(0)
xor rax,rax
xor rbx,rbx
mov rax,93 ; make a syscall exit 93
mov rbx, 0  ; store 0 argument into rbx, success to exit
int 0x80

Can someone pointed me what is problem to my NASM code and suggestions to fix the problem of "Segmentation fault (core dumped)". Appreciate thanks to anyone could help.


回答1:


Uh, where are you getting the system call numbers? Are you pulling them out of the air?

64bit sys_exit = 60 32bit sys_exit = 1

64bit sys_write = 1 32bit sys_write = 4

Linux 64-bit System Call List

Linux 32-bit System Call List

Linux System Call Table for x86_64

The above link will show what registers are used for what.

the 32 bit system call - int 80 does not use the 64bit registers and the register parameters are different. The 64 bit system call is - syscall.

32 bit sys_exit:

mov     ebx, ERR_CODE
mov     eax, sys_exit  ; 1
int     80h

64 bit sys_exit:

mov     rdi, ERR_CODE
mov     rax, sys_exit  ; 60
syscall

see the difference?

if you want to create an inc file of the system call names and numbers for YOUR system (maybe they are different for some reason)

grep __NR /usr/include/asm/unistd_64.h | grep define | sed -e 's/\#/\%/' -e 's/__NR_/sys_/' > unistd_64.inc

of course, adjust the path to unistd_64.h for your system. It will be the same for 32 bit but the file is called unistd_32.h I believe.

Now that I showed you the difference between the exit sys call, and with the provided links, you can fix your write system call to be correct.



来源:https://stackoverflow.com/questions/21119684/segmentation-fault-on-simple-asm-code

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