From 7159999eaa69125c72f958266c58c4140a844653 Mon Sep 17 00:00:00 2001
From: Terraneo Federico <fede.tft@miosix.org>
Date: Tue, 11 Feb 2025 15:01:06 +0100
Subject: [PATCH] Fix regression in MemoryProfiling::getCurrentFreeStack()
 caused by previous patch

---
 miosix/libsyscalls/memoryprofiling.cpp | 10 +++++++++-
 miosix/util/util.cpp                   | 10 +++++++++-
 2 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/miosix/libsyscalls/memoryprofiling.cpp b/miosix/libsyscalls/memoryprofiling.cpp
index 7bf144ca..7014a57c 100644
--- a/miosix/libsyscalls/memoryprofiling.cpp
+++ b/miosix/libsyscalls/memoryprofiling.cpp
@@ -107,7 +107,15 @@ unsigned int MemoryProfiling::getAbsoluteFreeStack()
 unsigned int MemoryProfiling::getCurrentFreeStack()
 {
     unsigned int stackOccupiedByCtxsave=sysconf(ctxsaveOnStack);
-    int *stack_ptr asm("sp");
+    #ifdef __ARM_EABI__
+    void *stack_ptr;
+    asm volatile("mov %0, sp" : "=r"(stack_ptr));
+    #else //__ARM_EABI__
+    //NOTE: __builtin_frame_address doesn't add the size of the current function
+    //frame, likely __builtin_stack_address would be better but GCC 9.2.0 does
+    //not have it
+    void *stack_ptr=__builtin_frame_address(0);
+    #endif //__ARM_EABI__
     const unsigned int *walk=getStackBottom();
     unsigned int freeStack=(reinterpret_cast<unsigned int>(stack_ptr)
                           - reinterpret_cast<unsigned int>(walk));
diff --git a/miosix/util/util.cpp b/miosix/util/util.cpp
index ac8b9617..1c24afe4 100644
--- a/miosix/util/util.cpp
+++ b/miosix/util/util.cpp
@@ -94,7 +94,15 @@ unsigned int MemoryProfiling::getAbsoluteFreeStack()
 
 unsigned int MemoryProfiling::getCurrentFreeStack()
 {
-    int *stack_ptr;
+    #ifdef __ARM_EABI__
+    void *stack_ptr;
+    asm volatile("mov %0, sp" : "=r"(stack_ptr));
+    #else //__ARM_EABI__
+    //NOTE: __builtin_frame_address doesn't add the size of the current function
+    //frame, likely __builtin_stack_address would be better but GCC 9.2.0 does
+    //not have it
+    void *stack_ptr=__builtin_frame_address(0);
+    #endif //__ARM_EABI__
     const unsigned int *walk=Thread::getStackBottom();
     unsigned int freeStack=(reinterpret_cast<unsigned int>(stack_ptr)
                           - reinterpret_cast<unsigned int>(walk));
-- 
GitLab