Imported Upstream version 2.74.3
[platform/upstream/glib.git] / glib / gvariant-serialiser.c
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 #include "config.h"
25
26 #include "gvariant-serialiser.h"
27
28 #include <glib/gvariant-internal.h>
29 #include <glib/gtestutils.h>
30 #include <glib/gstrfuncs.h>
31 #include <glib/gtypes.h>
32
33 #include <string.h>
34
35
36 /* GVariantSerialiser
37  *
38  * After this prologue section, this file has roughly 2 parts.
39  *
40  * The first part is split up into sections according to various
41  * container types.  Maybe, Array, Tuple, Variant.  The Maybe and Array
42  * sections are subdivided for element types being fixed or
43  * variable-sized types.
44  *
45  * Each section documents the format of that particular type of
46  * container and implements 5 functions for dealing with it:
47  *
48  *  n_children:
49  *    - determines (according to serialized data) how many child values
50  *      are inside a particular container value.
51  *
52  *  get_child:
53  *    - gets the type of and the serialized data corresponding to a
54  *      given child value within the container value.
55  *
56  *  needed_size:
57  *    - determines how much space would be required to serialize a
58  *      container of this type, containing the given children so that
59  *      buffers can be preallocated before serializing.
60  *
61  *  serialise:
62  *    - write the serialized data for a container of this type,
63  *      containing the given children, to a buffer.
64  *
65  *  is_normal:
66  *    - check the given data to ensure that it is in normal form.  For a
67  *      given set of child values, there is exactly one normal form for
68  *      the serialized data of a container.  Other forms are possible
69  *      while maintaining the same children (for example, by inserting
70  *      something other than zero bytes as padding) but only one form is
71  *      the normal form.
72  *
73  * The second part contains the main entry point for each of the above 5
74  * functions and logic to dispatch it to the handler for the appropriate
75  * container type code.
76  *
77  * The second part also contains a routine to byteswap serialized
78  * values.  This code makes use of the n_children() and get_child()
79  * functions above to do its work so no extra support is needed on a
80  * per-container-type basis.
81  *
82  * There is also additional code for checking for normal form.  All
83  * numeric types are always in normal form since the full range of
84  * values is permitted (eg: 0 to 255 is a valid byte).  Special checks
85  * need to be performed for booleans (only 0 or 1 allowed), strings
86  * (properly nul-terminated) and object paths and signature strings
87  * (meeting the D-Bus specification requirements).  Depth checks need to be
88  * performed for nested types (arrays, tuples, and variants), to avoid massive
89  * recursion which could exhaust our stack when handling untrusted input.
90  */
91
92 /* < private >
93  * GVariantSerialised:
94  * @type_info: the #GVariantTypeInfo of this value
95  * @data: (nullable): the serialized data of this value, or %NULL
96  * @size: the size of this value
97  *
98  * A structure representing a GVariant in serialized form.  This
99  * structure is used with #GVariantSerialisedFiller functions and as the
100  * primary interface to the serializer.  See #GVariantSerialisedFiller
101  * for a description of its use there.
102  *
103  * When used with the serializer API functions, the following invariants
104  * apply to all #GVariantTypeSerialised structures passed to and
105  * returned from the serializer.
106  *
107  * @type_info must be non-%NULL.
108  *
109  * @data must be properly aligned for the type described by @type_info.
110  *
111  * If @type_info describes a fixed-sized type then @size must always be
112  * equal to the fixed size of that type.
113  *
114  * For fixed-sized types (and only fixed-sized types), @data may be
115  * %NULL even if @size is non-zero.  This happens when a framing error
116  * occurs while attempting to extract a fixed-sized value out of a
117  * variable-sized container.  There is no data to return for the
118  * fixed-sized type, yet @size must be non-zero.  The effect of this
119  * combination should be as if @data were a pointer to an
120  * appropriately-sized zero-filled region.
121  *
122  * @depth has no restrictions; the depth of a top-level serialized #GVariant is
123  * zero, and it increases for each level of nested child.
124  */
125
126 /* < private >
127  * g_variant_serialised_check:
128  * @serialised: a #GVariantSerialised struct
129  *
130  * Checks @serialised for validity according to the invariants described
131  * above.
132  *
133  * Returns: %TRUE if @serialised is valid; %FALSE otherwise
134  */
135 gboolean
136 g_variant_serialised_check (GVariantSerialised serialised)
137 {
138   gsize fixed_size;
139   guint alignment;
140
141   if (serialised.type_info == NULL)
142     return FALSE;
143   g_variant_type_info_query (serialised.type_info, &alignment, &fixed_size);
144
145   if (fixed_size != 0 && serialised.size != fixed_size)
146     return FALSE;
147   else if (fixed_size == 0 &&
148            !(serialised.size == 0 || serialised.data != NULL))
149     return FALSE;
150
151   /* Depending on the native alignment requirements of the machine, the
152    * compiler will insert either 3 or 7 padding bytes after the char.
153    * This will result in the sizeof() the struct being 12 or 16.
154    * Subtract 9 to get 3 or 7 which is a nice bitmask to apply to get
155    * the alignment bits that we "care about" being zero: in the
156    * 4-aligned case, we care about 2 bits, and in the 8-aligned case, we
157    * care about 3 bits.
158    */
159   alignment &= sizeof (struct {
160                          char a;
161                          union {
162                            guint64 x;
163                            void *y;
164                            gdouble z;
165                          } b;
166                        }
167                       ) - 9;
168
169   /* Some OSes (FreeBSD is a known example) have a malloc() that returns
170    * unaligned memory if you request small sizes.  'malloc (1);', for
171    * example, has been seen to return pointers aligned to 6 mod 16.
172    *
173    * Check if this is a small allocation and return without enforcing
174    * the alignment assertion if this is the case.
175    */
176   return (serialised.size <= alignment ||
177           (alignment & (gsize) serialised.data) == 0);
178 }
179
180 /* < private >
181  * GVariantSerialisedFiller:
182  * @serialised: a #GVariantSerialised instance to fill
183  * @data: data from the children array
184  *
185  * This function is called back from g_variant_serialiser_needed_size()
186  * and g_variant_serialiser_serialise().  It fills in missing details
187  * from a partially-complete #GVariantSerialised.
188  *
189  * The @data parameter passed back to the function is one of the items
190  * that was passed to the serializer in the @children array.  It
191  * represents a single child item of the container that is being
192  * serialized.  The information filled in to @serialised is the
193  * information for this child.
194  *
195  * If the @type_info field of @serialised is %NULL then the callback
196  * function must set it to the type information corresponding to the
197  * type of the child.  No reference should be added.  If it is non-%NULL
198  * then the callback should assert that it is equal to the actual type
199  * of the child.
200  *
201  * If the @size field is zero then the callback must fill it in with the
202  * required amount of space to store the serialized form of the child.
203  * If it is non-zero then the callback should assert that it is equal to
204  * the needed size of the child.
205  *
206  * If @data is non-%NULL then it points to a space that is properly
207  * aligned for and large enough to store the serialized data of the
208  * child.  The callback must store the serialized form of the child at
209  * @data.
210  *
211  * If the child value is another container then the callback will likely
212  * recurse back into the serializer by calling
213  * g_variant_serialiser_needed_size() to determine @size and
214  * g_variant_serialiser_serialise() to write to @data.
215  */
216
217 /* PART 1: Container types {{{1
218  *
219  * This section contains the serializer implementation functions for
220  * each container type.
221  */
222
223 /* Maybe {{{2
224  *
225  * Maybe types are handled depending on if the element type of the maybe
226  * type is a fixed-sized or variable-sized type.  Although all maybe
227  * types themselves are variable-sized types, herein, a maybe value with
228  * a fixed-sized element type is called a "fixed-sized maybe" for
229  * convenience and a maybe value with a variable-sized element type is
230  * called a "variable-sized maybe".
231  */
232
233 /* Fixed-sized Maybe {{{3
234  *
235  * The size of a maybe value with a fixed-sized element type is either 0
236  * or equal to the fixed size of its element type.  The case where the
237  * size of the maybe value is zero corresponds to the "Nothing" case and
238  * the case where the size of the maybe value is equal to the fixed size
239  * of the element type corresponds to the "Just" case; in that case, the
240  * serialized data of the child value forms the entire serialized data
241  * of the maybe value.
242  *
243  * In the event that a fixed-sized maybe value is presented with a size
244  * that is not equal to the fixed size of the element type then the
245  * value must be taken to be "Nothing".
246  */
247
248 static gsize
249 gvs_fixed_sized_maybe_n_children (GVariantSerialised value)
250 {
251   gsize element_fixed_size;
252
253   g_variant_type_info_query_element (value.type_info, NULL,
254                                      &element_fixed_size);
255
256   return (element_fixed_size == value.size) ? 1 : 0;
257 }
258
259 static GVariantSerialised
260 gvs_fixed_sized_maybe_get_child (GVariantSerialised value,
261                                  gsize              index_)
262 {
263   /* the child has the same bounds as the
264    * container, so just update the type.
265    */
266   value.type_info = g_variant_type_info_element (value.type_info);
267   g_variant_type_info_ref (value.type_info);
268   value.depth++;
269
270   return value;
271 }
272
273 static gsize
274 gvs_fixed_sized_maybe_needed_size (GVariantTypeInfo         *type_info,
275                                    GVariantSerialisedFiller  gvs_filler,
276                                    const gpointer           *children,
277                                    gsize                     n_children)
278 {
279   if (n_children)
280     {
281       gsize element_fixed_size;
282
283       g_variant_type_info_query_element (type_info, NULL,
284                                          &element_fixed_size);
285
286       return element_fixed_size;
287     }
288   else
289     return 0;
290 }
291
292 static void
293 gvs_fixed_sized_maybe_serialise (GVariantSerialised        value,
294                                  GVariantSerialisedFiller  gvs_filler,
295                                  const gpointer           *children,
296                                  gsize                     n_children)
297 {
298   if (n_children)
299     {
300       GVariantSerialised child = { NULL, value.data, value.size, value.depth + 1 };
301
302       gvs_filler (&child, children[0]);
303     }
304 }
305
306 static gboolean
307 gvs_fixed_sized_maybe_is_normal (GVariantSerialised value)
308 {
309   if (value.size > 0)
310     {
311       gsize element_fixed_size;
312
313       g_variant_type_info_query_element (value.type_info,
314                                          NULL, &element_fixed_size);
315
316       if (value.size != element_fixed_size)
317         return FALSE;
318
319       /* proper element size: "Just".  recurse to the child. */
320       value.type_info = g_variant_type_info_element (value.type_info);
321       value.depth++;
322
323       return g_variant_serialised_is_normal (value);
324     }
325
326   /* size of 0: "Nothing" */
327   return TRUE;
328 }
329
330 /* Variable-sized Maybe
331  *
332  * The size of a maybe value with a variable-sized element type is
333  * either 0 or strictly greater than 0.  The case where the size of the
334  * maybe value is zero corresponds to the "Nothing" case and the case
335  * where the size of the maybe value is greater than zero corresponds to
336  * the "Just" case; in that case, the serialized data of the child value
337  * forms the first part of the serialized data of the maybe value and is
338  * followed by a single zero byte.  This zero byte is always appended,
339  * regardless of any zero bytes that may already be at the end of the
340  * serialized ata of the child value.
341  */
342
343 static gsize
344 gvs_variable_sized_maybe_n_children (GVariantSerialised value)
345 {
346   return (value.size > 0) ? 1 : 0;
347 }
348
349 static GVariantSerialised
350 gvs_variable_sized_maybe_get_child (GVariantSerialised value,
351                                     gsize              index_)
352 {
353   /* remove the padding byte and update the type. */
354   value.type_info = g_variant_type_info_element (value.type_info);
355   g_variant_type_info_ref (value.type_info);
356   value.size--;
357
358   /* if it's zero-sized then it may as well be NULL */
359   if (value.size == 0)
360     value.data = NULL;
361
362   value.depth++;
363
364   return value;
365 }
366
367 static gsize
368 gvs_variable_sized_maybe_needed_size (GVariantTypeInfo         *type_info,
369                                       GVariantSerialisedFiller  gvs_filler,
370                                       const gpointer           *children,
371                                       gsize                     n_children)
372 {
373   if (n_children)
374     {
375       GVariantSerialised child = { 0, };
376
377       gvs_filler (&child, children[0]);
378
379       return child.size + 1;
380     }
381   else
382     return 0;
383 }
384
385 static void
386 gvs_variable_sized_maybe_serialise (GVariantSerialised        value,
387                                     GVariantSerialisedFiller  gvs_filler,
388                                     const gpointer           *children,
389                                     gsize                     n_children)
390 {
391   if (n_children)
392     {
393       GVariantSerialised child = { NULL, value.data, value.size - 1, value.depth + 1 };
394
395       /* write the data for the child.  */
396       gvs_filler (&child, children[0]);
397       value.data[child.size] = '\0';
398     }
399 }
400
401 static gboolean
402 gvs_variable_sized_maybe_is_normal (GVariantSerialised value)
403 {
404   if (value.size == 0)
405     return TRUE;
406
407   if (value.data[value.size - 1] != '\0')
408     return FALSE;
409
410   value.type_info = g_variant_type_info_element (value.type_info);
411   value.size--;
412   value.depth++;
413
414   return g_variant_serialised_is_normal (value);
415 }
416
417 /* Arrays {{{2
418  *
419  * Just as with maybe types, array types are handled depending on if the
420  * element type of the array type is a fixed-sized or variable-sized
421  * type.  Similar to maybe types, for convenience, an array value with a
422  * fixed-sized element type is called a "fixed-sized array" and an array
423  * value with a variable-sized element type is called a "variable sized
424  * array".
425  */
426
427 /* Fixed-sized Array {{{3
428  *
429  * For fixed sized arrays, the serialized data is simply a concatenation
430  * of the serialized data of each element, in order.  Since fixed-sized
431  * values always have a fixed size that is a multiple of their alignment
432  * requirement no extra padding is required.
433  *
434  * In the event that a fixed-sized array is presented with a size that
435  * is not an integer multiple of the element size then the value of the
436  * array must be taken as being empty.
437  */
438
439 static gsize
440 gvs_fixed_sized_array_n_children (GVariantSerialised value)
441 {
442   gsize element_fixed_size;
443
444   g_variant_type_info_query_element (value.type_info, NULL,
445                                      &element_fixed_size);
446
447   if (value.size % element_fixed_size == 0)
448     return value.size / element_fixed_size;
449
450   return 0;
451 }
452
453 static GVariantSerialised
454 gvs_fixed_sized_array_get_child (GVariantSerialised value,
455                                  gsize              index_)
456 {
457   GVariantSerialised child = { 0, };
458
459   child.type_info = g_variant_type_info_element (value.type_info);
460   g_variant_type_info_query (child.type_info, NULL, &child.size);
461   child.data = value.data + (child.size * index_);
462   g_variant_type_info_ref (child.type_info);
463   child.depth = value.depth + 1;
464
465   return child;
466 }
467
468 static gsize
469 gvs_fixed_sized_array_needed_size (GVariantTypeInfo         *type_info,
470                                    GVariantSerialisedFiller  gvs_filler,
471                                    const gpointer           *children,
472                                    gsize                     n_children)
473 {
474   gsize element_fixed_size;
475
476   g_variant_type_info_query_element (type_info, NULL, &element_fixed_size);
477
478   return element_fixed_size * n_children;
479 }
480
481 static void
482 gvs_fixed_sized_array_serialise (GVariantSerialised        value,
483                                  GVariantSerialisedFiller  gvs_filler,
484                                  const gpointer           *children,
485                                  gsize                     n_children)
486 {
487   GVariantSerialised child = { 0, };
488   gsize i;
489
490   child.type_info = g_variant_type_info_element (value.type_info);
491   g_variant_type_info_query (child.type_info, NULL, &child.size);
492   child.data = value.data;
493   child.depth = value.depth + 1;
494
495   for (i = 0; i < n_children; i++)
496     {
497       gvs_filler (&child, children[i]);
498       child.data += child.size;
499     }
500 }
501
502 static gboolean
503 gvs_fixed_sized_array_is_normal (GVariantSerialised value)
504 {
505   GVariantSerialised child = { 0, };
506
507   child.type_info = g_variant_type_info_element (value.type_info);
508   g_variant_type_info_query (child.type_info, NULL, &child.size);
509   child.depth = value.depth + 1;
510
511   if (value.size % child.size != 0)
512     return FALSE;
513
514   for (child.data = value.data;
515        child.data < value.data + value.size;
516        child.data += child.size)
517     {
518       if (!g_variant_serialised_is_normal (child))
519         return FALSE;
520     }
521
522   return TRUE;
523 }
524
525 /* Variable-sized Array {{{3
526  *
527  * Variable sized arrays, containing variable-sized elements, must be
528  * able to determine the boundaries between the elements.  The items
529  * cannot simply be concatenated.  Additionally, we are faced with the
530  * fact that non-fixed-sized values do not necessarily have a size that
531  * is a multiple of their alignment requirement, so we may need to
532  * insert zero-filled padding.
533  *
534  * While it is possible to find the start of an item by starting from
535  * the end of the item before it and padding for alignment, it is not
536  * generally possible to do the reverse operation.  For this reason, we
537  * record the end point of each element in the array.
538  *
539  * GVariant works in terms of "offsets".  An offset is a pointer to a
540  * boundary between two bytes.  In 4 bytes of serialized data, there
541  * would be 5 possible offsets: one at the start ('0'), one between each
542  * pair of adjacent bytes ('1', '2', '3') and one at the end ('4').
543  *
544  * The numeric value of an offset is an unsigned integer given relative
545  * to the start of the serialized data of the array.  Offsets are always
546  * stored in little endian byte order and are always only as big as they
547  * need to be.  For example, in 255 bytes of serialized data, there are
548  * 256 offsets.  All possibilities can be stored in an 8 bit unsigned
549  * integer.  In 256 bytes of serialized data, however, there are 257
550  * possible offsets so 16 bit integers must be used.  The size of an
551  * offset is always a power of 2.
552  *
553  * The offsets are stored at the end of the serialized data of the
554  * array.  They are simply concatenated on without any particular
555  * alignment.  The size of the offsets is included in the size of the
556  * serialized data for purposes of determining the size of the offsets.
557  * This presents a possibly ambiguity; in certain cases, a particular
558  * value of array could have two different serialized forms.
559  *
560  * Imagine an array containing a single string of 253 bytes in length
561  * (so, 254 bytes including the nul terminator).  Now the offset must be
562  * written.  If an 8 bit offset is written, it will bring the size of
563  * the array's serialized data to 255 -- which means that the use of an
564  * 8 bit offset was valid.  If a 16 bit offset is used then the total
565  * size of the array will be 256 -- which means that the use of a 16 bit
566  * offset was valid.  Although both of these will be accepted by the
567  * deserializer, only the smaller of the two is considered to be in
568  * normal form and that is the one that the serializer must produce.
569  */
570
571 /* bytes may be NULL if (size == 0). */
572 static inline gsize
573 gvs_read_unaligned_le (guchar *bytes,
574                        guint   size)
575 {
576   union
577   {
578     guchar bytes[GLIB_SIZEOF_SIZE_T];
579     gsize integer;
580   } tmpvalue;
581
582   tmpvalue.integer = 0;
583   if (bytes != NULL)
584     memcpy (&tmpvalue.bytes, bytes, size);
585
586   return GSIZE_FROM_LE (tmpvalue.integer);
587 }
588
589 static inline void
590 gvs_write_unaligned_le (guchar *bytes,
591                         gsize   value,
592                         guint   size)
593 {
594   union
595   {
596     guchar bytes[GLIB_SIZEOF_SIZE_T];
597     gsize integer;
598   } tmpvalue;
599
600   tmpvalue.integer = GSIZE_TO_LE (value);
601   memcpy (bytes, &tmpvalue.bytes, size);
602 }
603
604 static guint
605 gvs_get_offset_size (gsize size)
606 {
607   if (size > G_MAXUINT32)
608     return 8;
609
610   else if (size > G_MAXUINT16)
611     return 4;
612
613   else if (size > G_MAXUINT8)
614     return 2;
615
616   else if (size > 0)
617     return 1;
618
619   return 0;
620 }
621
622 static gsize
623 gvs_calculate_total_size (gsize body_size,
624                           gsize offsets)
625 {
626   if (body_size + 1 * offsets <= G_MAXUINT8)
627     return body_size + 1 * offsets;
628
629   if (body_size + 2 * offsets <= G_MAXUINT16)
630     return body_size + 2 * offsets;
631
632   if (body_size + 4 * offsets <= G_MAXUINT32)
633     return body_size + 4 * offsets;
634
635   return body_size + 8 * offsets;
636 }
637
638 static gsize
639 gvs_variable_sized_array_n_children (GVariantSerialised value)
640 {
641   gsize offsets_array_size;
642   gsize offset_size;
643   gsize last_end;
644
645   if (value.size == 0)
646     return 0;
647
648   offset_size = gvs_get_offset_size (value.size);
649
650   last_end = gvs_read_unaligned_le (value.data + value.size -
651                                     offset_size, offset_size);
652
653   if (last_end > value.size)
654     return 0;
655
656   offsets_array_size = value.size - last_end;
657
658   if (offsets_array_size % offset_size)
659     return 0;
660
661   return offsets_array_size / offset_size;
662 }
663
664 static GVariantSerialised
665 gvs_variable_sized_array_get_child (GVariantSerialised value,
666                                     gsize              index_)
667 {
668   GVariantSerialised child = { 0, };
669   gsize offset_size;
670   gsize last_end;
671   gsize start;
672   gsize end;
673
674   child.type_info = g_variant_type_info_element (value.type_info);
675   g_variant_type_info_ref (child.type_info);
676   child.depth = value.depth + 1;
677
678   offset_size = gvs_get_offset_size (value.size);
679
680   last_end = gvs_read_unaligned_le (value.data + value.size -
681                                     offset_size, offset_size);
682
683   if (index_ > 0)
684     {
685       guint alignment;
686
687       start = gvs_read_unaligned_le (value.data + last_end +
688                                      (offset_size * (index_ - 1)),
689                                      offset_size);
690
691       g_variant_type_info_query (child.type_info, &alignment, NULL);
692       start += (-start) & alignment;
693     }
694   else
695     start = 0;
696
697   end = gvs_read_unaligned_le (value.data + last_end +
698                                (offset_size * index_),
699                                offset_size);
700
701   if (start < end && end <= value.size && end <= last_end)
702     {
703       child.data = value.data + start;
704       child.size = end - start;
705     }
706
707   return child;
708 }
709
710 static gsize
711 gvs_variable_sized_array_needed_size (GVariantTypeInfo         *type_info,
712                                       GVariantSerialisedFiller  gvs_filler,
713                                       const gpointer           *children,
714                                       gsize                     n_children)
715 {
716   guint alignment;
717   gsize offset;
718   gsize i;
719
720   g_variant_type_info_query (type_info, &alignment, NULL);
721   offset = 0;
722
723   for (i = 0; i < n_children; i++)
724     {
725       GVariantSerialised child = { 0, };
726
727       offset += (-offset) & alignment;
728       gvs_filler (&child, children[i]);
729       offset += child.size;
730     }
731
732   return gvs_calculate_total_size (offset, n_children);
733 }
734
735 static void
736 gvs_variable_sized_array_serialise (GVariantSerialised        value,
737                                     GVariantSerialisedFiller  gvs_filler,
738                                     const gpointer           *children,
739                                     gsize                     n_children)
740 {
741   guchar *offset_ptr;
742   gsize offset_size;
743   guint alignment;
744   gsize offset;
745   gsize i;
746
747   g_variant_type_info_query (value.type_info, &alignment, NULL);
748   offset_size = gvs_get_offset_size (value.size);
749   offset = 0;
750
751   offset_ptr = value.data + value.size - offset_size * n_children;
752
753   for (i = 0; i < n_children; i++)
754     {
755       GVariantSerialised child = { 0, };
756
757       while (offset & alignment)
758         value.data[offset++] = '\0';
759
760       child.data = value.data + offset;
761       gvs_filler (&child, children[i]);
762       offset += child.size;
763
764       gvs_write_unaligned_le (offset_ptr, offset, offset_size);
765       offset_ptr += offset_size;
766     }
767 }
768
769 static gboolean
770 gvs_variable_sized_array_is_normal (GVariantSerialised value)
771 {
772   GVariantSerialised child = { 0, };
773   gsize offsets_array_size;
774   guchar *offsets_array;
775   guint offset_size;
776   guint alignment;
777   gsize last_end;
778   gsize length;
779   gsize offset;
780   gsize i;
781
782   if (value.size == 0)
783     return TRUE;
784
785   offset_size = gvs_get_offset_size (value.size);
786   last_end = gvs_read_unaligned_le (value.data + value.size -
787                                     offset_size, offset_size);
788
789   if (last_end > value.size)
790     return FALSE;
791
792   offsets_array_size = value.size - last_end;
793
794   if (offsets_array_size % offset_size)
795     return FALSE;
796
797   offsets_array = value.data + value.size - offsets_array_size;
798   length = offsets_array_size / offset_size;
799
800   if (length == 0)
801     return FALSE;
802
803   child.type_info = g_variant_type_info_element (value.type_info);
804   g_variant_type_info_query (child.type_info, &alignment, NULL);
805   child.depth = value.depth + 1;
806   offset = 0;
807
808   for (i = 0; i < length; i++)
809     {
810       gsize this_end;
811
812       this_end = gvs_read_unaligned_le (offsets_array + offset_size * i,
813                                         offset_size);
814
815       if (this_end < offset || this_end > last_end)
816         return FALSE;
817
818       while (offset & alignment)
819         {
820           if (!(offset < this_end && value.data[offset] == '\0'))
821             return FALSE;
822           offset++;
823         }
824
825       child.data = value.data + offset;
826       child.size = this_end - offset;
827
828       if (child.size == 0)
829         child.data = NULL;
830
831       if (!g_variant_serialised_is_normal (child))
832         return FALSE;
833
834       offset = this_end;
835     }
836
837   g_assert (offset == last_end);
838
839   return TRUE;
840 }
841
842 /* Tuples {{{2
843  *
844  * Since tuples can contain a mix of variable- and fixed-sized items,
845  * they are, in terms of serialization, a hybrid of variable-sized and
846  * fixed-sized arrays.
847  *
848  * Offsets are only stored for variable-sized items.  Also, since the
849  * number of items in a tuple is known from its type, we are able to
850  * know exactly how many offsets to expect in the serialized data (and
851  * therefore how much space is taken up by the offset array).  This
852  * means that we know where the end of the serialized data for the last
853  * item is -- we can just subtract the size of the offset array from the
854  * total size of the tuple.  For this reason, the last item in the tuple
855  * doesn't need an offset stored.
856  *
857  * Tuple offsets are stored in reverse.  This design choice allows
858  * iterator-based deserializers to be more efficient.
859  *
860  * Most of the "heavy lifting" here is handled by the GVariantTypeInfo
861  * for the tuple.  See the notes in gvarianttypeinfo.h.
862  */
863
864 static gsize
865 gvs_tuple_n_children (GVariantSerialised value)
866 {
867   return g_variant_type_info_n_members (value.type_info);
868 }
869
870 static GVariantSerialised
871 gvs_tuple_get_child (GVariantSerialised value,
872                      gsize              index_)
873 {
874   const GVariantMemberInfo *member_info;
875   GVariantSerialised child = { 0, };
876   gsize offset_size;
877   gsize start, end, last_end;
878
879   member_info = g_variant_type_info_member_info (value.type_info, index_);
880   child.type_info = g_variant_type_info_ref (member_info->type_info);
881   child.depth = value.depth + 1;
882   offset_size = gvs_get_offset_size (value.size);
883
884   /* tuples are the only (potentially) fixed-sized containers, so the
885    * only ones that have to deal with the possibility of having %NULL
886    * data with a non-zero %size if errors occurred elsewhere.
887    */
888   if G_UNLIKELY (value.data == NULL && value.size != 0)
889     {
890       g_variant_type_info_query (child.type_info, NULL, &child.size);
891
892       /* this can only happen in fixed-sized tuples,
893        * so the child must also be fixed sized.
894        */
895       g_assert (child.size != 0);
896       child.data = NULL;
897
898       return child;
899     }
900
901   if (member_info->ending_type == G_VARIANT_MEMBER_ENDING_OFFSET)
902     {
903       if (offset_size * (member_info->i + 2) > value.size)
904         return child;
905     }
906   else
907     {
908       if (offset_size * (member_info->i + 1) > value.size)
909         {
910           /* if the child is fixed size, return its size.
911            * if child is not fixed-sized, return size = 0.
912            */
913           g_variant_type_info_query (child.type_info, NULL, &child.size);
914
915           return child;
916         }
917     }
918
919   if (member_info->i + 1)
920     start = gvs_read_unaligned_le (value.data + value.size -
921                                    offset_size * (member_info->i + 1),
922                                    offset_size);
923   else
924     start = 0;
925
926   start += member_info->a;
927   start &= member_info->b;
928   start |= member_info->c;
929
930   if (member_info->ending_type == G_VARIANT_MEMBER_ENDING_LAST)
931     end = value.size - offset_size * (member_info->i + 1);
932
933   else if (member_info->ending_type == G_VARIANT_MEMBER_ENDING_FIXED)
934     {
935       gsize fixed_size;
936
937       g_variant_type_info_query (child.type_info, NULL, &fixed_size);
938       end = start + fixed_size;
939       child.size = fixed_size;
940     }
941
942   else /* G_VARIANT_MEMBER_ENDING_OFFSET */
943     end = gvs_read_unaligned_le (value.data + value.size -
944                                  offset_size * (member_info->i + 2),
945                                  offset_size);
946
947   /* The child should not extend into the offset table. */
948   if (index_ != g_variant_type_info_n_members (value.type_info) - 1)
949     {
950       GVariantSerialised last_child;
951       last_child = gvs_tuple_get_child (value,
952                                         g_variant_type_info_n_members (value.type_info) - 1);
953       last_end = last_child.data + last_child.size - value.data;
954       g_variant_type_info_unref (last_child.type_info);
955     }
956   else
957     last_end = end;
958
959   if (start < end && end <= value.size && end <= last_end)
960     {
961       child.data = value.data + start;
962       child.size = end - start;
963     }
964
965   return child;
966 }
967
968 static gsize
969 gvs_tuple_needed_size (GVariantTypeInfo         *type_info,
970                        GVariantSerialisedFiller  gvs_filler,
971                        const gpointer           *children,
972                        gsize                     n_children)
973 {
974   const GVariantMemberInfo *member_info = NULL;
975   gsize fixed_size;
976   gsize offset;
977   gsize i;
978
979   g_variant_type_info_query (type_info, NULL, &fixed_size);
980
981   if (fixed_size)
982     return fixed_size;
983
984   offset = 0;
985
986   for (i = 0; i < n_children; i++)
987     {
988       guint alignment;
989
990       member_info = g_variant_type_info_member_info (type_info, i);
991       g_variant_type_info_query (member_info->type_info,
992                                  &alignment, &fixed_size);
993       offset += (-offset) & alignment;
994
995       if (fixed_size)
996         offset += fixed_size;
997       else
998         {
999           GVariantSerialised child = { 0, };
1000
1001           gvs_filler (&child, children[i]);
1002           offset += child.size;
1003         }
1004     }
1005
1006   return gvs_calculate_total_size (offset, member_info->i + 1);
1007 }
1008
1009 static void
1010 gvs_tuple_serialise (GVariantSerialised        value,
1011                      GVariantSerialisedFiller  gvs_filler,
1012                      const gpointer           *children,
1013                      gsize                     n_children)
1014 {
1015   gsize offset_size;
1016   gsize offset;
1017   gsize i;
1018
1019   offset_size = gvs_get_offset_size (value.size);
1020   offset = 0;
1021
1022   for (i = 0; i < n_children; i++)
1023     {
1024       const GVariantMemberInfo *member_info;
1025       GVariantSerialised child = { 0, };
1026       guint alignment;
1027
1028       member_info = g_variant_type_info_member_info (value.type_info, i);
1029       g_variant_type_info_query (member_info->type_info, &alignment, NULL);
1030
1031       while (offset & alignment)
1032         value.data[offset++] = '\0';
1033
1034       child.data = value.data + offset;
1035       gvs_filler (&child, children[i]);
1036       offset += child.size;
1037
1038       if (member_info->ending_type == G_VARIANT_MEMBER_ENDING_OFFSET)
1039         {
1040           value.size -= offset_size;
1041           gvs_write_unaligned_le (value.data + value.size,
1042                                   offset, offset_size);
1043         }
1044     }
1045
1046   while (offset < value.size)
1047     value.data[offset++] = '\0';
1048 }
1049
1050 static gboolean
1051 gvs_tuple_is_normal (GVariantSerialised value)
1052 {
1053   guint offset_size;
1054   gsize offset_ptr;
1055   gsize length;
1056   gsize offset;
1057   gsize i;
1058
1059   /* as per the comment in gvs_tuple_get_child() */
1060   if G_UNLIKELY (value.data == NULL && value.size != 0)
1061     return FALSE;
1062
1063   offset_size = gvs_get_offset_size (value.size);
1064   length = g_variant_type_info_n_members (value.type_info);
1065   offset_ptr = value.size;
1066   offset = 0;
1067
1068   for (i = 0; i < length; i++)
1069     {
1070       const GVariantMemberInfo *member_info;
1071       GVariantSerialised child;
1072       gsize fixed_size;
1073       guint alignment;
1074       gsize end;
1075
1076       member_info = g_variant_type_info_member_info (value.type_info, i);
1077       child.type_info = member_info->type_info;
1078       child.depth = value.depth + 1;
1079
1080       g_variant_type_info_query (child.type_info, &alignment, &fixed_size);
1081
1082       while (offset & alignment)
1083         {
1084           if (offset > value.size || value.data[offset] != '\0')
1085             return FALSE;
1086           offset++;
1087         }
1088
1089       child.data = value.data + offset;
1090
1091       switch (member_info->ending_type)
1092         {
1093         case G_VARIANT_MEMBER_ENDING_FIXED:
1094           end = offset + fixed_size;
1095           break;
1096
1097         case G_VARIANT_MEMBER_ENDING_LAST:
1098           end = offset_ptr;
1099           break;
1100
1101         case G_VARIANT_MEMBER_ENDING_OFFSET:
1102           if (offset_ptr < offset_size)
1103             return FALSE;
1104
1105           offset_ptr -= offset_size;
1106
1107           if (offset_ptr < offset)
1108             return FALSE;
1109
1110           end = gvs_read_unaligned_le (value.data + offset_ptr, offset_size);
1111           break;
1112
1113         default:
1114           g_assert_not_reached ();
1115         }
1116
1117       if (end < offset || end > offset_ptr)
1118         return FALSE;
1119
1120       child.size = end - offset;
1121
1122       if (child.size == 0)
1123         child.data = NULL;
1124
1125       if (!g_variant_serialised_is_normal (child))
1126         return FALSE;
1127
1128       offset = end;
1129     }
1130
1131   {
1132     gsize fixed_size;
1133     guint alignment;
1134
1135     g_variant_type_info_query (value.type_info, &alignment, &fixed_size);
1136
1137     if (fixed_size)
1138       {
1139         g_assert (fixed_size == value.size);
1140         g_assert (offset_ptr == value.size);
1141
1142         if (i == 0)
1143           {
1144             if (value.data[offset++] != '\0')
1145               return FALSE;
1146           }
1147         else
1148           {
1149             while (offset & alignment)
1150               if (value.data[offset++] != '\0')
1151                 return FALSE;
1152           }
1153
1154         g_assert (offset == value.size);
1155       }
1156   }
1157
1158   return offset_ptr == offset;
1159 }
1160
1161 /* Variants {{{2
1162  *
1163  * Variants are stored by storing the serialized data of the child,
1164  * followed by a '\0' character, followed by the type string of the
1165  * child.
1166  *
1167  * In the case that a value is presented that contains no '\0'
1168  * character, or doesn't have a single well-formed definite type string
1169  * following that character, the variant must be taken as containing the
1170  * unit tuple: ().
1171  */
1172
1173 static inline gsize
1174 gvs_variant_n_children (GVariantSerialised value)
1175 {
1176   return 1;
1177 }
1178
1179 static inline GVariantSerialised
1180 gvs_variant_get_child (GVariantSerialised value,
1181                        gsize              index_)
1182 {
1183   GVariantSerialised child = { 0, };
1184
1185   /* NOTE: not O(1) and impossible for it to be... */
1186   if (value.size)
1187     {
1188       /* find '\0' character */
1189       for (child.size = value.size - 1; child.size; child.size--)
1190         if (value.data[child.size] == '\0')
1191           break;
1192
1193       /* ensure we didn't just hit the start of the string */
1194       if (value.data[child.size] == '\0')
1195         {
1196           const gchar *type_string = (gchar *) &value.data[child.size + 1];
1197           const gchar *limit = (gchar *) &value.data[value.size];
1198           const gchar *end;
1199
1200           if (g_variant_type_string_scan (type_string, limit, &end) &&
1201               end == limit)
1202             {
1203               const GVariantType *type = (GVariantType *) type_string;
1204
1205               if (g_variant_type_is_definite (type))
1206                 {
1207                   gsize fixed_size;
1208                   gsize child_type_depth;
1209
1210                   child.type_info = g_variant_type_info_get (type);
1211                   child.depth = value.depth + 1;
1212
1213                   if (child.size != 0)
1214                     /* only set to non-%NULL if size > 0 */
1215                     child.data = value.data;
1216
1217                   g_variant_type_info_query (child.type_info,
1218                                              NULL, &fixed_size);
1219                   child_type_depth = g_variant_type_info_query_depth (child.type_info);
1220
1221                   if ((!fixed_size || fixed_size == child.size) &&
1222                       value.depth < G_VARIANT_MAX_RECURSION_DEPTH - child_type_depth)
1223                     return child;
1224
1225                   g_variant_type_info_unref (child.type_info);
1226                 }
1227             }
1228         }
1229     }
1230
1231   child.type_info = g_variant_type_info_get (G_VARIANT_TYPE_UNIT);
1232   child.data = NULL;
1233   child.size = 1;
1234   child.depth = value.depth + 1;
1235
1236   return child;
1237 }
1238
1239 static inline gsize
1240 gvs_variant_needed_size (GVariantTypeInfo         *type_info,
1241                          GVariantSerialisedFiller  gvs_filler,
1242                          const gpointer           *children,
1243                          gsize                     n_children)
1244 {
1245   GVariantSerialised child = { 0, };
1246   const gchar *type_string;
1247
1248   gvs_filler (&child, children[0]);
1249   type_string = g_variant_type_info_get_type_string (child.type_info);
1250
1251   return child.size + 1 + strlen (type_string);
1252 }
1253
1254 static inline void
1255 gvs_variant_serialise (GVariantSerialised        value,
1256                        GVariantSerialisedFiller  gvs_filler,
1257                        const gpointer           *children,
1258                        gsize                     n_children)
1259 {
1260   GVariantSerialised child = { 0, };
1261   const gchar *type_string;
1262
1263   child.data = value.data;
1264
1265   gvs_filler (&child, children[0]);
1266   type_string = g_variant_type_info_get_type_string (child.type_info);
1267   value.data[child.size] = '\0';
1268   memcpy (value.data + child.size + 1, type_string, strlen (type_string));
1269 }
1270
1271 static inline gboolean
1272 gvs_variant_is_normal (GVariantSerialised value)
1273 {
1274   GVariantSerialised child;
1275   gboolean normal;
1276   gsize child_type_depth;
1277
1278   child = gvs_variant_get_child (value, 0);
1279   child_type_depth = g_variant_type_info_query_depth (child.type_info);
1280
1281   normal = (value.depth < G_VARIANT_MAX_RECURSION_DEPTH - child_type_depth) &&
1282            (child.data != NULL || child.size == 0) &&
1283            g_variant_serialised_is_normal (child);
1284
1285   g_variant_type_info_unref (child.type_info);
1286
1287   return normal;
1288 }
1289
1290
1291
1292 /* PART 2: Serializer API {{{1
1293  *
1294  * This is the implementation of the API of the serializer as advertised
1295  * in gvariant-serialiser.h.
1296  */
1297
1298 /* Dispatch Utilities {{{2
1299  *
1300  * These macros allow a given function (for example,
1301  * g_variant_serialiser_serialise) to be dispatched to the appropriate
1302  * type-specific function above (fixed/variable-sized maybe,
1303  * fixed/variable-sized array, tuple or variant).
1304  */
1305 #define DISPATCH_FIXED(type_info, before, after) \
1306   {                                                     \
1307     gsize fixed_size;                                   \
1308                                                         \
1309     g_variant_type_info_query_element (type_info, NULL, \
1310                                        &fixed_size);    \
1311                                                         \
1312     if (fixed_size)                                     \
1313       {                                                 \
1314         before ## fixed_sized ## after                  \
1315       }                                                 \
1316     else                                                \
1317       {                                                 \
1318         before ## variable_sized ## after               \
1319       }                                                 \
1320   }
1321
1322 #define DISPATCH_CASES(type_info, before, after) \
1323   switch (g_variant_type_info_get_type_char (type_info))        \
1324     {                                                           \
1325       case G_VARIANT_TYPE_INFO_CHAR_MAYBE:                      \
1326         DISPATCH_FIXED (type_info, before, _maybe ## after)     \
1327                                                                 \
1328       case G_VARIANT_TYPE_INFO_CHAR_ARRAY:                      \
1329         DISPATCH_FIXED (type_info, before, _array ## after)     \
1330                                                                 \
1331       case G_VARIANT_TYPE_INFO_CHAR_DICT_ENTRY:                 \
1332       case G_VARIANT_TYPE_INFO_CHAR_TUPLE:                      \
1333         {                                                       \
1334           before ## tuple ## after                              \
1335         }                                                       \
1336                                                                 \
1337       case G_VARIANT_TYPE_INFO_CHAR_VARIANT:                    \
1338         {                                                       \
1339           before ## variant ## after                            \
1340         }                                                       \
1341     }
1342
1343 /* Serializer entry points {{{2
1344  *
1345  * These are the functions that are called in order for the serializer
1346  * to do its thing.
1347  */
1348
1349 /* < private >
1350  * g_variant_serialised_n_children:
1351  * @serialised: a #GVariantSerialised
1352  *
1353  * For serialized data that represents a container value (maybes,
1354  * tuples, arrays, variants), determine how many child items are inside
1355  * that container.
1356  *
1357  * Returns: the number of children
1358  */
1359 gsize
1360 g_variant_serialised_n_children (GVariantSerialised serialised)
1361 {
1362   g_assert (g_variant_serialised_check (serialised));
1363
1364   DISPATCH_CASES (serialised.type_info,
1365
1366                   return gvs_/**/,/**/_n_children (serialised);
1367
1368                  )
1369   g_assert_not_reached ();
1370 }
1371
1372 /* < private >
1373  * g_variant_serialised_get_child:
1374  * @serialised: a #GVariantSerialised
1375  * @index_: the index of the child to fetch
1376  *
1377  * Extracts a child from a serialized data representing a container
1378  * value.
1379  *
1380  * It is an error to call this function with an index out of bounds.
1381  *
1382  * If the result .data == %NULL and .size > 0 then there has been an
1383  * error extracting the requested fixed-sized value.  This number of
1384  * zero bytes needs to be allocated instead.
1385  *
1386  * In the case that .data == %NULL and .size == 0 then a zero-sized
1387  * item of a variable-sized type is being returned.
1388  *
1389  * .data is never non-%NULL if size is 0.
1390  *
1391  * Returns: a #GVariantSerialised for the child
1392  */
1393 GVariantSerialised
1394 g_variant_serialised_get_child (GVariantSerialised serialised,
1395                                 gsize              index_)
1396 {
1397   GVariantSerialised child;
1398
1399   g_assert (g_variant_serialised_check (serialised));
1400
1401   if G_LIKELY (index_ < g_variant_serialised_n_children (serialised))
1402     {
1403       DISPATCH_CASES (serialised.type_info,
1404
1405                       child = gvs_/**/,/**/_get_child (serialised, index_);
1406                       g_assert (child.size || child.data == NULL);
1407                       g_assert (g_variant_serialised_check (child));
1408                       return child;
1409
1410                      )
1411       g_assert_not_reached ();
1412     }
1413
1414   g_error ("Attempt to access item %"G_GSIZE_FORMAT
1415            " in a container with only %"G_GSIZE_FORMAT" items",
1416            index_, g_variant_serialised_n_children (serialised));
1417 }
1418
1419 /* < private >
1420  * g_variant_serialiser_serialise:
1421  * @serialised: a #GVariantSerialised, properly set up
1422  * @gvs_filler: the filler function
1423  * @children: an array of child items
1424  * @n_children: the size of @children
1425  *
1426  * Writes data in serialized form.
1427  *
1428  * The type_info field of @serialised must be filled in to type info for
1429  * the type that we are serializing.
1430  *
1431  * The size field of @serialised must be filled in with the value
1432  * returned by a previous call to g_variant_serialiser_needed_size().
1433  *
1434  * The data field of @serialised must be a pointer to a properly-aligned
1435  * memory region large enough to serialize into (ie: at least as big as
1436  * the size field).
1437  *
1438  * This function is only resonsible for serializing the top-level
1439  * container.  @gvs_filler is called on each child of the container in
1440  * order for all of the data of that child to be filled in.
1441  */
1442 void
1443 g_variant_serialiser_serialise (GVariantSerialised        serialised,
1444                                 GVariantSerialisedFiller  gvs_filler,
1445                                 const gpointer           *children,
1446                                 gsize                     n_children)
1447 {
1448   g_assert (g_variant_serialised_check (serialised));
1449
1450   DISPATCH_CASES (serialised.type_info,
1451
1452                   gvs_/**/,/**/_serialise (serialised, gvs_filler,
1453                                            children, n_children);
1454                   return;
1455
1456                  )
1457   g_assert_not_reached ();
1458 }
1459
1460 /* < private >
1461  * g_variant_serialiser_needed_size:
1462  * @type_info: the type to serialize for
1463  * @gvs_filler: the filler function
1464  * @children: an array of child items
1465  * @n_children: the size of @children
1466  *
1467  * Determines how much memory would be needed to serialize this value.
1468  *
1469  * This function is only resonsible for performing calculations for the
1470  * top-level container.  @gvs_filler is called on each child of the
1471  * container in order to determine its size.
1472  */
1473 gsize
1474 g_variant_serialiser_needed_size (GVariantTypeInfo         *type_info,
1475                                   GVariantSerialisedFiller  gvs_filler,
1476                                   const gpointer           *children,
1477                                   gsize                     n_children)
1478 {
1479   DISPATCH_CASES (type_info,
1480
1481                   return gvs_/**/,/**/_needed_size (type_info, gvs_filler,
1482                                                     children, n_children);
1483
1484                  )
1485   g_assert_not_reached ();
1486 }
1487
1488 /* Byteswapping {{{2 */
1489
1490 /* < private >
1491  * g_variant_serialised_byteswap:
1492  * @value: a #GVariantSerialised
1493  *
1494  * Byte-swap serialized data.  The result of this function is only
1495  * well-defined if the data is in normal form.
1496  */
1497 void
1498 g_variant_serialised_byteswap (GVariantSerialised serialised)
1499 {
1500   gsize fixed_size;
1501   guint alignment;
1502
1503   g_assert (g_variant_serialised_check (serialised));
1504
1505   if (!serialised.data)
1506     return;
1507
1508   /* the types we potentially need to byteswap are
1509    * exactly those with alignment requirements.
1510    */
1511   g_variant_type_info_query (serialised.type_info, &alignment, &fixed_size);
1512   if (!alignment)
1513     return;
1514
1515   /* if fixed size and alignment are equal then we are down
1516    * to the base integer type and we should swap it.  the
1517    * only exception to this is if we have a tuple with a
1518    * single item, and then swapping it will be OK anyway.
1519    */
1520   if (alignment + 1 == fixed_size)
1521     {
1522       switch (fixed_size)
1523       {
1524         case 2:
1525           {
1526             guint16 *ptr = (guint16 *) serialised.data;
1527
1528             g_assert_cmpint (serialised.size, ==, 2);
1529             *ptr = GUINT16_SWAP_LE_BE (*ptr);
1530           }
1531           return;
1532
1533         case 4:
1534           {
1535             guint32 *ptr = (guint32 *) serialised.data;
1536
1537             g_assert_cmpint (serialised.size, ==, 4);
1538             *ptr = GUINT32_SWAP_LE_BE (*ptr);
1539           }
1540           return;
1541
1542         case 8:
1543           {
1544             guint64 *ptr = (guint64 *) serialised.data;
1545
1546             g_assert_cmpint (serialised.size, ==, 8);
1547             *ptr = GUINT64_SWAP_LE_BE (*ptr);
1548           }
1549           return;
1550
1551         default:
1552           g_assert_not_reached ();
1553       }
1554     }
1555
1556   /* else, we have a container that potentially contains
1557    * some children that need to be byteswapped.
1558    */
1559   else
1560     {
1561       gsize children, i;
1562
1563       children = g_variant_serialised_n_children (serialised);
1564       for (i = 0; i < children; i++)
1565         {
1566           GVariantSerialised child;
1567
1568           child = g_variant_serialised_get_child (serialised, i);
1569           g_variant_serialised_byteswap (child);
1570           g_variant_type_info_unref (child.type_info);
1571         }
1572     }
1573 }
1574
1575 /* Normal form checking {{{2 */
1576
1577 /* < private >
1578  * g_variant_serialised_is_normal:
1579  * @serialised: a #GVariantSerialised
1580  *
1581  * Determines, recursively if @serialised is in normal form.  There is
1582  * precisely one normal form of serialized data for each possible value.
1583  *
1584  * It is possible that multiple byte sequences form the serialized data
1585  * for a given value if, for example, the padding bytes are filled in
1586  * with something other than zeros, but only one form is the normal
1587  * form.
1588  */
1589 gboolean
1590 g_variant_serialised_is_normal (GVariantSerialised serialised)
1591 {
1592   if (serialised.depth >= G_VARIANT_MAX_RECURSION_DEPTH)
1593     return FALSE;
1594
1595   DISPATCH_CASES (serialised.type_info,
1596
1597                   return gvs_/**/,/**/_is_normal (serialised);
1598
1599                  )
1600
1601   if (serialised.data == NULL)
1602     return FALSE;
1603
1604   /* some hard-coded terminal cases */
1605   switch (g_variant_type_info_get_type_char (serialised.type_info))
1606     {
1607     case 'b': /* boolean */
1608       return serialised.data[0] < 2;
1609
1610     case 's': /* string */
1611       return g_variant_serialiser_is_string (serialised.data,
1612                                              serialised.size);
1613
1614     case 'o':
1615       return g_variant_serialiser_is_object_path (serialised.data,
1616                                                   serialised.size);
1617
1618     case 'g':
1619       return g_variant_serialiser_is_signature (serialised.data,
1620                                                 serialised.size);
1621
1622     default:
1623       /* all of the other types are fixed-sized numerical types for
1624        * which all possible values are valid (including various NaN
1625        * representations for floating point values).
1626        */
1627       return TRUE;
1628     }
1629 }
1630
1631 /* Validity-checking functions {{{2
1632  *
1633  * Checks if strings, object paths and signature strings are valid.
1634  */
1635
1636 /* < private >
1637  * g_variant_serialiser_is_string:
1638  * @data: a possible string
1639  * @size: the size of @data
1640  *
1641  * Ensures that @data is a valid string with a nul terminator at the end
1642  * and no nul bytes embedded.
1643  */
1644 gboolean
1645 g_variant_serialiser_is_string (gconstpointer data,
1646                                 gsize         size)
1647 {
1648   const gchar *expected_end;
1649   const gchar *end;
1650
1651   /* Strings must end with a nul terminator. */
1652   if (size == 0)
1653     return FALSE;
1654
1655   expected_end = ((gchar *) data) + size - 1;
1656
1657   if (*expected_end != '\0')
1658     return FALSE;
1659
1660   g_utf8_validate_len (data, size, &end);
1661
1662   return end == expected_end;
1663 }
1664
1665 /* < private >
1666  * g_variant_serialiser_is_object_path:
1667  * @data: a possible D-Bus object path
1668  * @size: the size of @data
1669  *
1670  * Performs the checks for being a valid string.
1671  *
1672  * Also, ensures that @data is a valid D-Bus object path, as per the D-Bus
1673  * specification.
1674  */
1675 gboolean
1676 g_variant_serialiser_is_object_path (gconstpointer data,
1677                                      gsize         size)
1678 {
1679   const gchar *string = data;
1680   gsize i;
1681
1682   if (!g_variant_serialiser_is_string (data, size))
1683     return FALSE;
1684
1685   /* The path must begin with an ASCII '/' (integer 47) character */
1686   if (string[0] != '/')
1687     return FALSE;
1688
1689   for (i = 1; string[i]; i++)
1690     /* Each element must only contain the ASCII characters
1691      * "[A-Z][a-z][0-9]_"
1692      */
1693     if (g_ascii_isalnum (string[i]) || string[i] == '_')
1694       ;
1695
1696     /* must consist of elements separated by slash characters. */
1697     else if (string[i] == '/')
1698       {
1699         /* No element may be the empty string. */
1700         /* Multiple '/' characters cannot occur in sequence. */
1701         if (string[i - 1] == '/')
1702           return FALSE;
1703       }
1704
1705     else
1706       return FALSE;
1707
1708   /* A trailing '/' character is not allowed unless the path is the
1709    * root path (a single '/' character).
1710    */
1711   if (i > 1 && string[i - 1] == '/')
1712     return FALSE;
1713
1714   return TRUE;
1715 }
1716
1717 /* < private >
1718  * g_variant_serialiser_is_signature:
1719  * @data: a possible D-Bus signature
1720  * @size: the size of @data
1721  *
1722  * Performs the checks for being a valid string.
1723  *
1724  * Also, ensures that @data is a valid D-Bus type signature, as per the
1725  * D-Bus specification. Note that this means the empty string is valid, as the
1726  * D-Bus specification defines a signature as “zero or more single complete
1727  * types”.
1728  */
1729 gboolean
1730 g_variant_serialiser_is_signature (gconstpointer data,
1731                                    gsize         size)
1732 {
1733   const gchar *string = data;
1734   gsize first_invalid;
1735
1736   if (!g_variant_serialiser_is_string (data, size))
1737     return FALSE;
1738
1739   /* make sure no non-definite characters appear */
1740   first_invalid = strspn (string, "ybnqiuxthdvasog(){}");
1741   if (string[first_invalid])
1742     return FALSE;
1743
1744   /* make sure each type string is well-formed */
1745   while (*string)
1746     if (!g_variant_type_string_scan (string, NULL, &string))
1747       return FALSE;
1748
1749   return TRUE;
1750 }
1751
1752 /* Epilogue {{{1 */
1753 /* vim:set foldmethod=marker: */