]> gitweb.factorcode.org Git - factor.git/blob - vm/os-windows.cpp
VM: make allot_alien() and ffi_dlsym() use cell instead of void*
[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 cell factor_vm::ffi_dlsym(dll* dll, symbol_char* symbol) {
18   return (cell)GetProcAddress(dll ? (HMODULE) dll->handle : hFactorDll,
19                               symbol);
20 }
21
22 cell 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
99   if ((mem = (char*)VirtualAlloc(
100            NULL, getpagesize() * 2 + size, MEM_COMMIT,
101            executable_p ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE)) ==
102       0) {
103     out_of_memory("VirtualAlloc");
104   }
105
106   start = (cell)mem + getpagesize();
107   end = start + size;
108
109   set_border_locked(true);
110 }
111
112 void segment::set_border_locked(bool locked) {
113   int prot = locked ? PAGE_NOACCESS : PAGE_READWRITE;
114   int pagesize = getpagesize();
115   DWORD ignore;
116
117   cell lo = start - pagesize;
118   if (!VirtualProtect((char*)lo, pagesize, prot, &ignore)) {
119     fatal_error("Cannot (un)protect low guard page", lo);
120   }
121
122   cell hi = end;
123   if (!VirtualProtect((char*)hi, pagesize, prot, &ignore)) {
124     fatal_error("Cannot (un)protect high guard page", lo);
125   }
126 }
127
128 segment::~segment() {
129   SYSTEM_INFO si;
130   GetSystemInfo(&si);
131   if (!VirtualFree((void*)(start - si.dwPageSize), 0, MEM_RELEASE))
132     fatal_error("Segment deallocation failed", 0);
133 }
134
135 long getpagesize() {
136   static long g_pagesize = 0;
137   if (!g_pagesize) {
138     SYSTEM_INFO system_info;
139     GetSystemInfo(&system_info);
140     g_pagesize = system_info.dwPageSize;
141   }
142   return g_pagesize;
143 }
144
145 void code_heap::guard_safepoint() {
146   DWORD ignore;
147   if (!VirtualProtect(safepoint_page, getpagesize(), PAGE_NOACCESS, &ignore))
148     fatal_error("Cannot protect safepoint guard page", (cell)safepoint_page);
149 }
150
151 void code_heap::unguard_safepoint() {
152   DWORD ignore;
153   if (!VirtualProtect(safepoint_page, getpagesize(), PAGE_READWRITE, &ignore))
154     fatal_error("Cannot unprotect safepoint guard page", (cell)safepoint_page);
155 }
156
157 void factor_vm::move_file(const vm_char* path1, const vm_char* path2) {
158   if (MoveFileEx((path1), (path2), MOVEFILE_REPLACE_EXISTING) == false)
159     general_error(ERROR_IO, tag_fixnum(GetLastError()), false_object);
160 }
161
162 void factor_vm::init_signals() {}
163
164 THREADHANDLE start_thread(void* (*start_routine)(void*), void* args) {
165   return (void*)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) start_routine,
166                              args, 0, 0);
167 }
168
169 uint64_t nano_count() {
170   static double scale_factor;
171
172   static uint32_t hi = 0;
173   static uint32_t lo = 0;
174
175   LARGE_INTEGER count;
176   BOOL ret = QueryPerformanceCounter(&count);
177   if (ret == 0)
178     fatal_error("QueryPerformanceCounter", 0);
179
180   if (scale_factor == 0.0) {
181     LARGE_INTEGER frequency;
182     BOOL ret = QueryPerformanceFrequency(&frequency);
183     if (ret == 0)
184       fatal_error("QueryPerformanceFrequency", 0);
185     scale_factor = (1000000000.0 / frequency.QuadPart);
186   }
187
188 #ifdef FACTOR_64
189   hi = count.HighPart;
190 #else
191   /* On VirtualBox, QueryPerformanceCounter does not increment
192         the high part every time the low part overflows.  Workaround. */
193   if (lo > count.LowPart)
194     hi++;
195 #endif
196   lo = count.LowPart;
197
198   return (uint64_t)((((uint64_t)hi << 32) | (uint64_t)lo) * scale_factor);
199 }
200
201 void sleep_nanos(uint64_t nsec) { Sleep((DWORD)(nsec / 1000000)); }
202
203 typedef enum _EXCEPTION_DISPOSITION {
204   ExceptionContinueExecution = 0,
205   ExceptionContinueSearch = 1,
206   ExceptionNestedException = 2,
207   ExceptionCollidedUnwind = 3
208 } EXCEPTION_DISPOSITION;
209
210 LONG factor_vm::exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c,
211                                   void* dispatch) {
212   switch (e->ExceptionCode) {
213     case EXCEPTION_ACCESS_VIOLATION:
214       signal_fault_addr = e->ExceptionInformation[1];
215       verify_memory_protection_error(signal_fault_addr);
216       dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
217                               (cell)factor::memory_signal_handler_impl);
218       break;
219
220     case STATUS_FLOAT_DENORMAL_OPERAND:
221     case STATUS_FLOAT_DIVIDE_BY_ZERO:
222     case STATUS_FLOAT_INEXACT_RESULT:
223     case STATUS_FLOAT_INVALID_OPERATION:
224     case STATUS_FLOAT_OVERFLOW:
225     case STATUS_FLOAT_STACK_CHECK:
226     case STATUS_FLOAT_UNDERFLOW:
227     case STATUS_FLOAT_MULTIPLE_FAULTS:
228     case STATUS_FLOAT_MULTIPLE_TRAPS:
229 #ifdef FACTOR_64
230       signal_fpu_status = fpu_status(MXCSR(c));
231 #else
232       signal_fpu_status = fpu_status(X87SW(c) | MXCSR(c));
233
234       /* This seems to have no effect */
235       X87SW(c) = 0;
236 #endif
237       MXCSR(c) &= 0xffffffc0;
238       dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
239                               (cell)factor::fp_signal_handler_impl);
240       break;
241     default:
242       signal_number = e->ExceptionCode;
243       dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
244                               (cell)factor::synchronous_signal_handler_impl);
245       break;
246   }
247
248   return ExceptionContinueExecution;
249 }
250
251 VM_C_API LONG exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c,
252                                 void* dispatch) {
253   if (factor_vm::fatal_erroring_p)
254     return ExceptionContinueSearch;
255
256   factor_vm* vm = current_vm_p();
257   if (vm)
258     return vm->exception_handler(e, frame, c, dispatch);
259   else
260     return ExceptionContinueSearch;
261 }
262
263 /* On Unix SIGINT (ctrl-c) automatically interrupts blocking io system
264    calls. It doesn't on Windows, so we need to manually send some
265    cancellation requests to unblock the thread. */
266 VOID CALLBACK dummy_cb (ULONG_PTR dwParam) { }
267
268 // CancelSynchronousIo is not in Windows XP
269 #if _WIN32_WINNT >= 0x0600
270 static void wake_up_thread(HANDLE thread) {
271   if (!CancelSynchronousIo(thread)) {
272     DWORD err = GetLastError();
273     /* CancelSynchronousIo() didn't find anything to cancel, let's try
274        with QueueUserAPC() instead. */
275     if (err == ERROR_NOT_FOUND) {
276       if (!QueueUserAPC(&dummy_cb, thread, NULL)) {
277         fatal_error("QueueUserAPC() failed", GetLastError());
278       }
279     } else {
280       fatal_error("CancelSynchronousIo() failed", err);
281     }
282   }
283 }
284 #else
285 static void wake_up_thread(HANDLE thread) {}
286 #endif
287
288 static BOOL WINAPI ctrl_handler(DWORD dwCtrlType) {
289   switch (dwCtrlType) {
290     case CTRL_C_EVENT: {
291       /* The CtrlHandler runs in its own thread without stopping the main
292          thread. Since in practice nobody uses the multi-VM stuff yet, we just
293          grab the first VM we can get. This will not be a good idea when we
294          actually support native threads. */
295       FACTOR_ASSERT(thread_vms.size() == 1);
296       factor_vm* vm = thread_vms.begin()->second;
297       vm->safepoint.enqueue_fep(vm);
298
299       /* Before leaving the ctrl_handler, try and wake up the main
300          thread. */
301       wake_up_thread(factor::boot_thread);
302       return TRUE;
303     }
304     default:
305       return FALSE;
306   }
307 }
308
309 void open_console() { handle_ctrl_c(); }
310
311 void ignore_ctrl_c() {
312   SetConsoleCtrlHandler(factor::ctrl_handler, FALSE);
313 }
314
315 void handle_ctrl_c() {
316   SetConsoleCtrlHandler(factor::ctrl_handler, TRUE);
317 }
318
319 void lock_console() {}
320
321 void unlock_console() {}
322
323 void close_console() {}
324
325 void factor_vm::sampler_thread_loop() {
326   LARGE_INTEGER counter, new_counter, units_per_second;
327   DWORD ok;
328
329   ok = QueryPerformanceFrequency(&units_per_second);
330   FACTOR_ASSERT(ok);
331
332   ok = QueryPerformanceCounter(&counter);
333   FACTOR_ASSERT(ok);
334
335   counter.QuadPart *= samples_per_second;
336   while (atomic::load(&sampling_profiler_p)) {
337     SwitchToThread();
338     ok = QueryPerformanceCounter(&new_counter);
339     FACTOR_ASSERT(ok);
340     new_counter.QuadPart *= samples_per_second;
341     cell samples = 0;
342     while (new_counter.QuadPart - counter.QuadPart >
343            units_per_second.QuadPart) {
344       ++samples;
345       counter.QuadPart += units_per_second.QuadPart;
346     }
347
348     if (samples > 0) {
349       DWORD suscount = SuspendThread(thread);
350       FACTOR_ASSERT(suscount == 0);
351
352       CONTEXT context;
353       memset((void*)&context, 0, sizeof(CONTEXT));
354       context.ContextFlags = CONTEXT_CONTROL;
355       BOOL context_ok = GetThreadContext(thread, &context);
356       FACTOR_ASSERT(context_ok);
357
358       suscount = ResumeThread(thread);
359       FACTOR_ASSERT(suscount == 1);
360
361       safepoint.enqueue_samples(this, samples, context.EIP, false);
362     }
363   }
364 }
365
366 static DWORD WINAPI sampler_thread_entry(LPVOID parent_vm) {
367   static_cast<factor_vm*>(parent_vm)->sampler_thread_loop();
368   return 0;
369 }
370
371 void factor_vm::start_sampling_profiler_timer() {
372   sampler_thread = CreateThread(NULL, 0, &sampler_thread_entry,
373                                 static_cast<LPVOID>(this), 0, NULL);
374 }
375
376 void factor_vm::end_sampling_profiler_timer() {
377   atomic::store(&sampling_profiler_p, false);
378   DWORD wait_result =
379       WaitForSingleObject(sampler_thread, 3000 * (DWORD) samples_per_second);
380   if (wait_result != WAIT_OBJECT_0)
381     TerminateThread(sampler_thread, 0);
382   sampler_thread = NULL;
383 }
384
385 void abort() { ::abort(); }
386
387 }