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 if (aligned_size != 0)
558 memcpy (aligned_data, g_bytes_get_data (bytes, NULL), aligned_size);
559
560 bytes = owned_bytes = g_bytes_new_with_free_func (aligned_data,
561 aligned_size,
562 free, aligned_data);
563 aligned_data = NULL;
564 #else
565 /* NOTE: there may be platforms that lack posix_memalign() and also
566 * have malloc() that returns non-8-aligned. if so, we need to try
567 * harder here.
568 */
569 bytes = owned_bytes = g_bytes_new (g_bytes_get_data (bytes, NULL),
570 g_bytes_get_size (bytes));
571 #endif
572 }
573
574 value->contents.serialised.bytes = g_bytes_ref (bytes);
575
576 if (size && g_bytes_get_size (bytes) != size)
577 {
578 /* Creating a fixed-sized GVariant with a bytes of the wrong
579 * size.
580 *
581 * We should do the equivalent of pulling a fixed-sized child out
582 * of a brozen container (ie: data is NULL size is equal to the correct
583 * fixed size).
584 */
585 value->contents.serialised.data = NULL;
586 value->size = size;
587 }
588 else
589 {
590 value->contents.serialised.data = g_bytes_get_data (bytes, &value->size);
591 }
592
593 g_clear_pointer (&owned_bytes, g_bytes_unref);
594
595 return value;
596 }
597
598 /* -- internal -- */
599
600 /* < internal >
601 * g_variant_new_from_children:
602 * @type: a #GVariantType
603 * @children: an array of #GVariant pointers. Consumed.
604 * @n_children: the length of @children
605 * @trusted: %TRUE if every child in @children in trusted
606 *
607 * Constructs a new tree-mode #GVariant instance. This is the inner
608 * interface for creation of new serialised values that gets called from
609 * various functions in gvariant.c.
610 *
611 * @children is consumed by this function. g_free() will be called on
612 * it some time later.
613 *
614 * Returns: a new #GVariant with a floating reference
615 */
616 GVariant *
g_variant_new_from_children(const GVariantType * type,GVariant ** children,gsize n_children,gboolean trusted)617 g_variant_new_from_children (const GVariantType *type,
618 GVariant **children,
619 gsize n_children,
620 gboolean trusted)
621 {
622 GVariant *value;
623
624 value = g_variant_alloc (type, FALSE, trusted);
625 value->contents.tree.children = children;
626 value->contents.tree.n_children = n_children;
627
628 return value;
629 }
630
631 /* < internal >
632 * g_variant_get_type_info:
633 * @value: a #GVariant
634 *
635 * Returns the #GVariantTypeInfo corresponding to the type of @value. A
636 * reference is not added, so the return value is only good for the
637 * duration of the life of @value.
638 *
639 * Returns: the #GVariantTypeInfo for @value
640 */
641 GVariantTypeInfo *
g_variant_get_type_info(GVariant * value)642 g_variant_get_type_info (GVariant *value)
643 {
644 return value->type_info;
645 }
646
647 /* < internal >
648 * g_variant_is_trusted:
649 * @value: a #GVariant
650 *
651 * Determines if @value is trusted by #GVariant to contain only
652 * fully-valid data. All values constructed solely via #GVariant APIs
653 * are trusted, but values containing data read in from other sources
654 * are usually not trusted.
655 *
656 * The main advantage of trusted data is that certain checks can be
657 * skipped. For example, we don't need to check that a string is
658 * properly nul-terminated or that an object path is actually a
659 * properly-formatted object path.
660 *
661 * Returns: if @value is trusted
662 */
663 gboolean
g_variant_is_trusted(GVariant * value)664 g_variant_is_trusted (GVariant *value)
665 {
666 return (value->state & STATE_TRUSTED) != 0;
667 }
668
669 /* < internal >
670 * g_variant_get_depth:
671 * @value: a #GVariant
672 *
673 * Gets the nesting depth of a #GVariant. This is 0 for a #GVariant with no
674 * children.
675 *
676 * Returns: nesting depth of @value
677 */
678 gsize
g_variant_get_depth(GVariant * value)679 g_variant_get_depth (GVariant *value)
680 {
681 return value->depth;
682 }
683
684 /* -- public -- */
685
686 /**
687 * g_variant_unref:
688 * @value: a #GVariant
689 *
690 * Decreases the reference count of @value. When its reference count
691 * drops to 0, the memory used by the variant is freed.
692 *
693 * Since: 2.24
694 **/
695 void
g_variant_unref(GVariant * value)696 g_variant_unref (GVariant *value)
697 {
698 g_return_if_fail (value != NULL);
699
700 if (g_atomic_ref_count_dec (&value->ref_count))
701 {
702 if G_UNLIKELY (value->state & STATE_LOCKED)
703 g_critical ("attempting to free a locked GVariant instance. "
704 "This should never happen.");
705
706 value->state |= STATE_LOCKED;
707
708 g_variant_type_info_unref (value->type_info);
709
710 if (value->state & STATE_SERIALISED)
711 g_bytes_unref (value->contents.serialised.bytes);
712 else
713 g_variant_release_children (value);
714
715 memset (value, 0, sizeof (GVariant));
716 g_slice_free (GVariant, value);
717 }
718 }
719
720 /**
721 * g_variant_ref:
722 * @value: a #GVariant
723 *
724 * Increases the reference count of @value.
725 *
726 * Returns: the same @value
727 *
728 * Since: 2.24
729 **/
730 GVariant *
g_variant_ref(GVariant * value)731 g_variant_ref (GVariant *value)
732 {
733 g_return_val_if_fail (value != NULL, NULL);
734
735 g_atomic_ref_count_inc (&value->ref_count);
736
737 return value;
738 }
739
740 /**
741 * g_variant_ref_sink:
742 * @value: a #GVariant
743 *
744 * #GVariant uses a floating reference count system. All functions with
745 * names starting with `g_variant_new_` return floating
746 * references.
747 *
748 * Calling g_variant_ref_sink() on a #GVariant with a floating reference
749 * will convert the floating reference into a full reference. Calling
750 * g_variant_ref_sink() on a non-floating #GVariant results in an
751 * additional normal reference being added.
752 *
753 * In other words, if the @value is floating, then this call "assumes
754 * ownership" of the floating reference, converting it to a normal
755 * reference. If the @value is not floating, then this call adds a
756 * new normal reference increasing the reference count by one.
757 *
758 * All calls that result in a #GVariant instance being inserted into a
759 * container will call g_variant_ref_sink() on the instance. This means
760 * that if the value was just created (and has only its floating
761 * reference) then the container will assume sole ownership of the value
762 * at that point and the caller will not need to unreference it. This
763 * makes certain common styles of programming much easier while still
764 * maintaining normal refcounting semantics in situations where values
765 * are not floating.
766 *
767 * Returns: the same @value
768 *
769 * Since: 2.24
770 **/
771 GVariant *
g_variant_ref_sink(GVariant * value)772 g_variant_ref_sink (GVariant *value)
773 {
774 g_return_val_if_fail (value != NULL, NULL);
775 g_return_val_if_fail (!g_atomic_ref_count_compare (&value->ref_count, 0), NULL);
776
777 g_variant_lock (value);
778
779 if (~value->state & STATE_FLOATING)
780 g_variant_ref (value);
781 else
782 value->state &= ~STATE_FLOATING;
783
784 g_variant_unlock (value);
785
786 return value;
787 }
788
789 /**
790 * g_variant_take_ref:
791 * @value: a #GVariant
792 *
793 * If @value is floating, sink it. Otherwise, do nothing.
794 *
795 * Typically you want to use g_variant_ref_sink() in order to
796 * automatically do the correct thing with respect to floating or
797 * non-floating references, but there is one specific scenario where
798 * this function is helpful.
799 *
800 * The situation where this function is helpful is when creating an API
801 * that allows the user to provide a callback function that returns a
802 * #GVariant. We certainly want to allow the user the flexibility to
803 * return a non-floating reference from this callback (for the case
804 * where the value that is being returned already exists).
805 *
806 * At the same time, the style of the #GVariant API makes it likely that
807 * for newly-created #GVariant instances, the user can be saved some
808 * typing if they are allowed to return a #GVariant with a floating
809 * reference.
810 *
811 * Using this function on the return value of the user's callback allows
812 * the user to do whichever is more convenient for them. The caller
813 * will always receives exactly one full reference to the value: either
814 * the one that was returned in the first place, or a floating reference
815 * that has been converted to a full reference.
816 *
817 * This function has an odd interaction when combined with
818 * g_variant_ref_sink() running at the same time in another thread on
819 * the same #GVariant instance. If g_variant_ref_sink() runs first then
820 * the result will be that the floating reference is converted to a hard
821 * reference. If g_variant_take_ref() runs first then the result will
822 * be that the floating reference is converted to a hard reference and
823 * an additional reference on top of that one is added. It is best to
824 * avoid this situation.
825 *
826 * Returns: the same @value
827 **/
828 GVariant *
g_variant_take_ref(GVariant * value)829 g_variant_take_ref (GVariant *value)
830 {
831 g_return_val_if_fail (value != NULL, NULL);
832 g_return_val_if_fail (!g_atomic_ref_count_compare (&value->ref_count, 0), NULL);
833
834 g_atomic_int_and (&value->state, ~STATE_FLOATING);
835
836 return value;
837 }
838
839 /**
840 * g_variant_is_floating:
841 * @value: a #GVariant
842 *
843 * Checks whether @value has a floating reference count.
844 *
845 * This function should only ever be used to assert that a given variant
846 * is or is not floating, or for debug purposes. To acquire a reference
847 * to a variant that might be floating, always use g_variant_ref_sink()
848 * or g_variant_take_ref().
849 *
850 * See g_variant_ref_sink() for more information about floating reference
851 * counts.
852 *
853 * Returns: whether @value is floating
854 *
855 * Since: 2.26
856 **/
857 gboolean
g_variant_is_floating(GVariant * value)858 g_variant_is_floating (GVariant *value)
859 {
860 g_return_val_if_fail (value != NULL, FALSE);
861
862 return (value->state & STATE_FLOATING) != 0;
863 }
864
865 /**
866 * g_variant_get_size:
867 * @value: a #GVariant instance
868 *
869 * Determines the number of bytes that would be required to store @value
870 * with g_variant_store().
871 *
872 * If @value has a fixed-sized type then this function always returned
873 * that fixed size.
874 *
875 * In the case that @value is already in serialised form or the size has
876 * already been calculated (ie: this function has been called before)
877 * then this function is O(1). Otherwise, the size is calculated, an
878 * operation which is approximately O(n) in the number of values
879 * involved.
880 *
881 * Returns: the serialised size of @value
882 *
883 * Since: 2.24
884 **/
885 gsize
g_variant_get_size(GVariant * value)886 g_variant_get_size (GVariant *value)
887 {
888 g_variant_lock (value);
889 g_variant_ensure_size (value);
890 g_variant_unlock (value);
891
892 return value->size;
893 }
894
895 /**
896 * g_variant_get_data:
897 * @value: a #GVariant instance
898 *
899 * Returns a pointer to the serialised form of a #GVariant instance.
900 * The returned data may not be in fully-normalised form if read from an
901 * untrusted source. The returned data must not be freed; it remains
902 * valid for as long as @value exists.
903 *
904 * If @value is a fixed-sized value that was deserialised from a
905 * corrupted serialised container then %NULL may be returned. In this
906 * case, the proper thing to do is typically to use the appropriate
907 * number of nul bytes in place of @value. If @value is not fixed-sized
908 * then %NULL is never returned.
909 *
910 * In the case that @value is already in serialised form, this function
911 * is O(1). If the value is not already in serialised form,
912 * serialisation occurs implicitly and is approximately O(n) in the size
913 * of the result.
914 *
915 * To deserialise the data returned by this function, in addition to the
916 * serialised data, you must know the type of the #GVariant, and (if the
917 * machine might be different) the endianness of the machine that stored
918 * it. As a result, file formats or network messages that incorporate
919 * serialised #GVariants must include this information either
920 * implicitly (for instance "the file always contains a
921 * %G_VARIANT_TYPE_VARIANT and it is always in little-endian order") or
922 * explicitly (by storing the type and/or endianness in addition to the
923 * serialised data).
924 *
925 * Returns: (transfer none): the serialised form of @value, or %NULL
926 *
927 * Since: 2.24
928 **/
929 gconstpointer
g_variant_get_data(GVariant * value)930 g_variant_get_data (GVariant *value)
931 {
932 g_variant_lock (value);
933 g_variant_ensure_serialised (value);
934 g_variant_unlock (value);
935
936 return value->contents.serialised.data;
937 }
938
939 /**
940 * g_variant_get_data_as_bytes:
941 * @value: a #GVariant
942 *
943 * Returns a pointer to the serialised form of a #GVariant instance.
944 * The semantics of this function are exactly the same as
945 * g_variant_get_data(), except that the returned #GBytes holds
946 * a reference to the variant data.
947 *
948 * Returns: (transfer full): A new #GBytes representing the variant data
949 *
950 * Since: 2.36
951 */
952 GBytes *
g_variant_get_data_as_bytes(GVariant * value)953 g_variant_get_data_as_bytes (GVariant *value)
954 {
955 const gchar *bytes_data;
956 const gchar *data;
957 gsize bytes_size;
958 gsize size;
959
960 g_variant_lock (value);
961 g_variant_ensure_serialised (value);
962 g_variant_unlock (value);
963
964 bytes_data = g_bytes_get_data (value->contents.serialised.bytes, &bytes_size);
965 data = value->contents.serialised.data;
966 size = value->size;
967
968 if (data == NULL)
969 {
970 g_assert (size == 0);
971 data = bytes_data;
972 }
973
974 if (data == bytes_data && size == bytes_size)
975 return g_bytes_ref (value->contents.serialised.bytes);
976 else
977 return g_bytes_new_from_bytes (value->contents.serialised.bytes,
978 data - bytes_data, size);
979 }
980
981
982 /**
983 * g_variant_n_children:
984 * @value: a container #GVariant
985 *
986 * Determines the number of children in a container #GVariant instance.
987 * This includes variants, maybes, arrays, tuples and dictionary
988 * entries. It is an error to call this function on any other type of
989 * #GVariant.
990 *
991 * For variants, the return value is always 1. For values with maybe
992 * types, it is always zero or one. For arrays, it is the length of the
993 * array. For tuples it is the number of tuple items (which depends
994 * only on the type). For dictionary entries, it is always 2
995 *
996 * This function is O(1).
997 *
998 * Returns: the number of children in the container
999 *
1000 * Since: 2.24
1001 **/
1002 gsize
g_variant_n_children(GVariant * value)1003 g_variant_n_children (GVariant *value)
1004 {
1005 gsize n_children;
1006
1007 g_variant_lock (value);
1008
1009 if (value->state & STATE_SERIALISED)
1010 {
1011 GVariantSerialised serialised = {
1012 value->type_info,
1013 (gpointer) value->contents.serialised.data,
1014 value->size,
1015 value->depth,
1016 };
1017
1018 n_children = g_variant_serialised_n_children (serialised);
1019 }
1020 else
1021 n_children = value->contents.tree.n_children;
1022
1023 g_variant_unlock (value);
1024
1025 return n_children;
1026 }
1027
1028 /**
1029 * g_variant_get_child_value:
1030 * @value: a container #GVariant
1031 * @index_: the index of the child to fetch
1032 *
1033 * Reads a child item out of a container #GVariant instance. This
1034 * includes variants, maybes, arrays, tuples and dictionary
1035 * entries. It is an error to call this function on any other type of
1036 * #GVariant.
1037 *
1038 * It is an error if @index_ is greater than the number of child items
1039 * in the container. See g_variant_n_children().
1040 *
1041 * The returned value is never floating. You should free it with
1042 * g_variant_unref() when you're done with it.
1043 *
1044 * Note that values borrowed from the returned child are not guaranteed to
1045 * still be valid after the child is freed even if you still hold a reference
1046 * to @value, if @value has not been serialised at the time this function is
1047 * called. To avoid this, you can serialize @value by calling
1048 * g_variant_get_data() and optionally ignoring the return value.
1049 *
1050 * There may be implementation specific restrictions on deeply nested values,
1051 * which would result in the unit tuple being returned as the child value,
1052 * instead of further nested children. #GVariant is guaranteed to handle
1053 * nesting up to at least 64 levels.
1054 *
1055 * This function is O(1).
1056 *
1057 * Returns: (transfer full): the child at the specified index
1058 *
1059 * Since: 2.24
1060 **/
1061 GVariant *
g_variant_get_child_value(GVariant * value,gsize index_)1062 g_variant_get_child_value (GVariant *value,
1063 gsize index_)
1064 {
1065 g_return_val_if_fail (index_ < g_variant_n_children (value), NULL);
1066 g_return_val_if_fail (value->depth < G_MAXSIZE, NULL);
1067
1068 if (~g_atomic_int_get (&value->state) & STATE_SERIALISED)
1069 {
1070 g_variant_lock (value);
1071
1072 if (~value->state & STATE_SERIALISED)
1073 {
1074 GVariant *child;
1075
1076 child = g_variant_ref (value->contents.tree.children[index_]);
1077 g_variant_unlock (value);
1078
1079 return child;
1080 }
1081
1082 g_variant_unlock (value);
1083 }
1084
1085 {
1086 GVariantSerialised serialised = {
1087 value->type_info,
1088 (gpointer) value->contents.serialised.data,
1089 value->size,
1090 value->depth,
1091 };
1092 GVariantSerialised s_child;
1093 GVariant *child;
1094
1095 /* get the serialiser to extract the serialised data for the child
1096 * from the serialised data for the container
1097 */
1098 s_child = g_variant_serialised_get_child (serialised, index_);
1099
1100 /* Check whether this would cause nesting too deep. If so, return a fake
1101 * child. The only situation we expect this to happen in is with a variant,
1102 * as all other deeply-nested types have a static type, and hence should
1103 * have been rejected earlier. In the case of a variant whose nesting plus
1104 * the depth of its child is too great, return a unit variant () instead of
1105 * the real child. */
1106 if (!(value->state & STATE_TRUSTED) &&
1107 g_variant_type_info_query_depth (s_child.type_info) >=
1108 G_VARIANT_MAX_RECURSION_DEPTH - value->depth)
1109 {
1110 g_assert (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT));
1111 return g_variant_new_tuple (NULL, 0);
1112 }
1113
1114 /* create a new serialised instance out of it */
1115 child = g_slice_new (GVariant);
1116 child->type_info = s_child.type_info;
1117 child->state = (value->state & STATE_TRUSTED) |
1118 STATE_SERIALISED;
1119 child->size = s_child.size;
1120 g_atomic_ref_count_init (&child->ref_count);
1121 child->depth = value->depth + 1;
1122 child->contents.serialised.bytes =
1123 g_bytes_ref (value->contents.serialised.bytes);
1124 child->contents.serialised.data = s_child.data;
1125
1126 return child;
1127 }
1128 }
1129
1130 /**
1131 * g_variant_store:
1132 * @value: the #GVariant to store
1133 * @data: (not nullable): the location to store the serialised data at
1134 *
1135 * Stores the serialised form of @value at @data. @data should be
1136 * large enough. See g_variant_get_size().
1137 *
1138 * The stored data is in machine native byte order but may not be in
1139 * fully-normalised form if read from an untrusted source. See
1140 * g_variant_get_normal_form() for a solution.
1141 *
1142 * As with g_variant_get_data(), to be able to deserialise the
1143 * serialised variant successfully, its type and (if the destination
1144 * machine might be different) its endianness must also be available.
1145 *
1146 * This function is approximately O(n) in the size of @data.
1147 *
1148 * Since: 2.24
1149 **/
1150 void
g_variant_store(GVariant * value,gpointer data)1151 g_variant_store (GVariant *value,
1152 gpointer data)
1153 {
1154 g_variant_lock (value);
1155
1156 if (value->state & STATE_SERIALISED)
1157 {
1158 if (value->contents.serialised.data != NULL)
1159 memcpy (data, value->contents.serialised.data, value->size);
1160 else
1161 memset (data, 0, value->size);
1162 }
1163 else
1164 g_variant_serialise (value, data);
1165
1166 g_variant_unlock (value);
1167 }
1168
1169 /**
1170 * g_variant_is_normal_form:
1171 * @value: a #GVariant instance
1172 *
1173 * Checks if @value is in normal form.
1174 *
1175 * The main reason to do this is to detect if a given chunk of
1176 * serialised data is in normal form: load the data into a #GVariant
1177 * using g_variant_new_from_data() and then use this function to
1178 * check.
1179 *
1180 * If @value is found to be in normal form then it will be marked as
1181 * being trusted. If the value was already marked as being trusted then
1182 * this function will immediately return %TRUE.
1183 *
1184 * There may be implementation specific restrictions on deeply nested values.
1185 * GVariant is guaranteed to handle nesting up to at least 64 levels.
1186 *
1187 * Returns: %TRUE if @value is in normal form
1188 *
1189 * Since: 2.24
1190 **/
1191 gboolean
g_variant_is_normal_form(GVariant * value)1192 g_variant_is_normal_form (GVariant *value)
1193 {
1194 if (value->state & STATE_TRUSTED)
1195 return TRUE;
1196
1197 g_variant_lock (value);
1198
1199 if (value->depth >= G_VARIANT_MAX_RECURSION_DEPTH)
1200 return FALSE;
1201
1202 if (value->state & STATE_SERIALISED)
1203 {
1204 GVariantSerialised serialised = {
1205 value->type_info,
1206 (gpointer) value->contents.serialised.data,
1207 value->size,
1208 value->depth
1209 };
1210
1211 if (g_variant_serialised_is_normal (serialised))
1212 value->state |= STATE_TRUSTED;
1213 }
1214 else
1215 {
1216 gboolean normal = TRUE;
1217 gsize i;
1218
1219 for (i = 0; i < value->contents.tree.n_children; i++)
1220 normal &= g_variant_is_normal_form (value->contents.tree.children[i]);
1221
1222 if (normal)
1223 value->state |= STATE_TRUSTED;
1224 }
1225
1226 g_variant_unlock (value);
1227
1228 return (value->state & STATE_TRUSTED) != 0;
1229 }
1230