resources: compiler: Fix resources on big endian architectures
[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 compressed. 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 available) 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 available. (Constructor support is available 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
269 gboolean do_lookup (GResource             *resource,
270                     const gchar           *path,
271                     GResourceLookupFlags   lookup_flags,
272                     gsize                 *size,
273                     guint32               *flags,
274                     const void           **data,
275                     gsize                 *data_size,
276                     GError               **error)
277 {
278   char *free_path = NULL;
279   gsize path_len;
280   gboolean res = FALSE;
281   GVariant *value;
282
283   path_len = strlen (path);
284   if (path[path_len-1] == '/')
285     {
286       path = free_path = g_strdup (path);
287       free_path[path_len-1] = 0;
288     }
289
290   value = gvdb_table_get_raw_value (resource->table, path);
291
292   if (value == NULL)
293     {
294       g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
295                    _("The resource at '%s' does not exist"),
296                    path);
297     }
298   else
299     {
300       guint32 _size, _flags;
301       GVariant *array;
302
303       g_variant_get (value, "(uu@ay)",
304                      &_size,
305                      &_flags,
306                      &array);
307
308       _size = GUINT32_FROM_LE (_size);
309       _flags = GUINT32_FROM_LE (_flags);
310
311       if (size)
312         *size = _size;
313       if (flags)
314         *flags = _flags;
315       if (data)
316         *data = g_variant_get_data (array);
317       if (data_size)
318         {
319           /* Don't report trailing newline that non-compressed files has */
320           if (_flags & G_RESOURCE_FLAGS_COMPRESSED)
321             *data_size = g_variant_get_size (array);
322           else
323             *data_size = g_variant_get_size (array) - 1;
324         }
325       g_variant_unref (array);
326       g_variant_unref (value);
327
328       res = TRUE;
329     }
330
331   g_free (free_path);
332   return res;
333 }
334
335 /**
336  * g_resource_open_stream:
337  * @resource: A #GResource
338  * @path: A pathname inside the resource
339  * @lookup_flags: A #GResourceLookupFlags
340  * @error: return location for a #GError, or %NULL
341  *
342  * Looks for a file at the specified @path in the resource and
343  * returns a #GInputStream that lets you read the data.
344  *
345  * @lookup_flags controls the behaviour of the lookup.
346  *
347  * Returns: (transfer full): #GInputStream or %NULL on error.
348  *     Free the returned object with g_object_unref()
349  *
350  * Since: 2.32
351  **/
352 GInputStream *
353 g_resource_open_stream (GResource             *resource,
354                         const gchar           *path,
355                         GResourceLookupFlags   lookup_flags,
356                         GError               **error)
357 {
358   const void *data;
359   gsize data_size;
360   guint32 flags;
361   GInputStream *stream, *stream2;
362
363   if (!do_lookup (resource, path, lookup_flags, NULL, &flags, &data, &data_size, error))
364     return NULL;
365
366   stream = g_memory_input_stream_new_from_data (data, data_size, NULL);
367   g_object_set_data_full (G_OBJECT (stream), "g-resource",
368                           g_resource_ref (resource),
369                           (GDestroyNotify)g_resource_unref);
370
371   if (flags & G_RESOURCE_FLAGS_COMPRESSED)
372     {
373       GZlibDecompressor *decompressor =
374         g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB);
375
376       stream2 = g_converter_input_stream_new (stream, G_CONVERTER (decompressor));
377       g_object_unref (decompressor);
378       g_object_unref (stream);
379       stream = stream2;
380     }
381
382   return stream;
383 }
384
385 /**
386  * g_resource_lookup_data:
387  * @resource: A #GResource
388  * @path: A pathname inside the resource
389  * @lookup_flags: A #GResourceLookupFlags
390  * @error: return location for a #GError, or %NULL
391  *
392  * Looks for a file at the specified @path in the resource and
393  * returns a #GBytes that lets you directly access the data in
394  * memory.
395  *
396  * The data is always followed by a zero byte, so you
397  * can safely use the data as a C string. However, that byte
398  * is not included in the size of the GBytes.
399  *
400  * For uncompressed resource files this is a pointer directly into
401  * the resource bundle, which is typically in some readonly data section
402  * in the program binary. For compressed files we allocate memory on
403  * the heap and automatically uncompress the data.
404  *
405  * @lookup_flags controls the behaviour of the lookup.
406  *
407  * Returns: (transfer full): #GBytes or %NULL on error.
408  *     Free the returned object with g_bytes_unref()
409  *
410  * Since: 2.32
411  **/
412 GBytes *
413 g_resource_lookup_data (GResource             *resource,
414                         const gchar           *path,
415                         GResourceLookupFlags   lookup_flags,
416                         GError               **error)
417 {
418   const void *data;
419   guint32 flags;
420   gsize data_size;
421   gsize size;
422
423   if (!do_lookup (resource, path, lookup_flags, &size, &flags, &data, &data_size, error))
424     return NULL;
425
426   if (flags & G_RESOURCE_FLAGS_COMPRESSED)
427     {
428       char *uncompressed, *d;
429       const char *s;
430       GConverterResult res;
431       gsize d_size, s_size;
432       gsize bytes_read, bytes_written;
433
434
435       GZlibDecompressor *decompressor =
436         g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB);
437
438       uncompressed = g_malloc (size + 1);
439
440       s = data;
441       s_size = data_size;
442       d = uncompressed;
443       d_size = size;
444
445       do
446         {
447           res = g_converter_convert (G_CONVERTER (decompressor),
448                                      s, s_size,
449                                      d, d_size,
450                                      G_CONVERTER_INPUT_AT_END,
451                                      &bytes_read,
452                                      &bytes_written,
453                                      NULL);
454           if (res == G_CONVERTER_ERROR)
455             {
456               g_free (uncompressed);
457               g_object_unref (decompressor);
458
459               g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_INTERNAL,
460                            _("The resource at '%s' failed to decompress"),
461                            path);
462               return NULL;
463
464             }
465           s += bytes_read;
466           s_size -= bytes_read;
467           d += bytes_written;
468           d_size -= bytes_written;
469         }
470       while (res != G_CONVERTER_FINISHED);
471
472       uncompressed[size] = 0; /* Zero terminate */
473
474       g_object_unref (decompressor);
475
476       return g_bytes_new_take (uncompressed, size);
477     }
478   else
479     return g_bytes_new_with_free_func (data, data_size, (GDestroyNotify)g_resource_unref, g_resource_ref (resource));
480 }
481
482 /**
483  * g_resource_get_info:
484  * @resource: A #GResource
485  * @path: A pathname inside the resource
486  * @lookup_flags: A #GResourceLookupFlags
487  * @size:  (out) (allow-none): a location to place the length of the contents of the file,
488  *    or %NULL if the length is not needed
489  * @flags:  (out) (allow-none): a location to place the flags about the file,
490  *    or %NULL if the length is not needed
491  * @error: return location for a #GError, or %NULL
492  *
493  * Looks for a file at the specified @path in the resource and
494  * if found returns information about it.
495  *
496  * @lookup_flags controls the behaviour of the lookup.
497  *
498  * Returns: %TRUE if the file was found. %FALSE if there were errors
499  *
500  * Since: 2.32
501  **/
502 gboolean
503 g_resource_get_info (GResource             *resource,
504                      const gchar           *path,
505                      GResourceLookupFlags   lookup_flags,
506                      gsize                 *size,
507                      guint32               *flags,
508                      GError               **error)
509 {
510   return do_lookup (resource, path, lookup_flags, size, flags, NULL, NULL, error);
511 }
512
513 /**
514  * g_resource_enumerate_children:
515  * @resource: A #GResource
516  * @path: A pathname inside the resource
517  * @lookup_flags: A #GResourceLookupFlags
518  * @error: return location for a #GError, or %NULL
519  *
520  * Returns all the names of children at the specified @path in the resource.
521  * The return result is a %NULL terminated list of strings which should
522  * be released with g_strfreev().
523  *
524  * @lookup_flags controls the behaviour of the lookup.
525  *
526  * Returns: (array zero-terminated=1) (transfer full): an array of constant strings
527  *
528  * Since: 2.32
529  **/
530 gchar **
531 g_resource_enumerate_children (GResource             *resource,
532                                const gchar           *path,
533                                GResourceLookupFlags   lookup_flags,
534                                GError               **error)
535 {
536   gchar **children;
537   gsize path_len;
538   char *path_with_slash;
539
540   if (*path == 0)
541     {
542       g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
543                    _("The resource at '%s' does not exist"),
544                    path);
545       return NULL;
546     }
547
548   path_len = strlen (path);
549   if (path[path_len-1] != '/')
550     path_with_slash = g_strconcat (path, "/", NULL);
551   else
552     path_with_slash = g_strdup (path);
553
554   children = gvdb_table_list (resource->table, path_with_slash);
555   g_free (path_with_slash);
556
557   if (children == NULL)
558     {
559       g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
560                    _("The resource at '%s' does not exist"),
561                    path);
562       return NULL;
563     }
564
565   return children;
566 }
567
568 static GRWLock resources_lock;
569 static GList *registered_resources;
570
571 /* This is updated atomically, so we can append to it and check for NULL outside the
572    lock, but all other accesses are done under the write lock */
573 static GStaticResource *lazy_register_resources;
574
575 static void
576 g_resources_register_unlocked (GResource *resource)
577 {
578   registered_resources = g_list_prepend (registered_resources, g_resource_ref (resource));
579 }
580
581 static void
582 g_resources_unregister_unlocked (GResource *resource)
583 {
584   if (g_list_find (registered_resources, resource) == NULL)
585     {
586       g_warning ("Tried to remove not registred resource");
587     }
588   else
589     {
590       registered_resources = g_list_remove (registered_resources, resource);
591       g_resource_unref (resource);
592     }
593 }
594
595 /**
596  * g_resources_register:
597  * @resource: A #GResource
598  *
599  * Registers the resource with the process-global set of resources.
600  * Once a resource is registered the files in it can be accessed
601  * with the global resource lookup functions like g_resources_lookup_data().
602  *
603  * Since: 2.32
604  **/
605 void
606 g_resources_register (GResource *resource)
607 {
608   g_rw_lock_writer_lock (&resources_lock);
609   g_resources_register_unlocked (resource);
610   g_rw_lock_writer_unlock (&resources_lock);
611 }
612
613 /**
614  * g_resources_unregister:
615  * @resource: A #GResource
616  *
617  * Unregisters the resource from the process-global set of resources.
618  *
619  * Since: 2.32
620  **/
621 void
622 g_resources_unregister (GResource *resource)
623 {
624   g_rw_lock_writer_lock (&resources_lock);
625   g_resources_unregister_unlocked (resource);
626   g_rw_lock_writer_unlock (&resources_lock);
627 }
628
629 /**
630  * g_resources_open_stream:
631  * @path: A pathname inside the resource
632  * @lookup_flags: A #GResourceLookupFlags
633  * @error: return location for a #GError, or %NULL
634  *
635  * Looks for a file at the specified @path in the set of
636  * globally registred resources and returns a #GInputStream
637  * that lets you read the data.
638  *
639  * @lookup_flags controls the behaviour of the lookup.
640  *
641  * Returns: (transfer full): #GInputStream or %NULL on error.
642  *     Free the returned object with g_object_unref()
643  *
644  * Since: 2.32
645  **/
646 GInputStream *
647 g_resources_open_stream (const gchar           *path,
648                          GResourceLookupFlags   lookup_flags,
649                          GError               **error)
650 {
651   GInputStream *res = NULL;
652   GList *l;
653   GInputStream *stream;
654
655   register_lazy_static_resources ();
656
657   g_rw_lock_reader_lock (&resources_lock);
658
659   for (l = registered_resources; l != NULL; l = l->next)
660     {
661       GResource *r = l->data;
662       GError *my_error = NULL;
663
664       stream = g_resource_open_stream (r, path, lookup_flags, &my_error);
665       if (stream == NULL &&
666           g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
667         {
668           g_clear_error (&my_error);
669         }
670       else
671         {
672           if (stream == NULL)
673             g_propagate_error (error, my_error);
674           res = stream;
675           break;
676         }
677     }
678
679   if (l == NULL)
680     g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
681                  _("The resource at '%s' does not exist"),
682                  path);
683
684   g_rw_lock_reader_unlock (&resources_lock);
685
686   return res;
687 }
688
689 /**
690  * g_resources_lookup_data:
691  * @path: A pathname inside the resource
692  * @lookup_flags: A #GResourceLookupFlags
693  * @error: return location for a #GError, or %NULL
694  *
695  * Looks for a file at the specified @path in the set of
696  * globally registred resources and returns a #GBytes that
697  * lets you directly access the data in memory.
698  *
699  * The data is always followed by a zero byte, so you
700  * can safely use the data as a C string. However, that byte
701  * is not included in the size of the GBytes.
702  *
703  * For uncompressed resource files this is a pointer directly into
704  * the resource bundle, which is typically in some readonly data section
705  * in the program binary. For compressed files we allocate memory on
706  * the heap and automatically uncompress the data.
707  *
708  * @lookup_flags controls the behaviour of the lookup.
709  *
710  * Returns: (transfer full): #GBytes or %NULL on error.
711  *     Free the returned object with g_bytes_unref()
712  *
713  * Since: 2.32
714  **/
715 GBytes *
716 g_resources_lookup_data (const gchar           *path,
717                          GResourceLookupFlags   lookup_flags,
718                          GError               **error)
719 {
720   GBytes *res = NULL;
721   GList *l;
722   GBytes *data;
723
724   register_lazy_static_resources ();
725
726   g_rw_lock_reader_lock (&resources_lock);
727
728   for (l = registered_resources; l != NULL; l = l->next)
729     {
730       GResource *r = l->data;
731       GError *my_error = NULL;
732
733       data = g_resource_lookup_data (r, path, lookup_flags, &my_error);
734       if (data == NULL &&
735           g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
736         {
737           g_clear_error (&my_error);
738         }
739       else
740         {
741           if (data == NULL)
742             g_propagate_error (error, my_error);
743           res = data;
744           break;
745         }
746     }
747
748   if (l == NULL)
749     g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
750                  _("The resource at '%s' does not exist"),
751                  path);
752
753   g_rw_lock_reader_unlock (&resources_lock);
754
755   return res;
756 }
757
758 /**
759  * g_resources_enumerate_children:
760  * @path: A pathname inside the resource
761  * @lookup_flags: A #GResourceLookupFlags
762  * @error: return location for a #GError, or %NULL
763  *
764  * Returns all the names of children at the specified @path in the set of
765  * globally registred resources.
766  * The return result is a %NULL terminated list of strings which should
767  * be released with g_strfreev().
768  *
769  * @lookup_flags controls the behaviour of the lookup.
770  *
771  * Returns: (array zero-terminated=1) (transfer full): an array of constant strings
772  *
773  * Since: 2.32
774  **/
775 gchar **
776 g_resources_enumerate_children (const gchar           *path,
777                                 GResourceLookupFlags   lookup_flags,
778                                 GError               **error)
779 {
780   GHashTable *hash = NULL;
781   GList *l;
782   char **children;
783   int i;
784
785   register_lazy_static_resources ();
786
787   g_rw_lock_reader_lock (&resources_lock);
788
789   for (l = registered_resources; l != NULL; l = l->next)
790     {
791       GResource *r = l->data;
792
793       children = g_resource_enumerate_children (r, path, 0, NULL);
794
795       if (children != NULL)
796         {
797           if (hash == NULL)
798             hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
799
800           for (i = 0; children[i] != NULL; i++)
801             g_hash_table_insert (hash, children[i], children[i]);
802           g_free (children);
803         }
804     }
805
806   g_rw_lock_reader_unlock (&resources_lock);
807
808   if (hash == NULL)
809     {
810       g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
811                    _("The resource at '%s' does not exist"),
812                    path);
813       return NULL;
814     }
815   else
816     {
817       GHashTableIter iter;
818       const char *key;
819       guint n_children;
820       n_children = g_hash_table_size (hash);
821       children = g_new (char *, n_children + 1);
822       i = 0;
823
824       g_hash_table_iter_init (&iter, hash);
825       while (g_hash_table_iter_next (&iter, (gpointer *)&key, NULL))
826         children[i++] = g_strdup (key);
827       children[i++] = NULL;
828
829       g_hash_table_destroy (hash);
830
831       return children;
832     }
833 }
834
835 /**
836  * g_resources_get_info:
837  * @path: A pathname inside the resource
838  * @lookup_flags: A #GResourceLookupFlags
839  * @size:  (out) (allow-none): a location to place the length of the contents of the file,
840  *    or %NULL if the length is not needed
841  * @flags:  (out) (allow-none): a location to place the flags about the file,
842  *    or %NULL if the length is not needed
843  * @error: return location for a #GError, or %NULL
844  *
845  * Looks for a file at the specified @path in the set of
846  * globally registred resources and if found returns information about it.
847  *
848  * @lookup_flags controls the behaviour of the lookup.
849  *
850  * Returns: %TRUE if the file was found. %FALSE if there were errors
851  *
852  * Since: 2.32
853  **/
854 gboolean
855 g_resources_get_info (const gchar           *path,
856                       GResourceLookupFlags   lookup_flags,
857                       gsize                 *size,
858                       guint32               *flags,
859                       GError               **error)
860 {
861   gboolean res = FALSE;
862   GList *l;
863   gboolean r_res;
864
865   register_lazy_static_resources ();
866
867   g_rw_lock_reader_lock (&resources_lock);
868
869   for (l = registered_resources; l != NULL; l = l->next)
870     {
871       GResource *r = l->data;
872       GError *my_error = NULL;
873
874       r_res = g_resource_get_info (r, path, lookup_flags, size, flags, &my_error);
875       if (!r_res &&
876           g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
877         {
878           g_clear_error (&my_error);
879         }
880       else
881         {
882           if (!r_res)
883             g_propagate_error (error, my_error);
884           res = r_res;
885           break;
886         }
887     }
888
889   if (l == NULL)
890     g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
891                  _("The resource at '%s' does not exist"),
892                  path);
893
894   g_rw_lock_reader_unlock (&resources_lock);
895
896   return res;
897 }
898
899 /* This code is to handle registration of resources very early, from a constructor.
900  * At that point we'd like to do minimal work, to avoid ordering issues. For instance,
901  * we're not allowed to use g_malloc, as the user need to be able to call g_mem_set_vtable
902  * before the first call to g_malloc.
903  *
904  * So, what we do at construction time is that we just register a static structure on
905  * a list of resources that need to be initialized, and then later, when doing any lookups
906  * in the global list of registered resources, or when getting a reference to the
907  * lazily initialized resource we lazily create and register all the GResources on
908  * the lazy list.
909  *
910  * To avoid having to use locks in the constructor, and having to grab the writer lock
911  * when checking the lazy registering list we update lazy_register_resources in
912  * a lock-less fashion (atomic prepend-only, atomic replace with NULL). However, all
913  * operations except:
914  *  * check if there are any resources to lazily initialize
915  *  * Add a static resource to the lazy init list
916  * Do use the full writer lock for protection.
917  */
918
919 static void
920 register_lazy_static_resources_unlocked (void)
921 {
922   GStaticResource *list;
923
924   do
925     list = lazy_register_resources;
926   while (!g_atomic_pointer_compare_and_exchange (&lazy_register_resources, list, NULL));
927
928   while (list != NULL)
929     {
930       GBytes *bytes = g_bytes_new_static (list->data, list->data_len);
931       GResource *resource = g_resource_new_from_data (bytes, NULL);
932       if (resource)
933         {
934           g_resources_register_unlocked (resource);
935           g_atomic_pointer_set (&list->resource, resource);
936         }
937       g_bytes_unref (bytes);
938
939       list = list->next;
940     }
941 }
942
943 static void
944 register_lazy_static_resources (void)
945 {
946   if (g_atomic_pointer_get (&lazy_register_resources) == NULL)
947     return;
948
949   g_rw_lock_writer_lock (&resources_lock);
950   register_lazy_static_resources_unlocked ();
951   g_rw_lock_writer_unlock (&resources_lock);
952 }
953
954 /**
955  * g_static_resource_init:
956  * @static_resource: pointer to a static #GStaticResource
957  *
958  * Initializes a GResource from static data using a
959  * GStaticResource.
960  *
961  * This is normally used by code generated by
962  * <link linkend="glib-compile-resources">glib-compile-resources</link>
963  * and is not typically used by other code.
964  *
965  * Since: 2.32
966  **/
967 void
968 g_static_resource_init (GStaticResource *static_resource)
969 {
970   gpointer next;
971
972   do
973     {
974       next = lazy_register_resources;
975       static_resource->next = next;
976     }
977   while (!g_atomic_pointer_compare_and_exchange (&lazy_register_resources, next, static_resource));
978 }
979
980 /**
981  * g_static_resource_fini:
982  * @static_resource: pointer to a static #GStaticResource
983  *
984  * Finalized a GResource initialized by g_static_resource_init().
985  *
986  * This is normally used by code generated by
987  * <link linkend="glib-compile-resources">glib-compile-resources</link>
988  * and is not typically used by other code.
989  *
990  * Since: 2.32
991  **/
992 void
993 g_static_resource_fini (GStaticResource *static_resource)
994 {
995   GResource *resource;
996
997   g_rw_lock_writer_lock (&resources_lock);
998
999   register_lazy_static_resources_unlocked ();
1000
1001   resource = g_atomic_pointer_get (&static_resource->resource);
1002   if (resource)
1003     {
1004       g_atomic_pointer_set (&static_resource->resource, NULL);
1005       g_resources_unregister_unlocked (resource);
1006       g_resource_unref (resource);
1007     }
1008
1009   g_rw_lock_writer_unlock (&resources_lock);
1010 }
1011
1012 /**
1013  * g_static_resource_get_resource:
1014  * @static_resource: pointer to a static #GStaticResource
1015  *
1016  * Gets the GResource that was registred by a call to g_static_resource_init().
1017  *
1018  * This is normally used by code generated by
1019  * <link linkend="glib-compile-resources">glib-compile-resources</link>
1020  * and is not typically used by other code.
1021  *
1022  * Return value:  (transfer none): a #GResource
1023  *
1024  * Since: 2.32
1025  **/
1026 GResource *
1027 g_static_resource_get_resource (GStaticResource *static_resource)
1028 {
1029   register_lazy_static_resources ();
1030
1031   return g_atomic_pointer_get (&static_resource->resource);
1032 }