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