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