Coverage Report

Created: 2026-12-01 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/rauc/subprojects/glib-2.90.1/gio/gresource.c
Line
Count
Source
1
/* GIO - GLib Input, Output and Streaming Library
2
 *
3
 * Copyright © 2011 Red Hat, Inc
4
 *
5
 * SPDX-License-Identifier: LGPL-2.1-or-later
6
 *
7
 * This library is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * This library is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General
18
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
19
 *
20
 * Authors: Alexander Larsson <alexl@redhat.com>
21
 */
22
23
#include "config.h"
24
25
#include <stdint.h>
26
#include <string.h>
27
28
#include "gresource.h"
29
#include <gvdb/gvdb-reader.h>
30
#include <gi18n-lib.h>
31
#include <gstdio.h>
32
#include <gio/gfile.h>
33
#include <gio/gioerror.h>
34
#include <gio/gmemoryinputstream.h>
35
#include <gio/gzlibdecompressor.h>
36
#include <gio/gconverterinputstream.h>
37
38
#include "glib-private.h"
39
40
struct _GResource
41
{
42
  int ref_count;
43
44
  GvdbTable *table;
45
};
46
47
static void register_lazy_static_resources (void);
48
49
0
G_DEFINE_BOXED_TYPE (GResource, g_resource, g_resource_ref, g_resource_unref)
50
0
51
0
/**
52
0
 * GResource:
53
0
 *
54
0
 * Applications and libraries often contain binary or textual data that is
55
0
 * really part of the application, rather than user data. For instance
56
0
 * [`GtkBuilder`](https://docs.gtk.org/gtk4/class.Builder.html) `.ui` files,
57
0
 * splashscreen images, [class@Gio.Menu] markup XML, CSS files, icons, etc.
58
0
 * These are often shipped as files in `$datadir/appname`, or manually
59
0
 * included as literal strings in the code.
60
0
 *
61
0
 * The `GResource` API and the
62
0
 * [`glib-compile-resources`](glib-compile-resources.html) program provide a
63
0
 * convenient and efficient alternative to this which has some nice properties.
64
0
 * You maintain the files as normal files, so it’s easy to edit them, but during
65
0
 * the build the files are combined into a binary bundle that is linked into the
66
0
 * executable. This means that loading the resource files are efficient (as they
67
0
 * are already in memory, shared with other instances) and simple (no need to
68
0
 * check for things like I/O errors or locate the files in the filesystem). It
69
0
 * also makes it easier to create relocatable applications.
70
0
 *
71
0
 * Resource files can also be marked as compressed. Such files will be included
72
0
 * in the resource bundle in a compressed form, but will be automatically
73
0
 * uncompressed when the resource is used. This is very useful e.g. for larger
74
0
 * text files that are parsed once (or rarely) and then thrown away.
75
0
 *
76
0
 * Resource files can also be marked to be preprocessed, by setting the value of the
77
0
 * `preprocess` attribute to a comma-separated list of preprocessing options.
78
0
 * The only options currently supported are:
79
0
 *
80
0
 *  - `xml-stripblanks` which will use the [`xmllint`](man:xmllint(1)) command
81
0
 *    to strip ignorable whitespace from the XML file. For this to work,
82
0
 *    the `XMLLINT` environment variable must be set to the full path to
83
0
 *    the xmllint executable, or xmllint must be in the `PATH`; otherwise
84
0
 *    the preprocessing step is skipped.
85
0
 *
86
0
 *  - `to-pixdata` (deprecated since gdk-pixbuf 2.32) which will use the
87
0
 *    `gdk-pixbuf-pixdata` command to convert images to the [`GdkPixdata`](https://docs.gtk.org/gdk-pixbuf/class.Pixdata.html)
88
0
 *    format, which allows you to create pixbufs directly using the data inside
89
0
 *    the resource file, rather than an (uncompressed) copy of it. For this, the
90
0
 *    `gdk-pixbuf-pixdata` program must be in the `PATH`, or the
91
0
 *    `GDK_PIXBUF_PIXDATA` environment variable must be set to the full path to
92
0
 *    the `gdk-pixbuf-pixdata` executable; otherwise the resource compiler will
93
0
 *    abort. `to-pixdata` has been deprecated since gdk-pixbuf 2.32, as
94
0
 *    `GResource` supports embedding modern image formats just as well. Instead
95
0
 *    of using it, embed a PNG or SVG file in your `GResource`.
96
0
 *
97
0
 *  - `json-stripblanks` which will use the
98
0
 *    [`json-glib-format`](man:json-glib-format(1)) command to strip ignorable
99
0
 *    whitespace from the JSON file. For this to work, the `JSON_GLIB_FORMAT`
100
0
 *    environment variable must be set to the full path to the
101
0
 *    `json-glib-format` executable, or it must be in the `PATH`; otherwise the
102
0
 *    preprocessing step is skipped. In addition, at least version 1.6 of
103
0
 *    `json-glib-format` is required.
104
0
 *
105
0
 * Resource files will be exported in the `GResource` namespace using the
106
0
 * combination of the given `prefix` and the filename from the `file` element.
107
0
 * The `alias` attribute can be used to alter the filename to expose them at a
108
0
 * different location in the resource namespace. Typically, this is used to
109
0
 * include files from a different source directory without exposing the source
110
0
 * directory in the resource namespace, as in the example below.
111
0
 *
112
0
 * Resource bundles are created by the
113
0
 * [`glib-compile-resources`](glib-compile-resources.html) program
114
0
 * which takes an XML file that describes the bundle, and a set of files that
115
0
 * the XML references. These are combined into a binary resource bundle.
116
0
 *
117
0
 * An example resource description:
118
0
 * ```xml
119
0
 * <?xml version="1.0" encoding="UTF-8"?>
120
0
 * <gresources>
121
0
 *   <gresource prefix="/org/gtk/Example">
122
0
 *     <file>data/splashscreen.png</file>
123
0
 *     <file compressed="true">dialog.ui</file>
124
0
 *     <file preprocess="xml-stripblanks">menumarkup.xml</file>
125
0
 *     <file alias="example.css">data/example.css</file>
126
0
 *   </gresource>
127
0
 * </gresources>
128
0
 * ```
129
0
 *
130
0
 * This will create a resource bundle with the following files:
131
0
 * ```
132
0
 * /org/gtk/Example/data/splashscreen.png
133
0
 * /org/gtk/Example/dialog.ui
134
0
 * /org/gtk/Example/menumarkup.xml
135
0
 * /org/gtk/Example/example.css
136
0
 * ```
137
0
 *
138
0
 * Note that all resources in the process share the same namespace, so use
139
0
 * Java-style path prefixes (like in the above example) to avoid conflicts.
140
0
 *
141
0
 * You can then use [`glib-compile-resources`](glib-compile-resources.html) to
142
0
 * compile the XML to a binary bundle that you can load with
143
0
 * [func@Gio.Resource.load]. However, it’s more common to use the
144
0
 * `--generate-source` and `--generate-header` arguments to create a source file
145
0
 * and header to link directly into your application.
146
0
 * This will generate `get_resource()`, `register_resource()` and
147
0
 * `unregister_resource()` functions, prefixed by the `--c-name` argument passed
148
0
 * to [`glib-compile-resources`](glib-compile-resources.html). `get_resource()`
149
0
 * returns the generated `GResource` object. The register and unregister
150
0
 * functions register the resource so its files can be accessed using
151
0
 * [func@Gio.resources_lookup_data].
152
0
 *
153
0
 * Once a `GResource` has been created and registered all the data in it can be
154
0
 * accessed globally in the process by using API calls like
155
0
 * [func@Gio.resources_open_stream] to stream the data or
156
0
 * [func@Gio.resources_lookup_data] to get a direct pointer to the data. You can
157
0
 * also use URIs like `resource:///org/gtk/Example/data/splashscreen.png` with
158
0
 * [iface@Gio.File] to access the resource data.
159
0
 *
160
0
 * Some higher-level APIs, such as [`GtkApplication`](https://docs.gtk.org/gtk4/class.Application.html),
161
0
 * will automatically load resources from certain well-known paths in the
162
0
 * resource namespace as a convenience. See the documentation for those APIs
163
0
 * for details.
164
0
 *
165
0
 * There are two forms of the generated source, the default version uses the
166
0
 * compiler support for constructor and destructor functions (where available)
167
0
 * to automatically create and register the `GResource` on startup or library
168
0
 * load time. If you pass `--manual-register`, two functions to
169
0
 * register/unregister the resource are created instead. This requires an
170
0
 * explicit initialization call in your application/library, but it works on all
171
0
 * platforms, even on the minor ones where constructors are not supported.
172
0
 * (Constructor support is available for at least Win32, Mac OS and Linux.)
173
0
 *
174
0
 * Note that resource data can point directly into the data segment of e.g. a
175
0
 * library, so if you are unloading libraries during runtime you need to be very
176
0
 * careful with keeping around pointers to data from a resource, as this goes
177
0
 * away when the library is unloaded. However, in practice this is not generally
178
0
 * a problem, since most resource accesses are for your own resources, and
179
0
 * resource data is often used once, during parsing, and then released.
180
0
 *
181
0
 * # Overlays
182
0
 *
183
0
 * When debugging a program or testing a change to an installed version, it is
184
0
 * often useful to be able to replace resources in the program or library,
185
0
 * without recompiling, for debugging or quick hacking and testing purposes.
186
0
 * Since GLib 2.50, it is possible to use the `G_RESOURCE_OVERLAYS` environment
187
0
 * variable to selectively overlay resources with replacements from the
188
0
 * filesystem.  It is a `G_SEARCHPATH_SEPARATOR`-separated list of substitutions
189
0
 * to perform during resource lookups. It is ignored when running in a setuid
190
0
 * process.
191
0
 *
192
0
 * A substitution has the form
193
0
 *
194
0
 * ```
195
0
 * /org/gtk/libgtk=/home/desrt/gtk-overlay
196
0
 * ```
197
0
 *
198
0
 * The part before the `=` is the resource subpath for which the overlay
199
0
 * applies.  The part after is a filesystem path which contains files and
200
0
 * subdirectories as you would like to be loaded as resources with the
201
0
 * equivalent names.
202
0
 *
203
0
 * In the example above, if an application tried to load a resource with the
204
0
 * resource path `/org/gtk/libgtk/ui/gtkdialog.ui` then `GResource` would check
205
0
 * the filesystem path `/home/desrt/gtk-overlay/ui/gtkdialog.ui`.  If a file was
206
0
 * found there, it would be used instead.  This is an overlay, not an outright
207
0
 * replacement, which means that if a file is not found at that path, the
208
0
 * built-in version will be used instead.  Whiteouts are not currently
209
0
 * supported.
210
0
 *
211
0
 * Substitutions must start with a slash, and must not contain a trailing slash
212
0
 * before the `=`.  The filesystem path after the `=` should ideally be absolute,
213
0
 * but this is not strictly required.  It is possible to overlay the location of
214
0
 * a single resource with an individual file.
215
0
 *
216
0
 * Since: 2.32
217
0
 */
