xref: /openbmc/qemu/chardev/char.c (revision 6fdafac1c165821054e1d0786bd6630e90f2379f)
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 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 "qemu-common.h"
26 #include "qemu/cutils.h"
27 #include "monitor/monitor.h"
28 #include "sysemu/sysemu.h"
29 #include "sysemu/block-backend.h"
30 #include "qemu/error-report.h"
31 #include "qemu/timer.h"
32 #include "sysemu/char.h"
33 #include "hw/usb.h"
34 #include "qmp-commands.h"
35 #include "qapi/clone-visitor.h"
36 #include "qapi-visit.h"
37 #include "qemu/base64.h"
38 #include "io/channel-socket.h"
39 #include "io/channel-file.h"
40 #include "io/channel-tls.h"
41 #include "sysemu/replay.h"
42 #include "qemu/help_option.h"
43 
44 #include <zlib.h>
45 
46 #ifndef _WIN32
47 #include <sys/times.h>
48 #include <sys/wait.h>
49 #include <termios.h>
50 #include <sys/ioctl.h>
51 #include <sys/resource.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
54 #include <net/if.h>
55 #include <arpa/inet.h>
56 #include <netdb.h>
57 #include <sys/select.h>
58 #ifdef CONFIG_BSD
59 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
60 #include <dev/ppbus/ppi.h>
61 #include <dev/ppbus/ppbconf.h>
62 #elif defined(__DragonFly__)
63 #include <dev/misc/ppi/ppi.h>
64 #include <bus/ppbus/ppbconf.h>
65 #endif
66 #else
67 #ifdef __linux__
68 #include <linux/ppdev.h>
69 #include <linux/parport.h>
70 #endif
71 #ifdef __sun__
72 #include <sys/ethernet.h>
73 #include <sys/sockio.h>
74 #include <netinet/arp.h>
75 #include <netinet/in.h>
76 #include <netinet/in_systm.h>
77 #include <netinet/ip.h>
78 #include <netinet/ip_icmp.h> // must come after ip.h
79 #include <netinet/udp.h>
80 #include <netinet/tcp.h>
81 #endif
82 #endif
83 #endif
84 
85 #include "qemu/sockets.h"
86 #include "ui/qemu-spice.h"
87 
88 #include "char-mux.h"
89 #include "char-fd.h"
90 #include "char-io.h"
91 #ifdef _WIN32
92 #include "char-win.h"
93 #include "char-win-stdio.h"
94 #endif
95 
96 /***********************************************************/
97 /* character device */
98 
99 static QTAILQ_HEAD(ChardevHead, Chardev) chardevs =
100     QTAILQ_HEAD_INITIALIZER(chardevs);
101 
102 void qemu_chr_be_event(Chardev *s, int event)
103 {
104     CharBackend *be = s->be;
105 
106     /* Keep track if the char device is open */
107     switch (event) {
108         case CHR_EVENT_OPENED:
109             s->be_open = 1;
110             break;
111         case CHR_EVENT_CLOSED:
112             s->be_open = 0;
113             break;
114     }
115 
116     if (!be || !be->chr_event) {
117         return;
118     }
119 
120     be->chr_event(be->opaque, event);
121 }
122 
123 void qemu_chr_be_generic_open(Chardev *s)
124 {
125     qemu_chr_be_event(s, CHR_EVENT_OPENED);
126 }
127 
128 
129 /* Not reporting errors from writing to logfile, as logs are
130  * defined to be "best effort" only */
131 static void qemu_chr_fe_write_log(Chardev *s,
132                                   const uint8_t *buf, size_t len)
133 {
134     size_t done = 0;
135     ssize_t ret;
136 
137     if (s->logfd < 0) {
138         return;
139     }
140 
141     while (done < len) {
142     retry:
143         ret = write(s->logfd, buf + done, len - done);
144         if (ret == -1 && errno == EAGAIN) {
145             g_usleep(100);
146             goto retry;
147         }
148 
149         if (ret <= 0) {
150             return;
151         }
152         done += ret;
153     }
154 }
155 
156 static int qemu_chr_fe_write_buffer(Chardev *s,
157                                     const uint8_t *buf, int len, int *offset)
158 {
159     ChardevClass *cc = CHARDEV_GET_CLASS(s);
160     int res = 0;
161     *offset = 0;
162 
163     qemu_mutex_lock(&s->chr_write_lock);
164     while (*offset < len) {
165     retry:
166         res = cc->chr_write(s, buf + *offset, len - *offset);
167         if (res < 0 && errno == EAGAIN) {
168             g_usleep(100);
169             goto retry;
170         }
171 
172         if (res <= 0) {
173             break;
174         }
175 
176         *offset += res;
177     }
178     if (*offset > 0) {
179         qemu_chr_fe_write_log(s, buf, *offset);
180     }
181     qemu_mutex_unlock(&s->chr_write_lock);
182 
183     return res;
184 }
185 
186 static bool qemu_chr_replay(Chardev *chr)
187 {
188     return qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_REPLAY);
189 }
190 
191 int qemu_chr_fe_write(CharBackend *be, const uint8_t *buf, int len)
192 {
193     Chardev *s = be->chr;
194     ChardevClass *cc;
195     int ret;
196 
197     if (!s) {
198         return 0;
199     }
200 
201     if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_PLAY) {
202         int offset;
203         replay_char_write_event_load(&ret, &offset);
204         assert(offset <= len);
205         qemu_chr_fe_write_buffer(s, buf, offset, &offset);
206         return ret;
207     }
208 
209     cc = CHARDEV_GET_CLASS(s);
210     qemu_mutex_lock(&s->chr_write_lock);
211     ret = cc->chr_write(s, buf, len);
212 
213     if (ret > 0) {
214         qemu_chr_fe_write_log(s, buf, ret);
215     }
216 
217     qemu_mutex_unlock(&s->chr_write_lock);
218 
219     if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
220         replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
221     }
222 
223     return ret;
224 }
225 
226 int qemu_chr_write_all(Chardev *s, const uint8_t *buf, int len)
227 {
228     int offset;
229     int res;
230 
231     if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_PLAY) {
232         replay_char_write_event_load(&res, &offset);
233         assert(offset <= len);
234         qemu_chr_fe_write_buffer(s, buf, offset, &offset);
235         return res;
236     }
237 
238     res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
239 
240     if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
241         replay_char_write_event_save(res, offset);
242     }
243 
244     if (res < 0) {
245         return res;
246     }
247     return offset;
248 }
249 
250 int qemu_chr_fe_write_all(CharBackend *be, const uint8_t *buf, int len)
251 {
252     Chardev *s = be->chr;
253 
254     if (!s) {
255         return 0;
256     }
257 
258     return qemu_chr_write_all(s, buf, len);
259 }
260 
261 int qemu_chr_fe_read_all(CharBackend *be, uint8_t *buf, int len)
262 {
263     Chardev *s = be->chr;
264     int offset = 0, counter = 10;
265     int res;
266 
267     if (!s || !CHARDEV_GET_CLASS(s)->chr_sync_read) {
268         return 0;
269     }
270 
271     if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_PLAY) {
272         return replay_char_read_all_load(buf);
273     }
274 
275     while (offset < len) {
276     retry:
277         res = CHARDEV_GET_CLASS(s)->chr_sync_read(s, buf + offset,
278                                                   len - offset);
279         if (res == -1 && errno == EAGAIN) {
280             g_usleep(100);
281             goto retry;
282         }
283 
284         if (res == 0) {
285             break;
286         }
287 
288         if (res < 0) {
289             if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
290                 replay_char_read_all_save_error(res);
291             }
292             return res;
293         }
294 
295         offset += res;
296 
297         if (!counter--) {
298             break;
299         }
300     }
301 
302     if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
303         replay_char_read_all_save_buf(buf, offset);
304     }
305     return offset;
306 }
307 
308 int qemu_chr_fe_ioctl(CharBackend *be, int cmd, void *arg)
309 {
310     Chardev *s = be->chr;
311     int res;
312 
313     if (!s || !CHARDEV_GET_CLASS(s)->chr_ioctl || qemu_chr_replay(s)) {
314         res = -ENOTSUP;
315     } else {
316         res = CHARDEV_GET_CLASS(s)->chr_ioctl(s, cmd, arg);
317     }
318 
319     return res;
320 }
321 
322 int qemu_chr_be_can_write(Chardev *s)
323 {
324     CharBackend *be = s->be;
325 
326     if (!be || !be->chr_can_read) {
327         return 0;
328     }
329 
330     return be->chr_can_read(be->opaque);
331 }
332 
333 void qemu_chr_be_write_impl(Chardev *s, uint8_t *buf, int len)
334 {
335     CharBackend *be = s->be;
336 
337     if (be && be->chr_read) {
338         be->chr_read(be->opaque, buf, len);
339     }
340 }
341 
342 void qemu_chr_be_write(Chardev *s, uint8_t *buf, int len)
343 {
344     if (qemu_chr_replay(s)) {
345         if (replay_mode == REPLAY_MODE_PLAY) {
346             return;
347         }
348         replay_chr_be_write(s, buf, len);
349     } else {
350         qemu_chr_be_write_impl(s, buf, len);
351     }
352 }
353 
354 int qemu_chr_fe_get_msgfd(CharBackend *be)
355 {
356     Chardev *s = be->chr;
357     int fd;
358     int res = (qemu_chr_fe_get_msgfds(be, &fd, 1) == 1) ? fd : -1;
359     if (s && qemu_chr_replay(s)) {
360         error_report("Replay: get msgfd is not supported "
361                      "for serial devices yet");
362         exit(1);
363     }
364     return res;
365 }
366 
367 int qemu_chr_fe_get_msgfds(CharBackend *be, int *fds, int len)
368 {
369     Chardev *s = be->chr;
370 
371     if (!s) {
372         return -1;
373     }
374 
375     return CHARDEV_GET_CLASS(s)->get_msgfds ?
376         CHARDEV_GET_CLASS(s)->get_msgfds(s, fds, len) : -1;
377 }
378 
379 int qemu_chr_fe_set_msgfds(CharBackend *be, int *fds, int num)
380 {
381     Chardev *s = be->chr;
382 
383     if (!s) {
384         return -1;
385     }
386 
387     return CHARDEV_GET_CLASS(s)->set_msgfds ?
388         CHARDEV_GET_CLASS(s)->set_msgfds(s, fds, num) : -1;
389 }
390 
391 int qemu_chr_add_client(Chardev *s, int fd)
392 {
393     return CHARDEV_GET_CLASS(s)->chr_add_client ?
394         CHARDEV_GET_CLASS(s)->chr_add_client(s, fd) : -1;
395 }
396 
397 void qemu_chr_fe_accept_input(CharBackend *be)
398 {
399     Chardev *s = be->chr;
400 
401     if (!s) {
402         return;
403     }
404 
405     if (CHARDEV_GET_CLASS(s)->chr_accept_input) {
406         CHARDEV_GET_CLASS(s)->chr_accept_input(s);
407     }
408     qemu_notify_event();
409 }
410 
411 void qemu_chr_fe_printf(CharBackend *be, const char *fmt, ...)
412 {
413     char buf[CHR_READ_BUF_LEN];
414     va_list ap;
415     va_start(ap, fmt);
416     vsnprintf(buf, sizeof(buf), fmt, ap);
417     /* XXX this blocks entire thread. Rewrite to use
418      * qemu_chr_fe_write and background I/O callbacks */
419     qemu_chr_fe_write_all(be, (uint8_t *)buf, strlen(buf));
420     va_end(ap);
421 }
422 
423 static void qemu_char_open(Chardev *chr, ChardevBackend *backend,
424                            bool *be_opened, Error **errp)
425 {
426     ChardevClass *cc = CHARDEV_GET_CLASS(chr);
427     /* Any ChardevCommon member would work */
428     ChardevCommon *common = backend ? backend->u.null.data : NULL;
429 
430     if (common && common->has_logfile) {
431         int flags = O_WRONLY | O_CREAT;
432         if (common->has_logappend &&
433             common->logappend) {
434             flags |= O_APPEND;
435         } else {
436             flags |= O_TRUNC;
437         }
438         chr->logfd = qemu_open(common->logfile, flags, 0666);
439         if (chr->logfd < 0) {
440             error_setg_errno(errp, errno,
441                              "Unable to open logfile %s",
442                              common->logfile);
443             return;
444         }
445     }
446 
447     if (cc->open) {
448         cc->open(chr, backend, be_opened, errp);
449     }
450 }
451 
452 static void char_init(Object *obj)
453 {
454     Chardev *chr = CHARDEV(obj);
455 
456     chr->logfd = -1;
457     qemu_mutex_init(&chr->chr_write_lock);
458 }
459 
460 static int null_chr_write(Chardev *chr, const uint8_t *buf, int len)
461 {
462     return len;
463 }
464 
465 static void char_class_init(ObjectClass *oc, void *data)
466 {
467     ChardevClass *cc = CHARDEV_CLASS(oc);
468 
469     cc->chr_write = null_chr_write;
470 }
471 
472 static void char_finalize(Object *obj)
473 {
474     Chardev *chr = CHARDEV(obj);
475 
476     if (chr->be) {
477         chr->be->chr = NULL;
478     }
479     g_free(chr->filename);
480     g_free(chr->label);
481     if (chr->logfd != -1) {
482         close(chr->logfd);
483     }
484     qemu_mutex_destroy(&chr->chr_write_lock);
485 }
486 
487 static const TypeInfo char_type_info = {
488     .name = TYPE_CHARDEV,
489     .parent = TYPE_OBJECT,
490     .instance_size = sizeof(Chardev),
491     .instance_init = char_init,
492     .instance_finalize = char_finalize,
493     .abstract = true,
494     .class_size = sizeof(ChardevClass),
495     .class_init = char_class_init,
496 };
497 
498 /**
499  * Called after processing of default and command-line-specified
500  * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
501  * to a mux chardev. This is done here to ensure that
502  * output/prompts/banners are only displayed for the FE that has
503  * focus when initial command-line processing/machine init is
504  * completed.
505  *
506  * After this point, any new FE attached to any new or existing
507  * mux will receive CHR_EVENT_OPENED notifications for the BE
508  * immediately.
509  */
510 static void muxes_realize_done(Notifier *notifier, void *unused)
511 {
512     Chardev *chr;
513 
514     QTAILQ_FOREACH(chr, &chardevs, next) {
515         if (CHARDEV_IS_MUX(chr)) {
516             MuxChardev *d = MUX_CHARDEV(chr);
517             int i;
518 
519             /* send OPENED to all already-attached FEs */
520             for (i = 0; i < d->mux_cnt; i++) {
521                 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
522             }
523             /* mark mux as OPENED so any new FEs will immediately receive
524              * OPENED event
525              */
526             qemu_chr_be_generic_open(chr);
527         }
528     }
529     muxes_realized = true;
530 }
531 
532 static Notifier muxes_realize_notify = {
533     .notify = muxes_realize_done,
534 };
535 
536 Chardev *qemu_chr_fe_get_driver(CharBackend *be)
537 {
538     return be->chr;
539 }
540 
541 bool qemu_chr_fe_init(CharBackend *b, Chardev *s, Error **errp)
542 {
543     int tag = 0;
544 
545     if (CHARDEV_IS_MUX(s)) {
546         MuxChardev *d = MUX_CHARDEV(s);
547 
548         if (d->mux_cnt >= MAX_MUX) {
549             goto unavailable;
550         }
551 
552         d->backends[d->mux_cnt] = b;
553         tag = d->mux_cnt++;
554     } else if (s->be) {
555         goto unavailable;
556     } else {
557         s->be = b;
558     }
559 
560     b->fe_open = false;
561     b->tag = tag;
562     b->chr = s;
563     return true;
564 
565 unavailable:
566     error_setg(errp, QERR_DEVICE_IN_USE, s->label);
567     return false;
568 }
569 
570 static bool qemu_chr_is_busy(Chardev *s)
571 {
572     if (CHARDEV_IS_MUX(s)) {
573         MuxChardev *d = MUX_CHARDEV(s);
574         return d->mux_cnt >= 0;
575     } else {
576         return s->be != NULL;
577     }
578 }
579 
580 void qemu_chr_fe_deinit(CharBackend *b)
581 {
582     assert(b);
583 
584     if (b->chr) {
585         qemu_chr_fe_set_handlers(b, NULL, NULL, NULL, NULL, NULL, true);
586         if (b->chr->be == b) {
587             b->chr->be = NULL;
588         }
589         if (CHARDEV_IS_MUX(b->chr)) {
590             MuxChardev *d = MUX_CHARDEV(b->chr);
591             d->backends[b->tag] = NULL;
592         }
593         b->chr = NULL;
594     }
595 }
596 
597 void qemu_chr_fe_set_handlers(CharBackend *b,
598                               IOCanReadHandler *fd_can_read,
599                               IOReadHandler *fd_read,
600                               IOEventHandler *fd_event,
601                               void *opaque,
602                               GMainContext *context,
603                               bool set_open)
604 {
605     Chardev *s;
606     ChardevClass *cc;
607     int fe_open;
608 
609     s = b->chr;
610     if (!s) {
611         return;
612     }
613 
614     cc = CHARDEV_GET_CLASS(s);
615     if (!opaque && !fd_can_read && !fd_read && !fd_event) {
616         fe_open = 0;
617         remove_fd_in_watch(s);
618     } else {
619         fe_open = 1;
620     }
621     b->chr_can_read = fd_can_read;
622     b->chr_read = fd_read;
623     b->chr_event = fd_event;
624     b->opaque = opaque;
625     if (cc->chr_update_read_handler) {
626         cc->chr_update_read_handler(s, context);
627     }
628 
629     if (set_open) {
630         qemu_chr_fe_set_open(b, fe_open);
631     }
632 
633     if (fe_open) {
634         qemu_chr_fe_take_focus(b);
635         /* We're connecting to an already opened device, so let's make sure we
636            also get the open event */
637         if (s->be_open) {
638             qemu_chr_be_generic_open(s);
639         }
640     }
641 
642     if (CHARDEV_IS_MUX(s)) {
643         mux_chr_set_handlers(s, context);
644     }
645 }
646 
647 void qemu_chr_fe_take_focus(CharBackend *b)
648 {
649     if (!b->chr) {
650         return;
651     }
652 
653     if (CHARDEV_IS_MUX(b->chr)) {
654         mux_set_focus(b->chr, b->tag);
655     }
656 }
657 
658 #ifndef _WIN32
659 static void qemu_chr_open_pipe(Chardev *chr,
660                                ChardevBackend *backend,
661                                bool *be_opened,
662                                Error **errp)
663 {
664     ChardevHostdev *opts = backend->u.pipe.data;
665     int fd_in, fd_out;
666     char *filename_in;
667     char *filename_out;
668     const char *filename = opts->device;
669 
670     filename_in = g_strdup_printf("%s.in", filename);
671     filename_out = g_strdup_printf("%s.out", filename);
672     TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
673     TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
674     g_free(filename_in);
675     g_free(filename_out);
676     if (fd_in < 0 || fd_out < 0) {
677 	if (fd_in >= 0)
678 	    close(fd_in);
679 	if (fd_out >= 0)
680 	    close(fd_out);
681         TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
682         if (fd_in < 0) {
683             error_setg_file_open(errp, errno, filename);
684             return;
685         }
686     }
687     qemu_chr_open_fd(chr, fd_in, fd_out);
688 }
689 
690 /* init terminal so that we can grab keys */
691 static struct termios oldtty;
692 static int old_fd0_flags;
693 static bool stdio_in_use;
694 static bool stdio_allow_signal;
695 static bool stdio_echo_state;
696 
697 static void qemu_chr_set_echo_stdio(Chardev *chr, bool echo);
698 
699 static void term_exit(void)
700 {
701     tcsetattr (0, TCSANOW, &oldtty);
702     fcntl(0, F_SETFL, old_fd0_flags);
703 }
704 
705 static void term_stdio_handler(int sig)
706 {
707     /* restore echo after resume from suspend. */
708     qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
709 }
710 
711 static void qemu_chr_set_echo_stdio(Chardev *chr, bool echo)
712 {
713     struct termios tty;
714 
715     stdio_echo_state = echo;
716     tty = oldtty;
717     if (!echo) {
718         tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
719                           |INLCR|IGNCR|ICRNL|IXON);
720         tty.c_oflag |= OPOST;
721         tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
722         tty.c_cflag &= ~(CSIZE|PARENB);
723         tty.c_cflag |= CS8;
724         tty.c_cc[VMIN] = 1;
725         tty.c_cc[VTIME] = 0;
726     }
727     if (!stdio_allow_signal)
728         tty.c_lflag &= ~ISIG;
729 
730     tcsetattr (0, TCSANOW, &tty);
731 }
732 
733 static void char_stdio_finalize(Object *obj)
734 {
735     term_exit();
736 }
737 
738 static void qemu_chr_open_stdio(Chardev *chr,
739                                 ChardevBackend *backend,
740                                 bool *be_opened,
741                                 Error **errp)
742 {
743     ChardevStdio *opts = backend->u.stdio.data;
744     struct sigaction act;
745 
746     if (is_daemonized()) {
747         error_setg(errp, "cannot use stdio with -daemonize");
748         return;
749     }
750 
751     if (stdio_in_use) {
752         error_setg(errp, "cannot use stdio by multiple character devices");
753         return;
754     }
755 
756     stdio_in_use = true;
757     old_fd0_flags = fcntl(0, F_GETFL);
758     tcgetattr(0, &oldtty);
759     qemu_set_nonblock(0);
760     atexit(term_exit);
761 
762     memset(&act, 0, sizeof(act));
763     act.sa_handler = term_stdio_handler;
764     sigaction(SIGCONT, &act, NULL);
765 
766     qemu_chr_open_fd(chr, 0, 1);
767 
768     if (opts->has_signal) {
769         stdio_allow_signal = opts->signal;
770     }
771     qemu_chr_set_echo_stdio(chr, false);
772 }
773 
774 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
775     || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
776     || defined(__GLIBC__)
777 
778 #define HAVE_CHARDEV_SERIAL 1
779 #define HAVE_CHARDEV_PTY 1
780 
781 typedef struct {
782     Chardev parent;
783     QIOChannel *ioc;
784     int read_bytes;
785 
786     /* Protected by the Chardev chr_write_lock.  */
787     int connected;
788     guint timer_tag;
789     guint open_tag;
790 } PtyChardev;
791 
792 #define PTY_CHARDEV(obj) OBJECT_CHECK(PtyChardev, (obj), TYPE_CHARDEV_PTY)
793 
794 static void pty_chr_update_read_handler_locked(Chardev *chr);
795 static void pty_chr_state(Chardev *chr, int connected);
796 
797 static gboolean pty_chr_timer(gpointer opaque)
798 {
799     struct Chardev *chr = CHARDEV(opaque);
800     PtyChardev *s = PTY_CHARDEV(opaque);
801 
802     qemu_mutex_lock(&chr->chr_write_lock);
803     s->timer_tag = 0;
804     s->open_tag = 0;
805     if (!s->connected) {
806         /* Next poll ... */
807         pty_chr_update_read_handler_locked(chr);
808     }
809     qemu_mutex_unlock(&chr->chr_write_lock);
810     return FALSE;
811 }
812 
813 /* Called with chr_write_lock held.  */
814 static void pty_chr_rearm_timer(Chardev *chr, int ms)
815 {
816     PtyChardev *s = PTY_CHARDEV(chr);
817     char *name;
818 
819     if (s->timer_tag) {
820         g_source_remove(s->timer_tag);
821         s->timer_tag = 0;
822     }
823 
824     if (ms == 1000) {
825         name = g_strdup_printf("pty-timer-secs-%s", chr->label);
826         s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
827     } else {
828         name = g_strdup_printf("pty-timer-ms-%s", chr->label);
829         s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
830     }
831     g_source_set_name_by_id(s->timer_tag, name);
832     g_free(name);
833 }
834 
835 /* Called with chr_write_lock held.  */
836 static void pty_chr_update_read_handler_locked(Chardev *chr)
837 {
838     PtyChardev *s = PTY_CHARDEV(chr);
839     GPollFD pfd;
840     int rc;
841     QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
842 
843     pfd.fd = fioc->fd;
844     pfd.events = G_IO_OUT;
845     pfd.revents = 0;
846     do {
847         rc = g_poll(&pfd, 1, 0);
848     } while (rc == -1 && errno == EINTR);
849     assert(rc >= 0);
850 
851     if (pfd.revents & G_IO_HUP) {
852         pty_chr_state(chr, 0);
853     } else {
854         pty_chr_state(chr, 1);
855     }
856 }
857 
858 static void pty_chr_update_read_handler(Chardev *chr,
859                                         GMainContext *context)
860 {
861     qemu_mutex_lock(&chr->chr_write_lock);
862     pty_chr_update_read_handler_locked(chr);
863     qemu_mutex_unlock(&chr->chr_write_lock);
864 }
865 
866 /* Called with chr_write_lock held.  */
867 static int char_pty_chr_write(Chardev *chr, const uint8_t *buf, int len)
868 {
869     PtyChardev *s = PTY_CHARDEV(chr);
870 
871     if (!s->connected) {
872         /* guest sends data, check for (re-)connect */
873         pty_chr_update_read_handler_locked(chr);
874         if (!s->connected) {
875             return 0;
876         }
877     }
878     return io_channel_send(s->ioc, buf, len);
879 }
880 
881 static GSource *pty_chr_add_watch(Chardev *chr, GIOCondition cond)
882 {
883     PtyChardev *s = PTY_CHARDEV(chr);
884     if (!s->connected) {
885         return NULL;
886     }
887     return qio_channel_create_watch(s->ioc, cond);
888 }
889 
890 static int pty_chr_read_poll(void *opaque)
891 {
892     Chardev *chr = CHARDEV(opaque);
893     PtyChardev *s = PTY_CHARDEV(opaque);
894 
895     s->read_bytes = qemu_chr_be_can_write(chr);
896     return s->read_bytes;
897 }
898 
899 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
900 {
901     Chardev *chr = CHARDEV(opaque);
902     PtyChardev *s = PTY_CHARDEV(opaque);
903     gsize len;
904     uint8_t buf[CHR_READ_BUF_LEN];
905     ssize_t ret;
906 
907     len = sizeof(buf);
908     if (len > s->read_bytes)
909         len = s->read_bytes;
910     if (len == 0) {
911         return TRUE;
912     }
913     ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
914     if (ret <= 0) {
915         pty_chr_state(chr, 0);
916         return FALSE;
917     } else {
918         pty_chr_state(chr, 1);
919         qemu_chr_be_write(chr, buf, ret);
920     }
921     return TRUE;
922 }
923 
924 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
925 {
926     Chardev *chr = CHARDEV(opaque);
927     PtyChardev *s = PTY_CHARDEV(opaque);
928 
929     s->open_tag = 0;
930     qemu_chr_be_generic_open(chr);
931     return FALSE;
932 }
933 
934 /* Called with chr_write_lock held.  */
935 static void pty_chr_state(Chardev *chr, int connected)
936 {
937     PtyChardev *s = PTY_CHARDEV(chr);
938 
939     if (!connected) {
940         if (s->open_tag) {
941             g_source_remove(s->open_tag);
942             s->open_tag = 0;
943         }
944         remove_fd_in_watch(chr);
945         s->connected = 0;
946         /* (re-)connect poll interval for idle guests: once per second.
947          * We check more frequently in case the guests sends data to
948          * the virtual device linked to our pty. */
949         pty_chr_rearm_timer(chr, 1000);
950     } else {
951         if (s->timer_tag) {
952             g_source_remove(s->timer_tag);
953             s->timer_tag = 0;
954         }
955         if (!s->connected) {
956             g_assert(s->open_tag == 0);
957             s->connected = 1;
958             s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
959         }
960         if (!chr->fd_in_tag) {
961             chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
962                                                pty_chr_read_poll,
963                                                pty_chr_read,
964                                                chr, NULL);
965         }
966     }
967 }
968 
969 static void char_pty_finalize(Object *obj)
970 {
971     Chardev *chr = CHARDEV(obj);
972     PtyChardev *s = PTY_CHARDEV(obj);
973 
974     qemu_mutex_lock(&chr->chr_write_lock);
975     pty_chr_state(chr, 0);
976     object_unref(OBJECT(s->ioc));
977     if (s->timer_tag) {
978         g_source_remove(s->timer_tag);
979         s->timer_tag = 0;
980     }
981     qemu_mutex_unlock(&chr->chr_write_lock);
982     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
983 }
984 
985 static void char_pty_open(Chardev *chr,
986                           ChardevBackend *backend,
987                           bool *be_opened,
988                           Error **errp)
989 {
990     PtyChardev *s;
991     int master_fd, slave_fd;
992     char pty_name[PATH_MAX];
993     char *name;
994 
995     master_fd = qemu_openpty_raw(&slave_fd, pty_name);
996     if (master_fd < 0) {
997         error_setg_errno(errp, errno, "Failed to create PTY");
998         return;
999     }
1000 
1001     close(slave_fd);
1002     qemu_set_nonblock(master_fd);
1003 
1004     chr->filename = g_strdup_printf("pty:%s", pty_name);
1005     error_report("char device redirected to %s (label %s)",
1006                  pty_name, chr->label);
1007 
1008     s = PTY_CHARDEV(chr);
1009     s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1010     name = g_strdup_printf("chardev-pty-%s", chr->label);
1011     qio_channel_set_name(QIO_CHANNEL(s->ioc), name);
1012     g_free(name);
1013     s->timer_tag = 0;
1014     *be_opened = false;
1015 }
1016 
1017 static void char_pty_class_init(ObjectClass *oc, void *data)
1018 {
1019     ChardevClass *cc = CHARDEV_CLASS(oc);
1020 
1021     cc->open = char_pty_open;
1022     cc->chr_write = char_pty_chr_write;
1023     cc->chr_update_read_handler = pty_chr_update_read_handler;
1024     cc->chr_add_watch = pty_chr_add_watch;
1025 }
1026 
1027 static const TypeInfo char_pty_type_info = {
1028     .name = TYPE_CHARDEV_PTY,
1029     .parent = TYPE_CHARDEV,
1030     .instance_size = sizeof(PtyChardev),
1031     .instance_finalize = char_pty_finalize,
1032     .class_init = char_pty_class_init,
1033 };
1034 
1035 static void tty_serial_init(int fd, int speed,
1036                             int parity, int data_bits, int stop_bits)
1037 {
1038     struct termios tty;
1039     speed_t spd;
1040 
1041 #if 0
1042     printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1043            speed, parity, data_bits, stop_bits);
1044 #endif
1045     tcgetattr (fd, &tty);
1046 
1047 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1048     speed = speed * 10 / 11;
1049     do {
1050         check_speed(50);
1051         check_speed(75);
1052         check_speed(110);
1053         check_speed(134);
1054         check_speed(150);
1055         check_speed(200);
1056         check_speed(300);
1057         check_speed(600);
1058         check_speed(1200);
1059         check_speed(1800);
1060         check_speed(2400);
1061         check_speed(4800);
1062         check_speed(9600);
1063         check_speed(19200);
1064         check_speed(38400);
1065         /* Non-Posix values follow. They may be unsupported on some systems. */
1066         check_speed(57600);
1067         check_speed(115200);
1068 #ifdef B230400
1069         check_speed(230400);
1070 #endif
1071 #ifdef B460800
1072         check_speed(460800);
1073 #endif
1074 #ifdef B500000
1075         check_speed(500000);
1076 #endif
1077 #ifdef B576000
1078         check_speed(576000);
1079 #endif
1080 #ifdef B921600
1081         check_speed(921600);
1082 #endif
1083 #ifdef B1000000
1084         check_speed(1000000);
1085 #endif
1086 #ifdef B1152000
1087         check_speed(1152000);
1088 #endif
1089 #ifdef B1500000
1090         check_speed(1500000);
1091 #endif
1092 #ifdef B2000000
1093         check_speed(2000000);
1094 #endif
1095 #ifdef B2500000
1096         check_speed(2500000);
1097 #endif
1098 #ifdef B3000000
1099         check_speed(3000000);
1100 #endif
1101 #ifdef B3500000
1102         check_speed(3500000);
1103 #endif
1104 #ifdef B4000000
1105         check_speed(4000000);
1106 #endif
1107         spd = B115200;
1108     } while (0);
1109 
1110     cfsetispeed(&tty, spd);
1111     cfsetospeed(&tty, spd);
1112 
1113     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1114                           |INLCR|IGNCR|ICRNL|IXON);
1115     tty.c_oflag |= OPOST;
1116     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1117     tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1118     switch(data_bits) {
1119     default:
1120     case 8:
1121         tty.c_cflag |= CS8;
1122         break;
1123     case 7:
1124         tty.c_cflag |= CS7;
1125         break;
1126     case 6:
1127         tty.c_cflag |= CS6;
1128         break;
1129     case 5:
1130         tty.c_cflag |= CS5;
1131         break;
1132     }
1133     switch(parity) {
1134     default:
1135     case 'N':
1136         break;
1137     case 'E':
1138         tty.c_cflag |= PARENB;
1139         break;
1140     case 'O':
1141         tty.c_cflag |= PARENB | PARODD;
1142         break;
1143     }
1144     if (stop_bits == 2)
1145         tty.c_cflag |= CSTOPB;
1146 
1147     tcsetattr (fd, TCSANOW, &tty);
1148 }
1149 
1150 static int tty_serial_ioctl(Chardev *chr, int cmd, void *arg)
1151 {
1152     FDChardev *s = FD_CHARDEV(chr);
1153     QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1154 
1155     switch(cmd) {
1156     case CHR_IOCTL_SERIAL_SET_PARAMS:
1157         {
1158             QEMUSerialSetParams *ssp = arg;
1159             tty_serial_init(fioc->fd,
1160                             ssp->speed, ssp->parity,
1161                             ssp->data_bits, ssp->stop_bits);
1162         }
1163         break;
1164     case CHR_IOCTL_SERIAL_SET_BREAK:
1165         {
1166             int enable = *(int *)arg;
1167             if (enable) {
1168                 tcsendbreak(fioc->fd, 1);
1169             }
1170         }
1171         break;
1172     case CHR_IOCTL_SERIAL_GET_TIOCM:
1173         {
1174             int sarg = 0;
1175             int *targ = (int *)arg;
1176             ioctl(fioc->fd, TIOCMGET, &sarg);
1177             *targ = 0;
1178             if (sarg & TIOCM_CTS)
1179                 *targ |= CHR_TIOCM_CTS;
1180             if (sarg & TIOCM_CAR)
1181                 *targ |= CHR_TIOCM_CAR;
1182             if (sarg & TIOCM_DSR)
1183                 *targ |= CHR_TIOCM_DSR;
1184             if (sarg & TIOCM_RI)
1185                 *targ |= CHR_TIOCM_RI;
1186             if (sarg & TIOCM_DTR)
1187                 *targ |= CHR_TIOCM_DTR;
1188             if (sarg & TIOCM_RTS)
1189                 *targ |= CHR_TIOCM_RTS;
1190         }
1191         break;
1192     case CHR_IOCTL_SERIAL_SET_TIOCM:
1193         {
1194             int sarg = *(int *)arg;
1195             int targ = 0;
1196             ioctl(fioc->fd, TIOCMGET, &targ);
1197             targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1198                      | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1199             if (sarg & CHR_TIOCM_CTS)
1200                 targ |= TIOCM_CTS;
1201             if (sarg & CHR_TIOCM_CAR)
1202                 targ |= TIOCM_CAR;
1203             if (sarg & CHR_TIOCM_DSR)
1204                 targ |= TIOCM_DSR;
1205             if (sarg & CHR_TIOCM_RI)
1206                 targ |= TIOCM_RI;
1207             if (sarg & CHR_TIOCM_DTR)
1208                 targ |= TIOCM_DTR;
1209             if (sarg & CHR_TIOCM_RTS)
1210                 targ |= TIOCM_RTS;
1211             ioctl(fioc->fd, TIOCMSET, &targ);
1212         }
1213         break;
1214     default:
1215         return -ENOTSUP;
1216     }
1217     return 0;
1218 }
1219 #endif /* __linux__ || __sun__ */
1220 
1221 #if defined(__linux__)
1222 
1223 #define HAVE_CHARDEV_PARPORT 1
1224 
1225 typedef struct {
1226     Chardev parent;
1227     int fd;
1228     int mode;
1229 } ParallelChardev;
1230 
1231 #define PARALLEL_CHARDEV(obj) \
1232     OBJECT_CHECK(ParallelChardev, (obj), TYPE_CHARDEV_PARALLEL)
1233 
1234 static int pp_hw_mode(ParallelChardev *s, uint16_t mode)
1235 {
1236     if (s->mode != mode) {
1237 	int m = mode;
1238         if (ioctl(s->fd, PPSETMODE, &m) < 0)
1239             return 0;
1240 	s->mode = mode;
1241     }
1242     return 1;
1243 }
1244 
1245 static int pp_ioctl(Chardev *chr, int cmd, void *arg)
1246 {
1247     ParallelChardev *drv = PARALLEL_CHARDEV(chr);
1248     int fd = drv->fd;
1249     uint8_t b;
1250 
1251     switch(cmd) {
1252     case CHR_IOCTL_PP_READ_DATA:
1253         if (ioctl(fd, PPRDATA, &b) < 0)
1254             return -ENOTSUP;
1255         *(uint8_t *)arg = b;
1256         break;
1257     case CHR_IOCTL_PP_WRITE_DATA:
1258         b = *(uint8_t *)arg;
1259         if (ioctl(fd, PPWDATA, &b) < 0)
1260             return -ENOTSUP;
1261         break;
1262     case CHR_IOCTL_PP_READ_CONTROL:
1263         if (ioctl(fd, PPRCONTROL, &b) < 0)
1264             return -ENOTSUP;
1265 	/* Linux gives only the lowest bits, and no way to know data
1266 	   direction! For better compatibility set the fixed upper
1267 	   bits. */
1268         *(uint8_t *)arg = b | 0xc0;
1269         break;
1270     case CHR_IOCTL_PP_WRITE_CONTROL:
1271         b = *(uint8_t *)arg;
1272         if (ioctl(fd, PPWCONTROL, &b) < 0)
1273             return -ENOTSUP;
1274         break;
1275     case CHR_IOCTL_PP_READ_STATUS:
1276         if (ioctl(fd, PPRSTATUS, &b) < 0)
1277             return -ENOTSUP;
1278         *(uint8_t *)arg = b;
1279         break;
1280     case CHR_IOCTL_PP_DATA_DIR:
1281         if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1282             return -ENOTSUP;
1283         break;
1284     case CHR_IOCTL_PP_EPP_READ_ADDR:
1285 	if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1286 	    struct ParallelIOArg *parg = arg;
1287 	    int n = read(fd, parg->buffer, parg->count);
1288 	    if (n != parg->count) {
1289 		return -EIO;
1290 	    }
1291 	}
1292         break;
1293     case CHR_IOCTL_PP_EPP_READ:
1294 	if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1295 	    struct ParallelIOArg *parg = arg;
1296 	    int n = read(fd, parg->buffer, parg->count);
1297 	    if (n != parg->count) {
1298 		return -EIO;
1299 	    }
1300 	}
1301         break;
1302     case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1303 	if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1304 	    struct ParallelIOArg *parg = arg;
1305 	    int n = write(fd, parg->buffer, parg->count);
1306 	    if (n != parg->count) {
1307 		return -EIO;
1308 	    }
1309 	}
1310         break;
1311     case CHR_IOCTL_PP_EPP_WRITE:
1312 	if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1313 	    struct ParallelIOArg *parg = arg;
1314 	    int n = write(fd, parg->buffer, parg->count);
1315 	    if (n != parg->count) {
1316 		return -EIO;
1317 	    }
1318 	}
1319         break;
1320     default:
1321         return -ENOTSUP;
1322     }
1323     return 0;
1324 }
1325 
1326 static void qemu_chr_open_pp_fd(Chardev *chr,
1327                                 int fd,
1328                                 bool *be_opened,
1329                                 Error **errp)
1330 {
1331     ParallelChardev *drv = PARALLEL_CHARDEV(chr);
1332 
1333     if (ioctl(fd, PPCLAIM) < 0) {
1334         error_setg_errno(errp, errno, "not a parallel port");
1335         close(fd);
1336         return;
1337     }
1338 
1339     drv->fd = fd;
1340     drv->mode = IEEE1284_MODE_COMPAT;
1341 }
1342 #endif /* __linux__ */
1343 
1344 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1345 
1346 #define HAVE_CHARDEV_PARPORT 1
1347 
1348 typedef struct {
1349     Chardev parent;
1350     int fd;
1351 } ParallelChardev;
1352 
1353 #define PARALLEL_CHARDEV(obj)                                   \
1354     OBJECT_CHECK(ParallelChardev, (obj), TYPE_CHARDEV_PARALLEL)
1355 
1356 static int pp_ioctl(Chardev *chr, int cmd, void *arg)
1357 {
1358     ParallelChardev *drv = PARALLEL_CHARDEV(chr);
1359     uint8_t b;
1360 
1361     switch (cmd) {
1362     case CHR_IOCTL_PP_READ_DATA:
1363         if (ioctl(drv->fd, PPIGDATA, &b) < 0) {
1364             return -ENOTSUP;
1365         }
1366         *(uint8_t *)arg = b;
1367         break;
1368     case CHR_IOCTL_PP_WRITE_DATA:
1369         b = *(uint8_t *)arg;
1370         if (ioctl(drv->fd, PPISDATA, &b) < 0) {
1371             return -ENOTSUP;
1372         }
1373         break;
1374     case CHR_IOCTL_PP_READ_CONTROL:
1375         if (ioctl(drv->fd, PPIGCTRL, &b) < 0) {
1376             return -ENOTSUP;
1377         }
1378         *(uint8_t *)arg = b;
1379         break;
1380     case CHR_IOCTL_PP_WRITE_CONTROL:
1381         b = *(uint8_t *)arg;
1382         if (ioctl(drv->fd, PPISCTRL, &b) < 0) {
1383             return -ENOTSUP;
1384         }
1385         break;
1386     case CHR_IOCTL_PP_READ_STATUS:
1387         if (ioctl(drv->fd, PPIGSTATUS, &b) < 0) {
1388             return -ENOTSUP;
1389         }
1390         *(uint8_t *)arg = b;
1391         break;
1392     default:
1393         return -ENOTSUP;
1394     }
1395     return 0;
1396 }
1397 
1398 static void qemu_chr_open_pp_fd(Chardev *chr,
1399                                 int fd,
1400                                 bool *be_opened,
1401                                 Error **errp)
1402 {
1403     ParallelChardev *drv = PARALLEL_CHARDEV(chr);
1404     drv->fd = fd;
1405     *be_opened = false;
1406 }
1407 #endif
1408 
1409 #else /* _WIN32 */
1410 
1411 #define HAVE_CHARDEV_SERIAL 1
1412 
1413 #define MAXCONNECT 1
1414 #define NTIMEOUT 5000
1415 
1416 static int win_chr_pipe_init(Chardev *chr, const char *filename,
1417                              Error **errp)
1418 {
1419     WinChardev *s = WIN_CHARDEV(chr);
1420     OVERLAPPED ov;
1421     int ret;
1422     DWORD size;
1423     char *openname;
1424 
1425     s->fpipe = TRUE;
1426 
1427     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1428     if (!s->hsend) {
1429         error_setg(errp, "Failed CreateEvent");
1430         goto fail;
1431     }
1432     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1433     if (!s->hrecv) {
1434         error_setg(errp, "Failed CreateEvent");
1435         goto fail;
1436     }
1437 
1438     openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
1439     s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1440                               PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1441                               PIPE_WAIT,
1442                               MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1443     g_free(openname);
1444     if (s->hcom == INVALID_HANDLE_VALUE) {
1445         error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
1446         s->hcom = NULL;
1447         goto fail;
1448     }
1449 
1450     ZeroMemory(&ov, sizeof(ov));
1451     ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1452     ret = ConnectNamedPipe(s->hcom, &ov);
1453     if (ret) {
1454         error_setg(errp, "Failed ConnectNamedPipe");
1455         goto fail;
1456     }
1457 
1458     ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1459     if (!ret) {
1460         error_setg(errp, "Failed GetOverlappedResult");
1461         if (ov.hEvent) {
1462             CloseHandle(ov.hEvent);
1463             ov.hEvent = NULL;
1464         }
1465         goto fail;
1466     }
1467 
1468     if (ov.hEvent) {
1469         CloseHandle(ov.hEvent);
1470         ov.hEvent = NULL;
1471     }
1472     qemu_add_polling_cb(win_chr_pipe_poll, chr);
1473     return 0;
1474 
1475  fail:
1476     return -1;
1477 }
1478 
1479 
1480 static void qemu_chr_open_pipe(Chardev *chr,
1481                                ChardevBackend *backend,
1482                                bool *be_opened,
1483                                Error **errp)
1484 {
1485     ChardevHostdev *opts = backend->u.pipe.data;
1486     const char *filename = opts->device;
1487 
1488     if (win_chr_pipe_init(chr, filename, errp) < 0) {
1489         return;
1490     }
1491 }
1492 
1493 static void qemu_chr_open_win_con(Chardev *chr,
1494                                   ChardevBackend *backend,
1495                                   bool *be_opened,
1496                                   Error **errp)
1497 {
1498     qemu_chr_open_win_file(chr, GetStdHandle(STD_OUTPUT_HANDLE));
1499 }
1500 
1501 static void char_console_class_init(ObjectClass *oc, void *data)
1502 {
1503     ChardevClass *cc = CHARDEV_CLASS(oc);
1504 
1505     cc->open = qemu_chr_open_win_con;
1506 }
1507 
1508 static const TypeInfo char_console_type_info = {
1509     .name = TYPE_CHARDEV_CONSOLE,
1510     .parent = TYPE_CHARDEV_WIN,
1511     .class_init = char_console_class_init,
1512 };
1513 
1514 #endif /* !_WIN32 */
1515 
1516 int qemu_chr_wait_connected(Chardev *chr, Error **errp)
1517 {
1518     ChardevClass *cc = CHARDEV_GET_CLASS(chr);
1519 
1520     if (cc->chr_wait_connected) {
1521         return cc->chr_wait_connected(chr, errp);
1522     }
1523 
1524     return 0;
1525 }
1526 
1527 int qemu_chr_fe_wait_connected(CharBackend *be, Error **errp)
1528 {
1529     if (!be->chr) {
1530         error_setg(errp, "missing associated backend");
1531         return -1;
1532     }
1533 
1534     return qemu_chr_wait_connected(be->chr, errp);
1535 }
1536 
1537 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
1538 {
1539     char host[65], port[33], width[8], height[8];
1540     int pos;
1541     const char *p;
1542     QemuOpts *opts;
1543     Error *local_err = NULL;
1544 
1545     opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
1546     if (local_err) {
1547         error_report_err(local_err);
1548         return NULL;
1549     }
1550 
1551     if (strstart(filename, "mon:", &p)) {
1552         filename = p;
1553         qemu_opt_set(opts, "mux", "on", &error_abort);
1554         if (strcmp(filename, "stdio") == 0) {
1555             /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
1556              * but pass it to the guest.  Handle this only for compat syntax,
1557              * for -chardev syntax we have special option for this.
1558              * This is what -nographic did, redirecting+muxing serial+monitor
1559              * to stdio causing Ctrl+C to be passed to guest. */
1560             qemu_opt_set(opts, "signal", "off", &error_abort);
1561         }
1562     }
1563 
1564     if (strcmp(filename, "null")    == 0 ||
1565         strcmp(filename, "pty")     == 0 ||
1566         strcmp(filename, "msmouse") == 0 ||
1567         strcmp(filename, "braille") == 0 ||
1568         strcmp(filename, "testdev") == 0 ||
1569         strcmp(filename, "stdio")   == 0) {
1570         qemu_opt_set(opts, "backend", filename, &error_abort);
1571         return opts;
1572     }
1573     if (strstart(filename, "vc", &p)) {
1574         qemu_opt_set(opts, "backend", "vc", &error_abort);
1575         if (*p == ':') {
1576             if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
1577                 /* pixels */
1578                 qemu_opt_set(opts, "width", width, &error_abort);
1579                 qemu_opt_set(opts, "height", height, &error_abort);
1580             } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
1581                 /* chars */
1582                 qemu_opt_set(opts, "cols", width, &error_abort);
1583                 qemu_opt_set(opts, "rows", height, &error_abort);
1584             } else {
1585                 goto fail;
1586             }
1587         }
1588         return opts;
1589     }
1590     if (strcmp(filename, "con:") == 0) {
1591         qemu_opt_set(opts, "backend", "console", &error_abort);
1592         return opts;
1593     }
1594     if (strstart(filename, "COM", NULL)) {
1595         qemu_opt_set(opts, "backend", "serial", &error_abort);
1596         qemu_opt_set(opts, "path", filename, &error_abort);
1597         return opts;
1598     }
1599     if (strstart(filename, "file:", &p)) {
1600         qemu_opt_set(opts, "backend", "file", &error_abort);
1601         qemu_opt_set(opts, "path", p, &error_abort);
1602         return opts;
1603     }
1604     if (strstart(filename, "pipe:", &p)) {
1605         qemu_opt_set(opts, "backend", "pipe", &error_abort);
1606         qemu_opt_set(opts, "path", p, &error_abort);
1607         return opts;
1608     }
1609     if (strstart(filename, "tcp:", &p) ||
1610         strstart(filename, "telnet:", &p)) {
1611         if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
1612             host[0] = 0;
1613             if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
1614                 goto fail;
1615         }
1616         qemu_opt_set(opts, "backend", "socket", &error_abort);
1617         qemu_opt_set(opts, "host", host, &error_abort);
1618         qemu_opt_set(opts, "port", port, &error_abort);
1619         if (p[pos] == ',') {
1620             qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
1621             if (local_err) {
1622                 error_report_err(local_err);
1623                 goto fail;
1624             }
1625         }
1626         if (strstart(filename, "telnet:", &p))
1627             qemu_opt_set(opts, "telnet", "on", &error_abort);
1628         return opts;
1629     }
1630     if (strstart(filename, "udp:", &p)) {
1631         qemu_opt_set(opts, "backend", "udp", &error_abort);
1632         if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
1633             host[0] = 0;
1634             if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
1635                 goto fail;
1636             }
1637         }
1638         qemu_opt_set(opts, "host", host, &error_abort);
1639         qemu_opt_set(opts, "port", port, &error_abort);
1640         if (p[pos] == '@') {
1641             p += pos + 1;
1642             if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
1643                 host[0] = 0;
1644                 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
1645                     goto fail;
1646                 }
1647             }
1648             qemu_opt_set(opts, "localaddr", host, &error_abort);
1649             qemu_opt_set(opts, "localport", port, &error_abort);
1650         }
1651         return opts;
1652     }
1653     if (strstart(filename, "unix:", &p)) {
1654         qemu_opt_set(opts, "backend", "socket", &error_abort);
1655         qemu_opts_do_parse(opts, p, "path", &local_err);
1656         if (local_err) {
1657             error_report_err(local_err);
1658             goto fail;
1659         }
1660         return opts;
1661     }
1662     if (strstart(filename, "/dev/parport", NULL) ||
1663         strstart(filename, "/dev/ppi", NULL)) {
1664         qemu_opt_set(opts, "backend", "parport", &error_abort);
1665         qemu_opt_set(opts, "path", filename, &error_abort);
1666         return opts;
1667     }
1668     if (strstart(filename, "/dev/", NULL)) {
1669         qemu_opt_set(opts, "backend", "tty", &error_abort);
1670         qemu_opt_set(opts, "path", filename, &error_abort);
1671         return opts;
1672     }
1673 
1674 fail:
1675     qemu_opts_del(opts);
1676     return NULL;
1677 }
1678 
1679 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
1680 {
1681     const char *logfile = qemu_opt_get(opts, "logfile");
1682 
1683     backend->has_logfile = logfile != NULL;
1684     backend->logfile = logfile ? g_strdup(logfile) : NULL;
1685 
1686     backend->has_logappend = true;
1687     backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
1688 }
1689 
1690 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
1691                                  Error **errp)
1692 {
1693     ChardevStdio *stdio;
1694 
1695     backend->type = CHARDEV_BACKEND_KIND_STDIO;
1696     stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
1697     qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
1698     stdio->has_signal = true;
1699     stdio->signal = qemu_opt_get_bool(opts, "signal", true);
1700 }
1701 
1702 static void char_stdio_class_init(ObjectClass *oc, void *data)
1703 {
1704     ChardevClass *cc = CHARDEV_CLASS(oc);
1705 
1706     cc->parse = qemu_chr_parse_stdio;
1707 #ifndef _WIN32
1708     cc->open = qemu_chr_open_stdio;
1709     cc->chr_set_echo = qemu_chr_set_echo_stdio;
1710 #endif
1711 }
1712 
1713 static const TypeInfo char_stdio_type_info = {
1714     .name = TYPE_CHARDEV_STDIO,
1715 #ifdef _WIN32
1716     .parent = TYPE_CHARDEV_WIN_STDIO,
1717 #else
1718     .parent = TYPE_CHARDEV_FD,
1719     .instance_finalize = char_stdio_finalize,
1720 #endif
1721     .class_init = char_stdio_class_init,
1722 };
1723 
1724 #ifdef HAVE_CHARDEV_SERIAL
1725 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
1726                                   Error **errp)
1727 {
1728     const char *device = qemu_opt_get(opts, "path");
1729     ChardevHostdev *serial;
1730 
1731     backend->type = CHARDEV_BACKEND_KIND_SERIAL;
1732     if (device == NULL) {
1733         error_setg(errp, "chardev: serial/tty: no device path given");
1734         return;
1735     }
1736     serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
1737     qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
1738     serial->device = g_strdup(device);
1739 }
1740 #endif
1741 
1742 #ifdef HAVE_CHARDEV_PARPORT
1743 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
1744                                     Error **errp)
1745 {
1746     const char *device = qemu_opt_get(opts, "path");
1747     ChardevHostdev *parallel;
1748 
1749     backend->type = CHARDEV_BACKEND_KIND_PARALLEL;
1750     if (device == NULL) {
1751         error_setg(errp, "chardev: parallel: no device path given");
1752         return;
1753     }
1754     parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
1755     qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
1756     parallel->device = g_strdup(device);
1757 }
1758 #endif
1759 
1760 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
1761                                 Error **errp)
1762 {
1763     const char *device = qemu_opt_get(opts, "path");
1764     ChardevHostdev *dev;
1765 
1766     backend->type = CHARDEV_BACKEND_KIND_PIPE;
1767     if (device == NULL) {
1768         error_setg(errp, "chardev: pipe: no device path given");
1769         return;
1770     }
1771     dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
1772     qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
1773     dev->device = g_strdup(device);
1774 }
1775 
1776 static void char_pipe_class_init(ObjectClass *oc, void *data)
1777 {
1778     ChardevClass *cc = CHARDEV_CLASS(oc);
1779 
1780     cc->parse = qemu_chr_parse_pipe;
1781     cc->open = qemu_chr_open_pipe;
1782 }
1783 
1784 static const TypeInfo char_pipe_type_info = {
1785     .name = TYPE_CHARDEV_PIPE,
1786 #ifdef _WIN32
1787     .parent = TYPE_CHARDEV_WIN,
1788 #else
1789     .parent = TYPE_CHARDEV_FD,
1790 #endif
1791     .class_init = char_pipe_class_init,
1792 };
1793 
1794 static const ChardevClass *char_get_class(const char *driver, Error **errp)
1795 {
1796     ObjectClass *oc;
1797     const ChardevClass *cc;
1798     char *typename = g_strdup_printf("chardev-%s", driver);
1799 
1800     oc = object_class_by_name(typename);
1801     g_free(typename);
1802 
1803     if (!object_class_dynamic_cast(oc, TYPE_CHARDEV)) {
1804         error_setg(errp, "'%s' is not a valid char driver name", driver);
1805         return NULL;
1806     }
1807 
1808     if (object_class_is_abstract(oc)) {
1809         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "driver",
1810                    "abstract device type");
1811         return NULL;
1812     }
1813 
1814     cc = CHARDEV_CLASS(oc);
1815     if (cc->internal) {
1816         error_setg(errp, "'%s' is not a valid char driver name", driver);
1817         return NULL;
1818     }
1819 
1820     return cc;
1821 }
1822 
1823 static Chardev *qemu_chardev_add(const char *id, const char *typename,
1824                                  ChardevBackend *backend, Error **errp)
1825 {
1826     Chardev *chr;
1827 
1828     chr = qemu_chr_find(id);
1829     if (chr) {
1830         error_setg(errp, "Chardev '%s' already exists", id);
1831         return NULL;
1832     }
1833 
1834     chr = qemu_chardev_new(id, typename, backend, errp);
1835     if (!chr) {
1836         return NULL;
1837     }
1838 
1839     QTAILQ_INSERT_TAIL(&chardevs, chr, next);
1840     return chr;
1841 }
1842 
1843 static const struct ChardevAlias {
1844     const char *typename;
1845     const char *alias;
1846 } chardev_alias_table[] = {
1847 #ifdef HAVE_CHARDEV_PARPORT
1848     { "parallel", "parport" },
1849 #endif
1850 #ifdef HAVE_CHARDEV_SERIAL
1851     { "serial", "tty" },
1852 #endif
1853 };
1854 
1855 typedef struct ChadevClassFE {
1856     void (*fn)(const char *name, void *opaque);
1857     void *opaque;
1858 } ChadevClassFE;
1859 
1860 static void
1861 chardev_class_foreach(ObjectClass *klass, void *opaque)
1862 {
1863     ChadevClassFE *fe = opaque;
1864 
1865     assert(g_str_has_prefix(object_class_get_name(klass), "chardev-"));
1866     if (CHARDEV_CLASS(klass)->internal) {
1867         return;
1868     }
1869 
1870     fe->fn(object_class_get_name(klass) + 8, fe->opaque);
1871 }
1872 
1873 static void
1874 chardev_name_foreach(void (*fn)(const char *name, void *opaque), void *opaque)
1875 {
1876     ChadevClassFE fe = { .fn = fn, .opaque = opaque };
1877     int i;
1878 
1879     object_class_foreach(chardev_class_foreach, TYPE_CHARDEV, false, &fe);
1880 
1881     for (i = 0; i < ARRAY_SIZE(chardev_alias_table); i++) {
1882         fn(chardev_alias_table[i].alias, opaque);
1883     }
1884 }
1885 
1886 static void
1887 help_string_append(const char *name, void *opaque)
1888 {
1889     GString *str = opaque;
1890 
1891     g_string_append_printf(str, "\n%s", name);
1892 }
1893 
1894 Chardev *qemu_chr_new_from_opts(QemuOpts *opts,
1895                                 Error **errp)
1896 {
1897     Error *local_err = NULL;
1898     const ChardevClass *cc;
1899     Chardev *chr;
1900     int i;
1901     ChardevBackend *backend = NULL;
1902     const char *name = qemu_opt_get(opts, "backend");
1903     const char *id = qemu_opts_id(opts);
1904     char *bid = NULL;
1905 
1906     if (name == NULL) {
1907         error_setg(errp, "chardev: \"%s\" missing backend",
1908                    qemu_opts_id(opts));
1909         return NULL;
1910     }
1911 
1912     if (is_help_option(name)) {
1913         GString *str = g_string_new("");
1914 
1915         chardev_name_foreach(help_string_append, str);
1916 
1917         error_report("Available chardev backend types: %s", str->str);
1918         g_string_free(str, true);
1919         exit(0);
1920     }
1921 
1922     if (id == NULL) {
1923         error_setg(errp, "chardev: no id specified");
1924         return NULL;
1925     }
1926 
1927     for (i = 0; i < ARRAY_SIZE(chardev_alias_table); i++) {
1928         if (g_strcmp0(chardev_alias_table[i].alias, name) == 0) {
1929             name = chardev_alias_table[i].typename;
1930             break;
1931         }
1932     }
1933 
1934     cc = char_get_class(name, errp);
1935     if (cc == NULL) {
1936         return NULL;
1937     }
1938 
1939     backend = g_new0(ChardevBackend, 1);
1940     backend->type = CHARDEV_BACKEND_KIND_NULL;
1941 
1942     if (qemu_opt_get_bool(opts, "mux", 0)) {
1943         bid = g_strdup_printf("%s-base", id);
1944     }
1945 
1946     chr = NULL;
1947     if (cc->parse) {
1948         cc->parse(opts, backend, &local_err);
1949         if (local_err) {
1950             error_propagate(errp, local_err);
1951             goto out;
1952         }
1953     } else {
1954         ChardevCommon *ccom = g_new0(ChardevCommon, 1);
1955         qemu_chr_parse_common(opts, ccom);
1956         backend->u.null.data = ccom; /* Any ChardevCommon member would work */
1957     }
1958 
1959     chr = qemu_chardev_add(bid ? bid : id,
1960                            object_class_get_name(OBJECT_CLASS(cc)),
1961                            backend, errp);
1962     if (chr == NULL) {
1963         goto out;
1964     }
1965 
1966     if (bid) {
1967         Chardev *mux;
1968         qapi_free_ChardevBackend(backend);
1969         backend = g_new0(ChardevBackend, 1);
1970         backend->type = CHARDEV_BACKEND_KIND_MUX;
1971         backend->u.mux.data = g_new0(ChardevMux, 1);
1972         backend->u.mux.data->chardev = g_strdup(bid);
1973         mux = qemu_chardev_add(id, TYPE_CHARDEV_MUX, backend, errp);
1974         if (mux == NULL) {
1975             qemu_chr_delete(chr);
1976             chr = NULL;
1977             goto out;
1978         }
1979         chr = mux;
1980     }
1981 
1982 out:
1983     qapi_free_ChardevBackend(backend);
1984     g_free(bid);
1985     return chr;
1986 }
1987 
1988 Chardev *qemu_chr_new_noreplay(const char *label, const char *filename)
1989 {
1990     const char *p;
1991     Chardev *chr;
1992     QemuOpts *opts;
1993     Error *err = NULL;
1994 
1995     if (strstart(filename, "chardev:", &p)) {
1996         return qemu_chr_find(p);
1997     }
1998 
1999     opts = qemu_chr_parse_compat(label, filename);
2000     if (!opts)
2001         return NULL;
2002 
2003     chr = qemu_chr_new_from_opts(opts, &err);
2004     if (err) {
2005         error_report_err(err);
2006     }
2007     if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
2008         monitor_init(chr, MONITOR_USE_READLINE);
2009     }
2010     qemu_opts_del(opts);
2011     return chr;
2012 }
2013 
2014 Chardev *qemu_chr_new(const char *label, const char *filename)
2015 {
2016     Chardev *chr;
2017     chr = qemu_chr_new_noreplay(label, filename);
2018     if (chr) {
2019         if (replay_mode != REPLAY_MODE_NONE) {
2020             qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_REPLAY);
2021         }
2022         if (qemu_chr_replay(chr) && CHARDEV_GET_CLASS(chr)->chr_ioctl) {
2023             error_report("Replay: ioctl is not supported "
2024                          "for serial devices yet");
2025         }
2026         replay_register_char_driver(chr);
2027     }
2028     return chr;
2029 }
2030 
2031 void qemu_chr_fe_set_echo(CharBackend *be, bool echo)
2032 {
2033     Chardev *chr = be->chr;
2034 
2035     if (chr && CHARDEV_GET_CLASS(chr)->chr_set_echo) {
2036         CHARDEV_GET_CLASS(chr)->chr_set_echo(chr, echo);
2037     }
2038 }
2039 
2040 void qemu_chr_fe_set_open(CharBackend *be, int fe_open)
2041 {
2042     Chardev *chr = be->chr;
2043 
2044     if (!chr) {
2045         return;
2046     }
2047 
2048     if (be->fe_open == fe_open) {
2049         return;
2050     }
2051     be->fe_open = fe_open;
2052     if (CHARDEV_GET_CLASS(chr)->chr_set_fe_open) {
2053         CHARDEV_GET_CLASS(chr)->chr_set_fe_open(chr, fe_open);
2054     }
2055 }
2056 
2057 guint qemu_chr_fe_add_watch(CharBackend *be, GIOCondition cond,
2058                             GIOFunc func, void *user_data)
2059 {
2060     Chardev *s = be->chr;
2061     GSource *src;
2062     guint tag;
2063 
2064     if (!s || CHARDEV_GET_CLASS(s)->chr_add_watch == NULL) {
2065         return 0;
2066     }
2067 
2068     src = CHARDEV_GET_CLASS(s)->chr_add_watch(s, cond);
2069     if (!src) {
2070         return 0;
2071     }
2072 
2073     g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
2074     tag = g_source_attach(src, NULL);
2075     g_source_unref(src);
2076 
2077     return tag;
2078 }
2079 
2080 void qemu_chr_fe_disconnect(CharBackend *be)
2081 {
2082     Chardev *chr = be->chr;
2083 
2084     if (chr && CHARDEV_GET_CLASS(chr)->chr_disconnect) {
2085         CHARDEV_GET_CLASS(chr)->chr_disconnect(chr);
2086     }
2087 }
2088 
2089 void qemu_chr_delete(Chardev *chr)
2090 {
2091     QTAILQ_REMOVE(&chardevs, chr, next);
2092     object_unref(OBJECT(chr));
2093 }
2094 
2095 ChardevInfoList *qmp_query_chardev(Error **errp)
2096 {
2097     ChardevInfoList *chr_list = NULL;
2098     Chardev *chr;
2099 
2100     QTAILQ_FOREACH(chr, &chardevs, next) {
2101         ChardevInfoList *info = g_malloc0(sizeof(*info));
2102         info->value = g_malloc0(sizeof(*info->value));
2103         info->value->label = g_strdup(chr->label);
2104         info->value->filename = g_strdup(chr->filename);
2105         info->value->frontend_open = chr->be && chr->be->fe_open;
2106 
2107         info->next = chr_list;
2108         chr_list = info;
2109     }
2110 
2111     return chr_list;
2112 }
2113 
2114 static void
2115 qmp_prepend_backend(const char *name, void *opaque)
2116 {
2117     ChardevBackendInfoList **list = opaque;
2118     ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
2119 
2120     info->value = g_malloc0(sizeof(*info->value));
2121     info->value->name = g_strdup(name);
2122     info->next = *list;
2123     *list = info;
2124 }
2125 
2126 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
2127 {
2128     ChardevBackendInfoList *backend_list = NULL;
2129 
2130     chardev_name_foreach(qmp_prepend_backend, &backend_list);
2131 
2132     return backend_list;
2133 }
2134 
2135 Chardev *qemu_chr_find(const char *name)
2136 {
2137     Chardev *chr;
2138 
2139     QTAILQ_FOREACH(chr, &chardevs, next) {
2140         if (strcmp(chr->label, name) != 0)
2141             continue;
2142         return chr;
2143     }
2144     return NULL;
2145 }
2146 
2147 QemuOptsList qemu_chardev_opts = {
2148     .name = "chardev",
2149     .implied_opt_name = "backend",
2150     .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
2151     .desc = {
2152         {
2153             .name = "backend",
2154             .type = QEMU_OPT_STRING,
2155         },{
2156             .name = "path",
2157             .type = QEMU_OPT_STRING,
2158         },{
2159             .name = "host",
2160             .type = QEMU_OPT_STRING,
2161         },{
2162             .name = "port",
2163             .type = QEMU_OPT_STRING,
2164         },{
2165             .name = "localaddr",
2166             .type = QEMU_OPT_STRING,
2167         },{
2168             .name = "localport",
2169             .type = QEMU_OPT_STRING,
2170         },{
2171             .name = "to",
2172             .type = QEMU_OPT_NUMBER,
2173         },{
2174             .name = "ipv4",
2175             .type = QEMU_OPT_BOOL,
2176         },{
2177             .name = "ipv6",
2178             .type = QEMU_OPT_BOOL,
2179         },{
2180             .name = "wait",
2181             .type = QEMU_OPT_BOOL,
2182         },{
2183             .name = "server",
2184             .type = QEMU_OPT_BOOL,
2185         },{
2186             .name = "delay",
2187             .type = QEMU_OPT_BOOL,
2188         },{
2189             .name = "reconnect",
2190             .type = QEMU_OPT_NUMBER,
2191         },{
2192             .name = "telnet",
2193             .type = QEMU_OPT_BOOL,
2194         },{
2195             .name = "tls-creds",
2196             .type = QEMU_OPT_STRING,
2197         },{
2198             .name = "width",
2199             .type = QEMU_OPT_NUMBER,
2200         },{
2201             .name = "height",
2202             .type = QEMU_OPT_NUMBER,
2203         },{
2204             .name = "cols",
2205             .type = QEMU_OPT_NUMBER,
2206         },{
2207             .name = "rows",
2208             .type = QEMU_OPT_NUMBER,
2209         },{
2210             .name = "mux",
2211             .type = QEMU_OPT_BOOL,
2212         },{
2213             .name = "signal",
2214             .type = QEMU_OPT_BOOL,
2215         },{
2216             .name = "name",
2217             .type = QEMU_OPT_STRING,
2218         },{
2219             .name = "debug",
2220             .type = QEMU_OPT_NUMBER,
2221         },{
2222             .name = "size",
2223             .type = QEMU_OPT_SIZE,
2224         },{
2225             .name = "chardev",
2226             .type = QEMU_OPT_STRING,
2227         },{
2228             .name = "append",
2229             .type = QEMU_OPT_BOOL,
2230         },{
2231             .name = "logfile",
2232             .type = QEMU_OPT_STRING,
2233         },{
2234             .name = "logappend",
2235             .type = QEMU_OPT_BOOL,
2236         },
2237         { /* end of list */ }
2238     },
2239 };
2240 
2241 #ifdef _WIN32
2242 
2243 static void qmp_chardev_open_serial(Chardev *chr,
2244                                     ChardevBackend *backend,
2245                                     bool *be_opened,
2246                                     Error **errp)
2247 {
2248     ChardevHostdev *serial = backend->u.serial.data;
2249 
2250     win_chr_init(chr, serial->device, errp);
2251 }
2252 
2253 #else /* WIN32 */
2254 
2255 #ifdef HAVE_CHARDEV_SERIAL
2256 static void qmp_chardev_open_serial(Chardev *chr,
2257                                     ChardevBackend *backend,
2258                                     bool *be_opened,
2259                                     Error **errp)
2260 {
2261     ChardevHostdev *serial = backend->u.serial.data;
2262     int fd;
2263 
2264     fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
2265     if (fd < 0) {
2266         return;
2267     }
2268     qemu_set_nonblock(fd);
2269     tty_serial_init(fd, 115200, 'N', 8, 1);
2270 
2271     qemu_chr_open_fd(chr, fd, fd);
2272 }
2273 #endif
2274 
2275 #ifdef HAVE_CHARDEV_PARPORT
2276 static void qmp_chardev_open_parallel(Chardev *chr,
2277                                       ChardevBackend *backend,
2278                                       bool *be_opened,
2279                                       Error **errp)
2280 {
2281     ChardevHostdev *parallel = backend->u.parallel.data;
2282     int fd;
2283 
2284     fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
2285     if (fd < 0) {
2286         return;
2287     }
2288     qemu_chr_open_pp_fd(chr, fd, be_opened, errp);
2289 }
2290 
2291 static void char_parallel_class_init(ObjectClass *oc, void *data)
2292 {
2293     ChardevClass *cc = CHARDEV_CLASS(oc);
2294 
2295     cc->parse = qemu_chr_parse_parallel;
2296     cc->open = qmp_chardev_open_parallel;
2297 #if defined(__linux__)
2298     cc->chr_ioctl = pp_ioctl;
2299 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
2300     cc->chr_ioctl = pp_ioctl;
2301 #endif
2302 }
2303 
2304 static void char_parallel_finalize(Object *obj)
2305 {
2306 #if defined(__linux__)
2307     Chardev *chr = CHARDEV(obj);
2308     ParallelChardev *drv = PARALLEL_CHARDEV(chr);
2309     int fd = drv->fd;
2310 
2311     pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2312     ioctl(fd, PPRELEASE);
2313     close(fd);
2314     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2315 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
2316     /* FIXME: close fd? */
2317 #endif
2318 }
2319 
2320 static const TypeInfo char_parallel_type_info = {
2321     .name = TYPE_CHARDEV_PARALLEL,
2322     .parent = TYPE_CHARDEV,
2323     .instance_size = sizeof(ParallelChardev),
2324     .instance_finalize = char_parallel_finalize,
2325     .class_init = char_parallel_class_init,
2326 };
2327 #endif
2328 
2329 #endif /* WIN32 */
2330 
2331 #ifdef HAVE_CHARDEV_SERIAL
2332 
2333 static void char_serial_class_init(ObjectClass *oc, void *data)
2334 {
2335     ChardevClass *cc = CHARDEV_CLASS(oc);
2336 
2337     cc->parse = qemu_chr_parse_serial;
2338     cc->open = qmp_chardev_open_serial;
2339 #ifndef _WIN32
2340     cc->chr_ioctl = tty_serial_ioctl;
2341 #endif
2342 }
2343 
2344 static const TypeInfo char_serial_type_info = {
2345     .name = TYPE_CHARDEV_SERIAL,
2346 #ifdef _WIN32
2347     .parent = TYPE_CHARDEV_WIN,
2348 #else
2349     .parent = TYPE_CHARDEV_FD,
2350 #endif
2351     .class_init = char_serial_class_init,
2352 };
2353 #endif
2354 
2355 bool qemu_chr_has_feature(Chardev *chr,
2356                           ChardevFeature feature)
2357 {
2358     return test_bit(feature, chr->features);
2359 }
2360 
2361 void qemu_chr_set_feature(Chardev *chr,
2362                            ChardevFeature feature)
2363 {
2364     return set_bit(feature, chr->features);
2365 }
2366 
2367 Chardev *qemu_chardev_new(const char *id, const char *typename,
2368                           ChardevBackend *backend, Error **errp)
2369 {
2370     Chardev *chr = NULL;
2371     Error *local_err = NULL;
2372     bool be_opened = true;
2373 
2374     assert(g_str_has_prefix(typename, "chardev-"));
2375 
2376     chr = CHARDEV(object_new(typename));
2377     chr->label = g_strdup(id);
2378 
2379     qemu_char_open(chr, backend, &be_opened, &local_err);
2380     if (local_err) {
2381         error_propagate(errp, local_err);
2382         object_unref(OBJECT(chr));
2383         return NULL;
2384     }
2385 
2386     if (!chr->filename) {
2387         chr->filename = g_strdup(typename + 8);
2388     }
2389     if (be_opened) {
2390         qemu_chr_be_event(chr, CHR_EVENT_OPENED);
2391     }
2392 
2393     return chr;
2394 }
2395 
2396 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
2397                                Error **errp)
2398 {
2399     const ChardevClass *cc;
2400     ChardevReturn *ret;
2401     Chardev *chr;
2402 
2403     cc = char_get_class(ChardevBackendKind_lookup[backend->type], errp);
2404     if (!cc) {
2405         return NULL;
2406     }
2407 
2408     chr = qemu_chardev_add(id, object_class_get_name(OBJECT_CLASS(cc)),
2409                            backend, errp);
2410     if (!chr) {
2411         return NULL;
2412     }
2413 
2414     ret = g_new0(ChardevReturn, 1);
2415     if (CHARDEV_IS_PTY(chr)) {
2416         ret->pty = g_strdup(chr->filename + 4);
2417         ret->has_pty = true;
2418     }
2419 
2420     return ret;
2421 }
2422 
2423 void qmp_chardev_remove(const char *id, Error **errp)
2424 {
2425     Chardev *chr;
2426 
2427     chr = qemu_chr_find(id);
2428     if (chr == NULL) {
2429         error_setg(errp, "Chardev '%s' not found", id);
2430         return;
2431     }
2432     if (qemu_chr_is_busy(chr)) {
2433         error_setg(errp, "Chardev '%s' is busy", id);
2434         return;
2435     }
2436     if (qemu_chr_replay(chr)) {
2437         error_setg(errp,
2438             "Chardev '%s' cannot be unplugged in record/replay mode", id);
2439         return;
2440     }
2441     qemu_chr_delete(chr);
2442 }
2443 
2444 void qemu_chr_cleanup(void)
2445 {
2446     Chardev *chr, *tmp;
2447 
2448     QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
2449         qemu_chr_delete(chr);
2450     }
2451 }
2452 
2453 static void register_types(void)
2454 {
2455     type_register_static(&char_type_info);
2456     type_register_static(&char_stdio_type_info);
2457 #ifdef HAVE_CHARDEV_SERIAL
2458     type_register_static(&char_serial_type_info);
2459 #endif
2460 #ifdef HAVE_CHARDEV_PARPORT
2461     type_register_static(&char_parallel_type_info);
2462 #endif
2463 #ifdef HAVE_CHARDEV_PTY
2464     type_register_static(&char_pty_type_info);
2465 #endif
2466 #ifdef _WIN32
2467     type_register_static(&char_console_type_info);
2468 #endif
2469     type_register_static(&char_pipe_type_info);
2470 
2471     /* this must be done after machine init, since we register FEs with muxes
2472      * as part of realize functions like serial_isa_realizefn when -nographic
2473      * is specified
2474      */
2475     qemu_add_machine_init_done_notifier(&muxes_realize_notify);
2476 }
2477 
2478 type_init(register_types);
2479