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