218
0
219
0
/**
220
0
 * GStaticResource:
221
0
 *
222
0
 * `GStaticResource` is an opaque data structure and can only be accessed
223
0
 * using the following functions.
224
0
 **/
225
0
typedef gboolean (* CheckCandidate) (const gchar *candidate, gpointer user_data);
226
0
227
0
static gboolean
228
0
open_overlay_stream (const gchar *candidate,
229
0
                     gpointer     user_data)
230
0
{
231
0
  GInputStream **res = (GInputStream **) user_data;
232
0
  GError *error = NULL;
233
0
  GFile *file;
234
235
0
  file = g_file_new_for_path (candidate);
236
0
  *res = (GInputStream *) g_file_read (file, NULL, &error);
237
238
0
  if (*res)
239
0
    {
240
0
      g_message ("Opened file '%s' as a resource overlay", candidate);
241
0
    }
242
0
  else
243
0
    {
244
0
      if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
245
0
        g_warning ("Can't open overlay file '%s': %s", candidate, error->message);
246
0
      g_error_free (error);
247
0
    }
248
249
0
  g_object_unref (file);
250
251
0
  return *res != NULL;
252
0
}
253
254
static gboolean
255
get_overlay_bytes (const gchar *candidate,
256
                   gpointer     user_data)
257
0
{
258
0
  GBytes **res = (GBytes **) user_data;
259
0
  GMappedFile *mapped_file;
260
0
  GError *error = NULL;
261
262
0
  mapped_file = g_mapped_file_new (candidate, FALSE, &error);
263
264
0
  if (mapped_file)
265
0
    {
266
0
      g_message ("Mapped file '%s' as a resource overlay", candidate);
267
0
      *res = g_mapped_file_get_bytes (mapped_file);
268
0
      g_mapped_file_unref (mapped_file);
269
0
    }
270
0
  else
271
0
    {
272
0
      if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
273
0
        g_warning ("Can't mmap overlay file '%s': %s", candidate, error->message);
274
0
      g_error_free (error);
275
0
    }
276
277
0
  return *res != NULL;
278
0
}
279
280
static gboolean
281
enumerate_overlay_dir (const gchar *candidate,
282
                       gpointer     user_data)
283
0
{
284
0
  GHashTable **hash = (GHashTable **) user_data;
285
0
  GError *error = NULL;
286
0
  GDir *dir;
287
0
  const gchar *name;
288
289
0
  dir = g_dir_open (candidate, 0, &error);
290
0
  if (dir)
291
0
    {
292
0
      if (*hash == NULL)
293
        /* note: keep in sync with same line below */
294
0
        *hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
295
296
0
      g_message ("Enumerating directory '%s' as resource overlay", candidate);
297
298
0
      while ((name = g_dir_read_name (dir)))
299
0
        {
300
0
          gchar *fullname = g_build_filename (candidate, name, NULL);
301
302
          /* match gvdb behaviour by suffixing "/" on dirs */
303
0
          if (g_file_test (fullname, G_FILE_TEST_IS_DIR))
304
0
            g_hash_table_add (*hash, g_strconcat (name, "/", NULL));
305
0
          else
306
0
            g_hash_table_add (*hash, g_strdup (name));
307
308
0
          g_free (fullname);
309
0
        }
310
311
0
      g_dir_close (dir);
312
0
    }
313
0
  else
314
0
    {
315
0
      if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
316
0
        g_warning ("Can't enumerate overlay directory '%s': %s", candidate, error->message);
317
0
      g_error_free (error);
318
0
      return FALSE;
319
0
    }
320
321
  /* We may want to enumerate results from more than one overlay
322
   * directory.
323
   */
324
0
  return FALSE;
325
0
}
326
327
typedef struct {
328
  gsize size;
329
  guint32 flags;
330
} InfoData;
331
332
static gboolean
333
get_overlay_info (const gchar *candidate,
334
                  gpointer     user_data)
335
0
{
336
0
  InfoData *info = user_data;
337
0
  GStatBuf buf;
338
339
0
  if (g_stat (candidate, &buf) < 0)
340
0
    return FALSE;
341
342
0
  info->size = buf.st_size;
343
0
  info->flags = G_RESOURCE_FLAGS_NONE;
344
345
0
  return TRUE;
346
0
}
347
348
static gboolean
349
g_resource_find_overlay (const gchar    *path,
350
                         CheckCandidate  check,
351
                         gpointer        user_data)
