Macos 为什么osx 64位asm系统调用SEGFULT

Macos 为什么osx 64位asm系统调用SEGFULT,macos,assembly,segmentation-fault,x86-64,system-calls,Macos,Assembly,Segmentation Fault,X86 64,System Calls,我正试图在OSX上的汇编中编写x86-64 hello world,但每当我进行系统调用来编写时,它都会出错。我已经通过Gnu C内联汇编尝试了等效的系统调用,但效果良好,所以我完全搞不清楚: .section __TEXT,__text,regular,pure_instructions .globl _main .align 4, 0x90 _main: .cfi_startproc movq

我正试图在OSX上的汇编中编写x86-64 hello world,但每当我进行系统调用来编写时,它都会出错。我已经通过Gnu C内联汇编尝试了等效的系统调用,但效果良好,所以我完全搞不清楚:

        .section        __TEXT,__text,regular,pure_instructions
        .globl  _main
        .align  4, 0x90
_main:
        .cfi_startproc
        movq 0x2000004, %rax
        movq 1, %rdi
        leaq _hi(%rip), %rsi
        movq 12, %rdx
        syscall

        xor   %rax, %rax
        ret
        .cfi_endproc

        .section        __DATA,__data
        .globl  _hi
_hi:
        .asciz   "Hello world\n"
这是基于以下工作正常的Gnu C:

#include <string.h>

int main() {
  char *hw = "Hello World\n";
  unsigned long long result;
  asm volatile ("movq %1, %%rax\n"
       "movq %2, %%rdi\n"
       "movq %3, %%rsi\n"
       "movq %4, %%rdx\n"
       "syscall\n"
       : "=rax" (result)
       : "Z" (0x2000004),
         "Z" (1),
         "r" (hw),
         "Z" (12)
       : "rax", "rdi", "rsi", "rdx");
}
在本例中,这里是一个简单的64位“Hello World”(或Hello StackOverflow)。它应该建立在OSX之上。试一试:

section .data
    string1 db  0xa, "  Hello StackOverflow!!!", 0xa, 0xa, 0
    len equ $ - string1

section .text
    global _start

    _start:
    ; write string to stdout
        mov     rax, 1              ; set write to command
        mov     rsi, string1        ; string1 to source index
        mov     rdi, rax            ; set destination index to 1 (stdout) already in rax
        mov     rdx, len            ; set length in rdx
        syscall                     ; call kernel

        ; exit
        xor     rdi,rdi             ; zero rdi (rdi hold return value)
        mov     rax, 0x3c           ; set syscall number to 60 (0x3c hex)
        syscall                     ; call kernel

; **Compile/Output**
;
;     $ nasm -felf64 -o hello-stack_64.o hello-stack_64.asm
;     $ ld -o hello-stack_64 hello-stack_64.o

;     $ ./hello-stack_64
;
;       Hello StackOverflow!!!

您的问题在于以下几行:

movq 0x2000004, %rax
movq 1, %rdi
leaq _hi(%rip), %rsi
movq 12, %rdx
请注意,使用at&t语法,如果要使用常量,必须在它们前面加上$(美元符号),否则就是引用内存地址。如果没有$符号,您的值就是直接间接地址

例如:

movq 0x2000004, %rax
尝试将四字从内存地址
0x2000004
中移动并放入
%rax

您可能只需要修改代码,使其看起来像:

movq $0x2000004, %rax
movq $1, %rdi
leaq _hi(%rip), %rsi
movq $12, %rdx
请注意,我在每个常量的开头添加了一个美元符号

movq $0x2000004, %rax
movq $1, %rdi
leaq _hi(%rip), %rsi
movq $12, %rdx