From 5a4fd8e0a6bae0de3e2bae0e38c475b50a63f6ed Mon Sep 17 00:00:00 2001
From: Nils Hasenbanck <hasenbanck@users.noreply.github.com>
Date: Sun, 18 Nov 2018 08:30:46 +0100
Subject: [PATCH] Fix access to the DWT peripheral for STM32 HAL (#12434)

Access to the DWT peripheral for the `CYCCNT` register needs to happen before `main()`. The code needs to be called after the setup of the system clocks, so the right place is between the `premain()` and `main()` function of the STM32 Arduino core.

This patch moves the DWT access code to a new function, which is then placed between `premain()` and `main()`.
---
 Marlin/src/HAL/HAL_STM32/HAL.cpp | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/Marlin/src/HAL/HAL_STM32/HAL.cpp b/Marlin/src/HAL/HAL_STM32/HAL.cpp
index 6776530004..1bddf77f48 100644
--- a/Marlin/src/HAL/HAL_STM32/HAL.cpp
+++ b/Marlin/src/HAL/HAL_STM32/HAL.cpp
@@ -78,14 +78,20 @@ uint16_t HAL_adc_result;
 // Public functions
 // --------------------------------------------------------------------------
 
-// HAL initialization task
-void HAL_init(void) {
 
-  // Needed for DELAY_NS() / DELAY_US() on CORTEX-M7
-  #if (defined(__arm__) || defined(__thumb__)) && __CORTEX_M == 7
+// Needed for DELAY_NS() / DELAY_US() on CORTEX-M7
+#if (defined(__arm__) || defined(__thumb__)) && __CORTEX_M == 7
+  // HAL pre-initialization task
+  // Force the preinit function to run between the premain() and main() function
+  // of the STM32 arduino core
+  __attribute__((constructor (102)))
+  void HAL_preinit() {
     enableCycleCounter();
-  #endif
+  }
+#endif
 
+// HAL initialization task
+void HAL_init(void) {
   FastIO_init();
 
   #if ENABLED(SDSUPPORT)
-- 
GitLab