352
0
{
353
  /* This is a null-terminated array of replacement strings (with '=' inside) */
354
0
  static const gchar * const *overlay_dirs;
355
0
  gboolean res = FALSE;
356
0
  size_t path_len = 0;
357
358
  /* We try to be very fast in case there are no overlays.  Otherwise,
359
   * we can take a bit more time...
360
   */
361
362
0
  if (g_once_init_enter_pointer (&overlay_dirs))
363
0
    {
364
0
      gboolean is_setuid = GLIB_PRIVATE_CALL (g_check_setuid) ();
365
0
      const gchar * const *result;
366
0
      const gchar *envvar;
367
368
      /* Don’t load overlays if setuid, as they could allow reading privileged
369
       * files. */
370
0
      envvar = !is_setuid ? g_getenv ("G_RESOURCE_OVERLAYS") : NULL;
371
0
      if (envvar != NULL)
372
0
        {
373
0
          gchar **parts;
374
0
          size_t j = 0;
375
376
0
          parts = g_strsplit (envvar, G_SEARCHPATH_SEPARATOR_S, 0);
377
378
          /* Sanity check the parts, dropping those that are invalid.
379
           * 'i' may grow faster than 'j'.
380
           */
381
0
          for (size_t i = 0; parts[i]; i++)
382
0
            {
383
0
              gchar *part = parts[i];
384
0
              gchar *eq;
385
386
0
              eq = strchr (part, '=');
387
0
              if (eq == NULL)
388
0
                {
389
0
                  g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks '='.  Ignoring.", part);
390
0
                  g_free (part);
391
0
                  continue;
392
0
                }
393
394
0
              if (eq == part)
395
0
                {
396
0
                  g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks path before '='.  Ignoring.", part);
397
0
                  g_free (part);
398
0
                  continue;
399
0
                }
400
401
0
              if (eq[1] == '\0')
402
0
                {
403
0
                  g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks path after '='.  Ignoring", part);
404
0
                  g_free (part);
405
0
                  continue;
406
0
                }
407
408
0
              if (part[0] != '/')
409
0
                {
410
0
                  g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks leading '/'.  Ignoring.", part);
411
0
                  g_free (part);
412
0
                  continue;
413
0
                }
414
415
0
              if (eq[-1] == '/')
416
0
                {
417
0
                  g_critical ("G_RESOURCE_OVERLAYS segment '%s' has trailing '/' before '='.  Ignoring", part);
418
0
                  g_free (part);
419
0
                  continue;
420
0
                }
421
422
0
              if (!g_path_is_absolute (eq + 1))
423
0
                {
424
0
                  g_critical ("G_RESOURCE_OVERLAYS segment '%s' does not have an absolute path after '='.  Ignoring", part);
425
0
                  g_free (part);
426
0
                  continue;
427
0
                }
428
429
0
              g_message ("Adding GResources overlay '%s'", part);
430
0
              parts[j++] = part;
431
0
            }
432
433
0
          parts[j] = NULL;
434
435
0
          result = (const gchar **) parts;
436
0
        }
437
0
      else
438
0
        {
439
          /* We go out of the way to avoid malloc() in the normal case
440
           * where the environment variable is not set.
441
           */
442
0
          static const gchar *const empty_strv[0 + 1] = { 0 };
443
0
          result = empty_strv;
444
0
        }
445
446
0
      g_once_init_leave_pointer (&overlay_dirs, result);
447
0
    }
448
449
0
  for (size_t i = 0; overlay_dirs[i]; i++)
450
0
    {
451
0
      const gchar *src;
452
0
      size_t src_len;
453
0
      const gchar *dst;
454
0
      size_t dst_len;
455
0
      gchar *candidate;
456
457
0
      {
458
0
        const gchar *eq;
459
460
        /* split the overlay into src/dst */
461
0
        src = overlay_dirs[i];
462
0
        eq = strchr (src, '=');
463
0
        g_assert (eq); /* we checked this already */
464
0
        src_len = eq - src;
465
0
        dst = eq + 1;
466
        /* hold off on dst_len because we will probably fail the checks below */
467
0
      }
468
469
0
      if (i == 0)
470
0
        path_len = strlen (path);
471
472
      /* The entire path is too short to match the source */
473
0
      if (path_len < src_len)
474
0
        continue;
475
476
      /* It doesn't match the source */
477
0
      if (memcmp (path, src, src_len) != 0)
478
0
        continue;
479
480
      /* The prefix matches, but it's not a complete path component */
481
0
      if (path[src_len] && path[src_len] != '/')
482
0
        continue;
483
484
      /* OK.  Now we need this. */
485
0
      dst_len = strlen (dst);
486
487
      /* The candidate will be composed of:
488
       *
489
       *    dst + remaining_path + nul
490
       */
491
0
      if (path_len - src_len > SIZE_MAX - 1 ||
492
0
          dst_len > SIZE_MAX - 1 - (path_len - src_len))
493
0
        continue;
494
495
0
      candidate = g_malloc (dst_len + (path_len - src_len) + 1);
496
0
      memcpy (candidate, dst, dst_len);
497
0
      memcpy (candidate + dst_len, path + src_len, path_len - src_len);
498
0
      candidate[dst_len + (path_len - src_len)] = '\0';
499
500
      /* No matter what, 'r' is what we need, including the case where
501
       * we are trying to enumerate a directory.
502
       */
503
0
      res = (* check) (candidate, user_data);
504
0
      g_free (candidate);
505
506
0
      if (res)
507
0
        break;
508
0
    }
509
510
0
  return res;
511
0
}
512
513
/**
514
 * g_resource_error_quark:
515
 *
516
 * Gets the [struct@Gio.Resource] Error Quark.
517
 *
518
 * Returns: a [type@GLib.Quark]
519
 *
520
 * Since: 2.32
521
 */
522
G_DEFINE_QUARK (g-resource-error-quark, g_resource_error)
523
524
/**
525
 * g_resource_ref:
526
 * @resource: A [struct@Gio.Resource]
527
 *
528
 * Atomically increments the reference count of @resource by one.
529
 *
530
 * This function is threadsafe and may be called from any thread.
531
 *
532
 * Returns: The passed in [struct@Gio.Resource]
533
 *
534
 * Since: 2.32
535
 **/
536
GResource *
537
g_resource_ref (GResource *resource)
538
0
{
539
0
  g_atomic_int_inc (&resource->ref_count);
540
0
  return resource;
541
0
}
542
543
/**
544
 * g_resource_unref:
545
 * @resource: A [struct@Gio.Resource]
546
 *
547
 * Atomically decrements the reference count of @resource by one.
548
 *
549
 * If the reference count drops to 0, all memory allocated by the resource is
550
 * released. This function is threadsafe and may be called from any
551
 * thread.
552
 *
553
 * Since: 2.32
554
 **/
555
void
556
g_resource_unref (GResource *resource)
557
0
{
558
0
  if (g_atomic_int_dec_and_test (&resource->ref_count))
559
0
    {
560
0
      gvdb_table_free (resource->table);
561
0
      g_free (resource);
562
0
    }
563
0
}
564
565
/*< internal >
566
 * g_resource_new_from_table:
567
 * @table: (transfer full): a GvdbTable
568
 *
569
 * Returns: (transfer full): a new #GResource for @table
570
 */
