Skip to content

linux-user: incorrect alignment of sigframe::pretcode & rt_sigframe::pretcode cause crash

Fix Patch: https://lists.nongnu.org/archive/html/qemu-devel/2023-05/msg03122.html

Host environment

  • Operating system: Windows 11

  • OS/kernel version: Linux DESKTOP-388IRR7 5.15.90.1-microsoft-standard-WSL2 #1 SMP Fri Jan 27 02:56:13 UTC 2023 x86_64 GNU/Linux

  • Architecture: x86_64

  • QEMU flavor: qemu-x86_64 user mode

  • QEMU version: 8.0.0

  • QEMU command line:

    gcc -O3 test.c -o a.out   
    
    ./qemu-x86_64 a.out

    source of test.c

#include <signal.h>
#include <stdio.h>
#include <unistd.h>

#define SIGNUM 60

__attribute__((noinline)) void bar(void)
{
     printf("SUCCEEDED!\n");
}

__attribute__((noinline, ms_abi)) void foo(void)
{
     bar();
}

void sighandler(int num)
{
     void* sp[0];
     printf("sp: %x\n", sp);
     foo();
}

int main(void)
{
     signal(SIGNUM, &sighandler);
     kill(getpid(), SIGNUM);
     return 0;
}

Description of problem

Corrent Print Result:

sp: cdd3b4e8

SUCCEEDED!

qemu-x86_64 Print Result:

sp: 2804170

qemu: uncaught target signal 11 (Segmentation fault) - core dumped

Segmentation fault

Reason of Bug:

sigframe::pretcode & rt_sigframe::pretcode must align of 16n-sizeof(void*) instead of 16n, Because rsp align of 16n before instruction "call" in caller, After "call", push address of "call" in caller. sp of begin in callee is 16n-sizeof(void*)

For example on x86_64:

reference to "qemu/linux-user/i386/signal.c"

# define TARGET_FPSTATE_FXSAVE_OFFSET 0

struct rt_sigframe {
    abi_ulong pretcode;
    struct target_ucontext uc;
    struct target_siginfo info;
    struct target_fpstate fpstate QEMU_ALIGNED(16);
};
#define TARGET_RT_SIGFRAME_FXSAVE_OFFSET (                                 \
    offsetof(struct rt_sigframe, fpstate) + TARGET_FPSTATE_FXSAVE_OFFSET)

offsetof(struct rt_sigframe, fpstate) align of 16

TARGET_FPSTATE_FXSAVE_OFFSET is 0

TARGET_RT_SIGFRAME_FXSAVE_OFFSET is 16n, also alignment of fxsave is 64

so address of rt_sigframe::pretcode is 16n instead of 16n - sizeof(void*), It is incorect!

Fix the bug:

struct rt_sigframe {
    abi_ulong pretcode;
    struct target_ucontext uc;
    struct target_siginfo info;
    abi_ulong unused QEMU_ALIGNED(16);
    struct target_fpstate fpstate;
};

offsetof(struct rt_sigframe, fpstate) is 16n+8, so address of rt_sigframe::pretcode is 16n-8 on x86_64.

Edited by Fàn Wén Jié
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information