]> gitweb.factorcode.org Git - factor.git/blob - vm/os-windows.cpp
Support Link Time Optimization (off by default)
[factor.git] / vm / os-windows.cpp
1 #include "master.hpp"
2
3 namespace factor {
4
5 HMODULE hFactorDll;
6
7 bool set_memory_locked(cell base, cell size, bool locked) {
8   int prot = locked ? PAGE_NOACCESS : PAGE_READWRITE;
9   DWORD ignore;
10   int status = VirtualProtect((char*)base, size, prot, &ignore);
11   return status != 0;
12 }
13
14 void factor_vm::init_ffi() {
15   hFactorDll = GetModuleHandle(NULL);
16   if (!hFactorDll)
17     fatal_error("GetModuleHandle() failed", 0);
18 }
19
20 void factor_vm::ffi_dlopen(dll* dll) {
21   dll->handle = LoadLibraryEx((WCHAR*)alien_offset(dll->path), NULL, 0);
22 }
23
24 cell factor_vm::ffi_dlsym(dll* dll, symbol_char* symbol) {
25   return (cell)GetProcAddress(dll ? (HMODULE) dll->handle : hFactorDll,
26                               symbol);
27 }
28
29 cell factor_vm::ffi_dlsym_raw(dll* dll, symbol_char* symbol) {
30   return ffi_dlsym(dll, symbol);
31 }
32
33 void factor_vm::ffi_dlclose(dll* dll) {
34   FreeLibrary((HMODULE) dll->handle);
35   dll->handle = NULL;
36 }
37
38 BOOL factor_vm::windows_stat(vm_char* path) {
39   BY_HANDLE_FILE_INFORMATION bhfi;
40   HANDLE h = CreateFileW(path, FILE_READ_ATTRIBUTES, 0, NULL,
41                          OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
42
43   if (h == INVALID_HANDLE_VALUE) {
44     // FindFirstFile is the only call that can stat c:\pagefile.sys
45     WIN32_FIND_DATA st;
46     h = FindFirstFile(path, &st);
47     if (h == INVALID_HANDLE_VALUE)
48       return false;
49     FindClose(h);
50     return true;
51   }
52   BOOL ret = GetFileInformationByHandle(h, &bhfi);
53   CloseHandle(h);
54   return ret;
55 }
56
57 // You must free() this yourself.
58 const vm_char* factor_vm::default_image_path() {
59   vm_char full_path[MAX_UNICODE_PATH];
60   vm_char* ptr;
61   vm_char temp_path[MAX_UNICODE_PATH];
62
63   if (!GetModuleFileName(NULL, full_path, MAX_UNICODE_PATH))
64     fatal_error("GetModuleFileName() failed", 0);
65
66   if ((ptr = wcsrchr(full_path, '.')))
67     *ptr = 0;
68
69   wcsncpy(temp_path, full_path, MAX_UNICODE_PATH - 1);
70   size_t full_path_len = wcslen(full_path);
71   if (full_path_len < MAX_UNICODE_PATH - 1)
72     wcsncat(temp_path, L".image", MAX_UNICODE_PATH - full_path_len - 1);
73   temp_path[MAX_UNICODE_PATH - 1] = 0;
74
75   return safe_strdup(temp_path);
76 }
77
78 // You must free() this yourself.
79 const vm_char* factor_vm::vm_executable_path() {
80   vm_char full_path[MAX_UNICODE_PATH];
81   if (!GetModuleFileName(NULL, full_path, MAX_UNICODE_PATH))
82     fatal_error("GetModuleFileName() failed", 0);
83   return safe_strdup(full_path);
84 }
85
86 void factor_vm::primitive_existsp() {
87   vm_char* path = untag_check<byte_array>(ctx->pop())->data<vm_char>();
88   ctx->push(tag_boolean(windows_stat(path)));
89 }
90
91 segment::segment(cell size_, bool executable_p) {
92   size = size_;
93
94   char* mem;
95   cell alloc_size = getpagesize() * 2 + size;
96   if ((mem = (char*)VirtualAlloc(
97            NULL, alloc_size, MEM_COMMIT,
98            executable_p ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE)) ==
99       0) {
100     fatal_error("Out of memory in VirtualAlloc", alloc_size);
101   }
102
103   start = (cell)mem + getpagesize();
104   end = start + size;
105
106   set_border_locked(true);
107 }
108
109 segment::~segment() {
110   if (!VirtualFree((void*)(start - getpagesize()), 0, MEM_RELEASE))
111     fatal_error("Segment deallocation failed", 0);
112 }
113
114 long getpagesize() {
115   static long g_pagesize = 0;
116   if (!g_pagesize) {
117     SYSTEM_INFO system_info;
118     GetSystemInfo(&system_info);
119     g_pagesize = system_info.dwPageSize;
120   }
121   return g_pagesize;
122 }
123
124 bool move_file(const vm_char* path1, const vm_char* path2) {
125   // MoveFileEx returns FALSE on fail.
126   BOOL val = MoveFileEx((path1), (path2), MOVEFILE_REPLACE_EXISTING);
127   if (val == FALSE) {
128     // MoveFileEx doesn't set errno, which primitive_save_image()
129     // reads the error code from. Instead of converting from
130     // GetLastError() to errno values, we ust set it to the generic
131     // EIO value.
132     errno = EIO;
133   }
134   return val == TRUE;
135 }
136
137 void factor_vm::init_signals() {}
138
139 THREADHANDLE start_thread(void* (*start_routine)(void*), void* args) {
140   return (void*)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) start_routine,
141                              args, 0, 0);
142 }
143
144 uint64_t nano_count() {
145   static double scale_factor;
146
147   static uint32_t hi = 0;
148   static uint32_t lo = 0;
149
150   // Note: on older systems QueryPerformanceCounter may be unreliable
151   // until you add /usepmtimer to Boot.ini. I had an issue where two
152   // nano_count calls would show a difference of about 1 second,
153   // while actually about 80 seconds have passed. The /usepmtimer
154   // switch cured the issue on that PC (WinXP Pro SP3 32-bit).
155   // See also http://www.virtualdub.org/blog/pivot/entry.php?id=106
156   LARGE_INTEGER count;
157   BOOL ret = QueryPerformanceCounter(&count);
158   if (ret == 0)
159     fatal_error("QueryPerformanceCounter", 0);
160
161   if (scale_factor == 0.0) {
162     LARGE_INTEGER frequency;
163     BOOL ret = QueryPerformanceFrequency(&frequency);
164     if (ret == 0)
165       fatal_error("QueryPerformanceFrequency", 0);
166     scale_factor = (1000000000.0 / frequency.QuadPart);
167   }
168
169 #ifdef FACTOR_64
170   hi = count.HighPart;
171 #else
172   // On VirtualBox, QueryPerformanceCounter does not increment
173   // the high part every time the low part overflows.  Workaround.
174   if (lo > count.LowPart)
175     hi++;
176 #endif
177   lo = count.LowPart;
178
179   return (uint64_t)((((uint64_t)hi << 32) | (uint64_t)lo) * scale_factor);
180 }
181
182 void sleep_nanos(uint64_t nsec) { Sleep((DWORD)(nsec / 1000000)); }
183
184 #ifndef EXCEPTION_DISPOSITION
185 typedef enum _EXCEPTION_DISPOSITION {
186   ExceptionContinueExecution = 0,
187   ExceptionContinueSearch = 1,
188   ExceptionNestedException = 2,
189   ExceptionCollidedUnwind = 3
190 } EXCEPTION_DISPOSITION;
191 #endif
192
193 LONG factor_vm::exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c,
194                                   void* dispatch) {
195   (void)frame;
196   (void)dispatch;
197   switch (e->ExceptionCode) {
198     case EXCEPTION_ACCESS_VIOLATION:
199       set_memory_protection_error(e->ExceptionInformation[1], c->EIP);
200       dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
201                               (cell)factor::memory_signal_handler_impl);
202       break;
203
204     case STATUS_FLOAT_DENORMAL_OPERAND:
205     case STATUS_FLOAT_DIVIDE_BY_ZERO:
206     case STATUS_FLOAT_INEXACT_RESULT:
207     case STATUS_FLOAT_INVALID_OPERATION:
208     case STATUS_FLOAT_OVERFLOW:
209     case STATUS_FLOAT_STACK_CHECK:
210     case STATUS_FLOAT_UNDERFLOW:
211     case STATUS_FLOAT_MULTIPLE_FAULTS:
212     case STATUS_FLOAT_MULTIPLE_TRAPS:
213 #ifdef FACTOR_64
214       signal_fpu_status = fpu_status(MXCSR(c));
215 #else
216       signal_fpu_status = fpu_status(X87SW(c) | MXCSR(c));
217
218       // This seems to have no effect
219       X87SW(c) = 0;
220 #endif
221       MXCSR(c) &= 0xffffffc0;
222       dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
223                               (cell)factor::fp_signal_handler_impl);
224       break;
225     default:
226       signal_number = e->ExceptionCode;
227       dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
228                               (cell)factor::synchronous_signal_handler_impl);
229       break;
230   }
231   return ExceptionContinueExecution;
232 }
233
234 VM_C_API LONG exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c,
235                                 void* dispatch) {
236   factor_vm* vm = current_vm_p();
237   if (factor_vm::fatal_erroring_p || !vm)
238     return ExceptionContinueSearch;
239   return vm->exception_handler(e, frame, c, dispatch);
240 }
241
242 // On Unix SIGINT (ctrl-c) automatically interrupts blocking io system
243 // calls. It doesn't on Windows, so we need to manually send some
244 // cancellation requests to unblock the thread.
245 VOID CALLBACK dummy_cb(ULONG_PTR dwParam) { (void)dwParam; }
246
247 static void wake_up_thread(HANDLE thread) {
248   if (!CancelSynchronousIo(thread)) {
249     DWORD err = GetLastError();
250     // CancelSynchronousIo() didn't find anything to cancel, let's try
251     // with QueueUserAPC() instead.
252     if (err == ERROR_NOT_FOUND) {
253       if (!QueueUserAPC(&dummy_cb, thread, 0)) {
254         fatal_error("QueueUserAPC() failed", GetLastError());
255       }
256     } else {
257       fatal_error("CancelSynchronousIo() failed", err);
258     }
259   }
260 }
261
262 static BOOL WINAPI ctrl_handler(DWORD dwCtrlType) {
263   switch (dwCtrlType) {
264     case CTRL_C_EVENT: {
265       // The CtrlHandler runs in its own thread without stopping the main
266       // thread. Since in practice nobody uses the multi-VM stuff yet, we just
267       // grab the first VM we can get. This will not be a good idea when we
268       // actually support native threads.
269       FACTOR_ASSERT(thread_vms.size() == 1);
270       factor_vm* vm = thread_vms.begin()->second;
271       vm->enqueue_fep();
272
273       // Before leaving the ctrl_handler, try and wake up the main thread.
274       wake_up_thread(factor::boot_thread);
275       return TRUE;
276     }
277     default:
278       return FALSE;
279   }
280 }
281
282 void open_console() { handle_ctrl_c(); }
283
284 void ignore_ctrl_c() {
285   SetConsoleCtrlHandler(factor::ctrl_handler, FALSE);
286 }
287
288 void handle_ctrl_c() {
289   SetConsoleCtrlHandler(factor::ctrl_handler, TRUE);
290 }
291
292 const int ctrl_break_sleep = 10; /* msec */
293
294 static DWORD WINAPI ctrl_break_thread_proc(LPVOID parent_vm) {
295   bool ctrl_break_handled = false;
296   factor_vm* vm = static_cast<factor_vm*>(parent_vm);
297   while (vm->stop_on_ctrl_break) {
298     if (GetAsyncKeyState(VK_CANCEL) >= 0) { /* Ctrl-Break is released. */
299       ctrl_break_handled = false;  /* Wait for the next press. */
300     } else if (!ctrl_break_handled) {
301       /* Check if the VM thread has the same Id as the thread Id of the
302          currently active window. Note that thread Id is not a handle. */
303       DWORD fg_thd_id = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
304       if ((fg_thd_id == vm->thread_id) && !vm->fep_p) {
305         vm->enqueue_fep();
306         ctrl_break_handled = true;
307       }
308     }
309     Sleep(ctrl_break_sleep);
310   }
311   return 0;
312 }
313
314 void factor_vm::primitive_disable_ctrl_break() {
315   stop_on_ctrl_break = false;
316   if (ctrl_break_thread != NULL) {
317     DWORD wait_result = WaitForSingleObject(ctrl_break_thread,
318                                             2 * ctrl_break_sleep);
319     if (wait_result != WAIT_OBJECT_0)
320       TerminateThread(ctrl_break_thread, 0);
321     CloseHandle(ctrl_break_thread);
322     ctrl_break_thread = NULL;
323   }
324 }
325
326 void factor_vm::primitive_enable_ctrl_break() {
327   stop_on_ctrl_break = true;
328   if (ctrl_break_thread == NULL) {
329     DisableProcessWindowsGhosting();
330     ctrl_break_thread = CreateThread(NULL, 0, factor::ctrl_break_thread_proc,
331                                      static_cast<LPVOID>(this), 0, NULL);
332     SetThreadPriority(ctrl_break_thread, THREAD_PRIORITY_ABOVE_NORMAL);
333   }
334 }
335
336 void lock_console() {}
337
338 void unlock_console() {}
339
340 void close_console() {}
341
342 cell get_thread_pc(THREADHANDLE th) {
343   DWORD suscount = SuspendThread(th);
344   FACTOR_ASSERT(suscount == 0);
345
346   CONTEXT context;
347   memset((void*)&context, 0, sizeof(CONTEXT));
348   context.ContextFlags = CONTEXT_CONTROL;
349   BOOL context_ok = GetThreadContext(th, &context);
350   FACTOR_ASSERT(context_ok);
351
352   suscount = ResumeThread(th);
353   FACTOR_ASSERT(suscount == 1);
354
355   (void)suscount, (void)context_ok; // use all variables
356
357   return context.EIP;
358 }
359
360 void factor_vm::sampler_thread_loop() {
361   LARGE_INTEGER counter, new_counter, units_per_second;
362   DWORD ok;
363
364   ok = QueryPerformanceFrequency(&units_per_second);
365   FACTOR_ASSERT(ok);
366
367   ok = QueryPerformanceCounter(&counter);
368   FACTOR_ASSERT(ok);
369
370   counter.QuadPart *= samples_per_second;
371   while (atomic::load(&sampling_profiler_p)) {
372     SwitchToThread();
373     ok = QueryPerformanceCounter(&new_counter);
374     FACTOR_ASSERT(ok);
375     new_counter.QuadPart *= samples_per_second;
376     cell samples = 0;
377     while (new_counter.QuadPart - counter.QuadPart >
378            units_per_second.QuadPart) {
379       ++samples;
380       counter.QuadPart += units_per_second.QuadPart;
381     }
382     if (samples == 0)
383       continue;
384
385     cell pc = get_thread_pc(thread);
386     enqueue_samples(samples, pc, false);
387   }
388
389   (void)ok; // use all variables
390
391 }
392
393 static DWORD WINAPI sampler_thread_entry(LPVOID parent_vm) {
394   static_cast<factor_vm*>(parent_vm)->sampler_thread_loop();
395   return 0;
396 }
397
398 void factor_vm::start_sampling_profiler_timer() {
399   sampler_thread = CreateThread(NULL, 0, &sampler_thread_entry,
400                                 static_cast<LPVOID>(this), 0, NULL);
401 }
402
403 void factor_vm::end_sampling_profiler_timer() {
404   atomic::store(&sampling_profiler_p, false);
405   DWORD wait_result =
406       WaitForSingleObject(sampler_thread, 3000 * (DWORD) samples_per_second);
407   if (wait_result != WAIT_OBJECT_0)
408     TerminateThread(sampler_thread, 0);
409   CloseHandle(sampler_thread);
410   sampler_thread = NULL;
411 }
412
413 void abort() { ::abort(); }
414
415 }