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