mach: Define MACHINE_THREAD_STATE_SETUP_CALL

The existing two macros, MACHINE_THREAD_STATE_SET_PC and
MACHINE_THREAD_STATE_SET_SP, can be used to set program counter and the
stack pointer registers in a machine-specific thread state structure.

Useful as it is, this may not be enough to set up the thread to make a
function call, because the machine-specific ABI may impose additional
requirements. In particular, x86_64 ABI requires that upon function
entry, the stack pointer is 8 less than 16-byte aligned (sp & 15 == 8).

To deal with this, introduce a new macro,
MACHINE_THREAD_STATE_SETUP_CALL (), which sets both stack and
instruction pointers, and also applies any machine-specific requirements
to make a valid function call. The default implementation simply
forwards to MACHINE_THREAD_STATE_SET_PC and MACHINE_THREAD_STATE_SET_SP,
but on x86_64 we additionally align the stack pointer.

Signed-off-by: Sergey Bugaev <bugaevc@gmail.com>
Message-Id: <20230517191436.73636-3-bugaevc@gmail.com>
This commit is contained in:
Sergey Bugaev 2023-05-17 22:14:28 +03:00 committed by Samuel Thibault
parent 3f7b800d54
commit 4a373ea7d6
2 changed files with 22 additions and 0 deletions

View file

@ -38,6 +38,15 @@
#endif
#endif
/* Set up the thread state to call the given function on the given state.
Dependning on architecture, this may imply more than just setting PC
and SP. */
#ifndef MACHINE_THREAD_STATE_SETUP_CALL
#define MACHINE_THREAD_STATE_SETUP_CALL(ts, stack, size, func) \
(MACHINE_THREAD_STATE_SET_PC (ts, func), \
MACHINE_THREAD_STATE_SET_SP (ts, stack, size))
#endif
/* This copies architecture-specific bits from the current thread to the new
thread state. */
#ifndef MACHINE_THREAD_STATE_FIX_NEW

View file

@ -20,6 +20,7 @@
#define _MACH_X86_THREAD_STATE_H 1
#include <mach/machine/thread_status.h>
#include <libc-pointer-arith.h>
/* This lets the kernel define segments for a new thread. */
#define MACHINE_NEW_THREAD_STATE_FLAVOR i386_THREAD_STATE
@ -54,6 +55,18 @@ struct machine_thread_all_state
struct i386_float_state fpu;
};
#ifdef __x86_64__
/* We're setting up the stack to perform a function call. On function entry,
the stack pointer must be 8 bytes less than 16-aligned. */
#define PTR_ALIGN_DOWN_8_16(ptr) \
({ uintptr_t __ptr = PTR_ALIGN_DOWN (ptr, 8); \
PTR_IS_ALIGNED (__ptr, 16) ? (__ptr - 8) : __ptr; })
#define MACHINE_THREAD_STATE_SETUP_CALL(ts, stack, size, func) \
((ts)->SP = PTR_ALIGN_DOWN_8_16 ((uintptr_t) (stack) + (size)), \
(ts)->PC = (uintptr_t) func)
#endif
#include <sysdeps/mach/thread_state.h>
#endif /* mach/x86/thread_state.h */