macOS汇编:Hello World
你好,世界
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
.section __TEXT,__text,regular,pure_instructions
.build_version macos, 15, 0 sdk_version 15, 2
.globl _main ; -- Begin function main
.p2align 2
_main: ; @main
.cfi_startproc
; %bb.0:
sub sp, sp, #32
stp x29, x30, [sp, #16] ; 16-byte Folded Spill
add x29, sp, #16
.cfi_def_cfa w29, 16
.cfi_offset w30, -8
.cfi_offset w29, -16
mov w8, #0 ; =0x0
str w8, [sp, #8] ; 4-byte Folded Spill
stur wzr, [x29, #-4]
adrp x0, l_.str@PAGE
add x0, x0, l_.str@PAGEOFF
bl _printf
ldr w0, [sp, #8] ; 4-byte Folded Reload
ldp x29, x30, [sp, #16] ; 16-byte Folded Reload
add sp, sp, #32
ret
.cfi_endproc
; -- End function
.section __TEXT,__cstring,cstring_literals
l_.str: ; @.str
.asciz "Hello, World!\n"
.subsections_via_symbols
gcc -S hello.c -o hello.s
gcc -c hello.s -o hello.o
gcc hello.o -o hello
./hello
hexdump -C hello.o
实验
这段代码创建了一个“你好,世界!”程序。它使用系统调用将消息写入控制台,然后退出。.text
部分包含可执行指令,从 _start
开始。它首先设置 sys_write
调用(打印到标准输出),然后设置 sys_exit
调用(干净退出)。.data
部分存储消息本身并计算其长度。
.global _start
.text
_start:
// Write "Hello, World!" to stdout
mov x8, #64 // syscall number for write (sys_write)
mov x0, #1 // file descriptor 1 (stdout)
ldr x1, =msg // address of the message
mov x2, #14 // length of the message
svc #0 // invoke syscall
// Exit the program
mov x8, #93 // syscall number for exit (sys_exit)
mov x0, #0 // exit code 0
svc #0 // invoke syscall
.data
msg:
.asciz "Hello, World!\n"
as -o hello.o hello.s
% clang -o hello hello.o -nostdlib -e _start -Wl,-platform_version,macos,15.0,15.0 -arch arm64
% ./hello
zsh: invalid system call ./hello