micropython icon indicating copy to clipboard operation
micropython copied to clipboard

Stack protector for stmhal

Open prusnak opened this issue 8 years ago • 2 comments

I am starting this thread rather than sending a pull request, because I'd like to get more input on the issue first.

It seems that stack protector is turned off for stmhal port (#700).

Is there a significant reason why not to enable it?

My minimal changeset to enable it is here:

diff --git a/stmhal/Makefile b/stmhal/Makefile
index 1ad2783..7183237 100644
--- a/stmhal/Makefile
+++ b/stmhal/Makefile
@@ -66,6 +66,9 @@ LIBS =
 CFLAGS += -fdata-sections -ffunction-sections
 LDFLAGS += --gc-sections

+# Enable stack protector
+CFLAGS += -fstack-protector-all
+
 # Debugging/Optimization
 ifeq ($(DEBUG), 1)
 CFLAGS += -g -DPENDSV_DEBUG
diff --git a/stmhal/main.c b/stmhal/main.c
index 30dddaf..d626ad2 100644
--- a/stmhal/main.c
+++ b/stmhal/main.c
@@ -105,6 +105,12 @@ void nlr_jump_fail(void *val) {
     __fatal_error("");
 }

+uint32_t __stack_chk_guard;
+
+void NORETURN __stack_chk_fail(void) {
+    __fatal_error("Stack smashing detected");
+}
+
 #ifndef NDEBUG
 void MP_WEAK __assert_func(const char *file, int line, const char *func, const char *expr) {
     (void)func;
@@ -343,6 +349,9 @@ STATIC uint update_reset_mode(uint reset_mode) {
 }

 int main(void) {
+
+    __stack_chk_guard = rng_get();
+
     // TODO disable JTAG

     // Stack limit should be less than real stack size, so we have a chance

Couple of issues to resolve:

  • where to put __stack_chk_guard initialization? (obviously you want to have it closest to the beginning of the main function, but only after RNG is initialized)
  • compiling goes without problem, but linking fails with arm-none-eabi-ld: build-PYBV10/firmware.elf section.isr_vector' will not fit in region FLASH_ISR'

Ideas? Comments?

prusnak avatar Aug 04 '16 14:08 prusnak