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, 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) {
97 if ((mem = (char*)VirtualAlloc(
98 NULL, getpagesize() * 2 + size, MEM_COMMIT,
99 executable_p ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE)) ==
101 out_of_memory("VirtualAlloc");
104 start = (cell)mem + getpagesize();
107 set_border_locked(true);
110 void segment::set_border_locked(bool locked) {
111 int pagesize = getpagesize();
112 cell lo = start - pagesize;
113 if (!set_memory_locked(lo, pagesize, locked)) {
114 fatal_error("Cannot (un)protect low guard page", lo);
118 if (!set_memory_locked(hi, pagesize, locked)) {
119 fatal_error("Cannot (un)protect high guard page", hi);
123 segment::~segment() {
126 if (!VirtualFree((void*)(start - si.dwPageSize), 0, MEM_RELEASE))
127 fatal_error("Segment deallocation failed", 0);
131 static long g_pagesize = 0;
133 SYSTEM_INFO system_info;
134 GetSystemInfo(&system_info);
135 g_pagesize = system_info.dwPageSize;
140 // MoveFileEx returns FALSE on fail
141 bool move_file(const vm_char* path1, const vm_char* path2) {
142 return !(MoveFileEx((path1), (path2), MOVEFILE_REPLACE_EXISTING) == FALSE);
145 void factor_vm::init_signals() {}
147 THREADHANDLE start_thread(void* (*start_routine)(void*), void* args) {
148 return (void*)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) start_routine,
152 uint64_t nano_count() {
153 static double scale_factor;
155 static uint32_t hi = 0;
156 static uint32_t lo = 0;
159 BOOL ret = QueryPerformanceCounter(&count);
161 fatal_error("QueryPerformanceCounter", 0);
163 if (scale_factor == 0.0) {
164 LARGE_INTEGER frequency;
165 BOOL ret = QueryPerformanceFrequency(&frequency);
167 fatal_error("QueryPerformanceFrequency", 0);
168 scale_factor = (1000000000.0 / frequency.QuadPart);
174 /* On VirtualBox, QueryPerformanceCounter does not increment
175 the high part every time the low part overflows. Workaround. */
176 if (lo > count.LowPart)
181 return (uint64_t)((((uint64_t)hi << 32) | (uint64_t)lo) * scale_factor);
184 void sleep_nanos(uint64_t nsec) { Sleep((DWORD)(nsec / 1000000)); }
186 typedef enum _EXCEPTION_DISPOSITION {
187 ExceptionContinueExecution = 0,
188 ExceptionContinueSearch = 1,
189 ExceptionNestedException = 2,
190 ExceptionCollidedUnwind = 3
191 } EXCEPTION_DISPOSITION;
193 LONG factor_vm::exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c,
195 switch (e->ExceptionCode) {
196 case EXCEPTION_ACCESS_VIOLATION:
197 signal_fault_addr = e->ExceptionInformation[1];
198 signal_fault_pc = c->EIP;
199 verify_memory_protection_error(signal_fault_addr);
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) { }
247 // CancelSynchronousIo is not in Windows XP
248 #if _WIN32_WINNT >= 0x0600
249 static void wake_up_thread(HANDLE thread) {
250 if (!CancelSynchronousIo(thread)) {
251 DWORD err = GetLastError();
252 /* CancelSynchronousIo() didn't find anything to cancel, let's try
253 with QueueUserAPC() instead. */
254 if (err == ERROR_NOT_FOUND) {
255 if (!QueueUserAPC(&dummy_cb, thread, NULL)) {
256 fatal_error("QueueUserAPC() failed", GetLastError());
259 fatal_error("CancelSynchronousIo() failed", err);
264 static void wake_up_thread(HANDLE thread) {}
267 static BOOL WINAPI ctrl_handler(DWORD dwCtrlType) {
268 switch (dwCtrlType) {
270 /* The CtrlHandler runs in its own thread without stopping the main
271 thread. Since in practice nobody uses the multi-VM stuff yet, we just
272 grab the first VM we can get. This will not be a good idea when we
273 actually support native threads. */
274 FACTOR_ASSERT(thread_vms.size() == 1);
275 factor_vm* vm = thread_vms.begin()->second;
276 vm->safepoint.enqueue_fep(vm);
278 /* Before leaving the ctrl_handler, try and wake up the main
280 wake_up_thread(factor::boot_thread);
288 void open_console() { handle_ctrl_c(); }
290 void ignore_ctrl_c() {
291 SetConsoleCtrlHandler(factor::ctrl_handler, FALSE);
294 void handle_ctrl_c() {
295 SetConsoleCtrlHandler(factor::ctrl_handler, TRUE);
298 void lock_console() {}
300 void unlock_console() {}
302 void close_console() {}
304 cell get_thread_pc(THREADHANDLE th) {
305 DWORD suscount = SuspendThread(th);
306 FACTOR_ASSERT(suscount == 0);
309 memset((void*)&context, 0, sizeof(CONTEXT));
310 context.ContextFlags = CONTEXT_CONTROL;
311 BOOL context_ok = GetThreadContext(th, &context);
312 FACTOR_ASSERT(context_ok);
314 suscount = ResumeThread(th);
315 FACTOR_ASSERT(suscount == 1);
319 void factor_vm::sampler_thread_loop() {
320 LARGE_INTEGER counter, new_counter, units_per_second;
323 ok = QueryPerformanceFrequency(&units_per_second);
326 ok = QueryPerformanceCounter(&counter);
329 counter.QuadPart *= samples_per_second;
330 while (atomic::load(&sampling_profiler_p)) {
332 ok = QueryPerformanceCounter(&new_counter);
334 new_counter.QuadPart *= samples_per_second;
336 while (new_counter.QuadPart - counter.QuadPart >
337 units_per_second.QuadPart) {
339 counter.QuadPart += units_per_second.QuadPart;
344 cell pc = get_thread_pc(thread);
345 safepoint.enqueue_samples(this, samples, pc, false);
349 static DWORD WINAPI sampler_thread_entry(LPVOID parent_vm) {
350 static_cast<factor_vm*>(parent_vm)->sampler_thread_loop();
354 void factor_vm::start_sampling_profiler_timer() {
355 sampler_thread = CreateThread(NULL, 0, &sampler_thread_entry,
356 static_cast<LPVOID>(this), 0, NULL);
359 void factor_vm::end_sampling_profiler_timer() {
360 atomic::store(&sampling_profiler_p, false);
362 WaitForSingleObject(sampler_thread, 3000 * (DWORD) samples_per_second);
363 if (wait_result != WAIT_OBJECT_0)
364 TerminateThread(sampler_thread, 0);
365 sampler_thread = NULL;
368 void abort() { ::abort(); }