Add more boundary checking to sse3/4 parsing
[qemu/ar7.git] / qemu-char.c
blob9b69d928ef40cdd13b6725935868d1a95118cbac
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-common.h"
25 #include "net.h"
26 #include "monitor.h"
27 #include "console.h"
28 #include "sysemu.h"
29 #include "qemu-timer.h"
30 #include "qemu-char.h"
31 #include "hw/usb.h"
32 #include "hw/baum.h"
33 #include "hw/msmouse.h"
34 #include "qemu-objects.h"
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <signal.h>
39 #include <time.h>
40 #include <errno.h>
41 #include <sys/time.h>
42 #include <zlib.h>
44 #ifndef _WIN32
45 #include <sys/times.h>
46 #include <sys/wait.h>
47 #include <termios.h>
48 #include <sys/mman.h>
49 #include <sys/ioctl.h>
50 #include <sys/resource.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <net/if.h>
54 #include <arpa/inet.h>
55 #include <dirent.h>
56 #include <netdb.h>
57 #include <sys/select.h>
58 #ifdef CONFIG_BSD
59 #include <sys/stat.h>
60 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
61 #include <libutil.h>
62 #include <dev/ppbus/ppi.h>
63 #include <dev/ppbus/ppbconf.h>
64 #if defined(__GLIBC__)
65 #include <pty.h>
66 #endif
67 #elif defined(__DragonFly__)
68 #include <libutil.h>
69 #include <dev/misc/ppi/ppi.h>
70 #include <bus/ppbus/ppbconf.h>
71 #else
72 #include <util.h>
73 #endif
74 #else
75 #ifdef __linux__
76 #include <pty.h>
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
80 #endif
81 #ifdef __sun__
82 #include <sys/stat.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
92 #include <net/if.h>
93 #include <syslog.h>
94 #include <stropts.h>
95 #endif
96 #endif
97 #endif
99 #include "qemu_socket.h"
101 #define READ_BUF_LEN 4096
103 /***********************************************************/
104 /* character device */
106 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
107 QTAILQ_HEAD_INITIALIZER(chardevs);
109 static void qemu_chr_event(CharDriverState *s, int event)
111 /* Keep track if the char device is open */
112 switch (event) {
113 case CHR_EVENT_OPENED:
114 s->opened = 1;
115 break;
116 case CHR_EVENT_CLOSED:
117 s->opened = 0;
118 break;
121 if (!s->chr_event)
122 return;
123 s->chr_event(s->handler_opaque, event);
126 static void qemu_chr_generic_open_bh(void *opaque)
128 CharDriverState *s = opaque;
129 qemu_chr_event(s, CHR_EVENT_OPENED);
130 qemu_bh_delete(s->bh);
131 s->bh = NULL;
134 void qemu_chr_generic_open(CharDriverState *s)
136 if (s->bh == NULL) {
137 s->bh = qemu_bh_new(qemu_chr_generic_open_bh, s);
138 qemu_bh_schedule(s->bh);
142 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
144 return s->chr_write(s, buf, len);
147 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
149 if (!s->chr_ioctl)
150 return -ENOTSUP;
151 return s->chr_ioctl(s, cmd, arg);
154 int qemu_chr_can_read(CharDriverState *s)
156 if (!s->chr_can_read)
157 return 0;
158 return s->chr_can_read(s->handler_opaque);
161 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
163 s->chr_read(s->handler_opaque, buf, len);
166 int qemu_chr_get_msgfd(CharDriverState *s)
168 return s->get_msgfd ? s->get_msgfd(s) : -1;
171 void qemu_chr_accept_input(CharDriverState *s)
173 if (s->chr_accept_input)
174 s->chr_accept_input(s);
177 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
179 char buf[READ_BUF_LEN];
180 va_list ap;
181 va_start(ap, fmt);
182 vsnprintf(buf, sizeof(buf), fmt, ap);
183 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
184 va_end(ap);
187 void qemu_chr_send_event(CharDriverState *s, int event)
189 if (s->chr_send_event)
190 s->chr_send_event(s, event);
193 void qemu_chr_add_handlers(CharDriverState *s,
194 IOCanReadHandler *fd_can_read,
195 IOReadHandler *fd_read,
196 IOEventHandler *fd_event,
197 void *opaque)
199 s->chr_can_read = fd_can_read;
200 s->chr_read = fd_read;
201 s->chr_event = fd_event;
202 s->handler_opaque = opaque;
203 if (s->chr_update_read_handler)
204 s->chr_update_read_handler(s);
206 /* We're connecting to an already opened device, so let's make sure we
207 also get the open event */
208 if (s->opened) {
209 qemu_chr_generic_open(s);
213 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
215 return len;
218 static CharDriverState *qemu_chr_open_null(QemuOpts *opts)
220 CharDriverState *chr;
222 chr = qemu_mallocz(sizeof(CharDriverState));
223 chr->chr_write = null_chr_write;
224 return chr;
227 /* MUX driver for serial I/O splitting */
228 #define MAX_MUX 4
229 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
230 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
231 typedef struct {
232 IOCanReadHandler *chr_can_read[MAX_MUX];
233 IOReadHandler *chr_read[MAX_MUX];
234 IOEventHandler *chr_event[MAX_MUX];
235 void *ext_opaque[MAX_MUX];
236 CharDriverState *drv;
237 int focus;
238 int mux_cnt;
239 int term_got_escape;
240 int max_size;
241 /* Intermediate input buffer allows to catch escape sequences even if the
242 currently active device is not accepting any input - but only until it
243 is full as well. */
244 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
245 int prod[MAX_MUX];
246 int cons[MAX_MUX];
247 int timestamps;
248 int linestart;
249 int64_t timestamps_start;
250 } MuxDriver;
253 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
255 MuxDriver *d = chr->opaque;
256 int ret;
257 if (!d->timestamps) {
258 ret = d->drv->chr_write(d->drv, buf, len);
259 } else {
260 int i;
262 ret = 0;
263 for (i = 0; i < len; i++) {
264 if (d->linestart) {
265 char buf1[64];
266 int64_t ti;
267 int secs;
269 ti = qemu_get_clock(rt_clock);
270 if (d->timestamps_start == -1)
271 d->timestamps_start = ti;
272 ti -= d->timestamps_start;
273 secs = ti / 1000;
274 snprintf(buf1, sizeof(buf1),
275 "[%02d:%02d:%02d.%03d] ",
276 secs / 3600,
277 (secs / 60) % 60,
278 secs % 60,
279 (int)(ti % 1000));
280 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
281 d->linestart = 0;
283 ret += d->drv->chr_write(d->drv, buf+i, 1);
284 if (buf[i] == '\n') {
285 d->linestart = 1;
289 return ret;
292 static const char * const mux_help[] = {
293 "% h print this help\n\r",
294 "% x exit emulator\n\r",
295 "% s save disk data back to file (if -snapshot)\n\r",
296 "% t toggle console timestamps\n\r"
297 "% b send break (magic sysrq)\n\r",
298 "% c switch between console and monitor\n\r",
299 "% % sends %\n\r",
300 NULL
303 int term_escape_char = 0x01; /* ctrl-a is used for escape */
304 static void mux_print_help(CharDriverState *chr)
306 int i, j;
307 char ebuf[15] = "Escape-Char";
308 char cbuf[50] = "\n\r";
310 if (term_escape_char > 0 && term_escape_char < 26) {
311 snprintf(cbuf, sizeof(cbuf), "\n\r");
312 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
313 } else {
314 snprintf(cbuf, sizeof(cbuf),
315 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
316 term_escape_char);
318 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
319 for (i = 0; mux_help[i] != NULL; i++) {
320 for (j=0; mux_help[i][j] != '\0'; j++) {
321 if (mux_help[i][j] == '%')
322 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
323 else
324 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
329 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
331 if (d->chr_event[mux_nr])
332 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
335 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
337 if (d->term_got_escape) {
338 d->term_got_escape = 0;
339 if (ch == term_escape_char)
340 goto send_char;
341 switch(ch) {
342 case '?':
343 case 'h':
344 mux_print_help(chr);
345 break;
346 case 'x':
348 const char *term = "QEMU: Terminated\n\r";
349 chr->chr_write(chr,(uint8_t *)term,strlen(term));
350 exit(0);
351 break;
353 case 's':
354 bdrv_commit_all();
355 break;
356 case 'b':
357 qemu_chr_event(chr, CHR_EVENT_BREAK);
358 break;
359 case 'c':
360 /* Switch to the next registered device */
361 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
362 d->focus++;
363 if (d->focus >= d->mux_cnt)
364 d->focus = 0;
365 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
366 break;
367 case 't':
368 d->timestamps = !d->timestamps;
369 d->timestamps_start = -1;
370 d->linestart = 0;
371 break;
373 } else if (ch == term_escape_char) {
374 d->term_got_escape = 1;
375 } else {
376 send_char:
377 return 1;
379 return 0;
382 static void mux_chr_accept_input(CharDriverState *chr)
384 MuxDriver *d = chr->opaque;
385 int m = d->focus;
387 while (d->prod[m] != d->cons[m] &&
388 d->chr_can_read[m] &&
389 d->chr_can_read[m](d->ext_opaque[m])) {
390 d->chr_read[m](d->ext_opaque[m],
391 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
395 static int mux_chr_can_read(void *opaque)
397 CharDriverState *chr = opaque;
398 MuxDriver *d = chr->opaque;
399 int m = d->focus;
401 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
402 return 1;
403 if (d->chr_can_read[m])
404 return d->chr_can_read[m](d->ext_opaque[m]);
405 return 0;
408 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
410 CharDriverState *chr = opaque;
411 MuxDriver *d = chr->opaque;
412 int m = d->focus;
413 int i;
415 mux_chr_accept_input (opaque);
417 for(i = 0; i < size; i++)
418 if (mux_proc_byte(chr, d, buf[i])) {
419 if (d->prod[m] == d->cons[m] &&
420 d->chr_can_read[m] &&
421 d->chr_can_read[m](d->ext_opaque[m]))
422 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
423 else
424 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
428 static void mux_chr_event(void *opaque, int event)
430 CharDriverState *chr = opaque;
431 MuxDriver *d = chr->opaque;
432 int i;
434 /* Send the event to all registered listeners */
435 for (i = 0; i < d->mux_cnt; i++)
436 mux_chr_send_event(d, i, event);
439 static void mux_chr_update_read_handler(CharDriverState *chr)
441 MuxDriver *d = chr->opaque;
443 if (d->mux_cnt >= MAX_MUX) {
444 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
445 return;
447 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
448 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
449 d->chr_read[d->mux_cnt] = chr->chr_read;
450 d->chr_event[d->mux_cnt] = chr->chr_event;
451 /* Fix up the real driver with mux routines */
452 if (d->mux_cnt == 0) {
453 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
454 mux_chr_event, chr);
456 if (d->focus != -1) {
457 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
459 d->focus = d->mux_cnt;
460 d->mux_cnt++;
461 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
464 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
466 CharDriverState *chr;
467 MuxDriver *d;
469 chr = qemu_mallocz(sizeof(CharDriverState));
470 d = qemu_mallocz(sizeof(MuxDriver));
472 chr->opaque = d;
473 d->drv = drv;
474 d->focus = -1;
475 chr->chr_write = mux_chr_write;
476 chr->chr_update_read_handler = mux_chr_update_read_handler;
477 chr->chr_accept_input = mux_chr_accept_input;
479 /* Muxes are always open on creation */
480 qemu_chr_generic_open(chr);
482 return chr;
486 #ifdef _WIN32
487 int send_all(int fd, const void *buf, int len1)
489 int ret, len;
491 len = len1;
492 while (len > 0) {
493 ret = send(fd, buf, len, 0);
494 if (ret < 0) {
495 errno = WSAGetLastError();
496 if (errno != WSAEWOULDBLOCK) {
497 return -1;
499 } else if (ret == 0) {
500 break;
501 } else {
502 buf += ret;
503 len -= ret;
506 return len1 - len;
509 #else
511 static int unix_write(int fd, const uint8_t *buf, int len1)
513 int ret, len;
515 len = len1;
516 while (len > 0) {
517 ret = write(fd, buf, len);
518 if (ret < 0) {
519 if (errno != EINTR && errno != EAGAIN)
520 return -1;
521 } else if (ret == 0) {
522 break;
523 } else {
524 buf += ret;
525 len -= ret;
528 return len1 - len;
531 int send_all(int fd, const void *buf, int len1)
533 return unix_write(fd, buf, len1);
535 #endif /* !_WIN32 */
537 #ifndef _WIN32
539 typedef struct {
540 int fd_in, fd_out;
541 int max_size;
542 } FDCharDriver;
544 #define STDIO_MAX_CLIENTS 1
545 static int stdio_nb_clients = 0;
547 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
549 FDCharDriver *s = chr->opaque;
550 return send_all(s->fd_out, buf, len);
553 static int fd_chr_read_poll(void *opaque)
555 CharDriverState *chr = opaque;
556 FDCharDriver *s = chr->opaque;
558 s->max_size = qemu_chr_can_read(chr);
559 return s->max_size;
562 static void fd_chr_read(void *opaque)
564 CharDriverState *chr = opaque;
565 FDCharDriver *s = chr->opaque;
566 int size, len;
567 uint8_t buf[READ_BUF_LEN];
569 len = sizeof(buf);
570 if (len > s->max_size)
571 len = s->max_size;
572 if (len == 0)
573 return;
574 size = read(s->fd_in, buf, len);
575 if (size == 0) {
576 /* FD has been closed. Remove it from the active list. */
577 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
578 qemu_chr_event(chr, CHR_EVENT_CLOSED);
579 return;
581 if (size > 0) {
582 qemu_chr_read(chr, buf, size);
586 static void fd_chr_update_read_handler(CharDriverState *chr)
588 FDCharDriver *s = chr->opaque;
590 if (s->fd_in >= 0) {
591 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
592 } else {
593 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
594 fd_chr_read, NULL, chr);
599 static void fd_chr_close(struct CharDriverState *chr)
601 FDCharDriver *s = chr->opaque;
603 if (s->fd_in >= 0) {
604 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
605 } else {
606 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
610 qemu_free(s);
611 qemu_chr_event(chr, CHR_EVENT_CLOSED);
614 /* open a character device to a unix fd */
615 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
617 CharDriverState *chr;
618 FDCharDriver *s;
620 chr = qemu_mallocz(sizeof(CharDriverState));
621 s = qemu_mallocz(sizeof(FDCharDriver));
622 s->fd_in = fd_in;
623 s->fd_out = fd_out;
624 chr->opaque = s;
625 chr->chr_write = fd_chr_write;
626 chr->chr_update_read_handler = fd_chr_update_read_handler;
627 chr->chr_close = fd_chr_close;
629 qemu_chr_generic_open(chr);
631 return chr;
634 static CharDriverState *qemu_chr_open_file_out(QemuOpts *opts)
636 int fd_out;
638 TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
639 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
640 if (fd_out < 0)
641 return NULL;
642 return qemu_chr_open_fd(-1, fd_out);
645 static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)
647 int fd_in, fd_out;
648 char filename_in[256], filename_out[256];
649 const char *filename = qemu_opt_get(opts, "path");
651 if (filename == NULL) {
652 fprintf(stderr, "chardev: pipe: no filename given\n");
653 return NULL;
656 snprintf(filename_in, 256, "%s.in", filename);
657 snprintf(filename_out, 256, "%s.out", filename);
658 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
659 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
660 if (fd_in < 0 || fd_out < 0) {
661 if (fd_in >= 0)
662 close(fd_in);
663 if (fd_out >= 0)
664 close(fd_out);
665 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
666 if (fd_in < 0)
667 return NULL;
669 return qemu_chr_open_fd(fd_in, fd_out);
673 /* for STDIO, we handle the case where several clients use it
674 (nographic mode) */
676 #define TERM_FIFO_MAX_SIZE 1
678 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
679 static int term_fifo_size;
681 static int stdio_read_poll(void *opaque)
683 CharDriverState *chr = opaque;
685 /* try to flush the queue if needed */
686 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
687 qemu_chr_read(chr, term_fifo, 1);
688 term_fifo_size = 0;
690 /* see if we can absorb more chars */
691 if (term_fifo_size == 0)
692 return 1;
693 else
694 return 0;
697 static void stdio_read(void *opaque)
699 int size;
700 uint8_t buf[1];
701 CharDriverState *chr = opaque;
703 size = read(0, buf, 1);
704 if (size == 0) {
705 /* stdin has been closed. Remove it from the active list. */
706 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
707 qemu_chr_event(chr, CHR_EVENT_CLOSED);
708 return;
710 if (size > 0) {
711 if (qemu_chr_can_read(chr) > 0) {
712 qemu_chr_read(chr, buf, 1);
713 } else if (term_fifo_size == 0) {
714 term_fifo[term_fifo_size++] = buf[0];
719 /* init terminal so that we can grab keys */
720 static struct termios oldtty;
721 static int old_fd0_flags;
722 static int term_atexit_done;
724 static void term_exit(void)
726 tcsetattr (0, TCSANOW, &oldtty);
727 fcntl(0, F_SETFL, old_fd0_flags);
730 static void term_init(QemuOpts *opts)
732 struct termios tty;
734 tcgetattr (0, &tty);
735 oldtty = tty;
736 old_fd0_flags = fcntl(0, F_GETFL);
738 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
739 |INLCR|IGNCR|ICRNL|IXON);
740 tty.c_oflag |= OPOST;
741 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
742 /* if graphical mode, we allow Ctrl-C handling */
743 if (!qemu_opt_get_bool(opts, "signal", display_type != DT_NOGRAPHIC))
744 tty.c_lflag &= ~ISIG;
745 tty.c_cflag &= ~(CSIZE|PARENB);
746 tty.c_cflag |= CS8;
747 tty.c_cc[VMIN] = 1;
748 tty.c_cc[VTIME] = 0;
750 tcsetattr (0, TCSANOW, &tty);
752 if (!term_atexit_done++)
753 atexit(term_exit);
755 fcntl(0, F_SETFL, O_NONBLOCK);
758 static void qemu_chr_close_stdio(struct CharDriverState *chr)
760 term_exit();
761 stdio_nb_clients--;
762 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
763 fd_chr_close(chr);
766 static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)
768 CharDriverState *chr;
770 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
771 return NULL;
772 chr = qemu_chr_open_fd(0, 1);
773 chr->chr_close = qemu_chr_close_stdio;
774 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
775 stdio_nb_clients++;
776 term_init(opts);
778 return chr;
781 #ifdef __sun__
782 /* Once Solaris has openpty(), this is going to be removed. */
783 static int openpty(int *amaster, int *aslave, char *name,
784 struct termios *termp, struct winsize *winp)
786 const char *slave;
787 int mfd = -1, sfd = -1;
789 *amaster = *aslave = -1;
791 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
792 if (mfd < 0)
793 goto err;
795 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
796 goto err;
798 if ((slave = ptsname(mfd)) == NULL)
799 goto err;
801 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
802 goto err;
804 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
805 (termp != NULL && tcgetattr(sfd, termp) < 0))
806 goto err;
808 if (amaster)
809 *amaster = mfd;
810 if (aslave)
811 *aslave = sfd;
812 if (winp)
813 ioctl(sfd, TIOCSWINSZ, winp);
815 return 0;
817 err:
818 if (sfd != -1)
819 close(sfd);
820 close(mfd);
821 return -1;
824 static void cfmakeraw (struct termios *termios_p)
826 termios_p->c_iflag &=
827 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
828 termios_p->c_oflag &= ~OPOST;
829 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
830 termios_p->c_cflag &= ~(CSIZE|PARENB);
831 termios_p->c_cflag |= CS8;
833 termios_p->c_cc[VMIN] = 0;
834 termios_p->c_cc[VTIME] = 0;
836 #endif
838 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
839 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
840 || defined(__GLIBC__)
842 typedef struct {
843 int fd;
844 int connected;
845 int polling;
846 int read_bytes;
847 QEMUTimer *timer;
848 } PtyCharDriver;
850 static void pty_chr_update_read_handler(CharDriverState *chr);
851 static void pty_chr_state(CharDriverState *chr, int connected);
853 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
855 PtyCharDriver *s = chr->opaque;
857 if (!s->connected) {
858 /* guest sends data, check for (re-)connect */
859 pty_chr_update_read_handler(chr);
860 return 0;
862 return send_all(s->fd, buf, len);
865 static int pty_chr_read_poll(void *opaque)
867 CharDriverState *chr = opaque;
868 PtyCharDriver *s = chr->opaque;
870 s->read_bytes = qemu_chr_can_read(chr);
871 return s->read_bytes;
874 static void pty_chr_read(void *opaque)
876 CharDriverState *chr = opaque;
877 PtyCharDriver *s = chr->opaque;
878 int size, len;
879 uint8_t buf[READ_BUF_LEN];
881 len = sizeof(buf);
882 if (len > s->read_bytes)
883 len = s->read_bytes;
884 if (len == 0)
885 return;
886 size = read(s->fd, buf, len);
887 if ((size == -1 && errno == EIO) ||
888 (size == 0)) {
889 pty_chr_state(chr, 0);
890 return;
892 if (size > 0) {
893 pty_chr_state(chr, 1);
894 qemu_chr_read(chr, buf, size);
898 static void pty_chr_update_read_handler(CharDriverState *chr)
900 PtyCharDriver *s = chr->opaque;
902 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
903 pty_chr_read, NULL, chr);
904 s->polling = 1;
906 * Short timeout here: just need wait long enougth that qemu makes
907 * it through the poll loop once. When reconnected we want a
908 * short timeout so we notice it almost instantly. Otherwise
909 * read() gives us -EIO instantly, making pty_chr_state() reset the
910 * timeout to the normal (much longer) poll interval before the
911 * timer triggers.
913 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
916 static void pty_chr_state(CharDriverState *chr, int connected)
918 PtyCharDriver *s = chr->opaque;
920 if (!connected) {
921 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
922 s->connected = 0;
923 s->polling = 0;
924 /* (re-)connect poll interval for idle guests: once per second.
925 * We check more frequently in case the guests sends data to
926 * the virtual device linked to our pty. */
927 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
928 } else {
929 if (!s->connected)
930 qemu_chr_generic_open(chr);
931 s->connected = 1;
935 static void pty_chr_timer(void *opaque)
937 struct CharDriverState *chr = opaque;
938 PtyCharDriver *s = chr->opaque;
940 if (s->connected)
941 return;
942 if (s->polling) {
943 /* If we arrive here without polling being cleared due
944 * read returning -EIO, then we are (re-)connected */
945 pty_chr_state(chr, 1);
946 return;
949 /* Next poll ... */
950 pty_chr_update_read_handler(chr);
953 static void pty_chr_close(struct CharDriverState *chr)
955 PtyCharDriver *s = chr->opaque;
957 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
958 close(s->fd);
959 qemu_del_timer(s->timer);
960 qemu_free_timer(s->timer);
961 qemu_free(s);
962 qemu_chr_event(chr, CHR_EVENT_CLOSED);
965 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
967 CharDriverState *chr;
968 PtyCharDriver *s;
969 struct termios tty;
970 int slave_fd, len;
971 #if defined(__OpenBSD__) || defined(__DragonFly__)
972 char pty_name[PATH_MAX];
973 #define q_ptsname(x) pty_name
974 #else
975 char *pty_name = NULL;
976 #define q_ptsname(x) ptsname(x)
977 #endif
979 chr = qemu_mallocz(sizeof(CharDriverState));
980 s = qemu_mallocz(sizeof(PtyCharDriver));
982 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
983 return NULL;
986 /* Set raw attributes on the pty. */
987 tcgetattr(slave_fd, &tty);
988 cfmakeraw(&tty);
989 tcsetattr(slave_fd, TCSAFLUSH, &tty);
990 close(slave_fd);
992 len = strlen(q_ptsname(s->fd)) + 5;
993 chr->filename = qemu_malloc(len);
994 snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
995 qemu_opt_set(opts, "path", q_ptsname(s->fd));
996 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
998 chr->opaque = s;
999 chr->chr_write = pty_chr_write;
1000 chr->chr_update_read_handler = pty_chr_update_read_handler;
1001 chr->chr_close = pty_chr_close;
1003 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
1005 return chr;
1008 static void tty_serial_init(int fd, int speed,
1009 int parity, int data_bits, int stop_bits)
1011 struct termios tty;
1012 speed_t spd;
1014 #if 0
1015 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1016 speed, parity, data_bits, stop_bits);
1017 #endif
1018 tcgetattr (fd, &tty);
1019 if (!term_atexit_done) {
1020 oldtty = tty;
1023 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1024 speed = speed * 10 / 11;
1025 do {
1026 check_speed(50);
1027 check_speed(75);
1028 check_speed(110);
1029 check_speed(134);
1030 check_speed(150);
1031 check_speed(200);
1032 check_speed(300);
1033 check_speed(600);
1034 check_speed(1200);
1035 check_speed(1800);
1036 check_speed(2400);
1037 check_speed(4800);
1038 check_speed(9600);
1039 check_speed(19200);
1040 check_speed(38400);
1041 /* Non-Posix values follow. They may be unsupported on some systems. */
1042 check_speed(57600);
1043 check_speed(115200);
1044 #ifdef B230400
1045 check_speed(230400);
1046 #endif
1047 #ifdef B460800
1048 check_speed(460800);
1049 #endif
1050 #ifdef B500000
1051 check_speed(500000);
1052 #endif
1053 #ifdef B576000
1054 check_speed(576000);
1055 #endif
1056 #ifdef B921600
1057 check_speed(921600);
1058 #endif
1059 #ifdef B1000000
1060 check_speed(1000000);
1061 #endif
1062 #ifdef B1152000
1063 check_speed(1152000);
1064 #endif
1065 #ifdef B1500000
1066 check_speed(1500000);
1067 #endif
1068 #ifdef B2000000
1069 check_speed(2000000);
1070 #endif
1071 #ifdef B2500000
1072 check_speed(2500000);
1073 #endif
1074 #ifdef B3000000
1075 check_speed(3000000);
1076 #endif
1077 #ifdef B3500000
1078 check_speed(3500000);
1079 #endif
1080 #ifdef B4000000
1081 check_speed(4000000);
1082 #endif
1083 spd = B115200;
1084 } while (0);
1086 cfsetispeed(&tty, spd);
1087 cfsetospeed(&tty, spd);
1089 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1090 |INLCR|IGNCR|ICRNL|IXON);
1091 tty.c_oflag |= OPOST;
1092 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1093 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1094 switch(data_bits) {
1095 default:
1096 case 8:
1097 tty.c_cflag |= CS8;
1098 break;
1099 case 7:
1100 tty.c_cflag |= CS7;
1101 break;
1102 case 6:
1103 tty.c_cflag |= CS6;
1104 break;
1105 case 5:
1106 tty.c_cflag |= CS5;
1107 break;
1109 switch(parity) {
1110 default:
1111 case 'N':
1112 break;
1113 case 'E':
1114 tty.c_cflag |= PARENB;
1115 break;
1116 case 'O':
1117 tty.c_cflag |= PARENB | PARODD;
1118 break;
1120 if (stop_bits == 2)
1121 tty.c_cflag |= CSTOPB;
1123 tcsetattr (fd, TCSANOW, &tty);
1126 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1128 FDCharDriver *s = chr->opaque;
1130 switch(cmd) {
1131 case CHR_IOCTL_SERIAL_SET_PARAMS:
1133 QEMUSerialSetParams *ssp = arg;
1134 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1135 ssp->data_bits, ssp->stop_bits);
1137 break;
1138 case CHR_IOCTL_SERIAL_SET_BREAK:
1140 int enable = *(int *)arg;
1141 if (enable)
1142 tcsendbreak(s->fd_in, 1);
1144 break;
1145 case CHR_IOCTL_SERIAL_GET_TIOCM:
1147 int sarg = 0;
1148 int *targ = (int *)arg;
1149 ioctl(s->fd_in, TIOCMGET, &sarg);
1150 *targ = 0;
1151 if (sarg & TIOCM_CTS)
1152 *targ |= CHR_TIOCM_CTS;
1153 if (sarg & TIOCM_CAR)
1154 *targ |= CHR_TIOCM_CAR;
1155 if (sarg & TIOCM_DSR)
1156 *targ |= CHR_TIOCM_DSR;
1157 if (sarg & TIOCM_RI)
1158 *targ |= CHR_TIOCM_RI;
1159 if (sarg & TIOCM_DTR)
1160 *targ |= CHR_TIOCM_DTR;
1161 if (sarg & TIOCM_RTS)
1162 *targ |= CHR_TIOCM_RTS;
1164 break;
1165 case CHR_IOCTL_SERIAL_SET_TIOCM:
1167 int sarg = *(int *)arg;
1168 int targ = 0;
1169 ioctl(s->fd_in, TIOCMGET, &targ);
1170 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1171 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1172 if (sarg & CHR_TIOCM_CTS)
1173 targ |= TIOCM_CTS;
1174 if (sarg & CHR_TIOCM_CAR)
1175 targ |= TIOCM_CAR;
1176 if (sarg & CHR_TIOCM_DSR)
1177 targ |= TIOCM_DSR;
1178 if (sarg & CHR_TIOCM_RI)
1179 targ |= TIOCM_RI;
1180 if (sarg & CHR_TIOCM_DTR)
1181 targ |= TIOCM_DTR;
1182 if (sarg & CHR_TIOCM_RTS)
1183 targ |= TIOCM_RTS;
1184 ioctl(s->fd_in, TIOCMSET, &targ);
1186 break;
1187 default:
1188 return -ENOTSUP;
1190 return 0;
1193 static void tty_exit(void)
1195 tcsetattr(0, TCSANOW, &oldtty);
1198 static void qemu_chr_close_tty(CharDriverState *chr)
1200 FDCharDriver *s = chr->opaque;
1201 int fd = -1;
1203 if (s) {
1204 fd = s->fd_in;
1207 fd_chr_close(chr);
1209 if (fd >= 0) {
1210 close(fd);
1214 static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
1216 const char *filename = qemu_opt_get(opts, "path");
1217 CharDriverState *chr;
1218 int fd;
1220 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
1221 if (fd < 0) {
1222 return NULL;
1224 tty_serial_init(fd, 115200, 'N', 8, 1);
1225 chr = qemu_chr_open_fd(fd, fd);
1226 if (!chr) {
1227 close(fd);
1228 return NULL;
1230 chr->chr_ioctl = tty_serial_ioctl;
1231 chr->chr_close = qemu_chr_close_tty;
1232 if (!term_atexit_done++)
1233 atexit(tty_exit);
1234 return chr;
1236 #else /* ! __linux__ && ! __sun__ */
1237 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
1239 return NULL;
1241 #endif /* __linux__ || __sun__ */
1243 #if defined(__linux__)
1244 typedef struct {
1245 int fd;
1246 int mode;
1247 } ParallelCharDriver;
1249 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1251 if (s->mode != mode) {
1252 int m = mode;
1253 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1254 return 0;
1255 s->mode = mode;
1257 return 1;
1260 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1262 ParallelCharDriver *drv = chr->opaque;
1263 int fd = drv->fd;
1264 uint8_t b;
1266 switch(cmd) {
1267 case CHR_IOCTL_PP_READ_DATA:
1268 if (ioctl(fd, PPRDATA, &b) < 0)
1269 return -ENOTSUP;
1270 *(uint8_t *)arg = b;
1271 break;
1272 case CHR_IOCTL_PP_WRITE_DATA:
1273 b = *(uint8_t *)arg;
1274 if (ioctl(fd, PPWDATA, &b) < 0)
1275 return -ENOTSUP;
1276 break;
1277 case CHR_IOCTL_PP_READ_CONTROL:
1278 if (ioctl(fd, PPRCONTROL, &b) < 0)
1279 return -ENOTSUP;
1280 /* Linux gives only the lowest bits, and no way to know data
1281 direction! For better compatibility set the fixed upper
1282 bits. */
1283 *(uint8_t *)arg = b | 0xc0;
1284 break;
1285 case CHR_IOCTL_PP_WRITE_CONTROL:
1286 b = *(uint8_t *)arg;
1287 if (ioctl(fd, PPWCONTROL, &b) < 0)
1288 return -ENOTSUP;
1289 break;
1290 case CHR_IOCTL_PP_READ_STATUS:
1291 if (ioctl(fd, PPRSTATUS, &b) < 0)
1292 return -ENOTSUP;
1293 *(uint8_t *)arg = b;
1294 break;
1295 case CHR_IOCTL_PP_DATA_DIR:
1296 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1297 return -ENOTSUP;
1298 break;
1299 case CHR_IOCTL_PP_EPP_READ_ADDR:
1300 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1301 struct ParallelIOArg *parg = arg;
1302 int n = read(fd, parg->buffer, parg->count);
1303 if (n != parg->count) {
1304 return -EIO;
1307 break;
1308 case CHR_IOCTL_PP_EPP_READ:
1309 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1310 struct ParallelIOArg *parg = arg;
1311 int n = read(fd, parg->buffer, parg->count);
1312 if (n != parg->count) {
1313 return -EIO;
1316 break;
1317 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1318 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1319 struct ParallelIOArg *parg = arg;
1320 int n = write(fd, parg->buffer, parg->count);
1321 if (n != parg->count) {
1322 return -EIO;
1325 break;
1326 case CHR_IOCTL_PP_EPP_WRITE:
1327 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1328 struct ParallelIOArg *parg = arg;
1329 int n = write(fd, parg->buffer, parg->count);
1330 if (n != parg->count) {
1331 return -EIO;
1334 break;
1335 default:
1336 return -ENOTSUP;
1338 return 0;
1341 static void pp_close(CharDriverState *chr)
1343 ParallelCharDriver *drv = chr->opaque;
1344 int fd = drv->fd;
1346 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1347 ioctl(fd, PPRELEASE);
1348 close(fd);
1349 qemu_free(drv);
1350 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1353 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1355 const char *filename = qemu_opt_get(opts, "path");
1356 CharDriverState *chr;
1357 ParallelCharDriver *drv;
1358 int fd;
1360 TFR(fd = open(filename, O_RDWR));
1361 if (fd < 0)
1362 return NULL;
1364 if (ioctl(fd, PPCLAIM) < 0) {
1365 close(fd);
1366 return NULL;
1369 drv = qemu_mallocz(sizeof(ParallelCharDriver));
1370 drv->fd = fd;
1371 drv->mode = IEEE1284_MODE_COMPAT;
1373 chr = qemu_mallocz(sizeof(CharDriverState));
1374 chr->chr_write = null_chr_write;
1375 chr->chr_ioctl = pp_ioctl;
1376 chr->chr_close = pp_close;
1377 chr->opaque = drv;
1379 qemu_chr_generic_open(chr);
1381 return chr;
1383 #endif /* __linux__ */
1385 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1386 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1388 int fd = (int)(long)chr->opaque;
1389 uint8_t b;
1391 switch(cmd) {
1392 case CHR_IOCTL_PP_READ_DATA:
1393 if (ioctl(fd, PPIGDATA, &b) < 0)
1394 return -ENOTSUP;
1395 *(uint8_t *)arg = b;
1396 break;
1397 case CHR_IOCTL_PP_WRITE_DATA:
1398 b = *(uint8_t *)arg;
1399 if (ioctl(fd, PPISDATA, &b) < 0)
1400 return -ENOTSUP;
1401 break;
1402 case CHR_IOCTL_PP_READ_CONTROL:
1403 if (ioctl(fd, PPIGCTRL, &b) < 0)
1404 return -ENOTSUP;
1405 *(uint8_t *)arg = b;
1406 break;
1407 case CHR_IOCTL_PP_WRITE_CONTROL:
1408 b = *(uint8_t *)arg;
1409 if (ioctl(fd, PPISCTRL, &b) < 0)
1410 return -ENOTSUP;
1411 break;
1412 case CHR_IOCTL_PP_READ_STATUS:
1413 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1414 return -ENOTSUP;
1415 *(uint8_t *)arg = b;
1416 break;
1417 default:
1418 return -ENOTSUP;
1420 return 0;
1423 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1425 const char *filename = qemu_opt_get(opts, "path");
1426 CharDriverState *chr;
1427 int fd;
1429 fd = open(filename, O_RDWR);
1430 if (fd < 0)
1431 return NULL;
1433 chr = qemu_mallocz(sizeof(CharDriverState));
1434 chr->opaque = (void *)(long)fd;
1435 chr->chr_write = null_chr_write;
1436 chr->chr_ioctl = pp_ioctl;
1437 return chr;
1439 #endif
1441 #else /* _WIN32 */
1443 typedef struct {
1444 int max_size;
1445 HANDLE hcom, hrecv, hsend;
1446 OVERLAPPED orecv, osend;
1447 BOOL fpipe;
1448 DWORD len;
1449 } WinCharState;
1451 #define NSENDBUF 2048
1452 #define NRECVBUF 2048
1453 #define MAXCONNECT 1
1454 #define NTIMEOUT 5000
1456 static int win_chr_poll(void *opaque);
1457 static int win_chr_pipe_poll(void *opaque);
1459 static void win_chr_close(CharDriverState *chr)
1461 WinCharState *s = chr->opaque;
1463 if (s->hsend) {
1464 CloseHandle(s->hsend);
1465 s->hsend = NULL;
1467 if (s->hrecv) {
1468 CloseHandle(s->hrecv);
1469 s->hrecv = NULL;
1471 if (s->hcom) {
1472 CloseHandle(s->hcom);
1473 s->hcom = NULL;
1475 if (s->fpipe)
1476 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1477 else
1478 qemu_del_polling_cb(win_chr_poll, chr);
1480 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1483 static int win_chr_init(CharDriverState *chr, const char *filename)
1485 WinCharState *s = chr->opaque;
1486 COMMCONFIG comcfg;
1487 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1488 COMSTAT comstat;
1489 DWORD size;
1490 DWORD err;
1492 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1493 if (!s->hsend) {
1494 fprintf(stderr, "Failed CreateEvent\n");
1495 goto fail;
1497 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1498 if (!s->hrecv) {
1499 fprintf(stderr, "Failed CreateEvent\n");
1500 goto fail;
1503 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1504 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1505 if (s->hcom == INVALID_HANDLE_VALUE) {
1506 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1507 s->hcom = NULL;
1508 goto fail;
1511 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1512 fprintf(stderr, "Failed SetupComm\n");
1513 goto fail;
1516 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1517 size = sizeof(COMMCONFIG);
1518 GetDefaultCommConfig(filename, &comcfg, &size);
1519 comcfg.dcb.DCBlength = sizeof(DCB);
1520 CommConfigDialog(filename, NULL, &comcfg);
1522 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1523 fprintf(stderr, "Failed SetCommState\n");
1524 goto fail;
1527 if (!SetCommMask(s->hcom, EV_ERR)) {
1528 fprintf(stderr, "Failed SetCommMask\n");
1529 goto fail;
1532 cto.ReadIntervalTimeout = MAXDWORD;
1533 if (!SetCommTimeouts(s->hcom, &cto)) {
1534 fprintf(stderr, "Failed SetCommTimeouts\n");
1535 goto fail;
1538 if (!ClearCommError(s->hcom, &err, &comstat)) {
1539 fprintf(stderr, "Failed ClearCommError\n");
1540 goto fail;
1542 qemu_add_polling_cb(win_chr_poll, chr);
1543 return 0;
1545 fail:
1546 win_chr_close(chr);
1547 return -1;
1550 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1552 WinCharState *s = chr->opaque;
1553 DWORD len, ret, size, err;
1555 len = len1;
1556 ZeroMemory(&s->osend, sizeof(s->osend));
1557 s->osend.hEvent = s->hsend;
1558 while (len > 0) {
1559 if (s->hsend)
1560 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1561 else
1562 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1563 if (!ret) {
1564 err = GetLastError();
1565 if (err == ERROR_IO_PENDING) {
1566 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1567 if (ret) {
1568 buf += size;
1569 len -= size;
1570 } else {
1571 break;
1573 } else {
1574 break;
1576 } else {
1577 buf += size;
1578 len -= size;
1581 return len1 - len;
1584 static int win_chr_read_poll(CharDriverState *chr)
1586 WinCharState *s = chr->opaque;
1588 s->max_size = qemu_chr_can_read(chr);
1589 return s->max_size;
1592 static void win_chr_readfile(CharDriverState *chr)
1594 WinCharState *s = chr->opaque;
1595 int ret, err;
1596 uint8_t buf[READ_BUF_LEN];
1597 DWORD size;
1599 ZeroMemory(&s->orecv, sizeof(s->orecv));
1600 s->orecv.hEvent = s->hrecv;
1601 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1602 if (!ret) {
1603 err = GetLastError();
1604 if (err == ERROR_IO_PENDING) {
1605 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1609 if (size > 0) {
1610 qemu_chr_read(chr, buf, size);
1614 static void win_chr_read(CharDriverState *chr)
1616 WinCharState *s = chr->opaque;
1618 if (s->len > s->max_size)
1619 s->len = s->max_size;
1620 if (s->len == 0)
1621 return;
1623 win_chr_readfile(chr);
1626 static int win_chr_poll(void *opaque)
1628 CharDriverState *chr = opaque;
1629 WinCharState *s = chr->opaque;
1630 COMSTAT status;
1631 DWORD comerr;
1633 ClearCommError(s->hcom, &comerr, &status);
1634 if (status.cbInQue > 0) {
1635 s->len = status.cbInQue;
1636 win_chr_read_poll(chr);
1637 win_chr_read(chr);
1638 return 1;
1640 return 0;
1643 static CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1645 const char *filename = qemu_opt_get(opts, "path");
1646 CharDriverState *chr;
1647 WinCharState *s;
1649 chr = qemu_mallocz(sizeof(CharDriverState));
1650 s = qemu_mallocz(sizeof(WinCharState));
1651 chr->opaque = s;
1652 chr->chr_write = win_chr_write;
1653 chr->chr_close = win_chr_close;
1655 if (win_chr_init(chr, filename) < 0) {
1656 free(s);
1657 free(chr);
1658 return NULL;
1660 qemu_chr_generic_open(chr);
1661 return chr;
1664 static int win_chr_pipe_poll(void *opaque)
1666 CharDriverState *chr = opaque;
1667 WinCharState *s = chr->opaque;
1668 DWORD size;
1670 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1671 if (size > 0) {
1672 s->len = size;
1673 win_chr_read_poll(chr);
1674 win_chr_read(chr);
1675 return 1;
1677 return 0;
1680 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1682 WinCharState *s = chr->opaque;
1683 OVERLAPPED ov;
1684 int ret;
1685 DWORD size;
1686 char openname[256];
1688 s->fpipe = TRUE;
1690 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1691 if (!s->hsend) {
1692 fprintf(stderr, "Failed CreateEvent\n");
1693 goto fail;
1695 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1696 if (!s->hrecv) {
1697 fprintf(stderr, "Failed CreateEvent\n");
1698 goto fail;
1701 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1702 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1703 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1704 PIPE_WAIT,
1705 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1706 if (s->hcom == INVALID_HANDLE_VALUE) {
1707 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1708 s->hcom = NULL;
1709 goto fail;
1712 ZeroMemory(&ov, sizeof(ov));
1713 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1714 ret = ConnectNamedPipe(s->hcom, &ov);
1715 if (ret) {
1716 fprintf(stderr, "Failed ConnectNamedPipe\n");
1717 goto fail;
1720 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1721 if (!ret) {
1722 fprintf(stderr, "Failed GetOverlappedResult\n");
1723 if (ov.hEvent) {
1724 CloseHandle(ov.hEvent);
1725 ov.hEvent = NULL;
1727 goto fail;
1730 if (ov.hEvent) {
1731 CloseHandle(ov.hEvent);
1732 ov.hEvent = NULL;
1734 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1735 return 0;
1737 fail:
1738 win_chr_close(chr);
1739 return -1;
1743 static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
1745 const char *filename = qemu_opt_get(opts, "path");
1746 CharDriverState *chr;
1747 WinCharState *s;
1749 chr = qemu_mallocz(sizeof(CharDriverState));
1750 s = qemu_mallocz(sizeof(WinCharState));
1751 chr->opaque = s;
1752 chr->chr_write = win_chr_write;
1753 chr->chr_close = win_chr_close;
1755 if (win_chr_pipe_init(chr, filename) < 0) {
1756 free(s);
1757 free(chr);
1758 return NULL;
1760 qemu_chr_generic_open(chr);
1761 return chr;
1764 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1766 CharDriverState *chr;
1767 WinCharState *s;
1769 chr = qemu_mallocz(sizeof(CharDriverState));
1770 s = qemu_mallocz(sizeof(WinCharState));
1771 s->hcom = fd_out;
1772 chr->opaque = s;
1773 chr->chr_write = win_chr_write;
1774 qemu_chr_generic_open(chr);
1775 return chr;
1778 static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
1780 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1783 static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
1785 const char *file_out = qemu_opt_get(opts, "path");
1786 HANDLE fd_out;
1788 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1789 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1790 if (fd_out == INVALID_HANDLE_VALUE)
1791 return NULL;
1793 return qemu_chr_open_win_file(fd_out);
1795 #endif /* !_WIN32 */
1797 /***********************************************************/
1798 /* UDP Net console */
1800 typedef struct {
1801 int fd;
1802 uint8_t buf[READ_BUF_LEN];
1803 int bufcnt;
1804 int bufptr;
1805 int max_size;
1806 } NetCharDriver;
1808 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1810 NetCharDriver *s = chr->opaque;
1812 return send(s->fd, (const void *)buf, len, 0);
1815 static int udp_chr_read_poll(void *opaque)
1817 CharDriverState *chr = opaque;
1818 NetCharDriver *s = chr->opaque;
1820 s->max_size = qemu_chr_can_read(chr);
1822 /* If there were any stray characters in the queue process them
1823 * first
1825 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1826 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1827 s->bufptr++;
1828 s->max_size = qemu_chr_can_read(chr);
1830 return s->max_size;
1833 static void udp_chr_read(void *opaque)
1835 CharDriverState *chr = opaque;
1836 NetCharDriver *s = chr->opaque;
1838 if (s->max_size == 0)
1839 return;
1840 s->bufcnt = recv(s->fd, (void *)s->buf, sizeof(s->buf), 0);
1841 s->bufptr = s->bufcnt;
1842 if (s->bufcnt <= 0)
1843 return;
1845 s->bufptr = 0;
1846 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1847 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1848 s->bufptr++;
1849 s->max_size = qemu_chr_can_read(chr);
1853 static void udp_chr_update_read_handler(CharDriverState *chr)
1855 NetCharDriver *s = chr->opaque;
1857 if (s->fd >= 0) {
1858 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
1859 udp_chr_read, NULL, chr);
1863 static void udp_chr_close(CharDriverState *chr)
1865 NetCharDriver *s = chr->opaque;
1866 if (s->fd >= 0) {
1867 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1868 closesocket(s->fd);
1870 qemu_free(s);
1871 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1874 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
1876 CharDriverState *chr = NULL;
1877 NetCharDriver *s = NULL;
1878 int fd = -1;
1880 chr = qemu_mallocz(sizeof(CharDriverState));
1881 s = qemu_mallocz(sizeof(NetCharDriver));
1883 fd = inet_dgram_opts(opts);
1884 if (fd < 0) {
1885 fprintf(stderr, "inet_dgram_opts failed\n");
1886 goto return_err;
1889 s->fd = fd;
1890 s->bufcnt = 0;
1891 s->bufptr = 0;
1892 chr->opaque = s;
1893 chr->chr_write = udp_chr_write;
1894 chr->chr_update_read_handler = udp_chr_update_read_handler;
1895 chr->chr_close = udp_chr_close;
1896 return chr;
1898 return_err:
1899 if (chr)
1900 free(chr);
1901 if (s)
1902 free(s);
1903 if (fd >= 0)
1904 closesocket(fd);
1905 return NULL;
1908 /***********************************************************/
1909 /* TCP Net console */
1911 typedef struct {
1912 int fd, listen_fd;
1913 int connected;
1914 int max_size;
1915 int do_telnetopt;
1916 int do_nodelay;
1917 int is_unix;
1918 int msgfd;
1919 } TCPCharDriver;
1921 static void tcp_chr_accept(void *opaque);
1923 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1925 TCPCharDriver *s = chr->opaque;
1926 if (s->connected) {
1927 return send_all(s->fd, buf, len);
1928 } else {
1929 /* XXX: indicate an error ? */
1930 return len;
1934 static int tcp_chr_read_poll(void *opaque)
1936 CharDriverState *chr = opaque;
1937 TCPCharDriver *s = chr->opaque;
1938 if (!s->connected)
1939 return 0;
1940 s->max_size = qemu_chr_can_read(chr);
1941 return s->max_size;
1944 #define IAC 255
1945 #define IAC_BREAK 243
1946 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
1947 TCPCharDriver *s,
1948 uint8_t *buf, int *size)
1950 /* Handle any telnet client's basic IAC options to satisfy char by
1951 * char mode with no echo. All IAC options will be removed from
1952 * the buf and the do_telnetopt variable will be used to track the
1953 * state of the width of the IAC information.
1955 * IAC commands come in sets of 3 bytes with the exception of the
1956 * "IAC BREAK" command and the double IAC.
1959 int i;
1960 int j = 0;
1962 for (i = 0; i < *size; i++) {
1963 if (s->do_telnetopt > 1) {
1964 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
1965 /* Double IAC means send an IAC */
1966 if (j != i)
1967 buf[j] = buf[i];
1968 j++;
1969 s->do_telnetopt = 1;
1970 } else {
1971 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
1972 /* Handle IAC break commands by sending a serial break */
1973 qemu_chr_event(chr, CHR_EVENT_BREAK);
1974 s->do_telnetopt++;
1976 s->do_telnetopt++;
1978 if (s->do_telnetopt >= 4) {
1979 s->do_telnetopt = 1;
1981 } else {
1982 if ((unsigned char)buf[i] == IAC) {
1983 s->do_telnetopt = 2;
1984 } else {
1985 if (j != i)
1986 buf[j] = buf[i];
1987 j++;
1991 *size = j;
1994 static int tcp_get_msgfd(CharDriverState *chr)
1996 TCPCharDriver *s = chr->opaque;
1997 int fd = s->msgfd;
1998 s->msgfd = -1;
1999 return fd;
2002 #ifndef _WIN32
2003 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2005 TCPCharDriver *s = chr->opaque;
2006 struct cmsghdr *cmsg;
2008 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2009 int fd;
2011 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2012 cmsg->cmsg_level != SOL_SOCKET ||
2013 cmsg->cmsg_type != SCM_RIGHTS)
2014 continue;
2016 fd = *((int *)CMSG_DATA(cmsg));
2017 if (fd < 0)
2018 continue;
2020 if (s->msgfd != -1)
2021 close(s->msgfd);
2022 s->msgfd = fd;
2026 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2028 TCPCharDriver *s = chr->opaque;
2029 struct msghdr msg = { NULL, };
2030 struct iovec iov[1];
2031 union {
2032 struct cmsghdr cmsg;
2033 char control[CMSG_SPACE(sizeof(int))];
2034 } msg_control;
2035 ssize_t ret;
2037 iov[0].iov_base = buf;
2038 iov[0].iov_len = len;
2040 msg.msg_iov = iov;
2041 msg.msg_iovlen = 1;
2042 msg.msg_control = &msg_control;
2043 msg.msg_controllen = sizeof(msg_control);
2045 ret = recvmsg(s->fd, &msg, 0);
2046 if (ret > 0 && s->is_unix)
2047 unix_process_msgfd(chr, &msg);
2049 return ret;
2051 #else
2052 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2054 TCPCharDriver *s = chr->opaque;
2055 return recv(s->fd, buf, len, 0);
2057 #endif
2059 static void tcp_chr_read(void *opaque)
2061 CharDriverState *chr = opaque;
2062 TCPCharDriver *s = chr->opaque;
2063 uint8_t buf[READ_BUF_LEN];
2064 int len, size;
2066 if (!s->connected || s->max_size <= 0)
2067 return;
2068 len = sizeof(buf);
2069 if (len > s->max_size)
2070 len = s->max_size;
2071 size = tcp_chr_recv(chr, (void *)buf, len);
2072 if (size == 0) {
2073 /* connection closed */
2074 s->connected = 0;
2075 if (s->listen_fd >= 0) {
2076 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2078 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2079 closesocket(s->fd);
2080 s->fd = -1;
2081 qemu_chr_event(chr, CHR_EVENT_CLOSED);
2082 } else if (size > 0) {
2083 if (s->do_telnetopt)
2084 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2085 if (size > 0)
2086 qemu_chr_read(chr, buf, size);
2090 static void tcp_chr_connect(void *opaque)
2092 CharDriverState *chr = opaque;
2093 TCPCharDriver *s = chr->opaque;
2095 s->connected = 1;
2096 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2097 tcp_chr_read, NULL, chr);
2098 qemu_chr_generic_open(chr);
2101 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2102 static void tcp_chr_telnet_init(int fd)
2104 char buf[3];
2105 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2106 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2107 send(fd, (char *)buf, 3, 0);
2108 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2109 send(fd, (char *)buf, 3, 0);
2110 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2111 send(fd, (char *)buf, 3, 0);
2112 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2113 send(fd, (char *)buf, 3, 0);
2116 static void socket_set_nodelay(int fd)
2118 int val = 1;
2119 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2122 static void tcp_chr_accept(void *opaque)
2124 CharDriverState *chr = opaque;
2125 TCPCharDriver *s = chr->opaque;
2126 struct sockaddr_in saddr;
2127 #ifndef _WIN32
2128 struct sockaddr_un uaddr;
2129 #endif
2130 struct sockaddr *addr;
2131 socklen_t len;
2132 int fd;
2134 for(;;) {
2135 #ifndef _WIN32
2136 if (s->is_unix) {
2137 len = sizeof(uaddr);
2138 addr = (struct sockaddr *)&uaddr;
2139 } else
2140 #endif
2142 len = sizeof(saddr);
2143 addr = (struct sockaddr *)&saddr;
2145 fd = qemu_accept(s->listen_fd, addr, &len);
2146 if (fd < 0 && errno != EINTR) {
2147 return;
2148 } else if (fd >= 0) {
2149 if (s->do_telnetopt)
2150 tcp_chr_telnet_init(fd);
2151 break;
2154 socket_set_nonblock(fd);
2155 if (s->do_nodelay)
2156 socket_set_nodelay(fd);
2157 s->fd = fd;
2158 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2159 tcp_chr_connect(chr);
2162 static void tcp_chr_close(CharDriverState *chr)
2164 TCPCharDriver *s = chr->opaque;
2165 if (s->fd >= 0) {
2166 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2167 closesocket(s->fd);
2169 if (s->listen_fd >= 0) {
2170 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2171 closesocket(s->listen_fd);
2173 qemu_free(s);
2174 qemu_chr_event(chr, CHR_EVENT_CLOSED);
2177 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2179 CharDriverState *chr = NULL;
2180 TCPCharDriver *s = NULL;
2181 int fd = -1;
2182 int is_listen;
2183 int is_waitconnect;
2184 int do_nodelay;
2185 int is_unix;
2186 int is_telnet;
2188 is_listen = qemu_opt_get_bool(opts, "server", 0);
2189 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2190 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2191 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2192 is_unix = qemu_opt_get(opts, "path") != NULL;
2193 if (!is_listen)
2194 is_waitconnect = 0;
2196 chr = qemu_mallocz(sizeof(CharDriverState));
2197 s = qemu_mallocz(sizeof(TCPCharDriver));
2199 if (is_unix) {
2200 if (is_listen) {
2201 fd = unix_listen_opts(opts);
2202 } else {
2203 fd = unix_connect_opts(opts);
2205 } else {
2206 if (is_listen) {
2207 fd = inet_listen_opts(opts, 0);
2208 } else {
2209 fd = inet_connect_opts(opts);
2212 if (fd < 0)
2213 goto fail;
2215 if (!is_waitconnect)
2216 socket_set_nonblock(fd);
2218 s->connected = 0;
2219 s->fd = -1;
2220 s->listen_fd = -1;
2221 s->msgfd = -1;
2222 s->is_unix = is_unix;
2223 s->do_nodelay = do_nodelay && !is_unix;
2225 chr->opaque = s;
2226 chr->chr_write = tcp_chr_write;
2227 chr->chr_close = tcp_chr_close;
2228 chr->get_msgfd = tcp_get_msgfd;
2230 if (is_listen) {
2231 s->listen_fd = fd;
2232 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2233 if (is_telnet)
2234 s->do_telnetopt = 1;
2236 } else {
2237 s->connected = 1;
2238 s->fd = fd;
2239 socket_set_nodelay(fd);
2240 tcp_chr_connect(chr);
2243 /* for "info chardev" monitor command */
2244 chr->filename = qemu_malloc(256);
2245 if (is_unix) {
2246 snprintf(chr->filename, 256, "unix:%s%s",
2247 qemu_opt_get(opts, "path"),
2248 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2249 } else if (is_telnet) {
2250 snprintf(chr->filename, 256, "telnet:%s:%s%s",
2251 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2252 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2253 } else {
2254 snprintf(chr->filename, 256, "tcp:%s:%s%s",
2255 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2256 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2259 if (is_listen && is_waitconnect) {
2260 printf("QEMU waiting for connection on: %s\n",
2261 chr->filename);
2262 tcp_chr_accept(chr);
2263 socket_set_nonblock(s->listen_fd);
2265 return chr;
2267 fail:
2268 if (fd >= 0)
2269 closesocket(fd);
2270 qemu_free(s);
2271 qemu_free(chr);
2272 return NULL;
2275 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2277 char host[65], port[33], width[8], height[8];
2278 int pos;
2279 const char *p;
2280 QemuOpts *opts;
2282 opts = qemu_opts_create(&qemu_chardev_opts, label, 1);
2283 if (NULL == opts)
2284 return NULL;
2286 if (strstart(filename, "mon:", &p)) {
2287 filename = p;
2288 qemu_opt_set(opts, "mux", "on");
2291 if (strcmp(filename, "null") == 0 ||
2292 strcmp(filename, "pty") == 0 ||
2293 strcmp(filename, "msmouse") == 0 ||
2294 strcmp(filename, "braille") == 0 ||
2295 strcmp(filename, "stdio") == 0) {
2296 qemu_opt_set(opts, "backend", filename);
2297 return opts;
2299 if (strstart(filename, "vc", &p)) {
2300 qemu_opt_set(opts, "backend", "vc");
2301 if (*p == ':') {
2302 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2303 /* pixels */
2304 qemu_opt_set(opts, "width", width);
2305 qemu_opt_set(opts, "height", height);
2306 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2307 /* chars */
2308 qemu_opt_set(opts, "cols", width);
2309 qemu_opt_set(opts, "rows", height);
2310 } else {
2311 goto fail;
2314 return opts;
2316 if (strcmp(filename, "con:") == 0) {
2317 qemu_opt_set(opts, "backend", "console");
2318 return opts;
2320 if (strstart(filename, "COM", NULL)) {
2321 qemu_opt_set(opts, "backend", "serial");
2322 qemu_opt_set(opts, "path", filename);
2323 return opts;
2325 if (strstart(filename, "file:", &p)) {
2326 qemu_opt_set(opts, "backend", "file");
2327 qemu_opt_set(opts, "path", p);
2328 return opts;
2330 if (strstart(filename, "pipe:", &p)) {
2331 qemu_opt_set(opts, "backend", "pipe");
2332 qemu_opt_set(opts, "path", p);
2333 return opts;
2335 if (strstart(filename, "tcp:", &p) ||
2336 strstart(filename, "telnet:", &p)) {
2337 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2338 host[0] = 0;
2339 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2340 goto fail;
2342 qemu_opt_set(opts, "backend", "socket");
2343 qemu_opt_set(opts, "host", host);
2344 qemu_opt_set(opts, "port", port);
2345 if (p[pos] == ',') {
2346 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2347 goto fail;
2349 if (strstart(filename, "telnet:", &p))
2350 qemu_opt_set(opts, "telnet", "on");
2351 return opts;
2353 if (strstart(filename, "udp:", &p)) {
2354 qemu_opt_set(opts, "backend", "udp");
2355 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2356 host[0] = 0;
2357 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
2358 goto fail;
2361 qemu_opt_set(opts, "host", host);
2362 qemu_opt_set(opts, "port", port);
2363 if (p[pos] == '@') {
2364 p += pos + 1;
2365 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2366 host[0] = 0;
2367 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2368 goto fail;
2371 qemu_opt_set(opts, "localaddr", host);
2372 qemu_opt_set(opts, "localport", port);
2374 return opts;
2376 if (strstart(filename, "unix:", &p)) {
2377 qemu_opt_set(opts, "backend", "socket");
2378 if (qemu_opts_do_parse(opts, p, "path") != 0)
2379 goto fail;
2380 return opts;
2382 if (strstart(filename, "/dev/parport", NULL) ||
2383 strstart(filename, "/dev/ppi", NULL)) {
2384 qemu_opt_set(opts, "backend", "parport");
2385 qemu_opt_set(opts, "path", filename);
2386 return opts;
2388 if (strstart(filename, "/dev/", NULL)) {
2389 qemu_opt_set(opts, "backend", "tty");
2390 qemu_opt_set(opts, "path", filename);
2391 return opts;
2394 fail:
2395 qemu_opts_del(opts);
2396 return NULL;
2399 static const struct {
2400 const char *name;
2401 CharDriverState *(*open)(QemuOpts *opts);
2402 } backend_table[] = {
2403 { .name = "null", .open = qemu_chr_open_null },
2404 { .name = "socket", .open = qemu_chr_open_socket },
2405 { .name = "udp", .open = qemu_chr_open_udp },
2406 { .name = "msmouse", .open = qemu_chr_open_msmouse },
2407 { .name = "vc", .open = text_console_init },
2408 #ifdef _WIN32
2409 { .name = "file", .open = qemu_chr_open_win_file_out },
2410 { .name = "pipe", .open = qemu_chr_open_win_pipe },
2411 { .name = "console", .open = qemu_chr_open_win_con },
2412 { .name = "serial", .open = qemu_chr_open_win },
2413 #else
2414 { .name = "file", .open = qemu_chr_open_file_out },
2415 { .name = "pipe", .open = qemu_chr_open_pipe },
2416 { .name = "pty", .open = qemu_chr_open_pty },
2417 { .name = "stdio", .open = qemu_chr_open_stdio },
2418 #endif
2419 #ifdef CONFIG_BRLAPI
2420 { .name = "braille", .open = chr_baum_init },
2421 #endif
2422 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2423 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
2424 || defined(__FreeBSD_kernel__)
2425 { .name = "tty", .open = qemu_chr_open_tty },
2426 #endif
2427 #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) \
2428 || defined(__FreeBSD_kernel__)
2429 { .name = "parport", .open = qemu_chr_open_pp },
2430 #endif
2433 CharDriverState *qemu_chr_open_opts(QemuOpts *opts,
2434 void (*init)(struct CharDriverState *s))
2436 CharDriverState *chr;
2437 int i;
2439 if (qemu_opts_id(opts) == NULL) {
2440 fprintf(stderr, "chardev: no id specified\n");
2441 return NULL;
2444 for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
2445 if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
2446 break;
2448 if (i == ARRAY_SIZE(backend_table)) {
2449 fprintf(stderr, "chardev: backend \"%s\" not found\n",
2450 qemu_opt_get(opts, "backend"));
2451 return NULL;
2454 chr = backend_table[i].open(opts);
2455 if (!chr) {
2456 fprintf(stderr, "chardev: opening backend \"%s\" failed\n",
2457 qemu_opt_get(opts, "backend"));
2458 return NULL;
2461 if (!chr->filename)
2462 chr->filename = qemu_strdup(qemu_opt_get(opts, "backend"));
2463 chr->init = init;
2464 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2466 if (qemu_opt_get_bool(opts, "mux", 0)) {
2467 CharDriverState *base = chr;
2468 int len = strlen(qemu_opts_id(opts)) + 6;
2469 base->label = qemu_malloc(len);
2470 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
2471 chr = qemu_chr_open_mux(base);
2472 chr->filename = base->filename;
2473 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2475 chr->label = qemu_strdup(qemu_opts_id(opts));
2476 return chr;
2479 CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2481 const char *p;
2482 CharDriverState *chr;
2483 QemuOpts *opts;
2485 if (strstart(filename, "chardev:", &p)) {
2486 return qemu_chr_find(p);
2489 opts = qemu_chr_parse_compat(label, filename);
2490 if (!opts)
2491 return NULL;
2493 chr = qemu_chr_open_opts(opts, init);
2494 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
2495 monitor_init(chr, MONITOR_USE_READLINE);
2497 return chr;
2500 void qemu_chr_close(CharDriverState *chr)
2502 QTAILQ_REMOVE(&chardevs, chr, next);
2503 if (chr->chr_close)
2504 chr->chr_close(chr);
2505 qemu_free(chr->filename);
2506 qemu_free(chr->label);
2507 qemu_free(chr);
2510 static void qemu_chr_qlist_iter(QObject *obj, void *opaque)
2512 QDict *chr_dict;
2513 Monitor *mon = opaque;
2515 chr_dict = qobject_to_qdict(obj);
2516 monitor_printf(mon, "%s: filename=%s\n", qdict_get_str(chr_dict, "label"),
2517 qdict_get_str(chr_dict, "filename"));
2520 void qemu_chr_info_print(Monitor *mon, const QObject *ret_data)
2522 qlist_iter(qobject_to_qlist(ret_data), qemu_chr_qlist_iter, mon);
2525 void qemu_chr_info(Monitor *mon, QObject **ret_data)
2527 QList *chr_list;
2528 CharDriverState *chr;
2530 chr_list = qlist_new();
2532 QTAILQ_FOREACH(chr, &chardevs, next) {
2533 QObject *obj = qobject_from_jsonf("{ 'label': %s, 'filename': %s }",
2534 chr->label, chr->filename);
2535 qlist_append_obj(chr_list, obj);
2538 *ret_data = QOBJECT(chr_list);
2541 CharDriverState *qemu_chr_find(const char *name)
2543 CharDriverState *chr;
2545 QTAILQ_FOREACH(chr, &chardevs, next) {
2546 if (strcmp(chr->label, name) != 0)
2547 continue;
2548 return chr;
2550 return NULL;