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