xref: /qemu/util/oslib-win32.c (revision d0fb9657)
1 /*
2  * os-win32.c
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  * Copyright (c) 2010-2016 Red Hat, Inc.
6  *
7  * QEMU library functions for win32 which are shared between QEMU and
8  * the QEMU tools.
9  *
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:
16  *
17  * The above copyright notice and this permission notice shall be included in
18  * all copies or substantial portions of the Software.
19  *
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.
27  *
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.
31  */
32 
33 #include "qemu/osdep.h"
34 #include <windows.h>
35 #include "qemu-common.h"
36 #include "qapi/error.h"
37 #include "qemu/main-loop.h"
38 #include "trace.h"
39 #include "qemu/sockets.h"
40 #include "qemu/cutils.h"
41 #include <malloc.h>
42 
43 /* this must come after including "trace.h" */
44 #include <shlobj.h>
45 
46 void *qemu_oom_check(void *ptr)
47 {
48     if (ptr == NULL) {
49         fprintf(stderr, "Failed to allocate memory: %lu\n", GetLastError());
50         abort();
51     }
52     return ptr;
53 }
54 
55 void *qemu_try_memalign(size_t alignment, size_t size)
56 {
57     void *ptr;
58 
59     g_assert(size != 0);
60     g_assert(is_power_of_2(alignment));
61     ptr = _aligned_malloc(size, alignment);
62     trace_qemu_memalign(alignment, size, ptr);
63     return ptr;
64 }
65 
66 void *qemu_memalign(size_t alignment, size_t size)
67 {
68     return qemu_oom_check(qemu_try_memalign(alignment, size));
69 }
70 
71 static int get_allocation_granularity(void)
72 {
73     SYSTEM_INFO system_info;
74 
75     GetSystemInfo(&system_info);
76     return system_info.dwAllocationGranularity;
77 }
78 
79 void *qemu_anon_ram_alloc(size_t size, uint64_t *align, bool shared)
80 {
81     void *ptr;
82 
83     ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
84     trace_qemu_anon_ram_alloc(size, ptr);
85 
86     if (ptr && align) {
87         *align = MAX(get_allocation_granularity(), getpagesize());
88     }
89     return ptr;
90 }
91 
92 void qemu_vfree(void *ptr)
93 {
94     trace_qemu_vfree(ptr);
95     _aligned_free(ptr);
96 }
97 
98 void qemu_anon_ram_free(void *ptr, size_t size)
99 {
100     trace_qemu_anon_ram_free(ptr, size);
101     if (ptr) {
102         VirtualFree(ptr, 0, MEM_RELEASE);
103     }
104 }
105 
106 #ifndef _POSIX_THREAD_SAFE_FUNCTIONS
107 /* FIXME: add proper locking */
108 struct tm *gmtime_r(const time_t *timep, struct tm *result)
109 {
110     struct tm *p = gmtime(timep);
111     memset(result, 0, sizeof(*result));
112     if (p) {
113         *result = *p;
114         p = result;
115     }
116     return p;
117 }
118 
119 /* FIXME: add proper locking */
120 struct tm *localtime_r(const time_t *timep, struct tm *result)
121 {
122     struct tm *p = localtime(timep);
123     memset(result, 0, sizeof(*result));
124     if (p) {
125         *result = *p;
126         p = result;
127     }
128     return p;
129 }
130 #endif /* _POSIX_THREAD_SAFE_FUNCTIONS */
131 
132 static int socket_error(void)
133 {
134     switch (WSAGetLastError()) {
135     case 0:
136         return 0;
137     case WSAEINTR:
138         return EINTR;
139     case WSAEINVAL:
140         return EINVAL;
141     case WSA_INVALID_HANDLE:
142         return EBADF;
143     case WSA_NOT_ENOUGH_MEMORY:
144         return ENOMEM;
145     case WSA_INVALID_PARAMETER:
146         return EINVAL;
147     case WSAENAMETOOLONG:
148         return ENAMETOOLONG;
149     case WSAENOTEMPTY:
150         return ENOTEMPTY;
151     case WSAEWOULDBLOCK:
152          /* not using EWOULDBLOCK as we don't want code to have
153           * to check both EWOULDBLOCK and EAGAIN */
154         return EAGAIN;
155     case WSAEINPROGRESS:
156         return EINPROGRESS;
157     case WSAEALREADY:
158         return EALREADY;
159     case WSAENOTSOCK:
160         return ENOTSOCK;
161     case WSAEDESTADDRREQ:
162         return EDESTADDRREQ;
163     case WSAEMSGSIZE:
164         return EMSGSIZE;
165     case WSAEPROTOTYPE:
166         return EPROTOTYPE;
167     case WSAENOPROTOOPT:
168         return ENOPROTOOPT;
169     case WSAEPROTONOSUPPORT:
170         return EPROTONOSUPPORT;
171     case WSAEOPNOTSUPP:
172         return EOPNOTSUPP;
173     case WSAEAFNOSUPPORT:
174         return EAFNOSUPPORT;
175     case WSAEADDRINUSE:
176         return EADDRINUSE;
177     case WSAEADDRNOTAVAIL:
178         return EADDRNOTAVAIL;
179     case WSAENETDOWN:
180         return ENETDOWN;
181     case WSAENETUNREACH:
182         return ENETUNREACH;
183     case WSAENETRESET:
184         return ENETRESET;
185     case WSAECONNABORTED:
186         return ECONNABORTED;
187     case WSAECONNRESET:
188         return ECONNRESET;
189     case WSAENOBUFS:
190         return ENOBUFS;
191     case WSAEISCONN:
192         return EISCONN;
193     case WSAENOTCONN:
194         return ENOTCONN;
195     case WSAETIMEDOUT:
196         return ETIMEDOUT;
197     case WSAECONNREFUSED:
198         return ECONNREFUSED;
199     case WSAELOOP:
200         return ELOOP;
201     case WSAEHOSTUNREACH:
202         return EHOSTUNREACH;
203     default:
204         return EIO;
205     }
206 }
207 
208 void qemu_set_block(int fd)
209 {
210     unsigned long opt = 0;
211     WSAEventSelect(fd, NULL, 0);
212     ioctlsocket(fd, FIONBIO, &opt);
213 }
214 
215 int qemu_try_set_nonblock(int fd)
216 {
217     unsigned long opt = 1;
218     if (ioctlsocket(fd, FIONBIO, &opt) != NO_ERROR) {
219         return -socket_error();
220     }
221     return 0;
222 }
223 
224 void qemu_set_nonblock(int fd)
225 {
226     (void)qemu_try_set_nonblock(fd);
227 }
228 
229 int socket_set_fast_reuse(int fd)
230 {
231     /* Enabling the reuse of an endpoint that was used by a socket still in
232      * TIME_WAIT state is usually performed by setting SO_REUSEADDR. On Windows
233      * fast reuse is the default and SO_REUSEADDR does strange things. So we
234      * don't have to do anything here. More info can be found at:
235      * http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621.aspx */
236     return 0;
237 }
238 
239 int inet_aton(const char *cp, struct in_addr *ia)
240 {
241     uint32_t addr = inet_addr(cp);
242     if (addr == 0xffffffff) {
243         return 0;
244     }
245     ia->s_addr = addr;
246     return 1;
247 }
248 
249 void qemu_set_cloexec(int fd)
250 {
251 }
252 
253 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
254 #define _W32_FT_OFFSET (116444736000000000ULL)
255 
256 int qemu_gettimeofday(qemu_timeval *tp)
257 {
258   union {
259     unsigned long long ns100; /*time since 1 Jan 1601 in 100ns units */
260     FILETIME ft;
261   }  _now;
262 
263   if(tp) {
264       GetSystemTimeAsFileTime (&_now.ft);
265       tp->tv_usec=(long)((_now.ns100 / 10ULL) % 1000000ULL );
266       tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000ULL);
267   }
268   /* Always return 0 as per Open Group Base Specifications Issue 6.
269      Do not set errno on error.  */
270   return 0;
271 }
272 
273 int qemu_get_thread_id(void)
274 {
275     return GetCurrentThreadId();
276 }
277 
278 char *
279 qemu_get_local_state_pathname(const char *relative_pathname)
280 {
281     HRESULT result;
282     char base_path[MAX_PATH+1] = "";
283 
284     result = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL,
285                              /* SHGFP_TYPE_CURRENT */ 0, base_path);
286     if (result != S_OK) {
287         /* misconfigured environment */
288         g_critical("CSIDL_COMMON_APPDATA unavailable: %ld", (long)result);
289         abort();
290     }
291     return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", base_path,
292                            relative_pathname);
293 }
294 
295 void qemu_set_tty_echo(int fd, bool echo)
296 {
297     HANDLE handle = (HANDLE)_get_osfhandle(fd);
298     DWORD dwMode = 0;
299 
300     if (handle == INVALID_HANDLE_VALUE) {
301         return;
302     }
303 
304     GetConsoleMode(handle, &dwMode);
305 
306     if (echo) {
307         SetConsoleMode(handle, dwMode | ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT);
308     } else {
309         SetConsoleMode(handle,
310                        dwMode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT));
311     }
312 }
313 
314 static const char *exec_dir;
315 
316 void qemu_init_exec_dir(const char *argv0)
317 {
318 
319     char *p;
320     char buf[MAX_PATH];
321     DWORD len;
322 
323     if (exec_dir) {
324         return;
325     }
326 
327     len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
328     if (len == 0) {
329         return;
330     }
331 
332     buf[len] = 0;
333     p = buf + len - 1;
334     while (p != buf && *p != '\\') {
335         p--;
336     }
337     *p = 0;
338     if (access(buf, R_OK) == 0) {
339         exec_dir = g_strdup(buf);
340     } else {
341         exec_dir = CONFIG_BINDIR;
342     }
343 }
344 
345 const char *qemu_get_exec_dir(void)
346 {
347     return exec_dir;
348 }
349 
350 #if !GLIB_CHECK_VERSION(2, 50, 0)
351 /*
352  * The original implementation of g_poll from glib has a problem on Windows
353  * when using timeouts < 10 ms.
354  *
355  * Whenever g_poll is called with timeout < 10 ms, it does a quick poll instead
356  * of wait. This causes significant performance degradation of QEMU.
357  *
358  * The following code is a copy of the original code from glib/gpoll.c
359  * (glib commit 20f4d1820b8d4d0fc4447188e33efffd6d4a88d8 from 2014-02-19).
360  * Some debug code was removed and the code was reformatted.
361  * All other code modifications are marked with 'QEMU'.
362  */
363 
364 /*
365  * gpoll.c: poll(2) abstraction
366  * Copyright 1998 Owen Taylor
367  * Copyright 2008 Red Hat, Inc.
368  *
369  * This library is free software; you can redistribute it and/or
370  * modify it under the terms of the GNU Lesser General Public
371  * License as published by the Free Software Foundation; either
372  * version 2.1 of the License, or (at your option) any later version.
373  *
374  * This library is distributed in the hope that it will be useful,
375  * but WITHOUT ANY WARRANTY; without even the implied warranty of
376  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
377  * Lesser General Public License for more details.
378  *
379  * You should have received a copy of the GNU Lesser General Public
380  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
381  */
382 
383 static int poll_rest(gboolean poll_msgs, HANDLE *handles, gint nhandles,
384                      GPollFD *fds, guint nfds, gint timeout)
385 {
386     DWORD ready;
387     GPollFD *f;
388     int recursed_result;
389 
390     if (poll_msgs) {
391         /* Wait for either messages or handles
392          * -> Use MsgWaitForMultipleObjectsEx
393          */
394         ready = MsgWaitForMultipleObjectsEx(nhandles, handles, timeout,
395                                             QS_ALLINPUT, MWMO_ALERTABLE);
396 
397         if (ready == WAIT_FAILED) {
398             gchar *emsg = g_win32_error_message(GetLastError());
399             g_warning("MsgWaitForMultipleObjectsEx failed: %s", emsg);
400             g_free(emsg);
401         }
402     } else if (nhandles == 0) {
403         /* No handles to wait for, just the timeout */
404         if (timeout == INFINITE) {
405             ready = WAIT_FAILED;
406         } else {
407             SleepEx(timeout, TRUE);
408             ready = WAIT_TIMEOUT;
409         }
410     } else {
411         /* Wait for just handles
412          * -> Use WaitForMultipleObjectsEx
413          */
414         ready =
415             WaitForMultipleObjectsEx(nhandles, handles, FALSE, timeout, TRUE);
416         if (ready == WAIT_FAILED) {
417             gchar *emsg = g_win32_error_message(GetLastError());
418             g_warning("WaitForMultipleObjectsEx failed: %s", emsg);
419             g_free(emsg);
420         }
421     }
422 
423     if (ready == WAIT_FAILED) {
424         return -1;
425     } else if (ready == WAIT_TIMEOUT || ready == WAIT_IO_COMPLETION) {
426         return 0;
427     } else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles) {
428         for (f = fds; f < &fds[nfds]; ++f) {
429             if (f->fd == G_WIN32_MSG_HANDLE && f->events & G_IO_IN) {
430                 f->revents |= G_IO_IN;
431             }
432         }
433 
434         /* If we have a timeout, or no handles to poll, be satisfied
435          * with just noticing we have messages waiting.
436          */
437         if (timeout != 0 || nhandles == 0) {
438             return 1;
439         }
440 
441         /* If no timeout and handles to poll, recurse to poll them,
442          * too.
443          */
444         recursed_result = poll_rest(FALSE, handles, nhandles, fds, nfds, 0);
445         return (recursed_result == -1) ? -1 : 1 + recursed_result;
446     } else if (/* QEMU: removed the following unneeded statement which causes
447                 * a compiler warning: ready >= WAIT_OBJECT_0 && */
448                ready < WAIT_OBJECT_0 + nhandles) {
449         for (f = fds; f < &fds[nfds]; ++f) {
450             if ((HANDLE) f->fd == handles[ready - WAIT_OBJECT_0]) {
451                 f->revents = f->events;
452             }
453         }
454 
455         /* If no timeout and polling several handles, recurse to poll
456          * the rest of them.
457          */
458         if (timeout == 0 && nhandles > 1) {
459             /* Remove the handle that fired */
460             int i;
461             for (i = ready - WAIT_OBJECT_0 + 1; i < nhandles; i++) {
462                 handles[i-1] = handles[i];
463             }
464             nhandles--;
465             recursed_result = poll_rest(FALSE, handles, nhandles, fds, nfds, 0);
466             return (recursed_result == -1) ? -1 : 1 + recursed_result;
467         }
468         return 1;
469     }
470 
471     return 0;
472 }
473 
474 gint g_poll_fixed(GPollFD *fds, guint nfds, gint timeout)
475 {
476     HANDLE handles[MAXIMUM_WAIT_OBJECTS];
477     gboolean poll_msgs = FALSE;
478     GPollFD *f;
479     gint nhandles = 0;
480     int retval;
481 
482     for (f = fds; f < &fds[nfds]; ++f) {
483         if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN)) {
484             poll_msgs = TRUE;
485         } else if (f->fd > 0) {
486             /* Don't add the same handle several times into the array, as
487              * docs say that is not allowed, even if it actually does seem
488              * to work.
489              */
490             gint i;
491 
492             for (i = 0; i < nhandles; i++) {
493                 if (handles[i] == (HANDLE) f->fd) {
494                     break;
495                 }
496             }
497 
498             if (i == nhandles) {
499                 if (nhandles == MAXIMUM_WAIT_OBJECTS) {
500                     g_warning("Too many handles to wait for!\n");
501                     break;
502                 } else {
503                     handles[nhandles++] = (HANDLE) f->fd;
504                 }
505             }
506         }
507     }
508 
509     for (f = fds; f < &fds[nfds]; ++f) {
510         f->revents = 0;
511     }
512 
513     if (timeout == -1) {
514         timeout = INFINITE;
515     }
516 
517     /* Polling for several things? */
518     if (nhandles > 1 || (nhandles > 0 && poll_msgs)) {
519         /* First check if one or several of them are immediately
520          * available
521          */
522         retval = poll_rest(poll_msgs, handles, nhandles, fds, nfds, 0);
523 
524         /* If not, and we have a significant timeout, poll again with
525          * timeout then. Note that this will return indication for only
526          * one event, or only for messages. We ignore timeouts less than
527          * ten milliseconds as they are mostly pointless on Windows, the
528          * MsgWaitForMultipleObjectsEx() call will timeout right away
529          * anyway.
530          *
531          * Modification for QEMU: replaced timeout >= 10 by timeout > 0.
532          */
533         if (retval == 0 && (timeout == INFINITE || timeout > 0)) {
534             retval = poll_rest(poll_msgs, handles, nhandles,
535                                fds, nfds, timeout);
536         }
537     } else {
538         /* Just polling for one thing, so no need to check first if
539          * available immediately
540          */
541         retval = poll_rest(poll_msgs, handles, nhandles, fds, nfds, timeout);
542     }
543 
544     if (retval == -1) {
545         for (f = fds; f < &fds[nfds]; ++f) {
546             f->revents = 0;
547         }
548     }
549 
550     return retval;
551 }
552 #endif
553 
554 int getpagesize(void)
555 {
556     SYSTEM_INFO system_info;
557 
558     GetSystemInfo(&system_info);
559     return system_info.dwPageSize;
560 }
561 
562 void os_mem_prealloc(int fd, char *area, size_t memory, int smp_cpus,
563                      Error **errp)
564 {
565     int i;
566     size_t pagesize = qemu_real_host_page_size;
567 
568     memory = (memory + pagesize - 1) & -pagesize;
569     for (i = 0; i < memory / pagesize; i++) {
570         memset(area + pagesize * i, 0, 1);
571     }
572 }
573 
574 char *qemu_get_pid_name(pid_t pid)
575 {
576     /* XXX Implement me */
577     abort();
578 }
579 
580 
581 pid_t qemu_fork(Error **errp)
582 {
583     errno = ENOSYS;
584     error_setg_errno(errp, errno,
585                      "cannot fork child process");
586     return -1;
587 }
588 
589 
590 #undef connect
591 int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
592                       socklen_t addrlen)
593 {
594     int ret;
595     ret = connect(sockfd, addr, addrlen);
596     if (ret < 0) {
597         if (WSAGetLastError() == WSAEWOULDBLOCK) {
598             errno = EINPROGRESS;
599         } else {
600             errno = socket_error();
601         }
602     }
603     return ret;
604 }
605 
606 
607 #undef listen
608 int qemu_listen_wrap(int sockfd, int backlog)
609 {
610     int ret;
611     ret = listen(sockfd, backlog);
612     if (ret < 0) {
613         errno = socket_error();
614     }
615     return ret;
616 }
617 
618 
619 #undef bind
620 int qemu_bind_wrap(int sockfd, const struct sockaddr *addr,
621                    socklen_t addrlen)
622 {
623     int ret;
624     ret = bind(sockfd, addr, addrlen);
625     if (ret < 0) {
626         errno = socket_error();
627     }
628     return ret;
629 }
630 
631 
632 #undef socket
633 int qemu_socket_wrap(int domain, int type, int protocol)
634 {
635     int ret;
636     ret = socket(domain, type, protocol);
637     if (ret < 0) {
638         errno = socket_error();
639     }
640     return ret;
641 }
642 
643 
644 #undef accept
645 int qemu_accept_wrap(int sockfd, struct sockaddr *addr,
646                      socklen_t *addrlen)
647 {
648     int ret;
649     ret = accept(sockfd, addr, addrlen);
650     if (ret < 0) {
651         errno = socket_error();
652     }
653     return ret;
654 }
655 
656 
657 #undef shutdown
658 int qemu_shutdown_wrap(int sockfd, int how)
659 {
660     int ret;
661     ret = shutdown(sockfd, how);
662     if (ret < 0) {
663         errno = socket_error();
664     }
665     return ret;
666 }
667 
668 
669 #undef ioctlsocket
670 int qemu_ioctlsocket_wrap(int fd, int req, void *val)
671 {
672     int ret;
673     ret = ioctlsocket(fd, req, val);
674     if (ret < 0) {
675         errno = socket_error();
676     }
677     return ret;
678 }
679 
680 
681 #undef closesocket
682 int qemu_closesocket_wrap(int fd)
683 {
684     int ret;
685     ret = closesocket(fd);
686     if (ret < 0) {
687         errno = socket_error();
688     }
689     return ret;
690 }
691 
692 
693 #undef getsockopt
694 int qemu_getsockopt_wrap(int sockfd, int level, int optname,
695                          void *optval, socklen_t *optlen)
696 {
697     int ret;
698     ret = getsockopt(sockfd, level, optname, optval, optlen);
699     if (ret < 0) {
700         errno = socket_error();
701     }
702     return ret;
703 }
704 
705 
706 #undef setsockopt
707 int qemu_setsockopt_wrap(int sockfd, int level, int optname,
708                          const void *optval, socklen_t optlen)
709 {
710     int ret;
711     ret = setsockopt(sockfd, level, optname, optval, optlen);
712     if (ret < 0) {
713         errno = socket_error();
714     }
715     return ret;
716 }
717 
718 
719 #undef getpeername
720 int qemu_getpeername_wrap(int sockfd, struct sockaddr *addr,
721                           socklen_t *addrlen)
722 {
723     int ret;
724     ret = getpeername(sockfd, addr, addrlen);
725     if (ret < 0) {
726         errno = socket_error();
727     }
728     return ret;
729 }
730 
731 
732 #undef getsockname
733 int qemu_getsockname_wrap(int sockfd, struct sockaddr *addr,
734                           socklen_t *addrlen)
735 {
736     int ret;
737     ret = getsockname(sockfd, addr, addrlen);
738     if (ret < 0) {
739         errno = socket_error();
740     }
741     return ret;
742 }
743 
744 
745 #undef send
746 ssize_t qemu_send_wrap(int sockfd, const void *buf, size_t len, int flags)
747 {
748     int ret;
749     ret = send(sockfd, buf, len, flags);
750     if (ret < 0) {
751         errno = socket_error();
752     }
753     return ret;
754 }
755 
756 
757 #undef sendto
758 ssize_t qemu_sendto_wrap(int sockfd, const void *buf, size_t len, int flags,
759                          const struct sockaddr *addr, socklen_t addrlen)
760 {
761     int ret;
762     ret = sendto(sockfd, buf, len, flags, addr, addrlen);
763     if (ret < 0) {
764         errno = socket_error();
765     }
766     return ret;
767 }
768 
769 
770 #undef recv
771 ssize_t qemu_recv_wrap(int sockfd, void *buf, size_t len, int flags)
772 {
773     int ret;
774     ret = recv(sockfd, buf, len, flags);
775     if (ret < 0) {
776         errno = socket_error();
777     }
778     return ret;
779 }
780 
781 
782 #undef recvfrom
783 ssize_t qemu_recvfrom_wrap(int sockfd, void *buf, size_t len, int flags,
784                            struct sockaddr *addr, socklen_t *addrlen)
785 {
786     int ret;
787     ret = recvfrom(sockfd, buf, len, flags, addr, addrlen);
788     if (ret < 0) {
789         errno = socket_error();
790     }
791     return ret;
792 }
793 
794 bool qemu_write_pidfile(const char *filename, Error **errp)
795 {
796     char buffer[128];
797     int len;
798     HANDLE file;
799     OVERLAPPED overlap;
800     BOOL ret;
801     memset(&overlap, 0, sizeof(overlap));
802 
803     file = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ, NULL,
804                       OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
805 
806     if (file == INVALID_HANDLE_VALUE) {
807         error_setg(errp, "Failed to create PID file");
808         return false;
809     }
810     len = snprintf(buffer, sizeof(buffer), FMT_pid "\n", (pid_t)getpid());
811     ret = WriteFile(file, (LPCVOID)buffer, (DWORD)len,
812                     NULL, &overlap);
813     CloseHandle(file);
814     if (ret == 0) {
815         error_setg(errp, "Failed to write PID file");
816         return false;
817     }
818     return true;
819 }
820 
821 char *qemu_get_host_name(Error **errp)
822 {
823     wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
824     DWORD size = G_N_ELEMENTS(tmp);
825 
826     if (GetComputerNameW(tmp, &size) == 0) {
827         error_setg_win32(errp, GetLastError(), "failed close handle");
828         return NULL;
829     }
830 
831     return g_utf16_to_utf8(tmp, size, NULL, NULL, NULL);
832 }
833 
834 size_t qemu_get_host_physmem(void)
835 {
836     MEMORYSTATUSEX statex;
837     statex.dwLength = sizeof(statex);
838 
839     if (GlobalMemoryStatusEx(&statex)) {
840         return statex.ullTotalPhys;
841     }
842     return 0;
843 }
844