master
h 567 lines 18.9 KB
Raw
1 /*
2 * QEMU Error Objects
3 *
4 * Copyright IBM, Corp. 2011
5 * Copyright (C) 2011-2015 Red Hat, Inc.
6 *
7 * Authors:
8 * Anthony Liguori <aliguori@us.ibm.com>
9 * Markus Armbruster <armbru@redhat.com>
10 *
11 * This work is licensed under the terms of the GNU LGPL, version 2. See
12 * the COPYING.LIB file in the top-level directory.
13 */
14
15 /*
16 * Error reporting system loosely patterned after Glib's GError.
17 *
18 * = Rules =
19 *
20 * - Functions that use Error to report errors have an Error **errp
21 * parameter. It should be the last parameter, except for functions
22 * taking variable arguments.
23 *
24 * - You may pass NULL to not receive the error, &error_abort to abort
25 * on error, &error_fatal to exit(1) on error, or a pointer to a
26 * variable containing NULL to receive the error.
27 *
28 * - Separation of concerns: the function is responsible for detecting
29 * errors and failing cleanly; handling the error is its caller's
30 * job. Since the value of @errp is about handling the error, the
31 * function should not examine it.
32 *
33 * - The function may pass @errp to functions it calls to pass on
34 * their errors to its caller. If it dereferences @errp to check
35 * for errors, it must use ERRP_GUARD().
36 *
37 * - On success, the function should not touch *errp. On failure, it
38 * should set a new error, e.g. with error_setg(errp, ...), or
39 * propagate an existing one, e.g. with error_propagate(errp, ...).
40 *
41 * - Whenever practical, also return a value that indicates success /
42 * failure. This can make the error checking more concise, and can
43 * avoid useless error object creation and destruction. Note that
44 * we still have many functions returning void. We recommend
45 * • bool-valued functions return true on success / false on failure,
46 * • pointer-valued functions return non-null / null pointer, and
47 * • integer-valued functions return non-negative / negative.
48 *
49 * = Creating errors =
50 *
51 * Create an error:
52 * error_setg(errp, "situation normal, all fouled up");
53 * where @errp points to the location to receive the error.
54 *
55 * Create an error and add additional explanation:
56 * error_setg(errp, "invalid quark");
57 * error_append_hint(errp, "Valid quarks are up, down, strange, "
58 * "charm, top, bottom.\n");
59 * This may require use of ERRP_GUARD(); more on that below.
60 *
61 * Do *not* contract this to
62 * error_setg(errp, "invalid quark\n" // WRONG!
63 * "Valid quarks are up, down, strange, charm, top, bottom.");
64 *
65 * = Reporting and destroying errors =
66 *
67 * Report an error to the current HMP monitor if we have one, else
68 * stderr:
69 * error_report_err(err);
70 * This frees the error object.
71 *
72 * Likewise, but with additional text prepended:
73 * error_reportf_err(err, "Could not frobnicate '%s': ", name);
74 *
75 * Report an error somewhere else:
76 * const char *msg = error_get_pretty(err);
77 * do with msg what needs to be done...
78 * error_free(err);
79 * Note that this loses hints added with error_append_hint().
80 *
81 * Call a function ignoring errors:
82 * foo(arg, NULL);
83 * This is more concise than
84 * Error *err = NULL;
85 * foo(arg, &err);
86 * error_free(err); // don't do this
87 *
88 * Call a function aborting on errors:
89 * foo(arg, &error_abort);
90 * This is more concise and fails more nicely than
91 * Error *err = NULL;
92 * foo(arg, &err);
93 * assert(!err); // don't do this
94 *
95 * Call a function treating errors as fatal:
96 * foo(arg, &error_fatal);
97 * This is more concise than
98 * Error *err = NULL;
99 * foo(arg, &err);
100 * if (err) { // don't do this
101 * error_report_err(err);
102 * exit(1);
103 * }
104 *
105 * Handle an error without reporting it (just for completeness):
106 * error_free(err);
107 *
108 * Assert that an expected error occurred, but clean it up without
109 * reporting it (primarily useful in testsuites):
110 * error_free_or_abort(&err);
111 *
112 * = Passing errors around =
113 *
114 * Errors get passed to the caller through the conventional @errp
115 * parameter.
116 *
117 * Create a new error and pass it to the caller:
118 * error_setg(errp, "situation normal, all fouled up");
119 *
120 * Call a function, receive an error from it, and pass it to the caller
121 * - when the function returns a value that indicates failure, say
122 * false:
123 * if (!foo(arg, errp)) {
124 * handle the error...
125 * }
126 * - when it does not, say because it is a void function:
127 * ERRP_GUARD();
128 * foo(arg, errp);
129 * if (*errp) {
130 * handle the error...
131 * }
132 * More on ERRP_GUARD() below.
133 *
134 * Code predating ERRP_GUARD() still exists, and looks like this:
135 * Error *err = NULL;
136 * foo(arg, &err);
137 * if (err) {
138 * handle the error...
139 * error_propagate(errp, err); // deprecated
140 * }
141 * Avoid in new code. Do *not* "optimize" it to
142 * foo(arg, errp);
143 * if (*errp) { // WRONG!
144 * handle the error...
145 * }
146 * because errp may be NULL without the ERRP_GUARD() guard.
147 *
148 * But when all you do with the error is pass it on, please use
149 * foo(arg, errp);
150 * for readability.
151 *
152 * Receive an error, and handle it locally
153 * - when the function returns a value that indicates failure, say
154 * false:
155 * Error *err = NULL;
156 * if (!foo(arg, &err)) {
157 * handle the error...
158 * }
159 * - when it does not, say because it is a void function:
160 * Error *err = NULL;
161 * foo(arg, &err);
162 * if (err) {
163 * handle the error...
164 * }
165 *
166 * Pass an existing error to the caller:
167 * error_propagate(errp, err);
168 * This is rarely needed. When @err is a local variable, use of
169 * ERRP_GUARD() commonly results in more readable code.
170 *
171 * Pass an existing error to the caller with the message modified:
172 * error_propagate_prepend(errp, err,
173 * "Could not frobnicate '%s': ", name);
174 * This is more concise than
175 * error_propagate(errp, err); // don't do this
176 * error_prepend(errp, "Could not frobnicate '%s': ", name);
177 * and works even when @errp is &error_fatal.
178 *
179 * Receive and accumulate multiple errors (first one wins):
180 * Error *err = NULL, *local_err = NULL;
181 * foo(arg, &err);
182 * bar(arg, &local_err);
183 * error_propagate(&err, local_err);
184 * if (err) {
185 * handle the error...
186 * }
187 *
188 * Do *not* "optimize" this to
189 * Error *err = NULL;
190 * foo(arg, &err);
191 * bar(arg, &err); // WRONG!
192 * if (err) {
193 * handle the error...
194 * }
195 * because this may pass a non-null err to bar().
196 *
197 * Likewise, do *not*
198 * Error *err = NULL;
199 * if (cond1) {
200 * error_setg(&err, ...);
201 * }
202 * if (cond2) {
203 * error_setg(&err, ...); // WRONG!
204 * }
205 * because this may pass a non-null err to error_setg().
206 *
207 * = Why, when and how to use ERRP_GUARD() =
208 *
209 * Without ERRP_GUARD(), use of the @errp parameter is restricted:
210 * - It must not be dereferenced, because it may be null.
211 * - It should not be passed to error_prepend(), error_vprepend(), or
212 * error_append_hint(), because that doesn't work with &error_fatal.
213 * ERRP_GUARD() lifts these restrictions.
214 *
215 * To use ERRP_GUARD(), add it right at the beginning of the function.
216 * @errp can then be used without worrying about the argument being
217 * NULL or &error_fatal.
218 *
219 * Using it when it's not needed is safe, but please avoid cluttering
220 * the source with useless code.
221 *
222 * = Converting to ERRP_GUARD() =
223 *
224 * To convert a function to use ERRP_GUARD():
225 *
226 * 0. If the Error ** parameter is not named @errp, rename it to
227 * @errp.
228 *
229 * 1. Add an ERRP_GUARD() invocation, by convention right at the
230 * beginning of the function. This makes @errp safe to use.
231 *
232 * 2. Replace &err by errp, and err by *errp. Delete local variable
233 * @err.
234 *
235 * 3. Delete error_propagate(errp, *errp), replace
236 * error_propagate_prepend(errp, *errp, ...) by error_prepend(errp, ...)
237 *
238 * 4. Ensure @errp is valid at return: when you destroy *errp, set
239 * *errp = NULL.
240 *
241 * Example:
242 *
243 * bool fn(..., Error **errp)
244 * {
245 * Error *err = NULL;
246 *
247 * foo(arg, &err);
248 * if (err) {
249 * handle the error...
250 * error_propagate(errp, err);
251 * return false;
252 * }
253 * ...
254 * }
255 *
256 * becomes
257 *
258 * bool fn(..., Error **errp)
259 * {
260 * ERRP_GUARD();
261 *
262 * foo(arg, errp);
263 * if (*errp) {
264 * handle the error...
265 * return false;
266 * }
267 * ...
268 * }
269 *
270 * For mass-conversion, use scripts/coccinelle/errp-guard.cocci.
271 */
272
273 #ifndef ERROR_H
274 #define ERROR_H
275
276 #include "qapi/qapi-types-error.h"
277
278 /*
279 * Overall category of an error.
280 * Based on the qapi type QapiErrorClass, but reproduced here for nicer
281 * enum names.
282 */
283 typedef enum ErrorClass {
284 ERROR_CLASS_GENERIC_ERROR = QAPI_ERROR_CLASS_GENERICERROR,
285 ERROR_CLASS_COMMAND_NOT_FOUND = QAPI_ERROR_CLASS_COMMANDNOTFOUND,
286 ERROR_CLASS_DEVICE_NOT_ACTIVE = QAPI_ERROR_CLASS_DEVICENOTACTIVE,
287 ERROR_CLASS_DEVICE_NOT_FOUND = QAPI_ERROR_CLASS_DEVICENOTFOUND,
288 ERROR_CLASS_KVM_MISSING_CAP = QAPI_ERROR_CLASS_KVMMISSINGCAP,
289 } ErrorClass;
290
291 /*
292 * Get @err's human-readable error message.
293 */
294 const char *error_get_pretty(const Error *err);
295
296 /*
297 * Get @err's error class.
298 * Note: use of error classes other than ERROR_CLASS_GENERIC_ERROR is
299 * strongly discouraged.
300 */
301 ErrorClass error_get_class(const Error *err);
302
303 /*
304 * Create a new error object and assign it to *@errp.
305 * If @errp is NULL, the error is ignored. Don't bother creating one
306 * then.
307 * If @errp is &error_abort, print a suitable message and abort().
308 * If @errp is &error_fatal, print a suitable message and exit(1).
309 * If @errp is anything else, *@errp must be NULL.
310 * The new error's class is ERROR_CLASS_GENERIC_ERROR, and its
311 * human-readable error message is made from printf-style @fmt, ...
312 * The resulting message should be a single phrase, with no newline or
313 * trailing punctuation.
314 * Please don't error_setg(&error_fatal, ...), use error_report() and
315 * exit(), because that's more obvious.
316 * Likewise, don't error_setg(&error_abort, ...), use assert().
317 */
318 #define error_setg(errp, fmt, ...) \
319 error_setg_internal((errp), __FILE__, __LINE__, __func__, \
320 (fmt), ## __VA_ARGS__)
321 void error_setg_internal(Error **errp,
322 const char *src, int line, const char *func,
323 const char *fmt, ...)
324 G_GNUC_PRINTF(5, 6);
325
326 /*
327 * Just like error_setg(), with @os_error info added to the message.
328 * If @os_error is non-zero, ": " + strerror(os_error) is appended to
329 * the human-readable error message.
330 *
331 * The value of errno (which usually can get clobbered by almost any
332 * function call) will be preserved.
333 */
334 #define error_setg_errno(errp, os_error, fmt, ...) \
335 error_setg_errno_internal((errp), __FILE__, __LINE__, __func__, \
336 (os_error), (fmt), ## __VA_ARGS__)
337 void error_setg_errno_internal(Error **errp,
338 const char *fname, int line, const char *func,
339 int os_error, const char *fmt, ...)
340 G_GNUC_PRINTF(6, 7);
341
342 #ifdef _WIN32
343 /*
344 * Just like error_setg(), with @win32_error info added to the message.
345 * If @win32_error is non-zero, ": " + g_win32_error_message(win32_err)
346 * is appended to the human-readable error message.
347 */
348 #define error_setg_win32(errp, win32_err, fmt, ...) \
349 error_setg_win32_internal((errp), __FILE__, __LINE__, __func__, \
350 (win32_err), (fmt), ## __VA_ARGS__)
351 void error_setg_win32_internal(Error **errp,
352 const char *src, int line, const char *func,
353 int win32_err, const char *fmt, ...)
354 G_GNUC_PRINTF(6, 7);
355 #endif
356
357 /*
358 * Propagate error object (if any) from @local_err to @dst_errp.
359 * If @local_err is NULL, do nothing (because there's nothing to
360 * propagate).
361 * Else, if @dst_errp is NULL, errors are being ignored. Free the
362 * error object.
363 * Else, if @dst_errp is &error_abort, print a suitable message and
364 * abort().
365 * Else, if @dst_errp is &error_fatal, print a suitable message and
366 * exit(1).
367 * Else, if @dst_errp already contains an error, ignore this one: free
368 * the error object.
369 * Else, move the error object from @local_err to *@dst_errp.
370 * On return, @local_err is invalid.
371 * Please use ERRP_GUARD() instead when possible.
372 * Please don't error_propagate(&error_fatal, ...), use
373 * error_report_err() and exit(), because that's more obvious.
374 */
375 void error_propagate(Error **dst_errp, Error *local_err);
376
377
378 /*
379 * Propagate error object (if any) with some text prepended.
380 * Behaves like
381 * error_prepend(&local_err, fmt, ...);
382 * error_propagate(dst_errp, local_err);
383 * Please use ERRP_GUARD() and error_prepend() instead when possible.
384 */
385 void error_propagate_prepend(Error **dst_errp, Error *local_err,
386 const char *fmt, ...)
387 G_GNUC_PRINTF(3, 4);
388
389 /*
390 * Prepend some text to @errp's human-readable error message.
391 * The text is made by formatting @fmt, @ap like vprintf().
392 */
393 void error_vprepend(Error *const *errp, const char *fmt, va_list ap)
394 G_GNUC_PRINTF(2, 0);
395
396 /*
397 * Prepend some text to @errp's human-readable error message.
398 * The text is made by formatting @fmt, ... like printf().
399 */
400 void error_prepend(Error *const *errp, const char *fmt, ...)
401 G_GNUC_PRINTF(2, 3);
402
403 /*
404 * Append a printf-style human-readable explanation to an existing error.
405 * If the error is later reported to a human user with
406 * error_report_err() or warn_report_err(), the hints will be shown,
407 * too. If it's reported via QMP, the hints will be ignored.
408 * Intended use is adding helpful hints on the human user interface,
409 * e.g. a list of valid values. It's not for clarifying a confusing
410 * error message.
411 * @errp may be NULL, but not &error_fatal or &error_abort.
412 * Trivially the case if you call it only after error_setg() or
413 * error_propagate().
414 * May be called multiple times. The resulting hint should end with a
415 * newline.
416 */
417 void error_append_hint(Error *const *errp, const char *fmt, ...)
418 G_GNUC_PRINTF(2, 3);
419
420 /*
421 * Convenience function to report open() failure.
422 */
423 #define error_setg_file_open(errp, os_errno, filename) \
424 error_setg_file_open_internal((errp), __FILE__, __LINE__, __func__, \
425 (os_errno), (filename))
426 void error_setg_file_open_internal(Error **errp,
427 const char *src, int line, const char *func,
428 int os_errno, const char *filename);
429
430 /*
431 * Return an exact copy of @err.
432 */
433 Error *error_copy(const Error *err);
434
435 /*
436 * Free @err.
437 * @err may be NULL.
438 */
439 void error_free(Error *err);
440
441 /*
442 * Poison g_autoptr(Error) to prevent its use.
443 *
444 * Functions that report or propagate an error take ownership of the
445 * Error object. Explicit error_free() is needed when you handle an
446 * error in some other way. This is rare.
447 *
448 * g_autoptr(Error) would call error_free() automatically on return.
449 * To avoid a double-free, we'd have to manually clear the pointer
450 * every time we propagate or report.
451 *
452 * Thus, g_autoptr(Error) would make the rare case easier to get right
453 * (less prone to leaks), and the common case easier to get wrong
454 * (more prone to double-free).
455 */
456 extern void
457 __attribute__((error("Do not use g_autoptr() to declare Error * variables")))
458 error_free_poisoned(Error *err);
459 G_DEFINE_AUTOPTR_CLEANUP_FUNC(Error, error_free_poisoned)
460
461 /*
462 * Convenience function to assert that *@errp is set, then silently free it.
463 */
464 void error_free_or_abort(Error **errp);
465
466 /*
467 * Convenience function to warn_report() and free @err.
468 * The report includes hints added with error_append_hint().
469 */
470 void warn_report_err(Error *err);
471
472 /*
473 * Convenience function to error_report() and free @err.
474 * The report includes hints added with error_append_hint().
475 */
476 void error_report_err(Error *err);
477
478 /*
479 * Convenience function to error_prepend(), warn_report() and free @err.
480 */
481 void warn_reportf_err(Error *err, const char *fmt, ...)
482 G_GNUC_PRINTF(2, 3);
483
484 /*
485 * Convenience function to error_prepend(), error_report() and free @err.
486 */
487 void error_reportf_err(Error *err, const char *fmt, ...)
488 G_GNUC_PRINTF(2, 3);
489
490 /*
491 * Similar to warn_report_err(), except it prints the message just once.
492 * Return true when it prints, false otherwise.
493 */
494 bool warn_report_err_once_cond(bool *printed, Error *err);
495
496 #define warn_report_err_once(err) \
497 ({ \
498 static bool print_once_; \
499 warn_report_err_once_cond(&print_once_, err); \
500 })
501
502 /*
503 * Just like error_setg(), except you get to specify the error class.
504 * Note: use of error classes other than ERROR_CLASS_GENERIC_ERROR is
505 * strongly discouraged.
506 */
507 #define error_set(errp, err_class, fmt, ...) \
508 error_set_internal((errp), __FILE__, __LINE__, __func__, \
509 (err_class), (fmt), ## __VA_ARGS__)
510 void error_set_internal(Error **errp,
511 const char *src, int line, const char *func,
512 ErrorClass err_class, const char *fmt, ...)
513 G_GNUC_PRINTF(6, 7);
514
515 /*
516 * Make @errp parameter easier to use regardless of argument value
517 *
518 * This macro is for use right at the beginning of a function that
519 * takes an Error **errp parameter to pass errors to its caller. The
520 * parameter must be named @errp.
521 *
522 * It must be used when the function dereferences @errp or passes
523 * @errp to error_prepend(), error_vprepend(), or error_append_hint().
524 * It is safe to use even when it's not needed, but please avoid
525 * cluttering the source with useless code.
526 *
527 * If @errp is NULL or &error_fatal, rewrite it to point to a local
528 * Error variable, which will be automatically propagated to the
529 * original @errp on function exit.
530 *
531 * Note: &error_abort is not rewritten, because that would move the
532 * abort from the place where the error is created to the place where
533 * it's propagated.
534 */
535 #define ERRP_GUARD() \
536 g_auto(ErrorPropagator) _auto_errp_prop = {.errp = errp}; \
537 do { \
538 if (!errp || errp == &error_fatal) { \
539 errp = &_auto_errp_prop.local_err; \
540 } \
541 } while (0)
542
543 typedef struct ErrorPropagator {
544 Error *local_err;
545 Error **errp;
546 } ErrorPropagator;
547
548 static inline void error_propagator_cleanup(ErrorPropagator *prop)
549 {
550 error_propagate(prop->errp, prop->local_err);
551 }
552
553 G_DEFINE_AUTO_CLEANUP_CLEAR_FUNC(ErrorPropagator, error_propagator_cleanup);
554
555 /*
556 * Special error destination to abort on error.
557 * See error_setg() and error_propagate() for details.
558 */
559 extern Error *error_abort;
560
561 /*
562 * Special error destination to exit(1) on error.
563 * See error_setg() and error_propagate() for details.
564 */
565 extern Error *error_fatal;
566
567 #endif