2 * Copyright © 2007, 2008 Ryan Lortie
3 * Copyright © 2010 Codethink Limited
4 * Copyright © 2022 Endless OS Foundation, LLC
6 * SPDX-License-Identifier: LGPL-2.1-or-later
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
24 #include <glib/gvariant-core.h>
26 #include <glib/gvariant-internal.h>
27 #include <glib/gvariant-serialiser.h>
28 #include <glib/gtestutils.h>
29 #include <glib/gbitlock.h>
30 #include <glib/gatomic.h>
31 #include <glib/gbytes.h>
32 #include <glib/gslice.h>
33 #include <glib/gmem.h>
34 #include <glib/grefcount.h>
37 #include "glib_trace.h"
40 * This file includes the structure definition for GVariant and a small
41 * set of functions that are allowed to access the structure directly.
43 * This minimises the amount of code that can possibly touch a GVariant
44 * structure directly to a few simple fundamental operations. These few
45 * operations are written to be completely threadsafe with respect to
46 * all possible outside access. This means that we only need to be
47 * concerned about thread safety issues in this one small file.
49 * Most GVariant API functions are in gvariant.c.
55 * #GVariant is an opaque data structure and can only be accessed
56 * using the following functions.
61 /* see below for field member documentation */
63 GVariantTypeInfo *type_info;
72 gsize ordered_offsets_up_to;
73 gsize checked_offsets_up_to;
84 gatomicrefcount ref_count;
90 * There are two primary forms of GVariant instances: "serialized form"
93 * "serialized form": A serialized GVariant instance stores its value in
94 * the GVariant serialization format. All
95 * basic-typed instances (ie: non-containers) are in
96 * serialized format, as are some containers.
98 * "tree form": Some containers are in "tree form". In this case,
99 * instead of containing the serialized data for the
100 * container, the instance contains an array of pointers to
101 * the child values of the container (thus forming a tree).
103 * It is possible for an instance to transition from tree form to
104 * serialized form. This happens, implicitly, if the serialized data is
105 * requested (eg: via g_variant_get_data()). Serialized form instances
106 * never transition into tree form.
109 * The fields of the structure are documented here:
111 * type_info: this is a reference to a GVariantTypeInfo describing the
112 * type of the instance. When the instance is freed, this
113 * reference must be released with g_variant_type_info_unref().
115 * The type_info field never changes during the life of the
116 * instance, so it can be accessed without a lock.
118 * size: this is the size of the serialized form for the instance, if it
119 * is known. If the instance is in serialized form then it is, by
120 * definition, known. If the instance is in tree form then it may
121 * be unknown (in which case it is -1). It is possible for the
122 * size to be known when in tree form if, for example, the user
123 * has called g_variant_get_size() without calling
124 * g_variant_get_data(). Additionally, even when the user calls
125 * g_variant_get_data() the size of the data must first be
126 * determined so that a large enough buffer can be allocated for
129 * Once the size is known, it can never become unknown again.
130 * g_variant_ensure_size() is used to ensure that the size is in
131 * the known state -- it calculates the size if needed. After
132 * that, the size field can be accessed without a lock.
134 * contents: a union containing either the information associated with
135 * holding a value in serialized form or holding a value in
138 * .serialised: Only valid when the instance is in serialized form.
140 * Since an instance can never transition away from
141 * serialized form, once these fields are set, they will
142 * never be changed. It is therefore valid to access
143 * them without holding a lock.
145 * .bytes: the #GBytes that contains the memory pointed to by
146 * .data, or %NULL if .data is %NULL. In the event that
147 * the instance was deserialized from another instance,
148 * then the bytes will be shared by both of them. When
149 * the instance is freed, this reference must be released
150 * with g_bytes_unref().
152 * .data: the serialized data (of size 'size') of the instance.
153 * This pointer should not be freed or modified in any way.
154 * #GBytes is responsible for memory management.
156 * This pointer may be %NULL in two cases:
158 * - if the serialized size of the instance is 0
160 * - if the instance is of a fixed-sized type and was
161 * deserialized out of a corrupted container such that
162 * the container contains too few bytes to point to the
163 * entire proper fixed-size of this instance. In this
164 * case, 'size' will still be equal to the proper fixed
165 * size, but this pointer will be %NULL. This is exactly
166 * the reason that g_variant_get_data() sometimes returns
167 * %NULL. For all other calls, the effect should be as
168 * if .data pointed to the appropriate number of nul
171 * .ordered_offsets_up_to: If ordered_offsets_up_to == n this means that all
172 * the frame offsets up to and including the frame
173 * offset determining the end of element n are in
174 * order. This guarantees that the bytes of element
175 * n don't overlap with any previous element.
177 * For trusted data this is set to G_MAXSIZE and we
178 * don't check that the frame offsets are in order.
180 * Note: This doesn't imply the offsets are good in
181 * any way apart from their ordering. In particular
182 * offsets may be out of bounds for this value or
183 * may imply that the data overlaps the frame
184 * offsets themselves.
186 * This field is only relevant for arrays of non
187 * fixed width types and for tuples.
189 * .checked_offsets_up_to: Similarly to .ordered_offsets_up_to, this stores
190 * the index of the highest element, n, whose frame
191 * offsets (and all the preceding frame offsets)
192 * have been checked for validity.
194 * It is always the case that
195 * .checked_offsets_up_to ≥ .ordered_offsets_up_to.
197 * If .checked_offsets_up_to == .ordered_offsets_up_to,
198 * then a bad offset has not been found so far.
200 * If .checked_offsets_up_to > .ordered_offsets_up_to,
201 * then a bad offset has been found at
202 * (.ordered_offsets_up_to + 1).
204 * This field is only relevant for arrays of non
205 * fixed width types and for tuples.
207 * .tree: Only valid when the instance is in tree form.
209 * Note that accesses from other threads could result in
210 * conversion of the instance from tree form to serialized form
211 * at any time. For this reason, the instance lock must always
212 * be held while performing any operations on 'contents.tree'.
214 * .children: the array of the child instances of this instance.
215 * When the instance is freed (or converted to serialized
216 * form) then each child must have g_variant_unref()
217 * called on it and the array must be freed using
220 * .n_children: the number of items in the .children array.
222 * state: a bitfield describing the state of the instance. It is a
223 * bitwise-or of the following STATE_* constants:
225 * STATE_LOCKED: the instance lock is held. This is the bit used by
228 * STATE_SERIALISED: the instance is in serialized form. If this
229 * flag is not set then the instance is in tree
232 * STATE_TRUSTED: for serialized form instances, this means that the
233 * serialized data is known to be in normal form (ie:
236 * For tree form instances, this means that all of the
237 * child instances in the contents.tree.children array
238 * are trusted. This means that if the container is
239 * serialized then the resulting data will be in
242 * If this flag is unset it does not imply that the
243 * data is corrupted. It merely means that we're not
244 * sure that it's valid. See g_variant_is_trusted().
246 * STATE_FLOATING: if this flag is set then the object has a floating
247 * reference. See g_variant_ref_sink().
249 * ref_count: the reference count of the instance
251 * depth: the depth of the GVariant in a hierarchy of nested containers,
252 * increasing with the level of nesting. The top-most GVariant has depth
253 * zero. This is used to avoid recursing too deeply and overflowing the
254 * stack when handling deeply nested untrusted serialized GVariants.
256 #define STATE_LOCKED 1
257 #define STATE_SERIALISED 2
258 #define STATE_TRUSTED 4
259 #define STATE_FLOATING 8
264 * @value: a #GVariant
266 * Locks @value for performing sensitive operations.
269 g_variant_lock (GVariant *value)
271 g_bit_lock (&value->state, 0);
276 * @value: a #GVariant
278 * Unlocks @value after performing sensitive operations.
281 g_variant_unlock (GVariant *value)
283 g_bit_unlock (&value->state, 0);
287 * g_variant_release_children:
288 * @value: a #GVariant
290 * Releases the reference held on each child in the 'children' array of
291 * @value and frees the array itself. @value must be in tree form.
293 * This is done when freeing a tree-form instance or converting it to
296 * The current thread must hold the lock on @value.
299 g_variant_release_children (GVariant *value)
303 g_assert (value->state & STATE_LOCKED);
304 g_assert (~value->state & STATE_SERIALISED);
306 for (i = 0; i < value->contents.tree.n_children; i++)
307 g_variant_unref (value->contents.tree.children[i]);
309 g_free (value->contents.tree.children);
312 /* This begins the main body of the recursive serializer.
314 * There are 3 functions here that work as a team with the serializer to
315 * get things done. g_variant_store() has a trivial role, but as a
316 * public API function, it has its definition elsewhere.
318 * Note that "serialization" of an instance does not mean that the
319 * instance is converted to serialized form -- it means that the
320 * serialized form of an instance is written to an external buffer.
321 * g_variant_ensure_serialised() (which is not part of this set of
322 * functions) is the function that is responsible for converting an
323 * instance to serialized form.
325 * We are only concerned here with container types since non-container
326 * instances are always in serialized form. For these instances,
327 * storing their serialized form merely involves a memcpy().
329 * Serialization is a two-step process. First, the size of the
330 * serialized data must be calculated so that an appropriately-sized
331 * buffer can be allocated. Second, the data is written into the
334 * Determining the size:
335 * The process of determining the size is triggered by a call to
336 * g_variant_ensure_size() on a container. This invokes the
337 * serializer code to determine the size. The serializer is passed
338 * g_variant_fill_gvs() as a callback.
340 * g_variant_fill_gvs() is called by the serializer on each child of
341 * the container which, in turn, calls g_variant_ensure_size() on
342 * itself and fills in the result of its own size calculation.
344 * The serializer uses the size information from the children to
345 * calculate the size needed for the entire container.
348 * After the buffer has been allocated, g_variant_serialise() is
349 * called on the container. This invokes the serializer code to write
350 * the bytes to the container. The serializer is, again, passed
351 * g_variant_fill_gvs() as a callback.
353 * This time, when g_variant_fill_gvs() is called for each child, the
354 * child is given a pointer to a sub-region of the allocated buffer
355 * where it should write its data. This is done by calling
356 * g_variant_store(). In the event that the instance is in serialized
357 * form this means a memcpy() of the serialized data into the
358 * allocated buffer. In the event that the instance is in tree form
359 * this means a recursive call back into g_variant_serialise().
362 * The forward declaration here allows corecursion via callback:
364 static void g_variant_fill_gvs (GVariantSerialised *, gpointer);
367 * g_variant_ensure_size:
368 * @value: a #GVariant
370 * Ensures that the ->size field of @value is filled in properly. This
371 * must be done as a precursor to any serialization of the value in
372 * order to know how large of a buffer is needed to store the data.
374 * The current thread must hold the lock on @value.
377 g_variant_ensure_size (GVariant *value)
379 g_assert (value->state & STATE_LOCKED);
381 if (value->size == (gsize) -1)
386 children = (gpointer *) value->contents.tree.children;
387 n_children = value->contents.tree.n_children;
388 value->size = g_variant_serialiser_needed_size (value->type_info,
390 children, n_children);
395 * g_variant_to_serialised:
396 * @value: a #GVariant
398 * Gets a GVariantSerialised for a GVariant in state STATE_SERIALISED.
400 inline static GVariantSerialised
401 g_variant_to_serialised (GVariant *value)
403 g_assert (value->state & STATE_SERIALISED);
405 GVariantSerialised serialised = {
407 (gpointer) value->contents.serialised.data,
410 value->contents.serialised.ordered_offsets_up_to,
411 value->contents.serialised.checked_offsets_up_to,
418 * g_variant_serialise:
419 * @value: a #GVariant
420 * @data: an appropriately-sized buffer
422 * Serializes @value into @data. @value must be in tree form.
424 * No change is made to @value.
426 * The current thread must hold the lock on @value.
429 g_variant_serialise (GVariant *value,
432 GVariantSerialised serialised = { 0, };
436 g_assert (~value->state & STATE_SERIALISED);
437 g_assert (value->state & STATE_LOCKED);
439 serialised.type_info = value->type_info;
440 serialised.size = value->size;
441 serialised.data = data;
442 serialised.depth = value->depth;
443 serialised.ordered_offsets_up_to = 0;
444 serialised.checked_offsets_up_to = 0;
446 children = (gpointer *) value->contents.tree.children;
447 n_children = value->contents.tree.n_children;
449 g_variant_serialiser_serialise (serialised, g_variant_fill_gvs,
450 children, n_children);
454 * g_variant_fill_gvs:
455 * @serialised: a pointer to a #GVariantSerialised
456 * @data: a #GVariant instance
458 * This is the callback that is passed by a tree-form container instance
459 * to the serializer. This callback gets called on each child of the
460 * container. Each child is responsible for performing the following
463 * - reporting its type
465 * - reporting its serialized size (requires knowing the size first)
467 * - possibly storing its serialized form into the provided buffer
470 g_variant_fill_gvs (GVariantSerialised *serialised,
473 GVariant *value = data;
475 g_variant_lock (value);
476 g_variant_ensure_size (value);
477 g_variant_unlock (value);
479 if (serialised->type_info == NULL)
480 serialised->type_info = value->type_info;
481 g_assert (serialised->type_info == value->type_info);
483 if (serialised->size == 0)
484 serialised->size = value->size;
485 g_assert (serialised->size == value->size);
486 serialised->depth = value->depth;
488 if (value->state & STATE_SERIALISED)
490 serialised->ordered_offsets_up_to = value->contents.serialised.ordered_offsets_up_to;
491 serialised->checked_offsets_up_to = value->contents.serialised.checked_offsets_up_to;
495 serialised->ordered_offsets_up_to = 0;
496 serialised->checked_offsets_up_to = 0;
499 if (serialised->data)
500 /* g_variant_store() is a public API, so it
501 * it will reacquire the lock if it needs to.
503 g_variant_store (value, serialised->data);
506 /* this ends the main body of the recursive serializer */
509 * g_variant_ensure_serialised:
510 * @value: a #GVariant
512 * Ensures that @value is in serialized form.
514 * If @value is in tree form then this function ensures that the
515 * serialized size is known and then allocates a buffer of that size and
516 * serializes the instance into the buffer. The 'children' array is
517 * then released and the instance is set to serialized form based on the
518 * contents of the buffer.
520 * The current thread must hold the lock on @value.
523 g_variant_ensure_serialised (GVariant *value)
525 g_assert (value->state & STATE_LOCKED);
527 if (~value->state & STATE_SERIALISED)
532 TRACE(GLIB_VARIANT_START_SERIALISE(value, value->type_info));
533 g_variant_ensure_size (value);
534 data = g_malloc (value->size);
535 g_variant_serialise (value, data);
537 g_variant_release_children (value);
539 bytes = g_bytes_new_take (data, value->size);
540 value->contents.serialised.data = g_bytes_get_data (bytes, NULL);
541 value->contents.serialised.bytes = bytes;
542 value->contents.serialised.ordered_offsets_up_to = G_MAXSIZE;
543 value->contents.serialised.checked_offsets_up_to = G_MAXSIZE;
544 value->state |= STATE_SERIALISED;
545 TRACE(GLIB_VARIANT_END_SERIALISE(value, value->type_info));
551 * @type: the type of the new instance
552 * @serialised: if the instance will be in serialised form
553 * @trusted: if the instance will be trusted
555 * Allocates a #GVariant instance and does some common work (such as
556 * looking up and filling in the type info), setting the state field,
557 * and setting the ref_count to 1.
559 * Returns: a new #GVariant with a floating reference
562 g_variant_alloc (const GVariantType *type,
568 value = g_slice_new (GVariant);
569 value->type_info = g_variant_type_info_get (type);
570 value->state = (serialised ? STATE_SERIALISED : 0) |
571 (trusted ? STATE_TRUSTED : 0) |
573 value->size = (gssize) -1;
574 g_atomic_ref_count_init (&value->ref_count);
581 * g_variant_new_from_bytes:
582 * @type: a #GVariantType
584 * @trusted: if the contents of @bytes are trusted
586 * Constructs a new serialized-mode #GVariant instance. This is the
587 * inner interface for creation of new serialized values that gets
588 * called from various functions in gvariant.c.
590 * A reference is taken on @bytes.
592 * The data in @bytes must be aligned appropriately for the @type being loaded.
593 * Otherwise this function will internally create a copy of the memory (since
594 * GLib 2.60) or (in older versions) fail and exit the process.
596 * Returns: (transfer none): a new #GVariant with a floating reference
601 g_variant_new_from_bytes (const GVariantType *type,
608 GBytes *owned_bytes = NULL;
609 GVariantSerialised serialised;
611 value = g_variant_alloc (type, TRUE, trusted);
613 g_variant_type_info_query (value->type_info,
616 /* Ensure the alignment is correct. This is a huge performance hit if it’s
617 * not correct, but that’s better than aborting if a caller provides data
618 * with the wrong alignment (which is likely to happen very occasionally, and
619 * only cause an abort on some architectures — so is unlikely to be caught
620 * in testing). Callers can always actively ensure they use the correct
621 * alignment to avoid the performance hit. */
622 serialised.type_info = value->type_info;
623 serialised.data = (guchar *) g_bytes_get_data (bytes, &serialised.size);
624 serialised.depth = 0;
625 serialised.ordered_offsets_up_to = trusted ? G_MAXSIZE : 0;
626 serialised.checked_offsets_up_to = trusted ? G_MAXSIZE : 0;
628 if (!g_variant_serialised_check (serialised))
630 #ifdef HAVE_POSIX_MEMALIGN
631 gpointer aligned_data = NULL;
632 gsize aligned_size = g_bytes_get_size (bytes);
634 /* posix_memalign() requires the alignment to be a multiple of
635 * sizeof(void*), and a power of 2. See g_variant_type_info_query() for
636 * details on the alignment format. */
637 if (posix_memalign (&aligned_data, MAX (sizeof (void *), alignment + 1),
639 g_error ("posix_memalign failed");
641 if (aligned_size != 0)
642 memcpy (aligned_data, g_bytes_get_data (bytes, NULL), aligned_size);
644 bytes = owned_bytes = g_bytes_new_with_free_func (aligned_data,
649 /* NOTE: there may be platforms that lack posix_memalign() and also
650 * have malloc() that returns non-8-aligned. if so, we need to try
653 bytes = owned_bytes = g_bytes_new (g_bytes_get_data (bytes, NULL),
654 g_bytes_get_size (bytes));
658 value->contents.serialised.bytes = g_bytes_ref (bytes);
660 if (size && g_bytes_get_size (bytes) != size)
662 /* Creating a fixed-sized GVariant with a bytes of the wrong
665 * We should do the equivalent of pulling a fixed-sized child out
666 * of a brozen container (ie: data is NULL size is equal to the correct
669 value->contents.serialised.data = NULL;
674 value->contents.serialised.data = g_bytes_get_data (bytes, &value->size);
677 value->contents.serialised.ordered_offsets_up_to = trusted ? G_MAXSIZE : 0;
678 value->contents.serialised.checked_offsets_up_to = trusted ? G_MAXSIZE : 0;
680 g_clear_pointer (&owned_bytes, g_bytes_unref);
682 TRACE(GLIB_VARIANT_FROM_BUFFER(value, value->type_info, value->ref_count, value->state));
690 * g_variant_new_from_children:
691 * @type: a #GVariantType
692 * @children: an array of #GVariant pointers. Consumed.
693 * @n_children: the length of @children
694 * @trusted: %TRUE if every child in @children is trusted
696 * Constructs a new tree-mode #GVariant instance. This is the inner
697 * interface for creation of new serialized values that gets called from
698 * various functions in gvariant.c.
700 * @children is consumed by this function. g_free() will be called on
701 * it some time later.
703 * Returns: a new #GVariant with a floating reference
706 g_variant_new_from_children (const GVariantType *type,
713 value = g_variant_alloc (type, FALSE, trusted);
714 value->contents.tree.children = children;
715 value->contents.tree.n_children = n_children;
716 TRACE(GLIB_VARIANT_FROM_CHILDREN(value, value->type_info, value->ref_count, value->state));
722 * g_variant_get_type_info:
723 * @value: a #GVariant
725 * Returns the #GVariantTypeInfo corresponding to the type of @value. A
726 * reference is not added, so the return value is only good for the
727 * duration of the life of @value.
729 * Returns: the #GVariantTypeInfo for @value
732 g_variant_get_type_info (GVariant *value)
734 return value->type_info;
738 * g_variant_is_trusted:
739 * @value: a #GVariant
741 * Determines if @value is trusted by #GVariant to contain only
742 * fully-valid data. All values constructed solely via #GVariant APIs
743 * are trusted, but values containing data read in from other sources
744 * are usually not trusted.
746 * The main advantage of trusted data is that certain checks can be
747 * skipped. For example, we don't need to check that a string is
748 * properly nul-terminated or that an object path is actually a
749 * properly-formatted object path.
751 * Returns: if @value is trusted
754 g_variant_is_trusted (GVariant *value)
756 return (value->state & STATE_TRUSTED) != 0;
760 * g_variant_get_depth:
761 * @value: a #GVariant
763 * Gets the nesting depth of a #GVariant. This is 0 for a #GVariant with no
766 * Returns: nesting depth of @value
769 g_variant_get_depth (GVariant *value)
778 * @value: a #GVariant
780 * Decreases the reference count of @value. When its reference count
781 * drops to 0, the memory used by the variant is freed.
786 g_variant_unref (GVariant *value)
788 g_return_if_fail (value != NULL);
790 TRACE(GLIB_VARIANT_UNREF(value, value->type_info, value->ref_count, value->state));
792 if (g_atomic_ref_count_dec (&value->ref_count))
794 if G_UNLIKELY (value->state & STATE_LOCKED)
795 g_critical ("attempting to free a locked GVariant instance. "
796 "This should never happen.");
798 value->state |= STATE_LOCKED;
800 g_variant_type_info_unref (value->type_info);
802 if (value->state & STATE_SERIALISED)
803 g_bytes_unref (value->contents.serialised.bytes);
805 g_variant_release_children (value);
807 memset (value, 0, sizeof (GVariant));
808 g_slice_free (GVariant, value);
814 * @value: a #GVariant
816 * Increases the reference count of @value.
818 * Returns: the same @value
823 g_variant_ref (GVariant *value)
825 g_return_val_if_fail (value != NULL, NULL);
827 TRACE(GLIB_VARIANT_REF(value, value->type_info, value->ref_count, value->state));
829 g_atomic_ref_count_inc (&value->ref_count);
835 * g_variant_ref_sink:
836 * @value: a #GVariant
838 * #GVariant uses a floating reference count system. All functions with
839 * names starting with `g_variant_new_` return floating
842 * Calling g_variant_ref_sink() on a #GVariant with a floating reference
843 * will convert the floating reference into a full reference. Calling
844 * g_variant_ref_sink() on a non-floating #GVariant results in an
845 * additional normal reference being added.
847 * In other words, if the @value is floating, then this call "assumes
848 * ownership" of the floating reference, converting it to a normal
849 * reference. If the @value is not floating, then this call adds a
850 * new normal reference increasing the reference count by one.
852 * All calls that result in a #GVariant instance being inserted into a
853 * container will call g_variant_ref_sink() on the instance. This means
854 * that if the value was just created (and has only its floating
855 * reference) then the container will assume sole ownership of the value
856 * at that point and the caller will not need to unreference it. This
857 * makes certain common styles of programming much easier while still
858 * maintaining normal refcounting semantics in situations where values
861 * Returns: the same @value
866 g_variant_ref_sink (GVariant *value)
868 g_return_val_if_fail (value != NULL, NULL);
869 g_return_val_if_fail (!g_atomic_ref_count_compare (&value->ref_count, 0), NULL);
871 g_variant_lock (value);
873 TRACE(GLIB_VARIANT_REF_SINK(value, value->type_info, value->ref_count, value->state, value->state & STATE_FLOATING));
875 if (~value->state & STATE_FLOATING)
876 g_variant_ref (value);
878 value->state &= ~STATE_FLOATING;
880 g_variant_unlock (value);
886 * g_variant_take_ref:
887 * @value: a #GVariant
889 * If @value is floating, sink it. Otherwise, do nothing.
891 * Typically you want to use g_variant_ref_sink() in order to
892 * automatically do the correct thing with respect to floating or
893 * non-floating references, but there is one specific scenario where
894 * this function is helpful.
896 * The situation where this function is helpful is when creating an API
897 * that allows the user to provide a callback function that returns a
898 * #GVariant. We certainly want to allow the user the flexibility to
899 * return a non-floating reference from this callback (for the case
900 * where the value that is being returned already exists).
902 * At the same time, the style of the #GVariant API makes it likely that
903 * for newly-created #GVariant instances, the user can be saved some
904 * typing if they are allowed to return a #GVariant with a floating
907 * Using this function on the return value of the user's callback allows
908 * the user to do whichever is more convenient for them. The caller
909 * will always receives exactly one full reference to the value: either
910 * the one that was returned in the first place, or a floating reference
911 * that has been converted to a full reference.
913 * This function has an odd interaction when combined with
914 * g_variant_ref_sink() running at the same time in another thread on
915 * the same #GVariant instance. If g_variant_ref_sink() runs first then
916 * the result will be that the floating reference is converted to a hard
917 * reference. If g_variant_take_ref() runs first then the result will
918 * be that the floating reference is converted to a hard reference and
919 * an additional reference on top of that one is added. It is best to
920 * avoid this situation.
922 * Returns: the same @value
925 g_variant_take_ref (GVariant *value)
927 g_return_val_if_fail (value != NULL, NULL);
928 g_return_val_if_fail (!g_atomic_ref_count_compare (&value->ref_count, 0), NULL);
930 TRACE(GLIB_VARIANT_TAKE_REF(value, value->type_info, value->ref_count, value->state, value->state & STATE_FLOATING));
931 g_atomic_int_and (&value->state, ~STATE_FLOATING);
937 * g_variant_is_floating:
938 * @value: a #GVariant
940 * Checks whether @value has a floating reference count.
942 * This function should only ever be used to assert that a given variant
943 * is or is not floating, or for debug purposes. To acquire a reference
944 * to a variant that might be floating, always use g_variant_ref_sink()
945 * or g_variant_take_ref().
947 * See g_variant_ref_sink() for more information about floating reference
950 * Returns: whether @value is floating
955 g_variant_is_floating (GVariant *value)
957 g_return_val_if_fail (value != NULL, FALSE);
959 return (value->state & STATE_FLOATING) != 0;
963 * g_variant_get_size:
964 * @value: a #GVariant instance
966 * Determines the number of bytes that would be required to store @value
967 * with g_variant_store().
969 * If @value has a fixed-sized type then this function always returned
972 * In the case that @value is already in serialized form or the size has
973 * already been calculated (ie: this function has been called before)
974 * then this function is O(1). Otherwise, the size is calculated, an
975 * operation which is approximately O(n) in the number of values
978 * Returns: the serialized size of @value
983 g_variant_get_size (GVariant *value)
985 g_variant_lock (value);
986 g_variant_ensure_size (value);
987 g_variant_unlock (value);
993 * g_variant_get_data:
994 * @value: a #GVariant instance
996 * Returns a pointer to the serialized form of a #GVariant instance.
997 * The returned data may not be in fully-normalised form if read from an
998 * untrusted source. The returned data must not be freed; it remains
999 * valid for as long as @value exists.
1001 * If @value is a fixed-sized value that was deserialized from a
1002 * corrupted serialized container then %NULL may be returned. In this
1003 * case, the proper thing to do is typically to use the appropriate
1004 * number of nul bytes in place of @value. If @value is not fixed-sized
1005 * then %NULL is never returned.
1007 * In the case that @value is already in serialized form, this function
1008 * is O(1). If the value is not already in serialized form,
1009 * serialization occurs implicitly and is approximately O(n) in the size
1012 * To deserialize the data returned by this function, in addition to the
1013 * serialized data, you must know the type of the #GVariant, and (if the
1014 * machine might be different) the endianness of the machine that stored
1015 * it. As a result, file formats or network messages that incorporate
1016 * serialized #GVariants must include this information either
1017 * implicitly (for instance "the file always contains a
1018 * %G_VARIANT_TYPE_VARIANT and it is always in little-endian order") or
1019 * explicitly (by storing the type and/or endianness in addition to the
1022 * Returns: (transfer none): the serialized form of @value, or %NULL
1027 g_variant_get_data (GVariant *value)
1029 g_variant_lock (value);
1030 g_variant_ensure_serialised (value);
1031 g_variant_unlock (value);
1033 return value->contents.serialised.data;
1037 * g_variant_get_data_as_bytes:
1038 * @value: a #GVariant
1040 * Returns a pointer to the serialized form of a #GVariant instance.
1041 * The semantics of this function are exactly the same as
1042 * g_variant_get_data(), except that the returned #GBytes holds
1043 * a reference to the variant data.
1045 * Returns: (transfer full): A new #GBytes representing the variant data
1050 g_variant_get_data_as_bytes (GVariant *value)
1052 const gchar *bytes_data;
1057 g_variant_lock (value);
1058 g_variant_ensure_serialised (value);
1059 g_variant_unlock (value);
1061 bytes_data = g_bytes_get_data (value->contents.serialised.bytes, &bytes_size);
1062 data = value->contents.serialised.data;
1067 g_assert (size == 0);
1071 if (data == bytes_data && size == bytes_size)
1072 return g_bytes_ref (value->contents.serialised.bytes);
1074 return g_bytes_new_from_bytes (value->contents.serialised.bytes,
1075 data - bytes_data, size);
1080 * g_variant_n_children:
1081 * @value: a container #GVariant
1083 * Determines the number of children in a container #GVariant instance.
1084 * This includes variants, maybes, arrays, tuples and dictionary
1085 * entries. It is an error to call this function on any other type of
1088 * For variants, the return value is always 1. For values with maybe
1089 * types, it is always zero or one. For arrays, it is the length of the
1090 * array. For tuples it is the number of tuple items (which depends
1091 * only on the type). For dictionary entries, it is always 2
1093 * This function is O(1).
1095 * Returns: the number of children in the container
1100 g_variant_n_children (GVariant *value)
1104 g_variant_lock (value);
1106 if (value->state & STATE_SERIALISED)
1107 n_children = g_variant_serialised_n_children (
1108 g_variant_to_serialised (value));
1110 n_children = value->contents.tree.n_children;
1112 g_variant_unlock (value);
1118 * g_variant_get_child_value:
1119 * @value: a container #GVariant
1120 * @index_: the index of the child to fetch
1122 * Reads a child item out of a container #GVariant instance. This
1123 * includes variants, maybes, arrays, tuples and dictionary
1124 * entries. It is an error to call this function on any other type of
1127 * It is an error if @index_ is greater than the number of child items
1128 * in the container. See g_variant_n_children().
1130 * The returned value is never floating. You should free it with
1131 * g_variant_unref() when you're done with it.
1133 * Note that values borrowed from the returned child are not guaranteed to
1134 * still be valid after the child is freed even if you still hold a reference
1135 * to @value, if @value has not been serialized at the time this function is
1136 * called. To avoid this, you can serialize @value by calling
1137 * g_variant_get_data() and optionally ignoring the return value.
1139 * There may be implementation specific restrictions on deeply nested values,
1140 * which would result in the unit tuple being returned as the child value,
1141 * instead of further nested children. #GVariant is guaranteed to handle
1142 * nesting up to at least 64 levels.
1144 * This function is O(1).
1146 * Returns: (transfer full): the child at the specified index
1151 g_variant_get_child_value (GVariant *value,
1154 g_return_val_if_fail (value->depth < G_MAXSIZE, NULL);
1156 if (~g_atomic_int_get (&value->state) & STATE_SERIALISED)
1158 /* g_variant_serialised_get_child() does its own checks on index_ */
1159 g_return_val_if_fail (index_ < g_variant_n_children (value), NULL);
1161 g_variant_lock (value);
1163 if (~value->state & STATE_SERIALISED)
1167 child = g_variant_ref (value->contents.tree.children[index_]);
1168 g_variant_unlock (value);
1173 g_variant_unlock (value);
1177 GVariantSerialised serialised = g_variant_to_serialised (value);
1178 GVariantSerialised s_child;
1181 /* get the serializer to extract the serialized data for the child
1182 * from the serialized data for the container
1184 s_child = g_variant_serialised_get_child (serialised, index_);
1186 /* Update the cached ordered_offsets_up_to, since @serialised will be thrown away when this function exits */
1187 value->contents.serialised.ordered_offsets_up_to = MAX (value->contents.serialised.ordered_offsets_up_to, serialised.ordered_offsets_up_to);
1188 value->contents.serialised.checked_offsets_up_to = MAX (value->contents.serialised.checked_offsets_up_to, serialised.checked_offsets_up_to);
1190 /* Check whether this would cause nesting too deep. If so, return a fake
1191 * child. The only situation we expect this to happen in is with a variant,
1192 * as all other deeply-nested types have a static type, and hence should
1193 * have been rejected earlier. In the case of a variant whose nesting plus
1194 * the depth of its child is too great, return a unit variant () instead of
1195 * the real child. */
1196 if (!(value->state & STATE_TRUSTED) &&
1197 g_variant_type_info_query_depth (s_child.type_info) >=
1198 G_VARIANT_MAX_RECURSION_DEPTH - value->depth)
1200 g_assert (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT));
1201 g_variant_type_info_unref (s_child.type_info);
1202 return g_variant_new_tuple (NULL, 0);
1205 /* create a new serialized instance out of it */
1206 child = g_slice_new (GVariant);
1207 child->type_info = s_child.type_info;
1208 child->state = (value->state & STATE_TRUSTED) |
1210 child->size = s_child.size;
1211 g_atomic_ref_count_init (&child->ref_count);
1212 child->depth = value->depth + 1;
1213 child->contents.serialised.bytes =
1214 g_bytes_ref (value->contents.serialised.bytes);
1215 child->contents.serialised.data = s_child.data;
1216 child->contents.serialised.ordered_offsets_up_to = (value->state & STATE_TRUSTED) ? G_MAXSIZE : s_child.ordered_offsets_up_to;
1217 child->contents.serialised.checked_offsets_up_to = (value->state & STATE_TRUSTED) ? G_MAXSIZE : s_child.checked_offsets_up_to;
1219 TRACE(GLIB_VARIANT_FROM_PARENT(child, child->type_info, child->ref_count, child->state, value));
1226 * g_variant_maybe_get_child_value:
1227 * @value: a container #GVariant
1228 * @index_: the index of the child to fetch
1230 * Reads a child item out of a container #GVariant instance, if it is in normal
1231 * form. If it is not in normal form, return %NULL.
1233 * This function behaves the same as g_variant_get_child_value(), except that it
1234 * returns %NULL if the child is not in normal form. g_variant_get_child_value()
1235 * would instead return a new default value of the correct type.
1237 * This is intended to be used internally to avoid unnecessary #GVariant
1240 * The returned value is never floating. You should free it with
1241 * g_variant_unref() when you're done with it.
1243 * This function is O(1).
1245 * Returns: (transfer full): the child at the specified index
1250 g_variant_maybe_get_child_value (GVariant *value,
1253 g_return_val_if_fail (value->depth < G_MAXSIZE, NULL);
1255 if (~g_atomic_int_get (&value->state) & STATE_SERIALISED)
1257 /* g_variant_serialised_get_child() does its own checks on index_ */
1258 g_return_val_if_fail (index_ < g_variant_n_children (value), NULL);
1260 g_variant_lock (value);
1262 if (~value->state & STATE_SERIALISED)
1266 child = g_variant_ref (value->contents.tree.children[index_]);
1267 g_variant_unlock (value);
1272 g_variant_unlock (value);
1276 GVariantSerialised serialised = g_variant_to_serialised (value);
1277 GVariantSerialised s_child;
1279 /* get the serializer to extract the serialized data for the child
1280 * from the serialized data for the container
1282 s_child = g_variant_serialised_get_child (serialised, index_);
1284 if (!(value->state & STATE_TRUSTED) && s_child.data == NULL)
1286 g_variant_type_info_unref (s_child.type_info);
1290 g_variant_type_info_unref (s_child.type_info);
1291 return g_variant_get_child_value (value, index_);
1297 * @value: the #GVariant to store
1298 * @data: (not nullable): the location to store the serialized data at
1300 * Stores the serialized form of @value at @data. @data should be
1301 * large enough. See g_variant_get_size().
1303 * The stored data is in machine native byte order but may not be in
1304 * fully-normalised form if read from an untrusted source. See
1305 * g_variant_get_normal_form() for a solution.
1307 * As with g_variant_get_data(), to be able to deserialize the
1308 * serialized variant successfully, its type and (if the destination
1309 * machine might be different) its endianness must also be available.
1311 * This function is approximately O(n) in the size of @data.
1316 g_variant_store (GVariant *value,
1319 g_variant_lock (value);
1321 if (value->state & STATE_SERIALISED)
1323 if (value->contents.serialised.data != NULL)
1324 memcpy (data, value->contents.serialised.data, value->size);
1326 memset (data, 0, value->size);
1329 g_variant_serialise (value, data);
1331 g_variant_unlock (value);
1335 * g_variant_is_normal_form:
1336 * @value: a #GVariant instance
1338 * Checks if @value is in normal form.
1340 * The main reason to do this is to detect if a given chunk of
1341 * serialized data is in normal form: load the data into a #GVariant
1342 * using g_variant_new_from_data() and then use this function to
1345 * If @value is found to be in normal form then it will be marked as
1346 * being trusted. If the value was already marked as being trusted then
1347 * this function will immediately return %TRUE.
1349 * There may be implementation specific restrictions on deeply nested values.
1350 * GVariant is guaranteed to handle nesting up to at least 64 levels.
1352 * Returns: %TRUE if @value is in normal form
1357 g_variant_is_normal_form (GVariant *value)
1359 if (value->state & STATE_TRUSTED)
1362 g_variant_lock (value);
1364 if (value->depth >= G_VARIANT_MAX_RECURSION_DEPTH)
1367 if (value->state & STATE_SERIALISED)
1369 if (g_variant_serialised_is_normal (g_variant_to_serialised (value)))
1370 value->state |= STATE_TRUSTED;
1374 gboolean normal = TRUE;
1377 for (i = 0; i < value->contents.tree.n_children; i++)
1378 normal &= g_variant_is_normal_form (value->contents.tree.children[i]);
1381 value->state |= STATE_TRUSTED;
1384 g_variant_unlock (value);
1386 return (value->state & STATE_TRUSTED) != 0;