Updated FSF's address
[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 <emphasis>data type</emphasis> (the #GError
34  * object) and a <emphasis>set of rules.</emphasis> If you use #GError
35  * incorrectly, then your code will not properly interoperate with other
36  * code that uses #GError, and users of your API will probably get confused.
37  *
38  * First and foremost: <emphasis>#GError should only be used to report
39  * recoverable runtime errors, never to report programming
40  * errors.</emphasis> If the programmer has screwed up, then you should
41  * use g_warning(), g_return_if_fail(), g_assert(), g_error(), or some
42  * similar facility. (Incidentally, remember that the g_error() function
43  * should <emphasis>only</emphasis> be used for programming errors, it
44  * should not be used to print any error 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  * |[
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 <literal>error</literal>
63  * argument, it should point to a location where an error can be placed.
64  * For example:
65  * |[
66  * gchar *contents;
67  * GError *err = NULL;
68  * g_file_get_contents ("foo.txt", &amp;contents, NULL, &amp;err);
69  * g_assert ((contents == NULL &amp;&amp; err != NULL) || (contents != NULL &amp;&amp; err == NULL));
70  * if (err != NULL)
71  *   {
72  *     /&ast; Report error to user, and free error &ast;/
73  *     g_assert (contents == NULL);
74  *     fprintf (stderr, "Unable to read file: &percnt;s\n", err->message);
75  *     g_error_free (err);
76  *   }
77  * else
78  *   {
79  *     /&ast; Use file contents &ast;/
80  *     g_assert (contents != NULL);
81  *   }
82  * ]|
83  * Note that <literal>err != NULL</literal> in this example is a
84  * <emphasis>reliable</emphasis> indicator of whether
85  * g_file_get_contents() failed. Additionally, g_file_get_contents()
86  * returns a boolean which 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 <literal>error</literal>
91  * argument:
92  * |[
93  * if (g_file_get_contents ("foo.txt", &amp;contents, NULL, NULL)) /&ast; ignore errors &ast;/
94  *   /&ast; no error occurred &ast;/ ;
95  * else
96  *   /&ast; error &ast;/ ;
97  * ]|
98  *
99  * The #GError object contains three fields: <literal>domain</literal>
100  * indicates the module the error-reporting function is located in,
101  * <literal>code</literal> indicates the specific error that occurred,
102  * and <literal>message</literal> 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
110  * <literal>error-&gt;message</literal>, perhaps along with additional
111  * context known only to the calling function (the file being opened,
112  * or whatever -- though in the g_file_get_contents() case,
113  * <literal>error-&gt;message</literal> already contains a filename).
114  *
115  * When implementing a function that can report errors, the basic
116  * tool is g_set_error(). Typically, if a fatal error occurs you
117  * want to g_set_error(), then return immediately. g_set_error()
118  * does nothing if the error location passed to it is %NULL.
119  * Here's an example:
120  * |[
121  * gint
122  * foo_open_file (GError **error)
123  * {
124  *   gint fd;
125  *
126  *   fd = open ("file.txt", O_RDONLY);
127  *
128  *   if (fd &lt; 0)
129  *     {
130  *       g_set_error (error,
131  *                    FOO_ERROR,                 /&ast; error domain &ast;/
132  *                    FOO_ERROR_BLAH,            /&ast; error code &ast;/
133  *                    "Failed to open file: &percnt;s", /&ast; error message format string &ast;/
134  *                    g_strerror (errno));
135  *       return -1;
136  *     }
137  *   else
138  *     return fd;
139  * }
140  * ]|
141  *
142  * Things are somewhat more complicated if you yourself call another
143  * function that can report a #GError. If the sub-function indicates
144  * fatal errors in some way other than reporting a #GError, such as
145  * by returning %TRUE on success, you can simply do the following:
146  * |[
147  * gboolean
148  * my_function_that_can_fail (GError **err)
149  * {
150  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
151  *
152  *   if (!sub_function_that_can_fail (err))
153  *     {
154  *       /&ast; assert that error was set by the sub-function &ast;/
155  *       g_assert (err == NULL || *err != NULL);
156  *       return FALSE;
157  *     }
158  *
159  *   /&ast; otherwise continue, no error occurred &ast;/
160  *   g_assert (err == NULL || *err == NULL);
161  * }
162  * ]|
163  *
164  * If the sub-function does not indicate errors other than by
165  * reporting a #GError, you need to create a temporary #GError
166  * since the passed-in one may be %NULL. g_propagate_error() is
167  * intended for use in this case.
168  * |[
169  * gboolean
170  * my_function_that_can_fail (GError **err)
171  * {
172  *   GError *tmp_error;
173  *
174  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
175  *
176  *   tmp_error = NULL;
177  *   sub_function_that_can_fail (&amp;tmp_error);
178  *
179  *   if (tmp_error != NULL)
180  *     {
181  *       /&ast; store tmp_error in err, if err != NULL,
182  *        &ast; otherwise call g_error_free() on tmp_error
183  *        &ast;/
184  *       g_propagate_error (err, tmp_error);
185  *       return FALSE;
186  *     }
187  *
188  *   /&ast; otherwise continue, no error occurred &ast;/
189  * }
190  * ]|
191  *
192  * Error pileups are always a bug. For example, this code is incorrect:
193  * |[
194  * gboolean
195  * my_function_that_can_fail (GError **err)
196  * {
197  *   GError *tmp_error;
198  *
199  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
200  *
201  *   tmp_error = NULL;
202  *   sub_function_that_can_fail (&amp;tmp_error);
203  *   other_function_that_can_fail (&amp;tmp_error);
204  *
205  *   if (tmp_error != NULL)
206  *     {
207  *       g_propagate_error (err, tmp_error);
208  *       return FALSE;
209  *     }
210  * }
211  * ]|
212  * <literal>tmp_error</literal> should be checked immediately after
213  * sub_function_that_can_fail(), and either cleared or propagated
214  * upward. The rule is: <emphasis>after each error, you must either
215  * handle the error, or return it to the calling function</emphasis>.
216  * Note that passing %NULL for the error location is the equivalent
217  * of handling an error by always doing nothing about it. So the
218  * following code is fine, assuming errors in sub_function_that_can_fail()
219  * are not fatal to my_function_that_can_fail():
220  * |[
221  * gboolean
222  * my_function_that_can_fail (GError **err)
223  * {
224  *   GError *tmp_error;
225  *
226  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
227  *
228  *   sub_function_that_can_fail (NULL); /&ast; ignore errors &ast;/
229  *
230  *   tmp_error = NULL;
231  *   other_function_that_can_fail (&amp;tmp_error);
232  *
233  *   if (tmp_error != NULL)
234  *     {
235  *       g_propagate_error (err, tmp_error);
236  *       return FALSE;
237  *     }
238  * }
239  * ]|
240  *
241  * Note that passing %NULL for the error location
242  * <emphasis>ignores</emphasis> errors; it's equivalent to
243  * <literal>try { sub_function_that_can_fail (); } catch (...) {}</literal>
244  * in C++. It does <emphasis>not</emphasis> mean to leave errors
245  * unhandled; it means to handle them by doing nothing.
246  *
247  * Error domains and codes are conventionally named as follows:
248  * <itemizedlist>
249  * <listitem><para>
250  *   The error domain is called
251  *   <literal>&lt;NAMESPACE&gt;_&lt;MODULE&gt;_ERROR</literal>,
252  *   for example %G_SPAWN_ERROR or %G_THREAD_ERROR:
253  *   |[
254  * #define G_SPAWN_ERROR g_spawn_error_quark ()
255  *
256  * GQuark
257  * g_spawn_error_quark (void)
258  * {
259  *   return g_quark_from_static_string ("g-spawn-error-quark");
260  * }
261  *   ]|
262  * </para></listitem>
263  * <listitem><para>
264  *   The quark function for the error domain is called
265  *   <literal>&lt;namespace&gt;_&lt;module&gt;_error_quark</literal>,
266  *   for example g_spawn_error_quark() or g_thread_error_quark().
267  * </para></listitem>
268  * <listitem><para>
269  *   The error codes are in an enumeration called
270  *   <literal>&lt;Namespace&gt;&lt;Module&gt;Error</literal>;
271  *   for example,#GThreadError or #GSpawnError.
272  * </para></listitem>
273  * <listitem><para>
274  *   Members of the error code enumeration are called
275  *   <literal>&lt;NAMESPACE&gt;_&lt;MODULE&gt;_ERROR_&lt;CODE&gt;</literal>,
276  *   for example %G_SPAWN_ERROR_FORK or %G_THREAD_ERROR_AGAIN.
277  * </para></listitem>
278  * <listitem><para>
279  *   If there's a "generic" or "unknown" error code for unrecoverable
280  *   errors it doesn't make sense to distinguish with specific codes,
281  *   it should be called <literal>&lt;NAMESPACE&gt;_&lt;MODULE&gt;_ERROR_FAILED</literal>,
282  *   for example %G_SPAWN_ERROR_FAILED.
283  * </para></listitem>
284  * </itemizedlist>
285  *
286  * Summary of rules for use of #GError:
287  * <itemizedlist>
288  * <listitem><para>
289  *   Do not report programming errors via #GError.
290  * </para></listitem>
291  * <listitem><para>
292  *   The last argument of a function that returns an error should
293  *   be a location where a #GError can be placed (i.e. "#GError** error").
294  *   If #GError is used with varargs, the #GError** should be the last
295  *   argument before the "...".
296  * </para></listitem>
297  * <listitem><para>
298  *   The caller may pass %NULL for the #GError** if they are not interested
299  *   in details of the exact error that occurred.
300  * </para></listitem>
301  * <listitem><para>
302  *   If %NULL is passed for the #GError** argument, then errors should
303  *   not be returned to the caller, but your function should still
304  *   abort and return if an error occurs. That is, control flow should
305  *   not be affected by whether the caller wants to get a #GError.
306  * </para></listitem>
307  * <listitem><para>
308  *   If a #GError is reported, then your function by definition
309  *   <emphasis>had a fatal failure and did not complete whatever
310  *   it was supposed to do</emphasis>. If the failure was not fatal,
311  *   then you handled it and you should not report it. If it was fatal,
312  *   then you must report it and discontinue whatever you were doing
313  *   immediately.
314  * </para></listitem>
315  * <listitem><para>
316  *   If a #GError is reported, out parameters are not guaranteed to
317  *   be set to any defined value.
318  * </para></listitem>
319  * <listitem><para>
320  *   A #GError* must be initialized to %NULL before passing its address
321  *   to a function that can report errors.
322  * </para></listitem>
323  * <listitem><para>
324  *   "Piling up" errors is always a bug. That is, if you assign a
325  *   new #GError to a #GError* that is non-%NULL, thus overwriting
326  *   the previous error, it indicates that you should have aborted
327  *   the operation instead of continuing. If you were able to continue,
328  *   you should have cleared the previous error with g_clear_error().
329  *   g_set_error() will complain if you pile up errors.
330  * </para></listitem>
331  * <listitem><para>
332  *   By convention, if you return a boolean value indicating success
333  *   then %TRUE means success and %FALSE means failure. If %FALSE is
334  *   returned, the error <emphasis>must</emphasis> be set to a non-%NULL
335  *   value.
336  * </para></listitem>
337  * <listitem><para>
338  *   A %NULL return value is also frequently used to mean that an error
339  *   occurred. You should make clear in your documentation whether %NULL
340  *   is a valid return value in non-error cases; if %NULL is a valid value,
341  *   then users must check whether an error was returned to see if the
342  *   function succeeded.
343  * </para></listitem>
344  * <listitem><para>
345  *   When implementing a function that can report errors, you may want
346  *   to add a check at the top of your function that the error return
347  *   location is either %NULL or contains a %NULL error (e.g.
348  *   <literal>g_return_if_fail (error == NULL || *error == NULL);</literal>).
349  * </para></listitem>
350  * </itemizedlist>
351  */
352
353 #include "config.h"
354
355 #include "gerror.h"
356
357 #include "gslice.h"
358 #include "gstrfuncs.h"
359 #include "gtestutils.h"
360
361 /**
362  * g_error_new_valist:
363  * @domain: error domain
364  * @code: error code
365  * @format: printf()-style format for error message
366  * @args: #va_list of parameters for the message format
367  *
368  * Creates a new #GError with the given @domain and @code,
369  * and a message formatted with @format.
370  *
371  * Returns: a new #GError
372  *
373  * Since: 2.22
374  */
375 GError*
376 g_error_new_valist (GQuark       domain,
377                     gint         code,
378                     const gchar *format,
379                     va_list      args)
380 {
381   GError *error;
382
383   /* Historically, GError allowed this (although it was never meant to work),
384    * and it has significant use in the wild, which g_return_val_if_fail
385    * would break. It should maybe g_return_val_if_fail in GLib 4.
386    * (GNOME#660371, GNOME#560482)
387    */
388   g_warn_if_fail (domain != 0);
389   g_warn_if_fail (format != NULL);
390
391   error = g_slice_new (GError);
392
393   error->domain = domain;
394   error->code = code;
395   error->message = g_strdup_vprintf (format, args);
396
397   return error;
398 }
399
400 /**
401  * g_error_new:
402  * @domain: error domain
403  * @code: error code
404  * @format: printf()-style format for error message
405  * @...: parameters for message format
406  *
407  * Creates a new #GError with the given @domain and @code,
408  * and a message formatted with @format.
409  *
410  * Return value: a new #GError
411  */
412 GError*
413 g_error_new (GQuark       domain,
414              gint         code,
415              const gchar *format,
416              ...)
417 {
418   GError* error;
419   va_list args;
420
421   g_return_val_if_fail (format != NULL, NULL);
422   g_return_val_if_fail (domain != 0, NULL);
423
424   va_start (args, format);
425   error = g_error_new_valist (domain, code, format, args);
426   va_end (args);
427
428   return error;
429 }
430
431 /**
432  * g_error_new_literal:
433  * @domain: error domain
434  * @code: error code
435  * @message: error message
436  *
437  * Creates a new #GError; unlike g_error_new(), @message is
438  * not a printf()-style format string. Use this function if
439  * @message contains text you don't have control over,
440  * that could include printf() escape sequences.
441  *
442  * Return value: a new #GError
443  **/
444 GError*
445 g_error_new_literal (GQuark         domain,
446                      gint           code,
447                      const gchar   *message)
448 {
449   GError* err;
450
451   g_return_val_if_fail (message != NULL, NULL);
452   g_return_val_if_fail (domain != 0, NULL);
453
454   err = g_slice_new (GError);
455
456   err->domain = domain;
457   err->code = code;
458   err->message = g_strdup (message);
459
460   return err;
461 }
462
463 /**
464  * g_error_free:
465  * @error: a #GError
466  *
467  * Frees a #GError and associated resources.
468  */
469 void
470 g_error_free (GError *error)
471 {
472   g_return_if_fail (error != NULL);
473
474   g_free (error->message);
475
476   g_slice_free (GError, error);
477 }
478
479 /**
480  * g_error_copy:
481  * @error: a #GError
482  *
483  * Makes a copy of @error.
484  *
485  * Return value: a new #GError
486  */
487 GError*
488 g_error_copy (const GError *error)
489 {
490   GError *copy;
491  
492   g_return_val_if_fail (error != NULL, NULL);
493   /* See g_error_new_valist for why these don't return */
494   g_warn_if_fail (error->domain != 0);
495   g_warn_if_fail (error->message != NULL);
496
497   copy = g_slice_new (GError);
498
499   *copy = *error;
500
501   copy->message = g_strdup (error->message);
502
503   return copy;
504 }
505
506 /**
507  * g_error_matches:
508  * @error: (allow-none): a #GError or %NULL
509  * @domain: an error domain
510  * @code: an error code
511  *
512  * Returns %TRUE if @error matches @domain and @code, %FALSE
513  * otherwise. In particular, when @error is %NULL, %FALSE will
514  * be returned.
515  *
516  * Return value: 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 void
609 g_propagate_error (GError **dest,
610                    GError  *src)
611 {
612   g_return_if_fail (src != NULL);
613  
614   if (dest == NULL)
615     {
616       if (src)
617         g_error_free (src);
618       return;
619     }
620   else
621     {
622       if (*dest != NULL)
623         {
624           g_warning (ERROR_OVERWRITTEN_WARNING, src->message);
625           g_error_free (src);
626         }
627       else
628         *dest = src;
629     }
630 }
631
632 /**
633  * g_clear_error:
634  * @err: a #GError return location
635  *
636  * If @err is %NULL, does nothing. If @err is non-%NULL,
637  * calls g_error_free() on *@err and sets *@err to %NULL.
638  */
639 void
640 g_clear_error (GError **err)
641 {
642   if (err && *err)
643     {
644       g_error_free (*err);
645       *err = NULL;
646     }
647 }
648
649 G_GNUC_PRINTF(2, 0)
650 static void
651 g_error_add_prefix (gchar       **string,
652                     const gchar  *format,
653                     va_list       ap)
654 {
655   gchar *oldstring;
656   gchar *prefix;
657
658   prefix = g_strdup_vprintf (format, ap);
659   oldstring = *string;
660   *string = g_strconcat (prefix, oldstring, NULL);
661   g_free (oldstring);
662   g_free (prefix);
663 }
664
665 /**
666  * g_prefix_error:
667  * @err: (allow-none): a return location for a #GError, or %NULL
668  * @format: printf()-style format string
669  * @...: arguments to @format
670  *
671  * Formats a string according to @format and
672  * prefix it to an existing error message.  If
673  * @err is %NULL (ie: no error variable) then do
674  * nothing.
675  *
676  * If *@err is %NULL (ie: an error variable is
677  * present but there is no error condition) then
678  * also do nothing.  Whether or not it makes
679  * sense to take advantage of this feature is up
680  * to you.
681  *
682  * Since: 2.16
683  */
684 void
685 g_prefix_error (GError      **err,
686                 const gchar  *format,
687                 ...)
688 {
689   if (err && *err)
690     {
691       va_list ap;
692
693       va_start (ap, format);
694       g_error_add_prefix (&(*err)->message, format, ap);
695       va_end (ap);
696     }
697 }
698
699 /**
700  * g_propagate_prefixed_error:
701  * @dest: error return location
702  * @src: error to move into the return location
703  * @format: printf()-style format string
704  * @...: arguments to @format
705  *
706  * If @dest is %NULL, free @src; otherwise,
707  * moves @src into *@dest. *@dest must be %NULL.
708  * 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 }