2005-01-16 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 first_type_in_signature (const DBusString *str,
127                          int               pos)
128 {
129   unsigned char t;
130
131   t = _dbus_string_get_byte (str, pos);
132
133   if (t == DBUS_STRUCT_BEGIN_CHAR)
134     return DBUS_TYPE_STRUCT;
135   else
136     return t;
137 }
138
139 static int
140 element_type_get_alignment (const DBusString *str,
141                             int               pos)
142 {
143   return _dbus_type_get_alignment (first_type_in_signature (str, pos));
144 }
145
146 static void
147 reader_init (DBusTypeReader    *reader,
148              int                byte_order,
149              const DBusString  *type_str,
150              int                type_pos,
151              const DBusString  *value_str,
152              int                value_pos)
153 {
154   reader->byte_order = byte_order;
155   reader->finished = FALSE;
156   reader->type_str = type_str;
157   reader->type_pos = type_pos;
158   reader->value_str = value_str;
159   reader->value_pos = value_pos;
160 }
161
162 static void
163 base_reader_recurse (DBusTypeReader *sub,
164                      DBusTypeReader *parent)
165 {
166   /* point subreader at the same place as parent */
167   reader_init (sub,
168                parent->byte_order,
169                parent->type_str,
170                parent->type_pos,
171                parent->value_str,
172                parent->value_pos);
173 }
174
175 static void
176 struct_types_only_reader_recurse (DBusTypeReader *sub,
177                                   DBusTypeReader *parent)
178 {
179   base_reader_recurse (sub, parent);
180
181   _dbus_assert (_dbus_string_get_byte (sub->type_str,
182                                        sub->type_pos) == DBUS_STRUCT_BEGIN_CHAR);
183
184   sub->type_pos += 1;
185 }
186
187 static void
188 struct_reader_recurse (DBusTypeReader *sub,
189                        DBusTypeReader *parent)
190 {
191   struct_types_only_reader_recurse (sub, parent);
192
193   /* struct has 8 byte alignment */
194   sub->value_pos = _DBUS_ALIGN_VALUE (sub->value_pos, 8);
195 }
196
197 static void
198 array_types_only_reader_recurse (DBusTypeReader *sub,
199                                  DBusTypeReader *parent)
200 {
201   base_reader_recurse (sub, parent);
202
203   /* point type_pos at the array element type */
204   sub->type_pos += 1;
205
206   /* Init with values likely to crash things if misused */
207   sub->u.array.start_pos = _DBUS_INT_MAX;
208   sub->array_len_offset = 7;
209 }
210
211 /** compute position of array length given array_len_offset, which is
212     the offset back from start_pos to end of the len */
213 #define ARRAY_READER_LEN_POS(reader) \
214   ((reader)->u.array.start_pos - ((int)(reader)->array_len_offset) - 4)
215
216 static int
217 array_reader_get_array_len (const DBusTypeReader *reader)
218 {
219   dbus_uint32_t array_len;
220   int len_pos;
221
222   len_pos = ARRAY_READER_LEN_POS (reader);
223
224   _dbus_assert (_DBUS_ALIGN_VALUE (len_pos, 4) == (unsigned) len_pos);
225   array_len = _dbus_unpack_uint32 (reader->byte_order,
226                                    _dbus_string_get_const_data_len (reader->value_str, len_pos, 4));
227
228 #if RECURSIVE_MARSHAL_READ_TRACE
229   _dbus_verbose ("   reader %p len_pos %d array len %u len_offset %d\n",
230                  reader, len_pos, array_len, reader->array_len_offset);
231 #endif
232
233   _dbus_assert (reader->u.array.start_pos - len_pos - 4 < 8);
234
235   return array_len;
236 }
237
238 static void
239 array_reader_recurse (DBusTypeReader *sub,
240                       DBusTypeReader *parent)
241 {
242   int alignment;
243   int len_pos;
244
245   array_types_only_reader_recurse (sub, parent);
246
247   sub->value_pos = _DBUS_ALIGN_VALUE (sub->value_pos, 4);
248
249   len_pos = sub->value_pos;
250
251   sub->value_pos += 4; /* for the length */
252
253   alignment = element_type_get_alignment (sub->type_str,
254                                           sub->type_pos);
255
256   sub->value_pos = _DBUS_ALIGN_VALUE (sub->value_pos, alignment);
257
258   sub->u.array.start_pos = sub->value_pos;
259   _dbus_assert ((sub->u.array.start_pos - (len_pos + 4)) < 8); /* only 3 bits in array_len_offset */
260   sub->array_len_offset = sub->u.array.start_pos - (len_pos + 4);
261
262 #if RECURSIVE_MARSHAL_READ_TRACE
263   _dbus_verbose ("    type reader %p array start = %d len_offset = %d array len = %d array element type = %s\n",
264                  sub,
265                  sub->u.array.start_pos,
266                  sub->array_len_offset,
267                  array_reader_get_array_len (sub),
268                  _dbus_type_to_string (first_type_in_signature (sub->type_str,
269                                                                 sub->type_pos)));
270 #endif
271 }
272
273 static void
274 variant_reader_recurse (DBusTypeReader *sub,
275                         DBusTypeReader *parent)
276 {
277   int sig_len;
278
279   base_reader_recurse (sub, parent);
280
281   /* Variant is 1 byte sig length (without nul), signature with nul,
282    * padding to 8-boundary, then values
283    */
284
285   sig_len = _dbus_string_get_byte (sub->value_str, sub->value_pos);
286
287   sub->type_str = sub->value_str;
288   sub->type_pos = sub->value_pos + 1;
289
290   sub->value_pos = sub->type_pos + sig_len + 1;
291
292   sub->value_pos = _DBUS_ALIGN_VALUE (sub->value_pos, 8);
293
294 #if RECURSIVE_MARSHAL_READ_TRACE
295   _dbus_verbose ("    type reader %p variant containing '%s'\n",
296                  sub,
297                  _dbus_string_get_const_data_len (sub->type_str,
298                                                   sub->type_pos, 0));
299 #endif
300 }
301
302 static dbus_bool_t
303 array_reader_check_finished (const DBusTypeReader *reader)
304 {
305   int end_pos;
306
307   /* return the array element type if elements remain, and
308    * TYPE_INVALID otherwise
309    */
310
311   end_pos = reader->u.array.start_pos + array_reader_get_array_len (reader);
312
313   _dbus_assert (reader->value_pos <= end_pos);
314   _dbus_assert (reader->value_pos >= reader->u.array.start_pos);
315
316   return reader->value_pos == end_pos;
317 }
318
319 /* this is written a little oddly to try and overoptimize */
320 static void
321 skip_one_complete_type (const DBusString *type_str,
322                         int              *type_pos)
323 {
324   const unsigned char *p;
325   const unsigned char *start;
326
327   _dbus_assert (type_str != NULL);
328   _dbus_assert (type_pos != NULL);
329   
330   start = _dbus_string_get_const_data (type_str);
331   p = start + *type_pos;
332
333   _dbus_assert (*p != DBUS_STRUCT_END_CHAR);
334   
335   while (*p == DBUS_TYPE_ARRAY)
336     ++p;
337
338   _dbus_assert (*p != DBUS_STRUCT_END_CHAR);
339   
340   if (*p == DBUS_STRUCT_BEGIN_CHAR)
341     {
342       int depth;
343
344       depth = 1;
345
346       while (TRUE)
347         {
348           _dbus_assert (*p != DBUS_TYPE_INVALID);
349
350           ++p;
351
352           _dbus_assert (*p != DBUS_TYPE_INVALID);
353
354           if (*p == DBUS_STRUCT_BEGIN_CHAR)
355             depth += 1;
356           else if (*p == DBUS_STRUCT_END_CHAR)
357             {
358               depth -= 1;
359               if (depth == 0)
360                 {
361                   ++p;
362                   break;
363                 }
364             }
365         }
366     }
367   else
368     {
369       ++p;
370     }
371
372   *type_pos = (int) (p - start);
373 }
374
375 static int
376 find_len_of_complete_type (const DBusString *type_str,
377                            int               type_pos)
378 {
379   int end;
380
381   end = type_pos;
382
383   skip_one_complete_type (type_str, &end);
384
385   return end - type_pos;
386 }
387
388 static void
389 base_reader_next (DBusTypeReader *reader,
390                   int             current_type)
391 {
392   switch (current_type)
393     {
394     case DBUS_TYPE_STRUCT:
395     case DBUS_TYPE_VARIANT:
396       /* Scan forward over the entire container contents */
397       {
398         DBusTypeReader sub;
399
400         if (reader->klass->types_only && current_type == DBUS_TYPE_VARIANT)
401           ;
402         else
403           {
404             /* Recurse into the struct or variant */
405             _dbus_type_reader_recurse (reader, &sub);
406
407             /* Skip everything in this subreader */
408             while (_dbus_type_reader_next (&sub))
409               {
410                 /* nothing */;
411               }
412           }
413         if (!reader->klass->types_only)
414           reader->value_pos = sub.value_pos;
415
416         /* Now we are at the end of this container; for variants, the
417          * subreader's type_pos is totally inapplicable (it's in the
418          * value string) but we know that we increment by one past the
419          * DBUS_TYPE_VARIANT
420          */
421         if (current_type == DBUS_TYPE_VARIANT)
422           reader->type_pos += 1;
423         else
424           reader->type_pos = sub.type_pos;
425       }
426       break;
427
428     case DBUS_TYPE_ARRAY:
429       {
430         if (!reader->klass->types_only)
431           _dbus_marshal_skip_array (reader->value_str,
432                                     first_type_in_signature (reader->type_str,
433                                                              reader->type_pos + 1),
434                                     reader->byte_order,
435                                     &reader->value_pos);
436
437         skip_one_complete_type (reader->type_str, &reader->type_pos);
438       }
439       break;
440
441     default:
442       if (!reader->klass->types_only)
443         _dbus_marshal_skip_basic (reader->value_str,
444                                   current_type, reader->byte_order,
445                                   &reader->value_pos);
446
447       reader->type_pos += 1;
448       break;
449     }
450 }
451
452 static void
453 struct_reader_next (DBusTypeReader *reader,
454                     int             current_type)
455 {
456   int t;
457
458   base_reader_next (reader, current_type);
459
460   /* for STRUCT containers we return FALSE at the end of the struct,
461    * for INVALID we return FALSE at the end of the signature.
462    * In both cases we arrange for get_current_type() to return INVALID
463    * which is defined to happen iff we're at the end (no more next())
464    */
465   t = _dbus_string_get_byte (reader->type_str, reader->type_pos);
466   if (t == DBUS_STRUCT_END_CHAR)
467     {
468       reader->type_pos += 1;
469       reader->finished = TRUE;
470     }
471 }
472
473 static void
474 array_types_only_reader_next (DBusTypeReader *reader,
475                               int             current_type)
476 {
477   /* We have one "element" to be iterated over
478    * in each array, which is its element type.
479    * So the finished flag indicates whether we've
480    * iterated over it yet or not.
481    */
482   reader->finished = TRUE;
483 }
484
485 static void
486 array_reader_next (DBusTypeReader *reader,
487                    int             current_type)
488 {
489   /* Skip one array element */
490   int end_pos;
491
492   end_pos = reader->u.array.start_pos + array_reader_get_array_len (reader);
493
494 #if RECURSIVE_MARSHAL_READ_TRACE
495   _dbus_verbose ("  reader %p array next START start_pos = %d end_pos = %d value_pos = %d current_type = %s\n",
496                  reader,
497                  reader->u.array.start_pos,
498                  end_pos, reader->value_pos,
499                  _dbus_type_to_string (current_type));
500 #endif
501
502   _dbus_assert (reader->value_pos < end_pos);
503   _dbus_assert (reader->value_pos >= reader->u.array.start_pos);
504
505   switch (first_type_in_signature (reader->type_str,
506                                    reader->type_pos))
507     {
508     case DBUS_TYPE_STRUCT:
509     case DBUS_TYPE_VARIANT:
510       {
511         DBusTypeReader sub;
512
513         /* Recurse into the struct or variant */
514         _dbus_type_reader_recurse (reader, &sub);
515
516         /* Skip everything in this element */
517         while (_dbus_type_reader_next (&sub))
518           {
519             /* nothing */;
520           }
521
522         /* Now we are at the end of this element */
523         reader->value_pos = sub.value_pos;
524       }
525       break;
526
527     case DBUS_TYPE_ARRAY:
528       {
529         _dbus_marshal_skip_array (reader->value_str,
530                                   first_type_in_signature (reader->type_str,
531                                                            reader->type_pos + 1),
532                                   reader->byte_order,
533                                   &reader->value_pos);
534       }
535       break;
536
537     default:
538       {
539         _dbus_marshal_skip_basic (reader->value_str,
540                                   current_type, reader->byte_order,
541                                   &reader->value_pos);
542       }
543       break;
544     }
545
546 #if RECURSIVE_MARSHAL_READ_TRACE
547   _dbus_verbose ("  reader %p array next END start_pos = %d end_pos = %d value_pos = %d current_type = %s\n",
548                  reader,
549                  reader->u.array.start_pos,
550                  end_pos, reader->value_pos,
551                  _dbus_type_to_string (current_type));
552 #endif
553
554   _dbus_assert (reader->value_pos <= end_pos);
555
556   if (reader->value_pos == end_pos)
557     {
558       skip_one_complete_type (reader->type_str,
559                               &reader->type_pos);
560     }
561 }
562
563 static void
564 array_init_from_mark (DBusTypeReader     *reader,
565                       const DBusTypeMark *mark)
566 {
567   /* Fill in the array-specific fields from the mark. The general
568    * fields are already filled in.
569    */
570   reader->u.array.start_pos = mark->array_start_pos;
571   reader->array_len_offset = mark->array_len_offset;
572 }
573
574 static const DBusTypeReaderClass body_reader_class = {
575   "body", 0,
576   FALSE,
577   NULL, /* body is always toplevel, so doesn't get recursed into */
578   NULL,
579   base_reader_next,
580   NULL
581 };
582
583 static const DBusTypeReaderClass body_types_only_reader_class = {
584   "body types", 1,
585   TRUE,
586   NULL, /* body is always toplevel, so doesn't get recursed into */
587   NULL,
588   base_reader_next,
589   NULL
590 };
591
592 static const DBusTypeReaderClass struct_reader_class = {
593   "struct", 2,
594   FALSE,
595   struct_reader_recurse,
596   NULL,
597   struct_reader_next,
598   NULL
599 };
600
601 static const DBusTypeReaderClass struct_types_only_reader_class = {
602   "struct types", 3,
603   TRUE,
604   struct_types_only_reader_recurse,
605   NULL,
606   struct_reader_next,
607   NULL
608 };
609
610 static const DBusTypeReaderClass array_reader_class = {
611   "array", 4,
612   FALSE,
613   array_reader_recurse,
614   array_reader_check_finished,
615   array_reader_next,
616   array_init_from_mark
617 };
618
619 static const DBusTypeReaderClass array_types_only_reader_class = {
620   "array types", 5,
621   TRUE,
622   array_types_only_reader_recurse,
623   NULL,
624   array_types_only_reader_next,
625   NULL
626 };
627
628 static const DBusTypeReaderClass variant_reader_class = {
629   "variant", 6,
630   FALSE,
631   variant_reader_recurse,
632   NULL,
633   base_reader_next,
634   NULL
635 };
636
637 static const DBusTypeReaderClass const *
638 all_reader_classes[] = {
639   &body_reader_class,
640   &body_types_only_reader_class,
641   &struct_reader_class,
642   &struct_types_only_reader_class,
643   &array_reader_class,
644   &array_types_only_reader_class,
645   &variant_reader_class
646 };
647
648 /**
649  * Initializes a type reader.
650  *
651  * @param reader the reader
652  * @param byte_order the byte order of the block to read
653  * @param type_str the signature of the block to read
654  * @param type_pos location of signature
655  * @param value_str the string containing values block
656  * @param value_pos start of values block
657  */
658 void
659 _dbus_type_reader_init (DBusTypeReader    *reader,
660                         int                byte_order,
661                         const DBusString  *type_str,
662                         int                type_pos,
663                         const DBusString  *value_str,
664                         int                value_pos)
665 {
666   reader->klass = &body_reader_class;
667
668   reader_init (reader, byte_order, type_str, type_pos,
669                value_str, value_pos);
670
671 #if RECURSIVE_MARSHAL_READ_TRACE
672   _dbus_verbose ("  type reader %p init type_pos = %d value_pos = %d remaining sig '%s'\n",
673                  reader, reader->type_pos, reader->value_pos,
674                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
675 #endif
676 }
677
678 /**
679  * Initializes a type reader that's been compressed into a
680  * DBusTypeMark.  The args have to be the same as those passed in to
681  * create the original #DBusTypeReader.
682  *
683  * @param reader the reader
684  * @param byte_order the byte order of the value block
685  * @param type_str string containing the type signature
686  * @param value_str string containing the values block
687  * @param mark the mark to decompress from
688  */
689 void
690 _dbus_type_reader_init_from_mark (DBusTypeReader     *reader,
691                                   int                 byte_order,
692                                   const DBusString   *type_str,
693                                   const DBusString   *value_str,
694                                   const DBusTypeMark *mark)
695 {
696   reader->klass = all_reader_classes[mark->container_type];
697
698   reader_init (reader, byte_order,
699                mark->type_pos_in_value_str ? value_str : type_str,
700                mark->type_pos,
701                value_str, mark->value_pos);
702
703   if (reader->klass->init_from_mark)
704     (* reader->klass->init_from_mark) (reader, mark);
705
706 #if RECURSIVE_MARSHAL_READ_TRACE
707   _dbus_verbose ("  type reader %p init from mark type_pos = %d value_pos = %d remaining sig '%s'\n",
708                  reader, reader->type_pos, reader->value_pos,
709                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
710 #endif
711 }
712
713 /**
714  * Like _dbus_type_reader_init() but the iteration is over the
715  * signature, not over values.
716  *
717  * @param reader the reader
718  * @param type_str the signature string
719  * @param type_pos location in the signature string
720  */
721 void
722 _dbus_type_reader_init_types_only (DBusTypeReader    *reader,
723                                    const DBusString  *type_str,
724                                    int                type_pos)
725 {
726   reader->klass = &body_types_only_reader_class;
727
728   reader_init (reader, DBUS_COMPILER_BYTE_ORDER /* irrelevant */,
729                type_str, type_pos, NULL, _DBUS_INT_MAX /* crashes if we screw up */);
730
731 #if RECURSIVE_MARSHAL_READ_TRACE
732   _dbus_verbose ("  type reader %p init types only type_pos = %d remaining sig '%s'\n",
733                  reader, reader->type_pos,
734                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
735 #endif
736 }
737
738 /**
739  * Like _dbus_type_reader_init_from_mark() but only iterates over
740  * the signature, not the values.
741  *
742  * @param reader the reader
743  * @param type_str the signature string
744  * @param mark the mark to decompress from
745  */
746 void
747 _dbus_type_reader_init_types_only_from_mark (DBusTypeReader     *reader,
748                                              const DBusString   *type_str,
749                                              const DBusTypeMark *mark)
750 {
751   reader->klass = all_reader_classes[mark->container_type];
752   _dbus_assert (reader->klass->types_only);
753   _dbus_assert (!mark->type_pos_in_value_str);
754
755   reader_init (reader, DBUS_COMPILER_BYTE_ORDER, /* irrelevant */
756                type_str, mark->type_pos,
757                NULL, _DBUS_INT_MAX /* crashes if we screw up */);
758
759   if (reader->klass->init_from_mark)
760     (* reader->klass->init_from_mark) (reader, mark);
761
762 #if RECURSIVE_MARSHAL_READ_TRACE
763   _dbus_verbose ("  type reader %p init types only from mark type_pos = %d remaining sig '%s'\n",
764                  reader, reader->type_pos,
765                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
766 #endif
767 }
768
769 /**
770  * Compresses a type reader into a #DBusTypeMark, useful for example
771  * if you want to cache a bunch of positions in a block of values.
772  *
773  * @param reader the reader
774  * @param mark the mark to init
775  */
776 void
777 _dbus_type_reader_save_mark (const DBusTypeReader *reader,
778                              DBusTypeMark         *mark)
779 {
780   mark->type_pos_in_value_str = (reader->type_str == reader->value_str);
781   mark->container_type = reader->klass->id;
782   _dbus_assert (all_reader_classes[reader->klass->id] == reader->klass);
783
784   mark->type_pos = reader->type_pos;
785   mark->value_pos = reader->value_pos;
786
787   /* these are just junk if the reader isn't really an array of course */
788   mark->array_len_offset = reader->array_len_offset;
789   mark->array_start_pos = reader->u.array.start_pos;
790 }
791
792 /**
793  * Gets the type of the value the reader is currently pointing to;
794  * or for a types-only reader gets the type it's currently pointing to.
795  * If the reader is at the end of a block or end of a container such
796  * as an array, returns #DBUS_TYPE_INVALID.
797  *
798  * @param reader the reader
799  */
800 int
801 _dbus_type_reader_get_current_type (const DBusTypeReader *reader)
802 {
803   int t;
804
805   if (reader->finished ||
806       (reader->klass->check_finished &&
807        (* reader->klass->check_finished) (reader)))
808     t = DBUS_TYPE_INVALID;
809   else
810     t = first_type_in_signature (reader->type_str,
811                                  reader->type_pos);
812
813   _dbus_assert (t != DBUS_STRUCT_END_CHAR);
814   _dbus_assert (t != DBUS_STRUCT_BEGIN_CHAR);
815
816 #if 0
817   _dbus_verbose ("  type reader %p current type_pos = %d type = %s\n",
818                  reader, reader->type_pos,
819                  _dbus_type_to_string (t));
820 #endif
821
822   return t;
823 }
824
825 /**
826  * Gets the type of an element of the array the reader is currently
827  * pointing to. It's an error to call this if
828  * _dbus_type_reader_get_current_type() doesn't return #DBUS_TYPE_ARRAY
829  * for this reader.
830  *
831  * @param reader the reader
832  */
833 int
834 _dbus_type_reader_get_element_type (const DBusTypeReader  *reader)
835 {
836   int element_type;
837
838   _dbus_assert (_dbus_type_reader_get_current_type (reader) == DBUS_TYPE_ARRAY);
839
840   element_type = first_type_in_signature (reader->type_str,
841                                           reader->type_pos + 1);
842
843   return element_type;
844 }
845
846 /**
847  * Gets the current position in the value block
848  * @param reader the reader
849  */
850 int
851 _dbus_type_reader_get_value_pos (const DBusTypeReader  *reader)
852 {
853   return reader->value_pos;
854 }
855
856 /**
857  * Get the address of the marshaled value in the data being read.  The
858  * address may not be aligned; you have to align it to the type of the
859  * value you want to read. Most of the demarshal routines do this for
860  * you.
861  *
862  * @param reader the reader
863  * @param value_location the address of the marshaled value
864  */
865 void
866 _dbus_type_reader_read_raw (const DBusTypeReader  *reader,
867                             const unsigned char  **value_location)
868 {
869   _dbus_assert (!reader->klass->types_only);
870
871   *value_location = _dbus_string_get_const_data_len (reader->value_str,
872                                                      reader->value_pos,
873                                                      0);
874 }
875
876 /**
877  * Reads a basic-typed value, as with _dbus_marshal_read_basic().
878  *
879  * @param reader the reader
880  * @param value the address of the value
881  */
882 void
883 _dbus_type_reader_read_basic (const DBusTypeReader    *reader,
884                               void                    *value)
885 {
886   int t;
887
888   _dbus_assert (!reader->klass->types_only);
889
890   t = _dbus_type_reader_get_current_type (reader);
891
892   _dbus_marshal_read_basic (reader->value_str,
893                             reader->value_pos,
894                             t, value,
895                             reader->byte_order,
896                             NULL);
897
898
899 #if RECURSIVE_MARSHAL_READ_TRACE
900   _dbus_verbose ("  type reader %p read basic type_pos = %d value_pos = %d remaining sig '%s'\n",
901                  reader, reader->type_pos, reader->value_pos,
902                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
903 #endif
904 }
905
906 /**
907  * Reads a block of fixed-length basic values, from the current point
908  * in an array to the end of the array.  Does not work for arrays of
909  * string or container types.
910  *
911  * This function returns the array in-place; it does not make a copy,
912  * and it does not swap the bytes.
913  *
914  * If you ask for #DBUS_TYPE_DOUBLE you will get a "const double*" back
915  * and the "value" argument should be a "const double**" and so on.
916  *
917  * @param reader the reader to read from
918  * @param value place to return the array values
919  * @param n_elements place to return number of array elements
920  */
921 void
922 _dbus_type_reader_read_fixed_multi (const DBusTypeReader  *reader,
923                                     void                  *value,
924                                     int                   *n_elements)
925 {
926   int element_type;
927   int end_pos;
928   int remaining_len;
929   int alignment;
930   int total_len;
931
932   _dbus_assert (!reader->klass->types_only);
933   _dbus_assert (reader->klass == &array_reader_class);
934
935   element_type = first_type_in_signature (reader->type_str,
936                                           reader->type_pos);
937
938   _dbus_assert (element_type != DBUS_TYPE_INVALID); /* why we don't use get_current_type() */
939   _dbus_assert (_dbus_type_is_fixed (element_type));
940
941   alignment = _dbus_type_get_alignment (element_type);
942
943   _dbus_assert (reader->value_pos >= reader->u.array.start_pos);
944
945   total_len = array_reader_get_array_len (reader);
946   end_pos = reader->u.array.start_pos + total_len;
947   remaining_len = end_pos - reader->value_pos;
948
949 #if RECURSIVE_MARSHAL_READ_TRACE
950   _dbus_verbose ("end_pos %d total_len %d remaining_len %d value_pos %d\n",
951                  end_pos, total_len, remaining_len, reader->value_pos);
952 #endif
953
954   _dbus_assert (remaining_len <= total_len);
955
956   if (remaining_len == 0)
957     *(const DBusBasicValue**) value = NULL;
958   else
959     *(const DBusBasicValue**) value =
960       (void*) _dbus_string_get_const_data_len (reader->value_str,
961                                                reader->value_pos,
962                                                remaining_len);
963
964   *n_elements = remaining_len / alignment;
965   _dbus_assert ((remaining_len % alignment) == 0);
966
967 #if RECURSIVE_MARSHAL_READ_TRACE
968   _dbus_verbose ("  type reader %p read fixed array type_pos = %d value_pos = %d remaining sig '%s'\n",
969                  reader, reader->type_pos, reader->value_pos,
970                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0));
971 #endif
972 }
973
974 /**
975  * Initialize a new reader pointing to the first type and
976  * corresponding value that's a child of the current container. It's
977  * an error to call this if the current type is a non-container.
978  *
979  * Note that DBusTypeReader traverses values, not types. So if you
980  * have an empty array of array of int, you can't recurse into it. You
981  * can only recurse into each element.
982  *
983  * @param reader the reader
984  * @param sub a reader to init pointing to the first child
985  */
986 void
987 _dbus_type_reader_recurse (DBusTypeReader *reader,
988                            DBusTypeReader *sub)
989 {
990   int t;
991
992   t = first_type_in_signature (reader->type_str, reader->type_pos);
993
994   switch (t)
995     {
996     case DBUS_TYPE_STRUCT:
997       if (reader->klass->types_only)
998         sub->klass = &struct_types_only_reader_class;
999       else
1000         sub->klass = &struct_reader_class;
1001       break;
1002     case DBUS_TYPE_ARRAY:
1003       if (reader->klass->types_only)
1004         sub->klass = &array_types_only_reader_class;
1005       else
1006         sub->klass = &array_reader_class;
1007       break;
1008     case DBUS_TYPE_VARIANT:
1009       if (reader->klass->types_only)
1010         _dbus_assert_not_reached ("can't recurse into variant typecode");
1011       else
1012         sub->klass = &variant_reader_class;
1013       break;
1014     default:
1015       _dbus_verbose ("recursing into type %s\n", _dbus_type_to_string (t));
1016 #ifndef DBUS_DISABLE_CHECKS
1017       if (t == DBUS_TYPE_INVALID)
1018         _dbus_warn ("You can't recurse into an empty array or off the end of a message body\n");
1019 #endif /* DBUS_DISABLE_CHECKS */
1020
1021       _dbus_assert_not_reached ("don't yet handle recursing into this type");
1022     }
1023
1024   _dbus_assert (sub->klass == all_reader_classes[sub->klass->id]);
1025
1026   (* sub->klass->recurse) (sub, reader);
1027
1028 #if RECURSIVE_MARSHAL_READ_TRACE
1029   _dbus_verbose ("  type reader %p RECURSED type_pos = %d value_pos = %d remaining sig '%s'\n",
1030                  sub, sub->type_pos, sub->value_pos,
1031                  _dbus_string_get_const_data_len (sub->type_str, sub->type_pos, 0));
1032 #endif
1033 }
1034
1035 /**
1036  * Skip to the next value on this "level". e.g. the next field in a
1037  * struct, the next value in an array. Returns FALSE at the end of the
1038  * current container.
1039  *
1040  * @param reader the reader
1041  * @returns FALSE if nothing more to read at or below this level
1042  */
1043 dbus_bool_t
1044 _dbus_type_reader_next (DBusTypeReader *reader)
1045 {
1046   int t;
1047
1048   t = _dbus_type_reader_get_current_type (reader);
1049
1050 #if RECURSIVE_MARSHAL_READ_TRACE
1051   _dbus_verbose ("  type reader %p START next() { type_pos = %d value_pos = %d remaining sig '%s' current_type = %s\n",
1052                  reader, reader->type_pos, reader->value_pos,
1053                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0),
1054                  _dbus_type_to_string (t));
1055 #endif
1056
1057   if (t == DBUS_TYPE_INVALID)
1058     return FALSE;
1059
1060   (* reader->klass->next) (reader, t);
1061
1062 #if RECURSIVE_MARSHAL_READ_TRACE
1063   _dbus_verbose ("  type reader %p END next() type_pos = %d value_pos = %d remaining sig '%s' current_type = %s\n",
1064                  reader, reader->type_pos, reader->value_pos,
1065                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0),
1066                  _dbus_type_to_string (_dbus_type_reader_get_current_type (reader)));
1067 #endif
1068
1069   return _dbus_type_reader_get_current_type (reader) != DBUS_TYPE_INVALID;
1070 }
1071
1072 /**
1073  * Check whether there's another value on this "level". e.g. the next
1074  * field in a struct, the next value in an array. Returns FALSE at the
1075  * end of the current container.
1076  *
1077  * You probably don't want to use this; it makes for an awkward for/while
1078  * loop. A nicer one is "while ((current_type = get_current_type()) != INVALID)"
1079  *
1080  * @param reader the reader
1081  * @returns FALSE if nothing more to read at or below this level
1082  */
1083 dbus_bool_t
1084 _dbus_type_reader_has_next (const DBusTypeReader *reader)
1085 {
1086   /* Not efficient but works for now. */
1087   DBusTypeReader copy;
1088
1089   copy = *reader;
1090   return _dbus_type_reader_next (&copy);
1091 }
1092
1093 /**
1094  * Gets the string and range of said string containing the signature
1095  * of the current value. Essentially a more complete version of
1096  * _dbus_type_reader_get_current_type() (returns the full type
1097  * rather than only the outside of the onion).
1098  *
1099  * Note though that the first byte in a struct signature is
1100  * #DBUS_STRUCT_BEGIN_CHAR while the current type will be
1101  * #DBUS_TYPE_STRUCT so it isn't true that the first byte of the
1102  * signature is always the same as the current type. Another
1103  * difference is that this function will still return a signature when
1104  * inside an empty array; say you recurse into empty array of int32,
1105  * the signature is "i" but the current type will always be
1106  * #DBUS_TYPE_INVALID since there are no elements to be currently
1107  * pointing to.
1108  *
1109  * @param reader the reader
1110  * @param str_p place to return the string with the type in it
1111  * @param start_p place to return start of the type
1112  * @param len_p place to return the length of the type
1113  */
1114 void
1115 _dbus_type_reader_get_signature (const DBusTypeReader  *reader,
1116                                  const DBusString     **str_p,
1117                                  int                   *start_p,
1118                                  int                   *len_p)
1119 {
1120   *str_p = reader->type_str;
1121   *start_p = reader->type_pos;
1122   *len_p = find_len_of_complete_type (reader->type_str, reader->type_pos);
1123 }
1124
1125 typedef struct
1126 {
1127   DBusString replacement;
1128   int padding;
1129 } ReplacementBlock;
1130
1131 static dbus_bool_t
1132 replacement_block_init (ReplacementBlock *block,
1133                         DBusTypeReader   *reader)
1134 {
1135   if (!_dbus_string_init (&block->replacement))
1136     return FALSE;
1137
1138   /* % 8 is the padding to have the same align properties in
1139    * our replacement string as we do at the position being replaced
1140    */
1141   block->padding = reader->value_pos % 8;
1142
1143   if (!_dbus_string_lengthen (&block->replacement, block->padding))
1144     goto oom;
1145
1146   return TRUE;
1147
1148  oom:
1149   _dbus_string_free (&block->replacement);
1150   return FALSE;
1151 }
1152
1153 static dbus_bool_t
1154 replacement_block_replace (ReplacementBlock     *block,
1155                            DBusTypeReader       *reader,
1156                            const DBusTypeReader *realign_root)
1157 {
1158   DBusTypeWriter writer;
1159   DBusTypeReader realign_reader;
1160   DBusList *fixups;
1161   int orig_len;
1162
1163   _dbus_assert (realign_root != NULL);
1164
1165   orig_len = _dbus_string_get_length (&block->replacement);
1166
1167   realign_reader = *realign_root;
1168
1169 #if RECURSIVE_MARSHAL_WRITE_TRACE
1170   _dbus_verbose ("INITIALIZING replacement block writer %p at value_pos %d\n",
1171                  &writer, _dbus_string_get_length (&block->replacement));
1172 #endif
1173   _dbus_type_writer_init_values_only (&writer,
1174                                       realign_reader.byte_order,
1175                                       realign_reader.type_str,
1176                                       realign_reader.type_pos,
1177                                       &block->replacement,
1178                                       _dbus_string_get_length (&block->replacement));
1179
1180   _dbus_assert (realign_reader.value_pos <= reader->value_pos);
1181
1182 #if RECURSIVE_MARSHAL_WRITE_TRACE
1183   _dbus_verbose ("COPYING from reader at value_pos %d to writer %p starting after value_pos %d\n",
1184                  realign_reader.value_pos, &writer, reader->value_pos);
1185 #endif
1186   fixups = NULL;
1187   if (!_dbus_type_writer_write_reader_partial (&writer,
1188                                                &realign_reader,
1189                                                reader,
1190                                                block->padding,
1191                                                _dbus_string_get_length (&block->replacement) - block->padding,
1192                                                &fixups))
1193     goto oom;
1194
1195 #if RECURSIVE_MARSHAL_WRITE_TRACE
1196   _dbus_verbose ("REPLACEMENT at padding %d len %d\n", block->padding,
1197                  _dbus_string_get_length (&block->replacement) - block->padding);
1198   _dbus_verbose_bytes_of_string (&block->replacement, block->padding,
1199                                  _dbus_string_get_length (&block->replacement) - block->padding);
1200   _dbus_verbose ("TO BE REPLACED at value_pos = %d (align pad %d) len %d realign_reader.value_pos %d\n",
1201                  reader->value_pos, reader->value_pos % 8,
1202                  realign_reader.value_pos - reader->value_pos,
1203                  realign_reader.value_pos);
1204   _dbus_verbose_bytes_of_string (reader->value_str,
1205                                  reader->value_pos,
1206                                  realign_reader.value_pos - reader->value_pos);
1207 #endif
1208
1209   /* Move the replacement into position
1210    * (realign_reader should now be at the end of the block to be replaced)
1211    */
1212   if (!_dbus_string_replace_len (&block->replacement, block->padding,
1213                                  _dbus_string_get_length (&block->replacement) - block->padding,
1214                                  (DBusString*) reader->value_str,
1215                                  reader->value_pos,
1216                                  realign_reader.value_pos - reader->value_pos))
1217     goto oom;
1218
1219   /* Process our fixups now that we can't have an OOM error */
1220   apply_and_free_fixups (&fixups, reader);
1221
1222   return TRUE;
1223
1224  oom:
1225   _dbus_string_set_length (&block->replacement, orig_len);
1226   free_fixups (&fixups);
1227   return FALSE;
1228 }
1229
1230 static void
1231 replacement_block_free (ReplacementBlock *block)
1232 {
1233   _dbus_string_free (&block->replacement);
1234 }
1235
1236 /* In the variable-length case, we have to fix alignment after we insert.
1237  * The strategy is as follows:
1238  *
1239  *  - pad a new string to have the same alignment as the
1240  *    start of the current basic value
1241  *  - write the new basic value
1242  *  - copy from the original reader to the new string,
1243  *    which will fix the alignment of types following
1244  *    the new value
1245  *    - this copy has to start at realign_root,
1246  *      but not really write anything until it
1247  *      passes the value being set
1248  *    - as an optimization, we can stop copying
1249  *      when the source and dest values are both
1250  *      on an 8-boundary, since we know all following
1251  *      padding and alignment will be identical
1252  *  - copy the new string back to the original
1253  *    string, replacing the relevant part of the
1254  *    original string
1255  *  - now any arrays in the original string that
1256  *    contained the replaced string may have the
1257  *    wrong length; so we have to fix that
1258  */
1259 static dbus_bool_t
1260 reader_set_basic_variable_length (DBusTypeReader       *reader,
1261                                   int                   current_type,
1262                                   const void           *value,
1263                                   const DBusTypeReader *realign_root)
1264 {
1265   dbus_bool_t retval;
1266   ReplacementBlock block;
1267   DBusTypeWriter writer;
1268
1269   _dbus_assert (realign_root != NULL);
1270
1271   retval = FALSE;
1272
1273   if (!replacement_block_init (&block, reader))
1274     return FALSE;
1275
1276   /* Write the new basic value */
1277 #if RECURSIVE_MARSHAL_WRITE_TRACE
1278   _dbus_verbose ("INITIALIZING writer %p to write basic value at value_pos %d of replacement string\n",
1279                  &writer, _dbus_string_get_length (&block.replacement));
1280 #endif
1281   _dbus_type_writer_init_values_only (&writer,
1282                                       reader->byte_order,
1283                                       reader->type_str,
1284                                       reader->type_pos,
1285                                       &block.replacement,
1286                                       _dbus_string_get_length (&block.replacement));
1287 #if RECURSIVE_MARSHAL_WRITE_TRACE
1288   _dbus_verbose ("WRITING basic value to writer %p (replacement string)\n", &writer);
1289 #endif
1290   if (!_dbus_type_writer_write_basic (&writer, current_type, value))
1291     goto out;
1292
1293   if (!replacement_block_replace (&block,
1294                                   reader,
1295                                   realign_root))
1296     goto out;
1297
1298   retval = TRUE;
1299
1300  out:
1301   replacement_block_free (&block);
1302   return retval;
1303 }
1304
1305 static void
1306 reader_set_basic_fixed_length (DBusTypeReader *reader,
1307                                int             current_type,
1308                                const void     *value)
1309 {
1310   _dbus_marshal_set_basic ((DBusString*) reader->value_str,
1311                            reader->value_pos,
1312                            current_type,
1313                            value,
1314                            reader->byte_order,
1315                            NULL, NULL);
1316 }
1317
1318 /**
1319  * Sets a new value for the basic type value pointed to by the reader,
1320  * leaving the reader valid to continue reading. Any other readers
1321  * will be invalidated if you set a variable-length type such as a
1322  * string.
1323  *
1324  * The provided realign_root is the reader to start from when
1325  * realigning the data that follows the newly-set value. The reader
1326  * parameter must point to a value below the realign_root parameter.
1327  * If the type being set is fixed-length, then realign_root may be
1328  * #NULL. Only values reachable from realign_root will be realigned,
1329  * so if your string contains other values you will need to deal with
1330  * those somehow yourself. It is OK if realign_root is the same
1331  * reader as the reader parameter, though if you aren't setting the
1332  * root it may not be such a good idea.
1333  *
1334  * @todo DBusTypeReader currently takes "const" versions of the type
1335  * and value strings, and this function modifies those strings by
1336  * casting away the const, which is of course bad if we want to get
1337  * picky. (To be truly clean you'd have an object which contained the
1338  * type and value strings and set_basic would be a method on that
1339  * object... this would also make DBusTypeReader the same thing as
1340  * DBusTypeMark. But since DBusMessage is effectively that object for
1341  * D-BUS it doesn't seem worth creating some random object.)
1342  *
1343  * @todo optimize this by only rewriting until the old and new values
1344  * are at the same alignment. Frequently this should result in only
1345  * replacing the value that's immediately at hand.
1346  *
1347  * @param reader reader indicating where to set a new value
1348  * @param value address of the value to set
1349  * @param realign_root realign from here
1350  * @returns #FALSE if not enough memory
1351  */
1352 dbus_bool_t
1353 _dbus_type_reader_set_basic (DBusTypeReader       *reader,
1354                              const void           *value,
1355                              const DBusTypeReader *realign_root)
1356 {
1357   int current_type;
1358
1359   _dbus_assert (!reader->klass->types_only);
1360   _dbus_assert (reader->value_str == realign_root->value_str);
1361   _dbus_assert (reader->value_pos >= realign_root->value_pos);
1362
1363   current_type = _dbus_type_reader_get_current_type (reader);
1364
1365 #if RECURSIVE_MARSHAL_WRITE_TRACE
1366   _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",
1367                  reader, reader->type_pos, reader->value_pos,
1368                  _dbus_string_get_const_data_len (reader->type_str, reader->type_pos, 0),
1369                  realign_root,
1370                  realign_root ? realign_root->value_pos : -1,
1371                  _dbus_type_to_string (current_type));
1372   _dbus_verbose_bytes_of_string (realign_root->value_str, realign_root->value_pos,
1373                                  _dbus_string_get_length (realign_root->value_str) -
1374                                  realign_root->value_pos);
1375 #endif
1376
1377   _dbus_assert (_dbus_type_is_basic (current_type));
1378
1379   if (_dbus_type_is_fixed (current_type))
1380     {
1381       reader_set_basic_fixed_length (reader, current_type, value);
1382       return TRUE;
1383     }
1384   else
1385     {
1386       _dbus_assert (realign_root != NULL);
1387       return reader_set_basic_variable_length (reader, current_type,
1388                                                value, realign_root);
1389     }
1390 }
1391
1392 /**
1393  * Recursively deletes any value pointed to by the reader, leaving the
1394  * reader valid to continue reading. Any other readers will be
1395  * invalidated.
1396  *
1397  * The provided realign_root is the reader to start from when
1398  * realigning the data that follows the newly-set value.
1399  * See _dbus_type_reader_set_basic() for more details on the
1400  * realign_root paramter.
1401  *
1402  * @todo for now this does not delete the typecodes associated with
1403  * the value, so this function should only be used for array elements.
1404  *
1405  * @param reader reader indicating where to delete a value
1406  * @param realign_root realign from here
1407  * @returns #FALSE if not enough memory
1408  */
1409 dbus_bool_t
1410 _dbus_type_reader_delete (DBusTypeReader        *reader,
1411                           const DBusTypeReader  *realign_root)
1412 {
1413   dbus_bool_t retval;
1414   ReplacementBlock block;
1415
1416   _dbus_assert (realign_root != NULL);
1417   _dbus_assert (reader->klass == &array_reader_class);
1418
1419   retval = FALSE;
1420
1421   if (!replacement_block_init (&block, reader))
1422     return FALSE;
1423
1424   if (!replacement_block_replace (&block,
1425                                   reader,
1426                                   realign_root))
1427     goto out;
1428
1429   retval = TRUE;
1430
1431  out:
1432   replacement_block_free (&block);
1433   return retval;
1434 }
1435
1436 /**
1437  * Compares two readers, which must be iterating over the same value data.
1438  * Returns #TRUE if the first parameter is further along than the second parameter.
1439  *
1440  * @param lhs left-hand-side (first) parameter
1441  * @param rhs left-hand-side (first) parameter
1442  * @returns whether lhs is greater than rhs
1443  */
1444 dbus_bool_t
1445 _dbus_type_reader_greater_than (const DBusTypeReader  *lhs,
1446                                 const DBusTypeReader  *rhs)
1447 {
1448   _dbus_assert (lhs->value_str == rhs->value_str);
1449
1450   return lhs->value_pos > rhs->value_pos;
1451 }
1452
1453 /*
1454  *
1455  *
1456  *         DBusTypeWriter
1457  *
1458  *
1459  *
1460  */
1461
1462 /**
1463  * Initialize a write iterator, which is used to write out values in
1464  * serialized D-BUS format.
1465  *
1466  * The type_pos passed in is expected to be inside an already-valid,
1467  * though potentially empty, type signature. This means that the byte
1468  * after type_pos must be either #DBUS_TYPE_INVALID (aka nul) or some
1469  * other valid type. #DBusTypeWriter won't enforce that the signature
1470  * is already valid (you can append the nul byte at the end if you
1471  * like), but just be aware that you need the nul byte eventually and
1472  * #DBusTypeWriter isn't going to write it for you.
1473  *
1474  * @param writer the writer to init
1475  * @param byte_order the byte order to marshal into
1476  * @param type_str the string to write typecodes into
1477  * @param type_pos where to insert typecodes
1478  * @param value_str the string to write values into
1479  * @param value_pos where to insert values
1480  *
1481  */
1482 void
1483 _dbus_type_writer_init (DBusTypeWriter *writer,
1484                         int             byte_order,
1485                         DBusString     *type_str,
1486                         int             type_pos,
1487                         DBusString     *value_str,
1488                         int             value_pos)
1489 {
1490   writer->byte_order = byte_order;
1491   writer->type_str = type_str;
1492   writer->type_pos = type_pos;
1493   writer->value_str = value_str;
1494   writer->value_pos = value_pos;
1495   writer->container_type = DBUS_TYPE_INVALID;
1496   writer->type_pos_is_expectation = FALSE;
1497   writer->enabled = TRUE;
1498
1499 #if RECURSIVE_MARSHAL_WRITE_TRACE
1500   _dbus_verbose ("writer %p init remaining sig '%s'\n", writer,
1501                  writer->type_str ?
1502                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0) :
1503                  "unknown");
1504 #endif
1505 }
1506
1507 /**
1508  * Initialize a write iterator, with the signature to be provided
1509  * later.
1510  *
1511  * @param writer the writer to init
1512  * @param byte_order the byte order to marshal into
1513  * @param value_str the string to write values into
1514  * @param value_pos where to insert values
1515  *
1516  */
1517 void
1518 _dbus_type_writer_init_types_delayed (DBusTypeWriter *writer,
1519                                       int             byte_order,
1520                                       DBusString     *value_str,
1521                                       int             value_pos)
1522 {
1523   _dbus_type_writer_init (writer, byte_order,
1524                           NULL, 0, value_str, value_pos);
1525 }
1526
1527 /**
1528  * Adds type string to the writer, if it had none.
1529  *
1530  * @param writer the writer to init
1531  * @param type_str type string to add
1532  * @param type_pos type position
1533  *
1534  */
1535 void
1536 _dbus_type_writer_add_types (DBusTypeWriter *writer,
1537                              DBusString     *type_str,
1538                              int             type_pos)
1539 {
1540   if (writer->type_str == NULL) /* keeps us from using this as setter */
1541     {
1542       writer->type_str = type_str;
1543       writer->type_pos = type_pos;
1544     }
1545 }
1546
1547 /**
1548  * Removes type string from the writer.
1549  *
1550  * @param writer the writer to remove from
1551  */
1552 void
1553 _dbus_type_writer_remove_types (DBusTypeWriter *writer)
1554 {
1555   writer->type_str = NULL;
1556   writer->type_pos = -1;
1557 }
1558
1559 /**
1560  * Like _dbus_type_writer_init(), except the type string
1561  * passed in should correspond to an existing signature that
1562  * matches what you're going to write out. The writer will
1563  * check what you write vs. this existing signature.
1564  *
1565  * @param writer the writer to init
1566  * @param byte_order the byte order to marshal into
1567  * @param type_str the string with signature
1568  * @param type_pos start of signature
1569  * @param value_str the string to write values into
1570  * @param value_pos where to insert values
1571  *
1572  */
1573 void
1574 _dbus_type_writer_init_values_only (DBusTypeWriter   *writer,
1575                                     int               byte_order,
1576                                     const DBusString *type_str,
1577                                     int               type_pos,
1578                                     DBusString       *value_str,
1579                                     int               value_pos)
1580 {
1581   _dbus_type_writer_init (writer, byte_order,
1582                           (DBusString*)type_str, type_pos,
1583                           value_str, value_pos);
1584
1585   writer->type_pos_is_expectation = TRUE;
1586 }
1587
1588 static dbus_bool_t
1589 _dbus_type_writer_write_basic_no_typecode (DBusTypeWriter *writer,
1590                                            int             type,
1591                                            const void     *value)
1592 {
1593   if (writer->enabled)
1594     return _dbus_marshal_write_basic (writer->value_str,
1595                                       writer->value_pos,
1596                                       type,
1597                                       value,
1598                                       writer->byte_order,
1599                                       &writer->value_pos);
1600   else
1601     return TRUE;
1602 }
1603
1604 /* If our parent is an array, things are a little bit complicated.
1605  *
1606  * The parent must have a complete element type, such as
1607  * "i" or "aai" or "(ii)" or "a(ii)". There can't be
1608  * unclosed parens, or an "a" with no following type.
1609  *
1610  * To recurse, the only allowed operation is to recurse into the
1611  * first type in the element type. So for "i" you can't recurse, for
1612  * "ai" you can recurse into the array, for "(ii)" you can recurse
1613  * into the struct.
1614  *
1615  * If you recurse into the array for "ai", then you must specify
1616  * "i" for the element type of the array you recurse into.
1617  *
1618  * While inside an array at any level, we need to avoid writing to
1619  * type_str, since the type only appears once for the whole array,
1620  * it does not appear for each array element.
1621  *
1622  * While inside an array type_pos points to the expected next
1623  * typecode, rather than the next place we could write a typecode.
1624  */
1625 static void
1626 writer_recurse_init_and_check (DBusTypeWriter *writer,
1627                                int             container_type,
1628                                DBusTypeWriter *sub)
1629 {
1630   _dbus_type_writer_init (sub,
1631                           writer->byte_order,
1632                           writer->type_str,
1633                           writer->type_pos,
1634                           writer->value_str,
1635                           writer->value_pos);
1636
1637   sub->container_type = container_type;
1638
1639   if (writer->type_pos_is_expectation ||
1640       (sub->container_type == DBUS_TYPE_ARRAY || sub->container_type == DBUS_TYPE_VARIANT))
1641     sub->type_pos_is_expectation = TRUE;
1642   else
1643     sub->type_pos_is_expectation = FALSE;
1644
1645   sub->enabled = writer->enabled;
1646
1647 #ifndef DBUS_DISABLE_CHECKS
1648   if (writer->type_pos_is_expectation && writer->type_str)
1649     {
1650       int expected;
1651
1652       expected = first_type_in_signature (writer->type_str, writer->type_pos);
1653
1654       if (expected != sub->container_type)
1655         {
1656           _dbus_warn ("Writing an element of type %s, but the expected type here is %s\n",
1657                       _dbus_type_to_string (sub->container_type),
1658                       _dbus_type_to_string (expected));
1659           _dbus_assert_not_reached ("bad array element or variant content written");
1660         }
1661     }
1662 #endif /* DBUS_DISABLE_CHECKS */
1663
1664 #if RECURSIVE_MARSHAL_WRITE_TRACE
1665   _dbus_verbose ("  type writer %p recurse parent %s type_pos = %d value_pos = %d is_expectation = %d remaining sig '%s' enabled = %d\n",
1666                  writer,
1667                  _dbus_type_to_string (writer->container_type),
1668                  writer->type_pos, writer->value_pos, writer->type_pos_is_expectation,
1669                  writer->type_str ?
1670                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0) :
1671                  "unknown",
1672                  writer->enabled);
1673   _dbus_verbose ("  type writer %p recurse sub %s   type_pos = %d value_pos = %d is_expectation = %d enabled = %d\n",
1674                  sub,
1675                  _dbus_type_to_string (sub->container_type),
1676                  sub->type_pos, sub->value_pos,
1677                  sub->type_pos_is_expectation,
1678                  sub->enabled);
1679 #endif
1680 }
1681
1682 static dbus_bool_t
1683 write_or_verify_typecode (DBusTypeWriter *writer,
1684                           int             typecode)
1685 {
1686   /* A subwriter inside an array or variant will have type_pos
1687    * pointing to the expected typecode; a writer not inside an array
1688    * or variant has type_pos pointing to the next place to insert a
1689    * typecode.
1690    */
1691 #if RECURSIVE_MARSHAL_WRITE_TRACE
1692   _dbus_verbose ("  type writer %p write_or_verify start type_pos = %d remaining sig '%s' enabled = %d\n",
1693                  writer, writer->type_pos,
1694                  writer->type_str ?
1695                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0) :
1696                  "unknown",
1697                  writer->enabled);
1698 #endif
1699
1700   if (writer->type_str == NULL)
1701     return TRUE;
1702
1703   if (writer->type_pos_is_expectation)
1704     {
1705 #ifndef DBUS_DISABLE_CHECKS
1706       {
1707         int expected;
1708
1709         expected = _dbus_string_get_byte (writer->type_str, writer->type_pos);
1710
1711         if (expected != typecode)
1712           {
1713             _dbus_warn ("Array or variant type requires that type %s be written, but %s was written\n",
1714                         _dbus_type_to_string (expected), _dbus_type_to_string (typecode));
1715             _dbus_assert_not_reached ("bad type inserted somewhere inside an array or variant");
1716           }
1717       }
1718 #endif /* DBUS_DISABLE_CHECKS */
1719
1720       /* if immediately inside an array we'd always be appending an element,
1721        * so the expected type doesn't change; if inside a struct or something
1722        * below an array, we need to move through said struct or something.
1723        */
1724       if (writer->container_type != DBUS_TYPE_ARRAY)
1725         writer->type_pos += 1;
1726     }
1727   else
1728     {
1729       if (!_dbus_string_insert_byte (writer->type_str,
1730                                      writer->type_pos,
1731                                      typecode))
1732         return FALSE;
1733
1734       writer->type_pos += 1;
1735     }
1736
1737 #if RECURSIVE_MARSHAL_WRITE_TRACE
1738   _dbus_verbose ("  type writer %p write_or_verify end type_pos = %d remaining sig '%s'\n",
1739                  writer, writer->type_pos,
1740                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0));
1741 #endif
1742
1743   return TRUE;
1744 }
1745
1746 static dbus_bool_t
1747 writer_recurse_struct (DBusTypeWriter   *writer,
1748                        const DBusString *contained_type,
1749                        int               contained_type_start,
1750                        int               contained_type_len,
1751                        DBusTypeWriter   *sub)
1752 {
1753   /* FIXME right now contained_type is ignored; we could probably
1754    * almost trivially fix the code so if it's present we
1755    * write it out and then set type_pos_is_expectation
1756    */
1757
1758   /* Ensure that we'll be able to add alignment padding and the typecode */
1759   if (writer->enabled)
1760     {
1761       if (!_dbus_string_alloc_space (sub->value_str, 8))
1762         return FALSE;
1763     }
1764
1765   if (!write_or_verify_typecode (sub, DBUS_STRUCT_BEGIN_CHAR))
1766     _dbus_assert_not_reached ("failed to insert struct typecode after prealloc");
1767
1768   if (writer->enabled)
1769     {
1770       if (!_dbus_string_insert_bytes (sub->value_str,
1771                                       sub->value_pos,
1772                                       _DBUS_ALIGN_VALUE (sub->value_pos, 8) - sub->value_pos,
1773                                       '\0'))
1774         _dbus_assert_not_reached ("should not have failed to insert alignment padding for struct");
1775       sub->value_pos = _DBUS_ALIGN_VALUE (sub->value_pos, 8);
1776     }
1777
1778   return TRUE;
1779 }
1780
1781
1782 static dbus_bool_t
1783 writer_recurse_array (DBusTypeWriter   *writer,
1784                       const DBusString *contained_type,
1785                       int               contained_type_start,
1786                       int               contained_type_len,
1787                       DBusTypeWriter   *sub,
1788                       dbus_bool_t       is_array_append)
1789 {
1790   dbus_uint32_t value = 0;
1791   int alignment;
1792   int aligned;
1793
1794 #ifndef DBUS_DISABLE_CHECKS
1795   if (writer->container_type == DBUS_TYPE_ARRAY &&
1796       writer->type_str)
1797     {
1798       if (!_dbus_string_equal_substring (contained_type,
1799                                          contained_type_start,
1800                                          contained_type_len,
1801                                          writer->type_str,
1802                                          writer->u.array.element_type_pos + 1))
1803         {
1804           _dbus_warn ("Writing an array of '%s' but this is incompatible with the expected type of elements in the parent array\n",
1805                       _dbus_string_get_const_data_len (contained_type,
1806                                                        contained_type_start,
1807                                                        contained_type_len));
1808           _dbus_assert_not_reached ("incompatible type for child array");
1809         }
1810     }
1811 #endif /* DBUS_DISABLE_CHECKS */
1812
1813   if (writer->enabled && !is_array_append)
1814     {
1815       /* 3 pad + 4 bytes for the array length, and 4 bytes possible padding
1816        * before array values
1817        */
1818       if (!_dbus_string_alloc_space (sub->value_str, 3 + 4 + 4))
1819         return FALSE;
1820     }
1821
1822   if (writer->type_str != NULL)
1823     {
1824       sub->type_pos += 1; /* move to point to the element type, since type_pos
1825                            * should be the expected type for further writes
1826                            */
1827       sub->u.array.element_type_pos = sub->type_pos;
1828     }
1829
1830   if (!writer->type_pos_is_expectation)
1831     {
1832       /* sub is a toplevel/outermost array so we need to write the type data */
1833
1834       /* alloc space for array typecode, element signature */
1835       if (!_dbus_string_alloc_space (writer->type_str, 1 + contained_type_len))
1836         return FALSE;
1837
1838       if (!_dbus_string_insert_byte (writer->type_str,
1839                                      writer->type_pos,
1840                                      DBUS_TYPE_ARRAY))
1841         _dbus_assert_not_reached ("failed to insert array typecode after prealloc");
1842
1843       if (!_dbus_string_copy_len (contained_type,
1844                                   contained_type_start, contained_type_len,
1845                                   sub->type_str,
1846                                   sub->u.array.element_type_pos))
1847         _dbus_assert_not_reached ("should not have failed to insert array element typecodes");
1848     }
1849
1850   if (writer->type_str != NULL)
1851     {
1852       /* If the parent is an array, we hold type_pos pointing at the array element type;
1853        * otherwise advance it to reflect the array value we just recursed into
1854        */
1855       if (writer->container_type != DBUS_TYPE_ARRAY)
1856         writer->type_pos += 1 + contained_type_len;
1857       else
1858         _dbus_assert (writer->type_pos_is_expectation); /* because it's an array */
1859     }
1860
1861   if (writer->enabled)
1862     {
1863       /* Write (or jump over, if is_array_append) the length */
1864       sub->u.array.len_pos = _DBUS_ALIGN_VALUE (sub->value_pos, 4);
1865
1866       if (is_array_append)
1867         {
1868           sub->value_pos += 4;
1869         }
1870       else
1871         {
1872           if (!_dbus_type_writer_write_basic_no_typecode (sub, DBUS_TYPE_UINT32,
1873                                                           &value))
1874             _dbus_assert_not_reached ("should not have failed to insert array len");
1875         }
1876
1877       _dbus_assert (sub->u.array.len_pos == sub->value_pos - 4);
1878
1879       /* Write alignment padding for array elements
1880        * Note that we write the padding *even for empty arrays*
1881        * to avoid wonky special cases
1882        */
1883       alignment = element_type_get_alignment (contained_type, contained_type_start);
1884
1885       aligned = _DBUS_ALIGN_VALUE (sub->value_pos, alignment);
1886       if (aligned != sub->value_pos)
1887         {
1888           if (!is_array_append)
1889             {
1890               if (!_dbus_string_insert_bytes (sub->value_str,
1891                                               sub->value_pos,
1892                                               aligned - sub->value_pos,
1893                                               '\0'))
1894                 _dbus_assert_not_reached ("should not have failed to insert alignment padding");
1895             }
1896
1897           sub->value_pos = aligned;
1898         }
1899
1900       sub->u.array.start_pos = sub->value_pos;
1901
1902       if (is_array_append)
1903         {
1904           dbus_uint32_t len;
1905
1906           _dbus_assert (_DBUS_ALIGN_VALUE (sub->u.array.len_pos, 4) ==
1907                         (unsigned) sub->u.array.len_pos);
1908           len = _dbus_unpack_uint32 (sub->byte_order,
1909                                      _dbus_string_get_const_data_len (sub->value_str,
1910                                                                       sub->u.array.len_pos,
1911                                                                       4));
1912
1913           sub->value_pos += len;
1914         }
1915     }
1916   else
1917     {
1918       /* not enabled, so we won't write the len_pos; set it to -1 to so indicate */
1919       sub->u.array.len_pos = -1;
1920       sub->u.array.start_pos = sub->value_pos;
1921     }
1922
1923   _dbus_assert (sub->u.array.len_pos < sub->u.array.start_pos);
1924   _dbus_assert (is_array_append || sub->u.array.start_pos == sub->value_pos);
1925
1926 #if RECURSIVE_MARSHAL_WRITE_TRACE
1927       _dbus_verbose ("  type writer %p recurse array done remaining sig '%s' array start_pos = %d len_pos = %d value_pos = %d\n", sub,
1928                      sub->type_str ?
1929                      _dbus_string_get_const_data_len (sub->type_str, sub->type_pos, 0) :
1930                      "unknown",
1931                      sub->u.array.start_pos, sub->u.array.len_pos, sub->value_pos);
1932 #endif
1933
1934   return TRUE;
1935 }
1936
1937 /* Variant value will normally have:
1938  *   1 byte signature length not including nul
1939  *   signature typecodes (nul terminated)
1940  *   padding to 8-boundary
1941  *   body according to signature
1942  *
1943  * The signature string can only have a single type
1944  * in it but that type may be complex/recursive.
1945  *
1946  * So a typical variant type with the integer 3 will have these
1947  * octets:
1948  *   0x1 'i' '\0' [padding to 8-boundary] 0x0 0x0 0x0 0x3
1949  *
1950  * For an array of 4-byte types stuffed into variants, the padding to
1951  * 8-boundary is only the 1 byte that is required for the 4-boundary
1952  * anyhow for all array elements after the first one. And for single
1953  * variants in isolation, wasting a few bytes is hardly a big deal.
1954  *
1955  * The main world of hurt for writing out a variant is that the type
1956  * string is the same string as the value string. Which means
1957  * inserting to the type string will move the value_pos; and it means
1958  * that inserting to the type string could break type alignment.
1959  *
1960  * This type alignment issue is why the body of the variant is always
1961  * 8-aligned. Then we know that re-8-aligning the start of the body
1962  * will always correctly align the full contents of the variant type.
1963  */
1964 static dbus_bool_t
1965 writer_recurse_variant (DBusTypeWriter   *writer,
1966                         const DBusString *contained_type,
1967                         int               contained_type_start,
1968                         int               contained_type_len,
1969                         DBusTypeWriter   *sub)
1970 {
1971   if (writer->enabled)
1972     {
1973       /* Allocate space for the worst case, which is 1 byte sig
1974        * length, nul byte at end of sig, and 7 bytes padding to
1975        * 8-boundary.
1976        */
1977       if (!_dbus_string_alloc_space (sub->value_str, contained_type_len + 9))
1978         return FALSE;
1979     }
1980
1981   /* write VARIANT typecode to the parent's type string */
1982   if (!write_or_verify_typecode (writer, DBUS_TYPE_VARIANT))
1983     return FALSE;
1984
1985   /* If not enabled, mark that we have no type_str anymore ... */
1986
1987   if (!writer->enabled)
1988     {
1989       sub->type_str = NULL;
1990       sub->type_pos = -1;
1991
1992       return TRUE;
1993     }
1994
1995   /* If we're enabled then continue ... */
1996
1997   if (!_dbus_string_insert_byte (sub->value_str,
1998                                  sub->value_pos,
1999                                  contained_type_len))
2000     _dbus_assert_not_reached ("should not have failed to insert variant type sig len");
2001
2002   sub->value_pos += 1;
2003
2004   /* Here we switch over to the expected type sig we're about to write */
2005   sub->type_str = sub->value_str;
2006   sub->type_pos = sub->value_pos;
2007
2008   if (!_dbus_string_copy_len (contained_type, contained_type_start, contained_type_len,
2009                               sub->value_str, sub->value_pos))
2010     _dbus_assert_not_reached ("should not have failed to insert variant type sig");
2011
2012   sub->value_pos += contained_type_len;
2013
2014   if (!_dbus_string_insert_byte (sub->value_str,
2015                                  sub->value_pos,
2016                                  DBUS_TYPE_INVALID))
2017     _dbus_assert_not_reached ("should not have failed to insert variant type nul termination");
2018
2019   sub->value_pos += 1;
2020
2021   if (!_dbus_string_insert_bytes (sub->value_str,
2022                                   sub->value_pos,
2023                                   _DBUS_ALIGN_VALUE (sub->value_pos, 8) - sub->value_pos,
2024                                   '\0'))
2025     _dbus_assert_not_reached ("should not have failed to insert alignment padding for variant body");
2026   sub->value_pos = _DBUS_ALIGN_VALUE (sub->value_pos, 8);
2027
2028   return TRUE;
2029 }
2030
2031 static dbus_bool_t
2032 _dbus_type_writer_recurse_contained_len (DBusTypeWriter   *writer,
2033                                          int               container_type,
2034                                          const DBusString *contained_type,
2035                                          int               contained_type_start,
2036                                          int               contained_type_len,
2037                                          DBusTypeWriter   *sub,
2038                                          dbus_bool_t       is_array_append)
2039 {
2040   writer_recurse_init_and_check (writer, container_type, sub);
2041
2042   switch (container_type)
2043     {
2044     case DBUS_TYPE_STRUCT:
2045       return writer_recurse_struct (writer,
2046                                     contained_type, contained_type_start, contained_type_len,
2047                                     sub);
2048       break;
2049     case DBUS_TYPE_ARRAY:
2050       return writer_recurse_array (writer,
2051                                    contained_type, contained_type_start, contained_type_len,
2052                                    sub, is_array_append);
2053       break;
2054     case DBUS_TYPE_VARIANT:
2055       return writer_recurse_variant (writer,
2056                                      contained_type, contained_type_start, contained_type_len,
2057                                      sub);
2058       break;
2059     default:
2060       _dbus_assert_not_reached ("tried to recurse into type that doesn't support that");
2061       return FALSE;
2062       break;
2063     }
2064 }
2065
2066 /**
2067  * Opens a new container and writes out the initial information for that container.
2068  *
2069  * @param writer the writer
2070  * @param container_type the type of the container to open
2071  * @param contained_type the array element type or variant content type
2072  * @param contained_type_start position to look for the type
2073  * @param sub the new sub-writer to write container contents
2074  * @returns #FALSE if no memory
2075  */
2076 dbus_bool_t
2077 _dbus_type_writer_recurse (DBusTypeWriter   *writer,
2078                            int               container_type,
2079                            const DBusString *contained_type,
2080                            int               contained_type_start,
2081                            DBusTypeWriter   *sub)
2082 {
2083   int contained_type_len;
2084
2085   if (contained_type)
2086     contained_type_len = find_len_of_complete_type (contained_type, contained_type_start);
2087   else
2088     contained_type_len = 0;
2089
2090   return _dbus_type_writer_recurse_contained_len (writer, container_type,
2091                                                   contained_type,
2092                                                   contained_type_start,
2093                                                   contained_type_len,
2094                                                   sub,
2095                                                   FALSE);
2096 }
2097
2098 /**
2099  * Append to an existing array. Essentially, the writer will read an
2100  * existing length at the write location; jump over that length; and
2101  * write new fields. On unrecurse(), the existing length will be
2102  * updated.
2103  *
2104  * @param writer the writer
2105  * @param contained_type element type
2106  * @param contained_type_start position of element type
2107  * @param sub the subwriter to init
2108  * @returns #FALSE if no memory
2109  */
2110 dbus_bool_t
2111 _dbus_type_writer_append_array (DBusTypeWriter   *writer,
2112                                 const DBusString *contained_type,
2113                                 int               contained_type_start,
2114                                 DBusTypeWriter   *sub)
2115 {
2116   int contained_type_len;
2117
2118   if (contained_type)
2119     contained_type_len = find_len_of_complete_type (contained_type, contained_type_start);
2120   else
2121     contained_type_len = 0;
2122
2123   return _dbus_type_writer_recurse_contained_len (writer, DBUS_TYPE_ARRAY,
2124                                                   contained_type,
2125                                                   contained_type_start,
2126                                                   contained_type_len,
2127                                                   sub,
2128                                                   TRUE);
2129 }
2130
2131 static int
2132 writer_get_array_len (DBusTypeWriter *writer)
2133 {
2134   _dbus_assert (writer->container_type == DBUS_TYPE_ARRAY);
2135   return writer->value_pos - writer->u.array.start_pos;
2136 }
2137
2138 /**
2139  * Closes a container created by _dbus_type_writer_recurse()
2140  * and writes any additional information to the values block.
2141  *
2142  * @param writer the writer
2143  * @param sub the sub-writer created by _dbus_type_writer_recurse()
2144  * @returns #FALSE if no memory
2145  */
2146 dbus_bool_t
2147 _dbus_type_writer_unrecurse (DBusTypeWriter *writer,
2148                              DBusTypeWriter *sub)
2149 {
2150   /* type_pos_is_expectation never gets unset once set, or we'd get all hosed */
2151   _dbus_assert (!writer->type_pos_is_expectation ||
2152                 (writer->type_pos_is_expectation && sub->type_pos_is_expectation));
2153
2154 #if RECURSIVE_MARSHAL_WRITE_TRACE
2155   _dbus_verbose ("  type writer %p unrecurse type_pos = %d value_pos = %d is_expectation = %d container_type = %s\n",
2156                  writer, writer->type_pos, writer->value_pos, writer->type_pos_is_expectation,
2157                  _dbus_type_to_string (writer->container_type));
2158   _dbus_verbose ("  type writer %p unrecurse sub type_pos = %d value_pos = %d is_expectation = %d container_type = %s\n",
2159                  sub, sub->type_pos, sub->value_pos,
2160                  sub->type_pos_is_expectation,
2161                  _dbus_type_to_string (sub->container_type));
2162 #endif
2163
2164   if (sub->container_type == DBUS_TYPE_STRUCT)
2165     {
2166       if (!write_or_verify_typecode (sub, DBUS_STRUCT_END_CHAR))
2167         return FALSE;
2168     }
2169   else if (sub->container_type == DBUS_TYPE_ARRAY)
2170     {
2171       if (sub->u.array.len_pos >= 0) /* len_pos == -1 if we weren't enabled when we passed it */
2172         {
2173           dbus_uint32_t len;
2174
2175           /* Set the array length */
2176           len = writer_get_array_len (sub);
2177           _dbus_marshal_set_uint32 (sub->value_str,
2178                                     sub->u.array.len_pos,
2179                                     len,
2180                                     sub->byte_order);
2181 #if RECURSIVE_MARSHAL_WRITE_TRACE
2182           _dbus_verbose ("    filled in sub array len to %u at len_pos %d\n",
2183                          len, sub->u.array.len_pos);
2184 #endif
2185         }
2186 #if RECURSIVE_MARSHAL_WRITE_TRACE
2187       else
2188         {
2189           _dbus_verbose ("    not filling in sub array len because we were disabled when we passed the len\n");
2190         }
2191 #endif
2192     }
2193
2194   /* Now get type_pos right for the parent writer. Here are the cases:
2195    *
2196    * Cases !writer->type_pos_is_expectation:
2197    *   (in these cases we want to update to the new insertion point)
2198    *
2199    * - if we recursed into a STRUCT then we didn't know in advance
2200    *   what the types in the struct would be; so we have to fill in
2201    *   that information now.
2202    *       writer->type_pos = sub->type_pos
2203    *
2204    * - if we recursed into anything else, we knew the full array
2205    *   type, or knew the single typecode marking VARIANT, so
2206    *   writer->type_pos is already correct.
2207    *       writer->type_pos should remain as-is
2208    *
2209    * - note that the parent is never an ARRAY or VARIANT, if it were
2210    *   then type_pos_is_expectation would be TRUE. The parent
2211    *   is thus known to be a toplevel or STRUCT.
2212    *
2213    * Cases where writer->type_pos_is_expectation:
2214    *   (in these cases we want to update to next expected type to write)
2215    *
2216    * - we recursed from STRUCT into STRUCT and we didn't increment
2217    *   type_pos in the parent just to stay consistent with the
2218    *   !writer->type_pos_is_expectation case (though we could
2219    *   special-case this in recurse_struct instead if we wanted)
2220    *       writer->type_pos = sub->type_pos
2221    *
2222    * - we recursed from STRUCT into ARRAY or VARIANT and type_pos
2223    *   for parent should have been incremented already
2224    *       writer->type_pos should remain as-is
2225    *
2226    * - we recursed from ARRAY into a sub-element, so type_pos in the
2227    *   parent is the element type and should remain the element type
2228    *   for the benefit of the next child element
2229    *       writer->type_pos should remain as-is
2230    *
2231    * - we recursed from VARIANT into its value, so type_pos in the
2232    *   parent makes no difference since there's only one value
2233    *   and we just finished writing it and won't use type_pos again
2234    *       writer->type_pos should remain as-is
2235    */
2236   if (writer->type_str != NULL)
2237     {
2238       if (sub->container_type == DBUS_TYPE_STRUCT &&
2239           (writer->container_type == DBUS_TYPE_STRUCT ||
2240            writer->container_type == DBUS_TYPE_INVALID))
2241         {
2242           /* Advance the parent to the next struct field */
2243           writer->type_pos = sub->type_pos;
2244         }
2245     }
2246
2247   writer->value_pos = sub->value_pos;
2248
2249 #if RECURSIVE_MARSHAL_WRITE_TRACE
2250   _dbus_verbose ("  type writer %p unrecursed type_pos = %d value_pos = %d remaining sig '%s'\n",
2251                  writer, writer->type_pos, writer->value_pos,
2252                  writer->type_str ?
2253                  _dbus_string_get_const_data_len (writer->type_str, writer->type_pos, 0) :
2254                  "unknown");
2255 #endif
2256
2257   return TRUE;
2258 }
2259
2260 /**
2261  * Writes out a basic type.
2262  *
2263  * @param writer the writer
2264  * @param type the type to write
2265  * @param value the address of the value to write
2266  * @returns #FALSE if no memory
2267  */
2268 dbus_bool_t
2269 _dbus_type_writer_write_basic (DBusTypeWriter *writer,
2270                                int             type,
2271                                const void     *value)
2272 {
2273   dbus_bool_t retval;
2274
2275   /* First ensure that our type realloc will succeed */
2276   if (!writer->type_pos_is_expectation && writer->type_str != NULL)
2277     {
2278       if (!_dbus_string_alloc_space (writer->type_str, 1))
2279         return FALSE;
2280     }
2281
2282   retval = FALSE;
2283
2284   if (!_dbus_type_writer_write_basic_no_typecode (writer, type, value))
2285     goto out;
2286
2287   if (!write_or_verify_typecode (writer, type))
2288     _dbus_assert_not_reached ("failed to write typecode after prealloc");
2289
2290   retval = TRUE;
2291
2292  out:
2293 #if RECURSIVE_MARSHAL_WRITE_TRACE
2294   _dbus_verbose ("  type writer %p basic type_pos = %d value_pos = %d is_expectation = %d enabled = %d\n",
2295                  writer, writer->type_pos, writer->value_pos, writer->type_pos_is_expectation,
2296                  writer->enabled);
2297 #endif
2298
2299   return retval;
2300 }
2301
2302 /**
2303  * Writes a block of fixed-length basic values, i.e. those that are
2304  * both _dbus_type_is_fixed() and _dbus_type_is_basic(). The block
2305  * must be written inside an array.
2306  *
2307  * The value parameter should be the address of said array of values,
2308  * so e.g. if it's an array of double, pass in "const double**"
2309  *
2310  * @param writer the writer
2311  * @param element_type type of stuff in the array
2312  * @param value address of the array
2313  * @param n_elements number of elements in the array
2314  * @returns #FALSE if no memory
2315  */
2316 dbus_bool_t
2317 _dbus_type_writer_write_fixed_multi (DBusTypeWriter        *writer,
2318                                      int                    element_type,
2319                                      const void            *value,
2320                                      int                    n_elements)
2321 {
2322   _dbus_assert (writer->container_type == DBUS_TYPE_ARRAY);
2323   _dbus_assert (_dbus_type_is_fixed (element_type));
2324   _dbus_assert (writer->type_pos_is_expectation);
2325   _dbus_assert (n_elements >= 0);
2326
2327 #if RECURSIVE_MARSHAL_WRITE_TRACE
2328   _dbus_verbose ("  type writer %p entering fixed multi type_pos = %d value_pos = %d n_elements %d\n",
2329                  writer, writer->type_pos, writer->value_pos, n_elements);
2330 #endif
2331
2332   if (!write_or_verify_typecode (writer, element_type))
2333     _dbus_assert_not_reached ("OOM should not happen if only verifying typecode");
2334
2335   if (writer->enabled)
2336     {
2337       if (!_dbus_marshal_write_fixed_multi (writer->value_str,
2338                                             writer->value_pos,
2339                                             element_type,
2340                                             value,
2341                                             n_elements,
2342                                             writer->byte_order,
2343                                             &writer->value_pos))
2344         return FALSE;
2345     }
2346
2347 #if RECURSIVE_MARSHAL_WRITE_TRACE
2348   _dbus_verbose ("  type writer %p fixed multi written new type_pos = %d new value_pos = %d n_elements %d\n",
2349                  writer, writer->type_pos, writer->value_pos, n_elements);
2350 #endif
2351
2352   return TRUE;
2353 }
2354
2355 static void
2356 enable_if_after (DBusTypeWriter       *writer,
2357                  DBusTypeReader       *reader,
2358                  const DBusTypeReader *start_after)
2359 {
2360   if (start_after)
2361     {
2362       if (!writer->enabled && _dbus_type_reader_greater_than (reader, start_after))
2363         {
2364           _dbus_type_writer_set_enabled (writer, TRUE);
2365 #if RECURSIVE_MARSHAL_WRITE_TRACE
2366           _dbus_verbose ("ENABLING writer %p at %d because reader at value_pos %d is after reader at value_pos %d\n",
2367                          writer, writer->value_pos, reader->value_pos, start_after->value_pos);
2368 #endif
2369         }
2370
2371       _dbus_assert ((!writer->enabled && !_dbus_type_reader_greater_than (reader, start_after)) ||
2372                     (writer->enabled && _dbus_type_reader_greater_than (reader, start_after)));
2373     }
2374 }
2375
2376 static dbus_bool_t
2377 append_fixup (DBusList               **fixups,
2378               const DBusArrayLenFixup *fixup)
2379 {
2380   DBusArrayLenFixup *f;
2381
2382   f = dbus_new (DBusArrayLenFixup, 1);
2383   if (f == NULL)
2384     return FALSE;
2385
2386   *f = *fixup;
2387
2388   if (!_dbus_list_append (fixups, f))
2389     {
2390       dbus_free (f);
2391       return FALSE;
2392     }
2393
2394   _dbus_assert (f->len_pos_in_reader == fixup->len_pos_in_reader);
2395   _dbus_assert (f->new_len == fixup->new_len);
2396
2397   return TRUE;
2398 }
2399
2400 /* This loop is trivial if you ignore all the start_after nonsense,
2401  * so if you're trying to figure it out, start by ignoring that
2402  */
2403 static dbus_bool_t
2404 writer_write_reader_helper (DBusTypeWriter       *writer,
2405                             DBusTypeReader       *reader,
2406                             const DBusTypeReader *start_after,
2407                             int                   start_after_new_pos,
2408                             int                   start_after_new_len,
2409                             DBusList            **fixups,
2410                             dbus_bool_t           inside_start_after)
2411 {
2412   int current_type;
2413
2414   while ((current_type = _dbus_type_reader_get_current_type (reader)) != DBUS_TYPE_INVALID)
2415     {
2416       if (_dbus_type_is_container (current_type))
2417         {
2418           DBusTypeReader subreader;
2419           DBusTypeWriter subwriter;
2420           const DBusString *sig_str;
2421           int sig_start;
2422           int sig_len;
2423           dbus_bool_t enabled_at_recurse;
2424           dbus_bool_t past_start_after;
2425           int reader_array_len_pos;
2426           int reader_array_start_pos;
2427           dbus_bool_t this_is_start_after;
2428
2429           /* type_pos is checked since e.g. in a struct the struct
2430            * and its first field have the same value_pos.
2431            * type_str will differ in reader/start_after for variants
2432            * where type_str is inside the value_str
2433            */
2434           if (!inside_start_after && start_after &&
2435               reader->value_pos == start_after->value_pos &&
2436               reader->type_str == start_after->type_str &&
2437               reader->type_pos == start_after->type_pos)
2438             this_is_start_after = TRUE;
2439           else
2440             this_is_start_after = FALSE;
2441
2442           _dbus_type_reader_recurse (reader, &subreader);
2443
2444           if (current_type == DBUS_TYPE_ARRAY)
2445             {
2446               reader_array_len_pos = ARRAY_READER_LEN_POS (&subreader);
2447               reader_array_start_pos = subreader.u.array.start_pos;
2448             }
2449           else
2450             {
2451               /* quiet gcc */
2452               reader_array_len_pos = -1;
2453               reader_array_start_pos = -1;
2454             }
2455
2456           _dbus_type_reader_get_signature (&subreader, &sig_str,
2457                                            &sig_start, &sig_len);
2458
2459 #if RECURSIVE_MARSHAL_WRITE_TRACE
2460           _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",
2461                          _dbus_type_to_string (current_type),
2462                          reader->value_pos,
2463                          subreader.value_pos,
2464                          writer->value_pos,
2465                          start_after ? start_after->value_pos : -1,
2466                          _dbus_string_get_length (writer->value_str),
2467                          inside_start_after, this_is_start_after);
2468 #endif
2469
2470           if (!inside_start_after && !this_is_start_after)
2471             enable_if_after (writer, &subreader, start_after);
2472           enabled_at_recurse = writer->enabled;
2473           if (!_dbus_type_writer_recurse_contained_len (writer, current_type,
2474                                                         sig_str, sig_start, sig_len,
2475                                                         &subwriter, FALSE))
2476             goto oom;
2477
2478 #if RECURSIVE_MARSHAL_WRITE_TRACE
2479           _dbus_verbose ("recursed into subwriter at %d write target len %d\n",
2480                          subwriter.value_pos,
2481                          _dbus_string_get_length (subwriter.value_str));
2482 #endif
2483
2484           if (!writer_write_reader_helper (&subwriter, &subreader, start_after,
2485                                            start_after_new_pos, start_after_new_len,
2486                                            fixups,
2487                                            inside_start_after ||
2488                                            this_is_start_after))
2489             goto oom;
2490
2491 #if RECURSIVE_MARSHAL_WRITE_TRACE
2492           _dbus_verbose ("about to unrecurse from %s subreader at %d writer at %d subwriter at %d  write target len %d\n",
2493                          _dbus_type_to_string (current_type),
2494                          subreader.value_pos,
2495                          writer->value_pos,
2496                          subwriter.value_pos,
2497                          _dbus_string_get_length (writer->value_str));
2498 #endif
2499
2500           if (!inside_start_after && !this_is_start_after)
2501             enable_if_after (writer, &subreader, start_after);
2502           past_start_after = writer->enabled;
2503           if (!_dbus_type_writer_unrecurse (writer, &subwriter))
2504             goto oom;
2505
2506           /* If we weren't enabled when we recursed, we didn't
2507            * write an array len; if we passed start_after
2508            * somewhere inside the array, then we need to generate
2509            * a fixup.
2510            */
2511           if (start_after != NULL &&
2512               !enabled_at_recurse && past_start_after &&
2513               current_type == DBUS_TYPE_ARRAY &&
2514               fixups != NULL)
2515             {
2516               DBusArrayLenFixup fixup;
2517               int bytes_written_after_start_after;
2518               int bytes_before_start_after;
2519               int old_len;
2520
2521               /* this subwriter access is moderately unkosher since we
2522                * already unrecursed, but it works as long as unrecurse
2523                * doesn't break us on purpose
2524                */
2525               bytes_written_after_start_after = writer_get_array_len (&subwriter);
2526
2527               bytes_before_start_after =
2528                 start_after->value_pos - reader_array_start_pos;
2529
2530               fixup.len_pos_in_reader = reader_array_len_pos;
2531               fixup.new_len =
2532                 bytes_before_start_after +
2533                 start_after_new_len +
2534                 bytes_written_after_start_after;
2535
2536               _dbus_assert (_DBUS_ALIGN_VALUE (fixup.len_pos_in_reader, 4) ==
2537                             (unsigned) fixup.len_pos_in_reader);
2538
2539               old_len = _dbus_unpack_uint32 (reader->byte_order,
2540                                              _dbus_string_get_const_data_len (reader->value_str,
2541                                                                               fixup.len_pos_in_reader, 4));
2542
2543               if (old_len != fixup.new_len && !append_fixup (fixups, &fixup))
2544                 goto oom;
2545
2546 #if RECURSIVE_MARSHAL_WRITE_TRACE
2547               _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",
2548                              fixup.len_pos_in_reader,
2549                              fixup.new_len,
2550                              reader_array_start_pos,
2551                              start_after->value_pos,
2552                              bytes_before_start_after,
2553                              start_after_new_len,
2554                              bytes_written_after_start_after);
2555 #endif
2556             }
2557         }
2558       else
2559         {
2560           DBusBasicValue val;
2561
2562           _dbus_assert (_dbus_type_is_basic (current_type));
2563
2564 #if RECURSIVE_MARSHAL_WRITE_TRACE
2565           _dbus_verbose ("Reading basic value %s at %d\n",
2566                          _dbus_type_to_string (current_type),
2567                          reader->value_pos);
2568 #endif
2569
2570           _dbus_type_reader_read_basic (reader, &val);
2571
2572 #if RECURSIVE_MARSHAL_WRITE_TRACE
2573           _dbus_verbose ("Writing basic value %s at %d write target len %d inside_start_after = %d\n",
2574                          _dbus_type_to_string (current_type),
2575                          writer->value_pos,
2576                          _dbus_string_get_length (writer->value_str),
2577                          inside_start_after);
2578 #endif
2579           if (!inside_start_after)
2580             enable_if_after (writer, reader, start_after);
2581           if (!_dbus_type_writer_write_basic (writer, current_type, &val))
2582             goto oom;
2583 #if RECURSIVE_MARSHAL_WRITE_TRACE
2584           _dbus_verbose ("Wrote basic value %s, new value_pos %d write target len %d\n",
2585                          _dbus_type_to_string (current_type),
2586                          writer->value_pos,
2587                          _dbus_string_get_length (writer->value_str));
2588 #endif
2589         }
2590
2591       _dbus_type_reader_next (reader);
2592     }
2593
2594   return TRUE;
2595
2596  oom:
2597   if (fixups)
2598     apply_and_free_fixups (fixups, NULL); /* NULL for reader to apply to */
2599
2600   return FALSE;
2601 }
2602
2603 /**
2604  * Iterate through all values in the given reader, writing a copy of
2605  * each value to the writer.  The reader will be moved forward to its
2606  * end position.
2607  *
2608  * If a reader start_after is provided, it should be a reader for the
2609  * same data as the reader to be written. Only values occurring after
2610  * the value pointed to by start_after will be written to the writer.
2611  *
2612  * If start_after is provided, then the copy of the reader will be
2613  * partial. This means that array lengths will not have been copied.
2614  * The assumption is that you wrote a new version of the value at
2615  * start_after to the writer. You have to pass in the start position
2616  * and length of the new value. (If you are deleting the value
2617  * at start_after, pass in 0 for the length.)
2618  *
2619  * If the fixups parameter is non-#NULL, then any array length that
2620  * was read but not written due to start_after will be provided
2621  * as a #DBusArrayLenFixup. The fixup contains the position of the
2622  * array length in the source data, and the correct array length
2623  * assuming you combine the source data before start_after with
2624  * the written data at start_after and beyond.
2625  *
2626  * @param writer the writer to copy to
2627  * @param reader the reader to copy from
2628  * @param start_after #NULL or a reader showing where to start
2629  * @param start_after_new_pos the position of start_after equivalent in the target data
2630  * @param start_after_new_len the length of start_after equivalent in the target data
2631  * @param fixups list to append #DBusArrayLenFixup if the write was partial
2632  * @returns #FALSE if no memory
2633  */
2634 dbus_bool_t
2635 _dbus_type_writer_write_reader_partial (DBusTypeWriter       *writer,
2636                                         DBusTypeReader       *reader,
2637                                         const DBusTypeReader *start_after,
2638                                         int                   start_after_new_pos,
2639                                         int                   start_after_new_len,
2640                                         DBusList            **fixups)
2641 {
2642   DBusTypeWriter orig;
2643   int orig_type_len;
2644   int orig_value_len;
2645   int new_bytes;
2646   int orig_enabled;
2647
2648   orig = *writer;
2649   orig_type_len = _dbus_string_get_length (writer->type_str);
2650   orig_value_len = _dbus_string_get_length (writer->value_str);
2651   orig_enabled = writer->enabled;
2652
2653   if (start_after)
2654     _dbus_type_writer_set_enabled (writer, FALSE);
2655
2656   if (!writer_write_reader_helper (writer, reader, start_after,
2657                                    start_after_new_pos,
2658                                    start_after_new_len,
2659                                    fixups, FALSE))
2660     goto oom;
2661
2662   _dbus_type_writer_set_enabled (writer, orig_enabled);
2663   return TRUE;
2664
2665  oom:
2666   if (!writer->type_pos_is_expectation)
2667     {
2668       new_bytes = _dbus_string_get_length (writer->type_str) - orig_type_len;
2669       _dbus_string_delete (writer->type_str, orig.type_pos, new_bytes);
2670     }
2671   new_bytes = _dbus_string_get_length (writer->value_str) - orig_value_len;
2672   _dbus_string_delete (writer->value_str, orig.value_pos, new_bytes);
2673
2674   *writer = orig;
2675
2676   return FALSE;
2677 }
2678
2679 /**
2680  * Iterate through all values in the given reader, writing a copy of
2681  * each value to the writer.  The reader will be moved forward to its
2682  * end position.
2683  *
2684  * @param writer the writer to copy to
2685  * @param reader the reader to copy from
2686  * @returns #FALSE if no memory
2687  */
2688 dbus_bool_t
2689 _dbus_type_writer_write_reader (DBusTypeWriter       *writer,
2690                                 DBusTypeReader       *reader)
2691 {
2692   return _dbus_type_writer_write_reader_partial (writer, reader, NULL, 0, 0, NULL);
2693 }
2694
2695 /**
2696  * If disabled, a writer can still be iterated forward and recursed/unrecursed
2697  * but won't write any values. Types will still be written unless the
2698  * writer is a "values only" writer, because the writer needs access to
2699  * a valid signature to be able to iterate.
2700  *
2701  * @param writer the type writer
2702  * @param enabled #TRUE if values should be written
2703  */
2704 void
2705 _dbus_type_writer_set_enabled (DBusTypeWriter   *writer,
2706                                dbus_bool_t       enabled)
2707 {
2708   writer->enabled = enabled != FALSE;
2709 }
2710
2711 /** @} */ /* end of DBusMarshal group */
2712
2713 #ifdef DBUS_BUILD_TESTS
2714 #include "dbus-test.h"
2715 #include "dbus-list.h"
2716 #include <stdio.h>
2717 #include <stdlib.h>
2718
2719 /* Whether to do the OOM stuff (only with other expensive tests) */
2720 #define TEST_OOM_HANDLING 0
2721 /* We do start offset 0 through 9, to get various alignment cases. Still this
2722  * obviously makes the test suite run 10x as slow.
2723  */
2724 #define MAX_INITIAL_OFFSET 9
2725
2726 /* Largest iteration count to test copying, realignment,
2727  * etc. with. i.e. we only test this stuff with some of the smaller
2728  * data sets.
2729  */
2730 #define MAX_ITERATIONS_FOR_EXPENSIVE_TESTS 1000
2731
2732 typedef struct
2733 {
2734   int byte_order;
2735   int initial_offset;
2736   DBusString signature;
2737   DBusString body;
2738 } DataBlock;
2739
2740 typedef struct
2741 {
2742   int saved_sig_len;
2743   int saved_body_len;
2744 } DataBlockState;
2745
2746 #define N_FENCE_BYTES 5
2747 #define FENCE_BYTES_STR "abcde"
2748 #define INITIAL_PADDING_BYTE '\0'
2749
2750 static dbus_bool_t
2751 data_block_init (DataBlock *block,
2752                  int        byte_order,
2753                  int        initial_offset)
2754 {
2755   if (!_dbus_string_init (&block->signature))
2756     return FALSE;
2757
2758   if (!_dbus_string_init (&block->body))
2759     {
2760       _dbus_string_free (&block->signature);
2761       return FALSE;
2762     }
2763
2764   if (!_dbus_string_insert_bytes (&block->signature, 0, initial_offset,
2765                                   INITIAL_PADDING_BYTE) ||
2766       !_dbus_string_insert_bytes (&block->body, 0, initial_offset,
2767                                   INITIAL_PADDING_BYTE) ||
2768       !_dbus_string_append (&block->signature, FENCE_BYTES_STR) ||
2769       !_dbus_string_append (&block->body, FENCE_BYTES_STR))
2770     {
2771       _dbus_string_free (&block->signature);
2772       _dbus_string_free (&block->body);
2773       return FALSE;
2774     }
2775
2776   block->byte_order = byte_order;
2777   block->initial_offset = initial_offset;
2778
2779   return TRUE;
2780 }
2781
2782 static void
2783 data_block_save (DataBlock      *block,
2784                  DataBlockState *state)
2785 {
2786   state->saved_sig_len = _dbus_string_get_length (&block->signature) - N_FENCE_BYTES;
2787   state->saved_body_len = _dbus_string_get_length (&block->body) - N_FENCE_BYTES;
2788 }
2789
2790 static void
2791 data_block_restore (DataBlock      *block,
2792                     DataBlockState *state)
2793 {
2794   _dbus_string_delete (&block->signature,
2795                        state->saved_sig_len,
2796                        _dbus_string_get_length (&block->signature) - state->saved_sig_len - N_FENCE_BYTES);
2797   _dbus_string_delete (&block->body,
2798                        state->saved_body_len,
2799                        _dbus_string_get_length (&block->body) - state->saved_body_len - N_FENCE_BYTES);
2800 }
2801
2802 static void
2803 data_block_verify (DataBlock *block)
2804 {
2805   if (!_dbus_string_ends_with_c_str (&block->signature,
2806                                      FENCE_BYTES_STR))
2807     {
2808       int offset;
2809
2810       offset = _dbus_string_get_length (&block->signature) - N_FENCE_BYTES - 8;
2811       if (offset < 0)
2812         offset = 0;
2813
2814       _dbus_verbose_bytes_of_string (&block->signature,
2815                                      offset,
2816                                      _dbus_string_get_length (&block->signature) - offset);
2817       _dbus_assert_not_reached ("block did not verify: bad bytes at end of signature");
2818     }
2819   if (!_dbus_string_ends_with_c_str (&block->body,
2820                                      FENCE_BYTES_STR))
2821     {
2822       int offset;
2823
2824       offset = _dbus_string_get_length (&block->body) - N_FENCE_BYTES - 8;
2825       if (offset < 0)
2826         offset = 0;
2827
2828       _dbus_verbose_bytes_of_string (&block->body,
2829                                      offset,
2830                                      _dbus_string_get_length (&block->body) - offset);
2831       _dbus_assert_not_reached ("block did not verify: bad bytes at end of body");
2832     }
2833
2834   _dbus_assert (_dbus_string_validate_nul (&block->signature,
2835                                            0, block->initial_offset));
2836   _dbus_assert (_dbus_string_validate_nul (&block->body,
2837                                            0, block->initial_offset));
2838 }
2839
2840 static void
2841 data_block_free (DataBlock *block)
2842 {
2843   data_block_verify (block);
2844
2845   _dbus_string_free (&block->signature);
2846   _dbus_string_free (&block->body);
2847 }
2848
2849 static void
2850 data_block_reset (DataBlock *block)
2851 {
2852   data_block_verify (block);
2853
2854   _dbus_string_delete (&block->signature,
2855                        block->initial_offset,
2856                        _dbus_string_get_length (&block->signature) - N_FENCE_BYTES - block->initial_offset);
2857   _dbus_string_delete (&block->body,
2858                        block->initial_offset,
2859                        _dbus_string_get_length (&block->body) - N_FENCE_BYTES - block->initial_offset);
2860
2861   data_block_verify (block);
2862 }
2863
2864 static void
2865 data_block_init_reader_writer (DataBlock      *block,
2866                                DBusTypeReader *reader,
2867                                DBusTypeWriter *writer)
2868 {
2869   if (reader)
2870     _dbus_type_reader_init (reader,
2871                             block->byte_order,
2872                             &block->signature,
2873                             block->initial_offset,
2874                             &block->body,
2875                             block->initial_offset);
2876
2877   if (writer)
2878     _dbus_type_writer_init (writer,
2879                             block->byte_order,
2880                             &block->signature,
2881                             _dbus_string_get_length (&block->signature) - N_FENCE_BYTES,
2882                             &block->body,
2883                             _dbus_string_get_length (&block->body) - N_FENCE_BYTES);
2884 }
2885
2886 static void
2887 real_check_expected_type (DBusTypeReader *reader,
2888                           int             expected,
2889                           const char     *funcname,
2890                           int             line)
2891 {
2892   int t;
2893
2894   t = _dbus_type_reader_get_current_type (reader);
2895
2896   if (t != expected)
2897     {
2898       _dbus_warn ("Read type %s while expecting %s at %s line %d\n",
2899                   _dbus_type_to_string (t),
2900                   _dbus_type_to_string (expected),
2901                   funcname, line);
2902
2903       _dbus_assert_not_reached ("read wrong type");
2904     }
2905 }
2906
2907 #define check_expected_type(reader, expected) real_check_expected_type (reader, expected, _DBUS_FUNCTION_NAME, __LINE__)
2908
2909 #define NEXT_EXPECTING_TRUE(reader)  do { if (!_dbus_type_reader_next (reader))         \
2910  {                                                                                      \
2911     _dbus_warn ("_dbus_type_reader_next() should have returned TRUE at %s %d\n",        \
2912                               _DBUS_FUNCTION_NAME, __LINE__);                           \
2913     _dbus_assert_not_reached ("test failed");                                           \
2914  }                                                                                      \
2915 } while (0)
2916
2917 #define NEXT_EXPECTING_FALSE(reader) do { if (_dbus_type_reader_next (reader))          \
2918  {                                                                                      \
2919     _dbus_warn ("_dbus_type_reader_next() should have returned FALSE at %s %d\n",       \
2920                               _DBUS_FUNCTION_NAME, __LINE__);                           \
2921     _dbus_assert_not_reached ("test failed");                                           \
2922  }                                                                                      \
2923  check_expected_type (reader, DBUS_TYPE_INVALID);                                       \
2924 } while (0)
2925
2926 typedef struct TestTypeNode               TestTypeNode;
2927 typedef struct TestTypeNodeClass          TestTypeNodeClass;
2928 typedef struct TestTypeNodeContainer      TestTypeNodeContainer;
2929 typedef struct TestTypeNodeContainerClass TestTypeNodeContainerClass;
2930
2931 struct TestTypeNode
2932 {
2933   const TestTypeNodeClass *klass;
2934 };
2935
2936 struct TestTypeNodeContainer
2937 {
2938   TestTypeNode base;
2939   DBusList    *children;
2940 };
2941
2942 struct TestTypeNodeClass
2943 {
2944   int typecode;
2945
2946   int instance_size;
2947
2948   int subclass_detail; /* a bad hack to avoid a bunch of subclass casting */
2949
2950   dbus_bool_t   (* construct)     (TestTypeNode   *node);
2951   void          (* destroy)       (TestTypeNode   *node);
2952
2953   dbus_bool_t (* write_value)     (TestTypeNode   *node,
2954                                    DataBlock      *block,
2955                                    DBusTypeWriter *writer,
2956                                    int             seed);
2957   dbus_bool_t (* read_value)      (TestTypeNode   *node,
2958                                    DBusTypeReader *reader,
2959                                    int             seed);
2960   dbus_bool_t (* set_value)       (TestTypeNode   *node,
2961                                    DBusTypeReader *reader,
2962                                    DBusTypeReader *realign_root,
2963                                    int             seed);
2964   dbus_bool_t (* build_signature) (TestTypeNode   *node,
2965                                    DBusString     *str);
2966   dbus_bool_t (* write_multi)     (TestTypeNode   *node,
2967                                    DataBlock      *block,
2968                                    DBusTypeWriter *writer,
2969                                    int             seed,
2970                                    int             count);
2971   dbus_bool_t (* read_multi)      (TestTypeNode   *node,
2972                                    DBusTypeReader *reader,
2973                                    int             seed,
2974                                    int             count);
2975 };
2976
2977 struct TestTypeNodeContainerClass
2978 {
2979   TestTypeNodeClass base;
2980 };
2981
2982 /* FIXME this could be chilled out substantially by unifying
2983  * the basic types into basic_write_value/basic_read_value
2984  * and by merging read_value and set_value into one function
2985  * taking a flag argument.
2986  */
2987 static dbus_bool_t int32_write_value       (TestTypeNode   *node,
2988                                             DataBlock      *block,
2989                                             DBusTypeWriter *writer,
2990                                             int             seed);
2991 static dbus_bool_t int32_read_value        (TestTypeNode   *node,
2992                                             DBusTypeReader *reader,
2993                                             int             seed);
2994 static dbus_bool_t int32_set_value         (TestTypeNode   *node,
2995                                             DBusTypeReader *reader,
2996                                             DBusTypeReader *realign_root,
2997                                             int             seed);
2998 static dbus_bool_t int32_write_multi       (TestTypeNode   *node,
2999                                             DataBlock      *block,
3000                                             DBusTypeWriter *writer,
3001                                             int             seed,
3002                                             int             count);
3003 static dbus_bool_t int32_read_multi        (TestTypeNode   *node,
3004                                             DBusTypeReader *reader,
3005                                             int             seed,
3006                                             int             count);
3007 static dbus_bool_t int64_write_value       (TestTypeNode   *node,
3008                                             DataBlock      *block,
3009                                             DBusTypeWriter *writer,
3010                                             int             seed);
3011 static dbus_bool_t int64_read_value        (TestTypeNode   *node,
3012                                             DBusTypeReader *reader,
3013                                             int             seed);
3014 static dbus_bool_t int64_set_value         (TestTypeNode   *node,
3015                                             DBusTypeReader *reader,
3016                                             DBusTypeReader *realign_root,
3017                                             int             seed);
3018 static dbus_bool_t string_write_value      (TestTypeNode   *node,
3019                                             DataBlock      *block,
3020                                             DBusTypeWriter *writer,
3021                                             int             seed);
3022 static dbus_bool_t string_read_value       (TestTypeNode   *node,
3023                                             DBusTypeReader *reader,
3024                                             int             seed);
3025 static dbus_bool_t string_set_value        (TestTypeNode   *node,
3026                                             DBusTypeReader *reader,
3027                                             DBusTypeReader *realign_root,
3028                                             int             seed);
3029 static dbus_bool_t bool_write_value        (TestTypeNode   *node,
3030                                             DataBlock      *block,
3031                                             DBusTypeWriter *writer,
3032                                             int             seed);
3033 static dbus_bool_t bool_read_value         (TestTypeNode   *node,
3034                                             DBusTypeReader *reader,
3035                                             int             seed);
3036 static dbus_bool_t bool_set_value          (TestTypeNode   *node,
3037                                             DBusTypeReader *reader,
3038                                             DBusTypeReader *realign_root,
3039                                             int             seed);
3040 static dbus_bool_t byte_write_value        (TestTypeNode   *node,
3041                                             DataBlock      *block,
3042                                             DBusTypeWriter *writer,
3043                                             int             seed);
3044 static dbus_bool_t byte_read_value         (TestTypeNode   *node,
3045                                             DBusTypeReader *reader,
3046                                             int             seed);
3047 static dbus_bool_t byte_set_value          (TestTypeNode   *node,
3048                                             DBusTypeReader *reader,
3049                                             DBusTypeReader *realign_root,
3050                                             int             seed);
3051 static dbus_bool_t double_write_value      (TestTypeNode   *node,
3052                                             DataBlock      *block,
3053                                             DBusTypeWriter *writer,
3054                                             int             seed);
3055 static dbus_bool_t double_read_value       (TestTypeNode   *node,
3056                                             DBusTypeReader *reader,
3057                                             int             seed);
3058 static dbus_bool_t double_set_value        (TestTypeNode   *node,
3059                                             DBusTypeReader *reader,
3060                                             DBusTypeReader *realign_root,
3061                                             int             seed);
3062 static dbus_bool_t object_path_write_value (TestTypeNode   *node,
3063                                             DataBlock      *block,
3064                                             DBusTypeWriter *writer,
3065                                             int             seed);
3066 static dbus_bool_t object_path_read_value  (TestTypeNode   *node,
3067                                             DBusTypeReader *reader,
3068                                             int             seed);
3069 static dbus_bool_t object_path_set_value   (TestTypeNode   *node,
3070                                             DBusTypeReader *reader,
3071                                             DBusTypeReader *realign_root,
3072                                             int             seed);
3073 static dbus_bool_t signature_write_value   (TestTypeNode   *node,
3074                                             DataBlock      *block,
3075                                             DBusTypeWriter *writer,
3076                                             int             seed);
3077 static dbus_bool_t signature_read_value    (TestTypeNode   *node,
3078                                             DBusTypeReader *reader,
3079                                             int             seed);
3080 static dbus_bool_t signature_set_value     (TestTypeNode   *node,
3081                                             DBusTypeReader *reader,
3082                                             DBusTypeReader *realign_root,
3083                                             int             seed);
3084 static dbus_bool_t struct_write_value      (TestTypeNode   *node,
3085                                             DataBlock      *block,
3086                                             DBusTypeWriter *writer,
3087                                             int             seed);
3088 static dbus_bool_t struct_read_value       (TestTypeNode   *node,
3089                                             DBusTypeReader *reader,
3090                                             int             seed);
3091 static dbus_bool_t struct_set_value        (TestTypeNode   *node,
3092                                             DBusTypeReader *reader,
3093                                             DBusTypeReader *realign_root,
3094                                             int             seed);
3095 static dbus_bool_t struct_build_signature  (TestTypeNode   *node,
3096                                             DBusString     *str);
3097 static dbus_bool_t array_write_value       (TestTypeNode   *node,
3098                                             DataBlock      *block,
3099                                             DBusTypeWriter *writer,
3100                                             int             seed);
3101 static dbus_bool_t array_read_value        (TestTypeNode   *node,
3102                                             DBusTypeReader *reader,
3103                                             int             seed);
3104 static dbus_bool_t array_set_value         (TestTypeNode   *node,
3105                                             DBusTypeReader *reader,
3106                                             DBusTypeReader *realign_root,
3107                                             int             seed);
3108 static dbus_bool_t array_build_signature   (TestTypeNode   *node,
3109                                             DBusString     *str);
3110 static dbus_bool_t variant_write_value     (TestTypeNode   *node,
3111                                             DataBlock      *block,
3112                                             DBusTypeWriter *writer,
3113                                             int             seed);
3114 static dbus_bool_t variant_read_value      (TestTypeNode   *node,
3115                                             DBusTypeReader *reader,
3116                                             int             seed);
3117 static dbus_bool_t variant_set_value       (TestTypeNode   *node,
3118                                             DBusTypeReader *reader,
3119                                             DBusTypeReader *realign_root,
3120                                             int             seed);
3121 static void        container_destroy       (TestTypeNode   *node);
3122
3123
3124 static const TestTypeNodeClass int32_class = {
3125   DBUS_TYPE_INT32,
3126   sizeof (TestTypeNode),
3127   0,
3128   NULL,
3129   NULL,
3130   int32_write_value,
3131   int32_read_value,
3132   int32_set_value,
3133   NULL,
3134   int32_write_multi,
3135   int32_read_multi
3136 };
3137
3138 static const TestTypeNodeClass uint32_class = {
3139   DBUS_TYPE_UINT32,
3140   sizeof (TestTypeNode),
3141   0,
3142   NULL,
3143   NULL,
3144   int32_write_value, /* recycle from int32 */
3145   int32_read_value,  /* recycle from int32 */
3146   int32_set_value,   /* recycle from int32 */
3147   NULL,
3148   int32_write_multi, /* recycle from int32 */
3149   int32_read_multi   /* recycle from int32 */
3150 };
3151
3152 static const TestTypeNodeClass int64_class = {
3153   DBUS_TYPE_INT64,
3154   sizeof (TestTypeNode),
3155   0,
3156   NULL,
3157   NULL,
3158   int64_write_value,
3159   int64_read_value,
3160   int64_set_value,
3161   NULL,
3162   NULL, /* FIXME */
3163   NULL  /* FIXME */
3164 };
3165
3166 static const TestTypeNodeClass uint64_class = {
3167   DBUS_TYPE_UINT64,
3168   sizeof (TestTypeNode),
3169   0,
3170   NULL,
3171   NULL,
3172   int64_write_value, /* recycle from int64 */
3173   int64_read_value,  /* recycle from int64 */
3174   int64_set_value,   /* recycle from int64 */
3175   NULL,
3176   NULL, /* FIXME */
3177   NULL  /* FIXME */
3178 };
3179
3180 static const TestTypeNodeClass string_0_class = {
3181   DBUS_TYPE_STRING,
3182   sizeof (TestTypeNode),
3183   0, /* string length */
3184   NULL,
3185   NULL,
3186   string_write_value,
3187   string_read_value,
3188   string_set_value,
3189   NULL,
3190   NULL,
3191   NULL
3192 };
3193
3194 static const TestTypeNodeClass string_1_class = {
3195   DBUS_TYPE_STRING,
3196   sizeof (TestTypeNode),
3197   1, /* string length */
3198   NULL,
3199   NULL,
3200   string_write_value,
3201   string_read_value,
3202   string_set_value,
3203   NULL,
3204   NULL,
3205   NULL
3206 };
3207
3208 /* with nul, a len 3 string should fill 4 bytes and thus is "special" */
3209 static const TestTypeNodeClass string_3_class = {
3210   DBUS_TYPE_STRING,
3211   sizeof (TestTypeNode),
3212   3, /* string length */
3213   NULL,
3214   NULL,
3215   string_write_value,
3216   string_read_value,
3217   string_set_value,
3218   NULL,
3219   NULL,
3220   NULL
3221 };
3222
3223 /* with nul, a len 8 string should fill 9 bytes and thus is "special" (far-fetched I suppose) */
3224 static const TestTypeNodeClass string_8_class = {
3225   DBUS_TYPE_STRING,
3226   sizeof (TestTypeNode),
3227   8, /* string length */
3228   NULL,
3229   NULL,
3230   string_write_value,
3231   string_read_value,
3232   string_set_value,
3233   NULL,
3234   NULL,
3235   NULL
3236 };
3237
3238 static const TestTypeNodeClass bool_class = {
3239   DBUS_TYPE_BOOLEAN,
3240   sizeof (TestTypeNode),
3241   0,
3242   NULL,
3243   NULL,
3244   bool_write_value,
3245   bool_read_value,
3246   bool_set_value,
3247   NULL,
3248   NULL, /* FIXME */
3249   NULL  /* FIXME */
3250 };
3251
3252 static const TestTypeNodeClass byte_class = {
3253   DBUS_TYPE_BYTE,
3254   sizeof (TestTypeNode),
3255   0,
3256   NULL,
3257   NULL,
3258   byte_write_value,
3259   byte_read_value,
3260   byte_set_value,
3261   NULL,
3262   NULL, /* FIXME */
3263   NULL  /* FIXME */
3264 };
3265
3266 static const TestTypeNodeClass double_class = {
3267   DBUS_TYPE_DOUBLE,
3268   sizeof (TestTypeNode),
3269   0,
3270   NULL,
3271   NULL,
3272   double_write_value,
3273   double_read_value,
3274   double_set_value,
3275   NULL,
3276   NULL, /* FIXME */
3277   NULL  /* FIXME */
3278 };
3279
3280 static const TestTypeNodeClass object_path_class = {
3281   DBUS_TYPE_OBJECT_PATH,
3282   sizeof (TestTypeNode),
3283   0,
3284   NULL,
3285   NULL,
3286   object_path_write_value,
3287   object_path_read_value,
3288   object_path_set_value,
3289   NULL,
3290   NULL,
3291   NULL
3292 };
3293
3294 static const TestTypeNodeClass signature_class = {
3295   DBUS_TYPE_SIGNATURE,
3296   sizeof (TestTypeNode),
3297   0,
3298   NULL,
3299   NULL,
3300   signature_write_value,
3301   signature_read_value,
3302   signature_set_value,
3303   NULL,
3304   NULL,
3305   NULL
3306 };
3307
3308 static const TestTypeNodeClass struct_1_class = {
3309   DBUS_TYPE_STRUCT,
3310   sizeof (TestTypeNodeContainer),
3311   1, /* number of times children appear as fields */
3312   NULL,
3313   container_destroy,
3314   struct_write_value,
3315   struct_read_value,
3316   struct_set_value,
3317   struct_build_signature,
3318   NULL,
3319   NULL
3320 };
3321
3322 static const TestTypeNodeClass struct_2_class = {
3323   DBUS_TYPE_STRUCT,
3324   sizeof (TestTypeNodeContainer),
3325   2, /* number of times children appear as fields */
3326   NULL,
3327   container_destroy,
3328   struct_write_value,
3329   struct_read_value,
3330   struct_set_value,
3331   struct_build_signature,
3332   NULL,
3333   NULL
3334 };
3335
3336 static dbus_bool_t arrays_write_fixed_in_blocks = FALSE;
3337
3338 static const TestTypeNodeClass array_0_class = {
3339   DBUS_TYPE_ARRAY,
3340   sizeof (TestTypeNodeContainer),
3341   0, /* number of array elements */
3342   NULL,
3343   container_destroy,
3344   array_write_value,
3345   array_read_value,
3346   array_set_value,
3347   array_build_signature,
3348   NULL,
3349   NULL
3350 };
3351
3352 static const TestTypeNodeClass array_1_class = {
3353   DBUS_TYPE_ARRAY,
3354   sizeof (TestTypeNodeContainer),
3355   1, /* number of array elements */
3356   NULL,
3357   container_destroy,
3358   array_write_value,
3359   array_read_value,
3360   array_set_value,
3361   array_build_signature,
3362   NULL,
3363   NULL
3364 };
3365
3366 static const TestTypeNodeClass array_2_class = {
3367   DBUS_TYPE_ARRAY,
3368   sizeof (TestTypeNodeContainer),
3369   2, /* number of array elements */
3370   NULL,
3371   container_destroy,
3372   array_write_value,
3373   array_read_value,
3374   array_set_value,
3375   array_build_signature,
3376   NULL,
3377   NULL
3378 };
3379
3380 static const TestTypeNodeClass array_9_class = {
3381   DBUS_TYPE_ARRAY,
3382   sizeof (TestTypeNodeContainer),
3383   9, /* number of array elements */
3384   NULL,
3385   container_destroy,
3386   array_write_value,
3387   array_read_value,
3388   array_set_value,
3389   array_build_signature,
3390   NULL,
3391   NULL
3392 };
3393
3394 static const TestTypeNodeClass variant_class = {
3395   DBUS_TYPE_VARIANT,
3396   sizeof (TestTypeNodeContainer),
3397   0,
3398   NULL,
3399   container_destroy,
3400   variant_write_value,
3401   variant_read_value,
3402   variant_set_value,
3403   NULL,
3404   NULL,
3405   NULL
3406 };
3407
3408 static const TestTypeNodeClass* const
3409 basic_nodes[] = {
3410   &int32_class,
3411   &uint32_class,
3412   &int64_class,
3413   &uint64_class,
3414   &bool_class,
3415   &byte_class,
3416   &double_class,
3417   &string_0_class,
3418   &string_1_class,
3419   &string_3_class,
3420   &string_8_class,
3421   &object_path_class,
3422   &signature_class
3423 };
3424 #define N_BASICS (_DBUS_N_ELEMENTS (basic_nodes))
3425
3426 static const TestTypeNodeClass* const
3427 container_nodes[] = {
3428   &struct_1_class,
3429   &array_1_class,
3430   &struct_2_class,
3431   &array_0_class,
3432   &array_2_class,
3433   &variant_class
3434   /* array_9_class is omitted on purpose, it's too slow;
3435    * we only use it in one hardcoded test below
3436    */
3437 };
3438 #define N_CONTAINERS (_DBUS_N_ELEMENTS (container_nodes))
3439
3440 static TestTypeNode*
3441 node_new (const TestTypeNodeClass *klass)
3442 {
3443   TestTypeNode *node;
3444
3445   node = dbus_malloc0 (klass->instance_size);
3446   if (node == NULL)
3447     return NULL;
3448
3449   node->klass = klass;
3450
3451   if (klass->construct)
3452     {
3453       if (!(* klass->construct) (node))
3454         {
3455           dbus_free (node);
3456           return FALSE;
3457         }
3458     }
3459
3460   return node;
3461 }
3462
3463 static void
3464 node_destroy (TestTypeNode *node)
3465 {
3466   if (node->klass->destroy)
3467     (* node->klass->destroy) (node);
3468   dbus_free (node);
3469 }
3470
3471 static dbus_bool_t
3472 node_write_value (TestTypeNode   *node,
3473                   DataBlock      *block,
3474                   DBusTypeWriter *writer,
3475                   int             seed)
3476 {
3477   dbus_bool_t retval;
3478
3479   retval = (* node->klass->write_value) (node, block, writer, seed);
3480
3481 #if 0
3482   /* Handy to see where things break, but too expensive to do all the time */
3483   data_block_verify (block);
3484 #endif
3485
3486   return retval;
3487 }
3488
3489 static dbus_bool_t
3490 node_read_value (TestTypeNode   *node,
3491                  DBusTypeReader *reader,
3492                  int             seed)
3493 {
3494   DBusTypeMark mark;
3495   DBusTypeReader restored;
3496
3497   _dbus_type_reader_save_mark (reader, &mark);
3498
3499   if (!(* node->klass->read_value) (node, reader, seed))
3500     return FALSE;
3501
3502   _dbus_type_reader_init_from_mark (&restored,
3503                                     reader->byte_order,
3504                                     reader->type_str,
3505                                     reader->value_str,
3506                                     &mark);
3507
3508   if (!(* node->klass->read_value) (node, &restored, seed))
3509     return FALSE;
3510
3511   return TRUE;
3512 }
3513
3514 /* Warning: if this one fails due to OOM, it has side effects (can
3515  * modify only some of the sub-values). OK in a test suite, but we
3516  * never do this in real code.
3517  */
3518 static dbus_bool_t
3519 node_set_value (TestTypeNode   *node,
3520                 DBusTypeReader *reader,
3521                 DBusTypeReader *realign_root,
3522                 int             seed)
3523 {
3524   if (!(* node->klass->set_value) (node, reader, realign_root, seed))
3525     return FALSE;
3526
3527   return TRUE;
3528 }
3529
3530 static dbus_bool_t
3531 node_build_signature (TestTypeNode *node,
3532                       DBusString   *str)
3533 {
3534   if (node->klass->build_signature)
3535     return (* node->klass->build_signature) (node, str);
3536   else
3537     return _dbus_string_append_byte (str, node->klass->typecode);
3538 }
3539
3540 static dbus_bool_t
3541 node_append_child (TestTypeNode *node,
3542                    TestTypeNode *child)
3543 {
3544   TestTypeNodeContainer *container = (TestTypeNodeContainer*) node;
3545
3546   _dbus_assert (node->klass->instance_size >= (int) sizeof (TestTypeNodeContainer));
3547
3548   if (!_dbus_list_append (&container->children, child))
3549     _dbus_assert_not_reached ("no memory"); /* we never check the return value on node_append_child anyhow - it's run from outside the malloc-failure test code */
3550
3551   return TRUE;
3552 }
3553
3554 static dbus_bool_t
3555 node_write_multi (TestTypeNode   *node,
3556                   DataBlock      *block,
3557                   DBusTypeWriter *writer,
3558                   int             seed,
3559                   int             n_copies)
3560 {
3561   dbus_bool_t retval;
3562
3563   _dbus_assert (node->klass->write_multi != NULL);
3564   retval = (* node->klass->write_multi) (node, block, writer, seed, n_copies);
3565
3566 #if 0
3567   /* Handy to see where things break, but too expensive to do all the time */
3568   data_block_verify (block);
3569 #endif
3570
3571   return retval;
3572 }
3573
3574 static dbus_bool_t
3575 node_read_multi (TestTypeNode   *node,
3576                  DBusTypeReader *reader,
3577                  int             seed,
3578                  int             n_copies)
3579 {
3580   _dbus_assert (node->klass->read_multi != NULL);
3581
3582   if (!(* node->klass->read_multi) (node, reader, seed, n_copies))
3583     return FALSE;
3584
3585   return TRUE;
3586 }
3587
3588 static int n_iterations_completed_total = 0;
3589 static int n_iterations_completed_this_test = 0;
3590 static int n_iterations_expected_this_test = 0;
3591
3592 typedef struct
3593 {
3594   const DBusString   *signature;
3595   DataBlock          *block;
3596   int                 type_offset;
3597   TestTypeNode      **nodes;
3598   int                 n_nodes;
3599 } NodeIterationData;
3600
3601 static dbus_bool_t
3602 run_test_copy (NodeIterationData *nid)
3603 {
3604   DataBlock *src;
3605   DataBlock dest;
3606   dbus_bool_t retval;
3607   DBusTypeReader reader;
3608   DBusTypeWriter writer;
3609
3610   _dbus_verbose ("%s\n", _DBUS_FUNCTION_NAME);
3611
3612   src = nid->block;
3613
3614   retval = FALSE;
3615
3616   if (!data_block_init (&dest, src->byte_order, src->initial_offset))
3617     return FALSE;
3618
3619   data_block_init_reader_writer (src, &reader, NULL);
3620   data_block_init_reader_writer (&dest, NULL, &writer);
3621
3622   /* DBusTypeWriter assumes it's writing into an existing signature,
3623    * so doesn't add nul on its own. We have to do that.
3624    */
3625   if (!_dbus_string_insert_byte (&dest.signature,
3626                                  dest.initial_offset, '\0'))
3627     goto out;
3628
3629   if (!_dbus_type_writer_write_reader (&writer, &reader))
3630     goto out;
3631
3632   /* Data blocks should now be identical */
3633   if (!_dbus_string_equal (&src->signature, &dest.signature))
3634     {
3635       _dbus_verbose ("SOURCE\n");
3636       _dbus_verbose_bytes_of_string (&src->signature, 0,
3637                                      _dbus_string_get_length (&src->signature));
3638       _dbus_verbose ("DEST\n");
3639       _dbus_verbose_bytes_of_string (&dest.signature, 0,
3640                                      _dbus_string_get_length (&dest.signature));
3641       _dbus_assert_not_reached ("signatures did not match");
3642     }
3643
3644   if (!_dbus_string_equal (&src->body, &dest.body))
3645     {
3646       _dbus_verbose ("SOURCE\n");
3647       _dbus_verbose_bytes_of_string (&src->body, 0,
3648                                      _dbus_string_get_length (&src->body));
3649       _dbus_verbose ("DEST\n");
3650       _dbus_verbose_bytes_of_string (&dest.body, 0,
3651                                      _dbus_string_get_length (&dest.body));
3652       _dbus_assert_not_reached ("bodies did not match");
3653     }
3654
3655   retval = TRUE;
3656
3657  out:
3658
3659   data_block_free (&dest);
3660
3661   return retval;
3662 }
3663
3664 static dbus_bool_t
3665 run_test_values_only_write (NodeIterationData *nid)
3666 {
3667   DBusTypeReader reader;
3668   DBusTypeWriter writer;
3669   int i;
3670   dbus_bool_t retval;
3671   int sig_len;
3672
3673   _dbus_verbose ("%s\n", _DBUS_FUNCTION_NAME);
3674
3675   retval = FALSE;
3676
3677   data_block_reset (nid->block);
3678
3679   sig_len = _dbus_string_get_length (nid->signature);
3680
3681   _dbus_type_writer_init_values_only (&writer,
3682                                       nid->block->byte_order,
3683                                       nid->signature, 0,
3684                                       &nid->block->body,
3685                                       _dbus_string_get_length (&nid->block->body) - N_FENCE_BYTES);
3686   _dbus_type_reader_init (&reader,
3687                           nid->block->byte_order,
3688                           nid->signature, 0,
3689                           &nid->block->body,
3690                           nid->block->initial_offset);
3691
3692   i = 0;
3693   while (i < nid->n_nodes)
3694     {
3695       if (!node_write_value (nid->nodes[i], nid->block, &writer, i))
3696         goto out;
3697
3698       ++i;
3699     }
3700
3701   /* if we wrote any typecodes then this would fail */
3702   _dbus_assert (sig_len == _dbus_string_get_length (nid->signature));
3703
3704   /* But be sure we wrote out the values correctly */
3705   i = 0;
3706   while (i < nid->n_nodes)
3707     {
3708       if (!node_read_value (nid->nodes[i], &reader, i))
3709         goto out;
3710
3711       if (i + 1 == nid->n_nodes)
3712         NEXT_EXPECTING_FALSE (&reader);
3713       else
3714         NEXT_EXPECTING_TRUE (&reader);
3715
3716       ++i;
3717     }
3718
3719   retval = TRUE;
3720
3721  out:
3722   data_block_reset (nid->block);
3723   return retval;
3724 }
3725
3726 /* offset the seed for setting, so we set different numbers than
3727  * we originally wrote. Don't offset by a huge number since in
3728  * some cases it's value = possibilities[seed % n_possibilities]
3729  * and we don't want to wrap around. bool_from_seed
3730  * is just seed % 2 even.
3731  */
3732 #define SET_SEED 1
3733 static dbus_bool_t
3734 run_test_set_values (NodeIterationData *nid)
3735 {
3736   DBusTypeReader reader;
3737   DBusTypeReader realign_root;
3738   dbus_bool_t retval;
3739   int i;
3740
3741   _dbus_verbose ("%s\n", _DBUS_FUNCTION_NAME);
3742
3743   retval = FALSE;
3744
3745   data_block_init_reader_writer (nid->block,
3746                                  &reader, NULL);
3747
3748   realign_root = reader;
3749
3750   i = 0;
3751   while (i < nid->n_nodes)
3752     {
3753       if (!node_set_value (nid->nodes[i],
3754                            &reader, &realign_root,
3755                            i + SET_SEED))
3756         goto out;
3757
3758       if (i + 1 == nid->n_nodes)
3759         NEXT_EXPECTING_FALSE (&reader);
3760       else
3761         NEXT_EXPECTING_TRUE (&reader);
3762
3763       ++i;
3764     }
3765
3766   /* Check that the new values were set */
3767
3768   reader = realign_root;
3769
3770   i = 0;
3771   while (i < nid->n_nodes)
3772     {
3773       if (!node_read_value (nid->nodes[i], &reader,
3774                             i + SET_SEED))
3775         goto out;
3776
3777       if (i + 1 == nid->n_nodes)
3778         NEXT_EXPECTING_FALSE (&reader);
3779       else
3780         NEXT_EXPECTING_TRUE (&reader);
3781
3782       ++i;
3783     }
3784
3785   retval = TRUE;
3786
3787  out:
3788   return retval;
3789 }
3790
3791 static dbus_bool_t
3792 run_test_delete_values (NodeIterationData *nid)
3793 {
3794   DBusTypeReader reader;
3795   dbus_bool_t retval;
3796   int t;
3797
3798   _dbus_verbose ("%s\n", _DBUS_FUNCTION_NAME);
3799
3800   retval = FALSE;
3801
3802   data_block_init_reader_writer (nid->block,
3803                                  &reader, NULL);
3804
3805   while ((t = _dbus_type_reader_get_current_type (&reader)) != DBUS_TYPE_INVALID)
3806     {
3807       /* Right now, deleting only works on array elements.  We delete
3808        * all array elements, and then verify that there aren't any
3809        * left.
3810        */
3811       if (t == DBUS_TYPE_ARRAY)
3812         {
3813           DBusTypeReader array;
3814           int n_elements;
3815           int elem_type;
3816
3817           _dbus_type_reader_recurse (&reader, &array);
3818           n_elements = 0;
3819           while (_dbus_type_reader_get_current_type (&array) != DBUS_TYPE_INVALID)
3820             {
3821               n_elements += 1;
3822               _dbus_type_reader_next (&array);
3823             }
3824
3825           /* reset to start of array */
3826           _dbus_type_reader_recurse (&reader, &array);
3827           _dbus_verbose ("recursing into deletion loop reader.value_pos = %d array.value_pos = %d array.u.start_pos = %d\n",
3828                          reader.value_pos, array.value_pos, array.u.array.start_pos);
3829           while ((elem_type = _dbus_type_reader_get_current_type (&array)) != DBUS_TYPE_INVALID)
3830             {
3831               /* We don't want to always delete from the same part of the array. */
3832               static int cycle = 0;
3833               int elem;
3834
3835               _dbus_assert (n_elements > 0);
3836
3837               elem = cycle;
3838               if (elem == 3 || elem >= n_elements) /* end of array */
3839                 elem = n_elements - 1;
3840
3841               _dbus_verbose ("deleting array element %d of %d type %s cycle %d reader pos %d elem pos %d\n",
3842                              elem, n_elements, _dbus_type_to_string (elem_type),
3843                              cycle, reader.value_pos, array.value_pos);
3844               while (elem > 0)
3845                 {
3846                   if (!_dbus_type_reader_next (&array))
3847                     _dbus_assert_not_reached ("should have had another element\n");
3848                   --elem;
3849                 }
3850
3851               if (!_dbus_type_reader_delete (&array, &reader))
3852                 goto out;
3853
3854               n_elements -= 1;
3855
3856               /* reset */
3857               _dbus_type_reader_recurse (&reader, &array);
3858
3859               if (cycle > 2)
3860                 cycle = 0;
3861               else
3862                 cycle += 1;
3863             }
3864         }
3865       _dbus_type_reader_next (&reader);
3866     }
3867
3868   /* Check that there are no array elements left */
3869   data_block_init_reader_writer (nid->block,
3870                                  &reader, NULL);
3871
3872   while ((t = _dbus_type_reader_get_current_type (&reader)) != DBUS_TYPE_INVALID)
3873     {
3874       _dbus_type_reader_next (&reader);
3875     }
3876
3877   retval = TRUE;
3878
3879  out:
3880   return retval;
3881 }
3882
3883 static dbus_bool_t
3884 run_test_nodes_iteration (void *data)
3885 {
3886   NodeIterationData *nid = data;
3887   DBusTypeReader reader;
3888   DBusTypeWriter writer;
3889   int i;
3890   dbus_bool_t retval;
3891
3892   /* Stuff to do:
3893    * 1. write the value
3894    * 2. strcmp-compare with the signature we built
3895    * 3. read the value
3896    * 4. type-iterate the signature and the value and see if they are the same type-wise
3897    */
3898   retval = FALSE;
3899
3900   data_block_init_reader_writer (nid->block,
3901                                  &reader, &writer);
3902
3903   /* DBusTypeWriter assumes it's writing into an existing signature,
3904    * so doesn't add nul on its own. We have to do that.
3905    */
3906   if (!_dbus_string_insert_byte (&nid->block->signature,
3907                                  nid->type_offset, '\0'))
3908     goto out;
3909
3910   i = 0;
3911   while (i < nid->n_nodes)
3912     {
3913       if (!node_write_value (nid->nodes[i], nid->block, &writer, i))
3914         goto out;
3915
3916       ++i;
3917     }
3918
3919   if (!_dbus_string_equal_substring (nid->signature, 0, _dbus_string_get_length (nid->signature),
3920                                      &nid->block->signature, nid->type_offset))
3921     {
3922       _dbus_warn ("Expected signature '%s' and got '%s' with initial offset %d\n",
3923                   _dbus_string_get_const_data (nid->signature),
3924                   _dbus_string_get_const_data_len (&nid->block->signature, nid->type_offset, 0),
3925                   nid->type_offset);
3926       _dbus_assert_not_reached ("wrong signature");
3927     }
3928
3929   i = 0;
3930   while (i < nid->n_nodes)
3931     {
3932       if (!node_read_value (nid->nodes[i], &reader, i))
3933         goto out;
3934
3935       if (i + 1 == nid->n_nodes)
3936         NEXT_EXPECTING_FALSE (&reader);
3937       else
3938         NEXT_EXPECTING_TRUE (&reader);
3939
3940       ++i;
3941     }
3942
3943   if (n_iterations_expected_this_test <= MAX_ITERATIONS_FOR_EXPENSIVE_TESTS)
3944     {
3945       /* this set values test uses code from copy and
3946        * values_only_write so would ideally be last so you get a
3947        * simpler test case for problems with copying or values_only
3948        * writing; but it also needs an already-written DataBlock so it
3949        * has to go first. Comment it out if it breaks, and see if the
3950        * later tests also break - debug them first if so.
3951        */
3952       if (!run_test_set_values (nid))
3953         goto out;
3954
3955       if (!run_test_delete_values (nid))
3956         goto out;
3957
3958       if (!run_test_copy (nid))
3959         goto out;
3960
3961       if (!run_test_values_only_write (nid))
3962         goto out;
3963     }
3964
3965   /* FIXME type-iterate both signature and value and compare the resulting
3966    * tree to the node tree perhaps
3967    */
3968
3969   retval = TRUE;
3970
3971  out:
3972
3973   data_block_reset (nid->block);
3974
3975   return retval;
3976 }
3977
3978 static void
3979 run_test_nodes_in_one_configuration (TestTypeNode    **nodes,
3980                                      int               n_nodes,
3981                                      const DBusString *signature,
3982                                      int               byte_order,
3983                                      int               initial_offset)
3984 {
3985   DataBlock block;
3986   NodeIterationData nid;
3987
3988   if (!data_block_init (&block, byte_order, initial_offset))
3989     _dbus_assert_not_reached ("no memory");
3990
3991   nid.signature = signature;
3992   nid.block = &block;
3993   nid.type_offset = initial_offset;
3994   nid.nodes = nodes;
3995   nid.n_nodes = n_nodes;
3996
3997   if (TEST_OOM_HANDLING &&
3998       n_iterations_expected_this_test <= MAX_ITERATIONS_FOR_EXPENSIVE_TESTS)
3999     {
4000       _dbus_test_oom_handling ("running test node",
4001                                run_test_nodes_iteration,
4002                                &nid);
4003     }
4004   else
4005     {
4006       if (!run_test_nodes_iteration (&nid))
4007         _dbus_assert_not_reached ("no memory");
4008     }
4009
4010   data_block_free (&block);
4011 }
4012
4013 static void
4014 run_test_nodes (TestTypeNode **nodes,
4015                 int            n_nodes)
4016 {
4017   int i;
4018   DBusString signature;
4019
4020   if (!_dbus_string_init (&signature))
4021     _dbus_assert_not_reached ("no memory");
4022
4023   i = 0;
4024   while (i < n_nodes)
4025     {
4026       if (! node_build_signature (nodes[i], &signature))
4027         _dbus_assert_not_reached ("no memory");
4028
4029       ++i;
4030     }
4031
4032   _dbus_verbose (">>> test nodes with signature '%s'\n",
4033                  _dbus_string_get_const_data (&signature));
4034
4035   i = 0;
4036   while (i <= MAX_INITIAL_OFFSET)
4037     {
4038       run_test_nodes_in_one_configuration (nodes, n_nodes, &signature,
4039                                            DBUS_LITTLE_ENDIAN, i);
4040       run_test_nodes_in_one_configuration (nodes, n_nodes, &signature,
4041                                            DBUS_BIG_ENDIAN, i);
4042
4043       ++i;
4044     }
4045
4046   n_iterations_completed_this_test += 1;
4047   n_iterations_completed_total += 1;
4048
4049   if (n_iterations_completed_this_test == n_iterations_expected_this_test)
4050     {
4051       fprintf (stderr, " 100%% %d this test (%d cumulative)\n",
4052                n_iterations_completed_this_test,
4053                n_iterations_completed_total);
4054     }
4055   /* this happens to turn out well with mod == 1 */
4056   else if ((n_iterations_completed_this_test %
4057             (int)(n_iterations_expected_this_test / 10.0)) == 1)
4058     {
4059       fprintf (stderr, " %d%% ", (int) (n_iterations_completed_this_test / (double) n_iterations_expected_this_test * 100));
4060     }
4061
4062   _dbus_string_free (&signature);
4063 }
4064
4065 #define N_VALUES (N_BASICS * N_CONTAINERS + N_BASICS)
4066
4067 static TestTypeNode*
4068 value_generator (int *ip)
4069 {
4070   int i = *ip;
4071   const TestTypeNodeClass *child_klass;
4072   const TestTypeNodeClass *container_klass;
4073   TestTypeNode *child;
4074   TestTypeNode *node;
4075
4076   _dbus_assert (i <= N_VALUES);
4077
4078   if (i == N_VALUES)
4079     {
4080       return NULL;
4081     }
4082   else if (i < N_BASICS)
4083     {
4084       node = node_new (basic_nodes[i]);
4085     }
4086   else
4087     {
4088       /* imagine an array:
4089        * container 0 of basic 0
4090        * container 0 of basic 1
4091        * container 0 of basic 2
4092        * container 1 of basic 0
4093        * container 1 of basic 1
4094        * container 1 of basic 2
4095        */
4096       i -= N_BASICS;
4097
4098       container_klass = container_nodes[i / N_BASICS];
4099       child_klass = basic_nodes[i % N_BASICS];
4100
4101       node = node_new (container_klass);
4102       child = node_new (child_klass);
4103
4104       node_append_child (node, child);
4105     }
4106
4107   *ip += 1; /* increment the generator */
4108
4109   return node;
4110 }
4111
4112 static void
4113 make_and_run_values_inside_container (const TestTypeNodeClass *container_klass,
4114                                       int                      n_nested)
4115 {
4116   TestTypeNode *root;
4117   TestTypeNode *container;
4118   TestTypeNode *child;
4119   int i;
4120
4121   root = node_new (container_klass);
4122   container = root;
4123   for (i = 1; i < n_nested; i++)
4124     {
4125       child = node_new (container_klass);
4126       node_append_child (container, child);
4127       container = child;
4128     }
4129
4130   /* container should now be the most-nested container */
4131
4132   i = 0;
4133   while ((child = value_generator (&i)))
4134     {
4135       node_append_child (container, child);
4136
4137       run_test_nodes (&root, 1);
4138
4139       _dbus_list_clear (&((TestTypeNodeContainer*)container)->children);
4140       node_destroy (child);
4141     }
4142
4143   node_destroy (root);
4144 }
4145
4146 static void
4147 start_next_test (const char *format,
4148                  int         expected)
4149 {
4150   n_iterations_completed_this_test = 0;
4151   n_iterations_expected_this_test = expected;
4152
4153   fprintf (stderr, ">>> >>> ");
4154   fprintf (stderr, format,
4155            n_iterations_expected_this_test);
4156 }
4157
4158 static void
4159 make_and_run_test_nodes (void)
4160 {
4161   int i, j, k, m;
4162
4163   /* We try to do this in order of "complicatedness" so that test
4164    * failures tend to show up in the simplest test case that
4165    * demonstrates the failure.  There are also some tests that run
4166    * more than once for this reason, first while going through simple
4167    * cases, second while going through a broader range of complex
4168    * cases.
4169    */
4170   /* Each basic node. The basic nodes should include:
4171    *
4172    * - each fixed-size type (in such a way that it has different values each time,
4173    *                         so we can tell if we mix two of them up)
4174    * - strings of various lengths
4175    * - object path
4176    * - signature
4177    */
4178   /* Each container node. The container nodes should include:
4179    *
4180    *  struct with 1 and 2 copies of the contained item
4181    *  array with 0, 1, 2 copies of the contained item
4182    *  variant
4183    */
4184   /*  Let a "value" be a basic node, or a container containing a single basic node.
4185    *  Let n_values be the number of such values i.e. (n_container * n_basic + n_basic)
4186    *  When iterating through all values to make combinations, do the basic types
4187    *  first and the containers second.
4188    */
4189   /* Each item is shown with its number of iterations to complete so
4190    * we can keep a handle on this unit test
4191    */
4192
4193   /* FIXME test just an empty body, no types at all */
4194
4195   start_next_test ("Each value by itself %d iterations\n", N_VALUES);
4196   {
4197     TestTypeNode *node;
4198     i = 0;
4199     while ((node = value_generator (&i)))
4200       {
4201         run_test_nodes (&node, 1);
4202
4203         node_destroy (node);
4204       }
4205   }
4206
4207   start_next_test ("Each value by itself with arrays as blocks %d iterations\n", N_VALUES);
4208   arrays_write_fixed_in_blocks = TRUE;
4209   {
4210     TestTypeNode *node;
4211     i = 0;
4212     while ((node = value_generator (&i)))
4213       {
4214         run_test_nodes (&node, 1);
4215
4216         node_destroy (node);
4217       }
4218   }
4219   arrays_write_fixed_in_blocks = FALSE;
4220
4221   start_next_test ("All values in one big toplevel %d iteration\n", 1);
4222   {
4223     TestTypeNode *nodes[N_VALUES];
4224
4225     i = 0;
4226     while ((nodes[i] = value_generator (&i)))
4227       ;
4228
4229     run_test_nodes (nodes, N_VALUES);
4230
4231     for (i = 0; i < N_VALUES; i++)
4232       node_destroy (nodes[i]);
4233   }
4234
4235   start_next_test ("Each value,value pair combination as toplevel, in both orders %d iterations\n",
4236                    N_VALUES * N_VALUES);
4237   {
4238     TestTypeNode *nodes[2];
4239
4240     i = 0;
4241     while ((nodes[0] = value_generator (&i)))
4242       {
4243         j = 0;
4244         while ((nodes[1] = value_generator (&j)))
4245           {
4246             run_test_nodes (nodes, 2);
4247
4248             node_destroy (nodes[1]);
4249           }
4250
4251         node_destroy (nodes[0]);
4252       }
4253   }
4254
4255   start_next_test ("Each container containing each value %d iterations\n",
4256                    N_CONTAINERS * N_VALUES);
4257   for (i = 0; i < N_CONTAINERS; i++)
4258     {
4259       const TestTypeNodeClass *container_klass = container_nodes[i];
4260
4261       make_and_run_values_inside_container (container_klass, 1);
4262     }
4263
4264   start_next_test ("Each container containing each value with arrays as blocks %d iterations\n",
4265                    N_CONTAINERS * N_VALUES);
4266   arrays_write_fixed_in_blocks = TRUE;
4267   for (i = 0; i < N_CONTAINERS; i++)
4268     {
4269       const TestTypeNodeClass *container_klass = container_nodes[i];
4270
4271       make_and_run_values_inside_container (container_klass, 1);
4272     }
4273   arrays_write_fixed_in_blocks = FALSE;
4274
4275   start_next_test ("Each container of same container of each value %d iterations\n",
4276                    N_CONTAINERS * N_VALUES);
4277   for (i = 0; i < N_CONTAINERS; i++)
4278     {
4279       const TestTypeNodeClass *container_klass = container_nodes[i];
4280
4281       make_and_run_values_inside_container (container_klass, 2);
4282     }
4283
4284   start_next_test ("Each container of same container of same container of each value %d iterations\n",
4285                    N_CONTAINERS * N_VALUES);
4286   for (i = 0; i < N_CONTAINERS; i++)
4287     {
4288       const TestTypeNodeClass *container_klass = container_nodes[i];
4289
4290       make_and_run_values_inside_container (container_klass, 3);
4291     }
4292
4293   start_next_test ("Each value,value pair inside a struct %d iterations\n",
4294                    N_VALUES * N_VALUES);
4295   {
4296     TestTypeNode *val1, *val2;
4297     TestTypeNode *node;
4298
4299     node = node_new (&struct_1_class);
4300
4301     i = 0;
4302     while ((val1 = value_generator (&i)))
4303       {
4304         j = 0;
4305         while ((val2 = value_generator (&j)))
4306           {
4307             TestTypeNodeContainer *container = (TestTypeNodeContainer*) node;
4308
4309             node_append_child (node, val1);
4310             node_append_child (node, val2);
4311
4312             run_test_nodes (&node, 1);
4313
4314             _dbus_list_clear (&container->children);
4315             node_destroy (val2);
4316           }
4317         node_destroy (val1);
4318       }
4319     node_destroy (node);
4320   }
4321
4322   start_next_test ("All values in one big struct %d iteration\n",
4323                    1);
4324   {
4325     TestTypeNode *node;
4326     TestTypeNode *child;
4327
4328     node = node_new (&struct_1_class);
4329
4330     i = 0;
4331     while ((child = value_generator (&i)))
4332       node_append_child (node, child);
4333
4334     run_test_nodes (&node, 1);
4335
4336     node_destroy (node);
4337   }
4338
4339   start_next_test ("Each value in a large array %d iterations\n",
4340                    N_VALUES);
4341   {
4342     TestTypeNode *val;
4343     TestTypeNode *node;
4344
4345     node = node_new (&array_9_class);
4346
4347     i = 0;
4348     while ((val = value_generator (&i)))
4349       {
4350         TestTypeNodeContainer *container = (TestTypeNodeContainer*) node;
4351
4352         node_append_child (node, val);
4353
4354         run_test_nodes (&node, 1);
4355
4356         _dbus_list_clear (&container->children);
4357         node_destroy (val);
4358       }
4359
4360     node_destroy (node);
4361   }
4362
4363   start_next_test ("Each container of each container of each value %d iterations\n",
4364                    N_CONTAINERS * N_CONTAINERS * N_VALUES);
4365   for (i = 0; i < N_CONTAINERS; i++)
4366     {
4367       const TestTypeNodeClass *outer_container_klass = container_nodes[i];
4368       TestTypeNode *outer_container = node_new (outer_container_klass);
4369
4370       for (j = 0; j < N_CONTAINERS; j++)
4371         {
4372           TestTypeNode *child;
4373           const TestTypeNodeClass *inner_container_klass = container_nodes[j];
4374           TestTypeNode *inner_container = node_new (inner_container_klass);
4375
4376           node_append_child (outer_container, inner_container);
4377
4378           m = 0;
4379           while ((child = value_generator (&m)))
4380             {
4381               node_append_child (inner_container, child);
4382
4383               run_test_nodes (&outer_container, 1);
4384
4385               _dbus_list_clear (&((TestTypeNodeContainer*)inner_container)->children);
4386               node_destroy (child);
4387             }
4388           _dbus_list_clear (&((TestTypeNodeContainer*)outer_container)->children);
4389           node_destroy (inner_container);
4390         }
4391       node_destroy (outer_container);
4392     }
4393
4394   start_next_test ("Each container of each container of each container of each value %d iterations\n",
4395                    N_CONTAINERS * N_CONTAINERS * N_CONTAINERS * N_VALUES);
4396   for (i = 0; i < N_CONTAINERS; i++)
4397     {
4398       const TestTypeNodeClass *outer_container_klass = container_nodes[i];
4399       TestTypeNode *outer_container = node_new (outer_container_klass);
4400
4401       for (j = 0; j < N_CONTAINERS; j++)
4402         {
4403           const TestTypeNodeClass *inner_container_klass = container_nodes[j];
4404           TestTypeNode *inner_container = node_new (inner_container_klass);
4405
4406           node_append_child (outer_container, inner_container);
4407
4408           for (k = 0; k < N_CONTAINERS; k++)
4409             {
4410               TestTypeNode *child;
4411               const TestTypeNodeClass *center_container_klass = container_nodes[k];
4412               TestTypeNode *center_container = node_new (center_container_klass);
4413
4414               node_append_child (inner_container, center_container);
4415
4416               m = 0;
4417               while ((child = value_generator (&m)))
4418                 {
4419                   node_append_child (center_container, child);
4420
4421                   run_test_nodes (&outer_container, 1);
4422
4423                   _dbus_list_clear (&((TestTypeNodeContainer*)center_container)->children);
4424                   node_destroy (child);
4425                 }
4426               _dbus_list_clear (&((TestTypeNodeContainer*)inner_container)->children);
4427               node_destroy (center_container);
4428             }
4429           _dbus_list_clear (&((TestTypeNodeContainer*)outer_container)->children);
4430           node_destroy (inner_container);
4431         }
4432       node_destroy (outer_container);
4433     }
4434
4435 #if 0
4436   /* This one takes a really long time, so comment it out for now */
4437   start_next_test ("Each value,value,value triplet combination as toplevel, in all orders %d iterations\n",
4438                    N_VALUES * N_VALUES * N_VALUES);
4439   {
4440     TestTypeNode *nodes[3];
4441
4442     i = 0;
4443     while ((nodes[0] = value_generator (&i)))
4444       {
4445         j = 0;
4446         while ((nodes[1] = value_generator (&j)))
4447           {
4448             k = 0;
4449             while ((nodes[2] = value_generator (&k)))
4450               {
4451                 run_test_nodes (nodes, 3);
4452
4453                 node_destroy (nodes[2]);
4454               }
4455             node_destroy (nodes[1]);
4456           }
4457         node_destroy (nodes[0]);
4458       }
4459   }
4460 #endif /* #if 0 expensive test */
4461
4462   fprintf (stderr, "%d total iterations of recursive marshaling tests\n",
4463            n_iterations_completed_total);
4464   fprintf (stderr, "each iteration ran at initial offsets 0 through %d in both big and little endian\n",
4465            MAX_INITIAL_OFFSET);
4466   fprintf (stderr, "out of memory handling %s tested\n",
4467            TEST_OOM_HANDLING ? "was" : "was not");
4468 }
4469
4470 dbus_bool_t
4471 _dbus_marshal_recursive_test (void)
4472 {
4473   make_and_run_test_nodes ();
4474
4475   return TRUE;
4476 }
4477
4478 /*
4479  *
4480  *
4481  *         Implementations of each type node class
4482  *
4483  *
4484  *
4485  */
4486 #define MAX_MULTI_COUNT 5
4487
4488
4489 #define SAMPLE_INT32           12345678
4490 #define SAMPLE_INT32_ALTERNATE 53781429
4491 static dbus_int32_t
4492 int32_from_seed (int seed)
4493 {
4494   /* Generate an integer value that's predictable from seed.  We could
4495    * just use seed itself, but that would only ever touch one byte of
4496    * the int so would miss some kinds of bug.
4497    */
4498   dbus_int32_t v;
4499
4500   v = 42; /* just to quiet compiler afaik */
4501   switch (seed % 5)
4502     {
4503     case 0:
4504       v = SAMPLE_INT32;
4505       break;
4506     case 1:
4507       v = SAMPLE_INT32_ALTERNATE;
4508       break;
4509     case 2:
4510       v = -1;
4511       break;
4512     case 3:
4513       v = _DBUS_INT_MAX;
4514       break;
4515     case 4:
4516       v = 1;
4517       break;
4518     }
4519
4520   if (seed > 1)
4521     v *= seed; /* wraps around eventually, which is fine */
4522
4523   return v;
4524 }
4525
4526 static dbus_bool_t
4527 int32_write_value (TestTypeNode   *node,
4528                    DataBlock      *block,
4529                    DBusTypeWriter *writer,
4530                    int             seed)
4531 {
4532   /* also used for uint32 */
4533   dbus_int32_t v;
4534
4535   v = int32_from_seed (seed);
4536
4537   return _dbus_type_writer_write_basic (writer,
4538                                         node->klass->typecode,
4539                                         &v);
4540 }
4541
4542 static dbus_bool_t
4543 int32_read_value (TestTypeNode   *node,
4544                   DBusTypeReader *reader,
4545                   int             seed)
4546 {
4547   /* also used for uint32 */
4548   dbus_int32_t v;
4549
4550   check_expected_type (reader, node->klass->typecode);
4551
4552   _dbus_type_reader_read_basic (reader,
4553                                 (dbus_int32_t*) &v);
4554
4555   _dbus_assert (v == int32_from_seed (seed));
4556
4557   return TRUE;
4558 }
4559
4560 static dbus_bool_t
4561 int32_set_value (TestTypeNode   *node,
4562                  DBusTypeReader *reader,
4563                  DBusTypeReader *realign_root,
4564                  int             seed)
4565 {
4566   /* also used for uint32 */
4567   dbus_int32_t v;
4568
4569   v = int32_from_seed (seed);
4570
4571   return _dbus_type_reader_set_basic (reader,
4572                                       &v,
4573                                       realign_root);
4574 }
4575
4576 static dbus_bool_t
4577 int32_write_multi (TestTypeNode   *node,
4578                    DataBlock      *block,
4579                    DBusTypeWriter *writer,
4580                    int             seed,
4581                    int             count)
4582 {
4583   /* also used for uint32 */
4584   dbus_int32_t values[MAX_MULTI_COUNT];
4585   dbus_int32_t *v_ARRAY_INT32 = values;
4586   int i;
4587
4588   for (i = 0; i < count; ++i)
4589     values[i] = int32_from_seed (seed + i);
4590
4591   return _dbus_type_writer_write_fixed_multi (writer,
4592                                               node->klass->typecode,
4593                                               &v_ARRAY_INT32, count);
4594 }
4595
4596 static dbus_bool_t
4597 int32_read_multi (TestTypeNode   *node,
4598                   DBusTypeReader *reader,
4599                   int             seed,
4600                   int             count)
4601 {
4602   /* also used for uint32 */
4603   dbus_int32_t *values;
4604   int n_elements;
4605   int i;
4606
4607   check_expected_type (reader, node->klass->typecode);
4608
4609   _dbus_type_reader_read_fixed_multi (reader,
4610                                       &values,
4611                                       &n_elements);
4612
4613   if (n_elements != count)
4614     _dbus_warn ("got %d elements expected %d\n", n_elements, count);
4615   _dbus_assert (n_elements == count);
4616
4617   for (i = 0; i < count; i++)
4618     _dbus_assert (_dbus_unpack_int32 (reader->byte_order,
4619                                       (const unsigned char*)values + (i * 4)) ==
4620                   int32_from_seed (seed + i));
4621
4622   return TRUE;
4623 }
4624
4625 #ifdef DBUS_HAVE_INT64
4626 static dbus_int64_t
4627 int64_from_seed (int seed)
4628 {
4629   dbus_int32_t v32;
4630   dbus_int64_t v;
4631
4632   v32 = int32_from_seed (seed);
4633
4634   v = - (dbus_int32_t) ~ v32;
4635   v |= (((dbus_int64_t)v32) << 32);
4636
4637   return v;
4638 }
4639 #endif
4640
4641 static dbus_bool_t
4642 int64_write_value (TestTypeNode   *node,
4643                    DataBlock      *block,
4644                    DBusTypeWriter *writer,
4645                    int             seed)
4646 {
4647 #ifdef DBUS_HAVE_INT64
4648   /* also used for uint64 */
4649   dbus_int64_t v;
4650
4651   v = int64_from_seed (seed);
4652
4653   return _dbus_type_writer_write_basic (writer,
4654                                         node->klass->typecode,
4655                                         &v);
4656 #else
4657   return TRUE;
4658 #endif
4659 }
4660
4661 static dbus_bool_t
4662 int64_read_value (TestTypeNode   *node,
4663                   DBusTypeReader *reader,
4664                   int             seed)
4665 {
4666 #ifdef DBUS_HAVE_INT64
4667   /* also used for uint64 */
4668   dbus_int64_t v;
4669
4670   check_expected_type (reader, node->klass->typecode);
4671
4672   _dbus_type_reader_read_basic (reader,
4673                                 (dbus_int64_t*) &v);
4674
4675   _dbus_assert (v == int64_from_seed (seed));
4676
4677   return TRUE;
4678 #else
4679   return TRUE;
4680 #endif
4681 }
4682
4683 static dbus_bool_t
4684 int64_set_value (TestTypeNode   *node,
4685                  DBusTypeReader *reader,
4686                  DBusTypeReader *realign_root,
4687                  int             seed)
4688 {
4689 #ifdef DBUS_HAVE_INT64
4690   /* also used for uint64 */
4691   dbus_int64_t v;
4692
4693   v = int64_from_seed (seed);
4694
4695   return _dbus_type_reader_set_basic (reader,
4696                                       &v,
4697                                       realign_root);
4698 #else
4699   return TRUE;
4700 #endif
4701 }
4702
4703 #define MAX_SAMPLE_STRING_LEN 10
4704 static void
4705 string_from_seed (char *buf,
4706                   int   len,
4707                   int   seed)
4708 {
4709   int i;
4710   unsigned char v;
4711
4712   _dbus_assert (len < MAX_SAMPLE_STRING_LEN);
4713
4714   /* vary the length slightly, though we also have multiple string
4715    * value types for this, varying it here tests the set_value code
4716    */
4717   switch (seed % 3)
4718     {
4719     case 1:
4720       len += 2;
4721       break;
4722     case 2:
4723       len -= 2;
4724       break;
4725     }
4726   if (len < 0)
4727     len = 0;
4728
4729   v = (unsigned char) ('A' + seed);
4730
4731   i = 0;
4732   while (i < len)
4733     {
4734       if (v < 'A' || v > 'z')
4735         v = 'A';
4736
4737       buf[i] = v;
4738
4739       v += 1;
4740       ++i;
4741     }
4742
4743   buf[i] = '\0';
4744 }
4745
4746 static dbus_bool_t
4747 string_write_value (TestTypeNode   *node,
4748                     DataBlock      *block,
4749                     DBusTypeWriter *writer,
4750                     int             seed)
4751 {
4752   char buf[MAX_SAMPLE_STRING_LEN];
4753   const char *v_string = buf;
4754
4755   string_from_seed (buf, node->klass->subclass_detail,
4756                     seed);
4757
4758   return _dbus_type_writer_write_basic (writer,
4759                                         node->klass->typecode,
4760                                         &v_string);
4761 }
4762
4763 static dbus_bool_t
4764 string_read_value (TestTypeNode   *node,
4765                    DBusTypeReader *reader,
4766                    int             seed)
4767 {
4768   const char *v;
4769   char buf[MAX_SAMPLE_STRING_LEN];
4770
4771   check_expected_type (reader, node->klass->typecode);
4772
4773   _dbus_type_reader_read_basic (reader,
4774                                 (const char **) &v);
4775
4776   string_from_seed (buf, node->klass->subclass_detail,
4777                     seed);
4778
4779   if (strcmp (buf, v) != 0)
4780     {
4781       _dbus_warn ("read string '%s' expected '%s'\n",
4782                   v, buf);
4783       _dbus_assert_not_reached ("test failed");
4784     }
4785
4786   return TRUE;
4787 }
4788
4789 static dbus_bool_t
4790 string_set_value (TestTypeNode   *node,
4791                   DBusTypeReader *reader,
4792                   DBusTypeReader *realign_root,
4793                   int             seed)
4794 {
4795   char buf[MAX_SAMPLE_STRING_LEN];
4796   const char *v_string = buf;
4797
4798   string_from_seed (buf, node->klass->subclass_detail,
4799                     seed);
4800
4801 #if RECURSIVE_MARSHAL_WRITE_TRACE
4802  {
4803    const char *old;
4804    _dbus_type_reader_read_basic (reader, &old);
4805    _dbus_verbose ("SETTING new string '%s' len %d in place of '%s' len %d\n",
4806                   v_string, strlen (v_string), old, strlen (old));
4807  }
4808 #endif
4809
4810   return _dbus_type_reader_set_basic (reader,
4811                                       &v_string,
4812                                       realign_root);
4813 }
4814
4815 #define BOOL_FROM_SEED(seed) (seed % 2)
4816
4817 static dbus_bool_t
4818 bool_write_value (TestTypeNode   *node,
4819                   DataBlock      *block,
4820                   DBusTypeWriter *writer,
4821                   int             seed)
4822 {
4823   unsigned char v;
4824
4825   v = BOOL_FROM_SEED (seed);
4826
4827   return _dbus_type_writer_write_basic (writer,
4828                                         node->klass->typecode,
4829                                         &v);
4830 }
4831
4832 static dbus_bool_t
4833 bool_read_value (TestTypeNode   *node,
4834                  DBusTypeReader *reader,
4835                  int             seed)
4836 {
4837   unsigned char v;
4838
4839   check_expected_type (reader, node->klass->typecode);
4840
4841   _dbus_type_reader_read_basic (reader,
4842                                 (unsigned char*) &v);
4843
4844   _dbus_assert (v == BOOL_FROM_SEED (seed));
4845
4846   return TRUE;
4847 }
4848
4849 static dbus_bool_t
4850 bool_set_value (TestTypeNode   *node,
4851                 DBusTypeReader *reader,
4852                 DBusTypeReader *realign_root,
4853                 int             seed)
4854 {
4855   unsigned char v;
4856
4857   v = BOOL_FROM_SEED (seed);
4858
4859   return _dbus_type_reader_set_basic (reader,
4860                                       &v,
4861                                       realign_root);
4862 }
4863
4864 #define BYTE_FROM_SEED(seed) ((unsigned char) int32_from_seed (seed))
4865
4866 static dbus_bool_t
4867 byte_write_value (TestTypeNode   *node,
4868                   DataBlock      *block,
4869                   DBusTypeWriter *writer,
4870                   int             seed)
4871 {
4872   unsigned char v;
4873
4874   v = BYTE_FROM_SEED (seed);
4875
4876   return _dbus_type_writer_write_basic (writer,
4877                                         node->klass->typecode,
4878                                         &v);
4879 }
4880
4881 static dbus_bool_t
4882 byte_read_value (TestTypeNode   *node,
4883                  DBusTypeReader *reader,
4884                  int             seed)
4885 {
4886   unsigned char v;
4887
4888   check_expected_type (reader, node->klass->typecode);
4889
4890   _dbus_type_reader_read_basic (reader,
4891                                 (unsigned char*) &v);
4892
4893   _dbus_assert (v == BYTE_FROM_SEED (seed));
4894
4895   return TRUE;
4896 }
4897
4898
4899 static dbus_bool_t
4900 byte_set_value (TestTypeNode   *node,
4901                 DBusTypeReader *reader,
4902                 DBusTypeReader *realign_root,
4903                 int             seed)
4904 {
4905   unsigned char v;
4906
4907   v = BYTE_FROM_SEED (seed);
4908
4909   return _dbus_type_reader_set_basic (reader,
4910                                       &v,
4911                                       realign_root);
4912 }
4913
4914 static double
4915 double_from_seed (int seed)
4916 {
4917   return SAMPLE_INT32 * (double) seed + 0.3;
4918 }
4919
4920 static dbus_bool_t
4921 double_write_value (TestTypeNode   *node,
4922                     DataBlock      *block,
4923                     DBusTypeWriter *writer,
4924                     int             seed)
4925 {
4926   double v;
4927
4928   v = double_from_seed (seed);
4929
4930   return _dbus_type_writer_write_basic (writer,
4931                                         node->klass->typecode,
4932                                         &v);
4933 }
4934
4935 static dbus_bool_t
4936 double_read_value (TestTypeNode   *node,
4937                    DBusTypeReader *reader,
4938                    int             seed)
4939 {
4940   double v;
4941   double expected;
4942
4943   check_expected_type (reader, node->klass->typecode);
4944
4945   _dbus_type_reader_read_basic (reader,
4946                                 (double*) &v);
4947
4948   expected = double_from_seed (seed);
4949
4950   if (!_DBUS_DOUBLES_BITWISE_EQUAL (v, expected))
4951     {
4952 #ifdef DBUS_HAVE_INT64
4953       _dbus_warn ("Expected double %g got %g\n bits = 0x%llx vs.\n bits = 0x%llx)\n",
4954                   expected, v,
4955                   *(dbus_uint64_t*)(char*)&expected,
4956                   *(dbus_uint64_t*)(char*)&v);
4957 #endif
4958       _dbus_assert_not_reached ("test failed");
4959     }
4960
4961   return TRUE;
4962 }
4963
4964 static dbus_bool_t
4965 double_set_value (TestTypeNode   *node,
4966                 DBusTypeReader *reader,
4967                 DBusTypeReader *realign_root,
4968                 int             seed)
4969 {
4970   double v;
4971
4972   v = double_from_seed (seed);
4973
4974   return _dbus_type_reader_set_basic (reader,
4975                                       &v,
4976                                       realign_root);
4977 }
4978
4979 #define MAX_SAMPLE_OBJECT_PATH_LEN 10
4980 static void
4981 object_path_from_seed (char *buf,
4982                        int   seed)
4983 {
4984   int i;
4985   unsigned char v;
4986   int len;
4987
4988   len = seed % 9;
4989   _dbus_assert (len < MAX_SAMPLE_OBJECT_PATH_LEN);
4990
4991   v = (unsigned char) ('A' + seed);
4992
4993   i = 0;
4994   while (i + 1 < len)
4995     {
4996       if (v < 'A' || v > 'z')
4997         v = 'A';
4998
4999       buf[i] = '/';
5000       ++i;
5001       buf[i] = v;
5002       ++i;
5003
5004       v += 1;
5005     }
5006
5007   buf[i] = '\0';
5008 }
5009
5010 static dbus_bool_t
5011 object_path_write_value (TestTypeNode   *node,
5012                          DataBlock      *block,
5013                          DBusTypeWriter *writer,
5014                          int             seed)
5015 {
5016   char buf[MAX_SAMPLE_OBJECT_PATH_LEN];
5017   const char *v_string = buf;
5018
5019   object_path_from_seed (buf, seed);
5020
5021   return _dbus_type_writer_write_basic (writer,
5022                                         node->klass->typecode,
5023                                         &v_string);
5024 }
5025
5026 static dbus_bool_t
5027 object_path_read_value (TestTypeNode   *node,
5028                         DBusTypeReader *reader,
5029                         int             seed)
5030 {
5031   const char *v;
5032   char buf[MAX_SAMPLE_OBJECT_PATH_LEN];
5033
5034   check_expected_type (reader, node->klass->typecode);
5035
5036   _dbus_type_reader_read_basic (reader,
5037                                 (const char **) &v);
5038
5039   object_path_from_seed (buf, seed);
5040
5041   if (strcmp (buf, v) != 0)
5042     {
5043       _dbus_warn ("read object path '%s' expected '%s'\n",
5044                   v, buf);
5045       _dbus_assert_not_reached ("test failed");
5046     }
5047
5048   return TRUE;
5049 }
5050
5051 static dbus_bool_t
5052 object_path_set_value (TestTypeNode   *node,
5053                        DBusTypeReader *reader,
5054                        DBusTypeReader *realign_root,
5055                        int             seed)
5056 {
5057   char buf[MAX_SAMPLE_OBJECT_PATH_LEN];
5058   const char *v_string = buf;
5059
5060   object_path_from_seed (buf, seed);
5061
5062   return _dbus_type_reader_set_basic (reader,
5063                                       &v_string,
5064                                       realign_root);
5065 }
5066
5067 #define MAX_SAMPLE_SIGNATURE_LEN 10
5068 static void
5069 signature_from_seed (char *buf,
5070                      int   seed)
5071 {
5072   int i;
5073   const char *s;
5074   /* try to avoid ascending, descending, or alternating length to help find bugs */
5075   const char *sample_signatures[] = {
5076     "asax"
5077     "",
5078     "asau(xxxx)",
5079     "x",
5080     "ai",
5081     "a(ii)"
5082   };
5083
5084   s = sample_signatures[seed % _DBUS_N_ELEMENTS(sample_signatures)];
5085
5086   for (i = 0; s[i]; i++)
5087     {
5088       buf[i] = s[i];
5089     }
5090   buf[i] = '\0';
5091 }
5092
5093 static dbus_bool_t
5094 signature_write_value (TestTypeNode   *node,
5095                        DataBlock      *block,
5096                        DBusTypeWriter *writer,
5097                        int             seed)
5098 {
5099   char buf[MAX_SAMPLE_SIGNATURE_LEN];
5100   const char *v_string = buf;
5101
5102   signature_from_seed (buf, seed);
5103
5104   return _dbus_type_writer_write_basic (writer,
5105                                         node->klass->typecode,
5106                                         &v_string);
5107 }
5108
5109 static dbus_bool_t
5110 signature_read_value (TestTypeNode   *node,
5111                       DBusTypeReader *reader,
5112                       int             seed)
5113 {
5114   const char *v;
5115   char buf[MAX_SAMPLE_SIGNATURE_LEN];
5116
5117   check_expected_type (reader, node->klass->typecode);
5118
5119   _dbus_type_reader_read_basic (reader,
5120                                 (const char **) &v);
5121
5122   signature_from_seed (buf, seed);
5123
5124   if (strcmp (buf, v) != 0)
5125     {
5126       _dbus_warn ("read signature value '%s' expected '%s'\n",
5127                   v, buf);
5128       _dbus_assert_not_reached ("test failed");
5129     }
5130
5131   return TRUE;
5132 }
5133
5134
5135 static dbus_bool_t
5136 signature_set_value (TestTypeNode   *node,
5137                      DBusTypeReader *reader,
5138                      DBusTypeReader *realign_root,
5139                      int             seed)
5140 {
5141   char buf[MAX_SAMPLE_SIGNATURE_LEN];
5142   const char *v_string = buf;
5143
5144   signature_from_seed (buf, seed);
5145
5146   return _dbus_type_reader_set_basic (reader,
5147                                       &v_string,
5148                                       realign_root);
5149 }
5150
5151 static dbus_bool_t
5152 struct_write_value (TestTypeNode   *node,
5153                     DataBlock      *block,
5154                     DBusTypeWriter *writer,
5155                     int             seed)
5156 {
5157   TestTypeNodeContainer *container = (TestTypeNodeContainer*) node;
5158   DataBlockState saved;
5159   DBusTypeWriter sub;
5160   int i;
5161   int n_copies;
5162
5163   n_copies = node->klass->subclass_detail;
5164
5165   _dbus_assert (container->children != NULL);
5166
5167   data_block_save (block, &saved);
5168
5169   if (!_dbus_type_writer_recurse (writer, DBUS_TYPE_STRUCT,
5170                                   NULL, 0,
5171                                   &sub))
5172     return FALSE;
5173
5174   i = 0;
5175   while (i < n_copies)
5176     {
5177       DBusList *link;
5178
5179       link = _dbus_list_get_first_link (&container->children);
5180       while (link != NULL)
5181         {
5182           TestTypeNode *child = link->data;
5183           DBusList *next = _dbus_list_get_next_link (&container->children, link);
5184
5185           if (!node_write_value (child, block, &sub, seed + i))
5186             {
5187               data_block_restore (block, &saved);
5188               return FALSE;
5189             }
5190
5191           link = next;
5192         }
5193
5194       ++i;
5195     }
5196
5197   if (!_dbus_type_writer_unrecurse (writer, &sub))
5198     {
5199       data_block_restore (block, &saved);
5200       return FALSE;
5201     }
5202
5203   return TRUE;
5204 }
5205
5206 static dbus_bool_t
5207 struct_read_or_set_value (TestTypeNode   *node,
5208                           DBusTypeReader *reader,
5209                           DBusTypeReader *realign_root,
5210                           int             seed)
5211 {
5212   TestTypeNodeContainer *container = (TestTypeNodeContainer*) node;
5213   DBusTypeReader sub;
5214   int i;
5215   int n_copies;
5216
5217   n_copies = node->klass->subclass_detail;
5218
5219   check_expected_type (reader, DBUS_TYPE_STRUCT);
5220
5221   _dbus_type_reader_recurse (reader, &sub);
5222
5223   i = 0;
5224   while (i < n_copies)
5225     {
5226       DBusList *link;
5227
5228       link = _dbus_list_get_first_link (&container->children);
5229       while (link != NULL)
5230         {
5231           TestTypeNode *child = link->data;
5232           DBusList *next = _dbus_list_get_next_link (&container->children, link);
5233
5234           if (realign_root == NULL)
5235             {
5236               if (!node_read_value (child, &sub, seed + i))
5237                 return FALSE;
5238             }
5239           else
5240             {
5241               if (!node_set_value (child, &sub, realign_root, seed + i))
5242                 return FALSE;
5243             }
5244
5245           if (i == (n_copies - 1) && next == NULL)
5246             NEXT_EXPECTING_FALSE (&sub);
5247           else
5248             NEXT_EXPECTING_TRUE (&sub);
5249
5250           link = next;
5251         }
5252
5253       ++i;
5254     }
5255
5256   return TRUE;
5257 }
5258
5259 static dbus_bool_t
5260 struct_read_value (TestTypeNode   *node,
5261                    DBusTypeReader *reader,
5262                    int             seed)
5263 {
5264   return struct_read_or_set_value (node, reader, NULL, seed);
5265 }
5266
5267 static dbus_bool_t
5268 struct_set_value (TestTypeNode   *node,
5269                   DBusTypeReader *reader,
5270                   DBusTypeReader *realign_root,
5271                   int             seed)
5272 {
5273   return struct_read_or_set_value (node, reader, realign_root, seed);
5274 }
5275
5276 static dbus_bool_t
5277 struct_build_signature (TestTypeNode   *node,
5278                         DBusString     *str)
5279 {
5280   TestTypeNodeContainer *container = (TestTypeNodeContainer*) node;
5281   int i;
5282   int orig_len;
5283   int n_copies;
5284
5285   n_copies = node->klass->subclass_detail;
5286
5287   orig_len = _dbus_string_get_length (str);
5288
5289   if (!_dbus_string_append_byte (str, DBUS_STRUCT_BEGIN_CHAR))
5290     goto oom;
5291
5292   i = 0;
5293   while (i < n_copies)
5294     {
5295       DBusList *link;
5296
5297       link = _dbus_list_get_first_link (&container->children);
5298       while (link != NULL)
5299         {
5300           TestTypeNode *child = link->data;
5301           DBusList *next = _dbus_list_get_next_link (&container->children, link);
5302
5303           if (!node_build_signature (child, str))
5304             goto oom;
5305
5306           link = next;
5307         }
5308
5309       ++i;
5310     }
5311
5312   if (!_dbus_string_append_byte (str, DBUS_STRUCT_END_CHAR))
5313     goto oom;
5314
5315   return TRUE;
5316
5317  oom:
5318   _dbus_string_set_length (str, orig_len);
5319   return FALSE;
5320 }
5321
5322 static dbus_bool_t
5323 array_write_value (TestTypeNode   *node,
5324                    DataBlock      *block,
5325                    DBusTypeWriter *writer,
5326                    int             seed)
5327 {
5328   TestTypeNodeContainer *container = (TestTypeNodeContainer*) node;
5329   DataBlockState saved;
5330   DBusTypeWriter sub;
5331   DBusString element_signature;
5332   int i;
5333   int n_copies;
5334   int element_type;
5335   TestTypeNode *child;
5336
5337   n_copies = node->klass->subclass_detail;
5338
5339   _dbus_assert (container->children != NULL);
5340
5341   data_block_save (block, &saved);
5342
5343   if (!_dbus_string_init (&element_signature))
5344     return FALSE;
5345
5346   child = _dbus_list_get_first (&container->children);
5347
5348   if (!node_build_signature (child,
5349                              &element_signature))
5350     goto oom;
5351
5352   element_type = first_type_in_signature (&element_signature, 0);
5353
5354   if (!_dbus_type_writer_recurse (writer, DBUS_TYPE_ARRAY,
5355                                   &element_signature, 0,
5356                                   &sub))
5357     goto oom;
5358
5359   if (arrays_write_fixed_in_blocks &&
5360       _dbus_type_is_fixed (element_type) &&
5361       child->klass->write_multi)
5362     {
5363       if (!node_write_multi (child, block, &sub, seed, n_copies))
5364         goto oom;
5365     }
5366   else
5367     {
5368       i = 0;
5369       while (i < n_copies)
5370         {
5371           DBusList *link;
5372
5373           link = _dbus_list_get_first_link (&container->children);
5374           while (link != NULL)
5375             {
5376               TestTypeNode *child = link->data;
5377               DBusList *next = _dbus_list_get_next_link (&container->children, link);
5378
5379               if (!node_write_value (child, block, &sub, seed + i))
5380                 goto oom;
5381
5382               link = next;
5383             }
5384
5385           ++i;
5386         }
5387     }
5388
5389   if (!_dbus_type_writer_unrecurse (writer, &sub))
5390     goto oom;
5391
5392   _dbus_string_free (&element_signature);
5393   return TRUE;
5394
5395  oom:
5396   data_block_restore (block, &saved);
5397   _dbus_string_free (&element_signature);
5398   return FALSE;
5399 }
5400
5401 static dbus_bool_t
5402 array_read_or_set_value (TestTypeNode   *node,
5403                          DBusTypeReader *reader,
5404                          DBusTypeReader *realign_root,
5405                          int             seed)
5406 {
5407   TestTypeNodeContainer *container = (TestTypeNodeContainer*) node;
5408   DBusTypeReader sub;
5409   int i;
5410   int n_copies;
5411   TestTypeNode *child;
5412
5413   n_copies = node->klass->subclass_detail;
5414
5415   check_expected_type (reader, DBUS_TYPE_ARRAY);
5416
5417   child = _dbus_list_get_first (&container->children);
5418
5419   if (n_copies > 0)
5420     {
5421       _dbus_type_reader_recurse (reader, &sub);
5422
5423       if (realign_root == NULL && arrays_write_fixed_in_blocks &&
5424           _dbus_type_is_fixed (_dbus_type_reader_get_element_type (reader)) &&
5425           child->klass->read_multi)
5426         {
5427           if (!node_read_multi (child, &sub, seed, n_copies))
5428             return FALSE;
5429         }
5430       else
5431         {
5432           i = 0;
5433           while (i < n_copies)
5434             {
5435               DBusList *link;
5436
5437               link = _dbus_list_get_first_link (&container->children);
5438               while (link != NULL)
5439                 {
5440                   TestTypeNode *child = link->data;
5441                   DBusList *next = _dbus_list_get_next_link (&container->children, link);
5442
5443                   _dbus_assert (child->klass->typecode ==
5444                                 _dbus_type_reader_get_element_type (reader));
5445
5446                   if (realign_root == NULL)
5447                     {
5448                       if (!node_read_value (child, &sub, seed + i))
5449                         return FALSE;
5450                     }
5451                   else
5452                     {
5453                       if (!node_set_value (child, &sub, realign_root, seed + i))
5454                         return FALSE;
5455                     }
5456
5457                   if (i == (n_copies - 1) && next == NULL)
5458                     NEXT_EXPECTING_FALSE (&sub);
5459                   else
5460                     NEXT_EXPECTING_TRUE (&sub);
5461
5462                   link = next;
5463                 }
5464
5465               ++i;
5466             }
5467         }
5468     }
5469
5470   return TRUE;
5471 }
5472
5473 static dbus_bool_t
5474 array_read_value (TestTypeNode   *node,
5475                   DBusTypeReader *reader,
5476                   int             seed)
5477 {
5478   return array_read_or_set_value (node, reader, NULL, seed);
5479 }
5480
5481 static dbus_bool_t
5482 array_set_value (TestTypeNode   *node,
5483                  DBusTypeReader *reader,
5484                  DBusTypeReader *realign_root,
5485                  int             seed)
5486 {
5487   return array_read_or_set_value (node, reader, realign_root, seed);
5488 }
5489
5490 static dbus_bool_t
5491 array_build_signature (TestTypeNode   *node,
5492                        DBusString     *str)
5493 {
5494   TestTypeNodeContainer *container = (TestTypeNodeContainer*) node;
5495   int orig_len;
5496
5497   orig_len = _dbus_string_get_length (str);
5498
5499   if (!_dbus_string_append_byte (str, DBUS_TYPE_ARRAY))
5500     goto oom;
5501
5502   if (!node_build_signature (_dbus_list_get_first (&container->children),
5503                              str))
5504     goto oom;
5505
5506   return TRUE;
5507
5508  oom:
5509   _dbus_string_set_length (str, orig_len);
5510   return FALSE;
5511 }
5512
5513  /* 10 is random just to add another seed that we use in the suite */
5514 #define VARIANT_SEED 10
5515
5516 static dbus_bool_t
5517 variant_write_value (TestTypeNode   *node,
5518                      DataBlock      *block,
5519                      DBusTypeWriter *writer,
5520                      int             seed)
5521 {
5522   TestTypeNodeContainer *container = (TestTypeNodeContainer*) node;
5523   DataBlockState saved;
5524   DBusTypeWriter sub;
5525   DBusString content_signature;
5526   TestTypeNode *child;
5527
5528   _dbus_assert (container->children != NULL);
5529   _dbus_assert (_dbus_list_length_is_one (&container->children));
5530
5531   child = _dbus_list_get_first (&container->children);
5532
5533   data_block_save (block, &saved);
5534
5535   if (!_dbus_string_init (&content_signature))
5536     return FALSE;
5537
5538   if (!node_build_signature (child,
5539                              &content_signature))
5540     goto oom;
5541
5542   if (!_dbus_type_writer_recurse (writer, DBUS_TYPE_VARIANT,
5543                                   &content_signature, 0,
5544                                   &sub))
5545     goto oom;
5546
5547   if (!node_write_value (child, block, &sub, seed + VARIANT_SEED))
5548     goto oom;
5549
5550   if (!_dbus_type_writer_unrecurse (writer, &sub))
5551     goto oom;
5552
5553   _dbus_string_free (&content_signature);
5554   return TRUE;
5555
5556  oom:
5557   data_block_restore (block, &saved);
5558   _dbus_string_free (&content_signature);
5559   return FALSE;
5560 }
5561
5562 static dbus_bool_t
5563 variant_read_or_set_value (TestTypeNode   *node,
5564                            DBusTypeReader *reader,
5565                            DBusTypeReader *realign_root,
5566                            int             seed)
5567 {
5568   TestTypeNodeContainer *container = (TestTypeNodeContainer*) node;
5569   DBusTypeReader sub;
5570   TestTypeNode *child;
5571
5572   _dbus_assert (container->children != NULL);
5573   _dbus_assert (_dbus_list_length_is_one (&container->children));
5574
5575   child = _dbus_list_get_first (&container->children);
5576
5577   check_expected_type (reader, DBUS_TYPE_VARIANT);
5578
5579   _dbus_type_reader_recurse (reader, &sub);
5580
5581   if (realign_root == NULL)
5582     {
5583       if (!node_read_value (child, &sub, seed + VARIANT_SEED))
5584         return FALSE;
5585     }
5586   else
5587     {
5588       if (!node_set_value (child, &sub, realign_root, seed + VARIANT_SEED))
5589         return FALSE;
5590     }
5591
5592   NEXT_EXPECTING_FALSE (&sub);
5593
5594   return TRUE;
5595 }
5596
5597 static dbus_bool_t
5598 variant_read_value (TestTypeNode   *node,
5599                     DBusTypeReader *reader,
5600                     int             seed)
5601 {
5602   return variant_read_or_set_value (node, reader, NULL, seed);
5603 }
5604
5605 static dbus_bool_t
5606 variant_set_value (TestTypeNode   *node,
5607                    DBusTypeReader *reader,
5608                    DBusTypeReader *realign_root,
5609                    int             seed)
5610 {
5611   return variant_read_or_set_value (node, reader, realign_root, seed);
5612 }
5613
5614 static void
5615 container_destroy (TestTypeNode *node)
5616 {
5617   TestTypeNodeContainer *container = (TestTypeNodeContainer*) node;
5618   DBusList *link;
5619
5620   link = _dbus_list_get_first_link (&container->children);
5621   while (link != NULL)
5622     {
5623       TestTypeNode *child = link->data;
5624       DBusList *next = _dbus_list_get_next_link (&container->children, link);
5625
5626       node_destroy (child);
5627
5628       _dbus_list_free_link (link);
5629
5630       link = next;
5631     }
5632 }
5633
5634 #endif /* DBUS_BUILD_TESTS */