Coverage Report

Created: 2025-08-21 07:05

/src/glib/glib/gvariant.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright © 2007, 2008 Ryan Lortie
3
 * Copyright © 2010 Codethink Limited
4
 *
5
 * SPDX-License-Identifier: LGPL-2.1-or-later
6
 *
7
 * This library is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * This library is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19
 *
20
 * Author: Ryan Lortie <desrt@desrt.ca>
21
 */
22
23
/* Prologue {{{1 */
24
25
#include "config.h"
26
27
#include <glib/gvariant-serialiser.h>
28
#include "gvariant-internal.h"
29
#include <glib/gvariant-core.h>
30
#include <glib/gtestutils.h>
31
#include <glib/gstrfuncs.h>
32
#include <glib/gslice.h>
33
#include <glib/ghash.h>
34
#include <glib/gmem.h>
35
36
#include <string.h>
37
38
/**
39
 * SECTION:gvariant
40
 * @title: GVariant
41
 * @short_description: strongly typed value datatype
42
 * @see_also: GVariantType
43
 *
44
 * #GVariant is a variant datatype; it can contain one or more values
45
 * along with information about the type of the values.
46
 *
47
 * A #GVariant may contain simple types, like an integer, or a boolean value;
48
 * or complex types, like an array of two strings, or a dictionary of key
49
 * value pairs. A #GVariant is also immutable: once it's been created neither
50
 * its type nor its content can be modified further.
51
 *
52
 * GVariant is useful whenever data needs to be serialized, for example when
53
 * sending method parameters in D-Bus, or when saving settings using GSettings.
54
 *
55
 * When creating a new #GVariant, you pass the data you want to store in it
56
 * along with a string representing the type of data you wish to pass to it.
57
 *
58
 * For instance, if you want to create a #GVariant holding an integer value you
59
 * can use:
60
 *
61
 * |[<!-- language="C" -->
62
 *   GVariant *v = g_variant_new ("u", 40);
63
 * ]|
64
 *
65
 * The string "u" in the first argument tells #GVariant that the data passed to
66
 * the constructor (40) is going to be an unsigned integer.
67
 *
68
 * More advanced examples of #GVariant in use can be found in documentation for
69
 * [GVariant format strings][gvariant-format-strings-pointers].
70
 *
71
 * The range of possible values is determined by the type.
72
 *
73
 * The type system used by #GVariant is #GVariantType. 
74
 *
75
 * #GVariant instances always have a type and a value (which are given
76
 * at construction time).  The type and value of a #GVariant instance
77
 * can never change other than by the #GVariant itself being
78
 * destroyed.  A #GVariant cannot contain a pointer.
79
 *
80
 * #GVariant is reference counted using g_variant_ref() and
81
 * g_variant_unref().  #GVariant also has floating reference counts --
82
 * see g_variant_ref_sink().
83
 *
84
 * #GVariant is completely threadsafe.  A #GVariant instance can be
85
 * concurrently accessed in any way from any number of threads without
86
 * problems.
87
 *
88
 * #GVariant is heavily optimised for dealing with data in serialized
89
 * form.  It works particularly well with data located in memory-mapped
90
 * files.  It can perform nearly all deserialization operations in a
91
 * small constant time, usually touching only a single memory page.
92
 * Serialized #GVariant data can also be sent over the network.
93
 *
94
 * #GVariant is largely compatible with D-Bus.  Almost all types of
95
 * #GVariant instances can be sent over D-Bus.  See #GVariantType for
96
 * exceptions.  (However, #GVariant's serialization format is not the same
97
 * as the serialization format of a D-Bus message body: use #GDBusMessage,
98
 * in the gio library, for those.)
99
 *
100
 * For space-efficiency, the #GVariant serialization format does not
101
 * automatically include the variant's length, type or endianness,
102
 * which must either be implied from context (such as knowledge that a
103
 * particular file format always contains a little-endian
104
 * %G_VARIANT_TYPE_VARIANT which occupies the whole length of the file)
105
 * or supplied out-of-band (for instance, a length, type and/or endianness
106
 * indicator could be placed at the beginning of a file, network message
107
 * or network stream).
108
 *
109
 * A #GVariant's size is limited mainly by any lower level operating
110
 * system constraints, such as the number of bits in #gsize.  For
111
 * example, it is reasonable to have a 2GB file mapped into memory
112
 * with #GMappedFile, and call g_variant_new_from_data() on it.
113
 *
114
 * For convenience to C programmers, #GVariant features powerful
115
 * varargs-based value construction and destruction.  This feature is
116
 * designed to be embedded in other libraries.
117
 *
118
 * There is a Python-inspired text language for describing #GVariant
119
 * values.  #GVariant includes a printer for this language and a parser
120
 * with type inferencing.
121
 *
122
 * ## Memory Use
123
 *
124
 * #GVariant tries to be quite efficient with respect to memory use.
125
 * This section gives a rough idea of how much memory is used by the
126
 * current implementation.  The information here is subject to change
127
 * in the future.
128
 *
129
 * The memory allocated by #GVariant can be grouped into 4 broad
130
 * purposes: memory for serialized data, memory for the type
131
 * information cache, buffer management memory and memory for the
132
 * #GVariant structure itself.
133
 *
134
 * ## Serialized Data Memory
135
 *
136
 * This is the memory that is used for storing GVariant data in
137
 * serialized form.  This is what would be sent over the network or
138
 * what would end up on disk, not counting any indicator of the
139
 * endianness, or of the length or type of the top-level variant.
140
 *
141
 * The amount of memory required to store a boolean is 1 byte. 16,
142
 * 32 and 64 bit integers and double precision floating point numbers
143
 * use their "natural" size.  Strings (including object path and
144
 * signature strings) are stored with a nul terminator, and as such
145
 * use the length of the string plus 1 byte.
146
 *
147
 * Maybe types use no space at all to represent the null value and
148
 * use the same amount of space (sometimes plus one byte) as the
149
 * equivalent non-maybe-typed value to represent the non-null case.
150
 *
151
 * Arrays use the amount of space required to store each of their
152
 * members, concatenated.  Additionally, if the items stored in an
153
 * array are not of a fixed-size (ie: strings, other arrays, etc)
154
 * then an additional framing offset is stored for each item.  The
155
 * size of this offset is either 1, 2 or 4 bytes depending on the
156
 * overall size of the container.  Additionally, extra padding bytes
157
 * are added as required for alignment of child values.
158
 *
159
 * Tuples (including dictionary entries) use the amount of space
160
 * required to store each of their members, concatenated, plus one
161
 * framing offset (as per arrays) for each non-fixed-sized item in
162
 * the tuple, except for the last one.  Additionally, extra padding
163
 * bytes are added as required for alignment of child values.
164
 *
165
 * Variants use the same amount of space as the item inside of the
166
 * variant, plus 1 byte, plus the length of the type string for the
167
 * item inside the variant.
168
 *
169
 * As an example, consider a dictionary mapping strings to variants.
170
 * In the case that the dictionary is empty, 0 bytes are required for
171
 * the serialization.
172
 *
173
 * If we add an item "width" that maps to the int32 value of 500 then
174
 * we will use 4 byte to store the int32 (so 6 for the variant
175
 * containing it) and 6 bytes for the string.  The variant must be
176
 * aligned to 8 after the 6 bytes of the string, so that's 2 extra
177
 * bytes.  6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
178
 * for the dictionary entry.  An additional 1 byte is added to the
179
 * array as a framing offset making a total of 15 bytes.
180
 *
181
 * If we add another entry, "title" that maps to a nullable string
182
 * that happens to have a value of null, then we use 0 bytes for the
183
 * null value (and 3 bytes for the variant to contain it along with
184
 * its type string) plus 6 bytes for the string.  Again, we need 2
185
 * padding bytes.  That makes a total of 6 + 2 + 3 = 11 bytes.
186
 *
187
 * We now require extra padding between the two items in the array.
188
 * After the 14 bytes of the first item, that's 2 bytes required.
189
 * We now require 2 framing offsets for an extra two
190
 * bytes. 14 + 2 + 11 + 2 = 29 bytes to encode the entire two-item
191
 * dictionary.
192
 *
193
 * ## Type Information Cache
194
 *
195
 * For each GVariant type that currently exists in the program a type
196
 * information structure is kept in the type information cache.  The
197
 * type information structure is required for rapid deserialization.
198
 *
199
 * Continuing with the above example, if a #GVariant exists with the
200
 * type "a{sv}" then a type information struct will exist for
201
 * "a{sv}", "{sv}", "s", and "v".  Multiple uses of the same type
202
 * will share the same type information.  Additionally, all
203
 * single-digit types are stored in read-only static memory and do
204
 * not contribute to the writable memory footprint of a program using
205
 * #GVariant.
206
 *
207
 * Aside from the type information structures stored in read-only
208
 * memory, there are two forms of type information.  One is used for
209
 * container types where there is a single element type: arrays and
210
 * maybe types.  The other is used for container types where there
211
 * are multiple element types: tuples and dictionary entries.
212
 *
213
 * Array type info structures are 6 * sizeof (void *), plus the
214
 * memory required to store the type string itself.  This means that
215
 * on 32-bit systems, the cache entry for "a{sv}" would require 30
216
 * bytes of memory (plus malloc overhead).
217
 *
218
 * Tuple type info structures are 6 * sizeof (void *), plus 4 *
219
 * sizeof (void *) for each item in the tuple, plus the memory
220
 * required to store the type string itself.  A 2-item tuple, for
221
 * example, would have a type information structure that consumed
222
 * writable memory in the size of 14 * sizeof (void *) (plus type
223
 * string)  This means that on 32-bit systems, the cache entry for
224
 * "{sv}" would require 61 bytes of memory (plus malloc overhead).
225
 *
226
 * This means that in total, for our "a{sv}" example, 91 bytes of
227
 * type information would be allocated.
228
 * 
229
 * The type information cache, additionally, uses a #GHashTable to
230
 * store and look up the cached items and stores a pointer to this
231
 * hash table in static storage.  The hash table is freed when there
232
 * are zero items in the type cache.
233
 *
234
 * Although these sizes may seem large it is important to remember
235
 * that a program will probably only have a very small number of
236
 * different types of values in it and that only one type information
237
 * structure is required for many different values of the same type.
238
 *
239
 * ## Buffer Management Memory
240
 *
241
 * #GVariant uses an internal buffer management structure to deal
242
 * with the various different possible sources of serialized data
243
 * that it uses.  The buffer is responsible for ensuring that the
244
 * correct call is made when the data is no longer in use by
245
 * #GVariant.  This may involve a g_free() or a g_slice_free() or
246
 * even g_mapped_file_unref().
247
 *
248
 * One buffer management structure is used for each chunk of
249
 * serialized data.  The size of the buffer management structure
250
 * is 4 * (void *).  On 32-bit systems, that's 16 bytes.
251
 *
252
 * ## GVariant structure
253
 *
254
 * The size of a #GVariant structure is 6 * (void *).  On 32-bit
255
 * systems, that's 24 bytes.
256
 *
257
 * #GVariant structures only exist if they are explicitly created
258
 * with API calls.  For example, if a #GVariant is constructed out of
259
 * serialized data for the example given above (with the dictionary)
260
 * then although there are 9 individual values that comprise the
261
 * entire dictionary (two keys, two values, two variants containing
262
 * the values, two dictionary entries, plus the dictionary itself),
263
 * only 1 #GVariant instance exists -- the one referring to the
264
 * dictionary.
265
 *
266
 * If calls are made to start accessing the other values then
267
 * #GVariant instances will exist for those values only for as long
268
 * as they are in use (ie: until you call g_variant_unref()).  The
269
 * type information is shared.  The serialized data and the buffer
270
 * management structure for that serialized data is shared by the
271
 * child.
272
 *
273
 * ## Summary
274
 *
275
 * To put the entire example together, for our dictionary mapping
276
 * strings to variants (with two entries, as given above), we are
277
 * using 91 bytes of memory for type information, 29 bytes of memory
278
 * for the serialized data, 16 bytes for buffer management and 24
279
 * bytes for the #GVariant instance, or a total of 160 bytes, plus
280
 * malloc overhead.  If we were to use g_variant_get_child_value() to
281
 * access the two dictionary entries, we would use an additional 48
282
 * bytes.  If we were to have other dictionaries of the same type, we
283
 * would use more memory for the serialized data and buffer
284
 * management for those dictionaries, but the type information would
285
 * be shared.
286
 */
287
288
/* definition of GVariant structure is in gvariant-core.c */
289
290
/* this is a g_return_val_if_fail() for making
291
 * sure a (GVariant *) has the required type.
292
 */
293
#define TYPE_CHECK(value, TYPE, val) \
294
0
  if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) {           \
295
0
    g_return_if_fail_warning (G_LOG_DOMAIN, G_STRFUNC,            \
296
0
                              "g_variant_is_of_type (" #value     \
297
0
                              ", " #TYPE ")");                    \
298
0
    return val;                                                   \
299
0
  }
300
301
/* Numeric Type Constructor/Getters {{{1 */
302
/* < private >
303
 * g_variant_new_from_trusted:
304
 * @type: the #GVariantType
305
 * @data: the data to use
306
 * @size: the size of @data
307
 *
308
 * Constructs a new trusted #GVariant instance from the provided data.
309
 * This is used to implement g_variant_new_* for all the basic types.
310
 *
311
 * Note: @data must be backed by memory that is aligned appropriately for the
312
 * @type being loaded. Otherwise this function will internally create a copy of
313
 * the memory (since GLib 2.60) or (in older versions) fail and exit the
314
 * process.
315
 *
316
 * Returns: a new floating #GVariant
317
 */
318
static GVariant *
319
g_variant_new_from_trusted (const GVariantType *type,
320
                            gconstpointer       data,
321
                            gsize               size)
322
0
{
323
0
  GVariant *value;
324
0
  GBytes *bytes;
325
326
0
  bytes = g_bytes_new (data, size);
327
0
  value = g_variant_new_from_bytes (type, bytes, TRUE);
328
0
  g_bytes_unref (bytes);
329
330
0
  return value;
331
0
}
332
333
/**
334
 * g_variant_new_boolean:
335
 * @value: a #gboolean value
336
 *
337
 * Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
338
 *
339
 * Returns: (transfer none): a floating reference to a new boolean #GVariant instance
340
 *
341
 * Since: 2.24
342
 **/
343
GVariant *
344
g_variant_new_boolean (gboolean value)
345
0
{
346
0
  guchar v = value;
347
348
0
  return g_variant_new_from_trusted (G_VARIANT_TYPE_BOOLEAN, &v, 1);
349
0
}
350
351
/**
352
 * g_variant_get_boolean:
353
 * @value: a boolean #GVariant instance
354
 *
355
 * Returns the boolean value of @value.
356
 *
357
 * It is an error to call this function with a @value of any type
358
 * other than %G_VARIANT_TYPE_BOOLEAN.
359
 *
360
 * Returns: %TRUE or %FALSE
361
 *
362
 * Since: 2.24
363
 **/
364
gboolean
365
g_variant_get_boolean (GVariant *value)
366
0
{
367
0
  const guchar *data;
368
369
0
  TYPE_CHECK (value, G_VARIANT_TYPE_BOOLEAN, FALSE);
370
371
0
  data = g_variant_get_data (value);
372
373
0
  return data != NULL ? *data != 0 : FALSE;
374
0
}
375
376
/* the constructors and accessors for byte, int{16,32,64}, handles and
377
 * doubles all look pretty much exactly the same, so we reduce
378
 * copy/pasting here.
379
 */
380
#define NUMERIC_TYPE(TYPE, type, ctype) \
381
0
  GVariant *g_variant_new_##type (ctype value) {                \
382
0
    return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE,   \
383
0
                                       &value, sizeof value);   \
384
0
  }                                                             \
Unexecuted instantiation: g_variant_new_byte
Unexecuted instantiation: g_variant_new_int16
Unexecuted instantiation: g_variant_new_uint16
Unexecuted instantiation: g_variant_new_int32
Unexecuted instantiation: g_variant_new_uint32
Unexecuted instantiation: g_variant_new_int64
Unexecuted instantiation: g_variant_new_uint64
Unexecuted instantiation: g_variant_new_handle
Unexecuted instantiation: g_variant_new_double
385
0
  ctype g_variant_get_##type (GVariant *value) {                \
386
0
    const ctype *data;                                          \
387
0
    TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0);             \
388
0
    data = g_variant_get_data (value);                          \
389
0
    return data != NULL ? *data : 0;                            \
390
0
  }
Unexecuted instantiation: g_variant_get_byte
Unexecuted instantiation: g_variant_get_int16
Unexecuted instantiation: g_variant_get_uint16
Unexecuted instantiation: g_variant_get_int32
Unexecuted instantiation: g_variant_get_uint32
Unexecuted instantiation: g_variant_get_int64
Unexecuted instantiation: g_variant_get_uint64
Unexecuted instantiation: g_variant_get_handle
Unexecuted instantiation: g_variant_get_double
391
392
393
/**
394
 * g_variant_new_byte:
395
 * @value: a #guint8 value
396
 *
397
 * Creates a new byte #GVariant instance.
398
 *
399
 * Returns: (transfer none): a floating reference to a new byte #GVariant instance
400
 *
401
 * Since: 2.24
402
 **/
403
/**
404
 * g_variant_get_byte:
405
 * @value: a byte #GVariant instance
406
 *
407
 * Returns the byte value of @value.
408
 *
409
 * It is an error to call this function with a @value of any type
410
 * other than %G_VARIANT_TYPE_BYTE.
411
 *
412
 * Returns: a #guint8
413
 *
414
 * Since: 2.24
415
 **/
416
NUMERIC_TYPE (BYTE, byte, guint8)
417
418
/**
419
 * g_variant_new_int16:
420
 * @value: a #gint16 value
421
 *
422
 * Creates a new int16 #GVariant instance.
423
 *
424
 * Returns: (transfer none): a floating reference to a new int16 #GVariant instance
425
 *
426
 * Since: 2.24
427
 **/
428
/**
429
 * g_variant_get_int16:
430
 * @value: an int16 #GVariant instance
431
 *
432
 * Returns the 16-bit signed integer value of @value.
433
 *
434
 * It is an error to call this function with a @value of any type
435
 * other than %G_VARIANT_TYPE_INT16.
436
 *
437
 * Returns: a #gint16
438
 *
439
 * Since: 2.24
440
 **/
441
NUMERIC_TYPE (INT16, int16, gint16)
442
443
/**
444
 * g_variant_new_uint16:
445
 * @value: a #guint16 value
446
 *
447
 * Creates a new uint16 #GVariant instance.
448
 *
449
 * Returns: (transfer none): a floating reference to a new uint16 #GVariant instance
450
 *
451
 * Since: 2.24
452
 **/
453
/**
454
 * g_variant_get_uint16:
455
 * @value: a uint16 #GVariant instance
456
 *
457
 * Returns the 16-bit unsigned integer value of @value.
458
 *
459
 * It is an error to call this function with a @value of any type
460
 * other than %G_VARIANT_TYPE_UINT16.
461
 *
462
 * Returns: a #guint16
463
 *
464
 * Since: 2.24
465
 **/
466
NUMERIC_TYPE (UINT16, uint16, guint16)
467
468
/**
469
 * g_variant_new_int32:
470
 * @value: a #gint32 value
471
 *
472
 * Creates a new int32 #GVariant instance.
473
 *
474
 * Returns: (transfer none): a floating reference to a new int32 #GVariant instance
475
 *
476
 * Since: 2.24
477
 **/
478
/**
479
 * g_variant_get_int32:
480
 * @value: an int32 #GVariant instance
481
 *
482
 * Returns the 32-bit signed integer value of @value.
483
 *
484
 * It is an error to call this function with a @value of any type
485
 * other than %G_VARIANT_TYPE_INT32.
486
 *
487
 * Returns: a #gint32
488
 *
489
 * Since: 2.24
490
 **/
491
NUMERIC_TYPE (INT32, int32, gint32)
492
493
/**
494
 * g_variant_new_uint32:
495
 * @value: a #guint32 value
496
 *
497
 * Creates a new uint32 #GVariant instance.
498
 *
499
 * Returns: (transfer none): a floating reference to a new uint32 #GVariant instance
500
 *
501
 * Since: 2.24
502
 **/
503
/**
504
 * g_variant_get_uint32:
505
 * @value: a uint32 #GVariant instance
506
 *
507
 * Returns the 32-bit unsigned integer value of @value.
508
 *
509
 * It is an error to call this function with a @value of any type
510
 * other than %G_VARIANT_TYPE_UINT32.
511
 *
512
 * Returns: a #guint32
513
 *
514
 * Since: 2.24
515
 **/
516
NUMERIC_TYPE (UINT32, uint32, guint32)
517
518
/**
519
 * g_variant_new_int64:
520
 * @value: a #gint64 value
521
 *
522
 * Creates a new int64 #GVariant instance.
523
 *
524
 * Returns: (transfer none): a floating reference to a new int64 #GVariant instance
525
 *
526
 * Since: 2.24
527
 **/
528
/**
529
 * g_variant_get_int64:
530
 * @value: an int64 #GVariant instance
531
 *
532
 * Returns the 64-bit signed integer value of @value.
533
 *
534
 * It is an error to call this function with a @value of any type
535
 * other than %G_VARIANT_TYPE_INT64.
536
 *
537
 * Returns: a #gint64
538
 *
539
 * Since: 2.24
540
 **/
541
NUMERIC_TYPE (INT64, int64, gint64)
542
543
/**
544
 * g_variant_new_uint64:
545
 * @value: a #guint64 value
546
 *
547
 * Creates a new uint64 #GVariant instance.
548
 *
549
 * Returns: (transfer none): a floating reference to a new uint64 #GVariant instance
550
 *
551
 * Since: 2.24
552
 **/
553
/**
554
 * g_variant_get_uint64:
555
 * @value: a uint64 #GVariant instance
556
 *
557
 * Returns the 64-bit unsigned integer value of @value.
558
 *
559
 * It is an error to call this function with a @value of any type
560
 * other than %G_VARIANT_TYPE_UINT64.
561
 *
562
 * Returns: a #guint64
563
 *
564
 * Since: 2.24
565
 **/
566
NUMERIC_TYPE (UINT64, uint64, guint64)
567
568
/**
569
 * g_variant_new_handle:
570
 * @value: a #gint32 value
571
 *
572
 * Creates a new handle #GVariant instance.
573
 *
574
 * By convention, handles are indexes into an array of file descriptors
575
 * that are sent alongside a D-Bus message.  If you're not interacting
576
 * with D-Bus, you probably don't need them.
577
 *
578
 * Returns: (transfer none): a floating reference to a new handle #GVariant instance
579
 *
580
 * Since: 2.24
581
 **/
582
/**
583
 * g_variant_get_handle:
584
 * @value: a handle #GVariant instance
585
 *
586
 * Returns the 32-bit signed integer value of @value.
587
 *
588
 * It is an error to call this function with a @value of any type other
589
 * than %G_VARIANT_TYPE_HANDLE.
590
 *
591
 * By convention, handles are indexes into an array of file descriptors
592
 * that are sent alongside a D-Bus message.  If you're not interacting
593
 * with D-Bus, you probably don't need them.
594
 *
595
 * Returns: a #gint32
596
 *
597
 * Since: 2.24
598
 **/
599
NUMERIC_TYPE (HANDLE, handle, gint32)
600
601
/**
602
 * g_variant_new_double:
603
 * @value: a #gdouble floating point value
604
 *
605
 * Creates a new double #GVariant instance.
606
 *
607
 * Returns: (transfer none): a floating reference to a new double #GVariant instance
608
 *
609
 * Since: 2.24
610
 **/
611
/**
612
 * g_variant_get_double:
613
 * @value: a double #GVariant instance
614
 *
615
 * Returns the double precision floating point value of @value.
616
 *
617
 * It is an error to call this function with a @value of any type
618
 * other than %G_VARIANT_TYPE_DOUBLE.
619
 *
620
 * Returns: a #gdouble
621
 *
622
 * Since: 2.24
623
 **/
624
NUMERIC_TYPE (DOUBLE, double, gdouble)
625
626
/* Container type Constructor / Deconstructors {{{1 */
627
/**
628
 * g_variant_new_maybe:
629
 * @child_type: (nullable): the #GVariantType of the child, or %NULL
630
 * @child: (nullable): the child value, or %NULL
631
 *
632
 * Depending on if @child is %NULL, either wraps @child inside of a
633
 * maybe container or creates a Nothing instance for the given @type.
634
 *
635
 * At least one of @child_type and @child must be non-%NULL.
636
 * If @child_type is non-%NULL then it must be a definite type.
637
 * If they are both non-%NULL then @child_type must be the type
638
 * of @child.
639
 *
640
 * If @child is a floating reference (see g_variant_ref_sink()), the new
641
 * instance takes ownership of @child.
642
 *
643
 * Returns: (transfer none): a floating reference to a new #GVariant maybe instance
644
 *
645
 * Since: 2.24
646
 **/
647
GVariant *
648
g_variant_new_maybe (const GVariantType *child_type,
649
                     GVariant           *child)
650
0
{
651
0
  GVariantType *maybe_type;
652
0
  GVariant *value;
653
654
0
  g_return_val_if_fail (child_type == NULL || g_variant_type_is_definite
655
0
                        (child_type), 0);
656
0
  g_return_val_if_fail (child_type != NULL || child != NULL, NULL);
657
0
  g_return_val_if_fail (child_type == NULL || child == NULL ||
658
0
                        g_variant_is_of_type (child, child_type),
659
0
                        NULL);
660
661
0
  if (child_type == NULL)
662
0
    child_type = g_variant_get_type (child);
663
664
0
  maybe_type = g_variant_type_new_maybe (child_type);
665
666
0
  if (child != NULL)
667
0
    {
668
0
      GVariant **children;
669
0
      gboolean trusted;
670
671
0
      children = g_new (GVariant *, 1);
672
0
      children[0] = g_variant_ref_sink (child);
673
0
      trusted = g_variant_is_trusted (children[0]);
674
675
0
      value = g_variant_new_from_children (maybe_type, children, 1, trusted);
676
0
    }
677
0
  else
678
0
    value = g_variant_new_from_children (maybe_type, NULL, 0, TRUE);
679
680
0
  g_variant_type_free (maybe_type);
681
682
0
  return value;
683
0
}
684
685
/**
686
 * g_variant_get_maybe:
687
 * @value: a maybe-typed value
688
 *
689
 * Given a maybe-typed #GVariant instance, extract its value.  If the
690
 * value is Nothing, then this function returns %NULL.
691
 *
692
 * Returns: (nullable) (transfer full): the contents of @value, or %NULL
693
 *
694
 * Since: 2.24
695
 **/
696
GVariant *
697
g_variant_get_maybe (GVariant *value)
698
0
{
699
0
  TYPE_CHECK (value, G_VARIANT_TYPE_MAYBE, NULL);
700
701
0
  if (g_variant_n_children (value))
702
0
    return g_variant_get_child_value (value, 0);
703
704
0
  return NULL;
705
0
}
706
707
/**
708
 * g_variant_new_variant: (constructor)
709
 * @value: a #GVariant instance
710
 *
711
 * Boxes @value.  The result is a #GVariant instance representing a
712
 * variant containing the original value.
713
 *
714
 * If @child is a floating reference (see g_variant_ref_sink()), the new
715
 * instance takes ownership of @child.
716
 *
717
 * Returns: (transfer none): a floating reference to a new variant #GVariant instance
718
 *
719
 * Since: 2.24
720
 **/
721
GVariant *
722
g_variant_new_variant (GVariant *value)
723
0
{
724
0
  g_return_val_if_fail (value != NULL, NULL);
725
726
0
  g_variant_ref_sink (value);
727
728
0
  return g_variant_new_from_children (G_VARIANT_TYPE_VARIANT,
729
0
                                      g_memdup2 (&value, sizeof value),
730
0
                                      1, g_variant_is_trusted (value));
731
0
}
732
733
/**
734
 * g_variant_get_variant:
735
 * @value: a variant #GVariant instance
736
 *
737
 * Unboxes @value.  The result is the #GVariant instance that was
738
 * contained in @value.
739
 *
740
 * Returns: (transfer full): the item contained in the variant
741
 *
742
 * Since: 2.24
743
 **/
744
GVariant *
745
g_variant_get_variant (GVariant *value)
746
0
{
747
0
  TYPE_CHECK (value, G_VARIANT_TYPE_VARIANT, NULL);
748
749
0
  return g_variant_get_child_value (value, 0);
750
0
}
751
752
/**
753
 * g_variant_new_array:
754
 * @child_type: (nullable): the element type of the new array
755
 * @children: (nullable) (array length=n_children): an array of
756
 *            #GVariant pointers, the children
757
 * @n_children: the length of @children
758
 *
759
 * Creates a new #GVariant array from @children.
760
 *
761
 * @child_type must be non-%NULL if @n_children is zero.  Otherwise, the
762
 * child type is determined by inspecting the first element of the
763
 * @children array.  If @child_type is non-%NULL then it must be a
764
 * definite type.
765
 *
766
 * The items of the array are taken from the @children array.  No entry
767
 * in the @children array may be %NULL.
768
 *
769
 * All items in the array must have the same type, which must be the
770
 * same as @child_type, if given.
771
 *
772
 * If the @children are floating references (see g_variant_ref_sink()), the
773
 * new instance takes ownership of them as if via g_variant_ref_sink().
774
 *
775
 * Returns: (transfer none): a floating reference to a new #GVariant array
776
 *
777
 * Since: 2.24
778
 **/
