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