4 * Copyright (c) 2003-2008 Fabrice Bellard
5 * Copyright (c) 2010-2016 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.
33 #include "qemu/osdep.h"
35 #include "qemu-common.h"
36 #include "qapi/error.h"
37 #include "sysemu/sysemu.h"
38 #include "qemu/main-loop.h"
40 #include "qemu/sockets.h"
41 #include "qemu/cutils.h"
43 /* this must come after including "trace.h" */
46 void *qemu_oom_check(void *ptr
)
49 fprintf(stderr
, "Failed to allocate memory: %lu\n", GetLastError());
55 void *qemu_try_memalign(size_t alignment
, size_t size
)
62 ptr
= VirtualAlloc(NULL
, size
, MEM_COMMIT
, PAGE_READWRITE
);
63 trace_qemu_memalign(alignment
, size
, ptr
);
67 void *qemu_memalign(size_t alignment
, size_t size
)
69 return qemu_oom_check(qemu_try_memalign(alignment
, size
));
72 static int get_allocation_granularity(void)
74 SYSTEM_INFO system_info
;
76 GetSystemInfo(&system_info
);
77 return system_info
.dwAllocationGranularity
;
80 void *qemu_anon_ram_alloc(size_t size
, uint64_t *align
, bool shared
)
84 ptr
= VirtualAlloc(NULL
, size
, MEM_COMMIT
, PAGE_READWRITE
);
85 trace_qemu_anon_ram_alloc(size
, ptr
);
88 *align
= MAX(get_allocation_granularity(), getpagesize());
93 void qemu_vfree(void *ptr
)
95 trace_qemu_vfree(ptr
);
97 VirtualFree(ptr
, 0, MEM_RELEASE
);
101 void qemu_anon_ram_free(void *ptr
, size_t size
)
103 trace_qemu_anon_ram_free(ptr
, size
);
105 VirtualFree(ptr
, 0, MEM_RELEASE
);
109 #ifndef _POSIX_THREAD_SAFE_FUNCTIONS
110 /* FIXME: add proper locking */
111 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
113 struct tm
*p
= gmtime(timep
);
114 memset(result
, 0, sizeof(*result
));
122 /* FIXME: add proper locking */
123 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
125 struct tm
*p
= localtime(timep
);
126 memset(result
, 0, sizeof(*result
));
133 #endif /* _POSIX_THREAD_SAFE_FUNCTIONS */
135 static int socket_error(void)
137 switch (WSAGetLastError()) {
144 case WSA_INVALID_HANDLE
:
146 case WSA_NOT_ENOUGH_MEMORY
:
148 case WSA_INVALID_PARAMETER
:
150 case WSAENAMETOOLONG
:
155 /* not using EWOULDBLOCK as we don't want code to have
156 * to check both EWOULDBLOCK and EAGAIN */
164 case WSAEDESTADDRREQ
:
172 case WSAEPROTONOSUPPORT
:
173 return EPROTONOSUPPORT
;
176 case WSAEAFNOSUPPORT
:
180 case WSAEADDRNOTAVAIL
:
181 return EADDRNOTAVAIL
;
188 case WSAECONNABORTED
:
200 case WSAECONNREFUSED
:
204 case WSAEHOSTUNREACH
:
211 void qemu_set_block(int fd
)
213 unsigned long opt
= 0;
214 WSAEventSelect(fd
, NULL
, 0);
215 ioctlsocket(fd
, FIONBIO
, &opt
);
218 int qemu_try_set_nonblock(int fd
)
220 unsigned long opt
= 1;
221 if (ioctlsocket(fd
, FIONBIO
, &opt
) != NO_ERROR
) {
222 return -socket_error();
224 qemu_fd_register(fd
);
228 void qemu_set_nonblock(int fd
)
230 (void)qemu_try_set_nonblock(fd
);
233 int socket_set_fast_reuse(int fd
)
235 /* Enabling the reuse of an endpoint that was used by a socket still in
236 * TIME_WAIT state is usually performed by setting SO_REUSEADDR. On Windows
237 * fast reuse is the default and SO_REUSEADDR does strange things. So we
238 * don't have to do anything here. More info can be found at:
239 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621.aspx */
243 int inet_aton(const char *cp
, struct in_addr
*ia
)
245 uint32_t addr
= inet_addr(cp
);
246 if (addr
== 0xffffffff) {
253 void qemu_set_cloexec(int fd
)
257 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
258 #define _W32_FT_OFFSET (116444736000000000ULL)
260 int qemu_gettimeofday(qemu_timeval
*tp
)
263 unsigned long long ns100
; /*time since 1 Jan 1601 in 100ns units */
268 GetSystemTimeAsFileTime (&_now
.ft
);
269 tp
->tv_usec
=(long)((_now
.ns100
/ 10ULL) % 1000000ULL );
270 tp
->tv_sec
= (long)((_now
.ns100
- _W32_FT_OFFSET
) / 10000000ULL);
272 /* Always return 0 as per Open Group Base Specifications Issue 6.
273 Do not set errno on error. */
277 int qemu_get_thread_id(void)
279 return GetCurrentThreadId();
283 qemu_get_local_state_pathname(const char *relative_pathname
)
286 char base_path
[MAX_PATH
+1] = "";
288 result
= SHGetFolderPath(NULL
, CSIDL_COMMON_APPDATA
, NULL
,
289 /* SHGFP_TYPE_CURRENT */ 0, base_path
);
290 if (result
!= S_OK
) {
291 /* misconfigured environment */
292 g_critical("CSIDL_COMMON_APPDATA unavailable: %ld", (long)result
);
295 return g_strdup_printf("%s" G_DIR_SEPARATOR_S
"%s", base_path
,
299 void qemu_set_tty_echo(int fd
, bool echo
)
301 HANDLE handle
= (HANDLE
)_get_osfhandle(fd
);
304 if (handle
== INVALID_HANDLE_VALUE
) {
308 GetConsoleMode(handle
, &dwMode
);
311 SetConsoleMode(handle
, dwMode
| ENABLE_ECHO_INPUT
| ENABLE_LINE_INPUT
);
313 SetConsoleMode(handle
,
314 dwMode
& ~(ENABLE_ECHO_INPUT
| ENABLE_LINE_INPUT
));
318 static const char *exec_dir
;
320 void qemu_init_exec_dir(const char *argv0
)
331 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
338 while (p
!= buf
&& *p
!= '\\') {
342 if (access(buf
, R_OK
) == 0) {
343 exec_dir
= g_strdup(buf
);
345 exec_dir
= CONFIG_BINDIR
;
349 const char *qemu_get_exec_dir(void)
354 #if !GLIB_CHECK_VERSION(2, 50, 0)
356 * The original implementation of g_poll from glib has a problem on Windows
357 * when using timeouts < 10 ms.
359 * Whenever g_poll is called with timeout < 10 ms, it does a quick poll instead
360 * of wait. This causes significant performance degradation of QEMU.
362 * The following code is a copy of the original code from glib/gpoll.c
363 * (glib commit 20f4d1820b8d4d0fc4447188e33efffd6d4a88d8 from 2014-02-19).
364 * Some debug code was removed and the code was reformatted.
365 * All other code modifications are marked with 'QEMU'.
369 * gpoll.c: poll(2) abstraction
370 * Copyright 1998 Owen Taylor
371 * Copyright 2008 Red Hat, Inc.
373 * This library is free software; you can redistribute it and/or
374 * modify it under the terms of the GNU Lesser General Public
375 * License as published by the Free Software Foundation; either
376 * version 2 of the License, or (at your option) any later version.
378 * This library is distributed in the hope that it will be useful,
379 * but WITHOUT ANY WARRANTY; without even the implied warranty of
380 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
381 * Lesser General Public License for more details.
383 * You should have received a copy of the GNU Lesser General Public
384 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
387 static int poll_rest(gboolean poll_msgs
, HANDLE
*handles
, gint nhandles
,
388 GPollFD
*fds
, guint nfds
, gint timeout
)
395 /* Wait for either messages or handles
396 * -> Use MsgWaitForMultipleObjectsEx
398 ready
= MsgWaitForMultipleObjectsEx(nhandles
, handles
, timeout
,
399 QS_ALLINPUT
, MWMO_ALERTABLE
);
401 if (ready
== WAIT_FAILED
) {
402 gchar
*emsg
= g_win32_error_message(GetLastError());
403 g_warning("MsgWaitForMultipleObjectsEx failed: %s", emsg
);
406 } else if (nhandles
== 0) {
407 /* No handles to wait for, just the timeout */
408 if (timeout
== INFINITE
) {
411 SleepEx(timeout
, TRUE
);
412 ready
= WAIT_TIMEOUT
;
415 /* Wait for just handles
416 * -> Use WaitForMultipleObjectsEx
419 WaitForMultipleObjectsEx(nhandles
, handles
, FALSE
, timeout
, TRUE
);
420 if (ready
== WAIT_FAILED
) {
421 gchar
*emsg
= g_win32_error_message(GetLastError());
422 g_warning("WaitForMultipleObjectsEx failed: %s", emsg
);
427 if (ready
== WAIT_FAILED
) {
429 } else if (ready
== WAIT_TIMEOUT
|| ready
== WAIT_IO_COMPLETION
) {
431 } else if (poll_msgs
&& ready
== WAIT_OBJECT_0
+ nhandles
) {
432 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
433 if (f
->fd
== G_WIN32_MSG_HANDLE
&& f
->events
& G_IO_IN
) {
434 f
->revents
|= G_IO_IN
;
438 /* If we have a timeout, or no handles to poll, be satisfied
439 * with just noticing we have messages waiting.
441 if (timeout
!= 0 || nhandles
== 0) {
445 /* If no timeout and handles to poll, recurse to poll them,
448 recursed_result
= poll_rest(FALSE
, handles
, nhandles
, fds
, nfds
, 0);
449 return (recursed_result
== -1) ? -1 : 1 + recursed_result
;
450 } else if (/* QEMU: removed the following unneeded statement which causes
451 * a compiler warning: ready >= WAIT_OBJECT_0 && */
452 ready
< WAIT_OBJECT_0
+ nhandles
) {
453 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
454 if ((HANDLE
) f
->fd
== handles
[ready
- WAIT_OBJECT_0
]) {
455 f
->revents
= f
->events
;
459 /* If no timeout and polling several handles, recurse to poll
462 if (timeout
== 0 && nhandles
> 1) {
463 /* Remove the handle that fired */
465 for (i
= ready
- WAIT_OBJECT_0
+ 1; i
< nhandles
; i
++) {
466 handles
[i
-1] = handles
[i
];
469 recursed_result
= poll_rest(FALSE
, handles
, nhandles
, fds
, nfds
, 0);
470 return (recursed_result
== -1) ? -1 : 1 + recursed_result
;
478 gint
g_poll(GPollFD
*fds
, guint nfds
, gint timeout
)
480 HANDLE handles
[MAXIMUM_WAIT_OBJECTS
];
481 gboolean poll_msgs
= FALSE
;
486 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
487 if (f
->fd
== G_WIN32_MSG_HANDLE
&& (f
->events
& G_IO_IN
)) {
489 } else if (f
->fd
> 0) {
490 /* Don't add the same handle several times into the array, as
491 * docs say that is not allowed, even if it actually does seem
496 for (i
= 0; i
< nhandles
; i
++) {
497 if (handles
[i
] == (HANDLE
) f
->fd
) {
503 if (nhandles
== MAXIMUM_WAIT_OBJECTS
) {
504 g_warning("Too many handles to wait for!\n");
507 handles
[nhandles
++] = (HANDLE
) f
->fd
;
513 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
521 /* Polling for several things? */
522 if (nhandles
> 1 || (nhandles
> 0 && poll_msgs
)) {
523 /* First check if one or several of them are immediately
526 retval
= poll_rest(poll_msgs
, handles
, nhandles
, fds
, nfds
, 0);
528 /* If not, and we have a significant timeout, poll again with
529 * timeout then. Note that this will return indication for only
530 * one event, or only for messages. We ignore timeouts less than
531 * ten milliseconds as they are mostly pointless on Windows, the
532 * MsgWaitForMultipleObjectsEx() call will timeout right away
535 * Modification for QEMU: replaced timeout >= 10 by timeout > 0.
537 if (retval
== 0 && (timeout
== INFINITE
|| timeout
> 0)) {
538 retval
= poll_rest(poll_msgs
, handles
, nhandles
,
542 /* Just polling for one thing, so no need to check first if
543 * available immediately
545 retval
= poll_rest(poll_msgs
, handles
, nhandles
, fds
, nfds
, timeout
);
549 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
558 int getpagesize(void)
560 SYSTEM_INFO system_info
;
562 GetSystemInfo(&system_info
);
563 return system_info
.dwPageSize
;
566 void os_mem_prealloc(int fd
, char *area
, size_t memory
, int smp_cpus
,
570 size_t pagesize
= qemu_real_host_page_size
;
572 memory
= (memory
+ pagesize
- 1) & -pagesize
;
573 for (i
= 0; i
< memory
/ pagesize
; i
++) {
574 memset(area
+ pagesize
* i
, 0, 1);
578 char *qemu_get_pid_name(pid_t pid
)
580 /* XXX Implement me */
585 pid_t
qemu_fork(Error
**errp
)
588 error_setg_errno(errp
, errno
,
589 "cannot fork child process");
595 int qemu_connect_wrap(int sockfd
, const struct sockaddr
*addr
,
599 ret
= connect(sockfd
, addr
, addrlen
);
601 if (WSAGetLastError() == WSAEWOULDBLOCK
) {
604 errno
= socket_error();
612 int qemu_listen_wrap(int sockfd
, int backlog
)
615 ret
= listen(sockfd
, backlog
);
617 errno
= socket_error();
624 int qemu_bind_wrap(int sockfd
, const struct sockaddr
*addr
,
628 ret
= bind(sockfd
, addr
, addrlen
);
630 errno
= socket_error();
637 int qemu_socket_wrap(int domain
, int type
, int protocol
)
640 ret
= socket(domain
, type
, protocol
);
642 errno
= socket_error();
649 int qemu_accept_wrap(int sockfd
, struct sockaddr
*addr
,
653 ret
= accept(sockfd
, addr
, addrlen
);
655 errno
= socket_error();
662 int qemu_shutdown_wrap(int sockfd
, int how
)
665 ret
= shutdown(sockfd
, how
);
667 errno
= socket_error();
674 int qemu_ioctlsocket_wrap(int fd
, int req
, void *val
)
677 ret
= ioctlsocket(fd
, req
, val
);
679 errno
= socket_error();
686 int qemu_closesocket_wrap(int fd
)
689 ret
= closesocket(fd
);
691 errno
= socket_error();
698 int qemu_getsockopt_wrap(int sockfd
, int level
, int optname
,
699 void *optval
, socklen_t
*optlen
)
702 ret
= getsockopt(sockfd
, level
, optname
, optval
, optlen
);
704 errno
= socket_error();
711 int qemu_setsockopt_wrap(int sockfd
, int level
, int optname
,
712 const void *optval
, socklen_t optlen
)
715 ret
= setsockopt(sockfd
, level
, optname
, optval
, optlen
);
717 errno
= socket_error();
724 int qemu_getpeername_wrap(int sockfd
, struct sockaddr
*addr
,
728 ret
= getpeername(sockfd
, addr
, addrlen
);
730 errno
= socket_error();
737 int qemu_getsockname_wrap(int sockfd
, struct sockaddr
*addr
,
741 ret
= getsockname(sockfd
, addr
, addrlen
);
743 errno
= socket_error();
750 ssize_t
qemu_send_wrap(int sockfd
, const void *buf
, size_t len
, int flags
)
753 ret
= send(sockfd
, buf
, len
, flags
);
755 errno
= socket_error();
762 ssize_t
qemu_sendto_wrap(int sockfd
, const void *buf
, size_t len
, int flags
,
763 const struct sockaddr
*addr
, socklen_t addrlen
)
766 ret
= sendto(sockfd
, buf
, len
, flags
, addr
, addrlen
);
768 errno
= socket_error();
775 ssize_t
qemu_recv_wrap(int sockfd
, void *buf
, size_t len
, int flags
)
778 ret
= recv(sockfd
, buf
, len
, flags
);
780 errno
= socket_error();
787 ssize_t
qemu_recvfrom_wrap(int sockfd
, void *buf
, size_t len
, int flags
,
788 struct sockaddr
*addr
, socklen_t
*addrlen
)
791 ret
= recvfrom(sockfd
, buf
, len
, flags
, addr
, addrlen
);
793 errno
= socket_error();
798 bool qemu_write_pidfile(const char *filename
, Error
**errp
)
805 memset(&overlap
, 0, sizeof(overlap
));
807 file
= CreateFile(filename
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
808 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
810 if (file
== INVALID_HANDLE_VALUE
) {
811 error_setg(errp
, "Failed to create PID file");
814 len
= snprintf(buffer
, sizeof(buffer
), FMT_pid
"\n", (pid_t
)getpid());
815 ret
= WriteFile(file
, (LPCVOID
)buffer
, (DWORD
)len
,
819 error_setg(errp
, "Failed to write PID file");
825 char *qemu_get_host_name(Error
**errp
)
827 wchar_t tmp
[MAX_COMPUTERNAME_LENGTH
+ 1];
828 DWORD size
= G_N_ELEMENTS(tmp
);
830 if (GetComputerNameW(tmp
, &size
) == 0) {
831 error_setg_win32(errp
, GetLastError(), "failed close handle");
835 return g_utf16_to_utf8(tmp
, size
, NULL
, NULL
, NULL
);
838 size_t qemu_get_host_physmem(void)
840 MEMORYSTATUSEX statex
;
841 statex
.dwLength
= sizeof(statex
);
843 if (GlobalMemoryStatusEx(&statex
)) {
844 return statex
.ullTotalPhys
;