7 bool set_memory_locked(cell base, cell size, bool locked) {
8 int prot = locked ? PAGE_NOACCESS : PAGE_READWRITE;
10 int status = VirtualProtect((char*)base, size, prot, &ignore);
14 void factor_vm::init_ffi() {
15 hFactorDll = GetModuleHandle(NULL);
17 fatal_error("GetModuleHandle() failed", 0);
20 void factor_vm::ffi_dlopen(dll* dll) {
21 dll->handle = LoadLibraryEx((WCHAR*)alien_offset(dll->path), NULL, 0);
24 cell factor_vm::ffi_dlsym(dll* dll, symbol_char* symbol) {
25 return (cell)GetProcAddress(dll ? (HMODULE) dll->handle : hFactorDll,
29 cell factor_vm::ffi_dlsym_raw(dll* dll, symbol_char* symbol) {
30 return ffi_dlsym(dll, symbol);
33 void factor_vm::ffi_dlclose(dll* dll) {
34 FreeLibrary((HMODULE) dll->handle);
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 | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
41 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
43 if (h == INVALID_HANDLE_VALUE) {
44 // FindFirstFile is the only call that can stat c:\pagefile.sys
48 if (INVALID_HANDLE_VALUE == (h = FindFirstFile(path, &st)))
53 BOOL ret = GetFileInformationByHandle(h, &bhfi);
58 // You must free() this yourself.
59 const vm_char* factor_vm::default_image_path() {
60 vm_char full_path[MAX_UNICODE_PATH];
62 vm_char temp_path[MAX_UNICODE_PATH];
64 if (!GetModuleFileName(NULL, full_path, MAX_UNICODE_PATH))
65 fatal_error("GetModuleFileName() failed", 0);
67 if ((ptr = wcsrchr(full_path, '.')))
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;
76 return safe_strdup(temp_path);
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);
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)));
92 segment::segment(cell size_, bool executable_p) {
96 cell alloc_size = getpagesize() * 2 + size;
97 if ((mem = (char*)VirtualAlloc(
98 NULL, alloc_size, MEM_COMMIT,
99 executable_p ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE)) ==
101 fatal_error("Out of memory in VirtualAlloc", alloc_size);
104 start = (cell)mem + getpagesize();
107 set_border_locked(true);
110 segment::~segment() {
113 if (!VirtualFree((void*)(start - si.dwPageSize), 0, MEM_RELEASE))
114 fatal_error("Segment deallocation failed", 0);
118 static long g_pagesize = 0;
120 SYSTEM_INFO system_info;
121 GetSystemInfo(&system_info);
122 g_pagesize = system_info.dwPageSize;
128 bool move_file(const vm_char* path1, const vm_char* path2) {
129 // MoveFileEx returns FALSE on fail.
130 BOOL val = MoveFileEx((path1), (path2), MOVEFILE_REPLACE_EXISTING);
132 // MoveFileEx doesn't set errno, which primitive_save_image()
133 // reads the error code from. Instead of converting from
134 // GetLastError() to errno values, we ust set it to the generic
141 void factor_vm::init_signals() {}
143 THREADHANDLE start_thread(void* (*start_routine)(void*), void* args) {
144 return (void*)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) start_routine,
148 uint64_t nano_count() {
149 static double scale_factor;
151 static uint32_t hi = 0;
152 static uint32_t lo = 0;
154 // Note: on older systems QueryPerformanceCounter may be unreliable
155 // until you add /usepmtimer to Boot.ini. I had an issue where two
156 // nano_count calls would show a difference of about 1 second,
157 // while actually about 80 seconds have passed. The /usepmtimer
158 // switch cured the issue on that PC (WinXP Pro SP3 32-bit).
159 // See also http://www.virtualdub.org/blog/pivot/entry.php?id=106
161 BOOL ret = QueryPerformanceCounter(&count);
163 fatal_error("QueryPerformanceCounter", 0);
165 if (scale_factor == 0.0) {
166 LARGE_INTEGER frequency;
167 BOOL ret = QueryPerformanceFrequency(&frequency);
169 fatal_error("QueryPerformanceFrequency", 0);
170 scale_factor = (1000000000.0 / frequency.QuadPart);
176 // On VirtualBox, QueryPerformanceCounter does not increment
177 // the high part every time the low part overflows. Workaround.
178 if (lo > count.LowPart)
183 return (uint64_t)((((uint64_t)hi << 32) | (uint64_t)lo) * scale_factor);
186 void sleep_nanos(uint64_t nsec) { Sleep((DWORD)(nsec / 1000000)); }
188 #ifndef EXCEPTION_DISPOSITION
189 typedef enum _EXCEPTION_DISPOSITION {
190 ExceptionContinueExecution = 0,
191 ExceptionContinueSearch = 1,
192 ExceptionNestedException = 2,
193 ExceptionCollidedUnwind = 3
194 } EXCEPTION_DISPOSITION;
197 LONG factor_vm::exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c,
201 switch (e->ExceptionCode) {
202 case EXCEPTION_ACCESS_VIOLATION:
203 set_memory_protection_error(e->ExceptionInformation[1], c->EIP);
204 dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
205 (cell)factor::memory_signal_handler_impl);
208 case STATUS_FLOAT_DENORMAL_OPERAND:
209 case STATUS_FLOAT_DIVIDE_BY_ZERO:
210 case STATUS_FLOAT_INEXACT_RESULT:
211 case STATUS_FLOAT_INVALID_OPERATION:
212 case STATUS_FLOAT_OVERFLOW:
213 case STATUS_FLOAT_STACK_CHECK:
214 case STATUS_FLOAT_UNDERFLOW:
215 case STATUS_FLOAT_MULTIPLE_FAULTS:
216 case STATUS_FLOAT_MULTIPLE_TRAPS:
218 signal_fpu_status = fpu_status(MXCSR(c));
220 signal_fpu_status = fpu_status(X87SW(c) | MXCSR(c));
222 // This seems to have no effect
225 MXCSR(c) &= 0xffffffc0;
226 dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
227 (cell)factor::fp_signal_handler_impl);
230 signal_number = e->ExceptionCode;
231 dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
232 (cell)factor::synchronous_signal_handler_impl);
235 return ExceptionContinueExecution;
238 VM_C_API LONG exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c,
240 factor_vm* vm = current_vm_p();
241 if (factor_vm::fatal_erroring_p || !vm)
242 return ExceptionContinueSearch;
243 return vm->exception_handler(e, frame, c, dispatch);
246 // On Unix SIGINT (ctrl-c) automatically interrupts blocking io system
247 // calls. It doesn't on Windows, so we need to manually send some
248 // cancellation requests to unblock the thread.
249 VOID CALLBACK dummy_cb(ULONG_PTR dwParam) { (void)dwParam; }
251 // CancelSynchronousIo is not in Windows XP
252 #if _WIN32_WINNT >= 0x0600
253 static void wake_up_thread(HANDLE thread) {
254 if (!CancelSynchronousIo(thread)) {
255 DWORD err = GetLastError();
256 // CancelSynchronousIo() didn't find anything to cancel, let's try
257 // with QueueUserAPC() instead.
258 if (err == ERROR_NOT_FOUND) {
259 if (!QueueUserAPC(&dummy_cb, thread, NULL)) {
260 fatal_error("QueueUserAPC() failed", GetLastError());
263 fatal_error("CancelSynchronousIo() failed", err);
268 static void wake_up_thread(HANDLE thread) { (void)thread; }
271 static BOOL WINAPI ctrl_handler(DWORD dwCtrlType) {
272 switch (dwCtrlType) {
274 // The CtrlHandler runs in its own thread without stopping the main
275 // thread. Since in practice nobody uses the multi-VM stuff yet, we just
276 // grab the first VM we can get. This will not be a good idea when we
277 // actually support native threads.
278 FACTOR_ASSERT(thread_vms.size() == 1);
279 factor_vm* vm = thread_vms.begin()->second;
282 // Before leaving the ctrl_handler, try and wake up the main thread.
283 wake_up_thread(factor::boot_thread);
291 void open_console() { handle_ctrl_c(); }
293 void ignore_ctrl_c() {
294 SetConsoleCtrlHandler(factor::ctrl_handler, FALSE);
297 void handle_ctrl_c() {
298 SetConsoleCtrlHandler(factor::ctrl_handler, TRUE);
301 const int ctrl_break_sleep = 10; /* msec */
303 static DWORD WINAPI ctrl_break_thread_proc(LPVOID parent_vm) {
304 bool ctrl_break_handled = false;
305 factor_vm* vm = static_cast<factor_vm*>(parent_vm);
306 while (vm->stop_on_ctrl_break) {
307 if (GetAsyncKeyState(VK_CANCEL) >= 0) { /* Ctrl-Break is released. */
308 ctrl_break_handled = false; /* Wait for the next press. */
309 } else if (!ctrl_break_handled) {
310 /* Check if the VM thread has the same Id as the thread Id of the
311 currently active window. Note that thread Id is not a handle. */
312 DWORD fg_thd_id = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
313 if ((fg_thd_id == vm->thread_id) && !vm->fep_p) {
315 ctrl_break_handled = true;
318 Sleep(ctrl_break_sleep);
323 void factor_vm::primitive_disable_ctrl_break() {
324 stop_on_ctrl_break = false;
325 if (ctrl_break_thread != NULL) {
326 DWORD wait_result = WaitForSingleObject(ctrl_break_thread,
327 2 * ctrl_break_sleep);
328 if (wait_result != WAIT_OBJECT_0)
329 TerminateThread(ctrl_break_thread, 0);
330 CloseHandle(ctrl_break_thread);
331 ctrl_break_thread = NULL;
335 void factor_vm::primitive_enable_ctrl_break() {
336 stop_on_ctrl_break = true;
337 if (ctrl_break_thread == NULL) {
338 DisableProcessWindowsGhosting();
339 ctrl_break_thread = CreateThread(NULL, 0, factor::ctrl_break_thread_proc,
340 static_cast<LPVOID>(this), 0, NULL);
341 SetThreadPriority(ctrl_break_thread, THREAD_PRIORITY_ABOVE_NORMAL);
345 void lock_console() {}
347 void unlock_console() {}
349 void close_console() {}
351 cell get_thread_pc(THREADHANDLE th) {
352 DWORD suscount = SuspendThread(th);
353 FACTOR_ASSERT(suscount == 0);
356 memset((void*)&context, 0, sizeof(CONTEXT));
357 context.ContextFlags = CONTEXT_CONTROL;
358 BOOL context_ok = GetThreadContext(th, &context);
359 FACTOR_ASSERT(context_ok);
361 suscount = ResumeThread(th);
362 FACTOR_ASSERT(suscount == 1);
366 void factor_vm::sampler_thread_loop() {
367 LARGE_INTEGER counter, new_counter, units_per_second;
370 ok = QueryPerformanceFrequency(&units_per_second);
373 ok = QueryPerformanceCounter(&counter);
376 counter.QuadPart *= samples_per_second;
377 while (atomic::load(&sampling_profiler_p)) {
379 ok = QueryPerformanceCounter(&new_counter);
381 new_counter.QuadPart *= samples_per_second;
383 while (new_counter.QuadPart - counter.QuadPart >
384 units_per_second.QuadPart) {
386 counter.QuadPart += units_per_second.QuadPart;
391 cell pc = get_thread_pc(thread);
392 enqueue_samples(samples, pc, false);
396 static DWORD WINAPI sampler_thread_entry(LPVOID parent_vm) {
397 static_cast<factor_vm*>(parent_vm)->sampler_thread_loop();
401 void factor_vm::start_sampling_profiler_timer() {
402 sampler_thread = CreateThread(NULL, 0, &sampler_thread_entry,
403 static_cast<LPVOID>(this), 0, NULL);
406 void factor_vm::end_sampling_profiler_timer() {
407 atomic::store(&sampling_profiler_p, false);
409 WaitForSingleObject(sampler_thread, 3000 * (DWORD) samples_per_second);
410 if (wait_result != WAIT_OBJECT_0)
411 TerminateThread(sampler_thread, 0);
412 CloseHandle(sampler_thread);
413 sampler_thread = NULL;
416 void abort() { ::abort(); }