779
GVariant *
780
g_variant_new_array (const GVariantType *child_type,
781
                     GVariant * const   *children,
782
                     gsize               n_children)
783
0
{
784
0
  GVariantType *array_type;
785
0
  GVariant **my_children;
786
0
  gboolean trusted;
787
0
  GVariant *value;
788
0
  gsize i;
789
790
0
  g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
791
0
  g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
792
0
  g_return_val_if_fail (child_type == NULL ||
793
0
                        g_variant_type_is_definite (child_type), NULL);
794
795
0
  my_children = g_new (GVariant *, n_children);
796
0
  trusted = TRUE;
797
798
0
  if (child_type == NULL)
799
0
    child_type = g_variant_get_type (children[0]);
800
0
  array_type = g_variant_type_new_array (child_type);
801
802
0
  for (i = 0; i < n_children; i++)
803
0
    {
804
0
      gboolean is_of_child_type = g_variant_is_of_type (children[i], child_type);
805
0
      if G_UNLIKELY (!is_of_child_type)
806
0
        {
807
0
          while (i != 0)
808
0
            g_variant_unref (my_children[--i]);
809
0
          g_free (my_children);
810
0
          g_return_val_if_fail (is_of_child_type, NULL);
811
0
        }
812
0
      my_children[i] = g_variant_ref_sink (children[i]);
813
0
      trusted &= g_variant_is_trusted (children[i]);
814
0
    }
815
816
0
  value = g_variant_new_from_children (array_type, my_children,
817
0
                                       n_children, trusted);
818
0
  g_variant_type_free (array_type);
819
820
0
  return value;
821
0
}
822
823
/*< private >
824
 * g_variant_make_tuple_type:
825
 * @children: (array length=n_children): an array of GVariant *
826
 * @n_children: the length of @children
827
 *
828
 * Return the type of a tuple containing @children as its items.
829
 **/
830
static GVariantType *
831
g_variant_make_tuple_type (GVariant * const *children,
832
                           gsize             n_children)
833
0
{
834
0
  const GVariantType **types;
835
0
  GVariantType *type;
836
0
  gsize i;
837
838
0
  types = g_new (const GVariantType *, n_children);
839
840
0
  for (i = 0; i < n_children; i++)
841
0
    types[i] = g_variant_get_type (children[i]);
842
843
0
  type = g_variant_type_new_tuple (types, n_children);
844
0
  g_free (types);
845
846
0
  return type;
847
0
}
848
849
/**
850
 * g_variant_new_tuple:
851
 * @children: (array length=n_children): the items to make the tuple out of
852
 * @n_children: the length of @children
853
 *
854
 * Creates a new tuple #GVariant out of the items in @children.  The
855
 * type is determined from the types of @children.  No entry in the
856
 * @children array may be %NULL.
857
 *
858
 * If @n_children is 0 then the unit tuple is constructed.
859
 *
860
 * If the @children are floating references (see g_variant_ref_sink()), the
861
 * new instance takes ownership of them as if via g_variant_ref_sink().
862
 *
863
 * Returns: (transfer none): a floating reference to a new #GVariant tuple
864
 *
865
 * Since: 2.24
866
 **/
867
GVariant *
868
g_variant_new_tuple (GVariant * const *children,
869
                     gsize             n_children)
870
0
{
871
0
  GVariantType *tuple_type;
872
0
  GVariant **my_children;
873
0
  gboolean trusted;
874
0
  GVariant *value;
875
0
  gsize i;
876
877
0
  g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
878
879
0
  my_children = g_new (GVariant *, n_children);
880
0
  trusted = TRUE;
881
882
0
  for (i = 0; i < n_children; i++)
883
0
    {
884
0
      my_children[i] = g_variant_ref_sink (children[i]);
885
0
      trusted &= g_variant_is_trusted (children[i]);
886
0
    }
887
888
0
  tuple_type = g_variant_make_tuple_type (children, n_children);
889
0
  value = g_variant_new_from_children (tuple_type, my_children,
890
0
                                       n_children, trusted);
891
0
  g_variant_type_free (tuple_type);
892
893
0
  return value;
894
0
}
895
896
/*< private >
897
 * g_variant_make_dict_entry_type:
898
 * @key: a #GVariant, the key
899
 * @val: a #GVariant, the value
900
 *
901
 * Return the type of a dictionary entry containing @key and @val as its
902
 * children.
903
 **/
904
static GVariantType *
905
g_variant_make_dict_entry_type (GVariant *key,
906
                                GVariant *val)
907
0
{
908
0
  return g_variant_type_new_dict_entry (g_variant_get_type (key),
909
0
                                        g_variant_get_type (val));
910
0
}
911
912
/**
913
 * g_variant_new_dict_entry: (constructor)
914
 * @key: a basic #GVariant, the key
915
 * @value: a #GVariant, the value
916
 *
917
 * Creates a new dictionary entry #GVariant. @key and @value must be
918
 * non-%NULL. @key must be a value of a basic type (ie: not a container).
919
 *
920
 * If the @key or @value are floating references (see g_variant_ref_sink()),
921
 * the new instance takes ownership of them as if via g_variant_ref_sink().
922
 *
923
 * Returns: (transfer none): a floating reference to a new dictionary entry #GVariant
924
 *
925
 * Since: 2.24
926
 **/
927
GVariant *
928
g_variant_new_dict_entry (GVariant *key,
929
                          GVariant *value)
930
0
{
931
0
  GVariantType *dict_type;
932
0
  GVariant **children;
933
0
  gboolean trusted;
934
935
0
  g_return_val_if_fail (key != NULL && value != NULL, NULL);
936
0
  g_return_val_if_fail (!g_variant_is_container (key), NULL);
937
938
0
  children = g_new (GVariant *, 2);
939
0
  children[0] = g_variant_ref_sink (key);
940
0
  children[1] = g_variant_ref_sink (value);
941
0
  trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
942
943
0
  dict_type = g_variant_make_dict_entry_type (key, value);
944
0
  value = g_variant_new_from_children (dict_type, children, 2, trusted);
945
0
  g_variant_type_free (dict_type);
946
947
0
  return value;
948
0
}
949
950
/**
951
 * g_variant_lookup: (skip)
952
 * @dictionary: a dictionary #GVariant
953
 * @key: the key to look up in the dictionary
954
 * @format_string: a GVariant format string
955
 * @...: the arguments to unpack the value into
956
 *
957
 * Looks up a value in a dictionary #GVariant.
958
 *
959
 * This function is a wrapper around g_variant_lookup_value() and
960
 * g_variant_get().  In the case that %NULL would have been returned,
961
 * this function returns %FALSE.  Otherwise, it unpacks the returned
962
 * value and returns %TRUE.
963
 *
964
 * @format_string determines the C types that are used for unpacking
965
 * the values and also determines if the values are copied or borrowed,
966
 * see the section on
967
 * [GVariant format strings][gvariant-format-strings-pointers].
968
 *
969
 * This function is currently implemented with a linear scan.  If you
970
 * plan to do many lookups then #GVariantDict may be more efficient.
971
 *
972
 * Returns: %TRUE if a value was unpacked
973
 *
974
 * Since: 2.28
975
 */
976
gboolean
977
g_variant_lookup (GVariant    *dictionary,
978
                  const gchar *key,
979
                  const gchar *format_string,
980
                  ...)
981
0
{
982
0
  GVariantType *type;
983
0
  GVariant *value;
984
985
  /* flatten */
986
0
  g_variant_get_data (dictionary);
987
988
0
  type = g_variant_format_string_scan_type (format_string, NULL, NULL);
989
0
  value = g_variant_lookup_value (dictionary, key, type);
990
0
  g_variant_type_free (type);
991
992
0
  if (value)
993
0
    {
994
0
      va_list ap;
995
996
0
      va_start (ap, format_string);
997
0
      g_variant_get_va (value, format_string, NULL, &ap);
998
0
      g_variant_unref (value);
999
0
      va_end (ap);
1000
1001
0
      return TRUE;
1002
0
    }
1003
1004
0
  else
1005
0
    return FALSE;
1006
0
}
1007
1008
/**
1009
 * g_variant_lookup_value:
1010
 * @dictionary: a dictionary #GVariant
1011
 * @key: the key to look up in the dictionary
1012
 * @expected_type: (nullable): a #GVariantType, or %NULL
1013
 *
1014
 * Looks up a value in a dictionary #GVariant.
1015
 *
1016
 * This function works with dictionaries of the type a{s*} (and equally
1017
 * well with type a{o*}, but we only further discuss the string case
1018
 * for sake of clarity).
1019
 *
1020
 * In the event that @dictionary has the type a{sv}, the @expected_type
1021
 * string specifies what type of value is expected to be inside of the
1022
 * variant. If the value inside the variant has a different type then
1023
 * %NULL is returned. In the event that @dictionary has a value type other
1024
 * than v then @expected_type must directly match the value type and it is
1025
 * used to unpack the value directly or an error occurs.
1026
 *
1027
 * In either case, if @key is not found in @dictionary, %NULL is returned.
1028
 *
1029
 * If the key is found and the value has the correct type, it is
1030
 * returned.  If @expected_type was specified then any non-%NULL return
1031
 * value will have this type.
1032
 *
1033
 * This function is currently implemented with a linear scan.  If you
1034
 * plan to do many lookups then #GVariantDict may be more efficient.
1035
 *
1036
 * Returns: (transfer full): the value of the dictionary key, or %NULL
1037
 *
1038
 * Since: 2.28
1039
 */
1040
GVariant *
1041
g_variant_lookup_value (GVariant           *dictionary,
1042
                        const gchar        *key,
1043
                        const GVariantType *expected_type)
1044
0
{
1045
0
  GVariantIter iter;
1046
0
  GVariant *entry;
1047
0
  GVariant *value;
1048
1049
0
  g_return_val_if_fail (g_variant_is_of_type (dictionary,
1050
0
                                              G_VARIANT_TYPE ("a{s*}")) ||
1051
0
                        g_variant_is_of_type (dictionary,
1052
0
                                              G_VARIANT_TYPE ("a{o*}")),
1053
0
                        NULL);
1054
1055
0
  g_variant_iter_init (&iter, dictionary);
1056
1057
0
  while ((entry = g_variant_iter_next_value (&iter)))
1058
0
    {
1059
0
      GVariant *entry_key;
1060
0
      gboolean matches;
1061
1062
0
      entry_key = g_variant_get_child_value (entry, 0);
1063
0
      matches = strcmp (g_variant_get_string (entry_key, NULL), key) == 0;
1064
0
      g_variant_unref (entry_key);
1065
1066
0
      if (matches)
1067
0
        break;
1068
1069
0
      g_variant_unref (entry);
1070
0
    }
1071
1072
0
  if (entry == NULL)
1073
0
    return NULL;
1074
1075
0
  value = g_variant_get_child_value (entry, 1);
1076
0
  g_variant_unref (entry);
1077
1078
0
  if (g_variant_is_of_type (value, G_VARIANT_TYPE_VARIANT))
1079
0
    {
1080
0
      GVariant *tmp;
1081
1082
0
      tmp = g_variant_get_variant (value);
1083
0
      g_variant_unref (value);
1084
1085
0
      if (expected_type && !g_variant_is_of_type (tmp, expected_type))
1086
0
        {
1087
0
          g_variant_unref (tmp);
1088
0
          tmp = NULL;
1089
0
        }
1090
1091
0
      value = tmp;
1092
0
    }
1093
1094
0
  g_return_val_if_fail (expected_type == NULL || value == NULL ||
1095
0
                        g_variant_is_of_type (value, expected_type), NULL);
1096
1097
0
  return value;
1098
0
}
1099
1100
/**
1101
 * g_variant_get_fixed_array:
1102
 * @value: a #GVariant array with fixed-sized elements
1103
 * @n_elements: (out): a pointer to the location to store the number of items
1104
 * @element_size: the size of each element
1105
 *
1106
 * Provides access to the serialized data for an array of fixed-sized
1107
 * items.
1108
 *
1109
 * @value must be an array with fixed-sized elements.  Numeric types are
1110
 * fixed-size, as are tuples containing only other fixed-sized types.
1111
 *
1112
 * @element_size must be the size of a single element in the array,
1113
 * as given by the section on
1114
 * [serialized data memory][gvariant-serialized-data-memory].
1115
 *
1116
 * In particular, arrays of these fixed-sized types can be interpreted
1117
 * as an array of the given C type, with @element_size set to the size
1118
 * the appropriate type:
1119
 * - %G_VARIANT_TYPE_INT16 (etc.): #gint16 (etc.)
1120
 * - %G_VARIANT_TYPE_BOOLEAN: #guchar (not #gboolean!)
1121
 * - %G_VARIANT_TYPE_BYTE: #guint8
1122
 * - %G_VARIANT_TYPE_HANDLE: #guint32
1123
 * - %G_VARIANT_TYPE_DOUBLE: #gdouble
1124
 *
1125
 * For example, if calling this function for an array of 32-bit integers,
1126
 * you might say `sizeof(gint32)`. This value isn't used except for the purpose
1127
 * of a double-check that the form of the serialized data matches the caller's
1128
 * expectation.
1129
 *
1130
 * @n_elements, which must be non-%NULL, is set equal to the number of
1131
 * items in the array.
1132
 *
1133
 * Returns: (array length=n_elements) (transfer none): a pointer to
1134
 *     the fixed array
1135
 *
1136
 * Since: 2.24
1137
 **/
1138
gconstpointer
1139
g_variant_get_fixed_array (GVariant *value,
1140
                           gsize    *n_elements,
1141
                           gsize     element_size)
1142
0
{
1143
0
  GVariantTypeInfo *array_info;
1144
0
  gsize array_element_size;
1145
0
  gconstpointer data;
1146
0
  gsize size;
1147
1148
0
  TYPE_CHECK (value, G_VARIANT_TYPE_ARRAY, NULL);
1149
1150
0
  g_return_val_if_fail (n_elements != NULL, NULL);
1151
0
  g_return_val_if_fail (element_size > 0, NULL);
1152
1153
0
  array_info = g_variant_get_type_info (value);
1154
0
  g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1155
1156
0
  g_return_val_if_fail (array_element_size, NULL);
1157
1158
0
  if G_UNLIKELY (array_element_size != element_size)
1159
0
    {
1160
0
      if (array_element_size)
1161
0
        g_critical ("g_variant_get_fixed_array: assertion "
1162
0
                    "'g_variant_array_has_fixed_size (value, element_size)' "
1163
0
                    "failed: array size %"G_GSIZE_FORMAT" does not match "
1164
0
                    "given element_size %"G_GSIZE_FORMAT".",
1165
0
                    array_element_size, element_size);
1166
0
      else
1167
0
        g_critical ("g_variant_get_fixed_array: assertion "
1168
0
                    "'g_variant_array_has_fixed_size (value, element_size)' "
1169
0
                    "failed: array does not have fixed size.");
1170
0
    }
1171
1172
0
  data = g_variant_get_data (value);
1173
0
  size = g_variant_get_size (value);
1174
1175
0
  if (size % element_size)
1176
0
    *n_elements = 0;
1177
0
  else
1178
0
    *n_elements = size / element_size;
1179
1180
0
  if (*n_elements)
1181
0
    return data;
1182
1183
0
  return NULL;
1184
0
}
1185
1186
/**
1187
 * g_variant_new_fixed_array:
1188
 * @element_type: the #GVariantType of each element
1189
 * @elements: a pointer to the fixed array of contiguous elements
1190
 * @n_elements: the number of elements
1191
 * @element_size: the size of each element
1192
 *
1193
 * Constructs a new array #GVariant instance, where the elements are
1194
 * of @element_type type.
1195
 *
1196
 * @elements must be an array with fixed-sized elements.  Numeric types are
1197
 * fixed-size as are tuples containing only other fixed-sized types.
1198
 *
1199
 * @element_size must be the size of a single element in the array.
1200
 * For example, if calling this function for an array of 32-bit integers,
1201
 * you might say sizeof(gint32). This value isn't used except for the purpose
1202
 * of a double-check that the form of the serialized data matches the caller's
1203
 * expectation.
1204
 *
1205
 * @n_elements must be the length of the @elements array.
1206
 *
1207
 * Returns: (transfer none): a floating reference to a new array #GVariant instance
1208
 *
1209
 * Since: 2.32
1210
 **/
1211
GVariant *
1212
g_variant_new_fixed_array (const GVariantType  *element_type,
1213
                           gconstpointer        elements,
1214
                           gsize                n_elements,
1215
                           gsize                element_size)
1216
0
{
1217
0
  GVariantType *array_type;
1218
0
  gsize array_element_size;
1219
0
  GVariantTypeInfo *array_info;
1220
0
  GVariant *value;
1221
0
  gpointer data;
1222
1223
0
  g_return_val_if_fail (g_variant_type_is_definite (element_type), NULL);
1224
0
  g_return_val_if_fail (element_size > 0, NULL);
1225
1226
0
  array_type = g_variant_type_new_array (element_type);
1227
0
  array_info = g_variant_type_info_get (array_type);
1228
0
  g_variant_type_info_query_element (array_info, NULL, &array_element_size);
1229
0
  if G_UNLIKELY (array_element_size != element_size)
1230
0
    {
1231
0
      if (array_element_size)
1232
0
        g_critical ("g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
1233
0
                    " does not match given element_size %" G_GSIZE_FORMAT ".",
1234
0
                    array_element_size, element_size);
1235
0
      else
1236
0
        g_critical ("g_variant_get_fixed_array: array does not have fixed size.");
1237
0
      return NULL;
1238
0
    }
1239
1240
0
  data = g_memdup2 (elements, n_elements * element_size);
1241
0
  value = g_variant_new_from_data (array_type, data,
1242
0
                                   n_elements * element_size,
1243
0
                                   FALSE, g_free, data);
1244
1245
0
  g_variant_type_free (array_type);
1246
0
  g_variant_type_info_unref (array_info);
1247
1248
0
  return value;
1249
0
}
1250
1251
/* String type constructor/getters/validation {{{1 */
1252
/**
1253
 * g_variant_new_string:
1254
 * @string: a normal UTF-8 nul-terminated string
1255
 *
1256
 * Creates a string #GVariant with the contents of @string.
1257
 *
1258
 * @string must be valid UTF-8, and must not be %NULL. To encode
1259
 * potentially-%NULL strings, use g_variant_new() with `ms` as the
1260
 * [format string][gvariant-format-strings-maybe-types].
1261
 *
1262
 * Returns: (transfer none): a floating reference to a new string #GVariant instance
1263
 *
1264
 * Since: 2.24
1265
 **/
1266
GVariant *
1267
g_variant_new_string (const gchar *string)
1268
0
{
1269
0
  g_return_val_if_fail (string != NULL, NULL);
1270
0
  g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1271
1272
0
  return g_variant_new_from_trusted (G_VARIANT_TYPE_STRING,
1273
0
                                     string, strlen (string) + 1);
1274
0
}
1275
1276
/**
1277
 * g_variant_new_take_string: (skip)
1278
 * @string: a normal UTF-8 nul-terminated string
1279
 *
1280
 * Creates a string #GVariant with the contents of @string.
1281
 *
1282
 * @string must be valid UTF-8, and must not be %NULL. To encode
1283
 * potentially-%NULL strings, use this with g_variant_new_maybe().
1284
 *
1285
 * After this call, @string belongs to the #GVariant and may no longer be
1286
 * modified by the caller. The memory of @data has to be dynamically
1287
 * allocated and will eventually be freed with g_free().
1288
 *
1289
 * You must not modify or access @string in any other way after passing
1290
 * it to this function.  It is even possible that @string is immediately
1291
 * freed.
1292
 *
1293
 * Returns: (transfer none): a floating reference to a new string
1294
 *   #GVariant instance
1295
 *
1296
 * Since: 2.38
1297
 **/
1298
GVariant *
1299
g_variant_new_take_string (gchar *string)
1300
0
{
1301
0
  GVariant *value;
1302
0
  GBytes *bytes;
1303
1304
0
  g_return_val_if_fail (string != NULL, NULL);
1305
0
  g_return_val_if_fail (g_utf8_validate (string, -1, NULL), NULL);
1306
1307
0
  bytes = g_bytes_new_take (string, strlen (string) + 1);
1308
0
  value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1309
0
  g_bytes_unref (bytes);
1310
1311
0
  return value;
1312
0
}
1313
1314
/**
1315
 * g_variant_new_printf: (skip)
1316
 * @format_string: a printf-style format string
1317
 * @...: arguments for @format_string
1318
 *
1319
 * Creates a string-type GVariant using printf formatting.
1320
 *
1321
 * This is similar to calling g_strdup_printf() and then
1322
 * g_variant_new_string() but it saves a temporary variable and an
1323
 * unnecessary copy.
1324
 *
1325
 * Returns: (transfer none): a floating reference to a new string
1326
 *   #GVariant instance
1327
 *
1328
 * Since: 2.38
1329
 **/
1330
GVariant *
1331
g_variant_new_printf (const gchar *format_string,
1332
                      ...)
1333
0
{
1334
0
  GVariant *value;
1335
0
  GBytes *bytes;
1336
0
  gchar *string;
1337
0
  va_list ap;
1338
1339
0
  g_return_val_if_fail (format_string != NULL, NULL);
1340
1341
0
  va_start (ap, format_string);
1342
0
  string = g_strdup_vprintf (format_string, ap);
1343
0
  va_end (ap);
1344
1345
0
  bytes = g_bytes_new_take (string, strlen (string) + 1);
1346
0
  value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
1347
0
  g_bytes_unref (bytes);
1348
1349
0
  return value;
1350
0
}
1351
1352
/**
1353
 * g_variant_new_object_path:
1354
 * @object_path: a normal C nul-terminated string
1355
 *
1356
 * Creates a D-Bus object path #GVariant with the contents of @object_path.
1357
 * @object_path must be a valid D-Bus object path.  Use
1358
 * g_variant_is_object_path() if you're not sure.
1359
 *
1360
 * Returns: (transfer none): a floating reference to a new object path #GVariant instance
1361
 *
1362
 * Since: 2.24
1363
 **/
1364
GVariant *
1365
g_variant_new_object_path (const gchar *object_path)
1366
0
{
1367
0
  g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
1368
1369
0
  return g_variant_new_from_trusted (G_VARIANT_TYPE_OBJECT_PATH,
1370
0
                                     object_path, strlen (object_path) + 1);
1371
0
}
1372
1373
/**
1374
 * g_variant_is_object_path:
1375
 * @string: a normal C nul-terminated string
1376
 *
1377
 * Determines if a given string is a valid D-Bus object path.  You
1378
 * should ensure that a string is a valid D-Bus object path before
1379
 * passing it to g_variant_new_object_path().
1380
 *
1381
 * A valid object path starts with `/` followed by zero or more
1382
 * sequences of characters separated by `/` characters.  Each sequence
1383
 * must contain only the characters `[A-Z][a-z][0-9]_`.  No sequence
1384
 * (including the one following the final `/` character) may be empty.
1385
 *
1386
 * Returns: %TRUE if @string is a D-Bus object path
1387
 *
1388
 * Since: 2.24
1389
 **/
1390
gboolean
1391
g_variant_is_object_path (const gchar *string)
1392
0
{
1393
0
  g_return_val_if_fail (string != NULL, FALSE);
1394
1395
0
  return g_variant_serialiser_is_object_path (string, strlen (string) + 1);
1396
0
}
1397
1398
/**
1399
 * g_variant_new_signature:
1400
 * @signature: a normal C nul-terminated string
1401
 *
1402
 * Creates a D-Bus type signature #GVariant with the contents of
1403
 * @string.  @string must be a valid D-Bus type signature.  Use
1404
 * g_variant_is_signature() if you're not sure.
1405
 *
1406
 * Returns: (transfer none): a floating reference to a new signature #GVariant instance
1407
 *
1408
 * Since: 2.24
1409
 **/
1410
GVariant *
1411
g_variant_new_signature (const gchar *signature)
1412
0
{
1413
0
  g_return_val_if_fail (g_variant_is_signature (signature), NULL);
1414
1415
0
  return g_variant_new_from_trusted (G_VARIANT_TYPE_SIGNATURE,
1416
0
                                     signature, strlen (signature) + 1);
1417
0
}
1418
1419
/**
1420
 * g_variant_is_signature:
1421
 * @string: a normal C nul-terminated string
1422
 *
1423
 * Determines if a given string is a valid D-Bus type signature.  You
1424
 * should ensure that a string is a valid D-Bus type signature before
1425
 * passing it to g_variant_new_signature().
1426
 *
1427
 * D-Bus type signatures consist of zero or more definite #GVariantType
1428
 * strings in sequence.
1429
 *
1430
 * Returns: %TRUE if @string is a D-Bus type signature
1431
 *
1432
 * Since: 2.24
1433
 **/
1434
gboolean
1435
g_variant_is_signature (const gchar *string)
1436
0
{
1437
0
  g_return_val_if_fail (string != NULL, FALSE);
1438
1439
0
  return g_variant_serialiser_is_signature (string, strlen (string) + 1);
1440
0
}
1441
1442
/**
1443
 * g_variant_get_string:
1444
 * @value: a string #GVariant instance
1445
 * @length: (optional) (default 0) (out): a pointer to a #gsize,
1446
 *          to store the length
1447
 *
1448
 * Returns the string value of a #GVariant instance with a string
1449
 * type.  This includes the types %G_VARIANT_TYPE_STRING,
1450
 * %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
1451
 *
1452
 * The string will always be UTF-8 encoded, will never be %NULL, and will never
1453
 * contain nul bytes.
1454
 *
1455
 * If @length is non-%NULL then the length of the string (in bytes) is
1456
 * returned there.  For trusted values, this information is already
1457
 * known.  Untrusted values will be validated and, if valid, a strlen() will be
1458
 * performed. If invalid, a default value will be returned — for
1459
 * %G_VARIANT_TYPE_OBJECT_PATH, this is `"/"`, and for other types it is the
1460
 * empty string.
1461
 *
1462
 * It is an error to call this function with a @value of any type
1463
 * other than those three.
1464
 *
1465
 * The return value remains valid as long as @value exists.
1466
 *
1467
 * Returns: (transfer none): the constant string, UTF-8 encoded
1468
 *
1469
 * Since: 2.24
1470
 **/
1471
const gchar *
1472
g_variant_get_string (GVariant *value,
1473
                      gsize    *length)
1474
0
{
1475
0
  gconstpointer data;
1476
0
  gsize size;
1477
1478
0
  g_return_val_if_fail (value != NULL, NULL);
1479
0
  g_return_val_if_fail (
1480
0
    g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
1481
0
    g_variant_is_of_type (value, G_VARIANT_TYPE_OBJECT_PATH) ||
1482
0
    g_variant_is_of_type (value, G_VARIANT_TYPE_SIGNATURE), NULL);
1483
1484
0
  data = g_variant_get_data (value);
1485
0
  size = g_variant_get_size (value);
1486
1487
0
  if (!g_variant_is_trusted (value))
1488
0
    {
1489
0
      switch (g_variant_classify (value))
1490
0
        {
1491
0
        case G_VARIANT_CLASS_STRING:
1492
0
          if (g_variant_serialiser_is_string (data, size))
1493
0
            break;
1494
1495
0
          data = "";
1496
0
          size = 1;
1497
0
          break;
1498
1499
0
        case G_VARIANT_CLASS_OBJECT_PATH:
1500
0
          if (g_variant_serialiser_is_object_path (data, size))
1501
0
            break;
1502
1503
0
          data = "/";
1504
0
          size = 2;
1505
0
          break;
1506
1507
0
        case G_VARIANT_CLASS_SIGNATURE:
1508
0
          if (g_variant_serialiser_is_signature (data, size))
1509
0
            break;
1510
1511
0
          data = "";
1512
0
          size = 1;
1513
0
          break;
1514
1515
0
        default:
1516
0
          g_assert_not_reached ();
1517
0
        }
1518
0
    }
1519
1520
0
  if (length)
1521
0
    *length = size - 1;
1522
1523
0
  return data;
1524
0
}
1525
1526
/**
1527
 * g_variant_dup_string:
1528
 * @value: a string #GVariant instance
1529
 * @length: (out): a pointer to a #gsize, to store the length
1530
 *
1531
 * Similar to g_variant_get_string() except that instead of returning
1532
 * a constant string, the string is duplicated.
1533
 *
1534
 * The string will always be UTF-8 encoded.
1535
 *
1536
 * The return value must be freed using g_free().
1537
 *
1538
 * Returns: (transfer full): a newly allocated string, UTF-8 encoded
1539
 *
1540
 * Since: 2.24
1541
 **/
1542
gchar *
1543
g_variant_dup_string (GVariant *value,
1544
                      gsize    *length)
