Coverage Report

Created: 2025-10-10 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/irssi/subprojects/glib-2.74.3/glib/gerror.c
Line
Count
Source
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
8
{
525
8
  error_domain_ht = g_hash_table_new (NULL, NULL);
526
8
}
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
24.4k
{
542
24.4k
  return g_hash_table_lookup (error_domain_ht,
543
24.4k
                              GUINT_TO_POINTER (domain));
544
24.4k
}
545
546
/* Copied from gtype.c. */
547
0
#define STRUCT_ALIGNMENT (2 * sizeof (gsize))
548
#define ALIGN_STRUCT(offset) \
549
0
      ((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
0
{
558
0
  g_rw_lock_writer_lock (&error_domain_global);
559
0
  if (error_domain_lookup (error_quark) == NULL)
560
0
    {
561
0
      ErrorDomainInfo *info = g_new (ErrorDomainInfo, 1);
562
0
      info->private_size = ALIGN_STRUCT (error_type_private_size);
563
0
      info->init = error_type_init;
564
0
      info->copy = error_type_copy;
565
0
      info->clear = error_type_clear;
566
567
0
      g_hash_table_insert (error_domain_ht,
568
0
                           GUINT_TO_POINTER (error_quark),
569
0
                           info);
570
0
    }
571
0
  else
572
0
    {
573
0
      const char *name = g_quark_to_string (error_quark);
574
575
0
      g_critical ("Attempted to register an extended error domain for %s more than once", name);
576
0
    }
577
0
  g_rw_lock_writer_unlock (&error_domain_global);
578
0
}
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
0
{
616
0
  GQuark error_quark;
617
618
0
  g_return_val_if_fail (error_type_name != NULL, 0);
619
0
  g_return_val_if_fail (error_type_private_size > 0, 0);
620
0
  g_return_val_if_fail (error_type_init != NULL, 0);
621
0
  g_return_val_if_fail (error_type_copy != NULL, 0);
622
0
  g_return_val_if_fail (error_type_clear != NULL, 0);
623
624
0
  error_quark = g_quark_from_static_string (error_type_name);
625
0
  error_domain_register (error_quark,
626
0
                         error_type_private_size,
627
0
                         error_type_init,
628
0
                         error_type_copy,
629
0
                         error_type_clear);
630
0
  return error_quark;
631
0
}
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
0
{
655
0
  GQuark error_quark;
656
657
0
  g_return_val_if_fail (error_type_name != NULL, 0);
658
0
  g_return_val_if_fail (error_type_private_size > 0, 0);
659
0
  g_return_val_if_fail (error_type_init != NULL, 0);
660
0
  g_return_val_if_fail (error_type_copy != NULL, 0);
661
0
  g_return_val_if_fail (error_type_clear != NULL, 0);
662
663
0
  error_quark = g_quark_from_string (error_type_name);
664
0
  error_domain_register (error_quark,
665
0
                         error_type_private_size,
666
0
                         error_type_init,
667
0
                         error_type_copy,
668
0
                         error_type_clear);
669
0
  return error_quark;
670
0
}
671
672
static GError *
673
g_error_allocate (GQuark domain, ErrorDomainInfo *out_info)
674
12.2k
{
675
12.2k
  guint8 *allocated;
676
12.2k
  GError *error;
677
12.2k
  ErrorDomainInfo *info;
678
12.2k
  gsize private_size;
679
680
12.2k
  g_rw_lock_reader_lock (&error_domain_global);
681
12.2k
  info = error_domain_lookup (domain);
682
12.2k
  if (info != NULL)
683
0
    {
684
0
      if (out_info != NULL)
685
0
        *out_info = *info;
686
0
      private_size = info->private_size;
687
0
      g_rw_lock_reader_unlock (&error_domain_global);
688
0
    }
689
12.2k
  else
690
12.2k
    {
691
12.2k
      g_rw_lock_reader_unlock (&error_domain_global);
692
12.2k
      if (out_info != NULL)
693
12.2k
        memset (out_info, 0, sizeof (*out_info));
694
12.2k
      private_size = 0;
695
12.2k
    }
696
  /* See comments in g_type_create_instance in gtype.c to see what
697
   * this magic is about.
698
   */
699
12.2k
#ifdef ENABLE_VALGRIND
700
12.2k
  if (private_size > 0 && RUNNING_ON_VALGRIND)
701
0
    {
702
0
      private_size += ALIGN_STRUCT (1);
703
0
      allocated = g_slice_alloc0 (private_size + sizeof (GError) + sizeof (gpointer));
704
0
      *(gpointer *) (allocated + private_size + sizeof (GError)) = allocated + ALIGN_STRUCT (1);
705
0
      VALGRIND_MALLOCLIKE_BLOCK (allocated + private_size, sizeof (GError) + sizeof (gpointer), 0, TRUE);
706
0
      VALGRIND_MALLOCLIKE_BLOCK (allocated + ALIGN_STRUCT (1), private_size - ALIGN_STRUCT (1), 0, TRUE);
707
0
    }
708
12.2k
  else
709
12.2k
#endif
710
12.2k
    allocated = g_slice_alloc0 (private_size + sizeof (GError));
711
712
12.2k
  error = (GError *) (allocated + private_size);
713
12.2k
  return error;
714
12.2k
}
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
12.2k
{
723
12.2k
  ErrorDomainInfo info;
724
12.2k
  GError *error = g_error_allocate (domain, &info);
725
726
12.2k
  error->domain = domain;
727
12.2k
  error->code = code;
728
12.2k
  error->message = message;
729
730
12.2k
  if (info.init != NULL)
731
0
    info.init (error);
732
12.2k
  if (out_info != NULL)
733
0
    *out_info = info;
734
735
12.2k
  return error;
736
12.2k
}
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
0
{
758
  /* Historically, GError allowed this (although it was never meant to work),
759
   * and it has significant use in the wild, which g_return_val_if_fail
760
   * would break. It should maybe g_return_val_if_fail in GLib 4.
761
   * (GNOME#660371, GNOME#560482)
762
   */
763
0
  g_warn_if_fail (domain != 0);
764
0
  g_warn_if_fail (format != NULL);
765
766
0
  return g_error_new_steal (domain, code, g_strdup_vprintf (format, args), NULL);
767
0
}
768
769
/**
770
 * g_error_new:
771
 * @domain: error domain
772
 * @code: error code
773
 * @format: printf()-style format for error message
774
 * @...: parameters for message format
775
 *
776
 * Creates a new #GError with the given @domain and @code,
777
 * and a message formatted with @format.
778
 *
779
 * Returns: a new #GError
780
 */
781
GError*
782
g_error_new (GQuark       domain,
783
             gint         code,
784
             const gchar *format,
785
             ...)
786
0
{
787
0
  GError* error;
788
0
  va_list args;
789
790
0
  g_return_val_if_fail (format != NULL, NULL);
791
0
  g_return_val_if_fail (domain != 0, NULL);
792
793
0
  va_start (args, format);
794
0
  error = g_error_new_valist (domain, code, format, args);
795
0
  va_end (args);
796
797
0
  return error;
798
0
}
799
800
/**
801
 * g_error_new_literal:
802
 * @domain: error domain
803
 * @code: error code
804
 * @message: error message
805
 *
806
 * Creates a new #GError; unlike g_error_new(), @message is
807
 * not a printf()-style format string. Use this function if
808
 * @message contains text you don't have control over,
809
 * that could include printf() escape sequences.
810
 *
811
 * Returns: a new #GError
812
 **/
813
GError*
814
g_error_new_literal (GQuark         domain,
815
                     gint           code,
816
                     const gchar   *message)
817
12.2k
{
818
12.2k
  g_return_val_if_fail (message != NULL, NULL);
819
12.2k
  g_return_val_if_fail (domain != 0, NULL);
820
821
12.2k
  return g_error_new_steal (domain, code, g_strdup (message), NULL);
822
12.2k
}
823
824
/**
825
 * g_error_free:
826
 * @error: a #GError
827
 *
828
 * Frees a #GError and associated resources.
829
 */
830
void
831
g_error_free (GError *error)
832
12.2k
{
833
12.2k
  gsize private_size;
834
12.2k
  ErrorDomainInfo *info;
835
12.2k
  guint8 *allocated;
836
837
12.2k
  g_return_if_fail (error != NULL);
838
839
12.2k
  g_rw_lock_reader_lock (&error_domain_global);
840
12.2k
  info = error_domain_lookup (error->domain);
841
12.2k
  if (info != NULL)
842
0
    {
843
0
      GErrorClearFunc clear = info->clear;
844
845
0
      private_size = info->private_size;
846
0
      g_rw_lock_reader_unlock (&error_domain_global);
847
0
      clear (error);
848
0
    }
849
12.2k
  else
850
12.2k
    {
851
12.2k
      g_rw_lock_reader_unlock (&error_domain_global);
852
12.2k
      private_size = 0;
853
12.2k
    }
854
855
12.2k
  g_free (error->message);
856
12.2k
  allocated = ((guint8 *) error) - private_size;
857
  /* See comments in g_type_free_instance in gtype.c to see what this
858
   * magic is about.
859
   */
860
12.2k
#ifdef ENABLE_VALGRIND
861
12.2k
  if (private_size > 0 && RUNNING_ON_VALGRIND)
862
0
    {
863
0
      private_size += ALIGN_STRUCT (1);
864
0
      allocated -= ALIGN_STRUCT (1);
865
0
      *(gpointer *) (allocated + private_size + sizeof (GError)) = NULL;
866
0
      g_slice_free1 (private_size + sizeof (GError) + sizeof (gpointer), allocated);
867
0
      VALGRIND_FREELIKE_BLOCK (allocated + ALIGN_STRUCT (1), 0);
868
0
      VALGRIND_FREELIKE_BLOCK (error, 0);
869
0
    }
870
12.2k
  else
871
12.2k
#endif
872
12.2k
  g_slice_free1 (private_size + sizeof (GError), allocated);
873
12.2k
}
874
875
/**
876
 * g_error_copy:
877
 * @error: a #GError
878
 *
879
 * Makes a copy of @error.
880
 *
881
 * Returns: a new #GError
882
 */
883
GError*
884
g_error_copy (const GError *error)
885
0
{
886
0
  GError *copy;
887
0
  ErrorDomainInfo info;
888
889
0
  g_return_val_if_fail (error != NULL, NULL);
890
  /* See g_error_new_valist for why these don't return */
891
0
  g_warn_if_fail (error->domain != 0);
892
0
  g_warn_if_fail (error->message != NULL);
893
894
0
  copy = g_error_new_steal (error->domain,
895
0
                            error->code,
896
0
                            g_strdup (error->message),
897
0
                            &info);
898
0
  if (info.copy != NULL)
899
0
    info.copy (error, copy);
900
901
0
  return copy;
902
0
}
903
904
/**
905
 * g_error_matches:
906
 * @error: (nullable): a #GError
907
 * @domain: an error domain
908
 * @code: an error code
909
 *
910
 * Returns %TRUE if @error matches @domain and @code, %FALSE
911
 * otherwise. In particular, when @error is %NULL, %FALSE will
912
 * be returned.
913
 *
914
 * If @domain contains a `FAILED` (or otherwise generic) error code,
915
 * you should generally not check for it explicitly, but should
916
 * instead treat any not-explicitly-recognized error code as being
917
 * equivalent to the `FAILED` code. This way, if the domain is
918
 * extended in the future to provide a more specific error code for
919
 * a certain case, your code will still work.
920
 *
921
 * Returns: whether @error has @domain and @code
922
 */
923
gboolean
924
g_error_matches (const GError *error,
925
                 GQuark        domain,
926
                 gint          code)
927
3.01k
{
928
3.01k
  return error &&
929
3.01k
    error->domain == domain &&
930
3.01k
    error->code == code;
931
3.01k
}
932
933
#define ERROR_OVERWRITTEN_WARNING "GError set over the top of a previous GError or uninitialized memory.\n" \
934
               "This indicates a bug in someone's code. You must ensure an error is NULL before it's set.\n" \
935
               "The overwriting error message was: %s"
936
937
/**
938
 * g_set_error:
939
 * @err: (out callee-allocates) (optional): a return location for a #GError
940
 * @domain: error domain
941
 * @code: error code
942
 * @format: printf()-style format
943
 * @...: args for @format
944
 *
945
 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
946
 * must be %NULL. A new #GError is created and assigned to *@err.
947
 */
948
void
949
g_set_error (GError      **err,
950
             GQuark        domain,
951
             gint          code,
952
             const gchar  *format,
953
             ...)
954
1.22k
{
955
1.22k
  GError *new;
956
957
1.22k
  va_list args;
958
959
1.22k
  if (err == NULL)
960
1.22k
    return;
961
962
1.22k
  va_start (args, format);
963
0
  new = g_error_new_valist (domain, code, format, args);
964
0
  va_end (args);
965
966
0
  if (*err == NULL)
967
0
    *err = new;
968
0
  else
969
0
    {
970
0
      g_warning (ERROR_OVERWRITTEN_WARNING, new->message);
971
0
      g_error_free (new);
972
0
    }
973
0
}
974
975
/**
976
 * g_set_error_literal:
977
 * @err: (out callee-allocates) (optional): a return location for a #GError
978
 * @domain: error domain
979
 * @code: error code
980
 * @message: error message
981
 *
982
 * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err
983
 * must be %NULL. A new #GError is created and assigned to *@err.
984
 * Unlike g_set_error(), @message is not a printf()-style format string.
985
 * Use this function if @message contains text you don't have control over,
986
 * that could include printf() escape sequences.
987
 *
988
 * Since: 2.18
989
 */
990
void
991
g_set_error_literal (GError      **err,
992
                     GQuark        domain,
993
                     gint          code,
994
                     const gchar  *message)
995
81.0k
{
996
81.0k
  if (err == NULL)
997
68.8k
    return;
998
999
12.2k
  if (*err == NULL)
1000
12.2k
    *err = g_error_new_literal (domain, code, message);
1001
0
  else
1002
0
    g_warning (ERROR_OVERWRITTEN_WARNING, message);
1003
12.2k
}
1004
1005
/**
1006
 * g_propagate_error:
1007
 * @dest: (out callee-allocates) (optional) (nullable): error return location
1008
 * @src: (transfer full): error to move into the return location
1009
 *
1010
 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
1011
 * The error variable @dest points to must be %NULL.
1012
 *
1013
 * @src must be non-%NULL.
1014
 *
1015
 * Note that @src is no longer valid after this call. If you want
1016
 * to keep using the same GError*, you need to set it to %NULL
1017
 * after calling this function on it.
1018
 */
1019
void
1020
g_propagate_error (GError **dest,
1021
       GError  *src)
1022
0
{
1023
0
  g_return_if_fail (src != NULL);
1024
 
1025
0
  if (dest == NULL)
1026
0
    {
1027
0
      g_error_free (src);
1028
0
      return;
1029
0
    }
1030
0
  else
1031
0
    {
1032
0
      if (*dest != NULL)
1033
0
        {
1034
0
          g_warning (ERROR_OVERWRITTEN_WARNING, src->message);
1035
0
          g_error_free (src);
1036
0
        }
1037
0
      else
1038
0
        *dest = src;
1039
0
    }
1040
0
}
1041
1042
/**
1043
 * g_clear_error:
1044
 * @err: a #GError return location
1045
 *
1046
 * If @err or *@err is %NULL, does nothing. Otherwise,
1047
 * calls g_error_free() on *@err and sets *@err to %NULL.
1048
 */
1049
void
1050
g_clear_error (GError **err)
1051
59.6k
{
1052
59.6k
  if (err && *err)
1053
9.19k
    {
1054
9.19k
      g_error_free (*err);
1055
9.19k
      *err = NULL;
1056
9.19k
    }
1057
59.6k
}
1058
1059
G_GNUC_PRINTF(2, 0)
1060
static void
1061
g_error_add_prefix (gchar       **string,
1062
                    const gchar  *format,
1063
                    va_list       ap)
1064
0
{
1065
0
  gchar *oldstring;
1066
0
  gchar *prefix;
1067
1068
0
  prefix = g_strdup_vprintf (format, ap);
1069
0
  oldstring = *string;
1070
0
  *string = g_strconcat (prefix, oldstring, NULL);
1071
0
  g_free (oldstring);
1072
0
  g_free (prefix);
1073
0
}
1074
1075
/**
1076
 * g_prefix_error:
1077
 * @err: (inout) (optional) (nullable): a return location for a #GError
1078
 * @format: printf()-style format string
1079
 * @...: arguments to @format
1080
 *
1081
 * Formats a string according to @format and prefix it to an existing
1082
 * error message. If @err is %NULL (ie: no error variable) then do
1083
 * nothing.
1084
 *
1085
 * If *@err is %NULL (ie: an error variable is present but there is no
1086
 * error condition) then also do nothing.
1087
 *
1088
 * Since: 2.16
1089
 */
1090
void
1091
g_prefix_error (GError      **err,
1092
                const gchar  *format,
1093
                ...)
1094
0
{
1095
0
  if (err && *err)
1096
0
    {
1097
0
      va_list ap;
1098
1099
0
      va_start (ap, format);
1100
0
      g_error_add_prefix (&(*err)->message, format, ap);
1101
0
      va_end (ap);
1102
0
    }
1103
0
}
1104
1105
/**
1106
 * g_prefix_error_literal:
1107
 * @err: (allow-none): a return location for a #GError, or %NULL
1108
 * @prefix: string to prefix @err with
1109
 *
1110
 * Prefixes @prefix to an existing error message. If @err or *@err is
1111
 * %NULL (i.e.: no error variable) then do nothing.
1112
 *
1113
 * Since: 2.70
1114
 */
1115
void
1116
g_prefix_error_literal (GError      **err,
1117
                        const gchar  *prefix)
1118
0
{
1119
0
  if (err && *err)
1120
0
    {
1121
0
      gchar *oldstring;
1122
1123
0
      oldstring = (*err)->message;
1124
0
      (*err)->message = g_strconcat (prefix, oldstring, NULL);
1125
0
      g_free (oldstring);
1126
0
    }
1127
0
}
1128
1129
/**
1130
 * g_propagate_prefixed_error:
1131
 * @dest: error return location
1132
 * @src: error to move into the return location
1133
 * @format: printf()-style format string
1134
 * @...: arguments to @format
1135
 *
1136
 * If @dest is %NULL, free @src; otherwise, moves @src into *@dest.
1137
 * *@dest must be %NULL. After the move, add a prefix as with
1138
 * g_prefix_error().
1139
 *
1140
 * Since: 2.16
1141
 **/
1142
void
1143
g_propagate_prefixed_error (GError      **dest,
1144
                            GError       *src,
1145
                            const gchar  *format,
1146
                            ...)
1147
0
{
1148
0
  g_propagate_error (dest, src);
1149
1150
0
  if (dest)
1151
0
    {
1152
0
      va_list ap;
1153
1154
0
      g_assert (*dest != NULL);
1155
0
      va_start (ap, format);
1156
0
      g_error_add_prefix (&(*dest)->message, format, ap);
1157
      va_end (ap);
1158
0
    }
1159
0
}