xref: /xnu-10002.1.13/tests/ldt.c (revision 1031c584a5e37aff177559b9f69dbd3c8c3fd30a)
1*1031c584SApple OSS Distributions /*
2*1031c584SApple OSS Distributions  * Copyright (c) 2019 Apple Inc. All rights reserved.
3*1031c584SApple OSS Distributions  *
4*1031c584SApple OSS Distributions  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5*1031c584SApple OSS Distributions  *
6*1031c584SApple OSS Distributions  * This file contains Original Code and/or Modifications of Original Code
7*1031c584SApple OSS Distributions  * as defined in and that are subject to the Apple Public Source License
8*1031c584SApple OSS Distributions  * Version 2.0 (the 'License'). You may not use this file except in
9*1031c584SApple OSS Distributions  * compliance with the License. The rights granted to you under the License
10*1031c584SApple OSS Distributions  * may not be used to create, or enable the creation or redistribution of,
11*1031c584SApple OSS Distributions  * unlawful or unlicensed copies of an Apple operating system, or to
12*1031c584SApple OSS Distributions  * circumvent, violate, or enable the circumvention or violation of, any
13*1031c584SApple OSS Distributions  * terms of an Apple operating system software license agreement.
14*1031c584SApple OSS Distributions  *
15*1031c584SApple OSS Distributions  * Please obtain a copy of the License at
16*1031c584SApple OSS Distributions  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17*1031c584SApple OSS Distributions  *
18*1031c584SApple OSS Distributions  * The Original Code and all software distributed under the License are
19*1031c584SApple OSS Distributions  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20*1031c584SApple OSS Distributions  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21*1031c584SApple OSS Distributions  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22*1031c584SApple OSS Distributions  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23*1031c584SApple OSS Distributions  * Please see the License for the specific language governing rights and
24*1031c584SApple OSS Distributions  * limitations under the License.
25*1031c584SApple OSS Distributions  *
26*1031c584SApple OSS Distributions  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27*1031c584SApple OSS Distributions  */
28*1031c584SApple OSS Distributions 
29*1031c584SApple OSS Distributions // #define STANDALONE
30*1031c584SApple OSS Distributions 
31*1031c584SApple OSS Distributions #ifndef STANDALONE
32*1031c584SApple OSS Distributions #include <darwintest.h>
33*1031c584SApple OSS Distributions #endif
34*1031c584SApple OSS Distributions #include <architecture/i386/table.h>
35*1031c584SApple OSS Distributions #include <i386/user_ldt.h>
36*1031c584SApple OSS Distributions #include <mach/i386/vm_param.h>
37*1031c584SApple OSS Distributions #include <mach/i386/thread_status.h>
38*1031c584SApple OSS Distributions #include <mach/mach.h>
39*1031c584SApple OSS Distributions #include <signal.h>
40*1031c584SApple OSS Distributions #include <stdio.h>
41*1031c584SApple OSS Distributions #include <stdlib.h>
42*1031c584SApple OSS Distributions #include <strings.h>
43*1031c584SApple OSS Distributions #include <sys/mman.h>
44*1031c584SApple OSS Distributions #include <sys/types.h>
45*1031c584SApple OSS Distributions #include <sys/signal.h>
46*1031c584SApple OSS Distributions #include <sys/sysctl.h>
47*1031c584SApple OSS Distributions #include <assert.h>
48*1031c584SApple OSS Distributions #include <errno.h>
49*1031c584SApple OSS Distributions #include <fcntl.h>
50*1031c584SApple OSS Distributions #include <pthread.h>
51*1031c584SApple OSS Distributions #include <unistd.h>
52*1031c584SApple OSS Distributions #include <ldt_mach_exc.h>
53*1031c584SApple OSS Distributions 
54*1031c584SApple OSS Distributions #ifndef STANDALONE
55*1031c584SApple OSS Distributions T_GLOBAL_META(
56*1031c584SApple OSS Distributions 	T_META_NAMESPACE("xnu.intel"),
57*1031c584SApple OSS Distributions 	T_META_RADAR_COMPONENT_NAME("xnu"),
58*1031c584SApple OSS Distributions 	T_META_RADAR_COMPONENT_VERSION("intel"),
59*1031c584SApple OSS Distributions 	T_META_OWNER("seth_goldberg"),
60*1031c584SApple OSS Distributions 	T_META_CHECK_LEAKS(false)
61*1031c584SApple OSS Distributions 	);
62*1031c584SApple OSS Distributions #endif
63*1031c584SApple OSS Distributions 
64*1031c584SApple OSS Distributions #define COMPAT_MODE_CS_SELECTOR 0x1f
65*1031c584SApple OSS Distributions #define SYSENTER_SELECTOR 0xb
66*1031c584SApple OSS Distributions /* #define DEBUG 1 */
67*1031c584SApple OSS Distributions #define P2ROUNDUP(x, align)     (-(-((long)x) & -((long)align)))
68*1031c584SApple OSS Distributions #define MSG 2048
69*1031c584SApple OSS Distributions 
70*1031c584SApple OSS Distributions #define NORMAL_RUN_TIME  (10)
71*1031c584SApple OSS Distributions #define TIMEOUT_OVERHEAD (10)
72*1031c584SApple OSS Distributions 
73*1031c584SApple OSS Distributions /*
74*1031c584SApple OSS Distributions  * General theory of operation:
75*1031c584SApple OSS Distributions  * ----------------------------
76*1031c584SApple OSS Distributions  * (1) Ensure that all code and data to be accessed from compatibility mode is
77*1031c584SApple OSS Distributions  *     located in the low 4GiB of virtual address space.
78*1031c584SApple OSS Distributions  * (2) Allocate required segments via the i386_set_ldt() system call, making
79*1031c584SApple OSS Distributions  *     sure to set the descriptor type correctly (code vs. data).  Creating
80*1031c584SApple OSS Distributions  *     64-bit code segments is not allowed (just use the existing 0x2b selector.)
81*1031c584SApple OSS Distributions  * (3) Once you know which selector is associated with the desired code, use a
82*1031c584SApple OSS Distributions  *     trampoline (or thunk) to (a) switch to a stack that's located below 4GiB
83*1031c584SApple OSS Distributions  *     and (b) save ABI-mandated caller-saved state so that if it's trashed by
84*1031c584SApple OSS Distributions  *     compatibility-mode code, it can be restored before returning to 64-bit
85*1031c584SApple OSS Distributions  *     mode (if desired), and finally (c) long-jump or long-call (aka far call)
86*1031c584SApple OSS Distributions  *     to the segment and desired offset (this example uses an offset of 0 for
87*1031c584SApple OSS Distributions  *     simplicity.)
88*1031c584SApple OSS Distributions  * (4) Once in compatibility mode, if a framework call or system call is required,
89*1031c584SApple OSS Distributions  *     the code must trampoline back to 64-bit mode to do so.  System calls from
90*1031c584SApple OSS Distributions  *     compatibility mode code are not supported and will result in invalid opcode
91*1031c584SApple OSS Distributions  *     exceptions.  This example includes a simple 64-bit trampoline (which must
92*1031c584SApple OSS Distributions  *     be located in the low 4GiB of virtual address space, since it's executed
93*1031c584SApple OSS Distributions  *     by compatibility-mode code.)  Note that since the 64-bit ABI mandates that
94*1031c584SApple OSS Distributions  *     the stack must be aligned to a 16-byte boundary, the sample trampoline
95*1031c584SApple OSS Distributions  *     performs that rounding, to simplify compatibility-mode code.  Additionally,
96*1031c584SApple OSS Distributions  *     since 64-bit native code makes use of thread-local storage, the user-mode
97*1031c584SApple OSS Distributions  *     GSbase must be restored.  This sample includes two ways to do that-- (a) by
98*1031c584SApple OSS Distributions  *     calling into a C implementation that associates the thread-local storage
99*1031c584SApple OSS Distributions  *     pointer with a stack range (which will be unique for each thread.), and
100*1031c584SApple OSS Distributions  *     (b) by storing the original GSbase in a block of memory installed into
101*1031c584SApple OSS Distributions  *     GSbase before calling into compatibility-mode code.  A special machdep
102*1031c584SApple OSS Distributions  *     system call restores GSbase as needed.  Note that the sample trampoline
103*1031c584SApple OSS Distributions  *     does not save and restore %gs (or most other register state, so that is an
104*1031c584SApple OSS Distributions  *     area that may be tailored to the application's requirements.)
105*1031c584SApple OSS Distributions  * (5) Once running in compatibility mode, should synchronous or asynchronous
106*1031c584SApple OSS Distributions  *     exceptions occur, this sample shows how a mach exception handler (running
107*1031c584SApple OSS Distributions  *     in a detached thread, handling exceptions for the entire task) can catch
108*1031c584SApple OSS Distributions  *     such exceptions and manipulate thread state to perform recovery (or not.)
109*1031c584SApple OSS Distributions  *     Other ways to handle exceptions include installing per-thread exception
110*1031c584SApple OSS Distributions  *     servers.  Alternatively, BSD signal handlers can be used.  Note that once a
111*1031c584SApple OSS Distributions  *     process installs a custom LDT, *ALL* future signal deliveries will include
112*1031c584SApple OSS Distributions  *     ucontext pointers to mcontext structures that include enhanced thread
113*1031c584SApple OSS Distributions  *     state embedded (e.g. the %ds, %es, %ss, and GSBase registers) [This assumes
114*1031c584SApple OSS Distributions  *     that the SA_SIGINFO is passed to sigaction(2) when registering handlers].
115*1031c584SApple OSS Distributions  *     The mcontext size (part of the ucontext) can be used to differentiate between
116*1031c584SApple OSS Distributions  *     different mcontext flavors (e.g. those with/without full thread state plus
117*1031c584SApple OSS Distributions  *     x87 FP state, AVX state, or AVX2/3 state).
118*1031c584SApple OSS Distributions  */
119*1031c584SApple OSS Distributions 
120*1031c584SApple OSS Distributions /*
121*1031c584SApple OSS Distributions  * This test exercises the custom LDT functionality exposed via the i386_{get,set}_ldt
122*1031c584SApple OSS Distributions  * system calls.
123*1031c584SApple OSS Distributions  *
124*1031c584SApple OSS Distributions  * Tests include:
125*1031c584SApple OSS Distributions  * (1a) Exception handling (due to an exception or another thread sending a signal) while
126*1031c584SApple OSS Distributions  *      running in compatibility mode;
127*1031c584SApple OSS Distributions  * (1b) Signal handling while running in compatibility mode;
128*1031c584SApple OSS Distributions  * (2)  Thunking back to 64-bit mode and executing a framework function (e.g. printf)
129*1031c584SApple OSS Distributions  * (3)  Ensuring that transitions to compatibility mode and back to 64-bit mode
130*1031c584SApple OSS Distributions  *      do not negatively impact system calls and framework calls in 64-bit mode
131*1031c584SApple OSS Distributions  * (4)  Use of thread_get_state / thread_set_state to configure a thread to
132*1031c584SApple OSS Distributions  *      execute in compatibility mode with the proper LDT code segment (this is
133*1031c584SApple OSS Distributions  *      effectively what the exception handler does when the passed-in new_state
134*1031c584SApple OSS Distributions  *      is changed (or what the BSD signal handler return handling does when the
135*1031c584SApple OSS Distributions  *      mcontext is modified).)
136*1031c584SApple OSS Distributions  * (5)  Ensure that compatibility mode code cannot make system calls via sysenter or
137*1031c584SApple OSS Distributions  *      old-style int {0x80..0x82}.
138*1031c584SApple OSS Distributions  * (6)  Negative testing to ensure errors are returned if the consumer tries
139*1031c584SApple OSS Distributions  *      to set a disallowed segment type / Long flag. [TBD]
140*1031c584SApple OSS Distributions  */
141*1031c584SApple OSS Distributions 
142*1031c584SApple OSS Distributions /*
143*1031c584SApple OSS Distributions  * Note that these addresses are not necessarily available due to ASLR, so
144*1031c584SApple OSS Distributions  * a robust implementation should determine the proper range to use via
145*1031c584SApple OSS Distributions  * another means.
146*1031c584SApple OSS Distributions  */
147*1031c584SApple OSS Distributions #ifndef STANDALONE
148*1031c584SApple OSS Distributions /* libdarwintest needs LOTs of stack */
149*1031c584SApple OSS Distributions #endif
150*1031c584SApple OSS Distributions #define FIXED_STACK_SIZE (PAGE_SIZE * 16)
151*1031c584SApple OSS Distributions #define FIXED_TRAMP_MAXLEN (PAGE_SIZE * 8)
152*1031c584SApple OSS Distributions 
153*1031c584SApple OSS Distributions #pragma pack(1)
154*1031c584SApple OSS Distributions typedef struct {
155*1031c584SApple OSS Distributions 	uint64_t off;
156*1031c584SApple OSS Distributions 	uint16_t seg;
157*1031c584SApple OSS Distributions } far_call_t;
158*1031c584SApple OSS Distributions #pragma pack()
159*1031c584SApple OSS Distributions 
160*1031c584SApple OSS Distributions typedef struct {
161*1031c584SApple OSS Distributions 	uint64_t stack_base;
162*1031c584SApple OSS Distributions 	uint64_t stack_limit;
163*1031c584SApple OSS Distributions 	uint64_t GSbase;
164*1031c584SApple OSS Distributions } stackaddr_to_gsbase_t;
165*1031c584SApple OSS Distributions 
166*1031c584SApple OSS Distributions typedef struct thread_arg {
167*1031c584SApple OSS Distributions 	pthread_mutex_t         mutex;
168*1031c584SApple OSS Distributions 	pthread_cond_t          condvar;
169*1031c584SApple OSS Distributions 	volatile boolean_t      done;
170*1031c584SApple OSS Distributions 	uint32_t                compat_stackaddr;       /* Compatibility mode stack address */
171*1031c584SApple OSS Distributions } thread_arg_t;
172*1031c584SApple OSS Distributions 
173*1031c584SApple OSS Distributions typedef struct custom_tsd {
174*1031c584SApple OSS Distributions 	struct custom_tsd *     this_tsd_base;
175*1031c584SApple OSS Distributions 	uint64_t                orig_tsd_base;
176*1031c584SApple OSS Distributions } custom_tsd_t;
177*1031c584SApple OSS Distributions 
178*1031c584SApple OSS Distributions typedef uint64_t (*compat_tramp_t)(far_call_t *fcp, void *lowmemstk, uint64_t arg_for_32bit,
179*1031c584SApple OSS Distributions     uint64_t callback, uint64_t absolute_addr_of_thunk64);
180*1031c584SApple OSS Distributions 
181*1031c584SApple OSS Distributions #define GS_RELATIVE volatile __attribute__((address_space(256)))
182*1031c584SApple OSS Distributions static custom_tsd_t GS_RELATIVE *mytsd = (custom_tsd_t GS_RELATIVE *)0;
183*1031c584SApple OSS Distributions 
184*1031c584SApple OSS Distributions static far_call_t input_desc = { .seg = COMPAT_MODE_CS_SELECTOR, .off = 0 };
185*1031c584SApple OSS Distributions static uint64_t stackAddr = 0;
186*1031c584SApple OSS Distributions static compat_tramp_t thunkit = NULL;
187*1031c584SApple OSS Distributions static uint64_t thunk64_addr;
188*1031c584SApple OSS Distributions /* stack2gs[0] is initialized in map_lowmem_stack() */
189*1031c584SApple OSS Distributions static stackaddr_to_gsbase_t stack2gs[] = { { 0 } };
190*1031c584SApple OSS Distributions 
191*1031c584SApple OSS Distributions extern int compat_mode_trampoline(far_call_t *, void *, uint64_t);
192*1031c584SApple OSS Distributions extern void long_mode_trampoline(void);
193*1031c584SApple OSS Distributions extern boolean_t mach_exc_server(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP);
194*1031c584SApple OSS Distributions 
195*1031c584SApple OSS Distributions extern void code_32(void);
196*1031c584SApple OSS Distributions 
197*1031c584SApple OSS Distributions kern_return_t catch_mach_exception_raise_state_identity(mach_port_t exception_port,
198*1031c584SApple OSS Distributions     mach_port_t thread,
199*1031c584SApple OSS Distributions     mach_port_t task,
200*1031c584SApple OSS Distributions     exception_type_t exception,
201*1031c584SApple OSS Distributions     mach_exception_data_t code,
202*1031c584SApple OSS Distributions     mach_msg_type_number_t code_count,
203*1031c584SApple OSS Distributions     int * flavor,
204*1031c584SApple OSS Distributions     thread_state_t old_state,
205*1031c584SApple OSS Distributions     mach_msg_type_number_t old_state_count,
206*1031c584SApple OSS Distributions     thread_state_t new_state,
207*1031c584SApple OSS Distributions     mach_msg_type_number_t * new_state_count);
208*1031c584SApple OSS Distributions 
209*1031c584SApple OSS Distributions kern_return_t
210*1031c584SApple OSS Distributions catch_mach_exception_raise_state(mach_port_t exception_port,
211*1031c584SApple OSS Distributions     exception_type_t exception,
212*1031c584SApple OSS Distributions     const mach_exception_data_t code,
213*1031c584SApple OSS Distributions     mach_msg_type_number_t codeCnt,
214*1031c584SApple OSS Distributions     int *flavor,
215*1031c584SApple OSS Distributions     const thread_state_t old_state,
216*1031c584SApple OSS Distributions     mach_msg_type_number_t old_stateCnt,
217*1031c584SApple OSS Distributions     thread_state_t new_state,
218*1031c584SApple OSS Distributions     mach_msg_type_number_t *new_stateCnt);
219*1031c584SApple OSS Distributions 
220*1031c584SApple OSS Distributions kern_return_t
221*1031c584SApple OSS Distributions catch_mach_exception_raise(mach_port_t exception_port,
222*1031c584SApple OSS Distributions     mach_port_t thread,
223*1031c584SApple OSS Distributions     mach_port_t task,
224*1031c584SApple OSS Distributions     exception_type_t exception,
225*1031c584SApple OSS Distributions     mach_exception_data_t code,
226*1031c584SApple OSS Distributions     mach_msg_type_number_t codeCnt,
227*1031c584SApple OSS Distributions     int *flavor,
228*1031c584SApple OSS Distributions     thread_state_t old_state,
229*1031c584SApple OSS Distributions     mach_msg_type_number_t old_stateCnt,
230*1031c584SApple OSS Distributions     thread_state_t new_state,
231*1031c584SApple OSS Distributions     mach_msg_type_number_t *new_stateCnt);
232*1031c584SApple OSS Distributions 
233*1031c584SApple OSS Distributions extern void _thread_set_tsd_base(uint64_t);
234*1031c584SApple OSS Distributions static uint64_t stack_range_to_GSbase(uint64_t stackptr, uint64_t GSbase);
235*1031c584SApple OSS Distributions void restore_gsbase(uint64_t stackptr);
236*1031c584SApple OSS Distributions 
237*1031c584SApple OSS Distributions static uint64_t
get_gsbase(void)238*1031c584SApple OSS Distributions get_gsbase(void)
239*1031c584SApple OSS Distributions {
240*1031c584SApple OSS Distributions 	struct thread_identifier_info tiinfo;
241*1031c584SApple OSS Distributions 	unsigned int info_count = THREAD_IDENTIFIER_INFO_COUNT;
242*1031c584SApple OSS Distributions 	kern_return_t kr;
243*1031c584SApple OSS Distributions 
244*1031c584SApple OSS Distributions 	if ((kr = thread_info(mach_thread_self(), THREAD_IDENTIFIER_INFO,
245*1031c584SApple OSS Distributions 	    (thread_info_t) &tiinfo, &info_count)) != KERN_SUCCESS) {
246*1031c584SApple OSS Distributions 		fprintf(stderr, "Could not get tsd base address.  This will not end well.\n");
247*1031c584SApple OSS Distributions 		return 0;
248*1031c584SApple OSS Distributions 	}
249*1031c584SApple OSS Distributions 
250*1031c584SApple OSS Distributions 	return (uint64_t)tiinfo.thread_handle;
251*1031c584SApple OSS Distributions }
252*1031c584SApple OSS Distributions 
253*1031c584SApple OSS Distributions void
restore_gsbase(uint64_t stackptr)254*1031c584SApple OSS Distributions restore_gsbase(uint64_t stackptr)
255*1031c584SApple OSS Distributions {
256*1031c584SApple OSS Distributions 	/* Restore GSbase so tsd is accessible in long mode */
257*1031c584SApple OSS Distributions 	uint64_t orig_GSbase = stack_range_to_GSbase(stackptr, 0);
258*1031c584SApple OSS Distributions 
259*1031c584SApple OSS Distributions 	assert(orig_GSbase != 0);
260*1031c584SApple OSS Distributions 	_thread_set_tsd_base(orig_GSbase);
261*1031c584SApple OSS Distributions }
262*1031c584SApple OSS Distributions 
263*1031c584SApple OSS Distributions /*
264*1031c584SApple OSS Distributions  * Though we've directed all exceptions through the catch_mach_exception_raise_state_identity
265*1031c584SApple OSS Distributions  * entry point, we still must provide these two other entry points, otherwise a linker error
266*1031c584SApple OSS Distributions  * will occur.
267*1031c584SApple OSS Distributions  */
268*1031c584SApple OSS Distributions kern_return_t
catch_mach_exception_raise(mach_port_t exception_port,mach_port_t thread,mach_port_t task,exception_type_t exception,mach_exception_data_t code,mach_msg_type_number_t codeCnt,int * flavor,thread_state_t old_state,mach_msg_type_number_t old_stateCnt,thread_state_t new_state,mach_msg_type_number_t * new_stateCnt)269*1031c584SApple OSS Distributions catch_mach_exception_raise(mach_port_t exception_port,
270*1031c584SApple OSS Distributions     mach_port_t thread,
271*1031c584SApple OSS Distributions     mach_port_t task,
272*1031c584SApple OSS Distributions     exception_type_t exception,
273*1031c584SApple OSS Distributions     mach_exception_data_t code,
274*1031c584SApple OSS Distributions     mach_msg_type_number_t codeCnt,
275*1031c584SApple OSS Distributions     int *flavor,
276*1031c584SApple OSS Distributions     thread_state_t old_state,
277*1031c584SApple OSS Distributions     mach_msg_type_number_t old_stateCnt,
278*1031c584SApple OSS Distributions     thread_state_t new_state,
279*1031c584SApple OSS Distributions     mach_msg_type_number_t *new_stateCnt)
280*1031c584SApple OSS Distributions {
281*1031c584SApple OSS Distributions #pragma unused(exception_port, thread, task, exception, code, codeCnt, flavor, old_state, old_stateCnt, new_state, new_stateCnt)
282*1031c584SApple OSS Distributions 	fprintf(stderr, "Unexpected exception handler called: %s\n", __func__);
283*1031c584SApple OSS Distributions 	return KERN_FAILURE;
284*1031c584SApple OSS Distributions }
285*1031c584SApple OSS Distributions 
286*1031c584SApple OSS Distributions kern_return_t
catch_mach_exception_raise_state(mach_port_t exception_port,exception_type_t exception,const mach_exception_data_t code,mach_msg_type_number_t codeCnt,int * flavor,const thread_state_t old_state,mach_msg_type_number_t old_stateCnt,thread_state_t new_state,mach_msg_type_number_t * new_stateCnt)287*1031c584SApple OSS Distributions catch_mach_exception_raise_state(mach_port_t exception_port,
288*1031c584SApple OSS Distributions     exception_type_t exception,
289*1031c584SApple OSS Distributions     const mach_exception_data_t code,
290*1031c584SApple OSS Distributions     mach_msg_type_number_t codeCnt,
291*1031c584SApple OSS Distributions     int *flavor,
292*1031c584SApple OSS Distributions     const thread_state_t old_state,
293*1031c584SApple OSS Distributions     mach_msg_type_number_t old_stateCnt,
294*1031c584SApple OSS Distributions     thread_state_t new_state,
295*1031c584SApple OSS Distributions     mach_msg_type_number_t *new_stateCnt)
296*1031c584SApple OSS Distributions {
297*1031c584SApple OSS Distributions #pragma unused(exception_port, exception, code, codeCnt, flavor, old_state, old_stateCnt, new_state, new_stateCnt)
298*1031c584SApple OSS Distributions 	fprintf(stderr, "Unexpected exception handler called: %s\n", __func__);
299*1031c584SApple OSS Distributions 	return KERN_FAILURE;
300*1031c584SApple OSS Distributions }
301*1031c584SApple OSS Distributions 
302*1031c584SApple OSS Distributions static void
handle_arithmetic_exception(_STRUCT_X86_THREAD_FULL_STATE64 * xtfs64,uint64_t * ip_skip_countp)303*1031c584SApple OSS Distributions handle_arithmetic_exception(_STRUCT_X86_THREAD_FULL_STATE64 *xtfs64, uint64_t *ip_skip_countp)
304*1031c584SApple OSS Distributions {
305*1031c584SApple OSS Distributions 	fprintf(stderr, "Caught divide-error exception\n");
306*1031c584SApple OSS Distributions 	fprintf(stderr, "cs=0x%x rip=0x%x gs=0x%x ss=0x%x rsp=0x%llx\n",
307*1031c584SApple OSS Distributions 	    (unsigned)xtfs64->__ss64.__cs,
308*1031c584SApple OSS Distributions 	    (unsigned)xtfs64->__ss64.__rip, (unsigned)xtfs64->__ss64.__gs,
309*1031c584SApple OSS Distributions 	    (unsigned)xtfs64->__ss, xtfs64->__ss64.__rsp);
310*1031c584SApple OSS Distributions 	*ip_skip_countp = 2;
311*1031c584SApple OSS Distributions }
312*1031c584SApple OSS Distributions 
313*1031c584SApple OSS Distributions static void
handle_badinsn_exception(_STRUCT_X86_THREAD_FULL_STATE64 * xtfs64,uint64_t __unused * ip_skip_countp)314*1031c584SApple OSS Distributions handle_badinsn_exception(_STRUCT_X86_THREAD_FULL_STATE64 *xtfs64, uint64_t __unused *ip_skip_countp)
315*1031c584SApple OSS Distributions {
316*1031c584SApple OSS Distributions 	extern void first_invalid_opcode(void);
317*1031c584SApple OSS Distributions 	extern void last_invalid_opcode(void);
318*1031c584SApple OSS Distributions 
319*1031c584SApple OSS Distributions 	uint64_t start_addr = ((uintptr_t)first_invalid_opcode - (uintptr_t)code_32);
320*1031c584SApple OSS Distributions 	uint64_t end_addr = ((uintptr_t)last_invalid_opcode - (uintptr_t)code_32);
321*1031c584SApple OSS Distributions 
322*1031c584SApple OSS Distributions 	fprintf(stderr, "Caught invalid opcode exception\n");
323*1031c584SApple OSS Distributions 	fprintf(stderr, "cs=%x rip=%x gs=%x ss=0x%x rsp=0x%llx | handling between 0x%llx and 0x%llx\n",
324*1031c584SApple OSS Distributions 	    (unsigned)xtfs64->__ss64.__cs,
325*1031c584SApple OSS Distributions 	    (unsigned)xtfs64->__ss64.__rip, (unsigned)xtfs64->__ss64.__gs,
326*1031c584SApple OSS Distributions 	    (unsigned)xtfs64->__ss, xtfs64->__ss64.__rsp,
327*1031c584SApple OSS Distributions 	    start_addr, end_addr);
328*1031c584SApple OSS Distributions 
329*1031c584SApple OSS Distributions 	/*
330*1031c584SApple OSS Distributions 	 * We expect to handle 4 invalid opcode exceptions:
331*1031c584SApple OSS Distributions 	 * (1) sysenter
332*1031c584SApple OSS Distributions 	 * (2) int $0x80
333*1031c584SApple OSS Distributions 	 * (3) int $0x81
334*1031c584SApple OSS Distributions 	 * (4) int $0x82
335*1031c584SApple OSS Distributions 	 * (Note that due to the way the invalid opcode indication was implemented,
336*1031c584SApple OSS Distributions 	 * %rip is already set to the next instruction.)
337*1031c584SApple OSS Distributions 	 */
338*1031c584SApple OSS Distributions 	if (xtfs64->__ss64.__rip >= start_addr && xtfs64->__ss64.__rip <= end_addr) {
339*1031c584SApple OSS Distributions 		/*
340*1031c584SApple OSS Distributions 		 * On return from the failed sysenter, %cs is changed to the
341*1031c584SApple OSS Distributions 		 * sysenter code selector and %ss is set to 0x23, so switch them
342*1031c584SApple OSS Distributions 		 * back to sane values.
343*1031c584SApple OSS Distributions 		 */
344*1031c584SApple OSS Distributions 		if ((unsigned)xtfs64->__ss64.__cs == SYSENTER_SELECTOR) {
345*1031c584SApple OSS Distributions 			xtfs64->__ss64.__cs = COMPAT_MODE_CS_SELECTOR;
346*1031c584SApple OSS Distributions 			xtfs64->__ss = 0x23; /* XXX */
347*1031c584SApple OSS Distributions 		}
348*1031c584SApple OSS Distributions 	}
349*1031c584SApple OSS Distributions }
350*1031c584SApple OSS Distributions 
351*1031c584SApple OSS Distributions kern_return_t
catch_mach_exception_raise_state_identity(mach_port_t exception_port,mach_port_t thread,mach_port_t task,exception_type_t exception,mach_exception_data_t code,mach_msg_type_number_t codeCnt,int * flavor,thread_state_t old_state,mach_msg_type_number_t old_stateCnt,thread_state_t new_state,mach_msg_type_number_t * new_stateCnt)352*1031c584SApple OSS Distributions catch_mach_exception_raise_state_identity(mach_port_t exception_port,
353*1031c584SApple OSS Distributions     mach_port_t thread,
354*1031c584SApple OSS Distributions     mach_port_t task,
355*1031c584SApple OSS Distributions     exception_type_t exception,
356*1031c584SApple OSS Distributions     mach_exception_data_t code,
357*1031c584SApple OSS Distributions     mach_msg_type_number_t codeCnt,
358*1031c584SApple OSS Distributions     int * flavor,
359*1031c584SApple OSS Distributions     thread_state_t old_state,
360*1031c584SApple OSS Distributions     mach_msg_type_number_t old_stateCnt,
361*1031c584SApple OSS Distributions     thread_state_t new_state,
362*1031c584SApple OSS Distributions     mach_msg_type_number_t * new_stateCnt)
363*1031c584SApple OSS Distributions {
364*1031c584SApple OSS Distributions #pragma unused(exception_port, thread, task)
365*1031c584SApple OSS Distributions 
366*1031c584SApple OSS Distributions 	_STRUCT_X86_THREAD_FULL_STATE64 *xtfs64 = (_STRUCT_X86_THREAD_FULL_STATE64 *)(void *)old_state;
367*1031c584SApple OSS Distributions 	_STRUCT_X86_THREAD_FULL_STATE64 *new_xtfs64 = (_STRUCT_X86_THREAD_FULL_STATE64 *)(void *)new_state;
368*1031c584SApple OSS Distributions 	uint64_t rip_skip_count = 0;
369*1031c584SApple OSS Distributions 
370*1031c584SApple OSS Distributions 	/*
371*1031c584SApple OSS Distributions 	 * Check the exception code and thread state.
372*1031c584SApple OSS Distributions 	 * If we were executing 32-bit code (or 64-bit code on behalf of
373*1031c584SApple OSS Distributions 	 * 32-bit code), we could update the thread state to effectively longjmp
374*1031c584SApple OSS Distributions 	 * back to a safe location where the victim thread can recover.
375*1031c584SApple OSS Distributions 	 * Then again, we could return KERN_NOT_SUPPORTED and allow the process
376*1031c584SApple OSS Distributions 	 * to be nuked.
377*1031c584SApple OSS Distributions 	 */
378*1031c584SApple OSS Distributions 
379*1031c584SApple OSS Distributions 	switch (exception) {
380*1031c584SApple OSS Distributions 	case EXC_ARITHMETIC:
381*1031c584SApple OSS Distributions 		if (codeCnt >= 1 && code[0] == EXC_I386_DIV) {
382*1031c584SApple OSS Distributions 			handle_arithmetic_exception(xtfs64, &rip_skip_count);
383*1031c584SApple OSS Distributions 		}
384*1031c584SApple OSS Distributions 		break;
385*1031c584SApple OSS Distributions 
386*1031c584SApple OSS Distributions 	case EXC_BAD_INSTRUCTION:
387*1031c584SApple OSS Distributions 	{
388*1031c584SApple OSS Distributions 		if (codeCnt >= 1 && code[0] == EXC_I386_INVOP) {
389*1031c584SApple OSS Distributions 			handle_badinsn_exception(xtfs64, &rip_skip_count);
390*1031c584SApple OSS Distributions 		}
391*1031c584SApple OSS Distributions 		break;
392*1031c584SApple OSS Distributions 	}
393*1031c584SApple OSS Distributions 
394*1031c584SApple OSS Distributions 	default:
395*1031c584SApple OSS Distributions 		fprintf(stderr, "Unsupported catch_mach_exception_raise_state_identity: code 0x%llx sub 0x%llx\n",
396*1031c584SApple OSS Distributions 		    code[0], codeCnt > 1 ? code[1] : 0LL);
397*1031c584SApple OSS Distributions 		fprintf(stderr, "flavor=%d %%cs=0x%x %%rip=0x%llx\n", *flavor, (unsigned)xtfs64->__ss64.__cs,
398*1031c584SApple OSS Distributions 		    xtfs64->__ss64.__rip);
399*1031c584SApple OSS Distributions 	}
400*1031c584SApple OSS Distributions 
401*1031c584SApple OSS Distributions 	/*
402*1031c584SApple OSS Distributions 	 * If this exception happened in compatibility mode,
403*1031c584SApple OSS Distributions 	 * assume it was the intentional division-by-zero and set the
404*1031c584SApple OSS Distributions 	 * new state's cs register to just after the div instruction
405*1031c584SApple OSS Distributions 	 * to enable the thread to resume.
406*1031c584SApple OSS Distributions 	 */
407*1031c584SApple OSS Distributions 	if ((unsigned)xtfs64->__ss64.__cs == COMPAT_MODE_CS_SELECTOR) {
408*1031c584SApple OSS Distributions 		*new_stateCnt = old_stateCnt;
409*1031c584SApple OSS Distributions 		*new_xtfs64 = *xtfs64;
410*1031c584SApple OSS Distributions 		new_xtfs64->__ss64.__rip += rip_skip_count;
411*1031c584SApple OSS Distributions 		fprintf(stderr, "new cs=0x%x rip=0x%llx\n", (unsigned)new_xtfs64->__ss64.__cs,
412*1031c584SApple OSS Distributions 		    new_xtfs64->__ss64.__rip);
413*1031c584SApple OSS Distributions 		return KERN_SUCCESS;
414*1031c584SApple OSS Distributions 	} else {
415*1031c584SApple OSS Distributions 		return KERN_NOT_SUPPORTED;
416*1031c584SApple OSS Distributions 	}
417*1031c584SApple OSS Distributions }
418*1031c584SApple OSS Distributions 
419*1031c584SApple OSS Distributions static void *
handle_exceptions(void * arg)420*1031c584SApple OSS Distributions handle_exceptions(void *arg)
421*1031c584SApple OSS Distributions {
422*1031c584SApple OSS Distributions 	mach_port_t ePort = (mach_port_t)arg;
423*1031c584SApple OSS Distributions 	kern_return_t kret;
424*1031c584SApple OSS Distributions 
425*1031c584SApple OSS Distributions 	kret = mach_msg_server(mach_exc_server, MACH_MSG_SIZE_RELIABLE, ePort, 0);
426*1031c584SApple OSS Distributions 	if (kret != KERN_SUCCESS) {
427*1031c584SApple OSS Distributions 		fprintf(stderr, "mach_msg_server: %s (%d)", mach_error_string(kret), kret);
428*1031c584SApple OSS Distributions 	}
429*1031c584SApple OSS Distributions 
430*1031c584SApple OSS Distributions 	return NULL;
431*1031c584SApple OSS Distributions }
432*1031c584SApple OSS Distributions 
433*1031c584SApple OSS Distributions static void
init_task_exception_server(void)434*1031c584SApple OSS Distributions init_task_exception_server(void)
435*1031c584SApple OSS Distributions {
436*1031c584SApple OSS Distributions 	kern_return_t kr;
437*1031c584SApple OSS Distributions 	task_t me = mach_task_self();
438*1031c584SApple OSS Distributions 	pthread_t handler_thread;
439*1031c584SApple OSS Distributions 	pthread_attr_t  attr;
440*1031c584SApple OSS Distributions 	mach_port_t ePort;
441*1031c584SApple OSS Distributions 
442*1031c584SApple OSS Distributions 	kr = mach_port_allocate(me, MACH_PORT_RIGHT_RECEIVE, &ePort);
443*1031c584SApple OSS Distributions 	if (kr != KERN_SUCCESS) {
444*1031c584SApple OSS Distributions 		fprintf(stderr, "allocate receive right: %d\n", kr);
445*1031c584SApple OSS Distributions 		return;
446*1031c584SApple OSS Distributions 	}
447*1031c584SApple OSS Distributions 
448*1031c584SApple OSS Distributions 	kr = mach_port_insert_right(me, ePort, ePort, MACH_MSG_TYPE_MAKE_SEND);
449*1031c584SApple OSS Distributions 	if (kr != KERN_SUCCESS) {
450*1031c584SApple OSS Distributions 		fprintf(stderr, "insert right into port=[%d]: %d\n", ePort, kr);
451*1031c584SApple OSS Distributions 		return;
452*1031c584SApple OSS Distributions 	}
453*1031c584SApple OSS Distributions 
454*1031c584SApple OSS Distributions 	kr = task_set_exception_ports(me, EXC_MASK_BAD_INSTRUCTION | EXC_MASK_ARITHMETIC, ePort,
455*1031c584SApple OSS Distributions 	    (exception_behavior_t)(EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES), x86_THREAD_FULL_STATE64);
456*1031c584SApple OSS Distributions 	if (kr != KERN_SUCCESS) {
457*1031c584SApple OSS Distributions 		fprintf(stderr, "abort: error setting task exception ports on task=[%d], handler=[%d]: %d\n", me, ePort, kr);
458*1031c584SApple OSS Distributions 		exit(1);
459*1031c584SApple OSS Distributions 	}
460*1031c584SApple OSS Distributions 
461*1031c584SApple OSS Distributions 	pthread_attr_init(&attr);
462*1031c584SApple OSS Distributions 	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
463*1031c584SApple OSS Distributions 
464*1031c584SApple OSS Distributions 	if (pthread_create(&handler_thread, &attr, handle_exceptions, (void *)(uintptr_t)ePort) != 0) {
465*1031c584SApple OSS Distributions 		perror("pthread create error");
466*1031c584SApple OSS Distributions 		return;
467*1031c584SApple OSS Distributions 	}
468*1031c584SApple OSS Distributions 
469*1031c584SApple OSS Distributions 	pthread_attr_destroy(&attr);
470*1031c584SApple OSS Distributions }
471*1031c584SApple OSS Distributions 
472*1031c584SApple OSS Distributions static union ldt_entry *descs = 0;
473*1031c584SApple OSS Distributions static uint64_t idx;
474*1031c584SApple OSS Distributions static int saw_ud2 = 0;
475*1031c584SApple OSS Distributions static boolean_t ENV_set_ldt_in_sighandler = FALSE;
476*1031c584SApple OSS Distributions 
477*1031c584SApple OSS Distributions static void
signal_handler(int signo,siginfo_t * sinfop,void * ucontext)478*1031c584SApple OSS Distributions signal_handler(int signo, siginfo_t *sinfop, void *ucontext)
479*1031c584SApple OSS Distributions {
480*1031c584SApple OSS Distributions 	uint64_t rip_skip_count = 0;
481*1031c584SApple OSS Distributions 	ucontext_t *uctxp = (ucontext_t *)ucontext;
482*1031c584SApple OSS Distributions 	union {
483*1031c584SApple OSS Distributions 		_STRUCT_MCONTEXT_AVX512_64 *avx512_basep;
484*1031c584SApple OSS Distributions 		_STRUCT_MCONTEXT_AVX512_64_FULL *avx512_fullp;
485*1031c584SApple OSS Distributions 		_STRUCT_MCONTEXT_AVX64 *avx64_basep;
486*1031c584SApple OSS Distributions 		_STRUCT_MCONTEXT_AVX64_FULL *avx64_fullp;
487*1031c584SApple OSS Distributions 		_STRUCT_MCONTEXT64 *fp_basep;
488*1031c584SApple OSS Distributions 		_STRUCT_MCONTEXT64_FULL *fp_fullp;
489*1031c584SApple OSS Distributions 	} mctx;
490*1031c584SApple OSS Distributions 
491*1031c584SApple OSS Distributions 	mctx.fp_fullp = (_STRUCT_MCONTEXT64_FULL *)uctxp->uc_mcontext;
492*1031c584SApple OSS Distributions 
493*1031c584SApple OSS Distributions 	/*
494*1031c584SApple OSS Distributions 	 * Note that GSbase must be restored before calling into any frameworks
495*1031c584SApple OSS Distributions 	 * that might access anything %gs-relative (e.g. TSD) if the signal
496*1031c584SApple OSS Distributions 	 * handler was triggered while the thread was running with a non-default
497*1031c584SApple OSS Distributions 	 * (system-established) GSbase.
498*1031c584SApple OSS Distributions 	 */
499*1031c584SApple OSS Distributions 
500*1031c584SApple OSS Distributions 	if ((signo != SIGFPE && signo != SIGILL) || sinfop->si_signo != signo) {
501*1031c584SApple OSS Distributions #ifndef STANDALONE
502*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("Unexpected signal %d\n", signo);
503*1031c584SApple OSS Distributions #else
504*1031c584SApple OSS Distributions 		restore_gsbase(mctx.fp_fullp->__ss.__ss64.__rsp);
505*1031c584SApple OSS Distributions 		fprintf(stderr, "Not handling signal %d\n", signo);
506*1031c584SApple OSS Distributions 		abort();
507*1031c584SApple OSS Distributions #endif
508*1031c584SApple OSS Distributions 	}
509*1031c584SApple OSS Distributions 
510*1031c584SApple OSS Distributions 	if (uctxp->uc_mcsize == sizeof(_STRUCT_MCONTEXT_AVX512_64) ||
511*1031c584SApple OSS Distributions 	    uctxp->uc_mcsize == sizeof(_STRUCT_MCONTEXT_AVX64) ||
512*1031c584SApple OSS Distributions 	    uctxp->uc_mcsize == sizeof(_STRUCT_MCONTEXT64)) {
513*1031c584SApple OSS Distributions 		_STRUCT_X86_THREAD_STATE64 *ss64 = &mctx.fp_basep->__ss;
514*1031c584SApple OSS Distributions 
515*1031c584SApple OSS Distributions 		/*
516*1031c584SApple OSS Distributions 		 * The following block is an illustration of what NOT to do.
517*1031c584SApple OSS Distributions 		 * Configuring an LDT for the first time in a signal handler
518*1031c584SApple OSS Distributions 		 * will likely cause the process to crash.
519*1031c584SApple OSS Distributions 		 */
520*1031c584SApple OSS Distributions 		if (ENV_set_ldt_in_sighandler == TRUE && !saw_ud2) {
521*1031c584SApple OSS Distributions 			/* Set the LDT: */
522*1031c584SApple OSS Distributions 			int cnt = i386_set_ldt((int)idx, &descs[idx], 1);
523*1031c584SApple OSS Distributions 			if (cnt != (int)idx) {
524*1031c584SApple OSS Distributions #ifdef DEBUG
525*1031c584SApple OSS Distributions 				fprintf(stderr, "i386_set_ldt unexpectedly returned %d (errno = %s)\n", cnt, strerror(errno));
526*1031c584SApple OSS Distributions #endif
527*1031c584SApple OSS Distributions #ifndef STANDALONE
528*1031c584SApple OSS Distributions 				T_LOG("i386_set_ldt unexpectedly returned %d (errno: %s)\n", cnt, strerror(errno));
529*1031c584SApple OSS Distributions 				T_ASSERT_FAIL("i386_set_ldt failure");
530*1031c584SApple OSS Distributions #else
531*1031c584SApple OSS Distributions 				exit(1);
532*1031c584SApple OSS Distributions #endif
533*1031c584SApple OSS Distributions 			}
534*1031c584SApple OSS Distributions #ifdef DEBUG
535*1031c584SApple OSS Distributions 			printf("i386_set_ldt returned %d\n", cnt);
536*1031c584SApple OSS Distributions #endif
537*1031c584SApple OSS Distributions 			ss64->__rip += 2;       /* ud2 is 2 bytes */
538*1031c584SApple OSS Distributions 
539*1031c584SApple OSS Distributions 			saw_ud2 = 1;
540*1031c584SApple OSS Distributions 
541*1031c584SApple OSS Distributions 			/*
542*1031c584SApple OSS Distributions 			 * When we return here, the sigreturn processing code will try to copy a FULL
543*1031c584SApple OSS Distributions 			 * thread context from the signal stack, which will likely cause the resumed
544*1031c584SApple OSS Distributions 			 * thread to fault and be terminated.
545*1031c584SApple OSS Distributions 			 */
546*1031c584SApple OSS Distributions 			return;
547*1031c584SApple OSS Distributions 		}
548*1031c584SApple OSS Distributions 
549*1031c584SApple OSS Distributions 		restore_gsbase(ss64->__rsp);
550*1031c584SApple OSS Distributions 
551*1031c584SApple OSS Distributions 		/*
552*1031c584SApple OSS Distributions 		 * If we're in this block, either we are dispatching a signal received
553*1031c584SApple OSS Distributions 		 * before we installed a custom LDT or we are on a kernel without
554*1031c584SApple OSS Distributions 		 * BSD-signalling-sending-full-thread-state support.  It's likely the latter case.
555*1031c584SApple OSS Distributions 		 */
556*1031c584SApple OSS Distributions #ifndef STANDALONE
557*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("This system doesn't support BSD signals with full thread state.");
558*1031c584SApple OSS Distributions #else
559*1031c584SApple OSS Distributions 		fprintf(stderr, "This system doesn't support BSD signals with full thread state.  Aborting.\n");
560*1031c584SApple OSS Distributions 		abort();
561*1031c584SApple OSS Distributions #endif
562*1031c584SApple OSS Distributions 	} else if (uctxp->uc_mcsize == sizeof(_STRUCT_MCONTEXT_AVX512_64_FULL) ||
563*1031c584SApple OSS Distributions 	    uctxp->uc_mcsize == sizeof(_STRUCT_MCONTEXT_AVX64_FULL) ||
564*1031c584SApple OSS Distributions 	    uctxp->uc_mcsize == sizeof(_STRUCT_MCONTEXT64_FULL)) {
565*1031c584SApple OSS Distributions 		_STRUCT_X86_THREAD_FULL_STATE64 *ss64 = &mctx.fp_fullp->__ss;
566*1031c584SApple OSS Distributions 
567*1031c584SApple OSS Distributions 		/*
568*1031c584SApple OSS Distributions 		 * Since we're handing this signal on the same thread, we may need to
569*1031c584SApple OSS Distributions 		 * restore GSbase.
570*1031c584SApple OSS Distributions 		 */
571*1031c584SApple OSS Distributions 		uint64_t orig_gsbase = stack_range_to_GSbase(ss64->__ss64.__rsp, 0);
572*1031c584SApple OSS Distributions 		if (orig_gsbase != 0 && orig_gsbase != ss64->__gsbase) {
573*1031c584SApple OSS Distributions 			restore_gsbase(ss64->__ss64.__rsp);
574*1031c584SApple OSS Distributions 		}
575*1031c584SApple OSS Distributions 
576*1031c584SApple OSS Distributions 		if (signo == SIGFPE) {
577*1031c584SApple OSS Distributions 			handle_arithmetic_exception(ss64, &rip_skip_count);
578*1031c584SApple OSS Distributions 		} else if (signo == SIGILL) {
579*1031c584SApple OSS Distributions 			handle_badinsn_exception(ss64, &rip_skip_count);
580*1031c584SApple OSS Distributions 		}
581*1031c584SApple OSS Distributions 
582*1031c584SApple OSS Distributions 		/*
583*1031c584SApple OSS Distributions 		 * If this exception happened in compatibility mode,
584*1031c584SApple OSS Distributions 		 * assume it was the intentional division-by-zero and set the
585*1031c584SApple OSS Distributions 		 * new state's cs register to just after the div instruction
586*1031c584SApple OSS Distributions 		 * to enable the thread to resume.
587*1031c584SApple OSS Distributions 		 */
588*1031c584SApple OSS Distributions 		if ((unsigned)ss64->__ss64.__cs == COMPAT_MODE_CS_SELECTOR) {
589*1031c584SApple OSS Distributions 			ss64->__ss64.__rip += rip_skip_count;
590*1031c584SApple OSS Distributions 			fprintf(stderr, "new cs=0x%x rip=0x%llx\n", (unsigned)ss64->__ss64.__cs,
591*1031c584SApple OSS Distributions 			    ss64->__ss64.__rip);
592*1031c584SApple OSS Distributions 		}
593*1031c584SApple OSS Distributions 	} else {
594*1031c584SApple OSS Distributions 		_STRUCT_X86_THREAD_STATE64 *ss64 = &mctx.fp_basep->__ss;
595*1031c584SApple OSS Distributions 
596*1031c584SApple OSS Distributions 		restore_gsbase(ss64->__rsp);
597*1031c584SApple OSS Distributions #ifndef STANDALONE
598*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("Unknown mcontext size %lu: Aborting.", uctxp->uc_mcsize);
599*1031c584SApple OSS Distributions #else
600*1031c584SApple OSS Distributions 		fprintf(stderr, "Unknown mcontext size %lu: Aborting.\n", uctxp->uc_mcsize);
601*1031c584SApple OSS Distributions 		abort();
602*1031c584SApple OSS Distributions #endif
603*1031c584SApple OSS Distributions 	}
604*1031c584SApple OSS Distributions }
605*1031c584SApple OSS Distributions 
606*1031c584SApple OSS Distributions static void
setup_signal_handling(void)607*1031c584SApple OSS Distributions setup_signal_handling(void)
608*1031c584SApple OSS Distributions {
609*1031c584SApple OSS Distributions 	int rv;
610*1031c584SApple OSS Distributions 
611*1031c584SApple OSS Distributions 	struct sigaction sa = {
612*1031c584SApple OSS Distributions 		.__sigaction_u = { .__sa_sigaction = signal_handler },
613*1031c584SApple OSS Distributions 		.sa_flags = SA_SIGINFO
614*1031c584SApple OSS Distributions 	};
615*1031c584SApple OSS Distributions 
616*1031c584SApple OSS Distributions 	sigfillset(&sa.sa_mask);
617*1031c584SApple OSS Distributions 
618*1031c584SApple OSS Distributions 	rv = sigaction(SIGFPE, &sa, NULL);
619*1031c584SApple OSS Distributions 	if (rv != 0) {
620*1031c584SApple OSS Distributions #ifndef STANDALONE
621*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("Failed to configure SIGFPE signal handler\n");
622*1031c584SApple OSS Distributions #else
623*1031c584SApple OSS Distributions 		fprintf(stderr, "Failed to configure SIGFPE signal handler\n");
624*1031c584SApple OSS Distributions 		abort();
625*1031c584SApple OSS Distributions #endif
626*1031c584SApple OSS Distributions 	}
627*1031c584SApple OSS Distributions 
628*1031c584SApple OSS Distributions 	rv = sigaction(SIGILL, &sa, NULL);
629*1031c584SApple OSS Distributions 	if (rv != 0) {
630*1031c584SApple OSS Distributions #ifndef STANDALONE
631*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("Failed to configure SIGILL signal handler\n");
632*1031c584SApple OSS Distributions #else
633*1031c584SApple OSS Distributions 		fprintf(stderr, "Failed to configure SIGILL signal handler\n");
634*1031c584SApple OSS Distributions 		abort();
635*1031c584SApple OSS Distributions #endif
636*1031c584SApple OSS Distributions 	}
637*1031c584SApple OSS Distributions }
638*1031c584SApple OSS Distributions 
639*1031c584SApple OSS Distributions static void
teardown_signal_handling(void)640*1031c584SApple OSS Distributions teardown_signal_handling(void)
641*1031c584SApple OSS Distributions {
642*1031c584SApple OSS Distributions 	if (signal(SIGFPE, SIG_DFL) == SIG_ERR) {
643*1031c584SApple OSS Distributions #ifndef STANDALONE
644*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("Error resetting SIGFPE signal disposition\n");
645*1031c584SApple OSS Distributions #else
646*1031c584SApple OSS Distributions 		fprintf(stderr, "Error resetting SIGFPE signal disposition\n");
647*1031c584SApple OSS Distributions 		abort();
648*1031c584SApple OSS Distributions #endif
649*1031c584SApple OSS Distributions 	}
650*1031c584SApple OSS Distributions 
651*1031c584SApple OSS Distributions 	if (signal(SIGILL, SIG_DFL) == SIG_ERR) {
652*1031c584SApple OSS Distributions #ifndef STANDALONE
653*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("Error resetting SIGILL signal disposition\n");
654*1031c584SApple OSS Distributions #else
655*1031c584SApple OSS Distributions 		fprintf(stderr, "Error resetting SIGILL signal disposition\n");
656*1031c584SApple OSS Distributions 		abort();
657*1031c584SApple OSS Distributions #endif
658*1031c584SApple OSS Distributions 	}
659*1031c584SApple OSS Distributions }
660*1031c584SApple OSS Distributions 
661*1031c584SApple OSS Distributions #ifdef DEBUG
662*1031c584SApple OSS Distributions static void
dump_desc(union ldt_entry * entp)663*1031c584SApple OSS Distributions dump_desc(union ldt_entry *entp)
664*1031c584SApple OSS Distributions {
665*1031c584SApple OSS Distributions 	printf("base %p lim %p type 0x%x dpl %x present %x opsz %x granular %x\n",
666*1031c584SApple OSS Distributions 	    (void *)(uintptr_t)(entp->code.base00 + (entp->code.base16 << 16) + (entp->code.base24 << 24)),
667*1031c584SApple OSS Distributions 	    (void *)(uintptr_t)(entp->code.limit00 + (entp->code.limit16 << 16)),
668*1031c584SApple OSS Distributions 	    entp->code.type,
669*1031c584SApple OSS Distributions 	    entp->code.dpl,
670*1031c584SApple OSS Distributions 	    entp->code.present,
671*1031c584SApple OSS Distributions 	    entp->code.opsz,
672*1031c584SApple OSS Distributions 	    entp->code.granular);
673*1031c584SApple OSS Distributions }
674*1031c584SApple OSS Distributions #endif
675*1031c584SApple OSS Distributions 
676*1031c584SApple OSS Distributions static int
map_lowmem_stack(void ** lowmemstk)677*1031c584SApple OSS Distributions map_lowmem_stack(void **lowmemstk)
678*1031c584SApple OSS Distributions {
679*1031c584SApple OSS Distributions 	void *addr;
680*1031c584SApple OSS Distributions 	int err;
681*1031c584SApple OSS Distributions 
682*1031c584SApple OSS Distributions 	if ((addr = mmap(0, FIXED_STACK_SIZE + PAGE_SIZE, PROT_READ | PROT_WRITE,
683*1031c584SApple OSS Distributions 	    MAP_32BIT | MAP_PRIVATE | MAP_ANON, -1, 0)) == MAP_FAILED) {
684*1031c584SApple OSS Distributions 		return errno;
685*1031c584SApple OSS Distributions 	}
686*1031c584SApple OSS Distributions 
687*1031c584SApple OSS Distributions 	if ((uintptr_t)addr > 0xFFFFF000ULL) {
688*1031c584SApple OSS Distributions 		/* Error: This kernel does not support MAP_32BIT or there's a bug. */
689*1031c584SApple OSS Distributions #ifndef STANDALONE
690*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("%s: failed to map a 32-bit-accessible stack", __func__);
691*1031c584SApple OSS Distributions #else
692*1031c584SApple OSS Distributions 		fprintf(stderr, "This kernel returned a virtual address > 4G (%p) despite MAP_32BIT.  Aborting.\n", addr);
693*1031c584SApple OSS Distributions 		exit(1);
694*1031c584SApple OSS Distributions #endif
695*1031c584SApple OSS Distributions 	}
696*1031c584SApple OSS Distributions 
697*1031c584SApple OSS Distributions 	/* Enforce one page of redzone at the bottom of the stack */
698*1031c584SApple OSS Distributions 	if (mprotect(addr, PAGE_SIZE, PROT_NONE) < 0) {
699*1031c584SApple OSS Distributions 		err = errno;
700*1031c584SApple OSS Distributions 		(void) munmap(addr, FIXED_STACK_SIZE + PAGE_SIZE);
701*1031c584SApple OSS Distributions 		return err;
702*1031c584SApple OSS Distributions 	}
703*1031c584SApple OSS Distributions 
704*1031c584SApple OSS Distributions 	if (lowmemstk) {
705*1031c584SApple OSS Distributions 		stack2gs[0].stack_base = (uintptr_t)addr + PAGE_SIZE;
706*1031c584SApple OSS Distributions 		stack2gs[0].stack_limit = stack2gs[0].stack_base + FIXED_STACK_SIZE;
707*1031c584SApple OSS Distributions 		*lowmemstk = (void *)((uintptr_t)addr + PAGE_SIZE);
708*1031c584SApple OSS Distributions 	}
709*1031c584SApple OSS Distributions 
710*1031c584SApple OSS Distributions 	return 0;
711*1031c584SApple OSS Distributions }
712*1031c584SApple OSS Distributions 
713*1031c584SApple OSS Distributions static int
map_32bit_code_impl(uint8_t * code_src,size_t code_len,void ** codeptr,size_t szlimit)714*1031c584SApple OSS Distributions map_32bit_code_impl(uint8_t *code_src, size_t code_len, void **codeptr,
715*1031c584SApple OSS Distributions     size_t szlimit)
716*1031c584SApple OSS Distributions {
717*1031c584SApple OSS Distributions 	void *addr;
718*1031c584SApple OSS Distributions 	size_t sz = (size_t)P2ROUNDUP(code_len, (unsigned)PAGE_SIZE);
719*1031c584SApple OSS Distributions 
720*1031c584SApple OSS Distributions 	if (code_len > szlimit) {
721*1031c584SApple OSS Distributions 		return E2BIG;
722*1031c584SApple OSS Distributions 	}
723*1031c584SApple OSS Distributions 
724*1031c584SApple OSS Distributions #ifdef DEBUG
725*1031c584SApple OSS Distributions 	printf("size = %lu, szlimit = %u\n", sz, (unsigned)szlimit);
726*1031c584SApple OSS Distributions #endif
727*1031c584SApple OSS Distributions 
728*1031c584SApple OSS Distributions 	if ((addr = mmap(0, sz, PROT_READ | PROT_WRITE | PROT_EXEC,
729*1031c584SApple OSS Distributions 	    MAP_32BIT | MAP_PRIVATE | MAP_ANON, -1, 0)) == MAP_FAILED) {
730*1031c584SApple OSS Distributions 		return errno;
731*1031c584SApple OSS Distributions 	}
732*1031c584SApple OSS Distributions 
733*1031c584SApple OSS Distributions 	if ((uintptr_t)addr > 0xFFFFF000ULL) {
734*1031c584SApple OSS Distributions 		/* Error: This kernel does not support MAP_32BIT or there's a bug. */
735*1031c584SApple OSS Distributions #ifndef STANDALONE
736*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("%s: failed to map a 32-bit-accessible trampoline", __func__);
737*1031c584SApple OSS Distributions #else
738*1031c584SApple OSS Distributions 		fprintf(stderr, "This kernel returned a virtual address > 4G (%p) despite MAP_32BIT.  Aborting.\n", addr);
739*1031c584SApple OSS Distributions 		exit(1);
740*1031c584SApple OSS Distributions #endif
741*1031c584SApple OSS Distributions 	}
742*1031c584SApple OSS Distributions 
743*1031c584SApple OSS Distributions #ifdef DEBUG
744*1031c584SApple OSS Distributions 	printf("Mapping code @%p..%p => %p..%p\n", (void *)code_src,
745*1031c584SApple OSS Distributions 	    (void *)((uintptr_t)code_src + (unsigned)code_len),
746*1031c584SApple OSS Distributions 	    addr, (void *)((uintptr_t)addr + (unsigned)code_len));
747*1031c584SApple OSS Distributions #endif
748*1031c584SApple OSS Distributions 
749*1031c584SApple OSS Distributions 	bcopy(code_src, addr, code_len);
750*1031c584SApple OSS Distributions 
751*1031c584SApple OSS Distributions 	/* Fill the rest of the page with NOPs */
752*1031c584SApple OSS Distributions 	if ((sz - code_len) > 0) {
753*1031c584SApple OSS Distributions 		memset((void *)((uintptr_t)addr + code_len), 0x90, sz - code_len);
754*1031c584SApple OSS Distributions 	}
755*1031c584SApple OSS Distributions 
756*1031c584SApple OSS Distributions 	if (codeptr) {
757*1031c584SApple OSS Distributions 		*codeptr = addr;
758*1031c584SApple OSS Distributions 	}
759*1031c584SApple OSS Distributions 
760*1031c584SApple OSS Distributions 	return 0;
761*1031c584SApple OSS Distributions }
762*1031c584SApple OSS Distributions 
763*1031c584SApple OSS Distributions static int
map_32bit_trampoline(compat_tramp_t * lowmemtrampp)764*1031c584SApple OSS Distributions map_32bit_trampoline(compat_tramp_t *lowmemtrampp)
765*1031c584SApple OSS Distributions {
766*1031c584SApple OSS Distributions 	extern int compat_mode_trampoline_len;
767*1031c584SApple OSS Distributions 
768*1031c584SApple OSS Distributions 	return map_32bit_code_impl((uint8_t *)&compat_mode_trampoline,
769*1031c584SApple OSS Distributions 	           (size_t)compat_mode_trampoline_len, (void **)lowmemtrampp,
770*1031c584SApple OSS Distributions 	           FIXED_TRAMP_MAXLEN);
771*1031c584SApple OSS Distributions }
772*1031c584SApple OSS Distributions 
773*1031c584SApple OSS Distributions static uint64_t
stack_range_to_GSbase(uint64_t stackptr,uint64_t GSbase)774*1031c584SApple OSS Distributions stack_range_to_GSbase(uint64_t stackptr, uint64_t GSbase)
775*1031c584SApple OSS Distributions {
776*1031c584SApple OSS Distributions 	unsigned long i;
777*1031c584SApple OSS Distributions 
778*1031c584SApple OSS Distributions 	for (i = 0; i < sizeof(stack2gs) / sizeof(stack2gs[0]); i++) {
779*1031c584SApple OSS Distributions 		if (stackptr >= stack2gs[i].stack_base &&
780*1031c584SApple OSS Distributions 		    stackptr < stack2gs[i].stack_limit) {
781*1031c584SApple OSS Distributions 			if (GSbase != 0) {
782*1031c584SApple OSS Distributions #ifdef DEBUG
783*1031c584SApple OSS Distributions 				fprintf(stderr, "Updated gsbase for stack at 0x%llx..0x%llx to 0x%llx\n",
784*1031c584SApple OSS Distributions 				    stack2gs[i].stack_base, stack2gs[i].stack_limit, GSbase);
785*1031c584SApple OSS Distributions #endif
786*1031c584SApple OSS Distributions 				stack2gs[i].GSbase = GSbase;
787*1031c584SApple OSS Distributions 			}
788*1031c584SApple OSS Distributions 			return stack2gs[i].GSbase;
789*1031c584SApple OSS Distributions 		}
790*1031c584SApple OSS Distributions 	}
791*1031c584SApple OSS Distributions 	return 0;
792*1031c584SApple OSS Distributions }
793*1031c584SApple OSS Distributions 
794*1031c584SApple OSS Distributions static uint64_t
call_compatmode(uint32_t stackaddr,uint64_t compat_arg,uint64_t callback)795*1031c584SApple OSS Distributions call_compatmode(uint32_t stackaddr, uint64_t compat_arg, uint64_t callback)
796*1031c584SApple OSS Distributions {
797*1031c584SApple OSS Distributions 	uint64_t rv;
798*1031c584SApple OSS Distributions 
799*1031c584SApple OSS Distributions 	/*
800*1031c584SApple OSS Distributions 	 * Depending on how this is used, this allocation may need to be
801*1031c584SApple OSS Distributions 	 * made with an allocator that returns virtual addresses below 4G.
802*1031c584SApple OSS Distributions 	 */
803*1031c584SApple OSS Distributions 	custom_tsd_t *new_GSbase = malloc(PAGE_SIZE);
804*1031c584SApple OSS Distributions 
805*1031c584SApple OSS Distributions 	/*
806*1031c584SApple OSS Distributions 	 * Change the GSbase (so things like printf will fail unless GSbase is
807*1031c584SApple OSS Distributions 	 * restored)
808*1031c584SApple OSS Distributions 	 */
809*1031c584SApple OSS Distributions 	if (new_GSbase != NULL) {
810*1031c584SApple OSS Distributions #ifdef DEBUG
811*1031c584SApple OSS Distributions 		fprintf(stderr, "Setting new GS base: %p\n", (void *)new_GSbase);
812*1031c584SApple OSS Distributions #endif
813*1031c584SApple OSS Distributions 		new_GSbase->this_tsd_base = new_GSbase;
814*1031c584SApple OSS Distributions 		new_GSbase->orig_tsd_base = get_gsbase();
815*1031c584SApple OSS Distributions 		_thread_set_tsd_base((uintptr_t)new_GSbase);
816*1031c584SApple OSS Distributions 	} else {
817*1031c584SApple OSS Distributions #ifndef STANDALONE
818*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("Failed to allocate a page for new GSbase");
819*1031c584SApple OSS Distributions #else
820*1031c584SApple OSS Distributions 		fprintf(stderr, "Failed to allocate a page for new GSbase");
821*1031c584SApple OSS Distributions 		abort();
822*1031c584SApple OSS Distributions #endif
823*1031c584SApple OSS Distributions 	}
824*1031c584SApple OSS Distributions 
825*1031c584SApple OSS Distributions 	rv = thunkit(&input_desc, (void *)(uintptr_t)stackaddr, compat_arg,
826*1031c584SApple OSS Distributions 	    callback, thunk64_addr);
827*1031c584SApple OSS Distributions 
828*1031c584SApple OSS Distributions 	restore_gsbase(stackaddr);
829*1031c584SApple OSS Distributions 
830*1031c584SApple OSS Distributions 	free(new_GSbase);
831*1031c584SApple OSS Distributions 
832*1031c584SApple OSS Distributions 	return rv;
833*1031c584SApple OSS Distributions }
834*1031c584SApple OSS Distributions 
835*1031c584SApple OSS Distributions static uint64_t
get_cursp(void)836*1031c584SApple OSS Distributions get_cursp(void)
837*1031c584SApple OSS Distributions {
838*1031c584SApple OSS Distributions 	uint64_t curstk;
839*1031c584SApple OSS Distributions 	__asm__ __volatile__ ("movq %%rsp, %0" : "=r" (curstk) :: "memory");
840*1031c584SApple OSS Distributions 	return curstk;
841*1031c584SApple OSS Distributions }
842*1031c584SApple OSS Distributions 
843*1031c584SApple OSS Distributions static void
hello_from_32bit(void)844*1031c584SApple OSS Distributions hello_from_32bit(void)
845*1031c584SApple OSS Distributions {
846*1031c584SApple OSS Distributions 	uint64_t cur_tsd_base = (uint64_t)(uintptr_t)mytsd->this_tsd_base;
847*1031c584SApple OSS Distributions 	restore_gsbase(get_cursp());
848*1031c584SApple OSS Distributions 
849*1031c584SApple OSS Distributions 	printf("Hello on behalf of 32-bit compatibility mode!\n");
850*1031c584SApple OSS Distributions 
851*1031c584SApple OSS Distributions 	_thread_set_tsd_base(cur_tsd_base);
852*1031c584SApple OSS Distributions }
853*1031c584SApple OSS Distributions 
854*1031c584SApple OSS Distributions /*
855*1031c584SApple OSS Distributions  * Thread for executing 32-bit code
856*1031c584SApple OSS Distributions  */
857*1031c584SApple OSS Distributions static void *
thread_32bit(void * arg)858*1031c584SApple OSS Distributions thread_32bit(void *arg)
859*1031c584SApple OSS Distributions {
860*1031c584SApple OSS Distributions 	thread_arg_t *targp = (thread_arg_t *)arg;
861*1031c584SApple OSS Distributions 	uint64_t cthread_self = 0;
862*1031c584SApple OSS Distributions 
863*1031c584SApple OSS Distributions 	/* Save the GSbase for context switch back to 64-bit mode */
864*1031c584SApple OSS Distributions 	cthread_self = get_gsbase();
865*1031c584SApple OSS Distributions 
866*1031c584SApple OSS Distributions 	/*
867*1031c584SApple OSS Distributions 	 * Associate GSbase with the compat-mode stack (which will be used for long mode
868*1031c584SApple OSS Distributions 	 * thunk calls as well.)
869*1031c584SApple OSS Distributions 	 */
870*1031c584SApple OSS Distributions 	(void)stack_range_to_GSbase(targp->compat_stackaddr, cthread_self);
871*1031c584SApple OSS Distributions 
872*1031c584SApple OSS Distributions #ifdef DEBUG
873*1031c584SApple OSS Distributions 	printf("[thread %p] tsd base => %p\n", (void *)pthread_self(), (void *)cthread_self);
874*1031c584SApple OSS Distributions #endif
875*1031c584SApple OSS Distributions 
876*1031c584SApple OSS Distributions 	pthread_mutex_lock(&targp->mutex);
877*1031c584SApple OSS Distributions 
878*1031c584SApple OSS Distributions 	do {
879*1031c584SApple OSS Distributions 		if (targp->done == FALSE) {
880*1031c584SApple OSS Distributions 			pthread_cond_wait(&targp->condvar, &targp->mutex);
881*1031c584SApple OSS Distributions 		}
882*1031c584SApple OSS Distributions 
883*1031c584SApple OSS Distributions 		/* Finally, execute the test */
884*1031c584SApple OSS Distributions 		if (call_compatmode(targp->compat_stackaddr, 0,
885*1031c584SApple OSS Distributions 		    (uint64_t)&hello_from_32bit) == 1) {
886*1031c584SApple OSS Distributions 			printf("32-bit code test passed\n");
887*1031c584SApple OSS Distributions 		} else {
888*1031c584SApple OSS Distributions 			printf("32-bit code test failed\n");
889*1031c584SApple OSS Distributions 		}
890*1031c584SApple OSS Distributions 	} while (targp->done == FALSE);
891*1031c584SApple OSS Distributions 
892*1031c584SApple OSS Distributions 	pthread_mutex_unlock(&targp->mutex);
893*1031c584SApple OSS Distributions 
894*1031c584SApple OSS Distributions 	return 0;
895*1031c584SApple OSS Distributions }
896*1031c584SApple OSS Distributions 
897*1031c584SApple OSS Distributions static void
join_32bit_thread(pthread_t * thridp,thread_arg_t * cmargp)898*1031c584SApple OSS Distributions join_32bit_thread(pthread_t *thridp, thread_arg_t *cmargp)
899*1031c584SApple OSS Distributions {
900*1031c584SApple OSS Distributions 	(void)pthread_mutex_lock(&cmargp->mutex);
901*1031c584SApple OSS Distributions 	cmargp->done = TRUE;
902*1031c584SApple OSS Distributions 	(void)pthread_cond_signal(&cmargp->condvar);
903*1031c584SApple OSS Distributions 	(void)pthread_mutex_unlock(&cmargp->mutex);
904*1031c584SApple OSS Distributions 	(void)pthread_join(*thridp, NULL);
905*1031c584SApple OSS Distributions 	*thridp = 0;
906*1031c584SApple OSS Distributions }
907*1031c584SApple OSS Distributions 
908*1031c584SApple OSS Distributions static int
create_worker_thread(thread_arg_t * cmargp,uint32_t stackaddr,pthread_t * cmthreadp)909*1031c584SApple OSS Distributions create_worker_thread(thread_arg_t *cmargp, uint32_t stackaddr, pthread_t *cmthreadp)
910*1031c584SApple OSS Distributions {
911*1031c584SApple OSS Distributions 	*cmargp = (thread_arg_t) { .mutex = PTHREAD_MUTEX_INITIALIZER,
912*1031c584SApple OSS Distributions 		                   .condvar = PTHREAD_COND_INITIALIZER,
913*1031c584SApple OSS Distributions 		                   .done = FALSE,
914*1031c584SApple OSS Distributions 		                   .compat_stackaddr = stackaddr };
915*1031c584SApple OSS Distributions 
916*1031c584SApple OSS Distributions 	return pthread_create(cmthreadp, NULL, thread_32bit, cmargp);
917*1031c584SApple OSS Distributions }
918*1031c584SApple OSS Distributions 
919*1031c584SApple OSS Distributions static void
ldt64_test_setup(pthread_t * cmthreadp,thread_arg_t * cmargp,boolean_t setldt_in_sighandler)920*1031c584SApple OSS Distributions ldt64_test_setup(pthread_t *cmthreadp, thread_arg_t *cmargp, boolean_t setldt_in_sighandler)
921*1031c584SApple OSS Distributions {
922*1031c584SApple OSS Distributions 	extern void thunk64(void);
923*1031c584SApple OSS Distributions 	extern void thunk64_movabs(void);
924*1031c584SApple OSS Distributions 	int cnt = 0, err;
925*1031c584SApple OSS Distributions 	void *addr;
926*1031c584SApple OSS Distributions 	uintptr_t code_addr;
927*1031c584SApple OSS Distributions 	uintptr_t thunk64_movabs_addr;
928*1031c584SApple OSS Distributions 
929*1031c584SApple OSS Distributions 	descs = malloc(sizeof(union ldt_entry) * 256);
930*1031c584SApple OSS Distributions 	if (descs == 0) {
931*1031c584SApple OSS Distributions #ifndef STANDALONE
932*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("Could not allocate descriptor storage");
933*1031c584SApple OSS Distributions #else
934*1031c584SApple OSS Distributions 		fprintf(stderr, "Could not allocate descriptor storage\n");
935*1031c584SApple OSS Distributions 		abort();
936*1031c584SApple OSS Distributions #endif
937*1031c584SApple OSS Distributions 	}
938*1031c584SApple OSS Distributions 
939*1031c584SApple OSS Distributions #ifdef DEBUG
940*1031c584SApple OSS Distributions 	printf("32-bit code is at %p\n", (void *)&code_32);
941*1031c584SApple OSS Distributions #endif
942*1031c584SApple OSS Distributions 
943*1031c584SApple OSS Distributions 	if ((err = map_lowmem_stack(&addr)) != 0) {
944*1031c584SApple OSS Distributions #ifndef STANDALONE
945*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("failed to mmap lowmem stack: %s", strerror(err));
946*1031c584SApple OSS Distributions #else
947*1031c584SApple OSS Distributions 		fprintf(stderr, "Failed to mmap lowmem stack: %s\n", strerror(err));
948*1031c584SApple OSS Distributions 		exit(1);
949*1031c584SApple OSS Distributions #endif
950*1031c584SApple OSS Distributions 	}
951*1031c584SApple OSS Distributions 
952*1031c584SApple OSS Distributions 	stackAddr = (uintptr_t)addr + FIXED_STACK_SIZE - 16;
953*1031c584SApple OSS Distributions #ifdef DEBUG
954*1031c584SApple OSS Distributions 	printf("lowstack addr = %p\n", (void *)stackAddr);
955*1031c584SApple OSS Distributions #endif
956*1031c584SApple OSS Distributions 
957*1031c584SApple OSS Distributions 	if ((err = map_32bit_trampoline(&thunkit)) != 0) {
958*1031c584SApple OSS Distributions #ifndef STANDALONE
959*1031c584SApple OSS Distributions 		T_LOG("Failed to map trampoline into lowmem: %s\n", strerror(err));
960*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("Failed to map trampoline into lowmem");
961*1031c584SApple OSS Distributions #else
962*1031c584SApple OSS Distributions 		fprintf(stderr, "Failed to map trampoline into lowmem: %s\n", strerror(err));
963*1031c584SApple OSS Distributions 		exit(1);
964*1031c584SApple OSS Distributions #endif
965*1031c584SApple OSS Distributions 	}
966*1031c584SApple OSS Distributions 
967*1031c584SApple OSS Distributions 	/*
968*1031c584SApple OSS Distributions 	 * Store long_mode_trampoline's address into the constant part of the movabs
969*1031c584SApple OSS Distributions 	 * instruction in thunk64
970*1031c584SApple OSS Distributions 	 */
971*1031c584SApple OSS Distributions 	thunk64_movabs_addr = (uintptr_t)thunkit + ((uintptr_t)thunk64_movabs - (uintptr_t)compat_mode_trampoline);
972*1031c584SApple OSS Distributions 	*((uint64_t *)(thunk64_movabs_addr + 2)) = (uint64_t)&long_mode_trampoline;
973*1031c584SApple OSS Distributions 
974*1031c584SApple OSS Distributions 	bzero(descs, sizeof(union ldt_entry) * 256);
975*1031c584SApple OSS Distributions 
976*1031c584SApple OSS Distributions 	if ((cnt = i386_get_ldt(0, descs, 1)) <= 0) {
977*1031c584SApple OSS Distributions #ifndef STANDALONE
978*1031c584SApple OSS Distributions 		T_LOG("i386_get_ldt unexpectedly returned %d (errno: %s)\n", cnt, strerror(errno));
979*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("i386_get_ldt failure");
980*1031c584SApple OSS Distributions #else
981*1031c584SApple OSS Distributions 		fprintf(stderr, "i386_get_ldt unexpectedly returned %d (errno: %s)\n", cnt, strerror(errno));
982*1031c584SApple OSS Distributions 		exit(1);
983*1031c584SApple OSS Distributions #endif
984*1031c584SApple OSS Distributions 	}
985*1031c584SApple OSS Distributions 
986*1031c584SApple OSS Distributions #ifdef DEBUG
987*1031c584SApple OSS Distributions 	printf("i386_get_ldt returned %d\n", cnt);
988*1031c584SApple OSS Distributions #endif
989*1031c584SApple OSS Distributions 
990*1031c584SApple OSS Distributions 	idx = (unsigned)cnt;      /* Put the desired descriptor in the first available slot */
991*1031c584SApple OSS Distributions 
992*1031c584SApple OSS Distributions 	/*
993*1031c584SApple OSS Distributions 	 * code_32's address for the purposes of this descriptor is the base mapped address of
994*1031c584SApple OSS Distributions 	 * the thunkit function + the offset of code_32 from compat_mode_trampoline.
995*1031c584SApple OSS Distributions 	 */
996*1031c584SApple OSS Distributions 	code_addr = (uintptr_t)thunkit + ((uintptr_t)code_32 - (uintptr_t)compat_mode_trampoline);
997*1031c584SApple OSS Distributions 	thunk64_addr = (uintptr_t)thunkit + ((uintptr_t)thunk64 - (uintptr_t)compat_mode_trampoline);
998*1031c584SApple OSS Distributions 
999*1031c584SApple OSS Distributions 	/* Initialize desired descriptor */
1000*1031c584SApple OSS Distributions 	descs[idx].code.limit00 = (unsigned short)(((code_addr >> 12) + 1) & 0xFFFF);
1001*1031c584SApple OSS Distributions 	descs[idx].code.limit16 = (unsigned char)((((code_addr >> 12) + 1) >> 16) & 0xF);
1002*1031c584SApple OSS Distributions 	descs[idx].code.base00 = (unsigned short)((code_addr) & 0xFFFF);
1003*1031c584SApple OSS Distributions 	descs[idx].code.base16 = (unsigned char)((code_addr >> 16) & 0xFF);
1004*1031c584SApple OSS Distributions 	descs[idx].code.base24 = (unsigned char)((code_addr >> 24) & 0xFF);
1005*1031c584SApple OSS Distributions 	descs[idx].code.type = DESC_CODE_READ;
1006*1031c584SApple OSS Distributions 	descs[idx].code.opsz = DESC_CODE_32B;
1007*1031c584SApple OSS Distributions 	descs[idx].code.granular = DESC_GRAN_PAGE;
1008*1031c584SApple OSS Distributions 	descs[idx].code.dpl = 3;
1009*1031c584SApple OSS Distributions 	descs[idx].code.present = 1;
1010*1031c584SApple OSS Distributions 
1011*1031c584SApple OSS Distributions 	if (setldt_in_sighandler == FALSE) {
1012*1031c584SApple OSS Distributions 		/* Set the LDT: */
1013*1031c584SApple OSS Distributions 		cnt = i386_set_ldt((int)idx, &descs[idx], 1);
1014*1031c584SApple OSS Distributions 		if (cnt != (int)idx) {
1015*1031c584SApple OSS Distributions #ifndef STANDALONE
1016*1031c584SApple OSS Distributions 			T_LOG("i386_set_ldt unexpectedly returned %d (errno: %s)\n", cnt, strerror(errno));
1017*1031c584SApple OSS Distributions 			T_ASSERT_FAIL("i386_set_ldt failure");
1018*1031c584SApple OSS Distributions #else
1019*1031c584SApple OSS Distributions 			fprintf(stderr, "i386_set_ldt unexpectedly returned %d (errno: %s)\n", cnt, strerror(errno));
1020*1031c584SApple OSS Distributions 			exit(1);
1021*1031c584SApple OSS Distributions #endif
1022*1031c584SApple OSS Distributions 		}
1023*1031c584SApple OSS Distributions #ifdef DEBUG
1024*1031c584SApple OSS Distributions 		printf("i386_set_ldt returned %d\n", cnt);
1025*1031c584SApple OSS Distributions #endif
1026*1031c584SApple OSS Distributions 	} else {
1027*1031c584SApple OSS Distributions 		__asm__ __volatile__ ("ud2" ::: "memory");
1028*1031c584SApple OSS Distributions 	}
1029*1031c584SApple OSS Distributions 
1030*1031c584SApple OSS Distributions 
1031*1031c584SApple OSS Distributions 	/* Read back the LDT to ensure it was set properly */
1032*1031c584SApple OSS Distributions 	if ((cnt = i386_get_ldt(0, descs, (int)idx)) > 0) {
1033*1031c584SApple OSS Distributions #ifdef DEBUG
1034*1031c584SApple OSS Distributions 		for (int i = 0; i < cnt; i++) {
1035*1031c584SApple OSS Distributions 			dump_desc(&descs[i]);
1036*1031c584SApple OSS Distributions 		}
1037*1031c584SApple OSS Distributions #endif
1038*1031c584SApple OSS Distributions 	} else {
1039*1031c584SApple OSS Distributions #ifndef STANDALONE
1040*1031c584SApple OSS Distributions 		T_LOG("i386_get_ldt unexpectedly returned %d (errno: %s)\n", cnt, strerror(errno));
1041*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("i386_get_ldt failure");
1042*1031c584SApple OSS Distributions #else
1043*1031c584SApple OSS Distributions 		fprintf(stderr, "i386_get_ldt unexpectedly returned %d (errno: %s)\n", cnt, strerror(errno));
1044*1031c584SApple OSS Distributions 		exit(1);
1045*1031c584SApple OSS Distributions #endif
1046*1031c584SApple OSS Distributions 	}
1047*1031c584SApple OSS Distributions 
1048*1031c584SApple OSS Distributions 	free(descs);
1049*1031c584SApple OSS Distributions 
1050*1031c584SApple OSS Distributions 	if ((err = create_worker_thread(cmargp, (uint32_t)stackAddr, cmthreadp)) != 0) {
1051*1031c584SApple OSS Distributions #ifdef DEBUG
1052*1031c584SApple OSS Distributions 		fprintf(stderr, "Fatal: Could not create thread: %s\n", strerror(err));
1053*1031c584SApple OSS Distributions #endif
1054*1031c584SApple OSS Distributions #ifndef STANDALONE
1055*1031c584SApple OSS Distributions 		T_LOG("Fatal: Could not create thread: %s\n", strerror(err));
1056*1031c584SApple OSS Distributions 		T_ASSERT_FAIL("Thread creation failure");
1057*1031c584SApple OSS Distributions #else
1058*1031c584SApple OSS Distributions 		exit(1);
1059*1031c584SApple OSS Distributions #endif
1060*1031c584SApple OSS Distributions 	}
1061*1031c584SApple OSS Distributions }
1062*1031c584SApple OSS Distributions 
1063*1031c584SApple OSS Distributions #ifdef STANDALONE
1064*1031c584SApple OSS Distributions static void
test_ldt64_with_bsdsig(void)1065*1031c584SApple OSS Distributions test_ldt64_with_bsdsig(void)
1066*1031c584SApple OSS Distributions #else
1067*1031c584SApple OSS Distributions /*
1068*1031c584SApple OSS Distributions  * Main test declarations
1069*1031c584SApple OSS Distributions  */
1070*1031c584SApple OSS Distributions T_DECL(ldt64_with_bsd_sighandling,
1071*1031c584SApple OSS Distributions     "Ensures that a 64-bit process can create LDT entries and can execute code in "
1072*1031c584SApple OSS Distributions     "compatibility mode with BSD signal handling",
1073*1031c584SApple OSS Distributions     T_META_TIMEOUT(NORMAL_RUN_TIME + TIMEOUT_OVERHEAD))
1074*1031c584SApple OSS Distributions #endif
1075*1031c584SApple OSS Distributions {
1076*1031c584SApple OSS Distributions 	pthread_t cmthread;
1077*1031c584SApple OSS Distributions 	thread_arg_t cmarg;
1078*1031c584SApple OSS Distributions 
1079*1031c584SApple OSS Distributions 	int translated = 0;
1080*1031c584SApple OSS Distributions 	size_t translated_size = sizeof(int);
1081*1031c584SApple OSS Distributions 
1082*1031c584SApple OSS Distributions 	sysctlbyname("sysctl.proc_translated", &translated, &translated_size, NULL, 0);
1083*1031c584SApple OSS Distributions 
1084*1031c584SApple OSS Distributions 	if (translated) {
1085*1031c584SApple OSS Distributions 		T_SKIP("Skipping this test because it is translated");
1086*1031c584SApple OSS Distributions 	}
1087*1031c584SApple OSS Distributions 
1088*1031c584SApple OSS Distributions 	setup_signal_handling();
1089*1031c584SApple OSS Distributions 
1090*1031c584SApple OSS Distributions #ifndef STANDALONE
1091*1031c584SApple OSS Distributions 	T_SETUPBEGIN;
1092*1031c584SApple OSS Distributions #endif
1093*1031c584SApple OSS Distributions 	ENV_set_ldt_in_sighandler = (getenv("LDT_SET_IN_SIGHANDLER") != NULL) ? TRUE : FALSE;
1094*1031c584SApple OSS Distributions 	ldt64_test_setup(&cmthread, &cmarg, ENV_set_ldt_in_sighandler);
1095*1031c584SApple OSS Distributions #ifndef STANDALONE
1096*1031c584SApple OSS Distributions 	T_SETUPEND;
1097*1031c584SApple OSS Distributions #endif
1098*1031c584SApple OSS Distributions 
1099*1031c584SApple OSS Distributions 	join_32bit_thread(&cmthread, &cmarg);
1100*1031c584SApple OSS Distributions 
1101*1031c584SApple OSS Distributions 	teardown_signal_handling();
1102*1031c584SApple OSS Distributions 
1103*1031c584SApple OSS Distributions #ifndef STANDALONE
1104*1031c584SApple OSS Distributions 	T_PASS("Successfully completed ldt64 test with BSD signal handling");
1105*1031c584SApple OSS Distributions #else
1106*1031c584SApple OSS Distributions 	fprintf(stderr, "PASSED: ldt64_with_bsd_signal_handling\n");
1107*1031c584SApple OSS Distributions #endif
1108*1031c584SApple OSS Distributions }
1109*1031c584SApple OSS Distributions 
1110*1031c584SApple OSS Distributions #ifdef STANDALONE
1111*1031c584SApple OSS Distributions static void
test_ldt64_with_machexc(void)1112*1031c584SApple OSS Distributions test_ldt64_with_machexc(void)
1113*1031c584SApple OSS Distributions #else
1114*1031c584SApple OSS Distributions T_DECL(ldt64_with_mach_exception_handling,
1115*1031c584SApple OSS Distributions     "Ensures that a 64-bit process can create LDT entries and can execute code in "
1116*1031c584SApple OSS Distributions     "compatibility mode with Mach exception handling",
1117*1031c584SApple OSS Distributions     T_META_TIMEOUT(NORMAL_RUN_TIME + TIMEOUT_OVERHEAD))
1118*1031c584SApple OSS Distributions #endif
1119*1031c584SApple OSS Distributions {
1120*1031c584SApple OSS Distributions 	pthread_t cmthread;
1121*1031c584SApple OSS Distributions 	thread_arg_t cmarg;
1122*1031c584SApple OSS Distributions 
1123*1031c584SApple OSS Distributions 	int translated = 0;
1124*1031c584SApple OSS Distributions 	size_t translated_size = sizeof(int);
1125*1031c584SApple OSS Distributions 
1126*1031c584SApple OSS Distributions 	sysctlbyname("sysctl.proc_translated", &translated, &translated_size, NULL, 0);
1127*1031c584SApple OSS Distributions 
1128*1031c584SApple OSS Distributions 	if (translated) {
1129*1031c584SApple OSS Distributions 		T_SKIP("Skipping this test because it is translated");
1130*1031c584SApple OSS Distributions 	}
1131*1031c584SApple OSS Distributions 
1132*1031c584SApple OSS Distributions #ifndef STANDALONE
1133*1031c584SApple OSS Distributions 	T_SETUPBEGIN;
1134*1031c584SApple OSS Distributions #endif
1135*1031c584SApple OSS Distributions 	ldt64_test_setup(&cmthread, &cmarg, FALSE);
1136*1031c584SApple OSS Distributions #ifndef STANDALONE
1137*1031c584SApple OSS Distributions 	T_SETUPEND;
1138*1031c584SApple OSS Distributions #endif
1139*1031c584SApple OSS Distributions 
1140*1031c584SApple OSS Distributions 	/* Now repeat with Mach exception handling */
1141*1031c584SApple OSS Distributions 	init_task_exception_server();
1142*1031c584SApple OSS Distributions 
1143*1031c584SApple OSS Distributions 	join_32bit_thread(&cmthread, &cmarg);
1144*1031c584SApple OSS Distributions 
1145*1031c584SApple OSS Distributions #ifndef STANDALONE
1146*1031c584SApple OSS Distributions 	T_PASS("Successfully completed ldt64 test with mach exception handling");
1147*1031c584SApple OSS Distributions #else
1148*1031c584SApple OSS Distributions 	fprintf(stderr, "PASSED: ldt64_with_mach_exception_handling\n");
1149*1031c584SApple OSS Distributions #endif
1150*1031c584SApple OSS Distributions }
1151*1031c584SApple OSS Distributions 
1152*1031c584SApple OSS Distributions #ifdef STANDALONE
1153*1031c584SApple OSS Distributions int
main(int __unused argc,char ** __unused argv)1154*1031c584SApple OSS Distributions main(int __unused argc, char ** __unused argv)
1155*1031c584SApple OSS Distributions {
1156*1031c584SApple OSS Distributions 	test_ldt64_with_bsdsig();
1157*1031c584SApple OSS Distributions 	test_ldt64_with_machexc();
1158*1031c584SApple OSS Distributions }
1159*1031c584SApple OSS Distributions #endif
1160