1545
0
{
1546
0
  return g_strdup (g_variant_get_string (value, length));
1547
0
}
1548
1549
/**
1550
 * g_variant_new_strv:
1551
 * @strv: (array length=length) (element-type utf8): an array of strings
1552
 * @length: the length of @strv, or -1
1553
 *
1554
 * Constructs an array of strings #GVariant from the given array of
1555
 * strings.
1556
 *
1557
 * If @length is -1 then @strv is %NULL-terminated.
1558
 *
1559
 * Returns: (transfer none): a new floating #GVariant instance
1560
 *
1561
 * Since: 2.24
1562
 **/
1563
GVariant *
1564
g_variant_new_strv (const gchar * const *strv,
1565
                    gssize               length)
1566
0
{
1567
0
  GVariant **strings;
1568
0
  gsize i, length_unsigned;
1569
1570
0
  g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1571
1572
0
  if (length < 0)
1573
0
    length = g_strv_length ((gchar **) strv);
1574
0
  length_unsigned = length;
1575
1576
0
  strings = g_new (GVariant *, length_unsigned);
1577
0
  for (i = 0; i < length_unsigned; i++)
1578
0
    strings[i] = g_variant_ref_sink (g_variant_new_string (strv[i]));
1579
1580
0
  return g_variant_new_from_children (G_VARIANT_TYPE_STRING_ARRAY,
1581
0
                                      strings, length_unsigned, TRUE);
1582
0
}
1583
1584
/**
1585
 * g_variant_get_strv:
1586
 * @value: an array of strings #GVariant
1587
 * @length: (out) (optional): the length of the result, or %NULL
1588
 *
1589
 * Gets the contents of an array of strings #GVariant.  This call
1590
 * makes a shallow copy; the return result should be released with
1591
 * g_free(), but the individual strings must not be modified.
1592
 *
1593
 * If @length is non-%NULL then the number of elements in the result
1594
 * is stored there.  In any case, the resulting array will be
1595
 * %NULL-terminated.
1596
 *
1597
 * For an empty array, @length will be set to 0 and a pointer to a
1598
 * %NULL pointer will be returned.
1599
 *
1600
 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1601
 *
1602
 * Since: 2.24
1603
 **/
1604
const gchar **
1605
g_variant_get_strv (GVariant *value,
1606
                    gsize    *length)
1607
0
{
1608
0
  const gchar **strv;
1609
0
  gsize n;
1610
0
  gsize i;
1611
1612
0
  TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1613
1614
0
  g_variant_get_data (value);
1615
0
  n = g_variant_n_children (value);
1616
0
  strv = g_new (const gchar *, n + 1);
1617
1618
0
  for (i = 0; i < n; i++)
1619
0
    {
1620
0
      GVariant *string;
1621
1622
0
      string = g_variant_get_child_value (value, i);
1623
0
      strv[i] = g_variant_get_string (string, NULL);
1624
0
      g_variant_unref (string);
1625
0
    }
1626
0
  strv[i] = NULL;
1627
1628
0
  if (length)
1629
0
    *length = n;
1630
1631
0
  return strv;
1632
0
}
1633
1634
/**
1635
 * g_variant_dup_strv:
1636
 * @value: an array of strings #GVariant
1637
 * @length: (out) (optional): the length of the result, or %NULL
1638
 *
1639
 * Gets the contents of an array of strings #GVariant.  This call
1640
 * makes a deep copy; the return result should be released with
1641
 * g_strfreev().
1642
 *
1643
 * If @length is non-%NULL then the number of elements in the result
1644
 * is stored there.  In any case, the resulting array will be
1645
 * %NULL-terminated.
1646
 *
1647
 * For an empty array, @length will be set to 0 and a pointer to a
1648
 * %NULL pointer will be returned.
1649
 *
1650
 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1651
 *
1652
 * Since: 2.24
1653
 **/
1654
gchar **
1655
g_variant_dup_strv (GVariant *value,
1656
                    gsize    *length)
1657
0
{
1658
0
  gchar **strv;
1659
0
  gsize n;
1660
0
  gsize i;
1661
1662
0
  TYPE_CHECK (value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
1663
1664
0
  n = g_variant_n_children (value);
1665
0
  strv = g_new (gchar *, n + 1);
1666
1667
0
  for (i = 0; i < n; i++)
1668
0
    {
1669
0
      GVariant *string;
1670
1671
0
      string = g_variant_get_child_value (value, i);
1672
0
      strv[i] = g_variant_dup_string (string, NULL);
1673
0
      g_variant_unref (string);
1674
0
    }
1675
0
  strv[i] = NULL;
1676
1677
0
  if (length)
1678
0
    *length = n;
1679
1680
0
  return strv;
1681
0
}
1682
1683
/**
1684
 * g_variant_new_objv:
1685
 * @strv: (array length=length) (element-type utf8): an array of strings
1686
 * @length: the length of @strv, or -1
1687
 *
1688
 * Constructs an array of object paths #GVariant from the given array of
1689
 * strings.
1690
 *
1691
 * Each string must be a valid #GVariant object path; see
1692
 * g_variant_is_object_path().
1693
 *
1694
 * If @length is -1 then @strv is %NULL-terminated.
1695
 *
1696
 * Returns: (transfer none): a new floating #GVariant instance
1697
 *
1698
 * Since: 2.30
1699
 **/
1700
GVariant *
1701
g_variant_new_objv (const gchar * const *strv,
1702
                    gssize               length)
1703
0
{
1704
0
  GVariant **strings;
1705
0
  gsize i, length_unsigned;
1706
1707
0
  g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1708
1709
0
  if (length < 0)
1710
0
    length = g_strv_length ((gchar **) strv);
1711
0
  length_unsigned = length;
1712
1713
0
  strings = g_new (GVariant *, length_unsigned);
1714
0
  for (i = 0; i < length_unsigned; i++)
1715
0
    strings[i] = g_variant_ref_sink (g_variant_new_object_path (strv[i]));
1716
1717
0
  return g_variant_new_from_children (G_VARIANT_TYPE_OBJECT_PATH_ARRAY,
1718
0
                                      strings, length_unsigned, TRUE);
1719
0
}
1720
1721
/**
1722
 * g_variant_get_objv:
1723
 * @value: an array of object paths #GVariant
1724
 * @length: (out) (optional): the length of the result, or %NULL
1725
 *
1726
 * Gets the contents of an array of object paths #GVariant.  This call
1727
 * makes a shallow copy; the return result should be released with
1728
 * g_free(), but the individual strings must not be modified.
1729
 *
1730
 * If @length is non-%NULL then the number of elements in the result
1731
 * is stored there.  In any case, the resulting array will be
1732
 * %NULL-terminated.
1733
 *
1734
 * For an empty array, @length will be set to 0 and a pointer to a
1735
 * %NULL pointer will be returned.
1736
 *
1737
 * Returns: (array length=length zero-terminated=1) (transfer container): an array of constant strings
1738
 *
1739
 * Since: 2.30
1740
 **/
1741
const gchar **
1742
g_variant_get_objv (GVariant *value,
1743
                    gsize    *length)
1744
0
{
1745
0
  const gchar **strv;
1746
0
  gsize n;
1747
0
  gsize i;
1748
1749
0
  TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1750
1751
0
  g_variant_get_data (value);
1752
0
  n = g_variant_n_children (value);
1753
0
  strv = g_new (const gchar *, n + 1);
1754
1755
0
  for (i = 0; i < n; i++)
1756
0
    {
1757
0
      GVariant *string;
1758
1759
0
      string = g_variant_get_child_value (value, i);
1760
0
      strv[i] = g_variant_get_string (string, NULL);
1761
0
      g_variant_unref (string);
1762
0
    }
1763
0
  strv[i] = NULL;
1764
1765
0
  if (length)
1766
0
    *length = n;
1767
1768
0
  return strv;
1769
0
}
1770
1771
/**
1772
 * g_variant_dup_objv:
1773
 * @value: an array of object paths #GVariant
1774
 * @length: (out) (optional): the length of the result, or %NULL
1775
 *
1776
 * Gets the contents of an array of object paths #GVariant.  This call
1777
 * makes a deep copy; the return result should be released with
1778
 * g_strfreev().
1779
 *
1780
 * If @length is non-%NULL then the number of elements in the result
1781
 * is stored there.  In any case, the resulting array will be
1782
 * %NULL-terminated.
1783
 *
1784
 * For an empty array, @length will be set to 0 and a pointer to a
1785
 * %NULL pointer will be returned.
1786
 *
1787
 * Returns: (array length=length zero-terminated=1) (transfer full): an array of strings
1788
 *
1789
 * Since: 2.30
1790
 **/
1791
gchar **
1792
g_variant_dup_objv (GVariant *value,
1793
                    gsize    *length)
1794
0
{
1795
0
  gchar **strv;
1796
0
  gsize n;
1797
0
  gsize i;
1798
1799
0
  TYPE_CHECK (value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
1800
1801
0
  n = g_variant_n_children (value);
1802
0
  strv = g_new (gchar *, n + 1);
1803
1804
0
  for (i = 0; i < n; i++)
1805
0
    {
1806
0
      GVariant *string;
1807
1808
0
      string = g_variant_get_child_value (value, i);
1809
0
      strv[i] = g_variant_dup_string (string, NULL);
1810
0
      g_variant_unref (string);
1811
0
    }
1812
0
  strv[i] = NULL;
1813
1814
0
  if (length)
1815
0
    *length = n;
1816
1817
0
  return strv;
1818
0
}
1819
1820
1821
/**
1822
 * g_variant_new_bytestring:
1823
 * @string: (array zero-terminated=1) (element-type guint8): a normal
1824
 *          nul-terminated string in no particular encoding
1825
 *
1826
 * Creates an array-of-bytes #GVariant with the contents of @string.
1827
 * This function is just like g_variant_new_string() except that the
1828
 * string need not be valid UTF-8.
1829
 *
1830
 * The nul terminator character at the end of the string is stored in
1831
 * the array.
1832
 *
1833
 * Returns: (transfer none): a floating reference to a new bytestring #GVariant instance
1834
 *
1835
 * Since: 2.26
1836
 **/
1837
GVariant *
1838
g_variant_new_bytestring (const gchar *string)
1839
0
{
1840
0
  g_return_val_if_fail (string != NULL, NULL);
1841
1842
0
  return g_variant_new_from_trusted (G_VARIANT_TYPE_BYTESTRING,
1843
0
                                     string, strlen (string) + 1);
1844
0
}
1845
1846
/**
1847
 * g_variant_get_bytestring:
1848
 * @value: an array-of-bytes #GVariant instance
1849
 *
1850
 * Returns the string value of a #GVariant instance with an
1851
 * array-of-bytes type.  The string has no particular encoding.
1852
 *
1853
 * If the array does not end with a nul terminator character, the empty
1854
 * string is returned.  For this reason, you can always trust that a
1855
 * non-%NULL nul-terminated string will be returned by this function.
1856
 *
1857
 * If the array contains a nul terminator character somewhere other than
1858
 * the last byte then the returned string is the string, up to the first
1859
 * such nul character.
1860
 *
1861
 * g_variant_get_fixed_array() should be used instead if the array contains
1862
 * arbitrary data that could not be nul-terminated or could contain nul bytes.
1863
 *
1864
 * It is an error to call this function with a @value that is not an
1865
 * array of bytes.
1866
 *
1867
 * The return value remains valid as long as @value exists.
1868
 *
1869
 * Returns: (transfer none) (array zero-terminated=1) (element-type guint8):
1870
 *          the constant string
1871
 *
1872
 * Since: 2.26
1873
 **/
1874
const gchar *
1875
g_variant_get_bytestring (GVariant *value)
1876
0
{
1877
0
  const gchar *string;
1878
0
  gsize size;
1879
1880
0
  TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING, NULL);
1881
1882
  /* Won't be NULL since this is an array type */
1883
0
  string = g_variant_get_data (value);
1884
0
  size = g_variant_get_size (value);
1885
1886
0
  if (size && string[size - 1] == '\0')
1887
0
    return string;
1888
0
  else
1889
0
    return "";
1890
0
}
1891
1892
/**
1893
 * g_variant_dup_bytestring:
1894
 * @value: an array-of-bytes #GVariant instance
1895
 * @length: (out) (optional) (default NULL): a pointer to a #gsize, to store
1896
 *          the length (not including the nul terminator)
1897
 *
1898
 * Similar to g_variant_get_bytestring() except that instead of
1899
 * returning a constant string, the string is duplicated.
1900
 *
1901
 * The return value must be freed using g_free().
1902
 *
1903
 * Returns: (transfer full) (array zero-terminated=1 length=length) (element-type guint8):
1904
 *          a newly allocated string
1905
 *
1906
 * Since: 2.26
1907
 **/
1908
gchar *
1909
g_variant_dup_bytestring (GVariant *value,
1910
                          gsize    *length)
1911
0
{
1912
0
  const gchar *original = g_variant_get_bytestring (value);
1913
0
  gsize size;
1914
1915
  /* don't crash in case get_bytestring() had an assert failure */
1916
0
  if (original == NULL)
1917
0
    return NULL;
1918
1919
0
  size = strlen (original);
1920
1921
0
  if (length)
1922
0
    *length = size;
1923
1924
0
  return g_memdup2 (original, size + 1);
1925
0
}
1926
1927
/**
1928
 * g_variant_new_bytestring_array:
1929
 * @strv: (array length=length): an array of strings
1930
 * @length: the length of @strv, or -1
1931
 *
1932
 * Constructs an array of bytestring #GVariant from the given array of
1933
 * strings.
1934
 *
1935
 * If @length is -1 then @strv is %NULL-terminated.
1936
 *
1937
 * Returns: (transfer none): a new floating #GVariant instance
1938
 *
1939
 * Since: 2.26
1940
 **/
1941
GVariant *
1942
g_variant_new_bytestring_array (const gchar * const *strv,
1943
                                gssize               length)
1944
0
{
1945
0
  GVariant **strings;
1946
0
  gsize i, length_unsigned;
1947
1948
0
  g_return_val_if_fail (length == 0 || strv != NULL, NULL);
1949
1950
0
  if (length < 0)
1951
0
    length = g_strv_length ((gchar **) strv);
1952
0
  length_unsigned = length;
1953
1954
0
  strings = g_new (GVariant *, length_unsigned);
1955
0
  for (i = 0; i < length_unsigned; i++)
1956
0
    strings[i] = g_variant_ref_sink (g_variant_new_bytestring (strv[i]));
1957
1958
0
  return g_variant_new_from_children (G_VARIANT_TYPE_BYTESTRING_ARRAY,
1959
0
                                      strings, length_unsigned, TRUE);
1960
0
}
1961
1962
/**
1963
 * g_variant_get_bytestring_array:
1964
 * @value: an array of array of bytes #GVariant ('aay')
1965
 * @length: (out) (optional): the length of the result, or %NULL
1966
 *
1967
 * Gets the contents of an array of array of bytes #GVariant.  This call
1968
 * makes a shallow copy; the return result should be released with
1969
 * g_free(), but the individual strings must not be modified.
1970
 *
1971
 * If @length is non-%NULL then the number of elements in the result is
1972
 * stored there.  In any case, the resulting array will be
1973
 * %NULL-terminated.
1974
 *
1975
 * For an empty array, @length will be set to 0 and a pointer to a
1976
 * %NULL pointer will be returned.
1977
 *
1978
 * Returns: (array length=length) (transfer container): an array of constant strings
1979
 *
1980
 * Since: 2.26
1981
 **/
1982
const gchar **
1983
g_variant_get_bytestring_array (GVariant *value,
1984
                                gsize    *length)
1985
0
{
1986
0
  const gchar **strv;
1987
0
  gsize n;
1988
0
  gsize i;
1989
1990
0
  TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
1991
1992
0
  g_variant_get_data (value);
1993
0
  n = g_variant_n_children (value);
1994
0
  strv = g_new (const gchar *, n + 1);
1995
1996
0
  for (i = 0; i < n; i++)
1997
0
    {
1998
0
      GVariant *string;
1999
2000
0
      string = g_variant_get_child_value (value, i);
2001
0
      strv[i] = g_variant_get_bytestring (string);
2002
0
      g_variant_unref (string);
2003
0
    }
2004
0
  strv[i] = NULL;
2005
2006
0
  if (length)
2007
0
    *length = n;
2008
2009
0
  return strv;
2010
0
}
2011
2012
/**
2013
 * g_variant_dup_bytestring_array:
2014
 * @value: an array of array of bytes #GVariant ('aay')
2015
 * @length: (out) (optional): the length of the result, or %NULL
2016
 *
2017
 * Gets the contents of an array of array of bytes #GVariant.  This call
2018
 * makes a deep copy; the return result should be released with
2019
 * g_strfreev().
2020
 *
2021
 * If @length is non-%NULL then the number of elements in the result is
2022
 * stored there.  In any case, the resulting array will be
2023
 * %NULL-terminated.
2024
 *
2025
 * For an empty array, @length will be set to 0 and a pointer to a
2026
 * %NULL pointer will be returned.
2027
 *
2028
 * Returns: (array length=length) (transfer full): an array of strings
2029
 *
2030
 * Since: 2.26
2031
 **/
2032
gchar **
2033
g_variant_dup_bytestring_array (GVariant *value,
2034
                                gsize    *length)
2035
0
{
2036
0
  gchar **strv;
2037
0
  gsize n;
2038
0
  gsize i;
2039
2040
0
  TYPE_CHECK (value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
2041
2042
0
  g_variant_get_data (value);
2043
0
  n = g_variant_n_children (value);
2044
0
  strv = g_new (gchar *, n + 1);
2045
2046
0
  for (i = 0; i < n; i++)
2047
0
    {
2048
0
      GVariant *string;
2049
2050
0
      string = g_variant_get_child_value (value, i);
2051
0
      strv[i] = g_variant_dup_bytestring (string, NULL);
2052
0
      g_variant_unref (string);
2053
0
    }
2054
0
  strv[i] = NULL;
2055
2056
0
  if (length)
2057
0
    *length = n;
2058
2059
0
  return strv;
2060
0
}
2061
2062
/* Type checking and querying {{{1 */
2063
/**
2064
 * g_variant_get_type:
2065
 * @value: a #GVariant
2066
 *
2067
 * Determines the type of @value.
2068
 *
2069
 * The return value is valid for the lifetime of @value and must not
2070
 * be freed.
2071
 *
2072
 * Returns: a #GVariantType
2073
 *
2074
 * Since: 2.24
2075
 **/
2076
const GVariantType *
2077
g_variant_get_type (GVariant *value)
2078
0
{
2079
0
  GVariantTypeInfo *type_info;
2080
2081
0
  g_return_val_if_fail (value != NULL, NULL);
2082
2083
0
  type_info = g_variant_get_type_info (value);
2084
2085
0
  return (GVariantType *) g_variant_type_info_get_type_string (type_info);
2086
0
}
2087
2088
/**
2089
 * g_variant_get_type_string:
2090
 * @value: a #GVariant
2091
 *
2092
 * Returns the type string of @value.  Unlike the result of calling
2093
 * g_variant_type_peek_string(), this string is nul-terminated.  This
2094
 * string belongs to #GVariant and must not be freed.
2095
 *
2096
 * Returns: the type string for the type of @value
2097
 *
2098
 * Since: 2.24
2099
 **/
2100
const gchar *
2101
g_variant_get_type_string (GVariant *value)
2102
0
{
2103
0
  GVariantTypeInfo *type_info;
2104
2105
0
  g_return_val_if_fail (value != NULL, NULL);
2106
2107
0
  type_info = g_variant_get_type_info (value);
2108
2109
0
  return g_variant_type_info_get_type_string (type_info);
2110
0
}
2111
2112
/**
2113
 * g_variant_is_of_type:
2114
 * @value: a #GVariant instance
2115
 * @type: a #GVariantType
2116
 *
2117
 * Checks if a value has a type matching the provided type.
2118
 *
2119
 * Returns: %TRUE if the type of @value matches @type
2120
 *
2121
 * Since: 2.24
2122
 **/
2123
gboolean
2124
g_variant_is_of_type (GVariant           *value,
2125
                      const GVariantType *type)
2126
0
{
2127
0
  return g_variant_type_is_subtype_of (g_variant_get_type (value), type);
2128
0
}
2129
2130
/**
2131
 * g_variant_is_container:
2132
 * @value: a #GVariant instance
2133
 *
2134
 * Checks if @value is a container.
2135
 *
2136
 * Returns: %TRUE if @value is a container
2137
 *
2138
 * Since: 2.24
2139
 */
2140
gboolean
2141
g_variant_is_container (GVariant *value)
2142
0
{
2143
0
  return g_variant_type_is_container (g_variant_get_type (value));
2144
0
}
2145
2146
2147
/**
2148
 * g_variant_classify:
2149
 * @value: a #GVariant
2150
 *
2151
 * Classifies @value according to its top-level type.
2152
 *
2153
 * Returns: the #GVariantClass of @value
2154
 *
2155
 * Since: 2.24
2156
 **/
2157
/**
2158
 * GVariantClass:
2159
 * @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
2160
 * @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
2161
 * @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
2162
 * @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
2163
 * @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
2164
 * @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
2165
 * @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
2166
 * @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
2167
 * @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
2168
 * @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating 
2169
 *                          point value.
2170
 * @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
2171
 * @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path 
2172
 *                               string.
2173
 * @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
2174
 * @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
2175
 * @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
2176
 * @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
2177
 * @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
2178
 * @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
2179
 *
2180
 * The range of possible top-level types of #GVariant instances.
2181
 *
2182
 * Since: 2.24
2183
 **/
2184
GVariantClass
2185
g_variant_classify (GVariant *value)
2186
0
{
2187
0
  g_return_val_if_fail (value != NULL, 0);
2188
2189
0
  return *g_variant_get_type_string (value);
2190
0
}
2191
2192
/* Pretty printer {{{1 */
2193
/* This function is not introspectable because if @string is NULL,
2194
   @returns is (transfer full), otherwise it is (transfer none), which
2195
   is not supported by GObjectIntrospection */
2196
/**
2197
 * g_variant_print_string: (skip)
2198
 * @value: a #GVariant
2199
 * @string: (nullable) (default NULL): a #GString, or %NULL
2200
 * @type_annotate: %TRUE if type information should be included in
2201
 *                 the output
2202
 *
2203
 * Behaves as g_variant_print(), but operates on a #GString.
2204
 *
2205
 * If @string is non-%NULL then it is appended to and returned.  Else,
2206
 * a new empty #GString is allocated and it is returned.
2207
 *
2208
 * Returns: a #GString containing the string
2209
 *
2210
 * Since: 2.24
2211
 **/
2212
GString *
2213
g_variant_print_string (GVariant *value,
2214
                        GString  *string,
2215
                        gboolean  type_annotate)
2216
0
{
2217
0
  const gchar *value_type_string = g_variant_get_type_string (value);
2218
2219
0
  if G_UNLIKELY (string == NULL)
2220
0
    string = g_string_new (NULL);
2221
2222
0
  switch (value_type_string[0])
2223
0
    {
2224
0
    case G_VARIANT_CLASS_MAYBE:
2225
0
      if (type_annotate)
2226
0
        g_string_append_printf (string, "@%s ", value_type_string);
2227
2228
0
      if (g_variant_n_children (value))
2229
0
        {
2230
0
          const GVariantType *base_type;
2231
0
          guint i, depth;
2232
0
          GVariant *element = NULL;
2233
2234
          /* Nested maybes:
2235
           *
2236
           * Consider the case of the type "mmi".  In this case we could
2237
           * write "just just 4", but "4" alone is totally unambiguous,
2238
           * so we try to drop "just" where possible.
2239
           *
2240
           * We have to be careful not to always drop "just", though,
2241
           * since "nothing" needs to be distinguishable from "just
2242
           * nothing".  The case where we need to ensure we keep the
2243
           * "just" is actually exactly the case where we have a nested
2244
           * Nothing.
2245
           *
2246
           * Search for the nested Nothing, to save a lot of recursion if there
2247
           * are multiple levels of maybes.
2248
           */
2249
0
          for (depth = 0, base_type = g_variant_get_type (value);
2250
0
               g_variant_type_is_maybe (base_type);
2251
0
               depth++, base_type = g_variant_type_element (base_type));
2252
2253
0
          element = g_variant_ref (value);
2254
0
          for (i = 0; i < depth && element != NULL; i++)
2255
0
            {
2256
0
              GVariant *new_element = g_variant_n_children (element) ? g_variant_get_child_value (element, 0) : NULL;
2257
0
              g_variant_unref (element);
2258
0
              element = g_steal_pointer (&new_element);
2259
0
            }
2260
2261
0
          if (element == NULL)
2262
0
            {
2263
              /* One of the maybes was Nothing, so print out the right number of
2264
               * justs. */
2265
0
              for (; i > 1; i--)
2266
0
                g_string_append (string, "just ");
2267
0
              g_string_append (string, "nothing");
2268
0
            }
2269
0
          else
2270
0
            {
2271
              /* There are no Nothings, so print out the child with no prefixes. */
2272
0
              g_variant_print_string (element, string, FALSE);
2273
0
            }
2274
2275
0
          g_clear_pointer (&element, g_variant_unref);
2276
0
        }
2277
0
      else
2278
0
        g_string_append (string, "nothing");
2279
2280
0
      break;
2281
2282
0
    case G_VARIANT_CLASS_ARRAY:
2283
      /* it's an array so the first character of the type string is 'a'
2284
       *
2285
       * if the first two characters are 'ay' then it's a bytestring.
2286
       * under certain conditions we print those as strings.
2287
       */
2288
0
      if (value_type_string[1] == 'y')
2289
0
        {
2290
0
          const gchar *str;
2291
0
          gsize size;
2292
0
          gsize i;
2293
2294
          /* first determine if it is a byte string.
2295
           * that's when there's a single nul character: at the end.
2296
           */
2297
0
          str = g_variant_get_data (value);
2298
0
          size = g_variant_get_size (value);
2299
2300
0
          for (i = 0; i < size; i++)
2301
0
            if (str[i] == '\0')
2302
0
              break;
2303
2304
          /* first nul byte is the last byte -> it's a byte string. */
2305
0
          if (i == size - 1)
2306
0
            {
2307
0
              gchar *escaped = g_strescape (str, NULL);
2308
2309
              /* use double quotes only if a ' is in the string */
2310
0
              if (strchr (str, '\''))
2311
0
                g_string_append_printf (string, "b\"%s\"", escaped);
2312
0
              else
2313
0
                g_string_append_printf (string, "b'%s'", escaped);
2314
2315
0
              g_free (escaped);
2316
0
              break;
2317
0
            }
2318
2319
0
          else
2320
0
            {
2321
              /* fall through and handle normally... */
2322
0
            }
2323
0
        }
2324
2325
      /*
2326
       * if the first two characters are 'a{' then it's an array of
2327
       * dictionary entries (ie: a dictionary) so we print that
2328
       * differently.
2329
       */
2330
0
      if (value_type_string[1] == '{')
2331
        /* dictionary */
2332
0
        {
2333
0
          const gchar *comma = "";
2334
0
          gsize n, i;
2335
2336
0
          if ((n = g_variant_n_children (value)) == 0)
2337
0
            {
2338
0
              if (type_annotate)
2339
0
                g_string_append_printf (string, "@%s ", value_type_string);
2340
0
              g_string_append (string, "{}");
2341
0
              break;
2342
0
            }
2343
2344
0
          g_string_append_c (string, '{');
2345
0
          for (i = 0; i < n; i++)
2346
0
            {
2347
0
              GVariant *entry, *key, *val;
2348
2349
0
              g_string_append (string, comma);
2350
0
              comma = ", ";
2351
2352
0
              entry = g_variant_get_child_value (value, i);
2353
0
              key = g_variant_get_child_value (entry, 0);
2354
0
              val = g_variant_get_child_value (entry, 1);
2355
0
              g_variant_unref (entry);
2356
2357
0
              g_variant_print_string (key, string, type_annotate);
2358
0
              g_variant_unref (key);
2359
0
              g_string_append (string, ": ");
2360
0
              g_variant_print_string (val, string, type_annotate);
2361
0
              g_variant_unref (val);
2362
0
              type_annotate = FALSE;
2363
0
            }
2364
0
          g_string_append_c (string, '}');
2365
0
        }
2366
0
      else
2367
        /* normal (non-dictionary) array */
2368
0
        {
2369
0
          const gchar *comma = "";
2370
0
          gsize n, i;
2371
2372
0
          if ((n = g_variant_n_children (value)) == 0)
2373
0
            {
2374
0
              if (type_annotate)
2375
0
                g_string_append_printf (string, "@%s ", value_type_string);
2376
0
              g_string_append (string, "[]");
2377
0
              break;
2378
0
            }
2379
2380
0
          g_string_append_c (string, '[');
2381
0
          for (i = 0; i < n; i++)
2382
0
            {
2383
0
              GVariant *element;
2384
2385
0
              g_string_append (string, comma);
2386
0
              comma = ", ";
2387
2388
0
              element = g_variant_get_child_value (value, i);
2389
2390
0
              g_variant_print_string (element, string, type_annotate);
2391
0
              g_variant_unref (element);
2392
0
              type_annotate = FALSE;
2393
0
            }
2394
0
          g_string_append_c (string, ']');
2395
0
        }
2396
2397
0
      break;
2398
2399
0
    case G_VARIANT_CLASS_TUPLE:
2400
0
      {
2401
0
        gsize n, i;
2402
2403
0
        n = g_variant_n_children (value);
2404
2405
0
        g_string_append_c (string, '(');
2406
0
        for (i = 0; i < n; i++)
2407
0
          {
2408
0
            GVariant *element;
2409
2410
0
            element = g_variant_get_child_value (value, i);
2411
0
            g_variant_print_string (element, string, type_annotate);
2412
0
            g_string_append (string, ", ");
2413
0
            g_variant_unref (element);
2414
0
          }
2415
2416
        /* for >1 item:  remove final ", "
2417
         * for 1 item:   remove final " ", but leave the ","
2418
         * for 0 items:  there is only "(", so remove nothing
2419
         */
2420
0
        g_string_truncate (string, string->len - (n > 0) - (n > 1));
2421
0
        g_string_append_c (string, ')');
2422
0
      }
2423
0
      break;
2424
2425
0
    case G_VARIANT_CLASS_DICT_ENTRY:
2426
0
      {
2427
0
        GVariant *element;
2428
2429
0
        g_string_append_c (string, '{');
2430
2431
0
        element = g_variant_get_child_value (value, 0);
2432
0
        g_variant_print_string (element, string, type_annotate);
2433
0
        g_variant_unref (element);
2434
2435
0
        g_string_append (string, ", ");
2436
2437
0
        element = g_variant_get_child_value (value, 1);
2438
0
        g_variant_print_string (element, string, type_annotate);
2439
0
        g_variant_unref (element);
2440
2441
0
        g_string_append_c (string, '}');
2442
0
      }
2443
0
      break;
2444
2445
0
    case G_VARIANT_CLASS_VARIANT:
2446
0
      {
2447
0
        GVariant *child = g_variant_get_variant (value);
2448
2449
        /* Always annotate types in nested variants, because they are
2450
         * (by nature) of variable type.
2451
         */
2452
0
        g_string_append_c (string, '<');
2453
0
        g_variant_print_string (child, string, TRUE);
2454
0
        g_string_append_c (string, '>');
2455
2456
0
        g_variant_unref (child);
2457
0
      }
2458
0
      break;
2459
2460
0
    case G_VARIANT_CLASS_BOOLEAN:
2461
0
      if (g_variant_get_boolean (value))
2462
0
        g_string_append (string, "true");
2463
0
      else
2464
0
        g_string_append (string, "false");
2465
0
      break;
2466
2467
0
    case G_VARIANT_CLASS_STRING:
2468
0
      {
2469
0
        const gchar *str = g_variant_get_string (value, NULL);
2470
0
        gunichar quote = strchr (str, '\'') ? '"' : '\'';
2471
2472
0
        g_string_append_c (string, quote);
2473
2474
0
        while (*str)
2475
0
          {
2476
0
            gunichar c = g_utf8_get_char (str);
2477
2478
0
            if (c == quote || c == '\\')
2479
0
              g_string_append_c (string, '\\');
2480
2481
0
            if (g_unichar_isprint (c))
2482
0
              g_string_append_unichar (string, c);
2483
2484
0
            else
2485
0
              {
2486
0
                g_string_append_c (string, '\\');
2487
0
                if (c < 0x10000)
2488
0
                  switch (c)
2489
0
                    {
2490
0
                    case '\a':
2491
0
                      g_string_append_c (string, 'a');
2492
0
                      break;
2493
2494
0
                    case '\b':
2495
0
                      g_string_append_c (string, 'b');
2496
0
                      break;
2497
2498
0
                    case '\f':
2499
0
                      g_string_append_c (string, 'f');
2500
0
                      break;
2501
2502
0
                    case '\n':
2503
0
                      g_string_append_c (string, 'n');
2504
0
                      break;
2505
2506
0
                    case '\r':
2507
0
                      g_string_append_c (string, 'r');
2508
0
                      break;
2509
2510
0
                    case '\t':
2511
0
                      g_string_append_c (string, 't');
2512
0
                      break;
2513
2514
0
                    case '\v':
2515
0
                      g_string_append_c (string, 'v');
2516
0
                      break;
2517
2518
0
                    default:
2519
0
                      g_string_append_printf (string, "u%04x", c);
2520
0
                      break;
2521
0
                    }
2522
0
                 else
2523
0
                   g_string_append_printf (string, "U%08x", c);
2524
0
              }
2525
2526
0
            str = g_utf8_next_char (str);
2527
0
          }
2528
2529
0
        g_string_append_c (string, quote);
2530
0
      }
2531
0
      break;
2532
2533
0
    case G_VARIANT_CLASS_BYTE:
2534
0
      if (type_annotate)
2535
0
        g_string_append (string, "byte ");
2536
0
      g_string_append_printf (string, "0x%02x",
2537
0
                              g_variant_get_byte (value));
2538
0
      break;
2539
2540
0
    case G_VARIANT_CLASS_INT16:
2541
0
      if (type_annotate)
2542
0
        g_string_append (string, "int16 ");
2543
0
      g_string_append_printf (string, "%"G_GINT16_FORMAT,
2544
0
                              g_variant_get_int16 (value));
2545
0
      break;
2546
2547
0
    case G_VARIANT_CLASS_UINT16:
2548
0
      if (type_annotate)
2549
0
        g_string_append (string, "uint16 ");
2550
0
      g_string_append_printf (string, "%"G_GUINT16_FORMAT,
2551
0
                              g_variant_get_uint16 (value));
2552
0
      break;
2553
2554
0
    case G_VARIANT_CLASS_INT32:
2555
      /* Never annotate this type because it is the default for numbers
2556
       * (and this is a *pretty* printer)
2557
       */
2558
0
      g_string_append_printf (string, "%"G_GINT32_FORMAT,
2559
0
                              g_variant_get_int32 (value));
2560
0
      break;
2561
2562
0
    case G_VARIANT_CLASS_HANDLE:
2563
0
      if (type_annotate)
2564
0
        g_string_append (string, "handle ");
2565
0
      g_string_append_printf (string, "%"G_GINT32_FORMAT,
2566
0
                              g_variant_get_handle (value));
2567
0
      break;
2568
2569
0
    case G_VARIANT_CLASS_UINT32:
2570
0
      if (type_annotate)
2571
0
        g_string_append (string, "uint32 ");
2572
0
      g_string_append_printf (string, "%"G_GUINT32_FORMAT,
2573
0
                              g_variant_get_uint32 (value));
2574
0
      break;
2575
2576
0
    case G_VARIANT_CLASS_INT64:
2577
0
      if (type_annotate)
2578
0
        g_string_append (string, "int64 ");
2579
0
      g_string_append_printf (string, "%"G_GINT64_FORMAT,
2580
0
                              g_variant_get_int64 (value));
2581
0
      break;
2582
2583
0
    case G_VARIANT_CLASS_UINT64:
2584
0
      if (type_annotate)
2585
0
        g_string_append (string, "uint64 ");
2586
0
      g_string_append_printf (string, "%"G_GUINT64_FORMAT,
2587
0
                              g_variant_get_uint64 (value));
2588
0
      break;
2589
2590
0
    case G_VARIANT_CLASS_DOUBLE:
2591
0
      {
2592
0
        gchar buffer[100];
2593
0
        gint i;
2594
2595
0
        g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
2596
2597
0
        for (i = 0; buffer[i]; i++)
2598
0
          if (buffer[i] == '.' || buffer[i] == 'e' ||
2599
0
              buffer[i] == 'n' || buffer[i] == 'N')
2600
0
            break;
2601
2602
        /* if there is no '.' or 'e' in the float then add one */
2603
0
        if (buffer[i] == '\0')
2604
0
          {
2605
0
            buffer[i++] = '.';
2606
0
            buffer[i++] = '0';
2607
0
            buffer[i++] = '\0';
2608
0
          }
2609
2610
0
        g_string_append (string, buffer);
2611
0
      }
2612
0
      break;
2613
2614
0
    case G_VARIANT_CLASS_OBJECT_PATH:
2615
0
      if (type_annotate)
2616
0
        g_string_append (string, "objectpath ");
2617
0
      g_string_append_printf (string, "\'%s\'",
2618
0
                              g_variant_get_string (value, NULL));
2619
0
      break;
2620
2621
0
    case G_VARIANT_CLASS_SIGNATURE:
2622
0
      if (type_annotate)
2623
0
        g_string_append (string, "signature ");
2624
0
      g_string_append_printf (string, "\'%s\'",
2625
0
                              g_variant_get_string (value, NULL));
2626
0
      break;
2627
2628
0
    default:
2629
0
      g_assert_not_reached ();
2630
0
  }
2631
2632
0
  return string;
2633
0
}
2634
2635
/**
2636
 * g_variant_print:
2637
 * @value: a #GVariant
2638
 * @type_annotate: %TRUE if type information should be included in
2639
 *                 the output
2640
 *
2641
 * Pretty-prints @value in the format understood by g_variant_parse().
2642
 *
2643
 * The format is described [here][gvariant-text].
2644
 *
2645
 * If @type_annotate is %TRUE, then type information is included in
2646
 * the output.
2647
 *
2648
 * Returns: (transfer full): a newly-allocated string holding the result.
2649
 *
2650
 * Since: 2.24
2651
 */
2652
gchar *
2653
g_variant_print (GVariant *value,
2654
                 gboolean  type_annotate)
2655
0
{
2656
0
  return g_string_free (g_variant_print_string (value, NULL, type_annotate),
2657
0
                        FALSE);
2658
0
}
2659
2660
/* Hash, Equal, Compare {{{1 */
2661
/**
2662
 * g_variant_hash:
2663
 * @value: (type GVariant): a basic #GVariant value as a #gconstpointer
2664
 *
2665
 * Generates a hash value for a #GVariant instance.
2666
 *
2667
 * The output of this function is guaranteed to be the same for a given
2668
 * value only per-process.  It may change between different processor
2669
 * architectures or even different versions of GLib.  Do not use this
2670
 * function as a basis for building protocols or file formats.
2671
 *
2672
 * The type of @value is #gconstpointer only to allow use of this
2673
 * function with #GHashTable.  @value must be a #GVariant.
2674
 *
2675
 * Returns: a hash value corresponding to @value
2676
 *
2677
 * Since: 2.24
2678
 **/
2679
guint
2680
g_variant_hash (gconstpointer value_)
2681
0
{
2682
0
  GVariant *value = (GVariant *) value_;
2683
2684
0
  switch (g_variant_classify (value))
2685
0
    {
2686
0
    case G_VARIANT_CLASS_STRING:
2687
0
    case G_VARIANT_CLASS_OBJECT_PATH:
2688
0
    case G_VARIANT_CLASS_SIGNATURE:
2689
0
      return g_str_hash (g_variant_get_string (value, NULL));
2690
2691
0
    case G_VARIANT_CLASS_BOOLEAN:
2692
      /* this is a very odd thing to hash... */
2693
0
      return g_variant_get_boolean (value);
2694
2695
0
    case G_VARIANT_CLASS_BYTE:
2696
0
      return g_variant_get_byte (value);
2697
2698
0
    case G_VARIANT_CLASS_INT16:
2699
0
    case G_VARIANT_CLASS_UINT16:
2700
0
      {
2701
0
        const guint16 *ptr;
2702
2703
0
        ptr = g_variant_get_data (value);
2704
2705
0
        if (ptr)
2706
0
          return *ptr;
2707
0
        else
2708
0
          return 0;
2709
0
      }
2710
2711
0
    case G_VARIANT_CLASS_INT32:
2712
0
    case G_VARIANT_CLASS_UINT32:
2713
0
    case G_VARIANT_CLASS_HANDLE:
2714
0
      {
2715
0
        const guint *ptr;
2716
2717
0
        ptr = g_variant_get_data (value);
2718
2719
0
        if (ptr)
2720
0
          return *ptr;
2721
0
        else
2722
0
          return 0;
2723
0
      }
2724
2725
0
    case G_VARIANT_CLASS_INT64:
2726
0
    case G_VARIANT_CLASS_UINT64:
2727
0
    case G_VARIANT_CLASS_DOUBLE:
2728
      /* need a separate case for these guys because otherwise
2729
       * performance could be quite bad on big endian systems
2730
       */
2731
0
      {
2732
0
        const guint *ptr;
2733
2734
0
        ptr = g_variant_get_data (value);
2735
2736
0
        if (ptr)
2737
0
          return ptr[0] + ptr[1];
2738
0
        else
2739
0
          return 0;
2740
0
      }
2741
2742
0
    default:
2743
0
      g_return_val_if_fail (!g_variant_is_container (value), 0);
2744
0
      g_assert_not_reached ();
2745
0
    }
2746
0
}
2747
2748
/**
2749
 * g_variant_equal:
2750
 * @one: (type GVariant): a #GVariant instance
2751
 * @two: (type GVariant): a #GVariant instance
2752
 *
2753
 * Checks if @one and @two have the same type and value.
2754
 *
2755
 * The types of @one and @two are #gconstpointer only to allow use of
2756
 * this function with #GHashTable.  They must each be a #GVariant.
2757
 *
2758
 * Returns: %TRUE if @one and @two are equal
2759
 *
2760
 * Since: 2.24
2761
 **/
2762
gboolean
2763
g_variant_equal (gconstpointer one,
2764
                 gconstpointer two)
2765
0
{
2766
0
  gboolean equal;
2767
2768
0
  g_return_val_if_fail (one != NULL && two != NULL, FALSE);
2769
2770
0
  if (g_variant_get_type_info ((GVariant *) one) !=
2771
0
      g_variant_get_type_info ((GVariant *) two))
2772
0
    return FALSE;
2773
2774
  /* if both values are trusted to be in their canonical serialized form
2775
   * then a simple memcmp() of their serialized data will answer the
2776
   * question.
2777
   *
2778
   * if not, then this might generate a false negative (since it is
2779
   * possible for two different byte sequences to represent the same
2780
   * value).  for now we solve this by pretty-printing both values and
2781
   * comparing the result.
2782
   */
2783
0
  if (g_variant_is_trusted ((GVariant *) one) &&
2784
0
      g_variant_is_trusted ((GVariant *) two))
2785
0
    {
2786
0
      gconstpointer data_one, data_two;
2787
0
      gsize size_one, size_two;
2788
2789
0
      size_one = g_variant_get_size ((GVariant *) one);
2790
0
      size_two = g_variant_get_size ((GVariant *) two);
2791
2792
0
      if (size_one != size_two)
2793
0
        return FALSE;
2794
2795
0
      data_one = g_variant_get_data ((GVariant *) one);
2796
0
      data_two = g_variant_get_data ((GVariant *) two);
2797
2798
0
      if (size_one)
2799
0
        equal = memcmp (data_one, data_two, size_one) == 0;
2800
0
      else
2801
0
        equal = TRUE;
2802
0
    }
2803
0
  else
2804
0
    {
2805
0
      gchar *strone, *strtwo;
2806
2807
0
      strone = g_variant_print ((GVariant *) one, FALSE);
2808
0
      strtwo = g_variant_print ((GVariant *) two, FALSE);
2809
0
      equal = strcmp (strone, strtwo) == 0;
2810
0
      g_free (strone);
2811
0
      g_free (strtwo);
2812
0
    }
2813
2814
0
  return equal;
2815
0
}
2816
2817
/**
2818
 * g_variant_compare:
2819
 * @one: (type GVariant): a basic-typed #GVariant instance
2820
 * @two: (type GVariant): a #GVariant instance of the same type
2821
 *
2822
 * Compares @one and @two.
2823
 *
2824
 * The types of @one and @two are #gconstpointer only to allow use of
2825
 * this function with #GTree, #GPtrArray, etc.  They must each be a
2826
 * #GVariant.
2827
 *
2828
 * Comparison is only defined for basic types (ie: booleans, numbers,
2829
 * strings).  For booleans, %FALSE is less than %TRUE.  Numbers are
2830
 * ordered in the usual way.  Strings are in ASCII lexographical order.
2831
 *
2832
 * It is a programmer error to attempt to compare container values or
2833
 * two values that have types that are not exactly equal.  For example,
2834
 * you cannot compare a 32-bit signed integer with a 32-bit unsigned
2835
 * integer.  Also note that this function is not particularly
2836
 * well-behaved when it comes to comparison of doubles; in particular,
2837
 * the handling of incomparable values (ie: NaN) is undefined.
2838
 *
2839
 * If you only require an equality comparison, g_variant_equal() is more
2840
 * general.
2841
 *
2842
 * Returns: negative value if a < b;
2843
 *          zero if a = b;
2844
 *          positive value if a > b.
2845
 *
2846
 * Since: 2.26
2847
 **/
2848
gint
2849
g_variant_compare (gconstpointer one,
2850
                   gconstpointer two)
2851
0
{
2852
0
  GVariant *a = (GVariant *) one;
2853
0
  GVariant *b = (GVariant *) two;
2854
2855
0
  g_return_val_if_fail (g_variant_classify (a) == g_variant_classify (b), 0);
2856
2857
0
  switch (g_variant_classify (a))
2858
0
    {
2859
0
    case G_VARIANT_CLASS_BOOLEAN:
2860
0
      return g_variant_get_boolean (a) -
2861
0
             g_variant_get_boolean (b);
2862
2863
0
    case G_VARIANT_CLASS_BYTE:
2864
0
      return ((gint) g_variant_get_byte (a)) -
2865
0
             ((gint) g_variant_get_byte (b));
2866
2867
0
    case G_VARIANT_CLASS_INT16:
2868
0
      return ((gint) g_variant_get_int16 (a)) -
2869
0
             ((gint) g_variant_get_int16 (b));
2870
2871
0
    case G_VARIANT_CLASS_UINT16:
2872
0
      return ((gint) g_variant_get_uint16 (a)) -
2873
0
             ((gint) g_variant_get_uint16 (b));
2874
2875
0
    case G_VARIANT_CLASS_INT32:
2876
0
      {
2877
0
        gint32 a_val = g_variant_get_int32 (a);
2878
0
        gint32 b_val = g_variant_get_int32 (b);
2879
2880
0
        return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2881
0
      }
2882
2883
0
    case G_VARIANT_CLASS_UINT32:
2884
0
      {
2885
0
        guint32 a_val = g_variant_get_uint32 (a);
2886
0
        guint32 b_val = g_variant_get_uint32 (b);
2887
2888
0
        return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2889
0
      }
2890
2891
0
    case G_VARIANT_CLASS_INT64:
2892
0
      {
2893
0
        gint64 a_val = g_variant_get_int64 (a);
2894
0
        gint64 b_val = g_variant_get_int64 (b);
2895
2896
0
        return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2897
0
      }
2898
2899
0
    case G_VARIANT_CLASS_UINT64:
2900
0
      {
2901
0
        guint64 a_val = g_variant_get_uint64 (a);
2902
0
        guint64 b_val = g_variant_get_uint64 (b);
2903
2904
0
        return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2905
0
      }
2906
2907
0
    case G_VARIANT_CLASS_DOUBLE:
2908
0
      {
2909
0
        gdouble a_val = g_variant_get_double (a);
2910
0
        gdouble b_val = g_variant_get_double (b);
2911
2912
0
        return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
2913
0
      }
2914
2915
0
    case G_VARIANT_CLASS_STRING:
2916
0
    case G_VARIANT_CLASS_OBJECT_PATH:
2917
0
    case G_VARIANT_CLASS_SIGNATURE:
2918
0
      return strcmp (g_variant_get_string (a, NULL),
2919
0
                     g_variant_get_string (b, NULL));
2920
2921
0
    default:
2922
0
      g_return_val_if_fail (!g_variant_is_container (a), 0);
2923
0
      g_assert_not_reached ();
2924
0
    }
2925
0
}
2926
2927
/* GVariantIter {{{1 */
2928
/**
2929
 * GVariantIter: (skip)
2930
 *
2931
 * #GVariantIter is an opaque data structure and can only be accessed
2932
 * using the following functions.
2933
 **/
2934
struct stack_iter
2935
{
2936
  GVariant *value;
2937
  gssize n, i;
2938
2939
  const gchar *loop_format;
2940
2941
  gsize padding[3];
2942
  gsize magic;
2943
};
2944
2945
G_STATIC_ASSERT (sizeof (struct stack_iter) <= sizeof (GVariantIter));
2946
2947
struct heap_iter
2948
{
2949
  struct stack_iter iter;
2950
2951
  GVariant *value_ref;
2952
  gsize magic;
2953
};
2954
2955
G_STATIC_ASSERT (sizeof (struct heap_iter) <= sizeof (GVariantIter));
2956
2957
0
#define GVSI(i)                 ((struct stack_iter *) (i))
2958
0
#define GVHI(i)                 ((struct heap_iter *) (i))
2959
0
#define GVSI_MAGIC              ((gsize) 3579507750u)
2960
0
#define GVHI_MAGIC              ((gsize) 1450270775u)
2961
#define is_valid_iter(i)        (i != NULL && \
2962
                                 GVSI(i)->magic == GVSI_MAGIC)
2963
#define is_valid_heap_iter(i)   (is_valid_iter(i) && \
2964
                                 GVHI(i)->magic == GVHI_MAGIC)
