无法使用间接寻址模式获取存储在内存中的值



我有以下汇编代码:

间接1.s

.section .data
t1: 
.long 5
.section .text
.globl _start
_start: 
movl $t1, %ecx          #we are passing the address to %ecx
movl $5, %eax           #we are passing value 5 to %eax
movl (%ecx), %ebx   #Using indirect addressing mode we are getting the value from t1 and passing it to ebx
addl %eax, %ebx     # add the values in %eax, %ebx and store it in %ebx
movl $1, %eax       # call exit program
int $0x80       # Call Master Bruce Wayne

当上述程序运行时,我按预期得到值 10

[ashok@localhost asm-32]$ as indirect1.s -gstabs+ -o indirect1.o
[ashok@localhost asm-32]$ ld indirect1.o -o indirect1
[ashok@localhost asm-32]$ ./indirect1 
[ashok@localhost asm-32]$ echo $?
10

修改了上述程序以消除%ecx寄存器:

间接2.s

.section .data
t1: 
.long 5
.section .text
.globl _start
_start: 
    movl $t1, %ebx      # we are passing the address to %ebx
    movl $5, %eax       # we are passing value 5 to %eax
    addl %eax, (%ebx)   # add the values in %eax, %ebx and store it in %ebx
    movl $1, %eax       # call exit program
    int $0x80       # Call Master Bruce Wayne

当我运行上面的程序时,我没有得到预期的输出,即 10 我似乎获取存储在 %ebx 中的地址

[ashok@localhost asm-32]$ as indirect2.s -gstabs+ -o indirect2.o
[ashok@localhost asm-32]$ ld indirect2.o -o indirect2
[ashok@localhost asm-32]$ ./indirect2
[ashok@localhost asm-32]$ echo $?
136

我在间接2.s程序中做错了什么。

我认为你想要的是这样的东西:

movl $t1, %ebx      # ebx = address of t1
movl $5, %eax       # eax = 5
addl (%ebx), %eax   # eax += (ebx)
movl %eax, %ebx     # exit value
movl $1, %eax       # exit()
int $0x80          

或者,要使第二个示例正常工作:

.section .data
t1: 
.long 5
.section .text
.globl _start
_start: 
    movl $t1, %ebx      # we are passing the address to %ebx
    movl $5, %eax       # we are passing value 5 to %eax
    addl %eax, (%ebx)   # add the values in %eax, %ebx and store it in %ebx
    movl (%ebx), %ebx   # THE FORGOTTEN INSTRUCTION (read result back into %ebx)
    movl $1, %eax       # call exit program
    int $0x80       # Call Master Bruce Wayne

发生的事情是您的 indirect2 的初始版本打印出$t1的相对地址,即程序退出时%ebx的地址。

最新更新