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"
35 #include "sysemu/sysemu.h"
36 #include "qemu/main-loop.h"
38 #include "qemu/sockets.h"
40 /* this must come after including "trace.h" */
43 void *qemu_oom_check(void *ptr
)
46 fprintf(stderr
, "Failed to allocate memory: %lu\n", GetLastError());
52 void *qemu_try_memalign(size_t alignment
, size_t size
)
59 ptr
= VirtualAlloc(NULL
, size
, MEM_COMMIT
, PAGE_READWRITE
);
60 trace_qemu_memalign(alignment
, size
, ptr
);
64 void *qemu_memalign(size_t alignment
, size_t size
)
66 return qemu_oom_check(qemu_try_memalign(alignment
, size
));
69 void *qemu_anon_ram_alloc(size_t size
, uint64_t *align
)
73 /* FIXME: this is not exactly optimal solution since VirtualAlloc
74 has 64Kb granularity, but at least it guarantees us that the
75 memory is page aligned. */
76 ptr
= VirtualAlloc(NULL
, size
, MEM_COMMIT
, PAGE_READWRITE
);
77 trace_qemu_anon_ram_alloc(size
, ptr
);
81 void qemu_vfree(void *ptr
)
83 trace_qemu_vfree(ptr
);
85 VirtualFree(ptr
, 0, MEM_RELEASE
);
89 void qemu_anon_ram_free(void *ptr
, size_t size
)
91 trace_qemu_anon_ram_free(ptr
, size
);
93 VirtualFree(ptr
, 0, MEM_RELEASE
);
97 #ifndef CONFIG_LOCALTIME_R
98 /* FIXME: add proper locking */
99 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
101 struct tm
*p
= gmtime(timep
);
102 memset(result
, 0, sizeof(*result
));
110 /* FIXME: add proper locking */
111 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
113 struct tm
*p
= localtime(timep
);
114 memset(result
, 0, sizeof(*result
));
121 #endif /* CONFIG_LOCALTIME_R */
123 void qemu_set_block(int fd
)
125 unsigned long opt
= 0;
126 WSAEventSelect(fd
, NULL
, 0);
127 ioctlsocket(fd
, FIONBIO
, &opt
);
130 void qemu_set_nonblock(int fd
)
132 unsigned long opt
= 1;
133 ioctlsocket(fd
, FIONBIO
, &opt
);
134 qemu_fd_register(fd
);
137 int socket_set_fast_reuse(int fd
)
139 /* Enabling the reuse of an endpoint that was used by a socket still in
140 * TIME_WAIT state is usually performed by setting SO_REUSEADDR. On Windows
141 * fast reuse is the default and SO_REUSEADDR does strange things. So we
142 * don't have to do anything here. More info can be found at:
143 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621.aspx */
148 static int socket_error(void)
150 switch (WSAGetLastError()) {
157 case WSA_INVALID_HANDLE
:
159 case WSA_NOT_ENOUGH_MEMORY
:
161 case WSA_INVALID_PARAMETER
:
163 case WSAENAMETOOLONG
:
168 /* not using EWOULDBLOCK as we don't want code to have
169 * to check both EWOULDBLOCK and EAGAIN */
177 case WSAEDESTADDRREQ
:
185 case WSAEPROTONOSUPPORT
:
186 return EPROTONOSUPPORT
;
189 case WSAEAFNOSUPPORT
:
193 case WSAEADDRNOTAVAIL
:
194 return EADDRNOTAVAIL
;
201 case WSAECONNABORTED
:
213 case WSAECONNREFUSED
:
217 case WSAEHOSTUNREACH
:
224 int inet_aton(const char *cp
, struct in_addr
*ia
)
226 uint32_t addr
= inet_addr(cp
);
227 if (addr
== 0xffffffff) {
234 void qemu_set_cloexec(int fd
)
238 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
239 #define _W32_FT_OFFSET (116444736000000000ULL)
241 int qemu_gettimeofday(qemu_timeval
*tp
)
244 unsigned long long ns100
; /*time since 1 Jan 1601 in 100ns units */
249 GetSystemTimeAsFileTime (&_now
.ft
);
250 tp
->tv_usec
=(long)((_now
.ns100
/ 10ULL) % 1000000ULL );
251 tp
->tv_sec
= (long)((_now
.ns100
- _W32_FT_OFFSET
) / 10000000ULL);
253 /* Always return 0 as per Open Group Base Specifications Issue 6.
254 Do not set errno on error. */
258 int qemu_get_thread_id(void)
260 return GetCurrentThreadId();
264 qemu_get_local_state_pathname(const char *relative_pathname
)
267 char base_path
[MAX_PATH
+1] = "";
269 result
= SHGetFolderPath(NULL
, CSIDL_COMMON_APPDATA
, NULL
,
270 /* SHGFP_TYPE_CURRENT */ 0, base_path
);
271 if (result
!= S_OK
) {
272 /* misconfigured environment */
273 g_critical("CSIDL_COMMON_APPDATA unavailable: %ld", (long)result
);
276 return g_strdup_printf("%s" G_DIR_SEPARATOR_S
"%s", base_path
,
280 void qemu_set_tty_echo(int fd
, bool echo
)
282 HANDLE handle
= (HANDLE
)_get_osfhandle(fd
);
285 if (handle
== INVALID_HANDLE_VALUE
) {
289 GetConsoleMode(handle
, &dwMode
);
292 SetConsoleMode(handle
, dwMode
| ENABLE_ECHO_INPUT
| ENABLE_LINE_INPUT
);
294 SetConsoleMode(handle
,
295 dwMode
& ~(ENABLE_ECHO_INPUT
| ENABLE_LINE_INPUT
));
299 static char exec_dir
[PATH_MAX
];
301 void qemu_init_exec_dir(const char *argv0
)
308 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
315 while (p
!= buf
&& *p
!= '\\') {
319 if (access(buf
, R_OK
) == 0) {
320 pstrcpy(exec_dir
, sizeof(exec_dir
), buf
);
324 char *qemu_get_exec_dir(void)
326 return g_strdup(exec_dir
);
330 * The original implementation of g_poll from glib has a problem on Windows
331 * when using timeouts < 10 ms.
333 * Whenever g_poll is called with timeout < 10 ms, it does a quick poll instead
334 * of wait. This causes significant performance degradation of QEMU.
336 * The following code is a copy of the original code from glib/gpoll.c
337 * (glib commit 20f4d1820b8d4d0fc4447188e33efffd6d4a88d8 from 2014-02-19).
338 * Some debug code was removed and the code was reformatted.
339 * All other code modifications are marked with 'QEMU'.
343 * gpoll.c: poll(2) abstraction
344 * Copyright 1998 Owen Taylor
345 * Copyright 2008 Red Hat, Inc.
347 * This library is free software; you can redistribute it and/or
348 * modify it under the terms of the GNU Lesser General Public
349 * License as published by the Free Software Foundation; either
350 * version 2 of the License, or (at your option) any later version.
352 * This library is distributed in the hope that it will be useful,
353 * but WITHOUT ANY WARRANTY; without even the implied warranty of
354 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
355 * Lesser General Public License for more details.
357 * You should have received a copy of the GNU Lesser General Public
358 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
361 static int poll_rest(gboolean poll_msgs
, HANDLE
*handles
, gint nhandles
,
362 GPollFD
*fds
, guint nfds
, gint timeout
)
369 /* Wait for either messages or handles
370 * -> Use MsgWaitForMultipleObjectsEx
372 ready
= MsgWaitForMultipleObjectsEx(nhandles
, handles
, timeout
,
373 QS_ALLINPUT
, MWMO_ALERTABLE
);
375 if (ready
== WAIT_FAILED
) {
376 gchar
*emsg
= g_win32_error_message(GetLastError());
377 g_warning("MsgWaitForMultipleObjectsEx failed: %s", emsg
);
380 } else if (nhandles
== 0) {
381 /* No handles to wait for, just the timeout */
382 if (timeout
== INFINITE
) {
385 SleepEx(timeout
, TRUE
);
386 ready
= WAIT_TIMEOUT
;
389 /* Wait for just handles
390 * -> Use WaitForMultipleObjectsEx
393 WaitForMultipleObjectsEx(nhandles
, handles
, FALSE
, timeout
, TRUE
);
394 if (ready
== WAIT_FAILED
) {
395 gchar
*emsg
= g_win32_error_message(GetLastError());
396 g_warning("WaitForMultipleObjectsEx failed: %s", emsg
);
401 if (ready
== WAIT_FAILED
) {
403 } else if (ready
== WAIT_TIMEOUT
|| ready
== WAIT_IO_COMPLETION
) {
405 } else if (poll_msgs
&& ready
== WAIT_OBJECT_0
+ nhandles
) {
406 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
407 if (f
->fd
== G_WIN32_MSG_HANDLE
&& f
->events
& G_IO_IN
) {
408 f
->revents
|= G_IO_IN
;
412 /* If we have a timeout, or no handles to poll, be satisfied
413 * with just noticing we have messages waiting.
415 if (timeout
!= 0 || nhandles
== 0) {
419 /* If no timeout and handles to poll, recurse to poll them,
422 recursed_result
= poll_rest(FALSE
, handles
, nhandles
, fds
, nfds
, 0);
423 return (recursed_result
== -1) ? -1 : 1 + recursed_result
;
424 } else if (/* QEMU: removed the following unneeded statement which causes
425 * a compiler warning: ready >= WAIT_OBJECT_0 && */
426 ready
< WAIT_OBJECT_0
+ nhandles
) {
427 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
428 if ((HANDLE
) f
->fd
== handles
[ready
- WAIT_OBJECT_0
]) {
429 f
->revents
= f
->events
;
433 /* If no timeout and polling several handles, recurse to poll
436 if (timeout
== 0 && nhandles
> 1) {
437 /* Remove the handle that fired */
439 if (ready
< nhandles
- 1) {
440 for (i
= ready
- WAIT_OBJECT_0
+ 1; i
< nhandles
; i
++) {
441 handles
[i
-1] = handles
[i
];
445 recursed_result
= poll_rest(FALSE
, handles
, nhandles
, fds
, nfds
, 0);
446 return (recursed_result
== -1) ? -1 : 1 + recursed_result
;
454 gint
g_poll(GPollFD
*fds
, guint nfds
, gint timeout
)
456 HANDLE handles
[MAXIMUM_WAIT_OBJECTS
];
457 gboolean poll_msgs
= FALSE
;
462 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
463 if (f
->fd
== G_WIN32_MSG_HANDLE
&& (f
->events
& G_IO_IN
)) {
465 } else if (f
->fd
> 0) {
466 /* Don't add the same handle several times into the array, as
467 * docs say that is not allowed, even if it actually does seem
472 for (i
= 0; i
< nhandles
; i
++) {
473 if (handles
[i
] == (HANDLE
) f
->fd
) {
479 if (nhandles
== MAXIMUM_WAIT_OBJECTS
) {
480 g_warning("Too many handles to wait for!\n");
483 handles
[nhandles
++] = (HANDLE
) f
->fd
;
489 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
497 /* Polling for several things? */
498 if (nhandles
> 1 || (nhandles
> 0 && poll_msgs
)) {
499 /* First check if one or several of them are immediately
502 retval
= poll_rest(poll_msgs
, handles
, nhandles
, fds
, nfds
, 0);
504 /* If not, and we have a significant timeout, poll again with
505 * timeout then. Note that this will return indication for only
506 * one event, or only for messages. We ignore timeouts less than
507 * ten milliseconds as they are mostly pointless on Windows, the
508 * MsgWaitForMultipleObjectsEx() call will timeout right away
511 * Modification for QEMU: replaced timeout >= 10 by timeout > 0.
513 if (retval
== 0 && (timeout
== INFINITE
|| timeout
> 0)) {
514 retval
= poll_rest(poll_msgs
, handles
, nhandles
,
518 /* Just polling for one thing, so no need to check first if
519 * available immediately
521 retval
= poll_rest(poll_msgs
, handles
, nhandles
, fds
, nfds
, timeout
);
525 for (f
= fds
; f
< &fds
[nfds
]; ++f
) {
533 int getpagesize(void)
535 SYSTEM_INFO system_info
;
537 GetSystemInfo(&system_info
);
538 return system_info
.dwPageSize
;
541 void os_mem_prealloc(int fd
, char *area
, size_t memory
)
544 size_t pagesize
= getpagesize();
546 memory
= (memory
+ pagesize
- 1) & -pagesize
;
547 for (i
= 0; i
< memory
/ pagesize
; i
++) {
548 memset(area
+ pagesize
* i
, 0, 1);
553 /* XXX: put correct support for win32 */
554 int qemu_read_password(char *buf
, int buf_size
)
558 printf("Password: ");
566 } else if (c
== '\n') {
568 } else if (i
< (buf_size
- 1)) {
577 pid_t
qemu_fork(Error
**errp
)
580 error_setg_errno(errp
, errno
,
581 "cannot fork child process");
587 int qemu_connect_wrap(int sockfd
, const struct sockaddr
*addr
,
591 ret
= connect(sockfd
, addr
, addrlen
);
593 errno
= socket_error();
600 int qemu_listen_wrap(int sockfd
, int backlog
)
603 ret
= listen(sockfd
, backlog
);
605 errno
= socket_error();
612 int qemu_bind_wrap(int sockfd
, const struct sockaddr
*addr
,
616 ret
= bind(sockfd
, addr
, addrlen
);
618 errno
= socket_error();
625 int qemu_socket_wrap(int domain
, int type
, int protocol
)
628 ret
= socket(domain
, type
, protocol
);
630 errno
= socket_error();
637 int qemu_accept_wrap(int sockfd
, struct sockaddr
*addr
,
641 ret
= accept(sockfd
, addr
, addrlen
);
643 errno
= socket_error();
650 int qemu_shutdown_wrap(int sockfd
, int how
)
653 ret
= shutdown(sockfd
, how
);
655 errno
= socket_error();
662 int qemu_ioctlsocket_wrap(int fd
, int req
, void *val
)
665 ret
= ioctlsocket(fd
, req
, val
);
667 errno
= socket_error();
674 int qemu_closesocket_wrap(int fd
)
677 ret
= closesocket(fd
);
679 errno
= socket_error();
686 int qemu_getsockopt_wrap(int sockfd
, int level
, int optname
,
687 void *optval
, socklen_t
*optlen
)
690 ret
= getsockopt(sockfd
, level
, optname
, optval
, optlen
);
692 errno
= socket_error();
699 int qemu_setsockopt_wrap(int sockfd
, int level
, int optname
,
700 const void *optval
, socklen_t optlen
)
703 ret
= setsockopt(sockfd
, level
, optname
, optval
, optlen
);
705 errno
= socket_error();
712 int qemu_getpeername_wrap(int sockfd
, struct sockaddr
*addr
,
716 ret
= getpeername(sockfd
, addr
, addrlen
);
718 errno
= socket_error();
725 int qemu_getsockname_wrap(int sockfd
, struct sockaddr
*addr
,
729 ret
= getsockname(sockfd
, addr
, addrlen
);
731 errno
= socket_error();
738 ssize_t
qemu_send_wrap(int sockfd
, const void *buf
, size_t len
, int flags
)
741 ret
= send(sockfd
, buf
, len
, flags
);
743 errno
= socket_error();
750 ssize_t
qemu_sendto_wrap(int sockfd
, const void *buf
, size_t len
, int flags
,
751 const struct sockaddr
*addr
, socklen_t addrlen
)
754 ret
= sendto(sockfd
, buf
, len
, flags
, addr
, addrlen
);
756 errno
= socket_error();
763 ssize_t
qemu_recv_wrap(int sockfd
, void *buf
, size_t len
, int flags
)
766 ret
= recv(sockfd
, buf
, len
, flags
);
768 errno
= socket_error();
775 ssize_t
qemu_recvfrom_wrap(int sockfd
, void *buf
, size_t len
, int flags
,
776 struct sockaddr
*addr
, socklen_t
*addrlen
)
779 ret
= recvfrom(sockfd
, buf
, len
, flags
, addr
, addrlen
);
781 errno
= socket_error();