s390: avoid potential null dereference in s390_pcihost_unplug()
[qemu/ar7.git] / util / oslib-win32.c
blobb4c17f5dfaf7d2c0f6a9beee363ed530e992754f
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 "qapi/error.h"
35 #include "sysemu/sysemu.h"
36 #include "qemu/main-loop.h"
37 #include "trace.h"
38 #include "qemu/sockets.h"
39 #include "qemu/cutils.h"
41 /* this must come after including "trace.h" */
42 #include <shlobj.h>
44 void *qemu_oom_check(void *ptr)
46 if (ptr == NULL) {
47 fprintf(stderr, "Failed to allocate memory: %lu\n", GetLastError());
48 abort();
50 return ptr;
53 void *qemu_try_memalign(size_t alignment, size_t size)
55 void *ptr;
57 if (!size) {
58 abort();
60 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
61 trace_qemu_memalign(alignment, size, ptr);
62 return 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)
80 void *ptr;
82 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
83 trace_qemu_anon_ram_alloc(size, ptr);
85 if (ptr && align) {
86 *align = MAX(get_allocation_granularity(), getpagesize());
88 return ptr;
91 void qemu_vfree(void *ptr)
93 trace_qemu_vfree(ptr);
94 if (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);
102 if (ptr) {
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));
113 if (p) {
114 *result = *p;
115 p = result;
117 return p;
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));
125 if (p) {
126 *result = *p;
127 p = result;
129 return p;
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 */
154 return 0;
158 static int socket_error(void)
160 switch (WSAGetLastError()) {
161 case 0:
162 return 0;
163 case WSAEINTR:
164 return EINTR;
165 case WSAEINVAL:
166 return EINVAL;
167 case WSA_INVALID_HANDLE:
168 return EBADF;
169 case WSA_NOT_ENOUGH_MEMORY:
170 return ENOMEM;
171 case WSA_INVALID_PARAMETER:
172 return EINVAL;
173 case WSAENAMETOOLONG:
174 return ENAMETOOLONG;
175 case WSAENOTEMPTY:
176 return ENOTEMPTY;
177 case WSAEWOULDBLOCK:
178 /* not using EWOULDBLOCK as we don't want code to have
179 * to check both EWOULDBLOCK and EAGAIN */
180 return EAGAIN;
181 case WSAEINPROGRESS:
182 return EINPROGRESS;
183 case WSAEALREADY:
184 return EALREADY;
185 case WSAENOTSOCK:
186 return ENOTSOCK;
187 case WSAEDESTADDRREQ:
188 return EDESTADDRREQ;
189 case WSAEMSGSIZE:
190 return EMSGSIZE;
191 case WSAEPROTOTYPE:
192 return EPROTOTYPE;
193 case WSAENOPROTOOPT:
194 return ENOPROTOOPT;
195 case WSAEPROTONOSUPPORT:
196 return EPROTONOSUPPORT;
197 case WSAEOPNOTSUPP:
198 return EOPNOTSUPP;
199 case WSAEAFNOSUPPORT:
200 return EAFNOSUPPORT;
201 case WSAEADDRINUSE:
202 return EADDRINUSE;
203 case WSAEADDRNOTAVAIL:
204 return EADDRNOTAVAIL;
205 case WSAENETDOWN:
206 return ENETDOWN;
207 case WSAENETUNREACH:
208 return ENETUNREACH;
209 case WSAENETRESET:
210 return ENETRESET;
211 case WSAECONNABORTED:
212 return ECONNABORTED;
213 case WSAECONNRESET:
214 return ECONNRESET;
215 case WSAENOBUFS:
216 return ENOBUFS;
217 case WSAEISCONN:
218 return EISCONN;
219 case WSAENOTCONN:
220 return ENOTCONN;
221 case WSAETIMEDOUT:
222 return ETIMEDOUT;
223 case WSAECONNREFUSED:
224 return ECONNREFUSED;
225 case WSAELOOP:
226 return ELOOP;
227 case WSAEHOSTUNREACH:
228 return EHOSTUNREACH;
229 default:
230 return EIO;
234 int inet_aton(const char *cp, struct in_addr *ia)
236 uint32_t addr = inet_addr(cp);
237 if (addr == 0xffffffff) {
238 return 0;
240 ia->s_addr = addr;
241 return 1;
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)
253 union {
254 unsigned long long ns100; /*time since 1 Jan 1601 in 100ns units */
255 FILETIME ft;
256 } _now;
258 if(tp) {
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. */
265 return 0;
268 int qemu_get_thread_id(void)
270 return GetCurrentThreadId();
273 char *
274 qemu_get_local_state_pathname(const char *relative_pathname)
276 HRESULT result;
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);
284 abort();
286 return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", base_path,
287 relative_pathname);
290 void qemu_set_tty_echo(int fd, bool echo)
292 HANDLE handle = (HANDLE)_get_osfhandle(fd);
293 DWORD dwMode = 0;
295 if (handle == INVALID_HANDLE_VALUE) {
296 return;
299 GetConsoleMode(handle, &dwMode);
301 if (echo) {
302 SetConsoleMode(handle, dwMode | ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT);
303 } else {
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)
314 char *p;
315 char buf[MAX_PATH];
316 DWORD len;
318 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
319 if (len == 0) {
320 return;
323 buf[len] = 0;
324 p = buf + len - 1;
325 while (p != buf && *p != '\\') {
326 p--;
328 *p = 0;
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)
375 DWORD ready;
376 GPollFD *f;
377 int recursed_result;
379 if (poll_msgs) {
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);
389 g_free(emsg);
391 } else if (nhandles == 0) {
392 /* No handles to wait for, just the timeout */
393 if (timeout == INFINITE) {
394 ready = WAIT_FAILED;
395 } else {
396 SleepEx(timeout, TRUE);
397 ready = WAIT_TIMEOUT;
399 } else {
400 /* Wait for just handles
401 * -> Use WaitForMultipleObjectsEx
403 ready =
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);
408 g_free(emsg);
412 if (ready == WAIT_FAILED) {
413 return -1;
414 } else if (ready == WAIT_TIMEOUT || ready == WAIT_IO_COMPLETION) {
415 return 0;
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) {
427 return 1;
430 /* If no timeout and handles to poll, recurse to poll them,
431 * too.
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
445 * the rest of them.
447 if (timeout == 0 && nhandles > 1) {
448 /* Remove the handle that fired */
449 int i;
450 for (i = ready - WAIT_OBJECT_0 + 1; i < nhandles; i++) {
451 handles[i-1] = handles[i];
453 nhandles--;
454 recursed_result = poll_rest(FALSE, handles, nhandles, fds, nfds, 0);
455 return (recursed_result == -1) ? -1 : 1 + recursed_result;
457 return 1;
460 return 0;
463 gint g_poll(GPollFD *fds, guint nfds, gint timeout)
465 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
466 gboolean poll_msgs = FALSE;
467 GPollFD *f;
468 gint nhandles = 0;
469 int retval;
471 for (f = fds; f < &fds[nfds]; ++f) {
472 if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN)) {
473 poll_msgs = TRUE;
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
477 * to work.
479 gint i;
481 for (i = 0; i < nhandles; i++) {
482 if (handles[i] == (HANDLE) f->fd) {
483 break;
487 if (i == nhandles) {
488 if (nhandles == MAXIMUM_WAIT_OBJECTS) {
489 g_warning("Too many handles to wait for!\n");
490 break;
491 } else {
492 handles[nhandles++] = (HANDLE) f->fd;
498 for (f = fds; f < &fds[nfds]; ++f) {
499 f->revents = 0;
502 if (timeout == -1) {
503 timeout = INFINITE;
506 /* Polling for several things? */
507 if (nhandles > 1 || (nhandles > 0 && poll_msgs)) {
508 /* First check if one or several of them are immediately
509 * available
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
518 * anyway.
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,
524 fds, nfds, timeout);
526 } else {
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);
533 if (retval == -1) {
534 for (f = fds; f < &fds[nfds]; ++f) {
535 f->revents = 0;
539 return retval;
541 #endif
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,
552 Error **errp)
554 int i;
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 */
567 abort();
571 pid_t qemu_fork(Error **errp)
573 errno = ENOSYS;
574 error_setg_errno(errp, errno,
575 "cannot fork child process");
576 return -1;
580 #undef connect
581 int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
582 socklen_t addrlen)
584 int ret;
585 ret = connect(sockfd, addr, addrlen);
586 if (ret < 0) {
587 errno = socket_error();
589 return ret;
593 #undef listen
594 int qemu_listen_wrap(int sockfd, int backlog)
596 int ret;
597 ret = listen(sockfd, backlog);
598 if (ret < 0) {
599 errno = socket_error();
601 return ret;
605 #undef bind
606 int qemu_bind_wrap(int sockfd, const struct sockaddr *addr,
607 socklen_t addrlen)
609 int ret;
610 ret = bind(sockfd, addr, addrlen);
611 if (ret < 0) {
612 errno = socket_error();
614 return ret;
618 #undef socket
619 int qemu_socket_wrap(int domain, int type, int protocol)
621 int ret;
622 ret = socket(domain, type, protocol);
623 if (ret < 0) {
624 errno = socket_error();
626 return ret;
630 #undef accept
631 int qemu_accept_wrap(int sockfd, struct sockaddr *addr,
632 socklen_t *addrlen)
634 int ret;
635 ret = accept(sockfd, addr, addrlen);
636 if (ret < 0) {
637 errno = socket_error();
639 return ret;
643 #undef shutdown
644 int qemu_shutdown_wrap(int sockfd, int how)
646 int ret;
647 ret = shutdown(sockfd, how);
648 if (ret < 0) {
649 errno = socket_error();
651 return ret;
655 #undef ioctlsocket
656 int qemu_ioctlsocket_wrap(int fd, int req, void *val)
658 int ret;
659 ret = ioctlsocket(fd, req, val);
660 if (ret < 0) {
661 errno = socket_error();
663 return ret;
667 #undef closesocket
668 int qemu_closesocket_wrap(int fd)
670 int ret;
671 ret = closesocket(fd);
672 if (ret < 0) {
673 errno = socket_error();
675 return ret;
679 #undef getsockopt
680 int qemu_getsockopt_wrap(int sockfd, int level, int optname,
681 void *optval, socklen_t *optlen)
683 int ret;
684 ret = getsockopt(sockfd, level, optname, optval, optlen);
685 if (ret < 0) {
686 errno = socket_error();
688 return ret;
692 #undef setsockopt
693 int qemu_setsockopt_wrap(int sockfd, int level, int optname,
694 const void *optval, socklen_t optlen)
696 int ret;
697 ret = setsockopt(sockfd, level, optname, optval, optlen);
698 if (ret < 0) {
699 errno = socket_error();
701 return ret;
705 #undef getpeername
706 int qemu_getpeername_wrap(int sockfd, struct sockaddr *addr,
707 socklen_t *addrlen)
709 int ret;
710 ret = getpeername(sockfd, addr, addrlen);
711 if (ret < 0) {
712 errno = socket_error();
714 return ret;
718 #undef getsockname
719 int qemu_getsockname_wrap(int sockfd, struct sockaddr *addr,
720 socklen_t *addrlen)
722 int ret;
723 ret = getsockname(sockfd, addr, addrlen);
724 if (ret < 0) {
725 errno = socket_error();
727 return ret;
731 #undef send
732 ssize_t qemu_send_wrap(int sockfd, const void *buf, size_t len, int flags)
734 int ret;
735 ret = send(sockfd, buf, len, flags);
736 if (ret < 0) {
737 errno = socket_error();
739 return ret;
743 #undef sendto
744 ssize_t qemu_sendto_wrap(int sockfd, const void *buf, size_t len, int flags,
745 const struct sockaddr *addr, socklen_t addrlen)
747 int ret;
748 ret = sendto(sockfd, buf, len, flags, addr, addrlen);
749 if (ret < 0) {
750 errno = socket_error();
752 return ret;
756 #undef recv
757 ssize_t qemu_recv_wrap(int sockfd, void *buf, size_t len, int flags)
759 int ret;
760 ret = recv(sockfd, buf, len, flags);
761 if (ret < 0) {
762 errno = socket_error();
764 return ret;
768 #undef recvfrom
769 ssize_t qemu_recvfrom_wrap(int sockfd, void *buf, size_t len, int flags,
770 struct sockaddr *addr, socklen_t *addrlen)
772 int ret;
773 ret = recvfrom(sockfd, buf, len, flags, addr, addrlen);
774 if (ret < 0) {
775 errno = socket_error();
777 return ret;
780 bool qemu_write_pidfile(const char *filename, Error **errp)
782 char buffer[128];
783 int len;
784 HANDLE file;
785 OVERLAPPED overlap;
786 BOOL ret;
787 memset(&overlap, 0, sizeof(overlap));
789 file = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ, NULL,
790 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
792 if (file == INVALID_HANDLE_VALUE) {
793 error_setg(errp, "Failed to create PID file");
794 return false;
796 len = snprintf(buffer, sizeof(buffer), FMT_pid "\n", (pid_t)getpid());
797 ret = WriteFile(file, (LPCVOID)buffer, (DWORD)len,
798 NULL, &overlap);
799 CloseHandle(file);
800 if (ret == 0) {
801 error_setg(errp, "Failed to write PID file");
802 return false;
804 return true;