2965
2966
/**
2967
 * g_variant_iter_new:
2968
 * @value: a container #GVariant
2969
 *
2970
 * Creates a heap-allocated #GVariantIter for iterating over the items
2971
 * in @value.
2972
 *
2973
 * Use g_variant_iter_free() to free the return value when you no longer
2974
 * need it.
2975
 *
2976
 * A reference is taken to @value and will be released only when
2977
 * g_variant_iter_free() is called.
2978
 *
2979
 * Returns: (transfer full): a new heap-allocated #GVariantIter
2980
 *
2981
 * Since: 2.24
2982
 **/
2983
GVariantIter *
2984
g_variant_iter_new (GVariant *value)
2985
0
{
2986
0
  GVariantIter *iter;
2987
2988
0
  iter = (GVariantIter *) g_slice_new (struct heap_iter);
2989
0
  GVHI(iter)->value_ref = g_variant_ref (value);
2990
0
  GVHI(iter)->magic = GVHI_MAGIC;
2991
2992
0
  g_variant_iter_init (iter, value);
2993
2994
0
  return iter;
2995
0
}
2996
2997
/**
2998
 * g_variant_iter_init: (skip)
2999
 * @iter: a pointer to a #GVariantIter
3000
 * @value: a container #GVariant
3001
 *
3002
 * Initialises (without allocating) a #GVariantIter.  @iter may be
3003
 * completely uninitialised prior to this call; its old value is
3004
 * ignored.
3005
 *
3006
 * The iterator remains valid for as long as @value exists, and need not
3007
 * be freed in any way.
3008
 *
3009
 * Returns: the number of items in @value
3010
 *
3011
 * Since: 2.24
3012
 **/
3013
gsize
3014
g_variant_iter_init (GVariantIter *iter,
3015
                     GVariant     *value)
3016
0
{
3017
0
  GVSI(iter)->magic = GVSI_MAGIC;
3018
0
  GVSI(iter)->value = value;
3019
0
  GVSI(iter)->n = g_variant_n_children (value);
3020
0
  GVSI(iter)->i = -1;
3021
0
  GVSI(iter)->loop_format = NULL;
3022
3023
0
  return GVSI(iter)->n;
3024
0
}
3025
3026
/**
3027
 * g_variant_iter_copy:
3028
 * @iter: a #GVariantIter
3029
 *
3030
 * Creates a new heap-allocated #GVariantIter to iterate over the
3031
 * container that was being iterated over by @iter.  Iteration begins on
3032
 * the new iterator from the current position of the old iterator but
3033
 * the two copies are independent past that point.
3034
 *
3035
 * Use g_variant_iter_free() to free the return value when you no longer
3036
 * need it.
3037
 *
3038
 * A reference is taken to the container that @iter is iterating over
3039
 * and will be related only when g_variant_iter_free() is called.
3040
 *
3041
 * Returns: (transfer full): a new heap-allocated #GVariantIter
3042
 *
3043
 * Since: 2.24
3044
 **/
3045
GVariantIter *
3046
g_variant_iter_copy (GVariantIter *iter)
3047
0
{
3048
0
  GVariantIter *copy;
3049
3050
0
  g_return_val_if_fail (is_valid_iter (iter), 0);
3051
3052
0
  copy = g_variant_iter_new (GVSI(iter)->value);
3053
0
  GVSI(copy)->i = GVSI(iter)->i;
3054
3055
0
  return copy;
3056
0
}
3057
3058
/**
3059
 * g_variant_iter_n_children:
3060
 * @iter: a #GVariantIter
3061
 *
3062
 * Queries the number of child items in the container that we are
3063
 * iterating over.  This is the total number of items -- not the number
3064
 * of items remaining.
3065
 *
3066
 * This function might be useful for preallocation of arrays.
3067
 *
3068
 * Returns: the number of children in the container
3069
 *
3070
 * Since: 2.24
3071
 **/
3072
gsize
3073
g_variant_iter_n_children (GVariantIter *iter)
3074
0
{
3075
0
  g_return_val_if_fail (is_valid_iter (iter), 0);
3076
3077
0
  return GVSI(iter)->n;
3078
0
}
3079
3080
/**
3081
 * g_variant_iter_free:
3082
 * @iter: (transfer full): a heap-allocated #GVariantIter
3083
 *
3084
 * Frees a heap-allocated #GVariantIter.  Only call this function on
3085
 * iterators that were returned by g_variant_iter_new() or
3086
 * g_variant_iter_copy().
3087
 *
3088
 * Since: 2.24
3089
 **/
3090
void
3091
g_variant_iter_free (GVariantIter *iter)
3092
0
{
3093
0
  g_return_if_fail (is_valid_heap_iter (iter));
3094
3095
0
  g_variant_unref (GVHI(iter)->value_ref);
3096
0
  GVHI(iter)->magic = 0;
3097
3098
0
  g_slice_free (struct heap_iter, GVHI(iter));
3099
0
}
3100
3101
/**
3102
 * g_variant_iter_next_value:
3103
 * @iter: a #GVariantIter
3104
 *
3105
 * Gets the next item in the container.  If no more items remain then
3106
 * %NULL is returned.
3107
 *
3108
 * Use g_variant_unref() to drop your reference on the return value when
3109
 * you no longer need it.
3110
 *
3111
 * Here is an example for iterating with g_variant_iter_next_value():
3112
 * |[<!-- language="C" --> 
3113
 *   // recursively iterate a container
3114
 *   void
3115
 *   iterate_container_recursive (GVariant *container)
3116
 *   {
3117
 *     GVariantIter iter;
3118
 *     GVariant *child;
3119
 *
3120
 *     g_variant_iter_init (&iter, container);
3121
 *     while ((child = g_variant_iter_next_value (&iter)))
3122
 *       {
3123
 *         g_print ("type '%s'\n", g_variant_get_type_string (child));
3124
 *
3125
 *         if (g_variant_is_container (child))
3126
 *           iterate_container_recursive (child);
3127
 *
3128
 *         g_variant_unref (child);
3129
 *       }
3130
 *   }
3131
 * ]|
3132
 *
3133
 * Returns: (nullable) (transfer full): a #GVariant, or %NULL
3134
 *
3135
 * Since: 2.24
3136
 **/
3137
GVariant *
3138
g_variant_iter_next_value (GVariantIter *iter)
3139
0
{
3140
0
  g_return_val_if_fail (is_valid_iter (iter), FALSE);
3141
3142
0
  if G_UNLIKELY (GVSI(iter)->i >= GVSI(iter)->n)
3143
0
    {
3144
0
      g_critical ("g_variant_iter_next_value: must not be called again "
3145
0
                  "after NULL has already been returned.");
3146
0
      return NULL;
3147
0
    }
3148
3149
0
  GVSI(iter)->i++;
3150
3151
0
  if (GVSI(iter)->i < GVSI(iter)->n)
3152
0
    return g_variant_get_child_value (GVSI(iter)->value, GVSI(iter)->i);
3153
3154
0
  return NULL;
3155
0
}
3156
3157
/* GVariantBuilder {{{1 */
3158
/**
3159
 * GVariantBuilder:
3160
 *
3161
 * A utility type for constructing container-type #GVariant instances.
3162
 *
3163
 * This is an opaque structure and may only be accessed using the
3164
 * following functions.
3165
 *
3166
 * #GVariantBuilder is not threadsafe in any way.  Do not attempt to
3167
 * access it from more than one thread.
3168
 **/
3169
3170
struct stack_builder
3171
{
3172
  GVariantBuilder *parent;
3173
  GVariantType *type;
3174
3175
  /* type constraint explicitly specified by 'type'.
3176
   * for tuple types, this moves along as we add more items.
3177
   */
3178
  const GVariantType *expected_type;
3179
3180
  /* type constraint implied by previous array item.
3181
   */
3182
  const GVariantType *prev_item_type;
3183
3184
  /* constraints on the number of children.  max = -1 for unlimited. */
3185
  gsize min_items;
3186
  gsize max_items;
3187
3188
  /* dynamically-growing pointer array */
3189
  GVariant **children;
3190
  gsize allocated_children;
3191
  gsize offset;
3192
3193
  /* set to '1' if all items in the container will have the same type
3194
   * (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
3195
   */
3196
  guint uniform_item_types : 1;
3197
3198
  /* set to '1' initially and changed to '0' if an untrusted value is
3199
   * added
3200
   */
3201
  guint trusted : 1;
3202
3203
  gsize magic;
3204
};
3205
3206
G_STATIC_ASSERT (sizeof (struct stack_builder) <= sizeof (GVariantBuilder));
3207
3208
struct heap_builder
3209
{
3210
  GVariantBuilder builder;
3211
  gsize magic;
3212
3213
  gint ref_count;
3214
};
3215
3216
0
#define GVSB(b)                  ((struct stack_builder *) (b))
3217
0
#define GVHB(b)                  ((struct heap_builder *) (b))
3218
0
#define GVSB_MAGIC               ((gsize) 1033660112u)
3219
0
#define GVSB_MAGIC_PARTIAL       ((gsize) 2942751021u)
3220
0
#define GVHB_MAGIC               ((gsize) 3087242682u)
3221
0
#define is_valid_builder(b)      (GVSB(b)->magic == GVSB_MAGIC)
3222
#define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
3223
3224
/* Just to make sure that by adding a union to GVariantBuilder, we
3225
 * didn't accidentally change ABI. */
