32位Linux下NASM汇编寄存器赋值差异及用途疑问
int 80h System Calls Great question—this is a super common gotcha when you're first learning NASM for 32-bit Linux! Let's break down exactly what's going on here, because those register assignments aren't arbitrary at all.
The int 80h System Call Convention
On 32-bit Linux, the int 80h instruction triggers a system call, which asks the kernel to perform a privileged operation (like writing to stdout, reading a file, or exiting a program). For this to work, each register has a strict, predefined role—you can't just assign values to random registers and expect the kernel to understand what you want.
Here's the key convention for the sys_write system call (which is what your first code snippet is using):
eax: Must hold the system call number.sys_writeis assigned the number4, somov eax, 4tells the kernel "I want to perform a write operation."ebx: Holds the file descriptor.1refers to standard output (stdout), which is why we use it here to print to the terminal.ecx: Points to the memory address of the data to write—in your case, thestringvariable from the.datasection.edx: Holds the length of the data to write (in bytes), which is yourstr_lenvalue.
Why Your Second Snippet Won't Work
In the second code block, you've mixed up all the register assignments:
mov eax, str_len: Noweaxholds the length of your string, not thesys_writecall number. The kernel will interpret this number as a system call ID, which is almost certainly invalid—this will either return an error or crash your program.mov ecx, 4: Putting4here tells the kernel to read data from memory address4, which is not your string (it's probably a reserved memory location, so this will cause garbage output or a fault).- The other values in
ebxandedxare also in the wrong places, so the kernel has no idea you're trying to write to stdout.
To Sum Up
Registers are not interchangeable for int 80h system calls—each one has a specific job based on which system call you're invoking. For every Linux system call (like sys_read, sys_exit, etc.), you'll need to follow the required register assignments (system call number + parameter registers) to get it right.
Your first snippet follows the convention correctly, which is why it would work for printing your string. The second one breaks all the rules, so it won't do what you expect.
内容的提问来源于stack exchange,提问作者mujtaba-io

