7г. A whole project in Cortex-M assembly: STM32F103 firmware without a single line of C
Section 7б taught you to read the compiler's assembly, section 7в — to insert your own
pieces where there is no way around them. Here is the extreme case: the whole BluePill
firmware in assembly. The vector table, reset, a 72 MHz clock, an LED, a button, SysTick,
a UART with interrupt-driven reception — two files for arm-none-eabi-as, the ld linker,
not a single C file and not a single library function. Next to it — the same project in C
with CMSIS, and an honest comparison of the two.
The test bench is _verify/asm7e: the firmware app7e.S, addresses and macros
stm32f103.inc, the linker script linker7e.ld, the C variant app7e.c
and the script run7e.sh. Everything was built in the stm-arm:1 image and run in QEMU 7.2
on the stm32vldiscovery machine: it has a Cortex-M3 core and USART1 at the F1 addresses,
while RCC, flash memory, GPIO and EXTI are not modelled. Addresses and bits were checked against
RM0008 (rev 17) and the stm32f10x.h header from the Keil pack, the core rules — against
the Cortex-M3 guide (DUI 0552A) from the same pack. The check is
_verify/asm7e_check.py.
Foundations: the calling convention and the literal pool — 7б.1 and 7б.4; the .S file,
the Thumb bit, start-up code and the stack being a multiple of 8 — 7в.1–7в.3; the linker
script — 4в.3; what the core does on exception entry — 7а.
Terms used in the documentation
Term Meaning symbol assignment, .equa named assembler constant: an address or a mask .macro/.endman assembler macro: substituted as text at build time conditional assembly, .ifdefbuilding by condition without the preprocessor register alias, .reqa second name for a register read/clear (rc_w1) the bit is cleared by writing one, zero does not touch it ready flag, timeout a readiness flag and a limit on waiting for it multiply by reciprocal division by multiplying by the inverse number caller-saved / callee-saved registers registers the called function may corrupt / must give back
7г.1 A project without C: files and build
| File | What is in it |
|---|---|
stm32f103.inc |
addresses, offsets and bits (.equ) with names from stm32f10x.h; macros for masked writes and flag waits |
app7e.S |
vectors, reset, clock, ports, SysTick, UART, handlers, main |
linker7e.ld |
the script of section 4в: 64 KB of flash memory, 20 KB of RAM |
The build is two commands, without gcc:
arm-none-eabi-as -mcpu=cortex-m3 -mthumb --fatal-warnings -g app7e.S -o app7e.o
arm-none-eabi-ld -T linker7e.ld --gc-sections -Map=app7e.map app7e.o -o app7e.elf
as, called directly, does not run the preprocessor: #include and #ifdef
from 7в.1 do not work here. Their place is taken by the assembler's own directives —
.include "stm32f103.inc" and .ifdef/.else/.endif; symbols for
.ifdef are set by the switch --defsym NAME=1. This is also how the experiments of this section are built:
PERIPH_IN_RAM, BUG_THUMB, BUG_R4, BUG_POP, BUG_RMW.
The QEMU model has 8 KB of RAM, the F103C8 chip has 20 KB. So the top of the
stack in the script is set via PROVIDE(_estack = …), and for QEMU it is
overridden by the linker switch --defsym=_estack=0x20002000: the code is the same,
one word of the vector table changes.
The firmware prints to the UART the frequency, a check of number printing, a mark of the first
second and the echo of a received line with its length. The run in QEMU (hello and \r
fed to the input):
asm7e: SYSCLK=8000000 Hz
dec: 0 7 10 65535 4294967295
t=1000 ms
hello
len=5
8 MHz, not 72: QEMU does not model RCC, the HSERDY flag reads as zero, and
the firmware stays on HSI after the timeout (7г.3). Both builds of the C variant
(-Os and -O2) gave the same output.
7г.2 Addresses and macros
The names in .equ are taken from stm32f10x.h: a reader who knows CMSIS recognises
RCC_CR_HSEON and USART_SR_TXE, and the check compares all 54 values with the
header (it compiles them into an array and compares with the values from the
assembler's object file). Register offsets are fields of the structures
RCC_TypeDef, GPIO_TypeDef and others, checked via offsetof: 21 of 21.
| Name | Value | Where in the documentation |
|---|---|---|
RCC_BASE, FLASH_R_BASE |
0x40021000, 0x40022000 | RM0008, table 3, p. 49 |
EXTI_BASE, GPIOA_BASE, GPIOC_BASE, USART1_BASE |
0x40010400, 0x40010800, 0x40011000, 0x40013800 | RM0008, table 3, p. 50 |
RCC_CR (+0x00): HSEON, HSERDY, PLLON, PLLRDY |
bits 16, 17, 24, 25 | RM0008, 7.3.1, p. 98 |
RCC_CFGR (+0x04): SW, SWS, PPRE1, PLLSRC, PLLMULL |
bits 1:0, 3:2, 10:8, 16, 21:18 | RM0008, 7.3.2, pp. 100–102 |
RCC_APB2ENR (+0x18): IOPAEN, IOPCEN, USART1EN |
bits 2, 4, 14 | RM0008, 7.3.7, pp. 111–112 |
FLASH_ACR (+0x00): LATENCY, PRFTBE |
bits 2:0, 4 | RM0008, p. 59 |
GPIOx_CRL, CRH, IDR, ODR, BSRR |
+0x00, +0x04, +0x08, +0x0C, +0x10 | RM0008, 9.2.1–9.2.5, pp. 170–172 |
EXTI_IMR, EXTI_FTSR, EXTI_PR |
+0x00, +0x0C, +0x14 | RM0008, 10.3.1, 10.3.4, 10.3.6, pp. 210–212 |
USART_SR, DR, BRR, CR1 |
+0x00, +0x04, +0x08, +0x0C | RM0008, 27.6.1–27.6.4, pp. 819–822 |
EXTI0_IRQn, USART1_IRQn |
6 and 37 | RM0008, vector table, pp. 203–204 |
SysTick_BASE, NVIC_BASE, SCB_BASE |
0xE000E010, 0xE000E100, 0xE000ED00 | DUI 0552A, pp. 4-2, 4-33 |
Registers are almost always written the same way: read, clear the field, put in the value, write. A macro does this:
.macro REG_MOD rb, off, mask, val @ reg = (reg & ~mask) | val
ldr r0, [\rb, #\off]
ldr r1, =\mask
bics r0, r0, r1
ldr r1, =\val
orrs r0, r0, r1
str r0, [\rb, #\off]
.endm
ldr r1, =\mask does not always go to the literal pool: if the constant
fits into the instruction, the assembler puts mov.w itself — so RCC_CR_HSEON
became mov.w r1, #65536. Labels inside a macro are written with \@ (.Lwait\@):
the assembler substitutes the invocation number, and two waits in a row do not mix up their labels.
A macro is not a function: each invocation inserts all six instructions again. This is where the size of the assembly variant goes (7г.6).
7г.3 Vectors, reset, clock
The vector table is 16 core exceptions and 43 F103 interrupts (the number
of the last one, USBWakeUp_IRQn, is 42 in stm32f10x.h): 59 words, 236 bytes.
.rept fills the empty places:
.rept USART1_IRQn - EXTI0_IRQn - 1 @ IRQ 7–36
.word Default_Handler
.endr
Reset is copying .data and zeroing .bss with the same loop as
in 7в.2. One thing is added: the STKALIGN bit in SCB->CCR, so that the core aligns
the exception frame to 8 bytes (on F1 it may be off after reset, 7в.3).
After a write to a core register — dsb and isb: the guide requires barriers
when the new value must already apply to the following instructions
(DUI 0552A, p. 2-15). The whole Reset_Handler is 60 bytes.
The clock. HSE 8 MHz → PLL × 9 → 72 MHz. The order per RM0008:
HSEON, wait forHSERDY;- two flash memory wait states (
LATENCY = 2: 48 < SYSCLK ≤ 72 MHz, p. 59) and the prefetch buffer — before switching to 72 MHz; PLLSRC = HSE,PLLMULL9, APB1 divider of 2 (APB1 no higher than 36 MHz, p. 102);PLLON, wait forPLLRDY;SW = PLL, wait untilSWSbecomes10.
Each wait is the WAIT_EQ macro with a limit of HSE_TMO = 0x5000 turns
and a jump to the fallback branch: switch off the PLL and HSE, stay on HSI 8 MHz.
The wait loop is 8 instructions, that is no fewer than 0x5000 × 8 = 163840 clock cycles,
on HSI 8 MHz — no less than 20.48 ms. The crystal start-up time in the F103
documentation is 2 ms, typical (tSU(HSE), table 22). Without a timeout, firmware with
an unsoldered crystal hangs until the watchdog fires; with it, it
runs slower and reports its frequency.
Checking the 72 MHz branch. QEMU does not model RCC, so in QEMU only
the fallback branch ran. The PERIPH_IN_RAM variant moves the RCC, FLASH,
EXTI and GPIO bases into RAM (0x20001000…), and -device loader switches put there
the after-reset values and the ready flags that on the chip the hardware would set
(RCC_CR = 0x02020083, RCC_CFGR = 0x00000008). After set-up
GDB read the cells:
| Register | Before | After | Expected from the bits |
|---|---|---|---|
RCC_CR |
0x02020083 | 0x03030083 | + HSEON, PLLON |
RCC_CFGR |
0x00000008 | 0x001D040A | PLLMULL9 · PLLSRC · PPRE1_DIV2 · SW_PLL |
FLASH_ACR |
0x00000030 | 0x00000012 | PRFTBE · LATENCY_2 |
RCC_APB2ENR |
0 | 0x00004014 | USART1EN · IOPCEN · IOPAEN |
GPIOC_CRH |
0x44444444 | 0x44244444 | PC13: output 2 MHz, push-pull |
GPIOA_CRL |
0x44444444 | 0x44444448 | PA0: input with pull-up |
GPIOA_CRH |
0x44444444 | 0x444444B4 | PA9: alternate function output 50 MHz |
The firmware printed SYSCLK=72000000, and the real (modelled) registers
gave USART1_BRR = 0x271 and SysTick LOAD = 0x1193F. The experiment checks which
bits are written, but not how a real oscillator behaves.
7г.4 Ports, SysTick, UART and printing numbers
Ports. PC13 is the BluePill LED, lit at zero: right after
set-up 1 << 13 is written to BSRR. PA0 is a button to ground: an input with
pull-up (CNF0 = 10, a one in ODR), an EXTI0 interrupt on the falling edge. PA9 is
the TX output, PA10 stays an input after reset.
SysTick. LOAD = f / 1000 − 1: at 72 MHz — 71999 (0x1193F), at
8 MHz — 7999 (0x1F3F, read by GDB in QEMU). The division is one udiv instruction:
Cortex-M3 has it.
UART. The divider with rounding: BRR = (f + 57600) / 115200. At
72 MHz this is 625 = 0x271: mantissa 39, fraction 1/16, USARTDIV = 39.0625 — as
in the RM0008 table, p. 800. At 8 MHz — 69 = 0x45, as in 4в.9. Transmission is
polling TXE and writing to DR. Reception is by interrupt into a ring buffer of
64 bytes: only the handler moves the head, only main moves the tail, so
no lock is needed.
Printing numbers. Digits come from division by 10 with remainder. Instead of udiv
here it is multiplication by the reciprocal:
1: umull r1, r2, r0, r5 @ r2:r1 = n × 0xCCCCCCCD
lsrs r2, r2, #3 @ q = n / 10: старшее слово, сдвинутое ещё на 3 — всего на 35
mls r1, r2, r6, r0 @ остаток n − 10q
0xCCCCCCCD = (2^35 + 2) / 10. Then n × 0xCCCCCCCD / 2^35 = n/10 + n/(5 · 2^35),
and the addition is less than 1/40 for any 32-bit n. The fractional part of n/10 is at most
0.9, the sum does not reach one, and the quotient is correct for all n. The line
dec: 0 7 10 65535 4294967295 checks the edges: zero, one digit, a carry into the next
digit, 16 and 32 bits. The compiler uses the same trick itself: in the C build
with -O2 the code contains the constant 0xCCCCCCCD, and with -Os it chose the short
udiv. The reciprocal is needed where there is no udiv at all — on Cortex-M0.
7г.5 Handlers and the calling convention
On exception entry the core itself pushes eight words onto the stack — r0–r3,
r12, lr, pc, xPSR — and writes the EXC_RETURN value to lr
(DUI 0552A, pp. 2-26 and 2-27). These are exactly the registers the calling
convention allows to be corrupted. So a handler is an ordinary function: bx lr
is enough for it, and r4–r11 it must give back itself if it touches them.
GDB in QEMU stopped the first entry into SysTick_Handler:
lr 0xfffffff9 -7
sp 0x20001fe0 0x20001fe0
0x20001fe0: 0x20000004 0x20000010 0x00000000 0x00000000
0x20001ff0: 0x00000000 0x080004af 0x0800047e 0xa1000000
lr = 0xFFFFFFF9 is a return to Thread mode on the main stack. In the frame: r0–r3,
r12, then the lr of the interrupted code 0x080004AF, pc 0x0800047E — an instruction
inside main_loop where the core will return, and xPSR = 0xA1000000 with a one
in the T bit (bit 24).
All three handlers of the bench get by with these registers and save
nothing: SysTick_Handler uses r0–r3, USART1_IRQHandler uses r0–r3 and
r12. A second register name in the UART handler comes from .req:
.ifdef BUG_R4
nxt .req r4 @ ОШИБКА для опыта: r4 обработчик обязан сохранить сам
.else
nxt .req r12 @ r12 ядро уже сохранило
.endif
The BUG_R4 experiment. main keeps the length of the received line in r4. A handler
that writes to r4 and does not save it crashes nothing — the program
simply prints len=6 instead of len=5. Neither a fault nor a warning.
The rc_w1 flag. An EXTI_PR bit is cleared by writing one, zero changes
nothing (RM0008, pp. 45 and 212). The right way is to write just the mask of your own line:
str. A read-modify-write (ldr, orrs, str) writes ones into
all pending bits and clears other lines' requests. The BUG_RMW experiment in the
PERIPH_IN_RAM variant: 0x3 is put into the EXTI_PR cell in advance (lines 0 and
1 pending), the firmware pends EXTI0 in software via NVIC_ISPR0:
| EXTI0 handler | Written to EXTI_PR |
On the chip |
|---|---|---|
str of the mask |
0x00000001 | only line 0 cleared |
ldr + orrs + str |
0x00000003 | the other line 1 cleared too |
In both cases the handler ran once: key_count = 1, the UART shows key=1.
How many instructions. The QEMU trace (-d exec,nochain -singlestep -dfilter over
the handler addresses) for the same run:
| Handler | Assembly | C, gcc -Os |
|---|---|---|
| SysTick, ordinary tick | 10 instructions | 10 instructions |
| SysTick, with the LED toggle | 15 | 16 |
| USART1, receiving one byte | 16 | 23 |
| statically in the disassembly: SysTick / USART1 / EXTI0 | 15 / 20 / 8 | 16 / 23 / 8 |
In SysTick the compiler did the same as a human. In the UART it saved
r4 and lr (push {r4, lr} … pop {r4, pc}), read SR and DR as
half-words (ldrh, uxth — that is how the fields are declared in stm32f10x.h) and folded
two branches into IT blocks. The difference is seven instructions per byte.
7г.6 Debugging and comparison with C
Disassembler and map. arm-none-eabi-objdump -d app7e.elf shows
what the assembler made of the macros and ldr =: where mov.w appeared, where
the pool is and where there is a filler in it. The pool after bx lr is aligned to 4, and after a
16-bit instruction a .short 0x0000 appears in it — as in
SysTick_Handler and USART1_IRQHandler. The -Map map gives the layout:
.isr_vector 0x08000000 0xec
.text 0x080000ec 0x480
.data 0x20000000 0x4 load address 0x0800056c
.bss 0x20000004 0x58 load address 0x08000570
GDB. QEMU with the switches -S -gdb tcp:127.0.0.1:1234 waits for the debugger.
gdb-multiarch app7e.elf, then target remote 127.0.0.1:1234: the processor
stands at Reset_Handler, sp = 0x20002000, the first words of the table are
0x20002000 and 0x080000ED (the Thumb bit is in place). The assembler with the -g switch
writes line numbers, and stepi goes through the lines of app7e.S. The assembler does not
write frame descriptions, so backtrace in a handler does not
work — you look at x/8wx $sp, as above.
Comparison. The same project in C (app7e.c): CMSIS, no HAL and no
libc, the vector table and reset also in C, -Wall -Wextra -Werror.
| Assembly | C, gcc -Os |
C, gcc -O2 |
|
|---|---|---|---|
flash memory: vectors + code + .data |
236 + 1152 + 4 = 1392 bytes | 236 + 1044 + 4 = 1284 | 236 + 1368 + 4 = 1608 |
RAM: .data + .bss |
4 + 88 = 92 | 4 + 84 = 88 | 4 + 84 = 88 |
| source lines | 446 + 134 (.inc) |
218 | 218 |
| instructions per UART byte | 16 | 23 | — |
armclang 6.24 on the same app7e.c (object file, fromelf -z): with -Oz —
1028 bytes of code and 335 bytes of constants, with -Os — 1392 and 303.
The honest result: assembly did not give smaller firmware — gcc -Os is 108 bytes
shorter. The macros reload bases and masks again, while the compiler keeps them in
registers and shared pools. The gain of assembly is in hot spots: seven instructions
for every received byte and full control over which registers the
handler touches. Development time was not measured; but the three experiments with errors below
are ones the compiler would never have made, and the assembler let them through silently.
When assembly is justified:
- start-up code before the stack and
.dataexist (7в.2); - task switching — saving another task's
r4–r11(7в.7); - places with cycle counting, where every instruction and its order matter;
- instructions that C does not have:
ldrex/strex,dsb,cpsid, DSP (7в.5–7в.6).
When it is not: peripheral set-up, protocol parsing, application logic. There
C is shorter, quicker to write, and stm32f10x.h checks the names at build time.
7г.7 Pitfalls
HardFault on the first interrupt. .type name, %function (or
.thumb_func) is forgotten on a handler: the vector table has an address without the Thumb bit.
The BUG_THUMB experiment — SysTick_Handler without .type: the first tick gave
HardFault CFSR=00020000 PC=0800036C — INVSTATE, the frame holds the even address of the
handler. Per the guide the least significant bit of each vector must be 1
(DUI 0552A, p. 2-23).
"offset out of range" on ldr r0, =constant. The assembler puts the literal pool
at the end of the section, and ldr from the pool reaches only a short way forward
(within 4 KB). A function with 4096 bytes of data after ldr = did not
assemble: Error: offset out of range. The .ltorg directive after bx lr
puts the pool right there, aligned to 4: ldr r0, [pc, #0] and right after it
.word 0x12345678.
"thumb conditional instruction should be in IT block". In unified syntax
a conditional instruction outside it is an error; it eq covers one instruction, and
addne after it is the same error again. The -mimplicit-it=always switch silently
inserts it eq itself, and the logic error goes unnoticed: better not to
turn it on.
A register gets corrupted "by itself". A handler writes to r4–r11 without push:
the BUG_R4 experiment, len=6 instead of 5. No fault.
HardFault with PC = 0 after returning from a function. push and pop with a different
number of registers. The BUG_POP experiment: push {r4, r5, r6, lr}, but
pop {r4, r5, pc} — the saved r6, equal to zero, went into pc:
HardFault CFSR=00020000 PC=00000000, and the stack is shifted by a word.
Presses on other EXTI lines are lost. An rc_w1 flag cleared via
|=: the BUG_RMW experiment, 0x3 written instead of 0x1.
Core set-up takes effect "not at once". After writing to SCB registers — dsb and isb.
In QEMU the error is not visible without them: the model does not delay writes; the rule comes from
the guide.
Hangs at start-up on a board without a crystal. Waiting for HSERDY without a limit.
In QEMU, with a limit, the firmware went to HSI and printed SYSCLK=8000000.
72 MHz, but flash read failures. LATENCY is set
after switching to the PLL, not before.
7г.8 Summary
- Firmware without C:
as+ld,.includeand.ifdefinstead of the preprocessor,--defsymfor variants. Vectors — 59 words, 236 bytes; reset — 60 bytes. .equnames come fromstm32f10x.h: 54 values and 21 offsets checked against the header.- The clock with a timeout of 0x5000 turns (no less than 20.48 ms on HSI);
in QEMU — the fallback 8 MHz, the 72 MHz branch checked with RAM cells:
RCC_CFGR = 0x001D040A,FLASH_ACR = 0x12,BRR = 0x271,LOAD = 0x1193F. - Division by 10 —
umullby 0xCCCCCCCD and a shift by 35; correct for all 32-bit numbers. - The core saves eight words; the bench handlers get by with
r0–r3andr12. Touchr4—len=6instead of 5 without any fault. - rc_w1:
strof the mask wrote 0x1, read-modify-write — 0x3. - UART: 16 instructions per byte versus 23 for
gcc -Os; but the whole firmware in assembly is 1392 bytes versus 1284 for C.
Full sources
stm32f103.inc — STM32F103 addresses and bits with names from stm32f10x.h, macros for masked writes and flag waits.
/* Раздел 7г: адреса и биты STM32F103 для ассемблера. Имена — как в stm32f10x.h и core_cm3.h,
* страницы — RM0008 rev 17 и руководство по Cortex-M3 (DUI 0552A). Проверка сверяет каждое
* значение с заголовками: имя здесь = макрос там. */
/* ── базовые адреса периферии: RM0008, таблица 3 ── */
.ifndef PERIPH_IN_RAM
.equ RCC_BASE, 0x40021000 @ с. 49
.equ FLASH_R_BASE, 0x40022000 @ с. 49
.equ EXTI_BASE, 0x40010400 @ с. 50
.equ GPIOA_BASE, 0x40010800 @ с. 50
.equ GPIOC_BASE, 0x40011000 @ с. 50
.else @ опыт: регистры RCC, FLASH, EXTI и GPIO — ячейки ОЗУ
.equ RCC_BASE, 0x20001000 @ (QEMU их не моделирует)
.equ FLASH_R_BASE, 0x20001100
.equ EXTI_BASE, 0x20001200
.equ GPIOA_BASE, 0x20001300
.equ GPIOC_BASE, 0x20001400
.endif
.equ USART1_BASE, 0x40013800 @ с. 50
/* ── смещения регистров (поля структур RCC_TypeDef, GPIO_TypeDef …) ── */
.equ RCC_CR, 0x00 @ с. 98
.equ RCC_CFGR, 0x04 @ с. 100
.equ RCC_APB2ENR, 0x18 @ с. 111
.equ FLASH_ACR, 0x00 @ с. 59
.equ GPIO_CRL, 0x00 @ с. 170
.equ GPIO_CRH, 0x04 @ с. 171
.equ GPIO_IDR, 0x08 @ с. 171
.equ GPIO_ODR, 0x0C @ с. 172
.equ GPIO_BSRR, 0x10 @ с. 172
.equ EXTI_IMR, 0x00 @ с. 210
.equ EXTI_FTSR, 0x0C @ с. 211
.equ EXTI_PR, 0x14 @ с. 212
.equ USART_SR, 0x00 @ с. 819
.equ USART_DR, 0x04 @ с. 821
.equ USART_BRR, 0x08 @ с. 821
.equ USART_CR1, 0x0C @ с. 822
/* ── биты ── */
.equ RCC_CR_HSEON, 0x00010000
.equ RCC_CR_HSERDY, 0x00020000
.equ RCC_CR_PLLON, 0x01000000
.equ RCC_CR_PLLRDY, 0x02000000
.equ RCC_CFGR_SW, 0x00000003
.equ RCC_CFGR_SW_PLL, 0x00000002
.equ RCC_CFGR_SWS, 0x0000000C
.equ RCC_CFGR_SWS_PLL, 0x00000008
.equ RCC_CFGR_PPRE1, 0x00000700
.equ RCC_CFGR_PPRE1_DIV2, 0x00000400 @ APB1 не выше 36 МГц: с. 102
.equ RCC_CFGR_PLLSRC, 0x00010000
.equ RCC_CFGR_PLLMULL, 0x003C0000
.equ RCC_CFGR_PLLMULL9, 0x001C0000 @ 8 МГц × 9 = 72 МГц
.equ FLASH_ACR_LATENCY, 0x07
.equ FLASH_ACR_LATENCY_2, 0x02 @ два такта ожидания: 48 < SYSCLK ≤ 72 МГц, с. 59
.equ FLASH_ACR_PRFTBE, 0x10
.equ RCC_APB2ENR_IOPAEN, 0x00000004
.equ RCC_APB2ENR_IOPCEN, 0x00000010
.equ RCC_APB2ENR_USART1EN, 0x00004000
.equ GPIO_CRL_MODE0, 0x00000003
.equ GPIO_CRL_CNF0, 0x0000000C
.equ GPIO_CRL_CNF0_1, 0x00000008 @ вход с подтяжкой: направление задаёт ODR
.equ GPIO_CRH_MODE9, 0x00000030
.equ GPIO_CRH_CNF9, 0x000000C0
.equ GPIO_CRH_CNF9_1, 0x00000080 @ с MODE9 = 11: альтернативный двухтактный, 50 МГц
.equ GPIO_CRH_MODE13, 0x00300000
.equ GPIO_CRH_MODE13_1, 0x00200000 @ выход 2 МГц, CNF13 = 00 — двухтактный
.equ GPIO_CRH_CNF13, 0x00C00000
.equ GPIO_ODR_ODR0, 0x0001
.equ GPIO_ODR_ODR13, 0x2000
.equ EXTI_IMR_MR0, 0x00000001
.equ EXTI_FTSR_TR0, 0x00000001
.equ EXTI_PR_PR0, 0x00000001 @ rc_w1: сбрасывается записью единицы, с. 212
.equ USART_SR_RXNE, 0x0020
.equ USART_SR_TXE, 0x0080
.equ USART_CR1_RE, 0x0004
.equ USART_CR1_TE, 0x0008
.equ USART_CR1_RXNEIE, 0x0020
.equ USART_CR1_UE, 0x2000
/* ── ядро Cortex-M3: core_cm3.h, DUI 0552A ── */
.equ SysTick_BASE, 0xE000E010 @ с. 4-33
.equ SysTick_CTRL, 0x00
.equ SysTick_LOAD, 0x04
.equ SysTick_VAL, 0x08
.equ SysTick_CTRL_ENABLE_Msk, 1
.equ SysTick_CTRL_TICKINT_Msk, 2
.equ SysTick_CTRL_CLKSOURCE_Msk, 4
.equ NVIC_BASE, 0xE000E100 @ ISER0, ISER1 …: с. 4-3
.equ SCB_BASE, 0xE000ED00
.equ SCB_CCR, 0x14
.equ SCB_CFSR, 0x28
.equ SCB_CCR_STKALIGN_Msk, 0x200 @ с. 4-20
.equ EXTI0_IRQn, 6
.equ USART1_IRQn, 37
/* ── макросы: запись в регистр по маске. rb — регистр с базой; портят r0 и r1 ── */
.macro REG_SET rb, off, bits @ reg |= bits
ldr r0, [\rb, #\off]
ldr r1, =\bits
orrs r0, r0, r1
str r0, [\rb, #\off]
.endm
.macro REG_CLR rb, off, bits @ reg &= ~bits
ldr r0, [\rb, #\off]
ldr r1, =\bits
bics r0, r0, r1
str r0, [\rb, #\off]
.endm
.macro REG_MOD rb, off, mask, val @ reg = (reg & ~mask) | val
ldr r0, [\rb, #\off]
ldr r1, =\mask
bics r0, r0, r1
ldr r1, =\val
orrs r0, r0, r1
str r0, [\rb, #\off]
.endm
/* ждать (reg & mask) == want не дольше HSE_TMO оборотов, иначе перейти на fail; портит r0–r2 */
.macro WAIT_EQ rb, off, mask, want, fail
ldr r2, =HSE_TMO
.Lwait\@:
ldr r0, [\rb, #\off]
ldr r1, =\mask
ands r0, r0, r1
ldr r1, =\want
cmp r0, r1
beq .Lok\@
subs r2, r2, #1
bne .Lwait\@
b \fail
.Lok\@:
.endm
app7e.S — the whole firmware: vectors, reset, clock, ports, SysTick, USART1, handlers, main.
/* Раздел 7г: прошивка STM32F103 целиком на ассемблере, без единой строки C и без libc.
* Тактирование 72 МГц от HSE через PLL, светодиод PC13, кнопка PA0 по EXTI0, SysTick 1 мс,
* USART1 115200: печать строк и чисел, приём по прерыванию в кольцевой буфер.
* Сборка: arm-none-eabi-as -mcpu=cortex-m3 -mthumb app7e.S, затем arm-none-eabi-ld -T linker7e.ld.
* Опыты (--defsym ИМЯ=1): PERIPH_IN_RAM, BUG_THUMB, BUG_R4, BUG_POP, BUG_RMW — см. текст раздела. */
.syntax unified
.cpu cortex-m3
.thumb
.include "stm32f103.inc"
.equ HSE_TMO, 0x5000 @ оборотов ожидания флага, потом — тайм-аут
.equ RX_SIZE, 64 @ кольцевой буфер приёма, степень двойки
.equ RX_MASK, RX_SIZE - 1
.equ LED_HALF, 500 @ мс между переключениями светодиода
/* ── таблица векторов: 16 исключений ядра и 43 прерывания F103 ── */
.section .isr_vector, "a", %progbits
.global vectors
vectors:
.word _estack @ 0: начальный MSP
.word Reset_Handler @ 1
.word Default_Handler @ 2: NMI
.word HardFault_Handler @ 3
.word Default_Handler, Default_Handler, Default_Handler @ 4–6: MemManage, BusFault, UsageFault
.word 0, 0, 0, 0 @ 7–10
.word Default_Handler, Default_Handler, 0, Default_Handler @ 11 SVCall, 12 DebugMon, 13, 14 PendSV
.word SysTick_Handler @ 15
.rept EXTI0_IRQn @ IRQ 0–5
.word Default_Handler
.endr
.word EXTI0_IRQHandler @ IRQ 6
.rept USART1_IRQn - EXTI0_IRQn - 1 @ IRQ 7–36
.word Default_Handler
.endr
.word USART1_IRQHandler @ IRQ 37
.rept 42 - USART1_IRQn @ IRQ 38–42
.word Default_Handler
.endr
/* ── сброс: .data из флеш-памяти в ОЗУ, .bss в ноль, выравнивание стека, main ── */
.section .text.Reset_Handler, "ax", %progbits
.global Reset_Handler
.type Reset_Handler, %function
Reset_Handler:
ldr r0, =_sdata
ldr r1, =_edata
ldr r2, =_sidata
1: cmp r0, r1
ittt lo
ldrlo r3, [r2], #4
strlo r3, [r0], #4
blo 1b
ldr r0, =_sbss
ldr r1, =_ebss
movs r2, #0
2: cmp r0, r1
itt lo
strlo r2, [r0], #4
blo 2b
ldr r3, =SCB_BASE @ кадр исключения — на границе 8 байт (на F1 бит бывает сброшен)
REG_SET r3, SCB_CCR, SCB_CCR_STKALIGN_Msk
dsb @ запись в регистр ядра завершена…
isb @ …и следующие команды видят новое значение
b main
.size Reset_Handler, . - Reset_Handler
.section .text.Default_Handler, "ax", %progbits
.global Default_Handler
.type Default_Handler, %function
Default_Handler:
b .
.size Default_Handler, . - Default_Handler
/* ── тактирование: HSE 8 МГц → PLL × 9 → 72 МГц; r0 = частота SYSCLK, Гц ── */
.section .text.clock_init, "ax", %progbits
.type clock_init, %function
clock_init:
push {r4, lr}
ldr r4, =RCC_BASE
REG_SET r4, RCC_CR, RCC_CR_HSEON
WAIT_EQ r4, RCC_CR, RCC_CR_HSERDY, RCC_CR_HSERDY, .Lhsi
ldr r3, =FLASH_R_BASE @ флеш-память — до переключения на 72 МГц
movs r0, #(FLASH_ACR_PRFTBE | FLASH_ACR_LATENCY_2)
str r0, [r3, #FLASH_ACR]
REG_MOD r4, RCC_CFGR, (RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL | RCC_CFGR_PPRE1), (RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL9 | RCC_CFGR_PPRE1_DIV2)
REG_SET r4, RCC_CR, RCC_CR_PLLON
WAIT_EQ r4, RCC_CR, RCC_CR_PLLRDY, RCC_CR_PLLRDY, .Lhsi
REG_MOD r4, RCC_CFGR, RCC_CFGR_SW, RCC_CFGR_SW_PLL
WAIT_EQ r4, RCC_CFGR, RCC_CFGR_SWS, RCC_CFGR_SWS_PLL, .Lhsi
ldr r0, =72000000
pop {r4, pc}
.Lhsi: @ кварц или PLL не готовы: остаться на HSI 8 МГц
REG_CLR r4, RCC_CFGR, RCC_CFGR_SW
REG_CLR r4, RCC_CR, (RCC_CR_PLLON | RCC_CR_HSEON)
ldr r0, =8000000
pop {r4, pc}
.size clock_init, . - clock_init
/* ── порты: PC13 — светодиод, PA0 — кнопка на землю, PA9/PA10 — USART1 ── */
.section .text.gpio_init, "ax", %progbits
.type gpio_init, %function
gpio_init:
ldr r3, =RCC_BASE
REG_SET r3, RCC_APB2ENR, (RCC_APB2ENR_IOPAEN | RCC_APB2ENR_IOPCEN | RCC_APB2ENR_USART1EN)
ldr r3, =GPIOC_BASE
REG_MOD r3, GPIO_CRH, (GPIO_CRH_MODE13 | GPIO_CRH_CNF13), GPIO_CRH_MODE13_1
movs r0, #GPIO_ODR_ODR13 @ светодиод BluePill горит при 0: погасить
str r0, [r3, #GPIO_BSRR]
ldr r3, =GPIOA_BASE
REG_MOD r3, GPIO_CRL, (GPIO_CRL_MODE0 | GPIO_CRL_CNF0), GPIO_CRL_CNF0_1
REG_SET r3, GPIO_ODR, GPIO_ODR_ODR0 @ подтяжка вверх
REG_MOD r3, GPIO_CRH, (GPIO_CRH_MODE9 | GPIO_CRH_CNF9), (GPIO_CRH_MODE9 | GPIO_CRH_CNF9_1)
ldr r3, =EXTI_BASE @ PA0 → EXTI0 по спаду (AFIO_EXTICR1 после сброса = порт A)
REG_SET r3, EXTI_FTSR, EXTI_FTSR_TR0
REG_SET r3, EXTI_IMR, EXTI_IMR_MR0
ldr r3, =NVIC_BASE
movs r0, #(1 << EXTI0_IRQn)
str r0, [r3, #0] @ ISER0: запись единицы разрешает, нули ничего не меняют
bx lr
.size gpio_init, . - gpio_init
/* ── USART1 115200 8N1 и прерывание приёма; r0 = частота PCLK2, Гц ── */
.section .text.uart_init, "ax", %progbits
.type uart_init, %function
uart_init:
ldr r3, =USART1_BASE
ldr r1, =115200
add r0, r0, r1, lsr #1 @ (f + 57600) / 115200 — делитель с округлением
udiv r0, r0, r1
str r0, [r3, #USART_BRR]
ldr r0, =(USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | USART_CR1_RXNEIE)
str r0, [r3, #USART_CR1]
ldr r3, =NVIC_BASE
movs r0, #(1 << (USART1_IRQn - 32))
str r0, [r3, #4] @ ISER1
bx lr
.size uart_init, . - uart_init
/* ── SysTick: прерывание раз в 1 мс; r0 = частота ядра, Гц ── */
.section .text.systick_init, "ax", %progbits
.type systick_init, %function
systick_init:
ldr r3, =SysTick_BASE
movs r1, #1000
udiv r0, r0, r1
subs r0, r0, #1 @ LOAD = f / 1000 − 1
str r0, [r3, #SysTick_LOAD]
movs r0, #0
str r0, [r3, #SysTick_VAL]
movs r0, #(SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk)
str r0, [r3, #SysTick_CTRL]
bx lr
.size systick_init, . - systick_init
/* ── вывод: байт, строка, десятичное и шестнадцатеричное число. Портят только r0–r3, r12 ── */
.section .text.uart_putc, "ax", %progbits
.type uart_putc, %function
uart_putc: @ r0 = байт
ldr r1, =USART1_BASE
1: ldr r2, [r1, #USART_SR]
tst r2, #USART_SR_TXE
beq 1b
str r0, [r1, #USART_DR]
bx lr
.size uart_putc, . - uart_putc
.section .text.uart_puts, "ax", %progbits
.type uart_puts, %function
uart_puts: @ r0 = строка с нулём в конце
push {r4, lr}
mov r4, r0
1: ldrb r0, [r4], #1
cbz r0, 2f
bl uart_putc
b 1b
2: pop {r4, pc}
.size uart_puts, . - uart_puts
.section .text.uart_putdec, "ax", %progbits
.type uart_putdec, %function
uart_putdec: @ r0 = число без знака
push {r4, r5, r6, lr} @ четыре слова: стек остаётся кратен 8
sub sp, sp, #16 @ буфер под 10 цифр
add r4, sp, #16 @ цифры пишутся справа налево
ldr r5, =0xCCCCCCCD @ 2^35 / 10, округлено вверх
movs r6, #10
1: umull r1, r2, r0, r5 @ r2:r1 = n × 0xCCCCCCCD
lsrs r2, r2, #3 @ q = n / 10: старшее слово, сдвинутое ещё на 3 — всего на 35
mls r1, r2, r6, r0 @ остаток n − 10q
adds r1, r1, #'0'
strb r1, [r4, #-1]!
movs r0, r2
bne 1b
add r6, sp, #16
2: ldrb r0, [r4], #1
bl uart_putc
cmp r4, r6
bne 2b
add sp, sp, #16
.ifdef BUG_POP
pop {r4, r5, pc} @ ОШИБКА для опыта: снято на слово меньше, чем положено
.else
pop {r4, r5, r6, pc}
.endif
.size uart_putdec, . - uart_putdec
.section .text.uart_puthex, "ax", %progbits
.type uart_puthex, %function
uart_puthex: @ r0 = слово → 8 шестнадцатеричных цифр
push {r4, r5, r6, lr}
mov r4, r0
movs r5, #28
1: lsr r0, r4, r5
and r0, r0, #0xF
cmp r0, #10
ite lo
addlo r0, r0, #'0'
addhs r0, r0, #('A' - 10)
bl uart_putc
subs r5, r5, #4
bpl 1b
pop {r4, r5, r6, pc}
.size uart_puthex, . - uart_puthex
/* ── кольцевой буфер приёма: r0 = байт или −1, если пусто ── */
.section .text.rx_get, "ax", %progbits
.type rx_get, %function
rx_get:
ldr r1, =rx
ldr r2, [r1, #4] @ tail — двигает только main
ldr r3, [r1, #0] @ head — двигает только прерывание
cmp r2, r3
beq 1f
adds r3, r1, #12
ldrb r0, [r3, r2]
adds r2, r2, #1
and r2, r2, #RX_MASK
str r2, [r1, #4]
bx lr
1: mov r0, #-1
bx lr
.size rx_get, . - rx_get
/* ── обработчики. При входе ядро само кладёт в стек r0–r3, r12, lr, pc, xPSR,
* а в lr пишет EXC_RETURN. Обработчик, которому хватает этих регистров, ничего не сохраняет. ── */
.section .text.SysTick_Handler, "ax", %progbits
.global SysTick_Handler
.ifndef BUG_THUMB
.type SysTick_Handler, %function @ без этой строки в векторе адрес без бита Thumb
.endif
SysTick_Handler:
ldr r0, =ms_ticks
ldr r1, [r0]
adds r1, r1, #1
str r1, [r0]
ldr r0, =led_cnt
ldr r1, [r0]
subs r1, r1, #1
bne 1f
ldr r2, =GPIOC_BASE @ ODR пишет только этот обработчик — чтение-запись безопасно
ldr r3, [r2, #GPIO_ODR]
eor r3, r3, #GPIO_ODR_ODR13
str r3, [r2, #GPIO_ODR]
movw r1, #LED_HALF
1: str r1, [r0]
bx lr
.size SysTick_Handler, . - SysTick_Handler
.ifdef BUG_R4
nxt .req r4 @ ОШИБКА для опыта: r4 обработчик обязан сохранить сам
.else
nxt .req r12 @ r12 ядро уже сохранило
.endif
.section .text.USART1_IRQHandler, "ax", %progbits
.global USART1_IRQHandler
.type USART1_IRQHandler, %function
USART1_IRQHandler:
ldr r0, =USART1_BASE
ldr r1, [r0, #USART_SR]
tst r1, #USART_SR_RXNE
beq 9f
ldr r1, [r0, #USART_DR] @ чтение DR сбрасывает RXNE
ldr r0, =rx
ldr r2, [r0, #0] @ head
add nxt, r2, #1
and nxt, nxt, #RX_MASK
ldr r3, [r0, #4] @ tail
cmp nxt, r3
beq 8f @ буфер полон: байт пропадает
adds r3, r0, #12
strb r1, [r3, r2]
str nxt, [r0, #0]
bx lr
8: ldr r1, [r0, #8]
adds r1, r1, #1
str r1, [r0, #8] @ rx.lost++
9: bx lr
.size USART1_IRQHandler, . - USART1_IRQHandler
.section .text.EXTI0_IRQHandler, "ax", %progbits
.global EXTI0_IRQHandler
.type EXTI0_IRQHandler, %function
EXTI0_IRQHandler:
ldr r0, =EXTI_BASE
movs r1, #EXTI_PR_PR0
.ifdef BUG_RMW
ldr r2, [r0, #EXTI_PR] @ ОШИБКА для опыта: чтение-изменение-запись rc_w1
orrs r1, r1, r2 @ сбросит все ждущие линии, а не только свою
.endif
str r1, [r0, #EXTI_PR] @ единица сбрасывает PR0, нули не трогают остальные
ldr r0, =key_count
ldr r1, [r0]
adds r1, r1, #1
str r1, [r0]
bx lr
.size EXTI0_IRQHandler, . - EXTI0_IRQHandler
.section .text.HardFault_Handler, "ax", %progbits
.global HardFault_Handler
.type HardFault_Handler, %function
HardFault_Handler: @ не возвращается: r4, r5 можно не сохранять
mrs r5, msp @ кадр прерванного кода: pc — шестое слово
ldr r4, =SCB_BASE
ldr r0, =msg_hf
bl uart_puts
ldr r0, [r4, #SCB_CFSR]
bl uart_puthex
ldr r0, =msg_pc
bl uart_puts
ldr r0, [r5, #24]
bl uart_puthex
ldr r0, =msg_crlf
bl uart_puts
b .
.size HardFault_Handler, . - HardFault_Handler
/* ── main: настройка, затем цикл: секунда, кнопка, эхо строки ── */
.section .text.main, "ax", %progbits
.global main, main_loop, one_second
.type main, %function
main:
bl clock_init
mov r5, r0 @ r5 = SYSCLK до конца программы
ldr r1, =sysclk_hz
str r0, [r1]
bl gpio_init
mov r0, r5 @ PCLK2 = SYSCLK: делитель APB2 = 1
bl uart_init
mov r0, r5
bl systick_init
cpsie i
.ifdef PERIPH_IN_RAM @ опыт: «нажатие» — прерывание EXTI0 ставится в очередь программно
ldr r3, =NVIC_BASE
movs r0, #(1 << EXTI0_IRQn)
str r0, [r3, #0x100] @ ISPR0
.endif
ldr r0, =msg_hello
bl uart_puts
mov r0, r5
bl uart_putdec
ldr r0, =msg_dec
bl uart_puts
ldr r6, =dec_tests
movs r7, #(dec_tests_end - dec_tests) / 4
1: movs r0, #' '
bl uart_putc
ldr r0, [r6], #4
bl uart_putdec
subs r7, r7, #1
bne 1b
ldr r0, =msg_crlf
bl uart_puts
movs r4, #0 @ r4 — длина принятой строки
movs r6, #0 @ r6 = 1 — секунда уже напечатана
movs r7, #0 @ r7 — сколько нажатий уже напечатано
main_loop:
cbnz r6, 2f
ldr r0, =ms_ticks
ldr r0, [r0]
cmp r0, #1000
blo 2f
movs r6, #1
one_second:
ldr r0, =msg_1s
bl uart_puts
2: ldr r0, =key_count
ldr r0, [r0]
cmp r0, r7
beq 3f
mov r7, r0
ldr r0, =msg_key
bl uart_puts
mov r0, r7
bl uart_putdec
ldr r0, =msg_crlf
bl uart_puts
3: bl rx_get
cmp r0, #0
blt main_loop
cmp r0, #'\r'
beq 4f
cmp r0, #'\n'
beq 4f
adds r4, r4, #1
bl uart_putc @ эхо
b main_loop
4: cmp r4, #0
beq main_loop @ пустая строка — пара \r\n
ldr r0, =msg_len
bl uart_puts
mov r0, r4
bl uart_putdec
ldr r0, =msg_crlf
bl uart_puts
movs r4, #0
b main_loop
.size main, . - main
/* ── константы во флеш-памяти ── */
.section .rodata, "a", %progbits
.p2align 2
dec_tests:
.word 0, 7, 10, 65535, 4294967295
dec_tests_end:
msg_hello: .asciz "asm7e: SYSCLK="
msg_dec: .asciz " Hz\r\ndec:"
msg_crlf: .asciz "\r\n"
msg_1s: .asciz "t=1000 ms\r\n"
msg_key: .asciz "key="
msg_len: .asciz "\r\nlen="
msg_hf: .asciz "HardFault CFSR="
msg_pc: .asciz " PC="
/* ── переменные ── */
.section .data, "aw", %progbits
.p2align 2
.global led_cnt
led_cnt: .word LED_HALF @ начальное значение копирует Reset_Handler
.section .bss, "aw", %nobits
.p2align 2
.global ms_ticks, key_count, sysclk_hz, rx
ms_ticks: .space 4
key_count: .space 4
sysclk_hz: .space 4
rx: .space 12 + RX_SIZE @ head, tail, lost, данные
linker7e.ld — the linker script for STM32F103C8.
/* Раздел 7г: скрипт раздела 4в для STM32F103C8 — 64 КБ флеш-памяти, 20 КБ ОЗУ.
* Для QEMU (stm32vldiscovery, 8 КБ ОЗУ) вершину стека задают снаружи: --defsym=_estack=0x20002000. */
ENTRY(Reset_Handler)
MEMORY
{
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 64K
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 20K
}
PROVIDE(_estack = ORIGIN(RAM) + LENGTH(RAM));
_stack_size = 0x400;
SECTIONS
{
.isr_vector :
{
KEEP(*(.isr_vector))
} > FLASH
.text :
{
*(.text .text.*)
*(.rodata .rodata.*)
. = ALIGN(4);
_etext = .;
} > FLASH
.data :
{
_sdata = .;
*(.data .data.*)
. = ALIGN(4);
_edata = .;
} > RAM AT > FLASH
_sidata = LOADADDR(.data);
.bss (NOLOAD) :
{
_sbss = .;
*(.bss .bss.*)
*(COMMON)
. = ALIGN(4);
_ebss = .;
} > RAM
ASSERT(_ebss + _stack_size <= _estack, "RAM too small for .data + .bss + stack")
}
Next: section 8 "Input/output ports (GPIO)".