tests: Fix leak when checking for du binary
[glib.git] / glib / gerror.c
blob236e5286960cfc6170e857c6583987e6e0a10811
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
20 * file for a list of people on the GLib Team. See the ChangeLog
21 * files for a list of changes. These files are distributed with
22 * GLib at ftp://ftp.gtk.org/pub/gtk/.
25 /**
26 * SECTION:error_reporting
27 * @Title: Error Reporting
28 * @Short_description: a system for reporting errors
30 * GLib provides a standard method of reporting errors from a called
31 * function to the calling code. (This is the same problem solved by
32 * exceptions in other languages.) It's important to understand that
33 * this method is both a data type (the #GError struct) and a [set of
34 * rules][gerror-rules]. If you use #GError incorrectly, then your code will not
35 * properly interoperate with other code that uses #GError, and users
36 * of your API will probably get confused. In most cases, [using #GError is
37 * preferred over numeric error codes][gerror-comparison], but there are
38 * situations where numeric error codes are useful for performance.
40 * First and foremost: #GError should only be used to report recoverable
41 * runtime errors, never to report programming errors. If the programmer
42 * has screwed up, then you should use g_warning(), g_return_if_fail(),
43 * g_assert(), g_error(), or some similar facility. (Incidentally,
44 * remember that the g_error() function should only be used for
45 * programming errors, it should not be used to print any error
46 * reportable via #GError.)
48 * Examples of recoverable runtime errors are "file not found" or
49 * "failed to parse input." Examples of programming errors are "NULL
50 * passed to strcmp()" or "attempted to free the same pointer twice."
51 * These two kinds of errors are fundamentally different: runtime errors
52 * should be handled or reported to the user, programming errors should
53 * be eliminated by fixing the bug in the program. This is why most
54 * functions in GLib and GTK+ do not use the #GError facility.
56 * Functions that can fail take a return location for a #GError as their
57 * last argument. On error, a new #GError instance will be allocated and
58 * returned to the caller via this argument. For example:
59 * |[<!-- language="C" -->
60 * gboolean g_file_get_contents (const gchar *filename,
61 * gchar **contents,
62 * gsize *length,
63 * GError **error);
64 * ]|
65 * If you pass a non-%NULL value for the `error` argument, it should
66 * point to a location where an error can be placed. For example:
67 * |[<!-- language="C" -->
68 * gchar *contents;
69 * GError *err = NULL;
71 * g_file_get_contents ("foo.txt", &contents, NULL, &err);
72 * g_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));
73 * if (err != NULL)
74 * {
75 * // Report error to user, and free error
76 * g_assert (contents == NULL);
77 * fprintf (stderr, "Unable to read file: %s\n", err->message);
78 * g_error_free (err);
79 * }
80 * else
81 * {
82 * // Use file contents
83 * g_assert (contents != NULL);
84 * }
85 * ]|
86 * Note that `err != NULL` in this example is a reliable indicator
87 * of whether g_file_get_contents() failed. Additionally,
88 * g_file_get_contents() returns a boolean which
89 * indicates whether it was successful.
91 * Because g_file_get_contents() returns %FALSE on failure, if you
92 * are only interested in whether it failed and don't need to display
93 * an error message, you can pass %NULL for the @error argument:
94 * |[<!-- language="C" -->
95 * if (g_file_get_contents ("foo.txt", &contents, NULL, NULL)) // ignore errors
96 * // no error occurred
97 * ;
98 * else
99 * // error
101 * ]|
103 * The #GError object contains three fields: @domain indicates the module
104 * the error-reporting function is located in, @code indicates the specific
105 * error that occurred, and @message is a user-readable error message with
106 * as many details as possible. Several functions are provided to deal
107 * with an error received from a called function: g_error_matches()
108 * returns %TRUE if the error matches a given domain and code,
109 * g_propagate_error() copies an error into an error location (so the
110 * calling function will receive it), and g_clear_error() clears an
111 * error location by freeing the error and resetting the location to
112 * %NULL. To display an error to the user, simply display the @message,
113 * perhaps along with additional context known only to the calling
114 * function (the file being opened, or whatever - though in the
115 * g_file_get_contents() case, the @message already contains a filename).
117 * When implementing a function that can report errors, the basic
118 * tool is g_set_error(). Typically, if a fatal error occurs you
119 * want to g_set_error(), then return immediately. g_set_error()
120 * does nothing if the error location passed to it is %NULL.
121 * Here's an example:
122 * |[<!-- language="C" -->
123 * gint
124 * foo_open_file (GError **error)
126 * gint fd;
127 * int saved_errno;
129 * fd = open ("file.txt", O_RDONLY);
130 * saved_errno = errno;
132 * if (fd < 0)
134 * g_set_error (error,
135 * FOO_ERROR, // error domain
136 * FOO_ERROR_BLAH, // error code
137 * "Failed to open file: %s", // error message format string
138 * g_strerror (saved_errno));
139 * return -1;
141 * else
142 * return fd;
144 * ]|
146 * Things are somewhat more complicated if you yourself call another
147 * function that can report a #GError. If the sub-function indicates
148 * fatal errors in some way other than reporting a #GError, such as
149 * by returning %TRUE on success, you can simply do the following:
150 * |[<!-- language="C" -->
151 * gboolean
152 * my_function_that_can_fail (GError **err)
154 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
156 * if (!sub_function_that_can_fail (err))
158 * // assert that error was set by the sub-function
159 * g_assert (err == NULL || *err != NULL);
160 * return FALSE;
163 * // otherwise continue, no error occurred
164 * g_assert (err == NULL || *err == NULL);
166 * ]|
168 * If the sub-function does not indicate errors other than by
169 * reporting a #GError (or if its return value does not reliably indicate
170 * errors) you need to create a temporary #GError
171 * since the passed-in one may be %NULL. g_propagate_error() is
172 * intended for use in this case.
173 * |[<!-- language="C" -->
174 * gboolean
175 * my_function_that_can_fail (GError **err)
177 * GError *tmp_error;
179 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
181 * tmp_error = NULL;
182 * sub_function_that_can_fail (&tmp_error);
184 * if (tmp_error != NULL)
186 * // store tmp_error in err, if err != NULL,
187 * // otherwise call g_error_free() on tmp_error
188 * g_propagate_error (err, tmp_error);
189 * return FALSE;
192 * // otherwise continue, no error occurred
194 * ]|
196 * Error pileups are always a bug. For example, this code is incorrect:
197 * |[<!-- language="C" -->
198 * gboolean
199 * my_function_that_can_fail (GError **err)
201 * GError *tmp_error;
203 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
205 * tmp_error = NULL;
206 * sub_function_that_can_fail (&tmp_error);
207 * other_function_that_can_fail (&tmp_error);
209 * if (tmp_error != NULL)
211 * g_propagate_error (err, tmp_error);
212 * return FALSE;
215 * ]|
216 * @tmp_error should be checked immediately after sub_function_that_can_fail(),
217 * and either cleared or propagated upward. The rule is: after each error,
218 * you must either handle the error, or return it to the calling function.
220 * Note that passing %NULL for the error location is the equivalent
221 * of handling an error by always doing nothing about it. So the
222 * following code is fine, assuming errors in sub_function_that_can_fail()
223 * are not fatal to my_function_that_can_fail():
224 * |[<!-- language="C" -->
225 * gboolean
226 * my_function_that_can_fail (GError **err)
228 * GError *tmp_error;
230 * g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
232 * sub_function_that_can_fail (NULL); // ignore errors
234 * tmp_error = NULL;
235 * other_function_that_can_fail (&tmp_error);
237 * if (tmp_error != NULL)
239 * g_propagate_error (err, tmp_error);
240 * return FALSE;
243 * ]|
245 * Note that passing %NULL for the error location ignores errors;
246 * it's equivalent to
247 * `try { sub_function_that_can_fail (); } catch (...) {}`
248 * in C++. It does not mean to leave errors unhandled; it means
249 * to handle them by doing nothing.
251 * Error domains and codes are conventionally named as follows:
253 * - The error domain is called <NAMESPACE>_<MODULE>_ERROR,
254 * for example %G_SPAWN_ERROR or %G_THREAD_ERROR:
255 * |[<!-- language="C" -->
256 * #define G_SPAWN_ERROR g_spawn_error_quark ()
258 * GQuark
259 * g_spawn_error_quark (void)
261 * return g_quark_from_static_string ("g-spawn-error-quark");
263 * ]|
265 * - The quark function for the error domain is called
266 * <namespace>_<module>_error_quark,
267 * for example g_spawn_error_quark() or g_thread_error_quark().
269 * - The error codes are in an enumeration called
270 * <Namespace><Module>Error;
271 * for example, #GThreadError or #GSpawnError.
273 * - Members of the error code enumeration are called
274 * <NAMESPACE>_<MODULE>_ERROR_<CODE>,
275 * for example %G_SPAWN_ERROR_FORK or %G_THREAD_ERROR_AGAIN.
277 * - If there's a "generic" or "unknown" error code for unrecoverable
278 * errors it doesn't make sense to distinguish with specific codes,
279 * it should be called <NAMESPACE>_<MODULE>_ERROR_FAILED,
280 * for example %G_SPAWN_ERROR_FAILED. In the case of error code
281 * enumerations that may be extended in future releases, you should
282 * generally not handle this error code explicitly, but should
283 * instead treat any unrecognized error code as equivalent to
284 * FAILED.
286 * ## Comparison of #GError and traditional error handling # {#gerror-comparison}
288 * #GError has several advantages over traditional numeric error codes:
289 * importantly, tools like
290 * [gobject-introspection](https://developer.gnome.org/gi/stable/) understand
291 * #GErrors and convert them to exceptions in bindings; the message includes
292 * more information than just a code; and use of a domain helps prevent
293 * misinterpretation of error codes.
295 * #GError has disadvantages though: it requires a memory allocation, and
296 * formatting the error message string has a performance overhead. This makes it
297 * unsuitable for use in retry loops where errors are a common case, rather than
298 * being unusual. For example, using %G_IO_ERROR_WOULD_BLOCK means hitting these
299 * overheads in the normal control flow. String formatting overhead can be
300 * eliminated by using g_set_error_literal() in some cases.
302 * These performance issues can be compounded if a function wraps the #GErrors
303 * returned by the functions it calls: this multiplies the number of allocations
304 * and string formatting operations. This can be partially mitigated by using
305 * g_prefix_error().
307 * ## Rules for use of #GError # {#gerror-rules}
309 * Summary of rules for use of #GError:
311 * - Do not report programming errors via #GError.
313 * - The last argument of a function that returns an error should
314 * be a location where a #GError can be placed (i.e. "#GError** error").
315 * If #GError is used with varargs, the #GError** should be the last
316 * argument before the "...".
318 * - The caller may pass %NULL for the #GError** if they are not interested
319 * in details of the exact error that occurred.
321 * - If %NULL is passed for the #GError** argument, then errors should
322 * not be returned to the caller, but your function should still
323 * abort and return if an error occurs. That is, control flow should
324 * not be affected by whether the caller wants to get a #GError.
326 * - If a #GError is reported, then your function by definition had a
327 * fatal failure and did not complete whatever it was supposed to do.
328 * If the failure was not fatal, then you handled it and you should not
329 * report it. If it was fatal, then you must report it and discontinue
330 * whatever you were doing immediately.
332 * - If a #GError is reported, out parameters are not guaranteed to
333 * be set to any defined value.
335 * - A #GError* must be initialized to %NULL before passing its address
336 * to a function that can report errors.
338 * - "Piling up" errors is always a bug. That is, if you assign a
339 * new #GError to a #GError* that is non-%NULL, thus overwriting
340 * the previous error, it indicates that you should have aborted
341 * the operation instead of continuing. If you were able to continue,
342 * you should have cleared the previous error with g_clear_error().
343 * g_set_error() will complain if you pile up errors.
345 * - By convention, if you return a boolean value indicating success
346 * then %TRUE means success and %FALSE means failure. Avoid creating
347 * functions which have a boolean return value and a GError parameter,
348 * but where the boolean does something other than signal whether the
349 * GError is set. Among other problems, it requires C callers to allocate
350 * a temporary error. Instead, provide a "gboolean *" out parameter.
351 * There are functions in GLib itself such as g_key_file_has_key() that
352 * are deprecated because of this. If %FALSE is returned, the error must
353 * be set to a non-%NULL value. One exception to this is that in situations
354 * that are already considered to be undefined behaviour (such as when a
355 * g_return_val_if_fail() check fails), the error need not be set.
356 * Instead of checking separately whether the error is set, callers
357 * should ensure that they do not provoke undefined behaviour, then
358 * assume that the error will be set on failure.
360 * - A %NULL return value is also frequently used to mean that an error
361 * occurred. You should make clear in your documentation whether %NULL
362 * is a valid return value in non-error cases; if %NULL is a valid value,
363 * then users must check whether an error was returned to see if the
364 * function succeeded.
366 * - When implementing a function that can report errors, you may want
367 * to add a check at the top of your function that the error return
368 * location is either %NULL or contains a %NULL error (e.g.
369 * `g_return_if_fail (error == NULL || *error == NULL);`).
372 #include "config.h"
374 #include "gerror.h"
376 #include "gslice.h"
377 #include "gstrfuncs.h"
378 #include "gtestutils.h"
381 * g_error_new_valist:
382 * @domain: error domain
383 * @code: error code
384 * @format: printf()-style format for error message
385 * @args: #va_list of parameters for the message format
387 * Creates a new #GError with the given @domain and @code,
388 * and a message formatted with @format.
390 * Returns: a new #GError
392 * Since: 2.22
394 GError*
395 g_error_new_valist (GQuark domain,
396 gint code,
397 const gchar *format,
398 va_list args)
400 GError *error;
402 /* Historically, GError allowed this (although it was never meant to work),
403 * and it has significant use in the wild, which g_return_val_if_fail
404 * would break. It should maybe g_return_val_if_fail in GLib 4.
405 * (GNOME#660371, GNOME#560482)
407 g_warn_if_fail (domain != 0);
408 g_warn_if_fail (format != NULL);
410 error = g_slice_new (GError);
412 error->domain = domain;
413 error->code = code;
414 error->message = g_strdup_vprintf (format, args);
416 return error;
420 * g_error_new:
421 * @domain: error domain
422 * @code: error code
423 * @format: printf()-style format for error message
424 * @...: parameters for message format
426 * Creates a new #GError with the given @domain and @code,
427 * and a message formatted with @format.
429 * Returns: a new #GError
431 GError*
432 g_error_new (GQuark domain,
433 gint code,
434 const gchar *format,
435 ...)
437 GError* error;
438 va_list args;
440 g_return_val_if_fail (format != NULL, NULL);
441 g_return_val_if_fail (domain != 0, NULL);
443 va_start (args, format);
444 error = g_error_new_valist (domain, code, format, args);
445 va_end (args);
447 return error;
451 * g_error_new_literal:
452 * @domain: error domain
453 * @code: error code
454 * @message: error message
456 * Creates a new #GError; unlike g_error_new(), @message is
457 * not a printf()-style format string. Use this function if
458 * @message contains text you don't have control over,
459 * that could include printf() escape sequences.
461 * Returns: a new #GError
463 GError*
464 g_error_new_literal (GQuark domain,
465 gint code,
466 const gchar *message)
468 GError* err;
470 g_return_val_if_fail (message != NULL, NULL);
471 g_return_val_if_fail (domain != 0, NULL);
473 err = g_slice_new (GError);
475 err->domain = domain;
476 err->code = code;
477 err->message = g_strdup (message);
479 return err;
483 * g_error_free:
484 * @error: a #GError
486 * Frees a #GError and associated resources.
488 void
489 g_error_free (GError *error)
491 g_return_if_fail (error != NULL);
493 g_free (error->message);
495 g_slice_free (GError, error);
499 * g_error_copy:
500 * @error: a #GError
502 * Makes a copy of @error.
504 * Returns: a new #GError
506 GError*
507 g_error_copy (const GError *error)
509 GError *copy;
511 g_return_val_if_fail (error != NULL, NULL);
512 /* See g_error_new_valist for why these don't return */
513 g_warn_if_fail (error->domain != 0);
514 g_warn_if_fail (error->message != NULL);
516 copy = g_slice_new (GError);
518 *copy = *error;
520 copy->message = g_strdup (error->message);
522 return copy;
526 * g_error_matches:
527 * @error: (nullable): a #GError
528 * @domain: an error domain
529 * @code: an error code
531 * Returns %TRUE if @error matches @domain and @code, %FALSE
532 * otherwise. In particular, when @error is %NULL, %FALSE will
533 * be returned.
535 * If @domain contains a `FAILED` (or otherwise generic) error code,
536 * you should generally not check for it explicitly, but should
537 * instead treat any not-explicitly-recognized error code as being
538 * equivalent to the `FAILED` code. This way, if the domain is
539 * extended in the future to provide a more specific error code for
540 * a certain case, your code will still work.
542 * Returns: whether @error has @domain and @code
544 gboolean
545 g_error_matches (const GError *error,
546 GQuark domain,
547 gint code)
549 return error &&
550 error->domain == domain &&
551 error->code == code;
554 #define ERROR_OVERWRITTEN_WARNING "GError set over the top of a previous GError or uninitialized memory.\n" \
555 "This indicates a bug in someone's code. You must ensure an error is NULL before it's set.\n" \
556 "The overwriting error message was: %s"
559 * g_set_error:
560 * @err: (out callee-allocates) (optional): a return location for a #GError
561 * @domain: error domain
562 * @code: error code
563 * @format: printf()-style format
564 * @...: args for @format
566 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
567 * must be %NULL. A new #GError is created and assigned to *@err.
569 void
570 g_set_error (GError **err,
571 GQuark domain,
572 gint code,
573 const gchar *format,
574 ...)
576 GError *new;
578 va_list args;
580 if (err == NULL)
581 return;
583 va_start (args, format);
584 new = g_error_new_valist (domain, code, format, args);
585 va_end (args);
587 if (*err == NULL)
588 *err = new;
589 else
591 g_warning (ERROR_OVERWRITTEN_WARNING, new->message);
592 g_error_free (new);
597 * g_set_error_literal:
598 * @err: (out callee-allocates) (optional): a return location for a #GError
599 * @domain: error domain
600 * @code: error code
601 * @message: error message
603 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
604 * must be %NULL. A new #GError is created and assigned to *@err.
605 * Unlike g_set_error(), @message is not a printf()-style format string.
606 * Use this function if @message contains text you don't have control over,
607 * that could include printf() escape sequences.
609 * Since: 2.18
611 void
612 g_set_error_literal (GError **err,
613 GQuark domain,
614 gint code,
615 const gchar *message)
617 if (err == NULL)
618 return;
620 if (*err == NULL)
621 *err = g_error_new_literal (domain, code, message);
622 else
623 g_warning (ERROR_OVERWRITTEN_WARNING, message);
627 * g_propagate_error:
628 * @dest: (out callee-allocates) (optional) (nullable): error return location
629 * @src: (transfer full): error to move into the return location
631 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
632 * The error variable @dest points to must be %NULL.
634 * @src must be non-%NULL.
636 * Note that @src is no longer valid after this call. If you want
637 * to keep using the same GError*, you need to set it to %NULL
638 * after calling this function on it.
640 void
641 g_propagate_error (GError **dest,
642 GError *src)
644 g_return_if_fail (src != NULL);
646 if (dest == NULL)
648 if (src)
649 g_error_free (src);
650 return;
652 else
654 if (*dest != NULL)
656 g_warning (ERROR_OVERWRITTEN_WARNING, src->message);
657 g_error_free (src);
659 else
660 *dest = src;
665 * g_clear_error:
666 * @err: a #GError return location
668 * If @err or *@err is %NULL, does nothing. Otherwise,
669 * calls g_error_free() on *@err and sets *@err to %NULL.
671 void
672 g_clear_error (GError **err)
674 if (err && *err)
676 g_error_free (*err);
677 *err = NULL;
681 G_GNUC_PRINTF(2, 0)
682 static void
683 g_error_add_prefix (gchar **string,
684 const gchar *format,
685 va_list ap)
687 gchar *oldstring;
688 gchar *prefix;
690 prefix = g_strdup_vprintf (format, ap);
691 oldstring = *string;
692 *string = g_strconcat (prefix, oldstring, NULL);
693 g_free (oldstring);
694 g_free (prefix);
698 * g_prefix_error:
699 * @err: (inout) (optional) (nullable): a return location for a #GError
700 * @format: printf()-style format string
701 * @...: arguments to @format
703 * Formats a string according to @format and prefix it to an existing
704 * error message. If @err is %NULL (ie: no error variable) then do
705 * nothing.
707 * If *@err is %NULL (ie: an error variable is present but there is no
708 * error condition) then also do nothing.
710 * Since: 2.16
712 void
713 g_prefix_error (GError **err,
714 const gchar *format,
715 ...)
717 if (err && *err)
719 va_list ap;
721 va_start (ap, format);
722 g_error_add_prefix (&(*err)->message, format, ap);
723 va_end (ap);
728 * g_propagate_prefixed_error:
729 * @dest: error return location
730 * @src: error to move into the return location
731 * @format: printf()-style format string
732 * @...: arguments to @format
734 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
735 * *@dest must be %NULL. After the move, add a prefix as with
736 * g_prefix_error().
738 * Since: 2.16
740 void
741 g_propagate_prefixed_error (GError **dest,
742 GError *src,
743 const gchar *format,
744 ...)
746 g_propagate_error (dest, src);
748 if (dest && *dest)
750 va_list ap;
752 va_start (ap, format);
753 g_error_add_prefix (&(*dest)->message, format, ap);
754 va_end (ap);