How to get qemu to run an arm thumb binary? - arm

I'm trying to learn the basics of ARM assembly and wrote a fairly simple program to sort an array. I initially assembled it using the armv8-a option and ran the program under qemu while debugging with gdb. This worked fine and the program initialized the array and sorted it as expected.
Ultimately I would like to be able to write some assembly for my Raspberry Pi Pico, which has an ARM Cortex M0+, which I believe uses the armv6-m option. However, when I change the directive in my code, it compiles fine but behaves strangely in that the program counter increments by 4 after every instruction instead of the 2 that I expect for thumb. This is causing my program to not work correctly. I suspect that qemu is trying to run my code as if it were compiled for the full ARM instruction set instead of thumb, but I'm not sure why this is.
I am running on Ubuntu Linux 20.04 LTS, using qemu-arm version 4.2.1 (installed from the package manager). Does the qemu-arm executable only run full ARM binaries? If so, is there another qemu package I can install to run a thumb binary?
Here is my code if it is helpful:
.arch armv6-m
.cpu cortex-m0plus
.syntax unified
.thumb
.data
arr: .skip 4 * 10
len: .word 10
.section .text
.global _start
.align 2
_start:
ldr r0, arr_adr # load the address of the start of the array into register 0
movs r1, #0 # clear the counter register
movs r2, #100
init_loop:
str r2, [r0,r1] # store r2's value to the base address of the array plus the offset stored in r1
subs r2, r2, #10 # subtract 10 from r2
adds r1, #4 # add 4 to the offset (1 word in bytes)
cmp r1, #40 # check if we've reached the end of the array
bne init_loop
movs r1, #0 # clear the offset
out_loop:
mov r3, r1 # set the index of the minimum value to the current array index
mov r4, r1 # set the inner loop index to the outer loop index
in_loop:
ldr r5, [r0,r3] # load the minimum index's value to r5
ldr r6, [r0,r4] # load the inner loop's next value to r6
cmp r6, r5 # compare the two values
bge in_loop_inc # if r6 is greater than or equal to r5, increment and restart loop
mov r3, r4 # set the minimum index to the current index
in_loop_inc:
adds r4, #4
cmp r4, #40 # check if at end of array
blt in_loop
ldr r5, [r0,r3] # load the minimum index value into r5
ldr r6, [r0,r1] # load the current outer loop index value into r6
str r6, [r0,r3] # swap the two values
str r5, [r0,r1]
adds r1, #4 # increment outer loop index
cmp r1, #40 # check if at end of array
blt out_loop
loop:
nop
b loop
arr_adr: .word arr
Thank you for your help!

