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, FILE_READ_ATTRIBUTES, 0, 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
46 h = FindFirstFile(path, &st);
47 if (h == INVALID_HANDLE_VALUE)
52 BOOL ret = GetFileInformationByHandle(h, &bhfi);
57 // You must free() this yourself.
58 const vm_char* factor_vm::default_image_path() {
59 vm_char full_path[MAX_UNICODE_PATH];
61 vm_char temp_path[MAX_UNICODE_PATH];
63 if (!GetModuleFileName(NULL, full_path, MAX_UNICODE_PATH))
64 fatal_error("GetModuleFileName() failed", 0);
66 if ((ptr = wcsrchr(full_path, '.')))
69 wcsncpy(temp_path, full_path, MAX_UNICODE_PATH - 1);
70 size_t full_path_len = wcslen(full_path);
71 if (full_path_len < MAX_UNICODE_PATH - 1)
72 wcsncat(temp_path, L".image", MAX_UNICODE_PATH - full_path_len - 1);
73 temp_path[MAX_UNICODE_PATH - 1] = 0;
75 return safe_strdup(temp_path);
78 // You must free() this yourself.
79 const vm_char* factor_vm::vm_executable_path() {
80 vm_char full_path[MAX_UNICODE_PATH];
81 if (!GetModuleFileName(NULL, full_path, MAX_UNICODE_PATH))
82 fatal_error("GetModuleFileName() failed", 0);
83 return safe_strdup(full_path);
86 void factor_vm::primitive_existsp() {
87 vm_char* path = untag_check<byte_array>(ctx->pop())->data<vm_char>();
88 ctx->push(tag_boolean(windows_stat(path)));
91 segment::segment(cell size_, bool executable_p) {
95 cell alloc_size = getpagesize() * 2 + size;
96 if ((mem = (char*)VirtualAlloc(
97 NULL, alloc_size, MEM_COMMIT,
98 executable_p ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE)) ==
100 fatal_error("Out of memory in VirtualAlloc", alloc_size);
103 start = (cell)mem + getpagesize();
106 set_border_locked(true);
109 segment::~segment() {
110 if (!VirtualFree((void*)(start - getpagesize()), 0, MEM_RELEASE))
111 fatal_error("Segment deallocation failed", 0);
115 static long g_pagesize = 0;
117 SYSTEM_INFO system_info;
118 GetSystemInfo(&system_info);
119 g_pagesize = system_info.dwPageSize;
124 bool move_file(const vm_char* path1, const vm_char* path2) {
125 // MoveFileEx returns FALSE on fail.
126 BOOL val = MoveFileEx((path1), (path2), MOVEFILE_REPLACE_EXISTING);
128 // MoveFileEx doesn't set errno, which primitive_save_image()
129 // reads the error code from. Instead of converting from
130 // GetLastError() to errno values, we ust set it to the generic
137 void factor_vm::init_signals() {}
139 THREADHANDLE start_thread(void* (*start_routine)(void*), void* args) {
140 return (void*)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) start_routine,
144 uint64_t nano_count() {
145 static double scale_factor;
147 static uint32_t hi = 0;
148 static uint32_t lo = 0;
150 // Note: on older systems QueryPerformanceCounter may be unreliable
151 // until you add /usepmtimer to Boot.ini. I had an issue where two
152 // nano_count calls would show a difference of about 1 second,
153 // while actually about 80 seconds have passed. The /usepmtimer
154 // switch cured the issue on that PC (WinXP Pro SP3 32-bit).
155 // See also http://www.virtualdub.org/blog/pivot/entry.php?id=106
157 BOOL ret = QueryPerformanceCounter(&count);
159 fatal_error("QueryPerformanceCounter", 0);
161 if (scale_factor == 0.0) {
162 LARGE_INTEGER frequency;
163 BOOL ret = QueryPerformanceFrequency(&frequency);
165 fatal_error("QueryPerformanceFrequency", 0);
166 scale_factor = (1000000000.0 / frequency.QuadPart);
172 // On VirtualBox, QueryPerformanceCounter does not increment
173 // the high part every time the low part overflows. Workaround.
174 if (lo > count.LowPart)
179 return (uint64_t)((((uint64_t)hi << 32) | (uint64_t)lo) * scale_factor);
182 void sleep_nanos(uint64_t nsec) { Sleep((DWORD)(nsec / 1000000)); }
184 #ifndef EXCEPTION_DISPOSITION
185 typedef enum _EXCEPTION_DISPOSITION {
186 ExceptionContinueExecution = 0,
187 ExceptionContinueSearch = 1,
188 ExceptionNestedException = 2,
189 ExceptionCollidedUnwind = 3
190 } EXCEPTION_DISPOSITION;
193 LONG factor_vm::exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c,
197 switch (e->ExceptionCode) {
198 case EXCEPTION_ACCESS_VIOLATION:
199 set_memory_protection_error(e->ExceptionInformation[1], c->EIP);
200 dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
201 (cell)factor::memory_signal_handler_impl);
204 case STATUS_FLOAT_DENORMAL_OPERAND:
205 case STATUS_FLOAT_DIVIDE_BY_ZERO:
206 case STATUS_FLOAT_INEXACT_RESULT:
207 case STATUS_FLOAT_INVALID_OPERATION:
208 case STATUS_FLOAT_OVERFLOW:
209 case STATUS_FLOAT_STACK_CHECK:
210 case STATUS_FLOAT_UNDERFLOW:
211 case STATUS_FLOAT_MULTIPLE_FAULTS:
212 case STATUS_FLOAT_MULTIPLE_TRAPS:
214 signal_fpu_status = fpu_status(MXCSR(c));
216 signal_fpu_status = fpu_status(X87SW(c) | MXCSR(c));
218 // This seems to have no effect
221 MXCSR(c) &= 0xffffffc0;
222 dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
223 (cell)factor::fp_signal_handler_impl);
226 signal_number = e->ExceptionCode;
227 dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
228 (cell)factor::synchronous_signal_handler_impl);
231 return ExceptionContinueExecution;
234 VM_C_API LONG exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c,
236 factor_vm* vm = current_vm_p();
237 if (factor_vm::fatal_erroring_p || !vm)
238 return ExceptionContinueSearch;
239 return vm->exception_handler(e, frame, c, dispatch);
242 // On Unix SIGINT (ctrl-c) automatically interrupts blocking io system
243 // calls. It doesn't on Windows, so we need to manually send some
244 // cancellation requests to unblock the thread.
245 VOID CALLBACK dummy_cb(ULONG_PTR dwParam) { (void)dwParam; }
247 static void wake_up_thread(HANDLE thread) {
248 if (!CancelSynchronousIo(thread)) {
249 DWORD err = GetLastError();
250 // CancelSynchronousIo() didn't find anything to cancel, let's try
251 // with QueueUserAPC() instead.
252 if (err == ERROR_NOT_FOUND) {
253 if (!QueueUserAPC(&dummy_cb, thread, 0)) {
254 fatal_error("QueueUserAPC() failed", GetLastError());
257 fatal_error("CancelSynchronousIo() failed", err);
262 static BOOL WINAPI ctrl_handler(DWORD dwCtrlType) {
263 switch (dwCtrlType) {
265 // The CtrlHandler runs in its own thread without stopping the main
266 // thread. Since in practice nobody uses the multi-VM stuff yet, we just
267 // grab the first VM we can get. This will not be a good idea when we
268 // actually support native threads.
269 FACTOR_ASSERT(thread_vms.size() == 1);
270 factor_vm* vm = thread_vms.begin()->second;
273 // Before leaving the ctrl_handler, try and wake up the main thread.
274 wake_up_thread(factor::boot_thread);
282 void open_console() { handle_ctrl_c(); }
284 void ignore_ctrl_c() {
285 SetConsoleCtrlHandler(factor::ctrl_handler, FALSE);
288 void handle_ctrl_c() {
289 SetConsoleCtrlHandler(factor::ctrl_handler, TRUE);
292 const int ctrl_break_sleep = 10; /* msec */
294 static DWORD WINAPI ctrl_break_thread_proc(LPVOID parent_vm) {
295 bool ctrl_break_handled = false;
296 factor_vm* vm = static_cast<factor_vm*>(parent_vm);
297 while (vm->stop_on_ctrl_break) {
298 if (GetAsyncKeyState(VK_CANCEL) >= 0) { /* Ctrl-Break is released. */
299 ctrl_break_handled = false; /* Wait for the next press. */
300 } else if (!ctrl_break_handled) {
301 /* Check if the VM thread has the same Id as the thread Id of the
302 currently active window. Note that thread Id is not a handle. */
303 DWORD fg_thd_id = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
304 if ((fg_thd_id == vm->thread_id) && !vm->fep_p) {
306 ctrl_break_handled = true;
309 Sleep(ctrl_break_sleep);
314 void factor_vm::primitive_disable_ctrl_break() {
315 stop_on_ctrl_break = false;
316 if (ctrl_break_thread != NULL) {
317 DWORD wait_result = WaitForSingleObject(ctrl_break_thread,
318 2 * ctrl_break_sleep);
319 if (wait_result != WAIT_OBJECT_0)
320 TerminateThread(ctrl_break_thread, 0);
321 CloseHandle(ctrl_break_thread);
322 ctrl_break_thread = NULL;
326 void factor_vm::primitive_enable_ctrl_break() {
327 stop_on_ctrl_break = true;
328 if (ctrl_break_thread == NULL) {
329 DisableProcessWindowsGhosting();
330 ctrl_break_thread = CreateThread(NULL, 0, factor::ctrl_break_thread_proc,
331 static_cast<LPVOID>(this), 0, NULL);
332 SetThreadPriority(ctrl_break_thread, THREAD_PRIORITY_ABOVE_NORMAL);
336 void lock_console() {}
338 void unlock_console() {}
340 void close_console() {}
342 cell get_thread_pc(THREADHANDLE th) {
343 DWORD suscount = SuspendThread(th);
344 FACTOR_ASSERT(suscount == 0);
347 memset((void*)&context, 0, sizeof(CONTEXT));
348 context.ContextFlags = CONTEXT_CONTROL;
349 BOOL context_ok = GetThreadContext(th, &context);
350 FACTOR_ASSERT(context_ok);
352 suscount = ResumeThread(th);
353 FACTOR_ASSERT(suscount == 1);
355 (void)suscount, (void)context_ok; // use all variables
360 void factor_vm::sampler_thread_loop() {
361 LARGE_INTEGER counter, new_counter, units_per_second;
364 ok = QueryPerformanceFrequency(&units_per_second);
367 ok = QueryPerformanceCounter(&counter);
370 counter.QuadPart *= samples_per_second;
371 while (atomic::load(&sampling_profiler_p)) {
373 ok = QueryPerformanceCounter(&new_counter);
375 new_counter.QuadPart *= samples_per_second;
377 while (new_counter.QuadPart - counter.QuadPart >
378 units_per_second.QuadPart) {
380 counter.QuadPart += units_per_second.QuadPart;
385 cell pc = get_thread_pc(thread);
386 enqueue_samples(samples, pc, false);
389 (void)ok; // use all variables
393 static DWORD WINAPI sampler_thread_entry(LPVOID parent_vm) {
394 static_cast<factor_vm*>(parent_vm)->sampler_thread_loop();
398 void factor_vm::start_sampling_profiler_timer() {
399 sampler_thread = CreateThread(NULL, 0, &sampler_thread_entry,
400 static_cast<LPVOID>(this), 0, NULL);
403 void factor_vm::end_sampling_profiler_timer() {
404 atomic::store(&sampling_profiler_p, false);
406 WaitForSingleObject(sampler_thread, 3000 * (DWORD) samples_per_second);
407 if (wait_result != WAIT_OBJECT_0)
408 TerminateThread(sampler_thread, 0);
409 CloseHandle(sampler_thread);
410 sampler_thread = NULL;
413 void abort() { ::abort(); }