ppc: Rename current DAWR macros and variables
[qemu/ar7.git] / util / oslib-win32.c
blobf68b8012bb8c37c75e17fbc7adc69679371e11bb
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.
33 #include "qemu/osdep.h"
34 #include <windows.h>
35 #include "qemu-common.h"
36 #include "qapi/error.h"
37 #include "sysemu/sysemu.h"
38 #include "qemu/main-loop.h"
39 #include "trace.h"
40 #include "qemu/sockets.h"
41 #include "qemu/cutils.h"
42 #include <malloc.h>
44 /* this must come after including "trace.h" */
45 #include <shlobj.h>
47 void *qemu_oom_check(void *ptr)
49 if (ptr == NULL) {
50 fprintf(stderr, "Failed to allocate memory: %lu\n", GetLastError());
51 abort();
53 return ptr;
56 void *qemu_try_memalign(size_t alignment, size_t size)
58 void *ptr;
60 g_assert(size != 0);
61 g_assert(is_power_of_2(alignment));
62 ptr = _aligned_malloc(size, alignment);
63 trace_qemu_memalign(alignment, size, ptr);
64 return ptr;
67 void *qemu_memalign(size_t alignment, size_t size)
69 return qemu_oom_check(qemu_try_memalign(alignment, size));
72 static int get_allocation_granularity(void)
74 SYSTEM_INFO system_info;
76 GetSystemInfo(&system_info);
77 return system_info.dwAllocationGranularity;
80 void *qemu_anon_ram_alloc(size_t size, uint64_t *align, bool shared)
82 void *ptr;
84 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
85 trace_qemu_anon_ram_alloc(size, ptr);
87 if (ptr && align) {
88 *align = MAX(get_allocation_granularity(), getpagesize());
90 return ptr;
93 void qemu_vfree(void *ptr)
95 trace_qemu_vfree(ptr);
96 _aligned_free(ptr);
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 _POSIX_THREAD_SAFE_FUNCTIONS
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 /* _POSIX_THREAD_SAFE_FUNCTIONS */
133 static int socket_error(void)
135 switch (WSAGetLastError()) {
136 case 0:
137 return 0;
138 case WSAEINTR:
139 return EINTR;
140 case WSAEINVAL:
141 return EINVAL;
142 case WSA_INVALID_HANDLE:
143 return EBADF;
144 case WSA_NOT_ENOUGH_MEMORY:
145 return ENOMEM;
146 case WSA_INVALID_PARAMETER:
147 return EINVAL;
148 case WSAENAMETOOLONG:
149 return ENAMETOOLONG;
150 case WSAENOTEMPTY:
151 return ENOTEMPTY;
152 case WSAEWOULDBLOCK:
153 /* not using EWOULDBLOCK as we don't want code to have
154 * to check both EWOULDBLOCK and EAGAIN */
155 return EAGAIN;
156 case WSAEINPROGRESS:
157 return EINPROGRESS;
158 case WSAEALREADY:
159 return EALREADY;
160 case WSAENOTSOCK:
161 return ENOTSOCK;
162 case WSAEDESTADDRREQ:
163 return EDESTADDRREQ;
164 case WSAEMSGSIZE:
165 return EMSGSIZE;
166 case WSAEPROTOTYPE:
167 return EPROTOTYPE;
168 case WSAENOPROTOOPT:
169 return ENOPROTOOPT;
170 case WSAEPROTONOSUPPORT:
171 return EPROTONOSUPPORT;
172 case WSAEOPNOTSUPP:
173 return EOPNOTSUPP;
174 case WSAEAFNOSUPPORT:
175 return EAFNOSUPPORT;
176 case WSAEADDRINUSE:
177 return EADDRINUSE;
178 case WSAEADDRNOTAVAIL:
179 return EADDRNOTAVAIL;
180 case WSAENETDOWN:
181 return ENETDOWN;
182 case WSAENETUNREACH:
183 return ENETUNREACH;
184 case WSAENETRESET:
185 return ENETRESET;
186 case WSAECONNABORTED:
187 return ECONNABORTED;
188 case WSAECONNRESET:
189 return ECONNRESET;
190 case WSAENOBUFS:
191 return ENOBUFS;
192 case WSAEISCONN:
193 return EISCONN;
194 case WSAENOTCONN:
195 return ENOTCONN;
196 case WSAETIMEDOUT:
197 return ETIMEDOUT;
198 case WSAECONNREFUSED:
199 return ECONNREFUSED;
200 case WSAELOOP:
201 return ELOOP;
202 case WSAEHOSTUNREACH:
203 return EHOSTUNREACH;
204 default:
205 return EIO;
209 void qemu_set_block(int fd)
211 unsigned long opt = 0;
212 WSAEventSelect(fd, NULL, 0);
213 ioctlsocket(fd, FIONBIO, &opt);
216 int qemu_try_set_nonblock(int fd)
218 unsigned long opt = 1;
219 if (ioctlsocket(fd, FIONBIO, &opt) != NO_ERROR) {
220 return -socket_error();
222 return 0;
225 void qemu_set_nonblock(int fd)
227 (void)qemu_try_set_nonblock(fd);
230 int socket_set_fast_reuse(int fd)
232 /* Enabling the reuse of an endpoint that was used by a socket still in
233 * TIME_WAIT state is usually performed by setting SO_REUSEADDR. On Windows
234 * fast reuse is the default and SO_REUSEADDR does strange things. So we
235 * don't have to do anything here. More info can be found at:
236 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621.aspx */
237 return 0;
240 int inet_aton(const char *cp, struct in_addr *ia)
242 uint32_t addr = inet_addr(cp);
243 if (addr == 0xffffffff) {
244 return 0;
246 ia->s_addr = addr;
247 return 1;
250 void qemu_set_cloexec(int fd)
254 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
255 #define _W32_FT_OFFSET (116444736000000000ULL)
257 int qemu_gettimeofday(qemu_timeval *tp)
259 union {
260 unsigned long long ns100; /*time since 1 Jan 1601 in 100ns units */
261 FILETIME ft;
262 } _now;
264 if(tp) {
265 GetSystemTimeAsFileTime (&_now.ft);
266 tp->tv_usec=(long)((_now.ns100 / 10ULL) % 1000000ULL );
267 tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000ULL);
269 /* Always return 0 as per Open Group Base Specifications Issue 6.
270 Do not set errno on error. */
271 return 0;
274 int qemu_get_thread_id(void)
276 return GetCurrentThreadId();
279 char *
280 qemu_get_local_state_pathname(const char *relative_pathname)
282 HRESULT result;
283 char base_path[MAX_PATH+1] = "";
285 result = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL,
286 /* SHGFP_TYPE_CURRENT */ 0, base_path);
287 if (result != S_OK) {
288 /* misconfigured environment */
289 g_critical("CSIDL_COMMON_APPDATA unavailable: %ld", (long)result);
290 abort();
292 return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", base_path,
293 relative_pathname);
296 void qemu_set_tty_echo(int fd, bool echo)
298 HANDLE handle = (HANDLE)_get_osfhandle(fd);
299 DWORD dwMode = 0;
301 if (handle == INVALID_HANDLE_VALUE) {
302 return;
305 GetConsoleMode(handle, &dwMode);
307 if (echo) {
308 SetConsoleMode(handle, dwMode | ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT);
309 } else {
310 SetConsoleMode(handle,
311 dwMode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT));
315 static const char *exec_dir;
317 void qemu_init_exec_dir(const char *argv0)
320 char *p;
321 char buf[MAX_PATH];
322 DWORD len;
324 if (exec_dir) {
325 return;
328 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
329 if (len == 0) {
330 return;
333 buf[len] = 0;
334 p = buf + len - 1;
335 while (p != buf && *p != '\\') {
336 p--;
338 *p = 0;
339 if (access(buf, R_OK) == 0) {
340 exec_dir = g_strdup(buf);
341 } else {
342 exec_dir = CONFIG_BINDIR;
346 const char *qemu_get_exec_dir(void)
348 return exec_dir;
351 #if !GLIB_CHECK_VERSION(2, 50, 0)
353 * The original implementation of g_poll from glib has a problem on Windows
354 * when using timeouts < 10 ms.
356 * Whenever g_poll is called with timeout < 10 ms, it does a quick poll instead
357 * of wait. This causes significant performance degradation of QEMU.
359 * The following code is a copy of the original code from glib/gpoll.c
360 * (glib commit 20f4d1820b8d4d0fc4447188e33efffd6d4a88d8 from 2014-02-19).
361 * Some debug code was removed and the code was reformatted.
362 * All other code modifications are marked with 'QEMU'.
366 * gpoll.c: poll(2) abstraction
367 * Copyright 1998 Owen Taylor
368 * Copyright 2008 Red Hat, Inc.
370 * This library is free software; you can redistribute it and/or
371 * modify it under the terms of the GNU Lesser General Public
372 * License as published by the Free Software Foundation; either
373 * version 2.1 of the License, or (at your option) any later version.
375 * This library is distributed in the hope that it will be useful,
376 * but WITHOUT ANY WARRANTY; without even the implied warranty of
377 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
378 * Lesser General Public License for more details.
380 * You should have received a copy of the GNU Lesser General Public
381 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
384 static int poll_rest(gboolean poll_msgs, HANDLE *handles, gint nhandles,
385 GPollFD *fds, guint nfds, gint timeout)
387 DWORD ready;
388 GPollFD *f;
389 int recursed_result;
391 if (poll_msgs) {
392 /* Wait for either messages or handles
393 * -> Use MsgWaitForMultipleObjectsEx
395 ready = MsgWaitForMultipleObjectsEx(nhandles, handles, timeout,
396 QS_ALLINPUT, MWMO_ALERTABLE);
398 if (ready == WAIT_FAILED) {
399 gchar *emsg = g_win32_error_message(GetLastError());
400 g_warning("MsgWaitForMultipleObjectsEx failed: %s", emsg);
401 g_free(emsg);
403 } else if (nhandles == 0) {
404 /* No handles to wait for, just the timeout */
405 if (timeout == INFINITE) {
406 ready = WAIT_FAILED;
407 } else {
408 SleepEx(timeout, TRUE);
409 ready = WAIT_TIMEOUT;
411 } else {
412 /* Wait for just handles
413 * -> Use WaitForMultipleObjectsEx
415 ready =
416 WaitForMultipleObjectsEx(nhandles, handles, FALSE, timeout, TRUE);
417 if (ready == WAIT_FAILED) {
418 gchar *emsg = g_win32_error_message(GetLastError());
419 g_warning("WaitForMultipleObjectsEx failed: %s", emsg);
420 g_free(emsg);
424 if (ready == WAIT_FAILED) {
425 return -1;
426 } else if (ready == WAIT_TIMEOUT || ready == WAIT_IO_COMPLETION) {
427 return 0;
428 } else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles) {
429 for (f = fds; f < &fds[nfds]; ++f) {
430 if (f->fd == G_WIN32_MSG_HANDLE && f->events & G_IO_IN) {
431 f->revents |= G_IO_IN;
435 /* If we have a timeout, or no handles to poll, be satisfied
436 * with just noticing we have messages waiting.
438 if (timeout != 0 || nhandles == 0) {
439 return 1;
442 /* If no timeout and handles to poll, recurse to poll them,
443 * too.
445 recursed_result = poll_rest(FALSE, handles, nhandles, fds, nfds, 0);
446 return (recursed_result == -1) ? -1 : 1 + recursed_result;
447 } else if (/* QEMU: removed the following unneeded statement which causes
448 * a compiler warning: ready >= WAIT_OBJECT_0 && */
449 ready < WAIT_OBJECT_0 + nhandles) {
450 for (f = fds; f < &fds[nfds]; ++f) {
451 if ((HANDLE) f->fd == handles[ready - WAIT_OBJECT_0]) {
452 f->revents = f->events;
456 /* If no timeout and polling several handles, recurse to poll
457 * the rest of them.
459 if (timeout == 0 && nhandles > 1) {
460 /* Remove the handle that fired */
461 int i;
462 for (i = ready - WAIT_OBJECT_0 + 1; i < nhandles; i++) {
463 handles[i-1] = handles[i];
465 nhandles--;
466 recursed_result = poll_rest(FALSE, handles, nhandles, fds, nfds, 0);
467 return (recursed_result == -1) ? -1 : 1 + recursed_result;
469 return 1;
472 return 0;
475 gint g_poll(GPollFD *fds, guint nfds, gint timeout)
477 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
478 gboolean poll_msgs = FALSE;
479 GPollFD *f;
480 gint nhandles = 0;
481 int retval;
483 for (f = fds; f < &fds[nfds]; ++f) {
484 if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN)) {
485 poll_msgs = TRUE;
486 } else if (f->fd > 0) {
487 /* Don't add the same handle several times into the array, as
488 * docs say that is not allowed, even if it actually does seem
489 * to work.
491 gint i;
493 for (i = 0; i < nhandles; i++) {
494 if (handles[i] == (HANDLE) f->fd) {
495 break;
499 if (i == nhandles) {
500 if (nhandles == MAXIMUM_WAIT_OBJECTS) {
501 g_warning("Too many handles to wait for!\n");
502 break;
503 } else {
504 handles[nhandles++] = (HANDLE) f->fd;
510 for (f = fds; f < &fds[nfds]; ++f) {
511 f->revents = 0;
514 if (timeout == -1) {
515 timeout = INFINITE;
518 /* Polling for several things? */
519 if (nhandles > 1 || (nhandles > 0 && poll_msgs)) {
520 /* First check if one or several of them are immediately
521 * available
523 retval = poll_rest(poll_msgs, handles, nhandles, fds, nfds, 0);
525 /* If not, and we have a significant timeout, poll again with
526 * timeout then. Note that this will return indication for only
527 * one event, or only for messages. We ignore timeouts less than
528 * ten milliseconds as they are mostly pointless on Windows, the
529 * MsgWaitForMultipleObjectsEx() call will timeout right away
530 * anyway.
532 * Modification for QEMU: replaced timeout >= 10 by timeout > 0.
534 if (retval == 0 && (timeout == INFINITE || timeout > 0)) {
535 retval = poll_rest(poll_msgs, handles, nhandles,
536 fds, nfds, timeout);
538 } else {
539 /* Just polling for one thing, so no need to check first if
540 * available immediately
542 retval = poll_rest(poll_msgs, handles, nhandles, fds, nfds, timeout);
545 if (retval == -1) {
546 for (f = fds; f < &fds[nfds]; ++f) {
547 f->revents = 0;
551 return retval;
553 #endif
555 int getpagesize(void)
557 SYSTEM_INFO system_info;
559 GetSystemInfo(&system_info);
560 return system_info.dwPageSize;
563 void os_mem_prealloc(int fd, char *area, size_t memory, int smp_cpus,
564 Error **errp)
566 int i;
567 size_t pagesize = qemu_real_host_page_size;
569 memory = (memory + pagesize - 1) & -pagesize;
570 for (i = 0; i < memory / pagesize; i++) {
571 memset(area + pagesize * i, 0, 1);
575 char *qemu_get_pid_name(pid_t pid)
577 /* XXX Implement me */
578 abort();
582 pid_t qemu_fork(Error **errp)
584 errno = ENOSYS;
585 error_setg_errno(errp, errno,
586 "cannot fork child process");
587 return -1;
591 #undef connect
592 int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
593 socklen_t addrlen)
595 int ret;
596 ret = connect(sockfd, addr, addrlen);
597 if (ret < 0) {
598 if (WSAGetLastError() == WSAEWOULDBLOCK) {
599 errno = EINPROGRESS;
600 } else {
601 errno = socket_error();
604 return ret;
608 #undef listen
609 int qemu_listen_wrap(int sockfd, int backlog)
611 int ret;
612 ret = listen(sockfd, backlog);
613 if (ret < 0) {
614 errno = socket_error();
616 return ret;
620 #undef bind
621 int qemu_bind_wrap(int sockfd, const struct sockaddr *addr,
622 socklen_t addrlen)
624 int ret;
625 ret = bind(sockfd, addr, addrlen);
626 if (ret < 0) {
627 errno = socket_error();
629 return ret;
633 #undef socket
634 int qemu_socket_wrap(int domain, int type, int protocol)
636 int ret;
637 ret = socket(domain, type, protocol);
638 if (ret < 0) {
639 errno = socket_error();
641 return ret;
645 #undef accept
646 int qemu_accept_wrap(int sockfd, struct sockaddr *addr,
647 socklen_t *addrlen)
649 int ret;
650 ret = accept(sockfd, addr, addrlen);
651 if (ret < 0) {
652 errno = socket_error();
654 return ret;
658 #undef shutdown
659 int qemu_shutdown_wrap(int sockfd, int how)
661 int ret;
662 ret = shutdown(sockfd, how);
663 if (ret < 0) {
664 errno = socket_error();
666 return ret;
670 #undef ioctlsocket
671 int qemu_ioctlsocket_wrap(int fd, int req, void *val)
673 int ret;
674 ret = ioctlsocket(fd, req, val);
675 if (ret < 0) {
676 errno = socket_error();
678 return ret;
682 #undef closesocket
683 int qemu_closesocket_wrap(int fd)
685 int ret;
686 ret = closesocket(fd);
687 if (ret < 0) {
688 errno = socket_error();
690 return ret;
694 #undef getsockopt
695 int qemu_getsockopt_wrap(int sockfd, int level, int optname,
696 void *optval, socklen_t *optlen)
698 int ret;
699 ret = getsockopt(sockfd, level, optname, optval, optlen);
700 if (ret < 0) {
701 errno = socket_error();
703 return ret;
707 #undef setsockopt
708 int qemu_setsockopt_wrap(int sockfd, int level, int optname,
709 const void *optval, socklen_t optlen)
711 int ret;
712 ret = setsockopt(sockfd, level, optname, optval, optlen);
713 if (ret < 0) {
714 errno = socket_error();
716 return ret;
720 #undef getpeername
721 int qemu_getpeername_wrap(int sockfd, struct sockaddr *addr,
722 socklen_t *addrlen)
724 int ret;
725 ret = getpeername(sockfd, addr, addrlen);
726 if (ret < 0) {
727 errno = socket_error();
729 return ret;
733 #undef getsockname
734 int qemu_getsockname_wrap(int sockfd, struct sockaddr *addr,
735 socklen_t *addrlen)
737 int ret;
738 ret = getsockname(sockfd, addr, addrlen);
739 if (ret < 0) {
740 errno = socket_error();
742 return ret;
746 #undef send
747 ssize_t qemu_send_wrap(int sockfd, const void *buf, size_t len, int flags)
749 int ret;
750 ret = send(sockfd, buf, len, flags);
751 if (ret < 0) {
752 errno = socket_error();
754 return ret;
758 #undef sendto
759 ssize_t qemu_sendto_wrap(int sockfd, const void *buf, size_t len, int flags,
760 const struct sockaddr *addr, socklen_t addrlen)
762 int ret;
763 ret = sendto(sockfd, buf, len, flags, addr, addrlen);
764 if (ret < 0) {
765 errno = socket_error();
767 return ret;
771 #undef recv
772 ssize_t qemu_recv_wrap(int sockfd, void *buf, size_t len, int flags)
774 int ret;
775 ret = recv(sockfd, buf, len, flags);
776 if (ret < 0) {
777 errno = socket_error();
779 return ret;
783 #undef recvfrom
784 ssize_t qemu_recvfrom_wrap(int sockfd, void *buf, size_t len, int flags,
785 struct sockaddr *addr, socklen_t *addrlen)
787 int ret;
788 ret = recvfrom(sockfd, buf, len, flags, addr, addrlen);
789 if (ret < 0) {
790 errno = socket_error();
792 return ret;
795 bool qemu_write_pidfile(const char *filename, Error **errp)
797 char buffer[128];
798 int len;
799 HANDLE file;
800 OVERLAPPED overlap;
801 BOOL ret;
802 memset(&overlap, 0, sizeof(overlap));
804 file = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ, NULL,
805 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
807 if (file == INVALID_HANDLE_VALUE) {
808 error_setg(errp, "Failed to create PID file");
809 return false;
811 len = snprintf(buffer, sizeof(buffer), FMT_pid "\n", (pid_t)getpid());
812 ret = WriteFile(file, (LPCVOID)buffer, (DWORD)len,
813 NULL, &overlap);
814 CloseHandle(file);
815 if (ret == 0) {
816 error_setg(errp, "Failed to write PID file");
817 return false;
819 return true;
822 char *qemu_get_host_name(Error **errp)
824 wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
825 DWORD size = G_N_ELEMENTS(tmp);
827 if (GetComputerNameW(tmp, &size) == 0) {
828 error_setg_win32(errp, GetLastError(), "failed close handle");
829 return NULL;
832 return g_utf16_to_utf8(tmp, size, NULL, NULL, NULL);
835 size_t qemu_get_host_physmem(void)
837 MEMORYSTATUSEX statex;
838 statex.dwLength = sizeof(statex);
840 if (GlobalMemoryStatusEx(&statex)) {
841 return statex.ullTotalPhys;
843 return 0;