Change LGPL-2.1+ to LGPL-2.1-or-later
[platform/upstream/glib.git] / glib / gvariant-core.c
1 /*
2  * Copyright © 2007, 2008 Ryan Lortie
3  * Copyright © 2010 Codethink Limited
4  * Copyright © 2022 Endless OS Foundation, LLC
5  *
6  * SPDX-License-Identifier: LGPL-2.1-or-later
7  *
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.
12  *
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.
17  *
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/>.
20  */
21
22 #include "config.h"
23
24 #include <glib/gvariant-core.h>
25
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>
35 #include <string.h>
36
37 #include "glib_trace.h"
38
39 /*
40  * This file includes the structure definition for GVariant and a small
41  * set of functions that are allowed to access the structure directly.
42  *
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.
48  *
49  * Most GVariant API functions are in gvariant.c.
50  */
51
52 /**
53  * GVariant:
54  *
55  * #GVariant is an opaque data structure and can only be accessed
56  * using the following functions.
57  *
58  * Since: 2.24
59  **/
60 struct _GVariant
61 /* see below for field member documentation */
62 {
63   GVariantTypeInfo *type_info;
64   gsize size;
65
66   union
67   {
68     struct
69     {
70       GBytes *bytes;
71       gconstpointer data;
72       gsize ordered_offsets_up_to;
73       gsize checked_offsets_up_to;
74     } serialised;
75
76     struct
77     {
78       GVariant **children;
79       gsize n_children;
80     } tree;
81   } contents;
82
83   gint state;
84   gatomicrefcount ref_count;
85   gsize depth;
86 };
87
88 /* struct GVariant:
89  *
90  * There are two primary forms of GVariant instances: "serialized form"
91  * and "tree form".
92  *
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.
97  *
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).
102  *
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.
107  *
108  *
109  * The fields of the structure are documented here:
110  *
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().
114  *
115  *            The type_info field never changes during the life of the
116  *            instance, so it can be accessed without a lock.
117  *
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
127  *       the data.
128  *
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.
133  *
134  * contents: a union containing either the information associated with
135  *           holding a value in serialized form or holding a value in
136  *           tree form.
137  *
138  *   .serialised: Only valid when the instance is in serialized form.
139  *
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.
144  *
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().
151  *
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.
155  *
156  *            This pointer may be %NULL in two cases:
157  *
158  *              - if the serialized size of the instance is 0
159  *
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
169  *                bytes.
170  *
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.
176  *
177  *                             For trusted data this is set to G_MAXSIZE and we
178  *                             don't check that the frame offsets are in order.
179  *
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.
185  *
186  *                             This field is only relevant for arrays of non
187  *                             fixed width types and for tuples.
188  *
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.
193  *
194  *                             It is always the case that
195  *                             .checked_offsets_up_to ≥ .ordered_offsets_up_to.
196  *
197  *                             If .checked_offsets_up_to == .ordered_offsets_up_to,
198  *                             then a bad offset has not been found so far.
199  *
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).
203  *
204  *                             This field is only relevant for arrays of non
205  *                             fixed width types and for tuples.
206  *
207  *   .tree: Only valid when the instance is in tree form.
208  *
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'.
213  *
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
218  *                g_free().
219  *
220  *     .n_children: the number of items in the .children array.
221  *
222  * state: a bitfield describing the state of the instance.  It is a
223  *        bitwise-or of the following STATE_* constants:
224  *
225  *    STATE_LOCKED: the instance lock is held.  This is the bit used by
226  *                  g_bit_lock().
227  *
228  *    STATE_SERIALISED: the instance is in serialized form.  If this
229  *                      flag is not set then the instance is in tree
230  *                      form.
231  *
232  *    STATE_TRUSTED: for serialized form instances, this means that the
233  *                   serialized data is known to be in normal form (ie:
234  *                   not corrupted).
235  *
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
240  *                   normal form.
241  *
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().
245  *
246  *    STATE_FLOATING: if this flag is set then the object has a floating
247  *                    reference.  See g_variant_ref_sink().
248  *
249  * ref_count: the reference count of the instance
250  *
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.
255  */
256 #define STATE_LOCKED     1
257 #define STATE_SERIALISED 2
258 #define STATE_TRUSTED    4
259 #define STATE_FLOATING   8
260
261 /* -- private -- */
262 /* < private >
263  * g_variant_lock:
264  * @value: a #GVariant
265  *
266  * Locks @value for performing sensitive operations.
267  */
268 static void
269 g_variant_lock (GVariant *value)
270 {
271   g_bit_lock (&value->state, 0);
272 }
273
274 /* < private >
275  * g_variant_unlock:
276  * @value: a #GVariant
277  *
278  * Unlocks @value after performing sensitive operations.
279  */
280 static void
281 g_variant_unlock (GVariant *value)
282 {
283   g_bit_unlock (&value->state, 0);
284 }
285
286 /* < private >
287  * g_variant_release_children:
288  * @value: a #GVariant
289  *
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.
292  *
293  * This is done when freeing a tree-form instance or converting it to
294  * serialized form.
295  *
296  * The current thread must hold the lock on @value.
297  */
298 static void
299 g_variant_release_children (GVariant *value)
300 {
301   gsize i;
302
303   g_assert (value->state & STATE_LOCKED);
304   g_assert (~value->state & STATE_SERIALISED);
305
306   for (i = 0; i < value->contents.tree.n_children; i++)
307     g_variant_unref (value->contents.tree.children[i]);
308
309   g_free (value->contents.tree.children);
310 }
311
312 /* This begins the main body of the recursive serializer.
313  *
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.
317  *
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.
324  *
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().
328  *
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
332  * buffer.
333  *
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.
339  *
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.
343  *
344  *   The serializer uses the size information from the children to
345  *   calculate the size needed for the entire container.
346  *
347  * Writing the data:
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.
352  *
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().
360  *
361  *
362  * The forward declaration here allows corecursion via callback:
363  */
364 static void g_variant_fill_gvs (GVariantSerialised *, gpointer);
365
366 /* < private >
367  * g_variant_ensure_size:
368  * @value: a #GVariant
369  *
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.
373  *
374  * The current thread must hold the lock on @value.
375  */
376 static void
377 g_variant_ensure_size (GVariant *value)
378 {
379   g_assert (value->state & STATE_LOCKED);
380
381   if (value->size == (gsize) -1)
382     {
383       gpointer *children;
384       gsize n_children;
385
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,
389                                                       g_variant_fill_gvs,
390                                                       children, n_children);
391     }
392 }
393
394 /* < private >
395  * g_variant_to_serialised:
396  * @value: a #GVariant
397  *
398  * Gets a GVariantSerialised for a GVariant in state STATE_SERIALISED.
399  */
400 inline static GVariantSerialised
401 g_variant_to_serialised (GVariant *value)
402 {
403   g_assert (value->state & STATE_SERIALISED);
404   {
405     GVariantSerialised serialised = {
406       value->type_info,
407       (gpointer) value->contents.serialised.data,
408       value->size,
409       value->depth,
410       value->contents.serialised.ordered_offsets_up_to,
411       value->contents.serialised.checked_offsets_up_to,
412     };
413     return serialised;
414   }
415 }
416
417 /* < private >
418  * g_variant_serialise:
419  * @value: a #GVariant
420  * @data: an appropriately-sized buffer
421  *
422  * Serializes @value into @data.  @value must be in tree form.
423  *
424  * No change is made to @value.
425  *
426  * The current thread must hold the lock on @value.
427  */
428 static void
429 g_variant_serialise (GVariant *value,
430                      gpointer  data)
431 {
432   GVariantSerialised serialised = { 0, };
433   gpointer *children;
434   gsize n_children;
435
436   g_assert (~value->state & STATE_SERIALISED);
437   g_assert (value->state & STATE_LOCKED);
438
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;
445
446   children = (gpointer *) value->contents.tree.children;
447   n_children = value->contents.tree.n_children;
448
449   g_variant_serialiser_serialise (serialised, g_variant_fill_gvs,
450                                   children, n_children);
451 }
452
453 /* < private >
454  * g_variant_fill_gvs:
455  * @serialised: a pointer to a #GVariantSerialised
456  * @data: a #GVariant instance
457  *
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
461  * actions:
462  *
463  *  - reporting its type
464  *
465  *  - reporting its serialized size (requires knowing the size first)
466  *
467  *  - possibly storing its serialized form into the provided buffer
468  */
469 static void
470 g_variant_fill_gvs (GVariantSerialised *serialised,
471                     gpointer            data)
472 {
473   GVariant *value = data;
474
475   g_variant_lock (value);
476   g_variant_ensure_size (value);
477   g_variant_unlock (value);
478
479   if (serialised->type_info == NULL)
480     serialised->type_info = value->type_info;
481   g_assert (serialised->type_info == value->type_info);
482
483   if (serialised->size == 0)
484     serialised->size = value->size;
485   g_assert (serialised->size == value->size);
486   serialised->depth = value->depth;
487
488   if (value->state & STATE_SERIALISED)
489     {
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;
492     }
493   else
494     {
495       serialised->ordered_offsets_up_to = 0;
496       serialised->checked_offsets_up_to = 0;
497     }
498
499   if (serialised->data)
500     /* g_variant_store() is a public API, so it
501      * it will reacquire the lock if it needs to.
502      */
503     g_variant_store (value, serialised->data);
504 }
505
506 /* this ends the main body of the recursive serializer */
507
508 /* < private >
509  * g_variant_ensure_serialised:
510  * @value: a #GVariant
511  *
512  * Ensures that @value is in serialized form.
513  *
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.
519  *
520  * The current thread must hold the lock on @value.
521  */
522 static void
523 g_variant_ensure_serialised (GVariant *value)
524 {
525   g_assert (value->state & STATE_LOCKED);
526
527   if (~value->state & STATE_SERIALISED)
528     {
529       GBytes *bytes;
530       gpointer data;
531
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);
536
537       g_variant_release_children (value);
538
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));
546     }
547 }
548
549 /* < private >
550  * g_variant_alloc:
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
554  *
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.
558  *
559  * Returns: a new #GVariant with a floating reference
560  */
561 static GVariant *
562 g_variant_alloc (const GVariantType *type,
563                  gboolean            serialised,
564                  gboolean            trusted)
565 {
566   GVariant *value;
567
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) |
572                  STATE_FLOATING;
573   value->size = (gssize) -1;
574   g_atomic_ref_count_init (&value->ref_count);
575   value->depth = 0;
576
577   return value;
578 }
579
580 /**
581  * g_variant_new_from_bytes:
582  * @type: a #GVariantType
583  * @bytes: a #GBytes
584  * @trusted: if the contents of @bytes are trusted
585  *
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.
589  *
590  * A reference is taken on @bytes.
591  *
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.
595  *
596  * Returns: (transfer none): a new #GVariant with a floating reference
597  *
598  * Since: 2.36
599  */
600 GVariant *
601 g_variant_new_from_bytes (const GVariantType *type,
602                           GBytes             *bytes,
603                           gboolean            trusted)
604 {
605   GVariant *value;
606   guint alignment;
607   gsize size;
608   GBytes *owned_bytes = NULL;
609   GVariantSerialised serialised;
610
611   value = g_variant_alloc (type, TRUE, trusted);
612
613   g_variant_type_info_query (value->type_info,
614                              &alignment, &size);
615
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;
627
628   if (!g_variant_serialised_check (serialised))
629     {
630 #ifdef HAVE_POSIX_MEMALIGN
631       gpointer aligned_data = NULL;
632       gsize aligned_size = g_bytes_get_size (bytes);
633
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),
638                           aligned_size) != 0)
639         g_error ("posix_memalign failed");
640
641       if (aligned_size != 0)
642         memcpy (aligned_data, g_bytes_get_data (bytes, NULL), aligned_size);
643
644       bytes = owned_bytes = g_bytes_new_with_free_func (aligned_data,
645                                                         aligned_size,
646                                                         free, aligned_data);
647       aligned_data = NULL;
648 #else
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
651        * harder here.
652        */
653       bytes = owned_bytes = g_bytes_new (g_bytes_get_data (bytes, NULL),
654                                          g_bytes_get_size (bytes));
655 #endif
656     }
657
658   value->contents.serialised.bytes = g_bytes_ref (bytes);
659
660   if (size && g_bytes_get_size (bytes) != size)
661     {
662       /* Creating a fixed-sized GVariant with a bytes of the wrong
663        * size.
664        *
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
667        * fixed size).
668        */
669       value->contents.serialised.data = NULL;
670       value->size = size;
671     }
672   else
673     {
674       value->contents.serialised.data = g_bytes_get_data (bytes, &value->size);
675     }
676
677   value->contents.serialised.ordered_offsets_up_to = trusted ? G_MAXSIZE : 0;
678   value->contents.serialised.checked_offsets_up_to = trusted ? G_MAXSIZE : 0;
679
680   g_clear_pointer (&owned_bytes, g_bytes_unref);
681
682   TRACE(GLIB_VARIANT_FROM_BUFFER(value, value->type_info, value->ref_count, value->state));
683
684   return value;
685 }
686
687 /* -- internal -- */
688
689 /* < internal >
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
695  *
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.
699  *
700  * @children is consumed by this function.  g_free() will be called on
701  * it some time later.
702  *
703  * Returns: a new #GVariant with a floating reference
704  */
705 GVariant *
706 g_variant_new_from_children (const GVariantType  *type,
707                              GVariant           **children,
708                              gsize                n_children,
709                              gboolean             trusted)
710 {
711   GVariant *value;
712
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));
717
718   return value;
719 }
720
721 /* < internal >
722  * g_variant_get_type_info:
723  * @value: a #GVariant
724  *
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.
728  *
729  * Returns: the #GVariantTypeInfo for @value
730  */
731 GVariantTypeInfo *
732 g_variant_get_type_info (GVariant *value)
733 {
734   return value->type_info;
735 }
736
737 /* < internal >
738  * g_variant_is_trusted:
739  * @value: a #GVariant
740  *
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.
745  *
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.
750  *
751  * Returns: if @value is trusted
752  */
753 gboolean
754 g_variant_is_trusted (GVariant *value)
755 {
756   return (value->state & STATE_TRUSTED) != 0;
757 }
758
759 /* < internal >
760  * g_variant_get_depth:
761  * @value: a #GVariant
762  *
763  * Gets the nesting depth of a #GVariant. This is 0 for a #GVariant with no
764  * children.
765  *
766  * Returns: nesting depth of @value
767  */
768 gsize
769 g_variant_get_depth (GVariant *value)
770 {
771   return value->depth;
772 }
773
774 /* -- public -- */
775
776 /**
777  * g_variant_unref:
778  * @value: a #GVariant
779  *
780  * Decreases the reference count of @value.  When its reference count
781  * drops to 0, the memory used by the variant is freed.
782  *
783  * Since: 2.24
784  **/
785 void
786 g_variant_unref (GVariant *value)
787 {
788   g_return_if_fail (value != NULL);
789
790   TRACE(GLIB_VARIANT_UNREF(value, value->type_info, value->ref_count, value->state));
791
792   if (g_atomic_ref_count_dec (&value->ref_count))
793     {
794       if G_UNLIKELY (value->state & STATE_LOCKED)
795         g_critical ("attempting to free a locked GVariant instance.  "
796                     "This should never happen.");
797
798       value->state |= STATE_LOCKED;
799
800       g_variant_type_info_unref (value->type_info);
801
802       if (value->state & STATE_SERIALISED)
803         g_bytes_unref (value->contents.serialised.bytes);
804       else
805         g_variant_release_children (value);
806
807       memset (value, 0, sizeof (GVariant));
808       g_slice_free (GVariant, value);
809     }
810 }
811
812 /**
813  * g_variant_ref:
814  * @value: a #GVariant
815  *
816  * Increases the reference count of @value.
817  *
818  * Returns: the same @value
819  *
820  * Since: 2.24
821  **/
822 GVariant *
823 g_variant_ref (GVariant *value)
824 {
825   g_return_val_if_fail (value != NULL, NULL);
826
827   TRACE(GLIB_VARIANT_REF(value, value->type_info, value->ref_count, value->state));
828
829   g_atomic_ref_count_inc (&value->ref_count);
830
831   return value;
832 }
833
834 /**
835  * g_variant_ref_sink:
836  * @value: a #GVariant
837  *
838  * #GVariant uses a floating reference count system.  All functions with
839  * names starting with `g_variant_new_` return floating
840  * references.
841  *
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.
846  *
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.
851  *
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
859  * are not floating.
860  *
861  * Returns: the same @value
862  *
863  * Since: 2.24
864  **/
865 GVariant *
866 g_variant_ref_sink (GVariant *value)
867 {
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);
870
871   g_variant_lock (value);
872
873   TRACE(GLIB_VARIANT_REF_SINK(value, value->type_info, value->ref_count, value->state, value->state & STATE_FLOATING));
874
875   if (~value->state & STATE_FLOATING)
876     g_variant_ref (value);
877   else
878     value->state &= ~STATE_FLOATING;
879
880   g_variant_unlock (value);
881
882   return value;
883 }
884
885 /**
886  * g_variant_take_ref:
887  * @value: a #GVariant
888  *
889  * If @value is floating, sink it.  Otherwise, do nothing.
890  *
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.
895  *
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).
901  *
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
905  * reference.
906  *
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.
912  *
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.
921  *
922  * Returns: the same @value
923  **/
924 GVariant *
925 g_variant_take_ref (GVariant *value)
926 {
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);
929
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);
932
933   return value;
934 }
935
936 /**
937  * g_variant_is_floating:
938  * @value: a #GVariant
939  *
940  * Checks whether @value has a floating reference count.
941  *
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().
946  *
947  * See g_variant_ref_sink() for more information about floating reference
948  * counts.
949  *
950  * Returns: whether @value is floating
951  *
952  * Since: 2.26
953  **/
954 gboolean
955 g_variant_is_floating (GVariant *value)
956 {
957   g_return_val_if_fail (value != NULL, FALSE);
958
959   return (value->state & STATE_FLOATING) != 0;
960 }
961
962 /**
963  * g_variant_get_size:
964  * @value: a #GVariant instance
965  *
966  * Determines the number of bytes that would be required to store @value
967  * with g_variant_store().
968  *
969  * If @value has a fixed-sized type then this function always returned
970  * that fixed size.
971  *
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
976  * involved.
977  *
978  * Returns: the serialized size of @value
979  *
980  * Since: 2.24
981  **/
982 gsize
983 g_variant_get_size (GVariant *value)
984 {
985   g_variant_lock (value);
986   g_variant_ensure_size (value);
987   g_variant_unlock (value);
988
989   return value->size;
990 }
991
992 /**
993  * g_variant_get_data:
994  * @value: a #GVariant instance
995  *
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.
1000  *
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.
1006  *
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
1010  * of the result.
1011  *
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
1020  * serialized data).
1021  *
1022  * Returns: (transfer none): the serialized form of @value, or %NULL
1023  *
1024  * Since: 2.24
1025  **/
1026 gconstpointer
1027 g_variant_get_data (GVariant *value)
1028 {
1029   g_variant_lock (value);
1030   g_variant_ensure_serialised (value);
1031   g_variant_unlock (value);
1032
1033   return value->contents.serialised.data;
1034 }
1035
1036 /**
1037  * g_variant_get_data_as_bytes:
1038  * @value: a #GVariant
1039  *
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.
1044  *
1045  * Returns: (transfer full): A new #GBytes representing the variant data
1046  *
1047  * Since: 2.36
1048  */ 
1049 GBytes *
1050 g_variant_get_data_as_bytes (GVariant *value)
1051 {
1052   const gchar *bytes_data;
1053   const gchar *data;
1054   gsize bytes_size;
1055   gsize size;
1056
1057   g_variant_lock (value);
1058   g_variant_ensure_serialised (value);
1059   g_variant_unlock (value);
1060
1061   bytes_data = g_bytes_get_data (value->contents.serialised.bytes, &bytes_size);
1062   data = value->contents.serialised.data;
1063   size = value->size;
1064
1065   if (data == NULL)
1066     {
1067       g_assert (size == 0);
1068       data = bytes_data;
1069     }
1070
1071   if (data == bytes_data && size == bytes_size)
1072     return g_bytes_ref (value->contents.serialised.bytes);
1073   else
1074     return g_bytes_new_from_bytes (value->contents.serialised.bytes,
1075                                    data - bytes_data, size);
1076 }
1077
1078
1079 /**
1080  * g_variant_n_children:
1081  * @value: a container #GVariant
1082  *
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
1086  * #GVariant.
1087  *
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
1092  *
1093  * This function is O(1).
1094  *
1095  * Returns: the number of children in the container
1096  *
1097  * Since: 2.24
1098  **/
1099 gsize
1100 g_variant_n_children (GVariant *value)
1101 {
1102   gsize n_children;
1103
1104   g_variant_lock (value);
1105
1106   if (value->state & STATE_SERIALISED)
1107     n_children = g_variant_serialised_n_children (
1108         g_variant_to_serialised (value));
1109   else
1110     n_children = value->contents.tree.n_children;
1111
1112   g_variant_unlock (value);
1113
1114   return n_children;
1115 }
1116
1117 /**
1118  * g_variant_get_child_value:
1119  * @value: a container #GVariant
1120  * @index_: the index of the child to fetch
1121  *
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
1125  * #GVariant.
1126  *
1127  * It is an error if @index_ is greater than the number of child items
1128  * in the container.  See g_variant_n_children().
1129  *
1130  * The returned value is never floating.  You should free it with
1131  * g_variant_unref() when you're done with it.
1132  *
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.
1138  *
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.
1143  *
1144  * This function is O(1).
1145  *
1146  * Returns: (transfer full): the child at the specified index
1147  *
1148  * Since: 2.24
1149  **/
1150 GVariant *
1151 g_variant_get_child_value (GVariant *value,
1152                            gsize     index_)
1153 {
1154   g_return_val_if_fail (value->depth < G_MAXSIZE, NULL);
1155
1156   if (~g_atomic_int_get (&value->state) & STATE_SERIALISED)
1157     {
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);
1160
1161       g_variant_lock (value);
1162
1163       if (~value->state & STATE_SERIALISED)
1164         {
1165           GVariant *child;
1166
1167           child = g_variant_ref (value->contents.tree.children[index_]);
1168           g_variant_unlock (value);
1169
1170           return child;
1171         }
1172
1173       g_variant_unlock (value);
1174     }
1175
1176   {
1177     GVariantSerialised serialised = g_variant_to_serialised (value);
1178     GVariantSerialised s_child;
1179     GVariant *child;
1180
1181     /* get the serializer to extract the serialized data for the child
1182      * from the serialized data for the container
1183      */
1184     s_child = g_variant_serialised_get_child (serialised, index_);
1185
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);
1189
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)
1199       {
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);
1203       }
1204
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) |
1209                    STATE_SERIALISED;
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;
1218
1219     TRACE(GLIB_VARIANT_FROM_PARENT(child, child->type_info, child->ref_count, child->state, value));
1220
1221     return child;
1222   }
1223 }
1224
1225 /**
1226  * g_variant_maybe_get_child_value:
1227  * @value: a container #GVariant
1228  * @index_: the index of the child to fetch
1229  *
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.
1232  *
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.
1236  *
1237  * This is intended to be used internally to avoid unnecessary #GVariant
1238  * allocations.
1239  *
1240  * The returned value is never floating.  You should free it with
1241  * g_variant_unref() when you're done with it.
1242  *
1243  * This function is O(1).
1244  *
1245  * Returns: (transfer full): the child at the specified index
1246  *
1247  * Since: 2.74
1248  */
1249 GVariant *
1250 g_variant_maybe_get_child_value (GVariant *value,
1251                                  gsize     index_)
1252 {
1253   g_return_val_if_fail (value->depth < G_MAXSIZE, NULL);
1254
1255   if (~g_atomic_int_get (&value->state) & STATE_SERIALISED)
1256     {
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);
1259
1260       g_variant_lock (value);
1261
1262       if (~value->state & STATE_SERIALISED)
1263         {
1264           GVariant *child;
1265
1266           child = g_variant_ref (value->contents.tree.children[index_]);
1267           g_variant_unlock (value);
1268
1269           return child;
1270         }
1271
1272       g_variant_unlock (value);
1273     }
1274
1275   {
1276     GVariantSerialised serialised = g_variant_to_serialised (value);
1277     GVariantSerialised s_child;
1278
1279     /* get the serializer to extract the serialized data for the child
1280      * from the serialized data for the container
1281      */
1282     s_child = g_variant_serialised_get_child (serialised, index_);
1283
1284     if (!(value->state & STATE_TRUSTED) && s_child.data == NULL)
1285       {
1286         g_variant_type_info_unref (s_child.type_info);
1287         return NULL;
1288       }
1289
1290     g_variant_type_info_unref (s_child.type_info);
1291     return g_variant_get_child_value (value, index_);
1292   }
1293 }
1294
1295 /**
1296  * g_variant_store:
1297  * @value: the #GVariant to store
1298  * @data: (not nullable): the location to store the serialized data at
1299  *
1300  * Stores the serialized form of @value at @data.  @data should be
1301  * large enough.  See g_variant_get_size().
1302  *
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.
1306  *
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.
1310  *
1311  * This function is approximately O(n) in the size of @data.
1312  *
1313  * Since: 2.24
1314  **/
1315 void
1316 g_variant_store (GVariant *value,
1317                  gpointer  data)
1318 {
1319   g_variant_lock (value);
1320
1321   if (value->state & STATE_SERIALISED)
1322     {
1323       if (value->contents.serialised.data != NULL)
1324         memcpy (data, value->contents.serialised.data, value->size);
1325       else
1326         memset (data, 0, value->size);
1327     }
1328   else
1329     g_variant_serialise (value, data);
1330
1331   g_variant_unlock (value);
1332 }
1333
1334 /**
1335  * g_variant_is_normal_form:
1336  * @value: a #GVariant instance
1337  *
1338  * Checks if @value is in normal form.
1339  *
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
1343  * check.
1344  *
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.
1348  *
1349  * There may be implementation specific restrictions on deeply nested values.
1350  * GVariant is guaranteed to handle nesting up to at least 64 levels.
1351  *
1352  * Returns: %TRUE if @value is in normal form
1353  *
1354  * Since: 2.24
1355  **/
1356 gboolean
1357 g_variant_is_normal_form (GVariant *value)
1358 {
1359   if (value->state & STATE_TRUSTED)
1360     return TRUE;
1361
1362   g_variant_lock (value);
1363
1364   if (value->depth >= G_VARIANT_MAX_RECURSION_DEPTH)
1365     return FALSE;
1366
1367   if (value->state & STATE_SERIALISED)
1368     {
1369       if (g_variant_serialised_is_normal (g_variant_to_serialised (value)))
1370         value->state |= STATE_TRUSTED;
1371     }
1372   else
1373     {
1374       gboolean normal = TRUE;
1375       gsize i;
1376
1377       for (i = 0; i < value->contents.tree.n_children; i++)
1378         normal &= g_variant_is_normal_form (value->contents.tree.children[i]);
1379
1380       if (normal)
1381         value->state |= STATE_TRUSTED;
1382     }
1383
1384   g_variant_unlock (value);
1385
1386   return (value->state & STATE_TRUSTED) != 0;
1387 }