1

I found example of code on assembly, which finds the maximum number in array named data_items but that example was for x86 and I tried to adapt it for x64 because 32 bit absolute addressing is not supported by 64 bit system. To be short there are three actions:

lea data_items(%rip), %rdi #(1) Obtaining data_items address
add $4, %rdi #(2) Incrementing the pointer to 4 to read a next item
movl (%rdi), %eax #(3) Reading data at %rdi to %eax

The main questions:

  1. Is it correct way to pointing? Can it produce error after code relocation?
  2. If the %rip register constantly grows, why lea data_items(%rip), %rdi loads correct memory address? May be getting an offset by %rip have special meaning rather than "dataItems + %rip"?

Full adapted code here:

.section __DATA,__data

data_items:
.long 3,67,34,222,45,75,54,34,44,33,22,11,66,0

.section __TEXT,__text
.globl _main
_main:
lea data_items(%rip), %rdi #(1)
movl (%rdi), %eax
movl %eax, %ebx

start_loop:
cmpl $0, %eax
je loop_exit
add $4, %rdi #(2)
movl (%rdi), %eax #(3)
cmpl %ebx, %eax
jle start_loop

movl %eax, %ebx
jmp start_loop

loop_exit:
mov $0x2000001, %rax
mov $0, %rdi
syscall
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Arsynth
  • 761
  • 9
  • 22
  • 2
    Normally you'd use `lea data_items+4(%rip), %rdi` if that's the address you wanted. `mov data_items+4(%rip), %eax` if you just want to deref it, like a compiler would for accessing a global array. ([How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/q/38552116)). See [Why does this MOVSS instruction use RIP-relative addressing?](https://stackoverflow.com/q/44967075) / [How do RIP-relative variable references like "\[RIP + \_a\]" in x86-64 GAS Intel-syntax work?](https://stackoverflow.com/q/54745872) – Peter Cordes Aug 28 '22 at 13:44
  • 1
    It looks fine. The first code looks artificial, as already pointed out, but the rest is fine. `rip` doesn't grow forever, jumps set it to arbitrary values. In any case, an instruction is a definitive address once the program is loaded so, in a simplistic view, `rip` points to that address when executing it. – Margaret Bloom Aug 28 '22 at 16:54

0 Answers0