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