usb: Clean common object and dependency files
[qemu/ar7.git] / error.c
blob58f55a012e76fb111a4b9bddad55b22d1046c211
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;
35 assert(*errp == NULL);
37 err = g_malloc0(sizeof(*err));
39 va_start(ap, fmt);
40 err->obj = qobject_to_qdict(qobject_from_jsonv(fmt, &ap));
41 va_end(ap);
42 err->fmt = fmt;
44 *errp = err;
47 Error *error_copy(const Error *err)
49 Error *err_new;
51 err_new = g_malloc0(sizeof(*err));
52 err_new->msg = g_strdup(err->msg);
53 err_new->fmt = err->fmt;
54 err_new->obj = err->obj;
55 QINCREF(err_new->obj);
57 return err_new;
60 bool error_is_set(Error **errp)
62 return (errp && *errp);
65 const char *error_get_pretty(Error *err)
67 if (err->msg == NULL) {
68 QString *str;
69 str = qerror_format(err->fmt, err->obj);
70 err->msg = g_strdup(qstring_get_str(str));
71 QDECREF(str);
74 return err->msg;
77 const char *error_get_field(Error *err, const char *field)
79 if (strcmp(field, "class") == 0) {
80 return qdict_get_str(err->obj, field);
81 } else {
82 QDict *dict = qdict_get_qdict(err->obj, "data");
83 return qdict_get_str(dict, field);
87 QDict *error_get_data(Error *err)
89 QDict *data = qdict_get_qdict(err->obj, "data");
90 QINCREF(data);
91 return data;
94 void error_set_field(Error *err, const char *field, const char *value)
96 QDict *dict = qdict_get_qdict(err->obj, "data");
97 qdict_put(dict, field, qstring_from_str(value));
100 void error_free(Error *err)
102 if (err) {
103 QDECREF(err->obj);
104 g_free(err->msg);
105 g_free(err);
109 bool error_is_type(Error *err, const char *fmt)
111 const char *error_class;
112 char *ptr;
113 char *end;
115 if (!err) {
116 return false;
119 ptr = strstr(fmt, "'class': '");
120 assert(ptr != NULL);
121 ptr += strlen("'class': '");
123 end = strchr(ptr, '\'');
124 assert(end != NULL);
126 error_class = error_get_field(err, "class");
127 if (strlen(error_class) != end - ptr) {
128 return false;
131 return strncmp(ptr, error_class, end - ptr) == 0;
134 void error_propagate(Error **dst_err, Error *local_err)
136 if (dst_err && !*dst_err) {
137 *dst_err = local_err;
138 } else if (local_err) {
139 error_free(local_err);
143 QObject *error_get_qobject(Error *err)
145 QINCREF(err->obj);
146 return QOBJECT(err->obj);
149 void error_set_qobject(Error **errp, QObject *obj)
151 Error *err;
152 if (errp == NULL) {
153 return;
155 err = g_malloc0(sizeof(*err));
156 err->obj = qobject_to_qdict(obj);
157 qobject_incref(obj);
159 *errp = err;