3226
G_STATIC_ASSERT (sizeof (GVariantBuilder) == sizeof (guintptr[16]));
3227
3228
static gboolean
3229
ensure_valid_builder (GVariantBuilder *builder)
3230
0
{
3231
0
  if (builder == NULL)
3232
0
    return FALSE;
3233
0
  else if (is_valid_builder (builder))
3234
0
    return TRUE;
3235
0
  if (builder->u.s.partial_magic == GVSB_MAGIC_PARTIAL)
3236
0
    {
3237
0
      static GVariantBuilder cleared_builder;
3238
3239
      /* Make sure that only first two fields were set and the rest is
3240
       * zeroed to avoid messing up the builder that had parent
3241
       * address equal to GVSB_MAGIC_PARTIAL. */
3242
0
      if (memcmp (cleared_builder.u.s.y, builder->u.s.y, sizeof cleared_builder.u.s.y))
3243
0
        return FALSE;
3244
3245
0
      g_variant_builder_init (builder, builder->u.s.type);
3246
0
    }
3247
0
  return is_valid_builder (builder);
3248
0
}
3249
3250
/* return_if_invalid_builder (b) is like
3251
 * g_return_if_fail (ensure_valid_builder (b)), except that
3252
 * the side effects of ensure_valid_builder are evaluated
3253
 * regardless of whether G_DISABLE_CHECKS is defined or not. */
3254
0
#define return_if_invalid_builder(b) G_STMT_START {                \
3255
0
  gboolean valid_builder G_GNUC_UNUSED = ensure_valid_builder (b); \
3256
0
  g_return_if_fail (valid_builder);                                \
3257
0
} G_STMT_END
3258
3259
/* return_val_if_invalid_builder (b, val) is like
3260
 * g_return_val_if_fail (ensure_valid_builder (b), val), except that
3261
 * the side effects of ensure_valid_builder are evaluated
3262
 * regardless of whether G_DISABLE_CHECKS is defined or not. */
3263
0
#define return_val_if_invalid_builder(b, val) G_STMT_START {       \
3264
0
  gboolean valid_builder G_GNUC_UNUSED = ensure_valid_builder (b); \
3265
0
  g_return_val_if_fail (valid_builder, val);                       \
3266
0
} G_STMT_END
3267
3268
/**
3269
 * g_variant_builder_new:
3270
 * @type: a container type
3271
 *
3272
 * Allocates and initialises a new #GVariantBuilder.
3273
 *
3274
 * You should call g_variant_builder_unref() on the return value when it
3275
 * is no longer needed.  The memory will not be automatically freed by
3276
 * any other call.
3277
 *
3278
 * In most cases it is easier to place a #GVariantBuilder directly on
3279
 * the stack of the calling function and initialise it with
3280
 * g_variant_builder_init().
3281
 *
3282
 * Returns: (transfer full): a #GVariantBuilder
3283
 *
3284
 * Since: 2.24
3285
 **/
3286
GVariantBuilder *
3287
g_variant_builder_new (const GVariantType *type)
3288
0
{
3289
0
  GVariantBuilder *builder;
3290
3291
0
  builder = (GVariantBuilder *) g_slice_new (struct heap_builder);
3292
0
  g_variant_builder_init (builder, type);
3293
0
  GVHB(builder)->magic = GVHB_MAGIC;
3294
0
  GVHB(builder)->ref_count = 1;
3295
3296
0
  return builder;
3297
0
}
3298
3299
/**
3300
 * g_variant_builder_unref:
3301
 * @builder: (transfer full): a #GVariantBuilder allocated by g_variant_builder_new()
3302
 *
3303
 * Decreases the reference count on @builder.
3304
 *
3305
 * In the event that there are no more references, releases all memory
3306
 * associated with the #GVariantBuilder.
3307
 *
3308
 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3309
 * things will happen.
3310
 *
3311
 * Since: 2.24
3312
 **/
3313
void
3314
g_variant_builder_unref (GVariantBuilder *builder)
3315
0
{
3316
0
  g_return_if_fail (is_valid_heap_builder (builder));
3317
3318
0
  if (--GVHB(builder)->ref_count)
3319
0
    return;
3320
3321
0
  g_variant_builder_clear (builder);
3322
0
  GVHB(builder)->magic = 0;
3323
3324
0
  g_slice_free (struct heap_builder, GVHB(builder));
3325
0
}
3326
3327
/**
3328
 * g_variant_builder_ref:
3329
 * @builder: a #GVariantBuilder allocated by g_variant_builder_new()
3330
 *
3331
 * Increases the reference count on @builder.
3332
 *
3333
 * Don't call this on stack-allocated #GVariantBuilder instances or bad
3334
 * things will happen.
3335
 *
3336
 * Returns: (transfer full): a new reference to @builder
3337
 *
3338
 * Since: 2.24
3339
 **/
3340
GVariantBuilder *
3341
g_variant_builder_ref (GVariantBuilder *builder)
3342
0
{
3343
0
  g_return_val_if_fail (is_valid_heap_builder (builder), NULL);
3344
3345
0
  GVHB(builder)->ref_count++;
3346
3347
0
  return builder;
3348
0
}
3349
3350
/**
3351
 * g_variant_builder_clear: (skip)
3352
 * @builder: a #GVariantBuilder
3353
 *
3354
 * Releases all memory associated with a #GVariantBuilder without
3355
 * freeing the #GVariantBuilder structure itself.
3356
 *
3357
 * It typically only makes sense to do this on a stack-allocated
3358
 * #GVariantBuilder if you want to abort building the value part-way
3359
 * through.  This function need not be called if you call
3360
 * g_variant_builder_end() and it also doesn't need to be called on
3361
 * builders allocated with g_variant_builder_new() (see
3362
 * g_variant_builder_unref() for that).
3363
 *
3364
 * This function leaves the #GVariantBuilder structure set to all-zeros.
3365
 * It is valid to call this function on either an initialised
3366
 * #GVariantBuilder or one that is set to all-zeros but it is not valid
3367
 * to call this function on uninitialised memory.
3368
 *
3369
 * Since: 2.24
3370
 **/
3371
void
3372
g_variant_builder_clear (GVariantBuilder *builder)
3373
0
{
3374
0
  gsize i;
3375
3376
0
  if (GVSB(builder)->magic == 0)
3377
    /* all-zeros or partial case */
3378
0
    return;
3379
3380
0
  return_if_invalid_builder (builder);
3381
3382
0
  g_variant_type_free (GVSB(builder)->type);
3383
3384
0
  for (i = 0; i < GVSB(builder)->offset; i++)
3385
0
    g_variant_unref (GVSB(builder)->children[i]);
3386
3387
0
  g_free (GVSB(builder)->children);
3388
3389
0
  if (GVSB(builder)->parent)
3390
0
    {
3391
0
      g_variant_builder_clear (GVSB(builder)->parent);
3392
0
      g_slice_free (GVariantBuilder, GVSB(builder)->parent);
3393
0
    }
3394
3395
0
  memset (builder, 0, sizeof (GVariantBuilder));
3396
0
}
3397
3398
/**
3399
 * g_variant_builder_init: (skip)
3400
 * @builder: a #GVariantBuilder
3401
 * @type: a container type
3402
 *
3403
 * Initialises a #GVariantBuilder structure.
3404
 *
3405
 * @type must be non-%NULL.  It specifies the type of container to
3406
 * construct.  It can be an indefinite type such as
3407
 * %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
3408
 * Maybe, array, tuple, dictionary entry and variant-typed values may be
3409
 * constructed.
3410
 *
3411
 * After the builder is initialised, values are added using
3412
 * g_variant_builder_add_value() or g_variant_builder_add().
3413
 *
3414
 * After all the child values are added, g_variant_builder_end() frees
3415
 * the memory associated with the builder and returns the #GVariant that
3416
 * was created.
3417
 *
3418
 * This function completely ignores the previous contents of @builder.
3419
 * On one hand this means that it is valid to pass in completely
3420
 * uninitialised memory.  On the other hand, this means that if you are
3421
 * initialising over top of an existing #GVariantBuilder you need to
3422
 * first call g_variant_builder_clear() in order to avoid leaking
3423
 * memory.
3424
 *
3425
 * You must not call g_variant_builder_ref() or
3426
 * g_variant_builder_unref() on a #GVariantBuilder that was initialised
3427
 * with this function.  If you ever pass a reference to a
3428
 * #GVariantBuilder outside of the control of your own code then you
3429
 * should assume that the person receiving that reference may try to use
3430
 * reference counting; you should use g_variant_builder_new() instead of
3431
 * this function.
3432
 *
3433
 * Since: 2.24
3434
 **/
3435
void
3436
g_variant_builder_init (GVariantBuilder    *builder,
3437
                        const GVariantType *type)
3438
0
{
3439
0
  g_return_if_fail (type != NULL);
3440
0
  g_return_if_fail (g_variant_type_is_container (type));
3441
3442
0
  memset (builder, 0, sizeof (GVariantBuilder));
3443
3444
0
  GVSB(builder)->type = g_variant_type_copy (type);
3445
0
  GVSB(builder)->magic = GVSB_MAGIC;
3446
0
  GVSB(builder)->trusted = TRUE;
3447
3448
0
  switch (*(const gchar *) type)
3449
0
    {
3450
0
    case G_VARIANT_CLASS_VARIANT:
3451
0
      GVSB(builder)->uniform_item_types = TRUE;
3452
0
      GVSB(builder)->allocated_children = 1;
3453
0
      GVSB(builder)->expected_type = NULL;
3454
0
      GVSB(builder)->min_items = 1;
3455
0
      GVSB(builder)->max_items = 1;
3456
0
      break;
3457
3458
0
    case G_VARIANT_CLASS_ARRAY:
3459
0
      GVSB(builder)->uniform_item_types = TRUE;
3460
0
      GVSB(builder)->allocated_children = 8;
3461
0
      GVSB(builder)->expected_type =
3462
0
        g_variant_type_element (GVSB(builder)->type);
3463
0
      GVSB(builder)->min_items = 0;
3464
0
      GVSB(builder)->max_items = -1;
3465
0
      break;
3466
3467
0
    case G_VARIANT_CLASS_MAYBE:
3468
0
      GVSB(builder)->uniform_item_types = TRUE;
3469
0
      GVSB(builder)->allocated_children = 1;
3470
0
      GVSB(builder)->expected_type =
3471
0
        g_variant_type_element (GVSB(builder)->type);
3472
0
      GVSB(builder)->min_items = 0;
3473
0
      GVSB(builder)->max_items = 1;
3474
0
      break;
3475
3476
0
    case G_VARIANT_CLASS_DICT_ENTRY:
3477
0
      GVSB(builder)->uniform_item_types = FALSE;
3478
0
      GVSB(builder)->allocated_children = 2;
3479
0
      GVSB(builder)->expected_type =
3480
0
        g_variant_type_key (GVSB(builder)->type);
3481
0
      GVSB(builder)->min_items = 2;
3482
0
      GVSB(builder)->max_items = 2;
3483
0
      break;
3484
3485
0
    case 'r': /* G_VARIANT_TYPE_TUPLE was given */
3486
0
      GVSB(builder)->uniform_item_types = FALSE;
3487
0
      GVSB(builder)->allocated_children = 8;
3488
0
      GVSB(builder)->expected_type = NULL;
3489
0
      GVSB(builder)->min_items = 0;
3490
0
      GVSB(builder)->max_items = -1;
3491
0
      break;
3492
3493
0
    case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
3494
0
      GVSB(builder)->allocated_children = g_variant_type_n_items (type);
3495
0
      GVSB(builder)->expected_type =
3496
0
        g_variant_type_first (GVSB(builder)->type);
3497
0
      GVSB(builder)->min_items = GVSB(builder)->allocated_children;
3498
0
      GVSB(builder)->max_items = GVSB(builder)->allocated_children;
3499
0
      GVSB(builder)->uniform_item_types = FALSE;
3500
0
      break;
3501
3502
0
    default:
3503
0
      g_assert_not_reached ();
3504
0
   }
3505
3506
0
#ifdef G_ANALYZER_ANALYZING
3507
  /* Static analysers can’t couple the code in g_variant_builder_init() to the
3508
   * code in g_variant_builder_end() by GVariantType, so end up assuming that
3509
   * @offset and @children mismatch and that uninitialised memory is accessed
3510
   * from @children. At runtime, this is caught by the preconditions at the top
3511
   * of g_variant_builder_end(). Help the analyser by zero-initialising the
3512
   * memory to avoid a false positive. */
3513
0
  GVSB(builder)->children = g_new0 (GVariant *,
3514
0
                                    GVSB(builder)->allocated_children);
3515
#else
3516
  GVSB(builder)->children = g_new (GVariant *,
3517
                                   GVSB(builder)->allocated_children);
3518
#endif
3519
0
}
3520
3521
static void
3522
g_variant_builder_make_room (struct stack_builder *builder)
3523
0
{
3524
0
  if (builder->offset == builder->allocated_children)
3525
0
    {
3526
0
      builder->allocated_children *= 2;
3527
0
      builder->children = g_renew (GVariant *, builder->children,
3528
0
                                   builder->allocated_children);
3529
0
    }
3530
0
}
3531
3532
/**
3533
 * g_variant_builder_add_value:
3534
 * @builder: a #GVariantBuilder
3535
 * @value: a #GVariant
3536
 *
3537
 * Adds @value to @builder.
3538
 *
3539
 * It is an error to call this function in any way that would create an
3540
 * inconsistent value to be constructed.  Some examples of this are
3541
 * putting different types of items into an array, putting the wrong
3542
 * types or number of items in a tuple, putting more than one value into
3543
 * a variant, etc.
3544
 *
3545
 * If @value is a floating reference (see g_variant_ref_sink()),
3546
 * the @builder instance takes ownership of @value.
3547
 *
3548
 * Since: 2.24
3549
 **/
3550
void
3551
g_variant_builder_add_value (GVariantBuilder *builder,
3552
                             GVariant        *value)
3553
0
{
3554
0
  return_if_invalid_builder (builder);
3555
0
  g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3556
0
  g_return_if_fail (!GVSB(builder)->expected_type ||
3557
0
                    g_variant_is_of_type (value,
3558
0
                                          GVSB(builder)->expected_type));
3559
0
  g_return_if_fail (!GVSB(builder)->prev_item_type ||
3560
0
                    g_variant_is_of_type (value,
3561
0
                                          GVSB(builder)->prev_item_type));
3562
3563
0
  GVSB(builder)->trusted &= g_variant_is_trusted (value);
3564
3565
0
  if (!GVSB(builder)->uniform_item_types)
3566
0
    {
3567
      /* advance our expected type pointers */
3568
0
      if (GVSB(builder)->expected_type)
3569
0
        GVSB(builder)->expected_type =
3570
0
          g_variant_type_next (GVSB(builder)->expected_type);
3571
3572
0
      if (GVSB(builder)->prev_item_type)
3573
0
        GVSB(builder)->prev_item_type =
3574
0
          g_variant_type_next (GVSB(builder)->prev_item_type);
3575
0
    }
3576
0
  else
3577
0
    GVSB(builder)->prev_item_type = g_variant_get_type (value);
3578
3579
0
  g_variant_builder_make_room (GVSB(builder));
3580
3581
0
  GVSB(builder)->children[GVSB(builder)->offset++] =
3582
0
    g_variant_ref_sink (value);
3583
0
}
3584
3585
/**
3586
 * g_variant_builder_open:
3587
 * @builder: a #GVariantBuilder
3588
 * @type: the #GVariantType of the container
3589
 *
3590
 * Opens a subcontainer inside the given @builder.  When done adding
3591
 * items to the subcontainer, g_variant_builder_close() must be called. @type
3592
 * is the type of the container: so to build a tuple of several values, @type
3593
 * must include the tuple itself.
3594
 *
3595
 * It is an error to call this function in any way that would cause an
3596
 * inconsistent value to be constructed (ie: adding too many values or
3597
 * a value of an incorrect type).
3598
 *
3599
 * Example of building a nested variant:
3600
 * |[<!-- language="C" -->
3601
 * GVariantBuilder builder;
3602
 * guint32 some_number = get_number ();
3603
 * g_autoptr (GHashTable) some_dict = get_dict ();
3604
 * GHashTableIter iter;
3605
 * const gchar *key;
3606
 * const GVariant *value;
3607
 * g_autoptr (GVariant) output = NULL;
3608
 *
3609
 * g_variant_builder_init (&builder, G_VARIANT_TYPE ("(ua{sv})"));
3610
 * g_variant_builder_add (&builder, "u", some_number);
3611
 * g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3612
 *
3613
 * g_hash_table_iter_init (&iter, some_dict);
3614
 * while (g_hash_table_iter_next (&iter, (gpointer *) &key, (gpointer *) &value))
3615
 *   {
3616
 *     g_variant_builder_open (&builder, G_VARIANT_TYPE ("{sv}"));
3617
 *     g_variant_builder_add (&builder, "s", key);
3618
 *     g_variant_builder_add (&builder, "v", value);
3619
 *     g_variant_builder_close (&builder);
3620
 *   }
3621
 *
3622
 * g_variant_builder_close (&builder);
3623
 *
3624
 * output = g_variant_builder_end (&builder);
3625
 * ]|
3626
 *
3627
 * Since: 2.24
3628
 **/
3629
void
3630
g_variant_builder_open (GVariantBuilder    *builder,
3631
                        const GVariantType *type)
3632
0
{
3633
0
  GVariantBuilder *parent;
3634
3635
0
  return_if_invalid_builder (builder);
3636
0
  g_return_if_fail (GVSB(builder)->offset < GVSB(builder)->max_items);
3637
0
  g_return_if_fail (!GVSB(builder)->expected_type ||
3638
0
                    g_variant_type_is_subtype_of (type,
3639
0
                                                  GVSB(builder)->expected_type));
3640
0
  g_return_if_fail (!GVSB(builder)->prev_item_type ||
3641
0
                    g_variant_type_is_subtype_of (GVSB(builder)->prev_item_type,
3642
0
                                                  type));
3643
3644
0
  parent = g_slice_dup (GVariantBuilder, builder);
3645
0
  g_variant_builder_init (builder, type);
3646
0
  GVSB(builder)->parent = parent;
3647
3648
  /* push the prev_item_type down into the subcontainer */
3649
0
  if (GVSB(parent)->prev_item_type)
3650
0
    {
3651
0
      if (!GVSB(builder)->uniform_item_types)
3652
        /* tuples and dict entries */
3653
0
        GVSB(builder)->prev_item_type =
3654
0
          g_variant_type_first (GVSB(parent)->prev_item_type);
3655
3656
0
      else if (!g_variant_type_is_variant (GVSB(builder)->type))
3657
        /* maybes and arrays */
3658
0
        GVSB(builder)->prev_item_type =
3659
0
          g_variant_type_element (GVSB(parent)->prev_item_type);
3660
0
    }
3661
0
}
3662
3663
/**
3664
 * g_variant_builder_close:
3665
 * @builder: a #GVariantBuilder
3666
 *
3667
 * Closes the subcontainer inside the given @builder that was opened by
3668
 * the most recent call to g_variant_builder_open().
3669
 *
3670
 * It is an error to call this function in any way that would create an
3671
 * inconsistent value to be constructed (ie: too few values added to the
3672
 * subcontainer).
3673
 *
3674
 * Since: 2.24
3675
 **/
3676
void
3677
g_variant_builder_close (GVariantBuilder *builder)
3678
0
{
3679
0
  GVariantBuilder *parent;
3680
3681
0
  return_if_invalid_builder (builder);
3682
0
  g_return_if_fail (GVSB(builder)->parent != NULL);
3683
3684
0
  parent = GVSB(builder)->parent;
3685
0
  GVSB(builder)->parent = NULL;
3686
3687
0
  g_variant_builder_add_value (parent, g_variant_builder_end (builder));
3688
0
  *builder = *parent;
3689
3690
0
  g_slice_free (GVariantBuilder, parent);
3691
0
}
3692
3693
/*< private >
3694
 * g_variant_make_maybe_type:
3695
 * @element: a #GVariant
3696
 *
3697
 * Return the type of a maybe containing @element.
3698
 */
3699
static GVariantType *
3700
g_variant_make_maybe_type (GVariant *element)
3701
0
{
3702
0
  return g_variant_type_new_maybe (g_variant_get_type (element));
3703
0
}
3704
3705
/*< private >
3706
 * g_variant_make_array_type:
3707
 * @element: a #GVariant
3708
 *
3709
 * Return the type of an array containing @element.
3710
 */
3711
static GVariantType *
3712
g_variant_make_array_type (GVariant *element)
3713
0
{
3714
0
  return g_variant_type_new_array (g_variant_get_type (element));
3715
0
}
3716
3717
/**
3718
 * g_variant_builder_end:
3719
 * @builder: a #GVariantBuilder
3720
 *
3721
 * Ends the builder process and returns the constructed value.
3722
 *
3723
 * It is not permissible to use @builder in any way after this call
3724
 * except for reference counting operations (in the case of a
3725
 * heap-allocated #GVariantBuilder) or by reinitialising it with
3726
 * g_variant_builder_init() (in the case of stack-allocated). This
3727
 * means that for the stack-allocated builders there is no need to
3728
 * call g_variant_builder_clear() after the call to
3729
 * g_variant_builder_end().
3730
 *
3731
 * It is an error to call this function in any way that would create an
3732
 * inconsistent value to be constructed (ie: insufficient number of
3733
 * items added to a container with a specific number of children
3734
 * required).  It is also an error to call this function if the builder
3735
 * was created with an indefinite array or maybe type and no children
3736
 * have been added; in this case it is impossible to infer the type of
3737
 * the empty array.
3738
 *
3739
 * Returns: (transfer none): a new, floating, #GVariant
3740
 *
3741
 * Since: 2.24
3742
 **/
3743
GVariant *
3744
g_variant_builder_end (GVariantBuilder *builder)
3745
0
{
3746
0
  GVariantType *my_type;
3747
0
  GVariant *value;
3748
3749
0
  return_val_if_invalid_builder (builder, NULL);
3750
0
  g_return_val_if_fail (GVSB(builder)->offset >= GVSB(builder)->min_items,
3751
0
                        NULL);
3752
0
  g_return_val_if_fail (!GVSB(builder)->uniform_item_types ||
3753
0
                        GVSB(builder)->prev_item_type != NULL ||
3754
0
                        g_variant_type_is_definite (GVSB(builder)->type),
3755
0
                        NULL);
3756
3757
0
  if (g_variant_type_is_definite (GVSB(builder)->type))
3758
0
    my_type = g_variant_type_copy (GVSB(builder)->type);
3759
3760
0
  else if (g_variant_type_is_maybe (GVSB(builder)->type))
3761
0
    my_type = g_variant_make_maybe_type (GVSB(builder)->children[0]);
3762
3763
0
  else if (g_variant_type_is_array (GVSB(builder)->type))
3764
0
    my_type = g_variant_make_array_type (GVSB(builder)->children[0]);
3765
3766
0
  else if (g_variant_type_is_tuple (GVSB(builder)->type))
3767
0
    my_type = g_variant_make_tuple_type (GVSB(builder)->children,
3768
0
                                         GVSB(builder)->offset);
3769
3770
0
  else if (g_variant_type_is_dict_entry (GVSB(builder)->type))
3771
0
    my_type = g_variant_make_dict_entry_type (GVSB(builder)->children[0],
3772
0
                                              GVSB(builder)->children[1]);
3773
0
  else
3774
0
    g_assert_not_reached ();
3775
3776
0
  value = g_variant_new_from_children (my_type,
3777
0
                                       g_renew (GVariant *,
3778
0
                                                GVSB(builder)->children,
3779
0
                                                GVSB(builder)->offset),
3780
0
                                       GVSB(builder)->offset,
3781
0
                                       GVSB(builder)->trusted);
3782
0
  GVSB(builder)->children = NULL;
3783
0
  GVSB(builder)->offset = 0;
3784
3785
0
  g_variant_builder_clear (builder);
3786
0
  g_variant_type_free (my_type);
3787
3788
0
  return value;
3789
0
}
3790
3791
/* GVariantDict {{{1 */
3792
3793
/**
3794
 * GVariantDict:
3795
 *
3796
 * #GVariantDict is a mutable interface to #GVariant dictionaries.
3797
 *
3798
 * It can be used for doing a sequence of dictionary lookups in an
3799
 * efficient way on an existing #GVariant dictionary or it can be used
3800
 * to construct new dictionaries with a hashtable-like interface.  It
3801
 * can also be used for taking existing dictionaries and modifying them
3802
 * in order to create new ones.
3803
 *
3804
 * #GVariantDict can only be used with %G_VARIANT_TYPE_VARDICT
3805
 * dictionaries.
3806
 *
3807
 * It is possible to use #GVariantDict allocated on the stack or on the
3808
 * heap.  When using a stack-allocated #GVariantDict, you begin with a
3809
 * call to g_variant_dict_init() and free the resources with a call to
3810
 * g_variant_dict_clear().
3811
 *
3812
 * Heap-allocated #GVariantDict follows normal refcounting rules: you
3813
 * allocate it with g_variant_dict_new() and use g_variant_dict_ref()
3814
 * and g_variant_dict_unref().
3815
 *
3816
 * g_variant_dict_end() is used to convert the #GVariantDict back into a
3817
 * dictionary-type #GVariant.  When used with stack-allocated instances,
3818
 * this also implicitly frees all associated memory, but for
3819
 * heap-allocated instances, you must still call g_variant_dict_unref()
3820
 * afterwards.
3821
 *
3822
 * You will typically want to use a heap-allocated #GVariantDict when
3823
 * you expose it as part of an API.  For most other uses, the
3824
 * stack-allocated form will be more convenient.
3825
 *
3826
 * Consider the following two examples that do the same thing in each
3827
 * style: take an existing dictionary and look up the "count" uint32
3828
 * key, adding 1 to it if it is found, or returning an error if the
3829
 * key is not found.  Each returns the new dictionary as a floating
3830
 * #GVariant.
3831
 *
3832
 * ## Using a stack-allocated GVariantDict
3833
 *
3834
 * |[<!-- language="C" -->
3835
 *   GVariant *
3836
 *   add_to_count (GVariant  *orig,
3837
 *                 GError   **error)
3838
 *   {
3839
 *     GVariantDict dict;
3840
 *     guint32 count;
3841
 *
3842
 *     g_variant_dict_init (&dict, orig);
3843
 *     if (!g_variant_dict_lookup (&dict, "count", "u", &count))
3844
 *       {
3845
 *         g_set_error (...);
3846
 *         g_variant_dict_clear (&dict);
3847
 *         return NULL;
3848
 *       }
3849
 *
3850
 *     g_variant_dict_insert (&dict, "count", "u", count + 1);
3851
 *
3852
 *     return g_variant_dict_end (&dict);
3853
 *   }
3854
 * ]|
3855
 *
3856
 * ## Using heap-allocated GVariantDict
3857
 *
3858
 * |[<!-- language="C" -->
3859
 *   GVariant *
3860
 *   add_to_count (GVariant  *orig,
3861
 *                 GError   **error)
3862
 *   {
3863
 *     GVariantDict *dict;
3864
 *     GVariant *result;
3865
 *     guint32 count;
3866
 *
3867
 *     dict = g_variant_dict_new (orig);
3868
 *
3869
 *     if (g_variant_dict_lookup (dict, "count", "u", &count))
3870
 *       {
3871
 *         g_variant_dict_insert (dict, "count", "u", count + 1);
3872
 *         result = g_variant_dict_end (dict);
3873
 *       }
3874
 *     else
3875
 *       {
3876
 *         g_set_error (...);
3877
 *         result = NULL;
3878
 *       }
3879
 *
3880
 *     g_variant_dict_unref (dict);
3881
 *
3882
 *     return result;
3883
 *   }
3884
 * ]|
3885
 *
3886
 * Since: 2.40
3887
 **/