There are a couple of concepts to disentangle here:
(1) Arm vs Thumb : these are two different instruction sets. Most CPUs support both, some support only one. Both are available simultaneously if the CPU supports both. To simplify a little bit, if you jump to an address with the least significant bit set that means "go to Thumb mode", and jumping to an address with that bit clear means "go to Arm mode". (Interworking is a touch more complicated than that, but that's a good initial mental model.) Note that all Arm instructions are 4 bytes long, but Thumb instructions can be either 2 or 4 bytes long.
(2) A-profile vs M-profile : these are two different families of CPU architecture. M-profile is "microcontrollers"; A-profile is "applications processors", which is "(almost) everything else". M-profile CPUs always support Thumb and only Thumb code. A-profile CPUs support both Arm and Thumb. The Raspberry Pi Pico is a Cortex-M0+, which is M-profile.
(3) QEMU system emulation vs user-mode emulation : these are two different QEMU executables which run guest code in different ways. The system emulation binary (typically qemu-system-arm) runs "bare metal code", eg an entire OS. The guest code has full control and can handle exceptions, write to hardware devices, etc. The user emulation binary (typically qemu-arm) is for running Linux user-space binaries. Guest code is started in unprivileged mode and has access to the usual Linux system calls. For system emulation, which CPU is being emulated depends on what machine type you select with the -M or --machine option. For user-mode emulation, the default CPU is "A-profile with all supported features enabled" (this is --cpu max).
You're currently using qemu-arm which means you get user-mode emulation. This should support Thumb binaries, but unless you pass it a --cpu option it will be using an A-profile CPU. I would also suggest using a newer QEMU for M-profile work, because a lot of M-profile CPU bugs have been fixed since version 4.2. I think 4.2 is also too old to have the Cortex-M0 CPU.
GDB should tell you in the PSR what the T bit is set to -- use that to check whether you're in Thumb mode or Arm mode, rather than looking at how much the PC is incrementing by.
There's currently no QEMU system emulation of the Raspberry Pi Pico (though somebody has been doing some experimental work on one). If your assembly is just basic "working with registers and a bit of memory" you can do that with the user-mode emulator. Or you can try the 'microbit' machine model, which is a Cortex-M0 board -- if you're not doing things that are specific to the Pi Pico that might be good enough.

memmap
MEMORY
{
ram : ORIGIN = 0x00000000, LENGTH = 32K
}
SECTIONS
{
.text : { *(.text*) } > ram
}
strap.s
.cpu cortex-m0
.thumb
.syntax unified
.globl reset_entry
reset_entry:
.word 0x20001000
.word reset
.word hang
.word hang
.word hang
.thumb_func
reset:
ldr r0,=0x40002500
ldr r1,=4
str r1,[r0]
ldr r0,=0x40002008
ldr r1,=1
str r1,[r0]
ldr r0,=0x4000251C
ldr r1,=0x30
ldr r2,=0x37
loop_top:
str r1,[r0]
adds r1,r1,#1
ands r1,r1,r2
b loop_top
.thumb_func
hang:
b hang
build
arm-linux-gnueabi-as --warn --fatal-warnings strap.s -o strap.o
arm-linux-gnueabi-ld strap.o -T memmap -o notmain.elf
arm-linux-gnueabi-objdump -D notmain.elf > notmain.list
Check the vector table as a quick check:
Disassembly of section .text:
00000000 <reset_entry>:
0: 20001000 andcs r1, r0, r0
4: 00000015 andeq r0, r0, r5, lsl r0
8: 0000002f andeq r0, r0, pc, lsr #32
c: 0000002f andeq r0, r0, pc, lsr #32
10: 0000002f andeq r0, r0, pc, lsr #32
00000014 <reset>:
14: 4806 ldr r0, [pc, #24] ; (30 <hang+0x2>)
16: 4907 ldr r1, [pc, #28] ; (34 <hang+0x6>)
18: 6001 str r1, [r0, #0]
1a: 4807 ldr r0, [pc, #28] ; (38
Looks good,
run it
qemu-system-arm -M microbit -nographic -kernel notmain.elf
and it will spew out 0123456701234567...until you ctrl-a then x to exit qemu.
Note this binary will not work on a real chip as I am cheating the uart.
You can get your feet wet with this sim. There is also a luminary micro one from the first cortex-m chips and you can limit yourself to armv6m instructions on that platform as well.
qemu and sims like this have very limited value for mcu work since almost all of the work is related to peripherals and pins, and the instruction set is just like the language of a book, French, Russian, English, German, doesn't matter a biology book is a biology book and the book is the goal. The peripherals are specific to the chip (the pico, a specific stm32 chip, a specific TI tiva C chip, etc).

Related

Memory copying: ARM STM vs. ARM NEON

I need to copy large amounts of memory (on the order of 47k) (example, from a USB buffer to a more permanent buffer).
This is using an ARM Cortex A8.
(The ARM has the NEON code.)
The ARM NEON instruction can copy 4 32-bit elements at a time (per instruction).
The ARM LDM and STM instructions can load and store (copy) more than 4 registers at a time (per instruction).
Questions:
Which is more efficient for copying large amounts (e.g. 47k) of memory, the ARM NEON instruction or the ARM LDM and STM instructions? (I don't have benchmarking tools available; this is on an embedded system).
What is the advantage of the ARM NEON instructions for copying memory?
The project is primarily C language, but also has some assembly language.
Is there a method to suggest to the compiler to use ARM NEON or the LDM/STM instructions, without optimizations? (We are launching code without optimizations so there are no differences when the product is returned. There is a possibility that optimization can be responsible for issues in the product.)
Tools:
ARM Cortex A8 processor
IAR Electronic Workbench IDE & Compiler.
Development on Windows 10 PC, to remote embedded ARM processor (via JTAG).
Neon has the advantage of unaligned load and store, but it consumes more power.
And since you are copying form the USB buffer to a permant one where you have full control over alignment and size, it would be better without neon, because memory speed is the same.
The standard memcpy most probably already utilizes neon (it depends on the BSP), hence I'd write a mini version utilizing ldrd and strd which is slightly faster than ldm and stm.
.balign 64
push {r4-r11}
sub r1, r1, #8
sub r0, r0, #8
b 1f
.balign 64
1:
ldrd r4, r5, [r1, #8]
ldrd r6, r7, [r1, #16]
ldrd r8, r9, [r1, #24]
ldrd r10, r11, [r1, #32]!
subs r2, r2, #32
strd r4, r5, [r0, #8]
strd r6, r7, [r0, #16]
strd r8, r9, [r0, #24]
strd r10, r11, [r0, #32]!
bgt 1b
.balign 16
pop {r4-r11}
bx lr
I think you have no problem making the buffer size a multiple of 32, and both buffers aligned to 64 bytes(cache line length) or even better, 4096 bytes (page size).

I want to implement R10=R11+OxFFFFE in thumb assembly language

The immediate value i know can not be more then 12 bits in case of ADDW. is there any way to implement this in one instruction
Let the tools do the work, BTW immediates in arm (and other ISAs) has been asked and answered here many times. gnu assembler will choose the optimal solution (usually) using pseudocode.
.cpu cortex-m0
.thumb
ldr r0,=0xFFFFE
.align
00000000 <.text>:
0: 4800 ldr r0, [pc, #0] ; (4 <.text+0x4>)
2: 46c0 nop ; (mov r8, r8)
4: 000ffffe strdeq pc, [pc], -lr
enable thumb2 extensions
.cpu cortex-m7
.thumb
.syntax unified
ldr r0,=0xFFFFE
ldr r1,=0x00010001
.align
the other constant was to confirm it is attempting thumb2 extensions.
so no shortcuts you either need to build the value in parts or do a pc relative load from nearby. Or just code it with pseudocode and get what you get.
a similar constant
cpu cortex-m7
.thumb
.syntax unified
ldr r0,=0xFFFFFFFE
ldr r1,=0x00010001
.align
00000000 <.text>:
0: f06f 0001 mvn.w r0, #1
4: f04f 1101 mov.w r1, #65537 ; 0x10001
could have been done without the pc relative load.
No you cannot implement this with one instruction.
but this:
add r10,r11,#0xFFFFFFFE
you can...if that helps.

Enable GPIO on ARM STM32G030K6

I am trying to learn to program the STM32G030K6 by directly manipulating the registers (without relying on CubeMX). My program is intended to set pin PA5 to high.
// Target: STM32G030K6T6
// Goal: Set pin PA5 to high
#include "stm32g0xx.h" // Device header
int main(void)
{
RCC->IOPENR |= 1; // Enable GPIOA Clock
GPIOA->MODER |= 0x400; // Set GPIOA MODE5 to a general purpose output
GPIOA->ODR = 0x20; // Set PA5 high
while(1)
{
}
}
The program does not effect PA5 at all.
I have successfully tested the setup with a CubeMX blink program to prove it is not a hardware issue.
STM32G030K6: Data Sheet
STM32G030K6: Reference Manual
So what I have figured out from you so far is that you bought/acquired this part put it down on a breakout board. Have applied power and ground, added an led and resistor, and have an stlink hooked up. Can use CubeMX and make it work are using Kiel.
So I have made many a breakout board put the leds and such on the board because I got tired of wiring up items separately. The parts I have used you needed to make sure VDD and VDDA were connected but yours it is the same pin, check. VDD and VSS no doubt if you have it working. NRST pulled up for good measure although I think not required as there is an internal pull up, but BOOT0 did need a pull down, but this is an STM32G and you have pointed out that SWCLK and BOOT0 share the same pin. ST sadly is going away from the on chip bootloader or at least it is disabled by the factory
ST production value: 0xDFFF E1AA
Bit 24 nBOOT_SEL
0: BOOT0 signal is defined by BOOT0 pin value (legacy mode)
1: BOOT0 signal is defined by nBOOT0 option bit
So as shipped a new part BOOT0 is not something you can rely on to get into the bootloader and use a uart solution to download code into the flash, nor can you use it to get yourself unbricked while doing this level of work.
So the stlink is connected you said Kiel can talk to the part, so that is all in theory fine, not the problem.
I don't have Kiel off hand, but everyone can get a gnu cross compiler or build one from sources.
apt-get install binutils-arm-linux-gnueabi gcc-arm-linux-gnueabi
The code below does not care about arm-non-eabi- vs arm-linux-gnueabi- variations on the cross compiler it is independent of those differences, it just needs the compiler assembler and linker.
Now this will probably again get into a personal opinion battle with certain other SO users. Work through the noise. I am specifically avoiding CMSIS, I have seen the implementation, and you should inspect it to, for now you don't want to add that risk to your code, remove it and add it later as desired. This is my style it specifically controls the instruction used for access, everything about is based on a lot of experience even though you don't see that, designed for the reader to have a high chance of success. Make it your own if/when you get this to work and/or the side comments which is my real goal may help you examine the binary you are building with your own tool to eliminate common traps.
It is not simply a case of getting the C code in main() right for bare-metal code to work you need the whole thing from reset on to be right.
Flash based version:
flash.s
.cpu cortex-m0
.thumb
.thumb_func
.global _start
_start:
stacktop: .word 0x20001000
.word reset
.word hang
.word hang
.thumb_func
reset:
bl notmain
b hang
.thumb_func
hang: b .
.thumb_func
.globl PUT32
PUT32:
str r1,[r0]
bx lr
.thumb_func
.globl GET32
GET32:
ldr r0,[r0]
bx lr
.thumb_func
.globl dummy
dummy:
bx lr
notmain.c
void PUT32 ( unsigned int, unsigned int );
unsigned int GET32 ( unsigned int );
void dummy ( unsigned int );
#define RCC_BASE 0x40021000
#define RCC_IOPENR (RCC_BASE+0x34)
#define GPIOA_BASE 0x50000000
#define GPIOA_MODER (GPIOA_BASE+0x00)
#define GPIOA_OTYPER (GPIOA_BASE+0x04)
#define GPIOA_BSRR (GPIOA_BASE+0x18)
#define DCOUNT 2000000
int notmain ( void )
{
unsigned int ra;
unsigned int rx;
ra=GET32(RCC_IOPENR);
ra|=1<<0; //enable port a
PUT32(RCC_IOPENR,ra);
ra=GET32(GPIOA_MODER);
ra&=~(3<<(5<<1)); //clear bits 10,11
ra|= (1<<(5<<1)); //set bit 10
PUT32(GPIOA_MODER,ra);
ra=GET32(GPIOA_OTYPER);
ra&=~(1<<5); //clear bit 5
PUT32(GPIOA_OTYPER,ra);
for(rx=0;;rx++)
{
PUT32(GPIOA_BSRR, (1<<(5+ 0)) );
for(ra=0;ra<DCOUNT;ra++) dummy(ra);
PUT32(GPIOA_BSRR, (1<<(5+16)) );
for(ra=0;ra<DCOUNT;ra++) dummy(ra);
}
return(0);
}
flash.ld
MEMORY
{
rom : ORIGIN = 0x08000000, LENGTH = 0x1000
ram : ORIGIN = 0x20000000, LENGTH = 0x1000
}
SECTIONS
{
.text : { *(.text*) } > rom
.rodata : { *(.rodata*) } > rom
.bss : { *(.bss*) } > ram
}
build
arm-none-eabi-as --warn --fatal-warnings -mcpu=cortex-m0 flash.s -o flash.o
arm-none-eabi-gcc -Wall -Werror -O2 -nostdlib -nostartfiles -ffreestanding -mcpu=cortex-m0 -mthumb -c notmain.c -o notmain.o
arm-none-eabi-ld -o notmain.elf -T flash.ld flash.o notmain.o
arm-none-eabi-objdump -D notmain.elf > notmain.list
arm-none-eabi-objcopy notmain.elf notmain.bin -O binary
Again you can replace arm-none-eabi with arm-linux-gnueabi if that is what you have/found. This code doesn't care about the differences.
The point here is for the processor to boot:
Disassembly of section .text:
08000000 <_start>:
8000000: 20001000 andcs r1, r0, r0
8000004: 08000011 stmdaeq r0, {r0, r4}
8000008: 08000017 stmdaeq r0, {r0, r1, r2, r4}
800000c: 08000017 stmdaeq r0, {r0, r1, r2, r4}
08000010 <reset>:
8000010: f000 f808 bl 8000024 <notmain>
8000014: e7ff b.n 8000016 <hang>
08000016 <hang>:
8000016: e7fe b.n 8000016 <hang>
The application flash starts at 0x08000000 in the ARM memory space, called the Main Flash Memory in the reference manual. Depending on the boot strap settings 0x08000000 will be mirrored at 0x00000000, as documented in the ARM manuals this is where the vector table lives. The first word is a value loaded into the stack pointer on reset, the word at address 0x00000004 (which would be mirrored to 0x08000004) is the reset vector.
The above used the disassembler so it is trying to disassemble those values as instructions they are values/vectors ignore the disassembly for that table.
Assuming we can get the tools to put this binary in the flash at the desired location then
08000000 <_start>:
8000000: 20001000 value loaded into sp on reset
8000004: 08000011 reset vector
The reset vector is the address of the code to execute for that exception with the lsbit set to indicate thumb mode, the lsbit is stripped it does not go into the pc. So the reset vector address here is 0x08000010 which is correct:
08000010 <reset>:
8000010: f000 f808 bl 8000024 <notmain>
8000014: e7ff b.n 8000016 <hang>
And can follow this to notmain, name of the C entry point is not important, and some tools will add extra stuff it sees the label main(), have not seen one of those for years but continue to do this to also prove the point it doesn't matter.
So if this is put in the main flash at arm address 0x08000000 then this code will boot and run up to the C code.
Note sram starts at 0x20000000 and the RM shows this part has 32MBytes of sram so it has at least 0x1000 bytes to cover this project with plenty of extra room.
8000026: 481b ldr r0, [pc, #108] ; (8000094 <notmain+0x70>)
8000028: f7ff fff8 bl 800001c <GET32>
800002c: 2101 movs r1, #1
800002e: 4301 orrs r1, r0
8000030: 4818 ldr r0, [pc, #96] ; (8000094 <notmain+0x70>)
8000032: f7ff fff1 bl 8000018 <PUT32>
...
8000094: 40021034 andmi r1, r2, r4, lsr r0
Be it as I have programmed or through your program and CMSIS or HAL headers, you should see 0x40021034 being used in some form. Note this part of yours is a cortex-m0+ so it only has a limited number of thumb2 extensions note that bl is two separate 16 instructions that can be spaced apart, but are pretty much always found as a pair, they are two instructions, the rest of the instructions need to be 16 bit, if you see something.w in the disassembly or instructions other than bl being 32 or 16*2 bits then that may be a thumb2 instruction and that won't run on this processor and may be some setting you have used when building this code, you can see with this toolchain I have specifically called out an m0 which is effectively the same as m0+ from an instruction set perspective (architecture armv6-m). You do not want armv7-m for this chip it won't work, there are about a 100 or so instructions in armv7-m that won't work on armv6-m based chips.
The orring of the bit in the io enable register should resemble a read (ldr) from 0x40021034 a modification of the value read and a write (str) to that same address.
Your code as posted would have worked on other STM32 parts as many of them initialize the MODER register (if that part uses that flavor of GPIO peripheral) to zeros for most of the pins which is input. This part documents that most of the pins reset to 0b11 which is analog mode, curious why but whatever.
Reset value:
0xEBFF FFFF for port A
0xFFFF FFFF for other ports
So you can't simply set one of the two bits to change the mode if the bits started off as 0b00 then setting one can turn it into 0b01, but for this part you can either just clear bit 11 or better control both bits and not rely on the reset state, so clear the two bits and set one of them or clear one and set the other
5<<1 means 5 shifted left one 0b101 shift a zero in from the right gives 0b1010 which is a 0xA which is 10 this is a visual way to see that I am messing with PA5 and the number 5 is there, but for this register pin 5 mode settings are bits 10 and 11. 3 << (5<<1) means 3<<10 which is bits 10 and 11. the tilde means invert the whole thing so 00000C00 is the 3<<10 invert that you get FFFFF3FF which anded with the moder value will zero bits 10 and 11. now orr with 00000400 1<<10 to set bit 10.
We want the output at least for now to be a push-pull not open drain so even though the reset value is already push-pull, I clear it for good measure. Now I normally don't bother with the pull up or other gpio setup register, I mess with these two MODER and OTYPER for the STM32 parts that use this GPIO peripheral (you will see that not all STM32 parts use the same IP, the STM32F103 uses a different one for example, check it out.
So in some way confirm that CMSIS or not that the code produced is messing with these registers. From the documentation GPIOA starts at 0x50000000. so 0x50000000 and 0x50000004 registers.
Because this part has a GPIO BSRR register its a nice feature just use it for now so that you don't accidentally mess with other pins.
The dummy loop burns time so that in this case the led blinks on and off, you have to tune the DCOUNT based on the clock used for the processor when you get this running not too fast not too slow, just right. Doing it this way with an external function it is no longer dead code ( for(ra=0;ra<DCOUNT;ra++) continue; ) the compiler is forced to build it without using a volatile request.
No the code doesn't actually hit return(0); some compilers are not that smart and complain. (some are that smart and complain that you can't get there, YMMV)
All of these pieces need to be in place to have a half a chance of this working. Its not just about a few lines of C code.
With an stlink the kiel tools are fine and I would hope there is a way to examine memory space, you will want to examine 0x08000000 and compare that to the binary generated by the tool, and hopefully there is a way to examine the output of the tool as well to see what it built, easy to do with gnu.
You can use openocd instead of kiel to load and examine things from a command line it would be something in the form
openocd -f stlink.cfg -f target.cfg
and then in another window
telnet localhost 4444
gdb adds a whole lot more unknowns...
then you can use
mdw 0x08000000 40
In the telnet window to see what is in that main flash and then compare it to the loadable portion of the binary to see if your program is really there, if your program is not actually there then no matter what you do to the C code it wont make it blink.
There are ways to use openocd to flash parts, but it is very vendor/part specific as they have to add that capability to openocd and you have to have the right version, from memory it is something along the lines of
flash write_image erase notmain.elf
if using a "binary" with address information in it, if you are using a memory image then you need to put the address on that command line 0x08000000
Some st parts come locked or let's say boards like some blue pills where this doesn't work, virgin parts I don't know that I have seen locked, you bought loose parts it appears so they should not be locked.
If you get openocd working and gnu then you could also try using sram without having to have flash support initially.
sram.s
.cpu cortex-m0
.thumb
.thumb_func
.global _start
_start:
ldr r0,=0x20001000
mov sp,r0
bl notmain
b .
.thumb_func
.globl PUT32
PUT32:
str r1,[r0]
bx lr
.thumb_func
.globl GET32
GET32:
ldr r0,[r0]
bx lr
.thumb_func
.globl dummy
dummy:
bx lr
sram.ld
MEMORY
{
ram : ORIGIN = 0x20000000, LENGTH = 0x1000
}
SECTIONS
{
.text : { *(.text*) } > ram
.rodata : { *(.rodata*) } > ram
.bss : { *(.bss*) } > ram
}
Since this part uses a vector table and what is about to be described is using the debugger to place and run a program in sram, volatile so when you reset/reboot it is lost, but it provides a way to experiment without having to get flash writing working.
We will tell the debugger to start execution at 0x20000000 so we want there to be an instruction there not a vector table.
arm-none-eabi-as --warn --fatal-warnings -mcpu=cortex-m0 sram.s -o sram.o
arm-none-eabi-ld -o notmain.elf -T sram.ld sram.o notmain.o
arm-none-eabi-objdump -D notmain.elf > notmain.list
arm-none-eabi-objcopy notmain.elf notmain.bin -O binary
always inspect your binary on a new project before running
Disassembly of section .text:
20000000 <_start>:
20000000: 4804 ldr r0, [pc, #16] ; (20000014 <dummy+0x2>)
20000002: 4685 mov sp, r0
20000004: f000 f808 bl 20000018 <notmain>
20000008: e7fe b.n 20000008 <_start+0x8>
2000000a <PUT32>:
2000000a: 6001 str r1, [r0, #0]
2000000c: 4770 bx lr
2000000e <GET32>:
2000000e: 6800 ldr r0, [r0, #0]
20000010: 4770 bx lr
20000012 <dummy>:
20000012: 4770 bx lr
20000014: 20001000 andcs r1, r0, r0
20000018 <notmain>:
20000018: b570 push {r4, r5, r6, lr}
and that looks good.
with openocd you can now
reset halt
load_image notmain.elf
resume 0x20000000
To run the program (might need a path, if you run openocd in the directory where the elf file is and/or you copy the elf file to the directory where you launched openocd (not telnet, openocd) then you usually don't need to put a path.
This is in sram not flash so may run faster and may want a larger value in the delay loop.
If you simply want to make the output high or low then just use the desired bsrr line and get rid of the loops, this code as written puts you in a safe infinite loop when you return from notmain, one that will not interfere with the gpio port, as part of your investigation of the binary you are building with your tool you need to confirm that the while loop you have placed is actually not dead code and was implemented (clang has been known to dead code this so others might as well) and some sandboxes undo stuff when you return from main so it could be that your code is now fine, but exits from main and the bootstrap undoes what you did to PA5 faster than you can see it.
That's all I can do so far, I have an stm32 cortex-m0+ part with a working openocd config if that helps, this is a different part but the core is the same if there isn't another tap then it should just work but you never know.
Short answer, your moder code wouldn't have worked, otherwise it looked good, but the C code is only part of the story required for success. This long answer highlights the main points that have to be there for success in booting and setting up the led. It is possible that both of us missed an additional enable, I don't have this part specifically so I cannot actually pull one out and run this code on it.

How does a compiler/assembler make sense of processor core registers?

My question is specific to arm cortex M3 micro-controllers. Every peripheral on the micro controller is memory mapped and those memory addresses are used in processing.
For Eg.,: GPIOA->ODR = 0;
This will write a 0 at address 0x4001080C.
This address is defined in the device specific file of the micro controller.
Now, the cortex M3 has processor core registers R0-R12 (general purpose). I want to know, do these registers also have some address like other peripherals?
So, if I have instruction: MOV R0, #10;
will R0 be translated to some address when assembled? Do core registers have special numeric addresses exclusive for core peripherals. Is address of R0 defined in any file (I couldn't find any) like that of GPIOA? Or is it that register R0 and other core registers are referred to as R0 and their respective names only so that the assembler sees "R0" and generates the opcode from it?
I have this confusion because some 8 bit controllers also have addresses for general purpose registers.
Thanks,
Navin
Registers like R0-R12 or SP, PC, .. are registers inside CPU core and they are not mapped to global address space. Access to these registers is possible only from assembler.
And also direct access to core registers from higher level languages like C is not possible, because they are not addressable. These registers are used for internal processing and they are transparent for the programmer.
But registers like GPIOA->ODR are mapped to global address space, so each register has own address.
General Purpose registers are meant to do general purpose operations with the CPU. This is just like we use few temporary variables in any programming language. So if we relate this to your question, CPU requires few reserved memory segments to do it's basic operations. Hence there is no point in sharing this to outside world. This is how ARM based processors work.
You happened to have picked an instruction that is really easy to see...
.thumb
mov r0,#10
mov r1,#10
mov r2,#10
mov r3,#10
mov r4,#10
mov r5,#10
mov r6,#10
mov r7,#10
assemble then disassemble to see the machine code
Disassembly of section .text:
00000000 <.text>:
0: 200a movs r0, #10
2: 210a movs r1, #10
4: 220a movs r2, #10
6: 230a movs r3, #10
8: 240a movs r4, #10
a: 250a movs r5, #10
c: 260a movs r6, #10
e: 270a movs r7, #10
there will be three or four bits depending on the instruction and instruction set (arm vs thumb (and then thumb2 extensions)) that specify the register. In this case those bits happen to line up nicely with the hex representation of the machine code instruction so we can see the 0 through 7. For a cortex-m3 many of the thumb instructions are limited to r0-r7 (implying a 3 bit field within the instruction) with one or two to move between the lower and upper, thumb2 extensions allow for more access to the full r0-r15 (and thus will have a 4 bit field in the instruction). You should get the armv7m architectural reference manual which is what is associated with the cortex-m3 (after you get the cortex-m3 technical reference manual and see that it uses the armv7m architecture), you can also get the oldest armv5 architectural reference manual as it has the oldest description of the thumb instruction set which is the one instruciton set that is compatible across all arm cores armv6m covers the cortex-m0 which has a lot fewer thumb2 extensions then armv7m which covers the cortex-m3 m4 and m7 have tons more thumb2 extensions.
another example that takes only a second to try
.thumb
mov r0,r0
mov r1,r1
mov r2,r2
mov r3,r3
mov r4,r4
mov r5,r5
mov r6,r6
mov r7,r7
mov r0,r0
mov r1,r0
mov r2,r0
mov r3,r0
mov r4,r0
mov r5,r0
mov r6,r0
mov r7,r0
Disassembly of section .text:
00000000 <.text>:
0: 1c00 adds r0, r0, #0
2: 1c09 adds r1, r1, #0
4: 1c12 adds r2, r2, #0
6: 1c1b adds r3, r3, #0
8: 1c24 adds r4, r4, #0
a: 1c2d adds r5, r5, #0
c: 1c36 adds r6, r6, #0
e: 1c3f adds r7, r7, #0
10: 1c00 adds r0, r0, #0
12: 1c01 adds r1, r0, #0
14: 1c02 adds r2, r0, #0
16: 1c03 adds r3, r0, #0
18: 1c04 adds r4, r0, #0
1a: 1c05 adds r5, r0, #0
1c: 1c06 adds r6, r0, #0
1e: 1c07 adds r7, r0, #0
note that the bits didnt line up as nicely as before with hex values, doesnt matter look at the binary to see the three bits changing from instruction to instruction.
in this case the assembler chose to use an add instead of mov
Notes:
Encoding: This instruction is encoded as ADD Rd, Rn, #0.
and
Notes
Operand restriction: If a low register is specified for and
H1==0 and H2==0), the result is UNPREDICTABLE .
All this plus a zillion more things you learn when you read the documentation. http://infocenter.arm.com. on the left arm architecture then reference manuals you may have to sacrifice an email address. you can google arm architectural reference manual and you may get lucky...

Cortex m3 first instruction execution

I am using Sourcery CodeBench Lite 2012.03-56 compiler and gdb suite with texane gdb server.
Today I wanted to try FreeRTOS demo example for cheap STM32VLDISCOVERY board, I copied all the source files needed, compiled without errors but the example didn't work. I fired up debugger and noticed that example fails when it is trying to dereference pointer to GPIO registers. Global array variable which contains pointers to GPIO registers:
GPIO_TypeDef* GPIO_PORT[LEDn] = {LED3_GPIO_PORT, LED4_GPIO_PORT};
was not properly initialized and was filled with some random values. I checked preprocessor defines LED3_GPIO_PORT and LED3_GPIO_PORT and they were valid.
After some researching where the problem might be I looked at the start-up file provided for trueSTUDIO found in CMSIS lib. Original startup_stm32f10x_md_vl.S file:
.section .text.Reset_Handler
.weak Reset_Handler
.type Reset_Handler, %function
Reset_Handler:
/* Copy the data segment initializers from flash to SRAM */
movs r1, #0
b LoopCopyDataInit
CopyDataInit:
ldr r3, =_sidata
ldr r3, [r3, r1]
str r3, [r0, r1]
adds r1, r1, #4
LoopCopyDataInit:
ldr r0, =_sdata
ldr r3, =_edata
adds r2, r0, r1
cmp r2, r3
bcc CopyDataInit
ldr r2, =_sbss
b LoopFillZerobss
...
During the debugging I noticed that register r1 is never initialized to zero by first instruction movs r1, #0. Register r1 is used as a counter in loop so when the execution reaches loop LoopCopyDataInit it never enters the loop since register r1 is loaded with some garbage data from previous execution. As the result of this the startup code never initializes the .data section.
When I placed two nop instructions before movs r1, #0 instruction then register r1 was initialized to 0 and the example began to work:
Modified part of startup_stm32f10x_md_vl.S file:
/* Copy the data segment initializers from flash to SRAM */
nop
nop
movs r1, #0
b LoopCopyDataInit
This is disassembly of relevant parts of final code:
Disassembly of section .isr_vector:
08000000 <g_pfnVectors>:
8000000: 20002000 andcs r2, r0, r0
8000004: 08000961 stmdaeq r0, {r0, r5, r6, r8, fp}
...
Disassembly of section .text:
...
8000960 <Reset_Handler>:
8000960: 2100 movs r1, #0
8000962: f000 b804 b.w 800096e <LoopCopyDataInit>
08000966 <CopyDataInit>:
8000966: 4b0d ldr r3, [pc, #52] ; (800099c <LoopFillZerobss+0x16>)
8000968: 585b ldr r3, [r3, r1]
800096a: 5043 str r3, [r0, r1]
800096c: 3104 adds r1, #4
As you can see the ISR vector table is properly pointing to Reset_Handler address. So, what is happening? Why the first instruction movs r1, #0 was never executed in original start-up code?
EDIT:
The original code works when I power off the board and power it back on again. I can reset the MCU multiple times and it works. When I start gdb-server then the code doesn't work, even after reset. I have to power cycle it again to work. I guess this is some debugger weirdness going on.
NOTE:
I had a look what start-up code are other people using with this MCU and they either disable interrupts or load SP register with a linker defined value which is in both cases redundant. If they got hit by this odd behaviour they would not notice it, ever.
Sounds like a bug in your debugger. Probably it sets a breakpoint on the first instruction and either skips it completely or somehow reexecuting it doesn't work properly. The issue could be complicated by the fact that it's a reset vector, maybe it's just not possible to reliably stop at the first instruction. Since the NOPs help, I'd recommend leaving them in place while you're developing your program.
However, there is an alternative solution. Since it's unlikely that you'll need to modify the array, you don't really need it in writable section. To have the compiler put the array in the flash, usually it's enough to declare it as const:
GPIO_TypeDef* const GPIO_PORT[LEDn] = {LED3_GPIO_PORT, LED4_GPIO_PORT};
Nothing is hopping out right away as to what could be wrong there. First, how are you debugging this code? Are you attaching a debugger and then issuing a reset to the processor via JTAG? I would try putting b Reset_Handler in there right after your Reset_Handler: label as your first instruction, flash it on, turn on the board, then connect the JTAG just so you can minimize any possible weirdness from the debugger. Then set your PC to that mov instruction and see if it works. Is a bootloader or boot ROM launching this code? It could be something weird going on with the instruction or data cache.

Resources