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