2 * the Win32 incarnation of OS-dependent routines. See also
3 * $(sbcl_arch)-win32-os.c
5 * This file (along with os.h) exports an OS-independent interface to
6 * the operating system VM facilities. Surprise surprise, this
7 * interface looks a lot like the Mach interface (but simpler in some
8 * places). For some operating systems, a subset of these functions
9 * will have to be emulated.
13 * This software is part of the SBCL system. See the README file for
16 * This software is derived from the CMU CL system, which was
17 * written at Carnegie Mellon University and released into the
18 * public domain. The software is in the public domain and is
19 * provided with absolutely no warranty. See the COPYING and CREDITS
20 * files for more information.
24 * This file was copied from the Linux version of the same, and
25 * likely still has some linuxisms in it have haven't been elimiated
30 #include <sys/param.h>
39 #include "interrupt.h"
44 #include "genesis/primitive-objects.h"
46 #include <sys/types.h>
57 size_t os_vm_page_size;
61 #include "gencgc-internal.h"
64 int linux_sparc_siginfo_bug = 0;
65 int linux_supports_futex=0;
68 /* The exception handling function looks like this: */
69 EXCEPTION_DISPOSITION handle_exception(EXCEPTION_RECORD *,
70 struct lisp_exception_frame *,
76 static void *get_seh_frame(void)
79 asm volatile ("movl %%fs:0,%0": "=r" (retval));
83 static void set_seh_frame(void *frame)
85 asm volatile ("movl %0,%%fs:0": : "r" (frame));
88 static struct lisp_exception_frame *find_our_seh_frame(void)
90 struct lisp_exception_frame *frame = get_seh_frame();
92 while (frame->handler != handle_exception)
93 frame = frame->next_frame;
99 inline static void *get_stack_frame(void)
102 asm volatile ("movl %%ebp,%0": "=r" (retval));
107 void os_init(char *argv[], char *envp[])
109 SYSTEM_INFO system_info;
111 GetSystemInfo(&system_info);
112 os_vm_page_size = system_info.dwPageSize;
114 base_seh_frame = get_seh_frame();
119 * So we have three fun scenarios here.
121 * First, we could be being called to reserve the memory areas
122 * during initialization (prior to loading the core file).
124 * Second, we could be being called by the GC to commit a page
125 * that has just been decommitted (for easy zero-fill).
127 * Third, we could be being called by create_thread_struct()
128 * in order to create the sundry and various stacks.
130 * The third case is easy to pick out because it passes an
133 * The second case is easy to pick out because it will be for
134 * a range of memory that is MEM_RESERVE rather than MEM_FREE.
136 * The second case is also an easy implement, because we leave
137 * the memory as reserved (since we do lazy commits).
141 os_validate(os_vm_address_t addr, os_vm_size_t len)
143 MEMORY_BASIC_INFORMATION mem_info;
146 /* the simple case first */
147 os_vm_address_t real_addr;
148 if (!(real_addr = VirtualAlloc(addr, len, MEM_COMMIT, PAGE_EXECUTE_READWRITE))) {
149 fprintf(stderr, "VirtualAlloc: 0x%lx.\n", GetLastError());
156 if (!VirtualQuery(addr, &mem_info, sizeof mem_info)) {
157 fprintf(stderr, "VirtualQuery: 0x%lx.\n", GetLastError());
161 if ((mem_info.State == MEM_RESERVE) && (mem_info.RegionSize >=len)) return addr;
163 if (mem_info.State == MEM_RESERVE) {
164 fprintf(stderr, "validation of reserved space too short.\n");
168 if (!VirtualAlloc(addr, len, (mem_info.State == MEM_RESERVE)? MEM_COMMIT: MEM_RESERVE, PAGE_EXECUTE_READWRITE)) {
169 fprintf(stderr, "VirtualAlloc: 0x%lx.\n", GetLastError());
177 * For os_invalidate(), we merely decommit the memory rather than
178 * freeing the address space. This loses when freeing per-thread
179 * data and related memory since it leaks address space. It's not
180 * too lossy, however, since the two scenarios I'm aware of are
181 * fd-stream buffers, which are pooled rather than torched, and
182 * thread information, which I hope to pool (since windows creates
183 * threads at its own whim, and we probably want to be able to
184 * have them callback without funky magic on the part of the user,
185 * and full-on thread allocation is fairly heavyweight). Someone
186 * will probably shoot me down on this with some pithy comment on
187 * the use of (setf symbol-value) on a special variable. I'm happy
192 os_invalidate(os_vm_address_t addr, os_vm_size_t len)
194 if (!VirtualFree(addr, len, MEM_DECOMMIT)) {
195 fprintf(stderr, "VirtualFree: 0x%lx.\n", GetLastError());
200 * os_map() is called to map a chunk of the core file into memory.
202 * Unfortunately, Windows semantics completely screws this up, so
203 * we just add backing store from the swapfile to where the chunk
204 * goes and read it up like a normal file. We could consider using
205 * a lazy read (demand page) setup, but that would mean keeping an
206 * open file pointer for the core indefinately (and be one more
207 * thing to maintain).
211 os_map(int fd, int offset, os_vm_address_t addr, os_vm_size_t len)
216 fprintf(stderr, "os_map: %d, 0x%x, %p, 0x%x.\n", fd, offset, addr, len);
220 if (!VirtualAlloc(addr, len, MEM_COMMIT, PAGE_EXECUTE_READWRITE)) {
221 fprintf(stderr, "VirtualAlloc: 0x%lx.\n", GetLastError());
222 lose("os_map: VirtualAlloc failure");
225 if (lseek(fd, offset, SEEK_SET) == -1) {
226 lose("os_map: Seek failure.");
229 count = read(fd, addr, len);
231 fprintf(stderr, "expected 0x%x, read 0x%x.\n", len, count);
232 lose("os_map: Failed to read enough bytes.");
238 static DWORD os_protect_modes[8] = {
245 PAGE_EXECUTE_READWRITE,
246 PAGE_EXECUTE_READWRITE,
250 os_protect(os_vm_address_t address, os_vm_size_t length, os_vm_prot_t prot)
254 if (!VirtualProtect(address, length, os_protect_modes[prot], &old_prot)) {
255 fprintf(stderr, "VirtualProtect failed, code 0x%lx.\n", GetLastError());
260 /* FIXME: Now that FOO_END, rather than FOO_SIZE, is the fundamental
261 * description of a space, we could probably punt this and just do
262 * (FOO_START <= x && x < FOO_END) everywhere it's called. */
264 in_range_p(os_vm_address_t a, lispobj sbeg, size_t slen)
266 char* beg = (char*)((long)sbeg);
267 char* end = (char*)((long)sbeg) + slen;
268 char* adr = (char*)a;
269 return (adr >= beg && adr < end);
273 is_valid_lisp_addr(os_vm_address_t addr)
276 if(in_range_p(addr, READ_ONLY_SPACE_START, READ_ONLY_SPACE_SIZE) ||
277 in_range_p(addr, STATIC_SPACE_START , STATIC_SPACE_SIZE) ||
278 in_range_p(addr, DYNAMIC_SPACE_START , DYNAMIC_SPACE_SIZE))
280 for_each_thread(th) {
281 if(((os_vm_address_t)th->control_stack_start <= addr) && (addr < (os_vm_address_t)th->control_stack_end))
283 if(in_range_p(addr, (unsigned long)th->binding_stack_start, BINDING_STACK_SIZE))
290 * any OS-dependent special low-level handling for signals
293 /* A tiny bit of interrupt.c state we want our paws on. */
294 extern boolean internal_errors_enabled;
297 * FIXME: There is a potential problem with foreign code here.
298 * If we are running foreign code instead of lisp code and an
299 * exception occurs we arrange a call into Lisp. If the
300 * foreign code has installed an exception handler, we run the
301 * very great risk of throwing through their exception handler
302 * without asking it to unwind. This is more a problem with
303 * non-sigtrap (EXCEPTION_BREAKPOINT) exceptions, as they could
304 * reasonably be expected to happen in foreign code. We need to
305 * figure out the exception handler unwind semantics and adhere
306 * to them (probably by abusing the Lisp unwind-protect system)
307 * if we are going to handle this scenario correctly.
309 * A good explanation of the exception handling semantics is
310 * http://win32assembly.online.fr/Exceptionhandling.html .
311 * We will also need to handle this ourselves when foreign
312 * code tries to unwind -us-.
314 * When unwinding through foreign code we should unwind the
315 * Lisp stack to the entry from foreign code, then unwind the
316 * foreign code stack to the entry from Lisp, then resume
320 EXCEPTION_DISPOSITION sigtrap_emulator(CONTEXT *context,
321 struct lisp_exception_frame *exception_frame)
323 if (*((char *)context->Eip + 1) == trap_ContextRestore) {
325 * This is the cleanup for what is immediately below, and
326 * for the generic exception handling further below. We
327 * have to memcpy() the original context (emulated sigtrap
328 * or normal exception) over our context and resume it.
330 memcpy(context, &exception_frame->context, sizeof(CONTEXT));
331 return ExceptionContinueExecution;
333 } else { /* Not a trap_ContextRestore, must be a sigtrap. */
334 /* sigtrap_trampoline is defined in x86-assem.S. */
335 extern void sigtrap_trampoline;
338 * Unlike some other operating systems, Win32 leaves EIP
339 * pointing to the breakpoint instruction.
344 * We're not on an alternate stack like we would be in some
345 * other operating systems, and we don't want to risk leaking
346 * any important resources if we throw out of the sigtrap
347 * handler, so we need to copy off our context to a "safe"
348 * place and then monkey with the return EIP to point to a
349 * trampoline which calls another function which copies the
350 * context out to a really-safe place and then calls the real
351 * sigtrap handler. When the real sigtrap handler returns, the
352 * trampoline then contains another breakpoint with a code of
353 * trap_ContextRestore (see above). Essentially the same
354 * mechanism is used by the generic exception path. There is
355 * a small window of opportunity between us copying the
356 * context to the "safe" place and the sigtrap wrapper copying
357 * it to the really-safe place (allocated in its stack frame)
358 * during which the context can be smashed. The only scenario
359 * I can come up with for this, however, involves a stack
360 * overflow occuring at just the wrong time (which makes one
361 * wonder how stack overflow exceptions even happen, given
362 * that we don't switch stacks for exception processing...)
364 memcpy(&exception_frame->context, context, sizeof(CONTEXT));
365 context->Eax = context->Eip;
366 context->Eip = (unsigned long)&sigtrap_trampoline;
369 return ExceptionContinueExecution;
373 void sigtrap_wrapper(void)
376 * This is the wrapper around the sigtrap handler called from
377 * the trampoline returned to from the function above.
379 * There actually is a point to some of the commented-out code
380 * in this function, although it really belongs to the callback
381 * wrappers. Once it is installed there, it can probably be
385 extern void sigtrap_handler(int signal, siginfo_t *info, void *context);
387 /* volatile struct { */
388 /* void *handler[2]; */
392 struct lisp_exception_frame *frame = find_our_seh_frame();
394 /* wos_install_interrupt_handlers(handler); */
395 /* handler.handler[0] = get_seh_frame(); */
396 /* handler.handler[1] = &handle_exception; */
397 /* set_seh_frame(&handler); */
399 memcpy(&context, &frame->context, sizeof(CONTEXT));
400 sigtrap_handler(0, NULL, &context);
401 memcpy(&frame->context, &context, sizeof(CONTEXT));
403 /* set_seh_frame(handler.handler[0]); */
406 EXCEPTION_DISPOSITION handle_exception(EXCEPTION_RECORD *exception_record,
407 struct lisp_exception_frame *exception_frame,
409 void *dc) /* FIXME: What's dc again? */
412 /* For EXCEPTION_ACCESS_VIOLATION only. */
413 void *fault_address = (void *)exception_record->ExceptionInformation[1];
415 if (exception_record->ExceptionCode == EXCEPTION_BREAKPOINT) {
416 /* Pick off sigtrap case first. */
417 return sigtrap_emulator(context, exception_frame);
419 } else if (exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION &&
420 (is_valid_lisp_addr(fault_address) ||
421 /* the linkage table does not contain valid lisp
422 * objects, but is also committed on-demand here
424 in_range_p(fault_address, LINKAGE_TABLE_SPACE_START,
425 LINKAGE_TABLE_SPACE_END))) {
426 /* Pick off GC-related memory fault next. */
427 MEMORY_BASIC_INFORMATION mem_info;
429 if (!VirtualQuery(fault_address, &mem_info, sizeof mem_info)) {
430 fprintf(stderr, "VirtualQuery: 0x%lx.\n", GetLastError());
431 lose("handle_exception: VirtualQuery failure");
434 if (mem_info.State == MEM_RESERVE) {
435 /* First use new page, lets get some memory for it. */
436 if (!VirtualAlloc(mem_info.BaseAddress, os_vm_page_size,
437 MEM_COMMIT, PAGE_EXECUTE_READWRITE)) {
438 fprintf(stderr, "VirtualAlloc: 0x%lx.\n", GetLastError());
439 lose("handle_exception: VirtualAlloc failure");
443 * Now, if the page is supposedly write-protected and this
444 * is a write, tell the gc that it's been hit.
446 * FIXME: Are we supposed to fall-through to the Lisp
447 * exception handler if the gc doesn't take the wp violation?
449 if (exception_record->ExceptionInformation[0]) {
450 int index = find_page_index(fault_address);
451 if ((index != -1) && (page_table[index].write_protected)) {
452 gencgc_handle_wp_violation(fault_address);
455 return ExceptionContinueExecution;
458 } else if (gencgc_handle_wp_violation(fault_address)) {
459 /* gc accepts the wp violation, so resume where we left off. */
460 return ExceptionContinueExecution;
463 /* All else failed, drop through to the lisp-side exception handler. */
467 * If we fall through to here then we need to either forward
468 * the exception to the lisp-side exception handler if it's
469 * set up, or drop to LDB.
472 if (internal_errors_enabled) {
473 /* exception_trampoline is defined in x86-assem.S. */
474 extern void exception_trampoline;
477 * We're making the somewhat arbitrary decision that
478 * having internal errors enabled means that lisp has
479 * sufficient marbles to be able to handle exceptions.
481 * Exceptions aren't supposed to happen during cold
482 * init or reinit anyway.
486 * We use the same mechanism as the sigtrap emulator above
487 * with just a couple changes. We obviously use a different
488 * trampoline and wrapper function, we kill out any live
489 * floating point exceptions, and we save off the exception
490 * record as well as the context.
493 /* Save off context and exception information */
494 memcpy(&exception_frame->context, context, sizeof(CONTEXT));
495 memcpy(&exception_frame->exception, exception_record, sizeof(EXCEPTION_RECORD));
497 /* Set up to activate trampoline when we return */
498 context->Eax = context->Eip;
499 context->Eip = (unsigned long)&exception_trampoline;
501 /* Make sure a floating-point trap doesn't kill us */
502 context->FloatSave.StatusWord &= ~0x3f;
505 return ExceptionContinueExecution;
508 fprintf(stderr, "Exception Code: 0x%lx.\n", exception_record->ExceptionCode);
509 fprintf(stderr, "Faulting IP: 0x%lx.\n", (DWORD)exception_record->ExceptionAddress);
510 if (exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
511 MEMORY_BASIC_INFORMATION mem_info;
513 if (VirtualQuery(fault_address, &mem_info, sizeof mem_info)) {
514 fprintf(stderr, "page status: 0x%lx.\n", mem_info.State);
517 fprintf(stderr, "Was writing: %ld, where: 0x%lx.\n",
518 exception_record->ExceptionInformation[0],
519 (DWORD)fault_address);
524 fake_foreign_function_call(context);
525 lose("fake_foreign_function_call fell through");
527 /* FIXME: WTF? How are we supposed to end up here? */
528 return ExceptionContinueSearch;
531 void handle_win32_exception_wrapper(void)
533 struct lisp_exception_frame *frame = find_our_seh_frame();
535 EXCEPTION_RECORD exception_record;
537 lispobj exception_record_sap;
539 memcpy(&context, &frame->context, sizeof(CONTEXT));
540 memcpy(&exception_record, &frame->exception, sizeof(EXCEPTION_RECORD));
542 fake_foreign_function_call(&context);
544 /* Allocate the SAP objects while the "interrupts" are still
546 context_sap = alloc_sap(&context);
547 exception_record_sap = alloc_sap(&exception_record);
549 funcall2(SymbolFunction(HANDLE_WIN32_EXCEPTION), context_sap,
550 exception_record_sap);
552 undo_fake_foreign_function_call(&context);
554 memcpy(&frame->context, &context, sizeof(CONTEXT));
558 wos_install_interrupt_handlers(struct lisp_exception_frame *handler)
560 handler->next_frame = get_seh_frame();
561 handler->handler = &handle_exception;
562 set_seh_frame(handler);
565 void bcopy(const void *src, void *dest, size_t n)
567 MoveMemory(dest, src, n);
571 * The stubs below are replacements for the windows versions,
572 * which can -fail- when used in our memory spaces because they
573 * validate the memory spaces they are passed in a way that
574 * denies our exception handler a chance to run.
577 void *memmove(void *dest, const void *src, size_t n)
581 for (i = 0; i < n; i++) *(((char *)dest)+i) = *(((char *)src)+i);
583 while (n--) *(((char *)dest)+n) = *(((char *)src)+n);
588 void *memcpy(void *dest, const void *src, size_t n)
590 while (n--) *(((char *)dest)+n) = *(((char *)src)+n);
594 char *dirname(char *path)
596 static char buf[PATH_MAX + 1];
597 size_t pathlen = strlen(path);
600 if (pathlen >= sizeof(buf)) {
601 lose("Pathname too long in dirname.\n");
606 for (i = pathlen; i >= 0; --i) {
607 if (buf[i] == '/' || buf[i] == '\\') {
616 /* This is a manually-maintained version of ldso_stubs.S. */
628 #ifndef LISP_FEATURE_SB_UNICODE
633 #ifndef LISP_FEATURE_SB_UNICODE
634 GetCurrentDirectoryA(0,0);
636 GetCurrentDirectoryW(0,0);
640 GetProcAddress(0, 0);
642 #ifndef LISP_FEATURE_SB_UNICODE
643 CreateDirectoryA(0,0);
645 CreateDirectoryW(0,0);
651 FormatMessageA(0, 0, 0, 0, 0, 0, 0);
652 #ifdef LISP_FEATURE_SB_UNICODE
653 FormatMessageW(0, 0, 0, 0, 0, 0, 0);
656 ReadFile(0, 0, 0, 0, 0);
657 WriteFile(0, 0, 0, 0, 0);
658 PeekNamedPipe(0, 0, 0, 0, 0, 0);
659 FlushConsoleInputBuffer(0);
660 PeekConsoleInput(0, 0, 0, 0);
662 #ifndef LISP_FEATURE_SB_UNICODE
663 SHGetFolderPathA(0, 0, 0, 0, 0);
665 SHGetFolderPathW(0, 0, 0, 0, 0);
670 #ifndef LISP_FEATURE_SB_UNICODE
671 GetEnvironmentVariableA(0, 0, 0);
673 GetEnvironmentVariableW(0, 0, 0);
676 GetConsoleOutputCP();
677 GetExitCodeProcess(0, 0);
679 GetProcessTimes(0, 0, 0, 0, 0);
680 #ifndef LISP_FEATURE_SB_UNICODE
681 SetEnvironmentVariableA(0, 0);
683 SetEnvironmentVariableW(0, 0);
685 #ifndef LISP_FEATURE_SB_UNICODE
690 #ifndef LISP_FEATURE_SB_UNICODE
691 GetComputerNameA(0, 0);
693 GetComputerNameW(0, 0);
695 #ifndef LISP_FEATURE_SB_UNICODE
696 SetCurrentDirectoryA(0);
698 SetCurrentDirectoryW(0);
704 os_get_runtime_executable_path()
706 char path[MAX_PATH + 1];
707 DWORD bufsize = sizeof(path);
710 if ((size = GetModuleFileNameA(NULL, path, bufsize)) == 0)
712 else if (size == bufsize && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
715 return copied_string(path);