571
static GResource *
572
g_resource_new_from_table (GvdbTable *table)
573
0
{
574
0
  GResource *resource;
575
576
0
  resource = g_new (GResource, 1);
577
0
  resource->ref_count = 1;
578
0
  resource->table = table;
579
580
0
  return resource;
581
0
}
582
583
static void
584
g_resource_error_from_gvdb_table_error (GError **g_resource_error,
585
                                        GError  *gvdb_table_error  /* (transfer full) */)
586
0
{
587
0
  if (g_error_matches (gvdb_table_error, G_FILE_ERROR, G_FILE_ERROR_INVAL))
588
0
    g_set_error_literal (g_resource_error,
589
0
                         G_RESOURCE_ERROR, G_RESOURCE_ERROR_INTERNAL,
590
0
                         gvdb_table_error->message);
591
0
  else
592
0
    g_propagate_error (g_resource_error, g_steal_pointer (&gvdb_table_error));
593
0
  g_clear_error (&gvdb_table_error);
594
0
}
595
596
/**
597
 * g_resource_new_from_data:
598
 * @data: A [struct@GLib.Bytes]
599
 * @error: return location for a [type@GLib.Error], or `NULL`
600
 *
601
 * Creates a [struct@Gio.Resource] from a reference to the binary resource bundle.
602
 *
603
 * This will keep a reference to @data while the resource lives, so
604
 * the data should not be modified or freed.
605
 *
606
 * If you want to use this resource in the global resource namespace you need
607
 * to register it with [func@Gio.resources_register].
608
 *
609
 * Note: @data must be backed by memory that is at least pointer aligned.
610
 * Otherwise this function will internally create a copy of the memory since
611
 * GLib 2.56, or in older versions fail and exit the process.
612
 *
613
 * If @data is empty or corrupt, %G_RESOURCE_ERROR_INTERNAL will be returned.
614
 *
615
 * Returns: (transfer full): a new [struct@Gio.Resource], or `NULL` on error
616
 *
617
 * Since: 2.32
618
 **/
619
GResource *
620
g_resource_new_from_data (GBytes  *data,
621
                          GError **error)
622
0
{
623
0
  GvdbTable *table;
624
0
  gboolean unref_data = FALSE;
625
0
  GError *local_error = NULL;
626
627
0
  if (((guintptr) g_bytes_get_data (data, NULL)) % sizeof (gpointer) != 0)
628
0
    {
629
0
      data = g_bytes_new (g_bytes_get_data (data, NULL),
630
0
                          g_bytes_get_size (data));
631
0
      unref_data = TRUE;
632
0
    }
633
634
0
  table = gvdb_table_new_from_bytes (data, TRUE, &local_error);
635
636
0
  if (unref_data)
637
0
    g_bytes_unref (data);
638
639
0
  if (table == NULL)
640
0
    {
641
0
      g_resource_error_from_gvdb_table_error (error, g_steal_pointer (&local_error));
642
0
      return NULL;
643
0
    }
644
645
0
  return g_resource_new_from_table (table);
646
0
}
647
648
/**
649
 * g_resource_load:
650
 * @filename: (type filename): the path of a filename to load, in the GLib filename encoding
651
 * @error: return location for a [type@GLib.Error], or `NULL`
652
 *
653
 * Loads a binary resource bundle and creates a [struct@Gio.Resource]
654
 * representation of it, allowing you to query it for data.
655
 *
656
 * If you want to use this resource in the global resource namespace you need
657
 * to register it with [func@Gio.resources_register].
658
 *
659
 * If @filename is empty or the data in it is corrupt,
660
 * %G_RESOURCE_ERROR_INTERNAL will be returned. If @filename doesn’t exist, or
661
 * there is an error in reading it, an error from [ctor@GLib.MappedFile.new]
662
 * will be returned.
663
 *
664
 * Returns: (transfer full): a new [struct@Gio.Resource], or `NULL` on error
665
 *
666
 * Since: 2.32
667
 **/
668
GResource *
669
g_resource_load (const gchar  *filename,
670
                 GError      **error)
671
0
{
672
0
  GvdbTable *table;
673
0
  GError *local_error = NULL;
674
675
0
  table = gvdb_table_new (filename, FALSE, &local_error);
676
0
  if (table == NULL)
677
0
    {
678
0
      g_resource_error_from_gvdb_table_error (error, g_steal_pointer (&local_error));
679
0
      return NULL;
680
0
    }
681
682
0
  return g_resource_new_from_table (table);
683
0
}
684
685
static void
686
set_error_not_found (GError     **error,
687
                     const char  *path)
688
0
{
689
  /* Avoid looking up the translation if it’s not going to be used. This is a hot path. */
690
0
  if (error != NULL)
691
0
    g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
692
0
                 _("The resource at “%s” does not exist"),
693
0
                 path);
694
0
}
695
696
/* The only error this can return is %G_RESOURCE_ERROR_NOT_FOUND. */
697
static gboolean
698
do_lookup (GResource             *resource,
699
           const gchar           *path,
700
           GResourceLookupFlags   lookup_flags,
701
           gsize                 *size,
702
           guint32               *flags,
703
           const void           **data,
704
           gsize                 *data_size,
705
           GError               **error)
706
0
{
707
0
  char *free_path = NULL;
708
0
  gsize path_len;
709
0
  gboolean res = FALSE;
710
0
  GVariant *value;
711
712
  /* Drop any trailing slash. */
713
0
  path_len = strlen (path);
714
0
  if (path_len >= 1 && path[path_len-1] == '/')
715
0
    {
716
0
      path = free_path = g_strdup (path);
717
0
      free_path[path_len-1] = 0;
718
0
    }
719
720
0
  value = gvdb_table_get_raw_value (resource->table, path);
721
722
0
  if (value == NULL)
723
0
    {
724
0
      set_error_not_found (error, path);
725
0
    }
726
0
  else
727
0
    {
728
0
      guint32 _size, _flags;
729
0
      GVariant *array;
730
731
0
      g_variant_get (value, "(uu@ay)",
732
0
                     &_size,
733
0
                     &_flags,
734
0
                     &array);
735
736
0
      _size = GUINT32_FROM_LE (_size);
737
0
      _flags = GUINT32_FROM_LE (_flags);
738
739
0
      if (size)
740
0
        *size = _size;
741
0
      if (flags)
742
0
        *flags = _flags;
743
0
      if (data)
744
0
        *data = g_variant_get_data (array);
745
0
      if (data_size)
746
0
        {
747
0
          static const char *no_data = "";
748
0
          size_t array_size = g_variant_get_size (array);
749
750
          /* Don't report trailing nul that non-compressed files have */
751
0
          if (_flags & G_RESOURCE_FLAGS_COMPRESSED)
752
0
            *data_size = array_size;
753
0
          else if (array_size > 0)
754
0
            *data_size = array_size - 1;
755
0
          else
756
0
            {
757
0
              *data = no_data;
758
0
              *data_size = 0;
759
0
            }
760
0
        }
761
0
      g_variant_unref (array);
762
0
      g_variant_unref (value);
763
764
0
      res = TRUE;
765
0
    }
766
767
0
  g_free (free_path);
768
0
  return res;
769
0
}
770
771
/**
772
 * g_resource_open_stream:
773
 * @resource: A [struct@Gio.Resource]
774
 * @path: A path name inside the resource
775
 * @lookup_flags: A [flags@Gio.ResourceLookupFlags]
776
 * @error: return location for a [type@GLib.Error], or `NULL`
777
 *
778
 * Looks for a file at the specified @path in the resource and
779
 * returns a [class@Gio.InputStream] that lets you read the data.
780
 *
781
 * @lookup_flags controls the behaviour of the lookup.
782
 *
783
 * The only error this can return is %G_RESOURCE_ERROR_NOT_FOUND, if @path was
784
 * not found in @resource.
785
 *
786
 * Returns: (transfer full): [class@Gio.InputStream] or `NULL` on error
787
 *
788
 * Since: 2.32
789
 **/
