Fix memory leak with duplicated fields and PB_ENABLE_MALLOC.
[apps/low-level-can-service.git] / pb_decode.c
1 /* pb_decode.c -- decode a protobuf using minimal resources
2  *
3  * 2011 Petteri Aimonen <jpa@kapsi.fi>
4  */
5
6 /* Use the GCC warn_unused_result attribute to check that all return values
7  * are propagated correctly. On other compilers and gcc before 3.4.0 just
8  * ignore the annotation.
9  */
10 #if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)
11     #define checkreturn
12 #else
13     #define checkreturn __attribute__((warn_unused_result))
14 #endif
15
16 #include "pb.h"
17 #include "pb_decode.h"
18 #include "pb_common.h"
19
20 /**************************************
21  * Declarations internal to this file *
22  **************************************/
23
24 typedef bool (*pb_decoder_t)(pb_istream_t *stream, const pb_field_t *field, void *dest) checkreturn;
25
26 static bool checkreturn buf_read(pb_istream_t *stream, uint8_t *buf, size_t count);
27 static bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest);
28 static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, uint8_t *buf, size_t *size);
29 static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
30 static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
31 static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
32 static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type);
33 static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter);
34 static bool checkreturn find_extension_field(pb_field_iter_t *iter);
35 static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct);
36 static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest);
37 static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
38 static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
39 static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest);
40 static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest);
41 static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest);
42 static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest);
43 static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest);
44 static bool checkreturn pb_skip_varint(pb_istream_t *stream);
45 static bool checkreturn pb_skip_string(pb_istream_t *stream);
46
47 #ifdef PB_ENABLE_MALLOC
48 static void pb_release_single_field(const pb_field_iter_t *iter);
49 #endif
50
51 /* --- Function pointers to field decoders ---
52  * Order in the array must match pb_action_t LTYPE numbering.
53  */
54 static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = {
55     &pb_dec_varint,
56     &pb_dec_uvarint,
57     &pb_dec_svarint,
58     &pb_dec_fixed32,
59     &pb_dec_fixed64,
60     
61     &pb_dec_bytes,
62     &pb_dec_string,
63     &pb_dec_submessage,
64     NULL /* extensions */
65 };
66
67 /*******************************
68  * pb_istream_t implementation *
69  *******************************/
70
71 static bool checkreturn buf_read(pb_istream_t *stream, uint8_t *buf, size_t count)
72 {
73     uint8_t *source = (uint8_t*)stream->state;
74     stream->state = source + count;
75     
76     if (buf != NULL)
77     {
78         while (count--)
79             *buf++ = *source++;
80     }
81     
82     return true;
83 }
84
85 bool checkreturn pb_read(pb_istream_t *stream, uint8_t *buf, size_t count)
86 {
87 #ifndef PB_BUFFER_ONLY
88         if (buf == NULL && stream->callback != buf_read)
89         {
90                 /* Skip input bytes */
91                 uint8_t tmp[16];
92                 while (count > 16)
93                 {
94                         if (!pb_read(stream, tmp, 16))
95                                 return false;
96                         
97                         count -= 16;
98                 }
99                 
100                 return pb_read(stream, tmp, count);
101         }
102 #endif
103
104     if (stream->bytes_left < count)
105         PB_RETURN_ERROR(stream, "end-of-stream");
106     
107 #ifndef PB_BUFFER_ONLY
108     if (!stream->callback(stream, buf, count))
109         PB_RETURN_ERROR(stream, "io error");
110 #else
111     if (!buf_read(stream, buf, count))
112         return false;
113 #endif
114     
115     stream->bytes_left -= count;
116     return true;
117 }
118
119 /* Read a single byte from input stream. buf may not be NULL.
120  * This is an optimization for the varint decoding. */
121 static bool checkreturn pb_readbyte(pb_istream_t *stream, uint8_t *buf)
122 {
123     if (stream->bytes_left == 0)
124         PB_RETURN_ERROR(stream, "end-of-stream");
125
126 #ifndef PB_BUFFER_ONLY
127     if (!stream->callback(stream, buf, 1))
128         PB_RETURN_ERROR(stream, "io error");
129 #else
130     *buf = *(uint8_t*)stream->state;
131     stream->state = (uint8_t*)stream->state + 1;
132 #endif
133
134     stream->bytes_left--;
135     
136     return true;    
137 }
138
139 pb_istream_t pb_istream_from_buffer(uint8_t *buf, size_t bufsize)
140 {
141     pb_istream_t stream;
142 #ifdef PB_BUFFER_ONLY
143     stream.callback = NULL;
144 #else
145     stream.callback = &buf_read;
146 #endif
147     stream.state = buf;
148     stream.bytes_left = bufsize;
149 #ifndef PB_NO_ERRMSG
150     stream.errmsg = NULL;
151 #endif
152     return stream;
153 }
154
155 /********************
156  * Helper functions *
157  ********************/
158
159 static bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest)
160 {
161     uint8_t byte;
162     uint32_t result;
163     
164     if (!pb_readbyte(stream, &byte))
165         return false;
166     
167     if ((byte & 0x80) == 0)
168     {
169         /* Quick case, 1 byte value */
170         result = byte;
171     }
172     else
173     {
174         /* Multibyte case */
175         uint8_t bitpos = 7;
176         result = byte & 0x7F;
177         
178         do
179         {
180             if (bitpos >= 32)
181                 PB_RETURN_ERROR(stream, "varint overflow");
182             
183             if (!pb_readbyte(stream, &byte))
184                 return false;
185             
186             result |= (uint32_t)(byte & 0x7F) << bitpos;
187             bitpos = (uint8_t)(bitpos + 7);
188         } while (byte & 0x80);
189    }
190    
191    *dest = result;
192    return true;
193 }
194
195 bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest)
196 {
197     uint8_t byte;
198     uint8_t bitpos = 0;
199     uint64_t result = 0;
200     
201     do
202     {
203         if (bitpos >= 64)
204             PB_RETURN_ERROR(stream, "varint overflow");
205         
206         if (!pb_readbyte(stream, &byte))
207             return false;
208
209         result |= (uint64_t)(byte & 0x7F) << bitpos;
210         bitpos = (uint8_t)(bitpos + 7);
211     } while (byte & 0x80);
212     
213     *dest = result;
214     return true;
215 }
216
217 bool checkreturn pb_skip_varint(pb_istream_t *stream)
218 {
219     uint8_t byte;
220     do
221     {
222         if (!pb_read(stream, &byte, 1))
223             return false;
224     } while (byte & 0x80);
225     return true;
226 }
227
228 bool checkreturn pb_skip_string(pb_istream_t *stream)
229 {
230     uint32_t length;
231     if (!pb_decode_varint32(stream, &length))
232         return false;
233     
234     return pb_read(stream, NULL, length);
235 }
236
237 bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof)
238 {
239     uint32_t temp;
240     *eof = false;
241     *wire_type = (pb_wire_type_t) 0;
242     *tag = 0;
243     
244     if (!pb_decode_varint32(stream, &temp))
245     {
246         if (stream->bytes_left == 0)
247             *eof = true;
248
249         return false;
250     }
251     
252     if (temp == 0)
253     {
254         *eof = true; /* Special feature: allow 0-terminated messages. */
255         return false;
256     }
257     
258     *tag = temp >> 3;
259     *wire_type = (pb_wire_type_t)(temp & 7);
260     return true;
261 }
262
263 bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type)
264 {
265     switch (wire_type)
266     {
267         case PB_WT_VARINT: return pb_skip_varint(stream);
268         case PB_WT_64BIT: return pb_read(stream, NULL, 8);
269         case PB_WT_STRING: return pb_skip_string(stream);
270         case PB_WT_32BIT: return pb_read(stream, NULL, 4);
271         default: PB_RETURN_ERROR(stream, "invalid wire_type");
272     }
273 }
274
275 /* Read a raw value to buffer, for the purpose of passing it to callback as
276  * a substream. Size is maximum size on call, and actual size on return.
277  */
278 static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, uint8_t *buf, size_t *size)
279 {
280     size_t max_size = *size;
281     switch (wire_type)
282     {
283         case PB_WT_VARINT:
284             *size = 0;
285             do
286             {
287                 (*size)++;
288                 if (*size > max_size) return false;
289                 if (!pb_read(stream, buf, 1)) return false;
290             } while (*buf++ & 0x80);
291             return true;
292             
293         case PB_WT_64BIT:
294             *size = 8;
295             return pb_read(stream, buf, 8);
296         
297         case PB_WT_32BIT:
298             *size = 4;
299             return pb_read(stream, buf, 4);
300         
301         default: PB_RETURN_ERROR(stream, "invalid wire_type");
302     }
303 }
304
305 /* Decode string length from stream and return a substream with limited length.
306  * Remember to close the substream using pb_close_string_substream().
307  */
308 bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream)
309 {
310     uint32_t size;
311     if (!pb_decode_varint32(stream, &size))
312         return false;
313     
314     *substream = *stream;
315     if (substream->bytes_left < size)
316         PB_RETURN_ERROR(stream, "parent stream too short");
317     
318     substream->bytes_left = size;
319     stream->bytes_left -= size;
320     return true;
321 }
322
323 void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream)
324 {
325     stream->state = substream->state;
326
327 #ifndef PB_NO_ERRMSG
328     stream->errmsg = substream->errmsg;
329 #endif
330 }
331
332 /*************************
333  * Decode a single field *
334  *************************/
335
336 static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
337 {
338     pb_type_t type;
339     pb_decoder_t func;
340     
341     type = iter->pos->type;
342     func = PB_DECODERS[PB_LTYPE(type)];
343
344     switch (PB_HTYPE(type))
345     {
346         case PB_HTYPE_REQUIRED:
347             return func(stream, iter->pos, iter->pData);
348             
349         case PB_HTYPE_OPTIONAL:
350             *(bool*)iter->pSize = true;
351             return func(stream, iter->pos, iter->pData);
352     
353         case PB_HTYPE_REPEATED:
354             if (wire_type == PB_WT_STRING
355                 && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
356             {
357                 /* Packed array */
358                 bool status = true;
359                 pb_size_t *size = (pb_size_t*)iter->pSize;
360                 pb_istream_t substream;
361                 if (!pb_make_string_substream(stream, &substream))
362                     return false;
363                 
364                 while (substream.bytes_left > 0 && *size < iter->pos->array_size)
365                 {
366                     void *pItem = (uint8_t*)iter->pData + iter->pos->data_size * (*size);
367                     if (!func(&substream, iter->pos, pItem))
368                     {
369                         status = false;
370                         break;
371                     }
372                     (*size)++;
373                 }
374                 pb_close_string_substream(stream, &substream);
375                 
376                 if (substream.bytes_left != 0)
377                     PB_RETURN_ERROR(stream, "array overflow");
378                 
379                 return status;
380             }
381             else
382             {
383                 /* Repeated field */
384                 pb_size_t *size = (pb_size_t*)iter->pSize;
385                 void *pItem = (uint8_t*)iter->pData + iter->pos->data_size * (*size);
386                 if (*size >= iter->pos->array_size)
387                     PB_RETURN_ERROR(stream, "array overflow");
388                 
389                 (*size)++;
390                 return func(stream, iter->pos, pItem);
391             }
392
393         default:
394             PB_RETURN_ERROR(stream, "invalid field type");
395     }
396 }
397
398 #ifdef PB_ENABLE_MALLOC
399 /* Allocate storage for the field and store the pointer at iter->pData.
400  * array_size is the number of entries to reserve in an array.
401  * Zero size is not allowed, use pb_free() for releasing.
402  */
403 static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size)
404 {    
405     void *ptr = *(void**)pData;
406     
407     /* Check for multiplication overflows.
408      * This code avoids the costly division if the sizes are small enough.
409      * Multiplication is safe as long as only half of bits are set
410      * in either multiplicand.
411      */
412     const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4);
413     if (data_size >= check_limit || array_size >= check_limit)
414     {
415         const size_t size_max = (size_t)-1;
416         if (size_max / array_size < data_size)
417         {
418             PB_RETURN_ERROR(stream, "size too large");
419         }
420     }
421     
422     /* Allocate new or expand previous allocation */
423     /* Note: on failure the old pointer will remain in the structure,
424      * the message must be freed by caller also on error return. */
425     ptr = pb_realloc(ptr, array_size * data_size);
426     if (ptr == NULL)
427         PB_RETURN_ERROR(stream, "realloc failed");
428     
429     *(void**)pData = ptr;
430     return true;
431 }
432
433 /* Clear a newly allocated item in case it contains a pointer, or is a submessage. */
434 static void initialize_pointer_field(void *pItem, pb_field_iter_t *iter)
435 {
436     if (PB_LTYPE(iter->pos->type) == PB_LTYPE_STRING ||
437         PB_LTYPE(iter->pos->type) == PB_LTYPE_BYTES)
438     {
439         *(void**)pItem = NULL;
440     }
441     else if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE)
442     {
443         pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, pItem);
444     }
445 }
446 #endif
447
448 static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
449 {
450 #ifndef PB_ENABLE_MALLOC
451     PB_UNUSED(wire_type);
452     PB_UNUSED(iter);
453     PB_RETURN_ERROR(stream, "no malloc support");
454 #else
455     pb_type_t type;
456     pb_decoder_t func;
457     
458     type = iter->pos->type;
459     func = PB_DECODERS[PB_LTYPE(type)];
460     
461     switch (PB_HTYPE(type))
462     {
463         case PB_HTYPE_REQUIRED:
464         case PB_HTYPE_OPTIONAL:
465             if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&
466                 *(void**)iter->pData != NULL)
467             {
468                 /* Duplicate field, have to release the old allocation first. */
469                 pb_release_single_field(iter);
470             }
471         
472             if (PB_LTYPE(type) == PB_LTYPE_STRING ||
473                 PB_LTYPE(type) == PB_LTYPE_BYTES)
474             {
475                 return func(stream, iter->pos, iter->pData);
476             }
477             else
478             {
479                 if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))
480                     return false;
481                 
482                 initialize_pointer_field(*(void**)iter->pData, iter);
483                 return func(stream, iter->pos, *(void**)iter->pData);
484             }
485     
486         case PB_HTYPE_REPEATED:
487             if (wire_type == PB_WT_STRING
488                 && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
489             {
490                 /* Packed array, multiple items come in at once. */
491                 bool status = true;
492                 pb_size_t *size = (pb_size_t*)iter->pSize;
493                 size_t allocated_size = *size;
494                 void *pItem;
495                 pb_istream_t substream;
496                 
497                 if (!pb_make_string_substream(stream, &substream))
498                     return false;
499                 
500                 while (substream.bytes_left)
501                 {
502                     if ((size_t)*size + 1 > allocated_size)
503                     {
504                         /* Allocate more storage. This tries to guess the
505                          * number of remaining entries. Round the division
506                          * upwards. */
507                         allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1;
508                         
509                         if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))
510                         {
511                             status = false;
512                             break;
513                         }
514                     }
515
516                     /* Decode the array entry */
517                     pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size);
518                     initialize_pointer_field(pItem, iter);
519                     if (!func(&substream, iter->pos, pItem))
520                     {
521                         status = false;
522                         break;
523                     }
524                     
525                     if (*size == PB_SIZE_MAX)
526                     {
527 #ifndef PB_NO_ERRMSG
528                         stream->errmsg = "too many array entries";
529 #endif
530                         status = false;
531                         break;
532                     }
533                     
534                     (*size)++;
535                 }
536                 pb_close_string_substream(stream, &substream);
537                 
538                 return status;
539             }
540             else
541             {
542                 /* Normal repeated field, i.e. only one item at a time. */
543                 pb_size_t *size = (pb_size_t*)iter->pSize;
544                 void *pItem;
545                 
546                 if (*size == PB_SIZE_MAX)
547                     PB_RETURN_ERROR(stream, "too many array entries");
548                 
549                 (*size)++;
550                 if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size))
551                     return false;
552             
553                 pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size - 1);
554                 initialize_pointer_field(pItem, iter);
555                 return func(stream, iter->pos, pItem);
556             }
557             
558         default:
559             PB_RETURN_ERROR(stream, "invalid field type");
560     }
561 #endif
562 }
563
564 static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
565 {
566     pb_callback_t *pCallback = (pb_callback_t*)iter->pData;
567     
568 #ifdef PB_OLD_CALLBACK_STYLE
569     void *arg = pCallback->arg;
570 #else
571     void **arg = &(pCallback->arg);
572 #endif
573     
574     if (pCallback->funcs.decode == NULL)
575         return pb_skip_field(stream, wire_type);
576     
577     if (wire_type == PB_WT_STRING)
578     {
579         pb_istream_t substream;
580         
581         if (!pb_make_string_substream(stream, &substream))
582             return false;
583         
584         do
585         {
586             if (!pCallback->funcs.decode(&substream, iter->pos, arg))
587                 PB_RETURN_ERROR(stream, "callback failed");
588         } while (substream.bytes_left);
589         
590         pb_close_string_substream(stream, &substream);
591         return true;
592     }
593     else
594     {
595         /* Copy the single scalar value to stack.
596          * This is required so that we can limit the stream length,
597          * which in turn allows to use same callback for packed and
598          * not-packed fields. */
599         pb_istream_t substream;
600         uint8_t buffer[10];
601         size_t size = sizeof(buffer);
602         
603         if (!read_raw_value(stream, wire_type, buffer, &size))
604             return false;
605         substream = pb_istream_from_buffer(buffer, size);
606         
607         return pCallback->funcs.decode(&substream, iter->pos, arg);
608     }
609 }
610
611 static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
612 {
613     switch (PB_ATYPE(iter->pos->type))
614     {
615         case PB_ATYPE_STATIC:
616             return decode_static_field(stream, wire_type, iter);
617         
618         case PB_ATYPE_POINTER:
619             return decode_pointer_field(stream, wire_type, iter);
620         
621         case PB_ATYPE_CALLBACK:
622             return decode_callback_field(stream, wire_type, iter);
623         
624         default:
625             PB_RETURN_ERROR(stream, "invalid field type");
626     }
627 }
628
629 /* Default handler for extension fields. Expects a pb_field_t structure
630  * in extension->type->arg. */
631 static bool checkreturn default_extension_decoder(pb_istream_t *stream,
632     pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type)
633 {
634     const pb_field_t *field = (const pb_field_t*)extension->type->arg;
635     pb_field_iter_t iter;
636     
637     if (field->tag != tag)
638         return true;
639     
640     /* Fake a field iterator for the extension field.
641      * It is not actually safe to advance this iterator, but decode_field
642      * will not even try to. */
643     (void)pb_field_iter_begin(&iter, field, extension->dest);
644     iter.pData = extension->dest;
645     iter.pSize = &extension->found;
646     
647     return decode_field(stream, wire_type, &iter);
648 }
649
650 /* Try to decode an unknown field as an extension field. Tries each extension
651  * decoder in turn, until one of them handles the field or loop ends. */
652 static bool checkreturn decode_extension(pb_istream_t *stream,
653     uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter)
654 {
655     pb_extension_t *extension = *(pb_extension_t* const *)iter->pData;
656     size_t pos = stream->bytes_left;
657     
658     while (extension != NULL && pos == stream->bytes_left)
659     {
660         bool status;
661         if (extension->type->decode)
662             status = extension->type->decode(stream, extension, tag, wire_type);
663         else
664             status = default_extension_decoder(stream, extension, tag, wire_type);
665
666         if (!status)
667             return false;
668         
669         extension = extension->next;
670     }
671     
672     return true;
673 }
674
675 /* Step through the iterator until an extension field is found or until all
676  * entries have been checked. There can be only one extension field per
677  * message. Returns false if no extension field is found. */
678 static bool checkreturn find_extension_field(pb_field_iter_t *iter)
679 {
680     const pb_field_t *start = iter->pos;
681     
682     do {
683         if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION)
684             return true;
685         (void)pb_field_iter_next(iter);
686     } while (iter->pos != start);
687     
688     return false;
689 }
690
691 /* Initialize message fields to default values, recursively */
692 static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct)
693 {
694     pb_field_iter_t iter;
695
696     if (!pb_field_iter_begin(&iter, fields, dest_struct))
697         return; /* Empty message type */
698     
699     do
700     {
701         pb_type_t type;
702         type = iter.pos->type;
703         
704         if (PB_ATYPE(type) == PB_ATYPE_STATIC)
705         {
706             if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL)
707             {
708                 /* Set has_field to false. Still initialize the optional field
709                  * itself also. */
710                 *(bool*)iter.pSize = false;
711             }
712             else if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
713             {
714                 /* Set array count to 0, no need to initialize contents. */
715                 *(pb_size_t*)iter.pSize = 0;
716                 continue;
717             }
718             
719             if (PB_LTYPE(iter.pos->type) == PB_LTYPE_SUBMESSAGE)
720             {
721                 /* Initialize submessage to defaults */
722                 pb_message_set_to_defaults((const pb_field_t *) iter.pos->ptr, iter.pData);
723             }
724             else if (iter.pos->ptr != NULL)
725             {
726                 /* Initialize to default value */
727                 memcpy(iter.pData, iter.pos->ptr, iter.pos->data_size);
728             }
729             else
730             {
731                 /* Initialize to zeros */
732                 memset(iter.pData, 0, iter.pos->data_size);
733             }
734         }
735         else if (PB_ATYPE(type) == PB_ATYPE_POINTER)
736         {
737             /* Initialize the pointer to NULL. */
738             *(void**)iter.pData = NULL;
739             
740             /* Initialize array count to 0. */
741             if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
742             {
743                 *(pb_size_t*)iter.pSize = 0;
744             }
745         }
746         else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
747         {
748             /* Don't overwrite callback */
749         }
750     } while (pb_field_iter_next(&iter));
751 }
752
753 /*********************
754  * Decode all fields *
755  *********************/
756
757 bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
758 {
759     uint8_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 7) / 8] = {0, 0, 0, 0, 0, 0, 0, 0};
760     uint32_t extension_range_start = 0;
761     pb_field_iter_t iter;
762     
763     /* Return value ignored, as empty message types will be correctly handled by
764      * pb_field_iter_find() anyway. */
765     (void)pb_field_iter_begin(&iter, fields, dest_struct);
766     
767     while (stream->bytes_left)
768     {
769         uint32_t tag;
770         pb_wire_type_t wire_type;
771         bool eof;
772         
773         if (!pb_decode_tag(stream, &wire_type, &tag, &eof))
774         {
775             if (eof)
776                 break;
777             else
778                 return false;
779         }
780         
781         if (!pb_field_iter_find(&iter, tag))
782         {
783             /* No match found, check if it matches an extension. */
784             if (tag >= extension_range_start)
785             {
786                 if (!find_extension_field(&iter))
787                     extension_range_start = (uint32_t)-1;
788                 else
789                     extension_range_start = iter.pos->tag;
790                 
791                 if (tag >= extension_range_start)
792                 {
793                     size_t pos = stream->bytes_left;
794                 
795                     if (!decode_extension(stream, tag, wire_type, &iter))
796                         return false;
797                     
798                     if (pos != stream->bytes_left)
799                     {
800                         /* The field was handled */
801                         continue;                    
802                     }
803                 }
804             }
805         
806             /* No match found, skip data */
807             if (!pb_skip_field(stream, wire_type))
808                 return false;
809             continue;
810         }
811         
812         if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED
813             && iter.required_field_index < PB_MAX_REQUIRED_FIELDS)
814         {
815             fields_seen[iter.required_field_index >> 3] |= (uint8_t)(1 << (iter.required_field_index & 7));
816         }
817             
818         if (!decode_field(stream, wire_type, &iter))
819             return false;
820     }
821     
822     /* Check that all required fields were present. */
823     {
824         /* First figure out the number of required fields by
825          * seeking to the end of the field array. Usually we
826          * are already close to end after decoding.
827          */
828         unsigned req_field_count;
829         pb_type_t last_type;
830         unsigned i;
831         do {
832             req_field_count = iter.required_field_index;
833             last_type = iter.pos->type;
834         } while (pb_field_iter_next(&iter));
835         
836         /* Fixup if last field was also required. */
837         if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0)
838             req_field_count++;
839         
840         /* Check the whole bytes */
841         for (i = 0; i < (req_field_count >> 3); i++)
842         {
843             if (fields_seen[i] != 0xFF)
844                 PB_RETURN_ERROR(stream, "missing required field");
845         }
846         
847         /* Check the remaining bits */
848         if (fields_seen[req_field_count >> 3] != (0xFF >> (8 - (req_field_count & 7))))
849             PB_RETURN_ERROR(stream, "missing required field");
850     }
851     
852     return true;
853 }
854
855 bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
856 {
857     bool status;
858     pb_message_set_to_defaults(fields, dest_struct);
859     status = pb_decode_noinit(stream, fields, dest_struct);
860     
861 #ifdef PB_ENABLE_MALLOC
862     if (!status)
863         pb_release(fields, dest_struct);
864 #endif
865     
866     return status;
867 }
868
869 bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
870 {
871     pb_istream_t substream;
872     bool status;
873     
874     if (!pb_make_string_substream(stream, &substream))
875         return false;
876     
877     status = pb_decode(&substream, fields, dest_struct);
878     pb_close_string_substream(stream, &substream);
879     return status;
880 }
881
882 #ifdef PB_ENABLE_MALLOC
883 static void pb_release_single_field(const pb_field_iter_t *iter)
884 {
885     pb_type_t type;
886     type = iter->pos->type;
887
888     if (PB_ATYPE(type) == PB_ATYPE_POINTER)
889     {
890         if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&
891             (PB_LTYPE(type) == PB_LTYPE_STRING ||
892              PB_LTYPE(type) == PB_LTYPE_BYTES))
893         {
894             /* Release entries in repeated string or bytes array */
895             void **pItem = *(void***)iter->pData;
896             pb_size_t count = *(pb_size_t*)iter->pSize;
897             while (count--)
898             {
899                 pb_free(*pItem);
900                 *pItem++ = NULL;
901             }
902             *(pb_size_t*)iter->pSize = 0;
903         }
904         else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)
905         {
906             /* Release fields in submessages */
907             void *pItem = *(void**)iter->pData;
908             if (pItem)
909             {
910                 pb_size_t count = 1;
911                 
912                 if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
913                 {
914                     count = *(pb_size_t*)iter->pSize;
915                     *(pb_size_t*)iter->pSize = 0;
916                 }
917                 
918                 while (count--)
919                 {
920                     pb_release((const pb_field_t*)iter->pos->ptr, pItem);
921                     pItem = (uint8_t*)pItem + iter->pos->data_size;
922                 }
923             }
924         }
925         
926         /* Release main item */
927         pb_free(*(void**)iter->pData);
928         *(void**)iter->pData = NULL;
929     }
930 }
931
932 void pb_release(const pb_field_t fields[], void *dest_struct)
933 {
934     pb_field_iter_t iter;
935     
936     if (!pb_field_iter_begin(&iter, fields, dest_struct))
937         return; /* Empty message type */
938     
939     do
940     {
941         pb_release_single_field(&iter);
942     } while (pb_field_iter_next(&iter));
943 }
944 #endif
945
946 /* Field decoders */
947
948 bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest)
949 {
950     uint64_t value;
951     if (!pb_decode_varint(stream, &value))
952         return false;
953     
954     if (value & 1)
955         *dest = (int64_t)(~(value >> 1));
956     else
957         *dest = (int64_t)(value >> 1);
958     
959     return true;
960 }
961
962 bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
963 {
964     #ifdef __BIG_ENDIAN__
965     uint8_t *bytes = (uint8_t*)dest;
966     uint8_t lebytes[4];
967     
968     if (!pb_read(stream, lebytes, 4))
969         return false;
970     
971     bytes[0] = lebytes[3];
972     bytes[1] = lebytes[2];
973     bytes[2] = lebytes[1];
974     bytes[3] = lebytes[0];
975     return true;
976     #else
977     return pb_read(stream, (uint8_t*)dest, 4);
978     #endif   
979 }
980
981 bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
982 {
983     #ifdef __BIG_ENDIAN__
984     uint8_t *bytes = (uint8_t*)dest;
985     uint8_t lebytes[8];
986     
987     if (!pb_read(stream, lebytes, 8))
988         return false;
989     
990     bytes[0] = lebytes[7];
991     bytes[1] = lebytes[6];
992     bytes[2] = lebytes[5];
993     bytes[3] = lebytes[4];
994     bytes[4] = lebytes[3];
995     bytes[5] = lebytes[2];
996     bytes[6] = lebytes[1];
997     bytes[7] = lebytes[0];
998     return true;
999     #else
1000     return pb_read(stream, (uint8_t*)dest, 8);
1001     #endif   
1002 }
1003
1004 static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1005 {
1006     uint64_t value;
1007     if (!pb_decode_varint(stream, &value))
1008         return false;
1009     
1010     switch (field->data_size)
1011     {
1012         case 1: *(int8_t*)dest = (int8_t)value; break;
1013         case 2: *(int16_t*)dest = (int16_t)value; break;
1014         case 4: *(int32_t*)dest = (int32_t)value; break;
1015         case 8: *(int64_t*)dest = (int64_t)value; break;
1016         default: PB_RETURN_ERROR(stream, "invalid data_size");
1017     }
1018     
1019     return true;
1020 }
1021
1022 static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1023 {
1024     uint64_t value;
1025     if (!pb_decode_varint(stream, &value))
1026         return false;
1027     
1028     switch (field->data_size)
1029     {
1030         case 4: *(uint32_t*)dest = (uint32_t)value; break;
1031         case 8: *(uint64_t*)dest = value; break;
1032         default: PB_RETURN_ERROR(stream, "invalid data_size");
1033     }
1034     
1035     return true;
1036 }
1037
1038 static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1039 {
1040     int64_t value;
1041     if (!pb_decode_svarint(stream, &value))
1042         return false;
1043     
1044     switch (field->data_size)
1045     {
1046         case 4: *(int32_t*)dest = (int32_t)value; break;
1047         case 8: *(int64_t*)dest = value; break;
1048         default: PB_RETURN_ERROR(stream, "invalid data_size");
1049     }
1050     
1051     return true;
1052 }
1053
1054 static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)
1055 {
1056     PB_UNUSED(field);
1057     return pb_decode_fixed32(stream, dest);
1058 }
1059
1060 static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)
1061 {
1062     PB_UNUSED(field);
1063     return pb_decode_fixed64(stream, dest);
1064 }
1065
1066 static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
1067 {
1068     uint32_t size;
1069     pb_bytes_array_t *bdest;
1070     
1071     if (!pb_decode_varint32(stream, &size))
1072         return false;
1073     
1074     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1075     {
1076 #ifndef PB_ENABLE_MALLOC
1077         PB_RETURN_ERROR(stream, "no malloc support");
1078 #else
1079         if (!allocate_field(stream, dest, PB_BYTES_ARRAY_T_ALLOCSIZE(size), 1))
1080             return false;
1081         bdest = *(pb_bytes_array_t**)dest;
1082 #endif
1083     }
1084     else
1085     {
1086         if (PB_BYTES_ARRAY_T_ALLOCSIZE(size) > field->data_size)
1087             PB_RETURN_ERROR(stream, "bytes overflow");
1088         bdest = (pb_bytes_array_t*)dest;
1089     }
1090     
1091     if (size > PB_SIZE_MAX)
1092     {
1093         PB_RETURN_ERROR(stream, "bytes overflow");
1094     }
1095
1096     bdest->size = (pb_size_t)size;
1097     return pb_read(stream, bdest->bytes, size);
1098 }
1099
1100 static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
1101 {
1102     uint32_t size;
1103     size_t alloc_size;
1104     bool status;
1105     if (!pb_decode_varint32(stream, &size))
1106         return false;
1107     
1108     /* Space for null terminator */
1109     alloc_size = size + 1;
1110     
1111     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1112     {
1113 #ifndef PB_ENABLE_MALLOC
1114         PB_RETURN_ERROR(stream, "no malloc support");
1115 #else
1116         if (!allocate_field(stream, dest, alloc_size, 1))
1117             return false;
1118         dest = *(void**)dest;
1119 #endif
1120     }
1121     else
1122     {
1123         if (alloc_size > field->data_size)
1124             PB_RETURN_ERROR(stream, "string overflow");
1125     }
1126     
1127     status = pb_read(stream, (uint8_t*)dest, size);
1128     *((uint8_t*)dest + size) = 0;
1129     return status;
1130 }
1131
1132 static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
1133 {
1134     bool status;
1135     pb_istream_t substream;
1136     const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;
1137     
1138     if (!pb_make_string_substream(stream, &substream))
1139         return false;
1140     
1141     if (field->ptr == NULL)
1142         PB_RETURN_ERROR(stream, "invalid field descriptor");
1143     
1144     /* New array entries need to be initialized, while required and optional
1145      * submessages have already been initialized in the top-level pb_decode. */
1146     if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
1147         status = pb_decode(&substream, submsg_fields, dest);
1148     else
1149         status = pb_decode_noinit(&substream, submsg_fields, dest);
1150     
1151     pb_close_string_substream(stream, &substream);
1152     return status;
1153 }