7 void factor_vm::init_ffi() {
8 hFactorDll = GetModuleHandle(NULL);
10 fatal_error("GetModuleHandle() failed", 0);
13 void factor_vm::ffi_dlopen(dll* dll) {
14 dll->handle = LoadLibraryEx((WCHAR*)alien_offset(dll->path), NULL, 0);
17 void* factor_vm::ffi_dlsym(dll* dll, symbol_char* symbol) {
18 return (void*)GetProcAddress(dll ? (HMODULE) dll->handle : hFactorDll,
22 void* factor_vm::ffi_dlsym_raw(dll* dll, symbol_char* symbol) {
23 return ffi_dlsym(dll, symbol);
26 void factor_vm::ffi_dlclose(dll* dll) {
27 FreeLibrary((HMODULE) dll->handle);
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);
36 if (h == INVALID_HANDLE_VALUE) {
37 // FindFirstFile is the only call that can stat c:\pagefile.sys
41 if (INVALID_HANDLE_VALUE == (h = FindFirstFile(path, &st)))
46 BOOL ret = GetFileInformationByHandle(h, &bhfi);
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;
60 /* You must free() this yourself. */
61 const vm_char* factor_vm::default_image_path() {
62 vm_char full_path[MAX_UNICODE_PATH];
64 vm_char temp_path[MAX_UNICODE_PATH];
66 if (!GetModuleFileName(NULL, full_path, MAX_UNICODE_PATH))
67 fatal_error("GetModuleFileName() failed", 0);
69 if ((ptr = wcsrchr(full_path, '.')))
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;
78 return safe_strdup(temp_path);
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);
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)));
94 segment::segment(cell size_, bool executable_p) {
100 if ((mem = (char*)VirtualAlloc(
101 NULL, getpagesize() * 2 + size, MEM_COMMIT,
102 executable_p ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE)) ==
106 if (!VirtualProtect(mem, getpagesize(), PAGE_NOACCESS, &ignore))
107 fatal_error("Cannot allocate low guard page", (cell)mem);
109 if (!VirtualProtect(mem + size + getpagesize(), getpagesize(), PAGE_NOACCESS,
111 fatal_error("Cannot allocate high guard page", (cell)mem);
113 start = (cell)mem + getpagesize();
117 segment::~segment() {
120 if (!VirtualFree((void*)(start - si.dwPageSize), 0, MEM_RELEASE))
121 fatal_error("Segment deallocation failed", 0);
125 static long g_pagesize = 0;
127 SYSTEM_INFO system_info;
128 GetSystemInfo(&system_info);
129 g_pagesize = system_info.dwPageSize;
134 void code_heap::guard_safepoint() {
136 if (!VirtualProtect(safepoint_page, getpagesize(), PAGE_NOACCESS, &ignore))
137 fatal_error("Cannot protect safepoint guard page", (cell)safepoint_page);
140 void code_heap::unguard_safepoint() {
142 if (!VirtualProtect(safepoint_page, getpagesize(), PAGE_READWRITE, &ignore))
143 fatal_error("Cannot unprotect safepoint guard page", (cell)safepoint_page);
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);
151 void factor_vm::init_signals() {}
153 THREADHANDLE start_thread(void* (*start_routine)(void*), void* args) {
154 return (void*)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) start_routine,
158 uint64_t nano_count() {
159 static double scale_factor;
161 static uint32_t hi = 0;
162 static uint32_t lo = 0;
165 BOOL ret = QueryPerformanceCounter(&count);
167 fatal_error("QueryPerformanceCounter", 0);
169 if (scale_factor == 0.0) {
170 LARGE_INTEGER frequency;
171 BOOL ret = QueryPerformanceFrequency(&frequency);
173 fatal_error("QueryPerformanceFrequency", 0);
174 scale_factor = (1000000000.0 / frequency.QuadPart);
180 /* On VirtualBox, QueryPerformanceCounter does not increment
181 the high part every time the low part overflows. Workaround. */
182 if (lo > count.LowPart)
187 return (uint64_t)((((uint64_t)hi << 32) | (uint64_t)lo) * scale_factor);
190 void sleep_nanos(uint64_t nsec) { Sleep((DWORD)(nsec / 1000000)); }
192 typedef enum _EXCEPTION_DISPOSITION {
193 ExceptionContinueExecution = 0,
194 ExceptionContinueSearch = 1,
195 ExceptionNestedException = 2,
196 ExceptionCollidedUnwind = 3
197 } EXCEPTION_DISPOSITION;
199 LONG factor_vm::exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c,
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);
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:
219 signal_fpu_status = fpu_status(MXCSR(c));
221 signal_fpu_status = fpu_status(X87SW(c) | MXCSR(c));
223 /* This seems to have no effect */
226 MXCSR(c) &= 0xffffffc0;
227 dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
228 (cell)factor::fp_signal_handler_impl);
231 signal_number = e->ExceptionCode;
232 dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
233 (cell)factor::synchronous_signal_handler_impl);
237 return ExceptionContinueExecution;
240 VM_C_API LONG exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c,
242 if (factor_vm::fatal_erroring_p)
243 return ExceptionContinueSearch;
245 factor_vm* vm = current_vm_p();
247 return vm->exception_handler(e, frame, c, dispatch);
249 return ExceptionContinueSearch;
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) { }
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());
269 fatal_error("CancelSynchronousIo() failed", err);
274 static void wake_up_thread(HANDLE thread) {}
277 static BOOL WINAPI ctrl_handler(DWORD dwCtrlType) {
278 switch (dwCtrlType) {
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);
288 /* Before leaving the ctrl_handler, try and wake up the main
290 wake_up_thread(factor::boot_thread);
298 void factor_vm::open_console() { handle_ctrl_c(); }
300 void factor_vm::ignore_ctrl_c() {
301 SetConsoleCtrlHandler(factor::ctrl_handler, FALSE);
304 void factor_vm::handle_ctrl_c() {
305 SetConsoleCtrlHandler(factor::ctrl_handler, TRUE);
308 void factor_vm::lock_console() {}
310 void factor_vm::unlock_console() {}
312 void factor_vm::close_console() {}
314 void factor_vm::sampler_thread_loop() {
315 LARGE_INTEGER counter, new_counter, units_per_second;
318 ok = QueryPerformanceFrequency(&units_per_second);
321 ok = QueryPerformanceCounter(&counter);
324 counter.QuadPart *= samples_per_second;
325 while (atomic::load(&sampling_profiler_p)) {
327 ok = QueryPerformanceCounter(&new_counter);
329 new_counter.QuadPart *= samples_per_second;
331 while (new_counter.QuadPart - counter.QuadPart >
332 units_per_second.QuadPart) {
334 counter.QuadPart += units_per_second.QuadPart;
338 DWORD suscount = SuspendThread(thread);
339 FACTOR_ASSERT(suscount == 0);
342 memset((void*)&context, 0, sizeof(CONTEXT));
343 context.ContextFlags = CONTEXT_CONTROL;
344 BOOL context_ok = GetThreadContext(thread, &context);
345 FACTOR_ASSERT(context_ok);
347 suscount = ResumeThread(thread);
348 FACTOR_ASSERT(suscount == 1);
350 safepoint.enqueue_samples(this, samples, context.EIP, false);
355 static DWORD WINAPI sampler_thread_entry(LPVOID parent_vm) {
356 static_cast<factor_vm*>(parent_vm)->sampler_thread_loop();
360 void factor_vm::start_sampling_profiler_timer() {
361 sampler_thread = CreateThread(NULL, 0, &sampler_thread_entry,
362 static_cast<LPVOID>(this), 0, NULL);
365 void factor_vm::end_sampling_profiler_timer() {
366 atomic::store(&sampling_profiler_p, false);
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;
374 void abort() { ::abort(); }