Question

I have a below assembly code:

indirect1.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

when the above program is run, I get the value 10 as expected

[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

Modified the above program to eliminate %ecx register:

indirect2.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

When i run the above program , i don't get the expected output ,i.e 10 and i seem to get the address stored in %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

What i am doing wrong in indirect2.s program.

Was it helpful?

Solution

I think what you want is something like this:

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          

OTHER TIPS

Alternatively, to make your second example work:

.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

What happened is your initial version of indirect2 printed out the relative address of $t1 which is what was in %ebx when the program exited.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top