From 2215f29883ba140d2d16322462b035bf3a36c385 Mon Sep 17 00:00:00 2001
From: Gunar Schorcht <gunar@schorcht.net>
Date: Thu, 17 Jan 2019 13:50:56 +0100
Subject: [PATCH] cpu/esp32: add memset that cannot be optimized out

Adds a memset function `system_secure_memset` which cannot be optimized out by the compiler. It uses the libsodium approach of weak symbols. Function system_secure_memset calls the standard memset. Calling an empty function declared with weak attribute after the memset call, prevents the compiler to optimize it out. The overhead is only one function call.
---
 cpu/esp32/include/syscalls.h |  4 ++++
 cpu/esp32/syscalls.c         | 15 +++++++++++++++
 2 files changed, 19 insertions(+)

diff --git a/cpu/esp32/include/syscalls.h b/cpu/esp32/include/syscalls.h
index fa4182efcf..0151453b70 100644
--- a/cpu/esp32/include/syscalls.h
+++ b/cpu/esp32/include/syscalls.h
@@ -23,6 +23,7 @@
 
 #include <stdarg.h>
 #include <stdbool.h>
+#include <stdint.h>
 #include <stdlib.h>
 
 #include "esp_common.h"
@@ -61,6 +62,9 @@ void system_wdt_stop (void);
 /** reset the system watchdog timer */
 void system_wdt_feed (void);
 
+/** memset version that the compiler should not be allowed to optimize this */
+void *system_secure_memset(void *s, int c, size_t n);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/cpu/esp32/syscalls.c b/cpu/esp32/syscalls.c
index 6d3cc6da67..674441e6d8 100644
--- a/cpu/esp32/syscalls.c
+++ b/cpu/esp32/syscalls.c
@@ -595,3 +595,18 @@ void system_wdt_start (void)
     TIMERG0.wdt_wprotect = 0;     /* enable write protection */
     xt_ints_on(BIT(CPU_INUM_WDT));
 }
+
+__attribute__((weak)) void
+_system_prevent_memset_lto(void *const  s, int c, const size_t n)
+{
+    (void) s;
+    (void) c;
+    (void) n;
+}
+
+void *system_secure_memset(void *s, int c, size_t n)
+{
+    memset(s, c, n);
+    _system_prevent_memset_lto(s, c, n);
+    return s;
+}
-- 
GitLab