790
GInputStream *
791
g_resource_open_stream (GResource             *resource,
792
                        const gchar           *path,
793
                        GResourceLookupFlags   lookup_flags,
794
                        GError               **error)
795
0
{
796
0
  const void *data;
797
0
  gsize data_size;
798
0
  guint32 flags;
799
0
  GInputStream *stream, *stream2;
800
801
0
  if (!do_lookup (resource, path, lookup_flags, NULL, &flags, &data, &data_size, error))
802
0
    return NULL;
803
804
0
  stream = g_memory_input_stream_new_from_data (data, data_size, NULL);
805
0
  g_object_set_data_full (G_OBJECT (stream), "g-resource",
806
0
                          g_resource_ref (resource),
807
0
                          (GDestroyNotify)g_resource_unref);
808
809
0
  if (flags & G_RESOURCE_FLAGS_COMPRESSED)
810
0
    {
811
0
      GZlibDecompressor *decompressor =
812
0
        g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB);
813
814
0
      stream2 = g_converter_input_stream_new (stream, G_CONVERTER (decompressor));
815
0
      g_object_unref (decompressor);
816
0
      g_object_unref (stream);
817
0
      stream = stream2;
818
0
    }
819
820
0
  return stream;
821
0
}
822
823
static GBytes *resource_to_bytes (GResource   *resource,
824
                                  const char  *path,
825
                                  size_t       size,
826
                                  const void  *data,
827
                                  size_t       data_size,
828
                                  guint32      flags,
829
                                  GError     **error);
830
831
/**
832
 * g_resource_lookup_data:
833
 * @resource: A [struct@Gio.Resource]
834
 * @path: A path name inside the resource
835
 * @lookup_flags: A [flags@Gio.ResourceLookupFlags]
836
 * @error: return location for a [type@GLib.Error], or `NULL`
837
 *
838
 * Looks for a file at the specified @path in the resource and
839
 * returns a [struct@GLib.Bytes] that lets you directly access the data in
840
 * memory.
841
 *
842
 * The data is always followed by a zero byte, so you
843
 * can safely use the data as a C string. However, that byte
844
 * is not included in the size of the [struct@GLib.Bytes].
845
 *
846
 * For uncompressed resource files this is a pointer directly into
847
 * the resource bundle, which is typically in some read-only data section
848
 * in the program binary. For compressed files, memory is allocated on
849
 * the heap and the data is automatically uncompressed.
850
 *
851
 * @lookup_flags controls the behaviour of the lookup.
852
 *
853
 * This can return error %G_RESOURCE_ERROR_NOT_FOUND if @path was not found in
854
 * @resource, or %G_RESOURCE_ERROR_INTERNAL if decompression of a compressed
855
 * resource failed.
856
 *
857
 * Returns: (transfer full): [struct@GLib.Bytes] or `NULL` on error
858
 *
859
 * Since: 2.32
860
 **/
861
GBytes *
862
g_resource_lookup_data (GResource             *resource,
863
                        const gchar           *path,
864
                        GResourceLookupFlags   lookup_flags,
865
                        GError               **error)
866
0
{
867
0
  const void *data;
868
0
  guint32 flags;
869
0
  gsize data_size;
870
0
  gsize size;
871
872
0
  if (!do_lookup (resource, path, lookup_flags, &size, &flags, &data, &data_size, error))
873
0
    return NULL;
874
875
0
  return resource_to_bytes (resource, path, size, data, data_size, flags, error);
876
0
}
877
878
static GBytes *
879
resource_to_bytes (GResource   *resource,
880
                   const char  *path,
881
                   size_t       size,
882
                   const void  *data,
883
                   size_t       data_size,
884
                   guint32      flags,
885
                   GError     **error)
886
0
{
887
0
  if (size == 0)
888
0
    return g_bytes_new_with_free_func ("", 0, (GDestroyNotify) g_resource_unref, g_resource_ref (resource));
889
0
  else if (flags & G_RESOURCE_FLAGS_COMPRESSED)
890
0
    {
891
0
      char *uncompressed, *d;
892
0
      const char *s;
893
0
      GConverterResult res;
894
0
      gsize d_size, s_size;
895
0
      gsize bytes_read, bytes_written;
896
897
898
0
      GZlibDecompressor *decompressor =
899
0
        g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB);
900
901
0
      uncompressed = g_malloc (size + 1);
902
903
0
      s = data;
904
0
      s_size = data_size;
905
0
      d = uncompressed;
906
0
      d_size = size;
907
908
0
      do
909
0
        {
910
0
          res = g_converter_convert (G_CONVERTER (decompressor),
911
0
                                     s, s_size,
912
0
                                     d, d_size,
913
0
                                     G_CONVERTER_INPUT_AT_END,
914
0
                                     &bytes_read,
915
0
                                     &bytes_written,
916
0
                                     NULL);
917
0
          if (res == G_CONVERTER_ERROR)
918
0
            {
919
0
              g_free (uncompressed);
920
0
              g_object_unref (decompressor);
921
922
0
              g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_INTERNAL,
923
0
                           _("The resource at “%s” failed to decompress"),
924
0
                           path);
925
0
              return NULL;
926
927
0
            }
928
0
          s += bytes_read;
929
0
          s_size -= bytes_read;
930
0
          d += bytes_written;
931
0
          d_size -= bytes_written;
932
0
        }
933
0
      while (res != G_CONVERTER_FINISHED);
934
935
0
      uncompressed[size] = 0; /* Zero terminate */
936
937
0
      g_object_unref (decompressor);
938
939
0
      return g_bytes_new_take (uncompressed, size);
940
0
    }
941
0
  else
942
0
    return g_bytes_new_with_free_func (data, data_size, (GDestroyNotify)g_resource_unref, g_resource_ref (resource));
943
0
}
944
945
/**
946
 * g_resource_get_info:
947
 * @resource: A [struct@Gio.Resource]
948
 * @path: A path name inside the resource
949
 * @lookup_flags: A [flags@Gio.ResourceLookupFlags]
950
 * @size:  (out) (optional): a location to place the length of the contents of the file,
951
 *    or `NULL` if the length is not needed
952
 * @flags:  (out) (optional): a location to place the flags about the file,
953
 *    or `NULL` if the length is not needed
954
 * @error: return location for a [type@GLib.Error], or `NULL`
955
 *
956
 * Looks for a file at the specified @path in the resource and
957
 * if found returns information about it.
958
 *
959
 * @lookup_flags controls the behaviour of the lookup.
960
 *
961
 * The only error this can return is %G_RESOURCE_ERROR_NOT_FOUND, if @path was
962
 * not found in @resource.
963
 *
964
 * Returns: `TRUE` if the file was found, `FALSE` if there were errors
965
 *
966
 * Since: 2.32
967
 **/
968
gboolean
969
g_resource_get_info (GResource             *resource,
970
                     const gchar           *path,
971
                     GResourceLookupFlags   lookup_flags,
972
                     gsize                 *size,
973
                     guint32               *flags,
974
                     GError               **error)
975
0
{
976
0
  return do_lookup (resource, path, lookup_flags, size, flags, NULL, NULL, error);
977
0
}
978
979
static inline const char *
980
ensure_slash_suffix (const char  *path,
981
                     char        *local_str,
982
                     gsize        len,
983
                     char       **free_path)
