Search code examples
assemblyarmmachine-codeinstruction-encodingrelative-addressing

ARM instruction to hex for loads like pc-relative LDR


I've been trying to translate the arm instruction to hex which include PC register, for example

ldr rx, [pc, #xx]

I have checked the "ARM Architecture Reference Manual", and the description of LDR instruction is as below: enter image description here

Questions appeared, 1. the cond value, see Instruction Format, LDR instruction's correspond cond value is 0101(PLUS) or else? 2, Rd is PC register, and how to describe PC use the four bits[15:12]


Solution

  • A very simple way to figure this out is to just write some code and disassemble, see what that particular toolchain has encoded and then compare that to the docs...

    .globl _start
    _start:
    
    ldr r3,hello
    nop
    nop
    nop
    nop
    hello: .word 0x1234
    

    which gives

    00000000 <_start>:
       0:   e59f300c    ldr r3, [pc, #12]   ; 14 <hello>
       4:   e1a00000    nop         ; (mov r0, r0)
       8:   e1a00000    nop         ; (mov r0, r0)
       c:   e1a00000    nop         ; (mov r0, r0)
      10:   e1a00000    nop         ; (mov r0, r0)
    
    00000014 <hello>:
      14:   00001234    andeq   r1, r0, r4, lsr r2
    

    the instruction in question

    e59f300c
    11100101100111110011000000001100
    1110 01 0 1 1 0 0 1 1111 0011 000000001100
    

    as mentioned the condition code is 1110 which is "ALways". the Rn is the pc and the Rd is r3. The pc is in bits 19:16 not 15:12.

    the desired address is 0x14 in this case with the instruction at 0x00. So for that instruction the pc is 0x08 when executing so 0x14-0x08 is 0x0C which is the offset encoded.