0e30ca762635a0c57e767470226201cdd67f5dea
[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 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, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Authors: Alexander Larsson <alexl@redhat.com>
21  */
22
23 #include "config.h"
24
25 #include <string.h>
26
27 #include "gresource.h"
28 #include <gvdb/gvdb-reader.h>
29 #include <gi18n.h>
30 #include <gio/gmemoryinputstream.h>
31 #include <gio/gzlibdecompressor.h>
32 #include <gio/gconverterinputstream.h>
33
34 struct _GResource
35 {
36   int ref_count;
37
38   GvdbTable *table;
39 };
40
41 static void register_lazy_static_resources ();
42
43 G_DEFINE_BOXED_TYPE (GResource, g_resource, g_resource_ref, g_resource_unref)
44
45 /**
46  * SECTION:gresource
47  * @short_description: Resource framework
48  * @include: gio/gio.h
49  *
50  * Applications and libraries often contain binary or textual data that is really part of the
51  * application, rather than user data. For instance #GtkBuilder .ui files, splashscreen images,
52  * GMenu markup xml, CSS files, icons, etc. These are often shipped as files in <filename>$datadir/appname</filename>, or
53  * manually included as literal strings in the code.
54  *
55  * The #GResource API and the <link linkend="glib-compile-resources">glib-compile-resources</link> program
56  * provide a convenient and efficient alternative to this which has some nice properties. You
57  * maintain the files as normal files, so its easy to edit them, but during the build the files
58  * are combined into a binary bundle that is linked into the executable. This means that loading
59  * the resource files are efficient (as they are already in memory, shared with other instances) and
60  * simple (no need to check for things like I/O errors or locate the files in the filesystem). It
61  * also makes it easier to create relocatable applications.
62  *
63  * Resource files can also be marked as compresses. Such files will be included in the resource bundle
64  * in a compressed form, but will be automatically uncompressed when the resource is used. This
65  * is very useful e.g. for larger text files that are parsed once (or rarely) and then thrown away.
66  *
67  * Resource files can also be marked to be preprocessed, by setting the value of the
68  * <literal>preprocess</literal> attribute to a comma-separated list of preprocessing options.
69  * The only options currently supported are:
70  *
71  * <literal>xml-stripblanks</literal> which will use <command>xmllint</command> to strip
72  * ignorable whitespace from the xml file. For this to work, the <envar>XMLLINT</envar>
73  * environment variable must be set to the full path to the xmllint executable, or xmllint
74  * must be in the PATH; otherwise the preprocessing step is skipped.
75  *
76  * <literal>to-pixdata</literal> which will use <command>gdk-pixbuf-pixdata</command> to convert
77  * images to the GdkPixdata format, which allows you to create pixbufs directly using the data inside
78  * the resource file, rather than an (uncompressed) copy if it. For this, the gdk-pixbuf-pixdata
79  * program must be in the PATH, or the <envar>GDK_PIXBUF_PIXDATA</envar> environment variable must be
80  * set to the full path to the gdk-pixbuf-pixdata executable; otherwise the resource compiler will
81  * abort.
82  *
83  * Resource bundles are created by the <link linkend="glib-compile-resources">glib-compile-resources</link> program
84  * which takes an xml file that describes the bundle, and a set of files that the xml references. These
85  * are combined into a binary resource bundle.
86  *
87  * <example id="resource-example"><title>Example resource description</title>
88  * <programlisting><![CDATA[
89  * <?xml version="1.0" encoding="UTF-8"?>
90  * <gresources>
91  *   <gresource prefix="/org/gtk/Example">
92  *     <file>data/splashscreen.png</file>
93  *     <file compressed="true">dialog.ui</file>
94  *     <file preprocess="xml-stripblanks">menumarkup.xml</file>
95  *   </gresource>
96  * </gresources>
97  * ]]></programlisting></example>
98  *
99  * This will create a resource bundle with the following files:
100  * <programlisting><![CDATA[
101  * /org/gtk/Example/data/splashscreen.png
102  * /org/gtk/Example/dialog.ui
103  * /org/gtk/Example/menumarkup.xml
104  * ]]></programlisting>
105  *
106  * Note that all resources in the process share the same namespace, so use java-style
107  * path prefixes (like in the above example) to avoid conflicts.
108  *
109  * You can then use <link linkend="glib-compile-resources">glib-compile-resources</link> to compile the xml to a
110  * binary bundle that you can load with g_resource_load(). However, its more common to use the --generate-source and
111  * --generate-header arguments to create a source file and header to link directly into your application.
112  *
113  * Once a #GResource has been created and registered all the data in it can be accessed globally in the process by
114  * using API calls like g_resources_open_stream() to stream the data or g_resources_lookup_data() to get a direct pointer
115  * to the data. You can also use uris like "resource:///org/gtk/Example/data/splashscreen.png" with #GFile to access
116  * the resource data.
117  *
118  * There are two forms of the generated source, the default version uses the compiler support for constructor
119  * and destructor functions (where availible) to automatically create and register the #GResource on startup
120  * or library load time. If you pass --manual-register two functions to register/unregister the resource is instead
121  * created. This requires an explicit initialization call in your application/library, but it works on all platforms,
122  * even on the minor ones where this is not availible. (Constructor support is availible for at least Win32, MacOS and Linux.)
123  *
124  * Note that resource data can point directly into the data segment of e.g. a library, so if you are unloading libraries
125  * during runtime you need to be very careful with keeping around pointers to data from a resource, as this goes away
126  * when the library is unloaded. However, in practice this is not generally a problem, since most resource accesses
127  * is for your own resources, and resource data is often used once, during parsing, and then released.
128  *
129  * Since: 2.32
130  */
131
132 /**
133  * g_resource_error_quark:
134  *
135  * Gets the #GResource Error Quark.
136  *
137  * Return value: a #GQuark.
138  *
139  * Since: 2.32
140  */
141 GQuark
142 g_resource_error_quark (void)
143 {
144   return g_quark_from_static_string ("g-resource-error-quark");
145 }
146
147 /**
148  * g_resource_ref:
149  * @resource: A #GResource.
150  *
151  * Atomically increments the reference count of @array by one. This
152  * function is MT-safe and may be called from any thread.
153  *
154  * Returns: The passed in #GResource.
155  *
156  * Since: 2.32
157  **/
158 GResource *
159 g_resource_ref (GResource *resource)
160 {
161   g_atomic_int_inc (&resource->ref_count);
162   return resource;
163 }
164
165 /**
166  * g_resource_unref:
167  * @resource: A #GResource.
168  *
169  * Atomically decrements the reference count of @resource by one. If the
170  * reference count drops to 0, all memory allocated by the array is
171  * released. This function is MT-safe and may be called from any
172  * thread.
173  *
174  * Since: 2.32
175  **/
176 void
177 g_resource_unref (GResource *resource)
178 {
179   if (g_atomic_int_dec_and_test (&resource->ref_count))
180     {
181       gvdb_table_unref (resource->table);
182       g_free (resource);
183     }
184 }
185
186 /*
187  * g_resource_new_from_table:
188  * @table: (transfer full): a GvdbTable
189  *
190  * Returns: (transfer full): a new #GResource for @table
191  */
192 static GResource *
193 g_resource_new_from_table (GvdbTable *table)
194 {
195   GResource *resource;
196
197   resource = g_new (GResource, 1);
198   resource->ref_count = 1;
199   resource->table = table;
200
201   return resource;
202 }
203
204 /**
205  * g_resource_new_from_data:
206  * @data: A #GBytes.
207  * @error: return location for a #GError, or %NULL.
208  *
209  * Creates a GResource from a reference to the binary resource bundle.
210  * This will keep a reference to @data while the resource lives, so
211  * the data should not be modified or freed.
212  *
213  * If you want to use this resource in the global resource namespace you need
214  * to register it with g_resources_register().
215  *
216  * Return value: (transfer full): a new #GResource, or %NULL on error.
217  *
218  * Since: 2.32
219  **/
220 GResource *
221 g_resource_new_from_data (GBytes *data,
222                           GError **error)
223 {
224   GvdbTable *table;
225
226   table = gvdb_table_new_from_data (g_bytes_get_data (data, NULL),
227                                     g_bytes_get_size (data),
228                                     TRUE,
229                                     g_bytes_ref (data),
230                                     (GvdbRefFunc)g_bytes_ref,
231                                     (GDestroyNotify)g_bytes_unref,
232                                     error);
233
234   if (table == NULL)
235     return NULL;
236
237   return g_resource_new_from_table (table);
238 }
239
240 /**
241  * g_resource_load:
242  * @filename: (type filename): the path of a filename to load, in the GLib filename encoding.
243  * @error: return location for a #GError, or %NULL.
244  *
245  * Loads a binary resource bundle and creates a #GResource representation of it, allowing
246  * you to query it for data.
247  *
248  * If you want to use this resource in the global resource namespace you need
249  * to register it with g_resources_register().
250  *
251  * Return value: (transfer full): a new #GResource, or %NULL on error.
252  *
253  * Since: 2.32
254  **/
255 GResource *
256 g_resource_load (const gchar *filename,
257                  GError **error)
258 {
259   GvdbTable *table;
260
261   table = gvdb_table_new (filename, FALSE, error);
262   if (table == NULL)
263     return NULL;
264
265   return g_resource_new_from_table (table);
266 }
267
268 static gboolean do_lookup (GResource *resource,
269                            const char *path,
270                            GResourceLookupFlags lookup_flags,
271                            gsize *size,
272                            guint32 *flags,
273                            const void **data,
274                            gsize *data_size,
275                            GError **error)
276 {
277   char *free_path = NULL;
278   gsize path_len;
279   gboolean res = FALSE;
280   GVariant *value;
281
282   path_len = strlen (path);
283   if (path[path_len-1] == '/')
284     {
285       path = free_path = g_strdup (path);
286       free_path[path_len-1] = 0;
287     }
288
289   value = gvdb_table_get_value (resource->table, path);
290
291   if (value == NULL)
292     {
293       g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
294                    _("The resource at '%s' does not exist"),
295                    path);
296     }
297   else
298     {
299       guint32 _size, _flags;
300       GVariant *array;
301
302       g_variant_get (value, "(uu@ay)",
303                      &_size,
304                      &_flags,
305                      &array);
306
307       if (size)
308         *size = _size;
309       if (flags)
310         *flags = _flags;
311       if (data)
312         *data = g_variant_get_data (array);
313       if (data_size)
314         {
315           /* Don't report trailing newline that non-compressed files has */
316           if (_flags & G_RESOURCE_FLAGS_COMPRESSED)
317             *data_size = g_variant_get_size (array);
318           else
319             *data_size = g_variant_get_size (array) - 1;
320         }
321       g_variant_unref (array);
322       g_variant_unref (value);
323
324       res = TRUE;
325     }
326
327   g_free (free_path);
328   return res;
329 }
330
331 /**
332  * g_resource_open_stream:
333  * @resource: A #GResource.
334  * @path: A pathname inside the resource.
335  * @lookup_flags: A #GResourceLookupFlags.
336  * @error: return location for a #GError, or %NULL.
337  *
338  * Looks for a file at the specified @path in the resource and
339  * returns a #GInputStream that lets you read the data.
340  *
341  * @lookup_flags controls the behaviour of the lookup.
342  *
343  * Returns: (transfer full): #GInputStream or %NULL on error.
344  *     Free the returned object with g_object_unref().
345  *
346  * Since: 2.32
347  **/
348 GInputStream *
349 g_resource_open_stream (GResource *resource,
350                         const char *path,
351                         GResourceLookupFlags lookup_flags,
352                         GError **error)
353 {
354   const void *data;
355   gsize data_size;
356   guint32 flags;
357   GInputStream *stream, *stream2;
358
359   if (!do_lookup (resource, path, lookup_flags, NULL, &flags, &data, &data_size, error))
360     return NULL;
361
362   stream = g_memory_input_stream_new_from_data (data, data_size, NULL);
363   g_object_set_data_full (G_OBJECT (stream), "g-resource",
364                           g_resource_ref (resource),
365                           (GDestroyNotify)g_resource_unref);
366
367   if (flags & G_RESOURCE_FLAGS_COMPRESSED)
368     {
369       GZlibDecompressor *decompressor =
370         g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB);
371
372       stream2 = g_converter_input_stream_new (stream, G_CONVERTER (decompressor));
373       g_object_unref (decompressor);
374       g_object_unref (stream);
375       stream = stream2;
376     }
377
378   return stream;
379 }
380
381 /**
382  * g_resource_lookup_data:
383  * @resource: A #GResource.
384  * @path: A pathname inside the resource.
385  * @lookup_flags: A #GResourceLookupFlags.
386  * @error: return location for a #GError, or %NULL.
387  *
388  * Looks for a file at the specified @path in the resource and
389  * returns a #GBytes that lets you directly access the data in
390  * memory.
391  *
392  * The data is always followed by a zero byte, so you
393  * can safely use the data as a C string. However, that byte
394  * is not included in the size of the GBytes.
395  *
396  * For uncompressed resource files this is a pointer directly into
397  * the resource bundle, which is typically in some readonly data section
398  * in the program binary. For compressed files we allocate memory on
399  * the heap and automatically uncompress the data.
400  *
401  * @lookup_flags controls the behaviour of the lookup.
402  *
403  * Returns: (transfer full): #GBytes or %NULL on error.
404  *     Free the returned object with g_bytes_unref().
405  *
406  * Since: 2.32
407  **/
408 GBytes *
409 g_resource_lookup_data (GResource *resource,
410                         const char *path,
411                         GResourceLookupFlags lookup_flags,
412                         GError **error)
413 {
414   const void *data;
415   guint32 flags;
416   gsize data_size;
417   gsize size;
418
419   if (!do_lookup (resource, path, lookup_flags, &size, &flags, &data, &data_size, error))
420     return NULL;
421
422   if (flags & G_RESOURCE_FLAGS_COMPRESSED)
423     {
424       char *uncompressed, *d;
425       const char *s;
426       GConverterResult res;
427       gsize d_size, s_size;
428       gsize bytes_read, bytes_written;
429
430
431       GZlibDecompressor *decompressor =
432         g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB);
433
434       uncompressed = g_malloc (size + 1);
435
436       s = data;
437       s_size = data_size;
438       d = uncompressed;
439       d_size = size;
440
441       do
442         {
443           res = g_converter_convert (G_CONVERTER (decompressor),
444                                      s, s_size,
445                                      d, d_size,
446                                      G_CONVERTER_INPUT_AT_END,
447                                      &bytes_read,
448                                      &bytes_written,
449                                      NULL);
450           if (res == G_CONVERTER_ERROR)
451             {
452               g_free (uncompressed);
453               g_object_unref (decompressor);
454
455               g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_INTERNAL,
456                            _("The resource at '%s' failed to decompress"),
457                            path);
458               return NULL;
459
460             }
461           s += bytes_read;
462           s_size -= bytes_read;
463           d += bytes_written;
464           d_size -= bytes_written;
465         }
466       while (res != G_CONVERTER_FINISHED);
467
468       uncompressed[size] = 0; /* Zero terminate */
469
470       g_object_unref (decompressor);
471
472       return g_bytes_new_take (uncompressed, size);
473     }
474   else
475     return g_bytes_new_with_free_func (data, data_size, (GDestroyNotify)g_resource_unref, g_resource_ref (resource));
476 }
477
478 /**
479  * g_resource_get_info:
480  * @resource: A #GResource.
481  * @path: A pathname inside the resource.
482  * @lookup_flags: A #GResourceLookupFlags.
483  * @size:  (out) (allow-none): a location to place the length of the contents of the file,
484  *    or %NULL if the length is not needed
485  * @flags:  (out) (allow-none): a location to place the flags about the file,
486  *    or %NULL if the length is not needed
487  * @error: return location for a #GError, or %NULL.
488  *
489  * Looks for a file at the specified @path in the resource and
490  * if found returns information about it.
491  *
492  * @lookup_flags controls the behaviour of the lookup.
493  *
494  * Returns: %TRUE if the file was found. %FALSE if there were errors.
495  *
496  * Since: 2.32
497  **/
498 gboolean
499 g_resource_get_info (GResource *resource,
500                      const char *path,
501                      GResourceLookupFlags lookup_flags,
502                      gsize *size,
503                      guint32 *flags,
504                      GError **error)
505 {
506   return do_lookup (resource, path, lookup_flags, size, flags, NULL, NULL, error);
507 }
508
509 /**
510  * g_resource_enumerate_children:
511  * @resource: A #GResource.
512  * @path: A pathname inside the resource.
513  * @lookup_flags: A #GResourceLookupFlags.
514  * @error: return location for a #GError, or %NULL.
515  *
516  * Returns all the names of children at the specified @path in the resource.
517  * The return result is a %NULL terminated list of strings which should
518  * be released with g_strfreev().
519  *
520  * @lookup_flags controls the behaviour of the lookup.
521  *
522  * Returns: (array zero-terminated=1) (transfer full): an array of constant strings
523  *
524  * Since: 2.32
525  **/
526 char **
527 g_resource_enumerate_children (GResource *resource,
528                                const char *path,
529                                GResourceLookupFlags lookup_flags,
530                                GError **error)
531 {
532   gchar **children;
533   gsize path_len;
534   char *path_with_slash;
535
536   if (*path == 0)
537     {
538       g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
539                    _("The resource at '%s' does not exist"),
540                    path);
541       return NULL;
542     }
543
544   path_len = strlen (path);
545   if (path[path_len-1] != '/')
546     path_with_slash = g_strconcat (path, "/", NULL);
547   else
548     path_with_slash = g_strdup (path);
549
550   children = gvdb_table_list (resource->table, path_with_slash);
551   g_free (path_with_slash);
552
553   if (children == NULL)
554     {
555       g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
556                    _("The resource at '%s' does not exist"),
557                    path);
558       return NULL;
559     }
560
561   return children;
562 }
563
564 static GRWLock resources_lock;
565 static GList *registered_resources;
566
567 /* This is updated atomically, so we can append to it and check for NULL outside the
568    lock, but all other accesses are done under the write lock */
569 static GStaticResource *lazy_register_resources;
570
571 static void
572 g_resources_register_unlocked (GResource *resource)
573 {
574   registered_resources = g_list_prepend (registered_resources,
575                                         g_resource_ref (resource));
576 }
577
578 static void
579 g_resources_unregister_unlocked (GResource *resource)
580 {
581   if (g_list_find (registered_resources, resource) == NULL)
582     {
583       g_warning ("Tried to remove not registred resource");
584     }
585   else
586     {
587       registered_resources = g_list_remove (registered_resources,
588                                            resource);
589       g_resource_unref (resource);
590     }
591 }
592
593 /**
594  * g_resources_register:
595  * @resource: A #GResource.
596  *
597  * Registers the resource with the process-global set of resources.
598  * Once a resource is registered the files in it can be accessed
599  * with the global resource lookup functions like g_resources_lookup_data().
600  *
601  * Since: 2.32
602  **/
603 void
604 g_resources_register (GResource *resource)
605 {
606   g_rw_lock_writer_lock (&resources_lock);
607   g_resources_register_unlocked (resource);
608   g_rw_lock_writer_unlock (&resources_lock);
609 }
610
611 /**
612  * g_resources_unregister:
613  * @resource: A #GResource.
614  *
615  * Unregisters the resource from the process-global set of resources.
616  *
617  * Since: 2.32
618  **/
619 void
620 g_resources_unregister (GResource *resource)
621 {
622   g_rw_lock_writer_lock (&resources_lock);
623   g_resources_unregister_unlocked (resource);
624   g_rw_lock_writer_unlock (&resources_lock);
625 }
626
627 /**
628  * g_resources_open_stream:
629  * @path: A pathname inside the resource.
630  * @lookup_flags: A #GResourceLookupFlags.
631  * @error: return location for a #GError, or %NULL.
632  *
633  * Looks for a file at the specified @path in the set of
634  * globally registred resources and returns a #GInputStream
635  * that lets you read the data.
636  *
637  * @lookup_flags controls the behaviour of the lookup.
638  *
639  * Returns: (transfer full): #GInputStream or %NULL on error.
640  *     Free the returned object with g_object_unref().
641  *
642  * Since: 2.32
643  **/
644 GInputStream *
645 g_resources_open_stream (const char *path,
646                          GResourceLookupFlags lookup_flags,
647                          GError **error)
648 {
649   GInputStream *res = NULL;
650   GList *l;
651   GInputStream *stream;
652
653   register_lazy_static_resources ();
654
655   g_rw_lock_reader_lock (&resources_lock);
656
657   for (l = registered_resources; l != NULL; l = l->next)
658     {
659       GResource *r = l->data;
660       GError *my_error = NULL;
661
662       stream = g_resource_open_stream (r, path, lookup_flags, &my_error);
663       if (stream == NULL &&
664           g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
665         {
666           g_clear_error (&my_error);
667         }
668       else
669         {
670           if (stream == NULL)
671             g_propagate_error (error, my_error);
672           res = stream;
673           break;
674         }
675     }
676
677   if (l == NULL)
678     g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
679                  _("The resource at '%s' does not exist"),
680                  path);
681
682   g_rw_lock_reader_unlock (&resources_lock);
683
684   return res;
685 }
686
687 /**
688  * g_resources_lookup_data:
689  * @path: A pathname inside the resource.
690  * @lookup_flags: A #GResourceLookupFlags.
691  * @error: return location for a #GError, or %NULL.
692  *
693  * Looks for a file at the specified @path in the set of
694  * globally registred resources and returns a #GBytes that
695  * lets you directly access the data in memory.
696  *
697  * The data is always followed by a zero byte, so you
698  * can safely use the data as a C string. However, that byte
699  * is not included in the size of the GBytes.
700  *
701  * For uncompressed resource files this is a pointer directly into
702  * the resource bundle, which is typically in some readonly data section
703  * in the program binary. For compressed files we allocate memory on
704  * the heap and automatically uncompress the data.
705  *
706  * @lookup_flags controls the behaviour of the lookup.
707  *
708  * Returns: (transfer full): #GBytes or %NULL on error.
709  *     Free the returned object with g_bytes_unref().
710  *
711  * Since: 2.32
712  **/
713 GBytes *
714 g_resources_lookup_data (const char *path,
715                          GResourceLookupFlags lookup_flags,
716                          GError **error)
717 {
718   GBytes *res = NULL;
719   GList *l;
720   GBytes *data;
721
722   register_lazy_static_resources ();
723
724   g_rw_lock_reader_lock (&resources_lock);
725
726   for (l = registered_resources; l != NULL; l = l->next)
727     {
728       GResource *r = l->data;
729       GError *my_error = NULL;
730
731       data = g_resource_lookup_data (r, path, lookup_flags, &my_error);
732       if (data == NULL &&
733           g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
734         {
735           g_clear_error (&my_error);
736         }
737       else
738         {
739           if (data == NULL)
740             g_propagate_error (error, my_error);
741           res = data;
742           break;
743         }
744     }
745
746   if (l == NULL)
747     g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
748                  _("The resource at '%s' does not exist"),
749                  path);
750
751   g_rw_lock_reader_unlock (&resources_lock);
752
753   return res;
754 }
755
756 /**
757  * g_resources_enumerate_children:
758  * @path: A pathname inside the resource.
759  * @lookup_flags: A #GResourceLookupFlags.
760  * @error: return location for a #GError, or %NULL.
761  *
762  * Returns all the names of children at the specified @path in the set of
763  * globally registred resources.
764  * The return result is a %NULL terminated list of strings which should
765  * be released with g_strfreev().
766  *
767  * @lookup_flags controls the behaviour of the lookup.
768  *
769  * Returns: (array zero-terminated=1) (transfer full): an array of constant strings
770  *
771  * Since: 2.32
772  **/
773 char **
774 g_resources_enumerate_children (const char *path,
775                                 GResourceLookupFlags lookup_flags,
776                                 GError **error)
777 {
778   GHashTable *hash = NULL;
779   GList *l;
780   char **children;
781   int i;
782
783   register_lazy_static_resources ();
784
785   g_rw_lock_reader_lock (&resources_lock);
786
787   for (l = registered_resources; l != NULL; l = l->next)
788     {
789       GResource *r = l->data;
790
791       children = g_resource_enumerate_children (r, path, 0, NULL);
792
793       if (children != NULL)
794         {
795           if (hash == NULL)
796             hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
797
798           for (i = 0; children[i] != NULL; i++)
799             g_hash_table_insert (hash, children[i], children[i]);
800           g_free (children);
801         }
802     }
803
804   g_rw_lock_reader_unlock (&resources_lock);
805
806   if (hash == NULL)
807     {
808       g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
809                    _("The resource at '%s' does not exist"),
810                    path);
811       return NULL;
812     }
813   else
814     {
815       GHashTableIter iter;
816       const char *key;
817       guint n_children;
818       n_children = g_hash_table_size (hash);
819       children = g_new (char *, n_children + 1);
820       i = 0;
821
822       g_hash_table_iter_init (&iter, hash);
823       while (g_hash_table_iter_next (&iter, (gpointer *)&key, NULL))
824         children[i++] = g_strdup (key);
825       children[i++] = NULL;
826
827       g_hash_table_destroy (hash);
828
829       return children;
830     }
831 }
832
833 /**
834  * g_resources_get_info:
835  * @path: A pathname inside the resource.
836  * @lookup_flags: A #GResourceLookupFlags.
837  * @size:  (out) (allow-none): a location to place the length of the contents of the file,
838  *    or %NULL if the length is not needed
839  * @flags:  (out) (allow-none): a location to place the flags about the file,
840  *    or %NULL if the length is not needed
841  * @error: return location for a #GError, or %NULL.
842  *
843  * Looks for a file at the specified @path in the set of
844  * globally registred resources and if found returns information about it.
845  *
846  * @lookup_flags controls the behaviour of the lookup.
847  *
848  * Returns: %TRUE if the file was found. %FALSE if there were errors.
849  *
850  * Since: 2.32
851  **/
852 gboolean
853 g_resources_get_info (const char   *path,
854                       GResourceLookupFlags lookup_flags,
855                       gsize        *size,
856                       guint32      *flags,
857                       GError      **error)
858 {
859   gboolean res = FALSE;
860   GList *l;
861   gboolean r_res;
862
863   register_lazy_static_resources ();
864
865   g_rw_lock_reader_lock (&resources_lock);
866
867   for (l = registered_resources; l != NULL; l = l->next)
868     {
869       GResource *r = l->data;
870       GError *my_error = NULL;
871
872       r_res = g_resource_get_info (r, path, lookup_flags, size, flags, &my_error);
873       if (!r_res &&
874           g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
875         {
876           g_clear_error (&my_error);
877         }
878       else
879         {
880           if (!r_res)
881             g_propagate_error (error, my_error);
882           res = r_res;
883           break;
884         }
885     }
886
887   if (l == NULL)
888     g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
889                  _("The resource at '%s' does not exist"),
890                  path);
891
892   g_rw_lock_reader_unlock (&resources_lock);
893
894   return res;
895 }
896
897 /* This code is to handle registration of resources very early, from a constructor.
898  * At that point we'd like to do minimal work, to avoid ordering issues. For instance,
899  * we're not allowed to use g_malloc, as the user need to be able to call g_mem_set_vtable
900  * before the first call to g_malloc.
901  *
902  * So, what we do at construction time is that we just register a static structure on
903  * a list of resources that need to be initialized, and then later, when doing any lookups
904  * in the global list of registered resources, or when getting a reference to the
905  * lazily initialized resource we lazily create and register all the GResources on
906  * the lazy list.
907  *
908  * To avoid having to use locks in the constructor, and having to grab the writer lock
909  * when checking the lazy registering list we update lazy_register_resources in
910  * a lock-less fashion (atomic prepend-only, atomic replace with NULL). However, all
911  * operations except:
912  *  * check if there are any resources to lazily initialize
913  *  * Add a static resource to the lazy init list
914  * Do use the full writer lock for protection.
915  */
916
917 static void
918 register_lazy_static_resources_unlocked ()
919 {
920   GStaticResource *list;
921
922   do
923     list = lazy_register_resources;
924   while (!g_atomic_pointer_compare_and_exchange (&lazy_register_resources, list, NULL));
925
926   while (list != NULL)
927     {
928       GBytes *bytes = g_bytes_new_static (list->data, list->data_len);
929       GResource *resource = g_resource_new_from_data (bytes, NULL);
930       if (resource)
931         {
932           g_resources_register_unlocked (resource);
933           g_atomic_pointer_set (&list->resource, resource);
934         }
935       g_bytes_unref (bytes);
936
937       list = list->next;
938     }
939 }
940
941 static void
942 register_lazy_static_resources ()
943 {
944   if (g_atomic_pointer_get (&lazy_register_resources) == NULL)
945     return;
946
947   g_rw_lock_writer_lock (&resources_lock);
948   register_lazy_static_resources_unlocked ();
949   g_rw_lock_writer_unlock (&resources_lock);
950 }
951
952 /**
953  * g_static_resource_init:
954  * @static_resource: pointer to a static #GStaticResource.
955  *
956  * Initializes a GResource from static data using a
957  * GStaticResource.
958  *
959  * This is normally used by code generated by
960  * <link linkend="glib-compile-resources">glib-compile-resources</link> and is
961  * not typically used by other code.
962  *
963  * Since: 2.32
964  **/
965 void
966 g_static_resource_init (GStaticResource *static_resource)
967 {
968   gpointer next;
969
970   do
971     {
972       next = lazy_register_resources;
973       static_resource->next = next;
974     }
975   while (!g_atomic_pointer_compare_and_exchange (&lazy_register_resources, next, static_resource));
976 }
977
978 /**
979  * g_static_resource_fini:
980  * @static_resource: pointer to a static #GStaticResource.
981  *
982  * Finalized a GResource initialized by g_static_resource_init ().
983  *
984  * This is normally used by code generated by
985  * <link linkend="glib-compile-resources">glib-compile-resources</link> and is
986  * not typically used by other code.
987  *
988  * Since: 2.32
989  **/
990 void
991 g_static_resource_fini (GStaticResource *static_resource)
992 {
993   GResource *resource;
994
995   g_rw_lock_writer_lock (&resources_lock);
996
997   register_lazy_static_resources_unlocked ();
998
999   resource = g_atomic_pointer_get (&static_resource->resource);
1000   if (resource)
1001     {
1002       g_atomic_pointer_set (&static_resource->resource, NULL);
1003       g_resources_unregister_unlocked (resource);
1004       g_resource_unref (resource);
1005     }
1006
1007   g_rw_lock_writer_unlock (&resources_lock);
1008 }
1009
1010 /**
1011  * g_static_resource_get_resource:
1012  * @static_resource: pointer to a static #GStaticResource.
1013  *
1014  * Gets the GResource that was registred by a call to g_static_resource_init ().
1015  *
1016  * This is normally used by code generated by
1017  * <link linkend="glib-compile-resources">glib-compile-resources</link> and is
1018  * not typically used by other code.
1019  *
1020  * Return value:  (transfer none): a #GResource.
1021  *
1022  * Since: 2.32
1023  **/
1024 GResource *
1025 g_static_resource_get_resource  (GStaticResource *static_resource)
1026 {
1027   register_lazy_static_resources ();
1028
1029   return g_atomic_pointer_get (&static_resource->resource);
1030 }