984
0
{
985
0
  gsize path_len;
986
987
0
  path_len = strlen (path);
988
989
0
  if G_UNLIKELY (path[path_len-1] != '/')
990
0
    {
991
0
      if (path_len < len - 2)
992
0
        {
993
          /*
994
           * We got a path that does not have a trailing /. It is not the
995
           * ideal use of this API as we require trailing / for our lookup
996
           * into gvdb. Some degenerate application configurations can hit
997
           * this code path quite a bit, so we try to avoid using the
998
           * g_strconcat()/g_free().
999
           */
1000
0
          memcpy (local_str, path, path_len);
1001
0
          local_str[path_len] = '/';
1002
0
          local_str[path_len+1] = 0;
1003
0
          return local_str;
1004
0
        }
1005
0
      else
1006
0
        {
1007
0
          *free_path = g_strconcat (path, "/", NULL);
1008
0
          return *free_path;
1009
0
        }
1010
0
    }
1011
0
  else
1012
0
    {
1013
0
      return path;
1014
0
    }
1015
0
}
1016
1017
/**
1018
 * g_resource_enumerate_children:
1019
 * @resource: A [struct@Gio.Resource]
1020
 * @path: A path name inside the resource
1021
 * @lookup_flags: A [flags@Gio.ResourceLookupFlags]
1022
 * @error: return location for a [type@GLib.Error], or `NULL`
1023
 *
1024
 * Returns all the names of children at the specified @path in the resource.
1025
 *
1026
 * The return result is a `NULL` terminated list of strings which should
1027
 * be released with [func@GLib.strfreev].
1028
 *
1029
 * If @path is invalid or does not exist in the [struct@Gio.Resource],
1030
 * %G_RESOURCE_ERROR_NOT_FOUND will be returned.
1031
 *
1032
 * @lookup_flags controls the behaviour of the lookup.
1033
 *
1034
 * Returns: (array zero-terminated=1) (transfer full): an array of constant strings
1035
 *
1036
 * Since: 2.32
1037
 **/
1038
gchar **
1039
g_resource_enumerate_children (GResource             *resource,
1040
                               const gchar           *path,
1041
                               GResourceLookupFlags   lookup_flags,
1042
                               GError               **error)
1043
0
{
1044
  /* Size of 256 is arbitrarily chosen based on being large enough
1045
   * for pretty much everything we come across, but not cumbersome
1046
   * on the stack. It also matches common cacheline sizes.
1047
   */
1048
0
  gchar local_str[256];
1049
0
  const char *path_with_slash;
1050
0
  char *free_path = NULL;
1051
0
  gchar **children;
1052
1053
0
  if (*path == 0)
1054
0
    {
1055
0
      set_error_not_found (error, path);
1056
0
      return NULL;
1057
0
    }
1058
1059
0
  path_with_slash = ensure_slash_suffix (path, local_str, sizeof (local_str), &free_path);
1060
1061
0
  children = gvdb_table_list (resource->table, path_with_slash);
1062
1063
0
  g_free (free_path);
1064
1065
0
  if (children == NULL)
1066
0
    {
1067
0
      set_error_not_found (error, path);
1068
0
      return NULL;
1069
0
    }
1070
1071
0
  return children;
1072
0
}
1073
1074
/**
1075
 * g_resource_has_children:
1076
 * @resource: A #GResource
1077
 * @path: A pathname inside the resource
1078
 *
1079
 * Returns whether the specified @path in the resource
1080
 * has children.
1081
 *
1082
 * Returns: %TRUE if @path has children
1083
 *
1084
 * Since: 2.84
1085
 */
1086
gboolean
1087
g_resource_has_children (GResource  *resource,
1088
                         const char *path)
1089
0
{
1090
  /* Size of 256 is arbitrarily chosen based on being large enough
1091
   * for pretty much everything we come across, but not cumbersome
1092
   * on the stack. It also matches common cacheline sizes.
1093
   */
1094
0
  char local_str[256];
1095
0
  const char *path_with_slash;
1096
0
  guint n;
1097
0
  char *freeme = NULL;
1098
1099
0
  if (*path == 0)
1100
0
    return FALSE;
1101
1102
0
  path_with_slash = ensure_slash_suffix (path, local_str, sizeof (local_str), &freeme);
1103
1104
0
  n = gvdb_table_n_children (resource->table, path_with_slash);
1105
1106
0
  g_free (freeme);
1107
1108
0
  return n > 0;
1109
0
}
1110
1111
static GRWLock resources_lock;
1112
static GList *registered_resources;
1113
1114
/* This is updated atomically, so we can append to it and check for NULL outside the
1115
   lock, but all other accesses are done under the write lock */
1116
static GStaticResource *lazy_register_resources;
1117
1118
static void
1119
g_resources_register_unlocked (GResource *resource)
1120
0
{
1121
0
  registered_resources = g_list_prepend (registered_resources, g_resource_ref (resource));
1122
0
}
1123
1124
static void
1125
g_resources_unregister_unlocked (GResource *resource)
1126
0
{
1127
0
  GList *resource_link = g_list_find (registered_resources, resource);
1128
1129
0
  if (resource_link == NULL)
1130
0
    {
1131
0
      g_warning ("Tried to remove not registered resource");
1132
0
    }
1133
0
  else
1134
0
    {
1135
0
      g_resource_unref (resource_link->data);
1136
0
      registered_resources = g_list_delete_link (registered_resources, resource_link);
1137
0
    }
1138
0
}
1139
1140
/**
1141
 * g_resources_register:
1142
 * @resource: A [struct@Gio.Resource]
1143
 *
1144
 * Registers the resource with the process-global set of resources.
1145
 *
1146
 * Once a resource is registered the files in it can be accessed
1147
 * with the global resource lookup functions like
1148
 * [func@Gio.resources_lookup_data].
1149
 *
1150
 * Since: 2.32
1151
 **/
1152
void
1153
g_resources_register (GResource *resource)
1154
0
{
1155
0
  g_rw_lock_writer_lock (&resources_lock);
1156
0
  g_resources_register_unlocked (resource);
1157
0
  g_rw_lock_writer_unlock (&resources_lock);
1158
0
}
1159
1160
/**
1161
 * g_resources_unregister:
1162
 * @resource: A [struct@Gio.Resource]
1163
 *
1164
 * Unregisters the resource from the process-global set of resources.
1165
 *
1166
 * Since: 2.32
1167
 **/
1168
void
1169
g_resources_unregister (GResource *resource)
1170
0
{
1171
0
  g_rw_lock_writer_lock (&resources_lock);
1172
0
  g_resources_unregister_unlocked (resource);
1173
0
  g_rw_lock_writer_unlock (&resources_lock);
1174
0
}
1175
1176
/**
1177
 * g_resources_open_stream:
1178
 * @path: A path name inside the resource
1179
 * @lookup_flags: A [flags@Gio.ResourceLookupFlags]
1180
 * @error: return location for a [type@GLib.Error], or `NULL`
1181
 *
1182
 * Looks for a file at the specified @path in the set of
1183
 * globally registered resources and returns a [class@Gio.InputStream]
1184
 * that lets you read the data.
1185
 *
1186
 * @lookup_flags controls the behaviour of the lookup.
1187
 *
1188
 * Returns: (transfer full): [class@Gio.InputStream] or `NULL` on error
1189
 *
1190
 * Since: 2.32
1191
 **/
1192
GInputStream *
1193
g_resources_open_stream (const gchar           *path,
1194
                         GResourceLookupFlags   lookup_flags,
1195
                         GError               **error)
