Read content from memory location into register

Viewed 1123

I want to read content of particular memory location. for eg :0x10002432 into Register r0 using LDR instruction.

I have tried ldr r0, 0x10002432 and ldr r0, =0x10002432

But it's not working.

any suggestion on how to read value from a particular memory location.

2 Answers

ARM has no instruction to load from an immediate 32-bit address. (It can't, because instructions are only 32 bits long.)

ldr r0, =0x10002432 will load the address itself into r0 (from the literal pool). To actually load the value from that address, you can follow it with ldr r0, [r0].

Note that ldr r0, [r0] loads a full 32-bit word. The address you've given is not word aligned, so it's possible that's not what you want. If you want to load a 16-bit halfword or a byte, you can use ldrh r0, [r0] or ldrb for a byte.

Before starting assembly of any kind you should have the processor documentation in front of you (even if it uses another assembly language, the machine code is as important as the different assembly languages). at this time arm does not support an immediate address based load, no room for the address if nothing else. So you have to have the address in a register to then load from it. You can do an offset in some instructions, but that offset is limited in size and range. So it is a two step process put the address in some register then use that register to load from that address.

ldr r0,=0x10002432 to get the address into a register
ldr r0,[r0]. to get the value at that address into the register

as you will see

mov r0,#0x10002432

will not work with arm because there is not room for that immediate.

ldr r0,=0x12345678

is a pseudo instruction that not all ARM assemblers support, and how they support if varies. gas for some time will choose the optimal instruction if it can fit as an immediate in an instruction it will convert that to a mov or mvn, otherwise it will generate a pc relative load from a pool. Others will only generate the pc relative load and not optimize. It is good IMO to know the instruction set and use mov when you can because you know it will work and then a trick like this or implement the pc relative load manually (using other pseudo code).

And as Nate point's out then you have the alignment issue, which some cores will let you do if you disable the exception. But in general on any processor you should avoid unaligned transactions...

Related