misaligned_stack_error caused by LLVM code on MacOS: how to fix?

llvm-generated code that runs fine on linux/i386 causes EXC_BAD_ACCESS with misaligned_stack_error_ on MacOS/i386.

I read online that each function should have stack aligned by 16 on MacOS/i386 and such code should be used:

Fn->addAttribute(~0U, llvm::Attribute::constructStackAlignmentFromInt(16));

But when I run clang on some C++ code I don't see alignstack instructions generated at all.

What is the right way for fix this misaligned_stack_error?



What is the right way for fix this misaligned_stack_error?

Codegen stuff for darwin, there are many other differences in Linux/Darwin ABIs.

Calling set_module_triple with "i386-apple-darwin10.0.0" fixes the issue.

But I notice that when clang generates code the other difference is that all functions have ssp attribute on darwin which doesn't appear on linux and freebsd.
Why there is such a difference between MacOS and Linux?


That stack alignment check only happens when a lazy pointer is resolved, which happens the first time each external function is called. For example, if your program calls malloc() the first time malloc is called from any site in your program, the stack alignment is checked. After that, if your program calls malloc, no alignment checking is done.

So, not seeing a misaligned_stack_error does not mean the program is correct. It may be that in the code path you exercised the first time a function was called had the stack aligned. But there may be another code path involving a function that misaligns the stack, which could trigger the misaligned_stack_error.