Skip to content

Commit a97621e

Browse files
wasm: align fiber stack pointer to 16 bytes (ruby#12101)
wasm: align fiber stack pointer to 16 bytes In WebAssembly C ABI, the linear stack pointer must be always aligned to 16 bytes like other archs. The misaligned stack pointer causes some weird memory corruption since compiler assumes the aligned stack pointer.
1 parent a24570a commit a97621e

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

coroutine/asyncify/Context.h

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
#include <stddef.h>
1515
#include <stdio.h>
16+
#include <stdint.h>
1617
#include "wasm/asyncify.h"
1718
#include "wasm/machine.h"
1819
#include "wasm/fiber.h"
@@ -47,10 +48,13 @@ static inline void coroutine_initialize_main(struct coroutine_context * context)
4748

4849
static inline void coroutine_initialize(struct coroutine_context *context, coroutine_start start, void *stack, size_t size)
4950
{
50-
if (ASYNCIFY_CORO_DEBUG) fprintf(stderr, "[%s] entry (context = %p, stack = %p ... %p)\n", __func__, context, stack, (char *)stack + size);
51+
// Linear stack pointer must be always aligned down to 16 bytes.
52+
// https://github.com/WebAssembly/tool-conventions/blob/c74267a5897c1bdc9aa60adeaf41816387d3cd12/BasicCABI.md#the-linear-stack
53+
uintptr_t sp = ((uintptr_t)stack + size) & ~0xF;
54+
if (ASYNCIFY_CORO_DEBUG) fprintf(stderr, "[%s] entry (context = %p, stack = %p ... %p)\n", __func__, context, stack, (char *)sp);
5155
rb_wasm_init_context(&context->fc, coroutine_trampoline, start, context);
5256
// record the initial stack pointer position to restore it after resumption
53-
context->current_sp = (char *)stack + size;
57+
context->current_sp = (char *)sp;
5458
context->stack_base = stack;
5559
context->size = size;
5660
}

0 commit comments

Comments
 (0)