xref: /openbmc/qemu/util/osdep.c (revision 69242e7e)
1 /*
2  * QEMU low level functions
3  *
4  * Copyright (c) 2003 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "qemu/osdep.h"
25 #include "qapi/error.h"
26 #include "qemu-common.h"
27 #include "qemu/cutils.h"
28 #include "qemu/sockets.h"
29 #include "qemu/error-report.h"
30 #include "qemu/madvise.h"
31 #include "qemu/mprotect.h"
32 #include "qemu/hw-version.h"
33 #include "monitor/monitor.h"
34 
35 static bool fips_enabled = false;
36 
37 static const char *hw_version = QEMU_HW_VERSION;
38 
39 int socket_set_cork(int fd, int v)
40 {
41 #if defined(SOL_TCP) && defined(TCP_CORK)
42     return setsockopt(fd, SOL_TCP, TCP_CORK, &v, sizeof(v));
43 #else
44     return 0;
45 #endif
46 }
47 
48 int socket_set_nodelay(int fd)
49 {
50     int v = 1;
51     return setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &v, sizeof(v));
52 }
53 
54 int qemu_madvise(void *addr, size_t len, int advice)
55 {
56     if (advice == QEMU_MADV_INVALID) {
57         errno = EINVAL;
58         return -1;
59     }
60 #if defined(CONFIG_MADVISE)
61     return madvise(addr, len, advice);
62 #elif defined(CONFIG_POSIX_MADVISE)
63     return posix_madvise(addr, len, advice);
64 #else
65     errno = EINVAL;
66     return -1;
67 #endif
68 }
69 
70 static int qemu_mprotect__osdep(void *addr, size_t size, int prot)
71 {
72     g_assert(!((uintptr_t)addr & ~qemu_real_host_page_mask()));
73     g_assert(!(size & ~qemu_real_host_page_mask()));
74 
75 #ifdef _WIN32
76     DWORD old_protect;
77 
78     if (!VirtualProtect(addr, size, prot, &old_protect)) {
79         g_autofree gchar *emsg = g_win32_error_message(GetLastError());
80         error_report("%s: VirtualProtect failed: %s", __func__, emsg);
81         return -1;
82     }
83     return 0;
84 #else
85     if (mprotect(addr, size, prot)) {
86         error_report("%s: mprotect failed: %s", __func__, strerror(errno));
87         return -1;
88     }
89     return 0;
90 #endif
91 }
92 
93 int qemu_mprotect_rw(void *addr, size_t size)
94 {
95 #ifdef _WIN32
96     return qemu_mprotect__osdep(addr, size, PAGE_READWRITE);
97 #else
98     return qemu_mprotect__osdep(addr, size, PROT_READ | PROT_WRITE);
99 #endif
100 }
101 
102 int qemu_mprotect_rwx(void *addr, size_t size)
103 {
104 #ifdef _WIN32
105     return qemu_mprotect__osdep(addr, size, PAGE_EXECUTE_READWRITE);
106 #else
107     return qemu_mprotect__osdep(addr, size, PROT_READ | PROT_WRITE | PROT_EXEC);
108 #endif
109 }
110 
111 int qemu_mprotect_none(void *addr, size_t size)
112 {
113 #ifdef _WIN32
114     return qemu_mprotect__osdep(addr, size, PAGE_NOACCESS);
115 #else
116     return qemu_mprotect__osdep(addr, size, PROT_NONE);
117 #endif
118 }
119 
120 #ifndef _WIN32
121 
122 static int fcntl_op_setlk = -1;
123 static int fcntl_op_getlk = -1;
124 
125 /*
126  * Dups an fd and sets the flags
127  */
128 int qemu_dup_flags(int fd, int flags)
129 {
130     int ret;
131     int serrno;
132     int dup_flags;
133 
134     ret = qemu_dup(fd);
135     if (ret == -1) {
136         goto fail;
137     }
138 
139     dup_flags = fcntl(ret, F_GETFL);
140     if (dup_flags == -1) {
141         goto fail;
142     }
143 
144     if ((flags & O_SYNC) != (dup_flags & O_SYNC)) {
145         errno = EINVAL;
146         goto fail;
147     }
148 
149     /* Set/unset flags that we can with fcntl */
150     if (fcntl(ret, F_SETFL, flags) == -1) {
151         goto fail;
152     }
153 
154     /* Truncate the file in the cases that open() would truncate it */
155     if (flags & O_TRUNC ||
156             ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))) {
157         if (ftruncate(ret, 0) == -1) {
158             goto fail;
159         }
160     }
161 
162     return ret;
163 
164 fail:
165     serrno = errno;
166     if (ret != -1) {
167         close(ret);
168     }
169     errno = serrno;
170     return -1;
171 }
172 
173 int qemu_dup(int fd)
174 {
175     int ret;
176 #ifdef F_DUPFD_CLOEXEC
177     ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);
178 #else
179     ret = dup(fd);
180     if (ret != -1) {
181         qemu_set_cloexec(ret);
182     }
183 #endif
184     return ret;
185 }
186 
187 static int qemu_parse_fdset(const char *param)
188 {
189     return qemu_parse_fd(param);
190 }
191 
192 static void qemu_probe_lock_ops(void)
193 {
194     if (fcntl_op_setlk == -1) {
195 #ifdef F_OFD_SETLK
196         int fd;
197         int ret;
198         struct flock fl = {
199             .l_whence = SEEK_SET,
200             .l_start  = 0,
201             .l_len    = 0,
202             .l_type   = F_WRLCK,
203         };
204 
205         fd = open("/dev/null", O_RDWR);
206         if (fd < 0) {
207             fprintf(stderr,
208                     "Failed to open /dev/null for OFD lock probing: %s\n",
209                     strerror(errno));
210             fcntl_op_setlk = F_SETLK;
211             fcntl_op_getlk = F_GETLK;
212             return;
213         }
214         ret = fcntl(fd, F_OFD_GETLK, &fl);
215         close(fd);
216         if (!ret) {
217             fcntl_op_setlk = F_OFD_SETLK;
218             fcntl_op_getlk = F_OFD_GETLK;
219         } else {
220             fcntl_op_setlk = F_SETLK;
221             fcntl_op_getlk = F_GETLK;
222         }
223 #else
224         fcntl_op_setlk = F_SETLK;
225         fcntl_op_getlk = F_GETLK;
226 #endif
227     }
228 }
229 
230 bool qemu_has_ofd_lock(void)
231 {
232     qemu_probe_lock_ops();
233 #ifdef F_OFD_SETLK
234     return fcntl_op_setlk == F_OFD_SETLK;
235 #else
236     return false;
237 #endif
238 }
239 
240 static int qemu_lock_fcntl(int fd, int64_t start, int64_t len, int fl_type)
241 {
242     int ret;
243     struct flock fl = {
244         .l_whence = SEEK_SET,
245         .l_start  = start,
246         .l_len    = len,
247         .l_type   = fl_type,
248     };
249     qemu_probe_lock_ops();
250     do {
251         ret = fcntl(fd, fcntl_op_setlk, &fl);
252     } while (ret == -1 && errno == EINTR);
253     return ret == -1 ? -errno : 0;
254 }
255 
256 int qemu_lock_fd(int fd, int64_t start, int64_t len, bool exclusive)
257 {
258     return qemu_lock_fcntl(fd, start, len, exclusive ? F_WRLCK : F_RDLCK);
259 }
260 
261 int qemu_unlock_fd(int fd, int64_t start, int64_t len)
262 {
263     return qemu_lock_fcntl(fd, start, len, F_UNLCK);
264 }
265 
266 int qemu_lock_fd_test(int fd, int64_t start, int64_t len, bool exclusive)
267 {
268     int ret;
269     struct flock fl = {
270         .l_whence = SEEK_SET,
271         .l_start  = start,
272         .l_len    = len,
273         .l_type   = exclusive ? F_WRLCK : F_RDLCK,
274     };
275     qemu_probe_lock_ops();
276     ret = fcntl(fd, fcntl_op_getlk, &fl);
277     if (ret == -1) {
278         return -errno;
279     } else {
280         return fl.l_type == F_UNLCK ? 0 : -EAGAIN;
281     }
282 }
283 #endif
284 
285 static int qemu_open_cloexec(const char *name, int flags, mode_t mode)
286 {
287     int ret;
288 #ifdef O_CLOEXEC
289     ret = open(name, flags | O_CLOEXEC, mode);
290 #else
291     ret = open(name, flags, mode);
292     if (ret >= 0) {
293         qemu_set_cloexec(ret);
294     }
295 #endif
296     return ret;
297 }
298 
299 /*
300  * Opens a file with FD_CLOEXEC set
301  */
302 static int
303 qemu_open_internal(const char *name, int flags, mode_t mode, Error **errp)
304 {
305     int ret;
306 
307 #ifndef _WIN32
308     const char *fdset_id_str;
309 
310     /* Attempt dup of fd from fd set */
311     if (strstart(name, "/dev/fdset/", &fdset_id_str)) {
312         int64_t fdset_id;
313         int dupfd;
314 
315         fdset_id = qemu_parse_fdset(fdset_id_str);
316         if (fdset_id == -1) {
317             error_setg(errp, "Could not parse fdset %s", name);
318             errno = EINVAL;
319             return -1;
320         }
321 
322         dupfd = monitor_fdset_dup_fd_add(fdset_id, flags);
323         if (dupfd == -1) {
324             error_setg_errno(errp, errno, "Could not dup FD for %s flags %x",
325                              name, flags);
326             return -1;
327         }
328 
329         return dupfd;
330     }
331 #endif
332 
333     ret = qemu_open_cloexec(name, flags, mode);
334 
335     if (ret == -1) {
336         const char *action = flags & O_CREAT ? "create" : "open";
337 #ifdef O_DIRECT
338         /* Give more helpful error message for O_DIRECT */
339         if (errno == EINVAL && (flags & O_DIRECT)) {
340             ret = open(name, flags & ~O_DIRECT, mode);
341             if (ret != -1) {
342                 close(ret);
343                 error_setg(errp, "Could not %s '%s': "
344                            "filesystem does not support O_DIRECT",
345                            action, name);
346                 errno = EINVAL; /* restore first open()'s errno */
347                 return -1;
348             }
349         }
350 #endif /* O_DIRECT */
351         error_setg_errno(errp, errno, "Could not %s '%s'",
352                          action, name);
353     }
354 
355     return ret;
356 }
357 
358 
359 int qemu_open(const char *name, int flags, Error **errp)
360 {
361     assert(!(flags & O_CREAT));
362 
363     return qemu_open_internal(name, flags, 0, errp);
364 }
365 
366 
367 int qemu_create(const char *name, int flags, mode_t mode, Error **errp)
368 {
369     assert(!(flags & O_CREAT));
370 
371     return qemu_open_internal(name, flags | O_CREAT, mode, errp);
372 }
373 
374 
375 int qemu_open_old(const char *name, int flags, ...)
376 {
377     va_list ap;
378     mode_t mode = 0;
379     int ret;
380 
381     va_start(ap, flags);
382     if (flags & O_CREAT) {
383         mode = va_arg(ap, int);
384     }
385     va_end(ap);
386 
387     ret = qemu_open_internal(name, flags, mode, NULL);
388 
389 #ifdef O_DIRECT
390     if (ret == -1 && errno == EINVAL && (flags & O_DIRECT)) {
391         error_report("file system may not support O_DIRECT");
392         errno = EINVAL; /* in case it was clobbered */
393     }
394 #endif /* O_DIRECT */
395 
396     return ret;
397 }
398 
399 int qemu_close(int fd)
400 {
401     int64_t fdset_id;
402 
403     /* Close fd that was dup'd from an fdset */
404     fdset_id = monitor_fdset_dup_fd_find(fd);
405     if (fdset_id != -1) {
406         int ret;
407 
408         ret = close(fd);
409         if (ret == 0) {
410             monitor_fdset_dup_fd_remove(fd);
411         }
412 
413         return ret;
414     }
415 
416     return close(fd);
417 }
418 
419 /*
420  * Delete a file from the filesystem, unless the filename is /dev/fdset/...
421  *
422  * Returns: On success, zero is returned.  On error, -1 is returned,
423  * and errno is set appropriately.
424  */
425 int qemu_unlink(const char *name)
426 {
427     if (g_str_has_prefix(name, "/dev/fdset/")) {
428         return 0;
429     }
430 
431     return unlink(name);
432 }
433 
434 /*
435  * A variant of write(2) which handles partial write.
436  *
437  * Return the number of bytes transferred.
438  * Set errno if fewer than `count' bytes are written.
439  *
440  * This function don't work with non-blocking fd's.
441  * Any of the possibilities with non-blocking fd's is bad:
442  *   - return a short write (then name is wrong)
443  *   - busy wait adding (errno == EAGAIN) to the loop
444  */
445 ssize_t qemu_write_full(int fd, const void *buf, size_t count)
446 {
447     ssize_t ret = 0;
448     ssize_t total = 0;
449 
450     while (count) {
451         ret = write(fd, buf, count);
452         if (ret < 0) {
453             if (errno == EINTR)
454                 continue;
455             break;
456         }
457 
458         count -= ret;
459         buf += ret;
460         total += ret;
461     }
462 
463     return total;
464 }
465 
466 /*
467  * Opens a socket with FD_CLOEXEC set
468  */
469 int qemu_socket(int domain, int type, int protocol)
470 {
471     int ret;
472 
473 #ifdef SOCK_CLOEXEC
474     ret = socket(domain, type | SOCK_CLOEXEC, protocol);
475     if (ret != -1 || errno != EINVAL) {
476         return ret;
477     }
478 #endif
479     ret = socket(domain, type, protocol);
480     if (ret >= 0) {
481         qemu_set_cloexec(ret);
482     }
483 
484     return ret;
485 }
486 
487 /*
488  * Accept a connection and set FD_CLOEXEC
489  */
490 int qemu_accept(int s, struct sockaddr *addr, socklen_t *addrlen)
491 {
492     int ret;
493 
494 #ifdef CONFIG_ACCEPT4
495     ret = accept4(s, addr, addrlen, SOCK_CLOEXEC);
496     if (ret != -1 || errno != ENOSYS) {
497         return ret;
498     }
499 #endif
500     ret = accept(s, addr, addrlen);
501     if (ret >= 0) {
502         qemu_set_cloexec(ret);
503     }
504 
505     return ret;
506 }
507 
508 void qemu_set_hw_version(const char *version)
509 {
510     hw_version = version;
511 }
512 
513 const char *qemu_hw_version(void)
514 {
515     return hw_version;
516 }
517 
518 void fips_set_state(bool requested)
519 {
520 #ifdef __linux__
521     if (requested) {
522         FILE *fds = fopen("/proc/sys/crypto/fips_enabled", "r");
523         if (fds != NULL) {
524             fips_enabled = (fgetc(fds) == '1');
525             fclose(fds);
526         }
527     }
528 #else
529     fips_enabled = false;
530 #endif /* __linux__ */
531 
532 #ifdef _FIPS_DEBUG
533     fprintf(stderr, "FIPS mode %s (requested %s)\n",
534             (fips_enabled ? "enabled" : "disabled"),
535             (requested ? "enabled" : "disabled"));
536 #endif
537 }
538 
539 bool fips_get_state(void)
540 {
541     return fips_enabled;
542 }
543 
544 #ifdef _WIN32
545 static void socket_cleanup(void)
546 {
547     WSACleanup();
548 }
549 #endif
550 
551 int socket_init(void)
552 {
553 #ifdef _WIN32
554     WSADATA Data;
555     int ret, err;
556 
557     ret = WSAStartup(MAKEWORD(2, 2), &Data);
558     if (ret != 0) {
559         err = WSAGetLastError();
560         fprintf(stderr, "WSAStartup: %d\n", err);
561         return -1;
562     }
563     atexit(socket_cleanup);
564 #endif
565     return 0;
566 }
567 
568 
569 #ifndef CONFIG_IOVEC
570 /* helper function for iov_send_recv() */
571 static ssize_t
572 readv_writev(int fd, const struct iovec *iov, int iov_cnt, bool do_write)
573 {
574     unsigned i = 0;
575     ssize_t ret = 0;
576     while (i < iov_cnt) {
577         ssize_t r = do_write
578             ? write(fd, iov[i].iov_base, iov[i].iov_len)
579             : read(fd, iov[i].iov_base, iov[i].iov_len);
580         if (r > 0) {
581             ret += r;
582         } else if (!r) {
583             break;
584         } else if (errno == EINTR) {
585             continue;
586         } else {
587             /* else it is some "other" error,
588              * only return if there was no data processed. */
589             if (ret == 0) {
590                 ret = -1;
591             }
592             break;
593         }
594         i++;
595     }
596     return ret;
597 }
598 
599 ssize_t
600 readv(int fd, const struct iovec *iov, int iov_cnt)
601 {
602     return readv_writev(fd, iov, iov_cnt, false);
603 }
604 
605 ssize_t
606 writev(int fd, const struct iovec *iov, int iov_cnt)
607 {
608     return readv_writev(fd, iov, iov_cnt, true);
609 }
610 #endif
611