memory: remove memory_region_set_offset()
[qemu-kvm.git] / error.c
blob990050f792f73b7dd04221e3e371ace802fcc456
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 bool error_is_set(Error **errp)
48 return (errp && *errp);
51 const char *error_get_pretty(Error *err)
53 if (err->msg == NULL) {
54 QString *str;
55 str = qerror_format(err->fmt, err->obj);
56 err->msg = g_strdup(qstring_get_str(str));
57 QDECREF(str);
60 return err->msg;
63 const char *error_get_field(Error *err, const char *field)
65 if (strcmp(field, "class") == 0) {
66 return qdict_get_str(err->obj, field);
67 } else {
68 QDict *dict = qdict_get_qdict(err->obj, "data");
69 return qdict_get_str(dict, field);
73 QDict *error_get_data(Error *err)
75 QDict *data = qdict_get_qdict(err->obj, "data");
76 QINCREF(data);
77 return data;
80 void error_set_field(Error *err, const char *field, const char *value)
82 QDict *dict = qdict_get_qdict(err->obj, "data");
83 return qdict_put(dict, field, qstring_from_str(value));
86 void error_free(Error *err)
88 if (err) {
89 QDECREF(err->obj);
90 g_free(err->msg);
91 g_free(err);
95 bool error_is_type(Error *err, const char *fmt)
97 const char *error_class;
98 char *ptr;
99 char *end;
101 if (!err) {
102 return false;
105 ptr = strstr(fmt, "'class': '");
106 assert(ptr != NULL);
107 ptr += strlen("'class': '");
109 end = strchr(ptr, '\'');
110 assert(end != NULL);
112 error_class = error_get_field(err, "class");
113 if (strlen(error_class) != end - ptr) {
114 return false;
117 return strncmp(ptr, error_class, end - ptr) == 0;
120 void error_propagate(Error **dst_err, Error *local_err)
122 if (dst_err) {
123 *dst_err = local_err;
124 } else if (local_err) {
125 error_free(local_err);
129 QObject *error_get_qobject(Error *err)
131 QINCREF(err->obj);
132 return QOBJECT(err->obj);
135 void error_set_qobject(Error **errp, QObject *obj)
137 Error *err;
138 if (errp == NULL) {
139 return;
141 err = g_malloc0(sizeof(*err));
142 err->obj = qobject_to_qdict(obj);
143 qobject_incref(obj);
145 *errp = err;