4 * Copyright (c) 2003-2008 Fabrice Bellard
5 * Copyright (c) 2010 Red Hat, Inc.
7 * QEMU library functions for win32 which are shared between QEMU and
10 * Permission is hereby granted, free of charge, to any person obtaining a copy
11 * of this software and associated documentation files (the "Software"), to deal
12 * in the Software without restriction, including without limitation the rights
13 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the Software is
15 * furnished to do so, subject to the following conditions:
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28 * The implementation of g_poll (functions poll_rest, g_poll) at the end of
29 * this file are based on code from GNOME glib-2 and use a different license,
30 * see the license comment there.
35 #include "config-host.h"
36 #include "sysemu/sysemu.h"
37 #include "qemu/main-loop.h"
39 #include "qemu/sockets.h"
40 /* this must come after including "trace.h" */
44 #include "tizen/src/emulator_common.h"
46 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
51 LPFN_ISWOW64PROCESS fnIsWow64Process;
53 /* IsWow64Process is not available on all supported versions of Windows.
54 Use GetModuleHandle to get a handle to the DLL that contains the function
55 and GetProcAddress to get a pointer to the function if available. */
57 fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(
58 GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
60 if (NULL != fnIsWow64Process) {
61 if (!fnIsWow64Process(GetCurrentProcess(), &result)) {
62 /* No need to handle error,
63 just check whether is this WoW64 process */
69 static char wow64_java_path[JAVA_MAX_COMMAND_LENGTH];
70 bool get_java_path(char **java_path)
75 char strChoosenName[JAVA_MAX_COMMAND_LENGTH] = {0};
76 char strSubKeyName[JAVA_MAX_COMMAND_LENGTH] = {0};
77 char strJavaHome[JAVA_MAX_COMMAND_LENGTH] = {0};
78 DWORD dwSubKeyNameMax = JAVA_MAX_COMMAND_LENGTH;
79 DWORD dwBufLen = JAVA_MAX_COMMAND_LENGTH;
80 char strKeyList[4][64] = {
82 "SOFTWARE\\JavaSoft\\Java Runtime Environment",
83 "SOFTWARE\\JavaSoft\\Java Development Kit",
85 "SOFTWARE\\Wow6432Node\\JavaSoft\\Java Runtime Environment",
86 "SOFTWARE\\Wow6432Node\\JavaSoft\\Java Development Kit"
89 if (wow64_java_path[0] != '\0') {
90 strcpy(*java_path, wow64_java_path);
94 for (index = 0; index < ARRAY_SIZE(strKeyList); index++) {
95 res = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
99 KEY_ENUMERATE_SUB_KEYS |
102 if (res == ERROR_SUCCESS) {
107 if (res == ERROR_SUCCESS) {
108 RegEnumKeyEx(hKey, 0, (LPSTR)strSubKeyName, &dwSubKeyNameMax,
109 NULL, NULL, NULL, NULL);
110 strcpy(strChoosenName, strSubKeyName);
113 while (ERROR_SUCCESS ==
114 RegEnumKeyEx(hKey, index,
115 (LPSTR)strSubKeyName, &dwSubKeyNameMax,
116 NULL, NULL, NULL, NULL)) {
117 if (strcmp(strChoosenName, strSubKeyName) < 0) {
118 strcpy(strChoosenName, strSubKeyName);
123 RegOpenKeyEx(hKey, strChoosenName, 0,
124 KEY_QUERY_VALUE | MY_KEY_WOW64_64KEY, &hSubKey);
125 RegQueryValueEx(hSubKey, "JavaHome", NULL,
126 NULL, (LPBYTE)strJavaHome, &dwBufLen);
127 RegCloseKey(hSubKey);
131 get from %winDir%\System32
132 but, is this really needed?
135 char strJavaHomeVar[JAVA_MAX_COMMAND_LENGTH] = {0,};
136 dwRet = GetEnvironmentVariable("JAVA_HOME",
138 JAVA_MAX_COMMAND_LENGTH);
139 if (dwRet != 0 && dwRet < JAVA_MAX_COMMAND_LENGTH) {
140 strcpy(strJavaHome, strJavaHomeVar);
143 if (strJavaHome[0] != '\0') {
144 sprintf(*java_path, "\"%s\\bin\\javaw.exe\"", strJavaHome);
145 strcpy(wow64_java_path, *java_path);
154 void *qemu_oom_check(void *ptr)
157 const char _msg[] = "Failed to allocate memory in qemu.";
158 char cmd[JAVA_MAX_COMMAND_LENGTH] = { 0, };
159 char *JAVA_EXEFILE_PATH = NULL;
164 fprintf(stderr, "Failed to allocate memory: %lu\n", GetLastError());
166 JAVA_EXEFILE_PATH = malloc(JAVA_MAX_COMMAND_LENGTH);
167 if (!JAVA_EXEFILE_PATH) {
168 // TODO: print error message.
172 memset(JAVA_EXEFILE_PATH, 0, JAVA_MAX_COMMAND_LENGTH);
174 if (!get_java_path(&JAVA_EXEFILE_PATH)) {
175 strcpy(JAVA_EXEFILE_PATH, "java");
178 strcpy(JAVA_EXEFILE_PATH, "java");
180 len = strlen(JAVA_EXEFILE_PATH) + strlen(JAVA_EXEOPTION) +
181 strlen(JAR_SKINFILE) + strlen(JAVA_SIMPLEMODE_OPTION) +
183 if (len > JAVA_MAX_COMMAND_LENGTH) {
184 len = JAVA_MAX_COMMAND_LENGTH;
187 snprintf(cmd, len, "%s %s %s %s=\"%s\"",
188 JAVA_EXEFILE_PATH, JAVA_EXEOPTION, JAR_SKINFILE,
189 JAVA_SIMPLEMODE_OPTION, _msg);
190 ret = WinExec(cmd, SW_SHOW);
192 // TODO: error handling...
195 /* for 64bit windows */
196 free(JAVA_EXEFILE_PATH);
204 void *qemu_try_memalign(size_t alignment, size_t size)
211 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
212 trace_qemu_memalign(alignment, size, ptr);
216 void *qemu_memalign(size_t alignment, size_t size)
218 return qemu_oom_check(qemu_try_memalign(alignment, size));
222 void *preallocated_ram_ptr = NULL;
223 int preallocated_ram_size = -1;
226 void *qemu_anon_ram_alloc(size_t size, uint64_t *align)
230 /* FIXME: this is not exactly optimal solution since VirtualAlloc
231 has 64Kb granularity, but at least it guarantees us that the
232 memory is page aligned. */
234 if (size == preallocated_ram_size && preallocated_ram_ptr) {
235 void *ptr = preallocated_ram_ptr;
236 preallocated_ram_ptr = NULL;
237 preallocated_ram_size = -1;
241 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
242 trace_qemu_anon_ram_alloc(size, ptr);
246 void qemu_vfree(void *ptr)
248 trace_qemu_vfree(ptr);
250 VirtualFree(ptr, 0, MEM_RELEASE);
254 void qemu_anon_ram_free(void *ptr, size_t size)
256 trace_qemu_anon_ram_free(ptr, size);
258 VirtualFree(ptr, 0, MEM_RELEASE);
262 /* FIXME: add proper locking */
263 struct tm *gmtime_r(const time_t *timep, struct tm *result)
265 struct tm *p = gmtime(timep);
266 memset(result, 0, sizeof(*result));
274 /* FIXME: add proper locking */
275 struct tm *localtime_r(const time_t *timep, struct tm *result)
277 struct tm *p = localtime(timep);
278 memset(result, 0, sizeof(*result));
286 void qemu_set_block(int fd)
288 unsigned long opt = 0;
289 WSAEventSelect(fd, NULL, 0);
290 ioctlsocket(fd, FIONBIO, &opt);
293 void qemu_set_nonblock(int fd)
295 unsigned long opt = 1;
296 ioctlsocket(fd, FIONBIO, &opt);
297 qemu_fd_register(fd);
300 int socket_set_fast_reuse(int fd)
302 /* Enabling the reuse of an endpoint that was used by a socket still in
303 * TIME_WAIT state is usually performed by setting SO_REUSEADDR. On Windows
304 * fast reuse is the default and SO_REUSEADDR does strange things. So we
305 * don't have to do anything here. More info can be found at:
306 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621.aspx */
310 int inet_aton(const char *cp, struct in_addr *ia)
312 uint32_t addr = inet_addr(cp);
313 if (addr == 0xffffffff) {
320 void qemu_set_cloexec(int fd)
324 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
325 #define _W32_FT_OFFSET (116444736000000000ULL)
327 int qemu_gettimeofday(qemu_timeval *tp)
330 unsigned long long ns100; /*time since 1 Jan 1601 in 100ns units */
335 GetSystemTimeAsFileTime (&_now.ft);
336 tp->tv_usec=(long)((_now.ns100 / 10ULL) % 1000000ULL );
337 tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000ULL);
339 /* Always return 0 as per Open Group Base Specifications Issue 6.
340 Do not set errno on error. */
344 int qemu_get_thread_id(void)
346 return GetCurrentThreadId();
350 qemu_get_local_state_pathname(const char *relative_pathname)
353 char base_path[MAX_PATH+1] = "";
355 result = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL,
356 /* SHGFP_TYPE_CURRENT */ 0, base_path);
357 if (result != S_OK) {
358 /* misconfigured environment */
359 g_critical("CSIDL_COMMON_APPDATA unavailable: %ld", (long)result);
362 return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", base_path,
366 void qemu_set_tty_echo(int fd, bool echo)
368 HANDLE handle = (HANDLE)_get_osfhandle(fd);
371 if (handle == INVALID_HANDLE_VALUE) {
375 GetConsoleMode(handle, &dwMode);
378 SetConsoleMode(handle, dwMode | ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT);
380 SetConsoleMode(handle,
381 dwMode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT));
385 static char exec_dir[PATH_MAX];
387 void qemu_init_exec_dir(const char *argv0)
394 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
401 while (p != buf && *p != '\\') {
405 if (access(buf, R_OK) == 0) {
406 pstrcpy(exec_dir, sizeof(exec_dir), buf);
410 char *qemu_get_exec_dir(void)
412 return g_strdup(exec_dir);
416 * The original implementation of g_poll from glib has a problem on Windows
417 * when using timeouts < 10 ms.
419 * Whenever g_poll is called with timeout < 10 ms, it does a quick poll instead
420 * of wait. This causes significant performance degradation of QEMU.
422 * The following code is a copy of the original code from glib/gpoll.c
423 * (glib commit 20f4d1820b8d4d0fc4447188e33efffd6d4a88d8 from 2014-02-19).
424 * Some debug code was removed and the code was reformatted.
425 * All other code modifications are marked with 'QEMU'.
429 * gpoll.c: poll(2) abstraction
430 * Copyright 1998 Owen Taylor
431 * Copyright 2008 Red Hat, Inc.
433 * This library is free software; you can redistribute it and/or
434 * modify it under the terms of the GNU Lesser General Public
435 * License as published by the Free Software Foundation; either
436 * version 2 of the License, or (at your option) any later version.
438 * This library is distributed in the hope that it will be useful,
439 * but WITHOUT ANY WARRANTY; without even the implied warranty of
440 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
441 * Lesser General Public License for more details.
443 * You should have received a copy of the GNU Lesser General Public
444 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
447 static int poll_rest(gboolean poll_msgs, HANDLE *handles, gint nhandles,
448 GPollFD *fds, guint nfds, gint timeout)
455 /* Wait for either messages or handles
456 * -> Use MsgWaitForMultipleObjectsEx
458 ready = MsgWaitForMultipleObjectsEx(nhandles, handles, timeout,
459 QS_ALLINPUT, MWMO_ALERTABLE);
461 if (ready == WAIT_FAILED) {
462 gchar *emsg = g_win32_error_message(GetLastError());
463 g_warning("MsgWaitForMultipleObjectsEx failed: %s", emsg);
466 } else if (nhandles == 0) {
467 /* No handles to wait for, just the timeout */
468 if (timeout == INFINITE) {
471 SleepEx(timeout, TRUE);
472 ready = WAIT_TIMEOUT;
475 /* Wait for just handles
476 * -> Use WaitForMultipleObjectsEx
479 WaitForMultipleObjectsEx(nhandles, handles, FALSE, timeout, TRUE);
480 if (ready == WAIT_FAILED) {
481 gchar *emsg = g_win32_error_message(GetLastError());
482 g_warning("WaitForMultipleObjectsEx failed: %s", emsg);
487 if (ready == WAIT_FAILED) {
489 } else if (ready == WAIT_TIMEOUT || ready == WAIT_IO_COMPLETION) {
491 } else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles) {
492 for (f = fds; f < &fds[nfds]; ++f) {
493 if (f->fd == G_WIN32_MSG_HANDLE && f->events & G_IO_IN) {
494 f->revents |= G_IO_IN;
498 /* If we have a timeout, or no handles to poll, be satisfied
499 * with just noticing we have messages waiting.
501 if (timeout != 0 || nhandles == 0) {
505 /* If no timeout and handles to poll, recurse to poll them,
508 recursed_result = poll_rest(FALSE, handles, nhandles, fds, nfds, 0);
509 return (recursed_result == -1) ? -1 : 1 + recursed_result;
510 } else if (/* QEMU: removed the following unneeded statement which causes
511 * a compiler warning: ready >= WAIT_OBJECT_0 && */
512 ready < WAIT_OBJECT_0 + nhandles) {
513 for (f = fds; f < &fds[nfds]; ++f) {
514 if ((HANDLE) f->fd == handles[ready - WAIT_OBJECT_0]) {
515 f->revents = f->events;
519 /* If no timeout and polling several handles, recurse to poll
522 if (timeout == 0 && nhandles > 1) {
523 /* Remove the handle that fired */
525 if (ready < nhandles - 1) {
526 for (i = ready - WAIT_OBJECT_0 + 1; i < nhandles; i++) {
527 handles[i-1] = handles[i];
531 recursed_result = poll_rest(FALSE, handles, nhandles, fds, nfds, 0);
532 return (recursed_result == -1) ? -1 : 1 + recursed_result;
540 gint g_poll(GPollFD *fds, guint nfds, gint timeout)
542 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
543 gboolean poll_msgs = FALSE;
548 for (f = fds; f < &fds[nfds]; ++f) {
549 if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN)) {
551 } else if (f->fd > 0) {
552 /* Don't add the same handle several times into the array, as
553 * docs say that is not allowed, even if it actually does seem
558 for (i = 0; i < nhandles; i++) {
559 if (handles[i] == (HANDLE) f->fd) {
565 if (nhandles == MAXIMUM_WAIT_OBJECTS) {
566 g_warning("Too many handles to wait for!\n");
569 handles[nhandles++] = (HANDLE) f->fd;
575 for (f = fds; f < &fds[nfds]; ++f) {
583 /* Polling for several things? */
584 if (nhandles > 1 || (nhandles > 0 && poll_msgs)) {
585 /* First check if one or several of them are immediately
588 retval = poll_rest(poll_msgs, handles, nhandles, fds, nfds, 0);
590 /* If not, and we have a significant timeout, poll again with
591 * timeout then. Note that this will return indication for only
592 * one event, or only for messages. We ignore timeouts less than
593 * ten milliseconds as they are mostly pointless on Windows, the
594 * MsgWaitForMultipleObjectsEx() call will timeout right away
597 * Modification for QEMU: replaced timeout >= 10 by timeout > 0.
599 if (retval == 0 && (timeout == INFINITE || timeout > 0)) {
600 retval = poll_rest(poll_msgs, handles, nhandles,
604 /* Just polling for one thing, so no need to check first if
605 * available immediately
607 retval = poll_rest(poll_msgs, handles, nhandles, fds, nfds, timeout);
611 for (f = fds; f < &fds[nfds]; ++f) {
619 size_t getpagesize(void)
621 SYSTEM_INFO system_info;
623 GetSystemInfo(&system_info);
624 return system_info.dwPageSize;
627 void os_mem_prealloc(int fd, char *area, size_t memory)
630 size_t pagesize = getpagesize();
632 memory = (memory + pagesize - 1) & -pagesize;
633 for (i = 0; i < memory / pagesize; i++) {
634 memset(area + pagesize * i, 0, 1);
639 /* XXX: put correct support for win32 */
640 int qemu_read_password(char *buf, int buf_size)
644 printf("Password: ");
652 } else if (c == '\n') {
654 } else if (i < (buf_size - 1)) {