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
24 #include "qemu-common.h"
25 #include "monitor/monitor.h"
26 #include "ui/console.h"
27 #include "sysemu/sysemu.h"
28 #include "qemu/timer.h"
29 #include "sysemu/char.h"
31 #include "qmp-commands.h"
41 #include <sys/times.h>
45 #include <sys/ioctl.h>
46 #include <sys/resource.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
50 #include <arpa/inet.h>
53 #include <sys/select.h>
56 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
57 #include <dev/ppbus/ppi.h>
58 #include <dev/ppbus/ppbconf.h>
59 #elif defined(__DragonFly__)
60 #include <dev/misc/ppi/ppi.h>
61 #include <bus/ppbus/ppbconf.h>
65 #include <linux/ppdev.h>
66 #include <linux/parport.h>
70 #include <sys/ethernet.h>
71 #include <sys/sockio.h>
72 #include <netinet/arp.h>
73 #include <netinet/in.h>
74 #include <netinet/in_systm.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_icmp.h> // must come after ip.h
77 #include <netinet/udp.h>
78 #include <netinet/tcp.h>
85 #include "qemu/sockets.h"
86 #include "ui/qemu-spice.h"
88 #define READ_BUF_LEN 4096
90 /***********************************************************/
91 /* character device */
93 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
94 QTAILQ_HEAD_INITIALIZER(chardevs);
96 void qemu_chr_be_event(CharDriverState *s, int event)
98 /* Keep track if the char device is open */
100 case CHR_EVENT_OPENED:
103 case CHR_EVENT_CLOSED:
110 s->chr_event(s->handler_opaque, event);
113 void qemu_chr_be_generic_open(CharDriverState *s)
115 qemu_chr_be_event(s, CHR_EVENT_OPENED);
118 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
120 return s->chr_write(s, buf, len);
123 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
128 while (offset < len) {
130 res = s->chr_write(s, buf + offset, len - offset);
131 if (res == -1 && errno == EAGAIN) {
134 } while (res == -1 && errno == EAGAIN);
150 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
154 return s->chr_ioctl(s, cmd, arg);
157 int qemu_chr_be_can_write(CharDriverState *s)
159 if (!s->chr_can_read)
161 return s->chr_can_read(s->handler_opaque);
164 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
167 s->chr_read(s->handler_opaque, buf, len);
171 int qemu_chr_fe_get_msgfd(CharDriverState *s)
173 return s->get_msgfd ? s->get_msgfd(s) : -1;
176 int qemu_chr_add_client(CharDriverState *s, int fd)
178 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
181 void qemu_chr_accept_input(CharDriverState *s)
183 if (s->chr_accept_input)
184 s->chr_accept_input(s);
188 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
190 char buf[READ_BUF_LEN];
193 vsnprintf(buf, sizeof(buf), fmt, ap);
194 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
198 void qemu_chr_add_handlers(CharDriverState *s,
199 IOCanReadHandler *fd_can_read,
200 IOReadHandler *fd_read,
201 IOEventHandler *fd_event,
206 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
211 s->chr_can_read = fd_can_read;
212 s->chr_read = fd_read;
213 s->chr_event = fd_event;
214 s->handler_opaque = opaque;
215 if (s->chr_update_read_handler)
216 s->chr_update_read_handler(s);
218 if (!s->explicit_fe_open) {
219 qemu_chr_fe_set_open(s, fe_open);
222 /* We're connecting to an already opened device, so let's make sure we
223 also get the open event */
224 if (fe_open && s->be_open) {
225 qemu_chr_be_generic_open(s);
229 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
234 static CharDriverState *qemu_chr_open_null(void)
236 CharDriverState *chr;
238 chr = g_malloc0(sizeof(CharDriverState));
239 chr->chr_write = null_chr_write;
240 chr->explicit_be_open = true;
244 /* MUX driver for serial I/O splitting */
246 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
247 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
249 IOCanReadHandler *chr_can_read[MAX_MUX];
250 IOReadHandler *chr_read[MAX_MUX];
251 IOEventHandler *chr_event[MAX_MUX];
252 void *ext_opaque[MAX_MUX];
253 CharDriverState *drv;
258 /* Intermediate input buffer allows to catch escape sequences even if the
259 currently active device is not accepting any input - but only until it
261 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
266 int64_t timestamps_start;
270 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
272 MuxDriver *d = chr->opaque;
274 if (!d->timestamps) {
275 ret = d->drv->chr_write(d->drv, buf, len);
280 for (i = 0; i < len; i++) {
286 ti = qemu_get_clock_ms(rt_clock);
287 if (d->timestamps_start == -1)
288 d->timestamps_start = ti;
289 ti -= d->timestamps_start;
291 snprintf(buf1, sizeof(buf1),
292 "[%02d:%02d:%02d.%03d] ",
297 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
300 ret += d->drv->chr_write(d->drv, buf+i, 1);
301 if (buf[i] == '\n') {
309 static const char * const mux_help[] = {
310 "% h print this help\n\r",
311 "% x exit emulator\n\r",
312 "% s save disk data back to file (if -snapshot)\n\r",
313 "% t toggle console timestamps\n\r"
314 "% b send break (magic sysrq)\n\r",
315 "% c switch between console and monitor\n\r",
320 int term_escape_char = 0x01; /* ctrl-a is used for escape */
321 static void mux_print_help(CharDriverState *chr)
324 char ebuf[15] = "Escape-Char";
325 char cbuf[50] = "\n\r";
327 if (term_escape_char > 0 && term_escape_char < 26) {
328 snprintf(cbuf, sizeof(cbuf), "\n\r");
329 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
331 snprintf(cbuf, sizeof(cbuf),
332 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
335 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
336 for (i = 0; mux_help[i] != NULL; i++) {
337 for (j=0; mux_help[i][j] != '\0'; j++) {
338 if (mux_help[i][j] == '%')
339 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
341 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
346 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
348 if (d->chr_event[mux_nr])
349 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
352 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
354 if (d->term_got_escape) {
355 d->term_got_escape = 0;
356 if (ch == term_escape_char)
365 const char *term = "QEMU: Terminated\n\r";
366 chr->chr_write(chr,(uint8_t *)term,strlen(term));
374 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
377 /* Switch to the next registered device */
378 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
380 if (d->focus >= d->mux_cnt)
382 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
385 d->timestamps = !d->timestamps;
386 d->timestamps_start = -1;
390 } else if (ch == term_escape_char) {
391 d->term_got_escape = 1;
399 static void mux_chr_accept_input(CharDriverState *chr)
401 MuxDriver *d = chr->opaque;
404 while (d->prod[m] != d->cons[m] &&
405 d->chr_can_read[m] &&
406 d->chr_can_read[m](d->ext_opaque[m])) {
407 d->chr_read[m](d->ext_opaque[m],
408 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
412 static int mux_chr_can_read(void *opaque)
414 CharDriverState *chr = opaque;
415 MuxDriver *d = chr->opaque;
418 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
420 if (d->chr_can_read[m])
421 return d->chr_can_read[m](d->ext_opaque[m]);
425 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
427 CharDriverState *chr = opaque;
428 MuxDriver *d = chr->opaque;
432 mux_chr_accept_input (opaque);
434 for(i = 0; i < size; i++)
435 if (mux_proc_byte(chr, d, buf[i])) {
436 if (d->prod[m] == d->cons[m] &&
437 d->chr_can_read[m] &&
438 d->chr_can_read[m](d->ext_opaque[m]))
439 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
441 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
445 static void mux_chr_event(void *opaque, int event)
447 CharDriverState *chr = opaque;
448 MuxDriver *d = chr->opaque;
451 /* Send the event to all registered listeners */
452 for (i = 0; i < d->mux_cnt; i++)
453 mux_chr_send_event(d, i, event);
456 static void mux_chr_update_read_handler(CharDriverState *chr)
458 MuxDriver *d = chr->opaque;
460 if (d->mux_cnt >= MAX_MUX) {
461 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
464 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
465 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
466 d->chr_read[d->mux_cnt] = chr->chr_read;
467 d->chr_event[d->mux_cnt] = chr->chr_event;
468 /* Fix up the real driver with mux routines */
469 if (d->mux_cnt == 0) {
470 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
473 if (d->focus != -1) {
474 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
476 d->focus = d->mux_cnt;
478 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
481 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
483 CharDriverState *chr;
486 chr = g_malloc0(sizeof(CharDriverState));
487 d = g_malloc0(sizeof(MuxDriver));
492 chr->chr_write = mux_chr_write;
493 chr->chr_update_read_handler = mux_chr_update_read_handler;
494 chr->chr_accept_input = mux_chr_accept_input;
495 /* Frontend guest-open / -close notification is not support with muxes */
496 chr->chr_set_fe_open = NULL;
503 int send_all(int fd, const void *buf, int len1)
509 ret = send(fd, buf, len, 0);
511 errno = WSAGetLastError();
512 if (errno != WSAEWOULDBLOCK) {
515 } else if (ret == 0) {
527 int send_all(int fd, const void *_buf, int len1)
530 const uint8_t *buf = _buf;
534 ret = write(fd, buf, len);
536 if (errno != EINTR && errno != EAGAIN)
538 } else if (ret == 0) {
548 int recv_all(int fd, void *_buf, int len1, bool single_read)
554 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
556 if (errno != EINTR && errno != EAGAIN) {
573 typedef struct IOWatchPoll
580 IOCanReadHandler *fd_can_read;
585 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
587 return container_of(source, IOWatchPoll, parent);
590 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
592 IOWatchPoll *iwp = io_watch_poll_from_source(source);
593 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
594 bool was_active = iwp->src != NULL;
595 if (was_active == now_active) {
600 iwp->src = g_io_create_watch(iwp->channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
601 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
602 g_source_attach(iwp->src, NULL);
604 g_source_destroy(iwp->src);
605 g_source_unref(iwp->src);
611 static gboolean io_watch_poll_check(GSource *source)
616 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
622 static void io_watch_poll_finalize(GSource *source)
624 /* Due to a glib bug, removing the last reference to a source
625 * inside a finalize callback causes recursive locking (and a
626 * deadlock). This is not a problem inside other callbacks,
627 * including dispatch callbacks, so we call io_remove_watch_poll
628 * to remove this source. At this point, iwp->src must
629 * be NULL, or we would leak it.
631 * This would be solved much more elegantly by child sources,
632 * but we support older glib versions that do not have them.
634 IOWatchPoll *iwp = io_watch_poll_from_source(source);
635 assert(iwp->src == NULL);
638 static GSourceFuncs io_watch_poll_funcs = {
639 .prepare = io_watch_poll_prepare,
640 .check = io_watch_poll_check,
641 .dispatch = io_watch_poll_dispatch,
642 .finalize = io_watch_poll_finalize,
645 /* Can only be used for read */
646 static guint io_add_watch_poll(GIOChannel *channel,
647 IOCanReadHandler *fd_can_read,
654 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
655 iwp->fd_can_read = fd_can_read;
656 iwp->opaque = user_data;
657 iwp->channel = channel;
658 iwp->fd_read = (GSourceFunc) fd_read;
661 tag = g_source_attach(&iwp->parent, NULL);
662 g_source_unref(&iwp->parent);
666 static void io_remove_watch_poll(guint tag)
671 g_return_if_fail (tag > 0);
673 source = g_main_context_find_source_by_id(NULL, tag);
674 g_return_if_fail (source != NULL);
676 iwp = io_watch_poll_from_source(source);
678 g_source_destroy(iwp->src);
679 g_source_unref(iwp->src);
682 g_source_destroy(&iwp->parent);
686 static GIOChannel *io_channel_from_fd(int fd)
694 chan = g_io_channel_unix_new(fd);
696 g_io_channel_set_encoding(chan, NULL, NULL);
697 g_io_channel_set_buffered(chan, FALSE);
703 static GIOChannel *io_channel_from_socket(int fd)
712 chan = g_io_channel_win32_new_socket(fd);
714 chan = g_io_channel_unix_new(fd);
717 g_io_channel_set_encoding(chan, NULL, NULL);
718 g_io_channel_set_buffered(chan, FALSE);
723 static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
729 while (offset < len) {
732 status = g_io_channel_write_chars(fd, buf + offset, len - offset,
733 &bytes_written, NULL);
734 if (status != G_IO_STATUS_NORMAL) {
735 if (status == G_IO_STATUS_AGAIN) {
736 /* If we've written any data, return a partial write. */
746 } else if (status == G_IO_STATUS_EOF) {
750 offset += bytes_written;
758 typedef struct FDCharDriver {
759 CharDriverState *chr;
760 GIOChannel *fd_in, *fd_out;
763 QTAILQ_ENTRY(FDCharDriver) node;
766 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
768 FDCharDriver *s = chr->opaque;
770 return io_channel_send(s->fd_out, buf, len);
773 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
775 CharDriverState *chr = opaque;
776 FDCharDriver *s = chr->opaque;
778 uint8_t buf[READ_BUF_LEN];
783 if (len > s->max_size) {
790 status = g_io_channel_read_chars(chan, (gchar *)buf,
791 len, &bytes_read, NULL);
792 if (status == G_IO_STATUS_EOF) {
794 io_remove_watch_poll(s->fd_in_tag);
797 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
800 if (status == G_IO_STATUS_NORMAL) {
801 qemu_chr_be_write(chr, buf, bytes_read);
807 static int fd_chr_read_poll(void *opaque)
809 CharDriverState *chr = opaque;
810 FDCharDriver *s = chr->opaque;
812 s->max_size = qemu_chr_be_can_write(chr);
816 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
818 FDCharDriver *s = chr->opaque;
819 return g_io_create_watch(s->fd_out, cond);
822 static void fd_chr_update_read_handler(CharDriverState *chr)
824 FDCharDriver *s = chr->opaque;
827 io_remove_watch_poll(s->fd_in_tag);
832 s->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll, fd_chr_read, chr);
836 static void fd_chr_close(struct CharDriverState *chr)
838 FDCharDriver *s = chr->opaque;
841 io_remove_watch_poll(s->fd_in_tag);
846 g_io_channel_unref(s->fd_in);
849 g_io_channel_unref(s->fd_out);
853 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
856 /* open a character device to a unix fd */
857 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
859 CharDriverState *chr;
862 chr = g_malloc0(sizeof(CharDriverState));
863 s = g_malloc0(sizeof(FDCharDriver));
864 s->fd_in = io_channel_from_fd(fd_in);
865 s->fd_out = io_channel_from_fd(fd_out);
866 fcntl(fd_out, F_SETFL, O_NONBLOCK);
869 chr->chr_add_watch = fd_chr_add_watch;
870 chr->chr_write = fd_chr_write;
871 chr->chr_update_read_handler = fd_chr_update_read_handler;
872 chr->chr_close = fd_chr_close;
877 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
880 char filename_in[256], filename_out[256];
881 const char *filename = opts->device;
883 if (filename == NULL) {
884 fprintf(stderr, "chardev: pipe: no filename given\n");
888 snprintf(filename_in, 256, "%s.in", filename);
889 snprintf(filename_out, 256, "%s.out", filename);
890 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
891 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
892 if (fd_in < 0 || fd_out < 0) {
897 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
902 return qemu_chr_open_fd(fd_in, fd_out);
905 /* init terminal so that we can grab keys */
906 static struct termios oldtty;
907 static int old_fd0_flags;
908 static bool stdio_allow_signal;
910 static void term_exit(void)
912 tcsetattr (0, TCSANOW, &oldtty);
913 fcntl(0, F_SETFL, old_fd0_flags);
916 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
922 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
923 |INLCR|IGNCR|ICRNL|IXON);
924 tty.c_oflag |= OPOST;
925 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
926 tty.c_cflag &= ~(CSIZE|PARENB);
931 /* if graphical mode, we allow Ctrl-C handling */
932 if (!stdio_allow_signal)
933 tty.c_lflag &= ~ISIG;
935 tcsetattr (0, TCSANOW, &tty);
938 static void qemu_chr_close_stdio(struct CharDriverState *chr)
944 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
946 CharDriverState *chr;
948 if (is_daemonized()) {
949 error_report("cannot use stdio with -daemonize");
952 old_fd0_flags = fcntl(0, F_GETFL);
953 tcgetattr (0, &oldtty);
954 fcntl(0, F_SETFL, O_NONBLOCK);
957 chr = qemu_chr_open_fd(0, 1);
958 chr->chr_close = qemu_chr_close_stdio;
959 chr->chr_set_echo = qemu_chr_set_echo_stdio;
960 stdio_allow_signal = display_type != DT_NOGRAPHIC;
961 if (opts->has_signal) {
962 stdio_allow_signal = opts->signal;
964 qemu_chr_fe_set_echo(chr, false);
969 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
970 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
971 || defined(__GLIBC__)
973 #define HAVE_CHARDEV_TTY 1
983 static void pty_chr_update_read_handler(CharDriverState *chr);
984 static void pty_chr_state(CharDriverState *chr, int connected);
986 static gboolean pty_chr_timer(gpointer opaque)
988 struct CharDriverState *chr = opaque;
989 PtyCharDriver *s = chr->opaque;
996 pty_chr_update_read_handler(chr);
1003 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1005 PtyCharDriver *s = chr->opaque;
1008 g_source_remove(s->timer_tag);
1013 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1015 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1019 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1021 PtyCharDriver *s = chr->opaque;
1023 if (!s->connected) {
1024 /* guest sends data, check for (re-)connect */
1025 pty_chr_update_read_handler(chr);
1028 return io_channel_send(s->fd, buf, len);
1031 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1033 PtyCharDriver *s = chr->opaque;
1034 return g_io_create_watch(s->fd, cond);
1037 static int pty_chr_read_poll(void *opaque)
1039 CharDriverState *chr = opaque;
1040 PtyCharDriver *s = chr->opaque;
1042 s->read_bytes = qemu_chr_be_can_write(chr);
1043 return s->read_bytes;
1046 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1048 CharDriverState *chr = opaque;
1049 PtyCharDriver *s = chr->opaque;
1051 uint8_t buf[READ_BUF_LEN];
1055 if (len > s->read_bytes)
1056 len = s->read_bytes;
1060 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1061 if (status != G_IO_STATUS_NORMAL) {
1062 pty_chr_state(chr, 0);
1065 pty_chr_state(chr, 1);
1066 qemu_chr_be_write(chr, buf, size);
1071 static void pty_chr_update_read_handler(CharDriverState *chr)
1073 PtyCharDriver *s = chr->opaque;
1076 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1077 pfd.events = G_IO_OUT;
1080 if (pfd.revents & G_IO_HUP) {
1081 pty_chr_state(chr, 0);
1083 pty_chr_state(chr, 1);
1087 static void pty_chr_state(CharDriverState *chr, int connected)
1089 PtyCharDriver *s = chr->opaque;
1093 io_remove_watch_poll(s->fd_tag);
1097 /* (re-)connect poll interval for idle guests: once per second.
1098 * We check more frequently in case the guests sends data to
1099 * the virtual device linked to our pty. */
1100 pty_chr_rearm_timer(chr, 1000);
1103 g_source_remove(s->timer_tag);
1106 if (!s->connected) {
1107 qemu_chr_be_generic_open(chr);
1109 s->fd_tag = io_add_watch_poll(s->fd, pty_chr_read_poll, pty_chr_read, chr);
1115 static void pty_chr_close(struct CharDriverState *chr)
1117 PtyCharDriver *s = chr->opaque;
1121 io_remove_watch_poll(s->fd_tag);
1124 fd = g_io_channel_unix_get_fd(s->fd);
1125 g_io_channel_unref(s->fd);
1128 g_source_remove(s->timer_tag);
1132 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1135 static CharDriverState *qemu_chr_open_pty(const char *id,
1138 CharDriverState *chr;
1140 int master_fd, slave_fd;
1141 char pty_name[PATH_MAX];
1143 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1144 if (master_fd < 0) {
1150 chr = g_malloc0(sizeof(CharDriverState));
1152 chr->filename = g_strdup_printf("pty:%s", pty_name);
1153 ret->pty = g_strdup(pty_name);
1154 ret->has_pty = true;
1156 fprintf(stderr, "char device redirected to %s (label %s)\n",
1159 s = g_malloc0(sizeof(PtyCharDriver));
1161 chr->chr_write = pty_chr_write;
1162 chr->chr_update_read_handler = pty_chr_update_read_handler;
1163 chr->chr_close = pty_chr_close;
1164 chr->chr_add_watch = pty_chr_add_watch;
1165 chr->explicit_be_open = true;
1167 s->fd = io_channel_from_fd(master_fd);
1173 static void tty_serial_init(int fd, int speed,
1174 int parity, int data_bits, int stop_bits)
1180 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1181 speed, parity, data_bits, stop_bits);
1183 tcgetattr (fd, &tty);
1185 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1186 speed = speed * 10 / 11;
1203 /* Non-Posix values follow. They may be unsupported on some systems. */
1205 check_speed(115200);
1207 check_speed(230400);
1210 check_speed(460800);
1213 check_speed(500000);
1216 check_speed(576000);
1219 check_speed(921600);
1222 check_speed(1000000);
1225 check_speed(1152000);
1228 check_speed(1500000);
1231 check_speed(2000000);
1234 check_speed(2500000);
1237 check_speed(3000000);
1240 check_speed(3500000);
1243 check_speed(4000000);
1248 cfsetispeed(&tty, spd);
1249 cfsetospeed(&tty, spd);
1251 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1252 |INLCR|IGNCR|ICRNL|IXON);
1253 tty.c_oflag |= OPOST;
1254 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1255 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1276 tty.c_cflag |= PARENB;
1279 tty.c_cflag |= PARENB | PARODD;
1283 tty.c_cflag |= CSTOPB;
1285 tcsetattr (fd, TCSANOW, &tty);
1288 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1290 FDCharDriver *s = chr->opaque;
1293 case CHR_IOCTL_SERIAL_SET_PARAMS:
1295 QEMUSerialSetParams *ssp = arg;
1296 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1297 ssp->speed, ssp->parity,
1298 ssp->data_bits, ssp->stop_bits);
1301 case CHR_IOCTL_SERIAL_SET_BREAK:
1303 int enable = *(int *)arg;
1305 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1309 case CHR_IOCTL_SERIAL_GET_TIOCM:
1312 int *targ = (int *)arg;
1313 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1315 if (sarg & TIOCM_CTS)
1316 *targ |= CHR_TIOCM_CTS;
1317 if (sarg & TIOCM_CAR)
1318 *targ |= CHR_TIOCM_CAR;
1319 if (sarg & TIOCM_DSR)
1320 *targ |= CHR_TIOCM_DSR;
1321 if (sarg & TIOCM_RI)
1322 *targ |= CHR_TIOCM_RI;
1323 if (sarg & TIOCM_DTR)
1324 *targ |= CHR_TIOCM_DTR;
1325 if (sarg & TIOCM_RTS)
1326 *targ |= CHR_TIOCM_RTS;
1329 case CHR_IOCTL_SERIAL_SET_TIOCM:
1331 int sarg = *(int *)arg;
1333 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1334 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1335 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1336 if (sarg & CHR_TIOCM_CTS)
1338 if (sarg & CHR_TIOCM_CAR)
1340 if (sarg & CHR_TIOCM_DSR)
1342 if (sarg & CHR_TIOCM_RI)
1344 if (sarg & CHR_TIOCM_DTR)
1346 if (sarg & CHR_TIOCM_RTS)
1348 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1357 static void qemu_chr_close_tty(CharDriverState *chr)
1359 FDCharDriver *s = chr->opaque;
1363 fd = g_io_channel_unix_get_fd(s->fd_in);
1373 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1375 CharDriverState *chr;
1377 tty_serial_init(fd, 115200, 'N', 8, 1);
1378 chr = qemu_chr_open_fd(fd, fd);
1379 chr->chr_ioctl = tty_serial_ioctl;
1380 chr->chr_close = qemu_chr_close_tty;
1383 #endif /* __linux__ || __sun__ */
1385 #if defined(__linux__)
1387 #define HAVE_CHARDEV_PARPORT 1
1392 } ParallelCharDriver;
1394 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1396 if (s->mode != mode) {
1398 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1405 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1407 ParallelCharDriver *drv = chr->opaque;
1412 case CHR_IOCTL_PP_READ_DATA:
1413 if (ioctl(fd, PPRDATA, &b) < 0)
1415 *(uint8_t *)arg = b;
1417 case CHR_IOCTL_PP_WRITE_DATA:
1418 b = *(uint8_t *)arg;
1419 if (ioctl(fd, PPWDATA, &b) < 0)
1422 case CHR_IOCTL_PP_READ_CONTROL:
1423 if (ioctl(fd, PPRCONTROL, &b) < 0)
1425 /* Linux gives only the lowest bits, and no way to know data
1426 direction! For better compatibility set the fixed upper
1428 *(uint8_t *)arg = b | 0xc0;
1430 case CHR_IOCTL_PP_WRITE_CONTROL:
1431 b = *(uint8_t *)arg;
1432 if (ioctl(fd, PPWCONTROL, &b) < 0)
1435 case CHR_IOCTL_PP_READ_STATUS:
1436 if (ioctl(fd, PPRSTATUS, &b) < 0)
1438 *(uint8_t *)arg = b;
1440 case CHR_IOCTL_PP_DATA_DIR:
1441 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1444 case CHR_IOCTL_PP_EPP_READ_ADDR:
1445 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1446 struct ParallelIOArg *parg = arg;
1447 int n = read(fd, parg->buffer, parg->count);
1448 if (n != parg->count) {
1453 case CHR_IOCTL_PP_EPP_READ:
1454 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1455 struct ParallelIOArg *parg = arg;
1456 int n = read(fd, parg->buffer, parg->count);
1457 if (n != parg->count) {
1462 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1463 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1464 struct ParallelIOArg *parg = arg;
1465 int n = write(fd, parg->buffer, parg->count);
1466 if (n != parg->count) {
1471 case CHR_IOCTL_PP_EPP_WRITE:
1472 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1473 struct ParallelIOArg *parg = arg;
1474 int n = write(fd, parg->buffer, parg->count);
1475 if (n != parg->count) {
1486 static void pp_close(CharDriverState *chr)
1488 ParallelCharDriver *drv = chr->opaque;
1491 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1492 ioctl(fd, PPRELEASE);
1495 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1498 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1500 CharDriverState *chr;
1501 ParallelCharDriver *drv;
1503 if (ioctl(fd, PPCLAIM) < 0) {
1508 drv = g_malloc0(sizeof(ParallelCharDriver));
1510 drv->mode = IEEE1284_MODE_COMPAT;
1512 chr = g_malloc0(sizeof(CharDriverState));
1513 chr->chr_write = null_chr_write;
1514 chr->chr_ioctl = pp_ioctl;
1515 chr->chr_close = pp_close;
1520 #endif /* __linux__ */
1522 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1524 #define HAVE_CHARDEV_PARPORT 1
1526 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1528 int fd = (int)(intptr_t)chr->opaque;
1532 case CHR_IOCTL_PP_READ_DATA:
1533 if (ioctl(fd, PPIGDATA, &b) < 0)
1535 *(uint8_t *)arg = b;
1537 case CHR_IOCTL_PP_WRITE_DATA:
1538 b = *(uint8_t *)arg;
1539 if (ioctl(fd, PPISDATA, &b) < 0)
1542 case CHR_IOCTL_PP_READ_CONTROL:
1543 if (ioctl(fd, PPIGCTRL, &b) < 0)
1545 *(uint8_t *)arg = b;
1547 case CHR_IOCTL_PP_WRITE_CONTROL:
1548 b = *(uint8_t *)arg;
1549 if (ioctl(fd, PPISCTRL, &b) < 0)
1552 case CHR_IOCTL_PP_READ_STATUS:
1553 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1555 *(uint8_t *)arg = b;
1563 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1565 CharDriverState *chr;
1567 chr = g_malloc0(sizeof(CharDriverState));
1568 chr->opaque = (void *)(intptr_t)fd;
1569 chr->chr_write = null_chr_write;
1570 chr->chr_ioctl = pp_ioctl;
1571 chr->explicit_be_open = true;
1580 HANDLE hcom, hrecv, hsend;
1581 OVERLAPPED orecv, osend;
1588 HANDLE hInputReadyEvent;
1589 HANDLE hInputDoneEvent;
1590 HANDLE hInputThread;
1591 uint8_t win_stdio_buf;
1592 } WinStdioCharState;
1594 #define NSENDBUF 2048
1595 #define NRECVBUF 2048
1596 #define MAXCONNECT 1
1597 #define NTIMEOUT 5000
1599 static int win_chr_poll(void *opaque);
1600 static int win_chr_pipe_poll(void *opaque);
1602 static void win_chr_close(CharDriverState *chr)
1604 WinCharState *s = chr->opaque;
1607 CloseHandle(s->hsend);
1611 CloseHandle(s->hrecv);
1615 CloseHandle(s->hcom);
1619 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1621 qemu_del_polling_cb(win_chr_poll, chr);
1623 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1626 static int win_chr_init(CharDriverState *chr, const char *filename)
1628 WinCharState *s = chr->opaque;
1630 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1635 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1637 fprintf(stderr, "Failed CreateEvent\n");
1640 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1642 fprintf(stderr, "Failed CreateEvent\n");
1646 s->hcom = CreateFile(filename,
1647 GENERIC_READ|GENERIC_WRITE, 0, NULL,
1648 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1650 int open_flags = O_BINARY | O_RDWR;
1651 // TODO : FILE_FLAG_OVERLAPPED
1653 int ret = qemu_open(filename, open_flags, 0644);
1655 error_report("win_chr_init failed(%d) \n", ret);
1658 s->hcom = (HANDLE)_get_osfhandle(ret);
1661 if (s->hcom == INVALID_HANDLE_VALUE) {
1662 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1667 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1668 fprintf(stderr, "Failed SetupComm\n");
1672 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1673 size = sizeof(COMMCONFIG);
1674 GetDefaultCommConfig(filename, &comcfg, &size);
1675 comcfg.dcb.DCBlength = sizeof(DCB);
1676 CommConfigDialog(filename, NULL, &comcfg);
1678 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1679 fprintf(stderr, "Failed SetCommState\n");
1683 if (!SetCommMask(s->hcom, EV_ERR)) {
1684 fprintf(stderr, "Failed SetCommMask\n");
1688 cto.ReadIntervalTimeout = MAXDWORD;
1689 if (!SetCommTimeouts(s->hcom, &cto)) {
1690 fprintf(stderr, "Failed SetCommTimeouts\n");
1694 if (!ClearCommError(s->hcom, &err, &comstat)) {
1695 fprintf(stderr, "Failed ClearCommError\n");
1698 qemu_add_polling_cb(win_chr_poll, chr);
1706 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1708 WinCharState *s = chr->opaque;
1709 DWORD len, ret, size, err;
1712 ZeroMemory(&s->osend, sizeof(s->osend));
1713 s->osend.hEvent = s->hsend;
1716 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1718 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1720 err = GetLastError();
1721 if (err == ERROR_IO_PENDING) {
1722 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1740 static int win_chr_read_poll(CharDriverState *chr)
1742 WinCharState *s = chr->opaque;
1744 s->max_size = qemu_chr_be_can_write(chr);
1748 static void win_chr_readfile(CharDriverState *chr)
1750 WinCharState *s = chr->opaque;
1752 uint8_t buf[READ_BUF_LEN];
1755 ZeroMemory(&s->orecv, sizeof(s->orecv));
1756 s->orecv.hEvent = s->hrecv;
1757 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1759 err = GetLastError();
1760 if (err == ERROR_IO_PENDING) {
1761 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1766 qemu_chr_be_write(chr, buf, size);
1770 static void win_chr_read(CharDriverState *chr)
1772 WinCharState *s = chr->opaque;
1774 if (s->len > s->max_size)
1775 s->len = s->max_size;
1779 win_chr_readfile(chr);
1782 static int win_chr_poll(void *opaque)
1784 CharDriverState *chr = opaque;
1785 WinCharState *s = chr->opaque;
1789 ClearCommError(s->hcom, &comerr, &status);
1790 if (status.cbInQue > 0) {
1791 s->len = status.cbInQue;
1792 win_chr_read_poll(chr);
1799 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1801 CharDriverState *chr;
1804 chr = g_malloc0(sizeof(CharDriverState));
1805 s = g_malloc0(sizeof(WinCharState));
1807 chr->chr_write = win_chr_write;
1808 chr->chr_close = win_chr_close;
1810 if (win_chr_init(chr, filename) < 0) {
1818 static int win_chr_pipe_poll(void *opaque)
1820 CharDriverState *chr = opaque;
1821 WinCharState *s = chr->opaque;
1824 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1827 win_chr_read_poll(chr);
1834 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1836 WinCharState *s = chr->opaque;
1844 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1846 fprintf(stderr, "Failed CreateEvent\n");
1849 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1851 fprintf(stderr, "Failed CreateEvent\n");
1855 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1856 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1857 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1859 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1860 if (s->hcom == INVALID_HANDLE_VALUE) {
1861 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1866 ZeroMemory(&ov, sizeof(ov));
1867 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1868 ret = ConnectNamedPipe(s->hcom, &ov);
1870 fprintf(stderr, "Failed ConnectNamedPipe\n");
1874 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1876 fprintf(stderr, "Failed GetOverlappedResult\n");
1878 CloseHandle(ov.hEvent);
1885 CloseHandle(ov.hEvent);
1888 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1897 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
1899 const char *filename = opts->device;
1900 CharDriverState *chr;
1903 chr = g_malloc0(sizeof(CharDriverState));
1904 s = g_malloc0(sizeof(WinCharState));
1906 chr->chr_write = win_chr_write;
1907 chr->chr_close = win_chr_close;
1909 if (win_chr_pipe_init(chr, filename) < 0) {
1917 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1919 CharDriverState *chr;
1922 chr = g_malloc0(sizeof(CharDriverState));
1923 s = g_malloc0(sizeof(WinCharState));
1926 chr->chr_write = win_chr_write;
1930 static CharDriverState *qemu_chr_open_win_con(void)
1932 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1935 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1937 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1944 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
1954 static void win_stdio_wait_func(void *opaque)
1956 CharDriverState *chr = opaque;
1957 WinStdioCharState *stdio = chr->opaque;
1958 INPUT_RECORD buf[4];
1963 ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
1967 /* Avoid error storm */
1968 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
1972 for (i = 0; i < dwSize; i++) {
1973 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
1975 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
1977 if (kev->uChar.AsciiChar != 0) {
1978 for (j = 0; j < kev->wRepeatCount; j++) {
1979 if (qemu_chr_be_can_write(chr)) {
1980 uint8_t c = kev->uChar.AsciiChar;
1981 qemu_chr_be_write(chr, &c, 1);
1989 static DWORD WINAPI win_stdio_thread(LPVOID param)
1991 CharDriverState *chr = param;
1992 WinStdioCharState *stdio = chr->opaque;
1998 /* Wait for one byte */
1999 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2001 /* Exit in case of error, continue if nothing read */
2009 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2010 if (stdio->win_stdio_buf == '\r') {
2014 /* Signal the main thread and wait until the byte was eaten */
2015 if (!SetEvent(stdio->hInputReadyEvent)) {
2018 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2024 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2028 static void win_stdio_thread_wait_func(void *opaque)
2030 CharDriverState *chr = opaque;
2031 WinStdioCharState *stdio = chr->opaque;
2033 if (qemu_chr_be_can_write(chr)) {
2034 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2037 SetEvent(stdio->hInputDoneEvent);
2040 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2042 WinStdioCharState *stdio = chr->opaque;
2045 GetConsoleMode(stdio->hStdIn, &dwMode);
2048 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2050 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2054 static void win_stdio_close(CharDriverState *chr)
2056 WinStdioCharState *stdio = chr->opaque;
2058 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2059 CloseHandle(stdio->hInputReadyEvent);
2061 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2062 CloseHandle(stdio->hInputDoneEvent);
2064 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2065 TerminateThread(stdio->hInputThread, 0);
2068 g_free(chr->opaque);
2072 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2074 CharDriverState *chr;
2075 WinStdioCharState *stdio;
2079 chr = g_malloc0(sizeof(CharDriverState));
2080 stdio = g_malloc0(sizeof(WinStdioCharState));
2082 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2083 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2084 fprintf(stderr, "cannot open stdio: invalid handle\n");
2088 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2090 chr->opaque = stdio;
2091 chr->chr_write = win_stdio_write;
2092 chr->chr_close = win_stdio_close;
2095 if (qemu_add_wait_object(stdio->hStdIn,
2096 win_stdio_wait_func, chr)) {
2097 fprintf(stderr, "qemu_add_wait_object: failed\n");
2102 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2103 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2104 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2107 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2108 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2109 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2110 fprintf(stderr, "cannot create stdio thread or event\n");
2113 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2114 win_stdio_thread_wait_func, chr)) {
2115 fprintf(stderr, "qemu_add_wait_object: failed\n");
2119 dwMode |= ENABLE_LINE_INPUT;
2122 /* set the terminal in raw mode */
2123 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2124 dwMode |= ENABLE_PROCESSED_INPUT;
2127 SetConsoleMode(stdio->hStdIn, dwMode);
2129 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2130 qemu_chr_fe_set_echo(chr, false);
2134 #endif /* !_WIN32 */
2137 /***********************************************************/
2138 /* UDP Net console */
2144 uint8_t buf[READ_BUF_LEN];
2150 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2152 NetCharDriver *s = chr->opaque;
2153 gsize bytes_written;
2156 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2157 if (status == G_IO_STATUS_EOF) {
2159 } else if (status != G_IO_STATUS_NORMAL) {
2163 return bytes_written;
2166 static int udp_chr_read_poll(void *opaque)
2168 CharDriverState *chr = opaque;
2169 NetCharDriver *s = chr->opaque;
2171 s->max_size = qemu_chr_be_can_write(chr);
2173 /* If there were any stray characters in the queue process them
2176 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2177 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2179 s->max_size = qemu_chr_be_can_write(chr);
2184 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2186 CharDriverState *chr = opaque;
2187 NetCharDriver *s = chr->opaque;
2188 gsize bytes_read = 0;
2191 if (s->max_size == 0) {
2194 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2196 s->bufcnt = bytes_read;
2197 s->bufptr = s->bufcnt;
2198 if (status != G_IO_STATUS_NORMAL) {
2200 io_remove_watch_poll(s->tag);
2207 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2208 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2210 s->max_size = qemu_chr_be_can_write(chr);
2216 static void udp_chr_update_read_handler(CharDriverState *chr)
2218 NetCharDriver *s = chr->opaque;
2221 io_remove_watch_poll(s->tag);
2226 s->tag = io_add_watch_poll(s->chan, udp_chr_read_poll, udp_chr_read, chr);
2230 static void udp_chr_close(CharDriverState *chr)
2232 NetCharDriver *s = chr->opaque;
2234 io_remove_watch_poll(s->tag);
2238 g_io_channel_unref(s->chan);
2242 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2245 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2247 CharDriverState *chr = NULL;
2248 NetCharDriver *s = NULL;
2250 chr = g_malloc0(sizeof(CharDriverState));
2251 s = g_malloc0(sizeof(NetCharDriver));
2254 s->chan = io_channel_from_socket(s->fd);
2258 chr->chr_write = udp_chr_write;
2259 chr->chr_update_read_handler = udp_chr_update_read_handler;
2260 chr->chr_close = udp_chr_close;
2261 /* be isn't opened until we get a connection */
2262 chr->explicit_be_open = true;
2266 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2268 Error *local_err = NULL;
2271 fd = inet_dgram_opts(opts, &local_err);
2275 return qemu_chr_open_udp_fd(fd);
2278 /***********************************************************/
2279 /* TCP Net console */
2283 GIOChannel *chan, *listen_chan;
2284 guint tag, listen_tag;
2294 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2296 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2298 TCPCharDriver *s = chr->opaque;
2300 return io_channel_send(s->chan, buf, len);
2302 /* XXX: indicate an error ? */
2307 static int tcp_chr_read_poll(void *opaque)
2309 CharDriverState *chr = opaque;
2310 TCPCharDriver *s = chr->opaque;
2313 s->max_size = qemu_chr_be_can_write(chr);
2318 #define IAC_BREAK 243
2319 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2321 uint8_t *buf, int *size)
2323 /* Handle any telnet client's basic IAC options to satisfy char by
2324 * char mode with no echo. All IAC options will be removed from
2325 * the buf and the do_telnetopt variable will be used to track the
2326 * state of the width of the IAC information.
2328 * IAC commands come in sets of 3 bytes with the exception of the
2329 * "IAC BREAK" command and the double IAC.
2335 for (i = 0; i < *size; i++) {
2336 if (s->do_telnetopt > 1) {
2337 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2338 /* Double IAC means send an IAC */
2342 s->do_telnetopt = 1;
2344 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2345 /* Handle IAC break commands by sending a serial break */
2346 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2351 if (s->do_telnetopt >= 4) {
2352 s->do_telnetopt = 1;
2355 if ((unsigned char)buf[i] == IAC) {
2356 s->do_telnetopt = 2;
2367 static int tcp_get_msgfd(CharDriverState *chr)
2369 TCPCharDriver *s = chr->opaque;
2376 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2378 TCPCharDriver *s = chr->opaque;
2379 struct cmsghdr *cmsg;
2381 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2384 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2385 cmsg->cmsg_level != SOL_SOCKET ||
2386 cmsg->cmsg_type != SCM_RIGHTS)
2389 fd = *((int *)CMSG_DATA(cmsg));
2393 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2396 #ifndef MSG_CMSG_CLOEXEC
2397 qemu_set_cloexec(fd);
2405 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2407 TCPCharDriver *s = chr->opaque;
2408 struct msghdr msg = { NULL, };
2409 struct iovec iov[1];
2411 struct cmsghdr cmsg;
2412 char control[CMSG_SPACE(sizeof(int))];
2417 iov[0].iov_base = buf;
2418 iov[0].iov_len = len;
2422 msg.msg_control = &msg_control;
2423 msg.msg_controllen = sizeof(msg_control);
2425 #ifdef MSG_CMSG_CLOEXEC
2426 flags |= MSG_CMSG_CLOEXEC;
2428 ret = recvmsg(s->fd, &msg, flags);
2429 if (ret > 0 && s->is_unix) {
2430 unix_process_msgfd(chr, &msg);
2436 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2438 TCPCharDriver *s = chr->opaque;
2439 return qemu_recv(s->fd, buf, len, 0);
2443 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2445 TCPCharDriver *s = chr->opaque;
2446 return g_io_create_watch(s->chan, cond);
2449 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2451 CharDriverState *chr = opaque;
2452 TCPCharDriver *s = chr->opaque;
2453 uint8_t buf[READ_BUF_LEN];
2456 if (!s->connected || s->max_size <= 0) {
2460 if (len > s->max_size)
2462 size = tcp_chr_recv(chr, (void *)buf, len);
2464 /* connection closed */
2466 if (s->listen_chan) {
2467 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2470 io_remove_watch_poll(s->tag);
2473 g_io_channel_unref(s->chan);
2477 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2478 } else if (size > 0) {
2479 if (s->do_telnetopt)
2480 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2482 qemu_chr_be_write(chr, buf, size);
2489 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2491 return qemu_chr_open_fd(eventfd, eventfd);
2495 static void tcp_chr_connect(void *opaque)
2497 CharDriverState *chr = opaque;
2498 TCPCharDriver *s = chr->opaque;
2502 s->tag = io_add_watch_poll(s->chan, tcp_chr_read_poll, tcp_chr_read, chr);
2504 qemu_chr_be_generic_open(chr);
2507 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2508 static void tcp_chr_telnet_init(int fd)
2511 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2512 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2513 send(fd, (char *)buf, 3, 0);
2514 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2515 send(fd, (char *)buf, 3, 0);
2516 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2517 send(fd, (char *)buf, 3, 0);
2518 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2519 send(fd, (char *)buf, 3, 0);
2522 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2524 TCPCharDriver *s = chr->opaque;
2528 qemu_set_nonblock(fd);
2530 socket_set_nodelay(fd);
2532 s->chan = io_channel_from_socket(fd);
2533 if (s->listen_tag) {
2534 g_source_remove(s->listen_tag);
2537 tcp_chr_connect(chr);
2542 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2544 CharDriverState *chr = opaque;
2545 TCPCharDriver *s = chr->opaque;
2546 struct sockaddr_in saddr;
2548 struct sockaddr_un uaddr;
2550 struct sockaddr *addr;
2557 len = sizeof(uaddr);
2558 addr = (struct sockaddr *)&uaddr;
2562 len = sizeof(saddr);
2563 addr = (struct sockaddr *)&saddr;
2565 fd = qemu_accept(s->listen_fd, addr, &len);
2566 if (fd < 0 && errno != EINTR) {
2569 } else if (fd >= 0) {
2570 if (s->do_telnetopt)
2571 tcp_chr_telnet_init(fd);
2575 if (tcp_chr_add_client(chr, fd) < 0)
2581 static void tcp_chr_close(CharDriverState *chr)
2583 TCPCharDriver *s = chr->opaque;
2586 io_remove_watch_poll(s->tag);
2590 g_io_channel_unref(s->chan);
2594 if (s->listen_fd >= 0) {
2595 if (s->listen_tag) {
2596 g_source_remove(s->listen_tag);
2599 if (s->listen_chan) {
2600 g_io_channel_unref(s->listen_chan);
2602 closesocket(s->listen_fd);
2605 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2608 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2609 bool is_listen, bool is_telnet,
2610 bool is_waitconnect,
2613 CharDriverState *chr = NULL;
2614 TCPCharDriver *s = NULL;
2615 char host[NI_MAXHOST], serv[NI_MAXSERV];
2616 const char *left = "", *right = "";
2617 struct sockaddr_storage ss;
2618 socklen_t ss_len = sizeof(ss);
2620 memset(&ss, 0, ss_len);
2621 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2622 error_setg(errp, "getsockname: %s", strerror(errno));
2626 chr = g_malloc0(sizeof(CharDriverState));
2627 s = g_malloc0(sizeof(TCPCharDriver));
2634 chr->filename = g_malloc(256);
2635 switch (ss.ss_family) {
2639 snprintf(chr->filename, 256, "unix:%s%s",
2640 ((struct sockaddr_un *)(&ss))->sun_path,
2641 is_listen ? ",server" : "");
2649 s->do_nodelay = do_nodelay;
2650 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2651 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2652 snprintf(chr->filename, 256, "%s:%s%s%s:%s%s",
2653 is_telnet ? "telnet" : "tcp",
2654 left, host, right, serv,
2655 is_listen ? ",server" : "");
2660 chr->chr_write = tcp_chr_write;
2661 chr->chr_close = tcp_chr_close;
2662 chr->get_msgfd = tcp_get_msgfd;
2663 chr->chr_add_client = tcp_chr_add_client;
2664 chr->chr_add_watch = tcp_chr_add_watch;
2665 /* be isn't opened until we get a connection */
2666 chr->explicit_be_open = true;
2670 s->listen_chan = io_channel_from_socket(s->listen_fd);
2671 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2673 s->do_telnetopt = 1;
2678 socket_set_nodelay(fd);
2679 s->chan = io_channel_from_socket(s->fd);
2680 tcp_chr_connect(chr);
2683 if (is_listen && is_waitconnect) {
2684 printf("QEMU waiting for connection on: %s\n",
2686 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2687 qemu_set_nonblock(s->listen_fd);
2692 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2694 CharDriverState *chr = NULL;
2695 Error *local_err = NULL;
2703 is_listen = qemu_opt_get_bool(opts, "server", 0);
2704 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2705 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2706 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2707 is_unix = qemu_opt_get(opts, "path") != NULL;
2713 fd = unix_listen_opts(opts, &local_err);
2715 fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2719 fd = inet_listen_opts(opts, 0, &local_err);
2721 fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2728 if (!is_waitconnect)
2729 qemu_set_nonblock(fd);
2731 chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2732 is_waitconnect, &local_err);
2733 if (error_is_set(&local_err)) {
2741 qerror_report_err(local_err);
2742 error_free(local_err);
2748 g_free(chr->opaque);
2754 /*********************************************************/
2755 /* Ring buffer chardev */
2762 } RingBufCharDriver;
2764 static size_t ringbuf_count(const CharDriverState *chr)
2766 const RingBufCharDriver *d = chr->opaque;
2768 return d->prod - d->cons;
2771 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2773 RingBufCharDriver *d = chr->opaque;
2776 if (!buf || (len < 0)) {
2780 for (i = 0; i < len; i++ ) {
2781 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2782 if (d->prod - d->cons > d->size) {
2783 d->cons = d->prod - d->size;
2790 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2792 RingBufCharDriver *d = chr->opaque;
2795 for (i = 0; i < len && d->cons != d->prod; i++) {
2796 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2802 static void ringbuf_chr_close(struct CharDriverState *chr)
2804 RingBufCharDriver *d = chr->opaque;
2811 static CharDriverState *qemu_chr_open_ringbuf(ChardevRingbuf *opts,
2814 CharDriverState *chr;
2815 RingBufCharDriver *d;
2817 chr = g_malloc0(sizeof(CharDriverState));
2818 d = g_malloc(sizeof(*d));
2820 d->size = opts->has_size ? opts->size : 65536;
2822 /* The size must be power of 2 */
2823 if (d->size & (d->size - 1)) {
2824 error_setg(errp, "size of ringbuf chardev must be power of two");
2830 d->cbuf = g_malloc0(d->size);
2833 chr->chr_write = ringbuf_chr_write;
2834 chr->chr_close = ringbuf_chr_close;
2844 static bool chr_is_ringbuf(const CharDriverState *chr)
2846 return chr->chr_write == ringbuf_chr_write;
2849 void qmp_ringbuf_write(const char *device, const char *data,
2850 bool has_format, enum DataFormat format,
2853 CharDriverState *chr;
2854 const uint8_t *write_data;
2858 chr = qemu_chr_find(device);
2860 error_setg(errp, "Device '%s' not found", device);
2864 if (!chr_is_ringbuf(chr)) {
2865 error_setg(errp,"%s is not a ringbuf device", device);
2869 if (has_format && (format == DATA_FORMAT_BASE64)) {
2870 write_data = g_base64_decode(data, &write_count);
2872 write_data = (uint8_t *)data;
2873 write_count = strlen(data);
2876 ret = ringbuf_chr_write(chr, write_data, write_count);
2878 if (write_data != (uint8_t *)data) {
2879 g_free((void *)write_data);
2883 error_setg(errp, "Failed to write to device %s", device);
2888 char *qmp_ringbuf_read(const char *device, int64_t size,
2889 bool has_format, enum DataFormat format,
2892 CharDriverState *chr;
2897 chr = qemu_chr_find(device);
2899 error_setg(errp, "Device '%s' not found", device);
2903 if (!chr_is_ringbuf(chr)) {
2904 error_setg(errp,"%s is not a ringbuf device", device);
2909 error_setg(errp, "size must be greater than zero");
2913 count = ringbuf_count(chr);
2914 size = size > count ? count : size;
2915 read_data = g_malloc(size + 1);
2917 ringbuf_chr_read(chr, read_data, size);
2919 if (has_format && (format == DATA_FORMAT_BASE64)) {
2920 data = g_base64_encode(read_data, size);
2924 * FIXME should read only complete, valid UTF-8 characters up
2925 * to @size bytes. Invalid sequences should be replaced by a
2926 * suitable replacement character. Except when (and only
2927 * when) ring buffer lost characters since last read, initial
2928 * continuation characters should be dropped.
2930 read_data[size] = 0;
2931 data = (char *)read_data;
2937 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2939 char host[65], port[33], width[8], height[8];
2943 Error *local_err = NULL;
2945 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
2946 if (error_is_set(&local_err)) {
2947 qerror_report_err(local_err);
2948 error_free(local_err);
2952 if (strstart(filename, "mon:", &p)) {
2954 qemu_opt_set(opts, "mux", "on");
2957 if (strcmp(filename, "null") == 0 ||
2958 strcmp(filename, "pty") == 0 ||
2959 strcmp(filename, "msmouse") == 0 ||
2960 strcmp(filename, "braille") == 0 ||
2961 strcmp(filename, "stdio") == 0) {
2962 qemu_opt_set(opts, "backend", filename);
2965 if (strstart(filename, "vc", &p)) {
2966 qemu_opt_set(opts, "backend", "vc");
2968 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2970 qemu_opt_set(opts, "width", width);
2971 qemu_opt_set(opts, "height", height);
2972 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2974 qemu_opt_set(opts, "cols", width);
2975 qemu_opt_set(opts, "rows", height);
2982 if (strcmp(filename, "con:") == 0) {
2983 qemu_opt_set(opts, "backend", "console");
2986 if (strstart(filename, "COM", NULL)) {
2987 qemu_opt_set(opts, "backend", "serial");
2988 qemu_opt_set(opts, "path", filename);
2991 if (strstart(filename, "file:", &p)) {
2992 qemu_opt_set(opts, "backend", "file");
2993 qemu_opt_set(opts, "path", p);
2996 if (strstart(filename, "pipe:", &p)) {
2997 qemu_opt_set(opts, "backend", "pipe");
2998 qemu_opt_set(opts, "path", p);
3001 if (strstart(filename, "tcp:", &p) ||
3002 strstart(filename, "telnet:", &p)) {
3003 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3005 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3008 qemu_opt_set(opts, "backend", "socket");
3009 qemu_opt_set(opts, "host", host);
3010 qemu_opt_set(opts, "port", port);
3011 if (p[pos] == ',') {
3012 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3015 if (strstart(filename, "telnet:", &p))
3016 qemu_opt_set(opts, "telnet", "on");
3019 if (strstart(filename, "udp:", &p)) {
3020 qemu_opt_set(opts, "backend", "udp");
3021 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3023 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3027 qemu_opt_set(opts, "host", host);
3028 qemu_opt_set(opts, "port", port);
3029 if (p[pos] == '@') {
3031 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3033 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3037 qemu_opt_set(opts, "localaddr", host);
3038 qemu_opt_set(opts, "localport", port);
3042 if (strstart(filename, "unix:", &p)) {
3043 qemu_opt_set(opts, "backend", "socket");
3044 if (qemu_opts_do_parse(opts, p, "path") != 0)
3048 if (strstart(filename, "/dev/parport", NULL) ||
3049 strstart(filename, "/dev/ppi", NULL)) {
3050 qemu_opt_set(opts, "backend", "parport");
3051 qemu_opt_set(opts, "path", filename);
3054 if (strstart(filename, "/dev/", NULL)) {
3055 qemu_opt_set(opts, "backend", "tty");
3056 qemu_opt_set(opts, "path", filename);
3061 qemu_opts_del(opts);
3065 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3068 const char *path = qemu_opt_get(opts, "path");
3071 error_setg(errp, "chardev: file: no filename given");
3074 backend->file = g_new0(ChardevFile, 1);
3075 backend->file->out = g_strdup(path);
3078 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3081 backend->stdio = g_new0(ChardevStdio, 1);
3082 backend->stdio->has_signal = true;
3083 backend->stdio->signal =
3084 qemu_opt_get_bool(opts, "signal", display_type != DT_NOGRAPHIC);
3087 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3090 const char *device = qemu_opt_get(opts, "path");
3092 if (device == NULL) {
3093 error_setg(errp, "chardev: serial/tty: no device path given");
3096 backend->serial = g_new0(ChardevHostdev, 1);
3097 backend->serial->device = g_strdup(device);
3100 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3103 const char *device = qemu_opt_get(opts, "path");
3105 if (device == NULL) {
3106 error_setg(errp, "chardev: parallel: no device path given");
3109 backend->parallel = g_new0(ChardevHostdev, 1);
3110 backend->parallel->device = g_strdup(device);
3113 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3116 const char *device = qemu_opt_get(opts, "path");
3118 if (device == NULL) {
3119 error_setg(errp, "chardev: pipe: no device path given");
3122 backend->pipe = g_new0(ChardevHostdev, 1);
3123 backend->pipe->device = g_strdup(device);
3126 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3131 backend->memory = g_new0(ChardevRingbuf, 1);
3133 val = qemu_opt_get_number(opts, "size", 0);
3135 backend->memory->has_size = true;
3136 backend->memory->size = val;
3140 typedef struct CharDriver {
3143 CharDriverState *(*open)(QemuOpts *opts);
3144 /* new, qapi-based */
3146 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3149 static GSList *backends;
3151 void register_char_driver(const char *name, CharDriverState *(*open)(QemuOpts *))
3155 s = g_malloc0(sizeof(*s));
3156 s->name = g_strdup(name);
3159 backends = g_slist_append(backends, s);
3162 void register_char_driver_qapi(const char *name, int kind,
3163 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3167 s = g_malloc0(sizeof(*s));
3168 s->name = g_strdup(name);
3172 backends = g_slist_append(backends, s);
3175 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3176 void (*init)(struct CharDriverState *s),
3180 CharDriverState *chr;
3183 if (qemu_opts_id(opts) == NULL) {
3184 error_setg(errp, "chardev: no id specified");
3188 if (qemu_opt_get(opts, "backend") == NULL) {
3189 error_setg(errp, "chardev: \"%s\" missing backend",
3190 qemu_opts_id(opts));
3193 for (i = backends; i; i = i->next) {
3196 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3201 error_setg(errp, "chardev: backend \"%s\" not found",
3202 qemu_opt_get(opts, "backend"));
3207 /* using new, qapi init */
3208 ChardevBackend *backend = g_new0(ChardevBackend, 1);
3209 ChardevReturn *ret = NULL;
3210 const char *id = qemu_opts_id(opts);
3211 const char *bid = NULL;
3213 if (qemu_opt_get_bool(opts, "mux", 0)) {
3214 bid = g_strdup_printf("%s-base", id);
3218 backend->kind = cd->kind;
3220 cd->parse(opts, backend, errp);
3221 if (error_is_set(errp)) {
3225 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3226 if (error_is_set(errp)) {
3231 qapi_free_ChardevBackend(backend);
3232 qapi_free_ChardevReturn(ret);
3233 backend = g_new0(ChardevBackend, 1);
3234 backend->mux = g_new0(ChardevMux, 1);
3235 backend->kind = CHARDEV_BACKEND_KIND_MUX;
3236 backend->mux->chardev = g_strdup(bid);
3237 ret = qmp_chardev_add(id, backend, errp);
3238 if (error_is_set(errp)) {
3243 chr = qemu_chr_find(id);
3246 qapi_free_ChardevBackend(backend);
3247 qapi_free_ChardevReturn(ret);
3251 chr = cd->open(opts);
3253 error_setg(errp, "chardev: opening backend \"%s\" failed",
3254 qemu_opt_get(opts, "backend"));
3259 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3261 /* if we didn't create the chardev via qmp_chardev_add, we
3262 * need to send the OPENED event here
3264 if (!chr->explicit_be_open) {
3265 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
3267 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3269 if (qemu_opt_get_bool(opts, "mux", 0)) {
3270 CharDriverState *base = chr;
3271 int len = strlen(qemu_opts_id(opts)) + 6;
3272 base->label = g_malloc(len);
3273 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3274 chr = qemu_chr_open_mux(base);
3275 chr->filename = base->filename;
3276 chr->avail_connections = MAX_MUX;
3277 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3279 chr->avail_connections = 1;
3281 chr->label = g_strdup(qemu_opts_id(opts));
3286 qemu_opts_del(opts);
3290 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3293 CharDriverState *chr;
3297 if (strstart(filename, "chardev:", &p)) {
3298 return qemu_chr_find(p);
3301 opts = qemu_chr_parse_compat(label, filename);
3305 chr = qemu_chr_new_from_opts(opts, init, &err);
3306 if (error_is_set(&err)) {
3307 fprintf(stderr, "%s\n", error_get_pretty(err));
3310 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3311 qemu_chr_fe_claim_no_fail(chr);
3312 monitor_init(chr, MONITOR_USE_READLINE);
3317 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3319 if (chr->chr_set_echo) {
3320 chr->chr_set_echo(chr, echo);
3324 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3326 if (chr->fe_open == fe_open) {
3329 chr->fe_open = fe_open;
3330 if (chr->chr_set_fe_open) {
3331 chr->chr_set_fe_open(chr, fe_open);
3335 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3336 GIOFunc func, void *user_data)
3341 if (s->chr_add_watch == NULL) {
3345 src = s->chr_add_watch(s, cond);
3346 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3347 tag = g_source_attach(src, NULL);
3348 g_source_unref(src);
3353 int qemu_chr_fe_claim(CharDriverState *s)
3355 if (s->avail_connections < 1) {
3358 s->avail_connections--;
3362 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3364 if (qemu_chr_fe_claim(s) != 0) {
3365 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3366 __func__, s->label);
3371 void qemu_chr_fe_release(CharDriverState *s)
3373 s->avail_connections++;
3376 void qemu_chr_delete(CharDriverState *chr)
3378 QTAILQ_REMOVE(&chardevs, chr, next);
3379 if (chr->chr_close) {
3380 chr->chr_close(chr);
3382 g_free(chr->filename);
3385 qemu_opts_del(chr->opts);
3390 ChardevInfoList *qmp_query_chardev(Error **errp)
3392 ChardevInfoList *chr_list = NULL;
3393 CharDriverState *chr;
3395 QTAILQ_FOREACH(chr, &chardevs, next) {
3396 ChardevInfoList *info = g_malloc0(sizeof(*info));
3397 info->value = g_malloc0(sizeof(*info->value));
3398 info->value->label = g_strdup(chr->label);
3399 info->value->filename = g_strdup(chr->filename);
3401 info->next = chr_list;
3408 CharDriverState *qemu_chr_find(const char *name)
3410 CharDriverState *chr;
3412 QTAILQ_FOREACH(chr, &chardevs, next) {
3413 if (strcmp(chr->label, name) != 0)
3420 /* Get a character (serial) device interface. */
3421 CharDriverState *qemu_char_get_next_serial(void)
3423 static int next_serial;
3424 CharDriverState *chr;
3426 /* FIXME: This function needs to go away: use chardev properties! */
3428 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3429 chr = serial_hds[next_serial++];
3430 qemu_chr_fe_claim_no_fail(chr);
3436 QemuOptsList qemu_chardev_opts = {
3438 .implied_opt_name = "backend",
3439 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3443 .type = QEMU_OPT_STRING,
3446 .type = QEMU_OPT_STRING,
3449 .type = QEMU_OPT_STRING,
3452 .type = QEMU_OPT_STRING,
3454 .name = "localaddr",
3455 .type = QEMU_OPT_STRING,
3457 .name = "localport",
3458 .type = QEMU_OPT_STRING,
3461 .type = QEMU_OPT_NUMBER,
3464 .type = QEMU_OPT_BOOL,
3467 .type = QEMU_OPT_BOOL,
3470 .type = QEMU_OPT_BOOL,
3473 .type = QEMU_OPT_BOOL,
3476 .type = QEMU_OPT_BOOL,
3479 .type = QEMU_OPT_BOOL,
3482 .type = QEMU_OPT_NUMBER,
3485 .type = QEMU_OPT_NUMBER,
3488 .type = QEMU_OPT_NUMBER,
3491 .type = QEMU_OPT_NUMBER,
3494 .type = QEMU_OPT_BOOL,
3497 .type = QEMU_OPT_BOOL,
3500 .type = QEMU_OPT_STRING,
3503 .type = QEMU_OPT_NUMBER,
3506 .type = QEMU_OPT_SIZE,
3508 { /* end of list */ }
3514 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3519 error_setg(errp, "input file not supported");
3524 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3525 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3527 int open_flags, ret;
3529 open_flags = O_BINARY | O_RDWR | O_CREAT | O_TRUNC;
3530 ret = qemu_open(file->out, open_flags, 0644);
3532 error_report("qemu_chr_open_win_file_out failed(%d) \n", ret);
3535 out = (HANDLE)_get_osfhandle(ret);
3537 if (out == INVALID_HANDLE_VALUE) {
3538 error_setg(errp, "open %s failed", file->out);
3542 return qemu_chr_open_win_file(out);
3545 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3548 return qemu_chr_open_win_path(serial->device);
3551 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3554 error_setg(errp, "character device backend type 'parallel' not supported");
3560 static int qmp_chardev_open_file_source(char *src, int flags,
3565 TFR(fd = qemu_open(src, flags, 0666));
3567 error_setg(errp, "open %s: %s", src, strerror(errno));
3572 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3574 int flags, in = -1, out = -1;
3576 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3577 out = qmp_chardev_open_file_source(file->out, flags, errp);
3578 if (error_is_set(errp)) {
3584 in = qmp_chardev_open_file_source(file->in, flags, errp);
3585 if (error_is_set(errp)) {
3591 return qemu_chr_open_fd(in, out);
3594 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3597 #ifdef HAVE_CHARDEV_TTY
3600 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3601 if (error_is_set(errp)) {
3604 qemu_set_nonblock(fd);
3605 return qemu_chr_open_tty_fd(fd);
3607 error_setg(errp, "character device backend type 'serial' not supported");
3612 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3615 #ifdef HAVE_CHARDEV_PARPORT
3618 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3619 if (error_is_set(errp)) {
3622 return qemu_chr_open_pp_fd(fd);
3624 error_setg(errp, "character device backend type 'parallel' not supported");
3631 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3634 SocketAddress *addr = sock->addr;
3635 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3636 bool is_listen = sock->has_server ? sock->server : true;
3637 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3638 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3642 fd = socket_listen(addr, errp);
3644 fd = socket_connect(addr, errp, NULL, NULL);
3646 if (error_is_set(errp)) {
3649 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3650 is_telnet, is_waitconnect, errp);
3653 static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
3658 fd = socket_dgram(udp->remote, udp->local, errp);
3659 if (error_is_set(errp)) {
3662 return qemu_chr_open_udp_fd(fd);
3665 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3668 ChardevReturn *ret = g_new0(ChardevReturn, 1);
3669 CharDriverState *base, *chr = NULL;
3671 chr = qemu_chr_find(id);
3673 error_setg(errp, "Chardev '%s' already exists", id);
3678 switch (backend->kind) {
3679 case CHARDEV_BACKEND_KIND_FILE:
3680 chr = qmp_chardev_open_file(backend->file, errp);
3682 case CHARDEV_BACKEND_KIND_SERIAL:
3683 chr = qmp_chardev_open_serial(backend->serial, errp);
3685 case CHARDEV_BACKEND_KIND_PARALLEL:
3686 chr = qmp_chardev_open_parallel(backend->parallel, errp);
3688 case CHARDEV_BACKEND_KIND_PIPE:
3689 chr = qemu_chr_open_pipe(backend->pipe);
3691 case CHARDEV_BACKEND_KIND_SOCKET:
3692 chr = qmp_chardev_open_socket(backend->socket, errp);
3694 case CHARDEV_BACKEND_KIND_UDP:
3695 chr = qmp_chardev_open_udp(backend->udp, errp);
3697 #ifdef HAVE_CHARDEV_TTY
3698 case CHARDEV_BACKEND_KIND_PTY:
3699 chr = qemu_chr_open_pty(id, ret);
3702 case CHARDEV_BACKEND_KIND_NULL:
3703 chr = qemu_chr_open_null();
3705 case CHARDEV_BACKEND_KIND_MUX:
3706 base = qemu_chr_find(backend->mux->chardev);
3708 error_setg(errp, "mux: base chardev %s not found",
3709 backend->mux->chardev);
3712 chr = qemu_chr_open_mux(base);
3714 case CHARDEV_BACKEND_KIND_MSMOUSE:
3715 chr = qemu_chr_open_msmouse();
3717 #ifdef CONFIG_BRLAPI
3718 case CHARDEV_BACKEND_KIND_BRAILLE:
3719 chr = chr_baum_init();
3722 case CHARDEV_BACKEND_KIND_STDIO:
3723 chr = qemu_chr_open_stdio(backend->stdio);
3726 case CHARDEV_BACKEND_KIND_CONSOLE:
3727 chr = qemu_chr_open_win_con();
3731 case CHARDEV_BACKEND_KIND_SPICEVMC:
3732 chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
3734 case CHARDEV_BACKEND_KIND_SPICEPORT:
3735 chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
3738 case CHARDEV_BACKEND_KIND_VC:
3739 chr = vc_init(backend->vc);
3741 case CHARDEV_BACKEND_KIND_MEMORY:
3742 chr = qemu_chr_open_ringbuf(backend->memory, errp);
3745 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3749 if (chr == NULL && !error_is_set(errp)) {
3750 error_setg(errp, "Failed to create chardev");
3753 chr->label = g_strdup(id);
3754 chr->avail_connections =
3755 (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
3756 if (!chr->filename) {
3757 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
3759 if (!chr->explicit_be_open) {
3760 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
3762 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3770 void qmp_chardev_remove(const char *id, Error **errp)
3772 CharDriverState *chr;
3774 chr = qemu_chr_find(id);
3776 error_setg(errp, "Chardev '%s' not found", id);
3779 if (chr->chr_can_read || chr->chr_read ||
3780 chr->chr_event || chr->handler_opaque) {
3781 error_setg(errp, "Chardev '%s' is busy", id);
3784 qemu_chr_delete(chr);
3787 static void register_types(void)
3789 register_char_driver_qapi("null", CHARDEV_BACKEND_KIND_NULL, NULL);
3790 register_char_driver("socket", qemu_chr_open_socket);
3791 register_char_driver("udp", qemu_chr_open_udp);
3792 register_char_driver_qapi("memory", CHARDEV_BACKEND_KIND_MEMORY,
3793 qemu_chr_parse_ringbuf);
3794 register_char_driver_qapi("file", CHARDEV_BACKEND_KIND_FILE,
3795 qemu_chr_parse_file_out);
3796 register_char_driver_qapi("stdio", CHARDEV_BACKEND_KIND_STDIO,
3797 qemu_chr_parse_stdio);
3798 register_char_driver_qapi("serial", CHARDEV_BACKEND_KIND_SERIAL,
3799 qemu_chr_parse_serial);
3800 register_char_driver_qapi("tty", CHARDEV_BACKEND_KIND_SERIAL,
3801 qemu_chr_parse_serial);
3802 register_char_driver_qapi("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
3803 qemu_chr_parse_parallel);
3804 register_char_driver_qapi("parport", CHARDEV_BACKEND_KIND_PARALLEL,
3805 qemu_chr_parse_parallel);
3806 register_char_driver_qapi("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
3807 register_char_driver_qapi("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
3808 register_char_driver_qapi("pipe", CHARDEV_BACKEND_KIND_PIPE,
3809 qemu_chr_parse_pipe);
3812 type_init(register_types);