0

I do understand, both ADR and ADRP is for PC relative addressing where with 20 bit of immediate address (for ADR) , it can point upto +/-1 MB (2^20) of address range but how +/- 4GB is calculated for ADRP.

Apart from that I have simple snippet:

int g =1;
main()
{
  return g;
}

After disassembling it:

adrp.o:     file format elf64-littleaarch64

Disassembly of section .text:

0000000000000000 <main>:
0:  90000000    adrp    x0, 0 <main>
4:  b9400000    ldr w0, [x0]
8:  d65f03c0    ret

How do the addresses are patched in, and is the address of main at offset > 1MB ?

Milan
  • 1,447
  • 5
  • 19
  • 27
  • I'm not 100% sure what your question is, but check out https://stackoverflow.com/a/64841097/634919 and https://stackoverflow.com/questions/41906688/what-are-the-semantics-of-adrp-and-adrl-instructions-in-arm-assembly for info about how `adrp` is used. The appropriate displacements get patched in by the linker; it looks like you're disassembling the object file before linking has been done, so you don't see this. – Nate Eldredge Sep 06 '21 at 18:46
  • 4
    The other note is that the low 12 bits of the address get patched into the 12-bit offset field of the `ldr` instruction. 21 bits of immediate displacement in `adrp`, plus 12 bits of offset in `ldr`, gives 33 bits, which is where your +/- 4 GB comes from. – Nate Eldredge Sep 06 '21 at 18:49
  • So this convention (code model) is designed for a program in which `g` *could* be more than 1 MB, but less than 4 GB, away from the instruction in `main` where it is loaded. Whether it actually is or not would not be known until the program is linked; the compiler doesn't know whether this file is all of the program, or whether there might be a ton of other code and data in other source/object files. In this particular program it surely isn't, so simpler code might have been sufficient, but the compiler didn't know that. – Nate Eldredge Sep 06 '21 at 18:53
  • The RISC V compilers & linkers do what is being called linker "relaxation", which allows the linker to shorten the code sequence when it is not actually needed. (Quite involved and requires a lot more (i.e internal) relocations to be forwarded to the linker for final adjustment.) – Erik Eidt Sep 06 '21 at 19:09

0 Answers0