Imported Upstream version 2.74.3
[platform/upstream/glib.git] / glib / gvariant-core.c
1 /*
2  * Copyright © 2007, 2008 Ryan Lortie
3  * Copyright © 2010 Codethink Limited
4  *
5  * SPDX-License-Identifier: LGPL-2.1-or-later
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "config.h"
22
23 #include <glib/gvariant-core.h>
24
25 #include <glib/gvariant-internal.h>
26 #include <glib/gvariant-serialiser.h>
27 #include <glib/gtestutils.h>
28 #include <glib/gbitlock.h>
29 #include <glib/gatomic.h>
30 #include <glib/gbytes.h>
31 #include <glib/gslice.h>
32 #include <glib/gmem.h>
33 #include <glib/grefcount.h>
34 #include <string.h>
35
36
37 /*
38  * This file includes the structure definition for GVariant and a small
39  * set of functions that are allowed to access the structure directly.
40  *
41  * This minimises the amount of code that can possibly touch a GVariant
42  * structure directly to a few simple fundamental operations.  These few
43  * operations are written to be completely threadsafe with respect to
44  * all possible outside access.  This means that we only need to be
45  * concerned about thread safety issues in this one small file.
46  *
47  * Most GVariant API functions are in gvariant.c.
48  */
49
50 /**
51  * GVariant:
52  *
53  * #GVariant is an opaque data structure and can only be accessed
54  * using the following functions.
55  *
56  * Since: 2.24
57  **/
58 struct _GVariant
59 /* see below for field member documentation */
60 {
61   GVariantTypeInfo *type_info;
62   gsize size;
63
64   union
65   {
66     struct
67     {
68       GBytes *bytes;
69       gconstpointer data;
70     } serialised;
71
72     struct
73     {
74       GVariant **children;
75       gsize n_children;
76     } tree;
77   } contents;
78
79   gint state;
80   gatomicrefcount ref_count;
81   gsize depth;
82 };
83
84 /* struct GVariant:
85  *
86  * There are two primary forms of GVariant instances: "serialized form"
87  * and "tree form".
88  *
89  * "serialized form": A serialized GVariant instance stores its value in
90  *                    the GVariant serialization format.  All
91  *                    basic-typed instances (ie: non-containers) are in
92  *                    serialized format, as are some containers.
93  *
94  * "tree form": Some containers are in "tree form".  In this case,
95  *              instead of containing the serialized data for the
96  *              container, the instance contains an array of pointers to
97  *              the child values of the container (thus forming a tree).
98  *
99  * It is possible for an instance to transition from tree form to
100  * serialized form.  This happens, implicitly, if the serialized data is
101  * requested (eg: via g_variant_get_data()).  Serialized form instances
102  * never transition into tree form.
103  *
104  *
105  * The fields of the structure are documented here:
106  *
107  * type_info: this is a reference to a GVariantTypeInfo describing the
108  *            type of the instance.  When the instance is freed, this
109  *            reference must be released with g_variant_type_info_unref().
110  *
111  *            The type_info field never changes during the life of the
112  *            instance, so it can be accessed without a lock.
113  *
114  * size: this is the size of the serialized form for the instance, if it
115  *       is known.  If the instance is in serialized form then it is, by
116  *       definition, known.  If the instance is in tree form then it may
117  *       be unknown (in which case it is -1).  It is possible for the
118  *       size to be known when in tree form if, for example, the user
119  *       has called g_variant_get_size() without calling
120  *       g_variant_get_data().  Additionally, even when the user calls
121  *       g_variant_get_data() the size of the data must first be
122  *       determined so that a large enough buffer can be allocated for
123  *       the data.
124  *
125  *       Once the size is known, it can never become unknown again.
126  *       g_variant_ensure_size() is used to ensure that the size is in
127  *       the known state -- it calculates the size if needed.  After
128  *       that, the size field can be accessed without a lock.
129  *
130  * contents: a union containing either the information associated with
131  *           holding a value in serialized form or holding a value in
132  *           tree form.
133  *
134  *   .serialised: Only valid when the instance is in serialized form.
135  *
136  *                Since an instance can never transition away from
137  *                serialized form, once these fields are set, they will
138  *                never be changed.  It is therefore valid to access
139  *                them without holding a lock.
140  *
141  *     .bytes:  the #GBytes that contains the memory pointed to by
142  *              .data, or %NULL if .data is %NULL.  In the event that
143  *              the instance was deserialized from another instance,
144  *              then the bytes will be shared by both of them.  When
145  *              the instance is freed, this reference must be released
146  *              with g_bytes_unref().
147  *
148  *     .data: the serialized data (of size 'size') of the instance.
149  *            This pointer should not be freed or modified in any way.
150  *            #GBytes is responsible for memory management.
151  *
152  *            This pointer may be %NULL in two cases:
153  *
154  *              - if the serialized size of the instance is 0
155  *
156  *              - if the instance is of a fixed-sized type and was
157  *                deserialized out of a corrupted container such that
158  *                the container contains too few bytes to point to the
159  *                entire proper fixed-size of this instance.  In this
160  *                case, 'size' will still be equal to the proper fixed
161  *                size, but this pointer will be %NULL.  This is exactly
162  *                the reason that g_variant_get_data() sometimes returns
163  *                %NULL.  For all other calls, the effect should be as
164  *                if .data pointed to the appropriate number of nul
165  *                bytes.
166  *
167  *   .tree: Only valid when the instance is in tree form.
168  *
169  *          Note that accesses from other threads could result in
170  *          conversion of the instance from tree form to serialized form
171  *          at any time.  For this reason, the instance lock must always
172  *          be held while performing any operations on 'contents.tree'.
173  *
174  *     .children: the array of the child instances of this instance.
175  *                When the instance is freed (or converted to serialized
176  *                form) then each child must have g_variant_unref()
177  *                called on it and the array must be freed using
178  *                g_free().
179  *
180  *     .n_children: the number of items in the .children array.
181  *
182  * state: a bitfield describing the state of the instance.  It is a
183  *        bitwise-or of the following STATE_* constants:
184  *
185  *    STATE_LOCKED: the instance lock is held.  This is the bit used by
186  *                  g_bit_lock().
187  *
188  *    STATE_SERIALISED: the instance is in serialized form.  If this
189  *                      flag is not set then the instance is in tree
190  *                      form.
191  *
192  *    STATE_TRUSTED: for serialized form instances, this means that the
193  *                   serialized data is known to be in normal form (ie:
194  *                   not corrupted).
195  *
196  *                   For tree form instances, this means that all of the
197  *                   child instances in the contents.tree.children array
198  *                   are trusted.  This means that if the container is
199  *                   serialized then the resulting data will be in
200  *                   normal form.
201  *
202  *                   If this flag is unset it does not imply that the
203  *                   data is corrupted.  It merely means that we're not
204  *                   sure that it's valid.  See g_variant_is_trusted().
205  *
206  *    STATE_FLOATING: if this flag is set then the object has a floating
207  *                    reference.  See g_variant_ref_sink().
208  *
209  * ref_count: the reference count of the instance
210  *
211  * depth: the depth of the GVariant in a hierarchy of nested containers,
212  *        increasing with the level of nesting. The top-most GVariant has depth
213  *        zero.  This is used to avoid recursing too deeply and overflowing the
214  *        stack when handling deeply nested untrusted serialized GVariants.
215  */
216 #define STATE_LOCKED     1
217 #define STATE_SERIALISED 2
218 #define STATE_TRUSTED    4
219 #define STATE_FLOATING   8
220
221 /* -- private -- */
222 /* < private >
223  * g_variant_lock:
224  * @value: a #GVariant
225  *
226  * Locks @value for performing sensitive operations.
227  */
228 static void
229 g_variant_lock (GVariant *value)
230 {
231   g_bit_lock (&value->state, 0);
232 }
233
234 /* < private >
235  * g_variant_unlock:
236  * @value: a #GVariant
237  *
238  * Unlocks @value after performing sensitive operations.
239  */
240 static void
241 g_variant_unlock (GVariant *value)
242 {
243   g_bit_unlock (&value->state, 0);
244 }
245
246 /* < private >
247  * g_variant_release_children:
248  * @value: a #GVariant
249  *
250  * Releases the reference held on each child in the 'children' array of
251  * @value and frees the array itself.  @value must be in tree form.
252  *
253  * This is done when freeing a tree-form instance or converting it to
254  * serialized form.
255  *
256  * The current thread must hold the lock on @value.
257  */
258 static void
259 g_variant_release_children (GVariant *value)
260 {
261   gsize i;
262
263   g_assert (value->state & STATE_LOCKED);
264   g_assert (~value->state & STATE_SERIALISED);
265
266   for (i = 0; i < value->contents.tree.n_children; i++)
267     g_variant_unref (value->contents.tree.children[i]);
268
269   g_free (value->contents.tree.children);
270 }
271
272 /* This begins the main body of the recursive serializer.
273  *
274  * There are 3 functions here that work as a team with the serializer to
275  * get things done.  g_variant_store() has a trivial role, but as a
276  * public API function, it has its definition elsewhere.
277  *
278  * Note that "serialization" of an instance does not mean that the
279  * instance is converted to serialized form -- it means that the
280  * serialized form of an instance is written to an external buffer.
281  * g_variant_ensure_serialised() (which is not part of this set of
282  * functions) is the function that is responsible for converting an
283  * instance to serialized form.
284  *
285  * We are only concerned here with container types since non-container
286  * instances are always in serialized form.  For these instances,
287  * storing their serialized form merely involves a memcpy().
288  *
289  * Serialization is a two-step process.  First, the size of the
290  * serialized data must be calculated so that an appropriately-sized
291  * buffer can be allocated.  Second, the data is written into the
292  * buffer.
293  *
294  * Determining the size:
295  *   The process of determining the size is triggered by a call to
296  *   g_variant_ensure_size() on a container.  This invokes the
297  *   serializer code to determine the size.  The serializer is passed
298  *   g_variant_fill_gvs() as a callback.
299  *
300  *   g_variant_fill_gvs() is called by the serializer on each child of
301  *   the container which, in turn, calls g_variant_ensure_size() on
302  *   itself and fills in the result of its own size calculation.
303  *
304  *   The serializer uses the size information from the children to
305  *   calculate the size needed for the entire container.
306  *
307  * Writing the data:
308  *   After the buffer has been allocated, g_variant_serialise() is
309  *   called on the container.  This invokes the serializer code to write
310  *   the bytes to the container.  The serializer is, again, passed
311  *   g_variant_fill_gvs() as a callback.
312  *
313  *   This time, when g_variant_fill_gvs() is called for each child, the
314  *   child is given a pointer to a sub-region of the allocated buffer
315  *   where it should write its data.  This is done by calling
316  *   g_variant_store().  In the event that the instance is in serialized
317  *   form this means a memcpy() of the serialized data into the
318  *   allocated buffer.  In the event that the instance is in tree form
319  *   this means a recursive call back into g_variant_serialise().
320  *
321  *
322  * The forward declaration here allows corecursion via callback:
323  */
324 static void g_variant_fill_gvs (GVariantSerialised *, gpointer);
325
326 /* < private >
327  * g_variant_ensure_size:
328  * @value: a #GVariant
329  *
330  * Ensures that the ->size field of @value is filled in properly.  This
331  * must be done as a precursor to any serialization of the value in
332  * order to know how large of a buffer is needed to store the data.
333  *
334  * The current thread must hold the lock on @value.
335  */
336 static void
337 g_variant_ensure_size (GVariant *value)
338 {
339   g_assert (value->state & STATE_LOCKED);
340
341   if (value->size == (gsize) -1)
342     {
343       gpointer *children;
344       gsize n_children;
345
346       children = (gpointer *) value->contents.tree.children;
347       n_children = value->contents.tree.n_children;
348       value->size = g_variant_serialiser_needed_size (value->type_info,
349                                                       g_variant_fill_gvs,
350                                                       children, n_children);
351     }
352 }
353
354 /* < private >
355  * g_variant_serialise:
356  * @value: a #GVariant
357  * @data: an appropriately-sized buffer
358  *
359  * Serializes @value into @data.  @value must be in tree form.
360  *
361  * No change is made to @value.
362  *
363  * The current thread must hold the lock on @value.
364  */
365 static void
366 g_variant_serialise (GVariant *value,
367                      gpointer  data)
368 {
369   GVariantSerialised serialised = { 0, };
370   gpointer *children;
371   gsize n_children;
372
373   g_assert (~value->state & STATE_SERIALISED);
374   g_assert (value->state & STATE_LOCKED);
375
376   serialised.type_info = value->type_info;
377   serialised.size = value->size;
378   serialised.data = data;
379   serialised.depth = value->depth;
380
381   children = (gpointer *) value->contents.tree.children;
382   n_children = value->contents.tree.n_children;
383
384   g_variant_serialiser_serialise (serialised, g_variant_fill_gvs,
385                                   children, n_children);
386 }
387
388 /* < private >
389  * g_variant_fill_gvs:
390  * @serialised: a pointer to a #GVariantSerialised
391  * @data: a #GVariant instance
392  *
393  * This is the callback that is passed by a tree-form container instance
394  * to the serializer.  This callback gets called on each child of the
395  * container.  Each child is responsible for performing the following
396  * actions:
397  *
398  *  - reporting its type
399  *
400  *  - reporting its serialized size (requires knowing the size first)
401  *
402  *  - possibly storing its serialized form into the provided buffer
403  */
404 static void
405 g_variant_fill_gvs (GVariantSerialised *serialised,
406                     gpointer            data)
407 {
408   GVariant *value = data;
409
410   g_variant_lock (value);
411   g_variant_ensure_size (value);
412   g_variant_unlock (value);
413
414   if (serialised->type_info == NULL)
415     serialised->type_info = value->type_info;
416   g_assert (serialised->type_info == value->type_info);
417
418   if (serialised->size == 0)
419     serialised->size = value->size;
420   g_assert (serialised->size == value->size);
421   serialised->depth = value->depth;
422
423   if (serialised->data)
424     /* g_variant_store() is a public API, so it
425      * it will reacquire the lock if it needs to.
426      */
427     g_variant_store (value, serialised->data);
428 }
429
430 /* this ends the main body of the recursive serializer */
431
432 /* < private >
433  * g_variant_ensure_serialised:
434  * @value: a #GVariant
435  *
436  * Ensures that @value is in serialized form.
437  *
438  * If @value is in tree form then this function ensures that the
439  * serialized size is known and then allocates a buffer of that size and
440  * serializes the instance into the buffer.  The 'children' array is
441  * then released and the instance is set to serialized form based on the
442  * contents of the buffer.
443  *
444  * The current thread must hold the lock on @value.
445  */
446 static void
447 g_variant_ensure_serialised (GVariant *value)
448 {
449   g_assert (value->state & STATE_LOCKED);
450
451   if (~value->state & STATE_SERIALISED)
452     {
453       GBytes *bytes;
454       gpointer data;
455
456       g_variant_ensure_size (value);
457       data = g_malloc (value->size);
458       g_variant_serialise (value, data);
459
460       g_variant_release_children (value);
461
462       bytes = g_bytes_new_take (data, value->size);
463       value->contents.serialised.data = g_bytes_get_data (bytes, NULL);
464       value->contents.serialised.bytes = bytes;
465       value->state |= STATE_SERIALISED;
466     }
467 }
468
469 /* < private >
470  * g_variant_alloc:
471  * @type: the type of the new instance
472  * @serialised: if the instance will be in serialised form
473  * @trusted: if the instance will be trusted
474  *
475  * Allocates a #GVariant instance and does some common work (such as
476  * looking up and filling in the type info), setting the state field,
477  * and setting the ref_count to 1.
478  *
479  * Returns: a new #GVariant with a floating reference
480  */
481 static GVariant *
482 g_variant_alloc (const GVariantType *type,
483                  gboolean            serialised,
484                  gboolean            trusted)
485 {
486   GVariant *value;
487
488   value = g_slice_new (GVariant);
489   value->type_info = g_variant_type_info_get (type);
490   value->state = (serialised ? STATE_SERIALISED : 0) |
491                  (trusted ? STATE_TRUSTED : 0) |
492                  STATE_FLOATING;
493   value->size = (gssize) -1;
494   g_atomic_ref_count_init (&value->ref_count);
495   value->depth = 0;
496
497   return value;
498 }
499
500 /**
501  * g_variant_new_from_bytes:
502  * @type: a #GVariantType
503  * @bytes: a #GBytes
504  * @trusted: if the contents of @bytes are trusted
505  *
506  * Constructs a new serialized-mode #GVariant instance.  This is the
507  * inner interface for creation of new serialized values that gets
508  * called from various functions in gvariant.c.
509  *
510  * A reference is taken on @bytes.
511  *
512  * The data in @bytes must be aligned appropriately for the @type being loaded.
513  * Otherwise this function will internally create a copy of the memory (since
514  * GLib 2.60) or (in older versions) fail and exit the process.
515  *
516  * Returns: (transfer none): a new #GVariant with a floating reference
517  *
518  * Since: 2.36
519  */
520 GVariant *
521 g_variant_new_from_bytes (const GVariantType *type,
522                           GBytes             *bytes,
523                           gboolean            trusted)
524 {
525   GVariant *value;
526   guint alignment;
527   gsize size;
528   GBytes *owned_bytes = NULL;
529   GVariantSerialised serialised;
530
531   value = g_variant_alloc (type, TRUE, trusted);
532
533   g_variant_type_info_query (value->type_info,
534                              &alignment, &size);
535
536   /* Ensure the alignment is correct. This is a huge performance hit if it’s
537    * not correct, but that’s better than aborting if a caller provides data
538    * with the wrong alignment (which is likely to happen very occasionally, and
539    * only cause an abort on some architectures — so is unlikely to be caught
540    * in testing). Callers can always actively ensure they use the correct
541    * alignment to avoid the performance hit. */
542   serialised.type_info = value->type_info;
543   serialised.data = (guchar *) g_bytes_get_data (bytes, &serialised.size);
544   serialised.depth = 0;
545
546   if (!g_variant_serialised_check (serialised))
547     {
548 #ifdef HAVE_POSIX_MEMALIGN
549       gpointer aligned_data = NULL;
550       gsize aligned_size = g_bytes_get_size (bytes);
551
552       /* posix_memalign() requires the alignment to be a multiple of
553        * sizeof(void*), and a power of 2. See g_variant_type_info_query() for
554        * details on the alignment format. */
555       if (posix_memalign (&aligned_data, MAX (sizeof (void *), alignment + 1),
556                           aligned_size) != 0)
557         g_error ("posix_memalign failed");
558
559       if (aligned_size != 0)
560         memcpy (aligned_data, g_bytes_get_data (bytes, NULL), aligned_size);
561
562       bytes = owned_bytes = g_bytes_new_with_free_func (aligned_data,
563                                                         aligned_size,
564                                                         free, aligned_data);
565       aligned_data = NULL;
566 #else
567       /* NOTE: there may be platforms that lack posix_memalign() and also
568        * have malloc() that returns non-8-aligned.  if so, we need to try
569        * harder here.
570        */
571       bytes = owned_bytes = g_bytes_new (g_bytes_get_data (bytes, NULL),
572                                          g_bytes_get_size (bytes));
573 #endif
574     }
575
576   value->contents.serialised.bytes = g_bytes_ref (bytes);
577
578   if (size && g_bytes_get_size (bytes) != size)
579     {
580       /* Creating a fixed-sized GVariant with a bytes of the wrong
581        * size.
582        *
583        * We should do the equivalent of pulling a fixed-sized child out
584        * of a brozen container (ie: data is NULL size is equal to the correct
585        * fixed size).
586        */
587       value->contents.serialised.data = NULL;
588       value->size = size;
589     }
590   else
591     {
592       value->contents.serialised.data = g_bytes_get_data (bytes, &value->size);
593     }
594
595   g_clear_pointer (&owned_bytes, g_bytes_unref);
596
597   return value;
598 }
599
600 /* -- internal -- */
601
602 /* < internal >
603  * g_variant_new_from_children:
604  * @type: a #GVariantType
605  * @children: an array of #GVariant pointers.  Consumed.
606  * @n_children: the length of @children
607  * @trusted: %TRUE if every child in @children in trusted
608  *
609  * Constructs a new tree-mode #GVariant instance.  This is the inner
610  * interface for creation of new serialized values that gets called from
611  * various functions in gvariant.c.
612  *
613  * @children is consumed by this function.  g_free() will be called on
614  * it some time later.
615  *
616  * Returns: a new #GVariant with a floating reference
617  */
618 GVariant *
619 g_variant_new_from_children (const GVariantType  *type,
620                              GVariant           **children,
621                              gsize                n_children,
622                              gboolean             trusted)
623 {
624   GVariant *value;
625
626   value = g_variant_alloc (type, FALSE, trusted);
627   value->contents.tree.children = children;
628   value->contents.tree.n_children = n_children;
629
630   return value;
631 }
632
633 /* < internal >
634  * g_variant_get_type_info:
635  * @value: a #GVariant
636  *
637  * Returns the #GVariantTypeInfo corresponding to the type of @value.  A
638  * reference is not added, so the return value is only good for the
639  * duration of the life of @value.
640  *
641  * Returns: the #GVariantTypeInfo for @value
642  */
643 GVariantTypeInfo *
644 g_variant_get_type_info (GVariant *value)
645 {
646   return value->type_info;
647 }
648
649 /* < internal >
650  * g_variant_is_trusted:
651  * @value: a #GVariant
652  *
653  * Determines if @value is trusted by #GVariant to contain only
654  * fully-valid data.  All values constructed solely via #GVariant APIs
655  * are trusted, but values containing data read in from other sources
656  * are usually not trusted.
657  *
658  * The main advantage of trusted data is that certain checks can be
659  * skipped.  For example, we don't need to check that a string is
660  * properly nul-terminated or that an object path is actually a
661  * properly-formatted object path.
662  *
663  * Returns: if @value is trusted
664  */
665 gboolean
666 g_variant_is_trusted (GVariant *value)
667 {
668   return (value->state & STATE_TRUSTED) != 0;
669 }
670
671 /* < internal >
672  * g_variant_get_depth:
673  * @value: a #GVariant
674  *
675  * Gets the nesting depth of a #GVariant. This is 0 for a #GVariant with no
676  * children.
677  *
678  * Returns: nesting depth of @value
679  */
680 gsize
681 g_variant_get_depth (GVariant *value)
682 {
683   return value->depth;
684 }
685
686 /* -- public -- */
687
688 /**
689  * g_variant_unref:
690  * @value: a #GVariant
691  *
692  * Decreases the reference count of @value.  When its reference count
693  * drops to 0, the memory used by the variant is freed.
694  *
695  * Since: 2.24
696  **/
697 void
698 g_variant_unref (GVariant *value)
699 {
700   g_return_if_fail (value != NULL);
701
702   if (g_atomic_ref_count_dec (&value->ref_count))
703     {
704       if G_UNLIKELY (value->state & STATE_LOCKED)
705         g_critical ("attempting to free a locked GVariant instance.  "
706                     "This should never happen.");
707
708       value->state |= STATE_LOCKED;
709
710       g_variant_type_info_unref (value->type_info);
711
712       if (value->state & STATE_SERIALISED)
713         g_bytes_unref (value->contents.serialised.bytes);
714       else
715         g_variant_release_children (value);
716
717       memset (value, 0, sizeof (GVariant));
718       g_slice_free (GVariant, value);
719     }
720 }
721
722 /**
723  * g_variant_ref:
724  * @value: a #GVariant
725  *
726  * Increases the reference count of @value.
727  *
728  * Returns: the same @value
729  *
730  * Since: 2.24
731  **/
732 GVariant *
733 g_variant_ref (GVariant *value)
734 {
735   g_return_val_if_fail (value != NULL, NULL);
736
737   g_atomic_ref_count_inc (&value->ref_count);
738
739   return value;
740 }
741
742 /**
743  * g_variant_ref_sink:
744  * @value: a #GVariant
745  *
746  * #GVariant uses a floating reference count system.  All functions with
747  * names starting with `g_variant_new_` return floating
748  * references.
749  *
750  * Calling g_variant_ref_sink() on a #GVariant with a floating reference
751  * will convert the floating reference into a full reference.  Calling
752  * g_variant_ref_sink() on a non-floating #GVariant results in an
753  * additional normal reference being added.
754  *
755  * In other words, if the @value is floating, then this call "assumes
756  * ownership" of the floating reference, converting it to a normal
757  * reference.  If the @value is not floating, then this call adds a
758  * new normal reference increasing the reference count by one.
759  *
760  * All calls that result in a #GVariant instance being inserted into a
761  * container will call g_variant_ref_sink() on the instance.  This means
762  * that if the value was just created (and has only its floating
763  * reference) then the container will assume sole ownership of the value
764  * at that point and the caller will not need to unreference it.  This
765  * makes certain common styles of programming much easier while still
766  * maintaining normal refcounting semantics in situations where values
767  * are not floating.
768  *
769  * Returns: the same @value
770  *
771  * Since: 2.24
772  **/
773 GVariant *
774 g_variant_ref_sink (GVariant *value)
775 {
776   g_return_val_if_fail (value != NULL, NULL);
777   g_return_val_if_fail (!g_atomic_ref_count_compare (&value->ref_count, 0), NULL);
778
779   g_variant_lock (value);
780
781   if (~value->state & STATE_FLOATING)
782     g_variant_ref (value);
783   else
784     value->state &= ~STATE_FLOATING;
785
786   g_variant_unlock (value);
787
788   return value;
789 }
790
791 /**
792  * g_variant_take_ref:
793  * @value: a #GVariant
794  *
795  * If @value is floating, sink it.  Otherwise, do nothing.
796  *
797  * Typically you want to use g_variant_ref_sink() in order to
798  * automatically do the correct thing with respect to floating or
799  * non-floating references, but there is one specific scenario where
800  * this function is helpful.
801  *
802  * The situation where this function is helpful is when creating an API
803  * that allows the user to provide a callback function that returns a
804  * #GVariant.  We certainly want to allow the user the flexibility to
805  * return a non-floating reference from this callback (for the case
806  * where the value that is being returned already exists).
807  *
808  * At the same time, the style of the #GVariant API makes it likely that
809  * for newly-created #GVariant instances, the user can be saved some
810  * typing if they are allowed to return a #GVariant with a floating
811  * reference.
812  *
813  * Using this function on the return value of the user's callback allows
814  * the user to do whichever is more convenient for them.  The caller
815  * will always receives exactly one full reference to the value: either
816  * the one that was returned in the first place, or a floating reference
817  * that has been converted to a full reference.
818  *
819  * This function has an odd interaction when combined with
820  * g_variant_ref_sink() running at the same time in another thread on
821  * the same #GVariant instance.  If g_variant_ref_sink() runs first then
822  * the result will be that the floating reference is converted to a hard
823  * reference.  If g_variant_take_ref() runs first then the result will
824  * be that the floating reference is converted to a hard reference and
825  * an additional reference on top of that one is added.  It is best to
826  * avoid this situation.
827  *
828  * Returns: the same @value
829  **/
830 GVariant *
831 g_variant_take_ref (GVariant *value)
832 {
833   g_return_val_if_fail (value != NULL, NULL);
834   g_return_val_if_fail (!g_atomic_ref_count_compare (&value->ref_count, 0), NULL);
835
836   g_atomic_int_and (&value->state, ~STATE_FLOATING);
837
838   return value;
839 }
840
841 /**
842  * g_variant_is_floating:
843  * @value: a #GVariant
844  *
845  * Checks whether @value has a floating reference count.
846  *
847  * This function should only ever be used to assert that a given variant
848  * is or is not floating, or for debug purposes. To acquire a reference
849  * to a variant that might be floating, always use g_variant_ref_sink()
850  * or g_variant_take_ref().
851  *
852  * See g_variant_ref_sink() for more information about floating reference
853  * counts.
854  *
855  * Returns: whether @value is floating
856  *
857  * Since: 2.26
858  **/
859 gboolean
860 g_variant_is_floating (GVariant *value)
861 {
862   g_return_val_if_fail (value != NULL, FALSE);
863
864   return (value->state & STATE_FLOATING) != 0;
865 }
866
867 /**
868  * g_variant_get_size:
869  * @value: a #GVariant instance
870  *
871  * Determines the number of bytes that would be required to store @value
872  * with g_variant_store().
873  *
874  * If @value has a fixed-sized type then this function always returned
875  * that fixed size.
876  *
877  * In the case that @value is already in serialized form or the size has
878  * already been calculated (ie: this function has been called before)
879  * then this function is O(1).  Otherwise, the size is calculated, an
880  * operation which is approximately O(n) in the number of values
881  * involved.
882  *
883  * Returns: the serialized size of @value
884  *
885  * Since: 2.24
886  **/
887 gsize
888 g_variant_get_size (GVariant *value)
889 {
890   g_variant_lock (value);
891   g_variant_ensure_size (value);
892   g_variant_unlock (value);
893
894   return value->size;
895 }
896
897 /**
898  * g_variant_get_data:
899  * @value: a #GVariant instance
900  *
901  * Returns a pointer to the serialized form of a #GVariant instance.
902  * The returned data may not be in fully-normalised form if read from an
903  * untrusted source.  The returned data must not be freed; it remains
904  * valid for as long as @value exists.
905  *
906  * If @value is a fixed-sized value that was deserialized from a
907  * corrupted serialized container then %NULL may be returned.  In this
908  * case, the proper thing to do is typically to use the appropriate
909  * number of nul bytes in place of @value.  If @value is not fixed-sized
910  * then %NULL is never returned.
911  *
912  * In the case that @value is already in serialized form, this function
913  * is O(1).  If the value is not already in serialized form,
914  * serialization occurs implicitly and is approximately O(n) in the size
915  * of the result.
916  *
917  * To deserialize the data returned by this function, in addition to the
918  * serialized data, you must know the type of the #GVariant, and (if the
919  * machine might be different) the endianness of the machine that stored
920  * it. As a result, file formats or network messages that incorporate
921  * serialized #GVariants must include this information either
922  * implicitly (for instance "the file always contains a
923  * %G_VARIANT_TYPE_VARIANT and it is always in little-endian order") or
924  * explicitly (by storing the type and/or endianness in addition to the
925  * serialized data).
926  *
927  * Returns: (transfer none): the serialized form of @value, or %NULL
928  *
929  * Since: 2.24
930  **/
931 gconstpointer
932 g_variant_get_data (GVariant *value)
933 {
934   g_variant_lock (value);
935   g_variant_ensure_serialised (value);
936   g_variant_unlock (value);
937
938   return value->contents.serialised.data;
939 }
940
941 /**
942  * g_variant_get_data_as_bytes:
943  * @value: a #GVariant
944  *
945  * Returns a pointer to the serialized form of a #GVariant instance.
946  * The semantics of this function are exactly the same as
947  * g_variant_get_data(), except that the returned #GBytes holds
948  * a reference to the variant data.
949  *
950  * Returns: (transfer full): A new #GBytes representing the variant data
951  *
952  * Since: 2.36
953  */ 
954 GBytes *
955 g_variant_get_data_as_bytes (GVariant *value)
956 {
957   const gchar *bytes_data;
958   const gchar *data;
959   gsize bytes_size;
960   gsize size;
961
962   g_variant_lock (value);
963   g_variant_ensure_serialised (value);
964   g_variant_unlock (value);
965
966   bytes_data = g_bytes_get_data (value->contents.serialised.bytes, &bytes_size);
967   data = value->contents.serialised.data;
968   size = value->size;
969
970   if (data == NULL)
971     {
972       g_assert (size == 0);
973       data = bytes_data;
974     }
975
976   if (data == bytes_data && size == bytes_size)
977     return g_bytes_ref (value->contents.serialised.bytes);
978   else
979     return g_bytes_new_from_bytes (value->contents.serialised.bytes,
980                                    data - bytes_data, size);
981 }
982
983
984 /**
985  * g_variant_n_children:
986  * @value: a container #GVariant
987  *
988  * Determines the number of children in a container #GVariant instance.
989  * This includes variants, maybes, arrays, tuples and dictionary
990  * entries.  It is an error to call this function on any other type of
991  * #GVariant.
992  *
993  * For variants, the return value is always 1.  For values with maybe
994  * types, it is always zero or one.  For arrays, it is the length of the
995  * array.  For tuples it is the number of tuple items (which depends
996  * only on the type).  For dictionary entries, it is always 2
997  *
998  * This function is O(1).
999  *
1000  * Returns: the number of children in the container
1001  *
1002  * Since: 2.24
1003  **/
1004 gsize
1005 g_variant_n_children (GVariant *value)
1006 {
1007   gsize n_children;
1008
1009   g_variant_lock (value);
1010
1011   if (value->state & STATE_SERIALISED)
1012     {
1013       GVariantSerialised serialised = {
1014         value->type_info,
1015         (gpointer) value->contents.serialised.data,
1016         value->size,
1017         value->depth,
1018       };
1019
1020       n_children = g_variant_serialised_n_children (serialised);
1021     }
1022   else
1023     n_children = value->contents.tree.n_children;
1024
1025   g_variant_unlock (value);
1026
1027   return n_children;
1028 }
1029
1030 /**
1031  * g_variant_get_child_value:
1032  * @value: a container #GVariant
1033  * @index_: the index of the child to fetch
1034  *
1035  * Reads a child item out of a container #GVariant instance.  This
1036  * includes variants, maybes, arrays, tuples and dictionary
1037  * entries.  It is an error to call this function on any other type of
1038  * #GVariant.
1039  *
1040  * It is an error if @index_ is greater than the number of child items
1041  * in the container.  See g_variant_n_children().
1042  *
1043  * The returned value is never floating.  You should free it with
1044  * g_variant_unref() when you're done with it.
1045  *
1046  * Note that values borrowed from the returned child are not guaranteed to
1047  * still be valid after the child is freed even if you still hold a reference
1048  * to @value, if @value has not been serialized at the time this function is
1049  * called. To avoid this, you can serialize @value by calling
1050  * g_variant_get_data() and optionally ignoring the return value.
1051  *
1052  * There may be implementation specific restrictions on deeply nested values,
1053  * which would result in the unit tuple being returned as the child value,
1054  * instead of further nested children. #GVariant is guaranteed to handle
1055  * nesting up to at least 64 levels.
1056  *
1057  * This function is O(1).
1058  *
1059  * Returns: (transfer full): the child at the specified index
1060  *
1061  * Since: 2.24
1062  **/
1063 GVariant *
1064 g_variant_get_child_value (GVariant *value,
1065                            gsize     index_)
1066 {
1067   g_return_val_if_fail (index_ < g_variant_n_children (value), NULL);
1068   g_return_val_if_fail (value->depth < G_MAXSIZE, NULL);
1069
1070   if (~g_atomic_int_get (&value->state) & STATE_SERIALISED)
1071     {
1072       g_variant_lock (value);
1073
1074       if (~value->state & STATE_SERIALISED)
1075         {
1076           GVariant *child;
1077
1078           child = g_variant_ref (value->contents.tree.children[index_]);
1079           g_variant_unlock (value);
1080
1081           return child;
1082         }
1083
1084       g_variant_unlock (value);
1085     }
1086
1087   {
1088     GVariantSerialised serialised = {
1089       value->type_info,
1090       (gpointer) value->contents.serialised.data,
1091       value->size,
1092       value->depth,
1093     };
1094     GVariantSerialised s_child;
1095     GVariant *child;
1096
1097     /* get the serializer to extract the serialized data for the child
1098      * from the serialized data for the container
1099      */
1100     s_child = g_variant_serialised_get_child (serialised, index_);
1101
1102     /* Check whether this would cause nesting too deep. If so, return a fake
1103      * child. The only situation we expect this to happen in is with a variant,
1104      * as all other deeply-nested types have a static type, and hence should
1105      * have been rejected earlier. In the case of a variant whose nesting plus
1106      * the depth of its child is too great, return a unit variant () instead of
1107      * the real child. */
1108     if (!(value->state & STATE_TRUSTED) &&
1109         g_variant_type_info_query_depth (s_child.type_info) >=
1110         G_VARIANT_MAX_RECURSION_DEPTH - value->depth)
1111       {
1112         g_assert (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT));
1113         return g_variant_new_tuple (NULL, 0);
1114       }
1115
1116     /* create a new serialized instance out of it */
1117     child = g_slice_new (GVariant);
1118     child->type_info = s_child.type_info;
1119     child->state = (value->state & STATE_TRUSTED) |
1120                    STATE_SERIALISED;
1121     child->size = s_child.size;
1122     g_atomic_ref_count_init (&child->ref_count);
1123     child->depth = value->depth + 1;
1124     child->contents.serialised.bytes =
1125       g_bytes_ref (value->contents.serialised.bytes);
1126     child->contents.serialised.data = s_child.data;
1127
1128     return child;
1129   }
1130 }
1131
1132 /**
1133  * g_variant_store:
1134  * @value: the #GVariant to store
1135  * @data: (not nullable): the location to store the serialized data at
1136  *
1137  * Stores the serialized form of @value at @data.  @data should be
1138  * large enough.  See g_variant_get_size().
1139  *
1140  * The stored data is in machine native byte order but may not be in
1141  * fully-normalised form if read from an untrusted source.  See
1142  * g_variant_get_normal_form() for a solution.
1143  *
1144  * As with g_variant_get_data(), to be able to deserialize the
1145  * serialized variant successfully, its type and (if the destination
1146  * machine might be different) its endianness must also be available.
1147  *
1148  * This function is approximately O(n) in the size of @data.
1149  *
1150  * Since: 2.24
1151  **/
1152 void
1153 g_variant_store (GVariant *value,
1154                  gpointer  data)
1155 {
1156   g_variant_lock (value);
1157
1158   if (value->state & STATE_SERIALISED)
1159     {
1160       if (value->contents.serialised.data != NULL)
1161         memcpy (data, value->contents.serialised.data, value->size);
1162       else
1163         memset (data, 0, value->size);
1164     }
1165   else
1166     g_variant_serialise (value, data);
1167
1168   g_variant_unlock (value);
1169 }
1170
1171 /**
1172  * g_variant_is_normal_form:
1173  * @value: a #GVariant instance
1174  *
1175  * Checks if @value is in normal form.
1176  *
1177  * The main reason to do this is to detect if a given chunk of
1178  * serialized data is in normal form: load the data into a #GVariant
1179  * using g_variant_new_from_data() and then use this function to
1180  * check.
1181  *
1182  * If @value is found to be in normal form then it will be marked as
1183  * being trusted.  If the value was already marked as being trusted then
1184  * this function will immediately return %TRUE.
1185  *
1186  * There may be implementation specific restrictions on deeply nested values.
1187  * GVariant is guaranteed to handle nesting up to at least 64 levels.
1188  *
1189  * Returns: %TRUE if @value is in normal form
1190  *
1191  * Since: 2.24
1192  **/
1193 gboolean
1194 g_variant_is_normal_form (GVariant *value)
1195 {
1196   if (value->state & STATE_TRUSTED)
1197     return TRUE;
1198
1199   g_variant_lock (value);
1200
1201   if (value->depth >= G_VARIANT_MAX_RECURSION_DEPTH)
1202     return FALSE;
1203
1204   if (value->state & STATE_SERIALISED)
1205     {
1206       GVariantSerialised serialised = {
1207         value->type_info,
1208         (gpointer) value->contents.serialised.data,
1209         value->size,
1210         value->depth
1211       };
1212
1213       if (g_variant_serialised_is_normal (serialised))
1214         value->state |= STATE_TRUSTED;
1215     }
1216   else
1217     {
1218       gboolean normal = TRUE;
1219       gsize i;
1220
1221       for (i = 0; i < value->contents.tree.n_children; i++)
1222         normal &= g_variant_is_normal_form (value->contents.tree.children[i]);
1223
1224       if (normal)
1225         value->state |= STATE_TRUSTED;
1226     }
1227
1228   g_variant_unlock (value);
1229
1230   return (value->state & STATE_TRUSTED) != 0;
1231 }