block/vpc: choose size calculation method based on creator_app field
[qemu.git] / util / oslib-win32.c
bloba3f0664763a4defb6e7ccdbf650e10d43ac3795e
1 /*
2 * os-win32.c
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
8 * the QEMU tools.
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
26 * THE SOFTWARE.
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"
33 #include <windows.h>
34 #include <glib.h>
35 #include "sysemu/sysemu.h"
36 #include "qemu/main-loop.h"
37 #include "trace.h"
38 #include "qemu/sockets.h"
40 /* this must come after including "trace.h" */
41 #include <shlobj.h>
43 void *qemu_oom_check(void *ptr)
45 if (ptr == NULL) {
46 fprintf(stderr, "Failed to allocate memory: %lu\n", GetLastError());
47 abort();
49 return ptr;
52 void *qemu_try_memalign(size_t alignment, size_t size)
54 void *ptr;
56 if (!size) {
57 abort();
59 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
60 trace_qemu_memalign(alignment, size, ptr);
61 return 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)
71 void *ptr;
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);
78 return ptr;
81 void qemu_vfree(void *ptr)
83 trace_qemu_vfree(ptr);
84 if (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);
92 if (ptr) {
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));
103 if (p) {
104 *result = *p;
105 p = result;
107 return p;
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));
115 if (p) {
116 *result = *p;
117 p = result;
119 return p;
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 */
144 return 0;
148 static int socket_error(void)
150 switch (WSAGetLastError()) {
151 case 0:
152 return 0;
153 case WSAEINTR:
154 return EINTR;
155 case WSAEINVAL:
156 return EINVAL;
157 case WSA_INVALID_HANDLE:
158 return EBADF;
159 case WSA_NOT_ENOUGH_MEMORY:
160 return ENOMEM;
161 case WSA_INVALID_PARAMETER:
162 return EINVAL;
163 case WSAENAMETOOLONG:
164 return ENAMETOOLONG;
165 case WSAENOTEMPTY:
166 return ENOTEMPTY;
167 case WSAEWOULDBLOCK:
168 /* not using EWOULDBLOCK as we don't want code to have
169 * to check both EWOULDBLOCK and EAGAIN */
170 return EAGAIN;
171 case WSAEINPROGRESS:
172 return EINPROGRESS;
173 case WSAEALREADY:
174 return EALREADY;
175 case WSAENOTSOCK:
176 return ENOTSOCK;
177 case WSAEDESTADDRREQ:
178 return EDESTADDRREQ;
179 case WSAEMSGSIZE:
180 return EMSGSIZE;
181 case WSAEPROTOTYPE:
182 return EPROTOTYPE;
183 case WSAENOPROTOOPT:
184 return ENOPROTOOPT;
185 case WSAEPROTONOSUPPORT:
186 return EPROTONOSUPPORT;
187 case WSAEOPNOTSUPP:
188 return EOPNOTSUPP;
189 case WSAEAFNOSUPPORT:
190 return EAFNOSUPPORT;
191 case WSAEADDRINUSE:
192 return EADDRINUSE;
193 case WSAEADDRNOTAVAIL:
194 return EADDRNOTAVAIL;
195 case WSAENETDOWN:
196 return ENETDOWN;
197 case WSAENETUNREACH:
198 return ENETUNREACH;
199 case WSAENETRESET:
200 return ENETRESET;
201 case WSAECONNABORTED:
202 return ECONNABORTED;
203 case WSAECONNRESET:
204 return ECONNRESET;
205 case WSAENOBUFS:
206 return ENOBUFS;
207 case WSAEISCONN:
208 return EISCONN;
209 case WSAENOTCONN:
210 return ENOTCONN;
211 case WSAETIMEDOUT:
212 return ETIMEDOUT;
213 case WSAECONNREFUSED:
214 return ECONNREFUSED;
215 case WSAELOOP:
216 return ELOOP;
217 case WSAEHOSTUNREACH:
218 return EHOSTUNREACH;
219 default:
220 return EIO;
224 int inet_aton(const char *cp, struct in_addr *ia)
226 uint32_t addr = inet_addr(cp);
227 if (addr == 0xffffffff) {
228 return 0;
230 ia->s_addr = addr;
231 return 1;
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)
243 union {
244 unsigned long long ns100; /*time since 1 Jan 1601 in 100ns units */
245 FILETIME ft;
246 } _now;
248 if(tp) {
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. */
255 return 0;
258 int qemu_get_thread_id(void)
260 return GetCurrentThreadId();
263 char *
264 qemu_get_local_state_pathname(const char *relative_pathname)
266 HRESULT result;
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);
274 abort();
276 return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", base_path,
277 relative_pathname);
280 void qemu_set_tty_echo(int fd, bool echo)
282 HANDLE handle = (HANDLE)_get_osfhandle(fd);
283 DWORD dwMode = 0;
285 if (handle == INVALID_HANDLE_VALUE) {
286 return;
289 GetConsoleMode(handle, &dwMode);
291 if (echo) {
292 SetConsoleMode(handle, dwMode | ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT);
293 } else {
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)
304 char *p;
305 char buf[MAX_PATH];
306 DWORD len;
308 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
309 if (len == 0) {
310 return;
313 buf[len] = 0;
314 p = buf + len - 1;
315 while (p != buf && *p != '\\') {
316 p--;
318 *p = 0;
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)
364 DWORD ready;
365 GPollFD *f;
366 int recursed_result;
368 if (poll_msgs) {
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);
378 g_free(emsg);
380 } else if (nhandles == 0) {
381 /* No handles to wait for, just the timeout */
382 if (timeout == INFINITE) {
383 ready = WAIT_FAILED;
384 } else {
385 SleepEx(timeout, TRUE);
386 ready = WAIT_TIMEOUT;
388 } else {
389 /* Wait for just handles
390 * -> Use WaitForMultipleObjectsEx
392 ready =
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);
397 g_free(emsg);
401 if (ready == WAIT_FAILED) {
402 return -1;
403 } else if (ready == WAIT_TIMEOUT || ready == WAIT_IO_COMPLETION) {
404 return 0;
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) {
416 return 1;
419 /* If no timeout and handles to poll, recurse to poll them,
420 * too.
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
434 * the rest of them.
436 if (timeout == 0 && nhandles > 1) {
437 /* Remove the handle that fired */
438 int i;
439 if (ready < nhandles - 1) {
440 for (i = ready - WAIT_OBJECT_0 + 1; i < nhandles; i++) {
441 handles[i-1] = handles[i];
444 nhandles--;
445 recursed_result = poll_rest(FALSE, handles, nhandles, fds, nfds, 0);
446 return (recursed_result == -1) ? -1 : 1 + recursed_result;
448 return 1;
451 return 0;
454 gint g_poll(GPollFD *fds, guint nfds, gint timeout)
456 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
457 gboolean poll_msgs = FALSE;
458 GPollFD *f;
459 gint nhandles = 0;
460 int retval;
462 for (f = fds; f < &fds[nfds]; ++f) {
463 if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN)) {
464 poll_msgs = TRUE;
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
468 * to work.
470 gint i;
472 for (i = 0; i < nhandles; i++) {
473 if (handles[i] == (HANDLE) f->fd) {
474 break;
478 if (i == nhandles) {
479 if (nhandles == MAXIMUM_WAIT_OBJECTS) {
480 g_warning("Too many handles to wait for!\n");
481 break;
482 } else {
483 handles[nhandles++] = (HANDLE) f->fd;
489 for (f = fds; f < &fds[nfds]; ++f) {
490 f->revents = 0;
493 if (timeout == -1) {
494 timeout = INFINITE;
497 /* Polling for several things? */
498 if (nhandles > 1 || (nhandles > 0 && poll_msgs)) {
499 /* First check if one or several of them are immediately
500 * available
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
509 * anyway.
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,
515 fds, nfds, timeout);
517 } else {
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);
524 if (retval == -1) {
525 for (f = fds; f < &fds[nfds]; ++f) {
526 f->revents = 0;
530 return retval;
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)
543 int i;
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)
556 int c, i;
558 printf("Password: ");
559 fflush(stdout);
560 i = 0;
561 for (;;) {
562 c = getchar();
563 if (c < 0) {
564 buf[i] = '\0';
565 return -1;
566 } else if (c == '\n') {
567 break;
568 } else if (i < (buf_size - 1)) {
569 buf[i++] = c;
572 buf[i] = '\0';
573 return 0;
577 pid_t qemu_fork(Error **errp)
579 errno = ENOSYS;
580 error_setg_errno(errp, errno,
581 "cannot fork child process");
582 return -1;
586 #undef connect
587 int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
588 socklen_t addrlen)
590 int ret;
591 ret = connect(sockfd, addr, addrlen);
592 if (ret < 0) {
593 errno = socket_error();
595 return ret;
599 #undef listen
600 int qemu_listen_wrap(int sockfd, int backlog)
602 int ret;
603 ret = listen(sockfd, backlog);
604 if (ret < 0) {
605 errno = socket_error();
607 return ret;
611 #undef bind
612 int qemu_bind_wrap(int sockfd, const struct sockaddr *addr,
613 socklen_t addrlen)
615 int ret;
616 ret = bind(sockfd, addr, addrlen);
617 if (ret < 0) {
618 errno = socket_error();
620 return ret;
624 #undef socket
625 int qemu_socket_wrap(int domain, int type, int protocol)
627 int ret;
628 ret = socket(domain, type, protocol);
629 if (ret < 0) {
630 errno = socket_error();
632 return ret;
636 #undef accept
637 int qemu_accept_wrap(int sockfd, struct sockaddr *addr,
638 socklen_t *addrlen)
640 int ret;
641 ret = accept(sockfd, addr, addrlen);
642 if (ret < 0) {
643 errno = socket_error();
645 return ret;
649 #undef shutdown
650 int qemu_shutdown_wrap(int sockfd, int how)
652 int ret;
653 ret = shutdown(sockfd, how);
654 if (ret < 0) {
655 errno = socket_error();
657 return ret;
661 #undef ioctlsocket
662 int qemu_ioctlsocket_wrap(int fd, int req, void *val)
664 int ret;
665 ret = ioctlsocket(fd, req, val);
666 if (ret < 0) {
667 errno = socket_error();
669 return ret;
673 #undef closesocket
674 int qemu_closesocket_wrap(int fd)
676 int ret;
677 ret = closesocket(fd);
678 if (ret < 0) {
679 errno = socket_error();
681 return ret;
685 #undef getsockopt
686 int qemu_getsockopt_wrap(int sockfd, int level, int optname,
687 void *optval, socklen_t *optlen)
689 int ret;
690 ret = getsockopt(sockfd, level, optname, optval, optlen);
691 if (ret < 0) {
692 errno = socket_error();
694 return ret;
698 #undef setsockopt
699 int qemu_setsockopt_wrap(int sockfd, int level, int optname,
700 const void *optval, socklen_t optlen)
702 int ret;
703 ret = setsockopt(sockfd, level, optname, optval, optlen);
704 if (ret < 0) {
705 errno = socket_error();
707 return ret;
711 #undef getpeername
712 int qemu_getpeername_wrap(int sockfd, struct sockaddr *addr,
713 socklen_t *addrlen)
715 int ret;
716 ret = getpeername(sockfd, addr, addrlen);
717 if (ret < 0) {
718 errno = socket_error();
720 return ret;
724 #undef getsockname
725 int qemu_getsockname_wrap(int sockfd, struct sockaddr *addr,
726 socklen_t *addrlen)
728 int ret;
729 ret = getsockname(sockfd, addr, addrlen);
730 if (ret < 0) {
731 errno = socket_error();
733 return ret;
737 #undef send
738 ssize_t qemu_send_wrap(int sockfd, const void *buf, size_t len, int flags)
740 int ret;
741 ret = send(sockfd, buf, len, flags);
742 if (ret < 0) {
743 errno = socket_error();
745 return ret;
749 #undef sendto
750 ssize_t qemu_sendto_wrap(int sockfd, const void *buf, size_t len, int flags,
751 const struct sockaddr *addr, socklen_t addrlen)
753 int ret;
754 ret = sendto(sockfd, buf, len, flags, addr, addrlen);
755 if (ret < 0) {
756 errno = socket_error();
758 return ret;
762 #undef recv
763 ssize_t qemu_recv_wrap(int sockfd, void *buf, size_t len, int flags)
765 int ret;
766 ret = recv(sockfd, buf, len, flags);
767 if (ret < 0) {
768 errno = socket_error();
770 return ret;
774 #undef recvfrom
775 ssize_t qemu_recvfrom_wrap(int sockfd, void *buf, size_t len, int flags,
776 struct sockaddr *addr, socklen_t *addrlen)
778 int ret;
779 ret = recvfrom(sockfd, buf, len, flags, addr, addrlen);
780 if (ret < 0) {
781 errno = socket_error();
783 return ret;