[kdbus] KDBUS_ITEM_PAYLOAD_OFF items are (once again) relative to msg header
[platform/upstream/glib.git] / glib / gerror.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
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 of the License, or (at your option) any later version.
8  *
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.
13  *
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/>.
16  */
17
18 /*
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/.
23  */
24
25 /**
26  * SECTION:error_reporting
27  * @Title: Error Reporting
28  * @Short_description: a system for reporting errors
29  *
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. 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.
37  *
38  * First and foremost: #GError should only be used to report recoverable
39  * runtime errors, never to report programming errors. If the programmer
40  * has screwed up, then you should use g_warning(), g_return_if_fail(),
41  * g_assert(), g_error(), or some similar facility. (Incidentally,
42  * remember that the g_error() function should only be used for
43  * programming errors, it should not be used to print any error
44  * reportable via #GError.)
45  *
46  * Examples of recoverable runtime errors are "file not found" or
47  * "failed to parse input." Examples of programming errors are "NULL
48  * passed to strcmp()" or "attempted to free the same pointer twice."
49  * These two kinds of errors are fundamentally different: runtime errors
50  * should be handled or reported to the user, programming errors should
51  * be eliminated by fixing the bug in the program. This is why most
52  * functions in GLib and GTK+ do not use the #GError facility.
53  *
54  * Functions that can fail take a return location for a #GError as their
55  * last argument. For example:
56  * |[<!-- language="C" -->
57  * gboolean g_file_get_contents (const gchar  *filename,
58  *                               gchar       **contents,
59  *                               gsize        *length,
60  *                               GError      **error);
61  * ]|
62  * If you pass a non-%NULL value for the `error` argument, it should
63  * point to a location where an error can be placed. For example:
64  * |[<!-- language="C" -->
65  * gchar *contents;
66  * GError *err = NULL;
67  *
68  * g_file_get_contents ("foo.txt", &contents, NULL, &err);
69  * g_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));
70  * if (err != NULL)
71  *   {
72  *     // Report error to user, and free error
73  *     g_assert (contents == NULL);
74  *     fprintf (stderr, "Unable to read file: %s\n", err->message);
75  *     g_error_free (err);
76  *   }
77  * else
78  *   {
79  *     // Use file contents
80  *     g_assert (contents != NULL);
81  *   }
82  * ]|
83  * Note that `err != NULL` in this example is a reliable indicator
84  * of whether g_file_get_contents() failed. Additionally,
85  * g_file_get_contents() returns a boolean which
86  * indicates whether it was successful.
87  *
88  * Because g_file_get_contents() returns %FALSE on failure, if you
89  * are only interested in whether it failed and don't need to display
90  * an error message, you can pass %NULL for the @error argument:
91  * |[<!-- language="C" -->
92  * if (g_file_get_contents ("foo.txt", &contents, NULL, NULL)) // ignore errors
93  *   // no error occurred 
94  *   ;
95  * else
96  *   // error
97  *   ;
98  * ]|
99  *
100  * The #GError object contains three fields: @domain indicates the module
101  * the error-reporting function is located in, @code indicates the specific
102  * error that occurred, and @message is a user-readable error message with
103  * as many details as possible. Several functions are provided to deal
104  * with an error received from a called function: g_error_matches()
105  * returns %TRUE if the error matches a given domain and code,
106  * g_propagate_error() copies an error into an error location (so the
107  * calling function will receive it), and g_clear_error() clears an
108  * error location by freeing the error and resetting the location to
109  * %NULL. To display an error to the user, simply display the @message,
110  * perhaps along with additional context known only to the calling
111  * function (the file being opened, or whatever - though in the
112  * g_file_get_contents() case, the @message already contains a filename).
113  *
114  * When implementing a function that can report errors, the basic
115  * tool is g_set_error(). Typically, if a fatal error occurs you
116  * want to g_set_error(), then return immediately. g_set_error()
117  * does nothing if the error location passed to it is %NULL.
118  * Here's an example:
119  * |[<!-- language="C" -->
120  * gint
121  * foo_open_file (GError **error)
122  * {
123  *   gint fd;
124  *
125  *   fd = open ("file.txt", O_RDONLY);
126  *
127  *   if (fd < 0)
128  *     {
129  *       g_set_error (error,
130  *                    FOO_ERROR,                 // error domain
131  *                    FOO_ERROR_BLAH,            // error code
132  *                    "Failed to open file: %s", // error message format string
133  *                    g_strerror (errno));
134  *       return -1;
135  *     }
136  *   else
137  *     return fd;
138  * }
139  * ]|
140  *
141  * Things are somewhat more complicated if you yourself call another
142  * function that can report a #GError. If the sub-function indicates
143  * fatal errors in some way other than reporting a #GError, such as
144  * by returning %TRUE on success, you can simply do the following:
145  * |[<!-- language="C" -->
146  * gboolean
147  * my_function_that_can_fail (GError **err)
148  * {
149  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
150  *
151  *   if (!sub_function_that_can_fail (err))
152  *     {
153  *       // assert that error was set by the sub-function
154  *       g_assert (err == NULL || *err != NULL);
155  *       return FALSE;
156  *     }
157  *
158  *   // otherwise continue, no error occurred
159  *   g_assert (err == NULL || *err == NULL);
160  * }
161  * ]|
162  *
163  * If the sub-function does not indicate errors other than by
164  * reporting a #GError, you need to create a temporary #GError
165  * since the passed-in one may be %NULL. g_propagate_error() is
166  * intended for use in this case.
167  * |[<!-- language="C" -->
168  * gboolean
169  * my_function_that_can_fail (GError **err)
170  * {
171  *   GError *tmp_error;
172  *
173  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
174  *
175  *   tmp_error = NULL;
176  *   sub_function_that_can_fail (&tmp_error);
177  *
178  *   if (tmp_error != NULL)
179  *     {
180  *       // store tmp_error in err, if err != NULL,
181  *       // otherwise call g_error_free() on tmp_error
182  *       g_propagate_error (err, tmp_error);
183  *       return FALSE;
184  *     }
185  *
186  *   // otherwise continue, no error occurred
187  * }
188  * ]|
189  *
190  * Error pileups are always a bug. For example, this code is incorrect:
191  * |[<!-- language="C" -->
192  * gboolean
193  * my_function_that_can_fail (GError **err)
194  * {
195  *   GError *tmp_error;
196  *
197  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
198  *
199  *   tmp_error = NULL;
200  *   sub_function_that_can_fail (&tmp_error);
201  *   other_function_that_can_fail (&tmp_error);
202  *
203  *   if (tmp_error != NULL)
204  *     {
205  *       g_propagate_error (err, tmp_error);
206  *       return FALSE;
207  *     }
208  * }
209  * ]|
210  * @tmp_error should be checked immediately after sub_function_that_can_fail(),
211  * and either cleared or propagated upward. The rule is: after each error,
212  * you must either handle the error, or return it to the calling function.
213  *
214  * Note that passing %NULL for the error location is the equivalent
215  * of handling an error by always doing nothing about it. So the
216  * following code is fine, assuming errors in sub_function_that_can_fail()
217  * are not fatal to my_function_that_can_fail():
218  * |[<!-- language="C" -->
219  * gboolean
220  * my_function_that_can_fail (GError **err)
221  * {
222  *   GError *tmp_error;
223  *
224  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
225  *
226  *   sub_function_that_can_fail (NULL); // ignore errors
227  *
228  *   tmp_error = NULL;
229  *   other_function_that_can_fail (&tmp_error);
230  *
231  *   if (tmp_error != NULL)
232  *     {
233  *       g_propagate_error (err, tmp_error);
234  *       return FALSE;
235  *     }
236  * }
237  * ]|
238  *
239  * Note that passing %NULL for the error location ignores errors;
240  * it's equivalent to
241  * `try { sub_function_that_can_fail (); } catch (...) {}`
242  * in C++. It does not mean to leave errors unhandled; it means
243  * to handle them by doing nothing.
244  *
245  * Error domains and codes are conventionally named as follows:
246  *
247  * - The error domain is called <NAMESPACE>_<MODULE>_ERROR,
248  *   for example %G_SPAWN_ERROR or %G_THREAD_ERROR:
249  *   |[<!-- language="C" -->
250  *   #define G_SPAWN_ERROR g_spawn_error_quark ()
251  *
252  *   GQuark
253  *   g_spawn_error_quark (void)
254  *   {
255  *       return g_quark_from_static_string ("g-spawn-error-quark");
256  *   }
257  *   ]|
258  *
259  * - The quark function for the error domain is called
260  *   <namespace>_<module>_error_quark,
261  *   for example g_spawn_error_quark() or g_thread_error_quark().
262  *
263  * - The error codes are in an enumeration called
264  *   <Namespace><Module>Error;
265  *   for example, #GThreadError or #GSpawnError.
266  *
267  * - Members of the error code enumeration are called
268  *   <NAMESPACE>_<MODULE>_ERROR_<CODE>,
269  *   for example %G_SPAWN_ERROR_FORK or %G_THREAD_ERROR_AGAIN.
270  *
271  * - If there's a "generic" or "unknown" error code for unrecoverable
272  *   errors it doesn't make sense to distinguish with specific codes,
273  *   it should be called <NAMESPACE>_<MODULE>_ERROR_FAILED,
274  *   for example %G_SPAWN_ERROR_FAILED. In the case of error code
275  *   enumerations that may be extended in future releases, you should
276  *   generally not handle this error code explicitly, but should
277  *   instead treat any unrecognized error code as equivalent to
278  *   FAILED.
279  *
280  * Summary of rules for use of #GError:
281  *
282  * - Do not report programming errors via #GError.
283  * 
284  * - The last argument of a function that returns an error should
285  *   be a location where a #GError can be placed (i.e. "#GError** error").
286  *   If #GError is used with varargs, the #GError** should be the last
287  *   argument before the "...".
288  *
289  * - The caller may pass %NULL for the #GError** if they are not interested
290  *   in details of the exact error that occurred.
291  *
292  * - If %NULL is passed for the #GError** argument, then errors should
293  *   not be returned to the caller, but your function should still
294  *   abort and return if an error occurs. That is, control flow should
295  *   not be affected by whether the caller wants to get a #GError.
296  *
297  * - If a #GError is reported, then your function by definition had a
298  *   fatal failure and did not complete whatever it was supposed to do.
299  *   If the failure was not fatal, then you handled it and you should not
300  *   report it. If it was fatal, then you must report it and discontinue
301  *   whatever you were doing immediately.
302  *
303  * - If a #GError is reported, out parameters are not guaranteed to
304  *   be set to any defined value.
305  *
306  * - A #GError* must be initialized to %NULL before passing its address
307  *   to a function that can report errors.
308  *
309  * - "Piling up" errors is always a bug. That is, if you assign a
310  *   new #GError to a #GError* that is non-%NULL, thus overwriting
311  *   the previous error, it indicates that you should have aborted
312  *   the operation instead of continuing. If you were able to continue,
313  *   you should have cleared the previous error with g_clear_error().
314  *   g_set_error() will complain if you pile up errors.
315  *
316  * - By convention, if you return a boolean value indicating success
317  *   then %TRUE means success and %FALSE means failure.
318  *   <footnote><para>Avoid creating functions which have a boolean
319  *   return value and a GError parameter, but where the boolean does
320  *   something other than signal whether the GError is set.  Among other
321  *   problems, it requires C callers to allocate a temporary error.  Instead,
322  *   provide a "gboolean *" out parameter. There are functions in GLib
323  *   itself such as g_key_file_has_key() that are deprecated because of this.
324  *   </para></footnote>
325  *   If %FALSE is
326  *   returned, the error must be set to a non-%NULL value.
327  *   <footnote><para>One exception to this is that in situations that are
328  *   already considered to be undefined behaviour (such as when a
329  *   g_return_val_if_fail() check fails), the error need not be set.
330  *   Instead of checking separately whether the error is set, callers
331  *   should ensure that they do not provoke undefined behaviour, then
332  *   assume that the error will be set on failure.</para></footnote>
333  *
334  * - A %NULL return value is also frequently used to mean that an error
335  *   occurred. You should make clear in your documentation whether %NULL
336  *   is a valid return value in non-error cases; if %NULL is a valid value,
337  *   then users must check whether an error was returned to see if the
338  *   function succeeded.
339  *
340  * - When implementing a function that can report errors, you may want
341  *   to add a check at the top of your function that the error return
342  *   location is either %NULL or contains a %NULL error (e.g.
343  *   `g_return_if_fail (error == NULL || *error == NULL);`).
344  */
345
346 #include "config.h"
347
348 #include "gerror.h"
349
350 #include "gslice.h"
351 #include "gstrfuncs.h"
352 #include "gtestutils.h"
353
354 /**
355  * g_error_new_valist:
356  * @domain: error domain
357  * @code: error code
358  * @format: printf()-style format for error message
359  * @args: #va_list of parameters for the message format
360  *
361  * Creates a new #GError with the given @domain and @code,
362  * and a message formatted with @format.
363  *
364  * Returns: a new #GError
365  *
366  * Since: 2.22
367  */
368 GError*
369 g_error_new_valist (GQuark       domain,
370                     gint         code,
371                     const gchar *format,
372                     va_list      args)
373 {
374   GError *error;
375
376   /* Historically, GError allowed this (although it was never meant to work),
377    * and it has significant use in the wild, which g_return_val_if_fail
378    * would break. It should maybe g_return_val_if_fail in GLib 4.
379    * (GNOME#660371, GNOME#560482)
380    */
381   g_warn_if_fail (domain != 0);
382   g_warn_if_fail (format != NULL);
383
384   error = g_slice_new (GError);
385
386   error->domain = domain;
387   error->code = code;
388   error->message = g_strdup_vprintf (format, args);
389
390   return error;
391 }
392
393 /**
394  * g_error_new:
395  * @domain: error domain
396  * @code: error code
397  * @format: printf()-style format for error message
398  * @...: parameters for message format
399  *
400  * Creates a new #GError with the given @domain and @code,
401  * and a message formatted with @format.
402  *
403  * Returns: a new #GError
404  */
405 GError*
406 g_error_new (GQuark       domain,
407              gint         code,
408              const gchar *format,
409              ...)
410 {
411   GError* error;
412   va_list args;
413
414   g_return_val_if_fail (format != NULL, NULL);
415   g_return_val_if_fail (domain != 0, NULL);
416
417   va_start (args, format);
418   error = g_error_new_valist (domain, code, format, args);
419   va_end (args);
420
421   return error;
422 }
423
424 /**
425  * g_error_new_literal:
426  * @domain: error domain
427  * @code: error code
428  * @message: error message
429  *
430  * Creates a new #GError; unlike g_error_new(), @message is
431  * not a printf()-style format string. Use this function if
432  * @message contains text you don't have control over,
433  * that could include printf() escape sequences.
434  *
435  * Returns: a new #GError
436  **/
437 GError*
438 g_error_new_literal (GQuark         domain,
439                      gint           code,
440                      const gchar   *message)
441 {
442   GError* err;
443
444   g_return_val_if_fail (message != NULL, NULL);
445   g_return_val_if_fail (domain != 0, NULL);
446
447   err = g_slice_new (GError);
448
449   err->domain = domain;
450   err->code = code;
451   err->message = g_strdup (message);
452
453   return err;
454 }
455
456 /**
457  * g_error_free:
458  * @error: a #GError
459  *
460  * Frees a #GError and associated resources.
461  */
462 void
463 g_error_free (GError *error)
464 {
465   g_return_if_fail (error != NULL);
466
467   g_free (error->message);
468
469   g_slice_free (GError, error);
470 }
471
472 /**
473  * g_error_copy:
474  * @error: a #GError
475  *
476  * Makes a copy of @error.
477  *
478  * Returns: a new #GError
479  */
480 GError*
481 g_error_copy (const GError *error)
482 {
483   GError *copy;
484  
485   g_return_val_if_fail (error != NULL, NULL);
486   /* See g_error_new_valist for why these don't return */
487   g_warn_if_fail (error->domain != 0);
488   g_warn_if_fail (error->message != NULL);
489
490   copy = g_slice_new (GError);
491
492   *copy = *error;
493
494   copy->message = g_strdup (error->message);
495
496   return copy;
497 }
498
499 /**
500  * g_error_matches:
501  * @error: (allow-none): a #GError or %NULL
502  * @domain: an error domain
503  * @code: an error code
504  *
505  * Returns %TRUE if @error matches @domain and @code, %FALSE
506  * otherwise. In particular, when @error is %NULL, %FALSE will
507  * be returned.
508  *
509  * If @domain contains a `FAILED` (or otherwise generic) error code,
510  * you should generally not check for it explicitly, but should
511  * instead treat any not-explicitly-recognized error code as being
512  * equilalent to the `FAILED` code. This way, if the domain is
513  * extended in the future to provide a more specific error code for
514  * a certain case, your code will still work.
515  *
516  * Returns: whether @error has @domain and @code
517  */
518 gboolean
519 g_error_matches (const GError *error,
520                  GQuark        domain,
521                  gint          code)
522 {
523   return error &&
524     error->domain == domain &&
525     error->code == code;
526 }
527
528 #define ERROR_OVERWRITTEN_WARNING "GError set over the top of a previous GError or uninitialized memory.\n" \
529                "This indicates a bug in someone's code. You must ensure an error is NULL before it's set.\n" \
530                "The overwriting error message was: %s"
531
532 /**
533  * g_set_error:
534  * @err: (allow-none): a return location for a #GError, or %NULL
535  * @domain: error domain
536  * @code: error code
537  * @format: printf()-style format
538  * @...: args for @format
539  *
540  * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
541  * must be %NULL. A new #GError is created and assigned to *@err.
542  */
543 void
544 g_set_error (GError      **err,
545              GQuark        domain,
546              gint          code,
547              const gchar  *format,
548              ...)
549 {
550   GError *new;
551
552   va_list args;
553
554   if (err == NULL)
555     return;
556
557   va_start (args, format);
558   new = g_error_new_valist (domain, code, format, args);
559   va_end (args);
560
561   if (*err == NULL)
562     *err = new;
563   else
564     {
565       g_warning (ERROR_OVERWRITTEN_WARNING, new->message);
566       g_error_free (new);
567     }
568 }
569
570 /**
571  * g_set_error_literal:
572  * @err: (allow-none): a return location for a #GError, or %NULL
573  * @domain: error domain
574  * @code: error code
575  * @message: error message
576  *
577  * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
578  * must be %NULL. A new #GError is created and assigned to *@err.
579  * Unlike g_set_error(), @message is not a printf()-style format string.
580  * Use this function if @message contains text you don't have control over,
581  * that could include printf() escape sequences.
582  *
583  * Since: 2.18
584  */
585 void
586 g_set_error_literal (GError      **err,
587                      GQuark        domain,
588                      gint          code,
589                      const gchar  *message)
590 {
591   if (err == NULL)
592     return;
593
594   if (*err == NULL)
595     *err = g_error_new_literal (domain, code, message);
596   else
597     g_warning (ERROR_OVERWRITTEN_WARNING, message);
598 }
599
600 /**
601  * g_propagate_error:
602  * @dest: error return location
603  * @src: error to move into the return location
604  *
605  * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
606  * The error variable @dest points to must be %NULL.
607  *
608  * Note that @src is no longer valid after this call. If you want
609  * to keep using the same GError*, you need to set it to %NULL
610  * after calling this function on it.
611  */
612 void
613 g_propagate_error (GError **dest,
614                    GError  *src)
615 {
616   g_return_if_fail (src != NULL);
617  
618   if (dest == NULL)
619     {
620       if (src)
621         g_error_free (src);
622       return;
623     }
624   else
625     {
626       if (*dest != NULL)
627         {
628           g_warning (ERROR_OVERWRITTEN_WARNING, src->message);
629           g_error_free (src);
630         }
631       else
632         *dest = src;
633     }
634 }
635
636 /**
637  * g_clear_error:
638  * @err: a #GError return location
639  *
640  * If @err is %NULL, does nothing. If @err is non-%NULL,
641  * calls g_error_free() on *@err and sets *@err to %NULL.
642  */
643 void
644 g_clear_error (GError **err)
645 {
646   if (err && *err)
647     {
648       g_error_free (*err);
649       *err = NULL;
650     }
651 }
652
653 G_GNUC_PRINTF(2, 0)
654 static void
655 g_error_add_prefix (gchar       **string,
656                     const gchar  *format,
657                     va_list       ap)
658 {
659   gchar *oldstring;
660   gchar *prefix;
661
662   prefix = g_strdup_vprintf (format, ap);
663   oldstring = *string;
664   *string = g_strconcat (prefix, oldstring, NULL);
665   g_free (oldstring);
666   g_free (prefix);
667 }
668
669 /**
670  * g_prefix_error:
671  * @err: (allow-none): a return location for a #GError, or %NULL
672  * @format: printf()-style format string
673  * @...: arguments to @format
674  *
675  * Formats a string according to @format and prefix it to an existing
676  * error message. If @err is %NULL (ie: no error variable) then do
677  * nothing.
678  *
679  * If *@err is %NULL (ie: an error variable is present but there is no
680  * error condition) then also do nothing. Whether or not it makes sense
681  * to take advantage of this feature is up to you.
682  *
683  * Since: 2.16
684  */
685 void
686 g_prefix_error (GError      **err,
687                 const gchar  *format,
688                 ...)
689 {
690   if (err && *err)
691     {
692       va_list ap;
693
694       va_start (ap, format);
695       g_error_add_prefix (&(*err)->message, format, ap);
696       va_end (ap);
697     }
698 }
699
700 /**
701  * g_propagate_prefixed_error:
702  * @dest: error return location
703  * @src: error to move into the return location
704  * @format: printf()-style format string
705  * @...: arguments to @format
706  *
707  * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
708  * *@dest must be %NULL. After the move, add a prefix as with
709  * g_prefix_error().
710  *
711  * Since: 2.16
712  **/
713 void
714 g_propagate_prefixed_error (GError      **dest,
715                             GError       *src,
716                             const gchar  *format,
717                             ...)
718 {
719   g_propagate_error (dest, src);
720
721   if (dest && *dest)
722     {
723       va_list ap;
724
725       va_start (ap, format);
726       g_error_add_prefix (&(*dest)->message, format, ap);
727       va_end (ap);
728     }
729 }