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