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