我也一直在尝试自学一些入门级的汇编编程,但我遇到了类似的问题。我最初是使用 nasm 和 elf 编译的,但是当我尝试使用 ld 链接目标文件并创建可执行文件时,它不起作用。
我认为您的主要问题"what would the problem be then?" [to get this to run on 64bit MacOSX] 的答案是:您正在使用-f macho32 但希望它在64 位机器上运行,您需要将命令选项更改为-f macho64。 当然,这并不能解决您的汇编代码是为不同架构编写的事实(稍后会详细介绍)。
我发现 this handy answer 在正确的命令上用于在此实例中编译和链接您的代码(在您重构汇编代码以使用正确的语法而不是 duskwuff 声明的 *nix 之后):nasm -f macho64 main.asm -o main.o && ld -e _main -macosx_version_min 10.8 -arch x86_64 main.o -lSystem
经过一番搜索,这是我学到的……
- 在 Mac 64 位上,使用
as 汇编程序而不是 nasm 可能会更好(如果您想要更原生的东西),但如果您想要更便携的代码(了解差异)。
-
nasm 默认没有安装 macho64 输出类型
- 组装是一件很痛苦的事情(除了这个)
现在我的学习咆哮已经结束了......
这是应该在 MacOSX 64 上使用 nasm 运行的代码(如果您已将 nasm 更新为 macho64,归功于 Dustin Schultz):
section .data
hello_world db "Hello World!", 0x0a
section .text
global start
start:
mov rax, 0x2000004 ; System call write = 4
mov rdi, 1 ; Write to standard out = 1
mov rsi, hello_world ; The address of hello_world string
mov rdx, 14 ; The size to write
syscall ; Invoke the kernel
mov rax, 0x2000001 ; System call number for exit = 1
mov rdi, 0 ; Exit success = 0
syscall ; Invoke the kernel
我与 MacOSX64 原生的 as 汇编程序一起使用的工作代码:
.section __TEXT,__text
.global start
start:
movl $0x2000004, %eax # Preparing syscall 4
movl $1, %edi # stdout file descriptor = 1
movq str@GOTPCREL(%rip), %rsi # The string to print
movq $100, %rdx # The size of the value to print
syscall
movl $0, %ebx
movl $0x2000001, %eax # exit 0
syscall
.section __DATA,__data
str:
.asciz "Hello World!\n"
编译命令:as -arch x86_64 -o hello_as_64.o hello_as_64.asm
链接命令:ld -o hello_as_64 hello_as_64.o
执行命令:./hello_as_64
我在旅途中发现的一些有用资源:
ASOSX 汇编器参考:https://developer.apple.com/library/mac/documentation/DeveloperTools/Reference/Assembler/Assembler.pdf
在 Mac OSX 上编写 64 位程序集:http://www.idryman.org/blog/2014/12/02/writing-64-bit-assembly-on-mac-os-x/
无法使用 ld 链接目标文件:
Can't link object file using ld - Mac OS X
OSX i386 SysCalls:http://www.opensource.apple.com/source/xnu/xnu-1699.26.8/osfmk/mach/i386/syscall_sw.h
OSX 主系统调用定义:http://www.opensource.apple.com/source/xnu/xnu-1504.3.12/bsd/kern/syscalls.master
OSX 系统调用:https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/syscall.2.html