Search code examples
assemblyarmcortex-marmasm

How to reach indexed values in an array on a Cortex-M3 with assembly?


On the Cortex-M3 I wanted to set the first two values of the array to 0 and 1, so I did the following:

main    MOV R4, #0

array   DCD 4,7,6,8
        LDR R1, =array ; R1 = base address of array

        STR R4, [R1, R4, LSL #2]
        ADD R4, R4, #1
        STR R4, [R1, R4, LSL #2]

        END

Apparently the STR instruction does not what I wanted it to do. What's wrong with that? In the "The Cortex-M3 Instruction Set" manual it says:

STR R0, [R1, R2, LSL #2] ; Stores R0 to an address equal to sum of R1
; and four times R2.

Disassembly looks like that:

0x00000000 0200      DCW      0x0200
0x00000002 2000      DCW      0x2000
0x00000004 0009      DCW      0x0009
0x00000006 0000      DCW      0x0000
0x00000008 F04F0400  MOV      r4,#0x00
0x0000000C 0004      DCW      0x0004
0x0000000E 0000      DCW      0x0000
0x00000010 0007      DCW      0x0007
0x00000012 0000      DCW      0x0000
0x00000014 0006      DCW      0x0006
0x00000016 0000      DCW      0x0000
0x00000018 0008      DCW      0x0008
0x0000001A 0000      DCW      0x0000
0x0000001C 4903      LDR      r1,[pc,#12]  ; @0x0000002C
0x0000001E F8414024  STR      r4,[r1,r4,LSL #2]
0x00000022 F1040401  ADD      r4,r4,#0x01
0x00000026 F8414024  STR      r4,[r1,r4,LSL #2]
0x0000002A 0000      DCW      0x0000
0x0000002C 000C      DCW      0x000C
0x0000002E 0000      DCW      0x0000

Solution

  • As Michael explained the instruction array DCD 4,7,6,8 has to be after the AREA d, DATA directive - otherwise the array will be placed in read-only code area and can thus not be overwritten.