linux - 为什么在将数据从寄存器移动到内存时需要使用 [ ](方括号),而其他方式则不需要?

标签 linux assembly x86 nasm

这是我的代码,它工作正常:

section .bss
    bufflen equ 1024
    buff: resb bufflen

    whatread: resb 4

section .data

section .text

global main

main:
    nop
    read:
        mov eax,3           ; Specify sys_read
        mov ebx,0           ; Specify standard input
        mov ecx,buff        ; Where to read to...
        mov edx,bufflen     ; How long to read
        int 80h             ; Tell linux to do its magic

                            ; Eax currently has the return value from linux system call..
        add eax, 30h        ; Convert number to ASCII digit
        mov [whatread],eax  ; Store how many bytes has been read to memory at loc **whatread**

        mov eax,4           ; Specify sys_write
        mov ebx,1           ; Specify standart output
        mov ecx,whatread    ; Get the address of whatread to ecx
        mov edx,4           ; number of bytes to be written
        int 80h             ; Tell linux to do its work

        mov eax, 1; 
        mov ebx, 0; 
        int 80h

这是一个简单的运行和输出:

koray@koray-VirtualBox:~/asm/buffasm$ nasm -f elf -g -F dwarf buff.asm
koray@koray-VirtualBox:~/asm/buffasm$ gcc -o buff buff.o
koray@koray-VirtualBox:~/asm/buffasm$ ./buff
p
2koray@koray-VirtualBox:~/asm/buffasm$ ./buff
ppp
4koray@koray-VirtualBox:~/asm/buffasm$ 

我的问题是:这两条指令有什么用:

        mov [whatread],eax  ; Store how many byte reads info to memory at loc whatread
        mov ecx,whatread    ; Get the address of whatread in ecx

为什么第一个使用 [] 而另一个不使用?

当我尝试将上面的第二行替换为:

        mov ecx,[whatread]  ; Get the address of whatread in ecx

可执行文件将无法正常运行,它不会在控制台中显示任何内容。

最佳答案

使用括号和不使用括号基本上是两种不同的东西:

中括号表示给定地址处内存中的值。

没有括号的表达式表示地址(或值)本身。

例子:

mov ecx, 1234

意思是:将值1234写入寄存器ecx

mov ecx, [1234]

意思是:将内存中1234地址的值写入寄存器ecx

mov [1234], ecx

意思是:将ecx中存储的值写入地址为1234的内存

mov 1234, ecx

...没有意义(在这种语法中),因为 1234 是一个无法更改的常数。

Linux“写入”系统调用(INT 80h,EAX=4)需要写入值的地址,而不是值本身!

这就是为什么你不在这个位置使用方括号的原因!

关于linux - 为什么在将数据从寄存器移动到内存时需要使用 [ ](方括号),而其他方式则不需要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27923915/

相关文章:

php - 在终端中执行 php 脚本出现权限被拒绝错误

javascript - 是否有 JavaScript 函数可以将通用文本框添加到 Gnome 扩展小程序中?

c - GCC asm函数,汇编代码为 "heapend"

x86 - 如何像 SSE movlps/movhps 一样将 AVX/AVX2(YMM) 寄存器中的较低或较高值存储到内存中?

c - 动态创建适当对齐的 C 结构内存内容

c++ - SDL 在 1920x1080 上设置窗口显示模式

linux - 用于创建树目录的 Bash 脚本

c - y86 程序集标签没有发挥应有的作用

gcc - 无法用gcc编译asm hello world

assembly - 了解哪种汇编语法和体系结构最有用?