xref: /qemu/util/oslib-win32.c (revision a4aafea2)
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 
29 #include "qemu/osdep.h"
30 #include <windows.h>
31 #include "qapi/error.h"
32 #include "qemu/main-loop.h"
33 #include "trace.h"
34 #include "qemu/sockets.h"
35 #include "qemu/cutils.h"
36 #include "qemu/error-report.h"
37 #include <malloc.h>
38 
39 static int get_allocation_granularity(void)
40 {
41     SYSTEM_INFO system_info;
42 
43     GetSystemInfo(&system_info);
44     return system_info.dwAllocationGranularity;
45 }
46 
47 void *qemu_anon_ram_alloc(size_t size, uint64_t *align, bool shared,
48                           bool noreserve)
49 {
50     void *ptr;
51 
52     if (noreserve) {
53         /*
54          * We need a MEM_COMMIT before accessing any memory in a MEM_RESERVE
55          * area; we cannot easily mimic POSIX MAP_NORESERVE semantics.
56          */
57         error_report("Skipping reservation of swap space is not supported.");
58         return NULL;
59     }
60 
61     ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
62     trace_qemu_anon_ram_alloc(size, ptr);
63 
64     if (ptr && align) {
65         *align = MAX(get_allocation_granularity(), getpagesize());
66     }
67     return ptr;
68 }
69 
70 void qemu_anon_ram_free(void *ptr, size_t size)
71 {
72     trace_qemu_anon_ram_free(ptr, size);
73     if (ptr) {
74         VirtualFree(ptr, 0, MEM_RELEASE);
75     }
76 }
77 
78 #ifndef _POSIX_THREAD_SAFE_FUNCTIONS
79 /* FIXME: add proper locking */
80 struct tm *gmtime_r(const time_t *timep, struct tm *result)
81 {
82     struct tm *p = gmtime(timep);
83     memset(result, 0, sizeof(*result));
84     if (p) {
85         *result = *p;
86         p = result;
87     }
88     return p;
89 }
90 
91 /* FIXME: add proper locking */
92 struct tm *localtime_r(const time_t *timep, struct tm *result)
93 {
94     struct tm *p = localtime(timep);
95     memset(result, 0, sizeof(*result));
96     if (p) {
97         *result = *p;
98         p = result;
99     }
100     return p;
101 }
102 #endif /* _POSIX_THREAD_SAFE_FUNCTIONS */
103 
104 static int socket_error(void)
105 {
106     switch (WSAGetLastError()) {
107     case 0:
108         return 0;
109     case WSAEINTR:
110         return EINTR;
111     case WSAEINVAL:
112         return EINVAL;
113     case WSA_INVALID_HANDLE:
114         return EBADF;
115     case WSA_NOT_ENOUGH_MEMORY:
116         return ENOMEM;
117     case WSA_INVALID_PARAMETER:
118         return EINVAL;
119     case WSAENAMETOOLONG:
120         return ENAMETOOLONG;
121     case WSAENOTEMPTY:
122         return ENOTEMPTY;
123     case WSAEWOULDBLOCK:
124          /* not using EWOULDBLOCK as we don't want code to have
125           * to check both EWOULDBLOCK and EAGAIN */
126         return EAGAIN;
127     case WSAEINPROGRESS:
128         return EINPROGRESS;
129     case WSAEALREADY:
130         return EALREADY;
131     case WSAENOTSOCK:
132         return ENOTSOCK;
133     case WSAEDESTADDRREQ:
134         return EDESTADDRREQ;
135     case WSAEMSGSIZE:
136         return EMSGSIZE;
137     case WSAEPROTOTYPE:
138         return EPROTOTYPE;
139     case WSAENOPROTOOPT:
140         return ENOPROTOOPT;
141     case WSAEPROTONOSUPPORT:
142         return EPROTONOSUPPORT;
143     case WSAEOPNOTSUPP:
144         return EOPNOTSUPP;
145     case WSAEAFNOSUPPORT:
146         return EAFNOSUPPORT;
147     case WSAEADDRINUSE:
148         return EADDRINUSE;
149     case WSAEADDRNOTAVAIL:
150         return EADDRNOTAVAIL;
151     case WSAENETDOWN:
152         return ENETDOWN;
153     case WSAENETUNREACH:
154         return ENETUNREACH;
155     case WSAENETRESET:
156         return ENETRESET;
157     case WSAECONNABORTED:
158         return ECONNABORTED;
159     case WSAECONNRESET:
160         return ECONNRESET;
161     case WSAENOBUFS:
162         return ENOBUFS;
163     case WSAEISCONN:
164         return EISCONN;
165     case WSAENOTCONN:
166         return ENOTCONN;
167     case WSAETIMEDOUT:
168         return ETIMEDOUT;
169     case WSAECONNREFUSED:
170         return ECONNREFUSED;
171     case WSAELOOP:
172         return ELOOP;
173     case WSAEHOSTUNREACH:
174         return EHOSTUNREACH;
175     default:
176         return EIO;
177     }
178 }
179 
180 void qemu_socket_set_block(int fd)
181 {
182     unsigned long opt = 0;
183     qemu_socket_unselect(fd, NULL);
184     ioctlsocket(fd, FIONBIO, &opt);
185 }
186 
187 int qemu_socket_try_set_nonblock(int fd)
188 {
189     unsigned long opt = 1;
190     if (ioctlsocket(fd, FIONBIO, &opt) != NO_ERROR) {
191         return -socket_error();
192     }
193     return 0;
194 }
195 
196 void qemu_socket_set_nonblock(int fd)
197 {
198     (void)qemu_socket_try_set_nonblock(fd);
199 }
200 
201 int socket_set_fast_reuse(int fd)
202 {
203     /* Enabling the reuse of an endpoint that was used by a socket still in
204      * TIME_WAIT state is usually performed by setting SO_REUSEADDR. On Windows
205      * fast reuse is the default and SO_REUSEADDR does strange things. So we
206      * don't have to do anything here. More info can be found at:
207      * http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621.aspx */
208     return 0;
209 }
210 
211 int inet_aton(const char *cp, struct in_addr *ia)
212 {
213     uint32_t addr = inet_addr(cp);
214     if (addr == 0xffffffff) {
215         return 0;
216     }
217     ia->s_addr = addr;
218     return 1;
219 }
220 
221 void qemu_set_cloexec(int fd)
222 {
223 }
224 
225 int qemu_get_thread_id(void)
226 {
227     return GetCurrentThreadId();
228 }
229 
230 char *
231 qemu_get_local_state_dir(void)
232 {
233     const char * const *data_dirs = g_get_system_data_dirs();
234 
235     g_assert(data_dirs && data_dirs[0]);
236 
237     return g_strdup(data_dirs[0]);
238 }
239 
240 void qemu_set_tty_echo(int fd, bool echo)
241 {
242     HANDLE handle = (HANDLE)_get_osfhandle(fd);
243     DWORD dwMode = 0;
244 
245     if (handle == INVALID_HANDLE_VALUE) {
246         return;
247     }
248 
249     GetConsoleMode(handle, &dwMode);
250 
251     if (echo) {
252         SetConsoleMode(handle, dwMode | ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT);
253     } else {
254         SetConsoleMode(handle,
255                        dwMode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT));
256     }
257 }
258 
259 int getpagesize(void)
260 {
261     SYSTEM_INFO system_info;
262 
263     GetSystemInfo(&system_info);
264     return system_info.dwPageSize;
265 }
266 
267 void qemu_prealloc_mem(int fd, char *area, size_t sz, int max_threads,
268                        ThreadContext *tc, Error **errp)
269 {
270     int i;
271     size_t pagesize = qemu_real_host_page_size();
272 
273     sz = (sz + pagesize - 1) & -pagesize;
274     for (i = 0; i < sz / pagesize; i++) {
275         memset(area + pagesize * i, 0, 1);
276     }
277 }
278 
279 char *qemu_get_pid_name(pid_t pid)
280 {
281     /* XXX Implement me */
282     abort();
283 }
284 
285 
286 bool qemu_socket_select(SOCKET s, WSAEVENT hEventObject,
287                         long lNetworkEvents, Error **errp)
288 {
289     if (errp == NULL) {
290         errp = &error_warn;
291     }
292 
293     if (WSAEventSelect(s, hEventObject, lNetworkEvents) != 0) {
294         error_setg_win32(errp, WSAGetLastError(), "failed to WSAEventSelect()");
295         return false;
296     }
297 
298     return true;
299 }
300 
301 bool qemu_socket_unselect(SOCKET s, Error **errp)
302 {
303     return qemu_socket_select(s, NULL, 0, errp);
304 }
305 
306 #undef connect
307 int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
308                       socklen_t addrlen)
309 {
310     int ret;
311     ret = connect(sockfd, addr, addrlen);
312     if (ret < 0) {
313         if (WSAGetLastError() == WSAEWOULDBLOCK) {
314             errno = EINPROGRESS;
315         } else {
316             errno = socket_error();
317         }
318     }
319     return ret;
320 }
321 
322 
323 #undef listen
324 int qemu_listen_wrap(int sockfd, int backlog)
325 {
326     int ret;
327     ret = listen(sockfd, backlog);
328     if (ret < 0) {
329         errno = socket_error();
330     }
331     return ret;
332 }
333 
334 
335 #undef bind
336 int qemu_bind_wrap(int sockfd, const struct sockaddr *addr,
337                    socklen_t addrlen)
338 {
339     int ret;
340     ret = bind(sockfd, addr, addrlen);
341     if (ret < 0) {
342         errno = socket_error();
343     }
344     return ret;
345 }
346 
347 
348 #undef socket
349 int qemu_socket_wrap(int domain, int type, int protocol)
350 {
351     int ret;
352     ret = socket(domain, type, protocol);
353     if (ret < 0) {
354         errno = socket_error();
355     }
356     return ret;
357 }
358 
359 
360 #undef accept
361 int qemu_accept_wrap(int sockfd, struct sockaddr *addr,
362                      socklen_t *addrlen)
363 {
364     int ret;
365     ret = accept(sockfd, addr, addrlen);
366     if (ret < 0) {
367         errno = socket_error();
368     }
369     return ret;
370 }
371 
372 
373 #undef shutdown
374 int qemu_shutdown_wrap(int sockfd, int how)
375 {
376     int ret;
377     ret = shutdown(sockfd, how);
378     if (ret < 0) {
379         errno = socket_error();
380     }
381     return ret;
382 }
383 
384 
385 #undef ioctlsocket
386 int qemu_ioctlsocket_wrap(int fd, int req, void *val)
387 {
388     int ret;
389     ret = ioctlsocket(fd, req, val);
390     if (ret < 0) {
391         errno = socket_error();
392     }
393     return ret;
394 }
395 
396 
397 #undef closesocket
398 int qemu_closesocket_wrap(int fd)
399 {
400     int ret;
401     ret = closesocket(fd);
402     if (ret < 0) {
403         errno = socket_error();
404     }
405     return ret;
406 }
407 
408 
409 #undef getsockopt
410 int qemu_getsockopt_wrap(int sockfd, int level, int optname,
411                          void *optval, socklen_t *optlen)
412 {
413     int ret;
414     ret = getsockopt(sockfd, level, optname, optval, optlen);
415     if (ret < 0) {
416         errno = socket_error();
417     }
418     return ret;
419 }
420 
421 
422 #undef setsockopt
423 int qemu_setsockopt_wrap(int sockfd, int level, int optname,
424                          const void *optval, socklen_t optlen)
425 {
426     int ret;
427     ret = setsockopt(sockfd, level, optname, optval, optlen);
428     if (ret < 0) {
429         errno = socket_error();
430     }
431     return ret;
432 }
433 
434 
435 #undef getpeername
436 int qemu_getpeername_wrap(int sockfd, struct sockaddr *addr,
437                           socklen_t *addrlen)
438 {
439     int ret;
440     ret = getpeername(sockfd, addr, addrlen);
441     if (ret < 0) {
442         errno = socket_error();
443     }
444     return ret;
445 }
446 
447 
448 #undef getsockname
449 int qemu_getsockname_wrap(int sockfd, struct sockaddr *addr,
450                           socklen_t *addrlen)
451 {
452     int ret;
453     ret = getsockname(sockfd, addr, addrlen);
454     if (ret < 0) {
455         errno = socket_error();
456     }
457     return ret;
458 }
459 
460 
461 #undef send
462 ssize_t qemu_send_wrap(int sockfd, const void *buf, size_t len, int flags)
463 {
464     int ret;
465     ret = send(sockfd, buf, len, flags);
466     if (ret < 0) {
467         errno = socket_error();
468     }
469     return ret;
470 }
471 
472 
473 #undef sendto
474 ssize_t qemu_sendto_wrap(int sockfd, const void *buf, size_t len, int flags,
475                          const struct sockaddr *addr, socklen_t addrlen)
476 {
477     int ret;
478     ret = sendto(sockfd, buf, len, flags, addr, addrlen);
479     if (ret < 0) {
480         errno = socket_error();
481     }
482     return ret;
483 }
484 
485 
486 #undef recv
487 ssize_t qemu_recv_wrap(int sockfd, void *buf, size_t len, int flags)
488 {
489     int ret;
490     ret = recv(sockfd, buf, len, flags);
491     if (ret < 0) {
492         errno = socket_error();
493     }
494     return ret;
495 }
496 
497 
498 #undef recvfrom
499 ssize_t qemu_recvfrom_wrap(int sockfd, void *buf, size_t len, int flags,
500                            struct sockaddr *addr, socklen_t *addrlen)
501 {
502     int ret;
503     ret = recvfrom(sockfd, buf, len, flags, addr, addrlen);
504     if (ret < 0) {
505         errno = socket_error();
506     }
507     return ret;
508 }
509 
510 bool qemu_write_pidfile(const char *filename, Error **errp)
511 {
512     char buffer[128];
513     int len;
514     HANDLE file;
515     OVERLAPPED overlap;
516     BOOL ret;
517     memset(&overlap, 0, sizeof(overlap));
518 
519     file = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ, NULL,
520                       OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
521 
522     if (file == INVALID_HANDLE_VALUE) {
523         error_setg(errp, "Failed to create PID file");
524         return false;
525     }
526     len = snprintf(buffer, sizeof(buffer), FMT_pid "\n", (pid_t)getpid());
527     ret = WriteFile(file, (LPCVOID)buffer, (DWORD)len,
528                     NULL, &overlap);
529     CloseHandle(file);
530     if (ret == 0) {
531         error_setg(errp, "Failed to write PID file");
532         return false;
533     }
534     return true;
535 }
536 
537 size_t qemu_get_host_physmem(void)
538 {
539     MEMORYSTATUSEX statex;
540     statex.dwLength = sizeof(statex);
541 
542     if (GlobalMemoryStatusEx(&statex)) {
543         return statex.ullTotalPhys;
544     }
545     return 0;
546 }
547 
548 int qemu_msync(void *addr, size_t length, int fd)
549 {
550     /**
551      * Perform the sync based on the file descriptor
552      * The sync range will most probably be wider than the one
553      * requested - but it will still get the job done
554      */
555     return qemu_fdatasync(fd);
556 }
557