1196
0
{
1197
0
  GInputStream *res = NULL;
1198
0
  GList *l;
1199
0
  GInputStream *stream;
1200
1201
0
  if (g_resource_find_overlay (path, open_overlay_stream, &res))
1202
0
    return res;
1203
1204
0
  register_lazy_static_resources ();
1205
1206
0
  g_rw_lock_reader_lock (&resources_lock);
1207
1208
0
  for (l = registered_resources; l != NULL; l = l->next)
1209
0
    {
1210
0
      GResource *r = l->data;
1211
1212
0
      stream = g_resource_open_stream (r, path, lookup_flags, NULL);
1213
0
      if (stream == NULL)
1214
0
        {
1215
          /* g_resource_open_stream() guarantees it only fails with
1216
           * %G_RESOURCE_ERROR_NOT_FOUND */
1217
0
        }
1218
0
      else
1219
0
        {
1220
0
          res = stream;
1221
0
          break;
1222
0
        }
1223
0
    }
1224
1225
0
  if (l == NULL)
1226
0
    set_error_not_found (error, path);
1227
1228
0
  g_rw_lock_reader_unlock (&resources_lock);
1229
1230
0
  return res;
1231
0
}
1232
1233
/**
1234
 * g_resources_lookup_data:
1235
 * @path: A path name inside the resource
1236
 * @lookup_flags: A [flags@Gio.ResourceLookupFlags]
1237
 * @error: return location for a [type@GLib.Error], or `NULL`
1238
 *
1239
 * Looks for a file at the specified @path in the set of
1240
 * globally registered resources and returns a [struct@GLib.Bytes] that
1241
 * lets you directly access the data in memory.
1242
 *
1243
 * The data is always followed by a zero byte, so you
1244
 * can safely use the data as a C string. However, that byte
1245
 * is not included in the size of the [struct@GLib.Bytes].
1246
 *
1247
 * For uncompressed resource files this is a pointer directly into
1248
 * the resource bundle, which is typically in some read-only data section
1249
 * in the program binary. For compressed files we allocate memory on
1250
 * the heap and automatically uncompress the data.
1251
 *
1252
 * @lookup_flags controls the behaviour of the lookup.
1253
 *
1254
 * Returns: (transfer full): [struct@GLib.Bytes] or `NULL` on error
1255
 *
1256
 * Since: 2.32
1257
 **/
1258
GBytes *
1259
g_resources_lookup_data (const gchar           *path,
1260
                         GResourceLookupFlags   lookup_flags,
1261
                         GError               **error)
1262
0
{
1263
0
  GBytes *res = NULL;
1264
0
  GList *l;
1265
1266
0
  if (g_resource_find_overlay (path, get_overlay_bytes, &res))
1267
0
    return res;
1268
1269
0
  register_lazy_static_resources ();
1270
1271
0
  g_rw_lock_reader_lock (&resources_lock);
1272
1273
0
  for (l = registered_resources; l != NULL; l = l->next)
1274
0
    {
1275
0
      GResource *r = l->data;
1276
0
      const void *data;
1277
0
      guint32 flags;
1278
0
      gsize data_size;
1279
0
      gsize size;
1280
1281
      /* This is essentially g_resource_lookup_data(), but split up so we can
1282
       * avoid allocating a #GError if the resource is not found. */
1283
0
      if (do_lookup (r, path, lookup_flags, &size, &flags, &data, &data_size, NULL))
1284
0
        {
1285
0
          res = resource_to_bytes (r, path, size, data, data_size, flags, error);
1286
0
          break;
1287
0
        }
1288
0
    }
1289
1290
0
  if (l == NULL)
1291
0
    set_error_not_found (error, path);
1292
1293
0
  g_rw_lock_reader_unlock (&resources_lock);
1294
1295
0
  return res;
1296
0
}
1297
1298
/**
1299
 * g_resources_enumerate_children:
1300
 * @path: A path name inside the resource
1301
 * @lookup_flags: A [flags@Gio.ResourceLookupFlags]
1302
 * @error: return location for a [type@GLib.Error], or `NULL`
1303
 *
1304
 * Returns all the names of children at the specified @path in the set of
1305
 * globally registered resources.
1306
 *
1307
 * The return result is a `NULL` terminated list of strings which should
1308
 * be released with [func@GLib.strfreev].
1309
 *
1310
 * @lookup_flags controls the behaviour of the lookup.
1311
 *
1312
 * Returns: (array zero-terminated=1) (transfer full): an array of constant strings
1313
 *
1314
 * Since: 2.32
1315
 **/
1316
gchar **
1317
g_resources_enumerate_children (const gchar           *path,
1318
                                GResourceLookupFlags   lookup_flags,
1319
                                GError               **error)
1320
0
{
1321
0
  GHashTable *hash = NULL;
1322
0
  GList *l;
1323
0
  char **children;
1324
0
  int i;
1325
1326
  /* This will enumerate actual files found in overlay directories but
1327
   * will not enumerate the overlays themselves.  For example, if we
1328
   * have an overlay "/org/gtk=/path/to/files" and we enumerate "/org"
1329
   * then we will not see "gtk" in the result set unless it is provided
1330
   * by another resource file.
1331
   *
1332
   * This is probably not going to be a problem since if we are doing
1333
   * such an overlay, we probably will already have that path.
1334
   */
1335
0
  g_resource_find_overlay (path, enumerate_overlay_dir, &hash);
1336
1337
0
  register_lazy_static_resources ();
1338
1339
0
  g_rw_lock_reader_lock (&resources_lock);
1340
1341
0
  for (l = registered_resources; l != NULL; l = l->next)
1342
0
    {
1343
0
      GResource *r = l->data;
1344
1345
0
      children = g_resource_enumerate_children (r, path, 0, NULL);
1346
1347
0
      if (children != NULL)
1348
0
        {
1349
0
          if (hash == NULL)
1350
            /* note: keep in sync with same line above */
1351
0
            hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1352
1353
0
          for (i = 0; children[i] != NULL; i++)
1354
0
            g_hash_table_add (hash, children[i]);
1355
0
          g_free (children);
1356
0
        }
1357
0
    }
1358
1359
0
  g_rw_lock_reader_unlock (&resources_lock);
1360
1361
0
  if (hash == NULL)
1362
0
    {
1363
0
      set_error_not_found (error, path);
1364
0
      return NULL;
1365
0
    }
1366
0
  else
1367
0
    {
1368
0
      children = (gchar **) g_hash_table_get_keys_as_array (hash, NULL);
1369
0
      g_hash_table_steal_all (hash);
1370
0
      g_hash_table_destroy (hash);
1371
1372
0
      return children;
1373
0
    }
1374
0
}
1375
1376
/**
1377
 * g_resources_has_children:
1378
 * @path: A pathname
1379
 *
1380
 * Returns whether the specified @path in the set of
1381
 * globally registered resources has children.
1382
 *
1383
 * Returns: %TRUE if @patch has children
1384
 *
1385
 * Since: 2.84
1386
 */
1387
gboolean
1388
g_resources_has_children (const char *path)
1389
0
{
1390
0
  register_lazy_static_resources ();
1391
1392
0
  g_rw_lock_reader_lock (&resources_lock);
1393
1394
0
  for (GList *l = registered_resources; l != NULL; l = l->next)
1395
0
    {
1396
0
      GResource *r = l->data;
1397
1398
0
      if (g_resource_has_children (r, path))
1399
0
        {
1400
0
          g_rw_lock_reader_unlock (&resources_lock);
1401
0
          return TRUE;
1402
0
        }
1403
0
    }
1404
1405
0
  g_rw_lock_reader_unlock (&resources_lock);
1406
0
  return FALSE;
1407
0
}
1408
1409
/**
1410
 * g_resources_get_info:
1411
 * @path: A path name inside the resource
1412
 * @lookup_flags: A [flags@Gio.ResourceLookupFlags]
1413
 * @size:  (out) (optional): a location to place the length of the contents of the file,
1414
 *    or `NULL` if the length is not needed
1415
 * @flags:  (out) (optional): a location to place the [flags@Gio.ResourceFlags] about the file,
1416
 *    or `NULL` if the flags are not needed
1417
 * @error: return location for a [type@GLib.Error], or `NULL`
1418
 *
1419
 * Looks for a file at the specified @path in the set of
1420
 * globally registered resources and if found returns information about it.
1421
 *
1422
 * @lookup_flags controls the behaviour of the lookup.
1423
 *
1424
 * Returns: `TRUE` if the file was found, `FALSE` if there were errors
1425
 *
1426
 * Since: 2.32
1427
 **/
