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