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.
32 #include "qemu/osdep.h"
34 #include "qapi/error.h"
35 #include "sysemu/sysemu.h"
36 #include "qemu/main-loop.h"
38 #include "qemu/sockets.h"
39 #include "qemu/cutils.h"
41 /* this must come after including "trace.h" */
44 void *qemu_oom_check(void *ptr
)
47 fprintf(stderr
, "Failed to allocate memory: %lu\n", GetLastError());
53 void *qemu_try_memalign(size_t alignment
, size_t size
)
60 ptr
= VirtualAlloc(NULL
, size
, MEM_COMMIT
, PAGE_READWRITE
);
61 trace_qemu_memalign(alignment
, size
, ptr
);
65 void *qemu_memalign(size_t alignment
, size_t size
)
67 return qemu_oom_check(qemu_try_memalign(alignment
, size
));
70 static int get_allocation_granularity(void)
72 SYSTEM_INFO system_info
;
74 GetSystemInfo(&system_info
);
75 return system_info
.dwAllocationGranularity
;
78 void *qemu_anon_ram_alloc(size_t size
, uint64_t *align
, bool shared
)
82 ptr
= VirtualAlloc(NULL
, size
, MEM_COMMIT
, PAGE_READWRITE
);
83 trace_qemu_anon_ram_alloc(size
, ptr
);
86 *align
= MAX(get_allocation_granularity(), getpagesize());
91 void qemu_vfree(void *ptr
)
93 trace_qemu_vfree(ptr
);
95 VirtualFree(ptr
, 0, MEM_RELEASE
);
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 CONFIG_LOCALTIME_R
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 /* CONFIG_LOCALTIME_R */
133 void qemu_set_block(int fd
)
135 unsigned long opt
= 0;
136 WSAEventSelect(fd
, NULL
, 0);
137 ioctlsocket(fd
, FIONBIO
, &opt
);
140 void qemu_set_nonblock(int fd
)
142 unsigned long opt
= 1;
143 ioctlsocket(fd
, FIONBIO
, &opt
);
144 qemu_fd_register(fd
);
147 int socket_set_fast_reuse(int fd
)
149 /* Enabling the reuse of an endpoint that was used by a socket still in
150 * TIME_WAIT state is usually performed by setting SO_REUSEADDR. On Windows
151 * fast reuse is the default and SO_REUSEADDR does strange things. So we
152 * don't have to do anything here. More info can be found at:
153 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621.aspx */
158 static int socket_error(void)
160 switch (WSAGetLastError()) {
167 case WSA_INVALID_HANDLE
:
169 case WSA_NOT_ENOUGH_MEMORY
:
171 case WSA_INVALID_PARAMETER
:
173 case WSAENAMETOOLONG
:
178 /* not using EWOULDBLOCK as we don't want code to have
179 * to check both EWOULDBLOCK and EAGAIN */
187 case WSAEDESTADDRREQ
:
195 case WSAEPROTONOSUPPORT
:
196 return EPROTONOSUPPORT
;
199 case WSAEAFNOSUPPORT
:
203 case WSAEADDRNOTAVAIL
:
204 return EADDRNOTAVAIL
;
211 case WSAECONNABORTED
:
223 case WSAECONNREFUSED
:
227 case WSAEHOSTUNREACH
:
234 int inet_aton(const char *cp
, struct in_addr
*ia
)
236 uint32_t addr
= inet_addr(cp
);
237 if (addr
== 0xffffffff) {
244 void qemu_set_cloexec(int fd
)
248 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
249 #define _W32_FT_OFFSET (116444736000000000ULL)
251 int qemu_gettimeofday(qemu_timeval
*tp
)
254 unsigned long long ns100
; /*time since 1 Jan 1601 in 100ns units */
259 GetSystemTimeAsFileTime (&_now
.ft
);
260 tp
->tv_usec
=(long)((_now
.ns100
/ 10ULL) % 1000000ULL );
261 tp
->tv_sec
= (long)((_now
.ns100
- _W32_FT_OFFSET
) / 10000000ULL);
263 /* Always return 0 as per Open Group Base Specifications Issue 6.
264 Do not set errno on error. */
268 int qemu_get_thread_id(void)
270 return GetCurrentThreadId();
274 qemu_get_local_state_pathname(const char *relative_pathname
)
277 char base_path
[MAX_PATH
+1] = "";
279 result
= SHGetFolderPath(NULL
, CSIDL_COMMON_APPDATA
, NULL
,
280 /* SHGFP_TYPE_CURRENT */ 0, base_path
);
281 if (result
!= S_OK
) {
282 /* misconfigured environment */
283 g_critical("CSIDL_COMMON_APPDATA unavailable: %ld", (long)result
);
286 return g_strdup_printf("%s" G_DIR_SEPARATOR_S
"%s", base_path
,
290 void qemu_set_tty_echo(int fd
, bool echo
)
292 HANDLE handle
= (HANDLE
)_get_osfhandle(fd
);
295 if (handle
== INVALID_HANDLE_VALUE
) {
299 GetConsoleMode(handle
, &dwMode
);
302 SetConsoleMode(handle
, dwMode
| ENABLE_ECHO_INPUT
| ENABLE_LINE_INPUT
);
304 SetConsoleMode(handle
,
305 dwMode
& ~(ENABLE_ECHO_INPUT
| ENABLE_LINE_INPUT
));
309 static char exec_dir
[PATH_MAX
];
311 void qemu_init_exec_dir(const char *argv0
)
318 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
325 while (p
!= buf
&& *p
!= '\\') {
329 if (access(buf
, R_OK
) == 0) {
330 pstrcpy(exec_dir
, sizeof(exec_dir
), buf
);
334 char *qemu_get_exec_dir(void)
336 return g_strdup(exec_dir
);
339 #if !GLIB_CHECK_VERSION(2, 50, 0)
341 * The original implementation of g_poll from glib has a problem on Windows
342 * when using timeouts < 10 ms.
344 * Whenever g_poll is called with timeout < 10 ms, it does a quick poll instead
345 * of wait. This causes significant performance degradation of QEMU.
347 * The following code is a copy of the original code from glib/gpoll.c
348 * (glib commit 20f4d1820b8d4d0fc4447188e33efffd6d4a88d8 from 2014-02-19).
349 * Some debug code was removed and the code was reformatted.
350 * All other code modifications are marked with 'QEMU'.
354 * gpoll.c: poll(2) abstraction
355 * Copyright 1998 Owen Taylor
356 * Copyright 2008 Red Hat, Inc.
358 * This library is free software; you can redistribute it and/or
359 * modify it under the terms of the GNU Lesser General Public
360 * License as published by the Free Software Foundation; either
361 * version 2 of the License, or (at your option) any later version.
363 * This library is distributed in the hope that it will be useful,
364 * but WITHOUT ANY WARRANTY; without even the implied warranty of
365 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
366 * Lesser General Public License for more details.
368 * You should have received a copy of the GNU Lesser General Public
369 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
372 static int poll_rest(gboolean poll_msgs
, HANDLE
*handles
, gint nhandles
,
373 GPollFD
*fds
, guint nfds
, gint timeout
)
380 /* Wait for either messages or handles
381 * -> Use MsgWaitForMultipleObjectsEx
383 ready
= MsgWaitForMultipleObjectsEx(nhandles
, handles
, timeout
,
384 QS_ALLINPUT
, MWMO_ALERTABLE
);
386 if (ready
== WAIT_FAILED
) {
387 gchar
*emsg
= g_win32_error_message(GetLastError());
388 g_warning("MsgWaitForMultipleObjectsEx failed: %s", emsg
);
391 } else if (nhandles
== 0) {
392 /* No handles to wait for, just the timeout */
393 if (timeout
== INFINITE
) {
396 SleepEx(timeout
, TRUE
);
397 ready
= WAIT_TIMEOUT
;
400 /* Wait for just handles
401 * -> Use WaitForMultipleObjectsEx
404 WaitForMultipleObjectsEx(nhandles
, handles
, FALSE
, timeout
, TRUE
);
405 if (ready
== WAIT_FAILED
) {
406 gchar
*emsg
= g_win32_error_message(GetLastError());
407 g_warning("WaitForMultipleObjectsEx failed: %s", emsg
);
412 if (ready
== WAIT_FAILED
) {
414 } else if (ready
== WAIT_TIMEOUT
|| ready
== WAIT_IO_COMPLETION
) {
416 } else if (poll_msgs
&& ready
== WAIT_OBJECT_0
+ nhandles
) {
417 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
418 if (f
->fd
== G_WIN32_MSG_HANDLE
&& f
->events
& G_IO_IN
) {
419 f
->revents
|= G_IO_IN
;
423 /* If we have a timeout, or no handles to poll, be satisfied
424 * with just noticing we have messages waiting.
426 if (timeout
!= 0 || nhandles
== 0) {
430 /* If no timeout and handles to poll, recurse to poll them,
433 recursed_result
= poll_rest(FALSE
, handles
, nhandles
, fds
, nfds
, 0);
434 return (recursed_result
== -1) ? -1 : 1 + recursed_result
;
435 } else if (/* QEMU: removed the following unneeded statement which causes
436 * a compiler warning: ready >= WAIT_OBJECT_0 && */
437 ready
< WAIT_OBJECT_0
+ nhandles
) {
438 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
439 if ((HANDLE
) f
->fd
== handles
[ready
- WAIT_OBJECT_0
]) {
440 f
->revents
= f
->events
;
444 /* If no timeout and polling several handles, recurse to poll
447 if (timeout
== 0 && nhandles
> 1) {
448 /* Remove the handle that fired */
450 for (i
= ready
- WAIT_OBJECT_0
+ 1; i
< nhandles
; i
++) {
451 handles
[i
-1] = handles
[i
];
454 recursed_result
= poll_rest(FALSE
, handles
, nhandles
, fds
, nfds
, 0);
455 return (recursed_result
== -1) ? -1 : 1 + recursed_result
;
463 gint
g_poll(GPollFD
*fds
, guint nfds
, gint timeout
)
465 HANDLE handles
[MAXIMUM_WAIT_OBJECTS
];
466 gboolean poll_msgs
= FALSE
;
471 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
472 if (f
->fd
== G_WIN32_MSG_HANDLE
&& (f
->events
& G_IO_IN
)) {
474 } else if (f
->fd
> 0) {
475 /* Don't add the same handle several times into the array, as
476 * docs say that is not allowed, even if it actually does seem
481 for (i
= 0; i
< nhandles
; i
++) {
482 if (handles
[i
] == (HANDLE
) f
->fd
) {
488 if (nhandles
== MAXIMUM_WAIT_OBJECTS
) {
489 g_warning("Too many handles to wait for!\n");
492 handles
[nhandles
++] = (HANDLE
) f
->fd
;
498 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
506 /* Polling for several things? */
507 if (nhandles
> 1 || (nhandles
> 0 && poll_msgs
)) {
508 /* First check if one or several of them are immediately
511 retval
= poll_rest(poll_msgs
, handles
, nhandles
, fds
, nfds
, 0);
513 /* If not, and we have a significant timeout, poll again with
514 * timeout then. Note that this will return indication for only
515 * one event, or only for messages. We ignore timeouts less than
516 * ten milliseconds as they are mostly pointless on Windows, the
517 * MsgWaitForMultipleObjectsEx() call will timeout right away
520 * Modification for QEMU: replaced timeout >= 10 by timeout > 0.
522 if (retval
== 0 && (timeout
== INFINITE
|| timeout
> 0)) {
523 retval
= poll_rest(poll_msgs
, handles
, nhandles
,
527 /* Just polling for one thing, so no need to check first if
528 * available immediately
530 retval
= poll_rest(poll_msgs
, handles
, nhandles
, fds
, nfds
, timeout
);
534 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
543 int getpagesize(void)
545 SYSTEM_INFO system_info
;
547 GetSystemInfo(&system_info
);
548 return system_info
.dwPageSize
;
551 void os_mem_prealloc(int fd
, char *area
, size_t memory
, int smp_cpus
,
555 size_t pagesize
= getpagesize();
557 memory
= (memory
+ pagesize
- 1) & -pagesize
;
558 for (i
= 0; i
< memory
/ pagesize
; i
++) {
559 memset(area
+ pagesize
* i
, 0, 1);
564 char *qemu_get_pid_name(pid_t pid
)
566 /* XXX Implement me */
571 pid_t
qemu_fork(Error
**errp
)
574 error_setg_errno(errp
, errno
,
575 "cannot fork child process");
581 int qemu_connect_wrap(int sockfd
, const struct sockaddr
*addr
,
585 ret
= connect(sockfd
, addr
, addrlen
);
587 errno
= socket_error();
594 int qemu_listen_wrap(int sockfd
, int backlog
)
597 ret
= listen(sockfd
, backlog
);
599 errno
= socket_error();
606 int qemu_bind_wrap(int sockfd
, const struct sockaddr
*addr
,
610 ret
= bind(sockfd
, addr
, addrlen
);
612 errno
= socket_error();
619 int qemu_socket_wrap(int domain
, int type
, int protocol
)
622 ret
= socket(domain
, type
, protocol
);
624 errno
= socket_error();
631 int qemu_accept_wrap(int sockfd
, struct sockaddr
*addr
,
635 ret
= accept(sockfd
, addr
, addrlen
);
637 errno
= socket_error();
644 int qemu_shutdown_wrap(int sockfd
, int how
)
647 ret
= shutdown(sockfd
, how
);
649 errno
= socket_error();
656 int qemu_ioctlsocket_wrap(int fd
, int req
, void *val
)
659 ret
= ioctlsocket(fd
, req
, val
);
661 errno
= socket_error();
668 int qemu_closesocket_wrap(int fd
)
671 ret
= closesocket(fd
);
673 errno
= socket_error();
680 int qemu_getsockopt_wrap(int sockfd
, int level
, int optname
,
681 void *optval
, socklen_t
*optlen
)
684 ret
= getsockopt(sockfd
, level
, optname
, optval
, optlen
);
686 errno
= socket_error();
693 int qemu_setsockopt_wrap(int sockfd
, int level
, int optname
,
694 const void *optval
, socklen_t optlen
)
697 ret
= setsockopt(sockfd
, level
, optname
, optval
, optlen
);
699 errno
= socket_error();
706 int qemu_getpeername_wrap(int sockfd
, struct sockaddr
*addr
,
710 ret
= getpeername(sockfd
, addr
, addrlen
);
712 errno
= socket_error();
719 int qemu_getsockname_wrap(int sockfd
, struct sockaddr
*addr
,
723 ret
= getsockname(sockfd
, addr
, addrlen
);
725 errno
= socket_error();
732 ssize_t
qemu_send_wrap(int sockfd
, const void *buf
, size_t len
, int flags
)
735 ret
= send(sockfd
, buf
, len
, flags
);
737 errno
= socket_error();
744 ssize_t
qemu_sendto_wrap(int sockfd
, const void *buf
, size_t len
, int flags
,
745 const struct sockaddr
*addr
, socklen_t addrlen
)
748 ret
= sendto(sockfd
, buf
, len
, flags
, addr
, addrlen
);
750 errno
= socket_error();
757 ssize_t
qemu_recv_wrap(int sockfd
, void *buf
, size_t len
, int flags
)
760 ret
= recv(sockfd
, buf
, len
, flags
);
762 errno
= socket_error();
769 ssize_t
qemu_recvfrom_wrap(int sockfd
, void *buf
, size_t len
, int flags
,
770 struct sockaddr
*addr
, socklen_t
*addrlen
)
773 ret
= recvfrom(sockfd
, buf
, len
, flags
, addr
, addrlen
);
775 errno
= socket_error();