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

source code of gtk/subprojects/glib/glib/gerror.c