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