I'm wondering in ARM assembly which instruction I can use to branch to an address or label stored in some memory address.
For example, we can use B LABEL to jump to LABEL. But now the destination can only be known during run time, and it is stored in some known memory place, is there something like B [address]?
Thanks!
is there something like B [address]?
No. Load the address into a register first, and then use BX
to jump to it:
@ In this example, R0 points to the address to jump to
LDR R1, [R0]
BX R1
You could also load the address directly into PC
(though I'm not sure if this is valid across all ARM architectures, so consult the relevant reference document):
@ In this example, R0 points to the address to jump to
LDR PC, [R0]
One important design paradigm of the ARM architecture is that only very few instructions can operate on memory, which is potentially a slow operation: only LDR
and STR
. So there is no B [label]
from memory.
For the register part of the question, a good way to answer this kind of question is to look at the instruction summary sections, which group instructions by type. There is one for branch instructions in ARMv7 and ARMv8:
ARMv7 A4.3 "Branch instructions"
As mentioned at: https://stackoverflow.com/a/32305904/9160762 , in ARMv7 you can use BX register
, and there is also a BLX register
which sets the return address for a function call.
From that table, we know which ones use register since only those can jump to "Any" address: those that use immediates have limited ranges as full addresses don't fit into the fixed 4 bytes per instruction encoding.
Another option in ARMv7 mentioned at: https://stackoverflow.com/a/32305904/9160762 is to ldr
into the PC, since PC is just r15
:
ldr pc, [r0]
However, this is not possible anymore in ARMv8 where PC has a dedicated register. B1.2.1 "Registers in AArch64 state" says:
Software cannot write directly to the PC. It can only be updated on a branch, exception entry or exception return.
ARMv8 C3.1 "Branches, Exception generating, and System instructions"
In that section we learn about BLR
, BR
and RET
.
BR
is like BX
, but without X
since there is no thumb to worry about.
The docs then say that RET
is analogous to BR
, except that it:
x30
, which is where BL
puts the return address
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.