How does $ work in NASM, exactly? 解释了$ - msg 如何让 NASM 为您计算字符串长度作为汇编时间常数,而不是对其进行硬编码。
我最初是为SO Docs (topic ID: 1164, example ID: 19078) 写的其余部分,重写了@runner 的一个基本的注释较少的示例。 这看起来比part of my answer to another question 更适合放置它我之前在 SO docs 实验结束后移动了它。
通过将参数放入寄存器,然后运行int 0x80(32 位模式)或syscall(64 位模式)来进行系统调用。 What are the calling conventions for UNIX & Linux system calls on i386 and x86-64 和 The Definitive Guide to Linux System Calls。
将int 0x80 视为跨越用户/内核权限边界“调用”内核的一种方式。 内核根据int 0x80 时寄存器中的值执行操作执行,然后最终返回。返回值在 EAX 中。
当执行到达内核的入口点时,它会查看 EAX 并根据 EAX 中的调用号分派到正确的系统调用。来自其他寄存器的值作为函数参数传递给该系统调用的内核处理程序。 (例如 eax=4 / int 0x80 将让内核调用其 sys_write 内核函数,实现 POSIX write 系统调用。)
另请参阅What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code? - 该答案包括查看int 0x80“调用”的内核入口点中的asm。 (也适用于 32 位用户空间,而不仅仅是 64 位,您不应该使用 int 0x80)。
如果您还不了解低级 Unix 系统编程,您可能只想在 asm 中编写函数,这些函数接受 args 并返回一个值(或通过指针 arg 更新数组)并从 C 或 C++ 程序调用它们.然后,您只需担心学习如何处理寄存器和内存,而无需学习 POSIX 系统调用 API 和使用它的 ABI。这也使得将您的代码与 C 实现的编译器输出进行比较变得非常容易。编译器通常在编写高效代码方面做得很好,但是are rarely perfect。
libc 为系统调用提供包装函数,因此编译器生成的代码将使用call write,而不是直接使用int 0x80 调用它(或者如果您关心性能,sysenter)。 (在 x86-64 代码中,use syscall for the 64-bit ABI。)另见syscalls(2)。
系统调用记录在第 2 节手册页中,例如 write(2)。有关 libc 包装函数和底层 Linux 系统调用之间的差异,请参阅注释部分。请注意sys_exit 的包装器是_exit(2),而不是exit(3) ISO C 函数,它首先刷新 stdio 缓冲区和其他清理。还有一个exit_group 系统调用ends all threads。 exit(3) 实际上使用了它,因为单线程进程没有缺点。
这段代码进行了 2 次系统调用:
我对它进行了大量评论(以至于它开始掩盖实际代码而没有颜色语法突出显示)。这是向初学者指出问题的尝试,而不是您应该如何正常注释您的代码。
section .text ; Executable code goes in the .text section
global _start ; The linker looks for this symbol to set the process entry point, so execution start here
;;;a name followed by a colon defines a symbol. The global _start directive modifies it so it's a global symbol, not just one that we can CALL or JMP to from inside the asm.
;;; note that _start isn't really a "function". You can't return from it, and the kernel passes argc, argv, and env differently than main() would expect.
_start:
;;; write(1, msg, len);
; Start by moving the arguments into registers, where the kernel will look for them
mov edx,len ; 3rd arg goes in edx: buffer length
mov ecx,msg ; 2nd arg goes in ecx: pointer to the buffer
;Set output to stdout (goes to your terminal, or wherever you redirect or pipe)
mov ebx,1 ; 1st arg goes in ebx: Unix file descriptor. 1 = stdout, which is normally connected to the terminal.
mov eax,4 ; system call number (from SYS_write / __NR_write from unistd_32.h).
int 0x80 ; generate an interrupt, activating the kernel's system-call handling code. 64-bit code uses a different instruction, different registers, and different call numbers.
;; eax = return value, all other registers unchanged.
;;;Second, exit the process. There's nothing to return to, so we can't use a ret instruction (like we could if this was main() or any function with a caller)
;;; If we don't exit, execution continues into whatever bytes are next in the memory page,
;;; typically leading to a segmentation fault because the padding 00 00 decodes to add [eax],al.
;;; _exit(0);
xor ebx,ebx ; first arg = exit status = 0. (will be truncated to 8 bits). Zeroing registers is a special case on x86, and mov ebx,0 would be less efficient.
;; leaving out the zeroing of ebx would mean we exit(1), i.e. with an error status, since ebx still holds 1 from earlier.
mov eax,1 ; put __NR_exit into eax
int 0x80 ;Execute the Linux function
section .rodata ; Section for read-only constants
;; msg is a label, and in this context doesn't need to be msg:. It could be on a separate line.
;; db = Data Bytes: assemble some literal bytes into the output file.
msg db 'Hello, world!',0xa ; ASCII string constant plus a newline (0x10)
;; No terminating zero byte is needed, because we're using write(), which takes a buffer + length instead of an implicit-length string.
;; To make this a C string that we could pass to puts or strlen, we'd need a terminating 0 byte. (e.g. "...", 0x10, 0)
len equ $ - msg ; Define an assemble-time constant (not stored by itself in the output file, but will appear as an immediate operand in insns that use it)
; Calculate len = string length. subtract the address of the start
; of the string from the current position ($)
;; equivalently, we could have put a str_end: label after the string and done len equ str_end - str
请注意,我们不将字符串长度存储在数据内存中的任何位置。它是一个汇编时间常数,因此将其作为直接操作数比加载更有效。我们也可以使用三个push imm32 指令将字符串数据压入堆栈,但过度膨胀代码大小并不是一件好事。
在 Linux 上,您可以将此文件保存为 Hello.asm 并使用以下命令从中构建 32 位可执行文件:
nasm -felf32 Hello.asm # assemble as 32-bit code. Add -Worphan-labels -g -Fdwarf for debug symbols and warnings
gcc -static -nostdlib -m32 Hello.o -o Hello # link without CRT startup code or libc, making a static binary
请参阅this answer,了解有关将程序集构建为 32 位或 64 位静态或动态链接的 Linux 可执行文件、NASM/YASM 语法或带有 GNU as 指令的 GNU AT&T 语法的更多详细信息。 (关键点:确保在 64 位主机上构建 32 位代码时使用-m32 或等效项,否则在运行时会出现令人困惑的问题。)
您可以使用strace 跟踪其执行情况,以查看它进行的系统调用:
$ strace ./Hello
execve("./Hello", ["./Hello"], [/* 72 vars */]) = 0
[ Process PID=4019 runs in 32 bit mode. ]
write(1, "Hello, world!\n", 14Hello, world!
) = 14
_exit(0) = ?
+++ exited with 0 +++
将此与动态链接进程的跟踪(如 gcc 从 hello.c 或运行 strace /bin/ls)进行比较,以了解动态链接和 C 库启动在后台发生了多少事情。
stderr 上的跟踪和 stdout 上的常规输出都到这里的终端,因此它们干扰了write 系统调用的行。如果您关心,请重定向或跟踪到文件。请注意,这如何让我们轻松查看系统调用返回值,而无需添加代码来打印它们,实际上甚至比使用常规调试器(如 gdb)单步执行并查看 eax 更容易。有关 gdb asm 提示,请参阅 x86 tag wiki 的底部。 (标签 wiki 的其余部分充满了优质资源的链接。)
这个程序的 x86-64 版本非常相似,将相同的参数传递给相同的系统调用,只是在不同的寄存器中,并且使用 syscall 而不是 int 0x80。请参阅What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code? 的底部以获取编写字符串并以 64 位代码退出的工作示例。
相关:A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux。您可以运行的最小二进制文件,它只进行 exit() 系统调用。那是关于最小化二进制大小,而不是源大小,甚至只是实际运行的指令数量。