1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2011 Red Hat, Inc
5 * SPDX-License-Identifier: LGPL-2.1-or-later
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 * Authors: Alexander Larsson <alexl@redhat.com>
27 #include "gresource.h"
28 #include <gvdb/gvdb-reader.h>
29 #include <gi18n-lib.h>
31 #include <gio/gfile.h>
32 #include <gio/gioerror.h>
33 #include <gio/gmemoryinputstream.h>
34 #include <gio/gzlibdecompressor.h>
35 #include <gio/gconverterinputstream.h>
37 #include "glib-private.h"
46 static void register_lazy_static_resources (void);
48 G_DEFINE_BOXED_TYPE (GResource, g_resource, g_resource_ref, g_resource_unref)
52 * @short_description: Resource framework
55 * Applications and libraries often contain binary or textual data that is
56 * really part of the application, rather than user data. For instance
57 * #GtkBuilder .ui files, splashscreen images, GMenu markup XML, CSS files,
58 * icons, etc. These are often shipped as files in `$datadir/appname`, or
59 * manually included as literal strings in the code.
61 * The #GResource API and the [glib-compile-resources][glib-compile-resources] program
62 * provide a convenient and efficient alternative to this which has some nice properties. You
63 * maintain the files as normal files, so its easy to edit them, but during the build the files
64 * are combined into a binary bundle that is linked into the executable. This means that loading
65 * the resource files are efficient (as they are already in memory, shared with other instances) and
66 * simple (no need to check for things like I/O errors or locate the files in the filesystem). It
67 * also makes it easier to create relocatable applications.
69 * Resource files can also be marked as compressed. Such files will be included in the resource bundle
70 * in a compressed form, but will be automatically uncompressed when the resource is used. This
71 * is very useful e.g. for larger text files that are parsed once (or rarely) and then thrown away.
73 * Resource files can also be marked to be preprocessed, by setting the value of the
74 * `preprocess` attribute to a comma-separated list of preprocessing options.
75 * The only options currently supported are:
77 * `xml-stripblanks` which will use the xmllint command
78 * to strip ignorable whitespace from the XML file. For this to work,
79 * the `XMLLINT` environment variable must be set to the full path to
80 * the xmllint executable, or xmllint must be in the `PATH`; otherwise
81 * the preprocessing step is skipped.
83 * `to-pixdata` (deprecated since gdk-pixbuf 2.32) which will use the
84 * `gdk-pixbuf-pixdata` command to convert images to the #GdkPixdata format,
85 * which allows you to create pixbufs directly using the data inside the
86 * resource file, rather than an (uncompressed) copy of it. For this, the
87 * `gdk-pixbuf-pixdata` program must be in the `PATH`, or the
88 * `GDK_PIXBUF_PIXDATA` environment variable must be set to the full path to the
89 * `gdk-pixbuf-pixdata` executable; otherwise the resource compiler will abort.
90 * `to-pixdata` has been deprecated since gdk-pixbuf 2.32, as #GResource
91 * supports embedding modern image formats just as well. Instead of using it,
92 * embed a PNG or SVG file in your #GResource.
94 * `json-stripblanks` which will use the `json-glib-format` command to strip
95 * ignorable whitespace from the JSON file. For this to work, the
96 * `JSON_GLIB_FORMAT` environment variable must be set to the full path to the
97 * `json-glib-format` executable, or it must be in the `PATH`;
98 * otherwise the preprocessing step is skipped. In addition, at least version
99 * 1.6 of `json-glib-format` is required.
101 * Resource files will be exported in the GResource namespace using the
102 * combination of the given `prefix` and the filename from the `file` element.
103 * The `alias` attribute can be used to alter the filename to expose them at a
104 * different location in the resource namespace. Typically, this is used to
105 * include files from a different source directory without exposing the source
106 * directory in the resource namespace, as in the example below.
108 * Resource bundles are created by the [glib-compile-resources][glib-compile-resources] program
109 * which takes an XML file that describes the bundle, and a set of files that the XML references. These
110 * are combined into a binary resource bundle.
112 * An example resource description:
114 * <?xml version="1.0" encoding="UTF-8"?>
116 * <gresource prefix="/org/gtk/Example">
117 * <file>data/splashscreen.png</file>
118 * <file compressed="true">dialog.ui</file>
119 * <file preprocess="xml-stripblanks">menumarkup.xml</file>
120 * <file alias="example.css">data/example.css</file>
125 * This will create a resource bundle with the following files:
127 * /org/gtk/Example/data/splashscreen.png
128 * /org/gtk/Example/dialog.ui
129 * /org/gtk/Example/menumarkup.xml
130 * /org/gtk/Example/example.css
133 * Note that all resources in the process share the same namespace, so use Java-style
134 * path prefixes (like in the above example) to avoid conflicts.
136 * You can then use [glib-compile-resources][glib-compile-resources] to compile the XML to a
137 * binary bundle that you can load with g_resource_load(). However, its more common to use the --generate-source and
138 * --generate-header arguments to create a source file and header to link directly into your application.
139 * This will generate `get_resource()`, `register_resource()` and
140 * `unregister_resource()` functions, prefixed by the `--c-name` argument passed
141 * to [glib-compile-resources][glib-compile-resources]. `get_resource()` returns
142 * the generated #GResource object. The register and unregister functions
143 * register the resource so its files can be accessed using
144 * g_resources_lookup_data().
146 * Once a #GResource has been created and registered all the data in it can be accessed globally in the process by
147 * using API calls like g_resources_open_stream() to stream the data or g_resources_lookup_data() to get a direct pointer
148 * to the data. You can also use URIs like "resource:///org/gtk/Example/data/splashscreen.png" with #GFile to access
151 * Some higher-level APIs, such as #GtkApplication, will automatically load
152 * resources from certain well-known paths in the resource namespace as a
153 * convenience. See the documentation for those APIs for details.
155 * There are two forms of the generated source, the default version uses the compiler support for constructor
156 * and destructor functions (where available) to automatically create and register the #GResource on startup
157 * or library load time. If you pass `--manual-register`, two functions to register/unregister the resource are created
158 * instead. This requires an explicit initialization call in your application/library, but it works on all platforms,
159 * even on the minor ones where constructors are not supported. (Constructor support is available for at least Win32, Mac OS and Linux.)
161 * Note that resource data can point directly into the data segment of e.g. a library, so if you are unloading libraries
162 * during runtime you need to be very careful with keeping around pointers to data from a resource, as this goes away
163 * when the library is unloaded. However, in practice this is not generally a problem, since most resource accesses
164 * are for your own resources, and resource data is often used once, during parsing, and then released.
166 * When debugging a program or testing a change to an installed version, it is often useful to be able to
167 * replace resources in the program or library, without recompiling, for debugging or quick hacking and testing
168 * purposes. Since GLib 2.50, it is possible to use the `G_RESOURCE_OVERLAYS` environment variable to selectively overlay
169 * resources with replacements from the filesystem. It is a %G_SEARCHPATH_SEPARATOR-separated list of substitutions to perform
170 * during resource lookups. It is ignored when running in a setuid process.
172 * A substitution has the form
175 * /org/gtk/libgtk=/home/desrt/gtk-overlay
178 * The part before the `=` is the resource subpath for which the overlay applies. The part after is a
179 * filesystem path which contains files and subdirectories as you would like to be loaded as resources with the
182 * In the example above, if an application tried to load a resource with the resource path
183 * `/org/gtk/libgtk/ui/gtkdialog.ui` then GResource would check the filesystem path
184 * `/home/desrt/gtk-overlay/ui/gtkdialog.ui`. If a file was found there, it would be used instead. This is an
185 * overlay, not an outright replacement, which means that if a file is not found at that path, the built-in
186 * version will be used instead. Whiteouts are not currently supported.
188 * Substitutions must start with a slash, and must not contain a trailing slash before the '='. The path after
189 * the slash should ideally be absolute, but this is not strictly required. It is possible to overlay the
190 * location of a single resource with an individual file.
198 * #GStaticResource is an opaque data structure and can only be accessed
199 * using the following functions.
201 typedef gboolean (* CheckCandidate) (const gchar *candidate, gpointer user_data);
204 open_overlay_stream (const gchar *candidate,
207 GInputStream **res = (GInputStream **) user_data;
208 GError *error = NULL;
211 file = g_file_new_for_path (candidate);
212 *res = (GInputStream *) g_file_read (file, NULL, &error);
216 g_message ("Opened file '%s' as a resource overlay", candidate);
220 if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
221 g_warning ("Can't open overlay file '%s': %s", candidate, error->message);
222 g_error_free (error);
225 g_object_unref (file);
231 get_overlay_bytes (const gchar *candidate,
234 GBytes **res = (GBytes **) user_data;
235 GMappedFile *mapped_file;
236 GError *error = NULL;
238 mapped_file = g_mapped_file_new (candidate, FALSE, &error);
242 g_message ("Mapped file '%s' as a resource overlay", candidate);
243 *res = g_mapped_file_get_bytes (mapped_file);
244 g_mapped_file_unref (mapped_file);
248 if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
249 g_warning ("Can't mmap overlay file '%s': %s", candidate, error->message);
250 g_error_free (error);
257 enumerate_overlay_dir (const gchar *candidate,
260 GHashTable **hash = (GHashTable **) user_data;
261 GError *error = NULL;
265 dir = g_dir_open (candidate, 0, &error);
269 /* note: keep in sync with same line below */
270 *hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
272 g_message ("Enumerating directory '%s' as resource overlay", candidate);
274 while ((name = g_dir_read_name (dir)))
276 gchar *fullname = g_build_filename (candidate, name, NULL);
278 /* match gvdb behaviour by suffixing "/" on dirs */
279 if (g_file_test (fullname, G_FILE_TEST_IS_DIR))
280 g_hash_table_add (*hash, g_strconcat (name, "/", NULL));
282 g_hash_table_add (*hash, g_strdup (name));
291 if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
292 g_warning ("Can't enumerate overlay directory '%s': %s", candidate, error->message);
293 g_error_free (error);
297 /* We may want to enumerate results from more than one overlay
309 get_overlay_info (const gchar *candidate,
312 InfoData *info = user_data;
315 if (g_stat (candidate, &buf) < 0)
318 info->size = buf.st_size;
319 info->flags = G_RESOURCE_FLAGS_NONE;
325 g_resource_find_overlay (const gchar *path,
326 CheckCandidate check,
329 /* This is a null-terminated array of replacement strings (with '=' inside) */
330 static const gchar * const *overlay_dirs;
331 gboolean res = FALSE;
335 /* We try to be very fast in case there are no overlays. Otherwise,
336 * we can take a bit more time...
339 if (g_once_init_enter (&overlay_dirs))
341 gboolean is_setuid = GLIB_PRIVATE_CALL (g_check_setuid) ();
342 const gchar * const *result;
345 /* Don’t load overlays if setuid, as they could allow reading privileged
347 envvar = !is_setuid ? g_getenv ("G_RESOURCE_OVERLAYS") : NULL;
353 parts = g_strsplit (envvar, G_SEARCHPATH_SEPARATOR_S, 0);
355 /* Sanity check the parts, dropping those that are invalid.
356 * 'i' may grow faster than 'j'.
358 for (i = j = 0; parts[i]; i++)
360 gchar *part = parts[i];
363 eq = strchr (part, '=');
366 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks '='. Ignoring.", part);
373 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks path before '='. Ignoring.", part);
380 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks path after '='. Ignoring", part);
387 g_critical ("G_RESOURCE_OVERLAYS segment '%s' lacks leading '/'. Ignoring.", part);
394 g_critical ("G_RESOURCE_OVERLAYS segment '%s' has trailing '/' before '='. Ignoring", part);
399 if (!g_path_is_absolute (eq + 1))
401 g_critical ("G_RESOURCE_OVERLAYS segment '%s' does not have an absolute path after '='. Ignoring", part);
406 g_message ("Adding GResources overlay '%s'", part);
412 result = (const gchar **) parts;
416 /* We go out of the way to avoid malloc() in the normal case
417 * where the environment variable is not set.
419 static const gchar *const empty_strv[0 + 1] = { 0 };
423 g_once_init_leave (&overlay_dirs, result);
426 for (i = 0; overlay_dirs[i]; i++)
437 /* split the overlay into src/dst */
438 src = overlay_dirs[i];
439 eq = strchr (src, '=');
440 g_assert (eq); /* we checked this already */
443 /* hold off on dst_len because we will probably fail the checks below */
447 path_len = strlen (path);
449 /* The entire path is too short to match the source */
450 if (path_len < src_len)
453 /* It doesn't match the source */
454 if (memcmp (path, src, src_len) != 0)
457 /* The prefix matches, but it's not a complete path component */
458 if (path[src_len] && path[src_len] != '/')
461 /* OK. Now we need this. */
462 dst_len = strlen (dst);
464 /* The candidate will be composed of:
466 * dst + remaining_path + nul
468 candidate = g_malloc (dst_len + (path_len - src_len) + 1);
469 memcpy (candidate, dst, dst_len);
470 memcpy (candidate + dst_len, path + src_len, path_len - src_len);
471 candidate[dst_len + (path_len - src_len)] = '\0';
473 /* No matter what, 'r' is what we need, including the case where
474 * we are trying to enumerate a directory.
476 res = (* check) (candidate, user_data);
487 * g_resource_error_quark:
489 * Gets the #GResource Error Quark.
495 G_DEFINE_QUARK (g-resource-error-quark, g_resource_error)
499 * @resource: A #GResource
501 * Atomically increments the reference count of @resource by one. This
502 * function is MT-safe and may be called from any thread.
504 * Returns: The passed in #GResource
509 g_resource_ref (GResource *resource)
511 g_atomic_int_inc (&resource->ref_count);
517 * @resource: A #GResource
519 * Atomically decrements the reference count of @resource by one. If the
520 * reference count drops to 0, all memory allocated by the resource is
521 * released. This function is MT-safe and may be called from any
527 g_resource_unref (GResource *resource)
529 if (g_atomic_int_dec_and_test (&resource->ref_count))
531 gvdb_table_free (resource->table);
537 * g_resource_new_from_table:
538 * @table: (transfer full): a GvdbTable
540 * Returns: (transfer full): a new #GResource for @table
543 g_resource_new_from_table (GvdbTable *table)
547 resource = g_new (GResource, 1);
548 resource->ref_count = 1;
549 resource->table = table;
555 g_resource_error_from_gvdb_table_error (GError **g_resource_error,
556 GError *gvdb_table_error /* (transfer full) */)
558 if (g_error_matches (gvdb_table_error, G_FILE_ERROR, G_FILE_ERROR_INVAL))
559 g_set_error_literal (g_resource_error,
560 G_RESOURCE_ERROR, G_RESOURCE_ERROR_INTERNAL,
561 gvdb_table_error->message);
563 g_propagate_error (g_resource_error, g_steal_pointer (&gvdb_table_error));
564 g_clear_error (&gvdb_table_error);
568 * g_resource_new_from_data:
570 * @error: return location for a #GError, or %NULL
572 * Creates a GResource from a reference to the binary resource bundle.
573 * This will keep a reference to @data while the resource lives, so
574 * the data should not be modified or freed.
576 * If you want to use this resource in the global resource namespace you need
577 * to register it with g_resources_register().
579 * Note: @data must be backed by memory that is at least pointer aligned.
580 * Otherwise this function will internally create a copy of the memory since
581 * GLib 2.56, or in older versions fail and exit the process.
583 * If @data is empty or corrupt, %G_RESOURCE_ERROR_INTERNAL will be returned.
585 * Returns: (transfer full): a new #GResource, or %NULL on error
590 g_resource_new_from_data (GBytes *data,
594 gboolean unref_data = FALSE;
595 GError *local_error = NULL;
597 if (((guintptr) g_bytes_get_data (data, NULL)) % sizeof (gpointer) != 0)
599 data = g_bytes_new (g_bytes_get_data (data, NULL),
600 g_bytes_get_size (data));
604 table = gvdb_table_new_from_bytes (data, TRUE, &local_error);
607 g_bytes_unref (data);
611 g_resource_error_from_gvdb_table_error (error, g_steal_pointer (&local_error));
615 return g_resource_new_from_table (table);
620 * @filename: (type filename): the path of a filename to load, in the GLib filename encoding
621 * @error: return location for a #GError, or %NULL
623 * Loads a binary resource bundle and creates a #GResource representation of it, allowing
624 * you to query it for data.
626 * If you want to use this resource in the global resource namespace you need
627 * to register it with g_resources_register().
629 * If @filename is empty or the data in it is corrupt,
630 * %G_RESOURCE_ERROR_INTERNAL will be returned. If @filename doesn’t exist, or
631 * there is an error in reading it, an error from g_mapped_file_new() will be
634 * Returns: (transfer full): a new #GResource, or %NULL on error
639 g_resource_load (const gchar *filename,
643 GError *local_error = NULL;
645 table = gvdb_table_new (filename, FALSE, &local_error);
648 g_resource_error_from_gvdb_table_error (error, g_steal_pointer (&local_error));
652 return g_resource_new_from_table (table);
656 do_lookup (GResource *resource,
658 GResourceLookupFlags lookup_flags,
665 char *free_path = NULL;
667 gboolean res = FALSE;
670 /* Drop any trailing slash. */
671 path_len = strlen (path);
672 if (path_len >= 1 && path[path_len-1] == '/')
674 path = free_path = g_strdup (path);
675 free_path[path_len-1] = 0;
678 value = gvdb_table_get_raw_value (resource->table, path);
682 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
683 _("The resource at “%s” does not exist"),
688 guint32 _size, _flags;
691 g_variant_get (value, "(uu@ay)",
696 _size = GUINT32_FROM_LE (_size);
697 _flags = GUINT32_FROM_LE (_flags);
704 *data = g_variant_get_data (array);
707 /* Don't report trailing newline that non-compressed files has */
708 if (_flags & G_RESOURCE_FLAGS_COMPRESSED)
709 *data_size = g_variant_get_size (array);
711 *data_size = g_variant_get_size (array) - 1;
713 g_variant_unref (array);
714 g_variant_unref (value);
724 * g_resource_open_stream:
725 * @resource: A #GResource
726 * @path: A pathname inside the resource
727 * @lookup_flags: A #GResourceLookupFlags
728 * @error: return location for a #GError, or %NULL
730 * Looks for a file at the specified @path in the resource and
731 * returns a #GInputStream that lets you read the data.
733 * @lookup_flags controls the behaviour of the lookup.
735 * Returns: (transfer full): #GInputStream or %NULL on error.
736 * Free the returned object with g_object_unref()
741 g_resource_open_stream (GResource *resource,
743 GResourceLookupFlags lookup_flags,
749 GInputStream *stream, *stream2;
751 if (!do_lookup (resource, path, lookup_flags, NULL, &flags, &data, &data_size, error))
754 stream = g_memory_input_stream_new_from_data (data, data_size, NULL);
755 g_object_set_data_full (G_OBJECT (stream), "g-resource",
756 g_resource_ref (resource),
757 (GDestroyNotify)g_resource_unref);
759 if (flags & G_RESOURCE_FLAGS_COMPRESSED)
761 GZlibDecompressor *decompressor =
762 g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB);
764 stream2 = g_converter_input_stream_new (stream, G_CONVERTER (decompressor));
765 g_object_unref (decompressor);
766 g_object_unref (stream);
774 * g_resource_lookup_data:
775 * @resource: A #GResource
776 * @path: A pathname inside the resource
777 * @lookup_flags: A #GResourceLookupFlags
778 * @error: return location for a #GError, or %NULL
780 * Looks for a file at the specified @path in the resource and
781 * returns a #GBytes that lets you directly access the data in
784 * The data is always followed by a zero byte, so you
785 * can safely use the data as a C string. However, that byte
786 * is not included in the size of the GBytes.
788 * For uncompressed resource files this is a pointer directly into
789 * the resource bundle, which is typically in some readonly data section
790 * in the program binary. For compressed files we allocate memory on
791 * the heap and automatically uncompress the data.
793 * @lookup_flags controls the behaviour of the lookup.
795 * Returns: (transfer full): #GBytes or %NULL on error.
796 * Free the returned object with g_bytes_unref()
801 g_resource_lookup_data (GResource *resource,
803 GResourceLookupFlags lookup_flags,
811 if (!do_lookup (resource, path, lookup_flags, &size, &flags, &data, &data_size, error))
815 return g_bytes_new_with_free_func ("", 0, (GDestroyNotify) g_resource_unref, g_resource_ref (resource));
816 else if (flags & G_RESOURCE_FLAGS_COMPRESSED)
818 char *uncompressed, *d;
820 GConverterResult res;
821 gsize d_size, s_size;
822 gsize bytes_read, bytes_written;
825 GZlibDecompressor *decompressor =
826 g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB);
828 uncompressed = g_malloc (size + 1);
837 res = g_converter_convert (G_CONVERTER (decompressor),
840 G_CONVERTER_INPUT_AT_END,
844 if (res == G_CONVERTER_ERROR)
846 g_free (uncompressed);
847 g_object_unref (decompressor);
849 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_INTERNAL,
850 _("The resource at “%s” failed to decompress"),
856 s_size -= bytes_read;
858 d_size -= bytes_written;
860 while (res != G_CONVERTER_FINISHED);
862 uncompressed[size] = 0; /* Zero terminate */
864 g_object_unref (decompressor);
866 return g_bytes_new_take (uncompressed, size);
869 return g_bytes_new_with_free_func (data, data_size, (GDestroyNotify)g_resource_unref, g_resource_ref (resource));
873 * g_resource_get_info:
874 * @resource: A #GResource
875 * @path: A pathname inside the resource
876 * @lookup_flags: A #GResourceLookupFlags
877 * @size: (out) (optional): a location to place the length of the contents of the file,
878 * or %NULL if the length is not needed
879 * @flags: (out) (optional): a location to place the flags about the file,
880 * or %NULL if the length is not needed
881 * @error: return location for a #GError, or %NULL
883 * Looks for a file at the specified @path in the resource and
884 * if found returns information about it.
886 * @lookup_flags controls the behaviour of the lookup.
888 * Returns: %TRUE if the file was found. %FALSE if there were errors
893 g_resource_get_info (GResource *resource,
895 GResourceLookupFlags lookup_flags,
900 return do_lookup (resource, path, lookup_flags, size, flags, NULL, NULL, error);
904 * g_resource_enumerate_children:
905 * @resource: A #GResource
906 * @path: A pathname inside the resource
907 * @lookup_flags: A #GResourceLookupFlags
908 * @error: return location for a #GError, or %NULL
910 * Returns all the names of children at the specified @path in the resource.
911 * The return result is a %NULL terminated list of strings which should
912 * be released with g_strfreev().
914 * If @path is invalid or does not exist in the #GResource,
915 * %G_RESOURCE_ERROR_NOT_FOUND will be returned.
917 * @lookup_flags controls the behaviour of the lookup.
919 * Returns: (array zero-terminated=1) (transfer full): an array of constant strings
924 g_resource_enumerate_children (GResource *resource,
926 GResourceLookupFlags lookup_flags,
929 gchar local_str[256];
930 const gchar *path_with_slash;
932 gchar *free_path = NULL;
936 * Size of 256 is arbitrarily chosen based on being large enough
937 * for pretty much everything we come across, but not cumbersome
938 * on the stack. It also matches common cacheline sizes.
944 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
945 _("The resource at “%s” does not exist"),
950 path_len = strlen (path);
952 if G_UNLIKELY (path[path_len-1] != '/')
954 if (path_len < sizeof (local_str) - 2)
957 * We got a path that does not have a trailing /. It is not the
958 * ideal use of this API as we require trailing / for our lookup
959 * into gvdb. Some degenerate application configurations can hit
960 * this code path quite a bit, so we try to avoid using the
961 * g_strconcat()/g_free().
963 memcpy (local_str, path, path_len);
964 local_str[path_len] = '/';
965 local_str[path_len+1] = 0;
966 path_with_slash = local_str;
970 path_with_slash = free_path = g_strconcat (path, "/", NULL);
975 path_with_slash = path;
978 children = gvdb_table_list (resource->table, path_with_slash);
981 if (children == NULL)
984 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
985 _("The resource at “%s” does not exist"),
993 static GRWLock resources_lock;
994 static GList *registered_resources;
996 /* This is updated atomically, so we can append to it and check for NULL outside the
997 lock, but all other accesses are done under the write lock */
998 static GStaticResource *lazy_register_resources;
1001 g_resources_register_unlocked (GResource *resource)
1003 registered_resources = g_list_prepend (registered_resources, g_resource_ref (resource));
1007 g_resources_unregister_unlocked (GResource *resource)
1009 if (g_list_find (registered_resources, resource) == NULL)
1011 g_warning ("Tried to remove not registered resource");
1015 registered_resources = g_list_remove (registered_resources, resource);
1016 g_resource_unref (resource);
1021 * g_resources_register:
1022 * @resource: A #GResource
1024 * Registers the resource with the process-global set of resources.
1025 * Once a resource is registered the files in it can be accessed
1026 * with the global resource lookup functions like g_resources_lookup_data().
1031 g_resources_register (GResource *resource)
1033 g_rw_lock_writer_lock (&resources_lock);
1034 g_resources_register_unlocked (resource);
1035 g_rw_lock_writer_unlock (&resources_lock);
1039 * g_resources_unregister:
1040 * @resource: A #GResource
1042 * Unregisters the resource from the process-global set of resources.
1047 g_resources_unregister (GResource *resource)
1049 g_rw_lock_writer_lock (&resources_lock);
1050 g_resources_unregister_unlocked (resource);
1051 g_rw_lock_writer_unlock (&resources_lock);
1055 * g_resources_open_stream:
1056 * @path: A pathname inside the resource
1057 * @lookup_flags: A #GResourceLookupFlags
1058 * @error: return location for a #GError, or %NULL
1060 * Looks for a file at the specified @path in the set of
1061 * globally registered resources and returns a #GInputStream
1062 * that lets you read the data.
1064 * @lookup_flags controls the behaviour of the lookup.
1066 * Returns: (transfer full): #GInputStream or %NULL on error.
1067 * Free the returned object with g_object_unref()
1072 g_resources_open_stream (const gchar *path,
1073 GResourceLookupFlags lookup_flags,
1076 GInputStream *res = NULL;
1078 GInputStream *stream;
1080 if (g_resource_find_overlay (path, open_overlay_stream, &res))
1083 register_lazy_static_resources ();
1085 g_rw_lock_reader_lock (&resources_lock);
1087 for (l = registered_resources; l != NULL; l = l->next)
1089 GResource *r = l->data;
1090 GError *my_error = NULL;
1092 stream = g_resource_open_stream (r, path, lookup_flags, &my_error);
1093 if (stream == NULL &&
1094 g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
1096 g_clear_error (&my_error);
1101 g_propagate_error (error, my_error);
1108 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
1109 _("The resource at “%s” does not exist"),
1112 g_rw_lock_reader_unlock (&resources_lock);
1118 * g_resources_lookup_data:
1119 * @path: A pathname inside the resource
1120 * @lookup_flags: A #GResourceLookupFlags
1121 * @error: return location for a #GError, or %NULL
1123 * Looks for a file at the specified @path in the set of
1124 * globally registered resources and returns a #GBytes that
1125 * lets you directly access the data in memory.
1127 * The data is always followed by a zero byte, so you
1128 * can safely use the data as a C string. However, that byte
1129 * is not included in the size of the GBytes.
1131 * For uncompressed resource files this is a pointer directly into
1132 * the resource bundle, which is typically in some readonly data section
1133 * in the program binary. For compressed files we allocate memory on
1134 * the heap and automatically uncompress the data.
1136 * @lookup_flags controls the behaviour of the lookup.
1138 * Returns: (transfer full): #GBytes or %NULL on error.
1139 * Free the returned object with g_bytes_unref()
1144 g_resources_lookup_data (const gchar *path,
1145 GResourceLookupFlags lookup_flags,
1152 if (g_resource_find_overlay (path, get_overlay_bytes, &res))
1155 register_lazy_static_resources ();
1157 g_rw_lock_reader_lock (&resources_lock);
1159 for (l = registered_resources; l != NULL; l = l->next)
1161 GResource *r = l->data;
1162 GError *my_error = NULL;
1164 data = g_resource_lookup_data (r, path, lookup_flags, &my_error);
1166 g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
1168 g_clear_error (&my_error);
1173 g_propagate_error (error, my_error);
1180 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
1181 _("The resource at “%s” does not exist"),
1184 g_rw_lock_reader_unlock (&resources_lock);
1190 * g_resources_enumerate_children:
1191 * @path: A pathname inside the resource
1192 * @lookup_flags: A #GResourceLookupFlags
1193 * @error: return location for a #GError, or %NULL
1195 * Returns all the names of children at the specified @path in the set of
1196 * globally registered resources.
1197 * The return result is a %NULL terminated list of strings which should
1198 * be released with g_strfreev().
1200 * @lookup_flags controls the behaviour of the lookup.
1202 * Returns: (array zero-terminated=1) (transfer full): an array of constant strings
1207 g_resources_enumerate_children (const gchar *path,
1208 GResourceLookupFlags lookup_flags,
1211 GHashTable *hash = NULL;
1216 /* This will enumerate actual files found in overlay directories but
1217 * will not enumerate the overlays themselves. For example, if we
1218 * have an overlay "/org/gtk=/path/to/files" and we enumerate "/org"
1219 * then we will not see "gtk" in the result set unless it is provided
1220 * by another resource file.
1222 * This is probably not going to be a problem since if we are doing
1223 * such an overlay, we probably will already have that path.
1225 g_resource_find_overlay (path, enumerate_overlay_dir, &hash);
1227 register_lazy_static_resources ();
1229 g_rw_lock_reader_lock (&resources_lock);
1231 for (l = registered_resources; l != NULL; l = l->next)
1233 GResource *r = l->data;
1235 children = g_resource_enumerate_children (r, path, 0, NULL);
1237 if (children != NULL)
1240 /* note: keep in sync with same line above */
1241 hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1243 for (i = 0; children[i] != NULL; i++)
1244 g_hash_table_add (hash, children[i]);
1249 g_rw_lock_reader_unlock (&resources_lock);
1254 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
1255 _("The resource at “%s” does not exist"),
1261 children = (gchar **) g_hash_table_get_keys_as_array (hash, NULL);
1262 g_hash_table_steal_all (hash);
1263 g_hash_table_destroy (hash);
1270 * g_resources_get_info:
1271 * @path: A pathname inside the resource
1272 * @lookup_flags: A #GResourceLookupFlags
1273 * @size: (out) (optional): a location to place the length of the contents of the file,
1274 * or %NULL if the length is not needed
1275 * @flags: (out) (optional): a location to place the #GResourceFlags about the file,
1276 * or %NULL if the flags are not needed
1277 * @error: return location for a #GError, or %NULL
1279 * Looks for a file at the specified @path in the set of
1280 * globally registered resources and if found returns information about it.
1282 * @lookup_flags controls the behaviour of the lookup.
1284 * Returns: %TRUE if the file was found. %FALSE if there were errors
1289 g_resources_get_info (const gchar *path,
1290 GResourceLookupFlags lookup_flags,
1295 gboolean res = FALSE;
1300 if (g_resource_find_overlay (path, get_overlay_info, &info))
1305 *flags = info.flags;
1310 register_lazy_static_resources ();
1312 g_rw_lock_reader_lock (&resources_lock);
1314 for (l = registered_resources; l != NULL; l = l->next)
1316 GResource *r = l->data;
1317 GError *my_error = NULL;
1319 r_res = g_resource_get_info (r, path, lookup_flags, size, flags, &my_error);
1321 g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
1323 g_clear_error (&my_error);
1328 g_propagate_error (error, my_error);
1335 g_set_error (error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND,
1336 _("The resource at “%s” does not exist"),
1339 g_rw_lock_reader_unlock (&resources_lock);
1344 /* This code is to handle registration of resources very early, from a constructor.
1345 * At that point we'd like to do minimal work, to avoid ordering issues. For instance,
1346 * we're not allowed to use g_malloc, as the user need to be able to call g_mem_set_vtable
1347 * before the first call to g_malloc.
1349 * So, what we do at construction time is that we just register a static structure on
1350 * a list of resources that need to be initialized, and then later, when doing any lookups
1351 * in the global list of registered resources, or when getting a reference to the
1352 * lazily initialized resource we lazily create and register all the GResources on
1355 * To avoid having to use locks in the constructor, and having to grab the writer lock
1356 * when checking the lazy registering list we update lazy_register_resources in
1357 * a lock-less fashion (atomic prepend-only, atomic replace with NULL). However, all
1358 * operations except:
1359 * * check if there are any resources to lazily initialize
1360 * * Add a static resource to the lazy init list
1361 * Do use the full writer lock for protection.
1365 register_lazy_static_resources_unlocked (void)
1367 GStaticResource *list = g_atomic_pointer_get (&lazy_register_resources);
1369 while (!g_atomic_pointer_compare_and_exchange_full (&lazy_register_resources, list, NULL, &list))
1372 while (list != NULL)
1374 GBytes *bytes = g_bytes_new_static (list->data, list->data_len);
1375 GResource *resource = g_resource_new_from_data (bytes, NULL);
1378 g_resources_register_unlocked (resource);
1379 g_atomic_pointer_set (&list->resource, resource);
1381 g_bytes_unref (bytes);
1388 register_lazy_static_resources (void)
1390 if (g_atomic_pointer_get (&lazy_register_resources) == NULL)
1393 g_rw_lock_writer_lock (&resources_lock);
1394 register_lazy_static_resources_unlocked ();
1395 g_rw_lock_writer_unlock (&resources_lock);
1399 * g_static_resource_init:
1400 * @static_resource: pointer to a static #GStaticResource
1402 * Initializes a GResource from static data using a
1405 * This is normally used by code generated by
1406 * [glib-compile-resources][glib-compile-resources]
1407 * and is not typically used by other code.
1412 g_static_resource_init (GStaticResource *static_resource)
1414 GStaticResource *next;
1418 next = g_atomic_pointer_get (&lazy_register_resources);
1419 static_resource->next = next;
1421 while (!g_atomic_pointer_compare_and_exchange (&lazy_register_resources, next, static_resource));
1425 * g_static_resource_fini:
1426 * @static_resource: pointer to a static #GStaticResource
1428 * Finalized a GResource initialized by g_static_resource_init().
1430 * This is normally used by code generated by
1431 * [glib-compile-resources][glib-compile-resources]
1432 * and is not typically used by other code.
1437 g_static_resource_fini (GStaticResource *static_resource)
1439 GResource *resource;
1441 g_rw_lock_writer_lock (&resources_lock);
1443 register_lazy_static_resources_unlocked ();
1445 resource = g_atomic_pointer_exchange (&static_resource->resource, NULL);
1448 /* There should be at least two references to the resource now: one for
1449 * static_resource->resource, and one in the registered_resources list. */
1450 g_assert (g_atomic_int_get (&resource->ref_count) >= 2);
1452 g_resources_unregister_unlocked (resource);
1453 g_resource_unref (resource);
1456 g_rw_lock_writer_unlock (&resources_lock);
1460 * g_static_resource_get_resource:
1461 * @static_resource: pointer to a static #GStaticResource
1463 * Gets the GResource that was registered by a call to g_static_resource_init().
1465 * This is normally used by code generated by
1466 * [glib-compile-resources][glib-compile-resources]
1467 * and is not typically used by other code.
1469 * Returns: (transfer none): a #GResource
1474 g_static_resource_get_resource (GStaticResource *static_resource)
1476 register_lazy_static_resources ();
1478 return g_atomic_pointer_get (&static_resource->resource);