From 793f9c566a7a08eeee69e4e03e49ad1b84499747 Mon Sep 17 00:00:00 2001 From: Russ Butler Date: Mon, 23 May 2016 20:59:02 -0500 Subject: [PATCH] Add partial thread safety to GCC Add lock functions so that malloc and environment variable access are thread safe. Add the compiler option "-o thread-safe" to use the full version of newlib which is thread safe. Note that this patch does NOT make file access thread safe. --- rtos/rtx/TARGET_CORTEX_M/RTX_CM_lib.h | 30 +++++++++++++++++++++++++++ workspace_tools/toolchains/gcc.py | 3 ++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/rtos/rtx/TARGET_CORTEX_M/RTX_CM_lib.h b/rtos/rtx/TARGET_CORTEX_M/RTX_CM_lib.h index 736f08ebc7..698a7ce455 100755 --- a/rtos/rtx/TARGET_CORTEX_M/RTX_CM_lib.h +++ b/rtos/rtx/TARGET_CORTEX_M/RTX_CM_lib.h @@ -624,11 +624,18 @@ __asm void __rt_entry (void) { #elif defined (__GNUC__) +osMutexDef(malloc_mutex); +static osMutexId malloc_mutex_id; +osMutexDef(env_mutex); +static osMutexId env_mutex_id; + extern void __libc_fini_array(void); extern void __libc_init_array (void); extern int main(int argc, char **argv); void pre_main(void) { + malloc_mutex_id = osMutexCreate(osMutex(malloc_mutex)); + env_mutex_id = osMutexCreate(osMutex(env_mutex)); atexit(__libc_fini_array); __libc_init_array(); main(0, NULL); @@ -651,6 +658,29 @@ __attribute__((naked)) void software_init_hook (void) { ); } +// Opaque declaration of _reent structure +struct _reent; + +void __malloc_lock( struct _reent *_r ) +{ + osMutexWait(malloc_mutex_id, osWaitForever); +} + +void __malloc_unlock( struct _reent *_r ) +{ + osMutexRelease(malloc_mutex_id); +} + +void __env_lock( struct _reent *_r ) +{ + osMutexWait(env_mutex_id, osWaitForever); +} + +void __env_unlock( struct _reent *_r ) +{ + osMutexRelease(env_mutex_id); +} + #elif defined (__ICCARM__) extern void* __vector_table; diff --git a/workspace_tools/toolchains/gcc.py b/workspace_tools/toolchains/gcc.py index 7693652930..a6cb063335 100644 --- a/workspace_tools/toolchains/gcc.py +++ b/workspace_tools/toolchains/gcc.py @@ -183,7 +183,8 @@ class GCC_ARM(GCC): GCC.__init__(self, target, options, notify, macros, silent, GCC_ARM_PATH, extra_verbose=extra_verbose) # Use latest gcc nanolib - self.ld.append("--specs=nano.specs") + if "thread-safe" not in self.options: + self.ld.append("--specs=nano.specs") if target.name in ["LPC1768", "LPC4088", "LPC4088_DM", "LPC4330", "UBLOX_C027", "LPC2368"]: self.ld.extend(["-u _printf_float", "-u _scanf_float"]) elif target.name in ["RZ_A1H", "VK_RZ_A1H", "ARCH_MAX", "DISCO_F407VG", "DISCO_F429ZI", "DISCO_F469NI", "NUCLEO_F401RE", "NUCLEO_F410RB", "NUCLEO_F411RE", "NUCLEO_F446RE", "ELMO_F411RE", "MTS_MDOT_F411RE", "MTS_DRAGONFLY_F411RE", "DISCO_F746NG"]: