xref: /openbmc/qemu/chardev/char.c (revision 4f9205be)
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "qemu/cutils.h"
27 #include "monitor/monitor.h"
28 #include "qemu/config-file.h"
29 #include "qemu/error-report.h"
30 #include "qemu/qemu-print.h"
31 #include "chardev/char.h"
32 #include "qapi/error.h"
33 #include "qapi/qapi-commands-char.h"
34 #include "qapi/qmp/qerror.h"
35 #include "sysemu/replay.h"
36 #include "qemu/help_option.h"
37 #include "qemu/module.h"
38 #include "qemu/option.h"
39 #include "qemu/id.h"
40 #include "qemu/coroutine.h"
41 #include "qemu/yank.h"
42 
43 #include "chardev-internal.h"
44 
45 /***********************************************************/
46 /* character device */
47 
48 Object *get_chardevs_root(void)
49 {
50     return container_get(object_get_root(), "/chardevs");
51 }
52 
53 static void chr_be_event(Chardev *s, QEMUChrEvent event)
54 {
55     CharBackend *be = s->be;
56 
57     if (!be || !be->chr_event) {
58         return;
59     }
60 
61     be->chr_event(be->opaque, event);
62 }
63 
64 void qemu_chr_be_event(Chardev *s, QEMUChrEvent event)
65 {
66     /* Keep track if the char device is open */
67     switch (event) {
68         case CHR_EVENT_OPENED:
69             s->be_open = 1;
70             break;
71         case CHR_EVENT_CLOSED:
72             s->be_open = 0;
73             break;
74     case CHR_EVENT_BREAK:
75     case CHR_EVENT_MUX_IN:
76     case CHR_EVENT_MUX_OUT:
77         /* Ignore */
78         break;
79     }
80 
81     CHARDEV_GET_CLASS(s)->chr_be_event(s, event);
82 }
83 
84 /* Not reporting errors from writing to logfile, as logs are
85  * defined to be "best effort" only */
86 static void qemu_chr_write_log(Chardev *s, const uint8_t *buf, size_t len)
87 {
88     size_t done = 0;
89     ssize_t ret;
90 
91     if (s->logfd < 0) {
92         return;
93     }
94 
95     while (done < len) {
96     retry:
97         ret = write(s->logfd, buf + done, len - done);
98         if (ret == -1 && errno == EAGAIN) {
99             g_usleep(100);
100             goto retry;
101         }
102 
103         if (ret <= 0) {
104             return;
105         }
106         done += ret;
107     }
108 }
109 
110 static int qemu_chr_write_buffer(Chardev *s,
111                                  const uint8_t *buf, int len,
112                                  int *offset, bool write_all)
113 {
114     ChardevClass *cc = CHARDEV_GET_CLASS(s);
115     int res = 0;
116     *offset = 0;
117 
118     qemu_mutex_lock(&s->chr_write_lock);
119     while (*offset < len) {
120     retry:
121         res = cc->chr_write(s, buf + *offset, len - *offset);
122         if (res < 0 && errno == EAGAIN && write_all) {
123             if (qemu_in_coroutine()) {
124                 qemu_co_sleep_ns(QEMU_CLOCK_REALTIME, 100000);
125             } else {
126                 g_usleep(100);
127             }
128             goto retry;
129         }
130 
131         if (res <= 0) {
132             break;
133         }
134 
135         *offset += res;
136         if (!write_all) {
137             break;
138         }
139     }
140     if (*offset > 0) {
141         /*
142          * If some data was written by backend, we should
143          * only log what was actually written. This method
144          * may be invoked again to write the remaining
145          * method, thus we'll log the remainder at that time.
146          */
147         qemu_chr_write_log(s, buf, *offset);
148     } else if (res < 0) {
149         /*
150          * If a fatal error was reported by the backend,
151          * assume this method won't be invoked again with
152          * this buffer, so log it all right away.
153          */
154         qemu_chr_write_log(s, buf, len);
155     }
156     qemu_mutex_unlock(&s->chr_write_lock);
157 
158     return res;
159 }
160 
161 int qemu_chr_write(Chardev *s, const uint8_t *buf, int len, bool write_all)
162 {
163     int offset = 0;
164     int res;
165 
166     if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_PLAY) {
167         replay_char_write_event_load(&res, &offset);
168         assert(offset <= len);
169         qemu_chr_write_buffer(s, buf, offset, &offset, true);
170         return res;
171     }
172 
173     res = qemu_chr_write_buffer(s, buf, len, &offset, write_all);
174 
175     if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
176         replay_char_write_event_save(res, offset);
177     }
178 
179     if (res < 0) {
180         return res;
181     }
182     return offset;
183 }
184 
185 int qemu_chr_be_can_write(Chardev *s)
186 {
187     CharBackend *be = s->be;
188 
189     if (!be || !be->chr_can_read) {
190         return 0;
191     }
192 
193     return be->chr_can_read(be->opaque);
194 }
195 
196 void qemu_chr_be_write_impl(Chardev *s, uint8_t *buf, int len)
197 {
198     CharBackend *be = s->be;
199 
200     if (be && be->chr_read) {
201         be->chr_read(be->opaque, buf, len);
202     }
203 }
204 
205 void qemu_chr_be_write(Chardev *s, uint8_t *buf, int len)
206 {
207     if (qemu_chr_replay(s)) {
208         if (replay_mode == REPLAY_MODE_PLAY) {
209             return;
210         }
211         replay_chr_be_write(s, buf, len);
212     } else {
213         qemu_chr_be_write_impl(s, buf, len);
214     }
215 }
216 
217 void qemu_chr_be_update_read_handlers(Chardev *s,
218                                       GMainContext *context)
219 {
220     ChardevClass *cc = CHARDEV_GET_CLASS(s);
221 
222     assert(qemu_chr_has_feature(s, QEMU_CHAR_FEATURE_GCONTEXT)
223            || !context);
224     s->gcontext = context;
225     if (cc->chr_update_read_handler) {
226         cc->chr_update_read_handler(s);
227     }
228 }
229 
230 int qemu_chr_add_client(Chardev *s, int fd)
231 {
232     return CHARDEV_GET_CLASS(s)->chr_add_client ?
233         CHARDEV_GET_CLASS(s)->chr_add_client(s, fd) : -1;
234 }
235 
236 static void qemu_char_open(Chardev *chr, ChardevBackend *backend,
237                            bool *be_opened, Error **errp)
238 {
239     ChardevClass *cc = CHARDEV_GET_CLASS(chr);
240     /* Any ChardevCommon member would work */
241     ChardevCommon *common = backend ? backend->u.null.data : NULL;
242 
243     if (common && common->has_logfile) {
244         int flags = O_WRONLY | O_CREAT;
245         if (common->has_logappend &&
246             common->logappend) {
247             flags |= O_APPEND;
248         } else {
249             flags |= O_TRUNC;
250         }
251         chr->logfd = qemu_open_old(common->logfile, flags, 0666);
252         if (chr->logfd < 0) {
253             error_setg_errno(errp, errno,
254                              "Unable to open logfile %s",
255                              common->logfile);
256             return;
257         }
258     }
259 
260     if (cc->open) {
261         cc->open(chr, backend, be_opened, errp);
262     }
263 }
264 
265 static void char_init(Object *obj)
266 {
267     Chardev *chr = CHARDEV(obj);
268 
269     chr->handover_yank_instance = false;
270     chr->logfd = -1;
271     qemu_mutex_init(&chr->chr_write_lock);
272 
273     /*
274      * Assume if chr_update_read_handler is implemented it will
275      * take the updated gcontext into account.
276      */
277     if (CHARDEV_GET_CLASS(chr)->chr_update_read_handler) {
278         qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT);
279     }
280 
281 }
282 
283 static int null_chr_write(Chardev *chr, const uint8_t *buf, int len)
284 {
285     return len;
286 }
287 
288 static void char_class_init(ObjectClass *oc, void *data)
289 {
290     ChardevClass *cc = CHARDEV_CLASS(oc);
291 
292     cc->chr_write = null_chr_write;
293     cc->chr_be_event = chr_be_event;
294 }
295 
296 static void char_finalize(Object *obj)
297 {
298     Chardev *chr = CHARDEV(obj);
299 
300     if (chr->be) {
301         chr->be->chr = NULL;
302     }
303     g_free(chr->filename);
304     g_free(chr->label);
305     if (chr->logfd != -1) {
306         close(chr->logfd);
307     }
308     qemu_mutex_destroy(&chr->chr_write_lock);
309 }
310 
311 static const TypeInfo char_type_info = {
312     .name = TYPE_CHARDEV,
313     .parent = TYPE_OBJECT,
314     .instance_size = sizeof(Chardev),
315     .instance_init = char_init,
316     .instance_finalize = char_finalize,
317     .abstract = true,
318     .class_size = sizeof(ChardevClass),
319     .class_init = char_class_init,
320 };
321 
322 static bool qemu_chr_is_busy(Chardev *s)
323 {
324     if (CHARDEV_IS_MUX(s)) {
325         MuxChardev *d = MUX_CHARDEV(s);
326         return d->mux_cnt >= 0;
327     } else {
328         return s->be != NULL;
329     }
330 }
331 
332 int qemu_chr_wait_connected(Chardev *chr, Error **errp)
333 {
334     ChardevClass *cc = CHARDEV_GET_CLASS(chr);
335 
336     if (cc->chr_wait_connected) {
337         return cc->chr_wait_connected(chr, errp);
338     }
339 
340     return 0;
341 }
342 
343 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename,
344                                 bool permit_mux_mon)
345 {
346     char host[65], port[33], width[8], height[8];
347     int pos;
348     const char *p;
349     QemuOpts *opts;
350     Error *local_err = NULL;
351 
352     opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
353     if (local_err) {
354         error_report_err(local_err);
355         return NULL;
356     }
357 
358     if (strstart(filename, "mon:", &p)) {
359         if (!permit_mux_mon) {
360             error_report("mon: isn't supported in this context");
361             return NULL;
362         }
363         filename = p;
364         qemu_opt_set(opts, "mux", "on", &error_abort);
365         if (strcmp(filename, "stdio") == 0) {
366             /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
367              * but pass it to the guest.  Handle this only for compat syntax,
368              * for -chardev syntax we have special option for this.
369              * This is what -nographic did, redirecting+muxing serial+monitor
370              * to stdio causing Ctrl+C to be passed to guest. */
371             qemu_opt_set(opts, "signal", "off", &error_abort);
372         }
373     }
374 
375     if (strcmp(filename, "null")    == 0 ||
376         strcmp(filename, "pty")     == 0 ||
377         strcmp(filename, "msmouse") == 0 ||
378         strcmp(filename, "wctablet") == 0 ||
379         strcmp(filename, "braille") == 0 ||
380         strcmp(filename, "testdev") == 0 ||
381         strcmp(filename, "stdio")   == 0) {
382         qemu_opt_set(opts, "backend", filename, &error_abort);
383         return opts;
384     }
385     if (strstart(filename, "vc", &p)) {
386         qemu_opt_set(opts, "backend", "vc", &error_abort);
387         if (*p == ':') {
388             if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
389                 /* pixels */
390                 qemu_opt_set(opts, "width", width, &error_abort);
391                 qemu_opt_set(opts, "height", height, &error_abort);
392             } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
393                 /* chars */
394                 qemu_opt_set(opts, "cols", width, &error_abort);
395                 qemu_opt_set(opts, "rows", height, &error_abort);
396             } else {
397                 goto fail;
398             }
399         }
400         return opts;
401     }
402     if (strcmp(filename, "con:") == 0) {
403         qemu_opt_set(opts, "backend", "console", &error_abort);
404         return opts;
405     }
406     if (strstart(filename, "COM", NULL)) {
407         qemu_opt_set(opts, "backend", "serial", &error_abort);
408         qemu_opt_set(opts, "path", filename, &error_abort);
409         return opts;
410     }
411     if (strstart(filename, "file:", &p)) {
412         qemu_opt_set(opts, "backend", "file", &error_abort);
413         qemu_opt_set(opts, "path", p, &error_abort);
414         return opts;
415     }
416     if (strstart(filename, "pipe:", &p)) {
417         qemu_opt_set(opts, "backend", "pipe", &error_abort);
418         qemu_opt_set(opts, "path", p, &error_abort);
419         return opts;
420     }
421     if (strstart(filename, "tcp:", &p) ||
422         strstart(filename, "telnet:", &p) ||
423         strstart(filename, "tn3270:", &p) ||
424         strstart(filename, "websocket:", &p)) {
425         if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
426             host[0] = 0;
427             if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
428                 goto fail;
429         }
430         qemu_opt_set(opts, "backend", "socket", &error_abort);
431         qemu_opt_set(opts, "host", host, &error_abort);
432         qemu_opt_set(opts, "port", port, &error_abort);
433         if (p[pos] == ',') {
434             if (!qemu_opts_do_parse(opts, p + pos + 1, NULL, &local_err)) {
435                 error_report_err(local_err);
436                 goto fail;
437             }
438         }
439         if (strstart(filename, "telnet:", &p)) {
440             qemu_opt_set(opts, "telnet", "on", &error_abort);
441         } else if (strstart(filename, "tn3270:", &p)) {
442             qemu_opt_set(opts, "tn3270", "on", &error_abort);
443         } else if (strstart(filename, "websocket:", &p)) {
444             qemu_opt_set(opts, "websocket", "on", &error_abort);
445         }
446         return opts;
447     }
448     if (strstart(filename, "udp:", &p)) {
449         qemu_opt_set(opts, "backend", "udp", &error_abort);
450         if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
451             host[0] = 0;
452             if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
453                 goto fail;
454             }
455         }
456         qemu_opt_set(opts, "host", host, &error_abort);
457         qemu_opt_set(opts, "port", port, &error_abort);
458         if (p[pos] == '@') {
459             p += pos + 1;
460             if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
461                 host[0] = 0;
462                 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
463                     goto fail;
464                 }
465             }
466             qemu_opt_set(opts, "localaddr", host, &error_abort);
467             qemu_opt_set(opts, "localport", port, &error_abort);
468         }
469         return opts;
470     }
471     if (strstart(filename, "unix:", &p)) {
472         qemu_opt_set(opts, "backend", "socket", &error_abort);
473         if (!qemu_opts_do_parse(opts, p, "path", &local_err)) {
474             error_report_err(local_err);
475             goto fail;
476         }
477         return opts;
478     }
479     if (strstart(filename, "/dev/parport", NULL) ||
480         strstart(filename, "/dev/ppi", NULL)) {
481         qemu_opt_set(opts, "backend", "parallel", &error_abort);
482         qemu_opt_set(opts, "path", filename, &error_abort);
483         return opts;
484     }
485     if (strstart(filename, "/dev/", NULL)) {
486         qemu_opt_set(opts, "backend", "serial", &error_abort);
487         qemu_opt_set(opts, "path", filename, &error_abort);
488         return opts;
489     }
490 
491     error_report("'%s' is not a valid char driver", filename);
492 
493 fail:
494     qemu_opts_del(opts);
495     return NULL;
496 }
497 
498 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
499 {
500     const char *logfile = qemu_opt_get(opts, "logfile");
501 
502     backend->has_logfile = logfile != NULL;
503     backend->logfile = g_strdup(logfile);
504 
505     backend->has_logappend = true;
506     backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
507 }
508 
509 static const ChardevClass *char_get_class(const char *driver, Error **errp)
510 {
511     ObjectClass *oc;
512     const ChardevClass *cc;
513     char *typename = g_strdup_printf("chardev-%s", driver);
514 
515     oc = module_object_class_by_name(typename);
516     g_free(typename);
517 
518     if (!object_class_dynamic_cast(oc, TYPE_CHARDEV)) {
519         error_setg(errp, "'%s' is not a valid char driver name", driver);
520         return NULL;
521     }
522 
523     if (object_class_is_abstract(oc)) {
524         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "driver",
525                    "an abstract device type");
526         return NULL;
527     }
528 
529     cc = CHARDEV_CLASS(oc);
530     if (cc->internal) {
531         error_setg(errp, "'%s' is not a valid char driver name", driver);
532         return NULL;
533     }
534 
535     return cc;
536 }
537 
538 static struct ChardevAlias {
539     const char *typename;
540     const char *alias;
541     bool deprecation_warning_printed;
542 } chardev_alias_table[] = {
543 #ifdef HAVE_CHARDEV_PARPORT
544     { "parallel", "parport" },
545 #endif
546 #ifdef HAVE_CHARDEV_SERIAL
547     { "serial", "tty" },
548 #endif
549 };
550 
551 typedef struct ChadevClassFE {
552     void (*fn)(const char *name, void *opaque);
553     void *opaque;
554 } ChadevClassFE;
555 
556 static void
557 chardev_class_foreach(ObjectClass *klass, void *opaque)
558 {
559     ChadevClassFE *fe = opaque;
560 
561     assert(g_str_has_prefix(object_class_get_name(klass), "chardev-"));
562     if (CHARDEV_CLASS(klass)->internal) {
563         return;
564     }
565 
566     fe->fn(object_class_get_name(klass) + 8, fe->opaque);
567 }
568 
569 static void
570 chardev_name_foreach(void (*fn)(const char *name, void *opaque),
571                      void *opaque)
572 {
573     ChadevClassFE fe = { .fn = fn, .opaque = opaque };
574 
575     object_class_foreach(chardev_class_foreach, TYPE_CHARDEV, false, &fe);
576 }
577 
578 static void
579 help_string_append(const char *name, void *opaque)
580 {
581     GString *str = opaque;
582 
583     g_string_append_printf(str, "\n  %s", name);
584 }
585 
586 static const char *chardev_alias_translate(const char *name)
587 {
588     int i;
589     for (i = 0; i < (int)ARRAY_SIZE(chardev_alias_table); i++) {
590         if (g_strcmp0(chardev_alias_table[i].alias, name) == 0) {
591             if (!chardev_alias_table[i].deprecation_warning_printed) {
592                 warn_report("The alias '%s' is deprecated, use '%s' instead",
593                             name, chardev_alias_table[i].typename);
594                 chardev_alias_table[i].deprecation_warning_printed = true;
595             }
596             return chardev_alias_table[i].typename;
597         }
598     }
599     return name;
600 }
601 
602 ChardevBackend *qemu_chr_parse_opts(QemuOpts *opts, Error **errp)
603 {
604     Error *local_err = NULL;
605     const ChardevClass *cc;
606     ChardevBackend *backend = NULL;
607     const char *name = chardev_alias_translate(qemu_opt_get(opts, "backend"));
608 
609     if (name == NULL) {
610         error_setg(errp, "chardev: \"%s\" missing backend",
611                    qemu_opts_id(opts));
612         return NULL;
613     }
614 
615     cc = char_get_class(name, errp);
616     if (cc == NULL) {
617         return NULL;
618     }
619 
620     backend = g_new0(ChardevBackend, 1);
621     backend->type = CHARDEV_BACKEND_KIND_NULL;
622 
623     if (cc->parse) {
624         cc->parse(opts, backend, &local_err);
625         if (local_err) {
626             error_propagate(errp, local_err);
627             qapi_free_ChardevBackend(backend);
628             return NULL;
629         }
630     } else {
631         ChardevCommon *ccom = g_new0(ChardevCommon, 1);
632         qemu_chr_parse_common(opts, ccom);
633         backend->u.null.data = ccom; /* Any ChardevCommon member would work */
634     }
635 
636     return backend;
637 }
638 
639 Chardev *qemu_chr_new_from_opts(QemuOpts *opts, GMainContext *context,
640                                 Error **errp)
641 {
642     const ChardevClass *cc;
643     Chardev *chr = NULL;
644     ChardevBackend *backend = NULL;
645     const char *name = chardev_alias_translate(qemu_opt_get(opts, "backend"));
646     const char *id = qemu_opts_id(opts);
647     char *bid = NULL;
648 
649     if (name && is_help_option(name)) {
650         GString *str = g_string_new("");
651 
652         chardev_name_foreach(help_string_append, str);
653 
654         qemu_printf("Available chardev backend types: %s\n", str->str);
655         g_string_free(str, true);
656         return NULL;
657     }
658 
659     if (id == NULL) {
660         error_setg(errp, "chardev: no id specified");
661         return NULL;
662     }
663 
664     backend = qemu_chr_parse_opts(opts, errp);
665     if (backend == NULL) {
666         return NULL;
667     }
668 
669     cc = char_get_class(name, errp);
670     if (cc == NULL) {
671         goto out;
672     }
673 
674     if (qemu_opt_get_bool(opts, "mux", 0)) {
675         bid = g_strdup_printf("%s-base", id);
676     }
677 
678     chr = qemu_chardev_new(bid ? bid : id,
679                            object_class_get_name(OBJECT_CLASS(cc)),
680                            backend, context, errp);
681 
682     if (chr == NULL) {
683         goto out;
684     }
685 
686     if (bid) {
687         Chardev *mux;
688         qapi_free_ChardevBackend(backend);
689         backend = g_new0(ChardevBackend, 1);
690         backend->type = CHARDEV_BACKEND_KIND_MUX;
691         backend->u.mux.data = g_new0(ChardevMux, 1);
692         backend->u.mux.data->chardev = g_strdup(bid);
693         mux = qemu_chardev_new(id, TYPE_CHARDEV_MUX, backend, context, errp);
694         if (mux == NULL) {
695             object_unparent(OBJECT(chr));
696             chr = NULL;
697             goto out;
698         }
699         chr = mux;
700     }
701 
702 out:
703     qapi_free_ChardevBackend(backend);
704     g_free(bid);
705     return chr;
706 }
707 
708 Chardev *qemu_chr_new_noreplay(const char *label, const char *filename,
709                                bool permit_mux_mon, GMainContext *context)
710 {
711     const char *p;
712     Chardev *chr;
713     QemuOpts *opts;
714     Error *err = NULL;
715 
716     if (strstart(filename, "chardev:", &p)) {
717         return qemu_chr_find(p);
718     }
719 
720     opts = qemu_chr_parse_compat(label, filename, permit_mux_mon);
721     if (!opts)
722         return NULL;
723 
724     chr = qemu_chr_new_from_opts(opts, context, &err);
725     if (!chr) {
726         error_report_err(err);
727         goto out;
728     }
729 
730     if (qemu_opt_get_bool(opts, "mux", 0)) {
731         assert(permit_mux_mon);
732         monitor_init_hmp(chr, true, &err);
733         if (err) {
734             error_report_err(err);
735             object_unparent(OBJECT(chr));
736             chr = NULL;
737             goto out;
738         }
739     }
740 
741 out:
742     qemu_opts_del(opts);
743     return chr;
744 }
745 
746 static Chardev *qemu_chr_new_permit_mux_mon(const char *label,
747                                           const char *filename,
748                                           bool permit_mux_mon,
749                                           GMainContext *context)
750 {
751     Chardev *chr;
752     chr = qemu_chr_new_noreplay(label, filename, permit_mux_mon, context);
753     if (chr) {
754         if (replay_mode != REPLAY_MODE_NONE) {
755             qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_REPLAY);
756         }
757         if (qemu_chr_replay(chr) && CHARDEV_GET_CLASS(chr)->chr_ioctl) {
758             error_report("Replay: ioctl is not supported "
759                          "for serial devices yet");
760         }
761         replay_register_char_driver(chr);
762     }
763     return chr;
764 }
765 
766 Chardev *qemu_chr_new(const char *label, const char *filename,
767                       GMainContext *context)
768 {
769     return qemu_chr_new_permit_mux_mon(label, filename, false, context);
770 }
771 
772 Chardev *qemu_chr_new_mux_mon(const char *label, const char *filename,
773                               GMainContext *context)
774 {
775     return qemu_chr_new_permit_mux_mon(label, filename, true, context);
776 }
777 
778 static int qmp_query_chardev_foreach(Object *obj, void *data)
779 {
780     Chardev *chr = CHARDEV(obj);
781     ChardevInfoList **list = data;
782     ChardevInfo *value = g_malloc0(sizeof(*value));
783 
784     value->label = g_strdup(chr->label);
785     value->filename = g_strdup(chr->filename);
786     value->frontend_open = chr->be && chr->be->fe_open;
787 
788     QAPI_LIST_PREPEND(*list, value);
789 
790     return 0;
791 }
792 
793 ChardevInfoList *qmp_query_chardev(Error **errp)
794 {
795     ChardevInfoList *chr_list = NULL;
796 
797     object_child_foreach(get_chardevs_root(),
798                          qmp_query_chardev_foreach, &chr_list);
799 
800     return chr_list;
801 }
802 
803 static void
804 qmp_prepend_backend(const char *name, void *opaque)
805 {
806     ChardevBackendInfoList **list = opaque;
807     ChardevBackendInfo *value;
808 
809     value = g_new0(ChardevBackendInfo, 1);
810     value->name = g_strdup(name);
811     QAPI_LIST_PREPEND(*list, value);
812 }
813 
814 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
815 {
816     ChardevBackendInfoList *backend_list = NULL;
817 
818     chardev_name_foreach(qmp_prepend_backend, &backend_list);
819 
820     return backend_list;
821 }
822 
823 Chardev *qemu_chr_find(const char *name)
824 {
825     Object *obj = object_resolve_path_component(get_chardevs_root(), name);
826 
827     return obj ? CHARDEV(obj) : NULL;
828 }
829 
830 QemuOptsList qemu_chardev_opts = {
831     .name = "chardev",
832     .implied_opt_name = "backend",
833     .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
834     .desc = {
835         {
836             .name = "backend",
837             .type = QEMU_OPT_STRING,
838         },{
839             .name = "path",
840             .type = QEMU_OPT_STRING,
841         },{
842             .name = "host",
843             .type = QEMU_OPT_STRING,
844         },{
845             .name = "port",
846             .type = QEMU_OPT_STRING,
847         },{
848             .name = "fd",
849             .type = QEMU_OPT_STRING,
850         },{
851             .name = "localaddr",
852             .type = QEMU_OPT_STRING,
853         },{
854             .name = "localport",
855             .type = QEMU_OPT_STRING,
856         },{
857             .name = "to",
858             .type = QEMU_OPT_NUMBER,
859         },{
860             .name = "ipv4",
861             .type = QEMU_OPT_BOOL,
862         },{
863             .name = "ipv6",
864             .type = QEMU_OPT_BOOL,
865         },{
866             .name = "wait",
867             .type = QEMU_OPT_BOOL,
868         },{
869             .name = "server",
870             .type = QEMU_OPT_BOOL,
871         },{
872             .name = "delay",
873             .type = QEMU_OPT_BOOL,
874         },{
875             .name = "nodelay",
876             .type = QEMU_OPT_BOOL,
877         },{
878             .name = "reconnect",
879             .type = QEMU_OPT_NUMBER,
880         },{
881             .name = "telnet",
882             .type = QEMU_OPT_BOOL,
883         },{
884             .name = "tn3270",
885             .type = QEMU_OPT_BOOL,
886         },{
887             .name = "tls-creds",
888             .type = QEMU_OPT_STRING,
889         },{
890             .name = "tls-authz",
891             .type = QEMU_OPT_STRING,
892         },{
893             .name = "websocket",
894             .type = QEMU_OPT_BOOL,
895         },{
896             .name = "width",
897             .type = QEMU_OPT_NUMBER,
898         },{
899             .name = "height",
900             .type = QEMU_OPT_NUMBER,
901         },{
902             .name = "cols",
903             .type = QEMU_OPT_NUMBER,
904         },{
905             .name = "rows",
906             .type = QEMU_OPT_NUMBER,
907         },{
908             .name = "mux",
909             .type = QEMU_OPT_BOOL,
910         },{
911             .name = "signal",
912             .type = QEMU_OPT_BOOL,
913         },{
914             .name = "name",
915             .type = QEMU_OPT_STRING,
916         },{
917             .name = "debug",
918             .type = QEMU_OPT_NUMBER,
919         },{
920             .name = "size",
921             .type = QEMU_OPT_SIZE,
922         },{
923             .name = "chardev",
924             .type = QEMU_OPT_STRING,
925         },{
926             .name = "append",
927             .type = QEMU_OPT_BOOL,
928         },{
929             .name = "logfile",
930             .type = QEMU_OPT_STRING,
931         },{
932             .name = "logappend",
933             .type = QEMU_OPT_BOOL,
934         },{
935             .name = "mouse",
936             .type = QEMU_OPT_BOOL,
937         },{
938             .name = "clipboard",
939             .type = QEMU_OPT_BOOL,
940 #ifdef CONFIG_LINUX
941         },{
942             .name = "tight",
943             .type = QEMU_OPT_BOOL,
944             .def_value_str = "on",
945         },{
946             .name = "abstract",
947             .type = QEMU_OPT_BOOL,
948 #endif
949         },
950         { /* end of list */ }
951     },
952 };
953 
954 bool qemu_chr_has_feature(Chardev *chr,
955                           ChardevFeature feature)
956 {
957     return test_bit(feature, chr->features);
958 }
959 
960 void qemu_chr_set_feature(Chardev *chr,
961                            ChardevFeature feature)
962 {
963     return set_bit(feature, chr->features);
964 }
965 
966 static Chardev *chardev_new(const char *id, const char *typename,
967                             ChardevBackend *backend,
968                             GMainContext *gcontext,
969                             bool handover_yank_instance,
970                             Error **errp)
971 {
972     Object *obj;
973     Chardev *chr = NULL;
974     Error *local_err = NULL;
975     bool be_opened = true;
976 
977     assert(g_str_has_prefix(typename, "chardev-"));
978     assert(id);
979 
980     obj = object_new(typename);
981     chr = CHARDEV(obj);
982     chr->handover_yank_instance = handover_yank_instance;
983     chr->label = g_strdup(id);
984     chr->gcontext = gcontext;
985 
986     qemu_char_open(chr, backend, &be_opened, &local_err);
987     if (local_err) {
988         error_propagate(errp, local_err);
989         object_unref(obj);
990         return NULL;
991     }
992 
993     if (!chr->filename) {
994         chr->filename = g_strdup(typename + 8);
995     }
996     if (be_opened) {
997         qemu_chr_be_event(chr, CHR_EVENT_OPENED);
998     }
999 
1000     return chr;
1001 }
1002 
1003 Chardev *qemu_chardev_new(const char *id, const char *typename,
1004                           ChardevBackend *backend,
1005                           GMainContext *gcontext,
1006                           Error **errp)
1007 {
1008     Chardev *chr;
1009     g_autofree char *genid = NULL;
1010 
1011     if (!id) {
1012         genid = id_generate(ID_CHR);
1013         id = genid;
1014     }
1015 
1016     chr = chardev_new(id, typename, backend, gcontext, false, errp);
1017     if (!chr) {
1018         return NULL;
1019     }
1020 
1021     if (!object_property_try_add_child(get_chardevs_root(), id, OBJECT(chr),
1022                                        errp)) {
1023         object_unref(OBJECT(chr));
1024         return NULL;
1025     }
1026     object_unref(OBJECT(chr));
1027 
1028     return chr;
1029 }
1030 
1031 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
1032                                Error **errp)
1033 {
1034     ERRP_GUARD();
1035     const ChardevClass *cc;
1036     ChardevReturn *ret;
1037     g_autoptr(Chardev) chr = NULL;
1038 
1039     if (qemu_chr_find(id)) {
1040         error_setg(errp, "Chardev with id '%s' already exists", id);
1041         return NULL;
1042     }
1043 
1044     cc = char_get_class(ChardevBackendKind_str(backend->type), errp);
1045     if (!cc) {
1046         goto err;
1047     }
1048 
1049     chr = chardev_new(id, object_class_get_name(OBJECT_CLASS(cc)),
1050                       backend, NULL, false, errp);
1051     if (!chr) {
1052         goto err;
1053     }
1054 
1055     if (!object_property_try_add_child(get_chardevs_root(), id, OBJECT(chr),
1056                                        errp)) {
1057         goto err;
1058     }
1059 
1060     ret = g_new0(ChardevReturn, 1);
1061     if (CHARDEV_IS_PTY(chr)) {
1062         ret->pty = g_strdup(chr->filename + 4);
1063         ret->has_pty = true;
1064     }
1065 
1066     return ret;
1067 
1068 err:
1069     error_prepend(errp, "Failed to add chardev '%s': ", id);
1070     return NULL;
1071 }
1072 
1073 ChardevReturn *qmp_chardev_change(const char *id, ChardevBackend *backend,
1074                                   Error **errp)
1075 {
1076     CharBackend *be;
1077     const ChardevClass *cc, *cc_new;
1078     Chardev *chr, *chr_new;
1079     bool closed_sent = false;
1080     bool handover_yank_instance;
1081     ChardevReturn *ret;
1082 
1083     chr = qemu_chr_find(id);
1084     if (!chr) {
1085         error_setg(errp, "Chardev '%s' does not exist", id);
1086         return NULL;
1087     }
1088 
1089     if (CHARDEV_IS_MUX(chr)) {
1090         error_setg(errp, "Mux device hotswap not supported yet");
1091         return NULL;
1092     }
1093 
1094     if (qemu_chr_replay(chr)) {
1095         error_setg(errp,
1096             "Chardev '%s' cannot be changed in record/replay mode", id);
1097         return NULL;
1098     }
1099 
1100     be = chr->be;
1101     if (!be) {
1102         /* easy case */
1103         object_unparent(OBJECT(chr));
1104         return qmp_chardev_add(id, backend, errp);
1105     }
1106 
1107     if (!be->chr_be_change) {
1108         error_setg(errp, "Chardev user does not support chardev hotswap");
1109         return NULL;
1110     }
1111 
1112     cc = CHARDEV_GET_CLASS(chr);
1113     cc_new = char_get_class(ChardevBackendKind_str(backend->type), errp);
1114     if (!cc_new) {
1115         return NULL;
1116     }
1117 
1118     /*
1119      * The new chardev should not register a yank instance if the current
1120      * chardev has registered one already.
1121      */
1122     handover_yank_instance = cc->supports_yank && cc_new->supports_yank;
1123 
1124     chr_new = chardev_new(id, object_class_get_name(OBJECT_CLASS(cc_new)),
1125                           backend, chr->gcontext, handover_yank_instance, errp);
1126     if (!chr_new) {
1127         return NULL;
1128     }
1129 
1130     if (chr->be_open && !chr_new->be_open) {
1131         qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1132         closed_sent = true;
1133     }
1134 
1135     chr->be = NULL;
1136     qemu_chr_fe_init(be, chr_new, &error_abort);
1137 
1138     if (be->chr_be_change(be->opaque) < 0) {
1139         error_setg(errp, "Chardev '%s' change failed", chr_new->label);
1140         chr_new->be = NULL;
1141         qemu_chr_fe_init(be, chr, &error_abort);
1142         if (closed_sent) {
1143             qemu_chr_be_event(chr, CHR_EVENT_OPENED);
1144         }
1145         object_unref(OBJECT(chr_new));
1146         return NULL;
1147     }
1148 
1149     /* change successfull, clean up */
1150     chr_new->handover_yank_instance = false;
1151 
1152     /*
1153      * When the old chardev is freed, it should not unregister the yank
1154      * instance if the new chardev needs it.
1155      */
1156     chr->handover_yank_instance = handover_yank_instance;
1157 
1158     object_unparent(OBJECT(chr));
1159     object_property_add_child(get_chardevs_root(), chr_new->label,
1160                               OBJECT(chr_new));
1161     object_unref(OBJECT(chr_new));
1162 
1163     ret = g_new0(ChardevReturn, 1);
1164     if (CHARDEV_IS_PTY(chr_new)) {
1165         ret->pty = g_strdup(chr_new->filename + 4);
1166         ret->has_pty = true;
1167     }
1168 
1169     return ret;
1170 }
1171 
1172 void qmp_chardev_remove(const char *id, Error **errp)
1173 {
1174     Chardev *chr;
1175 
1176     chr = qemu_chr_find(id);
1177     if (chr == NULL) {
1178         error_setg(errp, "Chardev '%s' not found", id);
1179         return;
1180     }
1181     if (qemu_chr_is_busy(chr)) {
1182         error_setg(errp, "Chardev '%s' is busy", id);
1183         return;
1184     }
1185     if (qemu_chr_replay(chr)) {
1186         error_setg(errp,
1187             "Chardev '%s' cannot be unplugged in record/replay mode", id);
1188         return;
1189     }
1190     object_unparent(OBJECT(chr));
1191 }
1192 
1193 void qmp_chardev_send_break(const char *id, Error **errp)
1194 {
1195     Chardev *chr;
1196 
1197     chr = qemu_chr_find(id);
1198     if (chr == NULL) {
1199         error_setg(errp, "Chardev '%s' not found", id);
1200         return;
1201     }
1202     qemu_chr_be_event(chr, CHR_EVENT_BREAK);
1203 }
1204 
1205 /*
1206  * Add a timeout callback for the chardev (in milliseconds), return
1207  * the GSource object created. Please use this to add timeout hook for
1208  * chardev instead of g_timeout_add() and g_timeout_add_seconds(), to
1209  * make sure the gcontext that the task bound to is correct.
1210  */
1211 GSource *qemu_chr_timeout_add_ms(Chardev *chr, guint ms,
1212                                  GSourceFunc func, void *private)
1213 {
1214     GSource *source = g_timeout_source_new(ms);
1215 
1216     assert(func);
1217     g_source_set_callback(source, func, private, NULL);
1218     g_source_attach(source, chr->gcontext);
1219 
1220     return source;
1221 }
1222 
1223 void qemu_chr_cleanup(void)
1224 {
1225     object_unparent(get_chardevs_root());
1226 }
1227 
1228 static void register_types(void)
1229 {
1230     type_register_static(&char_type_info);
1231 }
1232 
1233 type_init(register_types);
1234