Change LGPL-2.1+ to LGPL-2.1-or-later
[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  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/.
25  */
26
27 /**
28  * SECTION:error_reporting
29  * @Title: Error Reporting
30  * @Short_description: a system for reporting errors
31  *
32  * GLib provides a standard method of reporting errors from a called
33  * function to the calling code. (This is the same problem solved by
34  * exceptions in other languages.) It's important to understand that
35  * this method is both a data type (the #GError struct) and a [set of
36  * rules][gerror-rules]. If you use #GError incorrectly, then your code will not
37  * properly interoperate with other code that uses #GError, and users
38  * of your API will probably get confused. In most cases, [using #GError is
39  * preferred over numeric error codes][gerror-comparison], but there are
40  * situations where numeric error codes are useful for performance.
41  *
42  * First and foremost: #GError should only be used to report recoverable
43  * runtime errors, never to report programming errors. If the programmer
44  * has screwed up, then you should use g_warning(), g_return_if_fail(),
45  * g_assert(), g_error(), or some similar facility. (Incidentally,
46  * remember that the g_error() function should only be used for
47  * programming errors, it should not be used to print any error
48  * reportable via #GError.)
49  *
50  * Examples of recoverable runtime errors are "file not found" or
51  * "failed to parse input." Examples of programming errors are "NULL
52  * passed to strcmp()" or "attempted to free the same pointer twice."
53  * These two kinds of errors are fundamentally different: runtime errors
54  * should be handled or reported to the user, programming errors should
55  * be eliminated by fixing the bug in the program. This is why most
56  * functions in GLib and GTK do not use the #GError facility.
57  *
58  * Functions that can fail take a return location for a #GError as their
59  * last argument. On error, a new #GError instance will be allocated and
60  * returned to the caller via this argument. For example:
61  * |[<!-- language="C" -->
62  * gboolean g_file_get_contents (const gchar  *filename,
63  *                               gchar       **contents,
64  *                               gsize        *length,
65  *                               GError      **error);
66  * ]|
67  * If you pass a non-%NULL value for the `error` argument, it should
68  * point to a location where an error can be placed. For example:
69  * |[<!-- language="C" -->
70  * gchar *contents;
71  * GError *err = NULL;
72  *
73  * g_file_get_contents ("foo.txt", &contents, NULL, &err);
74  * g_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));
75  * if (err != NULL)
76  *   {
77  *     // Report error to user, and free error
78  *     g_assert (contents == NULL);
79  *     fprintf (stderr, "Unable to read file: %s\n", err->message);
80  *     g_error_free (err);
81  *   }
82  * else
83  *   {
84  *     // Use file contents
85  *     g_assert (contents != NULL);
86  *   }
87  * ]|
88  * Note that `err != NULL` in this example is a reliable indicator
89  * of whether g_file_get_contents() failed. Additionally,
90  * g_file_get_contents() returns a boolean which
91  * indicates whether it was successful.
92  *
93  * Because g_file_get_contents() returns %FALSE on failure, if you
94  * are only interested in whether it failed and don't need to display
95  * an error message, you can pass %NULL for the @error argument:
96  * |[<!-- language="C" -->
97  * if (g_file_get_contents ("foo.txt", &contents, NULL, NULL)) // ignore errors
98  *   // no error occurred 
99  *   ;
100  * else
101  *   // error
102  *   ;
103  * ]|
104  *
105  * The #GError object contains three fields: @domain indicates the module
106  * the error-reporting function is located in, @code indicates the specific
107  * error that occurred, and @message is a user-readable error message with
108  * as many details as possible. Several functions are provided to deal
109  * with an error received from a called function: g_error_matches()
110  * returns %TRUE if the error matches a given domain and code,
111  * g_propagate_error() copies an error into an error location (so the
112  * calling function will receive it), and g_clear_error() clears an
113  * error location by freeing the error and resetting the location to
114  * %NULL. To display an error to the user, simply display the @message,
115  * perhaps along with additional context known only to the calling
116  * function (the file being opened, or whatever - though in the
117  * g_file_get_contents() case, the @message already contains a filename).
118  *
119  * Since error messages may be displayed to the user, they need to be valid
120  * UTF-8 (all GTK widgets expect text to be UTF-8). Keep this in mind in
121  * particular when formatting error messages with filenames, which are in
122  * the 'filename encoding', and need to be turned into UTF-8 using
123  * g_filename_to_utf8(), g_filename_display_name() or g_utf8_make_valid().
124  *
125  * Note, however, that many error messages are too technical to display to the
126  * user in an application, so prefer to use g_error_matches() to categorize errors
127  * from called functions, and build an appropriate error message for the context
128  * within your application. Error messages from a #GError are more appropriate
129  * to be printed in system logs or on the command line. They are typically
130  * translated.
131  *
132  * When implementing a function that can report errors, the basic
133  * tool is g_set_error(). Typically, if a fatal error occurs you
134  * want to g_set_error(), then return immediately. g_set_error()
135  * does nothing if the error location passed to it is %NULL.
136  * Here's an example:
137  * |[<!-- language="C" -->
138  * gint
139  * foo_open_file (GError **error)
140  * {
141  *   gint fd;
142  *   int saved_errno;
143  *
144  *   g_return_val_if_fail (error == NULL || *error == NULL, -1);
145  *
146  *   fd = open ("file.txt", O_RDONLY);
147  *   saved_errno = errno;
148  *
149  *   if (fd < 0)
150  *     {
151  *       g_set_error (error,
152  *                    FOO_ERROR,                 // error domain
153  *                    FOO_ERROR_BLAH,            // error code
154  *                    "Failed to open file: %s", // error message format string
155  *                    g_strerror (saved_errno));
156  *       return -1;
157  *     }
158  *   else
159  *     return fd;
160  * }
161  * ]|
162  *
163  * Things are somewhat more complicated if you yourself call another
164  * function that can report a #GError. If the sub-function indicates
165  * fatal errors in some way other than reporting a #GError, such as
166  * by returning %TRUE on success, you can simply do the following:
167  * |[<!-- language="C" -->
168  * gboolean
169  * my_function_that_can_fail (GError **err)
170  * {
171  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
172  *
173  *   if (!sub_function_that_can_fail (err))
174  *     {
175  *       // assert that error was set by the sub-function
176  *       g_assert (err == NULL || *err != NULL);
177  *       return FALSE;
178  *     }
179  *
180  *   // otherwise continue, no error occurred
181  *   g_assert (err == NULL || *err == NULL);
182  * }
183  * ]|
184  *
185  * If the sub-function does not indicate errors other than by
186  * reporting a #GError (or if its return value does not reliably indicate
187  * errors) you need to create a temporary #GError
188  * since the passed-in one may be %NULL. g_propagate_error() is
189  * intended for use in this case.
190  * |[<!-- language="C" -->
191  * gboolean
192  * my_function_that_can_fail (GError **err)
193  * {
194  *   GError *tmp_error;
195  *
196  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
197  *
198  *   tmp_error = NULL;
199  *   sub_function_that_can_fail (&tmp_error);
200  *
201  *   if (tmp_error != NULL)
202  *     {
203  *       // store tmp_error in err, if err != NULL,
204  *       // otherwise call g_error_free() on tmp_error
205  *       g_propagate_error (err, tmp_error);
206  *       return FALSE;
207  *     }
208  *
209  *   // otherwise continue, no error occurred
210  * }
211  * ]|
212  *
213  * Error pileups are always a bug. For example, this code is incorrect:
214  * |[<!-- language="C" -->
215  * gboolean
216  * my_function_that_can_fail (GError **err)
217  * {
218  *   GError *tmp_error;
219  *
220  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
221  *
222  *   tmp_error = NULL;
223  *   sub_function_that_can_fail (&tmp_error);
224  *   other_function_that_can_fail (&tmp_error);
225  *
226  *   if (tmp_error != NULL)
227  *     {
228  *       g_propagate_error (err, tmp_error);
229  *       return FALSE;
230  *     }
231  * }
232  * ]|
233  * @tmp_error should be checked immediately after sub_function_that_can_fail(),
234  * and either cleared or propagated upward. The rule is: after each error,
235  * you must either handle the error, or return it to the calling function.
236  *
237  * Note that passing %NULL for the error location is the equivalent
238  * of handling an error by always doing nothing about it. So the
239  * following code is fine, assuming errors in sub_function_that_can_fail()
240  * are not fatal to my_function_that_can_fail():
241  * |[<!-- language="C" -->
242  * gboolean
243  * my_function_that_can_fail (GError **err)
244  * {
245  *   GError *tmp_error;
246  *
247  *   g_return_val_if_fail (err == NULL || *err == NULL, FALSE);
248  *
249  *   sub_function_that_can_fail (NULL); // ignore errors
250  *
251  *   tmp_error = NULL;
252  *   other_function_that_can_fail (&tmp_error);
253  *
254  *   if (tmp_error != NULL)
255  *     {
256  *       g_propagate_error (err, tmp_error);
257  *       return FALSE;
258  *     }
259  * }
260  * ]|
261  *
262  * Note that passing %NULL for the error location ignores errors;
263  * it's equivalent to
264  * `try { sub_function_that_can_fail (); } catch (...) {}`
265  * in C++. It does not mean to leave errors unhandled; it means
266  * to handle them by doing nothing.
267  *
268  * Error domains and codes are conventionally named as follows:
269  *
270  * - The error domain is called <NAMESPACE>_<MODULE>_ERROR,
271  *   for example %G_SPAWN_ERROR or %G_THREAD_ERROR:
272  *   |[<!-- language="C" -->
273  *   #define G_SPAWN_ERROR g_spawn_error_quark ()
274  *
275  *   G_DEFINE_QUARK (g-spawn-error-quark, g_spawn_error)
276  *   ]|
277  *
278  * - The quark function for the error domain is called
279  *   <namespace>_<module>_error_quark,
280  *   for example g_spawn_error_quark() or g_thread_error_quark().
281  *
282  * - The error codes are in an enumeration called
283  *   <Namespace><Module>Error;
284  *   for example, #GThreadError or #GSpawnError.
285  *
286  * - Members of the error code enumeration are called
287  *   <NAMESPACE>_<MODULE>_ERROR_<CODE>,
288  *   for example %G_SPAWN_ERROR_FORK or %G_THREAD_ERROR_AGAIN.
289  *
290  * - If there's a "generic" or "unknown" error code for unrecoverable
291  *   errors it doesn't make sense to distinguish with specific codes,
292  *   it should be called <NAMESPACE>_<MODULE>_ERROR_FAILED,
293  *   for example %G_SPAWN_ERROR_FAILED. In the case of error code
294  *   enumerations that may be extended in future releases, you should
295  *   generally not handle this error code explicitly, but should
296  *   instead treat any unrecognized error code as equivalent to
297  *   FAILED.
298  *
299  * ## Comparison of #GError and traditional error handling # {#gerror-comparison}
300  *
301  * #GError has several advantages over traditional numeric error codes:
302  * importantly, tools like
303  * [gobject-introspection](https://developer.gnome.org/gi/stable/) understand
304  * #GErrors and convert them to exceptions in bindings; the message includes
305  * more information than just a code; and use of a domain helps prevent
306  * misinterpretation of error codes.
307  *
308  * #GError has disadvantages though: it requires a memory allocation, and
309  * formatting the error message string has a performance overhead. This makes it
310  * unsuitable for use in retry loops where errors are a common case, rather than
311  * being unusual. For example, using %G_IO_ERROR_WOULD_BLOCK means hitting these
312  * overheads in the normal control flow. String formatting overhead can be
313  * eliminated by using g_set_error_literal() in some cases.
314  *
315  * These performance issues can be compounded if a function wraps the #GErrors
316  * returned by the functions it calls: this multiplies the number of allocations
317  * and string formatting operations. This can be partially mitigated by using
318  * g_prefix_error().
319  *
320  * ## Rules for use of #GError # {#gerror-rules}
321  *
322  * Summary of rules for use of #GError:
323  *
324  * - Do not report programming errors via #GError.
325  * 
326  * - The last argument of a function that returns an error should
327  *   be a location where a #GError can be placed (i.e. `GError **error`).
328  *   If #GError is used with varargs, the `GError**` should be the last
329  *   argument before the `...`.
330  *
331  * - The caller may pass %NULL for the `GError**` if they are not interested
332  *   in details of the exact error that occurred.
333  *
334  * - If %NULL is passed for the `GError**` argument, then errors should
335  *   not be returned to the caller, but your function should still
336  *   abort and return if an error occurs. That is, control flow should
337  *   not be affected by whether the caller wants to get a #GError.
338  *
339  * - If a #GError is reported, then your function by definition had a
340  *   fatal failure and did not complete whatever it was supposed to do.
341  *   If the failure was not fatal, then you handled it and you should not
342  *   report it. If it was fatal, then you must report it and discontinue
343  *   whatever you were doing immediately.
344  *
345  * - If a #GError is reported, out parameters are not guaranteed to
346  *   be set to any defined value.
347  *
348  * - A `GError*` must be initialized to %NULL before passing its address
349  *   to a function that can report errors.
350  *
351  * - #GError structs must not be stack-allocated.
352  *
353  * - "Piling up" errors is always a bug. That is, if you assign a
354  *   new #GError to a `GError*` that is non-%NULL, thus overwriting
355  *   the previous error, it indicates that you should have aborted
356  *   the operation instead of continuing. If you were able to continue,
357  *   you should have cleared the previous error with g_clear_error().
358  *   g_set_error() will complain if you pile up errors.
359  *
360  * - By convention, if you return a boolean value indicating success
361  *   then %TRUE means success and %FALSE means failure. Avoid creating
362  *   functions which have a boolean return value and a #GError parameter,
363  *   but where the boolean does something other than signal whether the
364  *   #GError is set.  Among other problems, it requires C callers to allocate
365  *   a temporary error.  Instead, provide a `gboolean *` out parameter.
366  *   There are functions in GLib itself such as g_key_file_has_key() that
367  *   are hard to use because of this. If %FALSE is returned, the error must
368  *   be set to a non-%NULL value.  One exception to this is that in situations
369  *   that are already considered to be undefined behaviour (such as when a
370  *   g_return_val_if_fail() check fails), the error need not be set.
371  *   Instead of checking separately whether the error is set, callers
372  *   should ensure that they do not provoke undefined behaviour, then
373  *   assume that the error will be set on failure.
374  *
375  * - A %NULL return value is also frequently used to mean that an error
376  *   occurred. You should make clear in your documentation whether %NULL
377  *   is a valid return value in non-error cases; if %NULL is a valid value,
378  *   then users must check whether an error was returned to see if the
379  *   function succeeded.
380  *
381  * - When implementing a function that can report errors, you may want
382  *   to add a check at the top of your function that the error return
383  *   location is either %NULL or contains a %NULL error (e.g.
384  *   `g_return_if_fail (error == NULL || *error == NULL);`).
385  *
386  * ## Extended #GError Domains # {#gerror-extended-domains}
387  *
388  * Since GLib 2.68 it is possible to extend the #GError type. This is
389  * done with the G_DEFINE_EXTENDED_ERROR() macro. To create an
390  * extended #GError type do something like this in the header file:
391  * |[<!-- language="C" -->
392  * typedef enum
393  * {
394  *   MY_ERROR_BAD_REQUEST,
395  * } MyError;
396  * #define MY_ERROR (my_error_quark ())
397  * GQuark my_error_quark (void);
398  * int
399  * my_error_get_parse_error_id (GError *error);
400  * const char *
401  * my_error_get_bad_request_details (GError *error);
402  * ]|
403  * and in implementation:
404  * |[<!-- language="C" -->
405  * typedef struct
406  * {
407  *   int parse_error_id;
408  *   char *bad_request_details;
409  * } MyErrorPrivate;
410  *
411  * static void
412  * my_error_private_init (MyErrorPrivate *priv)
413  * {
414  *   priv->parse_error_id = -1;
415  *   // No need to set priv->bad_request_details to NULL,
416  *   // the struct is initialized with zeros.
417  * }
418  *
419  * static void
420  * my_error_private_copy (const MyErrorPrivate *src_priv, MyErrorPrivate *dest_priv)
421  * {
422  *   dest_priv->parse_error_id = src_priv->parse_error_id;
423  *   dest_priv->bad_request_details = g_strdup (src_priv->bad_request_details);
424  * }
425  *
426  * static void
427  * my_error_private_clear (MyErrorPrivate *priv)
428  * {
429  *   g_free (priv->bad_request_details);
430  * }
431  *
432  * // This defines the my_error_get_private and my_error_quark functions.
433  * G_DEFINE_EXTENDED_ERROR (MyError, my_error)
434  *
435  * int
436  * my_error_get_parse_error_id (GError *error)
437  * {
438  *   MyErrorPrivate *priv = my_error_get_private (error);
439  *   g_return_val_if_fail (priv != NULL, -1);
440  *   return priv->parse_error_id;
441  * }
442  *
443  * const char *
444  * my_error_get_bad_request_details (GError *error)
445  * {
446  *   MyErrorPrivate *priv = my_error_get_private (error);
447  *   g_return_val_if_fail (priv != NULL, NULL);
448  *   g_return_val_if_fail (error->code != MY_ERROR_BAD_REQUEST, NULL);
449  *   return priv->bad_request_details;
450  * }
451  *
452  * static void
453  * my_error_set_bad_request (GError     **error,
454  *                           const char  *reason,
455  *                           int          error_id,
456  *                           const char  *details)
457  * {
458  *   MyErrorPrivate *priv;
459  *   g_set_error (error, MY_ERROR, MY_ERROR_BAD_REQUEST, "Invalid request: %s", reason);
460  *   if (error != NULL && *error != NULL)
461  *     {
462  *       priv = my_error_get_private (error);
463  *       g_return_val_if_fail (priv != NULL, NULL);
464  *       priv->parse_error_id = error_id;
465  *       priv->bad_request_details = g_strdup (details);
466  *     }
467  * }
468  * ]|
469  * An example of use of the error could be:
470  * |[<!-- language="C" -->
471  * gboolean
472  * send_request (GBytes *request, GError **error)
473  * {
474  *   ParseFailedStatus *failure = validate_request (request);
475  *   if (failure != NULL)
476  *     {
477  *       my_error_set_bad_request (error, failure->reason, failure->error_id, failure->details);
478  *       parse_failed_status_free (failure);
479  *       return FALSE;
480  *     }
481  *
482  *   return send_one (request, error);
483  * }
484  * ]|
485  *
486  * Please note that if you are a library author and your library
487  * exposes an existing error domain, then you can't make this error
488  * domain an extended one without breaking ABI. This is because
489  * earlier it was possible to create an error with this error domain
490  * on the stack and then copy it with g_error_copy(). If the new
491  * version of your library makes the error domain an extended one,
492  * then g_error_copy() called by code that allocated the error on the
493  * stack will try to copy more data than it used to, which will lead
494  * to undefined behavior. You must not stack-allocate errors with an
495  * extended error domain, and it is bad practice to stack-allocate any
496  * other #GErrors.
497  *
498  * Extended error domains in unloadable plugins/modules are not
499  * supported.
500  */
501
502 #include "config.h"
503
504 #include "gvalgrind.h"
505 #include <string.h>
506
507 #include "gerror.h"
508
509 #include "ghash.h"
510 #include "glib-init.h"
511 #include "gslice.h"
512 #include "gstrfuncs.h"
513 #include "gtestutils.h"
514 #include "gthread.h"
515
516 static GRWLock error_domain_global;
517 /* error_domain_ht must be accessed with error_domain_global
518  * locked.
519  */
520 static GHashTable *error_domain_ht = NULL;
521
522 void
523 g_error_init (void)
524 {
525   error_domain_ht = g_hash_table_new (NULL, NULL);
526 }
527
528 typedef struct
529 {
530   /* private_size is already aligned. */
531   gsize private_size;
532   GErrorInitFunc init;
533   GErrorCopyFunc copy;
534   GErrorClearFunc clear;
535 } ErrorDomainInfo;
536
537 /* Must be called with error_domain_global locked.
538  */
539 static inline ErrorDomainInfo *
540 error_domain_lookup (GQuark domain)
541 {
542   return g_hash_table_lookup (error_domain_ht,
543                               GUINT_TO_POINTER (domain));
544 }
545
546 /* Copied from gtype.c. */
547 #define STRUCT_ALIGNMENT (2 * sizeof (gsize))
548 #define ALIGN_STRUCT(offset) \
549       ((offset + (STRUCT_ALIGNMENT - 1)) & -STRUCT_ALIGNMENT)
550
551 static void
552 error_domain_register (GQuark            error_quark,
553                        gsize             error_type_private_size,
554                        GErrorInitFunc    error_type_init,
555                        GErrorCopyFunc    error_type_copy,
556                        GErrorClearFunc   error_type_clear)
557 {
558   g_rw_lock_writer_lock (&error_domain_global);
559   if (error_domain_lookup (error_quark) == NULL)
560     {
561       ErrorDomainInfo *info = g_new (ErrorDomainInfo, 1);
562       info->private_size = ALIGN_STRUCT (error_type_private_size);
563       info->init = error_type_init;
564       info->copy = error_type_copy;
565       info->clear = error_type_clear;
566
567       g_hash_table_insert (error_domain_ht,
568                            GUINT_TO_POINTER (error_quark),
569                            info);
570     }
571   else
572     {
573       const char *name = g_quark_to_string (error_quark);
574
575       g_critical ("Attempted to register an extended error domain for %s more than once", name);
576     }
577   g_rw_lock_writer_unlock (&error_domain_global);
578 }
579
580 /**
581  * g_error_domain_register_static:
582  * @error_type_name: static string to create a #GQuark from
583  * @error_type_private_size: size of the private error data in bytes
584  * @error_type_init: function initializing fields of the private error data
585  * @error_type_copy: function copying fields of the private error data
586  * @error_type_clear: function freeing fields of the private error data
587  *
588  * This function registers an extended #GError domain.
589  *
590  * @error_type_name should not be freed. @error_type_private_size must
591  * be greater than 0.
592  *
593  * @error_type_init receives an initialized #GError and should then initialize
594  * the private data.
595  *
596  * @error_type_copy is a function that receives both original and a copy
597  * #GError and should copy the fields of the private error data. The standard
598  * #GError fields are already handled.
599  *
600  * @error_type_clear receives the pointer to the error, and it should free the
601  * fields of the private error data. It should not free the struct itself though.
602  *
603  * Normally, it is better to use G_DEFINE_EXTENDED_ERROR(), as it
604  * already takes care of passing valid information to this function.
605  *
606  * Returns: #GQuark representing the error domain
607  * Since: 2.68
608  */
609 GQuark
610 g_error_domain_register_static (const char        *error_type_name,
611                                 gsize              error_type_private_size,
612                                 GErrorInitFunc     error_type_init,
613                                 GErrorCopyFunc     error_type_copy,
614                                 GErrorClearFunc    error_type_clear)
615 {
616   GQuark error_quark;
617
618   g_return_val_if_fail (error_type_name != NULL, 0);
619   g_return_val_if_fail (error_type_private_size > 0, 0);
620   g_return_val_if_fail (error_type_init != NULL, 0);
621   g_return_val_if_fail (error_type_copy != NULL, 0);
622   g_return_val_if_fail (error_type_clear != NULL, 0);
623
624   error_quark = g_quark_from_static_string (error_type_name);
625   error_domain_register (error_quark,
626                          error_type_private_size,
627                          error_type_init,
628                          error_type_copy,
629                          error_type_clear);
630   return error_quark;
631 }
632
633 /**
634  * g_error_domain_register:
635  * @error_type_name: string to create a #GQuark from
636  * @error_type_private_size: size of the private error data in bytes
637  * @error_type_init: function initializing fields of the private error data
638  * @error_type_copy: function copying fields of the private error data
639  * @error_type_clear: function freeing fields of the private error data
640  *
641  * This function registers an extended #GError domain.
642  * @error_type_name will be duplicated. Otherwise does the same as
643  * g_error_domain_register_static().
644  *
645  * Returns: #GQuark representing the error domain
646  * Since: 2.68
647  */
648 GQuark
649 g_error_domain_register (const char        *error_type_name,
650                          gsize              error_type_private_size,
651                          GErrorInitFunc     error_type_init,
652                          GErrorCopyFunc     error_type_copy,
653                          GErrorClearFunc    error_type_clear)
654 {
655   GQuark error_quark;
656
657   g_return_val_if_fail (error_type_name != NULL, 0);
658   g_return_val_if_fail (error_type_private_size > 0, 0);
659   g_return_val_if_fail (error_type_init != NULL, 0);
660   g_return_val_if_fail (error_type_copy != NULL, 0);
661   g_return_val_if_fail (error_type_clear != NULL, 0);
662
663   error_quark = g_quark_from_string (error_type_name);
664   error_domain_register (error_quark,
665                          error_type_private_size,
666                          error_type_init,
667                          error_type_copy,
668                          error_type_clear);
669   return error_quark;
670 }
671
672 static GError *
673 g_error_allocate (GQuark domain, ErrorDomainInfo *out_info)
674 {
675   guint8 *allocated;
676   GError *error;
677   ErrorDomainInfo *info;
678   gsize private_size;
679
680   g_rw_lock_reader_lock (&error_domain_global);
681   info = error_domain_lookup (domain);
682   if (info != NULL)
683     {
684       if (out_info != NULL)
685         *out_info = *info;
686       private_size = info->private_size;
687       g_rw_lock_reader_unlock (&error_domain_global);
688     }
689   else
690     {
691       g_rw_lock_reader_unlock (&error_domain_global);
692       if (out_info != NULL)
693         memset (out_info, 0, sizeof (*out_info));
694       private_size = 0;
695     }
696   /* See comments in g_type_create_instance in gtype.c to see what
697    * this magic is about.
698    */
699 #ifdef ENABLE_VALGRIND
700   if (private_size > 0 && RUNNING_ON_VALGRIND)
701     {
702       private_size += ALIGN_STRUCT (1);
703       allocated = g_slice_alloc0 (private_size + sizeof (GError) + sizeof (gpointer));
704       *(gpointer *) (allocated + private_size + sizeof (GError)) = allocated + ALIGN_STRUCT (1);
705       VALGRIND_MALLOCLIKE_BLOCK (allocated + private_size, sizeof (GError) + sizeof (gpointer), 0, TRUE);
706       VALGRIND_MALLOCLIKE_BLOCK (allocated + ALIGN_STRUCT (1), private_size - ALIGN_STRUCT (1), 0, TRUE);
707     }
708   else
709 #endif
710     allocated = g_slice_alloc0 (private_size + sizeof (GError));
711
712   error = (GError *) (allocated + private_size);
713   return error;
714 }
715
716 /* This function takes ownership of @message. */
717 static GError *
718 g_error_new_steal (GQuark           domain,
719                    gint             code,
720                    gchar           *message,
721                    ErrorDomainInfo *out_info)
722 {
723   ErrorDomainInfo info;
724   GError *error = g_error_allocate (domain, &info);
725
726   error->domain = domain;
727   error->code = code;
728   error->message = message;
729
730   if (info.init != NULL)
731     info.init (error);
732   if (out_info != NULL)
733     *out_info = info;
734
735   return error;
736 }
737
738 /**
739  * g_error_new_valist:
740  * @domain: error domain
741  * @code: error code
742  * @format: printf()-style format for error message
743  * @args: #va_list of parameters for the message format
744  *
745  * Creates a new #GError with the given @domain and @code,
746  * and a message formatted with @format.
747  *
748  * Returns: a new #GError
749  *
750  * Since: 2.22
751  */
752 GError*
753 g_error_new_valist (GQuark       domain,
754                     gint         code,
755                     const gchar *format,
756                     va_list      args)
757 {
758   g_return_val_if_fail (format != NULL, NULL);
759
760   /* Historically, GError allowed this (although it was never meant to work),
761    * and it has significant use in the wild, which g_return_val_if_fail
762    * would break. It should maybe g_return_val_if_fail in GLib 4.
763    * (GNOME#660371, GNOME#560482)
764    */
765   g_warn_if_fail (domain != 0);
766
767   return g_error_new_steal (domain, code, g_strdup_vprintf (format, args), NULL);
768 }
769
770 /**
771  * g_error_new:
772  * @domain: error domain
773  * @code: error code
774  * @format: printf()-style format for error message
775  * @...: parameters for message format
776  *
777  * Creates a new #GError with the given @domain and @code,
778  * and a message formatted with @format.
779  *
780  * Returns: a new #GError
781  */
782 GError*
783 g_error_new (GQuark       domain,
784              gint         code,
785              const gchar *format,
786              ...)
787 {
788   GError* error;
789   va_list args;
790
791   g_return_val_if_fail (format != NULL, NULL);
792   g_return_val_if_fail (domain != 0, NULL);
793
794   va_start (args, format);
795   error = g_error_new_valist (domain, code, format, args);
796   va_end (args);
797
798   return error;
799 }
800
801 /**
802  * g_error_new_literal:
803  * @domain: error domain
804  * @code: error code
805  * @message: error message
806  *
807  * Creates a new #GError; unlike g_error_new(), @message is
808  * not a printf()-style format string. Use this function if
809  * @message contains text you don't have control over,
810  * that could include printf() escape sequences.
811  *
812  * Returns: a new #GError
813  **/
814 GError*
815 g_error_new_literal (GQuark         domain,
816                      gint           code,
817                      const gchar   *message)
818 {
819   g_return_val_if_fail (message != NULL, NULL);
820   g_return_val_if_fail (domain != 0, NULL);
821
822   return g_error_new_steal (domain, code, g_strdup (message), NULL);
823 }
824
825 /**
826  * g_error_free:
827  * @error: a #GError
828  *
829  * Frees a #GError and associated resources.
830  */
831 void
832 g_error_free (GError *error)
833 {
834   gsize private_size;
835   ErrorDomainInfo *info;
836   guint8 *allocated;
837
838   g_return_if_fail (error != NULL);
839
840   g_rw_lock_reader_lock (&error_domain_global);
841   info = error_domain_lookup (error->domain);
842   if (info != NULL)
843     {
844       GErrorClearFunc clear = info->clear;
845
846       private_size = info->private_size;
847       g_rw_lock_reader_unlock (&error_domain_global);
848       clear (error);
849     }
850   else
851     {
852       g_rw_lock_reader_unlock (&error_domain_global);
853       private_size = 0;
854     }
855
856   g_free (error->message);
857   allocated = ((guint8 *) error) - private_size;
858   /* See comments in g_type_free_instance in gtype.c to see what this
859    * magic is about.
860    */
861 #ifdef ENABLE_VALGRIND
862   if (private_size > 0 && RUNNING_ON_VALGRIND)
863     {
864       private_size += ALIGN_STRUCT (1);
865       allocated -= ALIGN_STRUCT (1);
866       *(gpointer *) (allocated + private_size + sizeof (GError)) = NULL;
867       g_slice_free1 (private_size + sizeof (GError) + sizeof (gpointer), allocated);
868       VALGRIND_FREELIKE_BLOCK (allocated + ALIGN_STRUCT (1), 0);
869       VALGRIND_FREELIKE_BLOCK (error, 0);
870     }
871   else
872 #endif
873   g_slice_free1 (private_size + sizeof (GError), allocated);
874 }
875
876 /**
877  * g_error_copy:
878  * @error: a #GError
879  *
880  * Makes a copy of @error.
881  *
882  * Returns: a new #GError
883  */
884 GError*
885 g_error_copy (const GError *error)
886 {
887   GError *copy;
888   ErrorDomainInfo info;
889
890   g_return_val_if_fail (error != NULL, NULL);
891   g_return_val_if_fail (error->message != NULL, NULL);
892
893   /* See g_error_new_valist for why this doesn’t return */
894   g_warn_if_fail (error->domain != 0);
895
896   copy = g_error_new_steal (error->domain,
897                             error->code,
898                             g_strdup (error->message),
899                             &info);
900   if (info.copy != NULL)
901     info.copy (error, copy);
902
903   return copy;
904 }
905
906 /**
907  * g_error_matches:
908  * @error: (nullable): a #GError
909  * @domain: an error domain
910  * @code: an error code
911  *
912  * Returns %TRUE if @error matches @domain and @code, %FALSE
913  * otherwise. In particular, when @error is %NULL, %FALSE will
914  * be returned.
915  *
916  * If @domain contains a `FAILED` (or otherwise generic) error code,
917  * you should generally not check for it explicitly, but should
918  * instead treat any not-explicitly-recognized error code as being
919  * equivalent to the `FAILED` code. This way, if the domain is
920  * extended in the future to provide a more specific error code for
921  * a certain case, your code will still work.
922  *
923  * Returns: whether @error has @domain and @code
924  */
925 gboolean
926 g_error_matches (const GError *error,
927                  GQuark        domain,
928                  gint          code)
929 {
930   return error &&
931     error->domain == domain &&
932     error->code == code;
933 }
934
935 #define ERROR_OVERWRITTEN_WARNING "GError set over the top of a previous GError or uninitialized memory.\n" \
936                "This indicates a bug in someone's code. You must ensure an error is NULL before it's set.\n" \
937                "The overwriting error message was: %s"
938
939 /**
940  * g_set_error:
941  * @err: (out callee-allocates) (optional): a return location for a #GError
942  * @domain: error domain
943  * @code: error code
944  * @format: printf()-style format
945  * @...: args for @format
946  *
947  * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
948  * must be %NULL. A new #GError is created and assigned to *@err.
949  */
950 void
951 g_set_error (GError      **err,
952              GQuark        domain,
953              gint          code,
954              const gchar  *format,
955              ...)
956 {
957   GError *new;
958
959   va_list args;
960
961   if (err == NULL)
962     return;
963
964   va_start (args, format);
965   new = g_error_new_valist (domain, code, format, args);
966   va_end (args);
967
968   if (*err == NULL)
969     *err = new;
970   else
971     {
972       g_warning (ERROR_OVERWRITTEN_WARNING, new->message);
973       g_error_free (new);
974     }
975 }
976
977 /**
978  * g_set_error_literal:
979  * @err: (out callee-allocates) (optional): a return location for a #GError
980  * @domain: error domain
981  * @code: error code
982  * @message: error message
983  *
984  * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
985  * must be %NULL. A new #GError is created and assigned to *@err.
986  * Unlike g_set_error(), @message is not a printf()-style format string.
987  * Use this function if @message contains text you don't have control over,
988  * that could include printf() escape sequences.
989  *
990  * Since: 2.18
991  */
992 void
993 g_set_error_literal (GError      **err,
994                      GQuark        domain,
995                      gint          code,
996                      const gchar  *message)
997 {
998   if (err == NULL)
999     return;
1000
1001   if (*err == NULL)
1002     *err = g_error_new_literal (domain, code, message);
1003   else
1004     g_warning (ERROR_OVERWRITTEN_WARNING, message);
1005 }
1006
1007 /**
1008  * g_propagate_error:
1009  * @dest: (out callee-allocates) (optional) (nullable): error return location
1010  * @src: (transfer full): error to move into the return location
1011  *
1012  * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
1013  * The error variable @dest points to must be %NULL.
1014  *
1015  * @src must be non-%NULL.
1016  *
1017  * Note that @src is no longer valid after this call. If you want
1018  * to keep using the same GError*, you need to set it to %NULL
1019  * after calling this function on it.
1020  */
1021 void
1022 g_propagate_error (GError **dest,
1023                    GError  *src)
1024 {
1025   g_return_if_fail (src != NULL);
1026  
1027   if (dest == NULL)
1028     {
1029       g_error_free (src);
1030       return;
1031     }
1032   else
1033     {
1034       if (*dest != NULL)
1035         {
1036           g_warning (ERROR_OVERWRITTEN_WARNING, src->message);
1037           g_error_free (src);
1038         }
1039       else
1040         *dest = src;
1041     }
1042 }
1043
1044 /**
1045  * g_clear_error:
1046  * @err: a #GError return location
1047  *
1048  * If @err or *@err is %NULL, does nothing. Otherwise,
1049  * calls g_error_free() on *@err and sets *@err to %NULL.
1050  */
1051 void
1052 g_clear_error (GError **err)
1053 {
1054   if (err && *err)
1055     {
1056       g_error_free (*err);
1057       *err = NULL;
1058     }
1059 }
1060
1061 G_GNUC_PRINTF(2, 0)
1062 static void
1063 g_error_add_prefix (gchar       **string,
1064                     const gchar  *format,
1065                     va_list       ap)
1066 {
1067   gchar *oldstring;
1068   gchar *prefix;
1069
1070   prefix = g_strdup_vprintf (format, ap);
1071   oldstring = *string;
1072   *string = g_strconcat (prefix, oldstring, NULL);
1073   g_free (oldstring);
1074   g_free (prefix);
1075 }
1076
1077 /**
1078  * g_prefix_error:
1079  * @err: (inout) (optional) (nullable): a return location for a #GError
1080  * @format: printf()-style format string
1081  * @...: arguments to @format
1082  *
1083  * Formats a string according to @format and prefix it to an existing
1084  * error message. If @err is %NULL (ie: no error variable) then do
1085  * nothing.
1086  *
1087  * If *@err is %NULL (ie: an error variable is present but there is no
1088  * error condition) then also do nothing.
1089  *
1090  * Since: 2.16
1091  */
1092 void
1093 g_prefix_error (GError      **err,
1094                 const gchar  *format,
1095                 ...)
1096 {
1097   if (err && *err)
1098     {
1099       va_list ap;
1100
1101       va_start (ap, format);
1102       g_error_add_prefix (&(*err)->message, format, ap);
1103       va_end (ap);
1104     }
1105 }
1106
1107 /**
1108  * g_prefix_error_literal:
1109  * @err: (allow-none): a return location for a #GError, or %NULL
1110  * @prefix: string to prefix @err with
1111  *
1112  * Prefixes @prefix to an existing error message. If @err or *@err is
1113  * %NULL (i.e.: no error variable) then do nothing.
1114  *
1115  * Since: 2.70
1116  */
1117 void
1118 g_prefix_error_literal (GError      **err,
1119                         const gchar  *prefix)
1120 {
1121   if (err && *err)
1122     {
1123       gchar *oldstring;
1124
1125       oldstring = (*err)->message;
1126       (*err)->message = g_strconcat (prefix, oldstring, NULL);
1127       g_free (oldstring);
1128     }
1129 }
1130
1131 /**
1132  * g_propagate_prefixed_error:
1133  * @dest: error return location
1134  * @src: error to move into the return location
1135  * @format: printf()-style format string
1136  * @...: arguments to @format
1137  *
1138  * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
1139  * *@dest must be %NULL. After the move, add a prefix as with
1140  * g_prefix_error().
1141  *
1142  * Since: 2.16
1143  **/
1144 void
1145 g_propagate_prefixed_error (GError      **dest,
1146                             GError       *src,
1147                             const gchar  *format,
1148                             ...)
1149 {
1150   g_propagate_error (dest, src);
1151
1152   if (dest)
1153     {
1154       va_list ap;
1155
1156       g_assert (*dest != NULL);
1157       va_start (ap, format);
1158       g_error_add_prefix (&(*dest)->message, format, ap);
1159       va_end (ap);
1160     }
1161 }