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 cell factor_vm::ffi_dlsym(dll* dll, symbol_char* symbol) {
18 return (cell)GetProcAddress(dll ? (HMODULE) dll->handle : hFactorDll,
22 cell 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) {
99 if ((mem = (char*)VirtualAlloc(
100 NULL, getpagesize() * 2 + size, MEM_COMMIT,
101 executable_p ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE)) ==
103 out_of_memory("VirtualAlloc");
106 start = (cell)mem + getpagesize();
109 set_border_locked(true);
112 void segment::set_border_locked(bool locked) {
113 int prot = locked ? PAGE_NOACCESS : PAGE_READWRITE;
114 int pagesize = getpagesize();
117 cell lo = start - pagesize;
118 if (!VirtualProtect((char*)lo, pagesize, prot, &ignore)) {
119 fatal_error("Cannot (un)protect low guard page", lo);
123 if (!VirtualProtect((char*)hi, pagesize, prot, &ignore)) {
124 fatal_error("Cannot (un)protect high guard page", lo);
128 segment::~segment() {
131 if (!VirtualFree((void*)(start - si.dwPageSize), 0, MEM_RELEASE))
132 fatal_error("Segment deallocation failed", 0);
136 static long g_pagesize = 0;
138 SYSTEM_INFO system_info;
139 GetSystemInfo(&system_info);
140 g_pagesize = system_info.dwPageSize;
145 void code_heap::guard_safepoint() {
147 if (!VirtualProtect(safepoint_page, getpagesize(), PAGE_NOACCESS, &ignore))
148 fatal_error("Cannot protect safepoint guard page", (cell)safepoint_page);
151 void code_heap::unguard_safepoint() {
153 if (!VirtualProtect(safepoint_page, getpagesize(), PAGE_READWRITE, &ignore))
154 fatal_error("Cannot unprotect safepoint guard page", (cell)safepoint_page);
157 void factor_vm::move_file(const vm_char* path1, const vm_char* path2) {
158 if (MoveFileEx((path1), (path2), MOVEFILE_REPLACE_EXISTING) == false)
159 general_error(ERROR_IO, tag_fixnum(GetLastError()), false_object);
162 void factor_vm::init_signals() {}
164 THREADHANDLE start_thread(void* (*start_routine)(void*), void* args) {
165 return (void*)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) start_routine,
169 uint64_t nano_count() {
170 static double scale_factor;
172 static uint32_t hi = 0;
173 static uint32_t lo = 0;
176 BOOL ret = QueryPerformanceCounter(&count);
178 fatal_error("QueryPerformanceCounter", 0);
180 if (scale_factor == 0.0) {
181 LARGE_INTEGER frequency;
182 BOOL ret = QueryPerformanceFrequency(&frequency);
184 fatal_error("QueryPerformanceFrequency", 0);
185 scale_factor = (1000000000.0 / frequency.QuadPart);
191 /* On VirtualBox, QueryPerformanceCounter does not increment
192 the high part every time the low part overflows. Workaround. */
193 if (lo > count.LowPart)
198 return (uint64_t)((((uint64_t)hi << 32) | (uint64_t)lo) * scale_factor);
201 void sleep_nanos(uint64_t nsec) { Sleep((DWORD)(nsec / 1000000)); }
203 typedef enum _EXCEPTION_DISPOSITION {
204 ExceptionContinueExecution = 0,
205 ExceptionContinueSearch = 1,
206 ExceptionNestedException = 2,
207 ExceptionCollidedUnwind = 3
208 } EXCEPTION_DISPOSITION;
210 LONG factor_vm::exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c,
212 switch (e->ExceptionCode) {
213 case EXCEPTION_ACCESS_VIOLATION:
214 signal_fault_addr = e->ExceptionInformation[1];
215 verify_memory_protection_error(signal_fault_addr);
216 dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
217 (cell)factor::memory_signal_handler_impl);
220 case STATUS_FLOAT_DENORMAL_OPERAND:
221 case STATUS_FLOAT_DIVIDE_BY_ZERO:
222 case STATUS_FLOAT_INEXACT_RESULT:
223 case STATUS_FLOAT_INVALID_OPERATION:
224 case STATUS_FLOAT_OVERFLOW:
225 case STATUS_FLOAT_STACK_CHECK:
226 case STATUS_FLOAT_UNDERFLOW:
227 case STATUS_FLOAT_MULTIPLE_FAULTS:
228 case STATUS_FLOAT_MULTIPLE_TRAPS:
230 signal_fpu_status = fpu_status(MXCSR(c));
232 signal_fpu_status = fpu_status(X87SW(c) | MXCSR(c));
234 /* This seems to have no effect */
237 MXCSR(c) &= 0xffffffc0;
238 dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
239 (cell)factor::fp_signal_handler_impl);
242 signal_number = e->ExceptionCode;
243 dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP,
244 (cell)factor::synchronous_signal_handler_impl);
248 return ExceptionContinueExecution;
251 VM_C_API LONG exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c,
253 if (factor_vm::fatal_erroring_p)
254 return ExceptionContinueSearch;
256 factor_vm* vm = current_vm_p();
258 return vm->exception_handler(e, frame, c, dispatch);
260 return ExceptionContinueSearch;
263 /* On Unix SIGINT (ctrl-c) automatically interrupts blocking io system
264 calls. It doesn't on Windows, so we need to manually send some
265 cancellation requests to unblock the thread. */
266 VOID CALLBACK dummy_cb (ULONG_PTR dwParam) { }
268 // CancelSynchronousIo is not in Windows XP
269 #if _WIN32_WINNT >= 0x0600
270 static void wake_up_thread(HANDLE thread) {
271 if (!CancelSynchronousIo(thread)) {
272 DWORD err = GetLastError();
273 /* CancelSynchronousIo() didn't find anything to cancel, let's try
274 with QueueUserAPC() instead. */
275 if (err == ERROR_NOT_FOUND) {
276 if (!QueueUserAPC(&dummy_cb, thread, NULL)) {
277 fatal_error("QueueUserAPC() failed", GetLastError());
280 fatal_error("CancelSynchronousIo() failed", err);
285 static void wake_up_thread(HANDLE thread) {}
288 static BOOL WINAPI ctrl_handler(DWORD dwCtrlType) {
289 switch (dwCtrlType) {
291 /* The CtrlHandler runs in its own thread without stopping the main
292 thread. Since in practice nobody uses the multi-VM stuff yet, we just
293 grab the first VM we can get. This will not be a good idea when we
294 actually support native threads. */
295 FACTOR_ASSERT(thread_vms.size() == 1);
296 factor_vm* vm = thread_vms.begin()->second;
297 vm->safepoint.enqueue_fep(vm);
299 /* Before leaving the ctrl_handler, try and wake up the main
301 wake_up_thread(factor::boot_thread);
309 void open_console() { handle_ctrl_c(); }
311 void ignore_ctrl_c() {
312 SetConsoleCtrlHandler(factor::ctrl_handler, FALSE);
315 void handle_ctrl_c() {
316 SetConsoleCtrlHandler(factor::ctrl_handler, TRUE);
319 void lock_console() {}
321 void unlock_console() {}
323 void close_console() {}
325 void factor_vm::sampler_thread_loop() {
326 LARGE_INTEGER counter, new_counter, units_per_second;
329 ok = QueryPerformanceFrequency(&units_per_second);
332 ok = QueryPerformanceCounter(&counter);
335 counter.QuadPart *= samples_per_second;
336 while (atomic::load(&sampling_profiler_p)) {
338 ok = QueryPerformanceCounter(&new_counter);
340 new_counter.QuadPart *= samples_per_second;
342 while (new_counter.QuadPart - counter.QuadPart >
343 units_per_second.QuadPart) {
345 counter.QuadPart += units_per_second.QuadPart;
349 DWORD suscount = SuspendThread(thread);
350 FACTOR_ASSERT(suscount == 0);
353 memset((void*)&context, 0, sizeof(CONTEXT));
354 context.ContextFlags = CONTEXT_CONTROL;
355 BOOL context_ok = GetThreadContext(thread, &context);
356 FACTOR_ASSERT(context_ok);
358 suscount = ResumeThread(thread);
359 FACTOR_ASSERT(suscount == 1);
361 safepoint.enqueue_samples(this, samples, context.EIP, false);
366 static DWORD WINAPI sampler_thread_entry(LPVOID parent_vm) {
367 static_cast<factor_vm*>(parent_vm)->sampler_thread_loop();
371 void factor_vm::start_sampling_profiler_timer() {
372 sampler_thread = CreateThread(NULL, 0, &sampler_thread_entry,
373 static_cast<LPVOID>(this), 0, NULL);
376 void factor_vm::end_sampling_profiler_timer() {
377 atomic::store(&sampling_profiler_p, false);
379 WaitForSingleObject(sampler_thread, 3000 * (DWORD) samples_per_second);
380 if (wait_result != WAIT_OBJECT_0)
381 TerminateThread(sampler_thread, 0);
382 sampler_thread = NULL;
385 void abort() { ::abort(); }