Merge branch 'g-clear-pointer-no-side-effects' into 'master'
[glib.git] / gio / gresource.c
blob2844f48081fc46ad5a5be722c167d351a9c808a4
1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2011 Red Hat, Inc
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.1 of the License, or (at your option) any later version.
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.
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/>.
18 * Authors: Alexander Larsson <alexl@redhat.com>
21 #include "config.h"
23 #include <string.h>
25 #include "gresource.h"
26 #include <gvdb/gvdb-reader.h>
27 #include <gi18n-lib.h>
28 #include <gstdio.h>
29 #include <gio/gfile.h>
30 #include <gio/gioerror.h>
31 #include <gio/gmemoryinputstream.h>
32 #include <gio/gzlibdecompressor.h>
33 #include <gio/gconverterinputstream.h>
35 struct _GResource
37 int ref_count;
39 GvdbTable *table;
42 static void register_lazy_static_resources (void);
44 G_DEFINE_BOXED_TYPE (GResource, g_resource, g_resource_ref, g_resource_unref)
46 /**
47 * SECTION:gresource
48 * @short_description: Resource framework
49 * @include: gio/gio.h
51 * Applications and libraries often contain binary or textual data that is
52 * really part of the application, rather than user data. For instance
53 * #GtkBuilder .ui files, splashscreen images, GMenu markup XML, CSS files,
54 * icons, etc. These are often shipped as files in `$datadir/appname`, or
55 * manually included as literal strings in the code.
57 * The #GResource API and the [glib-compile-resources][glib-compile-resources] program
58 * provide a convenient and efficient alternative to this which has some nice properties. You
59 * maintain the files as normal files, so its easy to edit them, but during the build the files
60 * are combined into a binary bundle that is linked into the executable. This means that loading
61 * the resource files are efficient (as they are already in memory, shared with other instances) and
62 * simple (no need to check for things like I/O errors or locate the files in the filesystem). It
63 * also makes it easier to create relocatable applications.
65 * Resource files can also be marked as compressed. Such files will be included in the resource bundle
66 * in a compressed form, but will be automatically uncompressed when the resource is used. This
67 * is very useful e.g. for larger text files that are parsed once (or rarely) and then thrown away.
69 * Resource files can also be marked to be preprocessed, by setting the value of the
70 * `preprocess` attribute to a comma-separated list of preprocessing options.
71 * The only options currently supported are:
73 * `xml-stripblanks` which will use the xmllint command
74 * to strip ignorable whitespace from the XML file. For this to work,
75 * the `XMLLINT` environment variable must be set to the full path to
76 * the xmllint executable, or xmllint must be in the `PATH`; otherwise
77 * the preprocessing step is skipped.
79 * `to-pixdata` which will use the gdk-pixbuf-pixdata command to convert
80 * images to the GdkPixdata format, which allows you to create pixbufs directly using the data inside
81 * the resource file, rather than an (uncompressed) copy if it. For this, the gdk-pixbuf-pixdata
82 * program must be in the PATH, or the `GDK_PIXBUF_PIXDATA` environment variable must be
83 * set to the full path to the gdk-pixbuf-pixdata executable; otherwise the resource compiler will
84 * abort.
86 * Resource files will be exported in the GResource namespace using the
87 * combination of the given `prefix` and the filename from the `file` element.
88 * The `alias` attribute can be used to alter the filename to expose them at a
89 * different location in the resource namespace. Typically, this is used to
90 * include files from a different source directory without exposing the source
91 * directory in the resource namespace, as in the example below.
93 * Resource bundles are created by the [glib-compile-resources][glib-compile-resources] program
94 * which takes an XML file that describes the bundle, and a set of files that the XML references. These
95 * are combined into a binary resource bundle.
97 * An example resource description:
98 * |[
99 * <?xml version="1.0" encoding="UTF-8"?>
100 * <gresources>
101 * <gresource prefix="/org/gtk/Example">
102 * <file>data/splashscreen.png</file>
103 * <file compressed="true">dialog.ui</file>
104 * <file preprocess="xml-stripblanks">menumarkup.xml</file>
105 * <file alias="example.css">data/example.css</file>
106 * </gresource>
107 * </gresources>
108 * ]|
110 * This will create a resource bundle with the following files:
111 * |[
112 * /org/gtk/Example/data/splashscreen.png
113 * /org/gtk/Example/dialog.ui
114 * /org/gtk/Example/menumarkup.xml
115 * /org/gtk/Example/example.css
116 * ]|
118 * Note that all resources in the process share the same namespace, so use Java-style
119 * path prefixes (like in the above example) to avoid conflicts.
121 * You can then use [glib-compile-resources][glib-compile-resources] to compile the XML to a
122 * binary bundle that you can load with g_resource_load(). However, its more common to use the --generate-source and
123 * --generate-header arguments to create a source file and header to link directly into your application.
124 * This will generate `get_resource()`, `register_resource()` and
125 * `unregister_resource()` functions, prefixed by the `--c-name` argument passed
126 * to [glib-compile-resources][glib-compile-resources]. `get_resource()` returns
127 * the generated #GResource object. The register and unregister functions
128 * register the resource so its files can be accessed using
129 * g_resources_lookup_data().
131 * Once a #GResource has been created and registered all the data in it can be accessed globally in the process by
132 * using API calls like g_resources_open_stream() to stream the data or g_resources_lookup_data() to get a direct pointer
133 * to the data. You can also use URIs like "resource:///org/gtk/Example/data/splashscreen.png" with #GFile to access
134 * the resource data.
136 * Some higher-level APIs, such as #GtkApplication, will automatically load
137 * resources from certain well-known paths in the resource namespace as a
138 * convenience. See the documentation for those APIs for details.
140 * There are two forms of the generated source, the default version uses the compiler support for constructor
141 * and destructor functions (where available) to automatically create and register the #GResource on startup
142 * or library load time. If you pass `--manual-register`, two functions to register/unregister the resource are created
143 * instead. This requires an explicit initialization call in your application/library, but it works on all platforms,
144 * even on the minor ones where constructors are not supported. (Constructor support is available for at least Win32, Mac OS and Linux.)
146 * Note that resource data can point directly into the data segment of e.g. a library, so if you are unloading libraries
147 * during runtime you need to be very careful with keeping around pointers to data from a resource, as this goes away
148 * when the library is unloaded. However, in practice this is not generally a problem, since most resource accesses
149 * are for your own resources, and resource data is often used once, during parsing, and then released.
151 * When debugging a program or testing a change to an installed version, it is often useful to be able to
152 * replace resources in the program or library, without recompiling, for debugging or quick hacking and testing
153 * purposes. Since GLib 2.50, it is possible to use the `G_RESOURCE_OVERLAYS` environment variable to selectively overlay
154 * resources with replacements from the filesystem. It is a colon-separated list of substitutions to perform
155 * during resource lookups.
157 * A substitution has the form
159 * |[
160 * /org/gtk/libgtk=/home/desrt/gtk-overlay
161 * ]|
163 * The part before the `=` is the resource subpath for which the overlay applies. The part after is a
164 * filesystem path which contains files and subdirectories as you would like to be loaded as resources with the
165 * equivalent names.
167 * In the example above, if an application tried to load a resource with the resource path
168 * `/org/gtk/libgtk/ui/gtkdialog.ui` then GResource would check the filesystem path
169 * `/home/desrt/gtk-overlay/ui/gtkdialog.ui`. If a file was found there, it would be used instead. This is an
170 * overlay, not an outright replacement, which means that if a file is not found at that path, the built-in
171 * version will be used instead. Whiteouts are not currently supported.
173 * Substitutions must start with a slash, and must not contain a trailing slash before the '='. The path after
174 * the slash should ideally be absolute, but this is not strictly required. It is possible to overlay the
175 * location of a single resource with an individual file.
177 * Since: 2.32
181 * GStaticResource:
183 * #GStaticResource is an opaque data structure and can only be accessed
184 * using the following functions.
186 typedef gboolean (* CheckCandidate) (const gchar *candidate, gpointer user_data);
188 static gboolean
189 open_overlay_stream (const gchar *candidate,
190 gpointer user_data)
192 GInputStream **res = (GInputStream **) user_data;
193 GError *error = NULL;
194 GFile *file;
196 file = g_file_new_for_path (candidate);
197 *res = (GInputStream *) g_file_read (file, NULL, &error);
199 if (*res)
201 g_message ("Opened file '%s' as a resource overlay", candidate);
203 else
205 if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
206 g_warning ("Can't open overlay file '%s': %s", candidate, error->message);
207 g_error_free (error);
210 g_object_unref (file);
212 return *res != NULL;
215 static gboolean
216 get_overlay_bytes (const gchar *candidate,
217 gpointer user_data)
219 GBytes **res = (GBytes **) user_data;
220 GMappedFile *mapped_file;
221 GError *error = NULL;
223 mapped_file = g_mapped_file_new (candidate, FALSE, &error);
225 if (mapped_file)
227 g_message ("Mapped file '%s' as a resource overlay", candidate);
228 *res = g_mapped_file_get_bytes (mapped_file);
229 g_mapped_file_unref (mapped_file);
231 else
233 if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
234 g_warning ("Can't mmap overlay file '%s': %s", candidate, error->message);
235 g_error_free (error);
238 return *res != NULL;
241 static gboolean
242 enumerate_overlay_dir (const gchar *candidate,
243 gpointer user_data)
245 GHashTable **hash = (GHashTable **) user_data;
246 GError *error = NULL;
247 GDir *dir;
248 const gchar *name;
250 dir = g_dir_open (candidate, 0, &error);
251 if (dir)
253 if (*hash == NULL)
254 /* note: keep in sync with same line below */
255 *hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
257 g_message ("Enumerating directory '%s' as resource overlay", candidate);
259 while ((name = g_dir_read_name (dir)))
261 gchar *fullname = g_build_filename (candidate, name, NULL);
263 /* match gvdb behaviour by suffixing "/" on dirs */
264 if (g_file_test (fullname, G_FILE_TEST_IS_DIR))
265 g_hash_table_add (*hash, g_strconcat (name, "/", NULL));
266 else
267 g_hash_table_add (*hash, g_strdup (name));
269 g_free (fullname);
272 g_dir_close (dir);
274 else
276 if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
277 g_warning ("Can't enumerate overlay directory '%s': %s", candidate, error->message);
278 g_error_free (error);
279 return FALSE;
282 /* We may want to enumerate results from more than one overlay
283 * directory.
285 return FALSE;
288 static gboolean
289 g_resource_find_overlay (const gchar *path,
290 CheckCandidate check,
291 gpointer user_data)
293 /* This is a null-terminated array of replacement strings (with '=' inside) */
294 static const gchar * const *overlay_dirs;
295 gboolean res = FALSE;
296 gint path_len = -1;
297 gint i;
299 /* We try to be very fast in case there are no overlays. Otherwise,
300 * we can take a bit more time...
303 if (g_once_init_enter (&overlay_dirs))
305 const gchar * const *result;
306 const gchar *envvar;
308 envvar = g_getenv ("G_RESOURCE_OVERLAYS");
309 if (envvar != NULL)
311 gchar **parts;
312 gint i, j;
314 parts = g_strsplit (envvar, ":", 0);
316 /* Sanity check the parts, dropping those that are invalid.
317 * 'i' may grow faster than 'j'.
319 for (i = j = 0; parts[i]; i++)
321 gchar *part = parts[i];
322 gchar *eq;
324 eq = strchr (part, '=');
325 if (eq == NULL)
327 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks '='. Ignoring.", part);
328 g_free (part);
329 continue;
332 if (eq == part)
334 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks path before '='. Ignoring.", part);
335 g_free (part);
336 continue;
339 if (eq[1] == '\0')
341 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks path after '='. Ignoring", part);
342 g_free (part);
343 continue;
346 if (part[0] != '/')
348 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks leading '/'. Ignoring.", part);
349 g_free (part);
350 continue;
353 if (eq[-1] == '/')
355 g_critical ("G_RESOURCE_OVERLAYS segment '%s' has trailing '/' before '='. Ignoring", part);
356 g_free (part);
357 continue;
360 if (eq[1] != '/')
362 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks leading '/' after '='. Ignoring", part);
363 g_free (part);
364 continue;
367 g_message ("Adding GResources overlay '%s'", part);
368 parts[j++] = part;
371 parts[j] = NULL;
373 result = (const gchar **) parts;
375 else
377 /* We go out of the way to avoid malloc() in the normal case
378 * where the environment variable is not set.
380 static const gchar * const empty_strv[0 + 1];
381 result = empty_strv;
384 g_once_init_leave (&overlay_dirs, result);
387 for (i = 0; overlay_dirs[i]; i++)
389 const gchar *src;
390 gint src_len;
391 const gchar *dst;
392 gint dst_len;
393 gchar *candidate;
396 gchar *eq;
398 /* split the overlay into src/dst */
399 src = overlay_dirs[i];
400 eq = strchr (src, '=');
401 g_assert (eq); /* we checked this already */
402 src_len = eq - src;
403 dst = eq + 1;
404 /* hold off on dst_len because we will probably fail the checks below */
407 if (path_len == -1)
408 path_len = strlen (path);
410 /* The entire path is too short to match the source */
411 if (path_len < src_len)
412 continue;
414 /* It doesn't match the source */
415 if (memcmp (path, src, src_len) != 0)
416 continue;
418 /* The prefix matches, but it's not a complete path component */
419 if (path[src_len] && path[src_len] != '/')
420 continue;
422 /* OK. Now we need this. */
423 dst_len = strlen (dst);
425 /* The candidate will be composed of:
427 * dst + remaining_path + nul
429 candidate = g_malloc (dst_len + (path_len - src_len) + 1);
430 memcpy (candidate, dst, dst_len);
431 memcpy (candidate + dst_len, path + src_len, path_len - src_len);
432 candidate[dst_len + (path_len - src_len)] = '\0';
434 /* No matter what, 'r' is what we need, including the case where
435 * we are trying to enumerate a directory.
437 res = (* check) (candidate, user_data);
438 g_free (candidate);
440 if (res)
441 break;
444 return res;
448 * g_resource_error_quark:
450 * Gets the #GResource Error Quark.
452 * Returns: a #GQuark
454 * Since: 2.32
456 G_DEFINE_QUARK (g-resource-error-quark, g_resource_error)
459 * g_resource_ref:
460 * @resource: A #GResource
462 * Atomically increments the reference count of @resource by one. This
463 * function is MT-safe and may be called from any thread.
465 * Returns: The passed in #GResource
467 * Since: 2.32
469 GResource *
470 g_resource_ref (GResource *resource)
472 g_atomic_int_inc (&resource->ref_count);
473 return resource;
477 * g_resource_unref:
478 * @resource: A #GResource
480 * Atomically decrements the reference count of @resource by one. If the
481 * reference count drops to 0, all memory allocated by the resource is
482 * released. This function is MT-safe and may be called from any
483 * thread.
485 * Since: 2.32
487 void
488 g_resource_unref (GResource *resource)
490 if (g_atomic_int_dec_and_test (&resource->ref_count))
492 gvdb_table_free (resource->table);
493 g_free (resource);
497 /*< internal >
498 * g_resource_new_from_table:
499 * @table: (transfer full): a GvdbTable
501 * Returns: (transfer full): a new #GResource for @table
503 static GResource *
504 g_resource_new_from_table (GvdbTable *table)
506 GResource *resource;
508 resource = g_new (GResource, 1);
509 resource->ref_count = 1;
510 resource->table = table;
512 return resource;
515 static void
516 g_resource_error_from_gvdb_table_error (GError **g_resource_error,
517 GError *gvdb_table_error /* (transfer full) */)
519 if (g_error_matches (gvdb_table_error, G_FILE_ERROR, G_FILE_ERROR_INVAL))
520 g_set_error_literal (g_resource_error,
521 G_RESOURCE_ERROR, G_RESOURCE_ERROR_INTERNAL,
522 gvdb_table_error->message);
523 else
524 g_propagate_error (g_resource_error, g_steal_pointer (&gvdb_table_error));
525 g_clear_error (&gvdb_table_error);
529 * g_resource_new_from_data:
530 * @data: A #GBytes
531 * @error: return location for a #GError, or %NULL
533 * Creates a GResource from a reference to the binary resource bundle.
534 * This will keep a reference to @data while the resource lives, so
535 * the data should not be modified or freed.
537 * If you want to use this resource in the global resource namespace you need
538 * to register it with g_resources_register().
540 * Note: @data must be backed by memory that is at least pointer aligned.
541 * Otherwise this function will internally create a copy of the memory since
542 * GLib 2.56, or in older versions fail and exit the process.
544 * If @data is empty or corrupt, %G_RESOURCE_ERROR_INTERNAL will be returned.
546 * Returns: (transfer full): a new #GResource, or %NULL on error
548 * Since: 2.32
550 GResource *
551 g_resource_new_from_data (GBytes *data,
552 GError **error)
554 GvdbTable *table;
555 gboolean unref_data = FALSE;
556 GError *local_error = NULL;
558 if (((guintptr) g_bytes_get_data (data, NULL)) % sizeof (gpointer) != 0)
560 data = g_bytes_new (g_bytes_get_data (data, NULL),
561 g_bytes_get_size (data));
562 unref_data = TRUE;
565 table = gvdb_table_new_from_bytes (data, TRUE, &local_error);
567 if (unref_data)
568 g_bytes_unref (data);
570 if (table == NULL)
572 g_resource_error_from_gvdb_table_error (error, g_steal_pointer (&local_error));
573 return NULL;
576 return g_resource_new_from_table (table);
580 * g_resource_load:
581 * @filename: (type filename): the path of a filename to load, in the GLib filename encoding
582 * @error: return location for a #GError, or %NULL
584 * Loads a binary resource bundle and creates a #GResource representation of it, allowing
585 * you to query it for data.
587 * If you want to use this resource in the global resource namespace you need
588 * to register it with g_resources_register().
590 * If @filename is empty or the data in it is corrupt,
591 * %G_RESOURCE_ERROR_INTERNAL will be returned. If @filename doesn’t exist, or
592 * there is an error in reading it, an error from g_mapped_file_new() will be
593 * returned.
595 * Returns: (transfer full): a new #GResource, or %NULL on error
597 * Since: 2.32
599 GResource *
600 g_resource_load (const gchar *filename,
601 GError **error)
603 GvdbTable *table;
604 GError *local_error = NULL;
606 table = gvdb_table_new (filename, FALSE, &local_error);
607 if (table == NULL)
609 g_resource_error_from_gvdb_table_error (error, g_steal_pointer (&local_error));
610 return NULL;
613 return g_resource_new_from_table (table);
616 static gboolean
617 do_lookup (GResource *resource,
618 const gchar *path,
619 GResourceLookupFlags lookup_flags,
620 gsize *size,
621 guint32 *flags,
622 const void **data,
623 gsize *data_size,
624 GError **error)
626 char *free_path = NULL;
627 gsize path_len;
628 gboolean res = FALSE;
629 GVariant *value;
631 /* Drop any trailing slash. */
632 path_len = strlen (path);
633 if (path_len >= 1 && path[path_len-1] == '/')
635 path = free_path = g_strdup (path);
636 free_path[path_len-1] = 0;
639 value = gvdb_table_get_raw_value (resource->table, path);
641 if (value == NULL)
643 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
644 _("The resource at “%s” does not exist"),
645 path);
647 else
649 guint32 _size, _flags;
650 GVariant *array;
652 g_variant_get (value, "(uu@ay)",
653 &_size,
654 &_flags,
655 &array);
657 _size = GUINT32_FROM_LE (_size);
658 _flags = GUINT32_FROM_LE (_flags);
660 if (size)
661 *size = _size;
662 if (flags)
663 *flags = _flags;
664 if (data)
665 *data = g_variant_get_data (array);
666 if (data_size)
668 /* Don't report trailing newline that non-compressed files has */
669 if (_flags & G_RESOURCE_FLAGS_COMPRESSED)
670 *data_size = g_variant_get_size (array);
671 else
672 *data_size = g_variant_get_size (array) - 1;
674 g_variant_unref (array);
675 g_variant_unref (value);
677 res = TRUE;
680 g_free (free_path);
681 return res;
685 * g_resource_open_stream:
686 * @resource: A #GResource
687 * @path: A pathname inside the resource
688 * @lookup_flags: A #GResourceLookupFlags
689 * @error: return location for a #GError, or %NULL
691 * Looks for a file at the specified @path in the resource and
692 * returns a #GInputStream that lets you read the data.
694 * @lookup_flags controls the behaviour of the lookup.
696 * Returns: (transfer full): #GInputStream or %NULL on error.
697 * Free the returned object with g_object_unref()
699 * Since: 2.32
701 GInputStream *
702 g_resource_open_stream (GResource *resource,
703 const gchar *path,
704 GResourceLookupFlags lookup_flags,
705 GError **error)
707 const void *data;
708 gsize data_size;
709 guint32 flags;
710 GInputStream *stream, *stream2;
712 if (!do_lookup (resource, path, lookup_flags, NULL, &flags, &data, &data_size, error))
713 return NULL;
715 stream = g_memory_input_stream_new_from_data (data, data_size, NULL);
716 g_object_set_data_full (G_OBJECT (stream), "g-resource",
717 g_resource_ref (resource),
718 (GDestroyNotify)g_resource_unref);
720 if (flags & G_RESOURCE_FLAGS_COMPRESSED)
722 GZlibDecompressor *decompressor =
723 g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB);
725 stream2 = g_converter_input_stream_new (stream, G_CONVERTER (decompressor));
726 g_object_unref (decompressor);
727 g_object_unref (stream);
728 stream = stream2;
731 return stream;
735 * g_resource_lookup_data:
736 * @resource: A #GResource
737 * @path: A pathname inside the resource
738 * @lookup_flags: A #GResourceLookupFlags
739 * @error: return location for a #GError, or %NULL
741 * Looks for a file at the specified @path in the resource and
742 * returns a #GBytes that lets you directly access the data in
743 * memory.
745 * The data is always followed by a zero byte, so you
746 * can safely use the data as a C string. However, that byte
747 * is not included in the size of the GBytes.
749 * For uncompressed resource files this is a pointer directly into
750 * the resource bundle, which is typically in some readonly data section
751 * in the program binary. For compressed files we allocate memory on
752 * the heap and automatically uncompress the data.
754 * @lookup_flags controls the behaviour of the lookup.
756 * Returns: (transfer full): #GBytes or %NULL on error.
757 * Free the returned object with g_bytes_unref()
759 * Since: 2.32
761 GBytes *
762 g_resource_lookup_data (GResource *resource,
763 const gchar *path,
764 GResourceLookupFlags lookup_flags,
765 GError **error)
767 const void *data;
768 guint32 flags;
769 gsize data_size;
770 gsize size;
772 if (!do_lookup (resource, path, lookup_flags, &size, &flags, &data, &data_size, error))
773 return NULL;
775 if (flags & G_RESOURCE_FLAGS_COMPRESSED)
777 char *uncompressed, *d;
778 const char *s;
779 GConverterResult res;
780 gsize d_size, s_size;
781 gsize bytes_read, bytes_written;
784 GZlibDecompressor *decompressor =
785 g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB);
787 uncompressed = g_malloc (size + 1);
789 s = data;
790 s_size = data_size;
791 d = uncompressed;
792 d_size = size;
796 res = g_converter_convert (G_CONVERTER (decompressor),
797 s, s_size,
798 d, d_size,
799 G_CONVERTER_INPUT_AT_END,
800 &bytes_read,
801 &bytes_written,
802 NULL);
803 if (res == G_CONVERTER_ERROR)
805 g_free (uncompressed);
806 g_object_unref (decompressor);
808 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_INTERNAL,
809 _("The resource at “%s” failed to decompress"),
810 path);
811 return NULL;
814 s += bytes_read;
815 s_size -= bytes_read;
816 d += bytes_written;
817 d_size -= bytes_written;
819 while (res != G_CONVERTER_FINISHED);
821 uncompressed[size] = 0; /* Zero terminate */
823 g_object_unref (decompressor);
825 return g_bytes_new_take (uncompressed, size);
827 else
828 return g_bytes_new_with_free_func (data, data_size, (GDestroyNotify)g_resource_unref, g_resource_ref (resource));
832 * g_resource_get_info:
833 * @resource: A #GResource
834 * @path: A pathname inside the resource
835 * @lookup_flags: A #GResourceLookupFlags
836 * @size: (out) (optional): a location to place the length of the contents of the file,
837 * or %NULL if the length is not needed
838 * @flags: (out) (optional): a location to place the flags about the file,
839 * or %NULL if the length is not needed
840 * @error: return location for a #GError, or %NULL
842 * Looks for a file at the specified @path in the resource and
843 * if found returns information about it.
845 * @lookup_flags controls the behaviour of the lookup.
847 * Returns: %TRUE if the file was found. %FALSE if there were errors
849 * Since: 2.32
851 gboolean
852 g_resource_get_info (GResource *resource,
853 const gchar *path,
854 GResourceLookupFlags lookup_flags,
855 gsize *size,
856 guint32 *flags,
857 GError **error)
859 return do_lookup (resource, path, lookup_flags, size, flags, NULL, NULL, error);
863 * g_resource_enumerate_children:
864 * @resource: A #GResource
865 * @path: A pathname inside the resource
866 * @lookup_flags: A #GResourceLookupFlags
867 * @error: return location for a #GError, or %NULL
869 * Returns all the names of children at the specified @path in the resource.
870 * The return result is a %NULL terminated list of strings which should
871 * be released with g_strfreev().
873 * If @path is invalid or does not exist in the #GResource,
874 * %G_RESOURCE_ERROR_NOT_FOUND will be returned.
876 * @lookup_flags controls the behaviour of the lookup.
878 * Returns: (array zero-terminated=1) (transfer full): an array of constant strings
880 * Since: 2.32
882 gchar **
883 g_resource_enumerate_children (GResource *resource,
884 const gchar *path,
885 GResourceLookupFlags lookup_flags,
886 GError **error)
888 gchar local_str[256];
889 const gchar *path_with_slash;
890 gchar **children;
891 gchar *free_path = NULL;
892 gsize path_len;
895 * Size of 256 is arbitrarily chosen based on being large enough
896 * for pretty much everything we come across, but not cumbersome
897 * on the stack. It also matches common cacheline sizes.
900 if (*path == 0)
902 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
903 _("The resource at “%s” does not exist"),
904 path);
905 return NULL;
908 path_len = strlen (path);
910 if G_UNLIKELY (path[path_len-1] != '/')
912 if (path_len < sizeof (local_str) - 2)
915 * We got a path that does not have a trailing /. It is not the
916 * ideal use of this API as we require trailing / for our lookup
917 * into gvdb. Some degenerate application configurations can hit
918 * this code path quite a bit, so we try to avoid using the
919 * g_strconcat()/g_free().
921 memcpy (local_str, path, path_len);
922 local_str[path_len] = '/';
923 local_str[path_len+1] = 0;
924 path_with_slash = local_str;
926 else
928 path_with_slash = free_path = g_strconcat (path, "/", NULL);
931 else
933 path_with_slash = path;
936 children = gvdb_table_list (resource->table, path_with_slash);
937 g_free (free_path);
939 if (children == NULL)
941 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
942 _("The resource at “%s” does not exist"),
943 path);
944 return NULL;
947 return children;
950 static GRWLock resources_lock;
951 static GList *registered_resources;
953 /* This is updated atomically, so we can append to it and check for NULL outside the
954 lock, but all other accesses are done under the write lock */
955 static GStaticResource *lazy_register_resources;
957 static void
958 g_resources_register_unlocked (GResource *resource)
960 registered_resources = g_list_prepend (registered_resources, g_resource_ref (resource));
963 static void
964 g_resources_unregister_unlocked (GResource *resource)
966 if (g_list_find (registered_resources, resource) == NULL)
968 g_warning ("Tried to remove not registered resource");
970 else
972 registered_resources = g_list_remove (registered_resources, resource);
973 g_resource_unref (resource);
978 * g_resources_register:
979 * @resource: A #GResource
981 * Registers the resource with the process-global set of resources.
982 * Once a resource is registered the files in it can be accessed
983 * with the global resource lookup functions like g_resources_lookup_data().
985 * Since: 2.32
987 void
988 g_resources_register (GResource *resource)
990 g_rw_lock_writer_lock (&resources_lock);
991 g_resources_register_unlocked (resource);
992 g_rw_lock_writer_unlock (&resources_lock);
996 * g_resources_unregister:
997 * @resource: A #GResource
999 * Unregisters the resource from the process-global set of resources.
1001 * Since: 2.32
1003 void
1004 g_resources_unregister (GResource *resource)
1006 g_rw_lock_writer_lock (&resources_lock);
1007 g_resources_unregister_unlocked (resource);
1008 g_rw_lock_writer_unlock (&resources_lock);
1012 * g_resources_open_stream:
1013 * @path: A pathname inside the resource
1014 * @lookup_flags: A #GResourceLookupFlags
1015 * @error: return location for a #GError, or %NULL
1017 * Looks for a file at the specified @path in the set of
1018 * globally registered resources and returns a #GInputStream
1019 * that lets you read the data.
1021 * @lookup_flags controls the behaviour of the lookup.
1023 * Returns: (transfer full): #GInputStream or %NULL on error.
1024 * Free the returned object with g_object_unref()
1026 * Since: 2.32
1028 GInputStream *
1029 g_resources_open_stream (const gchar *path,
1030 GResourceLookupFlags lookup_flags,
1031 GError **error)
1033 GInputStream *res = NULL;
1034 GList *l;
1035 GInputStream *stream;
1037 if (g_resource_find_overlay (path, open_overlay_stream, &res))
1038 return res;
1040 register_lazy_static_resources ();
1042 g_rw_lock_reader_lock (&resources_lock);
1044 for (l = registered_resources; l != NULL; l = l->next)
1046 GResource *r = l->data;
1047 GError *my_error = NULL;
1049 stream = g_resource_open_stream (r, path, lookup_flags, &my_error);
1050 if (stream == NULL &&
1051 g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
1053 g_clear_error (&my_error);
1055 else
1057 if (stream == NULL)
1058 g_propagate_error (error, my_error);
1059 res = stream;
1060 break;
1064 if (l == NULL)
1065 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
1066 _("The resource at “%s” does not exist"),
1067 path);
1069 g_rw_lock_reader_unlock (&resources_lock);
1071 return res;
1075 * g_resources_lookup_data:
1076 * @path: A pathname inside the resource
1077 * @lookup_flags: A #GResourceLookupFlags
1078 * @error: return location for a #GError, or %NULL
1080 * Looks for a file at the specified @path in the set of
1081 * globally registered resources and returns a #GBytes that
1082 * lets you directly access the data in memory.
1084 * The data is always followed by a zero byte, so you
1085 * can safely use the data as a C string. However, that byte
1086 * is not included in the size of the GBytes.
1088 * For uncompressed resource files this is a pointer directly into
1089 * the resource bundle, which is typically in some readonly data section
1090 * in the program binary. For compressed files we allocate memory on
1091 * the heap and automatically uncompress the data.
1093 * @lookup_flags controls the behaviour of the lookup.
1095 * Returns: (transfer full): #GBytes or %NULL on error.
1096 * Free the returned object with g_bytes_unref()
1098 * Since: 2.32
1100 GBytes *
1101 g_resources_lookup_data (const gchar *path,
1102 GResourceLookupFlags lookup_flags,
1103 GError **error)
1105 GBytes *res = NULL;
1106 GList *l;
1107 GBytes *data;
1109 if (g_resource_find_overlay (path, get_overlay_bytes, &res))
1110 return res;
1112 register_lazy_static_resources ();
1114 g_rw_lock_reader_lock (&resources_lock);
1116 for (l = registered_resources; l != NULL; l = l->next)
1118 GResource *r = l->data;
1119 GError *my_error = NULL;
1121 data = g_resource_lookup_data (r, path, lookup_flags, &my_error);
1122 if (data == NULL &&
1123 g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
1125 g_clear_error (&my_error);
1127 else
1129 if (data == NULL)
1130 g_propagate_error (error, my_error);
1131 res = data;
1132 break;
1136 if (l == NULL)
1137 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
1138 _("The resource at “%s” does not exist"),
1139 path);
1141 g_rw_lock_reader_unlock (&resources_lock);
1143 return res;
1147 * g_resources_enumerate_children:
1148 * @path: A pathname inside the resource
1149 * @lookup_flags: A #GResourceLookupFlags
1150 * @error: return location for a #GError, or %NULL
1152 * Returns all the names of children at the specified @path in the set of
1153 * globally registered resources.
1154 * The return result is a %NULL terminated list of strings which should
1155 * be released with g_strfreev().
1157 * @lookup_flags controls the behaviour of the lookup.
1159 * Returns: (array zero-terminated=1) (transfer full): an array of constant strings
1161 * Since: 2.32
1163 gchar **
1164 g_resources_enumerate_children (const gchar *path,
1165 GResourceLookupFlags lookup_flags,
1166 GError **error)
1168 GHashTable *hash = NULL;
1169 GList *l;
1170 char **children;
1171 int i;
1173 /* This will enumerate actual files found in overlay directories but
1174 * will not enumerate the overlays themselves. For example, if we
1175 * have an overlay "/org/gtk=/path/to/files" and we enumerate "/org"
1176 * then we will not see "gtk" in the result set unless it is provided
1177 * by another resource file.
1179 * This is probably not going to be a problem since if we are doing
1180 * such an overlay, we probably will already have that path.
1182 g_resource_find_overlay (path, enumerate_overlay_dir, &hash);
1184 register_lazy_static_resources ();
1186 g_rw_lock_reader_lock (&resources_lock);
1188 for (l = registered_resources; l != NULL; l = l->next)
1190 GResource *r = l->data;
1192 children = g_resource_enumerate_children (r, path, 0, NULL);
1194 if (children != NULL)
1196 if (hash == NULL)
1197 /* note: keep in sync with same line above */
1198 hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1200 for (i = 0; children[i] != NULL; i++)
1201 g_hash_table_add (hash, children[i]);
1202 g_free (children);
1206 g_rw_lock_reader_unlock (&resources_lock);
1208 if (hash == NULL)
1210 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
1211 _("The resource at “%s” does not exist"),
1212 path);
1213 return NULL;
1215 else
1217 children = (gchar **) g_hash_table_get_keys_as_array (hash, NULL);
1218 g_hash_table_steal_all (hash);
1219 g_hash_table_destroy (hash);
1221 return children;
1226 * g_resources_get_info:
1227 * @path: A pathname inside the resource
1228 * @lookup_flags: A #GResourceLookupFlags
1229 * @size: (out) (optional): a location to place the length of the contents of the file,
1230 * or %NULL if the length is not needed
1231 * @flags: (out) (optional): a location to place the #GResourceFlags about the file,
1232 * or %NULL if the flags are not needed
1233 * @error: return location for a #GError, or %NULL
1235 * Looks for a file at the specified @path in the set of
1236 * globally registered resources and if found returns information about it.
1238 * @lookup_flags controls the behaviour of the lookup.
1240 * Returns: %TRUE if the file was found. %FALSE if there were errors
1242 * Since: 2.32
1244 gboolean
1245 g_resources_get_info (const gchar *path,
1246 GResourceLookupFlags lookup_flags,
1247 gsize *size,
1248 guint32 *flags,
1249 GError **error)
1251 gboolean res = FALSE;
1252 GList *l;
1253 gboolean r_res;
1255 register_lazy_static_resources ();
1257 g_rw_lock_reader_lock (&resources_lock);
1259 for (l = registered_resources; l != NULL; l = l->next)
1261 GResource *r = l->data;
1262 GError *my_error = NULL;
1264 r_res = g_resource_get_info (r, path, lookup_flags, size, flags, &my_error);
1265 if (!r_res &&
1266 g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
1268 g_clear_error (&my_error);
1270 else
1272 if (!r_res)
1273 g_propagate_error (error, my_error);
1274 res = r_res;
1275 break;
1279 if (l == NULL)
1280 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
1281 _("The resource at “%s” does not exist"),
1282 path);
1284 g_rw_lock_reader_unlock (&resources_lock);
1286 return res;
1289 /* This code is to handle registration of resources very early, from a constructor.
1290 * At that point we'd like to do minimal work, to avoid ordering issues. For instance,
1291 * we're not allowed to use g_malloc, as the user need to be able to call g_mem_set_vtable
1292 * before the first call to g_malloc.
1294 * So, what we do at construction time is that we just register a static structure on
1295 * a list of resources that need to be initialized, and then later, when doing any lookups
1296 * in the global list of registered resources, or when getting a reference to the
1297 * lazily initialized resource we lazily create and register all the GResources on
1298 * the lazy list.
1300 * To avoid having to use locks in the constructor, and having to grab the writer lock
1301 * when checking the lazy registering list we update lazy_register_resources in
1302 * a lock-less fashion (atomic prepend-only, atomic replace with NULL). However, all
1303 * operations except:
1304 * * check if there are any resources to lazily initialize
1305 * * Add a static resource to the lazy init list
1306 * Do use the full writer lock for protection.
1309 static void
1310 register_lazy_static_resources_unlocked (void)
1312 GStaticResource *list;
1315 list = lazy_register_resources;
1316 while (!g_atomic_pointer_compare_and_exchange (&lazy_register_resources, list, NULL));
1318 while (list != NULL)
1320 GBytes *bytes = g_bytes_new_static (list->data, list->data_len);
1321 GResource *resource = g_resource_new_from_data (bytes, NULL);
1322 if (resource)
1324 g_resources_register_unlocked (resource);
1325 g_atomic_pointer_set (&list->resource, resource);
1327 g_bytes_unref (bytes);
1329 list = list->next;
1333 static void
1334 register_lazy_static_resources (void)
1336 if (g_atomic_pointer_get (&lazy_register_resources) == NULL)
1337 return;
1339 g_rw_lock_writer_lock (&resources_lock);
1340 register_lazy_static_resources_unlocked ();
1341 g_rw_lock_writer_unlock (&resources_lock);
1345 * g_static_resource_init:
1346 * @static_resource: pointer to a static #GStaticResource
1348 * Initializes a GResource from static data using a
1349 * GStaticResource.
1351 * This is normally used by code generated by
1352 * [glib-compile-resources][glib-compile-resources]
1353 * and is not typically used by other code.
1355 * Since: 2.32
1357 void
1358 g_static_resource_init (GStaticResource *static_resource)
1360 gpointer next;
1364 next = lazy_register_resources;
1365 static_resource->next = next;
1367 while (!g_atomic_pointer_compare_and_exchange (&lazy_register_resources, next, static_resource));
1371 * g_static_resource_fini:
1372 * @static_resource: pointer to a static #GStaticResource
1374 * Finalized a GResource initialized by g_static_resource_init().
1376 * This is normally used by code generated by
1377 * [glib-compile-resources][glib-compile-resources]
1378 * and is not typically used by other code.
1380 * Since: 2.32
1382 void
1383 g_static_resource_fini (GStaticResource *static_resource)
1385 GResource *resource;
1387 g_rw_lock_writer_lock (&resources_lock);
1389 register_lazy_static_resources_unlocked ();
1391 resource = g_atomic_pointer_get (&static_resource->resource);
1392 if (resource)
1394 g_atomic_pointer_set (&static_resource->resource, NULL);
1395 g_resources_unregister_unlocked (resource);
1396 g_resource_unref (resource);
1399 g_rw_lock_writer_unlock (&resources_lock);
1403 * g_static_resource_get_resource:
1404 * @static_resource: pointer to a static #GStaticResource
1406 * Gets the GResource that was registered by a call to g_static_resource_init().
1408 * This is normally used by code generated by
1409 * [glib-compile-resources][glib-compile-resources]
1410 * and is not typically used by other code.
1412 * Returns: (transfer none): a #GResource
1414 * Since: 2.32
1416 GResource *
1417 g_static_resource_get_resource (GStaticResource *static_resource)
1419 register_lazy_static_resources ();
1421 return g_atomic_pointer_get (&static_resource->resource);