[llvm-bugs] [Bug 49828] New: [x86] Unaligned stack pointer when calling always_inline function

via llvm-bugs llvm-bugs at lists.llvm.org
Sat Apr 3 12:28:40 PDT 2021


https://bugs.llvm.org/show_bug.cgi?id=49828

            Bug ID: 49828
           Summary: [x86] Unaligned stack pointer when calling
                    always_inline function
           Product: clang
           Version: unspecified
          Hardware: PC
                OS: Linux
            Status: NEW
          Severity: normal
          Priority: P
         Component: C
          Assignee: unassignedclangbugs at nondot.org
          Reporter: vladislav.valtchev at gmail.com
                CC: blitzrakete at gmail.com, dgregor at apple.com,
                    erik.pilkington at gmail.com, llvm-bugs at lists.llvm.org,
                    richard-llvm at metafoo.co.uk

I noticed that the following code:

#include <inttypes.h>

static __attribute__((always_inline)) inline void
bar(uint8_t a) {
    /* do nothing */
}

void foo(void)
{
   bar(0);
}

Compiled with -m32 -O0 -ffreestanding produces the following instructions, with
any version of clang, from 3.x to 11.x:

foo:                                    
        push    ebp
        mov     ebp, esp
        sub     esp, 1                  # ESP gets unaligned here
        mov     byte ptr [ebp - 1], 0
        add     esp, 1
        pop     ebp
        ret

Notes:
  1. It doesn't happen with any other compiler.
  2. It happens only when __attribute__((always_inline)) is used
  3. It happens only when bar() takes an argument that is < sizeof(void *)
  4. It happens only with -m32
  5. It happens only with -O0

That's, of course, the simplest code making ESP misaligned. I have a real-world
example too, but I believe that such minimal code snippets is what you need
most.


I believe that setting ESP to a misaligned value is pretty dangerous, even if
the function does not perform any function calls, because an interrupt might
occur and it will get the whole stack misaligned. That might lead to UB.
Actually, I discovered this thanks to the UBSAN: the interrupt handler hit the
"unaligned access" UB while reading a value on the stack.

Note: I'm using -ffreestanding just to tell the compiler that interrupts might
occur, but it doesn't make any difference. I suppose, having ESP temporarily
misaligned is a problem in userspace too, because of signals.

-- 
You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20210403/0e204b5d/attachment.html>


More information about the llvm-bugs mailing list