Skip to content

perf(core): reduce code size by linking peripheral drivers lazily - #3117

Merged
fpistm merged 8 commits into
stm32duino:mainfrom
fpistm:improve_size
Nov 24, 2026
Merged

fpistm merged 8 commits into
stm32duino:mainfrom
fpistm:improve_size

Conversation

@fpistm

@fpistm fpistm commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Reduce the flash and RAM used by sketches that do not use every peripheral. Before this PR, a bare Blink linked the UART, timer, EXTI and DAC/PWM drivers, malloc and stdio, none of which it uses.

Eight commits, each building on its own:

  1. perf(core): decouple pinMode from the PWM and DAC code
    pinMode() called pwm_stop()/dac_stop() directly, so every sketch using pinMode() or digitalWrite() linked the whole HardwareTimer, TIM and ADC/DAC stack. The stop is now done through a weak analog_output_stop() defined in wiring_analog.c, which is only linked when the sketch uses analogWrite().
  2. perf(core): link the peripheral drivers lazily
    uart.c, interrupt.cpp, HardwareTimer.cpp and analog.cpp move from libraries/SrcWrapper to cores/arduino/stm32, so they are members of core.a, only extracted when referenced. The ADC, DAC and TIM MSP functions are renamed (adc_msp_init(), dac_msp_init(), timer_msp_init(), ...), made static and called explicitly around HAL_xxx_Init()/HAL_xxx_DeInit() (see the SPI does not work without a call to delay(0) #797 note below). timer.c stays in SrcWrapper and only keeps the clock and IRQ helpers.
  3. perf(core): add a weak exit() to avoid linking the UART driver
    crt0 references exit(), whose C library version pulls the stdio cleanup, then _write() in Print.cpp, then the whole UART driver. A weak exit() that halts replaces it.
  4. refactor(usb): call the PCD MSP functions explicitly
    Same approach as for ADC/DAC/TIM, applied to HAL_PCD_MspInit()/HAL_PCD_MspDeInit() in usbd_conf.c, so no HAL MSP function relies on the weak vs strong resolution anymore.
  5. refactor(core): implement _write() in the core
    _write() moves from the ArduinoCore-API Print.cpp patch to cores/arduino/stm32/write.cpp, a core.a member only extracted when the C library requests _write(). stdout/stderr (printf(), core logs) go to the debug UART through uart_debug_write(), initialized on demand when no Serial uses it. The patch is removed from CI/update/patch/api.
  6. perf(uart): split the interrupt driven code from the UART driver
    The debug UART only needs uart_init() and the polling uart_debug_write(). The USARTx_IRQHandler(), the HAL callbacks and the interrupt driven functions move to cores/arduino/stm32/uart_serial.c, only extracted when HardwareSerial is used. A sketch not using Serial can define its own USARTx_IRQHandler() even in a build with the core logs enabled.
  7. chore(api): update ArduinoCore-API submodule
    Points cores/arduino/api to the revert of the weak _write() hook (ed8a91e). Needed by commit 5: without it both Print.cpp and write.cpp define a weak _write().
  8. fix(cmake): scan the core again after the C library
    The C library requests _write() but is scanned after libcore_bin.a in the CMake build, so write.cpp.o was never extracted. The core archive and the C library are now in a LINK_GROUP:RESCAN (CMake 3.24 or later), like the --start-group of platform.txt.

This PR fixes/implements the following bugs/features

  • Feature: code size reduction
  • Breaking changes (behaviour of exit(), and sketches calling the HAL init functions directly, see below)

Motivation

Code size is the main limit on the smaller STM32 parts. Flash, in bytes, from a build of one Nucleo board per series (31 boards), -Os:

Sketch Average change Range
Blink -55% -45% (H563ZI) to -73% (C031C6)
Serial -22% -14% (C562RE) to -33% (F207ZG)
Sketch using Serial, Wire, SPI, ADC, PWM, timer and EXTI unchanged (0.0%) -44 to +48 bytes, +208 bytes on C562RE

Examples: Blink on G071RB 13412 -> 5196, on F103RB 9744 -> 4660. RAM (data + bss) also drops by about 750 bytes on Blink and Serial, and by about 310 bytes on the all-peripherals sketch.

Sizes are the text + data of the ELF, main (bec38fd) vs the first four commits (c429227), 31 boards, same sketches and toolchain. The build matrix below was run again on the current head and gives the same picture.

Weak/strong linking and #797

#797 was caused by strong overrides living in core.a members that nothing referenced, so the weak default won. This PR keeps that class of problem out of the moved code:

  • The overrides left in core.a members are the IRQ handlers and the HAL callbacks the core itself uses. They are only needed when the peripheral is used through a core API, and that reference extracts the member. The IRQ handlers only act on handles owned by the core drivers (HardwareTimer_Handle[], uart_handlers[], ...), so they did nothing when the driver was not used.
  • The HAL MSP functions (HAL_TIM_Base_MspInit, HAL_ADC_MspInit, HAL_DAC_MspInit, HAL_PCD_MspInit, ...) are no longer overrides of the HAL weak functions. They are renamed, made static and called explicitly by the core: before HAL_xxx_Init(), because the HAL accesses the registers right away and needs the clock, and after HAL_xxx_DeInit(). The result does not depend on the weak vs strong symbol resolution anymore, wherever the code lives.
  • The unused HAL_TIM_OC_Msp* and HAL_TIM_IC_Msp* overrides are removed: the core never calls HAL_TIM_OC_Init() nor HAL_TIM_IC_Init().
  • I checked on F401RE and L476RG, on the old and new core, 8 sketches including the SPI does not work without a call to delay(0) #797 repro: no IRQ handler or HAL callback is lost for a peripheral the sketch uses, and SysTick_Handler still comes from clock.c.

Other behaviour changes

  • A sketch calling HAL_TIM_Base_Init(), HAL_ADC_Init(), HAL_DAC_Init() or HAL_PCD_Init() directly no longer gets the core MSP functions: it has to enable the clock and configure the GPIO itself (it can define its own HAL_xxx_MspInit(), which is now always the one used).
  • exit() now just halts: atexit handlers and static destructors are not run and stdio is not flushed. Nothing in the core calls it, and it is weak so a sketch can provide its own.
  • On HAL v2 targets (STM32C5), which only define USE_HAL_TIM_MODULE, pinMode() now stops the PWM started by analogWrite(). It did not before (the TIM guard was narrower than analogWrite()'s). Cost: +592 bytes on a PWM sketch on C562RE.
  • A sketch that does not use Serial can now define its own USARTx_IRQHandler, or its own HAL callback such as HAL_TIM_PeriodElapsedCallback(), without a multiple definition error. This also holds with the core logs enabled (see docs/Tools-menu.md).
  • A build with the core logs enabled (NDEBUG not defined, e.g. arduino-cli --optimize-for-debug) links the debug UART init and output code (not the interrupt driven code) in every sketch.

Build matrix

Built with arduino-cli on main (77b4c91) and on the PR head (90476a1), same toolchain (arm-none-eabi-gcc 14.2.1), 726 builds each. Boards were picked to cover the Cortex-M cores and the HAL/USB variants:

Board Why
C031C6 Cortex-M0+, 32 KB flash, no USB
G071RB Cortex-M0+, no USB
F103RB Cortex-M3, USB FS
L476RG Cortex-M4, USB FS
C562RE Cortex-M33, HAL v2 (USE_HALV2_DRIVER), USB FS (the only Nucleo C5 board)
H743ZI2 Cortex-M7, USB HS

Sketches: Blink, Serial (Serial.begin() + println()) and an all-peripherals sketch (Serial, Wire, SPI, analogRead, analogWrite, HardwareTimer interrupt and EXTI).

Tools menu combinations, for each board and sketch:

  • U(S)ART support: generic Serial / no generic Serial / disabled, x USB support: none / CDC (generic) / CDC / HID (boards with USB only), x core logs: off / on, x optimize: -Os / -Os + LTO, with Newlib Nano;
  • the other C runtime libraries (Nano + float printf, Newlib Standard), with generic Serial, no USB, -Os, core logs off / on;
  • H743ZI2 only: High Speed and High Speed in Full Speed mode with CDC.

Serial is not built when no Serial object exists (marked N/A).

Board Builds OK on main OK on PR Flash overflow on both Link error on both N/A OK on main, fails on PR Fails on main, OK on PR
C031C6 40 17 21 13 6 8 0 4
G071RB 40 31 31 2 7 8 0 0
F103RB 132 102 102 0 30 24 0 0
L476RG 132 102 102 0 30 24 0 0
C562RE (HAL v2) 132 102 102 0 30 24 0 0
H743ZI2 138 108 108 0 30 24 0 0
Total 614 462 466 15 133 112 0 4
  • No build that passes on main fails on this branch.
  • The 4 builds fixed are on C031C6 (32 KB flash): Blink with Nano + float printf (both with and without the core logs, 27588 / 28260 bytes) and Blink and Serial with Newlib Standard (2832 / 11840 bytes) overflowed the flash on main and now fit.
  • The flash overflows on both are the all-peripherals sketch on C031C6, and on G071RB with Newlib Standard (128 KB), plus the core logs combinations on C031C6.
  • All the link errors on both (133) are the same case: -Os + LTO with the core logs enabled, undefined reference to _close/_fstat/_isatty/_lseek/_read/_write from the C library. This is not caused by this PR (same failure on main) and is not addressed here.

Flash size with the default options (generic Serial, no USB, no core logs, -Os, Newlib Nano):

Board Sketch main PR Change
C031C6 Blink 9988 2572 -7416 (-74%)
C031C6 Serial 12716 11352 -1364 (-11%)
C031C6 All peripherals overflow overflow
G071RB Blink 13204 4996 -8208 (-62%)
G071RB Serial 16664 15216 -1448 (-9%)
G071RB All peripherals 43288 43328 +40 (+0%)
F103RB Blink 9456 4380 -5076 (-54%)
F103RB Serial 10080 8916 -1164 (-12%)
F103RB All peripherals 31280 31316 +36 (+0%)
L476RG Blink 13020 6232 -6788 (-52%)
L476RG Serial 15472 14136 -1336 (-9%)
L476RG All peripherals 43368 43436 +68 (+0%)
C562RE (HAL v2) Blink 9400 4144 -5256 (-56%)
C562RE (HAL v2) Serial 16864 14608 -2256 (-13%)
C562RE (HAL v2) All peripherals 39288 39520 +232 (+1%)
H743ZI2 Blink 18368 9080 -9288 (-51%)
H743ZI2 Serial 22684 21288 -1396 (-6%)
H743ZI2 All peripherals 54084 54088 +4 (+0%)

On C562RE (HAL v2) with USB, same options: Blink CDC (generic Serial) 21120 -> 15856, Blink HID 9440 -> 4184, all peripherals CDC (generic Serial) 43496 -> 40984.

Validation

  • Build matrix above: 726 builds on main and on the PR head, no regression.
  • Built with arduino-cli on 31 boards (one per series, Nucleo-32/64/144) with Blink, Serial and a sketch using every peripheral, on main and on the first four commits. The only failure is C031C6 with the last one, which overflows its flash on main too.
  • Built the Servo, STM32LowPower, STM32RTC, STM32Ethernet and FreeRTOS examples on several boards, and an ADC/Blink/Serial sketch with the CMake build system (same size as arduino-cli). Done before the MSP rework, not repeated since.
  • Also checked with an ADC + DAC (analogWrite) + HardwareTimer sketch on F446RE, F103RB, L476RG, G474RE and H743ZI2, and a USB CDC sketch on F446RE, L476RG, G474RE, H743ZI2 and Bluepill F103C8. The ELF only contains the weak HAL HAL_*_MspInit symbols.
  • Each of the first four commits was built on its own (Blink, Serial and all-peripherals sketches on F103RB, L476RG, G071RB, C562RE, WB09KE, H743ZI2 and U385RG): no failure. Blink on F103RB: 7408 -> 6192 -> 4660 -> 4660 bytes.
  • Tested on hardware.
  • Ensure CI build is passed.

Code formatting

  • AStyle applied

Assisted-by: GitHub Copilot: Claude Sonnet 5.5

@fpistm fpistm added this to the 3.2.0 milestone Nov 18, 2026
@fpistm fpistm added enhancement New feature or request fix 🩹 Bug fix labels Nov 18, 2026
@fpistm
fpistm force-pushed the improve_size branch 2 times, most recently from c429227 to 151ff66 Compare November 19, 2026 10:20
@fpistm fpistm self-assigned this Nov 19, 2026
@fpistm
fpistm force-pushed the improve_size branch 2 times, most recently from 44807ee to 15b6e12 Compare November 24, 2026 09:06
pinMode() called pwm_stop() and dac_stop() directly, so every sketch
using pinMode() or digitalWrite() linked the whole HardwareTimer, TIM
and ADC/DAC stack.

Move the pin configured map to wiring_digital.c and stop the analog
output through a weak analog_output_stop(), defined in wiring_analog.c
and so only linked when the sketch uses analogWrite().

Use the same TIM condition as analogWrite() (HAL_TIM_MODULE_ENABLED or
USE_HAL_TIM_MODULE) in pinMode() and analog_output_stop(). Before, HAL
v2 targets (STM32C5), which only define USE_HAL_TIM_MODULE, never
stopped the PWM in pinMode(). It now links pwm_stop(): +592 bytes on a
PWM sketch on C562RE.

Blink on F103 goes from 9744 to 7408 bytes (-24%). A sketch using
analogWrite() is unchanged on HAL v1 targets.

Signed-off-by: Frederic Pillon <frederic.pillon@st.com>
Assisted-by: GitHub Copilot: Claude Sonnet 5.5
SrcWrapper objects are linked unconditionally, so the strong IRQ
handlers of uart.c, HardwareTimer.cpp and interrupt.cpp were always kept
alive by the vector table, even in a sketch that does not use these
peripherals.

Move uart.c, interrupt.cpp, HardwareTimer.cpp and analog.cpp from
libraries/SrcWrapper to cores/arduino/stm32. They become members of
core.a and are only extracted when a sketch or a library references
them. The strong handlers and HAL callbacks they define still override
the weak ones as soon as the member is extracted.

An override in a core.a member is never used when nothing references the
member (see stm32duino#797), so the HAL MSP functions must not be overrides.
Rename the ADC, DAC and TIM ones adc_msp_init(), adc_msp_deinit(),
dac_msp_init(), dac_msp_deinit(), timer_msp_init() and
timer_msp_deinit(), make them static and call them explicitly from
analog.cpp and HardwareTimer.cpp: before HAL_xxx_Init(), as the HAL
accesses the registers right away and needs the clock, and after
HAL_xxx_DeInit(). This does not depend on the weak vs strong symbol
resolution anymore.

The HAL_TIM_OC and HAL_TIM_IC MSP overrides are removed: the core never
calls HAL_TIM_OC_Init() nor HAL_TIM_IC_Init().

Behavior change: a sketch calling HAL_TIM_Base_Init(), HAL_ADC_Init() or
HAL_DAC_Init() directly no longer gets the core MSP functions and has to
set the clock and the GPIO itself. The IRQ handlers of the moved files
only act on handles owned by the core drivers, so they are not needed
when these are not extracted.

Update the CMake source lists and License.md.

Blink on F103 goes from 7408 to 6192 bytes, an EXTI-only sketch from
10756 to 7680 bytes (-29%). A sketch using every peripheral is
unchanged.

Signed-off-by: Frederic Pillon <frederic.pillon@st.com>
Assisted-by: GitHub Copilot: Claude Sonnet 5.5
main() never returns, but crt0 still references exit(). The C library
exit() pulls the stdio cleanup, hence _write() in Print.cpp, hence
uart_debug_write() and so the whole UART driver (now an archive member),
in every sketch.

Provide a weak exit() that halts through _exit(). A sketch can still
override it.

Blink on F103 goes from 6192 to 4660 bytes (-25%), and from 9744 to 4660
bytes (-52%) with the two previous commits.

Behavior change: exit() no longer runs atexit handlers or static
destructors and does not flush stdio.

Signed-off-by: Frederic Pillon <frederic.pillon@st.com>
Assisted-by: GitHub Copilot: Claude Sonnet 5.5
HAL_PCD_MspInit() and HAL_PCD_MspDeInit() overrode the HAL weak
functions. Rename them pcd_msp_init() and pcd_msp_deinit(), make them
static and call them from USBD_LL_Init() and USBD_LL_DeInit(), so the
result no longer depends on the weak vs strong symbol resolution.

pcd_msp_init() is called before HAL_PCD_Init() as the HAL accesses the
registers right away and needs the clock. pcd_msp_deinit() is called
after HAL_PCD_DeInit().

Signed-off-by: Frederic Pillon <frederic.pillon@st.com>
Assisted-by: GitHub Copilot: Claude Sonnet 5.5
Move _write() from the Print.cpp API patch to
cores/arduino/stm32/write.cpp, so it is no longer part of the
ArduinoCore-API patches. The Print::printf() and VIRTIO_LOG paths are
kept. The member of core.a is only extracted when _write() is requested
by the C library.

The output of stdout and stderr (printf(), core_debug()) is sent to the
debug UART by uart_debug_write(), which initializes it through
uart_debug_init() when no Serial instance uses it. The core logs
therefore work with or without Serial.

Remove the _write() patch from CI/update/patch/api. The matching change
in the cores/arduino/api submodule (stm32duino/ArduinoCore-API) must be
applied before updating the submodule reference.

Document the behavior in Tools-menu.md.

Behavior change: a build with the core logs enabled (NDEBUG not defined,
e.g. arduino-cli --optimize-for-debug) links the UART driver in every
sketch, so a sketch defining its own USARTx_IRQHandler() fails to link.
Define NDEBUG or provide its own _write().

Signed-off-by: Frederic Pillon <frederic.pillon@st.com>
Assisted-by: GitHub Copilot: Claude Sonnet 5.5
The debug UART (core logs, printf()) only needs uart_init() and the
polling uart_debug_write(): its interrupt is never enabled. But the
strong USARTx_IRQHandler(), the HAL callbacks and the interrupt driven
functions were in uart.c, so they were linked with it. A sketch with
the core logs enabled (NDEBUG not defined, e.g. arduino-cli
--optimize-for-debug) could not define its own USARTx_IRQHandler(), and
every such sketch carried the Serial code.

Move to cores/arduino/stm32/uart_serial.c:
- the USARTx_IRQHandler();
- uart_getc(), uart_attach_rx_callback(), uart_attach_tx_callback(),
  uart_enable_tx(), uart_enable_rx() and serial_rx_active();
- HAL_UART_RxCpltCallback(), HAL_UART_TxCpltCallback(),
  HAL_UART_ErrorCallback() and HAL_UARTEx_WakeupCallback().
HardwareSerial references these functions, so the member of core.a is
only extracted when it is used, and its strong handlers override the weak
ones as before. uart.c keeps the initialization, the clock, the
deinitialization, the low power configuration and the debug output.

The new uart_private.h shares uart_index_t, uart_handlers[] (not static
anymore) and get_serial_obj() between the two files.

Flash, before -> after:
- Blink, debug build: F103RB 13588 -> 11964 (-12%), H743ZI2 28068 ->
  23500 (-16%)
- printf() only, release build, F103RB: 9868 -> 8440
- Serial, release build: F103RB 9396 -> 9436, H743ZI2 21836 -> 21884

Behavior change: a sketch not using Serial can define its own
USARTx_IRQHandler() in a build with the core logs enabled. A sketch using
Serial or a HardwareSerial still links all the handlers.

Update Tools-menu.md.

Signed-off-by: Frederic Pillon <frederic.pillon@st.com>
Assisted-by: GitHub Copilot: Claude Sonnet 5.5
Update cores/arduino/api to the revert of the weak _write() hook in
Print.cpp:

  ed8a91e Revert "feat: implement weak _write() hook for Print"

_write() is now implemented in the core, in cores/arduino/stm32/write.cpp,
and the matching patch is removed from CI/update/patch/api. Without this
update, both Print.cpp and write.cpp define a weak _write().

Signed-off-by: Frederic Pillon <frederic.pillon@st.com>
Assisted-by: GitHub Copilot: Claude Sonnet 5.5
The C library requests _write() when it is linked, for example through
vdprintf() used by Print::printf(), but it is scanned after libcore_bin.a:
write.cpp.o was never extracted and the link of the CMake build failed with
"undefined reference to `_write'". The Arduino build does not have the
issue as platform.txt puts the core archive and the C library in the same
--start-group ... --end-group.

Do the same in overall_settings(): add the core archive and the C library
in a LINK_GROUP:RESCAN (CMake 3.24 or later). The nano C library is
c_nano, as --specs=nano.specs adds it after the libraries of the link
line. The file of the archive is used, not the target, to not create a
dependency cycle.

Signed-off-by: Frederic Pillon <frederic.pillon@st.com>
Assisted-by: GitHub Copilot: Claude Sonnet 5.5
@fpistm
fpistm merged commit 0bac153 into stm32duino:main Nov 24, 2026
30 checks passed
@github-project-automation github-project-automation Bot moved this from In progress to Done in STM32 core based on ST HAL Nov 24, 2026
@fpistm
fpistm deleted the improve_size branch November 24, 2026 15:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request fix 🩹 Bug fix

Projects

Development

Successfully merging this pull request may close these issues.

1 participant