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