3888
struct stack_dict
3889
{
3890
  GHashTable *values;
3891
  gsize magic;
3892
};
3893
3894
G_STATIC_ASSERT (sizeof (struct stack_dict) <= sizeof (GVariantDict));
3895
3896
struct heap_dict
3897
{
3898
  struct stack_dict dict;
3899
  gint ref_count;
3900
  gsize magic;
3901
};
3902
3903
0
#define GVSD(d)                 ((struct stack_dict *) (d))
3904
0
#define GVHD(d)                 ((struct heap_dict *) (d))
3905
0
#define GVSD_MAGIC              ((gsize) 2579507750u)
3906
0
#define GVSD_MAGIC_PARTIAL      ((gsize) 3488698669u)
3907
0
#define GVHD_MAGIC              ((gsize) 2450270775u)
3908
0
#define is_valid_dict(d)        (GVSD(d)->magic == GVSD_MAGIC)
3909
#define is_valid_heap_dict(d)   (GVHD(d)->magic == GVHD_MAGIC)
3910
3911
/* Just to make sure that by adding a union to GVariantDict, we didn't
3912
 * accidentally change ABI. */
3913
G_STATIC_ASSERT (sizeof (GVariantDict) == sizeof (guintptr[16]));
3914
3915
static gboolean
3916
ensure_valid_dict (GVariantDict *dict)
3917
0
{
3918
0
  if (dict == NULL)
3919
0
    return FALSE;
3920
0
  else if (is_valid_dict (dict))
3921
0
    return TRUE;
3922
0
  if (dict->u.s.partial_magic == GVSD_MAGIC_PARTIAL)
3923
0
    {
3924
0
      static GVariantDict cleared_dict;
3925
3926
      /* Make sure that only first two fields were set and the rest is
3927
       * zeroed to avoid messing up the builder that had parent
3928
       * address equal to GVSB_MAGIC_PARTIAL. */
3929
0
      if (memcmp (cleared_dict.u.s.y, dict->u.s.y, sizeof cleared_dict.u.s.y))
3930
0
        return FALSE;
3931
3932
0
      g_variant_dict_init (dict, dict->u.s.asv);
3933
0
    }
3934
0
  return is_valid_dict (dict);
3935
0
}
3936
3937
/* return_if_invalid_dict (d) is like
3938
 * g_return_if_fail (ensure_valid_dict (d)), except that
3939
 * the side effects of ensure_valid_dict are evaluated
3940
 * regardless of whether G_DISABLE_CHECKS is defined or not. */
3941
0
#define return_if_invalid_dict(d) G_STMT_START {                \
3942
0
  gboolean valid_dict G_GNUC_UNUSED = ensure_valid_dict (d);    \
3943
0
  g_return_if_fail (valid_dict);                                \
3944
0
} G_STMT_END
3945
3946
/* return_val_if_invalid_dict (d, val) is like
3947
 * g_return_val_if_fail (ensure_valid_dict (d), val), except that
3948
 * the side effects of ensure_valid_dict are evaluated
3949
 * regardless of whether G_DISABLE_CHECKS is defined or not. */
3950
0
#define return_val_if_invalid_dict(d, val) G_STMT_START {       \
3951
0
  gboolean valid_dict G_GNUC_UNUSED = ensure_valid_dict (d);    \
3952
0
  g_return_val_if_fail (valid_dict, val);                       \
3953
0
} G_STMT_END
3954
3955
/**
3956
 * g_variant_dict_new:
3957
 * @from_asv: (nullable): the #GVariant with which to initialise the
3958
 *   dictionary
3959
 *
3960
 * Allocates and initialises a new #GVariantDict.
3961
 *
3962
 * You should call g_variant_dict_unref() on the return value when it
3963
 * is no longer needed.  The memory will not be automatically freed by
3964
 * any other call.
3965
 *
3966
 * In some cases it may be easier to place a #GVariantDict directly on
3967
 * the stack of the calling function and initialise it with
3968
 * g_variant_dict_init().  This is particularly useful when you are
3969
 * using #GVariantDict to construct a #GVariant.
3970
 *
3971
 * Returns: (transfer full): a #GVariantDict
3972
 *
3973
 * Since: 2.40
3974
 **/
3975
GVariantDict *
3976
g_variant_dict_new (GVariant *from_asv)
3977
0
{
3978
0
  GVariantDict *dict;
3979
3980
0
  dict = g_slice_alloc (sizeof (struct heap_dict));
3981
0
  g_variant_dict_init (dict, from_asv);
3982
0
  GVHD(dict)->magic = GVHD_MAGIC;
3983
0
  GVHD(dict)->ref_count = 1;
3984
3985
0
  return dict;
3986
0
}
3987
3988
/**
3989
 * g_variant_dict_init: (skip)
3990
 * @dict: a #GVariantDict
3991
 * @from_asv: (nullable): the initial value for @dict
3992
 *
3993
 * Initialises a #GVariantDict structure.
3994
 *
3995
 * If @from_asv is given, it is used to initialise the dictionary.
3996
 *
3997
 * This function completely ignores the previous contents of @dict.  On
3998
 * one hand this means that it is valid to pass in completely
3999
 * uninitialised memory.  On the other hand, this means that if you are
4000
 * initialising over top of an existing #GVariantDict you need to first
4001
 * call g_variant_dict_clear() in order to avoid leaking memory.
4002
 *
4003
 * You must not call g_variant_dict_ref() or g_variant_dict_unref() on a
4004
 * #GVariantDict that was initialised with this function.  If you ever
4005
 * pass a reference to a #GVariantDict outside of the control of your
4006
 * own code then you should assume that the person receiving that
4007
 * reference may try to use reference counting; you should use
4008
 * g_variant_dict_new() instead of this function.
4009
 *
4010
 * Since: 2.40
4011
 **/
4012
void
4013
g_variant_dict_init (GVariantDict *dict,
4014
                     GVariant     *from_asv)
4015
0
{
4016
0
  GVariantIter iter;
4017
0
  gchar *key;
4018
0
  GVariant *value;
4019
4020
0
  GVSD(dict)->values = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_variant_unref);
4021
0
  GVSD(dict)->magic = GVSD_MAGIC;
4022
4023
0
  if (from_asv)
4024
0
    {
4025
0
      g_variant_iter_init (&iter, from_asv);
4026
0
      while (g_variant_iter_next (&iter, "{sv}", &key, &value))
4027
0
        g_hash_table_insert (GVSD(dict)->values, key, value);
4028
0
    }
4029
0
}
4030
4031
/**
4032
 * g_variant_dict_lookup:
4033
 * @dict: a #GVariantDict
4034
 * @key: the key to look up in the dictionary
4035
 * @format_string: a GVariant format string
4036
 * @...: the arguments to unpack the value into
4037
 *
4038
 * Looks up a value in a #GVariantDict.
4039
 *
4040
 * This function is a wrapper around g_variant_dict_lookup_value() and
4041
 * g_variant_get().  In the case that %NULL would have been returned,
4042
 * this function returns %FALSE and does not modify the values of the arguments
4043
 * passed in to @....  Otherwise, it unpacks the returned
4044
 * value and returns %TRUE.
4045
 *
4046
 * @format_string determines the C types that are used for unpacking the
4047
 * values and also determines if the values are copied or borrowed, see the
4048
 * section on [GVariant format strings][gvariant-format-strings-pointers].
4049
 *
4050
 * Returns: %TRUE if a value was unpacked
4051
 *
4052
 * Since: 2.40
4053
 **/
4054
gboolean
4055
g_variant_dict_lookup (GVariantDict *dict,
4056
                       const gchar  *key,
4057
                       const gchar  *format_string,
4058
                       ...)
4059
0
{
4060
0
  GVariant *value;
4061
0
  va_list ap;
4062
4063
0
  return_val_if_invalid_dict (dict, FALSE);
4064
0
  g_return_val_if_fail (key != NULL, FALSE);
4065
0
  g_return_val_if_fail (format_string != NULL, FALSE);
4066
4067
0
  value = g_hash_table_lookup (GVSD(dict)->values, key);
4068
4069
0
  if (value == NULL || !g_variant_check_format_string (value, format_string, FALSE))
4070
0
    return FALSE;
4071
4072
0
  va_start (ap, format_string);
4073
0
  g_variant_get_va (value, format_string, NULL, &ap);
4074
0
  va_end (ap);
4075
4076
0
  return TRUE;
4077
0
}
4078
4079
/**
4080
 * g_variant_dict_lookup_value:
4081
 * @dict: a #GVariantDict
4082
 * @key: the key to look up in the dictionary
4083
 * @expected_type: (nullable): a #GVariantType, or %NULL
4084
 *
4085
 * Looks up a value in a #GVariantDict.
4086
 *
4087
 * If @key is not found in @dictionary, %NULL is returned.
4088
 *
4089
 * The @expected_type string specifies what type of value is expected.
4090
 * If the value associated with @key has a different type then %NULL is
4091
 * returned.
4092
 *
4093
 * If the key is found and the value has the correct type, it is
4094
 * returned.  If @expected_type was specified then any non-%NULL return
4095
 * value will have this type.
4096
 *
4097
 * Returns: (transfer full) (nullable): the value of the dictionary key, or %NULL
4098
 *
4099
 * Since: 2.40
4100
 **/
4101
GVariant *
4102
g_variant_dict_lookup_value (GVariantDict       *dict,
4103
                             const gchar        *key,
4104
                             const GVariantType *expected_type)
4105
0
{
4106
0
  GVariant *result;
4107
4108
0
  return_val_if_invalid_dict (dict, NULL);
4109
0
  g_return_val_if_fail (key != NULL, NULL);
4110
4111
0
  result = g_hash_table_lookup (GVSD(dict)->values, key);
4112
4113
0
  if (result && (!expected_type || g_variant_is_of_type (result, expected_type)))
4114
0
    return g_variant_ref (result);
4115
4116
0
  return NULL;
4117
0
}
4118
4119
/**
4120
 * g_variant_dict_contains:
4121
 * @dict: a #GVariantDict
4122
 * @key: the key to look up in the dictionary
4123
 *
4124
 * Checks if @key exists in @dict.
4125
 *
4126
 * Returns: %TRUE if @key is in @dict
4127
 *
4128
 * Since: 2.40
4129
 **/
4130
gboolean
4131
g_variant_dict_contains (GVariantDict *dict,
4132
                         const gchar  *key)
4133
0
{
4134
0
  return_val_if_invalid_dict (dict, FALSE);
4135
0
  g_return_val_if_fail (key != NULL, FALSE);
4136
4137
0
  return g_hash_table_contains (GVSD(dict)->values, key);
4138
0
}
4139
4140
/**
4141
 * g_variant_dict_insert:
4142
 * @dict: a #GVariantDict
4143
 * @key: the key to insert a value for
4144
 * @format_string: a #GVariant varargs format string
4145
 * @...: arguments, as per @format_string
4146
 *
4147
 * Inserts a value into a #GVariantDict.
4148
 *
4149
 * This call is a convenience wrapper that is exactly equivalent to
4150
 * calling g_variant_new() followed by g_variant_dict_insert_value().
4151
 *
4152
 * Since: 2.40
4153
 **/
4154
void
4155
g_variant_dict_insert (GVariantDict *dict,
4156
                       const gchar  *key,
4157
                       const gchar  *format_string,
4158
                       ...)
4159
0
{
4160
0
  va_list ap;
4161
4162
0
  return_if_invalid_dict (dict);
4163
0
  g_return_if_fail (key != NULL);
4164
0
  g_return_if_fail (format_string != NULL);
4165
4166
0
  va_start (ap, format_string);
4167
0
  g_variant_dict_insert_value (dict, key, g_variant_new_va (format_string, NULL, &ap));
4168
0
  va_end (ap);
4169
0
}
4170
4171
/**
4172
 * g_variant_dict_insert_value:
4173
 * @dict: a #GVariantDict
4174
 * @key: the key to insert a value for
4175
 * @value: the value to insert
4176
 *
4177
 * Inserts (or replaces) a key in a #GVariantDict.
4178
 *
4179
 * @value is consumed if it is floating.
4180
 *
4181
 * Since: 2.40
4182
 **/
4183
void
4184
g_variant_dict_insert_value (GVariantDict *dict,
4185
                             const gchar  *key,
4186
                             GVariant     *value)
4187
0
{
4188
0
  return_if_invalid_dict (dict);
4189
0
  g_return_if_fail (key != NULL);
4190
0
  g_return_if_fail (value != NULL);
4191
4192
0
  g_hash_table_insert (GVSD(dict)->values, g_strdup (key), g_variant_ref_sink (value));
4193
0
}
4194
4195
/**
4196
 * g_variant_dict_remove:
4197
 * @dict: a #GVariantDict
4198
 * @key: the key to remove
4199
 *
4200
 * Removes a key and its associated value from a #GVariantDict.
4201
 *
4202
 * Returns: %TRUE if the key was found and removed
4203
 *
4204
 * Since: 2.40
4205
 **/
4206
gboolean
4207
g_variant_dict_remove (GVariantDict *dict,
4208
                       const gchar  *key)
4209
0
{
4210
0
  return_val_if_invalid_dict (dict, FALSE);
4211
0
  g_return_val_if_fail (key != NULL, FALSE);
4212
4213
0
  return g_hash_table_remove (GVSD(dict)->values, key);
4214
0
}
4215
4216
/**
4217
 * g_variant_dict_clear:
4218
 * @dict: a #GVariantDict
4219
 *
4220
 * Releases all memory associated with a #GVariantDict without freeing
4221
 * the #GVariantDict structure itself.
4222
 *
4223
 * It typically only makes sense to do this on a stack-allocated
4224
 * #GVariantDict if you want to abort building the value part-way
4225
 * through.  This function need not be called if you call
4226
 * g_variant_dict_end() and it also doesn't need to be called on dicts
4227
 * allocated with g_variant_dict_new (see g_variant_dict_unref() for
4228
 * that).
4229
 *
4230
 * It is valid to call this function on either an initialised
4231
 * #GVariantDict or one that was previously cleared by an earlier call
4232
 * to g_variant_dict_clear() but it is not valid to call this function
4233
 * on uninitialised memory.
4234
 *
4235
 * Since: 2.40
4236
 **/
4237
void
4238
g_variant_dict_clear (GVariantDict *dict)
4239
0
{
4240
0
  if (GVSD(dict)->magic == 0)
4241
    /* all-zeros case */
4242
0
    return;
4243
4244
0
  return_if_invalid_dict (dict);
4245
4246
0
  g_hash_table_unref (GVSD(dict)->values);
4247
0
  GVSD(dict)->values = NULL;
4248
4249
0
  GVSD(dict)->magic = 0;
4250
0
}
4251
4252
/**
4253
 * g_variant_dict_end:
4254
 * @dict: a #GVariantDict
4255
 *
4256
 * Returns the current value of @dict as a #GVariant of type
4257
 * %G_VARIANT_TYPE_VARDICT, clearing it in the process.
4258
 *
4259
 * It is not permissible to use @dict in any way after this call except
4260
 * for reference counting operations (in the case of a heap-allocated
4261
 * #GVariantDict) or by reinitialising it with g_variant_dict_init() (in
4262
 * the case of stack-allocated).
4263
 *
4264
 * Returns: (transfer none): a new, floating, #GVariant
4265
 *
4266
 * Since: 2.40
4267
 **/
4268
GVariant *
4269
g_variant_dict_end (GVariantDict *dict)
4270
0
{
4271
0
  GVariantBuilder builder;
4272
0
  GHashTableIter iter;
4273
0
  gpointer key, value;
4274
4275
0
  return_val_if_invalid_dict (dict, NULL);
4276
4277
0
  g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
4278
4279
0
  g_hash_table_iter_init (&iter, GVSD(dict)->values);
4280
0
  while (g_hash_table_iter_next (&iter, &key, &value))
4281
0
    g_variant_builder_add (&builder, "{sv}", (const gchar *) key, (GVariant *) value);
4282
4283
0
  g_variant_dict_clear (dict);
4284
4285
0
  return g_variant_builder_end (&builder);
4286
0
}
4287
4288
/**
4289
 * g_variant_dict_ref:
4290
 * @dict: a heap-allocated #GVariantDict
4291
 *
4292
 * Increases the reference count on @dict.
4293
 *
4294
 * Don't call this on stack-allocated #GVariantDict instances or bad
4295
 * things will happen.
4296
 *
4297
 * Returns: (transfer full): a new reference to @dict
4298
 *
4299
 * Since: 2.40
4300
 **/
4301
GVariantDict *
4302
g_variant_dict_ref (GVariantDict *dict)
4303
0
{
4304
0
  g_return_val_if_fail (is_valid_heap_dict (dict), NULL);
4305
4306
0
  GVHD(dict)->ref_count++;
4307
4308
0
  return dict;
4309
0
}
4310
4311
/**
4312
 * g_variant_dict_unref:
4313
 * @dict: (transfer full): a heap-allocated #GVariantDict
4314
 *
4315
 * Decreases the reference count on @dict.
4316
 *
4317
 * In the event that there are no more references, releases all memory
4318
 * associated with the #GVariantDict.
4319
 *
4320
 * Don't call this on stack-allocated #GVariantDict instances or bad
4321
 * things will happen.
4322
 *
4323
 * Since: 2.40
4324
 **/
4325
void
4326
g_variant_dict_unref (GVariantDict *dict)
4327
0
{
4328
0
  g_return_if_fail (is_valid_heap_dict (dict));
4329
4330
0
  if (--GVHD(dict)->ref_count == 0)
4331
0
    {
4332
0
      g_variant_dict_clear (dict);
4333
0
      g_slice_free (struct heap_dict, (struct heap_dict *) dict);
4334
0
    }
4335
0
}
4336
4337
4338
/* Format strings {{{1 */
4339
/*< private >
4340
 * g_variant_format_string_scan:
4341
 * @string: a string that may be prefixed with a format string
4342
 * @limit: (nullable) (default NULL): a pointer to the end of @string,
4343
 *         or %NULL
4344
 * @endptr: (nullable) (default NULL): location to store the end pointer,
4345
 *          or %NULL
4346
 *
4347
 * Checks the string pointed to by @string for starting with a properly
4348
 * formed #GVariant varargs format string.  If no valid format string is
4349
 * found then %FALSE is returned.
4350
 *
4351
 * If @string does start with a valid format string then %TRUE is
4352
 * returned.  If @endptr is non-%NULL then it is updated to point to the
4353
 * first character after the format string.
4354
 *
4355
 * If @limit is non-%NULL then @limit (and any character after it) will
4356
 * not be accessed and the effect is otherwise equivalent to if the
4357
 * character at @limit were nul.
4358
 *
4359
 * See the section on [GVariant format strings][gvariant-format-strings].
4360
 *
4361
 * Returns: %TRUE if there was a valid format string
4362
 *
4363
 * Since: 2.24
4364
 */
4365
gboolean
4366
g_variant_format_string_scan (const gchar  *string,
4367
                              const gchar  *limit,
4368
                              const gchar **endptr)
4369
0
{
4370
0
#define next_char() (string == limit ? '\0' : *(string++))
4371
0
#define peek_char() (string == limit ? '\0' : *string)
4372
0
  char c;
4373
4374
0
  switch (next_char())
4375
0
    {
4376
0
    case 'b': case 'y': case 'n': case 'q': case 'i': case 'u':
4377
0
    case 'x': case 't': case 'h': case 'd': case 's': case 'o':
4378
0
    case 'g': case 'v': case '*': case '?': case 'r':
4379
0
      break;
4380
4381
0
    case 'm':
4382
0
      return g_variant_format_string_scan (string, limit, endptr);
4383
4384
0
    case 'a':
4385
0
    case '@':
4386
0
      return g_variant_type_string_scan (string, limit, endptr);
4387
4388
0
    case '(':
4389
0
      while (peek_char() != ')')
4390
0
        if (!g_variant_format_string_scan (string, limit, &string))
4391
0
          return FALSE;
4392
4393
0
      next_char(); /* consume ')' */
4394
0
      break;
4395
4396
0
    case '{':
4397
0
      c = next_char();
4398
4399
0
      if (c == '&')
4400
0
        {
4401
0
          c = next_char ();
4402
4403
0
          if (c != 's' && c != 'o' && c != 'g')
4404
0
            return FALSE;
4405
0
        }
4406
0
      else
4407
0
        {
4408
0
          if (c == '@')
4409
0
            c = next_char ();
4410
4411
          /* ISO/IEC 9899:1999 (C99) §7.21.5.2:
4412
           *    The terminating null character is considered to be
4413
           *    part of the string.
4414
           */
4415
0
          if (c != '\0' && strchr ("bynqiuxthdsog?", c) == NULL)
4416
0
            return FALSE;
4417
0
        }
4418
4419
0
      if (!g_variant_format_string_scan (string, limit, &string))
4420
0
        return FALSE;
4421
4422
0
      if (next_char() != '}')
4423
0
        return FALSE;
4424
4425
0
      break;
4426
4427
0
    case '^':
4428
0
      if ((c = next_char()) == 'a')
4429
0
        {
4430
0
          if ((c = next_char()) == '&')
4431
0
            {
4432
0
              if ((c = next_char()) == 'a')
4433
0
                {
4434
0
                  if ((c = next_char()) == 'y')
4435
0
                    break;      /* '^a&ay' */
4436
0
                }
4437
4438
0
              else if (c == 's' || c == 'o')
4439
0
                break;          /* '^a&s', '^a&o' */
4440
0
            }
4441
4442
0
          else if (c == 'a')
4443
0
            {
4444
0
              if ((c = next_char()) == 'y')
4445
0
                break;          /* '^aay' */
4446
0
            }
4447
4448
0
          else if (c == 's' || c == 'o')
4449
0
            break;              /* '^as', '^ao' */
4450
4451
0
          else if (c == 'y')
4452
0
            break;              /* '^ay' */
4453
0
        }
4454
0
      else if (c == '&')
4455
0
        {
4456
0
          if ((c = next_char()) == 'a')
4457
0
            {
4458
0
              if ((c = next_char()) == 'y')
4459
0
                break;          /* '^&ay' */
4460
0
            }
4461
0
        }
4462
4463
0
      return FALSE;
4464
4465
0
    case '&':
4466
0
      c = next_char();
4467
4468
0
      if (c != 's' && c != 'o' && c != 'g')
4469
0
        return FALSE;
4470
4471
0
      break;
4472
4473
0
    default:
4474
0
      return FALSE;
4475
0
    }
4476
4477
0
  if (endptr != NULL)
4478
0
    *endptr = string;
4479
4480
0
#undef next_char
4481
0
#undef peek_char
4482
4483
0
  return TRUE;
4484
0
}
4485
4486
/**
4487
 * g_variant_check_format_string:
4488
 * @value: a #GVariant
4489
 * @format_string: a valid #GVariant format string
4490
 * @copy_only: %TRUE to ensure the format string makes deep copies
4491
 *
4492
 * Checks if calling g_variant_get() with @format_string on @value would
4493
 * be valid from a type-compatibility standpoint.  @format_string is
4494
 * assumed to be a valid format string (from a syntactic standpoint).
4495
 *
4496
 * If @copy_only is %TRUE then this function additionally checks that it
4497
 * would be safe to call g_variant_unref() on @value immediately after
4498
 * the call to g_variant_get() without invalidating the result.  This is
4499
 * only possible if deep copies are made (ie: there are no pointers to
4500
 * the data inside of the soon-to-be-freed #GVariant instance).  If this
4501
 * check fails then a g_critical() is printed and %FALSE is returned.
4502
 *
4503
 * This function is meant to be used by functions that wish to provide
4504
 * varargs accessors to #GVariant values of uncertain values (eg:
4505
 * g_variant_lookup() or g_menu_model_get_item_attribute()).
4506
 *
4507
 * Returns: %TRUE if @format_string is safe to use
4508
 *
4509
 * Since: 2.34
4510
 */
4511
gboolean
4512
g_variant_check_format_string (GVariant    *value,
4513
                               const gchar *format_string,
4514
                               gboolean     copy_only)
4515
0
{
4516
0
  const gchar *original_format = format_string;
4517
0
  const gchar *type_string;
4518
4519
  /* Interesting factoid: assuming a format string is valid, it can be
4520
   * converted to a type string by removing all '@' '&' and '^'
4521
   * characters.
4522
   *
4523
   * Instead of doing that, we can just skip those characters when
4524
   * comparing it to the type string of @value.
4525
   *
4526
   * For the copy-only case we can just drop the '&' from the list of
4527
   * characters to skip over.  A '&' will never appear in a type string
4528
   * so we know that it won't be possible to return %TRUE if it is in a
4529
   * format string.
4530
   */
4531
0
  type_string = g_variant_get_type_string (value);
4532
4533
0
  while (*type_string || *format_string)
4534
0
    {
4535
0
      gchar format = *format_string++;
4536
4537
0
      switch (format)
4538
0
        {
4539
0
        case '&':
4540
0
          if G_UNLIKELY (copy_only)
4541
0
            {
4542
              /* for the love of all that is good, please don't mark this string for translation... */
4543
0
              g_critical ("g_variant_check_format_string() is being called by a function with a GVariant varargs "
4544
0
                          "interface to validate the passed format string for type safety.  The passed format "
4545
0
                          "(%s) contains a '&' character which would result in a pointer being returned to the "
4546
0
                          "data inside of a GVariant instance that may no longer exist by the time the function "
4547
0
                          "returns.  Modify your code to use a format string without '&'.", original_format);
4548
0
              return FALSE;
4549
0
            }
4550
4551
0
          G_GNUC_FALLTHROUGH;
4552
0
        case '^':
4553
0
        case '@':
4554
          /* ignore these 2 (or 3) */
4555
0
          continue;
4556
4557
0
        case '?':
4558
          /* attempt to consume one of 'bynqiuxthdsog' */
4559
0
          {
4560
0
            char s = *type_string++;
4561
4562
0
            if (s == '\0' || strchr ("bynqiuxthdsog", s) == NULL)
4563
0
              return FALSE;
4564
0
          }
4565
0
          continue;
4566
4567
0
        case 'r':
4568
          /* ensure it's a tuple */
4569
0
          if (*type_string != '(')
4570
0
            return FALSE;
4571
4572
0
          G_GNUC_FALLTHROUGH;
4573
0
        case '*':
4574
          /* consume a full type string for the '*' or 'r' */
4575
0
          if (!g_variant_type_string_scan (type_string, NULL, &type_string))
4576
0
            return FALSE;
4577
4578
0
          continue;
4579
4580
0
        default:
4581
          /* attempt to consume exactly one character equal to the format */
4582
0
          if (format != *type_string++)
4583
0
            return FALSE;
4584
0
        }
4585
0
    }
4586
4587
0
  return TRUE;
4588
0
}
4589
4590
/*< private >
4591
 * g_variant_format_string_scan_type:
4592
 * @string: a string that may be prefixed with a format string
4593
 * @limit: (nullable) (default NULL): a pointer to the end of @string,
4594
 *         or %NULL
4595
 * @endptr: (nullable) (default NULL): location to store the end pointer,
4596
 *          or %NULL
4597
 *
4598
 * If @string starts with a valid format string then this function will
4599
 * return the type that the format string corresponds to.  Otherwise
4600
 * this function returns %NULL.
4601
 *
4602
 * Use g_variant_type_free() to free the return value when you no longer
4603
 * need it.
4604
 *
4605
 * This function is otherwise exactly like
4606
 * g_variant_format_string_scan().
4607
 *
4608
 * Returns: (nullable): a #GVariantType if there was a valid format string
4609
 *
4610
 * Since: 2.24
4611
 */
4612
GVariantType *
4613
g_variant_format_string_scan_type (const gchar  *string,
4614
                                   const gchar  *limit,
4615
                                   const gchar **endptr)
4616
0
{
4617
0
  const gchar *my_end;
4618
0
  gchar *dest;
4619
0
  gchar *new;
4620
4621
0
  if (endptr == NULL)
4622
0
    endptr = &my_end;
4623
4624
0
  if (!g_variant_format_string_scan (string, limit, endptr))
4625
0
    return NULL;
4626
4627
0
  dest = new = g_malloc (*endptr - string + 1);
4628
0
  while (string != *endptr)
4629
0
    {
4630
0
      if (*string != '@' && *string != '&' && *string != '^')
4631
0
        *dest++ = *string;
4632
0
      string++;
4633
0
    }
4634
0
  *dest = '\0';
4635
4636
0
  return (GVariantType *) G_VARIANT_TYPE (new);
4637
0
}
4638
4639
static gboolean
4640
valid_format_string (const gchar *format_string,
4641
                     gboolean     single,
4642
                     GVariant    *value)
