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