dbus-marshal-byteswap: Byte-swap Unix fd indexes if needed
[platform/upstream/dbus.git] / dbus / dbus-marshal-recursive.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-marshal-recursive.c  Marshalling routines for recursive types
3  *
4  * Copyright (C) 2004, 2005 Red Hat, Inc.
5  * Copyright (C) 2015  Samsung Electronics
6  *
7  * Licensed under the Academic Free License version 2.1
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
22  *
23  */
24
25 #include <config.h>
26 #include "dbus-marshal-recursive.h"
27 #include "dbus-marshal-basic.h"
28 #include "dbus-signature.h"
29 #include "dbus-internals.h"
30 #include "dbus-marshal-gvariant.h"
31
32 /**
33  * @addtogroup DBusMarshal
34  * @{
35  */
36
37 static dbus_bool_t _dbus_type_reader_greater_than              (const DBusTypeReader  *lhs,
38                                                                 const DBusTypeReader  *rhs);
39
40 static void       _dbus_type_writer_set_enabled           (DBusTypeWriter        *writer,
41                                                            dbus_bool_t            enabled);
42 static dbus_bool_t _dbus_type_writer_write_reader_partial (DBusTypeWriter        *writer,
43                                                            DBusTypeReader        *reader,
44                                                            const DBusTypeReader  *start_after,
45                                                            int                    start_after_new_pos,
46                                                            int                    start_after_new_len,
47                                                            DBusList             **fixups);
48
49 /** turn this on to get deluged in TypeReader verbose spam */
50 #define RECURSIVE_MARSHAL_READ_TRACE  0
51
52 /** turn this on to get deluged in TypeWriter verbose spam */
53 #define RECURSIVE_MARSHAL_WRITE_TRACE 0
54
55 static void
56 free_fixups (DBusList **fixups)
57 {
58   DBusList *link;
59
60   link = _dbus_list_get_first_link (fixups);
61   while (link != NULL)
62     {
63       DBusList *next;
64
65       next = _dbus_list_get_next_link (fixups, link);
66
67       dbus_free (link->data);
68       _dbus_list_free_link (link);
69
70       link = next;
71     }
72
73   *fixups = NULL;
74 }
75
76 static void
77 apply_and_free_fixups (DBusList      **fixups,
78                        DBusTypeReader *reader)
79 {
80   DBusList *link;
81
82 #if RECURSIVE_MARSHAL_WRITE_TRACE
83   if (*fixups)
84     _dbus_verbose (" %d FIXUPS to apply\n",
85                    _dbus_list_get_length (fixups));
86 #endif
87
88   link = _dbus_list_get_first_link (fixups);
89   while (link != NULL)
90     {
91       DBusList *next;
92
93       next = _dbus_list_get_next_link (fixups, link);
94
95       if (reader)
96         {
97           DBusArrayLenFixup *f;
98
99           f = link->data;
100
101 #if RECURSIVE_MARSHAL_WRITE_TRACE
102           _dbus_verbose (" applying FIXUP to reader %p at pos %d new_len = %d old len %d\n",
103                          reader, f->len_pos_in_reader, f->new_len,
104                          _dbus_marshal_read_uint32 (reader->value_str,
105                                                     f->len_pos_in_reader,
106                                                     reader->byte_order, NULL));
107 #endif
108
109           _dbus_marshal_set_uint32 ((DBusString*) reader->value_str,
110                                     f->len_pos_in_reader,
111                                     f->new_len,
112                                     reader->byte_order);
113         }
114
115       dbus_free (link->data);
116       _dbus_list_free_link (link);
117
118       link = next;
119     }
120
121   *fixups = NULL;
122 }
123
124 /**
125  * Virtual table for a type reader.
126  */
127 struct DBusTypeReaderClass
128 {
129   const char *name;       /**< name for debugging */
130   int         id;         /**< index in all_reader_classes */
131   dbus_bool_t types_only; /**< only iterates over types, not values */
132   void        (* recurse)          (DBusTypeReader        *sub,
133                                     DBusTypeReader        *parent); /**< recurse with this reader as sub */
134   dbus_bool_t (* check_finished)   (const DBusTypeReader  *reader); /**< check whether reader is at the end */
135   void        (* next)             (DBusTypeReader        *reader,
136                                     int                    current_type); /**< go to the next value */
137 };
138
139 static int
140 element_type_get_alignment (const DBusString *str,
141                             int               pos)
142 {
143   return _dbus_type_get_alignment (_dbus_first_type_in_signature (str, pos));
144 }
145
146 static void
147 reader_init (DBusTypeReader    *reader,
148              int                byte_order,
149              const DBusString  *type_str,
150              int                type_pos,
151              const DBusString  *value_str,
152              int                value_pos,
153              dbus_bool_t        gvariant)
154 {
155   _DBUS_ZERO (*reader);
156   reader->byte_order = byte_order;
157   reader->finished = FALSE;
158   reader->type_str = type_str;
159   reader->type_pos = type_pos;
160   reader->value_str = value_str;
161   reader->value_pos = value_pos;
162   reader->value_start = value_pos;
163   reader->gvariant = gvariant;
164   reader->variable_index = 0;
165   reader->offsets_from_back = TRUE;
166   reader->is_variant = FALSE;
167 }
168
169 static void
170 base_reader_recurse (DBusTypeReader *sub,
171                      DBusTypeReader *parent)
172 {
173   /* point subreader at the same place as parent */
174   reader_init (sub,
175                parent->byte_order,
176                parent->type_str,
177                parent->type_pos,
178                parent->value_str,
179                parent->value_pos,
180                parent->gvariant);
181 }
182
183 static void
184 struct_or_dict_entry_types_only_reader_recurse (DBusTypeReader *sub,
185                                                 DBusTypeReader *parent)
186 {
187   base_reader_recurse (sub, parent);
188   
189   _dbus_assert (_dbus_string_get_byte (sub->type_str,
190                                        sub->type_pos) == DBUS_STRUCT_BEGIN_CHAR ||
191                 _dbus_string_get_byte (sub->type_str,
192                                        sub->type_pos) == DBUS_DICT_ENTRY_BEGIN_CHAR);
193
194   sub->type_pos += 1;
195 }
196
197 static void
198 struct_or_dict_entry_reader_recurse (DBusTypeReader *sub,
199                                      DBusTypeReader *parent)
200 {
201   struct_or_dict_entry_types_only_reader_recurse (sub, parent);
202
203   if (sub->gvariant)
204   {
205     /* GVARIANT */
206     /* check if current type is fixed or variable */
207     int alignment = 1;
208     int size = _dbus_reader_get_type_fixed_size (parent, &alignment);
209     sub->value_pos = _DBUS_ALIGN_VALUE (sub->value_pos, alignment); /* adjust alignment */
210     sub->value_start = sub->value_pos;
211     sub->n_offsets = _dbus_reader_count_offsets (sub);
212     sub->offsets_from_back = TRUE;
213
214     if (0 == size)
215     {
216       sub->value_end = _dbus_reader_get_offset_of_end_of_variable (parent);
217     }
218     else
219     {
220       sub->value_end = sub->value_pos + size;
221     }
222   }
223   else
224   {
225     /* struct and dict entry have 8 byte alignment */
226     sub->value_pos = sub->value_start = _DBUS_ALIGN_VALUE (sub->value_pos, 8);
227   }
228 }
229
230 static void
231 array_types_only_reader_recurse (DBusTypeReader *sub,
232                                  DBusTypeReader *parent)
233 {
234   base_reader_recurse (sub, parent);
235
236   /* point type_pos at the array element type */
237   sub->type_pos += 1;
238
239   /* Init with values likely to crash things if misused */
240   sub->u.array.start_pos = _DBUS_INT_MAX;
241   sub->array_len_offset = 7;
242 }
243
244 /** compute position of array length given array_len_offset, which is
245     the offset back from start_pos to end of the len */
246 #define ARRAY_READER_LEN_POS(reader) \
247   ((reader)->u.array.start_pos - ((int)(reader)->array_len_offset) - 4)
248
249 static int
250 array_reader_get_array_len (const DBusTypeReader *reader)
251 {
252   dbus_uint32_t array_len;
253   int len_pos;
254
255   if (reader->gvariant)
256     return reader->value_end - reader->value_start;
257
258   len_pos = ARRAY_READER_LEN_POS (reader);
259
260   _dbus_assert (_DBUS_ALIGN_VALUE (len_pos, 4) == (unsigned) len_pos);
261   array_len = _dbus_unpack_uint32 (reader->byte_order,
262                                    _dbus_string_get_const_udata_len (reader->value_str, len_pos, 4));
263
264 #if RECURSIVE_MARSHAL_READ_TRACE
265   _dbus_verbose ("   reader %p len_pos %d array len %u len_offset %d\n",
266                  reader, len_pos, array_len, reader->array_len_offset);
267 #endif
268
269   _dbus_assert (reader->u.array.start_pos - len_pos - 4 < 8);
270
271   return array_len;
272 }
273
274 static void
275 array_reader_recurse (DBusTypeReader *sub,
276                       DBusTypeReader *parent)
277 {
278   int alignment;
279   int len_pos;
280
281   array_types_only_reader_recurse (sub, parent);
282
283   if (sub->gvariant)
284   {
285     int size = _dbus_reader_get_type_fixed_size (sub, &alignment);
286     sub->value_pos = _DBUS_ALIGN_VALUE (sub->value_pos, alignment);
287     sub->value_start = sub->value_pos;
288     sub->offsets_from_back = FALSE;
289     sub->value_end = _dbus_reader_get_offset_of_end_of_variable (parent);
290     sub->variable_index = 0;
291     if (0 == size)
292       sub->n_offsets = _dbus_reader_count_array_elems (sub);
293     else
294       sub->n_offsets = 0;
295     sub->u.array.start_pos = sub->value_start;
296     sub->finished = (sub->value_end == sub->value_start);
297   }
298   else
299   {
300     sub->value_pos = _DBUS_ALIGN_VALUE (sub->value_pos, 4);
301
302     len_pos = sub->value_pos;
303
304     sub->value_pos += 4; /* for the length */
305
306     alignment = element_type_get_alignment (sub->type_str,
307                                             sub->type_pos);
308
309     sub->value_pos = _DBUS_ALIGN_VALUE (sub->value_pos, alignment);
310
311     sub->u.array.start_pos = sub->value_pos;
312     _dbus_assert ((sub->u.array.start_pos - (len_pos + 4)) < 8); /* only 3 bits in array_len_offset */
313     sub->array_len_offset = sub->u.array.start_pos - (len_pos + 4);
314   }
315
316 #if RECURSIVE_MARSHAL_READ_TRACE
317   _dbus_verbose ("    type reader %p array start = %d len_offset = %d array len = %d array element type = %s\n",
318                  sub,
319                  sub->u.array.start_pos,
320                  sub->array_len_offset,
321                  array_reader_get_array_len (sub),
322                  _dbus_type_to_string (_dbus_first_type_in_signature (sub->type_str,
323                                                                 sub->type_pos)));
324 #endif
325 }
326
327 static void
328 variant_reader_recurse (DBusTypeReader *sub,
329                         DBusTypeReader *parent)
330 {
331   int sig_len;
332   int contained_alignment;
333
334   base_reader_recurse (sub, parent);
335
336   if (sub->gvariant)
337   {
338     /* GVariant's Variant is values, then nul byte, then signature.
339      * Variant's alignment is 8.
340      */
341     sub->value_pos = sub->value_start = _DBUS_ALIGN_VALUE (sub->value_pos, 8); /* adjust alignment */
342     sub->value_end = _dbus_reader_get_offset_of_end_of_variable (parent);
343
344     /* find beginning of signature in variant */
345     sub->type_str = sub->value_str;
346     sub->type_pos = sub->value_end - 1;
347
348     while (sub->type_pos > 0 && _dbus_string_get_byte (sub->type_str, sub->type_pos) != 0)
349       sub->type_pos--;
350
351     if (_dbus_string_get_byte (sub->type_str, sub->type_pos) == 0)
352       sub->type_pos++;
353
354     /* set the end of variant's value to the zero byte before signature */
355     sub->value_end = sub->type_pos - 1;
356     sub->is_variant = TRUE;
357   }
358   else
359   {
360     /* Variant is 1 byte sig length (without nul), signature with nul,
361      * padding to 8-boundary, then values
362      */
363
364     sig_len = _dbus_string_get_byte (sub->value_str, sub->value_pos);
365
366     sub->type_str = sub->value_str;
367     sub->type_pos = sub->value_pos + 1;
368
369     sub->value_pos = sub->type_pos + sig_len + 1;
370
371     contained_alignment = _dbus_type_get_alignment (_dbus_first_type_in_signature (sub->type_str,
372                                                                              sub->type_pos));
373
374     sub->value_pos = _DBUS_ALIGN_VALUE (sub->value_pos, contained_alignment);
375   }
376
377 #if RECURSIVE_MARSHAL_READ_TRACE
378   _dbus_verbose ("    type reader %p variant containing '%s'\n",
379                  sub,
380                  _dbus_string_get_const_data_len (sub->type_str,
381                                                   sub->type_pos, 0));
382 #endif
383 }
384
385 static dbus_bool_t
386 array_reader_check_finished (const DBusTypeReader *reader)
387 {
388   int end_pos;
389
390   /* return the array element type if elements remain, and
391    * TYPE_INVALID otherwise
392    */
393
394   end_pos = reader->u.array.start_pos + array_reader_get_array_len (reader);
395
396   _dbus_assert (reader->value_pos <= end_pos);
397   _dbus_assert (reader->value_pos >= reader->u.array.start_pos);
398
399   return reader->value_pos == end_pos;
400 }
401
402 static void
403 skip_one_complete_type (const DBusString *type_str,
404                         int              *type_pos)
405 {
406   _dbus_type_signature_next (_dbus_string_get_const_data (type_str),
407                              type_pos);
408 }
409
410 /**
411  * Skips to the next "complete" type inside a type signature.
412  * The signature is read starting at type_pos, and the next
413  * type position is stored in the same variable.
414  *
415  * @param type_str a type signature (must be valid)
416  * @param type_pos an integer position in the type signature (in and out)
417  */
418 void
419 _dbus_type_signature_next (const char       *type_str,
420                            int              *type_pos)
421 {
422   const unsigned char *p;
423   const unsigned char *start;
424
425   _dbus_assert (type_str != NULL);
426   _dbus_assert (type_pos != NULL);
427   
428   start = (const unsigned char *)type_str;
429   p = start + *type_pos;
430
431   _dbus_assert (*p != DBUS_STRUCT_END_CHAR);
432   _dbus_assert (*p != DBUS_DICT_ENTRY_END_CHAR);
433   
434   while (*p == DBUS_TYPE_ARRAY)
435     ++p;
436
437   _dbus_assert (*p != DBUS_STRUCT_END_CHAR);
438   _dbus_assert (*p != DBUS_DICT_ENTRY_END_CHAR);
439   
440   if (*p == DBUS_STRUCT_BEGIN_CHAR)
441     {
442       int depth;
443
444       depth = 1;
445
446       while (TRUE)
447         {
448           _dbus_assert (*p != DBUS_TYPE_INVALID);
449
450           ++p;
451
452           _dbus_assert (*p != DBUS_TYPE_INVALID);
453
454           if (*p == DBUS_STRUCT_BEGIN_CHAR)
455             depth += 1;
456           else if (*p == DBUS_STRUCT_END_CHAR)
457             {
458               depth -= 1;
459               if (depth == 0)
460                 {
461                   ++p;
462                   break;
463                 }
464             }
465         }
466     }
467   else if (*p == DBUS_DICT_ENTRY_BEGIN_CHAR)
468     {
469       int depth;
470
471       depth = 1;
472
473       while (TRUE)
474         {
475           _dbus_assert (*p != DBUS_TYPE_INVALID);
476
477           ++p;
478
479           _dbus_assert (*p != DBUS_TYPE_INVALID);
480
481           if (*p == DBUS_DICT_ENTRY_BEGIN_CHAR)
482             depth += 1;
483           else if (*p == DBUS_DICT_ENTRY_END_CHAR)
484             {
485               depth -= 1;
486               if (depth == 0)
487                 {
488                   ++p;
489                   break;
490                 }
491             }
492         }
493     }
494   else
495     {
496       ++p;
497     }
498
499   *type_pos = (int) (p - start);
500 }
501
502 static int
503 find_len_of_complete_type (const DBusString *type_str,
504                            int               type_pos)
505 {
506   int end;
507
508   end = type_pos;
509
510   skip_one_complete_type (type_str, &end);
511
512   return end - type_pos;
513 }
514
515 static void
516 base_reader_next (DBusTypeReader *reader,
517                   int             current_type)
518 {
519   switch (current_type)
520     {
521     case DBUS_TYPE_DICT_ENTRY:
522     case DBUS_TYPE_STRUCT:
523     case DBUS_TYPE_VARIANT:
524       /* Scan forward over the entire container contents */
525       /* FIXME for GVariant - use offsets */
526       {
527         DBusTypeReader sub;
528
529         if (reader->klass->types_only && current_type == DBUS_TYPE_VARIANT)
530           ;
531         else
532           {
533             /* Recurse into the struct or variant */
534             _dbus_type_reader_recurse (reader, &sub);
535
536             /* Skip everything in this subreader */
537             while (_dbus_type_reader_next (&sub))
538               {
539                 /* nothing */;
540               }
541           }
542         if (!reader->klass->types_only)
543           reader->value_pos = sub.value_pos;
544
545         /* Now we are at the end of this container; for variants, the
546          * subreader's type_pos is totally inapplicable (it's in the
547          * value string) but we know that we increment by one past the
548          * DBUS_TYPE_VARIANT
549          */
550         if (current_type == DBUS_TYPE_VARIANT)
551           reader->type_pos += 1;
552         else
553           reader->type_pos = sub.type_pos;
554       }
555       break;
556
557     case DBUS_TYPE_ARRAY:
558       {
559         if (!reader->klass->types_only)
560           _dbus_marshal_skip_array (reader->value_str,
561                                     _dbus_first_type_in_signature (reader->type_str,
562                                                                    reader->type_pos + 1),
563                                     reader->byte_order,
564                                     &reader->value_pos);
565
566         skip_one_complete_type (reader->type_str, &reader->type_pos);
567       }
568       break;
569
570     default:
571       if (!reader->klass->types_only)
572         (reader->gvariant ? _dbus_marshal_skip_gvariant_basic : _dbus_marshal_skip_basic) (
573                                   reader->value_str,
574                                   current_type, reader->byte_order,
575                                   &reader->value_pos);
576
577       reader->type_pos += 1;
578       break;
579     }
580 }
581
582 static void
583 struct_or_dict_entry_reader_next (DBusTypeReader *reader,
584                             int             current_type)
585 {
586   if (reader->gvariant)
587     {
588       int alignment;
589       int size = _dbus_reader_get_type_fixed_size (reader, &alignment);
590       if (0 == size)
591         {
592           /* variable size - use offsets*/
593           reader->value_pos = _dbus_reader_get_offset_of_end_of_variable (reader);
594           reader->variable_index++;
595         }
596       else
597         {
598           /* just move, but consider alignment */
599           reader->value_pos = _DBUS_ALIGN_VALUE(reader->value_pos, alignment) + size;
600         }
601
602       skip_one_complete_type (reader->type_str, &reader->type_pos);
603     }
604   else
605     {
606       base_reader_next (reader, current_type);
607     }
608 }
609
610 static void
611 struct_reader_next (DBusTypeReader *reader,
612                     int             current_type)
613 {
614   int t;
615
616   struct_or_dict_entry_reader_next (reader, current_type);
617
618   /* for STRUCT containers we return FALSE at the end of the struct,
619    * for INVALID we return FALSE at the end of the signature.
620    * In both cases we arrange for get_current_type() to return INVALID
621    * which is defined to happen iff we're at the end (no more next())
622    */
623   t = _dbus_string_get_byte (reader->type_str, reader->type_pos);
624   if (t == DBUS_STRUCT_END_CHAR)
625     {
626       reader->type_pos += 1;
627       reader->finished = TRUE;
628     }
629 }
630
631 static void
632 body_reader_next (DBusTypeReader *reader,
633                   int             current_type)
634 {
635   if (reader->gvariant)
636     struct_reader_next (reader, current_type);
637   else
638     base_reader_next (reader, current_type);
639 }
640
641 static void
642 dict_entry_reader_next (DBusTypeReader *reader,
643                         int             current_type)
644 {
645   int t;
646
647   struct_or_dict_entry_reader_next (reader, current_type);
648
649   /* for STRUCT containers we return FALSE at the end of the struct,
650    * for INVALID we return FALSE at the end of the signature.
651    * In both cases we arrange for get_current_type() to return INVALID
652    * which is defined to happen iff we're at the end (no more next())
653    */
654   t = _dbus_string_get_byte (reader->type_str, reader->type_pos);
655   if (t == DBUS_DICT_ENTRY_END_CHAR)
656     {
657       reader->type_pos += 1;
658       reader->finished = TRUE;
659     }
660 }
661
662 static void
663 array_types_only_reader_next (DBusTypeReader *reader,
664                               int             current_type)
665 {
666   /* We have one "element" to be iterated over
667    * in each array, which is its element type.
668    * So the finished flag indicates whether we've
669    * iterated over it yet or not.
670    */
671   reader->finished = TRUE;
672 }
673
674 static void
675 array_reader_next (DBusTypeReader *reader,
676                    int             current_type)
677 {
678   /* Skip one array element */
679   int end_pos;
680
681   if (reader->gvariant)
682     {
683       int alignment;
684       int size = _dbus_reader_get_type_fixed_size (reader, &alignment);
685       if (0 == size)
686         {
687           /* variable size - use offsets - BUT consider also alignment,
688              because elements in the array might have alignment requirements.
689            */
690           reader->value_pos = _DBUS_ALIGN_VALUE(_dbus_reader_get_offset_of_end_of_variable (reader), alignment);
691           reader->variable_index++;
692           reader->finished = (reader->variable_index >= reader->n_offsets);
693         }
694       else
695         {
696           /* fixed size - move on; consider alignment */
697           reader->value_pos = _DBUS_ALIGN_VALUE(reader->value_pos, alignment) + size;
698           reader->finished = ((size_t)reader->value_pos >= reader->value_end);
699         }
700       return;
701     }
702
703   end_pos = reader->u.array.start_pos + array_reader_get_array_len (reader);
704
705 #if RECURSIVE_MARSHAL_READ_TRACE
706   _dbus_verbose ("  reader %p array next START start_pos = %d end_pos = %d value_pos = %d current_type = %s\n",
707                  reader,
708                  reader->u.array.start_pos,
709                  end_pos, reader->value_pos,
710                  _dbus_type_to_string (current_type));
711 #endif
712
713   _dbus_assert (reader->value_pos < end_pos);
714   _dbus_assert (reader->value_pos >= reader->u.array.start_pos);
715
716   switch (_dbus_first_type_in_signature (reader->type_str,
717                                          reader->type_pos))
718     {
719     case DBUS_TYPE_DICT_ENTRY:
720     case DBUS_TYPE_STRUCT:
721     case DBUS_TYPE_VARIANT:
722       {
723         DBusTypeReader sub;
724
725         /* Recurse into the struct or variant */
726         _dbus_type_reader_recurse (reader, &sub);
727
728         /* Skip everything in this element */
729         while (_dbus_type_reader_next (&sub))
730           {
731             /* nothing */;
732           }
733
734         /* Now we are at the end of this element */
735         reader->value_pos = sub.value_pos;
736       }
737       break;
738
739     case DBUS_TYPE_ARRAY:
740       {
741         _dbus_marshal_skip_array (reader->value_str,
742                                   _dbus_first_type_in_signature (reader->type_str,
743                                                            reader->type_pos + 1),
744                                   reader->byte_order,
745                                   &reader->value_pos);
746       }
747       break;
748
749     default:
750       {
751         _dbus_marshal_skip_basic (reader->value_str,
752                                   current_type, reader->byte_order,
753                                   &reader->value_pos);
754       }
755       break;
756     }
757
758 #if RECURSIVE_MARSHAL_READ_TRACE
759   _dbus_verbose ("  reader %p array next END start_pos = %d end_pos = %d value_pos = %d current_type = %s\n",
760                  reader,
761                  reader->u.array.start_pos,
762                  end_pos, reader->value_pos,
763                  _dbus_type_to_string (current_type));
764 #endif
765
766   _dbus_assert (reader->value_pos <= end_pos);
767
768   if (reader->value_pos == end_pos)
769     {
770       skip_one_complete_type (reader->type_str,
771                               &reader->type_pos);
772     }
773 }
774
775 static void
776 variant_reader_next (DBusTypeReader *reader,
777                      int             current_type)
778 {
779   if (reader->gvariant)
780     {
781       if (!reader->klass->types_only)
782         reader->value_pos = reader->value_end;
783
784       reader->type_pos += 1;
785
786       reader->finished = TRUE;
787
788       reader->variable_index++;
789     }
790   else
791     {
792       base_reader_next (reader, current_type);
793     }
794 }
795
796 static const DBusTypeReaderClass body_reader_class = {
797   "body", 0,
798   FALSE,
799   NULL, /* body is always toplevel, so doesn't get recursed into */
800   NULL,
801   body_reader_next
802 };
803
804 static const DBusTypeReaderClass body_types_only_reader_class = {
805   "body types", 1,
806   TRUE,
807   NULL, /* body is always toplevel, so doesn't get recursed into */
808   NULL,
809   body_reader_next
810 };
811
812 static const DBusTypeReaderClass struct_reader_class = {
813   "struct", 2,
814   FALSE,
815   struct_or_dict_entry_reader_recurse,
816   NULL,
817   struct_reader_next
818 };
819
820 static const DBusTypeReaderClass struct_types_only_reader_class = {
821   "struct types", 3,
822   TRUE,
823   struct_or_dict_entry_types_only_reader_recurse,
824   NULL,
825   struct_reader_next
826 };
827
828 static const DBusTypeReaderClass dict_entry_reader_class = {
829   "dict_entry", 4,
830   FALSE,
831   struct_or_dict_entry_reader_recurse,
832   NULL,
833   dict_entry_reader_next
834 };
835
836 static const DBusTypeReaderClass dict_entry_types_only_reader_class = {
837   "dict_entry types", 5,
838   TRUE,
839   struct_or_dict_entry_types_only_reader_recurse,
840   NULL,
841   dict_entry_reader_next
842 };
843
844 static const DBusTypeReaderClass array_reader_class = {
845   "array", 6,
846   FALSE,
847   array_reader_recurse,
848   array_reader_check_finished,
849   array_reader_next
850 };
851
852 static const DBusTypeReaderClass array_types_only_reader_class = {
853   "array types", 7,
854   TRUE,
855   array_types_only_reader_recurse,
856   NULL,
857   array_types_only_reader_next
858 };
859
860 static const DBusTypeReaderClass variant_reader_class = {
861   "variant", 8,
862   FALSE,
863   variant_reader_recurse,
864   NULL,
865   variant_reader_next
866 };
867
868 #ifndef DBUS_DISABLE_ASSERT
869 static const DBusTypeReaderClass * const
870 all_reader_classes[] = {
871   &body_reader_class,
872   &body_types_only_reader_class,
873   &struct_reader_class,
874   &struct_types_only_reader_class,
875   &dict_entry_reader_class,
876   &dict_entry_types_only_reader_class,
877   &array_reader_class,
878   &array_types_only_reader_class,
879   &variant_reader_class
880 };
881 #endif
882
883 /**
884  * Initializes a type reader.
885  *
886  * @param reader the reader
887  * @param byte_order the byte order of the block to read
888  * @param type_str the signature of the block to read
889  * @param type_pos location of signature
890  * @param value_str the string containing values block
891  * @param value_pos start of values block
892  */
893 void
894 _dbus_type_reader_init (DBusTypeReader    *reader,
895                         int                byte_order,
896                         const DBusString  *type_str,
897                         int                type_pos,
898                         const DBusString  *value_str,
899                         int                value_pos)
900 {
901   reader_init (reader, byte_order, type_str, type_pos,
902                value_str, value_pos, FALSE);
903
904   reader->klass = &body_reader_class;
905
906 #if RECURSIVE_MARSHAL_READ_TRACE
907   _dbus_verbose ("  type reader %p init type_pos = %d value_pos = %d remaining sig '%s'\n",
908                  reader, reader->type_pos, reader->value_pos,
909                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
910 #endif
911 }
912
913 /**
914  * Like _dbus_type_reader_init() but the iteration is over the
915  * signature, not over values.
916  *
917  * @param reader the reader
918  * @param type_str the signature string
919  * @param type_pos location in the signature string
920  */
921 void
922 _dbus_type_reader_init_types_only (DBusTypeReader    *reader,
923                                    const DBusString  *type_str,
924                                    int                type_pos)
925 {
926   reader_init (reader, DBUS_COMPILER_BYTE_ORDER /* irrelevant */,
927                type_str, type_pos, NULL, _DBUS_INT_MAX /* crashes if we screw up */,
928                FALSE);
929
930   reader->klass = &body_types_only_reader_class;
931
932 #if RECURSIVE_MARSHAL_READ_TRACE
933   _dbus_verbose ("  type reader %p init types only type_pos = %d remaining sig '%s'\n",
934                  reader, reader->type_pos,
935                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
936 #endif
937 }
938
939 /**
940  * Gets the type of the value the reader is currently pointing to;
941  * or for a types-only reader gets the type it's currently pointing to.
942  * If the reader is at the end of a block or end of a container such
943  * as an array, returns #DBUS_TYPE_INVALID.
944  *
945  * @param reader the reader
946  */
947 int
948 _dbus_type_reader_get_current_type (const DBusTypeReader *reader)
949 {
950   int t;
951
952   if (reader->finished ||
953       (reader->klass->check_finished &&
954        (* reader->klass->check_finished) (reader)))
955     t = DBUS_TYPE_INVALID;
956   else
957     t = _dbus_first_type_in_signature (reader->type_str,
958                                        reader->type_pos);
959
960   _dbus_assert (t != DBUS_STRUCT_END_CHAR);
961   _dbus_assert (t != DBUS_STRUCT_BEGIN_CHAR);
962   _dbus_assert (t != DBUS_DICT_ENTRY_END_CHAR);
963   _dbus_assert (t != DBUS_DICT_ENTRY_BEGIN_CHAR);
964   
965 #if 0
966   _dbus_verbose ("  type reader %p current type_pos = %d type = %s\n",
967                  reader, reader->type_pos,
968                  _dbus_type_to_string (t));
969 #endif
970
971   return t;
972 }
973
974 /**
975  * Gets the type of an element of the array the reader is currently
976  * pointing to. It's an error to call this if
977  * _dbus_type_reader_get_current_type() doesn't return #DBUS_TYPE_ARRAY
978  * for this reader.
979  *
980  * @param reader the reader
981  */
982 int
983 _dbus_type_reader_get_element_type (const DBusTypeReader  *reader)
984 {
985   int element_type;
986
987   _dbus_assert (_dbus_type_reader_get_current_type (reader) == DBUS_TYPE_ARRAY);
988
989   element_type = _dbus_first_type_in_signature (reader->type_str,
990                                           reader->type_pos + 1);
991
992   return element_type;
993 }
994
995 /**
996  * Gets the current position in the value block
997  * @param reader the reader
998  */
999 int
1000 _dbus_type_reader_get_value_pos (const DBusTypeReader  *reader)
1001 {
1002   return reader->value_pos;
1003 }
1004
1005 /**
1006  * Get the address of the marshaled value in the data being read.  The
1007  * address may not be aligned; you have to align it to the type of the
1008  * value you want to read. Most of the demarshal routines do this for
1009  * you.
1010  *
1011  * @param reader the reader
1012  * @param value_location the address of the marshaled value
1013  */
1014 void
1015 _dbus_type_reader_read_raw (const DBusTypeReader  *reader,
1016                             const unsigned char  **value_location)
1017 {
1018   _dbus_assert (!reader->klass->types_only);
1019
1020   *value_location = _dbus_string_get_const_udata_len (reader->value_str,
1021                                                       reader->value_pos,
1022                                                       0);
1023 }
1024
1025 /**
1026  * Reads a basic-typed value, as with _dbus_marshal_read_basic().
1027  *
1028  * @param reader the reader
1029  * @param value the address of the value
1030  */
1031 void
1032 _dbus_type_reader_read_basic (const DBusTypeReader    *reader,
1033                               void                    *value)
1034 {
1035   int t;
1036
1037   _dbus_assert (!reader->klass->types_only);
1038
1039   t = _dbus_type_reader_get_current_type (reader);
1040
1041   (reader->gvariant ? _dbus_marshal_read_gvariant_basic : _dbus_marshal_read_basic) (
1042                             reader->value_str,
1043                             reader->value_pos,
1044                             t, value,
1045                             reader->byte_order,
1046                             NULL);
1047
1048
1049 #if RECURSIVE_MARSHAL_READ_TRACE
1050   _dbus_verbose ("  type reader %p read basic type_pos = %d value_pos = %d remaining sig '%s'\n",
1051                  reader, reader->type_pos, reader->value_pos,
1052                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
1053 #endif
1054 }
1055
1056 /**
1057  * Returns the number of bytes in the array.
1058  *
1059  * @param reader the reader to read from
1060  * @returns the number of bytes in the array
1061  */
1062 int
1063 _dbus_type_reader_get_array_length (const DBusTypeReader  *reader)
1064 {
1065   _dbus_assert (!reader->klass->types_only);
1066   _dbus_assert (reader->klass == &array_reader_class);
1067
1068   return array_reader_get_array_len (reader);
1069 }
1070
1071 /**
1072  * Reads a block of fixed-length basic values, from the current point
1073  * in an array to the end of the array.  Does not work for arrays of
1074  * string or container types.
1075  *
1076  * This function returns the array in-place; it does not make a copy,
1077  * and it does not swap the bytes.
1078  *
1079  * If you ask for #DBUS_TYPE_DOUBLE you will get a "const double*" back
1080  * and the "value" argument should be a "const double**" and so on.
1081  *
1082  * @param reader the reader to read from
1083  * @param value place to return the array values
1084  * @param n_elements place to return number of array elements
1085  */
1086 void
1087 _dbus_type_reader_read_fixed_multi (const DBusTypeReader  *reader,
1088                                     void                  *value,
1089                                     int                   *n_elements)
1090 {
1091   int element_type;
1092   int end_pos;
1093   int remaining_len;
1094   int alignment;
1095   int total_len;
1096
1097   _dbus_assert (!reader->klass->types_only);
1098   _dbus_assert (reader->klass == &array_reader_class);
1099
1100   element_type = _dbus_first_type_in_signature (reader->type_str,
1101                                                 reader->type_pos);
1102
1103   _dbus_assert (element_type != DBUS_TYPE_INVALID); /* why we don't use get_current_type() */
1104   _dbus_assert (dbus_type_is_fixed (element_type));
1105
1106   alignment = _dbus_type_get_alignment (element_type);
1107
1108   _dbus_assert (reader->value_pos >= reader->u.array.start_pos);
1109
1110   total_len = array_reader_get_array_len (reader);
1111   end_pos = reader->u.array.start_pos + total_len;
1112   remaining_len = end_pos - reader->value_pos;
1113
1114 #if RECURSIVE_MARSHAL_READ_TRACE
1115   _dbus_verbose ("end_pos %d total_len %d remaining_len %d value_pos %d\n",
1116                  end_pos, total_len, remaining_len, reader->value_pos);
1117 #endif
1118
1119   _dbus_assert (remaining_len <= total_len);
1120
1121   if (remaining_len == 0)
1122     *(const DBusBasicValue**) value = NULL;
1123   else
1124     *(const DBusBasicValue**) value =
1125       (void*) _dbus_string_get_const_data_len (reader->value_str,
1126                                                reader->value_pos,
1127                                                remaining_len);
1128
1129   *n_elements = remaining_len / alignment;
1130   _dbus_assert ((remaining_len % alignment) == 0);
1131
1132 #if RECURSIVE_MARSHAL_READ_TRACE
1133   _dbus_verbose ("  type reader %p read fixed array type_pos = %d value_pos = %d remaining sig '%s'\n",
1134                  reader, reader->type_pos, reader->value_pos,
1135                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
1136 #endif
1137 }
1138
1139 /**
1140  * Initialize a new reader pointing to the first type and
1141  * corresponding value that's a child of the current container. It's
1142  * an error to call this if the current type is a non-container.
1143  *
1144  * Note that DBusTypeReader traverses values, not types. So if you
1145  * have an empty array of array of int, you can't recurse into it. You
1146  * can only recurse into each element.
1147  *
1148  * @param reader the reader
1149  * @param sub a reader to init pointing to the first child
1150  */
1151 void
1152 _dbus_type_reader_recurse (DBusTypeReader *reader,
1153                            DBusTypeReader *sub)
1154 {
1155   int t;
1156   const DBusTypeReaderClass *klass = NULL;
1157
1158   t = _dbus_first_type_in_signature (reader->type_str, reader->type_pos);
1159
1160   switch (t)
1161     {
1162     case DBUS_TYPE_STRUCT:
1163       if (reader->klass->types_only)
1164         klass = &struct_types_only_reader_class;
1165       else
1166         klass = &struct_reader_class;
1167       break;
1168     case DBUS_TYPE_DICT_ENTRY:
1169       if (reader->klass->types_only)
1170         klass = &dict_entry_types_only_reader_class;
1171       else
1172         klass = &dict_entry_reader_class;
1173       break;
1174     case DBUS_TYPE_ARRAY:
1175       if (reader->klass->types_only)
1176         klass = &array_types_only_reader_class;
1177       else
1178         klass = &array_reader_class;
1179       break;
1180     case DBUS_TYPE_VARIANT:
1181       if (reader->klass->types_only)
1182         _dbus_assert_not_reached ("can't recurse into variant typecode");
1183       else
1184         klass = &variant_reader_class;
1185       break;
1186     default:
1187       _dbus_verbose ("recursing into type %s\n", _dbus_type_to_string (t));
1188 #ifndef DBUS_DISABLE_CHECKS
1189       if (t == DBUS_TYPE_INVALID)
1190         _dbus_warn_check_failed ("You can't recurse into an empty array or off the end of a message body");
1191 #endif /* DBUS_DISABLE_CHECKS */
1192
1193       _dbus_assert_not_reached ("don't yet handle recursing into this type");
1194     }
1195
1196   _dbus_assert (klass != NULL);
1197   _dbus_assert (klass == all_reader_classes[klass->id]);
1198
1199   (* klass->recurse) (sub, reader);
1200   sub->klass = klass;
1201
1202 #if RECURSIVE_MARSHAL_READ_TRACE
1203   _dbus_verbose ("  type reader %p RECURSED type_pos = %d value_pos = %d remaining sig '%s'\n",
1204                  sub, sub->type_pos, sub->value_pos,
1205                  _dbus_string_get_const_data_len (sub->type_str, sub->type_pos, 0));
1206 #endif
1207 }
1208
1209 /**
1210  * Skip to the next value on this "level". e.g. the next field in a
1211  * struct, the next value in an array. Returns FALSE at the end of the
1212  * current container.
1213  *
1214  * @param reader the reader
1215  * @returns FALSE if nothing more to read at or below this level
1216  */
1217 dbus_bool_t
1218 _dbus_type_reader_next (DBusTypeReader *reader)
1219 {
1220   int t;
1221
1222   t = _dbus_type_reader_get_current_type (reader);
1223
1224 #if RECURSIVE_MARSHAL_READ_TRACE
1225   _dbus_verbose ("  type reader %p START next() { type_pos = %d value_pos = %d remaining sig '%s' current_type = %s\n",
1226                  reader, reader->type_pos, reader->value_pos,
1227                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0),
1228                  _dbus_type_to_string (t));
1229 #endif
1230
1231   if (t == DBUS_TYPE_INVALID)
1232     return FALSE;
1233
1234   (* reader->klass->next) (reader, t);
1235
1236 #if RECURSIVE_MARSHAL_READ_TRACE
1237   _dbus_verbose ("  type reader %p END next() type_pos = %d value_pos = %d remaining sig '%s' current_type = %s\n",
1238                  reader, reader->type_pos, reader->value_pos,
1239                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0),
1240                  _dbus_type_to_string (_dbus_type_reader_get_current_type (reader)));
1241 #endif
1242
1243   return _dbus_type_reader_get_current_type (reader) != DBUS_TYPE_INVALID;
1244 }
1245
1246 /**
1247  * Check whether there's another value on this "level". e.g. the next
1248  * field in a struct, the next value in an array. Returns FALSE at the
1249  * end of the current container.
1250  *
1251  * You probably don't want to use this; it makes for an awkward for/while
1252  * loop. A nicer one is "while ((current_type = get_current_type()) != INVALID)"
1253  *
1254  * @param reader the reader
1255  * @returns FALSE if nothing more to read at or below this level
1256  */
1257 dbus_bool_t
1258 _dbus_type_reader_has_next (const DBusTypeReader *reader)
1259 {
1260   /* Not efficient but works for now. */
1261   DBusTypeReader copy;
1262
1263   copy = *reader;
1264   return _dbus_type_reader_next (&copy);
1265 }
1266
1267 /**
1268  * Gets the string and range of said string containing the signature
1269  * of the current value. Essentially a more complete version of
1270  * _dbus_type_reader_get_current_type() (returns the full type
1271  * rather than only the outside of the onion).
1272  *
1273  * Note though that the first byte in a struct signature is
1274  * #DBUS_STRUCT_BEGIN_CHAR while the current type will be
1275  * #DBUS_TYPE_STRUCT so it isn't true that the first byte of the
1276  * signature is always the same as the current type. Another
1277  * difference is that this function will still return a signature when
1278  * inside an empty array; say you recurse into empty array of int32,
1279  * the signature is "i" but the current type will always be
1280  * #DBUS_TYPE_INVALID since there are no elements to be currently
1281  * pointing to.
1282  *
1283  * @param reader the reader
1284  * @param str_p place to return the string with the type in it
1285  * @param start_p place to return start of the type
1286  * @param len_p place to return the length of the type
1287  */
1288 void
1289 _dbus_type_reader_get_signature (const DBusTypeReader  *reader,
1290                                  const DBusString     **str_p,
1291                                  int                   *start_p,
1292                                  int                   *len_p)
1293 {
1294   *str_p = reader->type_str;
1295   *start_p = reader->type_pos;
1296   *len_p = find_len_of_complete_type (reader->type_str, reader->type_pos);
1297 }
1298
1299 typedef struct
1300 {
1301   DBusString replacement; /**< Marshaled value including alignment padding */
1302   int padding;            /**< How much of the replacement block is padding */
1303 } ReplacementBlock;
1304
1305 static dbus_bool_t
1306 replacement_block_init (ReplacementBlock *block,
1307                         DBusTypeReader   *reader)
1308 {
1309   if (!_dbus_string_init (&block->replacement))
1310     return FALSE;
1311
1312   /* % 8 is the padding to have the same align properties in
1313    * our replacement string as we do at the position being replaced
1314    */
1315   block->padding = reader->value_pos % 8;
1316
1317   if (!_dbus_string_lengthen (&block->replacement, block->padding))
1318     goto oom;
1319
1320   return TRUE;
1321
1322  oom:
1323   _dbus_string_free (&block->replacement);
1324   return FALSE;
1325 }
1326
1327 static dbus_bool_t
1328 replacement_block_replace (ReplacementBlock     *block,
1329                            DBusTypeReader       *reader,
1330                            const DBusTypeReader *realign_root)
1331 {
1332   DBusTypeWriter writer;
1333   DBusTypeReader realign_reader;
1334   DBusList *fixups;
1335   int orig_len;
1336
1337   _dbus_assert (realign_root != NULL);
1338
1339   orig_len = _dbus_string_get_length (&block->replacement);
1340
1341   realign_reader = *realign_root;
1342
1343 #if RECURSIVE_MARSHAL_WRITE_TRACE
1344   _dbus_verbose ("INITIALIZING replacement block writer %p at value_pos %d\n",
1345                  &writer, _dbus_string_get_length (&block->replacement));
1346 #endif
1347   _dbus_type_writer_init_values_only (&writer,
1348                                       realign_reader.byte_order,
1349                                       realign_reader.type_str,
1350                                       realign_reader.type_pos,
1351                                       &block->replacement,
1352                                       _dbus_string_get_length (&block->replacement));
1353
1354   _dbus_assert (realign_reader.value_pos <= reader->value_pos);
1355
1356 #if RECURSIVE_MARSHAL_WRITE_TRACE
1357   _dbus_verbose ("COPYING from reader at value_pos %d to writer %p starting after value_pos %d\n",
1358                  realign_reader.value_pos, &writer, reader->value_pos);
1359 #endif
1360   fixups = NULL;
1361   if (!_dbus_type_writer_write_reader_partial (&writer,
1362                                                &realign_reader,
1363                                                reader,
1364                                                block->padding,
1365                                                _dbus_string_get_length (&block->replacement) - block->padding,
1366                                                &fixups))
1367     goto oom;
1368
1369 #if RECURSIVE_MARSHAL_WRITE_TRACE
1370   _dbus_verbose ("REPLACEMENT at padding %d len %d\n", block->padding,
1371                  _dbus_string_get_length (&block->replacement) - block->padding);
1372   _dbus_verbose_bytes_of_string (&block->replacement, block->padding,
1373                                  _dbus_string_get_length (&block->replacement) - block->padding);
1374   _dbus_verbose ("TO BE REPLACED at value_pos = %d (align pad %d) len %d realign_reader.value_pos %d\n",
1375                  reader->value_pos, reader->value_pos % 8,
1376                  realign_reader.value_pos - reader->value_pos,
1377                  realign_reader.value_pos);
1378   _dbus_verbose_bytes_of_string (reader->value_str,
1379                                  reader->value_pos,
1380                                  realign_reader.value_pos - reader->value_pos);
1381 #endif
1382
1383   /* Move the replacement into position
1384    * (realign_reader should now be at the end of the block to be replaced)
1385    */
1386   if (!_dbus_string_replace_len (&block->replacement, block->padding,
1387                                  _dbus_string_get_length (&block->replacement) - block->padding,
1388                                  (DBusString*) reader->value_str,
1389                                  reader->value_pos,
1390                                  realign_reader.value_pos - reader->value_pos))
1391     goto oom;
1392
1393   /* Process our fixups now that we can't have an OOM error */
1394   apply_and_free_fixups (&fixups, reader);
1395
1396   return TRUE;
1397
1398  oom:
1399   _dbus_string_set_length (&block->replacement, orig_len);
1400   free_fixups (&fixups);
1401   return FALSE;
1402 }
1403
1404 static void
1405 replacement_block_free (ReplacementBlock *block)
1406 {
1407   _dbus_string_free (&block->replacement);
1408 }
1409
1410 /* In the variable-length case, we have to fix alignment after we insert.
1411  * The strategy is as follows:
1412  *
1413  *  - pad a new string to have the same alignment as the
1414  *    start of the current basic value
1415  *  - write the new basic value
1416  *  - copy from the original reader to the new string,
1417  *    which will fix the alignment of types following
1418  *    the new value
1419  *    - this copy has to start at realign_root,
1420  *      but not really write anything until it
1421  *      passes the value being set
1422  *    - as an optimization, we can stop copying
1423  *      when the source and dest values are both
1424  *      on an 8-boundary, since we know all following
1425  *      padding and alignment will be identical
1426  *  - copy the new string back to the original
1427  *    string, replacing the relevant part of the
1428  *    original string
1429  *  - now any arrays in the original string that
1430  *    contained the replaced string may have the
1431  *    wrong length; so we have to fix that
1432  */
1433 static dbus_bool_t
1434 reader_set_basic_variable_length (DBusTypeReader       *reader,
1435                                   int                   current_type,
1436                                   const void           *value,
1437                                   const DBusTypeReader *realign_root)
1438 {
1439   dbus_bool_t retval;
1440   ReplacementBlock block;
1441   DBusTypeWriter writer;
1442
1443   _dbus_assert (realign_root != NULL);
1444
1445   retval = FALSE;
1446
1447   if (!replacement_block_init (&block, reader))
1448     return FALSE;
1449
1450   /* Write the new basic value */
1451 #if RECURSIVE_MARSHAL_WRITE_TRACE
1452   _dbus_verbose ("INITIALIZING writer %p to write basic value at value_pos %d of replacement string\n",
1453                  &writer, _dbus_string_get_length (&block.replacement));
1454 #endif
1455   _dbus_type_writer_init_values_only (&writer,
1456                                       reader->byte_order,
1457                                       reader->type_str,
1458                                       reader->type_pos,
1459                                       &block.replacement,
1460                                       _dbus_string_get_length (&block.replacement));
1461 #if RECURSIVE_MARSHAL_WRITE_TRACE
1462   _dbus_verbose ("WRITING basic value to writer %p (replacement string)\n", &writer);
1463 #endif
1464   if (!_dbus_type_writer_write_basic (&writer, current_type, value))
1465     goto out;
1466
1467   if (!replacement_block_replace (&block,
1468                                   reader,
1469                                   realign_root))
1470     goto out;
1471
1472   retval = TRUE;
1473
1474  out:
1475   replacement_block_free (&block);
1476   return retval;
1477 }
1478
1479 static void
1480 reader_set_basic_fixed_length (DBusTypeReader *reader,
1481                                int             current_type,
1482                                const void     *value)
1483 {
1484   _dbus_marshal_set_basic ((DBusString*) reader->value_str,
1485                            reader->value_pos,
1486                            current_type,
1487                            value,
1488                            reader->byte_order,
1489                            NULL, NULL);
1490 }
1491
1492 /**
1493  * Sets a new value for the basic type value pointed to by the reader,
1494  * leaving the reader valid to continue reading. Any other readers
1495  * will be invalidated if you set a variable-length type such as a
1496  * string.
1497  *
1498  * The provided realign_root is the reader to start from when
1499  * realigning the data that follows the newly-set value. The reader
1500  * parameter must point to a value below the realign_root parameter.
1501  * If the type being set is fixed-length, then realign_root may be
1502  * #NULL. Only values reachable from realign_root will be realigned,
1503  * so if your string contains other values you will need to deal with
1504  * those somehow yourself. It is OK if realign_root is the same
1505  * reader as the reader parameter, though if you aren't setting the
1506  * root it may not be such a good idea.
1507  *
1508  * @todo DBusTypeReader currently takes "const" versions of the type
1509  * and value strings, and this function modifies those strings by
1510  * casting away the const, which is of course bad if we want to get
1511  * picky. (To be truly clean you'd have an object which contained the
1512  * type and value strings and set_basic would be a method on that
1513  * object... this would also make DBusTypeReader the same thing as
1514  * DBusTypeMark. But since DBusMessage is effectively that object for
1515  * D-Bus it doesn't seem worth creating some random object.)
1516  *
1517  * @todo optimize this by only rewriting until the old and new values
1518  * are at the same alignment. Frequently this should result in only
1519  * replacing the value that's immediately at hand.
1520  *
1521  * @param reader reader indicating where to set a new value
1522  * @param value address of the value to set
1523  * @param realign_root realign from here
1524  * @returns #FALSE if not enough memory
1525  */
1526 dbus_bool_t
1527 _dbus_type_reader_set_basic (DBusTypeReader       *reader,
1528                              const void           *value,
1529                              const DBusTypeReader *realign_root)
1530 {
1531   int current_type;
1532
1533   _dbus_assert (!reader->klass->types_only);
1534   _dbus_assert (reader->value_str == realign_root->value_str);
1535   _dbus_assert (reader->value_pos >= realign_root->value_pos);
1536
1537   current_type = _dbus_type_reader_get_current_type (reader);
1538
1539 #if RECURSIVE_MARSHAL_WRITE_TRACE
1540   _dbus_verbose ("  SET BASIC type reader %p type_pos = %d value_pos = %d remaining sig '%s' realign_root = %p with value_pos %d current_type = %s\n",
1541                  reader, reader->type_pos, reader->value_pos,
1542                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0),
1543                  realign_root,
1544                  realign_root ? realign_root->value_pos : -1,
1545                  _dbus_type_to_string (current_type));
1546   _dbus_verbose_bytes_of_string (realign_root->value_str, realign_root->value_pos,
1547                                  _dbus_string_get_length (realign_root->value_str) -
1548                                  realign_root->value_pos);
1549 #endif
1550
1551   _dbus_assert (dbus_type_is_basic (current_type));
1552
1553   if (dbus_type_is_fixed (current_type))
1554     {
1555       reader_set_basic_fixed_length (reader, current_type, value);
1556       return TRUE;
1557     }
1558   else
1559     {
1560       _dbus_assert (realign_root != NULL);
1561       return reader_set_basic_variable_length (reader, current_type,
1562                                                value, realign_root);
1563     }
1564 }
1565
1566 /**
1567  * Recursively deletes any value pointed to by the reader, leaving the
1568  * reader valid to continue reading. Any other readers will be
1569  * invalidated.
1570  *
1571  * The provided realign_root is the reader to start from when
1572  * realigning the data that follows the newly-set value.
1573  * See _dbus_type_reader_set_basic() for more details on the
1574  * realign_root paramter.
1575  *
1576  * @todo for now this does not delete the typecodes associated with
1577  * the value, so this function should only be used for array elements.
1578  *
1579  * @param reader reader indicating where to delete a value
1580  * @param realign_root realign from here
1581  * @returns #FALSE if not enough memory
1582  */
1583 dbus_bool_t
1584 _dbus_type_reader_delete (DBusTypeReader        *reader,
1585                           const DBusTypeReader  *realign_root)
1586 {
1587   dbus_bool_t retval;
1588   ReplacementBlock block;
1589
1590   _dbus_assert (realign_root != NULL);
1591   _dbus_assert (reader->klass == &array_reader_class);
1592
1593   retval = FALSE;
1594
1595   if (!replacement_block_init (&block, reader))
1596     return FALSE;
1597
1598   if (!replacement_block_replace (&block,
1599                                   reader,
1600                                   realign_root))
1601     goto out;
1602
1603   retval = TRUE;
1604
1605  out:
1606   replacement_block_free (&block);
1607   return retval;
1608 }
1609
1610 /*
1611  * Compares two readers, which must be iterating over the same value data.
1612  * Returns #TRUE if the first parameter is further along than the second parameter.
1613  *
1614  * @param lhs left-hand-side (first) parameter
1615  * @param rhs left-hand-side (first) parameter
1616  * @returns whether lhs is greater than rhs
1617  */
1618 static dbus_bool_t
1619 _dbus_type_reader_greater_than (const DBusTypeReader  *lhs,
1620                                 const DBusTypeReader  *rhs)
1621 {
1622   _dbus_assert (lhs->value_str == rhs->value_str);
1623
1624   return lhs->value_pos > rhs->value_pos;
1625 }
1626
1627 /*
1628  *
1629  *
1630  *         DBusTypeWriter
1631  *
1632  *
1633  *
1634  */
1635
1636 /**
1637  * Initialize a write iterator, which is used to write out values in
1638  * serialized D-Bus format.
1639  *
1640  * The type_pos passed in is expected to be inside an already-valid,
1641  * though potentially empty, type signature. This means that the byte
1642  * after type_pos must be either #DBUS_TYPE_INVALID (aka nul) or some
1643  * other valid type. #DBusTypeWriter won't enforce that the signature
1644  * is already valid (you can append the nul byte at the end if you
1645  * like), but just be aware that you need the nul byte eventually and
1646  * #DBusTypeWriter isn't going to write it for you.
1647  *
1648  * @param writer the writer to init
1649  * @param byte_order the byte order to marshal into
1650  * @param type_str the string to write typecodes into
1651  * @param type_pos where to insert typecodes
1652  * @param value_str the string to write values into
1653  * @param value_pos where to insert values
1654  *
1655  */
1656 void
1657 _dbus_type_writer_init (DBusTypeWriter *writer,
1658                         int             byte_order,
1659                         DBusString     *type_str,
1660                         int             type_pos,
1661                         DBusString     *value_str,
1662                         int             value_pos)
1663 {
1664   writer->byte_order = byte_order;
1665   writer->type_str = type_str;
1666   writer->type_pos = type_pos;
1667   writer->value_str = value_str;
1668   writer->value_pos = value_pos;
1669   writer->value_start = value_pos;
1670   writer->container_type = DBUS_TYPE_INVALID;
1671   writer->type_pos_is_expectation = FALSE;
1672   writer->enabled = TRUE;
1673   writer->gvariant = FALSE;
1674   writer->body_container = FALSE;
1675   writer->is_fixed = TRUE;
1676   writer->alignment = 1;
1677
1678 #if RECURSIVE_MARSHAL_WRITE_TRACE
1679   _dbus_verbose ("writer %p init remaining sig '%s'\n", writer,
1680                  writer->type_str ?
1681                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0) :
1682                  "unknown");
1683 #endif
1684 }
1685
1686 /**
1687  * Initialize a write iterator, with the signature to be provided
1688  * later.
1689  *
1690  * @param writer the writer to init
1691  * @param byte_order the byte order to marshal into
1692  * @param value_str the string to write values into
1693  * @param value_pos where to insert values
1694  *
1695  */
1696 void
1697 _dbus_type_writer_init_types_delayed (DBusTypeWriter *writer,
1698                                       int             byte_order,
1699                                       DBusString     *value_str,
1700                                       int             value_pos)
1701 {
1702   _dbus_type_writer_init (writer, byte_order,
1703                           NULL, 0, value_str, value_pos);
1704 }
1705
1706 /**
1707  * Initialize a write iterator, with the signature to be provided
1708  * later. Supports GVariant
1709  *
1710  * @param writer the writer to init
1711  * @param byte_order the byte order to marshal into
1712  * @param value_str the string to write values into
1713  * @param value_pos where to insert values
1714  * @param gvariant TRUE if append values with GVariant marshalling
1715  * @param last_offset pointer to root level offset of last variable-size value
1716  * @param last_pos pointer to root level position of offsets
1717  */
1718 void
1719 _dbus_type_writer_gvariant_init_types_delayed (DBusTypeWriter  *writer,
1720                                                int              byte_order,
1721                                                DBusString      *value_str,
1722                                                int              value_pos,
1723                                                dbus_bool_t      gvariant,
1724                                                size_t          *last_offset,
1725                                                size_t          *last_pos)
1726 {
1727   _dbus_type_writer_init (writer, byte_order,
1728                           NULL, 0, value_str, value_pos);
1729   writer->gvariant = gvariant;
1730   writer->body_container = TRUE;
1731   writer->is_fixed = TRUE;
1732   writer->alignment = 8;
1733   writer->u.root.last_offset = last_offset;
1734   writer->u.root.last_pos = last_pos;
1735   writer->offsets_size = 1;
1736   writer->offsets = NULL;
1737
1738   if (gvariant)
1739     {
1740       writer->value_pos = *last_pos;
1741       writer->value_start = 0;
1742     }
1743 }
1744
1745 /**
1746  * Adds type string to the writer, if it had none.
1747  *
1748  * @param writer the writer to init
1749  * @param type_str type string to add
1750  * @param type_pos type position
1751  *
1752  */
1753 void
1754 _dbus_type_writer_add_types (DBusTypeWriter *writer,
1755                              DBusString     *type_str,
1756                              int             type_pos)
1757 {
1758   if (writer->type_str == NULL) /* keeps us from using this as setter */
1759     {
1760       writer->type_str = type_str;
1761       writer->type_pos = type_pos;
1762     }
1763 }
1764
1765 /**
1766  * Removes type string from the writer.
1767  *
1768  * @param writer the writer to remove from
1769  */
1770 void
1771 _dbus_type_writer_remove_types (DBusTypeWriter *writer)
1772 {
1773   writer->type_str = NULL;
1774   writer->type_pos = -1;
1775 }
1776
1777 /**
1778  * Like _dbus_type_writer_init(), except the type string
1779  * passed in should correspond to an existing signature that
1780  * matches what you're going to write out. The writer will
1781  * check what you write vs. this existing signature.
1782  *
1783  * @param writer the writer to init
1784  * @param byte_order the byte order to marshal into
1785  * @param type_str the string with signature
1786  * @param type_pos start of signature
1787  * @param value_str the string to write values into
1788  * @param value_pos where to insert values
1789  *
1790  */
1791 void
1792 _dbus_type_writer_init_values_only (DBusTypeWriter   *writer,
1793                                     int               byte_order,
1794                                     const DBusString *type_str,
1795                                     int               type_pos,
1796                                     DBusString       *value_str,
1797                                     int               value_pos)
1798 {
1799   _dbus_type_writer_init (writer, byte_order,
1800                           (DBusString*)type_str, type_pos,
1801                           value_str, value_pos);
1802
1803   writer->type_pos_is_expectation = TRUE;
1804 }
1805
1806 static dbus_bool_t
1807 _dbus_type_writer_write_basic_no_typecode (DBusTypeWriter *writer,
1808                                            int             type,
1809                                            const void     *value)
1810 {
1811   if (writer->enabled)
1812     {
1813       if (writer->gvariant)
1814         {
1815           return _dbus_type_writer_gvariant_write_basic_no_typecode (writer, type, value);
1816         }
1817       else
1818         return _dbus_marshal_write_basic (writer->value_str,
1819                                           writer->value_pos,
1820                                           type,
1821                                           value,
1822                                           writer->byte_order,
1823                                           &writer->value_pos);
1824     }
1825   else
1826     return TRUE;
1827 }
1828
1829 /* If our parent is an array, things are a little bit complicated.
1830  *
1831  * The parent must have a complete element type, such as
1832  * "i" or "aai" or "(ii)" or "a(ii)". There can't be
1833  * unclosed parens, or an "a" with no following type.
1834  *
1835  * To recurse, the only allowed operation is to recurse into the
1836  * first type in the element type. So for "i" you can't recurse, for
1837  * "ai" you can recurse into the array, for "(ii)" you can recurse
1838  * into the struct.
1839  *
1840  * If you recurse into the array for "ai", then you must specify
1841  * "i" for the element type of the array you recurse into.
1842  *
1843  * While inside an array at any level, we need to avoid writing to
1844  * type_str, since the type only appears once for the whole array,
1845  * it does not appear for each array element.
1846  *
1847  * While inside an array type_pos points to the expected next
1848  * typecode, rather than the next place we could write a typecode.
1849  */
1850 static void
1851 writer_recurse_init_and_check (DBusTypeWriter *writer,
1852                                int             container_type,
1853                                DBusTypeWriter *sub)
1854 {
1855   _dbus_type_writer_init (sub,
1856                           writer->byte_order,
1857                           writer->type_str,
1858                           writer->type_pos,
1859                           writer->value_str,
1860                           writer->value_pos);
1861
1862   sub->container_type = container_type;
1863   sub->gvariant = writer->gvariant;
1864
1865   if (writer->type_pos_is_expectation ||
1866       (sub->container_type == DBUS_TYPE_ARRAY || sub->container_type == DBUS_TYPE_VARIANT))
1867     sub->type_pos_is_expectation = TRUE;
1868   else
1869     sub->type_pos_is_expectation = FALSE;
1870
1871   sub->enabled = writer->enabled;
1872
1873 #ifndef DBUS_DISABLE_CHECKS
1874   if (writer->type_pos_is_expectation && writer->type_str)
1875     {
1876       int expected;
1877
1878       expected = _dbus_first_type_in_signature (writer->type_str, writer->type_pos);
1879
1880       if (expected != sub->container_type)
1881         {
1882           if (expected != DBUS_TYPE_INVALID)
1883             _dbus_warn_check_failed ("Writing an element of type %s, but the expected type here is %s\n"
1884                                      "The overall signature expected here was '%s' and we are on byte %d of that signature.",
1885                                      _dbus_type_to_string (sub->container_type),
1886                                      _dbus_type_to_string (expected),
1887                                      _dbus_string_get_const_data (writer->type_str), writer->type_pos);
1888           else
1889             _dbus_warn_check_failed ("Writing an element of type %s, but no value is expected here\n"
1890                                      "The overall signature expected here was '%s' and we are on byte %d of that signature.",
1891                                      _dbus_type_to_string (sub->container_type),
1892                                      _dbus_string_get_const_data (writer->type_str), writer->type_pos);
1893           
1894           _dbus_assert_not_reached ("bad array element or variant content written");
1895         }
1896     }
1897 #endif /* DBUS_DISABLE_CHECKS */
1898
1899 #if RECURSIVE_MARSHAL_WRITE_TRACE
1900   _dbus_verbose ("  type writer %p recurse parent %s type_pos = %d value_pos = %d is_expectation = %d remaining sig '%s' enabled = %d\n",
1901                  writer,
1902                  _dbus_type_to_string (writer->container_type),
1903                  writer->type_pos, writer->value_pos, writer->type_pos_is_expectation,
1904                  writer->type_str ?
1905                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0) :
1906                  "unknown",
1907                  writer->enabled);
1908   _dbus_verbose ("  type writer %p recurse sub %s   type_pos = %d value_pos = %d is_expectation = %d enabled = %d\n",
1909                  sub,
1910                  _dbus_type_to_string (sub->container_type),
1911                  sub->type_pos, sub->value_pos,
1912                  sub->type_pos_is_expectation,
1913                  sub->enabled);
1914 #endif
1915 }
1916
1917 static dbus_bool_t
1918 write_or_verify_typecode (DBusTypeWriter *writer,
1919                           int             typecode)
1920 {
1921   /* A subwriter inside an array or variant will have type_pos
1922    * pointing to the expected typecode; a writer not inside an array
1923    * or variant has type_pos pointing to the next place to insert a
1924    * typecode.
1925    */
1926 #if RECURSIVE_MARSHAL_WRITE_TRACE
1927   _dbus_verbose ("  type writer %p write_or_verify start type_pos = %d remaining sig '%s' enabled = %d\n",
1928                  writer, writer->type_pos,
1929                  writer->type_str ?
1930                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0) :
1931                  "unknown",
1932                  writer->enabled);
1933 #endif
1934
1935   if (writer->type_str == NULL)
1936     return TRUE;
1937
1938   if (writer->type_pos_is_expectation)
1939     {
1940 #ifndef DBUS_DISABLE_CHECKS
1941       {
1942         int expected;
1943
1944         expected = _dbus_string_get_byte (writer->type_str, writer->type_pos);
1945
1946         if (expected != typecode)
1947           {
1948             if (expected != DBUS_TYPE_INVALID)
1949               _dbus_warn_check_failed ("Array or variant type requires that type %s be written, but %s was written.\n"
1950                                        "The overall signature expected here was '%s' and we are on byte %d of that signature.",
1951                                        _dbus_type_to_string (expected), _dbus_type_to_string (typecode),
1952                                        _dbus_string_get_const_data (writer->type_str), writer->type_pos);
1953             else
1954               _dbus_warn_check_failed ("Array or variant type wasn't expecting any more values to be written into it, but a value %s was written.\n"
1955                                        "The overall signature expected here was '%s' and we are on byte %d of that signature.",
1956                                        _dbus_type_to_string (typecode),
1957                                        _dbus_string_get_const_data (writer->type_str), writer->type_pos);
1958             _dbus_assert_not_reached ("bad type inserted somewhere inside an array or variant");
1959           }
1960       }
1961 #endif /* DBUS_DISABLE_CHECKS */
1962
1963       /* if immediately inside an array we'd always be appending an element,
1964        * so the expected type doesn't change; if inside a struct or something
1965        * below an array, we need to move through said struct or something.
1966        */
1967       if (writer->container_type != DBUS_TYPE_ARRAY)
1968         writer->type_pos += 1;
1969     }
1970   else
1971     {
1972       if (!_dbus_string_insert_byte (writer->type_str,
1973                                      writer->type_pos,
1974                                      typecode))
1975         return FALSE;
1976
1977       writer->type_pos += 1;
1978     }
1979
1980 #if RECURSIVE_MARSHAL_WRITE_TRACE
1981   _dbus_verbose ("  type writer %p write_or_verify end type_pos = %d remaining sig '%s'\n",
1982                  writer, writer->type_pos,
1983                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0));
1984 #endif
1985
1986   return TRUE;
1987 }
1988
1989 static dbus_bool_t
1990 writer_recurse_struct_or_dict_entry (DBusTypeWriter   *writer,
1991                                      int               begin_char,
1992                                      const DBusString *contained_type,
1993                                      int               contained_type_start,
1994                                      int               contained_type_len,
1995                                      DBusTypeWriter   *sub)
1996 {
1997   /* FIXME right now contained_type is ignored; we could probably
1998    * almost trivially fix the code so if it's present we
1999    * write it out and then set type_pos_is_expectation
2000    */
2001
2002   /* Ensure that we'll be able to add alignment padding and the typecode */
2003   if (writer->enabled)
2004     {
2005       if (!_dbus_string_alloc_space (sub->value_str, 8))
2006         return FALSE;
2007     }
2008
2009   if (!write_or_verify_typecode (sub, begin_char))
2010     _dbus_assert_not_reached ("failed to insert struct typecode after prealloc");
2011
2012   if (writer->enabled)
2013     {
2014       if (writer->gvariant)
2015         {
2016           sub->alignment = 1;
2017           sub->value_str = dbus_new (DBusString, 1);
2018           if (NULL == sub->value_str || !_dbus_string_init (sub->value_str))
2019             return FALSE;
2020           sub->value_start = sub->value_pos = 0;
2021           sub->u.struct_or_dict.last_offset = GVARIANT_LAST_OFFSET_NOT_SET;
2022           sub->offsets_size = 1;
2023           sub->is_fixed = TRUE;
2024           sub->offsets = dbus_new (DBusString, 1);
2025           _dbus_string_init (sub->offsets);
2026         }
2027       else
2028         {
2029           if (!_dbus_string_insert_bytes (sub->value_str,
2030                                           sub->value_pos,
2031                                           _DBUS_ALIGN_VALUE (sub->value_pos, 8) - sub->value_pos,
2032                                           '\0'))
2033             _dbus_assert_not_reached ("should not have failed to insert alignment padding for struct");
2034
2035           sub->value_pos =  _DBUS_ALIGN_VALUE (sub->value_pos, 8);
2036         }
2037     }
2038
2039   return TRUE;
2040 }
2041
2042
2043 static dbus_bool_t
2044 writer_recurse_array (DBusTypeWriter   *writer,
2045                       const DBusString *contained_type,
2046                       int               contained_type_start,
2047                       int               contained_type_len,
2048                       DBusTypeWriter   *sub,
2049                       dbus_bool_t       is_array_append)
2050 {
2051   dbus_uint32_t value = 0;
2052   int alignment;
2053   int aligned;
2054
2055 #ifndef DBUS_DISABLE_CHECKS
2056   if (writer->container_type == DBUS_TYPE_ARRAY &&
2057       writer->type_str)
2058     {
2059       if (!_dbus_string_equal_substring (contained_type,
2060                                          contained_type_start,
2061                                          contained_type_len,
2062                                          writer->type_str,
2063                                          writer->u.array.element_type_pos + 1))
2064         {
2065           _dbus_warn_check_failed ("Writing an array of '%s' but this is incompatible with the expected type of elements in the parent array",
2066                                    _dbus_string_get_const_data_len (contained_type,
2067                                                                     contained_type_start,
2068                                                                     contained_type_len));
2069           _dbus_assert_not_reached ("incompatible type for child array");
2070         }
2071     }
2072 #endif /* DBUS_DISABLE_CHECKS */
2073
2074   if (writer->enabled && !is_array_append)
2075     {
2076       /* 3 pad + 4 bytes for the array length, and 4 bytes possible padding
2077        * before array values
2078        */
2079       if (!_dbus_string_alloc_space (sub->value_str, 3 + 4 + 4))
2080         return FALSE;
2081     }
2082
2083   if (writer->type_str != NULL)
2084     {
2085       sub->type_pos += 1; /* move to point to the element type, since type_pos
2086                            * should be the expected type for further writes
2087                            */
2088       sub->u.array.element_type_pos = sub->type_pos;
2089     }
2090
2091   if (!writer->type_pos_is_expectation)
2092     {
2093       /* sub is a toplevel/outermost array so we need to write the type data */
2094
2095       /* alloc space for array typecode, element signature */
2096       if (!_dbus_string_alloc_space (writer->type_str, 1 + contained_type_len))
2097         return FALSE;
2098
2099       if (!_dbus_string_insert_byte (writer->type_str,
2100                                      writer->type_pos,
2101                                      DBUS_TYPE_ARRAY))
2102         _dbus_assert_not_reached ("failed to insert array typecode after prealloc");
2103
2104       if (!_dbus_string_copy_len (contained_type,
2105                                   contained_type_start, contained_type_len,
2106                                   sub->type_str,
2107                                   sub->u.array.element_type_pos))
2108         _dbus_assert_not_reached ("should not have failed to insert array element typecodes");
2109     }
2110
2111   if (writer->type_str != NULL)
2112     {
2113       /* If the parent is an array, we hold type_pos pointing at the array element type;
2114        * otherwise advance it to reflect the array value we just recursed into
2115        */
2116       if (writer->container_type != DBUS_TYPE_ARRAY)
2117         writer->type_pos += 1 + contained_type_len;
2118       else
2119         _dbus_assert (writer->type_pos_is_expectation); /* because it's an array */
2120     }
2121
2122   if (writer->enabled)
2123     {
2124       if (!writer->gvariant)
2125         {
2126           /* Write (or jump over, if is_array_append) the length */
2127           sub->u.array.len_pos = _DBUS_ALIGN_VALUE (sub->value_pos, 4);
2128
2129           if (is_array_append)
2130           {
2131             sub->value_pos += 4;
2132           }
2133           else
2134           {
2135             if (!_dbus_type_writer_write_basic_no_typecode (sub, DBUS_TYPE_UINT32, &value))
2136               _dbus_assert_not_reached ("should not have failed to insert array len");
2137           }
2138
2139           _dbus_assert (sub->u.array.len_pos == sub->value_pos - 4);
2140         }
2141
2142       /* Write alignment padding for array elements
2143        * Note that we write the padding *even for empty arrays*
2144        * to avoid wonky special cases
2145        */
2146       if (writer->gvariant)
2147         {
2148           int size = _dbus_type_gvariant_get_fixed_size (contained_type, contained_type_start, &alignment);
2149           if (0 == size)
2150             {
2151               sub->offsets_size = 1;
2152               sub->offsets = dbus_new (DBusString, 1);
2153               if (sub->offsets == NULL || !_dbus_string_init (sub->offsets))
2154                 return FALSE;
2155             }
2156           else
2157             {
2158               sub->offsets_size = 0;
2159               sub->offsets = NULL;
2160             }
2161         }
2162       else
2163       {
2164         alignment = element_type_get_alignment (contained_type, contained_type_start);
2165       }
2166
2167       aligned = _DBUS_ALIGN_VALUE (sub->value_pos, alignment);
2168       if (aligned != sub->value_pos)
2169         {
2170           if (!is_array_append)
2171             {
2172               if (!_dbus_string_insert_bytes (sub->value_str,
2173                                               sub->value_pos,
2174                                               aligned - sub->value_pos,
2175                                               '\0'))
2176                 _dbus_assert_not_reached ("should not have failed to insert alignment padding");
2177             }
2178
2179           sub->value_pos = aligned;
2180         }
2181
2182       sub->u.array.start_pos = sub->value_pos;
2183
2184       if (is_array_append && !writer->gvariant)
2185         {
2186           dbus_uint32_t len;
2187
2188           _dbus_assert (_DBUS_ALIGN_VALUE (sub->u.array.len_pos, 4) ==
2189                         (unsigned) sub->u.array.len_pos);
2190           len = _dbus_unpack_uint32 (sub->byte_order,
2191                                      _dbus_string_get_const_udata_len (sub->value_str,
2192                                                                       sub->u.array.len_pos,
2193                                                                       4));
2194
2195           sub->value_pos += len;
2196         }
2197       if (writer->gvariant)
2198         {
2199           sub->alignment = alignment;
2200           sub->is_fixed = FALSE;
2201           sub->value_start = sub->value_pos;
2202         }
2203     }
2204   else
2205     {
2206       /* not enabled, so we won't write the len_pos; set it to -1 to so indicate */
2207       sub->u.array.len_pos = -1;
2208       sub->u.array.start_pos = sub->value_pos;
2209     }
2210
2211   _dbus_assert (sub->gvariant || sub->u.array.len_pos < sub->u.array.start_pos);
2212   _dbus_assert (is_array_append || sub->u.array.start_pos == sub->value_pos);
2213
2214 #if RECURSIVE_MARSHAL_WRITE_TRACE
2215       _dbus_verbose ("  type writer %p recurse array done remaining sig '%s' array start_pos = %d len_pos = %d value_pos = %d\n", sub,
2216                      sub->type_str ?
2217                      _dbus_string_get_const_data_len (sub->type_str, sub->type_pos, 0) :
2218                      "unknown",
2219                      sub->u.array.start_pos, sub->u.array.len_pos, sub->value_pos);
2220 #endif
2221
2222   return TRUE;
2223 }
2224
2225 /* Variant value will normally have:
2226  *   1 byte signature length not including nul
2227  *   signature typecodes (nul terminated)
2228  *   padding to alignment of contained type
2229  *   body according to signature
2230  *
2231  * The signature string can only have a single type
2232  * in it but that type may be complex/recursive.
2233  *
2234  * So a typical variant type with the integer 3 will have these
2235  * octets:
2236  *   0x1 'i' '\0' [1 byte padding to alignment boundary] 0x0 0x0 0x0 0x3
2237  *
2238  * The main world of hurt for writing out a variant is that the type
2239  * string is the same string as the value string. Which means
2240  * inserting to the type string will move the value_pos; and it means
2241  * that inserting to the type string could break type alignment.
2242  */
2243 static dbus_bool_t
2244 writer_recurse_variant (DBusTypeWriter   *writer,
2245                         const DBusString *contained_type,
2246                         int               contained_type_start,
2247                         int               contained_type_len,
2248                         DBusTypeWriter   *sub)
2249 {
2250   int contained_alignment;
2251   
2252   if (writer->enabled)
2253     {
2254       /* Allocate space for the worst case, which is 1 byte sig
2255        * length, nul byte at end of sig, and 7 bytes padding to
2256        * 8-boundary.
2257        */
2258       if (!_dbus_string_alloc_space (sub->value_str, contained_type_len + 9))
2259         return FALSE;
2260     }
2261
2262   /* write VARIANT typecode to the parent's type string */
2263   if (!write_or_verify_typecode (writer, DBUS_TYPE_VARIANT))
2264     return FALSE;
2265
2266   /* If not enabled, mark that we have no type_str anymore ... */
2267
2268   if (!writer->enabled)
2269     {
2270       sub->type_str = NULL;
2271       sub->type_pos = -1;
2272
2273       return TRUE;
2274     }
2275
2276   /* If we're enabled then continue ... */
2277
2278   if (writer->gvariant)
2279     {
2280       /* GVariant case:
2281        * contents, then nul byte, then signature without nul byte.
2282        * The alignment is always 8.
2283        *
2284        * Signature is at the end of a variant. So, the easiest way is to write it down
2285        * when unrecursing. So, we need to copy it to a new string.
2286        */
2287       contained_alignment = 8;
2288       sub->alignment = 8;
2289       sub->type_str = dbus_new (DBusString, 1); /* to be deallocated on unrecurse */
2290       sub->type_pos = 0;
2291       sub->is_fixed = FALSE;
2292       _dbus_string_init_preallocated (sub->type_str, contained_type_len);
2293
2294       if (!_dbus_string_copy_len (contained_type, contained_type_start, contained_type_len,
2295                                   sub->type_str, sub->type_pos))
2296         _dbus_assert_not_reached ("should not have failed to insert variant type sig");
2297     }
2298   else
2299     {
2300       /* dbus1 case:
2301        * length, signature with nul byte, then contents
2302        * alignment depends on contents.
2303        */
2304       if (!_dbus_string_insert_byte (sub->value_str,
2305                                      sub->value_pos,
2306                                      contained_type_len))
2307         _dbus_assert_not_reached ("should not have failed to insert variant type sig len");
2308
2309       sub->value_pos += 1;
2310
2311       /* Here we switch over to the expected type sig we're about to write */
2312       sub->type_str = sub->value_str;
2313       sub->type_pos = sub->value_pos;
2314
2315       if (!_dbus_string_copy_len (contained_type, contained_type_start, contained_type_len,
2316                                   sub->value_str, sub->value_pos))
2317         _dbus_assert_not_reached ("should not have failed to insert variant type sig");
2318
2319       sub->value_pos += contained_type_len;
2320
2321       if (!_dbus_string_insert_byte (sub->value_str,
2322                                      sub->value_pos,
2323                                      DBUS_TYPE_INVALID))
2324         _dbus_assert_not_reached ("should not have failed to insert variant type nul termination");
2325
2326       sub->value_pos += 1;
2327
2328       contained_alignment = _dbus_type_get_alignment (_dbus_first_type_in_signature (contained_type, contained_type_start));
2329     }
2330   
2331   if (!_dbus_string_insert_bytes (sub->value_str,
2332                                   sub->value_pos,
2333                                   _DBUS_ALIGN_VALUE (sub->value_pos, contained_alignment) - sub->value_pos,
2334                                   '\0'))
2335     _dbus_assert_not_reached ("should not have failed to insert alignment padding for variant body");
2336   sub->value_pos = _DBUS_ALIGN_VALUE (sub->value_pos, contained_alignment);
2337   sub->value_start = sub->value_pos;
2338
2339   return TRUE;
2340 }
2341
2342 static dbus_bool_t
2343 _dbus_type_writer_recurse_contained_len (DBusTypeWriter   *writer,
2344                                          int               container_type,
2345                                          const DBusString *contained_type,
2346                                          int               contained_type_start,
2347                                          int               contained_type_len,
2348                                          DBusTypeWriter   *sub,
2349                                          dbus_bool_t       is_array_append)
2350 {
2351   writer_recurse_init_and_check (writer, container_type, sub);
2352
2353   switch (container_type)
2354     {
2355     case DBUS_TYPE_STRUCT:
2356       return writer_recurse_struct_or_dict_entry (writer,
2357                                                   DBUS_STRUCT_BEGIN_CHAR,
2358                                                   contained_type,
2359                                                   contained_type_start, contained_type_len,
2360                                                   sub);
2361       break;
2362     case DBUS_TYPE_DICT_ENTRY:
2363       return writer_recurse_struct_or_dict_entry (writer,
2364                                                   DBUS_DICT_ENTRY_BEGIN_CHAR,
2365                                                   contained_type,
2366                                                   contained_type_start, contained_type_len,
2367                                                   sub);
2368       break;
2369     case DBUS_TYPE_ARRAY:
2370       return writer_recurse_array (writer,
2371                                    contained_type, contained_type_start, contained_type_len,
2372                                    sub, is_array_append);
2373       break;
2374     case DBUS_TYPE_VARIANT:
2375       return writer_recurse_variant (writer,
2376                                      contained_type, contained_type_start, contained_type_len,
2377                                      sub);
2378       break;
2379     default:
2380       _dbus_assert_not_reached ("tried to recurse into type that doesn't support that");
2381       return FALSE;
2382       break;
2383     }
2384 }
2385
2386 /**
2387  * Opens a new container and writes out the initial information for that container.
2388  *
2389  * @param writer the writer
2390  * @param container_type the type of the container to open
2391  * @param contained_type the array element type or variant content type
2392  * @param contained_type_start position to look for the type
2393  * @param sub the new sub-writer to write container contents
2394  * @returns #FALSE if no memory
2395  */
2396 dbus_bool_t
2397 _dbus_type_writer_recurse (DBusTypeWriter   *writer,
2398                            int               container_type,
2399                            const DBusString *contained_type,
2400                            int               contained_type_start,
2401                            DBusTypeWriter   *sub)
2402 {
2403   int contained_type_len;
2404
2405   if (contained_type)
2406     contained_type_len = find_len_of_complete_type (contained_type, contained_type_start);
2407   else
2408     contained_type_len = 0;
2409
2410   sub->body_container = FALSE;
2411
2412   return _dbus_type_writer_recurse_contained_len (writer, container_type,
2413                                                   contained_type,
2414                                                   contained_type_start,
2415                                                   contained_type_len,
2416                                                   sub,
2417                                                   FALSE);
2418 }
2419
2420 /**
2421  * Append to an existing array. Essentially, the writer will read an
2422  * existing length at the write location; jump over that length; and
2423  * write new fields. On unrecurse(), the existing length will be
2424  * updated.
2425  *
2426  * @param writer the writer
2427  * @param contained_type element type
2428  * @param contained_type_start position of element type
2429  * @param sub the subwriter to init
2430  * @returns #FALSE if no memory
2431  */
2432 dbus_bool_t
2433 _dbus_type_writer_append_array (DBusTypeWriter   *writer,
2434                                 const DBusString *contained_type,
2435                                 int               contained_type_start,
2436                                 DBusTypeWriter   *sub)
2437 {
2438   int contained_type_len;
2439
2440   if (contained_type)
2441     contained_type_len = find_len_of_complete_type (contained_type, contained_type_start);
2442   else
2443     contained_type_len = 0;
2444
2445   return _dbus_type_writer_recurse_contained_len (writer, DBUS_TYPE_ARRAY,
2446                                                   contained_type,
2447                                                   contained_type_start,
2448                                                   contained_type_len,
2449                                                   sub,
2450                                                   TRUE);
2451 }
2452
2453 static int
2454 writer_get_array_len (DBusTypeWriter *writer)
2455 {
2456   _dbus_assert (writer->container_type == DBUS_TYPE_ARRAY);
2457   return writer->value_pos - writer->u.array.start_pos;
2458 }
2459
2460 static dbus_bool_t
2461 _dbus_type_writer_unrecurse_write (DBusTypeWriter *writer,
2462                                    DBusTypeWriter *sub)
2463 {
2464   if (sub->container_type == DBUS_TYPE_STRUCT)
2465     {
2466       if (!write_or_verify_typecode (sub, DBUS_STRUCT_END_CHAR))
2467         return FALSE;
2468     }
2469   else if (sub->container_type == DBUS_TYPE_DICT_ENTRY)
2470     {
2471       if (!write_or_verify_typecode (sub, DBUS_DICT_ENTRY_END_CHAR))
2472         return FALSE;
2473     }
2474   else if (sub->container_type == DBUS_TYPE_ARRAY && !sub->gvariant)
2475     {
2476       if (sub->u.array.len_pos >= 0) /* len_pos == -1 if we weren't enabled when we passed it */
2477         {
2478           dbus_uint32_t len;
2479
2480           /* Set the array length */
2481           len = writer_get_array_len (sub);
2482           _dbus_marshal_set_uint32 (sub->value_str,
2483                                     sub->u.array.len_pos,
2484                                     len,
2485                                     sub->byte_order);
2486 #if RECURSIVE_MARSHAL_WRITE_TRACE
2487           _dbus_verbose ("    filled in sub array len to %u at len_pos %d\n",
2488                          len, sub->u.array.len_pos);
2489 #endif
2490         }
2491 #if RECURSIVE_MARSHAL_WRITE_TRACE
2492       else
2493         {
2494           _dbus_verbose ("    not filling in sub array len because we were disabled when we passed the len\n");
2495         }
2496 #endif
2497     }
2498   return TRUE;
2499 }
2500
2501 /**
2502  * Closes a container created by _dbus_type_writer_recurse()
2503  * and writes any additional information to the values block.
2504  *
2505  * @param writer the writer
2506  * @param sub the sub-writer created by _dbus_type_writer_recurse()
2507  * @returns #FALSE if no memory
2508  */
2509 dbus_bool_t
2510 _dbus_type_writer_unrecurse (DBusTypeWriter *writer,
2511                              DBusTypeWriter *sub)
2512 {
2513   /* type_pos_is_expectation never gets unset once set, or we'd get all hosed */
2514   _dbus_assert (!writer->type_pos_is_expectation ||
2515                 (writer->type_pos_is_expectation && sub->type_pos_is_expectation));
2516
2517 #if RECURSIVE_MARSHAL_WRITE_TRACE
2518   _dbus_verbose ("  type writer %p unrecurse type_pos = %d value_pos = %d is_expectation = %d container_type = %s\n",
2519                  writer, writer->type_pos, writer->value_pos, writer->type_pos_is_expectation,
2520                  _dbus_type_to_string (writer->container_type));
2521   _dbus_verbose ("  type writer %p unrecurse sub type_pos = %d value_pos = %d is_expectation = %d container_type = %s\n",
2522                  sub, sub->type_pos, sub->value_pos,
2523                  sub->type_pos_is_expectation,
2524                  _dbus_type_to_string (sub->container_type));
2525 #endif
2526
2527   if (!_dbus_type_writer_unrecurse_write (writer, sub))
2528     return FALSE;
2529
2530   if (writer->gvariant)
2531     {
2532       if (!_dbus_writer_unrecurse_gvariant_write (writer, sub))
2533         return FALSE;
2534     }
2535   else
2536     writer->value_pos = sub->value_pos;
2537
2538
2539   /* Now get type_pos right for the parent writer. Here are the cases:
2540    *
2541    * Cases !writer->type_pos_is_expectation:
2542    *   (in these cases we want to update to the new insertion point)
2543    *
2544    * - if we recursed into a STRUCT then we didn't know in advance
2545    *   what the types in the struct would be; so we have to fill in
2546    *   that information now.
2547    *       writer->type_pos = sub->type_pos
2548    *
2549    * - if we recursed into anything else, we knew the full array
2550    *   type, or knew the single typecode marking VARIANT, so
2551    *   writer->type_pos is already correct.
2552    *       writer->type_pos should remain as-is
2553    *
2554    * - note that the parent is never an ARRAY or VARIANT, if it were
2555    *   then type_pos_is_expectation would be TRUE. The parent
2556    *   is thus known to be a toplevel or STRUCT.
2557    *
2558    * Cases where writer->type_pos_is_expectation:
2559    *   (in these cases we want to update to next expected type to write)
2560    *
2561    * - we recursed from STRUCT into STRUCT and we didn't increment
2562    *   type_pos in the parent just to stay consistent with the
2563    *   !writer->type_pos_is_expectation case (though we could
2564    *   special-case this in recurse_struct instead if we wanted)
2565    *       writer->type_pos = sub->type_pos
2566    *
2567    * - we recursed from STRUCT into ARRAY or VARIANT and type_pos
2568    *   for parent should have been incremented already
2569    *       writer->type_pos should remain as-is
2570    *
2571    * - we recursed from ARRAY into a sub-element, so type_pos in the
2572    *   parent is the element type and should remain the element type
2573    *   for the benefit of the next child element
2574    *       writer->type_pos should remain as-is
2575    *
2576    * - we recursed from VARIANT into its value, so type_pos in the
2577    *   parent makes no difference since there's only one value
2578    *   and we just finished writing it and won't use type_pos again
2579    *       writer->type_pos should remain as-is
2580    *
2581    *
2582    * For all these, DICT_ENTRY is the same as STRUCT
2583    */
2584   if (writer->type_str != NULL)
2585     {
2586       if ((sub->container_type == DBUS_TYPE_STRUCT ||
2587            sub->container_type == DBUS_TYPE_DICT_ENTRY) &&
2588           (writer->container_type == DBUS_TYPE_STRUCT ||
2589            writer->container_type == DBUS_TYPE_DICT_ENTRY ||
2590            writer->container_type == DBUS_TYPE_INVALID))
2591         {
2592           /* Advance the parent to the next struct field */
2593           writer->type_pos = sub->type_pos;
2594         }
2595     }
2596
2597 #if RECURSIVE_MARSHAL_WRITE_TRACE
2598   _dbus_verbose ("  type writer %p unrecursed type_pos = %d value_pos = %d remaining sig '%s'\n",
2599                  writer, writer->type_pos, writer->value_pos,
2600                  writer->type_str ?
2601                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0) :
2602                  "unknown");
2603 #endif
2604
2605   return TRUE;
2606 }
2607
2608 /**
2609  * Writes out a basic type.
2610  *
2611  * @param writer the writer
2612  * @param type the type to write
2613  * @param value the address of the value to write
2614  * @returns #FALSE if no memory
2615  */
2616 dbus_bool_t
2617 _dbus_type_writer_write_basic (DBusTypeWriter *writer,
2618                                int             type,
2619                                const void     *value)
2620 {
2621   dbus_bool_t retval;
2622
2623   /* First ensure that our type realloc will succeed */
2624   if (!writer->type_pos_is_expectation && writer->type_str != NULL)
2625     {
2626       if (!_dbus_string_alloc_space (writer->type_str, 1))
2627         return FALSE;
2628     }
2629
2630   retval = FALSE;
2631
2632   if (!_dbus_type_writer_write_basic_no_typecode (writer, type, value))
2633     goto out;
2634
2635   if (!write_or_verify_typecode (writer, type))
2636     _dbus_assert_not_reached ("failed to write typecode after prealloc");
2637
2638   retval = TRUE;
2639
2640  out:
2641 #if RECURSIVE_MARSHAL_WRITE_TRACE
2642   _dbus_verbose ("  type writer %p basic type_pos = %d value_pos = %d is_expectation = %d enabled = %d\n",
2643                  writer, writer->type_pos, writer->value_pos, writer->type_pos_is_expectation,
2644                  writer->enabled);
2645 #endif
2646
2647   return retval;
2648 }
2649
2650 /**
2651  * Writes a block of fixed-length basic values, i.e. those that are
2652  * both dbus_type_is_fixed() and _dbus_type_is_basic(). The block
2653  * must be written inside an array.
2654  *
2655  * The value parameter should be the address of said array of values,
2656  * so e.g. if it's an array of double, pass in "const double**"
2657  *
2658  * @param writer the writer
2659  * @param element_type type of stuff in the array
2660  * @param value address of the array
2661  * @param n_elements number of elements in the array
2662  * @returns #FALSE if no memory
2663  */
2664 dbus_bool_t
2665 _dbus_type_writer_write_fixed_multi (DBusTypeWriter        *writer,
2666                                      int                    element_type,
2667                                      const void            *value,
2668                                      int                    n_elements)
2669 {
2670   _dbus_assert (writer->container_type == DBUS_TYPE_ARRAY);
2671   _dbus_assert (dbus_type_is_fixed (element_type));
2672   _dbus_assert (writer->type_pos_is_expectation);
2673   _dbus_assert (n_elements >= 0);
2674
2675 #if RECURSIVE_MARSHAL_WRITE_TRACE
2676   _dbus_verbose ("  type writer %p entering fixed multi type_pos = %d value_pos = %d n_elements %d\n",
2677                  writer, writer->type_pos, writer->value_pos, n_elements);
2678 #endif
2679
2680   if (!write_or_verify_typecode (writer, element_type))
2681     _dbus_assert_not_reached ("OOM should not happen if only verifying typecode");
2682
2683   if (writer->enabled)
2684     {
2685       if (!_dbus_marshal_write_fixed_multi (writer->value_str,
2686                                             writer->value_pos,
2687                                             element_type,
2688                                             value,
2689                                             n_elements,
2690                                             writer->byte_order,
2691                                             &writer->value_pos))
2692         return FALSE;
2693     }
2694
2695 #if RECURSIVE_MARSHAL_WRITE_TRACE
2696   _dbus_verbose ("  type writer %p fixed multi written new type_pos = %d new value_pos = %d n_elements %d\n",
2697                  writer, writer->type_pos, writer->value_pos, n_elements);
2698 #endif
2699
2700   return TRUE;
2701 }
2702
2703 static void
2704 enable_if_after (DBusTypeWriter       *writer,
2705                  DBusTypeReader       *reader,
2706                  const DBusTypeReader *start_after)
2707 {
2708   if (start_after)
2709     {
2710       if (!writer->enabled && _dbus_type_reader_greater_than (reader, start_after))
2711         {
2712           _dbus_type_writer_set_enabled (writer, TRUE);
2713 #if RECURSIVE_MARSHAL_WRITE_TRACE
2714           _dbus_verbose ("ENABLING writer %p at %d because reader at value_pos %d is after reader at value_pos %d\n",
2715                          writer, writer->value_pos, reader->value_pos, start_after->value_pos);
2716 #endif
2717         }
2718
2719       _dbus_assert ((!writer->enabled && !_dbus_type_reader_greater_than (reader, start_after)) ||
2720                     (writer->enabled && _dbus_type_reader_greater_than (reader, start_after)));
2721     }
2722 }
2723
2724 static dbus_bool_t
2725 append_fixup (DBusList               **fixups,
2726               const DBusArrayLenFixup *fixup)
2727 {
2728   DBusArrayLenFixup *f;
2729
2730   f = dbus_new (DBusArrayLenFixup, 1);
2731   if (f == NULL)
2732     return FALSE;
2733
2734   *f = *fixup;
2735
2736   if (!_dbus_list_append (fixups, f))
2737     {
2738       dbus_free (f);
2739       return FALSE;
2740     }
2741
2742   _dbus_assert (f->len_pos_in_reader == fixup->len_pos_in_reader);
2743   _dbus_assert (f->new_len == fixup->new_len);
2744
2745   return TRUE;
2746 }
2747
2748 /* This loop is trivial if you ignore all the start_after nonsense,
2749  * so if you're trying to figure it out, start by ignoring that
2750  */
2751 static dbus_bool_t
2752 writer_write_reader_helper (DBusTypeWriter       *writer,
2753                             DBusTypeReader       *reader,
2754                             const DBusTypeReader *start_after,
2755                             int                   start_after_new_pos,
2756                             int                   start_after_new_len,
2757                             DBusList            **fixups,
2758                             dbus_bool_t           inside_start_after)
2759 {
2760   int current_type;
2761
2762   while ((current_type = _dbus_type_reader_get_current_type (reader)) != DBUS_TYPE_INVALID)
2763     {
2764       if (dbus_type_is_container (current_type))
2765         {
2766           DBusTypeReader subreader;
2767           DBusTypeWriter subwriter;
2768           const DBusString *sig_str;
2769           int sig_start;
2770           int sig_len;
2771           dbus_bool_t enabled_at_recurse;
2772           dbus_bool_t past_start_after;
2773           int reader_array_len_pos;
2774           int reader_array_start_pos;
2775           dbus_bool_t this_is_start_after;
2776
2777           /* type_pos is checked since e.g. in a struct the struct
2778            * and its first field have the same value_pos.
2779            * type_str will differ in reader/start_after for variants
2780            * where type_str is inside the value_str
2781            */
2782           if (!inside_start_after && start_after &&
2783               reader->value_pos == start_after->value_pos &&
2784               reader->type_str == start_after->type_str &&
2785               reader->type_pos == start_after->type_pos)
2786             this_is_start_after = TRUE;
2787           else
2788             this_is_start_after = FALSE;
2789
2790           _dbus_type_reader_recurse (reader, &subreader);
2791
2792           if (current_type == DBUS_TYPE_ARRAY)
2793             {
2794               reader_array_len_pos = ARRAY_READER_LEN_POS (&subreader);
2795               reader_array_start_pos = subreader.u.array.start_pos;
2796             }
2797           else
2798             {
2799               /* quiet gcc */
2800               reader_array_len_pos = -1;
2801               reader_array_start_pos = -1;
2802             }
2803
2804           _dbus_type_reader_get_signature (&subreader, &sig_str,
2805                                            &sig_start, &sig_len);
2806
2807 #if RECURSIVE_MARSHAL_WRITE_TRACE
2808           _dbus_verbose ("about to recurse into %s reader at %d subreader at %d writer at %d start_after reader at %d write target len %d inside_start_after = %d this_is_start_after = %d\n",
2809                          _dbus_type_to_string (current_type),
2810                          reader->value_pos,
2811                          subreader.value_pos,
2812                          writer->value_pos,
2813                          start_after ? start_after->value_pos : -1,
2814                          _dbus_string_get_length (writer->value_str),
2815                          inside_start_after, this_is_start_after);
2816 #endif
2817
2818           if (!inside_start_after && !this_is_start_after)
2819             enable_if_after (writer, &subreader, start_after);
2820           enabled_at_recurse = writer->enabled;
2821           if (!_dbus_type_writer_recurse_contained_len (writer, current_type,
2822                                                         sig_str, sig_start, sig_len,
2823                                                         &subwriter, FALSE))
2824             goto oom;
2825
2826 #if RECURSIVE_MARSHAL_WRITE_TRACE
2827           _dbus_verbose ("recursed into subwriter at %d write target len %d\n",
2828                          subwriter.value_pos,
2829                          _dbus_string_get_length (subwriter.value_str));
2830 #endif
2831
2832           if (!writer_write_reader_helper (&subwriter, &subreader, start_after,
2833                                            start_after_new_pos, start_after_new_len,
2834                                            fixups,
2835                                            inside_start_after ||
2836                                            this_is_start_after))
2837             goto oom;
2838
2839 #if RECURSIVE_MARSHAL_WRITE_TRACE
2840           _dbus_verbose ("about to unrecurse from %s subreader at %d writer at %d subwriter at %d  write target len %d\n",
2841                          _dbus_type_to_string (current_type),
2842                          subreader.value_pos,
2843                          writer->value_pos,
2844                          subwriter.value_pos,
2845                          _dbus_string_get_length (writer->value_str));
2846 #endif
2847
2848           if (!inside_start_after && !this_is_start_after)
2849             enable_if_after (writer, &subreader, start_after);
2850           past_start_after = writer->enabled;
2851           if (!_dbus_type_writer_unrecurse (writer, &subwriter))
2852             goto oom;
2853
2854           /* If we weren't enabled when we recursed, we didn't
2855            * write an array len; if we passed start_after
2856            * somewhere inside the array, then we need to generate
2857            * a fixup.
2858            */
2859           if (start_after != NULL &&
2860               !enabled_at_recurse && past_start_after &&
2861               current_type == DBUS_TYPE_ARRAY &&
2862               fixups != NULL)
2863             {
2864               DBusArrayLenFixup fixup;
2865               int bytes_written_after_start_after;
2866               int bytes_before_start_after;
2867               int old_len;
2868
2869               /* this subwriter access is moderately unkosher since we
2870                * already unrecursed, but it works as long as unrecurse
2871                * doesn't break us on purpose
2872                */
2873               bytes_written_after_start_after = writer_get_array_len (&subwriter);
2874
2875               bytes_before_start_after =
2876                 start_after->value_pos - reader_array_start_pos;
2877
2878               fixup.len_pos_in_reader = reader_array_len_pos;
2879               fixup.new_len =
2880                 bytes_before_start_after +
2881                 start_after_new_len +
2882                 bytes_written_after_start_after;
2883
2884               _dbus_assert (_DBUS_ALIGN_VALUE (fixup.len_pos_in_reader, 4) ==
2885                             (unsigned) fixup.len_pos_in_reader);
2886
2887               old_len = _dbus_unpack_uint32 (reader->byte_order,
2888                                              _dbus_string_get_const_udata_len (reader->value_str,
2889                                                                               fixup.len_pos_in_reader, 4));
2890
2891               if (old_len != fixup.new_len && !append_fixup (fixups, &fixup))
2892                 goto oom;
2893
2894 #if RECURSIVE_MARSHAL_WRITE_TRACE
2895               _dbus_verbose ("Generated fixup len_pos_in_reader = %d new_len = %d reader_array_start_pos = %d start_after->value_pos = %d bytes_before_start_after = %d start_after_new_len = %d bytes_written_after_start_after = %d\n",
2896                              fixup.len_pos_in_reader,
2897                              fixup.new_len,
2898                              reader_array_start_pos,
2899                              start_after->value_pos,
2900                              bytes_before_start_after,
2901                              start_after_new_len,
2902                              bytes_written_after_start_after);
2903 #endif
2904             }
2905         }
2906       else
2907         {
2908           DBusBasicValue val;
2909
2910           _dbus_assert (dbus_type_is_basic (current_type));
2911
2912 #if RECURSIVE_MARSHAL_WRITE_TRACE
2913           _dbus_verbose ("Reading basic value %s at %d\n",
2914                          _dbus_type_to_string (current_type),
2915                          reader->value_pos);
2916 #endif
2917
2918           _dbus_type_reader_read_basic (reader, &val);
2919
2920 #if RECURSIVE_MARSHAL_WRITE_TRACE
2921           _dbus_verbose ("Writing basic value %s at %d write target len %d inside_start_after = %d\n",
2922                          _dbus_type_to_string (current_type),
2923                          writer->value_pos,
2924                          _dbus_string_get_length (writer->value_str),
2925                          inside_start_after);
2926 #endif
2927           if (!inside_start_after)
2928             enable_if_after (writer, reader, start_after);
2929           if (!_dbus_type_writer_write_basic (writer, current_type, &val))
2930             goto oom;
2931 #if RECURSIVE_MARSHAL_WRITE_TRACE
2932           _dbus_verbose ("Wrote basic value %s, new value_pos %d write target len %d\n",
2933                          _dbus_type_to_string (current_type),
2934                          writer->value_pos,
2935                          _dbus_string_get_length (writer->value_str));
2936 #endif
2937         }
2938
2939       _dbus_type_reader_next (reader);
2940     }
2941
2942   return TRUE;
2943
2944  oom:
2945   if (fixups)
2946     apply_and_free_fixups (fixups, NULL); /* NULL for reader to apply to */
2947
2948   return FALSE;
2949 }
2950
2951 /*
2952  * Iterate through all values in the given reader, writing a copy of
2953  * each value to the writer.  The reader will be moved forward to its
2954  * end position.
2955  *
2956  * If a reader start_after is provided, it should be a reader for the
2957  * same data as the reader to be written. Only values occurring after
2958  * the value pointed to by start_after will be written to the writer.
2959  *
2960  * If start_after is provided, then the copy of the reader will be
2961  * partial. This means that array lengths will not have been copied.
2962  * The assumption is that you wrote a new version of the value at
2963  * start_after to the writer. You have to pass in the start position
2964  * and length of the new value. (If you are deleting the value
2965  * at start_after, pass in 0 for the length.)
2966  *
2967  * If the fixups parameter is non-#NULL, then any array length that
2968  * was read but not written due to start_after will be provided
2969  * as a #DBusArrayLenFixup. The fixup contains the position of the
2970  * array length in the source data, and the correct array length
2971  * assuming you combine the source data before start_after with
2972  * the written data at start_after and beyond.
2973  *
2974  * @param writer the writer to copy to
2975  * @param reader the reader to copy from
2976  * @param start_after #NULL or a reader showing where to start
2977  * @param start_after_new_pos the position of start_after equivalent in the target data
2978  * @param start_after_new_len the length of start_after equivalent in the target data
2979  * @param fixups list to append #DBusArrayLenFixup if the write was partial
2980  * @returns #FALSE if no memory
2981  */
2982 static dbus_bool_t
2983 _dbus_type_writer_write_reader_partial (DBusTypeWriter       *writer,
2984                                         DBusTypeReader       *reader,
2985                                         const DBusTypeReader *start_after,
2986                                         int                   start_after_new_pos,
2987                                         int                   start_after_new_len,
2988                                         DBusList            **fixups)
2989 {
2990   DBusTypeWriter orig;
2991   int orig_type_len;
2992   int orig_value_len;
2993   int new_bytes;
2994   int orig_enabled;
2995
2996   orig = *writer;
2997   orig_type_len = _dbus_string_get_length (writer->type_str);
2998   orig_value_len = _dbus_string_get_length (writer->value_str);
2999   orig_enabled = writer->enabled;
3000
3001   if (start_after)
3002     _dbus_type_writer_set_enabled (writer, FALSE);
3003
3004   if (!writer_write_reader_helper (writer, reader, start_after,
3005                                    start_after_new_pos,
3006                                    start_after_new_len,
3007                                    fixups, FALSE))
3008     goto oom;
3009
3010   _dbus_type_writer_set_enabled (writer, orig_enabled);
3011   return TRUE;
3012
3013  oom:
3014   if (!writer->type_pos_is_expectation)
3015     {
3016       new_bytes = _dbus_string_get_length (writer->type_str) - orig_type_len;
3017       _dbus_string_delete (writer->type_str, orig.type_pos, new_bytes);
3018     }
3019   new_bytes = _dbus_string_get_length (writer->value_str) - orig_value_len;
3020   _dbus_string_delete (writer->value_str, orig.value_pos, new_bytes);
3021
3022   *writer = orig;
3023
3024   return FALSE;
3025 }
3026
3027 /**
3028  * Iterate through all values in the given reader, writing a copy of
3029  * each value to the writer.  The reader will be moved forward to its
3030  * end position.
3031  *
3032  * @param writer the writer to copy to
3033  * @param reader the reader to copy from
3034  * @returns #FALSE if no memory
3035  */
3036 dbus_bool_t
3037 _dbus_type_writer_write_reader (DBusTypeWriter       *writer,
3038                                 DBusTypeReader       *reader)
3039 {
3040   return _dbus_type_writer_write_reader_partial (writer, reader, NULL, 0, 0, NULL);
3041 }
3042
3043 /*
3044  * If disabled, a writer can still be iterated forward and recursed/unrecursed
3045  * but won't write any values. Types will still be written unless the
3046  * writer is a "values only" writer, because the writer needs access to
3047  * a valid signature to be able to iterate.
3048  *
3049  * @param writer the type writer
3050  * @param enabled #TRUE if values should be written
3051  */
3052 static void
3053 _dbus_type_writer_set_enabled (DBusTypeWriter   *writer,
3054                                dbus_bool_t       enabled)
3055 {
3056   writer->enabled = enabled != FALSE;
3057 }
3058
3059 /** @} */ /* end of DBusMarshal group */
3060
3061 /* tests in dbus-marshal-recursive-util.c */