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