4643
0
{
4644
0
  const gchar *endptr;
4645
0
  GVariantType *type;
4646
4647
0
  type = g_variant_format_string_scan_type (format_string, NULL, &endptr);
4648
4649
0
  if G_UNLIKELY (type == NULL || (single && *endptr != '\0'))
4650
0
    {
4651
0
      if (single)
4652
0
        g_critical ("'%s' is not a valid GVariant format string",
4653
0
                    format_string);
4654
0
      else
4655
0
        g_critical ("'%s' does not have a valid GVariant format "
4656
0
                    "string as a prefix", format_string);
4657
4658
0
      if (type != NULL)
4659
0
        g_variant_type_free (type);
4660
4661
0
      return FALSE;
4662
0
    }
4663
4664
0
  if G_UNLIKELY (value && !g_variant_is_of_type (value, type))
4665
0
    {
4666
0
      gchar *fragment;
4667
0
      gchar *typestr;
4668
4669
0
      fragment = g_strndup (format_string, endptr - format_string);
4670
0
      typestr = g_variant_type_dup_string (type);
4671
4672
0
      g_critical ("the GVariant format string '%s' has a type of "
4673
0
                  "'%s' but the given value has a type of '%s'",
4674
0
                  fragment, typestr, g_variant_get_type_string (value));
4675
4676
0
      g_variant_type_free (type);
4677
0
      g_free (fragment);
4678
0
      g_free (typestr);
4679
4680
0
      return FALSE;
4681
0
    }
4682
4683
0
  g_variant_type_free (type);
4684
4685
0
  return TRUE;
4686
0
}
4687
4688
/* Variable Arguments {{{1 */
4689
/* We consider 2 main classes of format strings:
4690
 *
4691
 *   - recursive format strings
4692
 *      these are ones that result in recursion and the collection of
4693
 *      possibly more than one argument.  Maybe types, tuples,
4694
 *      dictionary entries.
4695
 *
4696
 *   - leaf format string
4697
 *      these result in the collection of a single argument.
4698
 *
4699
 * Leaf format strings are further subdivided into two categories:
4700
 *
4701
 *   - single non-null pointer ("nnp")
4702
 *      these either collect or return a single non-null pointer.
4703
 *
4704
 *   - other
4705
 *      these collect or return something else (bool, number, etc).
4706
 *
4707
 * Based on the above, the varargs handling code is split into 4 main parts:
4708
 *
4709
 *   - nnp handling code
4710
 *   - leaf handling code (which may invoke nnp code)
4711
 *   - generic handling code (may be recursive, may invoke leaf code)
4712
 *   - user-facing API (which invokes the generic code)
4713
 *
4714
 * Each section implements some of the following functions:
4715
 *
4716
 *   - skip:
4717
 *      collect the arguments for the format string as if
4718
 *      g_variant_new() had been called, but do nothing with them.  used
4719
 *      for skipping over arguments when constructing a Nothing maybe
4720
 *      type.
4721
 *
4722
 *   - new:
4723
 *      create a GVariant *
4724
 *
4725
 *   - get:
4726
 *      unpack a GVariant *
4727
 *
4728
 *   - free (nnp only):
4729
 *      free a previously allocated item
4730
 */
4731
4732
static gboolean
4733
g_variant_format_string_is_leaf (const gchar *str)
4734
0
{
4735
0
  return str[0] != 'm' && str[0] != '(' && str[0] != '{';
4736
0
}
4737
4738
static gboolean
4739
g_variant_format_string_is_nnp (const gchar *str)
4740
0
{
4741
0
  return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
4742
0
         str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
4743
0
         str[0] == 'r' || str[0] == 'v' || str[0] == '&';
4744
0
}
4745
4746
/* Single non-null pointer ("nnp") {{{2 */
4747
static void
4748
g_variant_valist_free_nnp (const gchar *str,
4749
                           gpointer     ptr)
4750
0
{
4751
0
  switch (*str)
4752
0
    {
4753
0
    case 'a':
4754
0
      g_variant_iter_free (ptr);
4755
0
      break;
4756
4757
0
    case '^':
4758
0
      if (g_str_has_suffix (str, "y"))
4759
0
        {
4760
0
          if (str[2] != 'a') /* '^a&ay', '^ay' */
4761
0
            g_free (ptr);
4762
0
          else if (str[1] == 'a') /* '^aay' */
4763
0
            g_strfreev (ptr);
4764
0
          break; /* '^&ay' */
4765
0
        }
4766
0
      else if (str[2] != '&') /* '^as', '^ao' */
4767
0
        g_strfreev (ptr);
4768
0
      else                      /* '^a&s', '^a&o' */
4769
0
        g_free (ptr);
4770
0
      break;
4771
4772
0
    case 's':
4773
0
    case 'o':
4774
0
    case 'g':
4775
0
      g_free (ptr);
4776
0
      break;
4777
4778
0
    case '@':
4779
0
    case '*':
4780
0
    case '?':
4781
0
    case 'v':
4782
0
      g_variant_unref (ptr);
4783
0
      break;
4784
4785
0
    case '&':
4786
0
      break;
4787
4788
0
    default:
4789
0
      g_assert_not_reached ();
4790
0
    }
4791
0
}
4792
4793
static gchar
4794
g_variant_scan_convenience (const gchar **str,
4795
                            gboolean     *constant,
4796
                            guint        *arrays)
4797
0
{
4798
0
  *constant = FALSE;
4799
0
  *arrays = 0;
4800
4801
0
  for (;;)
4802
0
    {
4803
0
      char c = *(*str)++;
4804
4805
0
      if (c == '&')
4806
0
        *constant = TRUE;
4807
4808
0
      else if (c == 'a')
4809
0
        (*arrays)++;
4810
4811
0
      else
4812
0
        return c;
4813
0
    }
4814
0
}
4815
4816
static GVariant *
4817
g_variant_valist_new_nnp (const gchar **str,
4818
                          gpointer      ptr)
4819
0
{
4820
0
  if (**str == '&')
4821
0
    (*str)++;
4822
4823
0
  switch (*(*str)++)
4824
0
    {
4825
0
    case 'a':
4826
0
      if (ptr != NULL)
4827
0
        {
4828
0
          const GVariantType *type;
4829
0
          GVariant *value;
4830
4831
0
          value = g_variant_builder_end (ptr);
4832
0
          type = g_variant_get_type (value);
4833
4834
0
          if G_UNLIKELY (!g_variant_type_is_array (type))
4835
0
            g_error ("g_variant_new: expected array GVariantBuilder but "
4836
0
                     "the built value has type '%s'",
4837
0
                     g_variant_get_type_string (value));
4838
4839
0
          type = g_variant_type_element (type);
4840
4841
0
          if G_UNLIKELY (!g_variant_type_is_subtype_of (type, (GVariantType *) *str))
4842
0
            {
4843
0
              gchar *type_string = g_variant_type_dup_string ((GVariantType *) *str);
4844
0
              g_error ("g_variant_new: expected GVariantBuilder array element "
4845
0
                       "type '%s' but the built value has element type '%s'",
4846
0
                       type_string, g_variant_get_type_string (value) + 1);
4847
0
              g_free (type_string);
4848
0
            }
4849
4850
0
          g_variant_type_string_scan (*str, NULL, str);
4851
4852
0
          return value;
4853
0
        }
4854
0
      else
4855
4856
        /* special case: NULL pointer for empty array */
4857
0
        {
4858
0
          const GVariantType *type = (GVariantType *) *str;
4859
4860
0
          g_variant_type_string_scan (*str, NULL, str);
4861
4862
0
          if G_UNLIKELY (!g_variant_type_is_definite (type))
4863
0
            g_error ("g_variant_new: NULL pointer given with indefinite "
4864
0
                     "array type; unable to determine which type of empty "
4865
0
                     "array to construct.");
4866
4867
0
          return g_variant_new_array (type, NULL, 0);
4868
0
        }
4869
4870
0
    case 's':
4871
0
      {
4872
0
        GVariant *value;
4873
4874
0
        value = g_variant_new_string (ptr);
4875
4876
0
        if (value == NULL)
4877
0
          value = g_variant_new_string ("[Invalid UTF-8]");
4878
4879
0
        return value;
4880
0
      }
4881
4882
0
    case 'o':
4883
0
      return g_variant_new_object_path (ptr);
4884
4885
0
    case 'g':
4886
0
      return g_variant_new_signature (ptr);
4887
4888
0
    case '^':
4889
0
      {
4890
0
        gboolean constant;
4891
0
        guint arrays;
4892
0
        gchar type;
4893
4894
0
        type = g_variant_scan_convenience (str, &constant, &arrays);
4895
4896
0
        if (type == 's')
4897
0
          return g_variant_new_strv (ptr, -1);
4898
4899
0
        if (type == 'o')
4900
0
          return g_variant_new_objv (ptr, -1);
4901
4902
0
        if (arrays > 1)
4903
0
          return g_variant_new_bytestring_array (ptr, -1);
4904
4905
0
        return g_variant_new_bytestring (ptr);
4906
0
      }
4907
4908
0
    case '@':
4909
0
      if G_UNLIKELY (!g_variant_is_of_type (ptr, (GVariantType *) *str))
4910
0
        {
4911
0
          gchar *type_string = g_variant_type_dup_string ((GVariantType *) *str);
4912
0
          g_error ("g_variant_new: expected GVariant of type '%s' but "
4913
0
                   "received value has type '%s'",
4914
0
                   type_string, g_variant_get_type_string (ptr));
4915
0
          g_free (type_string);
4916
0
        }
4917
4918
0
      g_variant_type_string_scan (*str, NULL, str);
4919
4920
0
      return ptr;
4921
4922
0
    case '*':
4923
0
      return ptr;
4924
4925
0
    case '?':
4926
0
      if G_UNLIKELY (!g_variant_type_is_basic (g_variant_get_type (ptr)))
4927
0
        g_error ("g_variant_new: format string '?' expects basic-typed "
4928
0
                 "GVariant, but received value has type '%s'",
4929
0
                 g_variant_get_type_string (ptr));
4930
4931
0
      return ptr;
4932
4933
0
    case 'r':
4934
0
      if G_UNLIKELY (!g_variant_type_is_tuple (g_variant_get_type (ptr)))
4935
0
        g_error ("g_variant_new: format string 'r' expects tuple-typed "
4936
0
                 "GVariant, but received value has type '%s'",
4937
0
                 g_variant_get_type_string (ptr));
4938
4939
0
      return ptr;
4940
4941
0
    case 'v':
4942
0
      return g_variant_new_variant (ptr);
4943
4944
0
    default:
4945
0
      g_assert_not_reached ();
4946
0
    }
4947
0
}
4948
4949
static gpointer
4950
g_variant_valist_get_nnp (const gchar **str,
4951
                          GVariant     *value)
4952
0
{
4953
0
  switch (*(*str)++)
4954
0
    {
4955
0
    case 'a':
4956
0
      g_variant_type_string_scan (*str, NULL, str);
4957
0
      return g_variant_iter_new (value);
4958
4959
0
    case '&':
4960
0
      (*str)++;
4961
0
      return (gchar *) g_variant_get_string (value, NULL);
4962
4963
0
    case 's':
4964
0
    case 'o':
4965
0
    case 'g':
4966
0
      return g_variant_dup_string (value, NULL);
4967
4968
0
    case '^':
4969
0
      {
4970
0
        gboolean constant;
4971
0
        guint arrays;
4972
0
        gchar type;
4973
4974
0
        type = g_variant_scan_convenience (str, &constant, &arrays);
4975
4976
0
        if (type == 's')
4977
0
          {
4978
0
            if (constant)
4979
0
              return g_variant_get_strv (value, NULL);
4980
0
            else
4981
0
              return g_variant_dup_strv (value, NULL);
4982
0
          }
4983
4984
0
        else if (type == 'o')
4985
0
          {
4986
0
            if (constant)
4987
0
              return g_variant_get_objv (value, NULL);
4988
0
            else
4989
0
              return g_variant_dup_objv (value, NULL);
4990
0
          }
4991
4992
0
        else if (arrays > 1)
4993
0
          {
4994
0
            if (constant)
4995
0
              return g_variant_get_bytestring_array (value, NULL);
4996
0
            else
4997
0
              return g_variant_dup_bytestring_array (value, NULL);
4998
0
          }
4999
5000
0
        else
5001
0
          {
5002
0
            if (constant)
5003
0
              return (gchar *) g_variant_get_bytestring (value);
5004
0
            else
5005
0
              return g_variant_dup_bytestring (value, NULL);
5006
0
          }
5007
0
      }
5008
5009
0
    case '@':
5010
0
      g_variant_type_string_scan (*str, NULL, str);
5011
0
      G_GNUC_FALLTHROUGH;
5012
5013
0
    case '*':
5014
0
    case '?':
5015
0
    case 'r':
5016
0
      return g_variant_ref (value);
5017
5018
0
    case 'v':
5019
0
      return g_variant_get_variant (value);
5020
5021
0
    default:
5022
0
      g_assert_not_reached ();
5023
0
    }
5024
0
}
5025
5026
/* Leaves {{{2 */
5027
static void
5028
g_variant_valist_skip_leaf (const gchar **str,
5029
                            va_list      *app)
5030
0
{
5031
0
  if (g_variant_format_string_is_nnp (*str))
5032
0
    {
5033
0
      g_variant_format_string_scan (*str, NULL, str);
5034
0
      va_arg (*app, gpointer);
5035
0
      return;
5036
0
    }
5037
5038
0
  switch (*(*str)++)
5039
0
    {
5040
0
    case 'b':
5041
0
    case 'y':
5042
0
    case 'n':
5043
0
    case 'q':
5044
0
    case 'i':
5045
0
    case 'u':
5046
0
    case 'h':
5047
0
      va_arg (*app, int);
5048
0
      return;
5049
5050
0
    case 'x':
5051
0
    case 't':
5052
0
      va_arg (*app, guint64);
5053
0
      return;
5054
5055
0
    case 'd':
5056
0
      va_arg (*app, gdouble);
5057
0
      return;
5058
5059
0
    default:
5060
0
      g_assert_not_reached ();
5061
0
    }
5062
0
}
5063
5064
static GVariant *
5065
g_variant_valist_new_leaf (const gchar **str,
5066
                           va_list      *app)
5067
0
{
5068
0
  if (g_variant_format_string_is_nnp (*str))
5069
0
    return g_variant_valist_new_nnp (str, va_arg (*app, gpointer));
5070
5071
0
  switch (*(*str)++)
5072
0
    {
5073
0
    case 'b':
5074
0
      return g_variant_new_boolean (va_arg (*app, gboolean));
5075
5076
0
    case 'y':
5077
0
      return g_variant_new_byte (va_arg (*app, guint));
5078
5079
0
    case 'n':
5080
0
      return g_variant_new_int16 (va_arg (*app, gint));
5081
5082
0
    case 'q':
5083
0
      return g_variant_new_uint16 (va_arg (*app, guint));
5084
5085
0
    case 'i':
5086
0
      return g_variant_new_int32 (va_arg (*app, gint));
5087
5088
0
    case 'u':
5089
0
      return g_variant_new_uint32 (va_arg (*app, guint));
5090
5091
0
    case 'x':
5092
0
      return g_variant_new_int64 (va_arg (*app, gint64));
5093
5094
0
    case 't':
5095
0
      return g_variant_new_uint64 (va_arg (*app, guint64));
5096
5097
0
    case 'h':
5098
0
      return g_variant_new_handle (va_arg (*app, gint));
5099
5100
0
    case 'd':
5101
0
      return g_variant_new_double (va_arg (*app, gdouble));
5102
5103
0
    default:
5104
0
      g_assert_not_reached ();
5105
0
    }
5106
0
}
5107
5108
/* The code below assumes this */
5109
G_STATIC_ASSERT (sizeof (gboolean) == sizeof (guint32));
5110
G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
5111
5112
static void
5113
g_variant_valist_get_leaf (const gchar **str,
5114
                           GVariant     *value,
5115
                           gboolean      free,
5116
                           va_list      *app)
5117
0
{
5118
0
  gpointer ptr = va_arg (*app, gpointer);
5119
5120
0
  if (ptr == NULL)
5121
0
    {
5122
0
      g_variant_format_string_scan (*str, NULL, str);
5123
0
      return;
5124
0
    }
5125
5126
0
  if (g_variant_format_string_is_nnp (*str))
5127
0
    {
5128
0
      gpointer *nnp = (gpointer *) ptr;
5129
5130
0
      if (free && *nnp != NULL)
5131
0
        g_variant_valist_free_nnp (*str, *nnp);
5132
5133
0
      *nnp = NULL;
5134
5135
0
      if (value != NULL)
5136
0
        *nnp = g_variant_valist_get_nnp (str, value);
5137
0
      else
5138
0
        g_variant_format_string_scan (*str, NULL, str);
5139
5140
0
      return;
5141
0
    }
5142
5143
0
  if (value != NULL)
5144
0
    {
5145
0
      switch (*(*str)++)
5146
0
        {
5147
0
        case 'b':
5148
0
          *(gboolean *) ptr = g_variant_get_boolean (value);
5149
0
          return;
5150
5151
0
        case 'y':
5152
0
          *(guint8 *) ptr = g_variant_get_byte (value);
5153
0
          return;
5154
5155
0
        case 'n':
5156
0
          *(gint16 *) ptr = g_variant_get_int16 (value);
5157
0
          return;
5158
5159
0
        case 'q':
5160
0
          *(guint16 *) ptr = g_variant_get_uint16 (value);
5161
0
          return;
5162
5163
0
        case 'i':
5164
0
          *(gint32 *) ptr = g_variant_get_int32 (value);
5165
0
          return;
5166
5167
0
        case 'u':
5168
0
          *(guint32 *) ptr = g_variant_get_uint32 (value);
5169
0
          return;
5170
5171
0
        case 'x':
5172
0
          *(gint64 *) ptr = g_variant_get_int64 (value);
5173
0
          return;
5174
5175
0
        case 't':
5176
0
          *(guint64 *) ptr = g_variant_get_uint64 (value);
5177
0
          return;
5178
5179
0
        case 'h':
5180
0
          *(gint32 *) ptr = g_variant_get_handle (value);
5181
0
          return;
5182
5183
0
        case 'd':
5184
0
          *(gdouble *) ptr = g_variant_get_double (value);
5185
0
          return;
5186
0
        }
5187
0
    }
5188
0
  else
5189
0
    {
5190
0
      switch (*(*str)++)
5191
0
        {
5192
0
        case 'y':
5193
0
          *(guint8 *) ptr = 0;
5194
0
          return;
5195
5196
0
        case 'n':
5197
0
        case 'q':
5198
0
          *(guint16 *) ptr = 0;
5199
0
          return;
5200
5201
0
        case 'i':
5202
0
        case 'u':
5203
0
        case 'h':
5204
0
        case 'b':
5205
0
          *(guint32 *) ptr = 0;
5206
0
          return;
5207
5208
0
        case 'x':
5209
0
        case 't':
5210
0
        case 'd':
5211
0
          *(guint64 *) ptr = 0;
5212
0
          return;
5213
0
        }
5214
0
    }
5215
5216
0
  g_assert_not_reached ();
5217
0
}
5218
5219
/* Generic (recursive) {{{2 */
5220
static void
5221
g_variant_valist_skip (const gchar **str,
5222
                       va_list      *app)
5223
0
{
5224
0
  if (g_variant_format_string_is_leaf (*str))
5225
0
    g_variant_valist_skip_leaf (str, app);
5226
5227
0
  else if (**str == 'm') /* maybe */
5228
0
    {
5229
0
      (*str)++;
5230
5231
0
      if (!g_variant_format_string_is_nnp (*str))
5232
0
        va_arg (*app, gboolean);
5233
5234
0
      g_variant_valist_skip (str, app);
5235
0
    }
5236
0
  else /* tuple, dictionary entry */
5237
0
    {
5238
0
      g_assert (**str == '(' || **str == '{');
5239
0
      (*str)++;
5240
0
      while (**str != ')' && **str != '}')
5241
0
        g_variant_valist_skip (str, app);
5242
0
      (*str)++;
5243
0
    }
5244
0
}
5245
5246
static GVariant *
5247
g_variant_valist_new (const gchar **str,
5248
                      va_list      *app)
5249
0
{
5250
0
  if (g_variant_format_string_is_leaf (*str))
5251
0
    return g_variant_valist_new_leaf (str, app);
5252
5253
0
  if (**str == 'm') /* maybe */
5254
0
    {
5255
0
      GVariantType *type = NULL;
5256
0
      GVariant *value = NULL;
5257
5258
0
      (*str)++;
5259
5260
0
      if (g_variant_format_string_is_nnp (*str))
5261
0
        {
5262
0
          gpointer nnp = va_arg (*app, gpointer);
5263
5264
0
          if (nnp != NULL)
5265
0
            value = g_variant_valist_new_nnp (str, nnp);
5266
0
          else
5267
0
            type = g_variant_format_string_scan_type (*str, NULL, str);
5268
0
        }
5269
0
      else
5270
0
        {
5271
0
          gboolean just = va_arg (*app, gboolean);
5272
5273
0
          if (just)
5274
0
            value = g_variant_valist_new (str, app);
5275
0
          else
5276
0
            {
5277
0
              type = g_variant_format_string_scan_type (*str, NULL, NULL);
5278
0
              g_variant_valist_skip (str, app);
5279
0
            }
5280
0
        }
5281
5282
0
      value = g_variant_new_maybe (type, value);
5283
5284
0
      if (type != NULL)
5285
0
        g_variant_type_free (type);
5286
5287
0
      return value;
5288
0
    }
5289
0
  else /* tuple, dictionary entry */
5290
0
    {
5291
0
      GVariantBuilder b;
5292
5293
0
      if (**str == '(')
5294
0
        g_variant_builder_init (&b, G_VARIANT_TYPE_TUPLE);
5295
0
      else
5296
0
        {
5297
0
          g_assert (**str == '{');
5298
0
          g_variant_builder_init (&b, G_VARIANT_TYPE_DICT_ENTRY);
5299
0
        }
5300
5301
0
      (*str)++; /* '(' */
5302
0
      while (**str != ')' && **str != '}')
5303
0
        g_variant_builder_add_value (&b, g_variant_valist_new (str, app));
5304
0
      (*str)++; /* ')' */
5305
5306
0
      return g_variant_builder_end (&b);
5307
0
    }
5308
0
}
5309
5310
static void
5311
g_variant_valist_get (const gchar **str,
5312
                      GVariant     *value,
5313
                      gboolean      free,
5314
                      va_list      *app)
5315
0
{
5316
0
  if (g_variant_format_string_is_leaf (*str))
5317
0
    g_variant_valist_get_leaf (str, value, free, app);
5318
5319
0
  else if (**str == 'm')
5320
0
    {
5321
0
      (*str)++;
5322
5323
0
      if (value != NULL)
5324
0
        value = g_variant_get_maybe (value);
5325
5326
0
      if (!g_variant_format_string_is_nnp (*str))
5327
0
        {
5328
0
          gboolean *ptr = va_arg (*app, gboolean *);
5329
5330
0
          if (ptr != NULL)
5331
0
            *ptr = value != NULL;
5332
0
        }
5333
5334
0
      g_variant_valist_get (str, value, free, app);
5335
5336
0
      if (value != NULL)
5337
0
        g_variant_unref (value);
5338
0
    }
5339
5340
0
  else /* tuple, dictionary entry */
5341
0
    {
5342
0
      gint index = 0;
5343
5344
0
      g_assert (**str == '(' || **str == '{');
5345
5346
0
      (*str)++;
5347
0
      while (**str != ')' && **str != '}')
5348
0
        {
5349
0
          if (value != NULL)
5350
0
            {
5351
0
              GVariant *child = g_variant_get_child_value (value, index++);
5352
0
              g_variant_valist_get (str, child, free, app);
5353
0
              g_variant_unref (child);
5354
0
            }
5355
0
          else
5356
0
            g_variant_valist_get (str, NULL, free, app);
5357
0
        }
5358
0
      (*str)++;
5359
0
    }
5360
0
}
5361
5362
/* User-facing API {{{2 */
5363
/**
5364
 * g_variant_new: (skip)
5365
 * @format_string: a #GVariant format string
5366
 * @...: arguments, as per @format_string
5367
 *
5368
 * Creates a new #GVariant instance.
5369
 *
5370
 * Think of this function as an analogue to g_strdup_printf().
5371
 *
5372
 * The type of the created instance and the arguments that are expected
5373
 * by this function are determined by @format_string. See the section on
5374
 * [GVariant format strings][gvariant-format-strings]. Please note that
5375
 * the syntax of the format string is very likely to be extended in the
5376
 * future.
5377
 *
5378
 * The first character of the format string must not be '*' '?' '@' or
5379
 * 'r'; in essence, a new #GVariant must always be constructed by this
5380
 * function (and not merely passed through it unmodified).
5381
 *
5382
 * Note that the arguments must be of the correct width for their types
5383
 * specified in @format_string. This can be achieved by casting them. See
5384
 * the [GVariant varargs documentation][gvariant-varargs].
5385
 *
5386
 * |[<!-- language="C" -->
5387
 * MyFlags some_flags = FLAG_ONE | FLAG_TWO;
5388
 * const gchar *some_strings[] = { "a", "b", "c", NULL };
5389
 * GVariant *new_variant;
5390
 *
5391
 * new_variant = g_variant_new ("(t^as)",
5392
 *                              // This cast is required.
5393
 *                              (guint64) some_flags,
5394
 *                              some_strings);
5395
 * ]|
5396
 *
5397
 * Returns: a new floating #GVariant instance
5398
 *
5399
 * Since: 2.24
5400
 **/
5401
GVariant *
5402
g_variant_new (const gchar *format_string,
5403
               ...)
5404
0
{
5405
0
  GVariant *value;
5406
0
  va_list ap;
5407
5408
0
  g_return_val_if_fail (valid_format_string (format_string, TRUE, NULL) &&
5409
0
                        format_string[0] != '?' && format_string[0] != '@' &&
5410
0
                        format_string[0] != '*' && format_string[0] != 'r',
5411
0
                        NULL);
5412
5413
0
  va_start (ap, format_string);
5414
0
  value = g_variant_new_va (format_string, NULL, &ap);
5415
0
  va_end (ap);
5416
5417
0
  return value;
5418
0
}
5419
5420
/**
5421
 * g_variant_new_va: (skip)
5422
 * @format_string: a string that is prefixed with a format string
5423
 * @endptr: (nullable) (default NULL): location to store the end pointer,
5424
 *          or %NULL
5425
 * @app: a pointer to a #va_list
5426
 *
5427
 * This function is intended to be used by libraries based on
5428
 * #GVariant that want to provide g_variant_new()-like functionality
5429
 * to their users.
5430
 *
5431
 * The API is more general than g_variant_new() to allow a wider range
5432
 * of possible uses.
5433
 *
5434
 * @format_string must still point to a valid format string, but it only
5435
 * needs to be nul-terminated if @endptr is %NULL.  If @endptr is
5436
 * non-%NULL then it is updated to point to the first character past the
5437
 * end of the format string.
5438
 *
5439
 * @app is a pointer to a #va_list.  The arguments, according to
5440
 * @format_string, are collected from this #va_list and the list is left
5441
 * pointing to the argument following the last.
5442
 *
5443
 * Note that the arguments in @app must be of the correct width for their
5444
 * types specified in @format_string when collected into the #va_list.
5445
 * See the [GVariant varargs documentation][gvariant-varargs].
5446
 *
5447
 * These two generalisations allow mixing of multiple calls to
5448
 * g_variant_new_va() and g_variant_get_va() within a single actual
5449
 * varargs call by the user.
5450
 *
5451
 * The return value will be floating if it was a newly created GVariant
5452
 * instance (for example, if the format string was "(ii)").  In the case
5453
 * that the format_string was '*', '?', 'r', or a format starting with
5454
 * '@' then the collected #GVariant pointer will be returned unmodified,
5455
 * without adding any additional references.
5456
 *
5457
 * In order to behave correctly in all cases it is necessary for the
5458
 * calling function to g_variant_ref_sink() the return result before
5459
 * returning control to the user that originally provided the pointer.
5460
 * At this point, the caller will have their own full reference to the
5461
 * result.  This can also be done by adding the result to a container,
5462
 * or by passing it to another g_variant_new() call.
5463
 *
5464
 * Returns: a new, usually floating, #GVariant
5465
 *
5466
 * Since: 2.24
5467
 **/
5468
GVariant *
5469
g_variant_new_va (const gchar  *format_string,
5470
                  const gchar **endptr,
5471
                  va_list      *app)
5472
0
{
5473
0
  GVariant *value;
5474
5475
0
  g_return_val_if_fail (valid_format_string (format_string, !endptr, NULL),
5476
0
                        NULL);
5477
0
  g_return_val_if_fail (app != NULL, NULL);
5478
5479
0
  value = g_variant_valist_new (&format_string, app);
5480
5481
0
  if (endptr != NULL)
5482
0
    *endptr = format_string;
5483
5484
0
  return value;
5485
0
}
5486
5487
/**
5488
 * g_variant_get: (skip)
5489
 * @value: a #GVariant instance
5490
 * @format_string: a #GVariant format string
5491
 * @...: arguments, as per @format_string
5492
 *
5493
 * Deconstructs a #GVariant instance.
5494
 *
5495
 * Think of this function as an analogue to scanf().
5496
 *
5497
 * The arguments that are expected by this function are entirely
5498
 * determined by @format_string.  @format_string also restricts the
5499
 * permissible types of @value.  It is an error to give a value with
5500
 * an incompatible type.  See the section on
5501
 * [GVariant format strings][gvariant-format-strings].
5502
 * Please note that the syntax of the format string is very likely to be
5503
 * extended in the future.
5504
 *
5505
 * @format_string determines the C types that are used for unpacking
5506
 * the values and also determines if the values are copied or borrowed,
5507
 * see the section on
5508
 * [GVariant format strings][gvariant-format-strings-pointers].
5509
 *
5510
 * Since: 2.24
5511
 **/
5512
void
5513
g_variant_get (GVariant    *value,
5514
               const gchar *format_string,
5515
               ...)
