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"
44 /* this must come after including "trace.h" */
47 void *qemu_oom_check(void *ptr
)
50 fprintf(stderr
, "Failed to allocate memory: %lu\n", GetLastError());
56 void *qemu_try_memalign(size_t alignment
, size_t size
)
61 g_assert(is_power_of_2(alignment
));
62 ptr
= _aligned_malloc(size
, alignment
);
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
);
99 void qemu_anon_ram_free(void *ptr
, size_t size
)
101 trace_qemu_anon_ram_free(ptr
, size
);
103 VirtualFree(ptr
, 0, MEM_RELEASE
);
107 #ifndef _POSIX_THREAD_SAFE_FUNCTIONS
108 /* FIXME: add proper locking */
109 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
111 struct tm
*p
= gmtime(timep
);
112 memset(result
, 0, sizeof(*result
));
120 /* FIXME: add proper locking */
121 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
123 struct tm
*p
= localtime(timep
);
124 memset(result
, 0, sizeof(*result
));
131 #endif /* _POSIX_THREAD_SAFE_FUNCTIONS */
133 static int socket_error(void)
135 switch (WSAGetLastError()) {
142 case WSA_INVALID_HANDLE
:
144 case WSA_NOT_ENOUGH_MEMORY
:
146 case WSA_INVALID_PARAMETER
:
148 case WSAENAMETOOLONG
:
153 /* not using EWOULDBLOCK as we don't want code to have
154 * to check both EWOULDBLOCK and EAGAIN */
162 case WSAEDESTADDRREQ
:
170 case WSAEPROTONOSUPPORT
:
171 return EPROTONOSUPPORT
;
174 case WSAEAFNOSUPPORT
:
178 case WSAEADDRNOTAVAIL
:
179 return EADDRNOTAVAIL
;
186 case WSAECONNABORTED
:
198 case WSAECONNREFUSED
:
202 case WSAEHOSTUNREACH
:
209 void qemu_set_block(int fd
)
211 unsigned long opt
= 0;
212 WSAEventSelect(fd
, NULL
, 0);
213 ioctlsocket(fd
, FIONBIO
, &opt
);
216 int qemu_try_set_nonblock(int fd
)
218 unsigned long opt
= 1;
219 if (ioctlsocket(fd
, FIONBIO
, &opt
) != NO_ERROR
) {
220 return -socket_error();
225 void qemu_set_nonblock(int fd
)
227 (void)qemu_try_set_nonblock(fd
);
230 int socket_set_fast_reuse(int fd
)
232 /* Enabling the reuse of an endpoint that was used by a socket still in
233 * TIME_WAIT state is usually performed by setting SO_REUSEADDR. On Windows
234 * fast reuse is the default and SO_REUSEADDR does strange things. So we
235 * don't have to do anything here. More info can be found at:
236 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621.aspx */
240 int inet_aton(const char *cp
, struct in_addr
*ia
)
242 uint32_t addr
= inet_addr(cp
);
243 if (addr
== 0xffffffff) {
250 void qemu_set_cloexec(int fd
)
254 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
255 #define _W32_FT_OFFSET (116444736000000000ULL)
257 int qemu_gettimeofday(qemu_timeval
*tp
)
260 unsigned long long ns100
; /*time since 1 Jan 1601 in 100ns units */
265 GetSystemTimeAsFileTime (&_now
.ft
);
266 tp
->tv_usec
=(long)((_now
.ns100
/ 10ULL) % 1000000ULL );
267 tp
->tv_sec
= (long)((_now
.ns100
- _W32_FT_OFFSET
) / 10000000ULL);
269 /* Always return 0 as per Open Group Base Specifications Issue 6.
270 Do not set errno on error. */
274 int qemu_get_thread_id(void)
276 return GetCurrentThreadId();
280 qemu_get_local_state_pathname(const char *relative_pathname
)
283 char base_path
[MAX_PATH
+1] = "";
285 result
= SHGetFolderPath(NULL
, CSIDL_COMMON_APPDATA
, NULL
,
286 /* SHGFP_TYPE_CURRENT */ 0, base_path
);
287 if (result
!= S_OK
) {
288 /* misconfigured environment */
289 g_critical("CSIDL_COMMON_APPDATA unavailable: %ld", (long)result
);
292 return g_strdup_printf("%s" G_DIR_SEPARATOR_S
"%s", base_path
,
296 void qemu_set_tty_echo(int fd
, bool echo
)
298 HANDLE handle
= (HANDLE
)_get_osfhandle(fd
);
301 if (handle
== INVALID_HANDLE_VALUE
) {
305 GetConsoleMode(handle
, &dwMode
);
308 SetConsoleMode(handle
, dwMode
| ENABLE_ECHO_INPUT
| ENABLE_LINE_INPUT
);
310 SetConsoleMode(handle
,
311 dwMode
& ~(ENABLE_ECHO_INPUT
| ENABLE_LINE_INPUT
));
315 static const char *exec_dir
;
317 void qemu_init_exec_dir(const char *argv0
)
328 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
335 while (p
!= buf
&& *p
!= '\\') {
339 if (access(buf
, R_OK
) == 0) {
340 exec_dir
= g_strdup(buf
);
342 exec_dir
= CONFIG_BINDIR
;
346 const char *qemu_get_exec_dir(void)
351 #if !GLIB_CHECK_VERSION(2, 50, 0)
353 * The original implementation of g_poll from glib has a problem on Windows
354 * when using timeouts < 10 ms.
356 * Whenever g_poll is called with timeout < 10 ms, it does a quick poll instead
357 * of wait. This causes significant performance degradation of QEMU.
359 * The following code is a copy of the original code from glib/gpoll.c
360 * (glib commit 20f4d1820b8d4d0fc4447188e33efffd6d4a88d8 from 2014-02-19).
361 * Some debug code was removed and the code was reformatted.
362 * All other code modifications are marked with 'QEMU'.
366 * gpoll.c: poll(2) abstraction
367 * Copyright 1998 Owen Taylor
368 * Copyright 2008 Red Hat, Inc.
370 * This library is free software; you can redistribute it and/or
371 * modify it under the terms of the GNU Lesser General Public
372 * License as published by the Free Software Foundation; either
373 * version 2.1 of the License, or (at your option) any later version.
375 * This library is distributed in the hope that it will be useful,
376 * but WITHOUT ANY WARRANTY; without even the implied warranty of
377 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
378 * Lesser General Public License for more details.
380 * You should have received a copy of the GNU Lesser General Public
381 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
384 static int poll_rest(gboolean poll_msgs
, HANDLE
*handles
, gint nhandles
,
385 GPollFD
*fds
, guint nfds
, gint timeout
)
392 /* Wait for either messages or handles
393 * -> Use MsgWaitForMultipleObjectsEx
395 ready
= MsgWaitForMultipleObjectsEx(nhandles
, handles
, timeout
,
396 QS_ALLINPUT
, MWMO_ALERTABLE
);
398 if (ready
== WAIT_FAILED
) {
399 gchar
*emsg
= g_win32_error_message(GetLastError());
400 g_warning("MsgWaitForMultipleObjectsEx failed: %s", emsg
);
403 } else if (nhandles
== 0) {
404 /* No handles to wait for, just the timeout */
405 if (timeout
== INFINITE
) {
408 SleepEx(timeout
, TRUE
);
409 ready
= WAIT_TIMEOUT
;
412 /* Wait for just handles
413 * -> Use WaitForMultipleObjectsEx
416 WaitForMultipleObjectsEx(nhandles
, handles
, FALSE
, timeout
, TRUE
);
417 if (ready
== WAIT_FAILED
) {
418 gchar
*emsg
= g_win32_error_message(GetLastError());
419 g_warning("WaitForMultipleObjectsEx failed: %s", emsg
);
424 if (ready
== WAIT_FAILED
) {
426 } else if (ready
== WAIT_TIMEOUT
|| ready
== WAIT_IO_COMPLETION
) {
428 } else if (poll_msgs
&& ready
== WAIT_OBJECT_0
+ nhandles
) {
429 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
430 if (f
->fd
== G_WIN32_MSG_HANDLE
&& f
->events
& G_IO_IN
) {
431 f
->revents
|= G_IO_IN
;
435 /* If we have a timeout, or no handles to poll, be satisfied
436 * with just noticing we have messages waiting.
438 if (timeout
!= 0 || nhandles
== 0) {
442 /* If no timeout and handles to poll, recurse to poll them,
445 recursed_result
= poll_rest(FALSE
, handles
, nhandles
, fds
, nfds
, 0);
446 return (recursed_result
== -1) ? -1 : 1 + recursed_result
;
447 } else if (/* QEMU: removed the following unneeded statement which causes
448 * a compiler warning: ready >= WAIT_OBJECT_0 && */
449 ready
< WAIT_OBJECT_0
+ nhandles
) {
450 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
451 if ((HANDLE
) f
->fd
== handles
[ready
- WAIT_OBJECT_0
]) {
452 f
->revents
= f
->events
;
456 /* If no timeout and polling several handles, recurse to poll
459 if (timeout
== 0 && nhandles
> 1) {
460 /* Remove the handle that fired */
462 for (i
= ready
- WAIT_OBJECT_0
+ 1; i
< nhandles
; i
++) {
463 handles
[i
-1] = handles
[i
];
466 recursed_result
= poll_rest(FALSE
, handles
, nhandles
, fds
, nfds
, 0);
467 return (recursed_result
== -1) ? -1 : 1 + recursed_result
;
475 gint
g_poll(GPollFD
*fds
, guint nfds
, gint timeout
)
477 HANDLE handles
[MAXIMUM_WAIT_OBJECTS
];
478 gboolean poll_msgs
= FALSE
;
483 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
484 if (f
->fd
== G_WIN32_MSG_HANDLE
&& (f
->events
& G_IO_IN
)) {
486 } else if (f
->fd
> 0) {
487 /* Don't add the same handle several times into the array, as
488 * docs say that is not allowed, even if it actually does seem
493 for (i
= 0; i
< nhandles
; i
++) {
494 if (handles
[i
] == (HANDLE
) f
->fd
) {
500 if (nhandles
== MAXIMUM_WAIT_OBJECTS
) {
501 g_warning("Too many handles to wait for!\n");
504 handles
[nhandles
++] = (HANDLE
) f
->fd
;
510 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
518 /* Polling for several things? */
519 if (nhandles
> 1 || (nhandles
> 0 && poll_msgs
)) {
520 /* First check if one or several of them are immediately
523 retval
= poll_rest(poll_msgs
, handles
, nhandles
, fds
, nfds
, 0);
525 /* If not, and we have a significant timeout, poll again with
526 * timeout then. Note that this will return indication for only
527 * one event, or only for messages. We ignore timeouts less than
528 * ten milliseconds as they are mostly pointless on Windows, the
529 * MsgWaitForMultipleObjectsEx() call will timeout right away
532 * Modification for QEMU: replaced timeout >= 10 by timeout > 0.
534 if (retval
== 0 && (timeout
== INFINITE
|| timeout
> 0)) {
535 retval
= poll_rest(poll_msgs
, handles
, nhandles
,
539 /* Just polling for one thing, so no need to check first if
540 * available immediately
542 retval
= poll_rest(poll_msgs
, handles
, nhandles
, fds
, nfds
, timeout
);
546 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
555 int getpagesize(void)
557 SYSTEM_INFO system_info
;
559 GetSystemInfo(&system_info
);
560 return system_info
.dwPageSize
;
563 void os_mem_prealloc(int fd
, char *area
, size_t memory
, int smp_cpus
,
567 size_t pagesize
= qemu_real_host_page_size
;
569 memory
= (memory
+ pagesize
- 1) & -pagesize
;
570 for (i
= 0; i
< memory
/ pagesize
; i
++) {
571 memset(area
+ pagesize
* i
, 0, 1);
575 char *qemu_get_pid_name(pid_t pid
)
577 /* XXX Implement me */
582 pid_t
qemu_fork(Error
**errp
)
585 error_setg_errno(errp
, errno
,
586 "cannot fork child process");
592 int qemu_connect_wrap(int sockfd
, const struct sockaddr
*addr
,
596 ret
= connect(sockfd
, addr
, addrlen
);
598 if (WSAGetLastError() == WSAEWOULDBLOCK
) {
601 errno
= socket_error();
609 int qemu_listen_wrap(int sockfd
, int backlog
)
612 ret
= listen(sockfd
, backlog
);
614 errno
= socket_error();
621 int qemu_bind_wrap(int sockfd
, const struct sockaddr
*addr
,
625 ret
= bind(sockfd
, addr
, addrlen
);
627 errno
= socket_error();
634 int qemu_socket_wrap(int domain
, int type
, int protocol
)
637 ret
= socket(domain
, type
, protocol
);
639 errno
= socket_error();
646 int qemu_accept_wrap(int sockfd
, struct sockaddr
*addr
,
650 ret
= accept(sockfd
, addr
, addrlen
);
652 errno
= socket_error();
659 int qemu_shutdown_wrap(int sockfd
, int how
)
662 ret
= shutdown(sockfd
, how
);
664 errno
= socket_error();
671 int qemu_ioctlsocket_wrap(int fd
, int req
, void *val
)
674 ret
= ioctlsocket(fd
, req
, val
);
676 errno
= socket_error();
683 int qemu_closesocket_wrap(int fd
)
686 ret
= closesocket(fd
);
688 errno
= socket_error();
695 int qemu_getsockopt_wrap(int sockfd
, int level
, int optname
,
696 void *optval
, socklen_t
*optlen
)
699 ret
= getsockopt(sockfd
, level
, optname
, optval
, optlen
);
701 errno
= socket_error();
708 int qemu_setsockopt_wrap(int sockfd
, int level
, int optname
,
709 const void *optval
, socklen_t optlen
)
712 ret
= setsockopt(sockfd
, level
, optname
, optval
, optlen
);
714 errno
= socket_error();
721 int qemu_getpeername_wrap(int sockfd
, struct sockaddr
*addr
,
725 ret
= getpeername(sockfd
, addr
, addrlen
);
727 errno
= socket_error();
734 int qemu_getsockname_wrap(int sockfd
, struct sockaddr
*addr
,
738 ret
= getsockname(sockfd
, addr
, addrlen
);
740 errno
= socket_error();
747 ssize_t
qemu_send_wrap(int sockfd
, const void *buf
, size_t len
, int flags
)
750 ret
= send(sockfd
, buf
, len
, flags
);
752 errno
= socket_error();
759 ssize_t
qemu_sendto_wrap(int sockfd
, const void *buf
, size_t len
, int flags
,
760 const struct sockaddr
*addr
, socklen_t addrlen
)
763 ret
= sendto(sockfd
, buf
, len
, flags
, addr
, addrlen
);
765 errno
= socket_error();
772 ssize_t
qemu_recv_wrap(int sockfd
, void *buf
, size_t len
, int flags
)
775 ret
= recv(sockfd
, buf
, len
, flags
);
777 errno
= socket_error();
784 ssize_t
qemu_recvfrom_wrap(int sockfd
, void *buf
, size_t len
, int flags
,
785 struct sockaddr
*addr
, socklen_t
*addrlen
)
788 ret
= recvfrom(sockfd
, buf
, len
, flags
, addr
, addrlen
);
790 errno
= socket_error();
795 bool qemu_write_pidfile(const char *filename
, Error
**errp
)
802 memset(&overlap
, 0, sizeof(overlap
));
804 file
= CreateFile(filename
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
805 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
807 if (file
== INVALID_HANDLE_VALUE
) {
808 error_setg(errp
, "Failed to create PID file");
811 len
= snprintf(buffer
, sizeof(buffer
), FMT_pid
"\n", (pid_t
)getpid());
812 ret
= WriteFile(file
, (LPCVOID
)buffer
, (DWORD
)len
,
816 error_setg(errp
, "Failed to write PID file");
822 char *qemu_get_host_name(Error
**errp
)
824 wchar_t tmp
[MAX_COMPUTERNAME_LENGTH
+ 1];
825 DWORD size
= G_N_ELEMENTS(tmp
);
827 if (GetComputerNameW(tmp
, &size
) == 0) {
828 error_setg_win32(errp
, GetLastError(), "failed close handle");
832 return g_utf16_to_utf8(tmp
, size
, NULL
, NULL
, NULL
);
835 size_t qemu_get_host_physmem(void)
837 MEMORYSTATUSEX statex
;
838 statex
.dwLength
= sizeof(statex
);
840 if (GlobalMemoryStatusEx(&statex
)) {
841 return statex
.ullTotalPhys
;