tracetool: Add MAINTAINERS info
[qemu/opensuse.git] / error.c
blobd3455ab9e6dbb214d8e86ced200255540e5e2acc
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.
13 #include "qemu-common.h"
14 #include "error.h"
15 #include "qjson.h"
16 #include "qdict.h"
17 #include "error_int.h"
18 #include "qerror.h"
20 struct Error
22 QDict *obj;
23 const char *fmt;
24 char *msg;
27 void error_set(Error **errp, const char *fmt, ...)
29 Error *err;
30 va_list ap;
32 if (errp == NULL) {
33 return;
36 err = g_malloc0(sizeof(*err));
38 va_start(ap, fmt);
39 err->obj = qobject_to_qdict(qobject_from_jsonv(fmt, &ap));
40 va_end(ap);
41 err->fmt = fmt;
43 *errp = err;
46 Error *error_copy(const Error *err)
48 Error *err_new;
50 err_new = g_malloc0(sizeof(*err));
51 err_new->msg = g_strdup(err->msg);
52 err_new->fmt = err->fmt;
53 err_new->obj = err->obj;
54 QINCREF(err_new->obj);
56 return err_new;
59 bool error_is_set(Error **errp)
61 return (errp && *errp);
64 const char *error_get_pretty(Error *err)
66 if (err->msg == NULL) {
67 QString *str;
68 str = qerror_format(err->fmt, err->obj);
69 err->msg = g_strdup(qstring_get_str(str));
70 QDECREF(str);
73 return err->msg;
76 const char *error_get_field(Error *err, const char *field)
78 if (strcmp(field, "class") == 0) {
79 return qdict_get_str(err->obj, field);
80 } else {
81 QDict *dict = qdict_get_qdict(err->obj, "data");
82 return qdict_get_str(dict, field);
86 QDict *error_get_data(Error *err)
88 QDict *data = qdict_get_qdict(err->obj, "data");
89 QINCREF(data);
90 return data;
93 void error_set_field(Error *err, const char *field, const char *value)
95 QDict *dict = qdict_get_qdict(err->obj, "data");
96 return qdict_put(dict, field, qstring_from_str(value));
99 void error_free(Error *err)
101 if (err) {
102 QDECREF(err->obj);
103 g_free(err->msg);
104 g_free(err);
108 bool error_is_type(Error *err, const char *fmt)
110 const char *error_class;
111 char *ptr;
112 char *end;
114 if (!err) {
115 return false;
118 ptr = strstr(fmt, "'class': '");
119 assert(ptr != NULL);
120 ptr += strlen("'class': '");
122 end = strchr(ptr, '\'');
123 assert(end != NULL);
125 error_class = error_get_field(err, "class");
126 if (strlen(error_class) != end - ptr) {
127 return false;
130 return strncmp(ptr, error_class, end - ptr) == 0;
133 void error_propagate(Error **dst_err, Error *local_err)
135 if (dst_err) {
136 *dst_err = local_err;
137 } else if (local_err) {
138 error_free(local_err);
142 QObject *error_get_qobject(Error *err)
144 QINCREF(err->obj);
145 return QOBJECT(err->obj);
148 void error_set_qobject(Error **errp, QObject *obj)
150 Error *err;
151 if (errp == NULL) {
152 return;
154 err = g_malloc0(sizeof(*err));
155 err->obj = qobject_to_qdict(obj);
156 qobject_incref(obj);
158 *errp = err;