5516
0
{
5517
0
  va_list ap;
5518
5519
0
  g_return_if_fail (value != NULL);
5520
0
  g_return_if_fail (valid_format_string (format_string, TRUE, value));
5521
5522
  /* if any direct-pointer-access formats are in use, flatten first */
5523
0
  if (strchr (format_string, '&'))
5524
0
    g_variant_get_data (value);
5525
5526
0
  va_start (ap, format_string);
5527
0
  g_variant_get_va (value, format_string, NULL, &ap);
5528
0
  va_end (ap);
5529
0
}
5530
5531
/**
5532
 * g_variant_get_va: (skip)
5533
 * @value: a #GVariant
5534
 * @format_string: a string that is prefixed with a format string
5535
 * @endptr: (nullable) (default NULL): location to store the end pointer,
5536
 *          or %NULL
5537
 * @app: a pointer to a #va_list
5538
 *
5539
 * This function is intended to be used by libraries based on #GVariant
5540
 * that want to provide g_variant_get()-like functionality to their
5541
 * users.
5542
 *
5543
 * The API is more general than g_variant_get() to allow a wider range
5544
 * of possible uses.
5545
 *
5546
 * @format_string must still point to a valid format string, but it only
5547
 * need to be nul-terminated if @endptr is %NULL.  If @endptr is
5548
 * non-%NULL then it is updated to point to the first character past the
5549
 * end of the format string.
5550
 *
5551
 * @app is a pointer to a #va_list.  The arguments, according to
5552
 * @format_string, are collected from this #va_list and the list is left
5553
 * pointing to the argument following the last.
5554
 *
5555
 * These two generalisations allow mixing of multiple calls to
5556
 * g_variant_new_va() and g_variant_get_va() within a single actual
5557
 * varargs call by the user.
5558
 *
5559
 * @format_string determines the C types that are used for unpacking
5560
 * the values and also determines if the values are copied or borrowed,
5561
 * see the section on
5562
 * [GVariant format strings][gvariant-format-strings-pointers].
5563
 *
5564
 * Since: 2.24
5565
 **/
5566
void
5567
g_variant_get_va (GVariant     *value,
5568
                  const gchar  *format_string,
5569
                  const gchar **endptr,
5570
                  va_list      *app)
5571
0
{
5572
0
  g_return_if_fail (valid_format_string (format_string, !endptr, value));
5573
0
  g_return_if_fail (value != NULL);
5574
0
  g_return_if_fail (app != NULL);
5575
5576
  /* if any direct-pointer-access formats are in use, flatten first */
5577
0
  if (strchr (format_string, '&'))
5578
0
    g_variant_get_data (value);
5579
5580
0
  g_variant_valist_get (&format_string, value, FALSE, app);
5581
5582
0
  if (endptr != NULL)
5583
0
    *endptr = format_string;
5584
0
}
5585
5586
/* Varargs-enabled Utility Functions {{{1 */
5587
5588
/**
5589
 * g_variant_builder_add: (skip)
5590
 * @builder: a #GVariantBuilder
5591
 * @format_string: a #GVariant varargs format string
5592
 * @...: arguments, as per @format_string
5593
 *
5594
 * Adds to a #GVariantBuilder.
5595
 *
5596
 * This call is a convenience wrapper that is exactly equivalent to
5597
 * calling g_variant_new() followed by g_variant_builder_add_value().
5598
 *
5599
 * Note that the arguments must be of the correct width for their types
5600
 * specified in @format_string. This can be achieved by casting them. See
5601
 * the [GVariant varargs documentation][gvariant-varargs].
5602
 *
5603
 * This function might be used as follows:
5604
 *
5605
 * |[<!-- language="C" --> 
5606
 * GVariant *
5607
 * make_pointless_dictionary (void)
5608
 * {
5609
 *   GVariantBuilder builder;
5610
 *   int i;
5611
 *
5612
 *   g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
5613
 *   for (i = 0; i < 16; i++)
5614
 *     {
5615
 *       gchar buf[3];
5616
 *
5617
 *       sprintf (buf, "%d", i);
5618
 *       g_variant_builder_add (&builder, "{is}", i, buf);
5619
 *     }
5620
 *
5621
 *   return g_variant_builder_end (&builder);
5622
 * }
5623
 * ]|
5624
 *
5625
 * Since: 2.24
5626
 */
5627
void
5628
g_variant_builder_add (GVariantBuilder *builder,
5629
                       const gchar     *format_string,
5630
                       ...)
5631
0
{
5632
0
  GVariant *variant;
5633
0
  va_list ap;
5634
5635
0
  va_start (ap, format_string);
5636
0
  variant = g_variant_new_va (format_string, NULL, &ap);
5637
0
  va_end (ap);
5638
5639
0
  g_variant_builder_add_value (builder, variant);
5640
0
}
5641
5642
/**
5643
 * g_variant_get_child: (skip)
5644
 * @value: a container #GVariant
5645
 * @index_: the index of the child to deconstruct
5646
 * @format_string: a #GVariant format string
5647
 * @...: arguments, as per @format_string
5648
 *
5649
 * Reads a child item out of a container #GVariant instance and
5650
 * deconstructs it according to @format_string.  This call is
5651
 * essentially a combination of g_variant_get_child_value() and
5652
 * g_variant_get().
5653
 *
5654
 * @format_string determines the C types that are used for unpacking
5655
 * the values and also determines if the values are copied or borrowed,
5656
 * see the section on
5657
 * [GVariant format strings][gvariant-format-strings-pointers].
5658
 *
5659
 * Since: 2.24
5660
 **/
5661
void
5662
g_variant_get_child (GVariant    *value,
5663
                     gsize        index_,
5664
                     const gchar *format_string,
5665
                     ...)
5666
0
{
5667
0
  GVariant *child;
5668
0
  va_list ap;
5669
5670
  /* if any direct-pointer-access formats are in use, flatten first */
5671
0
  if (strchr (format_string, '&'))
5672
0
    g_variant_get_data (value);
5673
5674
0
  child = g_variant_get_child_value (value, index_);
5675
0
  g_return_if_fail (valid_format_string (format_string, TRUE, child));
5676
5677
0
  va_start (ap, format_string);
5678
0
  g_variant_get_va (child, format_string, NULL, &ap);
5679
0
  va_end (ap);
5680
5681
0
  g_variant_unref (child);
5682
0
}
5683
5684
/**
5685
 * g_variant_iter_next: (skip)
5686
 * @iter: a #GVariantIter
5687
 * @format_string: a GVariant format string
5688
 * @...: the arguments to unpack the value into
5689
 *
5690
 * Gets the next item in the container and unpacks it into the variable
5691
 * argument list according to @format_string, returning %TRUE.
5692
 *
5693
 * If no more items remain then %FALSE is returned.
5694
 *
5695
 * All of the pointers given on the variable arguments list of this
5696
 * function are assumed to point at uninitialised memory.  It is the
5697
 * responsibility of the caller to free all of the values returned by
5698
 * the unpacking process.
5699
 *
5700
 * Here is an example for memory management with g_variant_iter_next():
5701
 * |[<!-- language="C" --> 
5702
 *   // Iterates a dictionary of type 'a{sv}'
5703
 *   void
5704
 *   iterate_dictionary (GVariant *dictionary)
5705
 *   {
5706
 *     GVariantIter iter;
5707
 *     GVariant *value;
5708
 *     gchar *key;
5709
 *
5710
 *     g_variant_iter_init (&iter, dictionary);
5711
 *     while (g_variant_iter_next (&iter, "{sv}", &key, &value))
5712
 *       {
5713
 *         g_print ("Item '%s' has type '%s'\n", key,
5714
 *                  g_variant_get_type_string (value));
5715
 *
5716
 *         // must free data for ourselves
5717
 *         g_variant_unref (value);
5718
 *         g_free (key);
5719
 *       }
5720
 *   }
5721
 * ]|
5722
 *
5723
 * For a solution that is likely to be more convenient to C programmers
5724
 * when dealing with loops, see g_variant_iter_loop().
5725
 *
5726
 * @format_string determines the C types that are used for unpacking
5727
 * the values and also determines if the values are copied or borrowed.
5728
 *
5729
 * See the section on
5730
 * [GVariant format strings][gvariant-format-strings-pointers].
5731
 *
5732
 * Returns: %TRUE if a value was unpacked, or %FALSE if there as no value
5733
 *
5734
 * Since: 2.24
5735
 **/
5736
gboolean
5737
g_variant_iter_next (GVariantIter *iter,
5738
                     const gchar  *format_string,
5739
                     ...)
5740
0
{
5741
0
  GVariant *value;
5742
5743
0
  value = g_variant_iter_next_value (iter);
5744
5745
0
  g_return_val_if_fail (valid_format_string (format_string, TRUE, value),
5746
0
                        FALSE);
5747
5748
0
  if (value != NULL)
5749
0
    {
5750
0
      va_list ap;
5751
5752
0
      va_start (ap, format_string);
5753
0
      g_variant_valist_get (&format_string, value, FALSE, &ap);
5754
0
      va_end (ap);
5755
5756
0
      g_variant_unref (value);
5757
0
    }
5758
5759
0
  return value != NULL;
5760
0
}
5761
5762
/**
5763
 * g_variant_iter_loop: (skip)
5764
 * @iter: a #GVariantIter
5765
 * @format_string: a GVariant format string
5766
 * @...: the arguments to unpack the value into
5767
 *
5768
 * Gets the next item in the container and unpacks it into the variable
5769
 * argument list according to @format_string, returning %TRUE.
5770
 *
5771
 * If no more items remain then %FALSE is returned.
5772
 *
5773
 * On the first call to this function, the pointers appearing on the
5774
 * variable argument list are assumed to point at uninitialised memory.
5775
 * On the second and later calls, it is assumed that the same pointers
5776
 * will be given and that they will point to the memory as set by the
5777
 * previous call to this function.  This allows the previous values to
5778
 * be freed, as appropriate.
5779
 *
5780
 * This function is intended to be used with a while loop as
5781
 * demonstrated in the following example.  This function can only be
5782
 * used when iterating over an array.  It is only valid to call this
5783
 * function with a string constant for the format string and the same
5784
 * string constant must be used each time.  Mixing calls to this
5785
 * function and g_variant_iter_next() or g_variant_iter_next_value() on
5786
 * the same iterator causes undefined behavior.
5787
 *
5788
 * If you break out of a such a while loop using g_variant_iter_loop() then
5789
 * you must free or unreference all the unpacked values as you would with
5790
 * g_variant_get(). Failure to do so will cause a memory leak.
5791
 *
5792
 * Here is an example for memory management with g_variant_iter_loop():
5793
 * |[<!-- language="C" --> 
5794
 *   // Iterates a dictionary of type 'a{sv}'
5795
 *   void
5796
 *   iterate_dictionary (GVariant *dictionary)
5797
 *   {
5798
 *     GVariantIter iter;
5799
 *     GVariant *value;
5800
 *     gchar *key;
5801
 *
5802
 *     g_variant_iter_init (&iter, dictionary);
5803
 *     while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
5804
 *       {
5805
 *         g_print ("Item '%s' has type '%s'\n", key,
5806
 *                  g_variant_get_type_string (value));
5807
 *
5808
 *         // no need to free 'key' and 'value' here
5809
 *         // unless breaking out of this loop
5810
 *       }
5811
 *   }
5812
 * ]|
5813
 *
5814
 * For most cases you should use g_variant_iter_next().
5815
 *
5816
 * This function is really only useful when unpacking into #GVariant or
5817
 * #GVariantIter in order to allow you to skip the call to
5818
 * g_variant_unref() or g_variant_iter_free().
5819
 *
5820
 * For example, if you are only looping over simple integer and string
5821
 * types, g_variant_iter_next() is definitely preferred.  For string
5822
 * types, use the '&' prefix to avoid allocating any memory at all (and
5823
 * thereby avoiding the need to free anything as well).
5824
 *
5825
 * @format_string determines the C types that are used for unpacking
5826
 * the values and also determines if the values are copied or borrowed.
5827
 *
5828
 * See the section on
5829
 * [GVariant format strings][gvariant-format-strings-pointers].
5830
 *
5831
 * Returns: %TRUE if a value was unpacked, or %FALSE if there was no
5832
 *          value
5833
 *
5834
 * Since: 2.24
5835
 **/
5836
gboolean
5837
g_variant_iter_loop (GVariantIter *iter,
5838
                     const gchar  *format_string,
5839
                     ...)
5840
0
{
5841
0
  gboolean first_time = GVSI(iter)->loop_format == NULL;
5842
0
  GVariant *value;
5843
0
  va_list ap;
5844
5845
0
  g_return_val_if_fail (first_time ||
5846
0
                        format_string == GVSI(iter)->loop_format,
5847
0
                        FALSE);
5848
5849
0
  if (first_time)
5850
0
    {
5851
0
      TYPE_CHECK (GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
5852
0
      GVSI(iter)->loop_format = format_string;
5853
5854
0
      if (strchr (format_string, '&'))
5855
0
        g_variant_get_data (GVSI(iter)->value);
5856
0
    }
5857
5858
0
  value = g_variant_iter_next_value (iter);
5859
5860
0
  g_return_val_if_fail (!first_time ||
5861
0
                        valid_format_string (format_string, TRUE, value),
5862
0
                        FALSE);
5863
5864
0
  va_start (ap, format_string);
5865
0
  g_variant_valist_get (&format_string, value, !first_time, &ap);
5866
0
  va_end (ap);
5867
5868
0
  if (value != NULL)
5869
0
    g_variant_unref (value);
5870
5871
0
  return value != NULL;
5872
0
}
5873
5874
/* Serialized data {{{1 */
5875
static GVariant *
5876
g_variant_deep_copy (GVariant *value,
5877
                     gboolean  byteswap)
5878
0
{
5879
0
  switch (g_variant_classify (value))
5880
0
    {
5881
0
    case G_VARIANT_CLASS_MAYBE:
5882
0
    case G_VARIANT_CLASS_TUPLE:
5883
0
    case G_VARIANT_CLASS_DICT_ENTRY:
5884
0
    case G_VARIANT_CLASS_VARIANT:
5885
0
      {
5886
0
        GVariantBuilder builder;
5887
0
        gsize i, n_children;
5888
5889
0
        g_variant_builder_init (&builder, g_variant_get_type (value));
5890
5891
0
        for (i = 0, n_children = g_variant_n_children (value); i < n_children; i++)
5892
0
          {
5893
0
            GVariant *child = g_variant_get_child_value (value, i);
5894
0
            g_variant_builder_add_value (&builder, g_variant_deep_copy (child, byteswap));
5895
0
            g_variant_unref (child);
5896
0
          }
5897
5898
0
        return g_variant_builder_end (&builder);
5899
0
      }
5900
5901
0
    case G_VARIANT_CLASS_ARRAY:
5902
0
      {
5903
0
        GVariantBuilder builder;
5904
0
        gsize i, n_children;
5905
0
        GVariant *first_invalid_child_deep_copy = NULL;
5906
5907
        /* Arrays are in theory treated the same as maybes, tuples, dict entries
5908
         * and variants, and could be another case in the above block of code.
5909
         *
5910
         * However, they have the property that when dealing with non-normal
5911
         * data (which is the only time g_variant_deep_copy() is currently
5912
         * called) in a variable-sized array, the code above can easily end up
5913
         * creating many default child values in order to return an array which
5914
         * is of the right length and type, but without containing non-normal
5915
         * data. This can happen if the offset table for the array is malformed.
5916
         *
5917
         * In this case, the code above would end up allocating the same default
5918
         * value for each one of the child indexes beyond the first malformed
5919
         * entry in the offset table. This can end up being a lot of identical
5920
         * allocations of default values, particularly if the non-normal array
5921
         * is crafted maliciously.
5922
         *
5923
         * Avoid that problem by returning a new reference to the same default
5924
         * value for every child after the first invalid one. This results in
5925
         * returning an equivalent array, in normal form and trusted — but with
5926
         * significantly fewer memory allocations.
5927
         *
5928
         * See https://gitlab.gnome.org/GNOME/glib/-/issues/2540 */
5929
5930
0
        g_variant_builder_init (&builder, g_variant_get_type (value));
5931
5932
0
        for (i = 0, n_children = g_variant_n_children (value); i < n_children; i++)
5933
0
          {
5934
            /* Try maybe_get_child_value() first; if it returns NULL, this child
5935
             * is non-normal. get_child_value() would have constructed and
5936
             * returned a default value in that case. */
5937
0
            GVariant *child = g_variant_maybe_get_child_value (value, i);
5938
5939
0
            if (child != NULL)
5940
0
              {
5941
                /* Non-normal children may not always be contiguous, as they may
5942
                 * be non-normal for reasons other than invalid offset table
5943
                 * entries. As they are all the same type, they will all have
5944
                 * the same default value though, so keep that around. */
5945
0
                g_variant_builder_add_value (&builder, g_variant_deep_copy (child, byteswap));
5946
0
              }
5947
0
            else if (child == NULL && first_invalid_child_deep_copy != NULL)
5948
0
              {
5949
0
                g_variant_builder_add_value (&builder, first_invalid_child_deep_copy);
5950
0
              }
5951
0
            else if (child == NULL)
5952
0
              {
5953
0
                child = g_variant_get_child_value (value, i);
5954
0
                first_invalid_child_deep_copy = g_variant_ref_sink (g_variant_deep_copy (child, byteswap));
5955
0
                g_variant_builder_add_value (&builder, first_invalid_child_deep_copy);
5956
0
              }
5957
5958
0
            g_clear_pointer (&child, g_variant_unref);
5959
0
          }
5960
5961
0
        g_clear_pointer (&first_invalid_child_deep_copy, g_variant_unref);
5962
5963
0
        return g_variant_builder_end (&builder);
5964
0
      }
5965
5966
0
    case G_VARIANT_CLASS_BOOLEAN:
5967
0
      return g_variant_new_boolean (g_variant_get_boolean (value));
5968
5969
0
    case G_VARIANT_CLASS_BYTE:
5970
0
      return g_variant_new_byte (g_variant_get_byte (value));
5971
5972
0
    case G_VARIANT_CLASS_INT16:
5973
0
      if (byteswap)
5974
0
        return g_variant_new_int16 (GUINT16_SWAP_LE_BE (g_variant_get_int16 (value)));
5975
0
      else
5976
0
        return g_variant_new_int16 (g_variant_get_int16 (value));
5977
5978
0
    case G_VARIANT_CLASS_UINT16:
5979
0
      if (byteswap)
5980
0
        return g_variant_new_uint16 (GUINT16_SWAP_LE_BE (g_variant_get_uint16 (value)));
5981
0
      else
5982
0
        return g_variant_new_uint16 (g_variant_get_uint16 (value));
5983
5984
0
    case G_VARIANT_CLASS_INT32:
5985
0
      if (byteswap)
5986
0
        return g_variant_new_int32 (GUINT32_SWAP_LE_BE (g_variant_get_int32 (value)));
5987
0
      else
5988
0
        return g_variant_new_int32 (g_variant_get_int32 (value));
5989
5990
0
    case G_VARIANT_CLASS_UINT32:
5991
0
      if (byteswap)
5992
0
        return g_variant_new_uint32 (GUINT32_SWAP_LE_BE (g_variant_get_uint32 (value)));
5993
0
      else
5994
0
        return g_variant_new_uint32 (g_variant_get_uint32 (value));
5995
5996
0
    case G_VARIANT_CLASS_INT64:
5997
0
      if (byteswap)
5998
0
        return g_variant_new_int64 (GUINT64_SWAP_LE_BE (g_variant_get_int64 (value)));
5999
0
      else
6000
0
        return g_variant_new_int64 (g_variant_get_int64 (value));
6001
6002
0
    case G_VARIANT_CLASS_UINT64:
6003
0
      if (byteswap)
6004
0
        return g_variant_new_uint64 (GUINT64_SWAP_LE_BE (g_variant_get_uint64 (value)));
6005
0
      else
6006
0
        return g_variant_new_uint64 (g_variant_get_uint64 (value));
6007
6008
0
    case G_VARIANT_CLASS_HANDLE:
6009
0
      if (byteswap)
6010
0
        return g_variant_new_handle (GUINT32_SWAP_LE_BE (g_variant_get_handle (value)));
6011
0
      else
6012
0
        return g_variant_new_handle (g_variant_get_handle (value));
6013
6014
0
    case G_VARIANT_CLASS_DOUBLE:
6015
0
      if (byteswap)
6016
0
        {
6017
          /* We have to convert the double to a uint64 here using a union,
6018
           * because a cast will round it numerically. */
6019
0
          union
6020
0
            {
6021
0
              guint64 u64;
6022
0
              gdouble dbl;
6023
0
            } u1, u2;
6024
0
          u1.dbl = g_variant_get_double (value);
6025
0
          u2.u64 = GUINT64_SWAP_LE_BE (u1.u64);
6026
0
          return g_variant_new_double (u2.dbl);
6027
0
        }
6028
0
      else
6029
0
        return g_variant_new_double (g_variant_get_double (value));
6030
6031
0
    case G_VARIANT_CLASS_STRING:
6032
0
      return g_variant_new_string (g_variant_get_string (value, NULL));
6033
6034
0
    case G_VARIANT_CLASS_OBJECT_PATH:
6035
0
      return g_variant_new_object_path (g_variant_get_string (value, NULL));
6036
6037
0
    case G_VARIANT_CLASS_SIGNATURE:
6038
0
      return g_variant_new_signature (g_variant_get_string (value, NULL));
6039
0
    }
6040
6041
0
  g_assert_not_reached ();
6042
0
}
6043
6044
/**
6045
 * g_variant_get_normal_form:
6046
 * @value: a #GVariant
6047
 *
6048
 * Gets a #GVariant instance that has the same value as @value and is
6049
 * trusted to be in normal form.
6050
 *
6051
 * If @value is already trusted to be in normal form then a new
6052
 * reference to @value is returned.
6053
 *
6054
 * If @value is not already trusted, then it is scanned to check if it
6055
 * is in normal form.  If it is found to be in normal form then it is
6056
 * marked as trusted and a new reference to it is returned.
6057
 *
6058
 * If @value is found not to be in normal form then a new trusted
6059
 * #GVariant is created with the same value as @value. The non-normal parts of
6060
 * @value will be replaced with default values which are guaranteed to be in
6061
 * normal form.
6062
 *
6063
 * It makes sense to call this function if you've received #GVariant
6064
 * data from untrusted sources and you want to ensure your serialized
6065
 * output is definitely in normal form.
6066
 *
6067
 * If @value is already in normal form, a new reference will be returned
6068
 * (which will be floating if @value is floating). If it is not in normal form,
6069
 * the newly created #GVariant will be returned with a single non-floating
6070
 * reference. Typically, g_variant_take_ref() should be called on the return
6071
 * value from this function to guarantee ownership of a single non-floating
6072
 * reference to it.
6073
 *
6074
 * Returns: (transfer full): a trusted #GVariant
6075
 *
6076
 * Since: 2.24
6077
 **/
6078
GVariant *
6079
g_variant_get_normal_form (GVariant *value)
6080
0
{
6081
0
  GVariant *trusted;
6082
6083
0
  if (g_variant_is_normal_form (value))
6084
0
    return g_variant_ref (value);
6085
6086
0
  trusted = g_variant_deep_copy (value, FALSE);
6087
0
  g_assert (g_variant_is_trusted (trusted));
6088
6089
0
  return g_variant_ref_sink (trusted);
6090
0
}
6091
6092
/**
6093
 * g_variant_byteswap:
6094
 * @value: a #GVariant
6095
 *
6096
 * Performs a byteswapping operation on the contents of @value.  The
6097
 * result is that all multi-byte numeric data contained in @value is
6098
 * byteswapped.  That includes 16, 32, and 64bit signed and unsigned
6099
 * integers as well as file handles and double precision floating point
6100
 * values.
6101
 *
6102
 * This function is an identity mapping on any value that does not
6103
 * contain multi-byte numeric data.  That include strings, booleans,
6104
 * bytes and containers containing only these things (recursively).
6105
 *
6106
 * While this function can safely handle untrusted, non-normal data, it is
6107
 * recommended to check whether the input is in normal form beforehand, using
6108
 * g_variant_is_normal_form(), and to reject non-normal inputs if your
6109
 * application can be strict about what inputs it rejects.
6110
 *
6111
 * The returned value is always in normal form and is marked as trusted.
6112
 * A full, not floating, reference is returned.
6113
 *
6114
 * Returns: (transfer full): the byteswapped form of @value
6115
 *
6116
 * Since: 2.24
6117
 **/
6118
GVariant *
6119
g_variant_byteswap (GVariant *value)
6120
0
{
6121
0
  GVariantTypeInfo *type_info;
6122
0
  guint alignment;
6123
0
  GVariant *new;
6124
6125
0
  type_info = g_variant_get_type_info (value);
6126
6127
0
  g_variant_type_info_query (type_info, &alignment, NULL);
6128
6129
0
  if (alignment && g_variant_is_normal_form (value))
6130
0
    {
6131
      /* (potentially) contains multi-byte numeric data, but is also already in
6132
       * normal form so we can use a faster byteswapping codepath on the
6133
       * serialised data */
6134
0
      GVariantSerialised serialised = { 0, };
6135
0
      GBytes *bytes;
6136
6137
0
      serialised.type_info = g_variant_get_type_info (value);
6138
0
      serialised.size = g_variant_get_size (value);
6139
0
      serialised.data = g_malloc (serialised.size);
6140
0
      serialised.depth = g_variant_get_depth (value);
6141
0
      serialised.ordered_offsets_up_to = G_MAXSIZE;  /* operating on the normal form */
6142
0
      serialised.checked_offsets_up_to = G_MAXSIZE;
6143
0
      g_variant_store (value, serialised.data);
6144
6145
0
      g_variant_serialised_byteswap (serialised);
6146
6147
0
      bytes = g_bytes_new_take (serialised.data, serialised.size);
6148
0
      new = g_variant_ref_sink (g_variant_new_from_bytes (g_variant_get_type (value), bytes, TRUE));
6149
0
      g_bytes_unref (bytes);
6150
0
    }
6151
0
  else if (alignment)
6152
    /* (potentially) contains multi-byte numeric data */
6153
0
    new = g_variant_ref_sink (g_variant_deep_copy (value, TRUE));
6154
0
  else
6155
    /* contains no multi-byte data */
6156
0
    new = g_variant_get_normal_form (value);
6157
6158
0
  g_assert (g_variant_is_trusted (new));
6159
6160
0
  return g_steal_pointer (&new);
6161
0
}
6162
6163
/**
6164
 * g_variant_new_from_data:
6165
 * @type: a definite #GVariantType
6166
 * @data: (array length=size) (element-type guint8): the serialized data
6167
 * @size: the size of @data
6168
 * @trusted: %TRUE if @data is definitely in normal form
6169
 * @notify: (scope async): function to call when @data is no longer needed
6170
 * @user_data: data for @notify
6171
 *
6172
 * Creates a new #GVariant instance from serialized data.
6173
 *
6174
 * @type is the type of #GVariant instance that will be constructed.
6175
 * The interpretation of @data depends on knowing the type.
6176
 *
6177
 * @data is not modified by this function and must remain valid with an
6178
 * unchanging value until such a time as @notify is called with
6179
 * @user_data.  If the contents of @data change before that time then
6180
 * the result is undefined.
6181
 *
6182
 * If @data is trusted to be serialized data in normal form then
6183
 * @trusted should be %TRUE.  This applies to serialized data created
6184
 * within this process or read from a trusted location on the disk (such
6185
 * as a file installed in /usr/lib alongside your application).  You
6186
 * should set trusted to %FALSE if @data is read from the network, a
6187
 * file in the user's home directory, etc.
6188
 *
6189
 * If @data was not stored in this machine's native endianness, any multi-byte
6190
 * numeric values in the returned variant will also be in non-native
6191
 * endianness. g_variant_byteswap() can be used to recover the original values.
6192
 *
6193
 * @notify will be called with @user_data when @data is no longer
6194
 * needed.  The exact time of this call is unspecified and might even be
6195
 * before this function returns.
6196
 *
6197
 * Note: @data must be backed by memory that is aligned appropriately for the
6198
 * @type being loaded. Otherwise this function will internally create a copy of
6199
 * the memory (since GLib 2.60) or (in older versions) fail and exit the
6200
 * process.
6201
 *
6202
 * Returns: (transfer none): a new floating #GVariant of type @type
6203
 *
6204
 * Since: 2.24
6205
 **/
6206
GVariant *
6207
g_variant_new_from_data (const GVariantType *type,
6208
                         gconstpointer       data,
6209
                         gsize               size,
6210
                         gboolean            trusted,
6211
                         GDestroyNotify      notify,
6212
                         gpointer            user_data)
6213
0
{
6214
0
  GVariant *value;
6215
0
  GBytes *bytes;
6216
6217
0
  g_return_val_if_fail (g_variant_type_is_definite (type), NULL);
6218
0
  g_return_val_if_fail (data != NULL || size == 0, NULL);
6219
6220
0
  if (notify)
6221
0
    bytes = g_bytes_new_with_free_func (data, size, notify, user_data);
6222
0
  else
6223
0
    bytes = g_bytes_new_static (data, size);
6224
6225
0
  value = g_variant_new_from_bytes (type, bytes, trusted);
6226
0
  g_bytes_unref (bytes);
6227
6228
0
  return value;
6229
0
}
6230
6231
/* Epilogue {{{1 */
6232
/* vim:set foldmethod=marker: */