GVariant: calculate size at construction
[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 /* This begins the main body of the recursive serialiser.
253  *
254  * There are 3 functions here that work as a team with the serialiser to
255  * get things done.  g_variant_store() has a trivial role, but as a
256  * public API function, it has its definition elsewhere.
257  *
258  * Note that "serialisation" of an instance does not mean that the
259  * instance is converted to serialised form -- it means that the
260  * serialised form of an instance is written to an external buffer.
261  * g_variant_ensure_serialised() (which is not part of this set of
262  * functions) is the function that is responsible for converting an
263  * instance to serialised form.
264  *
265  * We are only concerned here with container types since non-container
266  * instances are always in serialised form.  For these instances,
267  * storing their serialised form merely involves a memcpy().
268  *
269  * Converting to serialised form:
270  *
271  *   The first step in the process of converting a GVariant to
272  *   serialised form is to allocate a buffer.  The size of the buffer is
273  *   always known because we computed at construction time of the
274  *   GVariant.
275  *
276  *   After the buffer has been allocated, g_variant_serialise() is
277  *   called on the container.  This invokes the serialiser code to write
278  *   the bytes to the container.  The serialiser is passed
279  *   g_variant_fill_gvs() as a callback.
280  *
281  *   At the time that g_variant_fill_gvs() is called for each child, the
282  *   child is given a pointer to a sub-region of the allocated buffer
283  *   where it should write its data.  This is done by calling
284  *   g_variant_store().  In the event that the instance is in serialised
285  *   form this means a memcpy() of the serialised data into the
286  *   allocated buffer.  In the event that the instance is in tree form
287  *   this means a recursive call back into g_variant_serialise().
288  *
289  *
290  * The forward declaration here allows corecursion via callback:
291  */
292 static void g_variant_fill_gvs (GVariantSerialised *, gpointer);
293
294 /* < private >
295  * g_variant_serialise:
296  * @value: a #GVariant
297  * @data: an appropriately-sized buffer
298  *
299  * Serialises @value into @data.  @value must be in tree form.
300  *
301  * No change is made to @value.
302  *
303  * The current thread must hold the lock on @value.
304  */
305 static void
306 g_variant_serialise (GVariant *value,
307                      gpointer  data)
308 {
309   GVariantSerialised serialised = { 0, };
310   gpointer *children;
311   gsize n_children;
312
313   g_assert (~value->state & STATE_SERIALISED);
314   g_assert (value->state & STATE_LOCKED);
315
316   serialised.type_info = value->type_info;
317   serialised.size = value->size;
318   serialised.data = data;
319
320   children = (gpointer *) value->contents.tree.children;
321   n_children = value->contents.tree.n_children;
322
323   g_variant_serialiser_serialise (serialised, g_variant_fill_gvs,
324                                   children, n_children);
325 }
326
327 /* < private >
328  * g_variant_fill_gvs:
329  * @serialised: a pointer to a #GVariantSerialised
330  * @data: a #GVariant instance
331  *
332  * This is the callback that is passed by a tree-form container instance
333  * to the serialiser.  This callback gets called on each child of the
334  * container.  Each child is responsible for performing the following
335  * actions:
336  *
337  *  - reporting its type
338  *
339  *  - reporting its serialised size
340  *
341  *  - possibly storing its serialised form into the provided buffer
342  *
343  * This callback is also used during g_variant_new_from_children() in
344  * order to discover the size and type of each child.
345  */
346 static void
347 g_variant_fill_gvs (GVariantSerialised *serialised,
348                     gpointer            data)
349 {
350   GVariant *value = data;
351
352   if (serialised->type_info == NULL)
353     serialised->type_info = value->type_info;
354   g_assert (serialised->type_info == value->type_info);
355
356   if (serialised->size == 0)
357     serialised->size = value->size;
358   g_assert (serialised->size == value->size);
359
360   if (serialised->data)
361     /* g_variant_store() is a public API, so it
362      * it will reacquire the lock if it needs to.
363      */
364     g_variant_store (value, serialised->data);
365 }
366
367 /* this ends the main body of the recursive serialiser */
368
369 /* < private >
370  * g_variant_ensure_serialised:
371  * @value: a #GVariant
372  *
373  * Ensures that @value is in serialised form.
374  *
375  * If @value is in tree form then this function allocates a buffer of
376  * that size and serialises the instance into the buffer.  The
377  * 'children' array is then released and the instance is set to
378  * serialised form based on the contents of the buffer.
379  *
380  * The current thread must hold the lock on @value.
381  */
382 static void
383 g_variant_ensure_serialised (GVariant *value)
384 {
385   g_assert (value->state & STATE_LOCKED);
386
387   if (~value->state & STATE_SERIALISED)
388     {
389       GBytes *bytes;
390       gpointer data;
391
392       data = g_malloc (value->size);
393       g_variant_serialise (value, data);
394
395       g_variant_release_children (value);
396
397       bytes = g_bytes_new_take (data, value->size);
398       value->contents.serialised.data = g_bytes_get_data (bytes, NULL);
399       value->contents.serialised.bytes = bytes;
400       value->state |= STATE_SERIALISED;
401     }
402 }
403
404 /* < private >
405  * g_variant_alloc:
406  * @type: the type of the new instance
407  * @serialised: if the instance will be in serialised form
408  * @trusted: if the instance will be trusted
409  *
410  * Allocates a #GVariant instance and does some common work (such as
411  * looking up and filling in the type info), setting the state field,
412  * and setting the ref_count to 1.
413  *
414  * Returns: a new #GVariant with a floating reference
415  */
416 static GVariant *
417 g_variant_alloc (const GVariantType *type,
418                  gboolean            serialised,
419                  gboolean            trusted)
420 {
421   GVariant *value;
422
423   value = g_slice_new (GVariant);
424   value->type_info = g_variant_type_info_get (type);
425   value->state = (serialised ? STATE_SERIALISED : 0) |
426                  (trusted ? STATE_TRUSTED : 0) |
427                  STATE_FLOATING;
428   value->ref_count = 1;
429
430   return value;
431 }
432
433 /**
434  * g_variant_new_from_bytes:
435  * @type: a #GVariantType
436  * @bytes: a #GBytes
437  * @trusted: if the contents of @bytes are trusted
438  *
439  * Constructs a new serialised-mode #GVariant instance.  This is the
440  * inner interface for creation of new serialised values that gets
441  * called from various functions in gvariant.c.
442  *
443  * A reference is taken on @bytes.
444  *
445  * Returns: (transfer none): a new #GVariant with a floating reference
446  *
447  * Since: 2.36
448  */
449 GVariant *
450 g_variant_new_from_bytes (const GVariantType *type,
451                           GBytes             *bytes,
452                           gboolean            trusted)
453 {
454   GVariant *value;
455   guint alignment;
456   gsize size;
457
458   value = g_variant_alloc (type, TRUE, trusted);
459
460   value->contents.serialised.bytes = g_bytes_ref (bytes);
461
462   g_variant_type_info_query (value->type_info,
463                              &alignment, &size);
464
465   if (size && g_bytes_get_size (bytes) != size)
466     {
467       /* Creating a fixed-sized GVariant with a bytes of the wrong
468        * size.
469        *
470        * We should do the equivalent of pulling a fixed-sized child out
471        * of a brozen container (ie: data is NULL size is equal to the correct
472        * fixed size).
473        */
474       value->contents.serialised.data = NULL;
475       value->size = size;
476     }
477   else
478     {
479       value->contents.serialised.data = g_bytes_get_data (bytes, &value->size);
480     }
481
482   return value;
483 }
484
485 /* -- internal -- */
486
487 /* < internal >
488  * g_variant_new_from_children:
489  * @type: a #GVariantType
490  * @children: an array of #GVariant pointers.  Consumed.
491  * @n_children: the length of @children
492  * @trusted: %TRUE if every child in @children in trusted
493  *
494  * Constructs a new tree-mode #GVariant instance.  This is the inner
495  * interface for creation of new serialised values that gets called from
496  * various functions in gvariant.c.
497  *
498  * @children is consumed by this function.  g_free() will be called on
499  * it some time later.
500  *
501  * Returns: a new #GVariant with a floating reference
502  */
503 GVariant *
504 g_variant_new_from_children (const GVariantType  *type,
505                              GVariant           **children,
506                              gsize                n_children,
507                              gboolean             trusted)
508 {
509   GVariant *value;
510
511   value = g_variant_alloc (type, FALSE, trusted);
512   value->contents.tree.children = children;
513   value->contents.tree.n_children = n_children;
514   value->size = g_variant_serialiser_needed_size (value->type_info, g_variant_fill_gvs,
515                                                   (gpointer *) children, n_children);
516
517   return value;
518 }
519
520 /* < internal >
521  * g_variant_get_type_info:
522  * @value: a #GVariant
523  *
524  * Returns the #GVariantTypeInfo corresponding to the type of @value.  A
525  * reference is not added, so the return value is only good for the
526  * duration of the life of @value.
527  *
528  * Returns: the #GVariantTypeInfo for @value
529  */
530 GVariantTypeInfo *
531 g_variant_get_type_info (GVariant *value)
532 {
533   return value->type_info;
534 }
535
536 /* < internal >
537  * g_variant_is_trusted:
538  * @value: a #GVariant
539  *
540  * Determines if @value is trusted by #GVariant to contain only
541  * fully-valid data.  All values constructed solely via #GVariant APIs
542  * are trusted, but values containing data read in from other sources
543  * are usually not trusted.
544  *
545  * The main advantage of trusted data is that certain checks can be
546  * skipped.  For example, we don't need to check that a string is
547  * properly nul-terminated or that an object path is actually a
548  * properly-formatted object path.
549  *
550  * Returns: if @value is trusted
551  */
552 gboolean
553 g_variant_is_trusted (GVariant *value)
554 {
555   return (value->state & STATE_TRUSTED) != 0;
556 }
557
558 /* -- public -- */
559
560 /**
561  * g_variant_unref:
562  * @value: a #GVariant
563  *
564  * Decreases the reference count of @value.  When its reference count
565  * drops to 0, the memory used by the variant is freed.
566  *
567  * Since: 2.24
568  **/
569 void
570 g_variant_unref (GVariant *value)
571 {
572   g_return_if_fail (value != NULL);
573   g_return_if_fail (value->ref_count > 0);
574
575   if (g_atomic_int_dec_and_test (&value->ref_count))
576     {
577       if G_UNLIKELY (value->state & STATE_LOCKED)
578         g_critical ("attempting to free a locked GVariant instance.  "
579                     "This should never happen.");
580
581       value->state |= STATE_LOCKED;
582
583       g_variant_type_info_unref (value->type_info);
584
585       if (value->state & STATE_SERIALISED)
586         g_bytes_unref (value->contents.serialised.bytes);
587       else
588         g_variant_release_children (value);
589
590       memset (value, 0, sizeof (GVariant));
591       g_slice_free (GVariant, value);
592     }
593 }
594
595 /**
596  * g_variant_ref:
597  * @value: a #GVariant
598  *
599  * Increases the reference count of @value.
600  *
601  * Returns: the same @value
602  *
603  * Since: 2.24
604  **/
605 GVariant *
606 g_variant_ref (GVariant *value)
607 {
608   g_return_val_if_fail (value != NULL, NULL);
609   g_return_val_if_fail (value->ref_count > 0, NULL);
610
611   g_atomic_int_inc (&value->ref_count);
612
613   return value;
614 }
615
616 /**
617  * g_variant_ref_sink:
618  * @value: a #GVariant
619  *
620  * #GVariant uses a floating reference count system.  All functions with
621  * names starting with `g_variant_new_` return floating
622  * references.
623  *
624  * Calling g_variant_ref_sink() on a #GVariant with a floating reference
625  * will convert the floating reference into a full reference.  Calling
626  * g_variant_ref_sink() on a non-floating #GVariant results in an
627  * additional normal reference being added.
628  *
629  * In other words, if the @value is floating, then this call "assumes
630  * ownership" of the floating reference, converting it to a normal
631  * reference.  If the @value is not floating, then this call adds a
632  * new normal reference increasing the reference count by one.
633  *
634  * All calls that result in a #GVariant instance being inserted into a
635  * container will call g_variant_ref_sink() on the instance.  This means
636  * that if the value was just created (and has only its floating
637  * reference) then the container will assume sole ownership of the value
638  * at that point and the caller will not need to unreference it.  This
639  * makes certain common styles of programming much easier while still
640  * maintaining normal refcounting semantics in situations where values
641  * are not floating.
642  *
643  * Returns: the same @value
644  *
645  * Since: 2.24
646  **/
647 GVariant *
648 g_variant_ref_sink (GVariant *value)
649 {
650   g_return_val_if_fail (value != NULL, NULL);
651   g_return_val_if_fail (value->ref_count > 0, NULL);
652
653   g_variant_lock (value);
654
655   if (~value->state & STATE_FLOATING)
656     g_variant_ref (value);
657   else
658     value->state &= ~STATE_FLOATING;
659
660   g_variant_unlock (value);
661
662   return value;
663 }
664
665 /**
666  * g_variant_take_ref:
667  * @value: a #GVariant
668  *
669  * If @value is floating, sink it.  Otherwise, do nothing.
670  *
671  * Typically you want to use g_variant_ref_sink() in order to
672  * automatically do the correct thing with respect to floating or
673  * non-floating references, but there is one specific scenario where
674  * this function is helpful.
675  *
676  * The situation where this function is helpful is when creating an API
677  * that allows the user to provide a callback function that returns a
678  * #GVariant.  We certainly want to allow the user the flexibility to
679  * return a non-floating reference from this callback (for the case
680  * where the value that is being returned already exists).
681  *
682  * At the same time, the style of the #GVariant API makes it likely that
683  * for newly-created #GVariant instances, the user can be saved some
684  * typing if they are allowed to return a #GVariant with a floating
685  * reference.
686  *
687  * Using this function on the return value of the user's callback allows
688  * the user to do whichever is more convenient for them.  The caller
689  * will alway receives exactly one full reference to the value: either
690  * the one that was returned in the first place, or a floating reference
691  * that has been converted to a full reference.
692  *
693  * This function has an odd interaction when combined with
694  * g_variant_ref_sink() running at the same time in another thread on
695  * the same #GVariant instance.  If g_variant_ref_sink() runs first then
696  * the result will be that the floating reference is converted to a hard
697  * reference.  If g_variant_take_ref() runs first then the result will
698  * be that the floating reference is converted to a hard reference and
699  * an additional reference on top of that one is added.  It is best to
700  * avoid this situation.
701  *
702  * Returns: the same @value
703  **/
704 GVariant *
705 g_variant_take_ref (GVariant *value)
706 {
707   g_return_val_if_fail (value != NULL, NULL);
708   g_return_val_if_fail (value->ref_count > 0, NULL);
709
710   g_atomic_int_and (&value->state, ~STATE_FLOATING);
711
712   return value;
713 }
714
715 /**
716  * g_variant_is_floating:
717  * @value: a #GVariant
718  *
719  * Checks whether @value has a floating reference count.
720  *
721  * This function should only ever be used to assert that a given variant
722  * is or is not floating, or for debug purposes. To acquire a reference
723  * to a variant that might be floating, always use g_variant_ref_sink()
724  * or g_variant_take_ref().
725  *
726  * See g_variant_ref_sink() for more information about floating reference
727  * counts.
728  *
729  * Returns: whether @value is floating
730  *
731  * Since: 2.26
732  **/
733 gboolean
734 g_variant_is_floating (GVariant *value)
735 {
736   g_return_val_if_fail (value != NULL, FALSE);
737
738   return (value->state & STATE_FLOATING) != 0;
739 }
740
741 /**
742  * g_variant_get_size:
743  * @value: a #GVariant instance
744  *
745  * Determines the number of bytes that would be required to store @value
746  * with g_variant_store().
747  *
748  * If @value has a fixed-sized type then this function always returned
749  * that fixed size.
750  *
751  * In the case that @value is already in serialised form or the size has
752  * already been calculated (ie: this function has been called before)
753  * then this function is O(1).  Otherwise, the size is calculated, an
754  * operation which is approximately O(n) in the number of values
755  * involved.
756  *
757  * Returns: the serialised size of @value
758  *
759  * Since: 2.24
760  **/
761 gsize
762 g_variant_get_size (GVariant *value)
763 {
764   return value->size;
765 }
766
767 /**
768  * g_variant_get_data:
769  * @value: a #GVariant instance
770  *
771  * Returns a pointer to the serialised form of a #GVariant instance.
772  * The returned data may not be in fully-normalised form if read from an
773  * untrusted source.  The returned data must not be freed; it remains
774  * valid for as long as @value exists.
775  *
776  * If @value is a fixed-sized value that was deserialised from a
777  * corrupted serialised container then %NULL may be returned.  In this
778  * case, the proper thing to do is typically to use the appropriate
779  * number of nul bytes in place of @value.  If @value is not fixed-sized
780  * then %NULL is never returned.
781  *
782  * In the case that @value is already in serialised form, this function
783  * is O(1).  If the value is not already in serialised form,
784  * serialisation occurs implicitly and is approximately O(n) in the size
785  * of the result.
786  *
787  * To deserialise the data returned by this function, in addition to the
788  * serialised data, you must know the type of the #GVariant, and (if the
789  * machine might be different) the endianness of the machine that stored
790  * it. As a result, file formats or network messages that incorporate
791  * serialised #GVariants must include this information either
792  * implicitly (for instance "the file always contains a
793  * %G_VARIANT_TYPE_VARIANT and it is always in little-endian order") or
794  * explicitly (by storing the type and/or endianness in addition to the
795  * serialised data).
796  *
797  * Returns: (transfer none): the serialised form of @value, or %NULL
798  *
799  * Since: 2.24
800  **/
801 gconstpointer
802 g_variant_get_data (GVariant *value)
803 {
804   g_variant_lock (value);
805   g_variant_ensure_serialised (value);
806   g_variant_unlock (value);
807
808   return value->contents.serialised.data;
809 }
810
811 /**
812  * g_variant_get_data_as_bytes:
813  * @value: a #GVariant
814  *
815  * Returns a pointer to the serialised form of a #GVariant instance.
816  * The semantics of this function are exactly the same as
817  * g_variant_get_data(), except that the returned #GBytes holds
818  * a reference to the variant data.
819  *
820  * Returns: (transfer full): A new #GBytes representing the variant data
821  *
822  * Since: 2.36
823  */ 
824 GBytes *
825 g_variant_get_data_as_bytes (GVariant *value)
826 {
827   const gchar *bytes_data;
828   const gchar *data;
829   gsize bytes_size;
830   gsize size;
831
832   g_variant_lock (value);
833   g_variant_ensure_serialised (value);
834   g_variant_unlock (value);
835
836   bytes_data = g_bytes_get_data (value->contents.serialised.bytes, &bytes_size);
837   data = value->contents.serialised.data;
838   size = value->size;
839
840   if (data == bytes_data && size == bytes_size)
841     return g_bytes_ref (value->contents.serialised.bytes);
842   else
843     return g_bytes_new_from_bytes (value->contents.serialised.bytes,
844                                    data - bytes_data, size);
845 }
846
847
848 /**
849  * g_variant_n_children:
850  * @value: a container #GVariant
851  *
852  * Determines the number of children in a container #GVariant instance.
853  * This includes variants, maybes, arrays, tuples and dictionary
854  * entries.  It is an error to call this function on any other type of
855  * #GVariant.
856  *
857  * For variants, the return value is always 1.  For values with maybe
858  * types, it is always zero or one.  For arrays, it is the length of the
859  * array.  For tuples it is the number of tuple items (which depends
860  * only on the type).  For dictionary entries, it is always 2
861  *
862  * This function is O(1).
863  *
864  * Returns: the number of children in the container
865  *
866  * Since: 2.24
867  **/
868 gsize
869 g_variant_n_children (GVariant *value)
870 {
871   gsize n_children;
872
873   g_variant_lock (value);
874
875   if (value->state & STATE_SERIALISED)
876     {
877       GVariantSerialised serialised = {
878         value->type_info,
879         (gpointer) value->contents.serialised.data,
880         value->size
881       };
882
883       n_children = g_variant_serialised_n_children (serialised);
884     }
885   else
886     n_children = value->contents.tree.n_children;
887
888   g_variant_unlock (value);
889
890   return n_children;
891 }
892
893 /**
894  * g_variant_get_child_value:
895  * @value: a container #GVariant
896  * @index_: the index of the child to fetch
897  *
898  * Reads a child item out of a container #GVariant instance.  This
899  * includes variants, maybes, arrays, tuples and dictionary
900  * entries.  It is an error to call this function on any other type of
901  * #GVariant.
902  *
903  * It is an error if @index_ is greater than the number of child items
904  * in the container.  See g_variant_n_children().
905  *
906  * The returned value is never floating.  You should free it with
907  * g_variant_unref() when you're done with it.
908  *
909  * This function is O(1).
910  *
911  * Returns: (transfer full): the child at the specified index
912  *
913  * Since: 2.24
914  **/
915 GVariant *
916 g_variant_get_child_value (GVariant *value,
917                            gsize     index_)
918 {
919   g_return_val_if_fail (index_ < g_variant_n_children (value), NULL);
920
921   if (~g_atomic_int_get (&value->state) & STATE_SERIALISED)
922     {
923       g_variant_lock (value);
924
925       if (~value->state & STATE_SERIALISED)
926         {
927           GVariant *child;
928
929           child = g_variant_ref (value->contents.tree.children[index_]);
930           g_variant_unlock (value);
931
932           return child;
933         }
934
935       g_variant_unlock (value);
936     }
937
938   {
939     GVariantSerialised serialised = {
940       value->type_info,
941       (gpointer) value->contents.serialised.data,
942       value->size
943     };
944     GVariantSerialised s_child;
945     GVariant *child;
946
947     /* get the serialiser to extract the serialised data for the child
948      * from the serialised data for the container
949      */
950     s_child = g_variant_serialised_get_child (serialised, index_);
951
952     /* create a new serialised instance out of it */
953     child = g_slice_new (GVariant);
954     child->type_info = s_child.type_info;
955     child->state = (value->state & STATE_TRUSTED) |
956                    STATE_SERIALISED;
957     child->size = s_child.size;
958     child->ref_count = 1;
959     child->contents.serialised.bytes =
960       g_bytes_ref (value->contents.serialised.bytes);
961     child->contents.serialised.data = s_child.data;
962
963     return child;
964   }
965 }
966
967 /**
968  * g_variant_store:
969  * @value: the #GVariant to store
970  * @data: the location to store the serialised data at
971  *
972  * Stores the serialised form of @value at @data.  @data should be
973  * large enough.  See g_variant_get_size().
974  *
975  * The stored data is in machine native byte order but may not be in
976  * fully-normalised form if read from an untrusted source.  See
977  * g_variant_get_normal_form() for a solution.
978  *
979  * As with g_variant_get_data(), to be able to deserialise the
980  * serialised variant successfully, its type and (if the destination
981  * machine might be different) its endianness must also be available.
982  *
983  * This function is approximately O(n) in the size of @data.
984  *
985  * Since: 2.24
986  **/
987 void
988 g_variant_store (GVariant *value,
989                  gpointer  data)
990 {
991   g_variant_lock (value);
992
993   if (value->state & STATE_SERIALISED)
994     {
995       if (value->contents.serialised.data != NULL)
996         memcpy (data, value->contents.serialised.data, value->size);
997       else
998         memset (data, 0, value->size);
999     }
1000   else
1001     g_variant_serialise (value, data);
1002
1003   g_variant_unlock (value);
1004 }
1005
1006 /**
1007  * g_variant_is_normal_form:
1008  * @value: a #GVariant instance
1009  *
1010  * Checks if @value is in normal form.
1011  *
1012  * The main reason to do this is to detect if a given chunk of
1013  * serialised data is in normal form: load the data into a #GVariant
1014  * using g_variant_new_from_data() and then use this function to
1015  * check.
1016  *
1017  * If @value is found to be in normal form then it will be marked as
1018  * being trusted.  If the value was already marked as being trusted then
1019  * this function will immediately return %TRUE.
1020  *
1021  * Returns: %TRUE if @value is in normal form
1022  *
1023  * Since: 2.24
1024  **/
1025 gboolean
1026 g_variant_is_normal_form (GVariant *value)
1027 {
1028   if (value->state & STATE_TRUSTED)
1029     return TRUE;
1030
1031   g_variant_lock (value);
1032
1033   if (value->state & STATE_SERIALISED)
1034     {
1035       GVariantSerialised serialised = {
1036         value->type_info,
1037         (gpointer) value->contents.serialised.data,
1038         value->size
1039       };
1040
1041       if (g_variant_serialised_is_normal (serialised))
1042         value->state |= STATE_TRUSTED;
1043     }
1044   else
1045     {
1046       gboolean normal = TRUE;
1047       gsize i;
1048
1049       for (i = 0; i < value->contents.tree.n_children; i++)
1050         normal &= g_variant_is_normal_form (value->contents.tree.children[i]);
1051
1052       if (normal)
1053         value->state |= STATE_TRUSTED;
1054     }
1055
1056   g_variant_unlock (value);
1057
1058   return (value->state & STATE_TRUSTED) != 0;
1059 }