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