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
29 #include "qemu/osdep.h"
31 #include "qapi/error.h"
32 #include "qemu/main-loop.h"
34 #include "qemu/sockets.h"
35 #include "qemu/cutils.h"
36 #include "qemu/error-report.h"
39 static int get_allocation_granularity(void)
41 SYSTEM_INFO system_info
;
43 GetSystemInfo(&system_info
);
44 return system_info
.dwAllocationGranularity
;
47 void *qemu_anon_ram_alloc(size_t size
, uint64_t *align
, bool shared
,
54 * We need a MEM_COMMIT before accessing any memory in a MEM_RESERVE
55 * area; we cannot easily mimic POSIX MAP_NORESERVE semantics.
57 error_report("Skipping reservation of swap space is not supported.");
61 ptr
= VirtualAlloc(NULL
, size
, MEM_COMMIT
, PAGE_READWRITE
);
62 trace_qemu_anon_ram_alloc(size
, ptr
);
65 *align
= MAX(get_allocation_granularity(), getpagesize());
70 void qemu_anon_ram_free(void *ptr
, size_t size
)
72 trace_qemu_anon_ram_free(ptr
, size
);
74 VirtualFree(ptr
, 0, MEM_RELEASE
);
78 #ifndef _POSIX_THREAD_SAFE_FUNCTIONS
79 /* FIXME: add proper locking */
80 struct tm
*gmtime_r(const time_t *timep
, struct tm
*result
)
82 struct tm
*p
= gmtime(timep
);
83 memset(result
, 0, sizeof(*result
));
91 /* FIXME: add proper locking */
92 struct tm
*localtime_r(const time_t *timep
, struct tm
*result
)
94 struct tm
*p
= localtime(timep
);
95 memset(result
, 0, sizeof(*result
));
102 #endif /* _POSIX_THREAD_SAFE_FUNCTIONS */
104 static int socket_error(void)
106 switch (WSAGetLastError()) {
113 case WSA_INVALID_HANDLE
:
115 case WSA_NOT_ENOUGH_MEMORY
:
117 case WSA_INVALID_PARAMETER
:
119 case WSAENAMETOOLONG
:
124 /* not using EWOULDBLOCK as we don't want code to have
125 * to check both EWOULDBLOCK and EAGAIN */
133 case WSAEDESTADDRREQ
:
141 case WSAEPROTONOSUPPORT
:
142 return EPROTONOSUPPORT
;
145 case WSAEAFNOSUPPORT
:
149 case WSAEADDRNOTAVAIL
:
150 return EADDRNOTAVAIL
;
157 case WSAECONNABORTED
:
169 case WSAECONNREFUSED
:
173 case WSAEHOSTUNREACH
:
180 void qemu_socket_set_block(int fd
)
182 unsigned long opt
= 0;
183 qemu_socket_unselect(fd
, NULL
);
184 ioctlsocket(fd
, FIONBIO
, &opt
);
187 int qemu_socket_try_set_nonblock(int fd
)
189 unsigned long opt
= 1;
190 if (ioctlsocket(fd
, FIONBIO
, &opt
) != NO_ERROR
) {
191 return -socket_error();
196 void qemu_socket_set_nonblock(int fd
)
198 (void)qemu_socket_try_set_nonblock(fd
);
201 int socket_set_fast_reuse(int fd
)
203 /* Enabling the reuse of an endpoint that was used by a socket still in
204 * TIME_WAIT state is usually performed by setting SO_REUSEADDR. On Windows
205 * fast reuse is the default and SO_REUSEADDR does strange things. So we
206 * don't have to do anything here. More info can be found at:
207 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621.aspx */
211 int inet_aton(const char *cp
, struct in_addr
*ia
)
213 uint32_t addr
= inet_addr(cp
);
214 if (addr
== 0xffffffff) {
221 void qemu_set_cloexec(int fd
)
225 int qemu_get_thread_id(void)
227 return GetCurrentThreadId();
231 qemu_get_local_state_dir(void)
233 const char * const *data_dirs
= g_get_system_data_dirs();
235 g_assert(data_dirs
&& data_dirs
[0]);
237 return g_strdup(data_dirs
[0]);
240 void qemu_set_tty_echo(int fd
, bool echo
)
242 HANDLE handle
= (HANDLE
)_get_osfhandle(fd
);
245 if (handle
== INVALID_HANDLE_VALUE
) {
249 GetConsoleMode(handle
, &dwMode
);
252 SetConsoleMode(handle
, dwMode
| ENABLE_ECHO_INPUT
| ENABLE_LINE_INPUT
);
254 SetConsoleMode(handle
,
255 dwMode
& ~(ENABLE_ECHO_INPUT
| ENABLE_LINE_INPUT
));
259 int getpagesize(void)
261 SYSTEM_INFO system_info
;
263 GetSystemInfo(&system_info
);
264 return system_info
.dwPageSize
;
267 bool qemu_prealloc_mem(int fd
, char *area
, size_t sz
, int max_threads
,
268 ThreadContext
*tc
, bool async
, Error
**errp
)
271 size_t pagesize
= qemu_real_host_page_size();
273 sz
= (sz
+ pagesize
- 1) & -pagesize
;
274 for (i
= 0; i
< sz
/ pagesize
; i
++) {
275 memset(area
+ pagesize
* i
, 0, 1);
281 bool qemu_finish_async_prealloc_mem(Error
**errp
)
283 /* async prealloc not supported, there is nothing to finish */
287 char *qemu_get_pid_name(pid_t pid
)
289 /* XXX Implement me */
294 bool qemu_socket_select(int sockfd
, WSAEVENT hEventObject
,
295 long lNetworkEvents
, Error
**errp
)
297 SOCKET s
= _get_osfhandle(sockfd
);
303 if (s
== INVALID_SOCKET
) {
304 error_setg(errp
, "invalid socket fd=%d", sockfd
);
308 if (WSAEventSelect(s
, hEventObject
, lNetworkEvents
) != 0) {
309 error_setg_win32(errp
, WSAGetLastError(), "failed to WSAEventSelect()");
316 bool qemu_socket_unselect(int sockfd
, Error
**errp
)
318 return qemu_socket_select(sockfd
, NULL
, 0, errp
);
321 int qemu_socketpair(int domain
, int type
, int protocol
, int sv
[2])
323 struct sockaddr_un addr
= {
330 g_autofree
char *path
= NULL
;
335 g_return_val_if_fail(sv
!= NULL
, -1);
337 addr
.sun_family
= AF_UNIX
;
338 socklen
= sizeof(addr
);
340 tmpfd
= g_file_open_tmp(NULL
, &path
, NULL
);
341 if (tmpfd
== -1 || !path
) {
348 if (strlen(path
) >= sizeof(addr
.sun_path
)) {
353 strncpy(addr
.sun_path
, path
, sizeof(addr
.sun_path
) - 1);
355 listener
= socket(domain
, type
, protocol
);
356 if (listener
== -1) {
360 if (DeleteFile(path
) == 0 && GetLastError() != ERROR_FILE_NOT_FOUND
) {
364 g_clear_pointer(&path
, g_free
);
366 if (bind(listener
, (struct sockaddr
*)&addr
, socklen
) == -1) {
370 if (listen(listener
, 1) == -1) {
374 client
= socket(domain
, type
, protocol
);
380 if (ioctlsocket(client
, FIONBIO
, &arg
) != NO_ERROR
) {
384 if (connect(client
, (struct sockaddr
*)&addr
, socklen
) == -1 &&
385 WSAGetLastError() != WSAEWOULDBLOCK
) {
389 server
= accept(listener
, NULL
, NULL
);
395 if (ioctlsocket(client
, FIONBIO
, &arg
) != NO_ERROR
) {
400 if (ioctlsocket(client
, SIO_AF_UNIX_GETPEERPID
, &arg
) != NO_ERROR
) {
404 if (arg
!= GetCurrentProcessId()) {
416 if (listener
!= -1) {
432 int qemu_connect_wrap(int sockfd
, const struct sockaddr
*addr
,
436 SOCKET s
= _get_osfhandle(sockfd
);
438 if (s
== INVALID_SOCKET
) {
442 ret
= connect(s
, addr
, addrlen
);
444 if (WSAGetLastError() == WSAEWOULDBLOCK
) {
447 errno
= socket_error();
455 int qemu_listen_wrap(int sockfd
, int backlog
)
458 SOCKET s
= _get_osfhandle(sockfd
);
460 if (s
== INVALID_SOCKET
) {
464 ret
= listen(s
, backlog
);
466 errno
= socket_error();
473 int qemu_bind_wrap(int sockfd
, const struct sockaddr
*addr
,
477 SOCKET s
= _get_osfhandle(sockfd
);
479 if (s
== INVALID_SOCKET
) {
483 ret
= bind(s
, addr
, addrlen
);
485 errno
= socket_error();
490 QEMU_USED EXCEPTION_DISPOSITION
491 win32_close_exception_handler(struct _EXCEPTION_RECORD
*exception_record
,
492 void *registration
, struct _CONTEXT
*context
,
495 return EXCEPTION_EXECUTE_HANDLER
;
499 int qemu_close_socket_osfhandle(int fd
)
501 SOCKET s
= _get_osfhandle(fd
);
505 * If we were to just call _close on the descriptor, it would close the
506 * HANDLE, but it wouldn't free any of the resources associated to the
507 * SOCKET, and we can't call _close after calling closesocket, because
508 * closesocket has already closed the HANDLE, and _close would attempt to
509 * close the HANDLE again, resulting in a double free. We can however
510 * protect the HANDLE from actually being closed long enough to close the
511 * file descriptor, then close the socket itself.
513 if (!GetHandleInformation((HANDLE
)s
, &flags
)) {
518 if (!SetHandleInformation((HANDLE
)s
, HANDLE_FLAG_PROTECT_FROM_CLOSE
, HANDLE_FLAG_PROTECT_FROM_CLOSE
)) {
523 __try1(win32_close_exception_handler
) {
525 * close() returns EBADF since we PROTECT_FROM_CLOSE the underlying
526 * handle, but the FD is actually freed
528 if (close(fd
) < 0 && errno
!= EBADF
) {
535 if (!SetHandleInformation((HANDLE
)s
, flags
, flags
)) {
543 int qemu_close_wrap(int fd
)
545 SOCKET s
= INVALID_SOCKET
;
548 if (!fd_is_socket(fd
)) {
552 s
= _get_osfhandle(fd
);
553 qemu_close_socket_osfhandle(fd
);
555 ret
= closesocket(s
);
557 errno
= socket_error();
565 int qemu_socket_wrap(int domain
, int type
, int protocol
)
570 s
= socket(domain
, type
, protocol
);
572 errno
= socket_error();
576 fd
= _open_osfhandle(s
, _O_BINARY
);
579 /* _open_osfhandle may not set errno, and closesocket() may override it */
588 int qemu_accept_wrap(int sockfd
, struct sockaddr
*addr
,
592 SOCKET s
= _get_osfhandle(sockfd
);
594 if (s
== INVALID_SOCKET
) {
598 s
= accept(s
, addr
, addrlen
);
600 errno
= socket_error();
604 fd
= _open_osfhandle(s
, _O_BINARY
);
607 /* _open_osfhandle may not set errno, and closesocket() may override it */
616 int qemu_shutdown_wrap(int sockfd
, int how
)
619 SOCKET s
= _get_osfhandle(sockfd
);
621 if (s
== INVALID_SOCKET
) {
625 ret
= shutdown(s
, how
);
627 errno
= socket_error();
634 int qemu_ioctlsocket_wrap(int fd
, int req
, void *val
)
637 SOCKET s
= _get_osfhandle(fd
);
639 if (s
== INVALID_SOCKET
) {
643 ret
= ioctlsocket(s
, req
, val
);
645 errno
= socket_error();
652 int qemu_getsockopt_wrap(int sockfd
, int level
, int optname
,
653 void *optval
, socklen_t
*optlen
)
656 SOCKET s
= _get_osfhandle(sockfd
);
658 if (s
== INVALID_SOCKET
) {
662 ret
= getsockopt(s
, level
, optname
, optval
, optlen
);
664 errno
= socket_error();
671 int qemu_setsockopt_wrap(int sockfd
, int level
, int optname
,
672 const void *optval
, socklen_t optlen
)
675 SOCKET s
= _get_osfhandle(sockfd
);
677 if (s
== INVALID_SOCKET
) {
681 ret
= setsockopt(s
, level
, optname
, optval
, optlen
);
683 errno
= socket_error();
690 int qemu_getpeername_wrap(int sockfd
, struct sockaddr
*addr
,
694 SOCKET s
= _get_osfhandle(sockfd
);
696 if (s
== INVALID_SOCKET
) {
700 ret
= getpeername(s
, addr
, addrlen
);
702 errno
= socket_error();
709 int qemu_getsockname_wrap(int sockfd
, struct sockaddr
*addr
,
713 SOCKET s
= _get_osfhandle(sockfd
);
715 if (s
== INVALID_SOCKET
) {
719 ret
= getsockname(s
, addr
, addrlen
);
721 errno
= socket_error();
728 ssize_t
qemu_send_wrap(int sockfd
, const void *buf
, size_t len
, int flags
)
731 SOCKET s
= _get_osfhandle(sockfd
);
733 if (s
== INVALID_SOCKET
) {
737 ret
= send(s
, buf
, len
, flags
);
739 errno
= socket_error();
746 ssize_t
qemu_sendto_wrap(int sockfd
, const void *buf
, size_t len
, int flags
,
747 const struct sockaddr
*addr
, socklen_t addrlen
)
750 SOCKET s
= _get_osfhandle(sockfd
);
752 if (s
== INVALID_SOCKET
) {
756 ret
= sendto(s
, buf
, len
, flags
, addr
, addrlen
);
758 errno
= socket_error();
765 ssize_t
qemu_recv_wrap(int sockfd
, void *buf
, size_t len
, int flags
)
768 SOCKET s
= _get_osfhandle(sockfd
);
770 if (s
== INVALID_SOCKET
) {
774 ret
= recv(s
, buf
, len
, flags
);
776 errno
= socket_error();
783 ssize_t
qemu_recvfrom_wrap(int sockfd
, void *buf
, size_t len
, int flags
,
784 struct sockaddr
*addr
, socklen_t
*addrlen
)
787 SOCKET s
= _get_osfhandle(sockfd
);
789 if (s
== INVALID_SOCKET
) {
793 ret
= recvfrom(s
, buf
, len
, flags
, addr
, addrlen
);
795 errno
= socket_error();
800 bool qemu_write_pidfile(const char *filename
, Error
**errp
)
807 memset(&overlap
, 0, sizeof(overlap
));
809 file
= CreateFile(filename
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
810 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
812 if (file
== INVALID_HANDLE_VALUE
) {
813 error_setg(errp
, "Failed to create PID file");
816 len
= snprintf(buffer
, sizeof(buffer
), FMT_pid
"\n", (pid_t
)getpid());
817 ret
= WriteFile(file
, (LPCVOID
)buffer
, (DWORD
)len
,
821 error_setg(errp
, "Failed to write PID file");
827 size_t qemu_get_host_physmem(void)
829 MEMORYSTATUSEX statex
;
830 statex
.dwLength
= sizeof(statex
);
832 if (GlobalMemoryStatusEx(&statex
)) {
833 return statex
.ullTotalPhys
;
838 int qemu_msync(void *addr
, size_t length
, int fd
)
841 * Perform the sync based on the file descriptor
842 * The sync range will most probably be wider than the one
843 * requested - but it will still get the job done
845 return qemu_fdatasync(fd
);
848 void *qemu_win32_map_alloc(size_t size
, HANDLE
*h
, Error
**errp
)
852 trace_win32_map_alloc(size
);
854 *h
= CreateFileMapping(INVALID_HANDLE_VALUE
, NULL
, PAGE_READWRITE
, 0,
857 error_setg_win32(errp
, GetLastError(), "Failed to CreateFileMapping");
861 bits
= MapViewOfFile(*h
, FILE_MAP_ALL_ACCESS
, 0, 0, size
);
863 error_setg_win32(errp
, GetLastError(), "Failed to MapViewOfFile");
871 void qemu_win32_map_free(void *ptr
, HANDLE h
, Error
**errp
)
873 trace_win32_map_free(ptr
, h
);
875 if (UnmapViewOfFile(ptr
) == 0) {
876 error_setg_win32(errp
, GetLastError(), "Failed to UnmapViewOfFile");