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