From 2aa88fc6d0fc072c7743e543a7bbba5984e5da41 Mon Sep 17 00:00:00 2001 From: Harald Hoyer Date: Thu, 26 Sep 2019 09:01:26 +0200 Subject: [PATCH] Correct stack alignment calculation Previously align_offset(STACK_ALIGNMENT) was substracted, which is wrong, because the documentation states: > Computes the offset that needs to be applied to the pointer in > order to make it aligned. This patch first substracts STACK_ALIGNMENT and then adds align_offset(STACK_ALIGNMENT), if the stack was not yet aligned Also calculating the top with .add(stack.len() - 1) so the stack pointer points initially to a valid memory address. --- src/lib.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index c5a278e..c2bcc57 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -248,8 +248,14 @@ impl<'a, Y, R> Coroutine<'a, Y, R> { unsafe { // Calculate the aligned top of the stack. - let top = stack.as_mut_ptr().add(stack.len()); - let top = top.sub(top.align_offset(STACK_ALIGNMENT)); + let top = stack.as_mut_ptr().add(stack.len() - 1); + // If the top isn't aligned yet, calculate the aligned top of the stack. + let top = if top.align_offset(STACK_ALIGNMENT) != 0 { + let top = top.sub(STACK_ALIGNMENT); + top.add(top.align_offset(STACK_ALIGNMENT)) + } else { + top + }; // Call into the callback on the specified stack. jump_init(