linux-user: Use glib malloc functions in load_symbols()
[qemu/ar7.git] / qemu-char.c
blob8826419d7d57badb25950e3e78bfdf997bdc2954
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
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"
44 #include <zlib.h>
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
85 #include "qemu/sockets.h"
86 #include "ui/qemu-spice.h"
88 #define READ_BUF_LEN 4096
89 #define READ_RETRIES 10
90 #define TCP_MAX_FDS 16
92 /***********************************************************/
93 /* Socket address helpers */
95 static char *SocketAddress_to_str(const char *prefix, SocketAddress *addr,
96 bool is_listen, bool is_telnet)
98 switch (addr->type) {
99 case SOCKET_ADDRESS_KIND_INET:
100 return g_strdup_printf("%s%s:%s:%s%s", prefix,
101 is_telnet ? "telnet" : "tcp",
102 addr->u.inet.data->host,
103 addr->u.inet.data->port,
104 is_listen ? ",server" : "");
105 break;
106 case SOCKET_ADDRESS_KIND_UNIX:
107 return g_strdup_printf("%sunix:%s%s", prefix,
108 addr->u.q_unix.data->path,
109 is_listen ? ",server" : "");
110 break;
111 case SOCKET_ADDRESS_KIND_FD:
112 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd.data->str,
113 is_listen ? ",server" : "");
114 break;
115 default:
116 abort();
120 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
121 struct sockaddr_storage *ps, socklen_t ps_len,
122 bool is_listen, bool is_telnet)
124 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
125 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
126 const char *left = "", *right = "";
128 switch (ss->ss_family) {
129 #ifndef _WIN32
130 case AF_UNIX:
131 return g_strdup_printf("unix:%s%s",
132 ((struct sockaddr_un *)(ss))->sun_path,
133 is_listen ? ",server" : "");
134 #endif
135 case AF_INET6:
136 left = "[";
137 right = "]";
138 /* fall through */
139 case AF_INET:
140 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
141 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
142 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
143 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
144 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
145 is_telnet ? "telnet" : "tcp",
146 left, shost, right, sserv,
147 is_listen ? ",server" : "",
148 left, phost, right, pserv);
150 default:
151 return g_strdup_printf("unknown");
155 /***********************************************************/
156 /* character device */
158 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
159 QTAILQ_HEAD_INITIALIZER(chardevs);
161 static void qemu_chr_free_common(CharDriverState *chr);
163 CharDriverState *qemu_chr_alloc(ChardevCommon *backend, Error **errp)
165 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
166 qemu_mutex_init(&chr->chr_write_lock);
168 if (backend->has_logfile) {
169 int flags = O_WRONLY | O_CREAT;
170 if (backend->has_logappend &&
171 backend->logappend) {
172 flags |= O_APPEND;
173 } else {
174 flags |= O_TRUNC;
176 chr->logfd = qemu_open(backend->logfile, flags, 0666);
177 if (chr->logfd < 0) {
178 error_setg_errno(errp, errno,
179 "Unable to open logfile %s",
180 backend->logfile);
181 g_free(chr);
182 return NULL;
184 } else {
185 chr->logfd = -1;
188 return chr;
191 void qemu_chr_be_event(CharDriverState *s, int event)
193 /* Keep track if the char device is open */
194 switch (event) {
195 case CHR_EVENT_OPENED:
196 s->be_open = 1;
197 break;
198 case CHR_EVENT_CLOSED:
199 s->be_open = 0;
200 break;
203 if (!s->chr_event)
204 return;
205 s->chr_event(s->handler_opaque, event);
208 void qemu_chr_be_generic_open(CharDriverState *s)
210 qemu_chr_be_event(s, CHR_EVENT_OPENED);
214 /* Not reporting errors from writing to logfile, as logs are
215 * defined to be "best effort" only */
216 static void qemu_chr_fe_write_log(CharDriverState *s,
217 const uint8_t *buf, size_t len)
219 size_t done = 0;
220 ssize_t ret;
222 if (s->logfd < 0) {
223 return;
226 while (done < len) {
227 retry:
228 ret = write(s->logfd, buf + done, len - done);
229 if (ret == -1 && errno == EAGAIN) {
230 g_usleep(100);
231 goto retry;
234 if (ret <= 0) {
235 return;
237 done += ret;
241 static int qemu_chr_fe_write_buffer(CharDriverState *s, const uint8_t *buf, int len, int *offset)
243 int res = 0;
244 *offset = 0;
246 qemu_mutex_lock(&s->chr_write_lock);
247 while (*offset < len) {
248 retry:
249 res = s->chr_write(s, buf + *offset, len - *offset);
250 if (res < 0 && errno == EAGAIN) {
251 g_usleep(100);
252 goto retry;
255 if (res <= 0) {
256 break;
259 *offset += res;
261 if (*offset > 0) {
262 qemu_chr_fe_write_log(s, buf, *offset);
264 qemu_mutex_unlock(&s->chr_write_lock);
266 return res;
269 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
271 int ret;
273 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
274 int offset;
275 replay_char_write_event_load(&ret, &offset);
276 assert(offset <= len);
277 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
278 return ret;
281 qemu_mutex_lock(&s->chr_write_lock);
282 ret = s->chr_write(s, buf, len);
284 if (ret > 0) {
285 qemu_chr_fe_write_log(s, buf, ret);
288 qemu_mutex_unlock(&s->chr_write_lock);
290 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
291 replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
294 return ret;
297 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
299 int offset;
300 int res;
302 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
303 replay_char_write_event_load(&res, &offset);
304 assert(offset <= len);
305 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
306 return res;
309 res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
311 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
312 replay_char_write_event_save(res, offset);
315 if (res < 0) {
316 return res;
318 return offset;
321 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
323 int offset = 0, counter = 10;
324 int res;
326 if (!s->chr_sync_read) {
327 return 0;
330 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
331 return replay_char_read_all_load(buf);
334 while (offset < len) {
335 retry:
336 res = s->chr_sync_read(s, buf + offset, len - offset);
337 if (res == -1 && errno == EAGAIN) {
338 g_usleep(100);
339 goto retry;
342 if (res == 0) {
343 break;
346 if (res < 0) {
347 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
348 replay_char_read_all_save_error(res);
350 return res;
353 offset += res;
355 if (!counter--) {
356 break;
360 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
361 replay_char_read_all_save_buf(buf, offset);
363 return offset;
366 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
368 int res;
369 if (!s->chr_ioctl || s->replay) {
370 res = -ENOTSUP;
371 } else {
372 res = s->chr_ioctl(s, cmd, arg);
375 return res;
378 int qemu_chr_be_can_write(CharDriverState *s)
380 if (!s->chr_can_read)
381 return 0;
382 return s->chr_can_read(s->handler_opaque);
385 void qemu_chr_be_write_impl(CharDriverState *s, uint8_t *buf, int len)
387 if (s->chr_read) {
388 s->chr_read(s->handler_opaque, buf, len);
392 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
394 if (s->replay) {
395 if (replay_mode == REPLAY_MODE_PLAY) {
396 return;
398 replay_chr_be_write(s, buf, len);
399 } else {
400 qemu_chr_be_write_impl(s, buf, len);
404 int qemu_chr_fe_get_msgfd(CharDriverState *s)
406 int fd;
407 int res = (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
408 if (s->replay) {
409 fprintf(stderr,
410 "Replay: get msgfd is not supported for serial devices yet\n");
411 exit(1);
413 return res;
416 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
418 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
421 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
423 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
426 int qemu_chr_add_client(CharDriverState *s, int fd)
428 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
431 void qemu_chr_accept_input(CharDriverState *s)
433 if (s->chr_accept_input)
434 s->chr_accept_input(s);
435 qemu_notify_event();
438 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
440 char buf[READ_BUF_LEN];
441 va_list ap;
442 va_start(ap, fmt);
443 vsnprintf(buf, sizeof(buf), fmt, ap);
444 /* XXX this blocks entire thread. Rewrite to use
445 * qemu_chr_fe_write and background I/O callbacks */
446 qemu_chr_fe_write_all(s, (uint8_t *)buf, strlen(buf));
447 va_end(ap);
450 static void remove_fd_in_watch(CharDriverState *chr);
452 void qemu_chr_add_handlers(CharDriverState *s,
453 IOCanReadHandler *fd_can_read,
454 IOReadHandler *fd_read,
455 IOEventHandler *fd_event,
456 void *opaque)
458 int fe_open;
460 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
461 fe_open = 0;
462 remove_fd_in_watch(s);
463 } else {
464 fe_open = 1;
466 s->chr_can_read = fd_can_read;
467 s->chr_read = fd_read;
468 s->chr_event = fd_event;
469 s->handler_opaque = opaque;
470 if (fe_open && s->chr_update_read_handler)
471 s->chr_update_read_handler(s);
473 if (!s->explicit_fe_open) {
474 qemu_chr_fe_set_open(s, fe_open);
477 /* We're connecting to an already opened device, so let's make sure we
478 also get the open event */
479 if (fe_open && s->be_open) {
480 qemu_chr_be_generic_open(s);
484 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
486 return len;
489 static CharDriverState *qemu_chr_open_null(const char *id,
490 ChardevBackend *backend,
491 ChardevReturn *ret,
492 Error **errp)
494 CharDriverState *chr;
495 ChardevCommon *common = backend->u.null.data;
497 chr = qemu_chr_alloc(common, errp);
498 if (!chr) {
499 return NULL;
501 chr->chr_write = null_chr_write;
502 chr->explicit_be_open = true;
503 return chr;
506 /* MUX driver for serial I/O splitting */
507 #define MAX_MUX 4
508 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
509 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
510 typedef struct {
511 IOCanReadHandler *chr_can_read[MAX_MUX];
512 IOReadHandler *chr_read[MAX_MUX];
513 IOEventHandler *chr_event[MAX_MUX];
514 void *ext_opaque[MAX_MUX];
515 CharDriverState *drv;
516 int focus;
517 int mux_cnt;
518 int term_got_escape;
519 int max_size;
520 /* Intermediate input buffer allows to catch escape sequences even if the
521 currently active device is not accepting any input - but only until it
522 is full as well. */
523 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
524 int prod[MAX_MUX];
525 int cons[MAX_MUX];
526 int timestamps;
528 /* Protected by the CharDriverState chr_write_lock. */
529 int linestart;
530 int64_t timestamps_start;
531 } MuxDriver;
534 /* Called with chr_write_lock held. */
535 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
537 MuxDriver *d = chr->opaque;
538 int ret;
539 if (!d->timestamps) {
540 ret = qemu_chr_fe_write(d->drv, buf, len);
541 } else {
542 int i;
544 ret = 0;
545 for (i = 0; i < len; i++) {
546 if (d->linestart) {
547 char buf1[64];
548 int64_t ti;
549 int secs;
551 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
552 if (d->timestamps_start == -1)
553 d->timestamps_start = ti;
554 ti -= d->timestamps_start;
555 secs = ti / 1000;
556 snprintf(buf1, sizeof(buf1),
557 "[%02d:%02d:%02d.%03d] ",
558 secs / 3600,
559 (secs / 60) % 60,
560 secs % 60,
561 (int)(ti % 1000));
562 /* XXX this blocks entire thread. Rewrite to use
563 * qemu_chr_fe_write and background I/O callbacks */
564 qemu_chr_fe_write_all(d->drv, (uint8_t *)buf1, strlen(buf1));
565 d->linestart = 0;
567 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
568 if (buf[i] == '\n') {
569 d->linestart = 1;
573 return ret;
576 static const char * const mux_help[] = {
577 "% h print this help\n\r",
578 "% x exit emulator\n\r",
579 "% s save disk data back to file (if -snapshot)\n\r",
580 "% t toggle console timestamps\n\r",
581 "% b send break (magic sysrq)\n\r",
582 "% c switch between console and monitor\n\r",
583 "% % sends %\n\r",
584 NULL
587 int term_escape_char = 0x01; /* ctrl-a is used for escape */
588 static void mux_print_help(CharDriverState *chr)
590 int i, j;
591 char ebuf[15] = "Escape-Char";
592 char cbuf[50] = "\n\r";
594 if (term_escape_char > 0 && term_escape_char < 26) {
595 snprintf(cbuf, sizeof(cbuf), "\n\r");
596 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
597 } else {
598 snprintf(cbuf, sizeof(cbuf),
599 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
600 term_escape_char);
602 /* XXX this blocks entire thread. Rewrite to use
603 * qemu_chr_fe_write and background I/O callbacks */
604 qemu_chr_fe_write_all(chr, (uint8_t *)cbuf, strlen(cbuf));
605 for (i = 0; mux_help[i] != NULL; i++) {
606 for (j=0; mux_help[i][j] != '\0'; j++) {
607 if (mux_help[i][j] == '%')
608 qemu_chr_fe_write_all(chr, (uint8_t *)ebuf, strlen(ebuf));
609 else
610 qemu_chr_fe_write_all(chr, (uint8_t *)&mux_help[i][j], 1);
615 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
617 if (d->chr_event[mux_nr])
618 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
621 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
623 if (d->term_got_escape) {
624 d->term_got_escape = 0;
625 if (ch == term_escape_char)
626 goto send_char;
627 switch(ch) {
628 case '?':
629 case 'h':
630 mux_print_help(chr);
631 break;
632 case 'x':
634 const char *term = "QEMU: Terminated\n\r";
635 qemu_chr_fe_write_all(chr, (uint8_t *)term, strlen(term));
636 exit(0);
637 break;
639 case 's':
640 blk_commit_all();
641 break;
642 case 'b':
643 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
644 break;
645 case 'c':
646 /* Switch to the next registered device */
647 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
648 d->focus++;
649 if (d->focus >= d->mux_cnt)
650 d->focus = 0;
651 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
652 break;
653 case 't':
654 d->timestamps = !d->timestamps;
655 d->timestamps_start = -1;
656 d->linestart = 0;
657 break;
659 } else if (ch == term_escape_char) {
660 d->term_got_escape = 1;
661 } else {
662 send_char:
663 return 1;
665 return 0;
668 static void mux_chr_accept_input(CharDriverState *chr)
670 MuxDriver *d = chr->opaque;
671 int m = d->focus;
673 while (d->prod[m] != d->cons[m] &&
674 d->chr_can_read[m] &&
675 d->chr_can_read[m](d->ext_opaque[m])) {
676 d->chr_read[m](d->ext_opaque[m],
677 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
681 static int mux_chr_can_read(void *opaque)
683 CharDriverState *chr = opaque;
684 MuxDriver *d = chr->opaque;
685 int m = d->focus;
687 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
688 return 1;
689 if (d->chr_can_read[m])
690 return d->chr_can_read[m](d->ext_opaque[m]);
691 return 0;
694 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
696 CharDriverState *chr = opaque;
697 MuxDriver *d = chr->opaque;
698 int m = d->focus;
699 int i;
701 mux_chr_accept_input (opaque);
703 for(i = 0; i < size; i++)
704 if (mux_proc_byte(chr, d, buf[i])) {
705 if (d->prod[m] == d->cons[m] &&
706 d->chr_can_read[m] &&
707 d->chr_can_read[m](d->ext_opaque[m]))
708 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
709 else
710 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
714 static void mux_chr_event(void *opaque, int event)
716 CharDriverState *chr = opaque;
717 MuxDriver *d = chr->opaque;
718 int i;
720 /* Send the event to all registered listeners */
721 for (i = 0; i < d->mux_cnt; i++)
722 mux_chr_send_event(d, i, event);
725 static void mux_chr_update_read_handler(CharDriverState *chr)
727 MuxDriver *d = chr->opaque;
729 if (d->mux_cnt >= MAX_MUX) {
730 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
731 return;
733 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
734 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
735 d->chr_read[d->mux_cnt] = chr->chr_read;
736 d->chr_event[d->mux_cnt] = chr->chr_event;
737 /* Fix up the real driver with mux routines */
738 if (d->mux_cnt == 0) {
739 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
740 mux_chr_event, chr);
742 if (d->focus != -1) {
743 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
745 d->focus = d->mux_cnt;
746 d->mux_cnt++;
747 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
750 static bool muxes_realized;
753 * Called after processing of default and command-line-specified
754 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
755 * to a mux chardev. This is done here to ensure that
756 * output/prompts/banners are only displayed for the FE that has
757 * focus when initial command-line processing/machine init is
758 * completed.
760 * After this point, any new FE attached to any new or existing
761 * mux will receive CHR_EVENT_OPENED notifications for the BE
762 * immediately.
764 static void muxes_realize_done(Notifier *notifier, void *unused)
766 CharDriverState *chr;
768 QTAILQ_FOREACH(chr, &chardevs, next) {
769 if (chr->is_mux) {
770 MuxDriver *d = chr->opaque;
771 int i;
773 /* send OPENED to all already-attached FEs */
774 for (i = 0; i < d->mux_cnt; i++) {
775 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
777 /* mark mux as OPENED so any new FEs will immediately receive
778 * OPENED event
780 qemu_chr_be_generic_open(chr);
783 muxes_realized = true;
786 static Notifier muxes_realize_notify = {
787 .notify = muxes_realize_done,
790 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
792 MuxDriver *d = s->opaque;
793 return d->drv->chr_add_watch(d->drv, cond);
796 static void mux_chr_close(struct CharDriverState *chr)
798 MuxDriver *d = chr->opaque;
800 g_free(d);
803 static CharDriverState *qemu_chr_open_mux(const char *id,
804 ChardevBackend *backend,
805 ChardevReturn *ret, Error **errp)
807 ChardevMux *mux = backend->u.mux.data;
808 CharDriverState *chr, *drv;
809 MuxDriver *d;
810 ChardevCommon *common = qapi_ChardevMux_base(mux);
812 drv = qemu_chr_find(mux->chardev);
813 if (drv == NULL) {
814 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
815 return NULL;
818 chr = qemu_chr_alloc(common, errp);
819 if (!chr) {
820 return NULL;
822 d = g_new0(MuxDriver, 1);
824 chr->opaque = d;
825 d->drv = drv;
826 d->focus = -1;
827 chr->chr_close = mux_chr_close;
828 chr->chr_write = mux_chr_write;
829 chr->chr_update_read_handler = mux_chr_update_read_handler;
830 chr->chr_accept_input = mux_chr_accept_input;
831 /* Frontend guest-open / -close notification is not support with muxes */
832 chr->chr_set_fe_open = NULL;
833 if (drv->chr_add_watch) {
834 chr->chr_add_watch = mux_chr_add_watch;
836 /* only default to opened state if we've realized the initial
837 * set of muxes
839 chr->explicit_be_open = muxes_realized ? 0 : 1;
840 chr->is_mux = 1;
842 return chr;
846 typedef struct IOWatchPoll
848 GSource parent;
850 QIOChannel *ioc;
851 GSource *src;
853 IOCanReadHandler *fd_can_read;
854 GSourceFunc fd_read;
855 void *opaque;
856 } IOWatchPoll;
858 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
860 return container_of(source, IOWatchPoll, parent);
863 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
865 IOWatchPoll *iwp = io_watch_poll_from_source(source);
866 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
867 bool was_active = iwp->src != NULL;
868 if (was_active == now_active) {
869 return FALSE;
872 if (now_active) {
873 iwp->src = qio_channel_create_watch(
874 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
875 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
876 g_source_attach(iwp->src, NULL);
877 } else {
878 g_source_destroy(iwp->src);
879 g_source_unref(iwp->src);
880 iwp->src = NULL;
882 return FALSE;
885 static gboolean io_watch_poll_check(GSource *source)
887 return FALSE;
890 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
891 gpointer user_data)
893 abort();
896 static void io_watch_poll_finalize(GSource *source)
898 /* Due to a glib bug, removing the last reference to a source
899 * inside a finalize callback causes recursive locking (and a
900 * deadlock). This is not a problem inside other callbacks,
901 * including dispatch callbacks, so we call io_remove_watch_poll
902 * to remove this source. At this point, iwp->src must
903 * be NULL, or we would leak it.
905 * This would be solved much more elegantly by child sources,
906 * but we support older glib versions that do not have them.
908 IOWatchPoll *iwp = io_watch_poll_from_source(source);
909 assert(iwp->src == NULL);
912 static GSourceFuncs io_watch_poll_funcs = {
913 .prepare = io_watch_poll_prepare,
914 .check = io_watch_poll_check,
915 .dispatch = io_watch_poll_dispatch,
916 .finalize = io_watch_poll_finalize,
919 /* Can only be used for read */
920 static guint io_add_watch_poll(QIOChannel *ioc,
921 IOCanReadHandler *fd_can_read,
922 QIOChannelFunc fd_read,
923 gpointer user_data)
925 IOWatchPoll *iwp;
926 int tag;
928 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
929 iwp->fd_can_read = fd_can_read;
930 iwp->opaque = user_data;
931 iwp->ioc = ioc;
932 iwp->fd_read = (GSourceFunc) fd_read;
933 iwp->src = NULL;
935 tag = g_source_attach(&iwp->parent, NULL);
936 g_source_unref(&iwp->parent);
937 return tag;
940 static void io_remove_watch_poll(guint tag)
942 GSource *source;
943 IOWatchPoll *iwp;
945 g_return_if_fail (tag > 0);
947 source = g_main_context_find_source_by_id(NULL, tag);
948 g_return_if_fail (source != NULL);
950 iwp = io_watch_poll_from_source(source);
951 if (iwp->src) {
952 g_source_destroy(iwp->src);
953 g_source_unref(iwp->src);
954 iwp->src = NULL;
956 g_source_destroy(&iwp->parent);
959 static void remove_fd_in_watch(CharDriverState *chr)
961 if (chr->fd_in_tag) {
962 io_remove_watch_poll(chr->fd_in_tag);
963 chr->fd_in_tag = 0;
968 static int io_channel_send_full(QIOChannel *ioc,
969 const void *buf, size_t len,
970 int *fds, size_t nfds)
972 size_t offset = 0;
974 while (offset < len) {
975 ssize_t ret = 0;
976 struct iovec iov = { .iov_base = (char *)buf + offset,
977 .iov_len = len - offset };
979 ret = qio_channel_writev_full(
980 ioc, &iov, 1,
981 fds, nfds, NULL);
982 if (ret == QIO_CHANNEL_ERR_BLOCK) {
983 if (offset) {
984 return offset;
987 errno = EAGAIN;
988 return -1;
989 } else if (ret < 0) {
990 errno = EINVAL;
991 return -1;
994 offset += ret;
997 return offset;
1001 #ifndef _WIN32
1002 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
1004 return io_channel_send_full(ioc, buf, len, NULL, 0);
1008 typedef struct FDCharDriver {
1009 CharDriverState *chr;
1010 QIOChannel *ioc_in, *ioc_out;
1011 int max_size;
1012 } FDCharDriver;
1014 /* Called with chr_write_lock held. */
1015 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1017 FDCharDriver *s = chr->opaque;
1019 return io_channel_send(s->ioc_out, buf, len);
1022 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1024 CharDriverState *chr = opaque;
1025 FDCharDriver *s = chr->opaque;
1026 int len;
1027 uint8_t buf[READ_BUF_LEN];
1028 ssize_t ret;
1030 len = sizeof(buf);
1031 if (len > s->max_size) {
1032 len = s->max_size;
1034 if (len == 0) {
1035 return TRUE;
1038 ret = qio_channel_read(
1039 chan, (gchar *)buf, len, NULL);
1040 if (ret == 0) {
1041 remove_fd_in_watch(chr);
1042 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1043 return FALSE;
1045 if (ret > 0) {
1046 qemu_chr_be_write(chr, buf, ret);
1049 return TRUE;
1052 static int fd_chr_read_poll(void *opaque)
1054 CharDriverState *chr = opaque;
1055 FDCharDriver *s = chr->opaque;
1057 s->max_size = qemu_chr_be_can_write(chr);
1058 return s->max_size;
1061 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1063 FDCharDriver *s = chr->opaque;
1064 return qio_channel_create_watch(s->ioc_out, cond);
1067 static void fd_chr_update_read_handler(CharDriverState *chr)
1069 FDCharDriver *s = chr->opaque;
1071 remove_fd_in_watch(chr);
1072 if (s->ioc_in) {
1073 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
1074 fd_chr_read_poll,
1075 fd_chr_read, chr);
1079 static void fd_chr_close(struct CharDriverState *chr)
1081 FDCharDriver *s = chr->opaque;
1083 remove_fd_in_watch(chr);
1084 if (s->ioc_in) {
1085 object_unref(OBJECT(s->ioc_in));
1087 if (s->ioc_out) {
1088 object_unref(OBJECT(s->ioc_out));
1091 g_free(s);
1092 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1095 /* open a character device to a unix fd */
1096 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1097 ChardevCommon *backend, Error **errp)
1099 CharDriverState *chr;
1100 FDCharDriver *s;
1102 chr = qemu_chr_alloc(backend, errp);
1103 if (!chr) {
1104 return NULL;
1106 s = g_new0(FDCharDriver, 1);
1107 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1108 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1109 qemu_set_nonblock(fd_out);
1110 s->chr = chr;
1111 chr->opaque = s;
1112 chr->chr_add_watch = fd_chr_add_watch;
1113 chr->chr_write = fd_chr_write;
1114 chr->chr_update_read_handler = fd_chr_update_read_handler;
1115 chr->chr_close = fd_chr_close;
1117 return chr;
1120 static CharDriverState *qemu_chr_open_pipe(const char *id,
1121 ChardevBackend *backend,
1122 ChardevReturn *ret,
1123 Error **errp)
1125 ChardevHostdev *opts = backend->u.pipe.data;
1126 int fd_in, fd_out;
1127 char *filename_in;
1128 char *filename_out;
1129 const char *filename = opts->device;
1130 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1133 filename_in = g_strdup_printf("%s.in", filename);
1134 filename_out = g_strdup_printf("%s.out", filename);
1135 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1136 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1137 g_free(filename_in);
1138 g_free(filename_out);
1139 if (fd_in < 0 || fd_out < 0) {
1140 if (fd_in >= 0)
1141 close(fd_in);
1142 if (fd_out >= 0)
1143 close(fd_out);
1144 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1145 if (fd_in < 0) {
1146 error_setg_file_open(errp, errno, filename);
1147 return NULL;
1150 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1153 /* init terminal so that we can grab keys */
1154 static struct termios oldtty;
1155 static int old_fd0_flags;
1156 static bool stdio_in_use;
1157 static bool stdio_allow_signal;
1158 static bool stdio_echo_state;
1160 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1162 static void term_exit(void)
1164 tcsetattr (0, TCSANOW, &oldtty);
1165 fcntl(0, F_SETFL, old_fd0_flags);
1168 static void term_stdio_handler(int sig)
1170 /* restore echo after resume from suspend. */
1171 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1174 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1176 struct termios tty;
1178 stdio_echo_state = echo;
1179 tty = oldtty;
1180 if (!echo) {
1181 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1182 |INLCR|IGNCR|ICRNL|IXON);
1183 tty.c_oflag |= OPOST;
1184 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1185 tty.c_cflag &= ~(CSIZE|PARENB);
1186 tty.c_cflag |= CS8;
1187 tty.c_cc[VMIN] = 1;
1188 tty.c_cc[VTIME] = 0;
1190 if (!stdio_allow_signal)
1191 tty.c_lflag &= ~ISIG;
1193 tcsetattr (0, TCSANOW, &tty);
1196 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1198 term_exit();
1199 fd_chr_close(chr);
1202 static CharDriverState *qemu_chr_open_stdio(const char *id,
1203 ChardevBackend *backend,
1204 ChardevReturn *ret,
1205 Error **errp)
1207 ChardevStdio *opts = backend->u.stdio.data;
1208 CharDriverState *chr;
1209 struct sigaction act;
1210 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1212 if (is_daemonized()) {
1213 error_setg(errp, "cannot use stdio with -daemonize");
1214 return NULL;
1217 if (stdio_in_use) {
1218 error_setg(errp, "cannot use stdio by multiple character devices");
1219 return NULL;
1222 stdio_in_use = true;
1223 old_fd0_flags = fcntl(0, F_GETFL);
1224 tcgetattr(0, &oldtty);
1225 qemu_set_nonblock(0);
1226 atexit(term_exit);
1228 memset(&act, 0, sizeof(act));
1229 act.sa_handler = term_stdio_handler;
1230 sigaction(SIGCONT, &act, NULL);
1232 chr = qemu_chr_open_fd(0, 1, common, errp);
1233 if (!chr) {
1234 return NULL;
1236 chr->chr_close = qemu_chr_close_stdio;
1237 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1238 if (opts->has_signal) {
1239 stdio_allow_signal = opts->signal;
1241 qemu_chr_fe_set_echo(chr, false);
1243 return chr;
1246 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1247 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1248 || defined(__GLIBC__)
1250 #define HAVE_CHARDEV_SERIAL 1
1251 #define HAVE_CHARDEV_PTY 1
1253 typedef struct {
1254 QIOChannel *ioc;
1255 int read_bytes;
1257 /* Protected by the CharDriverState chr_write_lock. */
1258 int connected;
1259 guint timer_tag;
1260 guint open_tag;
1261 } PtyCharDriver;
1263 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1264 static void pty_chr_state(CharDriverState *chr, int connected);
1266 static gboolean pty_chr_timer(gpointer opaque)
1268 struct CharDriverState *chr = opaque;
1269 PtyCharDriver *s = chr->opaque;
1271 qemu_mutex_lock(&chr->chr_write_lock);
1272 s->timer_tag = 0;
1273 s->open_tag = 0;
1274 if (!s->connected) {
1275 /* Next poll ... */
1276 pty_chr_update_read_handler_locked(chr);
1278 qemu_mutex_unlock(&chr->chr_write_lock);
1279 return FALSE;
1282 /* Called with chr_write_lock held. */
1283 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1285 PtyCharDriver *s = chr->opaque;
1287 if (s->timer_tag) {
1288 g_source_remove(s->timer_tag);
1289 s->timer_tag = 0;
1292 if (ms == 1000) {
1293 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1294 } else {
1295 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1299 /* Called with chr_write_lock held. */
1300 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1302 PtyCharDriver *s = chr->opaque;
1303 GPollFD pfd;
1304 int rc;
1305 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1307 pfd.fd = fioc->fd;
1308 pfd.events = G_IO_OUT;
1309 pfd.revents = 0;
1310 do {
1311 rc = g_poll(&pfd, 1, 0);
1312 } while (rc == -1 && errno == EINTR);
1313 assert(rc >= 0);
1315 if (pfd.revents & G_IO_HUP) {
1316 pty_chr_state(chr, 0);
1317 } else {
1318 pty_chr_state(chr, 1);
1322 static void pty_chr_update_read_handler(CharDriverState *chr)
1324 qemu_mutex_lock(&chr->chr_write_lock);
1325 pty_chr_update_read_handler_locked(chr);
1326 qemu_mutex_unlock(&chr->chr_write_lock);
1329 /* Called with chr_write_lock held. */
1330 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1332 PtyCharDriver *s = chr->opaque;
1334 if (!s->connected) {
1335 /* guest sends data, check for (re-)connect */
1336 pty_chr_update_read_handler_locked(chr);
1337 if (!s->connected) {
1338 return 0;
1341 return io_channel_send(s->ioc, buf, len);
1344 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1346 PtyCharDriver *s = chr->opaque;
1347 if (!s->connected) {
1348 return NULL;
1350 return qio_channel_create_watch(s->ioc, cond);
1353 static int pty_chr_read_poll(void *opaque)
1355 CharDriverState *chr = opaque;
1356 PtyCharDriver *s = chr->opaque;
1358 s->read_bytes = qemu_chr_be_can_write(chr);
1359 return s->read_bytes;
1362 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1364 CharDriverState *chr = opaque;
1365 PtyCharDriver *s = chr->opaque;
1366 gsize len;
1367 uint8_t buf[READ_BUF_LEN];
1368 ssize_t ret;
1370 len = sizeof(buf);
1371 if (len > s->read_bytes)
1372 len = s->read_bytes;
1373 if (len == 0) {
1374 return TRUE;
1376 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1377 if (ret <= 0) {
1378 pty_chr_state(chr, 0);
1379 return FALSE;
1380 } else {
1381 pty_chr_state(chr, 1);
1382 qemu_chr_be_write(chr, buf, ret);
1384 return TRUE;
1387 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1389 CharDriverState *chr = opaque;
1390 PtyCharDriver *s = chr->opaque;
1392 s->open_tag = 0;
1393 qemu_chr_be_generic_open(chr);
1394 return FALSE;
1397 /* Called with chr_write_lock held. */
1398 static void pty_chr_state(CharDriverState *chr, int connected)
1400 PtyCharDriver *s = chr->opaque;
1402 if (!connected) {
1403 if (s->open_tag) {
1404 g_source_remove(s->open_tag);
1405 s->open_tag = 0;
1407 remove_fd_in_watch(chr);
1408 s->connected = 0;
1409 /* (re-)connect poll interval for idle guests: once per second.
1410 * We check more frequently in case the guests sends data to
1411 * the virtual device linked to our pty. */
1412 pty_chr_rearm_timer(chr, 1000);
1413 } else {
1414 if (s->timer_tag) {
1415 g_source_remove(s->timer_tag);
1416 s->timer_tag = 0;
1418 if (!s->connected) {
1419 g_assert(s->open_tag == 0);
1420 s->connected = 1;
1421 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1423 if (!chr->fd_in_tag) {
1424 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1425 pty_chr_read_poll,
1426 pty_chr_read, chr);
1431 static void pty_chr_close(struct CharDriverState *chr)
1433 PtyCharDriver *s = chr->opaque;
1435 qemu_mutex_lock(&chr->chr_write_lock);
1436 pty_chr_state(chr, 0);
1437 object_unref(OBJECT(s->ioc));
1438 if (s->timer_tag) {
1439 g_source_remove(s->timer_tag);
1440 s->timer_tag = 0;
1442 qemu_mutex_unlock(&chr->chr_write_lock);
1443 g_free(s);
1444 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1447 static CharDriverState *qemu_chr_open_pty(const char *id,
1448 ChardevBackend *backend,
1449 ChardevReturn *ret,
1450 Error **errp)
1452 CharDriverState *chr;
1453 PtyCharDriver *s;
1454 int master_fd, slave_fd;
1455 char pty_name[PATH_MAX];
1456 ChardevCommon *common = backend->u.pty.data;
1458 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1459 if (master_fd < 0) {
1460 error_setg_errno(errp, errno, "Failed to create PTY");
1461 return NULL;
1464 close(slave_fd);
1465 qemu_set_nonblock(master_fd);
1467 chr = qemu_chr_alloc(common, errp);
1468 if (!chr) {
1469 close(master_fd);
1470 return NULL;
1473 chr->filename = g_strdup_printf("pty:%s", pty_name);
1474 ret->pty = g_strdup(pty_name);
1475 ret->has_pty = true;
1477 fprintf(stderr, "char device redirected to %s (label %s)\n",
1478 pty_name, id);
1480 s = g_new0(PtyCharDriver, 1);
1481 chr->opaque = s;
1482 chr->chr_write = pty_chr_write;
1483 chr->chr_update_read_handler = pty_chr_update_read_handler;
1484 chr->chr_close = pty_chr_close;
1485 chr->chr_add_watch = pty_chr_add_watch;
1486 chr->explicit_be_open = true;
1488 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1489 s->timer_tag = 0;
1491 return chr;
1494 static void tty_serial_init(int fd, int speed,
1495 int parity, int data_bits, int stop_bits)
1497 struct termios tty;
1498 speed_t spd;
1500 #if 0
1501 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1502 speed, parity, data_bits, stop_bits);
1503 #endif
1504 tcgetattr (fd, &tty);
1506 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1507 speed = speed * 10 / 11;
1508 do {
1509 check_speed(50);
1510 check_speed(75);
1511 check_speed(110);
1512 check_speed(134);
1513 check_speed(150);
1514 check_speed(200);
1515 check_speed(300);
1516 check_speed(600);
1517 check_speed(1200);
1518 check_speed(1800);
1519 check_speed(2400);
1520 check_speed(4800);
1521 check_speed(9600);
1522 check_speed(19200);
1523 check_speed(38400);
1524 /* Non-Posix values follow. They may be unsupported on some systems. */
1525 check_speed(57600);
1526 check_speed(115200);
1527 #ifdef B230400
1528 check_speed(230400);
1529 #endif
1530 #ifdef B460800
1531 check_speed(460800);
1532 #endif
1533 #ifdef B500000
1534 check_speed(500000);
1535 #endif
1536 #ifdef B576000
1537 check_speed(576000);
1538 #endif
1539 #ifdef B921600
1540 check_speed(921600);
1541 #endif
1542 #ifdef B1000000
1543 check_speed(1000000);
1544 #endif
1545 #ifdef B1152000
1546 check_speed(1152000);
1547 #endif
1548 #ifdef B1500000
1549 check_speed(1500000);
1550 #endif
1551 #ifdef B2000000
1552 check_speed(2000000);
1553 #endif
1554 #ifdef B2500000
1555 check_speed(2500000);
1556 #endif
1557 #ifdef B3000000
1558 check_speed(3000000);
1559 #endif
1560 #ifdef B3500000
1561 check_speed(3500000);
1562 #endif
1563 #ifdef B4000000
1564 check_speed(4000000);
1565 #endif
1566 spd = B115200;
1567 } while (0);
1569 cfsetispeed(&tty, spd);
1570 cfsetospeed(&tty, spd);
1572 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1573 |INLCR|IGNCR|ICRNL|IXON);
1574 tty.c_oflag |= OPOST;
1575 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1576 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1577 switch(data_bits) {
1578 default:
1579 case 8:
1580 tty.c_cflag |= CS8;
1581 break;
1582 case 7:
1583 tty.c_cflag |= CS7;
1584 break;
1585 case 6:
1586 tty.c_cflag |= CS6;
1587 break;
1588 case 5:
1589 tty.c_cflag |= CS5;
1590 break;
1592 switch(parity) {
1593 default:
1594 case 'N':
1595 break;
1596 case 'E':
1597 tty.c_cflag |= PARENB;
1598 break;
1599 case 'O':
1600 tty.c_cflag |= PARENB | PARODD;
1601 break;
1603 if (stop_bits == 2)
1604 tty.c_cflag |= CSTOPB;
1606 tcsetattr (fd, TCSANOW, &tty);
1609 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1611 FDCharDriver *s = chr->opaque;
1612 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1614 switch(cmd) {
1615 case CHR_IOCTL_SERIAL_SET_PARAMS:
1617 QEMUSerialSetParams *ssp = arg;
1618 tty_serial_init(fioc->fd,
1619 ssp->speed, ssp->parity,
1620 ssp->data_bits, ssp->stop_bits);
1622 break;
1623 case CHR_IOCTL_SERIAL_SET_BREAK:
1625 int enable = *(int *)arg;
1626 if (enable) {
1627 tcsendbreak(fioc->fd, 1);
1630 break;
1631 case CHR_IOCTL_SERIAL_GET_TIOCM:
1633 int sarg = 0;
1634 int *targ = (int *)arg;
1635 ioctl(fioc->fd, TIOCMGET, &sarg);
1636 *targ = 0;
1637 if (sarg & TIOCM_CTS)
1638 *targ |= CHR_TIOCM_CTS;
1639 if (sarg & TIOCM_CAR)
1640 *targ |= CHR_TIOCM_CAR;
1641 if (sarg & TIOCM_DSR)
1642 *targ |= CHR_TIOCM_DSR;
1643 if (sarg & TIOCM_RI)
1644 *targ |= CHR_TIOCM_RI;
1645 if (sarg & TIOCM_DTR)
1646 *targ |= CHR_TIOCM_DTR;
1647 if (sarg & TIOCM_RTS)
1648 *targ |= CHR_TIOCM_RTS;
1650 break;
1651 case CHR_IOCTL_SERIAL_SET_TIOCM:
1653 int sarg = *(int *)arg;
1654 int targ = 0;
1655 ioctl(fioc->fd, TIOCMGET, &targ);
1656 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1657 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1658 if (sarg & CHR_TIOCM_CTS)
1659 targ |= TIOCM_CTS;
1660 if (sarg & CHR_TIOCM_CAR)
1661 targ |= TIOCM_CAR;
1662 if (sarg & CHR_TIOCM_DSR)
1663 targ |= TIOCM_DSR;
1664 if (sarg & CHR_TIOCM_RI)
1665 targ |= TIOCM_RI;
1666 if (sarg & CHR_TIOCM_DTR)
1667 targ |= TIOCM_DTR;
1668 if (sarg & CHR_TIOCM_RTS)
1669 targ |= TIOCM_RTS;
1670 ioctl(fioc->fd, TIOCMSET, &targ);
1672 break;
1673 default:
1674 return -ENOTSUP;
1676 return 0;
1679 static void qemu_chr_close_tty(CharDriverState *chr)
1681 fd_chr_close(chr);
1684 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1685 ChardevCommon *backend,
1686 Error **errp)
1688 CharDriverState *chr;
1690 tty_serial_init(fd, 115200, 'N', 8, 1);
1691 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1692 if (!chr) {
1693 return NULL;
1695 chr->chr_ioctl = tty_serial_ioctl;
1696 chr->chr_close = qemu_chr_close_tty;
1697 return chr;
1699 #endif /* __linux__ || __sun__ */
1701 #if defined(__linux__)
1703 #define HAVE_CHARDEV_PARPORT 1
1705 typedef struct {
1706 int fd;
1707 int mode;
1708 } ParallelCharDriver;
1710 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1712 if (s->mode != mode) {
1713 int m = mode;
1714 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1715 return 0;
1716 s->mode = mode;
1718 return 1;
1721 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1723 ParallelCharDriver *drv = chr->opaque;
1724 int fd = drv->fd;
1725 uint8_t b;
1727 switch(cmd) {
1728 case CHR_IOCTL_PP_READ_DATA:
1729 if (ioctl(fd, PPRDATA, &b) < 0)
1730 return -ENOTSUP;
1731 *(uint8_t *)arg = b;
1732 break;
1733 case CHR_IOCTL_PP_WRITE_DATA:
1734 b = *(uint8_t *)arg;
1735 if (ioctl(fd, PPWDATA, &b) < 0)
1736 return -ENOTSUP;
1737 break;
1738 case CHR_IOCTL_PP_READ_CONTROL:
1739 if (ioctl(fd, PPRCONTROL, &b) < 0)
1740 return -ENOTSUP;
1741 /* Linux gives only the lowest bits, and no way to know data
1742 direction! For better compatibility set the fixed upper
1743 bits. */
1744 *(uint8_t *)arg = b | 0xc0;
1745 break;
1746 case CHR_IOCTL_PP_WRITE_CONTROL:
1747 b = *(uint8_t *)arg;
1748 if (ioctl(fd, PPWCONTROL, &b) < 0)
1749 return -ENOTSUP;
1750 break;
1751 case CHR_IOCTL_PP_READ_STATUS:
1752 if (ioctl(fd, PPRSTATUS, &b) < 0)
1753 return -ENOTSUP;
1754 *(uint8_t *)arg = b;
1755 break;
1756 case CHR_IOCTL_PP_DATA_DIR:
1757 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1758 return -ENOTSUP;
1759 break;
1760 case CHR_IOCTL_PP_EPP_READ_ADDR:
1761 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1762 struct ParallelIOArg *parg = arg;
1763 int n = read(fd, parg->buffer, parg->count);
1764 if (n != parg->count) {
1765 return -EIO;
1768 break;
1769 case CHR_IOCTL_PP_EPP_READ:
1770 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1771 struct ParallelIOArg *parg = arg;
1772 int n = read(fd, parg->buffer, parg->count);
1773 if (n != parg->count) {
1774 return -EIO;
1777 break;
1778 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1779 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1780 struct ParallelIOArg *parg = arg;
1781 int n = write(fd, parg->buffer, parg->count);
1782 if (n != parg->count) {
1783 return -EIO;
1786 break;
1787 case CHR_IOCTL_PP_EPP_WRITE:
1788 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1789 struct ParallelIOArg *parg = arg;
1790 int n = write(fd, parg->buffer, parg->count);
1791 if (n != parg->count) {
1792 return -EIO;
1795 break;
1796 default:
1797 return -ENOTSUP;
1799 return 0;
1802 static void pp_close(CharDriverState *chr)
1804 ParallelCharDriver *drv = chr->opaque;
1805 int fd = drv->fd;
1807 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1808 ioctl(fd, PPRELEASE);
1809 close(fd);
1810 g_free(drv);
1811 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1814 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1815 ChardevCommon *backend,
1816 Error **errp)
1818 CharDriverState *chr;
1819 ParallelCharDriver *drv;
1821 if (ioctl(fd, PPCLAIM) < 0) {
1822 error_setg_errno(errp, errno, "not a parallel port");
1823 close(fd);
1824 return NULL;
1827 chr = qemu_chr_alloc(backend, errp);
1828 if (!chr) {
1829 return NULL;
1832 drv = g_new0(ParallelCharDriver, 1);
1833 chr->opaque = drv;
1834 chr->chr_write = null_chr_write;
1835 chr->chr_ioctl = pp_ioctl;
1836 chr->chr_close = pp_close;
1838 drv->fd = fd;
1839 drv->mode = IEEE1284_MODE_COMPAT;
1841 return chr;
1843 #endif /* __linux__ */
1845 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1847 #define HAVE_CHARDEV_PARPORT 1
1849 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1851 int fd = (int)(intptr_t)chr->opaque;
1852 uint8_t b;
1854 switch(cmd) {
1855 case CHR_IOCTL_PP_READ_DATA:
1856 if (ioctl(fd, PPIGDATA, &b) < 0)
1857 return -ENOTSUP;
1858 *(uint8_t *)arg = b;
1859 break;
1860 case CHR_IOCTL_PP_WRITE_DATA:
1861 b = *(uint8_t *)arg;
1862 if (ioctl(fd, PPISDATA, &b) < 0)
1863 return -ENOTSUP;
1864 break;
1865 case CHR_IOCTL_PP_READ_CONTROL:
1866 if (ioctl(fd, PPIGCTRL, &b) < 0)
1867 return -ENOTSUP;
1868 *(uint8_t *)arg = b;
1869 break;
1870 case CHR_IOCTL_PP_WRITE_CONTROL:
1871 b = *(uint8_t *)arg;
1872 if (ioctl(fd, PPISCTRL, &b) < 0)
1873 return -ENOTSUP;
1874 break;
1875 case CHR_IOCTL_PP_READ_STATUS:
1876 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1877 return -ENOTSUP;
1878 *(uint8_t *)arg = b;
1879 break;
1880 default:
1881 return -ENOTSUP;
1883 return 0;
1886 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1887 ChardevCommon *backend,
1888 Error **errp)
1890 CharDriverState *chr;
1892 chr = qemu_chr_alloc(backend, errp);
1893 if (!chr) {
1894 return NULL;
1896 chr->opaque = (void *)(intptr_t)fd;
1897 chr->chr_write = null_chr_write;
1898 chr->chr_ioctl = pp_ioctl;
1899 chr->explicit_be_open = true;
1900 return chr;
1902 #endif
1904 #else /* _WIN32 */
1906 #define HAVE_CHARDEV_SERIAL 1
1908 typedef struct {
1909 int max_size;
1910 HANDLE hcom, hrecv, hsend;
1911 OVERLAPPED orecv;
1912 BOOL fpipe;
1913 DWORD len;
1915 /* Protected by the CharDriverState chr_write_lock. */
1916 OVERLAPPED osend;
1917 } WinCharState;
1919 typedef struct {
1920 HANDLE hStdIn;
1921 HANDLE hInputReadyEvent;
1922 HANDLE hInputDoneEvent;
1923 HANDLE hInputThread;
1924 uint8_t win_stdio_buf;
1925 } WinStdioCharState;
1927 #define NSENDBUF 2048
1928 #define NRECVBUF 2048
1929 #define MAXCONNECT 1
1930 #define NTIMEOUT 5000
1932 static int win_chr_poll(void *opaque);
1933 static int win_chr_pipe_poll(void *opaque);
1935 static void win_chr_close(CharDriverState *chr)
1937 WinCharState *s = chr->opaque;
1939 if (s->hsend) {
1940 CloseHandle(s->hsend);
1941 s->hsend = NULL;
1943 if (s->hrecv) {
1944 CloseHandle(s->hrecv);
1945 s->hrecv = NULL;
1947 if (s->hcom) {
1948 CloseHandle(s->hcom);
1949 s->hcom = NULL;
1951 if (s->fpipe)
1952 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1953 else
1954 qemu_del_polling_cb(win_chr_poll, chr);
1956 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1959 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1961 WinCharState *s = chr->opaque;
1962 COMMCONFIG comcfg;
1963 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1964 COMSTAT comstat;
1965 DWORD size;
1966 DWORD err;
1968 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1969 if (!s->hsend) {
1970 error_setg(errp, "Failed CreateEvent");
1971 goto fail;
1973 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1974 if (!s->hrecv) {
1975 error_setg(errp, "Failed CreateEvent");
1976 goto fail;
1979 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1980 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1981 if (s->hcom == INVALID_HANDLE_VALUE) {
1982 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1983 s->hcom = NULL;
1984 goto fail;
1987 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1988 error_setg(errp, "Failed SetupComm");
1989 goto fail;
1992 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1993 size = sizeof(COMMCONFIG);
1994 GetDefaultCommConfig(filename, &comcfg, &size);
1995 comcfg.dcb.DCBlength = sizeof(DCB);
1996 CommConfigDialog(filename, NULL, &comcfg);
1998 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1999 error_setg(errp, "Failed SetCommState");
2000 goto fail;
2003 if (!SetCommMask(s->hcom, EV_ERR)) {
2004 error_setg(errp, "Failed SetCommMask");
2005 goto fail;
2008 cto.ReadIntervalTimeout = MAXDWORD;
2009 if (!SetCommTimeouts(s->hcom, &cto)) {
2010 error_setg(errp, "Failed SetCommTimeouts");
2011 goto fail;
2014 if (!ClearCommError(s->hcom, &err, &comstat)) {
2015 error_setg(errp, "Failed ClearCommError");
2016 goto fail;
2018 qemu_add_polling_cb(win_chr_poll, chr);
2019 return 0;
2021 fail:
2022 win_chr_close(chr);
2023 return -1;
2026 /* Called with chr_write_lock held. */
2027 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2029 WinCharState *s = chr->opaque;
2030 DWORD len, ret, size, err;
2032 len = len1;
2033 ZeroMemory(&s->osend, sizeof(s->osend));
2034 s->osend.hEvent = s->hsend;
2035 while (len > 0) {
2036 if (s->hsend)
2037 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2038 else
2039 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2040 if (!ret) {
2041 err = GetLastError();
2042 if (err == ERROR_IO_PENDING) {
2043 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2044 if (ret) {
2045 buf += size;
2046 len -= size;
2047 } else {
2048 break;
2050 } else {
2051 break;
2053 } else {
2054 buf += size;
2055 len -= size;
2058 return len1 - len;
2061 static int win_chr_read_poll(CharDriverState *chr)
2063 WinCharState *s = chr->opaque;
2065 s->max_size = qemu_chr_be_can_write(chr);
2066 return s->max_size;
2069 static void win_chr_readfile(CharDriverState *chr)
2071 WinCharState *s = chr->opaque;
2072 int ret, err;
2073 uint8_t buf[READ_BUF_LEN];
2074 DWORD size;
2076 ZeroMemory(&s->orecv, sizeof(s->orecv));
2077 s->orecv.hEvent = s->hrecv;
2078 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2079 if (!ret) {
2080 err = GetLastError();
2081 if (err == ERROR_IO_PENDING) {
2082 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2086 if (size > 0) {
2087 qemu_chr_be_write(chr, buf, size);
2091 static void win_chr_read(CharDriverState *chr)
2093 WinCharState *s = chr->opaque;
2095 if (s->len > s->max_size)
2096 s->len = s->max_size;
2097 if (s->len == 0)
2098 return;
2100 win_chr_readfile(chr);
2103 static int win_chr_poll(void *opaque)
2105 CharDriverState *chr = opaque;
2106 WinCharState *s = chr->opaque;
2107 COMSTAT status;
2108 DWORD comerr;
2110 ClearCommError(s->hcom, &comerr, &status);
2111 if (status.cbInQue > 0) {
2112 s->len = status.cbInQue;
2113 win_chr_read_poll(chr);
2114 win_chr_read(chr);
2115 return 1;
2117 return 0;
2120 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2121 ChardevCommon *backend,
2122 Error **errp)
2124 CharDriverState *chr;
2125 WinCharState *s;
2127 chr = qemu_chr_alloc(backend, errp);
2128 if (!chr) {
2129 return NULL;
2131 s = g_new0(WinCharState, 1);
2132 chr->opaque = s;
2133 chr->chr_write = win_chr_write;
2134 chr->chr_close = win_chr_close;
2136 if (win_chr_init(chr, filename, errp) < 0) {
2137 g_free(s);
2138 qemu_chr_free_common(chr);
2139 return NULL;
2141 return chr;
2144 static int win_chr_pipe_poll(void *opaque)
2146 CharDriverState *chr = opaque;
2147 WinCharState *s = chr->opaque;
2148 DWORD size;
2150 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2151 if (size > 0) {
2152 s->len = size;
2153 win_chr_read_poll(chr);
2154 win_chr_read(chr);
2155 return 1;
2157 return 0;
2160 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2161 Error **errp)
2163 WinCharState *s = chr->opaque;
2164 OVERLAPPED ov;
2165 int ret;
2166 DWORD size;
2167 char *openname;
2169 s->fpipe = TRUE;
2171 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2172 if (!s->hsend) {
2173 error_setg(errp, "Failed CreateEvent");
2174 goto fail;
2176 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2177 if (!s->hrecv) {
2178 error_setg(errp, "Failed CreateEvent");
2179 goto fail;
2182 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2183 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2184 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2185 PIPE_WAIT,
2186 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2187 g_free(openname);
2188 if (s->hcom == INVALID_HANDLE_VALUE) {
2189 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2190 s->hcom = NULL;
2191 goto fail;
2194 ZeroMemory(&ov, sizeof(ov));
2195 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2196 ret = ConnectNamedPipe(s->hcom, &ov);
2197 if (ret) {
2198 error_setg(errp, "Failed ConnectNamedPipe");
2199 goto fail;
2202 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2203 if (!ret) {
2204 error_setg(errp, "Failed GetOverlappedResult");
2205 if (ov.hEvent) {
2206 CloseHandle(ov.hEvent);
2207 ov.hEvent = NULL;
2209 goto fail;
2212 if (ov.hEvent) {
2213 CloseHandle(ov.hEvent);
2214 ov.hEvent = NULL;
2216 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2217 return 0;
2219 fail:
2220 win_chr_close(chr);
2221 return -1;
2225 static CharDriverState *qemu_chr_open_pipe(const char *id,
2226 ChardevBackend *backend,
2227 ChardevReturn *ret,
2228 Error **errp)
2230 ChardevHostdev *opts = backend->u.pipe.data;
2231 const char *filename = opts->device;
2232 CharDriverState *chr;
2233 WinCharState *s;
2234 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2236 chr = qemu_chr_alloc(common, errp);
2237 if (!chr) {
2238 return NULL;
2240 s = g_new0(WinCharState, 1);
2241 chr->opaque = s;
2242 chr->chr_write = win_chr_write;
2243 chr->chr_close = win_chr_close;
2245 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2246 g_free(s);
2247 qemu_chr_free_common(chr);
2248 return NULL;
2250 return chr;
2253 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2254 ChardevCommon *backend,
2255 Error **errp)
2257 CharDriverState *chr;
2258 WinCharState *s;
2260 chr = qemu_chr_alloc(backend, errp);
2261 if (!chr) {
2262 return NULL;
2264 s = g_new0(WinCharState, 1);
2265 s->hcom = fd_out;
2266 chr->opaque = s;
2267 chr->chr_write = win_chr_write;
2268 return chr;
2271 static CharDriverState *qemu_chr_open_win_con(const char *id,
2272 ChardevBackend *backend,
2273 ChardevReturn *ret,
2274 Error **errp)
2276 ChardevCommon *common = backend->u.console.data;
2277 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2278 common, errp);
2281 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2283 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2284 DWORD dwSize;
2285 int len1;
2287 len1 = len;
2289 while (len1 > 0) {
2290 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2291 break;
2293 buf += dwSize;
2294 len1 -= dwSize;
2297 return len - len1;
2300 static void win_stdio_wait_func(void *opaque)
2302 CharDriverState *chr = opaque;
2303 WinStdioCharState *stdio = chr->opaque;
2304 INPUT_RECORD buf[4];
2305 int ret;
2306 DWORD dwSize;
2307 int i;
2309 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2311 if (!ret) {
2312 /* Avoid error storm */
2313 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2314 return;
2317 for (i = 0; i < dwSize; i++) {
2318 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2320 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2321 int j;
2322 if (kev->uChar.AsciiChar != 0) {
2323 for (j = 0; j < kev->wRepeatCount; j++) {
2324 if (qemu_chr_be_can_write(chr)) {
2325 uint8_t c = kev->uChar.AsciiChar;
2326 qemu_chr_be_write(chr, &c, 1);
2334 static DWORD WINAPI win_stdio_thread(LPVOID param)
2336 CharDriverState *chr = param;
2337 WinStdioCharState *stdio = chr->opaque;
2338 int ret;
2339 DWORD dwSize;
2341 while (1) {
2343 /* Wait for one byte */
2344 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2346 /* Exit in case of error, continue if nothing read */
2347 if (!ret) {
2348 break;
2350 if (!dwSize) {
2351 continue;
2354 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2355 if (stdio->win_stdio_buf == '\r') {
2356 continue;
2359 /* Signal the main thread and wait until the byte was eaten */
2360 if (!SetEvent(stdio->hInputReadyEvent)) {
2361 break;
2363 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2364 != WAIT_OBJECT_0) {
2365 break;
2369 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2370 return 0;
2373 static void win_stdio_thread_wait_func(void *opaque)
2375 CharDriverState *chr = opaque;
2376 WinStdioCharState *stdio = chr->opaque;
2378 if (qemu_chr_be_can_write(chr)) {
2379 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2382 SetEvent(stdio->hInputDoneEvent);
2385 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2387 WinStdioCharState *stdio = chr->opaque;
2388 DWORD dwMode = 0;
2390 GetConsoleMode(stdio->hStdIn, &dwMode);
2392 if (echo) {
2393 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2394 } else {
2395 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2399 static void win_stdio_close(CharDriverState *chr)
2401 WinStdioCharState *stdio = chr->opaque;
2403 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2404 CloseHandle(stdio->hInputReadyEvent);
2406 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2407 CloseHandle(stdio->hInputDoneEvent);
2409 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2410 TerminateThread(stdio->hInputThread, 0);
2413 g_free(chr->opaque);
2414 g_free(chr);
2417 static CharDriverState *qemu_chr_open_stdio(const char *id,
2418 ChardevBackend *backend,
2419 ChardevReturn *ret,
2420 Error **errp)
2422 CharDriverState *chr;
2423 WinStdioCharState *stdio;
2424 DWORD dwMode;
2425 int is_console = 0;
2426 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio.data);
2428 chr = qemu_chr_alloc(common, errp);
2429 if (!chr) {
2430 return NULL;
2432 stdio = g_new0(WinStdioCharState, 1);
2434 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2435 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2436 error_setg(errp, "cannot open stdio: invalid handle");
2437 return NULL;
2440 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2442 chr->opaque = stdio;
2443 chr->chr_write = win_stdio_write;
2444 chr->chr_close = win_stdio_close;
2446 if (is_console) {
2447 if (qemu_add_wait_object(stdio->hStdIn,
2448 win_stdio_wait_func, chr)) {
2449 error_setg(errp, "qemu_add_wait_object: failed");
2450 goto err1;
2452 } else {
2453 DWORD dwId;
2455 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2456 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2457 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2458 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2459 error_setg(errp, "cannot create event");
2460 goto err2;
2462 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2463 win_stdio_thread_wait_func, chr)) {
2464 error_setg(errp, "qemu_add_wait_object: failed");
2465 goto err2;
2467 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2468 chr, 0, &dwId);
2470 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2471 error_setg(errp, "cannot create stdio thread");
2472 goto err3;
2476 dwMode |= ENABLE_LINE_INPUT;
2478 if (is_console) {
2479 /* set the terminal in raw mode */
2480 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2481 dwMode |= ENABLE_PROCESSED_INPUT;
2484 SetConsoleMode(stdio->hStdIn, dwMode);
2486 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2487 qemu_chr_fe_set_echo(chr, false);
2489 return chr;
2491 err3:
2492 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2493 err2:
2494 CloseHandle(stdio->hInputReadyEvent);
2495 CloseHandle(stdio->hInputDoneEvent);
2496 err1:
2497 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2498 return NULL;
2500 #endif /* !_WIN32 */
2503 /***********************************************************/
2504 /* UDP Net console */
2506 typedef struct {
2507 QIOChannel *ioc;
2508 uint8_t buf[READ_BUF_LEN];
2509 int bufcnt;
2510 int bufptr;
2511 int max_size;
2512 } NetCharDriver;
2514 /* Called with chr_write_lock held. */
2515 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2517 NetCharDriver *s = chr->opaque;
2519 return qio_channel_write(
2520 s->ioc, (const char *)buf, len, NULL);
2523 static int udp_chr_read_poll(void *opaque)
2525 CharDriverState *chr = opaque;
2526 NetCharDriver *s = chr->opaque;
2528 s->max_size = qemu_chr_be_can_write(chr);
2530 /* If there were any stray characters in the queue process them
2531 * first
2533 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2534 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2535 s->bufptr++;
2536 s->max_size = qemu_chr_be_can_write(chr);
2538 return s->max_size;
2541 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2543 CharDriverState *chr = opaque;
2544 NetCharDriver *s = chr->opaque;
2545 ssize_t ret;
2547 if (s->max_size == 0) {
2548 return TRUE;
2550 ret = qio_channel_read(
2551 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2552 if (ret <= 0) {
2553 remove_fd_in_watch(chr);
2554 return FALSE;
2556 s->bufcnt = ret;
2558 s->bufptr = 0;
2559 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2560 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2561 s->bufptr++;
2562 s->max_size = qemu_chr_be_can_write(chr);
2565 return TRUE;
2568 static void udp_chr_update_read_handler(CharDriverState *chr)
2570 NetCharDriver *s = chr->opaque;
2572 remove_fd_in_watch(chr);
2573 if (s->ioc) {
2574 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2575 udp_chr_read_poll,
2576 udp_chr_read, chr);
2580 static void udp_chr_close(CharDriverState *chr)
2582 NetCharDriver *s = chr->opaque;
2584 remove_fd_in_watch(chr);
2585 if (s->ioc) {
2586 object_unref(OBJECT(s->ioc));
2588 g_free(s);
2589 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2592 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2593 ChardevCommon *backend,
2594 Error **errp)
2596 CharDriverState *chr = NULL;
2597 NetCharDriver *s = NULL;
2599 chr = qemu_chr_alloc(backend, errp);
2600 if (!chr) {
2601 return NULL;
2603 s = g_new0(NetCharDriver, 1);
2605 s->ioc = QIO_CHANNEL(sioc);
2606 s->bufcnt = 0;
2607 s->bufptr = 0;
2608 chr->opaque = s;
2609 chr->chr_write = udp_chr_write;
2610 chr->chr_update_read_handler = udp_chr_update_read_handler;
2611 chr->chr_close = udp_chr_close;
2612 /* be isn't opened until we get a connection */
2613 chr->explicit_be_open = true;
2614 return chr;
2617 /***********************************************************/
2618 /* TCP Net console */
2620 typedef struct {
2621 QIOChannel *ioc; /* Client I/O channel */
2622 QIOChannelSocket *sioc; /* Client master channel */
2623 QIOChannelSocket *listen_ioc;
2624 guint listen_tag;
2625 QCryptoTLSCreds *tls_creds;
2626 int connected;
2627 int max_size;
2628 int do_telnetopt;
2629 int do_nodelay;
2630 int is_unix;
2631 int *read_msgfds;
2632 size_t read_msgfds_num;
2633 int *write_msgfds;
2634 size_t write_msgfds_num;
2636 SocketAddress *addr;
2637 bool is_listen;
2638 bool is_telnet;
2640 guint reconnect_timer;
2641 int64_t reconnect_time;
2642 bool connect_err_reported;
2643 } TCPCharDriver;
2645 static gboolean socket_reconnect_timeout(gpointer opaque);
2647 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2649 TCPCharDriver *s = chr->opaque;
2650 assert(s->connected == 0);
2651 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2652 socket_reconnect_timeout, chr);
2655 static void check_report_connect_error(CharDriverState *chr,
2656 Error *err)
2658 TCPCharDriver *s = chr->opaque;
2660 if (!s->connect_err_reported) {
2661 error_report("Unable to connect character device %s: %s",
2662 chr->label, error_get_pretty(err));
2663 s->connect_err_reported = true;
2665 qemu_chr_socket_restart_timer(chr);
2668 static gboolean tcp_chr_accept(QIOChannel *chan,
2669 GIOCondition cond,
2670 void *opaque);
2672 /* Called with chr_write_lock held. */
2673 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2675 TCPCharDriver *s = chr->opaque;
2676 if (s->connected) {
2677 int ret = io_channel_send_full(s->ioc, buf, len,
2678 s->write_msgfds,
2679 s->write_msgfds_num);
2681 /* free the written msgfds, no matter what */
2682 if (s->write_msgfds_num) {
2683 g_free(s->write_msgfds);
2684 s->write_msgfds = 0;
2685 s->write_msgfds_num = 0;
2688 return ret;
2689 } else {
2690 /* XXX: indicate an error ? */
2691 return len;
2695 static int tcp_chr_read_poll(void *opaque)
2697 CharDriverState *chr = opaque;
2698 TCPCharDriver *s = chr->opaque;
2699 if (!s->connected)
2700 return 0;
2701 s->max_size = qemu_chr_be_can_write(chr);
2702 return s->max_size;
2705 #define IAC 255
2706 #define IAC_BREAK 243
2707 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2708 TCPCharDriver *s,
2709 uint8_t *buf, int *size)
2711 /* Handle any telnet client's basic IAC options to satisfy char by
2712 * char mode with no echo. All IAC options will be removed from
2713 * the buf and the do_telnetopt variable will be used to track the
2714 * state of the width of the IAC information.
2716 * IAC commands come in sets of 3 bytes with the exception of the
2717 * "IAC BREAK" command and the double IAC.
2720 int i;
2721 int j = 0;
2723 for (i = 0; i < *size; i++) {
2724 if (s->do_telnetopt > 1) {
2725 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2726 /* Double IAC means send an IAC */
2727 if (j != i)
2728 buf[j] = buf[i];
2729 j++;
2730 s->do_telnetopt = 1;
2731 } else {
2732 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2733 /* Handle IAC break commands by sending a serial break */
2734 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2735 s->do_telnetopt++;
2737 s->do_telnetopt++;
2739 if (s->do_telnetopt >= 4) {
2740 s->do_telnetopt = 1;
2742 } else {
2743 if ((unsigned char)buf[i] == IAC) {
2744 s->do_telnetopt = 2;
2745 } else {
2746 if (j != i)
2747 buf[j] = buf[i];
2748 j++;
2752 *size = j;
2755 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2757 TCPCharDriver *s = chr->opaque;
2758 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2760 assert(num <= TCP_MAX_FDS);
2762 if (to_copy) {
2763 int i;
2765 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2767 /* Close unused fds */
2768 for (i = to_copy; i < s->read_msgfds_num; i++) {
2769 close(s->read_msgfds[i]);
2772 g_free(s->read_msgfds);
2773 s->read_msgfds = 0;
2774 s->read_msgfds_num = 0;
2777 return to_copy;
2780 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2782 TCPCharDriver *s = chr->opaque;
2784 /* clear old pending fd array */
2785 g_free(s->write_msgfds);
2786 s->write_msgfds = NULL;
2787 s->write_msgfds_num = 0;
2789 if (!s->connected ||
2790 !qio_channel_has_feature(s->ioc,
2791 QIO_CHANNEL_FEATURE_FD_PASS)) {
2792 return -1;
2795 if (num) {
2796 s->write_msgfds = g_new(int, num);
2797 memcpy(s->write_msgfds, fds, num * sizeof(int));
2800 s->write_msgfds_num = num;
2802 return 0;
2805 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2807 TCPCharDriver *s = chr->opaque;
2808 struct iovec iov = { .iov_base = buf, .iov_len = len };
2809 int ret;
2810 size_t i;
2811 int *msgfds = NULL;
2812 size_t msgfds_num = 0;
2814 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2815 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2816 &msgfds, &msgfds_num,
2817 NULL);
2818 } else {
2819 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2820 NULL, NULL,
2821 NULL);
2824 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2825 errno = EAGAIN;
2826 ret = -1;
2827 } else if (ret == -1) {
2828 errno = EIO;
2831 if (msgfds_num) {
2832 /* close and clean read_msgfds */
2833 for (i = 0; i < s->read_msgfds_num; i++) {
2834 close(s->read_msgfds[i]);
2837 if (s->read_msgfds_num) {
2838 g_free(s->read_msgfds);
2841 s->read_msgfds = msgfds;
2842 s->read_msgfds_num = msgfds_num;
2845 for (i = 0; i < s->read_msgfds_num; i++) {
2846 int fd = s->read_msgfds[i];
2847 if (fd < 0) {
2848 continue;
2851 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2852 qemu_set_block(fd);
2854 #ifndef MSG_CMSG_CLOEXEC
2855 qemu_set_cloexec(fd);
2856 #endif
2859 return ret;
2862 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2864 TCPCharDriver *s = chr->opaque;
2865 return qio_channel_create_watch(s->ioc, cond);
2868 static void tcp_chr_free_connection(CharDriverState *chr)
2870 TCPCharDriver *s = chr->opaque;
2871 int i;
2873 if (!s->connected) {
2874 return;
2877 if (s->read_msgfds_num) {
2878 for (i = 0; i < s->read_msgfds_num; i++) {
2879 close(s->read_msgfds[i]);
2881 g_free(s->read_msgfds);
2882 s->read_msgfds = NULL;
2883 s->read_msgfds_num = 0;
2886 tcp_set_msgfds(chr, NULL, 0);
2887 remove_fd_in_watch(chr);
2888 object_unref(OBJECT(s->sioc));
2889 s->sioc = NULL;
2890 object_unref(OBJECT(s->ioc));
2891 s->ioc = NULL;
2892 g_free(chr->filename);
2893 chr->filename = NULL;
2894 s->connected = 0;
2897 static void tcp_chr_disconnect(CharDriverState *chr)
2899 TCPCharDriver *s = chr->opaque;
2901 if (!s->connected) {
2902 return;
2905 tcp_chr_free_connection(chr);
2907 if (s->listen_ioc) {
2908 s->listen_tag = qio_channel_add_watch(
2909 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
2911 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
2912 s->is_listen, s->is_telnet);
2913 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2914 if (s->reconnect_time) {
2915 qemu_chr_socket_restart_timer(chr);
2919 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2921 CharDriverState *chr = opaque;
2922 TCPCharDriver *s = chr->opaque;
2923 uint8_t buf[READ_BUF_LEN];
2924 int len, size;
2926 if (!s->connected || s->max_size <= 0) {
2927 return TRUE;
2929 len = sizeof(buf);
2930 if (len > s->max_size)
2931 len = s->max_size;
2932 size = tcp_chr_recv(chr, (void *)buf, len);
2933 if (size == 0 || size == -1) {
2934 /* connection closed */
2935 tcp_chr_disconnect(chr);
2936 } else if (size > 0) {
2937 if (s->do_telnetopt)
2938 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2939 if (size > 0)
2940 qemu_chr_be_write(chr, buf, size);
2943 return TRUE;
2946 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2948 TCPCharDriver *s = chr->opaque;
2949 int size;
2951 if (!s->connected) {
2952 return 0;
2955 size = tcp_chr_recv(chr, (void *) buf, len);
2956 if (size == 0) {
2957 /* connection closed */
2958 tcp_chr_disconnect(chr);
2961 return size;
2964 static void tcp_chr_connect(void *opaque)
2966 CharDriverState *chr = opaque;
2967 TCPCharDriver *s = chr->opaque;
2969 g_free(chr->filename);
2970 chr->filename = sockaddr_to_str(
2971 &s->sioc->localAddr, s->sioc->localAddrLen,
2972 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
2973 s->is_listen, s->is_telnet);
2975 s->connected = 1;
2976 if (s->ioc) {
2977 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2978 tcp_chr_read_poll,
2979 tcp_chr_read, chr);
2981 qemu_chr_be_generic_open(chr);
2984 static void tcp_chr_update_read_handler(CharDriverState *chr)
2986 TCPCharDriver *s = chr->opaque;
2988 if (!s->connected) {
2989 return;
2992 remove_fd_in_watch(chr);
2993 if (s->ioc) {
2994 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2995 tcp_chr_read_poll,
2996 tcp_chr_read, chr);
3000 typedef struct {
3001 CharDriverState *chr;
3002 char buf[12];
3003 size_t buflen;
3004 } TCPCharDriverTelnetInit;
3006 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
3007 GIOCondition cond G_GNUC_UNUSED,
3008 gpointer user_data)
3010 TCPCharDriverTelnetInit *init = user_data;
3011 ssize_t ret;
3013 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
3014 if (ret < 0) {
3015 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3016 ret = 0;
3017 } else {
3018 tcp_chr_disconnect(init->chr);
3019 return FALSE;
3022 init->buflen -= ret;
3024 if (init->buflen == 0) {
3025 tcp_chr_connect(init->chr);
3026 return FALSE;
3029 memmove(init->buf, init->buf + ret, init->buflen);
3031 return TRUE;
3034 static void tcp_chr_telnet_init(CharDriverState *chr)
3036 TCPCharDriver *s = chr->opaque;
3037 TCPCharDriverTelnetInit *init =
3038 g_new0(TCPCharDriverTelnetInit, 1);
3039 size_t n = 0;
3041 init->chr = chr;
3042 init->buflen = 12;
3044 #define IACSET(x, a, b, c) \
3045 do { \
3046 x[n++] = a; \
3047 x[n++] = b; \
3048 x[n++] = c; \
3049 } while (0)
3051 /* Prep the telnet negotion to put telnet in binary,
3052 * no echo, single char mode */
3053 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3054 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3055 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3056 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3058 #undef IACSET
3060 qio_channel_add_watch(
3061 s->ioc, G_IO_OUT,
3062 tcp_chr_telnet_init_io,
3063 init, NULL);
3067 static void tcp_chr_tls_handshake(Object *source,
3068 Error *err,
3069 gpointer user_data)
3071 CharDriverState *chr = user_data;
3072 TCPCharDriver *s = chr->opaque;
3074 if (err) {
3075 tcp_chr_disconnect(chr);
3076 } else {
3077 if (s->do_telnetopt) {
3078 tcp_chr_telnet_init(chr);
3079 } else {
3080 tcp_chr_connect(chr);
3086 static void tcp_chr_tls_init(CharDriverState *chr)
3088 TCPCharDriver *s = chr->opaque;
3089 QIOChannelTLS *tioc;
3090 Error *err = NULL;
3092 if (s->is_listen) {
3093 tioc = qio_channel_tls_new_server(
3094 s->ioc, s->tls_creds,
3095 NULL, /* XXX Use an ACL */
3096 &err);
3097 } else {
3098 tioc = qio_channel_tls_new_client(
3099 s->ioc, s->tls_creds,
3100 s->addr->u.inet.data->host,
3101 &err);
3103 if (tioc == NULL) {
3104 error_free(err);
3105 tcp_chr_disconnect(chr);
3107 object_unref(OBJECT(s->ioc));
3108 s->ioc = QIO_CHANNEL(tioc);
3110 qio_channel_tls_handshake(tioc,
3111 tcp_chr_tls_handshake,
3112 chr,
3113 NULL);
3117 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3119 TCPCharDriver *s = chr->opaque;
3120 if (s->ioc != NULL) {
3121 return -1;
3124 s->ioc = QIO_CHANNEL(sioc);
3125 object_ref(OBJECT(sioc));
3126 s->sioc = sioc;
3127 object_ref(OBJECT(sioc));
3129 qio_channel_set_blocking(s->ioc, false, NULL);
3131 if (s->do_nodelay) {
3132 qio_channel_set_delay(s->ioc, false);
3134 if (s->listen_tag) {
3135 g_source_remove(s->listen_tag);
3136 s->listen_tag = 0;
3139 if (s->tls_creds) {
3140 tcp_chr_tls_init(chr);
3141 } else {
3142 if (s->do_telnetopt) {
3143 tcp_chr_telnet_init(chr);
3144 } else {
3145 tcp_chr_connect(chr);
3149 return 0;
3153 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3155 int ret;
3156 QIOChannelSocket *sioc;
3158 sioc = qio_channel_socket_new_fd(fd, NULL);
3159 if (!sioc) {
3160 return -1;
3162 ret = tcp_chr_new_client(chr, sioc);
3163 object_unref(OBJECT(sioc));
3164 return ret;
3167 static gboolean tcp_chr_accept(QIOChannel *channel,
3168 GIOCondition cond,
3169 void *opaque)
3171 CharDriverState *chr = opaque;
3172 QIOChannelSocket *sioc;
3174 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3175 NULL);
3176 if (!sioc) {
3177 return TRUE;
3180 tcp_chr_new_client(chr, sioc);
3182 object_unref(OBJECT(sioc));
3184 return TRUE;
3187 static int tcp_chr_wait_connected(CharDriverState *chr, Error **errp)
3189 TCPCharDriver *s = chr->opaque;
3190 QIOChannelSocket *sioc;
3192 /* It can't wait on s->connected, since it is set asynchronously
3193 * in TLS and telnet cases, only wait for an accepted socket */
3194 while (!s->ioc) {
3195 if (s->is_listen) {
3196 fprintf(stderr, "QEMU waiting for connection on: %s\n",
3197 chr->filename);
3198 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), true, NULL);
3199 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
3200 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
3201 } else {
3202 sioc = qio_channel_socket_new();
3203 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3204 object_unref(OBJECT(sioc));
3205 return -1;
3207 tcp_chr_new_client(chr, sioc);
3208 object_unref(OBJECT(sioc));
3212 return 0;
3215 int qemu_chr_wait_connected(CharDriverState *chr, Error **errp)
3217 if (chr->chr_wait_connected) {
3218 return chr->chr_wait_connected(chr, errp);
3221 return 0;
3224 static void tcp_chr_close(CharDriverState *chr)
3226 TCPCharDriver *s = chr->opaque;
3228 tcp_chr_free_connection(chr);
3230 if (s->reconnect_timer) {
3231 g_source_remove(s->reconnect_timer);
3232 s->reconnect_timer = 0;
3234 qapi_free_SocketAddress(s->addr);
3235 if (s->listen_tag) {
3236 g_source_remove(s->listen_tag);
3237 s->listen_tag = 0;
3239 if (s->listen_ioc) {
3240 object_unref(OBJECT(s->listen_ioc));
3242 if (s->tls_creds) {
3243 object_unref(OBJECT(s->tls_creds));
3245 g_free(s);
3246 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3250 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3252 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3253 CharDriverState *chr = opaque;
3254 TCPCharDriver *s = chr->opaque;
3256 if (err) {
3257 check_report_connect_error(chr, err);
3258 object_unref(src);
3259 return;
3262 s->connect_err_reported = false;
3263 tcp_chr_new_client(chr, sioc);
3264 object_unref(OBJECT(sioc));
3268 /*********************************************************/
3269 /* Ring buffer chardev */
3271 typedef struct {
3272 size_t size;
3273 size_t prod;
3274 size_t cons;
3275 uint8_t *cbuf;
3276 } RingBufCharDriver;
3278 static size_t ringbuf_count(const CharDriverState *chr)
3280 const RingBufCharDriver *d = chr->opaque;
3282 return d->prod - d->cons;
3285 /* Called with chr_write_lock held. */
3286 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3288 RingBufCharDriver *d = chr->opaque;
3289 int i;
3291 if (!buf || (len < 0)) {
3292 return -1;
3295 for (i = 0; i < len; i++ ) {
3296 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3297 if (d->prod - d->cons > d->size) {
3298 d->cons = d->prod - d->size;
3302 return 0;
3305 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3307 RingBufCharDriver *d = chr->opaque;
3308 int i;
3310 qemu_mutex_lock(&chr->chr_write_lock);
3311 for (i = 0; i < len && d->cons != d->prod; i++) {
3312 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3314 qemu_mutex_unlock(&chr->chr_write_lock);
3316 return i;
3319 static void ringbuf_chr_close(struct CharDriverState *chr)
3321 RingBufCharDriver *d = chr->opaque;
3323 g_free(d->cbuf);
3324 g_free(d);
3325 chr->opaque = NULL;
3328 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3329 ChardevBackend *backend,
3330 ChardevReturn *ret,
3331 Error **errp)
3333 ChardevRingbuf *opts = backend->u.ringbuf.data;
3334 ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
3335 CharDriverState *chr;
3336 RingBufCharDriver *d;
3338 chr = qemu_chr_alloc(common, errp);
3339 if (!chr) {
3340 return NULL;
3342 d = g_malloc(sizeof(*d));
3344 d->size = opts->has_size ? opts->size : 65536;
3346 /* The size must be power of 2 */
3347 if (d->size & (d->size - 1)) {
3348 error_setg(errp, "size of ringbuf chardev must be power of two");
3349 goto fail;
3352 d->prod = 0;
3353 d->cons = 0;
3354 d->cbuf = g_malloc0(d->size);
3356 chr->opaque = d;
3357 chr->chr_write = ringbuf_chr_write;
3358 chr->chr_close = ringbuf_chr_close;
3360 return chr;
3362 fail:
3363 g_free(d);
3364 qemu_chr_free_common(chr);
3365 return NULL;
3368 bool chr_is_ringbuf(const CharDriverState *chr)
3370 return chr->chr_write == ringbuf_chr_write;
3373 void qmp_ringbuf_write(const char *device, const char *data,
3374 bool has_format, enum DataFormat format,
3375 Error **errp)
3377 CharDriverState *chr;
3378 const uint8_t *write_data;
3379 int ret;
3380 gsize write_count;
3382 chr = qemu_chr_find(device);
3383 if (!chr) {
3384 error_setg(errp, "Device '%s' not found", device);
3385 return;
3388 if (!chr_is_ringbuf(chr)) {
3389 error_setg(errp,"%s is not a ringbuf device", device);
3390 return;
3393 if (has_format && (format == DATA_FORMAT_BASE64)) {
3394 write_data = qbase64_decode(data, -1,
3395 &write_count,
3396 errp);
3397 if (!write_data) {
3398 return;
3400 } else {
3401 write_data = (uint8_t *)data;
3402 write_count = strlen(data);
3405 ret = ringbuf_chr_write(chr, write_data, write_count);
3407 if (write_data != (uint8_t *)data) {
3408 g_free((void *)write_data);
3411 if (ret < 0) {
3412 error_setg(errp, "Failed to write to device %s", device);
3413 return;
3417 char *qmp_ringbuf_read(const char *device, int64_t size,
3418 bool has_format, enum DataFormat format,
3419 Error **errp)
3421 CharDriverState *chr;
3422 uint8_t *read_data;
3423 size_t count;
3424 char *data;
3426 chr = qemu_chr_find(device);
3427 if (!chr) {
3428 error_setg(errp, "Device '%s' not found", device);
3429 return NULL;
3432 if (!chr_is_ringbuf(chr)) {
3433 error_setg(errp,"%s is not a ringbuf device", device);
3434 return NULL;
3437 if (size <= 0) {
3438 error_setg(errp, "size must be greater than zero");
3439 return NULL;
3442 count = ringbuf_count(chr);
3443 size = size > count ? count : size;
3444 read_data = g_malloc(size + 1);
3446 ringbuf_chr_read(chr, read_data, size);
3448 if (has_format && (format == DATA_FORMAT_BASE64)) {
3449 data = g_base64_encode(read_data, size);
3450 g_free(read_data);
3451 } else {
3453 * FIXME should read only complete, valid UTF-8 characters up
3454 * to @size bytes. Invalid sequences should be replaced by a
3455 * suitable replacement character. Except when (and only
3456 * when) ring buffer lost characters since last read, initial
3457 * continuation characters should be dropped.
3459 read_data[size] = 0;
3460 data = (char *)read_data;
3463 return data;
3466 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3468 char host[65], port[33], width[8], height[8];
3469 int pos;
3470 const char *p;
3471 QemuOpts *opts;
3472 Error *local_err = NULL;
3474 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3475 if (local_err) {
3476 error_report_err(local_err);
3477 return NULL;
3480 if (strstart(filename, "mon:", &p)) {
3481 filename = p;
3482 qemu_opt_set(opts, "mux", "on", &error_abort);
3483 if (strcmp(filename, "stdio") == 0) {
3484 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3485 * but pass it to the guest. Handle this only for compat syntax,
3486 * for -chardev syntax we have special option for this.
3487 * This is what -nographic did, redirecting+muxing serial+monitor
3488 * to stdio causing Ctrl+C to be passed to guest. */
3489 qemu_opt_set(opts, "signal", "off", &error_abort);
3493 if (strcmp(filename, "null") == 0 ||
3494 strcmp(filename, "pty") == 0 ||
3495 strcmp(filename, "msmouse") == 0 ||
3496 strcmp(filename, "braille") == 0 ||
3497 strcmp(filename, "testdev") == 0 ||
3498 strcmp(filename, "stdio") == 0) {
3499 qemu_opt_set(opts, "backend", filename, &error_abort);
3500 return opts;
3502 if (strstart(filename, "vc", &p)) {
3503 qemu_opt_set(opts, "backend", "vc", &error_abort);
3504 if (*p == ':') {
3505 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3506 /* pixels */
3507 qemu_opt_set(opts, "width", width, &error_abort);
3508 qemu_opt_set(opts, "height", height, &error_abort);
3509 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3510 /* chars */
3511 qemu_opt_set(opts, "cols", width, &error_abort);
3512 qemu_opt_set(opts, "rows", height, &error_abort);
3513 } else {
3514 goto fail;
3517 return opts;
3519 if (strcmp(filename, "con:") == 0) {
3520 qemu_opt_set(opts, "backend", "console", &error_abort);
3521 return opts;
3523 if (strstart(filename, "COM", NULL)) {
3524 qemu_opt_set(opts, "backend", "serial", &error_abort);
3525 qemu_opt_set(opts, "path", filename, &error_abort);
3526 return opts;
3528 if (strstart(filename, "file:", &p)) {
3529 qemu_opt_set(opts, "backend", "file", &error_abort);
3530 qemu_opt_set(opts, "path", p, &error_abort);
3531 return opts;
3533 if (strstart(filename, "pipe:", &p)) {
3534 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3535 qemu_opt_set(opts, "path", p, &error_abort);
3536 return opts;
3538 if (strstart(filename, "tcp:", &p) ||
3539 strstart(filename, "telnet:", &p)) {
3540 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3541 host[0] = 0;
3542 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3543 goto fail;
3545 qemu_opt_set(opts, "backend", "socket", &error_abort);
3546 qemu_opt_set(opts, "host", host, &error_abort);
3547 qemu_opt_set(opts, "port", port, &error_abort);
3548 if (p[pos] == ',') {
3549 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3550 if (local_err) {
3551 error_report_err(local_err);
3552 goto fail;
3555 if (strstart(filename, "telnet:", &p))
3556 qemu_opt_set(opts, "telnet", "on", &error_abort);
3557 return opts;
3559 if (strstart(filename, "udp:", &p)) {
3560 qemu_opt_set(opts, "backend", "udp", &error_abort);
3561 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3562 host[0] = 0;
3563 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3564 goto fail;
3567 qemu_opt_set(opts, "host", host, &error_abort);
3568 qemu_opt_set(opts, "port", port, &error_abort);
3569 if (p[pos] == '@') {
3570 p += pos + 1;
3571 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3572 host[0] = 0;
3573 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3574 goto fail;
3577 qemu_opt_set(opts, "localaddr", host, &error_abort);
3578 qemu_opt_set(opts, "localport", port, &error_abort);
3580 return opts;
3582 if (strstart(filename, "unix:", &p)) {
3583 qemu_opt_set(opts, "backend", "socket", &error_abort);
3584 qemu_opts_do_parse(opts, p, "path", &local_err);
3585 if (local_err) {
3586 error_report_err(local_err);
3587 goto fail;
3589 return opts;
3591 if (strstart(filename, "/dev/parport", NULL) ||
3592 strstart(filename, "/dev/ppi", NULL)) {
3593 qemu_opt_set(opts, "backend", "parport", &error_abort);
3594 qemu_opt_set(opts, "path", filename, &error_abort);
3595 return opts;
3597 if (strstart(filename, "/dev/", NULL)) {
3598 qemu_opt_set(opts, "backend", "tty", &error_abort);
3599 qemu_opt_set(opts, "path", filename, &error_abort);
3600 return opts;
3603 fail:
3604 qemu_opts_del(opts);
3605 return NULL;
3608 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3610 const char *logfile = qemu_opt_get(opts, "logfile");
3612 backend->has_logfile = logfile != NULL;
3613 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3615 backend->has_logappend = true;
3616 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3620 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3621 Error **errp)
3623 const char *path = qemu_opt_get(opts, "path");
3624 ChardevFile *file;
3626 if (path == NULL) {
3627 error_setg(errp, "chardev: file: no filename given");
3628 return;
3630 file = backend->u.file.data = g_new0(ChardevFile, 1);
3631 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3632 file->out = g_strdup(path);
3634 file->has_append = true;
3635 file->append = qemu_opt_get_bool(opts, "append", false);
3638 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3639 Error **errp)
3641 ChardevStdio *stdio;
3643 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3644 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3645 stdio->has_signal = true;
3646 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3649 #ifdef HAVE_CHARDEV_SERIAL
3650 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3651 Error **errp)
3653 const char *device = qemu_opt_get(opts, "path");
3654 ChardevHostdev *serial;
3656 if (device == NULL) {
3657 error_setg(errp, "chardev: serial/tty: no device path given");
3658 return;
3660 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3661 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3662 serial->device = g_strdup(device);
3664 #endif
3666 #ifdef HAVE_CHARDEV_PARPORT
3667 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3668 Error **errp)
3670 const char *device = qemu_opt_get(opts, "path");
3671 ChardevHostdev *parallel;
3673 if (device == NULL) {
3674 error_setg(errp, "chardev: parallel: no device path given");
3675 return;
3677 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3678 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3679 parallel->device = g_strdup(device);
3681 #endif
3683 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3684 Error **errp)
3686 const char *device = qemu_opt_get(opts, "path");
3687 ChardevHostdev *dev;
3689 if (device == NULL) {
3690 error_setg(errp, "chardev: pipe: no device path given");
3691 return;
3693 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3694 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3695 dev->device = g_strdup(device);
3698 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3699 Error **errp)
3701 int val;
3702 ChardevRingbuf *ringbuf;
3704 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3705 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3707 val = qemu_opt_get_size(opts, "size", 0);
3708 if (val != 0) {
3709 ringbuf->has_size = true;
3710 ringbuf->size = val;
3714 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3715 Error **errp)
3717 const char *chardev = qemu_opt_get(opts, "chardev");
3718 ChardevMux *mux;
3720 if (chardev == NULL) {
3721 error_setg(errp, "chardev: mux: no chardev given");
3722 return;
3724 mux = backend->u.mux.data = g_new0(ChardevMux, 1);
3725 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
3726 mux->chardev = g_strdup(chardev);
3729 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3730 Error **errp)
3732 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3733 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3734 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3735 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3736 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3737 const char *path = qemu_opt_get(opts, "path");
3738 const char *host = qemu_opt_get(opts, "host");
3739 const char *port = qemu_opt_get(opts, "port");
3740 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3741 SocketAddress *addr;
3742 ChardevSocket *sock;
3744 if (!path) {
3745 if (!host) {
3746 error_setg(errp, "chardev: socket: no host given");
3747 return;
3749 if (!port) {
3750 error_setg(errp, "chardev: socket: no port given");
3751 return;
3753 } else {
3754 if (tls_creds) {
3755 error_setg(errp, "TLS can only be used over TCP socket");
3756 return;
3760 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
3761 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
3763 sock->has_nodelay = true;
3764 sock->nodelay = do_nodelay;
3765 sock->has_server = true;
3766 sock->server = is_listen;
3767 sock->has_telnet = true;
3768 sock->telnet = is_telnet;
3769 sock->has_wait = true;
3770 sock->wait = is_waitconnect;
3771 sock->has_reconnect = true;
3772 sock->reconnect = reconnect;
3773 sock->tls_creds = g_strdup(tls_creds);
3775 addr = g_new0(SocketAddress, 1);
3776 if (path) {
3777 UnixSocketAddress *q_unix;
3778 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3779 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
3780 q_unix->path = g_strdup(path);
3781 } else {
3782 addr->type = SOCKET_ADDRESS_KIND_INET;
3783 addr->u.inet.data = g_new(InetSocketAddress, 1);
3784 *addr->u.inet.data = (InetSocketAddress) {
3785 .host = g_strdup(host),
3786 .port = g_strdup(port),
3787 .has_to = qemu_opt_get(opts, "to"),
3788 .to = qemu_opt_get_number(opts, "to", 0),
3789 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3790 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3791 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3792 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3795 sock->addr = addr;
3798 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3799 Error **errp)
3801 const char *host = qemu_opt_get(opts, "host");
3802 const char *port = qemu_opt_get(opts, "port");
3803 const char *localaddr = qemu_opt_get(opts, "localaddr");
3804 const char *localport = qemu_opt_get(opts, "localport");
3805 bool has_local = false;
3806 SocketAddress *addr;
3807 ChardevUdp *udp;
3809 if (host == NULL || strlen(host) == 0) {
3810 host = "localhost";
3812 if (port == NULL || strlen(port) == 0) {
3813 error_setg(errp, "chardev: udp: remote port not specified");
3814 return;
3816 if (localport == NULL || strlen(localport) == 0) {
3817 localport = "0";
3818 } else {
3819 has_local = true;
3821 if (localaddr == NULL || strlen(localaddr) == 0) {
3822 localaddr = "";
3823 } else {
3824 has_local = true;
3827 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
3828 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
3830 addr = g_new0(SocketAddress, 1);
3831 addr->type = SOCKET_ADDRESS_KIND_INET;
3832 addr->u.inet.data = g_new(InetSocketAddress, 1);
3833 *addr->u.inet.data = (InetSocketAddress) {
3834 .host = g_strdup(host),
3835 .port = g_strdup(port),
3836 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3837 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3838 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3839 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3841 udp->remote = addr;
3843 if (has_local) {
3844 udp->has_local = true;
3845 addr = g_new0(SocketAddress, 1);
3846 addr->type = SOCKET_ADDRESS_KIND_INET;
3847 addr->u.inet.data = g_new(InetSocketAddress, 1);
3848 *addr->u.inet.data = (InetSocketAddress) {
3849 .host = g_strdup(localaddr),
3850 .port = g_strdup(localport),
3852 udp->local = addr;
3856 typedef struct CharDriver {
3857 const char *name;
3858 ChardevBackendKind kind;
3859 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3860 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3861 ChardevReturn *ret, Error **errp);
3862 } CharDriver;
3864 static GSList *backends;
3866 void register_char_driver(const char *name, ChardevBackendKind kind,
3867 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3868 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3869 ChardevReturn *ret, Error **errp))
3871 CharDriver *s;
3873 s = g_malloc0(sizeof(*s));
3874 s->name = g_strdup(name);
3875 s->kind = kind;
3876 s->parse = parse;
3877 s->create = create;
3879 backends = g_slist_append(backends, s);
3882 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3883 void (*init)(struct CharDriverState *s),
3884 Error **errp)
3886 Error *local_err = NULL;
3887 CharDriver *cd;
3888 CharDriverState *chr;
3889 GSList *i;
3890 ChardevReturn *ret = NULL;
3891 ChardevBackend *backend;
3892 const char *id = qemu_opts_id(opts);
3893 char *bid = NULL;
3895 if (qemu_opt_get(opts, "backend") == NULL) {
3896 error_setg(errp, "chardev: \"%s\" missing backend",
3897 qemu_opts_id(opts));
3898 goto err;
3901 if (is_help_option(qemu_opt_get(opts, "backend"))) {
3902 fprintf(stderr, "Available chardev backend types:\n");
3903 for (i = backends; i; i = i->next) {
3904 cd = i->data;
3905 fprintf(stderr, "%s\n", cd->name);
3907 exit(!is_help_option(qemu_opt_get(opts, "backend")));
3910 if (id == NULL) {
3911 error_setg(errp, "chardev: no id specified");
3912 goto err;
3915 for (i = backends; i; i = i->next) {
3916 cd = i->data;
3918 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3919 break;
3922 if (i == NULL) {
3923 error_setg(errp, "chardev: backend \"%s\" not found",
3924 qemu_opt_get(opts, "backend"));
3925 goto err;
3928 backend = g_new0(ChardevBackend, 1);
3930 if (qemu_opt_get_bool(opts, "mux", 0)) {
3931 bid = g_strdup_printf("%s-base", id);
3934 chr = NULL;
3935 backend->type = cd->kind;
3936 if (cd->parse) {
3937 cd->parse(opts, backend, &local_err);
3938 if (local_err) {
3939 error_propagate(errp, local_err);
3940 goto qapi_out;
3942 } else {
3943 ChardevCommon *cc = g_new0(ChardevCommon, 1);
3944 qemu_chr_parse_common(opts, cc);
3945 backend->u.null.data = cc; /* Any ChardevCommon member would work */
3948 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3949 if (!ret) {
3950 goto qapi_out;
3953 if (bid) {
3954 qapi_free_ChardevBackend(backend);
3955 qapi_free_ChardevReturn(ret);
3956 backend = g_new0(ChardevBackend, 1);
3957 backend->u.mux.data = g_new0(ChardevMux, 1);
3958 backend->type = CHARDEV_BACKEND_KIND_MUX;
3959 backend->u.mux.data->chardev = g_strdup(bid);
3960 ret = qmp_chardev_add(id, backend, errp);
3961 if (!ret) {
3962 chr = qemu_chr_find(bid);
3963 qemu_chr_delete(chr);
3964 chr = NULL;
3965 goto qapi_out;
3969 chr = qemu_chr_find(id);
3970 chr->opts = opts;
3972 qapi_out:
3973 qapi_free_ChardevBackend(backend);
3974 qapi_free_ChardevReturn(ret);
3975 g_free(bid);
3976 return chr;
3978 err:
3979 qemu_opts_del(opts);
3980 return NULL;
3983 CharDriverState *qemu_chr_new_noreplay(const char *label, const char *filename,
3984 void (*init)(struct CharDriverState *s))
3986 const char *p;
3987 CharDriverState *chr;
3988 QemuOpts *opts;
3989 Error *err = NULL;
3991 if (strstart(filename, "chardev:", &p)) {
3992 return qemu_chr_find(p);
3995 opts = qemu_chr_parse_compat(label, filename);
3996 if (!opts)
3997 return NULL;
3999 chr = qemu_chr_new_from_opts(opts, init, &err);
4000 if (err) {
4001 error_report_err(err);
4003 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
4004 qemu_chr_fe_claim_no_fail(chr);
4005 monitor_init(chr, MONITOR_USE_READLINE);
4007 return chr;
4010 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
4012 CharDriverState *chr;
4013 chr = qemu_chr_new_noreplay(label, filename, init);
4014 if (chr) {
4015 chr->replay = replay_mode != REPLAY_MODE_NONE;
4016 if (chr->replay && chr->chr_ioctl) {
4017 fprintf(stderr,
4018 "Replay: ioctl is not supported for serial devices yet\n");
4020 replay_register_char_driver(chr);
4022 return chr;
4025 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
4027 if (chr->chr_set_echo) {
4028 chr->chr_set_echo(chr, echo);
4032 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
4034 if (chr->fe_open == fe_open) {
4035 return;
4037 chr->fe_open = fe_open;
4038 if (chr->chr_set_fe_open) {
4039 chr->chr_set_fe_open(chr, fe_open);
4043 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
4045 if (chr->chr_fe_event) {
4046 chr->chr_fe_event(chr, event);
4050 guint qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
4051 GIOFunc func, void *user_data)
4053 GSource *src;
4054 guint tag;
4056 if (s->chr_add_watch == NULL) {
4057 return 0;
4060 src = s->chr_add_watch(s, cond);
4061 if (!src) {
4062 return 0;
4065 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
4066 tag = g_source_attach(src, NULL);
4067 g_source_unref(src);
4069 return tag;
4072 int qemu_chr_fe_claim(CharDriverState *s)
4074 if (s->avail_connections < 1) {
4075 return -1;
4077 s->avail_connections--;
4078 return 0;
4081 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
4083 if (qemu_chr_fe_claim(s) != 0) {
4084 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
4085 __func__, s->label);
4086 exit(1);
4090 void qemu_chr_fe_release(CharDriverState *s)
4092 s->avail_connections++;
4095 void qemu_chr_disconnect(CharDriverState *chr)
4097 if (chr->chr_disconnect) {
4098 chr->chr_disconnect(chr);
4102 static void qemu_chr_free_common(CharDriverState *chr)
4104 g_free(chr->filename);
4105 g_free(chr->label);
4106 qemu_opts_del(chr->opts);
4107 if (chr->logfd != -1) {
4108 close(chr->logfd);
4110 qemu_mutex_destroy(&chr->chr_write_lock);
4111 g_free(chr);
4114 void qemu_chr_free(CharDriverState *chr)
4116 if (chr->chr_close) {
4117 chr->chr_close(chr);
4119 qemu_chr_free_common(chr);
4122 void qemu_chr_delete(CharDriverState *chr)
4124 QTAILQ_REMOVE(&chardevs, chr, next);
4125 qemu_chr_free(chr);
4128 ChardevInfoList *qmp_query_chardev(Error **errp)
4130 ChardevInfoList *chr_list = NULL;
4131 CharDriverState *chr;
4133 QTAILQ_FOREACH(chr, &chardevs, next) {
4134 ChardevInfoList *info = g_malloc0(sizeof(*info));
4135 info->value = g_malloc0(sizeof(*info->value));
4136 info->value->label = g_strdup(chr->label);
4137 info->value->filename = g_strdup(chr->filename);
4138 info->value->frontend_open = chr->fe_open;
4140 info->next = chr_list;
4141 chr_list = info;
4144 return chr_list;
4147 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4149 ChardevBackendInfoList *backend_list = NULL;
4150 CharDriver *c = NULL;
4151 GSList *i = NULL;
4153 for (i = backends; i; i = i->next) {
4154 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4155 c = i->data;
4156 info->value = g_malloc0(sizeof(*info->value));
4157 info->value->name = g_strdup(c->name);
4159 info->next = backend_list;
4160 backend_list = info;
4163 return backend_list;
4166 CharDriverState *qemu_chr_find(const char *name)
4168 CharDriverState *chr;
4170 QTAILQ_FOREACH(chr, &chardevs, next) {
4171 if (strcmp(chr->label, name) != 0)
4172 continue;
4173 return chr;
4175 return NULL;
4178 QemuOptsList qemu_chardev_opts = {
4179 .name = "chardev",
4180 .implied_opt_name = "backend",
4181 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4182 .desc = {
4184 .name = "backend",
4185 .type = QEMU_OPT_STRING,
4187 .name = "path",
4188 .type = QEMU_OPT_STRING,
4190 .name = "host",
4191 .type = QEMU_OPT_STRING,
4193 .name = "port",
4194 .type = QEMU_OPT_STRING,
4196 .name = "localaddr",
4197 .type = QEMU_OPT_STRING,
4199 .name = "localport",
4200 .type = QEMU_OPT_STRING,
4202 .name = "to",
4203 .type = QEMU_OPT_NUMBER,
4205 .name = "ipv4",
4206 .type = QEMU_OPT_BOOL,
4208 .name = "ipv6",
4209 .type = QEMU_OPT_BOOL,
4211 .name = "wait",
4212 .type = QEMU_OPT_BOOL,
4214 .name = "server",
4215 .type = QEMU_OPT_BOOL,
4217 .name = "delay",
4218 .type = QEMU_OPT_BOOL,
4220 .name = "reconnect",
4221 .type = QEMU_OPT_NUMBER,
4223 .name = "telnet",
4224 .type = QEMU_OPT_BOOL,
4226 .name = "tls-creds",
4227 .type = QEMU_OPT_STRING,
4229 .name = "width",
4230 .type = QEMU_OPT_NUMBER,
4232 .name = "height",
4233 .type = QEMU_OPT_NUMBER,
4235 .name = "cols",
4236 .type = QEMU_OPT_NUMBER,
4238 .name = "rows",
4239 .type = QEMU_OPT_NUMBER,
4241 .name = "mux",
4242 .type = QEMU_OPT_BOOL,
4244 .name = "signal",
4245 .type = QEMU_OPT_BOOL,
4247 .name = "name",
4248 .type = QEMU_OPT_STRING,
4250 .name = "debug",
4251 .type = QEMU_OPT_NUMBER,
4253 .name = "size",
4254 .type = QEMU_OPT_SIZE,
4256 .name = "chardev",
4257 .type = QEMU_OPT_STRING,
4259 .name = "append",
4260 .type = QEMU_OPT_BOOL,
4262 .name = "logfile",
4263 .type = QEMU_OPT_STRING,
4265 .name = "logappend",
4266 .type = QEMU_OPT_BOOL,
4268 { /* end of list */ }
4272 #ifdef _WIN32
4274 static CharDriverState *qmp_chardev_open_file(const char *id,
4275 ChardevBackend *backend,
4276 ChardevReturn *ret,
4277 Error **errp)
4279 ChardevFile *file = backend->u.file.data;
4280 ChardevCommon *common = qapi_ChardevFile_base(file);
4281 HANDLE out;
4282 DWORD accessmode;
4283 DWORD flags;
4285 if (file->has_in) {
4286 error_setg(errp, "input file not supported");
4287 return NULL;
4290 if (file->has_append && file->append) {
4291 /* Append to file if it already exists. */
4292 accessmode = FILE_GENERIC_WRITE & ~FILE_WRITE_DATA;
4293 flags = OPEN_ALWAYS;
4294 } else {
4295 /* Truncate file if it already exists. */
4296 accessmode = GENERIC_WRITE;
4297 flags = CREATE_ALWAYS;
4300 out = CreateFile(file->out, accessmode, FILE_SHARE_READ, NULL, flags,
4301 FILE_ATTRIBUTE_NORMAL, NULL);
4302 if (out == INVALID_HANDLE_VALUE) {
4303 error_setg(errp, "open %s failed", file->out);
4304 return NULL;
4306 return qemu_chr_open_win_file(out, common, errp);
4309 static CharDriverState *qmp_chardev_open_serial(const char *id,
4310 ChardevBackend *backend,
4311 ChardevReturn *ret,
4312 Error **errp)
4314 ChardevHostdev *serial = backend->u.serial.data;
4315 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4316 return qemu_chr_open_win_path(serial->device, common, errp);
4319 #else /* WIN32 */
4321 static int qmp_chardev_open_file_source(char *src, int flags,
4322 Error **errp)
4324 int fd = -1;
4326 TFR(fd = qemu_open(src, flags, 0666));
4327 if (fd == -1) {
4328 error_setg_file_open(errp, errno, src);
4330 return fd;
4333 static CharDriverState *qmp_chardev_open_file(const char *id,
4334 ChardevBackend *backend,
4335 ChardevReturn *ret,
4336 Error **errp)
4338 ChardevFile *file = backend->u.file.data;
4339 ChardevCommon *common = qapi_ChardevFile_base(file);
4340 int flags, in = -1, out;
4342 flags = O_WRONLY | O_CREAT | O_BINARY;
4343 if (file->has_append && file->append) {
4344 flags |= O_APPEND;
4345 } else {
4346 flags |= O_TRUNC;
4349 out = qmp_chardev_open_file_source(file->out, flags, errp);
4350 if (out < 0) {
4351 return NULL;
4354 if (file->has_in) {
4355 flags = O_RDONLY;
4356 in = qmp_chardev_open_file_source(file->in, flags, errp);
4357 if (in < 0) {
4358 qemu_close(out);
4359 return NULL;
4363 return qemu_chr_open_fd(in, out, common, errp);
4366 #ifdef HAVE_CHARDEV_SERIAL
4367 static CharDriverState *qmp_chardev_open_serial(const char *id,
4368 ChardevBackend *backend,
4369 ChardevReturn *ret,
4370 Error **errp)
4372 ChardevHostdev *serial = backend->u.serial.data;
4373 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4374 int fd;
4376 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4377 if (fd < 0) {
4378 return NULL;
4380 qemu_set_nonblock(fd);
4381 return qemu_chr_open_tty_fd(fd, common, errp);
4383 #endif
4385 #ifdef HAVE_CHARDEV_PARPORT
4386 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4387 ChardevBackend *backend,
4388 ChardevReturn *ret,
4389 Error **errp)
4391 ChardevHostdev *parallel = backend->u.parallel.data;
4392 ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
4393 int fd;
4395 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4396 if (fd < 0) {
4397 return NULL;
4399 return qemu_chr_open_pp_fd(fd, common, errp);
4401 #endif
4403 #endif /* WIN32 */
4405 static gboolean socket_reconnect_timeout(gpointer opaque)
4407 CharDriverState *chr = opaque;
4408 TCPCharDriver *s = chr->opaque;
4409 QIOChannelSocket *sioc;
4411 s->reconnect_timer = 0;
4413 if (chr->be_open) {
4414 return false;
4417 sioc = qio_channel_socket_new();
4418 qio_channel_socket_connect_async(sioc, s->addr,
4419 qemu_chr_socket_connected,
4420 chr, NULL);
4422 return false;
4425 static CharDriverState *qmp_chardev_open_socket(const char *id,
4426 ChardevBackend *backend,
4427 ChardevReturn *ret,
4428 Error **errp)
4430 CharDriverState *chr;
4431 TCPCharDriver *s;
4432 ChardevSocket *sock = backend->u.socket.data;
4433 SocketAddress *addr = sock->addr;
4434 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4435 bool is_listen = sock->has_server ? sock->server : true;
4436 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4437 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4438 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4439 ChardevCommon *common = qapi_ChardevSocket_base(sock);
4440 QIOChannelSocket *sioc = NULL;
4442 chr = qemu_chr_alloc(common, errp);
4443 if (!chr) {
4444 return NULL;
4446 s = g_new0(TCPCharDriver, 1);
4448 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4449 s->is_listen = is_listen;
4450 s->is_telnet = is_telnet;
4451 s->do_nodelay = do_nodelay;
4452 if (sock->tls_creds) {
4453 Object *creds;
4454 creds = object_resolve_path_component(
4455 object_get_objects_root(), sock->tls_creds);
4456 if (!creds) {
4457 error_setg(errp, "No TLS credentials with id '%s'",
4458 sock->tls_creds);
4459 goto error;
4461 s->tls_creds = (QCryptoTLSCreds *)
4462 object_dynamic_cast(creds,
4463 TYPE_QCRYPTO_TLS_CREDS);
4464 if (!s->tls_creds) {
4465 error_setg(errp, "Object with id '%s' is not TLS credentials",
4466 sock->tls_creds);
4467 goto error;
4469 object_ref(OBJECT(s->tls_creds));
4470 if (is_listen) {
4471 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4472 error_setg(errp, "%s",
4473 "Expected TLS credentials for server endpoint");
4474 goto error;
4476 } else {
4477 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4478 error_setg(errp, "%s",
4479 "Expected TLS credentials for client endpoint");
4480 goto error;
4485 s->addr = QAPI_CLONE(SocketAddress, sock->addr);
4487 chr->opaque = s;
4488 chr->chr_wait_connected = tcp_chr_wait_connected;
4489 chr->chr_write = tcp_chr_write;
4490 chr->chr_sync_read = tcp_chr_sync_read;
4491 chr->chr_close = tcp_chr_close;
4492 chr->chr_disconnect = tcp_chr_disconnect;
4493 chr->get_msgfds = tcp_get_msgfds;
4494 chr->set_msgfds = tcp_set_msgfds;
4495 chr->chr_add_client = tcp_chr_add_client;
4496 chr->chr_add_watch = tcp_chr_add_watch;
4497 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4498 /* be isn't opened until we get a connection */
4499 chr->explicit_be_open = true;
4501 chr->filename = SocketAddress_to_str("disconnected:",
4502 addr, is_listen, is_telnet);
4504 if (is_listen) {
4505 if (is_telnet) {
4506 s->do_telnetopt = 1;
4508 } else if (reconnect > 0) {
4509 s->reconnect_time = reconnect;
4512 if (s->reconnect_time) {
4513 sioc = qio_channel_socket_new();
4514 qio_channel_socket_connect_async(sioc, s->addr,
4515 qemu_chr_socket_connected,
4516 chr, NULL);
4517 } else {
4518 if (s->is_listen) {
4519 sioc = qio_channel_socket_new();
4520 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4521 goto error;
4523 s->listen_ioc = sioc;
4524 if (is_waitconnect &&
4525 qemu_chr_wait_connected(chr, errp) < 0) {
4526 goto error;
4528 if (!s->ioc) {
4529 s->listen_tag = qio_channel_add_watch(
4530 QIO_CHANNEL(s->listen_ioc), G_IO_IN,
4531 tcp_chr_accept, chr, NULL);
4533 } else if (qemu_chr_wait_connected(chr, errp) < 0) {
4534 goto error;
4538 return chr;
4540 error:
4541 if (sioc) {
4542 object_unref(OBJECT(sioc));
4544 if (s->tls_creds) {
4545 object_unref(OBJECT(s->tls_creds));
4547 g_free(s);
4548 qemu_chr_free_common(chr);
4549 return NULL;
4552 static CharDriverState *qmp_chardev_open_udp(const char *id,
4553 ChardevBackend *backend,
4554 ChardevReturn *ret,
4555 Error **errp)
4557 ChardevUdp *udp = backend->u.udp.data;
4558 ChardevCommon *common = qapi_ChardevUdp_base(udp);
4559 QIOChannelSocket *sioc = qio_channel_socket_new();
4561 if (qio_channel_socket_dgram_sync(sioc,
4562 udp->local, udp->remote,
4563 errp) < 0) {
4564 object_unref(OBJECT(sioc));
4565 return NULL;
4567 return qemu_chr_open_udp(sioc, common, errp);
4570 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4571 Error **errp)
4573 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4574 CharDriverState *chr = NULL;
4575 Error *local_err = NULL;
4576 GSList *i;
4577 CharDriver *cd;
4579 chr = qemu_chr_find(id);
4580 if (chr) {
4581 error_setg(errp, "Chardev '%s' already exists", id);
4582 g_free(ret);
4583 return NULL;
4586 for (i = backends; i; i = i->next) {
4587 cd = i->data;
4589 if (cd->kind == backend->type) {
4590 chr = cd->create(id, backend, ret, &local_err);
4591 if (local_err) {
4592 error_propagate(errp, local_err);
4593 goto out_error;
4595 break;
4599 if (chr == NULL) {
4600 assert(!i);
4601 error_setg(errp, "chardev backend not available");
4602 goto out_error;
4605 chr->label = g_strdup(id);
4606 chr->avail_connections =
4607 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4608 if (!chr->filename) {
4609 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4611 if (!chr->explicit_be_open) {
4612 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4614 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4615 return ret;
4617 out_error:
4618 g_free(ret);
4619 return NULL;
4622 void qmp_chardev_remove(const char *id, Error **errp)
4624 CharDriverState *chr;
4626 chr = qemu_chr_find(id);
4627 if (chr == NULL) {
4628 error_setg(errp, "Chardev '%s' not found", id);
4629 return;
4631 if (chr->chr_can_read || chr->chr_read ||
4632 chr->chr_event || chr->handler_opaque) {
4633 error_setg(errp, "Chardev '%s' is busy", id);
4634 return;
4636 if (chr->replay) {
4637 error_setg(errp,
4638 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4639 return;
4641 qemu_chr_delete(chr);
4644 void qemu_chr_cleanup(void)
4646 CharDriverState *chr, *tmp;
4648 QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
4649 qemu_chr_delete(chr);
4653 static void register_types(void)
4655 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4656 qemu_chr_open_null);
4657 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4658 qemu_chr_parse_socket, qmp_chardev_open_socket);
4659 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4660 qmp_chardev_open_udp);
4661 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4662 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4663 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4664 qemu_chr_parse_file_out, qmp_chardev_open_file);
4665 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4666 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4667 #if defined HAVE_CHARDEV_SERIAL
4668 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4669 qemu_chr_parse_serial, qmp_chardev_open_serial);
4670 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4671 qemu_chr_parse_serial, qmp_chardev_open_serial);
4672 #endif
4673 #ifdef HAVE_CHARDEV_PARPORT
4674 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4675 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4676 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4677 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4678 #endif
4679 #ifdef HAVE_CHARDEV_PTY
4680 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4681 qemu_chr_open_pty);
4682 #endif
4683 #ifdef _WIN32
4684 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4685 qemu_chr_open_win_con);
4686 #endif
4687 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4688 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4689 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4690 qemu_chr_open_mux);
4691 /* Bug-compatibility: */
4692 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4693 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4694 /* this must be done after machine init, since we register FEs with muxes
4695 * as part of realize functions like serial_isa_realizefn when -nographic
4696 * is specified
4698 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4701 type_init(register_types);