Fix setjmp/longjmp on native Windows (#1331)

* Add setjmp wrapper

* Add to projects

* Use wrapper on x64

* Always build on x64 and exclude on win32

* Fix signature

* Add comments

* Add comments for os-win32.h

* Add extern decleration

* Support cmake Windows build

* Fix for MinGW
This commit is contained in:
lazymio
2020-09-22 02:02:43 +08:00
committed by GitHub
parent 225f6f2889
commit 644da9babc
7 changed files with 73 additions and 3 deletions

View File

@ -56,13 +56,27 @@
# define EWOULDBLOCK WSAEWOULDBLOCK
#endif
#if defined(_WIN64) && !defined(_MSC_VER)
#if defined(_WIN64)
/* On w64, setjmp is implemented by _setjmp which needs a second parameter.
* If this parameter is NULL, longjump does no stack unwinding.
* That is what we need for QEMU. Passing the value of register rsp (default)
* lets longjmp try a stack unwinding which will crash with generated code. */
#if defined(_MSC_VER) // MSVC
// See qemu/include/utils/setjmp-wrapper-win32.asm for details.
extern int _setjmp_wrapper(jmp_buf);
# undef setjmp
# define setjmp(env) _setjmp_wrapper(env)
#else // MinGW
// Original QEMU patch.
# undef setjmp
# define setjmp(env) _setjmp(env, NULL)
#endif
#endif
/* QEMU uses sigsetjmp()/siglongjmp() as the portable way to specify
* "longjmp and don't touch the signal masks". Since we know that the

View File

@ -0,0 +1,26 @@
EXTERN _setjmp: proc
PUBLIC _setjmp_wrapper
_TEXT SEGMENT
_setjmp_wrapper PROC
; Why do we need this wrapper?
; Short answer: Windows default implementation of setjmp/longjmp is incompatible with generated code.
; A longer answer: https://blog.lazym.io/2020/09/21/Unicorn-Devblog-setjmp-longjmp-on-Windows/.
; From qemu os-win32 comments:
; > On w64, setjmp is implemented by _setjmp which needs a second parameter.
; > If this parameter is NULL, longjump does no stack unwinding.
; > That is what we need for QEMU. Passing the value of register rsp (default)
; > lets longjmp try a stack unwinding which will crash with generated code.
; It's true indeed, but MSVC doesn't has a setjmp signature which receives two arguements.
; Therefore, we add a wrapper to keep the second argument zero.
xor rdx, rdx
jmp _setjmp
_setjmp_wrapper ENDP
_TEXT ENDS
END