]> gitweb.factorcode.org Git - factor.git/blob - vm/os-windows.cpp
Windows: Add two new targets, x86-32-vista and x86-64-vista for bjourne's
[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 // CancelSynchronousIo is not in Windows XP
258 #if _WIN32_WINNT >= 0x0600
259 static void wake_up_thread(HANDLE thread) {
260   if (!CancelSynchronousIo(thread)) {
261     DWORD err = GetLastError();
262     /* CancelSynchronousIo() didn't find anything to cancel, let's try
263        with QueueUserAPC() instead. */
264     if (err == ERROR_NOT_FOUND) {
265       if (!QueueUserAPC(&dummy_cb, thread, NULL)) {
266         fatal_error("QueueUserAPC() failed", GetLastError());
267       }
268     } else {
269       fatal_error("CancelSynchronousIo() failed", err);
270     }
271   }
272 }
273 #else
274 static void wake_up_thread(HANDLE thread) {}
275 #endif
276
277 static BOOL WINAPI ctrl_handler(DWORD dwCtrlType) {
278   switch (dwCtrlType) {
279     case CTRL_C_EVENT: {
280       /* The CtrlHandler runs in its own thread without stopping the main
281          thread. Since in practice nobody uses the multi-VM stuff yet, we just
282          grab the first VM we can get. This will not be a good idea when we
283          actually support native threads. */
284       FACTOR_ASSERT(thread_vms.size() == 1);
285       factor_vm* vm = thread_vms.begin()->second;
286       vm->safepoint.enqueue_fep(vm);
287
288       /* Before leaving the ctrl_handler, try and wake up the main
289          thread. */
290       wake_up_thread(factor::boot_thread);
291       return TRUE;
292     }
293     default:
294       return FALSE;
295   }
296 }
297
298 void factor_vm::open_console() { handle_ctrl_c(); }
299
300 void factor_vm::ignore_ctrl_c() {
301   SetConsoleCtrlHandler(factor::ctrl_handler, FALSE);
302 }
303
304 void factor_vm::handle_ctrl_c() {
305   SetConsoleCtrlHandler(factor::ctrl_handler, TRUE);
306 }
307
308 void factor_vm::lock_console() {}
309
310 void factor_vm::unlock_console() {}
311
312 void factor_vm::close_console() {}
313
314 void factor_vm::sampler_thread_loop() {
315   LARGE_INTEGER counter, new_counter, units_per_second;
316   DWORD ok;
317
318   ok = QueryPerformanceFrequency(&units_per_second);
319   FACTOR_ASSERT(ok);
320
321   ok = QueryPerformanceCounter(&counter);
322   FACTOR_ASSERT(ok);
323
324   counter.QuadPart *= samples_per_second;
325   while (atomic::load(&sampling_profiler_p)) {
326     SwitchToThread();
327     ok = QueryPerformanceCounter(&new_counter);
328     FACTOR_ASSERT(ok);
329     new_counter.QuadPart *= samples_per_second;
330     cell samples = 0;
331     while (new_counter.QuadPart - counter.QuadPart >
332            units_per_second.QuadPart) {
333       ++samples;
334       counter.QuadPart += units_per_second.QuadPart;
335     }
336
337     if (samples > 0) {
338       DWORD suscount = SuspendThread(thread);
339       FACTOR_ASSERT(suscount == 0);
340
341       CONTEXT context;
342       memset((void*)&context, 0, sizeof(CONTEXT));
343       context.ContextFlags = CONTEXT_CONTROL;
344       BOOL context_ok = GetThreadContext(thread, &context);
345       FACTOR_ASSERT(context_ok);
346
347       suscount = ResumeThread(thread);
348       FACTOR_ASSERT(suscount == 1);
349
350       safepoint.enqueue_samples(this, samples, context.EIP, false);
351     }
352   }
353 }
354
355 static DWORD WINAPI sampler_thread_entry(LPVOID parent_vm) {
356   static_cast<factor_vm*>(parent_vm)->sampler_thread_loop();
357   return 0;
358 }
359
360 void factor_vm::start_sampling_profiler_timer() {
361   sampler_thread = CreateThread(NULL, 0, &sampler_thread_entry,
362                                 static_cast<LPVOID>(this), 0, NULL);
363 }
364
365 void factor_vm::end_sampling_profiler_timer() {
366   atomic::store(&sampling_profiler_p, false);
367   DWORD wait_result =
368       WaitForSingleObject(sampler_thread, 3000 * (DWORD) samples_per_second);
369   if (wait_result != WAIT_OBJECT_0)
370     TerminateThread(sampler_thread, 0);
371   sampler_thread = NULL;
372 }
373
374 void abort() { ::abort(); }
375
376 }