Merge branch 'upstream-merge' into next
[qemu-dev-zwu.git] / error.c
blob867eec2c1af8e5cf555d5068086729e66d1484b2
1 /*
2 * QEMU Error Objects
4 * Copyright IBM, Corp. 2011
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU LGPL, version 2. See
10 * the COPYING.LIB file in the top-level directory.
12 #include "error.h"
13 #include "error_int.h"
14 #include "qemu-objects.h"
15 #include "qerror.h"
16 #include <assert.h>
18 struct Error
20 QDict *obj;
21 const char *fmt;
22 char *msg;
25 void error_set(Error **errp, const char *fmt, ...)
27 Error *err;
28 va_list ap;
30 if (errp == NULL) {
31 return;
34 err = qemu_mallocz(sizeof(*err));
36 va_start(ap, fmt);
37 err->obj = qobject_to_qdict(qobject_from_jsonv(fmt, &ap));
38 va_end(ap);
39 err->fmt = fmt;
41 *errp = err;
44 bool error_is_set(Error **errp)
46 return (errp && *errp);
49 const char *error_get_pretty(Error *err)
51 if (err->msg == NULL) {
52 QString *str;
53 str = qerror_format(err->fmt, err->obj);
54 err->msg = qemu_strdup(qstring_get_str(str));
55 QDECREF(str);
58 return err->msg;
61 const char *error_get_field(Error *err, const char *field)
63 if (strcmp(field, "class") == 0) {
64 return qdict_get_str(err->obj, field);
65 } else {
66 QDict *dict = qdict_get_qdict(err->obj, "data");
67 return qdict_get_str(dict, field);
71 QDict *error_get_data(Error *err)
73 QDict *data = qdict_get_qdict(err->obj, "data");
74 QINCREF(data);
75 return data;
78 void error_set_field(Error *err, const char *field, const char *value)
80 QDict *dict = qdict_get_qdict(err->obj, "data");
81 return qdict_put(dict, field, qstring_from_str(value));
84 void error_free(Error *err)
86 if (err) {
87 QDECREF(err->obj);
88 qemu_free(err->msg);
89 qemu_free(err);
93 bool error_is_type(Error *err, const char *fmt)
95 const char *error_class;
96 char *ptr;
97 char *end;
99 ptr = strstr(fmt, "'class': '");
100 assert(ptr != NULL);
101 ptr += strlen("'class': '");
103 end = strchr(ptr, '\'');
104 assert(end != NULL);
106 error_class = error_get_field(err, "class");
107 if (strlen(error_class) != end - ptr) {
108 return false;
111 return strncmp(ptr, error_class, end - ptr) == 0;
114 void error_propagate(Error **dst_err, Error *local_err)
116 if (dst_err) {
117 *dst_err = local_err;
118 } else if (local_err) {
119 error_free(local_err);
123 QObject *error_get_qobject(Error *err)
125 QINCREF(err->obj);
126 return QOBJECT(err->obj);
129 void error_set_qobject(Error **errp, QObject *obj)
131 Error *err;
132 if (errp == NULL) {
133 return;
135 err = qemu_mallocz(sizeof(*err));
136 err->obj = qobject_to_qdict(obj);
137 qobject_incref(obj);
139 *errp = err;