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