GVariant: fix for not having offset for empty arrays
[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_data_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 = 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*/
688           reader->value_pos = _dbus_reader_get_offset_of_end_of_variable (reader);
689           reader->variable_index++;
690           reader->finished = (reader->variable_index >= reader->n_offsets);
691         }
692       else
693         {
694           /* fixed size - move on; consider alignment */
695           reader->value_pos = _DBUS_ALIGN_VALUE(reader->value_pos, alignment) + size;
696           reader->finished = ((size_t)reader->value_pos >= reader->value_end);
697         }
698       return;
699     }
700
701   end_pos = reader->u.array.start_pos + array_reader_get_array_len (reader);
702
703 #if RECURSIVE_MARSHAL_READ_TRACE
704   _dbus_verbose ("  reader %p array next START start_pos = %d end_pos = %d value_pos = %d current_type = %s\n",
705                  reader,
706                  reader->u.array.start_pos,
707                  end_pos, reader->value_pos,
708                  _dbus_type_to_string (current_type));
709 #endif
710
711   _dbus_assert (reader->value_pos < end_pos);
712   _dbus_assert (reader->value_pos >= reader->u.array.start_pos);
713
714   switch (_dbus_first_type_in_signature (reader->type_str,
715                                          reader->type_pos))
716     {
717     case DBUS_TYPE_DICT_ENTRY:
718     case DBUS_TYPE_STRUCT:
719     case DBUS_TYPE_VARIANT:
720       {
721         DBusTypeReader sub;
722
723         /* Recurse into the struct or variant */
724         _dbus_type_reader_recurse (reader, &sub);
725
726         /* Skip everything in this element */
727         while (_dbus_type_reader_next (&sub))
728           {
729             /* nothing */;
730           }
731
732         /* Now we are at the end of this element */
733         reader->value_pos = sub.value_pos;
734       }
735       break;
736
737     case DBUS_TYPE_ARRAY:
738       {
739         _dbus_marshal_skip_array (reader->value_str,
740                                   _dbus_first_type_in_signature (reader->type_str,
741                                                            reader->type_pos + 1),
742                                   reader->byte_order,
743                                   &reader->value_pos);
744       }
745       break;
746
747     default:
748       {
749         _dbus_marshal_skip_basic (reader->value_str,
750                                   current_type, reader->byte_order,
751                                   &reader->value_pos);
752       }
753       break;
754     }
755
756 #if RECURSIVE_MARSHAL_READ_TRACE
757   _dbus_verbose ("  reader %p array next END start_pos = %d end_pos = %d value_pos = %d current_type = %s\n",
758                  reader,
759                  reader->u.array.start_pos,
760                  end_pos, reader->value_pos,
761                  _dbus_type_to_string (current_type));
762 #endif
763
764   _dbus_assert (reader->value_pos <= end_pos);
765
766   if (reader->value_pos == end_pos)
767     {
768       skip_one_complete_type (reader->type_str,
769                               &reader->type_pos);
770     }
771 }
772
773 static void
774 variant_reader_next (DBusTypeReader *reader,
775                      int             current_type)
776 {
777   if (reader->gvariant)
778     {
779       if (!reader->klass->types_only)
780         reader->value_pos = reader->value_end;
781
782       reader->type_pos += 1;
783
784       reader->finished = TRUE;
785
786       reader->variable_index++;
787     }
788   else
789     {
790       base_reader_next (reader, current_type);
791     }
792 }
793
794 static const DBusTypeReaderClass body_reader_class = {
795   "body", 0,
796   FALSE,
797   NULL, /* body is always toplevel, so doesn't get recursed into */
798   NULL,
799   body_reader_next
800 };
801
802 static const DBusTypeReaderClass body_types_only_reader_class = {
803   "body types", 1,
804   TRUE,
805   NULL, /* body is always toplevel, so doesn't get recursed into */
806   NULL,
807   body_reader_next
808 };
809
810 static const DBusTypeReaderClass struct_reader_class = {
811   "struct", 2,
812   FALSE,
813   struct_or_dict_entry_reader_recurse,
814   NULL,
815   struct_reader_next
816 };
817
818 static const DBusTypeReaderClass struct_types_only_reader_class = {
819   "struct types", 3,
820   TRUE,
821   struct_or_dict_entry_types_only_reader_recurse,
822   NULL,
823   struct_reader_next
824 };
825
826 static const DBusTypeReaderClass dict_entry_reader_class = {
827   "dict_entry", 4,
828   FALSE,
829   struct_or_dict_entry_reader_recurse,
830   NULL,
831   dict_entry_reader_next
832 };
833
834 static const DBusTypeReaderClass dict_entry_types_only_reader_class = {
835   "dict_entry types", 5,
836   TRUE,
837   struct_or_dict_entry_types_only_reader_recurse,
838   NULL,
839   dict_entry_reader_next
840 };
841
842 static const DBusTypeReaderClass array_reader_class = {
843   "array", 6,
844   FALSE,
845   array_reader_recurse,
846   array_reader_check_finished,
847   array_reader_next
848 };
849
850 static const DBusTypeReaderClass array_types_only_reader_class = {
851   "array types", 7,
852   TRUE,
853   array_types_only_reader_recurse,
854   NULL,
855   array_types_only_reader_next
856 };
857
858 static const DBusTypeReaderClass variant_reader_class = {
859   "variant", 8,
860   FALSE,
861   variant_reader_recurse,
862   NULL,
863   variant_reader_next
864 };
865
866 #ifndef DBUS_DISABLE_ASSERT
867 static const DBusTypeReaderClass * const
868 all_reader_classes[] = {
869   &body_reader_class,
870   &body_types_only_reader_class,
871   &struct_reader_class,
872   &struct_types_only_reader_class,
873   &dict_entry_reader_class,
874   &dict_entry_types_only_reader_class,
875   &array_reader_class,
876   &array_types_only_reader_class,
877   &variant_reader_class
878 };
879 #endif
880
881 /**
882  * Initializes a type reader.
883  *
884  * @param reader the reader
885  * @param byte_order the byte order of the block to read
886  * @param type_str the signature of the block to read
887  * @param type_pos location of signature
888  * @param value_str the string containing values block
889  * @param value_pos start of values block
890  */
891 void
892 _dbus_type_reader_init (DBusTypeReader    *reader,
893                         int                byte_order,
894                         const DBusString  *type_str,
895                         int                type_pos,
896                         const DBusString  *value_str,
897                         int                value_pos)
898 {
899   reader_init (reader, byte_order, type_str, type_pos,
900                value_str, value_pos, FALSE);
901
902   reader->klass = &body_reader_class;
903
904 #if RECURSIVE_MARSHAL_READ_TRACE
905   _dbus_verbose ("  type reader %p init type_pos = %d value_pos = %d remaining sig '%s'\n",
906                  reader, reader->type_pos, reader->value_pos,
907                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
908 #endif
909 }
910
911 /**
912  * Like _dbus_type_reader_init() but the iteration is over the
913  * signature, not over values.
914  *
915  * @param reader the reader
916  * @param type_str the signature string
917  * @param type_pos location in the signature string
918  */
919 void
920 _dbus_type_reader_init_types_only (DBusTypeReader    *reader,
921                                    const DBusString  *type_str,
922                                    int                type_pos)
923 {
924   reader_init (reader, DBUS_COMPILER_BYTE_ORDER /* irrelevant */,
925                type_str, type_pos, NULL, _DBUS_INT_MAX /* crashes if we screw up */,
926                FALSE);
927
928   reader->klass = &body_types_only_reader_class;
929
930 #if RECURSIVE_MARSHAL_READ_TRACE
931   _dbus_verbose ("  type reader %p init types only type_pos = %d remaining sig '%s'\n",
932                  reader, reader->type_pos,
933                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
934 #endif
935 }
936
937 /**
938  * Gets the type of the value the reader is currently pointing to;
939  * or for a types-only reader gets the type it's currently pointing to.
940  * If the reader is at the end of a block or end of a container such
941  * as an array, returns #DBUS_TYPE_INVALID.
942  *
943  * @param reader the reader
944  */
945 int
946 _dbus_type_reader_get_current_type (const DBusTypeReader *reader)
947 {
948   int t;
949
950   if (reader->finished ||
951       (reader->klass->check_finished &&
952        (* reader->klass->check_finished) (reader)))
953     t = DBUS_TYPE_INVALID;
954   else
955     t = _dbus_first_type_in_signature (reader->type_str,
956                                        reader->type_pos);
957
958   _dbus_assert (t != DBUS_STRUCT_END_CHAR);
959   _dbus_assert (t != DBUS_STRUCT_BEGIN_CHAR);
960   _dbus_assert (t != DBUS_DICT_ENTRY_END_CHAR);
961   _dbus_assert (t != DBUS_DICT_ENTRY_BEGIN_CHAR);
962   
963 #if 0
964   _dbus_verbose ("  type reader %p current type_pos = %d type = %s\n",
965                  reader, reader->type_pos,
966                  _dbus_type_to_string (t));
967 #endif
968
969   return t;
970 }
971
972 /**
973  * Gets the type of an element of the array the reader is currently
974  * pointing to. It's an error to call this if
975  * _dbus_type_reader_get_current_type() doesn't return #DBUS_TYPE_ARRAY
976  * for this reader.
977  *
978  * @param reader the reader
979  */
980 int
981 _dbus_type_reader_get_element_type (const DBusTypeReader  *reader)
982 {
983   int element_type;
984
985   _dbus_assert (_dbus_type_reader_get_current_type (reader) == DBUS_TYPE_ARRAY);
986
987   element_type = _dbus_first_type_in_signature (reader->type_str,
988                                           reader->type_pos + 1);
989
990   return element_type;
991 }
992
993 /**
994  * Gets the current position in the value block
995  * @param reader the reader
996  */
997 int
998 _dbus_type_reader_get_value_pos (const DBusTypeReader  *reader)
999 {
1000   return reader->value_pos;
1001 }
1002
1003 /**
1004  * Get the address of the marshaled value in the data being read.  The
1005  * address may not be aligned; you have to align it to the type of the
1006  * value you want to read. Most of the demarshal routines do this for
1007  * you.
1008  *
1009  * @param reader the reader
1010  * @param value_location the address of the marshaled value
1011  */
1012 void
1013 _dbus_type_reader_read_raw (const DBusTypeReader  *reader,
1014                             const unsigned char  **value_location)
1015 {
1016   _dbus_assert (!reader->klass->types_only);
1017
1018   *value_location = _dbus_string_get_const_data_len (reader->value_str,
1019                                                      reader->value_pos,
1020                                                      0);
1021 }
1022
1023 /**
1024  * Reads a basic-typed value, as with _dbus_marshal_read_basic().
1025  *
1026  * @param reader the reader
1027  * @param value the address of the value
1028  */
1029 void
1030 _dbus_type_reader_read_basic (const DBusTypeReader    *reader,
1031                               void                    *value)
1032 {
1033   int t;
1034
1035   _dbus_assert (!reader->klass->types_only);
1036
1037   t = _dbus_type_reader_get_current_type (reader);
1038
1039   (reader->gvariant ? _dbus_marshal_read_gvariant_basic : _dbus_marshal_read_basic) (
1040                             reader->value_str,
1041                             reader->value_pos,
1042                             t, value,
1043                             reader->byte_order,
1044                             NULL);
1045
1046
1047 #if RECURSIVE_MARSHAL_READ_TRACE
1048   _dbus_verbose ("  type reader %p read basic type_pos = %d value_pos = %d remaining sig '%s'\n",
1049                  reader, reader->type_pos, reader->value_pos,
1050                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
1051 #endif
1052 }
1053
1054 /**
1055  * Returns the number of bytes in the array.
1056  *
1057  * @param reader the reader to read from
1058  * @returns the number of bytes in the array
1059  */
1060 int
1061 _dbus_type_reader_get_array_length (const DBusTypeReader  *reader)
1062 {
1063   _dbus_assert (!reader->klass->types_only);
1064   _dbus_assert (reader->klass == &array_reader_class);
1065
1066   return array_reader_get_array_len (reader);
1067 }
1068
1069 /**
1070  * Reads a block of fixed-length basic values, from the current point
1071  * in an array to the end of the array.  Does not work for arrays of
1072  * string or container types.
1073  *
1074  * This function returns the array in-place; it does not make a copy,
1075  * and it does not swap the bytes.
1076  *
1077  * If you ask for #DBUS_TYPE_DOUBLE you will get a "const double*" back
1078  * and the "value" argument should be a "const double**" and so on.
1079  *
1080  * @param reader the reader to read from
1081  * @param value place to return the array values
1082  * @param n_elements place to return number of array elements
1083  */
1084 void
1085 _dbus_type_reader_read_fixed_multi (const DBusTypeReader  *reader,
1086                                     void                  *value,
1087                                     int                   *n_elements)
1088 {
1089   int element_type;
1090   int end_pos;
1091   int remaining_len;
1092   int alignment;
1093   int total_len;
1094
1095   _dbus_assert (!reader->klass->types_only);
1096   _dbus_assert (reader->klass == &array_reader_class);
1097
1098   element_type = _dbus_first_type_in_signature (reader->type_str,
1099                                                 reader->type_pos);
1100
1101   _dbus_assert (element_type != DBUS_TYPE_INVALID); /* why we don't use get_current_type() */
1102   _dbus_assert (dbus_type_is_fixed (element_type));
1103
1104   alignment = _dbus_type_get_alignment (element_type);
1105
1106   _dbus_assert (reader->value_pos >= reader->u.array.start_pos);
1107
1108   total_len = array_reader_get_array_len (reader);
1109   end_pos = reader->u.array.start_pos + total_len;
1110   remaining_len = end_pos - reader->value_pos;
1111
1112 #if RECURSIVE_MARSHAL_READ_TRACE
1113   _dbus_verbose ("end_pos %d total_len %d remaining_len %d value_pos %d\n",
1114                  end_pos, total_len, remaining_len, reader->value_pos);
1115 #endif
1116
1117   _dbus_assert (remaining_len <= total_len);
1118
1119   if (remaining_len == 0)
1120     *(const DBusBasicValue**) value = NULL;
1121   else
1122     *(const DBusBasicValue**) value =
1123       (void*) _dbus_string_get_const_data_len (reader->value_str,
1124                                                reader->value_pos,
1125                                                remaining_len);
1126
1127   *n_elements = remaining_len / alignment;
1128   _dbus_assert ((remaining_len % alignment) == 0);
1129
1130 #if RECURSIVE_MARSHAL_READ_TRACE
1131   _dbus_verbose ("  type reader %p read fixed array type_pos = %d value_pos = %d remaining sig '%s'\n",
1132                  reader, reader->type_pos, reader->value_pos,
1133                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
1134 #endif
1135 }
1136
1137 /**
1138  * Initialize a new reader pointing to the first type and
1139  * corresponding value that's a child of the current container. It's
1140  * an error to call this if the current type is a non-container.
1141  *
1142  * Note that DBusTypeReader traverses values, not types. So if you
1143  * have an empty array of array of int, you can't recurse into it. You
1144  * can only recurse into each element.
1145  *
1146  * @param reader the reader
1147  * @param sub a reader to init pointing to the first child
1148  */
1149 void
1150 _dbus_type_reader_recurse (DBusTypeReader *reader,
1151                            DBusTypeReader *sub)
1152 {
1153   const DBusTypeReaderClass *klass = NULL;
1154   int t;
1155
1156   t = _dbus_first_type_in_signature (reader->type_str, reader->type_pos);
1157
1158   switch (t)
1159     {
1160     case DBUS_TYPE_STRUCT:
1161       if (reader->klass->types_only)
1162         klass = &struct_types_only_reader_class;
1163       else
1164         klass = &struct_reader_class;
1165       break;
1166     case DBUS_TYPE_DICT_ENTRY:
1167       if (reader->klass->types_only)
1168         klass = &dict_entry_types_only_reader_class;
1169       else
1170         klass = &dict_entry_reader_class;
1171       break;
1172     case DBUS_TYPE_ARRAY:
1173       if (reader->klass->types_only)
1174         klass = &array_types_only_reader_class;
1175       else
1176         klass = &array_reader_class;
1177       break;
1178     case DBUS_TYPE_VARIANT:
1179       if (reader->klass->types_only)
1180         _dbus_assert_not_reached ("can't recurse into variant typecode");
1181       else
1182         klass = &variant_reader_class;
1183       break;
1184     default:
1185       _dbus_verbose ("recursing into type %s\n", _dbus_type_to_string (t));
1186 #ifndef DBUS_DISABLE_CHECKS
1187       if (t == DBUS_TYPE_INVALID)
1188         _dbus_warn_check_failed ("You can't recurse into an empty array or off the end of a message body\n");
1189 #endif /* DBUS_DISABLE_CHECKS */
1190
1191       _dbus_assert_not_reached ("don't yet handle recursing into this type");
1192     }
1193
1194   _dbus_assert (klass == all_reader_classes[klass->id]);
1195
1196   (* klass->recurse) (sub, reader);
1197   sub->klass = klass;
1198
1199 #if RECURSIVE_MARSHAL_READ_TRACE
1200   _dbus_verbose ("  type reader %p RECURSED type_pos = %d value_pos = %d remaining sig '%s'\n",
1201                  sub, sub->type_pos, sub->value_pos,
1202                  _dbus_string_get_const_data_len (sub->type_str, sub->type_pos, 0));
1203 #endif
1204 }
1205
1206 /**
1207  * Skip to the next value on this "level". e.g. the next field in a
1208  * struct, the next value in an array. Returns FALSE at the end of the
1209  * current container.
1210  *
1211  * @param reader the reader
1212  * @returns FALSE if nothing more to read at or below this level
1213  */
1214 dbus_bool_t
1215 _dbus_type_reader_next (DBusTypeReader *reader)
1216 {
1217   int t;
1218
1219   t = _dbus_type_reader_get_current_type (reader);
1220
1221 #if RECURSIVE_MARSHAL_READ_TRACE
1222   _dbus_verbose ("  type reader %p START next() { type_pos = %d value_pos = %d remaining sig '%s' current_type = %s\n",
1223                  reader, reader->type_pos, reader->value_pos,
1224                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0),
1225                  _dbus_type_to_string (t));
1226 #endif
1227
1228   if (t == DBUS_TYPE_INVALID)
1229     return FALSE;
1230
1231   (* reader->klass->next) (reader, t);
1232
1233 #if RECURSIVE_MARSHAL_READ_TRACE
1234   _dbus_verbose ("  type reader %p END next() type_pos = %d value_pos = %d remaining sig '%s' current_type = %s\n",
1235                  reader, reader->type_pos, reader->value_pos,
1236                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0),
1237                  _dbus_type_to_string (_dbus_type_reader_get_current_type (reader)));
1238 #endif
1239
1240   return _dbus_type_reader_get_current_type (reader) != DBUS_TYPE_INVALID;
1241 }
1242
1243 /**
1244  * Check whether there's another value on this "level". e.g. the next
1245  * field in a struct, the next value in an array. Returns FALSE at the
1246  * end of the current container.
1247  *
1248  * You probably don't want to use this; it makes for an awkward for/while
1249  * loop. A nicer one is "while ((current_type = get_current_type()) != INVALID)"
1250  *
1251  * @param reader the reader
1252  * @returns FALSE if nothing more to read at or below this level
1253  */
1254 dbus_bool_t
1255 _dbus_type_reader_has_next (const DBusTypeReader *reader)
1256 {
1257   /* Not efficient but works for now. */
1258   DBusTypeReader copy;
1259
1260   copy = *reader;
1261   return _dbus_type_reader_next (&copy);
1262 }
1263
1264 /**
1265  * Gets the string and range of said string containing the signature
1266  * of the current value. Essentially a more complete version of
1267  * _dbus_type_reader_get_current_type() (returns the full type
1268  * rather than only the outside of the onion).
1269  *
1270  * Note though that the first byte in a struct signature is
1271  * #DBUS_STRUCT_BEGIN_CHAR while the current type will be
1272  * #DBUS_TYPE_STRUCT so it isn't true that the first byte of the
1273  * signature is always the same as the current type. Another
1274  * difference is that this function will still return a signature when
1275  * inside an empty array; say you recurse into empty array of int32,
1276  * the signature is "i" but the current type will always be
1277  * #DBUS_TYPE_INVALID since there are no elements to be currently
1278  * pointing to.
1279  *
1280  * @param reader the reader
1281  * @param str_p place to return the string with the type in it
1282  * @param start_p place to return start of the type
1283  * @param len_p place to return the length of the type
1284  */
1285 void
1286 _dbus_type_reader_get_signature (const DBusTypeReader  *reader,
1287                                  const DBusString     **str_p,
1288                                  int                   *start_p,
1289                                  int                   *len_p)
1290 {
1291   *str_p = reader->type_str;
1292   *start_p = reader->type_pos;
1293   *len_p = find_len_of_complete_type (reader->type_str, reader->type_pos);
1294 }
1295
1296 typedef struct
1297 {
1298   DBusString replacement; /**< Marshaled value including alignment padding */
1299   int padding;            /**< How much of the replacement block is padding */
1300 } ReplacementBlock;
1301
1302 static dbus_bool_t
1303 replacement_block_init (ReplacementBlock *block,
1304                         DBusTypeReader   *reader)
1305 {
1306   if (!_dbus_string_init (&block->replacement))
1307     return FALSE;
1308
1309   /* % 8 is the padding to have the same align properties in
1310    * our replacement string as we do at the position being replaced
1311    */
1312   block->padding = reader->value_pos % 8;
1313
1314   if (!_dbus_string_lengthen (&block->replacement, block->padding))
1315     goto oom;
1316
1317   return TRUE;
1318
1319  oom:
1320   _dbus_string_free (&block->replacement);
1321   return FALSE;
1322 }
1323
1324 static dbus_bool_t
1325 replacement_block_replace (ReplacementBlock     *block,
1326                            DBusTypeReader       *reader,
1327                            const DBusTypeReader *realign_root)
1328 {
1329   DBusTypeWriter writer;
1330   DBusTypeReader realign_reader;
1331   DBusList *fixups;
1332   int orig_len;
1333
1334   _dbus_assert (realign_root != NULL);
1335
1336   orig_len = _dbus_string_get_length (&block->replacement);
1337
1338   realign_reader = *realign_root;
1339
1340 #if RECURSIVE_MARSHAL_WRITE_TRACE
1341   _dbus_verbose ("INITIALIZING replacement block writer %p at value_pos %d\n",
1342                  &writer, _dbus_string_get_length (&block->replacement));
1343 #endif
1344   _dbus_type_writer_init_values_only (&writer,
1345                                       realign_reader.byte_order,
1346                                       realign_reader.type_str,
1347                                       realign_reader.type_pos,
1348                                       &block->replacement,
1349                                       _dbus_string_get_length (&block->replacement));
1350
1351   _dbus_assert (realign_reader.value_pos <= reader->value_pos);
1352
1353 #if RECURSIVE_MARSHAL_WRITE_TRACE
1354   _dbus_verbose ("COPYING from reader at value_pos %d to writer %p starting after value_pos %d\n",
1355                  realign_reader.value_pos, &writer, reader->value_pos);
1356 #endif
1357   fixups = NULL;
1358   if (!_dbus_type_writer_write_reader_partial (&writer,
1359                                                &realign_reader,
1360                                                reader,
1361                                                block->padding,
1362                                                _dbus_string_get_length (&block->replacement) - block->padding,
1363                                                &fixups))
1364     goto oom;
1365
1366 #if RECURSIVE_MARSHAL_WRITE_TRACE
1367   _dbus_verbose ("REPLACEMENT at padding %d len %d\n", block->padding,
1368                  _dbus_string_get_length (&block->replacement) - block->padding);
1369   _dbus_verbose_bytes_of_string (&block->replacement, block->padding,
1370                                  _dbus_string_get_length (&block->replacement) - block->padding);
1371   _dbus_verbose ("TO BE REPLACED at value_pos = %d (align pad %d) len %d realign_reader.value_pos %d\n",
1372                  reader->value_pos, reader->value_pos % 8,
1373                  realign_reader.value_pos - reader->value_pos,
1374                  realign_reader.value_pos);
1375   _dbus_verbose_bytes_of_string (reader->value_str,
1376                                  reader->value_pos,
1377                                  realign_reader.value_pos - reader->value_pos);
1378 #endif
1379
1380   /* Move the replacement into position
1381    * (realign_reader should now be at the end of the block to be replaced)
1382    */
1383   if (!_dbus_string_replace_len (&block->replacement, block->padding,
1384                                  _dbus_string_get_length (&block->replacement) - block->padding,
1385                                  (DBusString*) reader->value_str,
1386                                  reader->value_pos,
1387                                  realign_reader.value_pos - reader->value_pos))
1388     goto oom;
1389
1390   /* Process our fixups now that we can't have an OOM error */
1391   apply_and_free_fixups (&fixups, reader);
1392
1393   return TRUE;
1394
1395  oom:
1396   _dbus_string_set_length (&block->replacement, orig_len);
1397   free_fixups (&fixups);
1398   return FALSE;
1399 }
1400
1401 static void
1402 replacement_block_free (ReplacementBlock *block)
1403 {
1404   _dbus_string_free (&block->replacement);
1405 }
1406
1407 /* In the variable-length case, we have to fix alignment after we insert.
1408  * The strategy is as follows:
1409  *
1410  *  - pad a new string to have the same alignment as the
1411  *    start of the current basic value
1412  *  - write the new basic value
1413  *  - copy from the original reader to the new string,
1414  *    which will fix the alignment of types following
1415  *    the new value
1416  *    - this copy has to start at realign_root,
1417  *      but not really write anything until it
1418  *      passes the value being set
1419  *    - as an optimization, we can stop copying
1420  *      when the source and dest values are both
1421  *      on an 8-boundary, since we know all following
1422  *      padding and alignment will be identical
1423  *  - copy the new string back to the original
1424  *    string, replacing the relevant part of the
1425  *    original string
1426  *  - now any arrays in the original string that
1427  *    contained the replaced string may have the
1428  *    wrong length; so we have to fix that
1429  */
1430 static dbus_bool_t
1431 reader_set_basic_variable_length (DBusTypeReader       *reader,
1432                                   int                   current_type,
1433                                   const void           *value,
1434                                   const DBusTypeReader *realign_root)
1435 {
1436   dbus_bool_t retval;
1437   ReplacementBlock block;
1438   DBusTypeWriter writer;
1439
1440   _dbus_assert (realign_root != NULL);
1441
1442   retval = FALSE;
1443
1444   if (!replacement_block_init (&block, reader))
1445     return FALSE;
1446
1447   /* Write the new basic value */
1448 #if RECURSIVE_MARSHAL_WRITE_TRACE
1449   _dbus_verbose ("INITIALIZING writer %p to write basic value at value_pos %d of replacement string\n",
1450                  &writer, _dbus_string_get_length (&block.replacement));
1451 #endif
1452   _dbus_type_writer_init_values_only (&writer,
1453                                       reader->byte_order,
1454                                       reader->type_str,
1455                                       reader->type_pos,
1456                                       &block.replacement,
1457                                       _dbus_string_get_length (&block.replacement));
1458 #if RECURSIVE_MARSHAL_WRITE_TRACE
1459   _dbus_verbose ("WRITING basic value to writer %p (replacement string)\n", &writer);
1460 #endif
1461   if (!_dbus_type_writer_write_basic (&writer, current_type, value))
1462     goto out;
1463
1464   if (!replacement_block_replace (&block,
1465                                   reader,
1466                                   realign_root))
1467     goto out;
1468
1469   retval = TRUE;
1470
1471  out:
1472   replacement_block_free (&block);
1473   return retval;
1474 }
1475
1476 static void
1477 reader_set_basic_fixed_length (DBusTypeReader *reader,
1478                                int             current_type,
1479                                const void     *value)
1480 {
1481   _dbus_marshal_set_basic ((DBusString*) reader->value_str,
1482                            reader->value_pos,
1483                            current_type,
1484                            value,
1485                            reader->byte_order,
1486                            NULL, NULL);
1487 }
1488
1489 /**
1490  * Sets a new value for the basic type value pointed to by the reader,
1491  * leaving the reader valid to continue reading. Any other readers
1492  * will be invalidated if you set a variable-length type such as a
1493  * string.
1494  *
1495  * The provided realign_root is the reader to start from when
1496  * realigning the data that follows the newly-set value. The reader
1497  * parameter must point to a value below the realign_root parameter.
1498  * If the type being set is fixed-length, then realign_root may be
1499  * #NULL. Only values reachable from realign_root will be realigned,
1500  * so if your string contains other values you will need to deal with
1501  * those somehow yourself. It is OK if realign_root is the same
1502  * reader as the reader parameter, though if you aren't setting the
1503  * root it may not be such a good idea.
1504  *
1505  * @todo DBusTypeReader currently takes "const" versions of the type
1506  * and value strings, and this function modifies those strings by
1507  * casting away the const, which is of course bad if we want to get
1508  * picky. (To be truly clean you'd have an object which contained the
1509  * type and value strings and set_basic would be a method on that
1510  * object... this would also make DBusTypeReader the same thing as
1511  * DBusTypeMark. But since DBusMessage is effectively that object for
1512  * D-Bus it doesn't seem worth creating some random object.)
1513  *
1514  * @todo optimize this by only rewriting until the old and new values
1515  * are at the same alignment. Frequently this should result in only
1516  * replacing the value that's immediately at hand.
1517  *
1518  * @param reader reader indicating where to set a new value
1519  * @param value address of the value to set
1520  * @param realign_root realign from here
1521  * @returns #FALSE if not enough memory
1522  */
1523 dbus_bool_t
1524 _dbus_type_reader_set_basic (DBusTypeReader       *reader,
1525                              const void           *value,
1526                              const DBusTypeReader *realign_root)
1527 {
1528   int current_type;
1529
1530   _dbus_assert (!reader->klass->types_only);
1531   _dbus_assert (reader->value_str == realign_root->value_str);
1532   _dbus_assert (reader->value_pos >= realign_root->value_pos);
1533
1534   current_type = _dbus_type_reader_get_current_type (reader);
1535
1536 #if RECURSIVE_MARSHAL_WRITE_TRACE
1537   _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",
1538                  reader, reader->type_pos, reader->value_pos,
1539                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0),
1540                  realign_root,
1541                  realign_root ? realign_root->value_pos : -1,
1542                  _dbus_type_to_string (current_type));
1543   _dbus_verbose_bytes_of_string (realign_root->value_str, realign_root->value_pos,
1544                                  _dbus_string_get_length (realign_root->value_str) -
1545                                  realign_root->value_pos);
1546 #endif
1547
1548   _dbus_assert (dbus_type_is_basic (current_type));
1549
1550   if (dbus_type_is_fixed (current_type))
1551     {
1552       reader_set_basic_fixed_length (reader, current_type, value);
1553       return TRUE;
1554     }
1555   else
1556     {
1557       _dbus_assert (realign_root != NULL);
1558       return reader_set_basic_variable_length (reader, current_type,
1559                                                value, realign_root);
1560     }
1561 }
1562
1563 /**
1564  * Recursively deletes any value pointed to by the reader, leaving the
1565  * reader valid to continue reading. Any other readers will be
1566  * invalidated.
1567  *
1568  * The provided realign_root is the reader to start from when
1569  * realigning the data that follows the newly-set value.
1570  * See _dbus_type_reader_set_basic() for more details on the
1571  * realign_root paramter.
1572  *
1573  * @todo for now this does not delete the typecodes associated with
1574  * the value, so this function should only be used for array elements.
1575  *
1576  * @param reader reader indicating where to delete a value
1577  * @param realign_root realign from here
1578  * @returns #FALSE if not enough memory
1579  */
1580 dbus_bool_t
1581 _dbus_type_reader_delete (DBusTypeReader        *reader,
1582                           const DBusTypeReader  *realign_root)
1583 {
1584   dbus_bool_t retval;
1585   ReplacementBlock block;
1586
1587   _dbus_assert (realign_root != NULL);
1588   _dbus_assert (reader->klass == &array_reader_class);
1589
1590   retval = FALSE;
1591
1592   if (!replacement_block_init (&block, reader))
1593     return FALSE;
1594
1595   if (!replacement_block_replace (&block,
1596                                   reader,
1597                                   realign_root))
1598     goto out;
1599
1600   retval = TRUE;
1601
1602  out:
1603   replacement_block_free (&block);
1604   return retval;
1605 }
1606
1607 /*
1608  * Compares two readers, which must be iterating over the same value data.
1609  * Returns #TRUE if the first parameter is further along than the second parameter.
1610  *
1611  * @param lhs left-hand-side (first) parameter
1612  * @param rhs left-hand-side (first) parameter
1613  * @returns whether lhs is greater than rhs
1614  */
1615 static dbus_bool_t
1616 _dbus_type_reader_greater_than (const DBusTypeReader  *lhs,
1617                                 const DBusTypeReader  *rhs)
1618 {
1619   _dbus_assert (lhs->value_str == rhs->value_str);
1620
1621   return lhs->value_pos > rhs->value_pos;
1622 }
1623
1624 /*
1625  *
1626  *
1627  *         DBusTypeWriter
1628  *
1629  *
1630  *
1631  */
1632
1633 /**
1634  * Initialize a write iterator, which is used to write out values in
1635  * serialized D-Bus format.
1636  *
1637  * The type_pos passed in is expected to be inside an already-valid,
1638  * though potentially empty, type signature. This means that the byte
1639  * after type_pos must be either #DBUS_TYPE_INVALID (aka nul) or some
1640  * other valid type. #DBusTypeWriter won't enforce that the signature
1641  * is already valid (you can append the nul byte at the end if you
1642  * like), but just be aware that you need the nul byte eventually and
1643  * #DBusTypeWriter isn't going to write it for you.
1644  *
1645  * @param writer the writer to init
1646  * @param byte_order the byte order to marshal into
1647  * @param type_str the string to write typecodes into
1648  * @param type_pos where to insert typecodes
1649  * @param value_str the string to write values into
1650  * @param value_pos where to insert values
1651  *
1652  */
1653 void
1654 _dbus_type_writer_init (DBusTypeWriter *writer,
1655                         int             byte_order,
1656                         DBusString     *type_str,
1657                         int             type_pos,
1658                         DBusString     *value_str,
1659                         int             value_pos)
1660 {
1661   writer->byte_order = byte_order;
1662   writer->type_str = type_str;
1663   writer->type_pos = type_pos;
1664   writer->value_str = value_str;
1665   writer->value_pos = value_pos;
1666   writer->value_start = value_pos;
1667   writer->container_type = DBUS_TYPE_INVALID;
1668   writer->type_pos_is_expectation = FALSE;
1669   writer->enabled = TRUE;
1670   writer->gvariant = FALSE;
1671   writer->body_container = FALSE;
1672   writer->is_fixed = TRUE;
1673   writer->alignment = 1;
1674
1675 #if RECURSIVE_MARSHAL_WRITE_TRACE
1676   _dbus_verbose ("writer %p init remaining sig '%s'\n", writer,
1677                  writer->type_str ?
1678                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0) :
1679                  "unknown");
1680 #endif
1681 }
1682
1683 /**
1684  * Initialize a write iterator, with the signature to be provided
1685  * later.
1686  *
1687  * @param writer the writer to init
1688  * @param byte_order the byte order to marshal into
1689  * @param value_str the string to write values into
1690  * @param value_pos where to insert values
1691  *
1692  */
1693 void
1694 _dbus_type_writer_init_types_delayed (DBusTypeWriter *writer,
1695                                       int             byte_order,
1696                                       DBusString     *value_str,
1697                                       int             value_pos)
1698 {
1699   _dbus_type_writer_init (writer, byte_order,
1700                           NULL, 0, value_str, value_pos);
1701 }
1702
1703 /**
1704  * Initialize a write iterator, with the signature to be provided
1705  * later. Supports GVariant
1706  *
1707  * @param writer the writer to init
1708  * @param byte_order the byte order to marshal into
1709  * @param value_str the string to write values into
1710  * @param value_pos where to insert values
1711  * @param gvariant TRUE if append values with GVariant marshalling
1712  * @param last_offset pointer to root level offset of last variable-size value
1713  * @param last_pos pointer to root level position of offsets
1714  */
1715 void
1716 _dbus_type_writer_gvariant_init_types_delayed (DBusTypeWriter  *writer,
1717                                                int              byte_order,
1718                                                DBusString      *value_str,
1719                                                int              value_pos,
1720                                                dbus_bool_t      gvariant,
1721                                                size_t          *last_offset,
1722                                                size_t          *last_pos)
1723 {
1724   _dbus_type_writer_init (writer, byte_order,
1725                           NULL, 0, value_str, value_pos);
1726   writer->gvariant = gvariant;
1727   writer->body_container = TRUE;
1728   writer->is_fixed = TRUE;
1729   writer->alignment = 8;
1730   writer->u.root.last_offset = last_offset;
1731   writer->u.root.last_pos = last_pos;
1732   writer->offsets_size = 1;
1733   writer->offsets = NULL;
1734
1735   if (gvariant)
1736     {
1737       writer->value_pos = *last_pos;
1738       writer->value_start = 0;
1739     }
1740 }
1741
1742 /**
1743  * Adds type string to the writer, if it had none.
1744  *
1745  * @param writer the writer to init
1746  * @param type_str type string to add
1747  * @param type_pos type position
1748  *
1749  */
1750 void
1751 _dbus_type_writer_add_types (DBusTypeWriter *writer,
1752                              DBusString     *type_str,
1753                              int             type_pos)
1754 {
1755   if (writer->type_str == NULL) /* keeps us from using this as setter */
1756     {
1757       writer->type_str = type_str;
1758       writer->type_pos = type_pos;
1759     }
1760 }
1761
1762 /**
1763  * Removes type string from the writer.
1764  *
1765  * @param writer the writer to remove from
1766  */
1767 void
1768 _dbus_type_writer_remove_types (DBusTypeWriter *writer)
1769 {
1770   writer->type_str = NULL;
1771   writer->type_pos = -1;
1772 }
1773
1774 /**
1775  * Like _dbus_type_writer_init(), except the type string
1776  * passed in should correspond to an existing signature that
1777  * matches what you're going to write out. The writer will
1778  * check what you write vs. this existing signature.
1779  *
1780  * @param writer the writer to init
1781  * @param byte_order the byte order to marshal into
1782  * @param type_str the string with signature
1783  * @param type_pos start of signature
1784  * @param value_str the string to write values into
1785  * @param value_pos where to insert values
1786  *
1787  */
1788 void
1789 _dbus_type_writer_init_values_only (DBusTypeWriter   *writer,
1790                                     int               byte_order,
1791                                     const DBusString *type_str,
1792                                     int               type_pos,
1793                                     DBusString       *value_str,
1794                                     int               value_pos)
1795 {
1796   _dbus_type_writer_init (writer, byte_order,
1797                           (DBusString*)type_str, type_pos,
1798                           value_str, value_pos);
1799
1800   writer->type_pos_is_expectation = TRUE;
1801 }
1802
1803 static dbus_bool_t
1804 _dbus_type_writer_write_basic_no_typecode (DBusTypeWriter *writer,
1805                                            int             type,
1806                                            const void     *value)
1807 {
1808   if (writer->enabled)
1809     {
1810       if (writer->gvariant)
1811         {
1812           return _dbus_type_writer_gvariant_write_basic_no_typecode (writer, type, value);
1813         }
1814       else
1815         return _dbus_marshal_write_basic (writer->value_str,
1816                                           writer->value_pos,
1817                                           type,
1818                                           value,
1819                                           writer->byte_order,
1820                                           &writer->value_pos);
1821     }
1822   else
1823     return TRUE;
1824 }
1825
1826 /* If our parent is an array, things are a little bit complicated.
1827  *
1828  * The parent must have a complete element type, such as
1829  * "i" or "aai" or "(ii)" or "a(ii)". There can't be
1830  * unclosed parens, or an "a" with no following type.
1831  *
1832  * To recurse, the only allowed operation is to recurse into the
1833  * first type in the element type. So for "i" you can't recurse, for
1834  * "ai" you can recurse into the array, for "(ii)" you can recurse
1835  * into the struct.
1836  *
1837  * If you recurse into the array for "ai", then you must specify
1838  * "i" for the element type of the array you recurse into.
1839  *
1840  * While inside an array at any level, we need to avoid writing to
1841  * type_str, since the type only appears once for the whole array,
1842  * it does not appear for each array element.
1843  *
1844  * While inside an array type_pos points to the expected next
1845  * typecode, rather than the next place we could write a typecode.
1846  */
1847 static void
1848 writer_recurse_init_and_check (DBusTypeWriter *writer,
1849                                int             container_type,
1850                                DBusTypeWriter *sub)
1851 {
1852   _dbus_type_writer_init (sub,
1853                           writer->byte_order,
1854                           writer->type_str,
1855                           writer->type_pos,
1856                           writer->value_str,
1857                           writer->value_pos);
1858
1859   sub->container_type = container_type;
1860   sub->gvariant = writer->gvariant;
1861
1862   if (writer->type_pos_is_expectation ||
1863       (sub->container_type == DBUS_TYPE_ARRAY || sub->container_type == DBUS_TYPE_VARIANT))
1864     sub->type_pos_is_expectation = TRUE;
1865   else
1866     sub->type_pos_is_expectation = FALSE;
1867
1868   sub->enabled = writer->enabled;
1869
1870 #ifndef DBUS_DISABLE_CHECKS
1871   if (writer->type_pos_is_expectation && writer->type_str)
1872     {
1873       int expected;
1874
1875       expected = _dbus_first_type_in_signature (writer->type_str, writer->type_pos);
1876
1877       if (expected != sub->container_type)
1878         {
1879           if (expected != DBUS_TYPE_INVALID)
1880             _dbus_warn_check_failed ("Writing an element of type %s, but the expected type here is %s\n"
1881                                      "The overall signature expected here was '%s' and we are on byte %d of that signature.\n",
1882                                      _dbus_type_to_string (sub->container_type),
1883                                      _dbus_type_to_string (expected),
1884                                      _dbus_string_get_const_data (writer->type_str), writer->type_pos);
1885           else
1886             _dbus_warn_check_failed ("Writing an element of type %s, but no value is expected here\n"
1887                                      "The overall signature expected here was '%s' and we are on byte %d of that signature.\n",
1888                                      _dbus_type_to_string (sub->container_type),
1889                                      _dbus_string_get_const_data (writer->type_str), writer->type_pos);
1890           
1891           _dbus_assert_not_reached ("bad array element or variant content written");
1892         }
1893     }
1894 #endif /* DBUS_DISABLE_CHECKS */
1895
1896 #if RECURSIVE_MARSHAL_WRITE_TRACE
1897   _dbus_verbose ("  type writer %p recurse parent %s type_pos = %d value_pos = %d is_expectation = %d remaining sig '%s' enabled = %d\n",
1898                  writer,
1899                  _dbus_type_to_string (writer->container_type),
1900                  writer->type_pos, writer->value_pos, writer->type_pos_is_expectation,
1901                  writer->type_str ?
1902                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0) :
1903                  "unknown",
1904                  writer->enabled);
1905   _dbus_verbose ("  type writer %p recurse sub %s   type_pos = %d value_pos = %d is_expectation = %d enabled = %d\n",
1906                  sub,
1907                  _dbus_type_to_string (sub->container_type),
1908                  sub->type_pos, sub->value_pos,
1909                  sub->type_pos_is_expectation,
1910                  sub->enabled);
1911 #endif
1912 }
1913
1914 static dbus_bool_t
1915 write_or_verify_typecode (DBusTypeWriter *writer,
1916                           int             typecode)
1917 {
1918   /* A subwriter inside an array or variant will have type_pos
1919    * pointing to the expected typecode; a writer not inside an array
1920    * or variant has type_pos pointing to the next place to insert a
1921    * typecode.
1922    */
1923 #if RECURSIVE_MARSHAL_WRITE_TRACE
1924   _dbus_verbose ("  type writer %p write_or_verify start type_pos = %d remaining sig '%s' enabled = %d\n",
1925                  writer, writer->type_pos,
1926                  writer->type_str ?
1927                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0) :
1928                  "unknown",
1929                  writer->enabled);
1930 #endif
1931
1932   if (writer->type_str == NULL)
1933     return TRUE;
1934
1935   if (writer->type_pos_is_expectation)
1936     {
1937 #ifndef DBUS_DISABLE_CHECKS
1938       {
1939         int expected;
1940
1941         expected = _dbus_string_get_byte (writer->type_str, writer->type_pos);
1942
1943         if (expected != typecode)
1944           {
1945             if (expected != DBUS_TYPE_INVALID)
1946               _dbus_warn_check_failed ("Array or variant type requires that type %s be written, but %s was written.\n"
1947                                        "The overall signature expected here was '%s' and we are on byte %d of that signature.\n",
1948                                        _dbus_type_to_string (expected), _dbus_type_to_string (typecode),
1949                                        _dbus_string_get_const_data (writer->type_str), writer->type_pos);
1950             else
1951               _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"
1952                                        "The overall signature expected here was '%s' and we are on byte %d of that signature.\n",
1953                                        _dbus_type_to_string (typecode),
1954                                        _dbus_string_get_const_data (writer->type_str), writer->type_pos);
1955             _dbus_assert_not_reached ("bad type inserted somewhere inside an array or variant");
1956           }
1957       }
1958 #endif /* DBUS_DISABLE_CHECKS */
1959
1960       /* if immediately inside an array we'd always be appending an element,
1961        * so the expected type doesn't change; if inside a struct or something
1962        * below an array, we need to move through said struct or something.
1963        */
1964       if (writer->container_type != DBUS_TYPE_ARRAY)
1965         writer->type_pos += 1;
1966     }
1967   else
1968     {
1969       if (!_dbus_string_insert_byte (writer->type_str,
1970                                      writer->type_pos,
1971                                      typecode))
1972         return FALSE;
1973
1974       writer->type_pos += 1;
1975     }
1976
1977 #if RECURSIVE_MARSHAL_WRITE_TRACE
1978   _dbus_verbose ("  type writer %p write_or_verify end type_pos = %d remaining sig '%s'\n",
1979                  writer, writer->type_pos,
1980                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0));
1981 #endif
1982
1983   return TRUE;
1984 }
1985
1986 static dbus_bool_t
1987 writer_recurse_struct_or_dict_entry (DBusTypeWriter   *writer,
1988                                      int               begin_char,
1989                                      const DBusString *contained_type,
1990                                      int               contained_type_start,
1991                                      int               contained_type_len,
1992                                      DBusTypeWriter   *sub)
1993 {
1994   /* FIXME right now contained_type is ignored; we could probably
1995    * almost trivially fix the code so if it's present we
1996    * write it out and then set type_pos_is_expectation
1997    */
1998
1999   /* Ensure that we'll be able to add alignment padding and the typecode */
2000   if (writer->enabled)
2001     {
2002       if (!_dbus_string_alloc_space (sub->value_str, 8))
2003         return FALSE;
2004     }
2005
2006   if (!write_or_verify_typecode (sub, begin_char))
2007     _dbus_assert_not_reached ("failed to insert struct typecode after prealloc");
2008
2009   if (writer->enabled)
2010     {
2011       if (writer->gvariant)
2012         {
2013           sub->alignment = 1;
2014           sub->value_str = dbus_new (DBusString, 1);
2015           if (NULL == sub->value_str || !_dbus_string_init (sub->value_str))
2016             return FALSE;
2017           sub->value_start = sub->value_pos = 0;
2018           sub->u.struct_or_dict.last_offset = GVARIANT_LAST_OFFSET_NOT_SET;
2019           sub->offsets_size = 1;
2020           sub->is_fixed = TRUE;
2021           sub->offsets = dbus_new (DBusString, 1);
2022           _dbus_string_init (sub->offsets);
2023         }
2024       else
2025         {
2026           if (!_dbus_string_insert_bytes (sub->value_str,
2027                                           sub->value_pos,
2028                                           _DBUS_ALIGN_VALUE (sub->value_pos, 8) - sub->value_pos,
2029                                           '\0'))
2030             _dbus_assert_not_reached ("should not have failed to insert alignment padding for struct");
2031
2032           sub->value_pos =  _DBUS_ALIGN_VALUE (sub->value_pos, 8);
2033         }
2034     }
2035
2036   return TRUE;
2037 }
2038
2039
2040 static dbus_bool_t
2041 writer_recurse_array (DBusTypeWriter   *writer,
2042                       const DBusString *contained_type,
2043                       int               contained_type_start,
2044                       int               contained_type_len,
2045                       DBusTypeWriter   *sub,
2046                       dbus_bool_t       is_array_append)
2047 {
2048   dbus_uint32_t value = 0;
2049   int alignment;
2050   int aligned;
2051
2052 #ifndef DBUS_DISABLE_CHECKS
2053   if (writer->container_type == DBUS_TYPE_ARRAY &&
2054       writer->type_str)
2055     {
2056       if (!_dbus_string_equal_substring (contained_type,
2057                                          contained_type_start,
2058                                          contained_type_len,
2059                                          writer->type_str,
2060                                          writer->u.array.element_type_pos + 1))
2061         {
2062           _dbus_warn_check_failed ("Writing an array of '%s' but this is incompatible with the expected type of elements in the parent array\n",
2063                                    _dbus_string_get_const_data_len (contained_type,
2064                                                                     contained_type_start,
2065                                                                     contained_type_len));
2066           _dbus_assert_not_reached ("incompatible type for child array");
2067         }
2068     }
2069 #endif /* DBUS_DISABLE_CHECKS */
2070
2071   if (writer->enabled && !is_array_append)
2072     {
2073       /* 3 pad + 4 bytes for the array length, and 4 bytes possible padding
2074        * before array values
2075        */
2076       if (!_dbus_string_alloc_space (sub->value_str, 3 + 4 + 4))
2077         return FALSE;
2078     }
2079
2080   if (writer->type_str != NULL)
2081     {
2082       sub->type_pos += 1; /* move to point to the element type, since type_pos
2083                            * should be the expected type for further writes
2084                            */
2085       sub->u.array.element_type_pos = sub->type_pos;
2086     }
2087
2088   if (!writer->type_pos_is_expectation)
2089     {
2090       /* sub is a toplevel/outermost array so we need to write the type data */
2091
2092       /* alloc space for array typecode, element signature */
2093       if (!_dbus_string_alloc_space (writer->type_str, 1 + contained_type_len))
2094         return FALSE;
2095
2096       if (!_dbus_string_insert_byte (writer->type_str,
2097                                      writer->type_pos,
2098                                      DBUS_TYPE_ARRAY))
2099         _dbus_assert_not_reached ("failed to insert array typecode after prealloc");
2100
2101       if (!_dbus_string_copy_len (contained_type,
2102                                   contained_type_start, contained_type_len,
2103                                   sub->type_str,
2104                                   sub->u.array.element_type_pos))
2105         _dbus_assert_not_reached ("should not have failed to insert array element typecodes");
2106     }
2107
2108   if (writer->type_str != NULL)
2109     {
2110       /* If the parent is an array, we hold type_pos pointing at the array element type;
2111        * otherwise advance it to reflect the array value we just recursed into
2112        */
2113       if (writer->container_type != DBUS_TYPE_ARRAY)
2114         writer->type_pos += 1 + contained_type_len;
2115       else
2116         _dbus_assert (writer->type_pos_is_expectation); /* because it's an array */
2117     }
2118
2119   if (writer->enabled)
2120     {
2121       if (!writer->gvariant)
2122         {
2123           /* Write (or jump over, if is_array_append) the length */
2124           sub->u.array.len_pos = _DBUS_ALIGN_VALUE (sub->value_pos, 4);
2125
2126           if (is_array_append)
2127           {
2128             sub->value_pos += 4;
2129           }
2130           else
2131           {
2132             if (!_dbus_type_writer_write_basic_no_typecode (sub, DBUS_TYPE_UINT32, &value))
2133               _dbus_assert_not_reached ("should not have failed to insert array len");
2134           }
2135
2136           _dbus_assert (sub->u.array.len_pos == sub->value_pos - 4);
2137         }
2138
2139       /* Write alignment padding for array elements
2140        * Note that we write the padding *even for empty arrays*
2141        * to avoid wonky special cases
2142        */
2143       if (writer->gvariant)
2144         {
2145           int size = _dbus_type_gvariant_get_fixed_size (contained_type, contained_type_start, &alignment);
2146           if (0 == size)
2147             {
2148               sub->offsets_size = 1;
2149               sub->offsets = dbus_new (DBusString, 1);
2150               _dbus_string_init (sub->offsets);
2151             }
2152           else
2153             {
2154               sub->offsets_size = 0;
2155               sub->offsets = NULL;
2156             }
2157         }
2158       else
2159       {
2160         alignment = element_type_get_alignment (contained_type, contained_type_start);
2161       }
2162
2163       aligned = _DBUS_ALIGN_VALUE (sub->value_pos, alignment);
2164       if (aligned != sub->value_pos)
2165         {
2166           if (!is_array_append)
2167             {
2168               if (!_dbus_string_insert_bytes (sub->value_str,
2169                                               sub->value_pos,
2170                                               aligned - sub->value_pos,
2171                                               '\0'))
2172                 _dbus_assert_not_reached ("should not have failed to insert alignment padding");
2173             }
2174
2175           sub->value_pos = aligned;
2176         }
2177
2178       sub->u.array.start_pos = sub->value_pos;
2179
2180       if (is_array_append && !writer->gvariant)
2181         {
2182           dbus_uint32_t len;
2183
2184           _dbus_assert (_DBUS_ALIGN_VALUE (sub->u.array.len_pos, 4) ==
2185                         (unsigned) sub->u.array.len_pos);
2186           len = _dbus_unpack_uint32 (sub->byte_order,
2187                                      _dbus_string_get_const_data_len (sub->value_str,
2188                                                                       sub->u.array.len_pos,
2189                                                                       4));
2190
2191           sub->value_pos += len;
2192         }
2193       if (writer->gvariant)
2194         {
2195           sub->alignment = alignment;
2196           sub->is_fixed = FALSE;
2197           sub->value_start = sub->value_pos;
2198         }
2199     }
2200   else
2201     {
2202       /* not enabled, so we won't write the len_pos; set it to -1 to so indicate */
2203       sub->u.array.len_pos = -1;
2204       sub->u.array.start_pos = sub->value_pos;
2205     }
2206
2207   _dbus_assert (sub->gvariant || sub->u.array.len_pos < sub->u.array.start_pos);
2208   _dbus_assert (is_array_append || sub->u.array.start_pos == sub->value_pos);
2209
2210 #if RECURSIVE_MARSHAL_WRITE_TRACE
2211       _dbus_verbose ("  type writer %p recurse array done remaining sig '%s' array start_pos = %d len_pos = %d value_pos = %d\n", sub,
2212                      sub->type_str ?
2213                      _dbus_string_get_const_data_len (sub->type_str, sub->type_pos, 0) :
2214                      "unknown",
2215                      sub->u.array.start_pos, sub->u.array.len_pos, sub->value_pos);
2216 #endif
2217
2218   return TRUE;
2219 }
2220
2221 /* Variant value will normally have:
2222  *   1 byte signature length not including nul
2223  *   signature typecodes (nul terminated)
2224  *   padding to alignment of contained type
2225  *   body according to signature
2226  *
2227  * The signature string can only have a single type
2228  * in it but that type may be complex/recursive.
2229  *
2230  * So a typical variant type with the integer 3 will have these
2231  * octets:
2232  *   0x1 'i' '\0' [1 byte padding to alignment boundary] 0x0 0x0 0x0 0x3
2233  *
2234  * The main world of hurt for writing out a variant is that the type
2235  * string is the same string as the value string. Which means
2236  * inserting to the type string will move the value_pos; and it means
2237  * that inserting to the type string could break type alignment.
2238  */
2239 static dbus_bool_t
2240 writer_recurse_variant (DBusTypeWriter   *writer,
2241                         const DBusString *contained_type,
2242                         int               contained_type_start,
2243                         int               contained_type_len,
2244                         DBusTypeWriter   *sub)
2245 {
2246   int contained_alignment;
2247   
2248   if (writer->enabled)
2249     {
2250       /* Allocate space for the worst case, which is 1 byte sig
2251        * length, nul byte at end of sig, and 7 bytes padding to
2252        * 8-boundary.
2253        */
2254       if (!_dbus_string_alloc_space (sub->value_str, contained_type_len + 9))
2255         return FALSE;
2256     }
2257
2258   /* write VARIANT typecode to the parent's type string */
2259   if (!write_or_verify_typecode (writer, DBUS_TYPE_VARIANT))
2260     return FALSE;
2261
2262   /* If not enabled, mark that we have no type_str anymore ... */
2263
2264   if (!writer->enabled)
2265     {
2266       sub->type_str = NULL;
2267       sub->type_pos = -1;
2268
2269       return TRUE;
2270     }
2271
2272   /* If we're enabled then continue ... */
2273
2274   if (writer->gvariant)
2275     {
2276       /* GVariant case:
2277        * contents, then nul byte, then signature without nul byte.
2278        * The alignment is always 8.
2279        *
2280        * Signature is at the end of a variant. So, the easiest way is to write it down
2281        * when unrecursing. So, we need to copy it to a new string.
2282        */
2283       contained_alignment = 8;
2284       sub->alignment = 8;
2285       sub->type_str = dbus_new (DBusString, 1); /* to be deallocated on unrecurse */
2286       sub->type_pos = 0;
2287       sub->is_fixed = FALSE;
2288       _dbus_string_init_preallocated (sub->type_str, contained_type_len);
2289
2290       if (!_dbus_string_copy_len (contained_type, contained_type_start, contained_type_len,
2291                                   sub->type_str, sub->type_pos))
2292         _dbus_assert_not_reached ("should not have failed to insert variant type sig");
2293     }
2294   else
2295     {
2296       /* dbus1 case:
2297        * length, signature with nul byte, then contents
2298        * alignment depends on contents.
2299        */
2300       if (!_dbus_string_insert_byte (sub->value_str,
2301                                      sub->value_pos,
2302                                      contained_type_len))
2303         _dbus_assert_not_reached ("should not have failed to insert variant type sig len");
2304
2305       sub->value_pos += 1;
2306
2307       /* Here we switch over to the expected type sig we're about to write */
2308       sub->type_str = sub->value_str;
2309       sub->type_pos = sub->value_pos;
2310
2311       if (!_dbus_string_copy_len (contained_type, contained_type_start, contained_type_len,
2312                                   sub->value_str, sub->value_pos))
2313         _dbus_assert_not_reached ("should not have failed to insert variant type sig");
2314
2315       sub->value_pos += contained_type_len;
2316
2317       if (!_dbus_string_insert_byte (sub->value_str,
2318                                      sub->value_pos,
2319                                      DBUS_TYPE_INVALID))
2320         _dbus_assert_not_reached ("should not have failed to insert variant type nul termination");
2321
2322       sub->value_pos += 1;
2323
2324       contained_alignment = _dbus_type_get_alignment (_dbus_first_type_in_signature (contained_type, contained_type_start));
2325     }
2326   
2327   if (!_dbus_string_insert_bytes (sub->value_str,
2328                                   sub->value_pos,
2329                                   _DBUS_ALIGN_VALUE (sub->value_pos, contained_alignment) - sub->value_pos,
2330                                   '\0'))
2331     _dbus_assert_not_reached ("should not have failed to insert alignment padding for variant body");
2332   sub->value_pos = _DBUS_ALIGN_VALUE (sub->value_pos, contained_alignment);
2333   sub->value_start = sub->value_pos;
2334
2335   return TRUE;
2336 }
2337
2338 static dbus_bool_t
2339 _dbus_type_writer_recurse_contained_len (DBusTypeWriter   *writer,
2340                                          int               container_type,
2341                                          const DBusString *contained_type,
2342                                          int               contained_type_start,
2343                                          int               contained_type_len,
2344                                          DBusTypeWriter   *sub,
2345                                          dbus_bool_t       is_array_append)
2346 {
2347   writer_recurse_init_and_check (writer, container_type, sub);
2348
2349   switch (container_type)
2350     {
2351     case DBUS_TYPE_STRUCT:
2352       return writer_recurse_struct_or_dict_entry (writer,
2353                                                   DBUS_STRUCT_BEGIN_CHAR,
2354                                                   contained_type,
2355                                                   contained_type_start, contained_type_len,
2356                                                   sub);
2357       break;
2358     case DBUS_TYPE_DICT_ENTRY:
2359       return writer_recurse_struct_or_dict_entry (writer,
2360                                                   DBUS_DICT_ENTRY_BEGIN_CHAR,
2361                                                   contained_type,
2362                                                   contained_type_start, contained_type_len,
2363                                                   sub);
2364       break;
2365     case DBUS_TYPE_ARRAY:
2366       return writer_recurse_array (writer,
2367                                    contained_type, contained_type_start, contained_type_len,
2368                                    sub, is_array_append);
2369       break;
2370     case DBUS_TYPE_VARIANT:
2371       return writer_recurse_variant (writer,
2372                                      contained_type, contained_type_start, contained_type_len,
2373                                      sub);
2374       break;
2375     default:
2376       _dbus_assert_not_reached ("tried to recurse into type that doesn't support that");
2377       return FALSE;
2378       break;
2379     }
2380 }
2381
2382 /**
2383  * Opens a new container and writes out the initial information for that container.
2384  *
2385  * @param writer the writer
2386  * @param container_type the type of the container to open
2387  * @param contained_type the array element type or variant content type
2388  * @param contained_type_start position to look for the type
2389  * @param sub the new sub-writer to write container contents
2390  * @returns #FALSE if no memory
2391  */
2392 dbus_bool_t
2393 _dbus_type_writer_recurse (DBusTypeWriter   *writer,
2394                            int               container_type,
2395                            const DBusString *contained_type,
2396                            int               contained_type_start,
2397                            DBusTypeWriter   *sub)
2398 {
2399   int contained_type_len;
2400
2401   if (contained_type)
2402     contained_type_len = find_len_of_complete_type (contained_type, contained_type_start);
2403   else
2404     contained_type_len = 0;
2405
2406   sub->body_container = FALSE;
2407
2408   return _dbus_type_writer_recurse_contained_len (writer, container_type,
2409                                                   contained_type,
2410                                                   contained_type_start,
2411                                                   contained_type_len,
2412                                                   sub,
2413                                                   FALSE);
2414 }
2415
2416 /**
2417  * Append to an existing array. Essentially, the writer will read an
2418  * existing length at the write location; jump over that length; and
2419  * write new fields. On unrecurse(), the existing length will be
2420  * updated.
2421  *
2422  * @param writer the writer
2423  * @param contained_type element type
2424  * @param contained_type_start position of element type
2425  * @param sub the subwriter to init
2426  * @returns #FALSE if no memory
2427  */
2428 dbus_bool_t
2429 _dbus_type_writer_append_array (DBusTypeWriter   *writer,
2430                                 const DBusString *contained_type,
2431                                 int               contained_type_start,
2432                                 DBusTypeWriter   *sub)
2433 {
2434   int contained_type_len;
2435
2436   if (contained_type)
2437     contained_type_len = find_len_of_complete_type (contained_type, contained_type_start);
2438   else
2439     contained_type_len = 0;
2440
2441   return _dbus_type_writer_recurse_contained_len (writer, DBUS_TYPE_ARRAY,
2442                                                   contained_type,
2443                                                   contained_type_start,
2444                                                   contained_type_len,
2445                                                   sub,
2446                                                   TRUE);
2447 }
2448
2449 static int
2450 writer_get_array_len (DBusTypeWriter *writer)
2451 {
2452   _dbus_assert (writer->container_type == DBUS_TYPE_ARRAY);
2453   return writer->value_pos - writer->u.array.start_pos;
2454 }
2455
2456 static dbus_bool_t
2457 _dbus_type_writer_unrecurse_write (DBusTypeWriter *writer,
2458                                    DBusTypeWriter *sub)
2459 {
2460   if (sub->container_type == DBUS_TYPE_STRUCT)
2461     {
2462       if (!write_or_verify_typecode (sub, DBUS_STRUCT_END_CHAR))
2463         return FALSE;
2464     }
2465   else if (sub->container_type == DBUS_TYPE_DICT_ENTRY)
2466     {
2467       if (!write_or_verify_typecode (sub, DBUS_DICT_ENTRY_END_CHAR))
2468         return FALSE;
2469     }
2470   else if (sub->container_type == DBUS_TYPE_ARRAY && !sub->gvariant)
2471     {
2472       if (sub->u.array.len_pos >= 0) /* len_pos == -1 if we weren't enabled when we passed it */
2473         {
2474           dbus_uint32_t len;
2475
2476           /* Set the array length */
2477           len = writer_get_array_len (sub);
2478           _dbus_marshal_set_uint32 (sub->value_str,
2479                                     sub->u.array.len_pos,
2480                                     len,
2481                                     sub->byte_order);
2482 #if RECURSIVE_MARSHAL_WRITE_TRACE
2483           _dbus_verbose ("    filled in sub array len to %u at len_pos %d\n",
2484                          len, sub->u.array.len_pos);
2485 #endif
2486         }
2487 #if RECURSIVE_MARSHAL_WRITE_TRACE
2488       else
2489         {
2490           _dbus_verbose ("    not filling in sub array len because we were disabled when we passed the len\n");
2491         }
2492 #endif
2493     }
2494   return TRUE;
2495 }
2496
2497 /**
2498  * Closes a container created by _dbus_type_writer_recurse()
2499  * and writes any additional information to the values block.
2500  *
2501  * @param writer the writer
2502  * @param sub the sub-writer created by _dbus_type_writer_recurse()
2503  * @returns #FALSE if no memory
2504  */
2505 dbus_bool_t
2506 _dbus_type_writer_unrecurse (DBusTypeWriter *writer,
2507                              DBusTypeWriter *sub)
2508 {
2509   /* type_pos_is_expectation never gets unset once set, or we'd get all hosed */
2510   _dbus_assert (!writer->type_pos_is_expectation ||
2511                 (writer->type_pos_is_expectation && sub->type_pos_is_expectation));
2512
2513 #if RECURSIVE_MARSHAL_WRITE_TRACE
2514   _dbus_verbose ("  type writer %p unrecurse type_pos = %d value_pos = %d is_expectation = %d container_type = %s\n",
2515                  writer, writer->type_pos, writer->value_pos, writer->type_pos_is_expectation,
2516                  _dbus_type_to_string (writer->container_type));
2517   _dbus_verbose ("  type writer %p unrecurse sub type_pos = %d value_pos = %d is_expectation = %d container_type = %s\n",
2518                  sub, sub->type_pos, sub->value_pos,
2519                  sub->type_pos_is_expectation,
2520                  _dbus_type_to_string (sub->container_type));
2521 #endif
2522
2523   if (!_dbus_type_writer_unrecurse_write (writer, sub))
2524     return FALSE;
2525
2526   if (writer->gvariant)
2527     {
2528       if (!_dbus_writer_unrecurse_gvariant_write (writer, sub))
2529         return FALSE;
2530     }
2531   else
2532     writer->value_pos = sub->value_pos;
2533
2534
2535   /* Now get type_pos right for the parent writer. Here are the cases:
2536    *
2537    * Cases !writer->type_pos_is_expectation:
2538    *   (in these cases we want to update to the new insertion point)
2539    *
2540    * - if we recursed into a STRUCT then we didn't know in advance
2541    *   what the types in the struct would be; so we have to fill in
2542    *   that information now.
2543    *       writer->type_pos = sub->type_pos
2544    *
2545    * - if we recursed into anything else, we knew the full array
2546    *   type, or knew the single typecode marking VARIANT, so
2547    *   writer->type_pos is already correct.
2548    *       writer->type_pos should remain as-is
2549    *
2550    * - note that the parent is never an ARRAY or VARIANT, if it were
2551    *   then type_pos_is_expectation would be TRUE. The parent
2552    *   is thus known to be a toplevel or STRUCT.
2553    *
2554    * Cases where writer->type_pos_is_expectation:
2555    *   (in these cases we want to update to next expected type to write)
2556    *
2557    * - we recursed from STRUCT into STRUCT and we didn't increment
2558    *   type_pos in the parent just to stay consistent with the
2559    *   !writer->type_pos_is_expectation case (though we could
2560    *   special-case this in recurse_struct instead if we wanted)
2561    *       writer->type_pos = sub->type_pos
2562    *
2563    * - we recursed from STRUCT into ARRAY or VARIANT and type_pos
2564    *   for parent should have been incremented already
2565    *       writer->type_pos should remain as-is
2566    *
2567    * - we recursed from ARRAY into a sub-element, so type_pos in the
2568    *   parent is the element type and should remain the element type
2569    *   for the benefit of the next child element
2570    *       writer->type_pos should remain as-is
2571    *
2572    * - we recursed from VARIANT into its value, so type_pos in the
2573    *   parent makes no difference since there's only one value
2574    *   and we just finished writing it and won't use type_pos again
2575    *       writer->type_pos should remain as-is
2576    *
2577    *
2578    * For all these, DICT_ENTRY is the same as STRUCT
2579    */
2580   if (writer->type_str != NULL)
2581     {
2582       if ((sub->container_type == DBUS_TYPE_STRUCT ||
2583            sub->container_type == DBUS_TYPE_DICT_ENTRY) &&
2584           (writer->container_type == DBUS_TYPE_STRUCT ||
2585            writer->container_type == DBUS_TYPE_DICT_ENTRY ||
2586            writer->container_type == DBUS_TYPE_INVALID))
2587         {
2588           /* Advance the parent to the next struct field */
2589           writer->type_pos = sub->type_pos;
2590         }
2591     }
2592
2593 #if RECURSIVE_MARSHAL_WRITE_TRACE
2594   _dbus_verbose ("  type writer %p unrecursed type_pos = %d value_pos = %d remaining sig '%s'\n",
2595                  writer, writer->type_pos, writer->value_pos,
2596                  writer->type_str ?
2597                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0) :
2598                  "unknown");
2599 #endif
2600
2601   return TRUE;
2602 }
2603
2604 /**
2605  * Writes out a basic type.
2606  *
2607  * @param writer the writer
2608  * @param type the type to write
2609  * @param value the address of the value to write
2610  * @returns #FALSE if no memory
2611  */
2612 dbus_bool_t
2613 _dbus_type_writer_write_basic (DBusTypeWriter *writer,
2614                                int             type,
2615                                const void     *value)
2616 {
2617   dbus_bool_t retval;
2618
2619   /* First ensure that our type realloc will succeed */
2620   if (!writer->type_pos_is_expectation && writer->type_str != NULL)
2621     {
2622       if (!_dbus_string_alloc_space (writer->type_str, 1))
2623         return FALSE;
2624     }
2625
2626   retval = FALSE;
2627
2628   if (!_dbus_type_writer_write_basic_no_typecode (writer, type, value))
2629     goto out;
2630
2631   if (!write_or_verify_typecode (writer, type))
2632     _dbus_assert_not_reached ("failed to write typecode after prealloc");
2633
2634   retval = TRUE;
2635
2636  out:
2637 #if RECURSIVE_MARSHAL_WRITE_TRACE
2638   _dbus_verbose ("  type writer %p basic type_pos = %d value_pos = %d is_expectation = %d enabled = %d\n",
2639                  writer, writer->type_pos, writer->value_pos, writer->type_pos_is_expectation,
2640                  writer->enabled);
2641 #endif
2642
2643   return retval;
2644 }
2645
2646 /**
2647  * Writes a block of fixed-length basic values, i.e. those that are
2648  * both dbus_type_is_fixed() and _dbus_type_is_basic(). The block
2649  * must be written inside an array.
2650  *
2651  * The value parameter should be the address of said array of values,
2652  * so e.g. if it's an array of double, pass in "const double**"
2653  *
2654  * @param writer the writer
2655  * @param element_type type of stuff in the array
2656  * @param value address of the array
2657  * @param n_elements number of elements in the array
2658  * @returns #FALSE if no memory
2659  */
2660 dbus_bool_t
2661 _dbus_type_writer_write_fixed_multi (DBusTypeWriter        *writer,
2662                                      int                    element_type,
2663                                      const void            *value,
2664                                      int                    n_elements)
2665 {
2666   _dbus_assert (writer->container_type == DBUS_TYPE_ARRAY);
2667   _dbus_assert (dbus_type_is_fixed (element_type));
2668   _dbus_assert (writer->type_pos_is_expectation);
2669   _dbus_assert (n_elements >= 0);
2670
2671 #if RECURSIVE_MARSHAL_WRITE_TRACE
2672   _dbus_verbose ("  type writer %p entering fixed multi type_pos = %d value_pos = %d n_elements %d\n",
2673                  writer, writer->type_pos, writer->value_pos, n_elements);
2674 #endif
2675
2676   if (!write_or_verify_typecode (writer, element_type))
2677     _dbus_assert_not_reached ("OOM should not happen if only verifying typecode");
2678
2679   if (writer->enabled)
2680     {
2681       if (!_dbus_marshal_write_fixed_multi (writer->value_str,
2682                                             writer->value_pos,
2683                                             element_type,
2684                                             value,
2685                                             n_elements,
2686                                             writer->byte_order,
2687                                             &writer->value_pos))
2688         return FALSE;
2689     }
2690
2691 #if RECURSIVE_MARSHAL_WRITE_TRACE
2692   _dbus_verbose ("  type writer %p fixed multi written new type_pos = %d new value_pos = %d n_elements %d\n",
2693                  writer, writer->type_pos, writer->value_pos, n_elements);
2694 #endif
2695
2696   return TRUE;
2697 }
2698
2699 static void
2700 enable_if_after (DBusTypeWriter       *writer,
2701                  DBusTypeReader       *reader,
2702                  const DBusTypeReader *start_after)
2703 {
2704   if (start_after)
2705     {
2706       if (!writer->enabled && _dbus_type_reader_greater_than (reader, start_after))
2707         {
2708           _dbus_type_writer_set_enabled (writer, TRUE);
2709 #if RECURSIVE_MARSHAL_WRITE_TRACE
2710           _dbus_verbose ("ENABLING writer %p at %d because reader at value_pos %d is after reader at value_pos %d\n",
2711                          writer, writer->value_pos, reader->value_pos, start_after->value_pos);
2712 #endif
2713         }
2714
2715       _dbus_assert ((!writer->enabled && !_dbus_type_reader_greater_than (reader, start_after)) ||
2716                     (writer->enabled && _dbus_type_reader_greater_than (reader, start_after)));
2717     }
2718 }
2719
2720 static dbus_bool_t
2721 append_fixup (DBusList               **fixups,
2722               const DBusArrayLenFixup *fixup)
2723 {
2724   DBusArrayLenFixup *f;
2725
2726   f = dbus_new (DBusArrayLenFixup, 1);
2727   if (f == NULL)
2728     return FALSE;
2729
2730   *f = *fixup;
2731
2732   if (!_dbus_list_append (fixups, f))
2733     {
2734       dbus_free (f);
2735       return FALSE;
2736     }
2737
2738   _dbus_assert (f->len_pos_in_reader == fixup->len_pos_in_reader);
2739   _dbus_assert (f->new_len == fixup->new_len);
2740
2741   return TRUE;
2742 }
2743
2744 /* This loop is trivial if you ignore all the start_after nonsense,
2745  * so if you're trying to figure it out, start by ignoring that
2746  */
2747 static dbus_bool_t
2748 writer_write_reader_helper (DBusTypeWriter       *writer,
2749                             DBusTypeReader       *reader,
2750                             const DBusTypeReader *start_after,
2751                             int                   start_after_new_pos,
2752                             int                   start_after_new_len,
2753                             DBusList            **fixups,
2754                             dbus_bool_t           inside_start_after)
2755 {
2756   int current_type;
2757
2758   while ((current_type = _dbus_type_reader_get_current_type (reader)) != DBUS_TYPE_INVALID)
2759     {
2760       if (dbus_type_is_container (current_type))
2761         {
2762           DBusTypeReader subreader;
2763           DBusTypeWriter subwriter;
2764           const DBusString *sig_str;
2765           int sig_start;
2766           int sig_len;
2767           dbus_bool_t enabled_at_recurse;
2768           dbus_bool_t past_start_after;
2769           int reader_array_len_pos;
2770           int reader_array_start_pos;
2771           dbus_bool_t this_is_start_after;
2772
2773           /* type_pos is checked since e.g. in a struct the struct
2774            * and its first field have the same value_pos.
2775            * type_str will differ in reader/start_after for variants
2776            * where type_str is inside the value_str
2777            */
2778           if (!inside_start_after && start_after &&
2779               reader->value_pos == start_after->value_pos &&
2780               reader->type_str == start_after->type_str &&
2781               reader->type_pos == start_after->type_pos)
2782             this_is_start_after = TRUE;
2783           else
2784             this_is_start_after = FALSE;
2785
2786           _dbus_type_reader_recurse (reader, &subreader);
2787
2788           if (current_type == DBUS_TYPE_ARRAY)
2789             {
2790               reader_array_len_pos = ARRAY_READER_LEN_POS (&subreader);
2791               reader_array_start_pos = subreader.u.array.start_pos;
2792             }
2793           else
2794             {
2795               /* quiet gcc */
2796               reader_array_len_pos = -1;
2797               reader_array_start_pos = -1;
2798             }
2799
2800           _dbus_type_reader_get_signature (&subreader, &sig_str,
2801                                            &sig_start, &sig_len);
2802
2803 #if RECURSIVE_MARSHAL_WRITE_TRACE
2804           _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",
2805                          _dbus_type_to_string (current_type),
2806                          reader->value_pos,
2807                          subreader.value_pos,
2808                          writer->value_pos,
2809                          start_after ? start_after->value_pos : -1,
2810                          _dbus_string_get_length (writer->value_str),
2811                          inside_start_after, this_is_start_after);
2812 #endif
2813
2814           if (!inside_start_after && !this_is_start_after)
2815             enable_if_after (writer, &subreader, start_after);
2816           enabled_at_recurse = writer->enabled;
2817           if (!_dbus_type_writer_recurse_contained_len (writer, current_type,
2818                                                         sig_str, sig_start, sig_len,
2819                                                         &subwriter, FALSE))
2820             goto oom;
2821
2822 #if RECURSIVE_MARSHAL_WRITE_TRACE
2823           _dbus_verbose ("recursed into subwriter at %d write target len %d\n",
2824                          subwriter.value_pos,
2825                          _dbus_string_get_length (subwriter.value_str));
2826 #endif
2827
2828           if (!writer_write_reader_helper (&subwriter, &subreader, start_after,
2829                                            start_after_new_pos, start_after_new_len,
2830                                            fixups,
2831                                            inside_start_after ||
2832                                            this_is_start_after))
2833             goto oom;
2834
2835 #if RECURSIVE_MARSHAL_WRITE_TRACE
2836           _dbus_verbose ("about to unrecurse from %s subreader at %d writer at %d subwriter at %d  write target len %d\n",
2837                          _dbus_type_to_string (current_type),
2838                          subreader.value_pos,
2839                          writer->value_pos,
2840                          subwriter.value_pos,
2841                          _dbus_string_get_length (writer->value_str));
2842 #endif
2843
2844           if (!inside_start_after && !this_is_start_after)
2845             enable_if_after (writer, &subreader, start_after);
2846           past_start_after = writer->enabled;
2847           if (!_dbus_type_writer_unrecurse (writer, &subwriter))
2848             goto oom;
2849
2850           /* If we weren't enabled when we recursed, we didn't
2851            * write an array len; if we passed start_after
2852            * somewhere inside the array, then we need to generate
2853            * a fixup.
2854            */
2855           if (start_after != NULL &&
2856               !enabled_at_recurse && past_start_after &&
2857               current_type == DBUS_TYPE_ARRAY &&
2858               fixups != NULL)
2859             {
2860               DBusArrayLenFixup fixup;
2861               int bytes_written_after_start_after;
2862               int bytes_before_start_after;
2863               int old_len;
2864
2865               /* this subwriter access is moderately unkosher since we
2866                * already unrecursed, but it works as long as unrecurse
2867                * doesn't break us on purpose
2868                */
2869               bytes_written_after_start_after = writer_get_array_len (&subwriter);
2870
2871               bytes_before_start_after =
2872                 start_after->value_pos - reader_array_start_pos;
2873
2874               fixup.len_pos_in_reader = reader_array_len_pos;
2875               fixup.new_len =
2876                 bytes_before_start_after +
2877                 start_after_new_len +
2878                 bytes_written_after_start_after;
2879
2880               _dbus_assert (_DBUS_ALIGN_VALUE (fixup.len_pos_in_reader, 4) ==
2881                             (unsigned) fixup.len_pos_in_reader);
2882
2883               old_len = _dbus_unpack_uint32 (reader->byte_order,
2884                                              _dbus_string_get_const_data_len (reader->value_str,
2885                                                                               fixup.len_pos_in_reader, 4));
2886
2887               if (old_len != fixup.new_len && !append_fixup (fixups, &fixup))
2888                 goto oom;
2889
2890 #if RECURSIVE_MARSHAL_WRITE_TRACE
2891               _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",
2892                              fixup.len_pos_in_reader,
2893                              fixup.new_len,
2894                              reader_array_start_pos,
2895                              start_after->value_pos,
2896                              bytes_before_start_after,
2897                              start_after_new_len,
2898                              bytes_written_after_start_after);
2899 #endif
2900             }
2901         }
2902       else
2903         {
2904           DBusBasicValue val;
2905
2906           _dbus_assert (dbus_type_is_basic (current_type));
2907
2908 #if RECURSIVE_MARSHAL_WRITE_TRACE
2909           _dbus_verbose ("Reading basic value %s at %d\n",
2910                          _dbus_type_to_string (current_type),
2911                          reader->value_pos);
2912 #endif
2913
2914           _dbus_type_reader_read_basic (reader, &val);
2915
2916 #if RECURSIVE_MARSHAL_WRITE_TRACE
2917           _dbus_verbose ("Writing basic value %s at %d write target len %d inside_start_after = %d\n",
2918                          _dbus_type_to_string (current_type),
2919                          writer->value_pos,
2920                          _dbus_string_get_length (writer->value_str),
2921                          inside_start_after);
2922 #endif
2923           if (!inside_start_after)
2924             enable_if_after (writer, reader, start_after);
2925           if (!_dbus_type_writer_write_basic (writer, current_type, &val))
2926             goto oom;
2927 #if RECURSIVE_MARSHAL_WRITE_TRACE
2928           _dbus_verbose ("Wrote basic value %s, new value_pos %d write target len %d\n",
2929                          _dbus_type_to_string (current_type),
2930                          writer->value_pos,
2931                          _dbus_string_get_length (writer->value_str));
2932 #endif
2933         }
2934
2935       _dbus_type_reader_next (reader);
2936     }
2937
2938   return TRUE;
2939
2940  oom:
2941   if (fixups)
2942     apply_and_free_fixups (fixups, NULL); /* NULL for reader to apply to */
2943
2944   return FALSE;
2945 }
2946
2947 /*
2948  * Iterate through all values in the given reader, writing a copy of
2949  * each value to the writer.  The reader will be moved forward to its
2950  * end position.
2951  *
2952  * If a reader start_after is provided, it should be a reader for the
2953  * same data as the reader to be written. Only values occurring after
2954  * the value pointed to by start_after will be written to the writer.
2955  *
2956  * If start_after is provided, then the copy of the reader will be
2957  * partial. This means that array lengths will not have been copied.
2958  * The assumption is that you wrote a new version of the value at
2959  * start_after to the writer. You have to pass in the start position
2960  * and length of the new value. (If you are deleting the value
2961  * at start_after, pass in 0 for the length.)
2962  *
2963  * If the fixups parameter is non-#NULL, then any array length that
2964  * was read but not written due to start_after will be provided
2965  * as a #DBusArrayLenFixup. The fixup contains the position of the
2966  * array length in the source data, and the correct array length
2967  * assuming you combine the source data before start_after with
2968  * the written data at start_after and beyond.
2969  *
2970  * @param writer the writer to copy to
2971  * @param reader the reader to copy from
2972  * @param start_after #NULL or a reader showing where to start
2973  * @param start_after_new_pos the position of start_after equivalent in the target data
2974  * @param start_after_new_len the length of start_after equivalent in the target data
2975  * @param fixups list to append #DBusArrayLenFixup if the write was partial
2976  * @returns #FALSE if no memory
2977  */
2978 static dbus_bool_t
2979 _dbus_type_writer_write_reader_partial (DBusTypeWriter       *writer,
2980                                         DBusTypeReader       *reader,
2981                                         const DBusTypeReader *start_after,
2982                                         int                   start_after_new_pos,
2983                                         int                   start_after_new_len,
2984                                         DBusList            **fixups)
2985 {
2986   DBusTypeWriter orig;
2987   int orig_type_len;
2988   int orig_value_len;
2989   int new_bytes;
2990   int orig_enabled;
2991
2992   orig = *writer;
2993   orig_type_len = _dbus_string_get_length (writer->type_str);
2994   orig_value_len = _dbus_string_get_length (writer->value_str);
2995   orig_enabled = writer->enabled;
2996
2997   if (start_after)
2998     _dbus_type_writer_set_enabled (writer, FALSE);
2999
3000   if (!writer_write_reader_helper (writer, reader, start_after,
3001                                    start_after_new_pos,
3002                                    start_after_new_len,
3003                                    fixups, FALSE))
3004     goto oom;
3005
3006   _dbus_type_writer_set_enabled (writer, orig_enabled);
3007   return TRUE;
3008
3009  oom:
3010   if (!writer->type_pos_is_expectation)
3011     {
3012       new_bytes = _dbus_string_get_length (writer->type_str) - orig_type_len;
3013       _dbus_string_delete (writer->type_str, orig.type_pos, new_bytes);
3014     }
3015   new_bytes = _dbus_string_get_length (writer->value_str) - orig_value_len;
3016   _dbus_string_delete (writer->value_str, orig.value_pos, new_bytes);
3017
3018   *writer = orig;
3019
3020   return FALSE;
3021 }
3022
3023 /**
3024  * Iterate through all values in the given reader, writing a copy of
3025  * each value to the writer.  The reader will be moved forward to its
3026  * end position.
3027  *
3028  * @param writer the writer to copy to
3029  * @param reader the reader to copy from
3030  * @returns #FALSE if no memory
3031  */
3032 dbus_bool_t
3033 _dbus_type_writer_write_reader (DBusTypeWriter       *writer,
3034                                 DBusTypeReader       *reader)
3035 {
3036   return _dbus_type_writer_write_reader_partial (writer, reader, NULL, 0, 0, NULL);
3037 }
3038
3039 /*
3040  * If disabled, a writer can still be iterated forward and recursed/unrecursed
3041  * but won't write any values. Types will still be written unless the
3042  * writer is a "values only" writer, because the writer needs access to
3043  * a valid signature to be able to iterate.
3044  *
3045  * @param writer the type writer
3046  * @param enabled #TRUE if values should be written
3047  */
3048 static void
3049 _dbus_type_writer_set_enabled (DBusTypeWriter   *writer,
3050                                dbus_bool_t       enabled)
3051 {
3052   writer->enabled = enabled != FALSE;
3053 }
3054
3055 /** @} */ /* end of DBusMarshal group */
3056
3057 /* tests in dbus-marshal-recursive-util.c */