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