Skip to content

Commit 49883c3

Browse files
Merge pull request #5405 from c1728p9/align_stack
Ensure Thread stack is 8 byte aligned
2 parents 6c15360 + d98a011 commit 49883c3

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

rtos/Thread.cpp

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,15 @@
2323

2424
#include "mbed.h"
2525
#include "rtos/rtos_idle.h"
26+
#include "mbed_assert.h"
27+
28+
#define ALIGN_UP(pos, align) ((pos) % (align) ? (pos) + ((align) - (pos) % (align)) : (pos))
29+
MBED_STATIC_ASSERT(ALIGN_UP(0, 8) == 0, "ALIGN_UP macro error");
30+
MBED_STATIC_ASSERT(ALIGN_UP(1, 8) == 8, "ALIGN_UP macro error");
31+
32+
#define ALIGN_DOWN(pos, align) ((pos) - ((pos) % (align)))
33+
MBED_STATIC_ASSERT(ALIGN_DOWN(7, 8) == 0, "ALIGN_DOWN macro error");
34+
MBED_STATIC_ASSERT(ALIGN_DOWN(8, 8) == 8, "ALIGN_DOWN macro error");
2635

2736
static void (*terminate_hook)(osThreadId_t id) = 0;
2837
extern "C" void thread_terminate_hook(osThreadId_t id)
@@ -36,15 +45,21 @@ namespace rtos {
3645

3746
void Thread::constructor(osPriority priority,
3847
uint32_t stack_size, unsigned char *stack_mem, const char *name) {
48+
49+
const uintptr_t unaligned_mem = reinterpret_cast<uintptr_t>(stack_mem);
50+
const uintptr_t aligned_mem = ALIGN_UP(unaligned_mem, 8);
51+
const uint32_t offset = aligned_mem - unaligned_mem;
52+
const uint32_t aligned_size = ALIGN_DOWN(stack_size - offset, 8);
53+
3954
_tid = 0;
4055
_dynamic_stack = (stack_mem == NULL);
4156
_finished = false;
4257
memset(&_obj_mem, 0, sizeof(_obj_mem));
4358
memset(&_attr, 0, sizeof(_attr));
4459
_attr.priority = priority;
45-
_attr.stack_size = stack_size;
60+
_attr.stack_size = aligned_size;
4661
_attr.name = name ? name : "application_unnamed_thread";
47-
_attr.stack_mem = (uint32_t*)stack_mem;
62+
_attr.stack_mem = reinterpret_cast<uint32_t*>(aligned_mem);
4863
}
4964

5065
void Thread::constructor(Callback<void()> task,

0 commit comments

Comments
 (0)