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