Merge remote-tracking branch 'remotes/jasowang/tags/net-pull-request' into staging
[qemu.git] / util / oslib-win32.c
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 int getpagesize(void)
351 {
352 SYSTEM_INFO system_info;
353
354 GetSystemInfo(&system_info);
355 return system_info.dwPageSize;
356 }
357
358 void os_mem_prealloc(int fd, char *area, size_t memory, int smp_cpus,
359 Error **errp)
360 {
361 int i;
362 size_t pagesize = qemu_real_host_page_size;
363
364 memory = (memory + pagesize - 1) & -pagesize;
365 for (i = 0; i < memory / pagesize; i++) {
366 memset(area + pagesize * i, 0, 1);
367 }
368 }
369
370 char *qemu_get_pid_name(pid_t pid)
371 {
372 /* XXX Implement me */
373 abort();
374 }
375
376
377 pid_t qemu_fork(Error **errp)
378 {
379 errno = ENOSYS;
380 error_setg_errno(errp, errno,
381 "cannot fork child process");
382 return -1;
383 }
384
385
386 #undef connect
387 int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
388 socklen_t addrlen)
389 {
390 int ret;
391 ret = connect(sockfd, addr, addrlen);
392 if (ret < 0) {
393 if (WSAGetLastError() == WSAEWOULDBLOCK) {
394 errno = EINPROGRESS;
395 } else {
396 errno = socket_error();
397 }
398 }
399 return ret;
400 }
401
402
403 #undef listen
404 int qemu_listen_wrap(int sockfd, int backlog)
405 {
406 int ret;
407 ret = listen(sockfd, backlog);
408 if (ret < 0) {
409 errno = socket_error();
410 }
411 return ret;
412 }
413
414
415 #undef bind
416 int qemu_bind_wrap(int sockfd, const struct sockaddr *addr,
417 socklen_t addrlen)
418 {
419 int ret;
420 ret = bind(sockfd, addr, addrlen);
421 if (ret < 0) {
422 errno = socket_error();
423 }
424 return ret;
425 }
426
427
428 #undef socket
429 int qemu_socket_wrap(int domain, int type, int protocol)
430 {
431 int ret;
432 ret = socket(domain, type, protocol);
433 if (ret < 0) {
434 errno = socket_error();
435 }
436 return ret;
437 }
438
439
440 #undef accept
441 int qemu_accept_wrap(int sockfd, struct sockaddr *addr,
442 socklen_t *addrlen)
443 {
444 int ret;
445 ret = accept(sockfd, addr, addrlen);
446 if (ret < 0) {
447 errno = socket_error();
448 }
449 return ret;
450 }
451
452
453 #undef shutdown
454 int qemu_shutdown_wrap(int sockfd, int how)
455 {
456 int ret;
457 ret = shutdown(sockfd, how);
458 if (ret < 0) {
459 errno = socket_error();
460 }
461 return ret;
462 }
463
464
465 #undef ioctlsocket
466 int qemu_ioctlsocket_wrap(int fd, int req, void *val)
467 {
468 int ret;
469 ret = ioctlsocket(fd, req, val);
470 if (ret < 0) {
471 errno = socket_error();
472 }
473 return ret;
474 }
475
476
477 #undef closesocket
478 int qemu_closesocket_wrap(int fd)
479 {
480 int ret;
481 ret = closesocket(fd);
482 if (ret < 0) {
483 errno = socket_error();
484 }
485 return ret;
486 }
487
488
489 #undef getsockopt
490 int qemu_getsockopt_wrap(int sockfd, int level, int optname,
491 void *optval, socklen_t *optlen)
492 {
493 int ret;
494 ret = getsockopt(sockfd, level, optname, optval, optlen);
495 if (ret < 0) {
496 errno = socket_error();
497 }
498 return ret;
499 }
500
501
502 #undef setsockopt
503 int qemu_setsockopt_wrap(int sockfd, int level, int optname,
504 const void *optval, socklen_t optlen)
505 {
506 int ret;
507 ret = setsockopt(sockfd, level, optname, optval, optlen);
508 if (ret < 0) {
509 errno = socket_error();
510 }
511 return ret;
512 }
513
514
515 #undef getpeername
516 int qemu_getpeername_wrap(int sockfd, struct sockaddr *addr,
517 socklen_t *addrlen)
518 {
519 int ret;
520 ret = getpeername(sockfd, addr, addrlen);
521 if (ret < 0) {
522 errno = socket_error();
523 }
524 return ret;
525 }
526
527
528 #undef getsockname
529 int qemu_getsockname_wrap(int sockfd, struct sockaddr *addr,
530 socklen_t *addrlen)
531 {
532 int ret;
533 ret = getsockname(sockfd, addr, addrlen);
534 if (ret < 0) {
535 errno = socket_error();
536 }
537 return ret;
538 }
539
540
541 #undef send
542 ssize_t qemu_send_wrap(int sockfd, const void *buf, size_t len, int flags)
543 {
544 int ret;
545 ret = send(sockfd, buf, len, flags);
546 if (ret < 0) {
547 errno = socket_error();
548 }
549 return ret;
550 }
551
552
553 #undef sendto
554 ssize_t qemu_sendto_wrap(int sockfd, const void *buf, size_t len, int flags,
555 const struct sockaddr *addr, socklen_t addrlen)
556 {
557 int ret;
558 ret = sendto(sockfd, buf, len, flags, addr, addrlen);
559 if (ret < 0) {
560 errno = socket_error();
561 }
562 return ret;
563 }
564
565
566 #undef recv
567 ssize_t qemu_recv_wrap(int sockfd, void *buf, size_t len, int flags)
568 {
569 int ret;
570 ret = recv(sockfd, buf, len, flags);
571 if (ret < 0) {
572 errno = socket_error();
573 }
574 return ret;
575 }
576
577
578 #undef recvfrom
579 ssize_t qemu_recvfrom_wrap(int sockfd, void *buf, size_t len, int flags,
580 struct sockaddr *addr, socklen_t *addrlen)
581 {
582 int ret;
583 ret = recvfrom(sockfd, buf, len, flags, addr, addrlen);
584 if (ret < 0) {
585 errno = socket_error();
586 }
587 return ret;
588 }
589
590 bool qemu_write_pidfile(const char *filename, Error **errp)
591 {
592 char buffer[128];
593 int len;
594 HANDLE file;
595 OVERLAPPED overlap;
596 BOOL ret;
597 memset(&overlap, 0, sizeof(overlap));
598
599 file = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ, NULL,
600 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
601
602 if (file == INVALID_HANDLE_VALUE) {
603 error_setg(errp, "Failed to create PID file");
604 return false;
605 }
606 len = snprintf(buffer, sizeof(buffer), FMT_pid "\n", (pid_t)getpid());
607 ret = WriteFile(file, (LPCVOID)buffer, (DWORD)len,
608 NULL, &overlap);
609 CloseHandle(file);
610 if (ret == 0) {
611 error_setg(errp, "Failed to write PID file");
612 return false;
613 }
614 return true;
615 }
616
617 char *qemu_get_host_name(Error **errp)
618 {
619 wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
620 DWORD size = G_N_ELEMENTS(tmp);
621
622 if (GetComputerNameW(tmp, &size) == 0) {
623 error_setg_win32(errp, GetLastError(), "failed close handle");
624 return NULL;
625 }
626
627 return g_utf16_to_utf8(tmp, size, NULL, NULL, NULL);
628 }
629
630 size_t qemu_get_host_physmem(void)
631 {
632 MEMORYSTATUSEX statex;
633 statex.dwLength = sizeof(statex);
634
635 if (GlobalMemoryStatusEx(&statex)) {
636 return statex.ullTotalPhys;
637 }
638 return 0;
639 }