error.h 18 KB

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