Merge tag 'v2.4.0' into tizen_3.0_qemu_2.4
[sdk/emulator/qemu.git] / util / oslib-win32.c
1 /*
2  * os-win32.c
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  * Copyright (c) 2010 Red Hat, Inc.
6  *
7  * QEMU library functions for win32 which are shared between QEMU and
8  * the QEMU tools.
9  *
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:
16  *
17  * The above copyright notice and this permission notice shall be included in
18  * all copies or substantial portions of the Software.
19  *
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
26  * THE SOFTWARE.
27  *
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.
31  */
32 #include <windows.h>
33 #include <glib.h>
34 #include <stdlib.h>
35 #include "config-host.h"
36 #include "sysemu/sysemu.h"
37 #include "qemu/main-loop.h"
38 #include "trace.h"
39 #include "qemu/sockets.h"
40 /* this must come after including "trace.h" */
41 #include <shlobj.h>
42
43 #ifdef CONFIG_MARU
44 #include "tizen/src/emulator_common.h"
45
46 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
47
48 int is_wow64(void)
49 {
50     int result = 0;
51     LPFN_ISWOW64PROCESS fnIsWow64Process;
52
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. */
56
57     fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(
58         GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
59
60     if (NULL != fnIsWow64Process) {
61         if (!fnIsWow64Process(GetCurrentProcess(), &result)) {
62             /* No need to handle error,
63                just check whether is this WoW64 process */
64         }
65     }
66     return result;
67 }
68
69 static char wow64_java_path[JAVA_MAX_COMMAND_LENGTH];
70 bool get_java_path(char **java_path)
71 {
72     int index;
73     LONG res;
74     HKEY hKey, hSubKey;
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] = {
81                 /* 64bit runtime */
82                 "SOFTWARE\\JavaSoft\\Java Runtime Environment",
83                 "SOFTWARE\\JavaSoft\\Java Development Kit",
84                 /* 32bit runtime */
85                 "SOFTWARE\\Wow6432Node\\JavaSoft\\Java Runtime Environment",
86                 "SOFTWARE\\Wow6432Node\\JavaSoft\\Java Development Kit"
87             };
88
89     if (wow64_java_path[0] != '\0') {
90         strcpy(*java_path, wow64_java_path);
91         return true;
92     }
93
94     for (index = 0; index < ARRAY_SIZE(strKeyList); index++) {
95         res = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
96                            strKeyList[index],
97                            0,
98                            KEY_QUERY_VALUE |
99                            KEY_ENUMERATE_SUB_KEYS |
100                            MY_KEY_WOW64_64KEY,
101                            &hKey);
102         if (res == ERROR_SUCCESS) {
103             break;
104         }
105     }
106
107     if (res == ERROR_SUCCESS) {
108         RegEnumKeyEx(hKey, 0, (LPSTR)strSubKeyName, &dwSubKeyNameMax,
109                      NULL, NULL, NULL, NULL);
110         strcpy(strChoosenName, strSubKeyName);
111
112         index = 1;
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);
119             }
120             index++;
121         }
122
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);
128         RegCloseKey(hKey);
129     } else {
130         /* TODO:
131            get from %winDir%\System32
132            but, is this really needed?
133         */
134         DWORD dwRet = 0;
135         char strJavaHomeVar[JAVA_MAX_COMMAND_LENGTH] = {0,};
136         dwRet = GetEnvironmentVariable("JAVA_HOME",
137                                        strJavaHomeVar,
138                                        JAVA_MAX_COMMAND_LENGTH);
139         if (dwRet != 0 && dwRet < JAVA_MAX_COMMAND_LENGTH) {
140             strcpy(strJavaHome, strJavaHomeVar);
141         }
142     }
143     if (strJavaHome[0] != '\0') {
144         sprintf(*java_path, "\"%s\\bin\\javaw.exe\"", strJavaHome);
145         strcpy(wow64_java_path, *java_path);
146     } else {
147         return false;
148     }
149
150     return true;
151 }
152 #endif
153
154 void *qemu_oom_check(void *ptr)
155 {
156 #ifdef CONFIG_MARU
157     const char _msg[] = "Failed to allocate memory in qemu.";
158     char cmd[JAVA_MAX_COMMAND_LENGTH] = { 0, };
159     char *JAVA_EXEFILE_PATH = NULL;
160     int len, ret;
161 #endif
162
163     if (ptr == NULL) {
164         fprintf(stderr, "Failed to allocate memory: %lu\n", GetLastError());
165 #ifdef CONFIG_MARU
166         JAVA_EXEFILE_PATH = malloc(JAVA_MAX_COMMAND_LENGTH);
167         if (!JAVA_EXEFILE_PATH) {
168             // TODO: print error message.
169             return ptr;
170         }
171
172         memset(JAVA_EXEFILE_PATH, 0, JAVA_MAX_COMMAND_LENGTH);
173         if (is_wow64()) {
174             if (!get_java_path(&JAVA_EXEFILE_PATH)) {
175                 strcpy(JAVA_EXEFILE_PATH, "java");
176             }
177         } else {
178             strcpy(JAVA_EXEFILE_PATH, "java");
179         }
180         len = strlen(JAVA_EXEFILE_PATH) + strlen(JAVA_EXEOPTION) +
181                   strlen(JAR_SKINFILE) + strlen(JAVA_SIMPLEMODE_OPTION) +
182                   strlen(_msg) + 7;
183         if (len > JAVA_MAX_COMMAND_LENGTH) {
184             len = JAVA_MAX_COMMAND_LENGTH;
185         }
186
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);
191         if (ret < 32) {
192             // TODO: error handling...
193         }
194
195         /* for 64bit windows */
196         free(JAVA_EXEFILE_PATH);
197         JAVA_EXEFILE_PATH=0;
198 #endif
199         abort();
200     }
201     return ptr;
202 }
203
204 void *qemu_try_memalign(size_t alignment, size_t size)
205 {
206     void *ptr;
207
208     if (!size) {
209         abort();
210     }
211     ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
212     trace_qemu_memalign(alignment, size, ptr);
213     return ptr;
214 }
215
216 void *qemu_memalign(size_t alignment, size_t size)
217 {
218     return qemu_oom_check(qemu_try_memalign(alignment, size));
219 }
220
221 #ifdef CONFIG_MARU
222 void *preallocated_ram_ptr = NULL;
223 int preallocated_ram_size = -1;
224 #endif
225
226 void *qemu_anon_ram_alloc(size_t size, uint64_t *align)
227 {
228     void *ptr;
229
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. */
233 #ifdef CONFIG_MARU
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;
238         return ptr;
239     }
240 #endif
241     ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
242     trace_qemu_anon_ram_alloc(size, ptr);
243     return ptr;
244 }
245
246 void qemu_vfree(void *ptr)
247 {
248     trace_qemu_vfree(ptr);
249     if (ptr) {
250         VirtualFree(ptr, 0, MEM_RELEASE);
251     }
252 }
253
254 void qemu_anon_ram_free(void *ptr, size_t size)
255 {
256     trace_qemu_anon_ram_free(ptr, size);
257     if (ptr) {
258         VirtualFree(ptr, 0, MEM_RELEASE);
259     }
260 }
261
262 /* FIXME: add proper locking */
263 struct tm *gmtime_r(const time_t *timep, struct tm *result)
264 {
265     struct tm *p = gmtime(timep);
266     memset(result, 0, sizeof(*result));
267     if (p) {
268         *result = *p;
269         p = result;
270     }
271     return p;
272 }
273
274 /* FIXME: add proper locking */
275 struct tm *localtime_r(const time_t *timep, struct tm *result)
276 {
277     struct tm *p = localtime(timep);
278     memset(result, 0, sizeof(*result));
279     if (p) {
280         *result = *p;
281         p = result;
282     }
283     return p;
284 }
285
286 void qemu_set_block(int fd)
287 {
288     unsigned long opt = 0;
289     WSAEventSelect(fd, NULL, 0);
290     ioctlsocket(fd, FIONBIO, &opt);
291 }
292
293 void qemu_set_nonblock(int fd)
294 {
295     unsigned long opt = 1;
296     ioctlsocket(fd, FIONBIO, &opt);
297     qemu_fd_register(fd);
298 }
299
300 int socket_set_fast_reuse(int fd)
301 {
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 */
307     return 0;
308 }
309
310 int inet_aton(const char *cp, struct in_addr *ia)
311 {
312     uint32_t addr = inet_addr(cp);
313     if (addr == 0xffffffff) {
314         return 0;
315     }
316     ia->s_addr = addr;
317     return 1;
318 }
319
320 void qemu_set_cloexec(int fd)
321 {
322 }
323
324 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
325 #define _W32_FT_OFFSET (116444736000000000ULL)
326
327 int qemu_gettimeofday(qemu_timeval *tp)
328 {
329   union {
330     unsigned long long ns100; /*time since 1 Jan 1601 in 100ns units */
331     FILETIME ft;
332   }  _now;
333
334   if(tp) {
335       GetSystemTimeAsFileTime (&_now.ft);
336       tp->tv_usec=(long)((_now.ns100 / 10ULL) % 1000000ULL );
337       tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000ULL);
338   }
339   /* Always return 0 as per Open Group Base Specifications Issue 6.
340      Do not set errno on error.  */
341   return 0;
342 }
343
344 int qemu_get_thread_id(void)
345 {
346     return GetCurrentThreadId();
347 }
348
349 char *
350 qemu_get_local_state_pathname(const char *relative_pathname)
351 {
352     HRESULT result;
353     char base_path[MAX_PATH+1] = "";
354
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);
360         abort();
361     }
362     return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", base_path,
363                            relative_pathname);
364 }
365
366 void qemu_set_tty_echo(int fd, bool echo)
367 {
368     HANDLE handle = (HANDLE)_get_osfhandle(fd);
369     DWORD dwMode = 0;
370
371     if (handle == INVALID_HANDLE_VALUE) {
372         return;
373     }
374
375     GetConsoleMode(handle, &dwMode);
376
377     if (echo) {
378         SetConsoleMode(handle, dwMode | ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT);
379     } else {
380         SetConsoleMode(handle,
381                        dwMode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT));
382     }
383 }
384
385 static char exec_dir[PATH_MAX];
386
387 void qemu_init_exec_dir(const char *argv0)
388 {
389
390     char *p;
391     char buf[MAX_PATH];
392     DWORD len;
393
394     len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
395     if (len == 0) {
396         return;
397     }
398
399     buf[len] = 0;
400     p = buf + len - 1;
401     while (p != buf && *p != '\\') {
402         p--;
403     }
404     *p = 0;
405     if (access(buf, R_OK) == 0) {
406         pstrcpy(exec_dir, sizeof(exec_dir), buf);
407     }
408 }
409
410 char *qemu_get_exec_dir(void)
411 {
412     return g_strdup(exec_dir);
413 }
414
415 /*
416  * The original implementation of g_poll from glib has a problem on Windows
417  * when using timeouts < 10 ms.
418  *
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.
421  *
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'.
426  */
427
428 /*
429  * gpoll.c: poll(2) abstraction
430  * Copyright 1998 Owen Taylor
431  * Copyright 2008 Red Hat, Inc.
432  *
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.
437  *
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.
442  *
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/>.
445  */
446
447 static int poll_rest(gboolean poll_msgs, HANDLE *handles, gint nhandles,
448                      GPollFD *fds, guint nfds, gint timeout)
449 {
450     DWORD ready;
451     GPollFD *f;
452     int recursed_result;
453
454     if (poll_msgs) {
455         /* Wait for either messages or handles
456          * -> Use MsgWaitForMultipleObjectsEx
457          */
458         ready = MsgWaitForMultipleObjectsEx(nhandles, handles, timeout,
459                                             QS_ALLINPUT, MWMO_ALERTABLE);
460
461         if (ready == WAIT_FAILED) {
462             gchar *emsg = g_win32_error_message(GetLastError());
463             g_warning("MsgWaitForMultipleObjectsEx failed: %s", emsg);
464             g_free(emsg);
465         }
466     } else if (nhandles == 0) {
467         /* No handles to wait for, just the timeout */
468         if (timeout == INFINITE) {
469             ready = WAIT_FAILED;
470         } else {
471             SleepEx(timeout, TRUE);
472             ready = WAIT_TIMEOUT;
473         }
474     } else {
475         /* Wait for just handles
476          * -> Use WaitForMultipleObjectsEx
477          */
478         ready =
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);
483             g_free(emsg);
484         }
485     }
486
487     if (ready == WAIT_FAILED) {
488         return -1;
489     } else if (ready == WAIT_TIMEOUT || ready == WAIT_IO_COMPLETION) {
490         return 0;
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;
495             }
496         }
497
498         /* If we have a timeout, or no handles to poll, be satisfied
499          * with just noticing we have messages waiting.
500          */
501         if (timeout != 0 || nhandles == 0) {
502             return 1;
503         }
504
505         /* If no timeout and handles to poll, recurse to poll them,
506          * too.
507          */
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;
516             }
517         }
518
519         /* If no timeout and polling several handles, recurse to poll
520          * the rest of them.
521          */
522         if (timeout == 0 && nhandles > 1) {
523             /* Remove the handle that fired */
524             int i;
525             if (ready < nhandles - 1) {
526                 for (i = ready - WAIT_OBJECT_0 + 1; i < nhandles; i++) {
527                     handles[i-1] = handles[i];
528                 }
529             }
530             nhandles--;
531             recursed_result = poll_rest(FALSE, handles, nhandles, fds, nfds, 0);
532             return (recursed_result == -1) ? -1 : 1 + recursed_result;
533         }
534         return 1;
535     }
536
537     return 0;
538 }
539
540 gint g_poll(GPollFD *fds, guint nfds, gint timeout)
541 {
542     HANDLE handles[MAXIMUM_WAIT_OBJECTS];
543     gboolean poll_msgs = FALSE;
544     GPollFD *f;
545     gint nhandles = 0;
546     int retval;
547
548     for (f = fds; f < &fds[nfds]; ++f) {
549         if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN)) {
550             poll_msgs = TRUE;
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
554              * to work.
555              */
556             gint i;
557
558             for (i = 0; i < nhandles; i++) {
559                 if (handles[i] == (HANDLE) f->fd) {
560                     break;
561                 }
562             }
563
564             if (i == nhandles) {
565                 if (nhandles == MAXIMUM_WAIT_OBJECTS) {
566                     g_warning("Too many handles to wait for!\n");
567                     break;
568                 } else {
569                     handles[nhandles++] = (HANDLE) f->fd;
570                 }
571             }
572         }
573     }
574
575     for (f = fds; f < &fds[nfds]; ++f) {
576         f->revents = 0;
577     }
578
579     if (timeout == -1) {
580         timeout = INFINITE;
581     }
582
583     /* Polling for several things? */
584     if (nhandles > 1 || (nhandles > 0 && poll_msgs)) {
585         /* First check if one or several of them are immediately
586          * available
587          */
588         retval = poll_rest(poll_msgs, handles, nhandles, fds, nfds, 0);
589
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
595          * anyway.
596          *
597          * Modification for QEMU: replaced timeout >= 10 by timeout > 0.
598          */
599         if (retval == 0 && (timeout == INFINITE || timeout > 0)) {
600             retval = poll_rest(poll_msgs, handles, nhandles,
601                                fds, nfds, timeout);
602         }
603     } else {
604         /* Just polling for one thing, so no need to check first if
605          * available immediately
606          */
607         retval = poll_rest(poll_msgs, handles, nhandles, fds, nfds, timeout);
608     }
609
610     if (retval == -1) {
611         for (f = fds; f < &fds[nfds]; ++f) {
612             f->revents = 0;
613         }
614     }
615
616     return retval;
617 }
618
619 size_t getpagesize(void)
620 {
621     SYSTEM_INFO system_info;
622
623     GetSystemInfo(&system_info);
624     return system_info.dwPageSize;
625 }
626
627 void os_mem_prealloc(int fd, char *area, size_t memory)
628 {
629     int i;
630     size_t pagesize = getpagesize();
631
632     memory = (memory + pagesize - 1) & -pagesize;
633     for (i = 0; i < memory / pagesize; i++) {
634         memset(area + pagesize * i, 0, 1);
635     }
636 }
637
638
639 /* XXX: put correct support for win32 */
640 int qemu_read_password(char *buf, int buf_size)
641 {
642     int c, i;
643
644     printf("Password: ");
645     fflush(stdout);
646     i = 0;
647     for (;;) {
648         c = getchar();
649         if (c < 0) {
650             buf[i] = '\0';
651             return -1;
652         } else if (c == '\n') {
653             break;
654         } else if (i < (buf_size - 1)) {
655             buf[i++] = c;
656         }
657     }
658     buf[i] = '\0';
659     return 0;
660 }