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