为什么osx 64位asm syscall段错误

时间:2015-09-10 06:15:40

标签: macos assembly segmentation-fault system-calls

我正在尝试在OSX上的汇编中编写x86-64 hello世界,但每当我编写一个系统调用时,它都是segfaulting。我已经通过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");
}

编译时的C块生成以下asm:

        .section        __TEXT,__text,regular,pure_instructions
        .globl  _main
        .align  4, 0x90
_main:                                  ## @main
        .cfi_startproc
## BB#0:
        pushq   %rbp
Ltmp2:
        .cfi_def_cfa_offset 16
Ltmp3:
        .cfi_offset %rbp, -16
        movq    %rsp, %rbp
Ltmp4:
        .cfi_def_cfa_register %rbp
        leaq    L_.str(%rip), %rcx
        movq    %rcx, -8(%rbp)
        ## InlineAsm Start
        movq $33554436, %rax
movq $1, %rdi
movq %rcx, %rsi
movq $12, %rdx
syscall

        ## InlineAsm End
        movq    %rcx, -16(%rbp)
        xorl    %eax, %eax
        popq    %rbp
        ret
        .cfi_endproc

        .section        __TEXT,__cstring,cstring_literals
L_.str:                                 ## @.str
        .asciz   "Hello World\n"

1 个答案:

答案 0 :(得分:0)

在这种情况下,这是一个简单的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!!!