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