1428
gboolean
1429
g_resources_get_info (const gchar           *path,
1430
                      GResourceLookupFlags   lookup_flags,
1431
                      gsize                 *size,
1432
                      guint32               *flags,
1433
                      GError               **error)
1434
0
{
1435
0
  gboolean res = FALSE;
1436
0
  GList *l;
1437
0
  InfoData info;
1438
1439
0
  if (g_resource_find_overlay (path, get_overlay_info, &info))
1440
0
    {
1441
0
      if (size)
1442
0
        *size = info.size;
1443
0
      if (flags)
1444
0
        *flags = info.flags;
1445
1446
0
      return TRUE;
1447
0
    }
1448
1449
0
  register_lazy_static_resources ();
1450
1451
0
  g_rw_lock_reader_lock (&resources_lock);
1452
1453
0
  for (l = registered_resources; l != NULL; l = l->next)
1454
0
    {
1455
0
      GResource *r = l->data;
1456
1457
0
      if (g_resource_get_info (r, path, lookup_flags, size, flags, NULL))
1458
0
        {
1459
0
          res = TRUE;
1460
0
          break;
1461
0
        }
1462
0
    }
1463
1464
0
  if (l == NULL)
1465
0
    set_error_not_found (error, path);
1466
1467
0
  g_rw_lock_reader_unlock (&resources_lock);
1468
1469
0
  return res;
1470
0
}
1471
1472
/* This code is to handle registration of resources very early, from a constructor.
1473
 * At that point we'd like to do minimal work, to avoid ordering issues. For instance,
1474
 * we're not allowed to use g_malloc, as the user need to be able to call g_mem_set_vtable
1475
 * before the first call to g_malloc.
1476
 *
1477
 * So, what we do at construction time is that we just register a static structure on
1478
 * a list of resources that need to be initialized, and then later, when doing any lookups
1479
 * in the global list of registered resources, or when getting a reference to the
1480
 * lazily initialized resource we lazily create and register all the GResources on
1481
 * the lazy list.
1482
 *
1483
 * To avoid having to use locks in the constructor, and having to grab the writer lock
1484
 * when checking the lazy registering list we update lazy_register_resources in
1485
 * a lock-less fashion (atomic prepend-only, atomic replace with NULL). However, all
1486
 * operations except:
1487
 *  * check if there are any resources to lazily initialize
1488
 *  * Add a static resource to the lazy init list
1489
 * Do use the full writer lock for protection.
1490
 */
1491
1492
static void
1493
register_lazy_static_resources_unlocked (void)
1494
0
{
1495
0
  GStaticResource *list = g_atomic_pointer_get (&lazy_register_resources);
1496
1497
0
  while (!g_atomic_pointer_compare_and_exchange_full (&lazy_register_resources, list, NULL, &list))
1498
0
    ;
1499
1500
0
  while (list != NULL)
1501
0
    {
1502
0
      GBytes *bytes = g_bytes_new_static (list->data, list->data_len);
1503
0
      GResource *resource = g_resource_new_from_data (bytes, NULL);
1504
0
      if (resource)
1505
0
        {
1506
0
          g_resources_register_unlocked (resource);
1507
0
          g_atomic_pointer_set (&list->resource, resource);
1508
0
        }
1509
0
      g_bytes_unref (bytes);
1510
1511
0
      list = list->next;
1512
0
    }
1513
0
}
1514
1515
static void
1516
register_lazy_static_resources (void)
1517
0
{
1518
0
  if (g_atomic_pointer_get (&lazy_register_resources) == NULL)
1519
0
    return;
1520
1521
0
  g_rw_lock_writer_lock (&resources_lock);
1522
0
  register_lazy_static_resources_unlocked ();
1523
0
  g_rw_lock_writer_unlock (&resources_lock);
1524
0
}
1525
1526
/**
1527
 * g_static_resource_init:
1528
 * @static_resource: pointer to a static [struct@Gio.StaticResource]
1529
 *
1530
 * Initializes a [struct@Gio.Resource] from static data using a
1531
 * [struct@Gio.StaticResource].
1532
 *
1533
 * This is normally used by code generated by
1534
 * [`glib-compile-resources`](glib-compile-resources.html)
1535
 * and is not typically used by other code.
1536
 *
1537
 * Since: 2.32
1538
 **/
1539
void
1540
g_static_resource_init (GStaticResource *static_resource)
1541
0
{
1542
0
  GStaticResource *next;
1543
1544
0
  g_return_if_fail (static_resource != NULL);
1545
0
  g_return_if_fail (static_resource->next == NULL);
1546
0
  g_return_if_fail (static_resource != g_atomic_pointer_get (&lazy_register_resources));
1547
1548
0
  do
1549
0
    {
1550
0
      next = g_atomic_pointer_get (&lazy_register_resources);
1551
0
      static_resource->next = next;
1552
0
    }
1553
0
  while (!g_atomic_pointer_compare_and_exchange (&lazy_register_resources, next, static_resource));
1554
0
}
1555
1556
/**
1557
 * g_static_resource_fini:
1558
 * @static_resource: pointer to a static [struct@Gio.StaticResource]
1559
 *
1560
 * Finalizes a [struct@Gio.Resource] initialized by
1561
 * [method@Gio.StaticResource.init].
1562
 *
1563
 * This is normally used by code generated by
1564
 * [`glib-compile-resources`](glib-compile-resources.html)
1565
 * and is not typically used by other code.
1566
 *
1567
 * Since: 2.32
1568
 **/
1569
void
1570
g_static_resource_fini (GStaticResource *static_resource)
1571
0
{
1572
0
  GResource *resource;
1573
1574
0
  g_rw_lock_writer_lock (&resources_lock);
1575
1576
0
  register_lazy_static_resources_unlocked ();
1577
1578
0
  resource = g_atomic_pointer_exchange (&static_resource->resource, NULL);
1579
0
  if (resource)
1580
0
    {
1581
      /* There should be at least two references to the resource now: one for
1582
       * static_resource->resource, and one in the registered_resources list. */
1583
0
      g_assert (g_atomic_int_get (&resource->ref_count) >= 2);
1584
1585
0
      g_resources_unregister_unlocked (resource);
1586
0
      g_resource_unref (resource);
1587
0
    }
1588
1589
0
  g_rw_lock_writer_unlock (&resources_lock);
1590
0
}
1591
1592
/**
1593
 * g_static_resource_get_resource:
1594
 * @static_resource: pointer to a static [struct@Gio.StaticResource]
1595
 *
1596
 * Gets the [struct@Gio.Resource] that was registered by a call to
1597
 * [method@Gio.StaticResource.init].
1598
 *
1599
 * This is normally used by code generated by
1600
 * [`glib-compile-resources`](glib-compile-resources.html)
1601
 * and is not typically used by other code.
1602
 *
1603
 * Returns:  (transfer none): a [struct@Gio.Resource]
1604
 *
1605
 * Since: 2.32
1606
 **/
1607
GResource *
1608
g_static_resource_get_resource (GStaticResource *static_resource)
1609
0
{
1610
0
  register_lazy_static_resources ();
1611
1612
0
  return g_atomic_pointer_get (&static_resource->resource);
1613
0
}