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