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