Repository navigation
perf(core): reduce code size by linking peripheral drivers lazily - #3117
Merged
Merged
Conversation
fpistm
force-pushed
the
improve_size
branch
2 times, most recently
from
November 19, 2026 10:20
c429227 to
151ff66
Compare
fpistm
force-pushed
the
improve_size
branch
2 times, most recently
from
November 24, 2026 09:06
44807ee to
15b6e12
Compare
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Reduce the flash and RAM used by sketches that do not use every peripheral. Before this PR, a bare
Blinklinked the UART, timer, EXTI and DAC/PWM drivers,mallocand stdio, none of which it uses.Eight commits, each building on its own:
perf(core): decouple pinMode from the PWM and DAC codepinMode()calledpwm_stop()/dac_stop()directly, so every sketch usingpinMode()ordigitalWrite()linked the whole HardwareTimer, TIM and ADC/DAC stack. The stop is now done through a weakanalog_output_stop()defined inwiring_analog.c, which is only linked when the sketch usesanalogWrite().perf(core): link the peripheral drivers lazilyuart.c,interrupt.cpp,HardwareTimer.cppandanalog.cppmove fromlibraries/SrcWrappertocores/arduino/stm32, so they are members ofcore.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 aroundHAL_xxx_Init()/HAL_xxx_DeInit()(see the SPI does not work without a call to delay(0) #797 note below).timer.cstays inSrcWrapperand only keeps the clock and IRQ helpers.perf(core): add a weak exit() to avoid linking the UART drivercrt0 references
exit(), whose C library version pulls the stdio cleanup, then_write()inPrint.cpp, then the whole UART driver. A weakexit()that halts replaces it.refactor(usb): call the PCD MSP functions explicitlySame approach as for ADC/DAC/TIM, applied to
HAL_PCD_MspInit()/HAL_PCD_MspDeInit()inusbd_conf.c, so no HAL MSP function relies on the weak vs strong resolution anymore.refactor(core): implement _write() in the core_write()moves from the ArduinoCore-APIPrint.cpppatch tocores/arduino/stm32/write.cpp, acore.amember only extracted when the C library requests_write(). stdout/stderr (printf(), core logs) go to the debug UART throughuart_debug_write(), initialized on demand when noSerialuses it. The patch is removed fromCI/update/patch/api.perf(uart): split the interrupt driven code from the UART driverThe debug UART only needs
uart_init()and the pollinguart_debug_write(). TheUSARTx_IRQHandler(), the HAL callbacks and the interrupt driven functions move tocores/arduino/stm32/uart_serial.c, only extracted whenHardwareSerialis used. A sketch not usingSerialcan define its ownUSARTx_IRQHandler()even in a build with the core logs enabled.chore(api): update ArduinoCore-API submodulePoints
cores/arduino/apito the revert of the weak_write()hook (ed8a91e). Needed by commit 5: without it bothPrint.cppandwrite.cppdefine a weak_write().fix(cmake): scan the core again after the C libraryThe C library requests
_write()but is scanned afterlibcore_bin.ain the CMake build, sowrite.cpp.owas never extracted. The core archive and the C library are now in aLINK_GROUP:RESCAN(CMake 3.24 or later), like the--start-groupofplatform.txt.This PR fixes/implements the following bugs/features
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:Examples:
Blinkon 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.amembers that nothing referenced, so the weak default won. This PR keeps that class of problem out of the moved code:core.amembers 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.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: beforeHAL_xxx_Init(), because the HAL accesses the registers right away and needs the clock, and afterHAL_xxx_DeInit(). The result does not depend on the weak vs strong symbol resolution anymore, wherever the code lives.HAL_TIM_OC_Msp*andHAL_TIM_IC_Msp*overrides are removed: the core never callsHAL_TIM_OC_Init()norHAL_TIM_IC_Init().SysTick_Handlerstill comes fromclock.c.Other behaviour changes
HAL_TIM_Base_Init(),HAL_ADC_Init(),HAL_DAC_Init()orHAL_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 ownHAL_xxx_MspInit(), which is now always the one used).exit()now just halts:atexithandlers 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.USE_HAL_TIM_MODULE,pinMode()now stops the PWM started byanalogWrite(). It did not before (the TIM guard was narrower thananalogWrite()'s). Cost: +592 bytes on a PWM sketch on C562RE.Serialcan now define its ownUSARTx_IRQHandler, or its own HAL callback such asHAL_TIM_PeriodElapsedCallback(), without a multiple definition error. This also holds with the core logs enabled (seedocs/Tools-menu.md).NDEBUGnot 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:USE_HALV2_DRIVER), USB FS (the only Nucleo C5 board)Sketches:
Blink,Serial(Serial.begin()+println()) and an all-peripherals sketch (Serial, Wire, SPI,analogRead,analogWrite,HardwareTimerinterrupt and EXTI).Tools menu combinations, for each board and sketch:
Serial/ no genericSerial/ 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;Serial, no USB,-Os, core logs off / on;Serialis not built when noSerialobject exists (marked N/A).mainmain, fails on PRmain, OK on PRmainfails on this branch.mainand now fit.-Os+ LTO with the core logs enabled,undefined reference to _close/_fstat/_isatty/_lseek/_read/_writefrom the C library. This is not caused by this PR (same failure onmain) and is not addressed here.Flash size with the default options (generic
Serial, no USB, no core logs,-Os, Newlib Nano):mainOn C562RE (HAL v2) with USB, same options: Blink CDC (generic
Serial) 21120 -> 15856, Blink HID 9440 -> 4184, all peripherals CDC (genericSerial) 43496 -> 40984.Validation
mainand on the PR head, no regression.mainand on the first four commits. The only failure is C031C6 with the last one, which overflows its flash onmaintoo.analogWrite) +HardwareTimersketch 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 HALHAL_*_MspInitsymbols.Blinkon F103RB: 7408 -> 6192 -> 4660 -> 4660 bytes.Code formatting
Assisted-by: GitHub Copilot: Claude Sonnet 5.5