Change the _count fields to use pb_size_t datatype.
[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                 pb_size_t *size = (pb_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                 pb_size_t *size = (pb_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                 pb_size_t *size = (pb_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_t)*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                     
514                     if (*size == PB_SIZE_MAX)
515                     {
516 #ifndef PB_NO_ERRMSG
517                         stream->errmsg = "too many array entries";
518 #endif
519                         status = false;
520                         break;
521                     }
522                     
523                     (*size)++;
524                 }
525                 pb_close_string_substream(stream, &substream);
526                 
527                 return status;
528             }
529             else
530             {
531                 /* Normal repeated field, i.e. only one item at a time. */
532                 pb_size_t *size = (pb_size_t*)iter->pSize;
533                 void *pItem;
534                 
535                 if (*size == PB_SIZE_MAX)
536                     PB_RETURN_ERROR(stream, "too many array entries");
537                 
538                 (*size)++;
539                 if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size))
540                     return false;
541             
542                 pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size - 1);
543                 initialize_pointer_field(pItem, iter);
544                 return func(stream, iter->pos, pItem);
545             }
546             
547         default:
548             PB_RETURN_ERROR(stream, "invalid field type");
549     }
550 #endif
551 }
552
553 static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
554 {
555     pb_callback_t *pCallback = (pb_callback_t*)iter->pData;
556     
557 #ifdef PB_OLD_CALLBACK_STYLE
558     void *arg = pCallback->arg;
559 #else
560     void **arg = &(pCallback->arg);
561 #endif
562     
563     if (pCallback->funcs.decode == NULL)
564         return pb_skip_field(stream, wire_type);
565     
566     if (wire_type == PB_WT_STRING)
567     {
568         pb_istream_t substream;
569         
570         if (!pb_make_string_substream(stream, &substream))
571             return false;
572         
573         do
574         {
575             if (!pCallback->funcs.decode(&substream, iter->pos, arg))
576                 PB_RETURN_ERROR(stream, "callback failed");
577         } while (substream.bytes_left);
578         
579         pb_close_string_substream(stream, &substream);
580         return true;
581     }
582     else
583     {
584         /* Copy the single scalar value to stack.
585          * This is required so that we can limit the stream length,
586          * which in turn allows to use same callback for packed and
587          * not-packed fields. */
588         pb_istream_t substream;
589         uint8_t buffer[10];
590         size_t size = sizeof(buffer);
591         
592         if (!read_raw_value(stream, wire_type, buffer, &size))
593             return false;
594         substream = pb_istream_from_buffer(buffer, size);
595         
596         return pCallback->funcs.decode(&substream, iter->pos, arg);
597     }
598 }
599
600 static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
601 {
602     switch (PB_ATYPE(iter->pos->type))
603     {
604         case PB_ATYPE_STATIC:
605             return decode_static_field(stream, wire_type, iter);
606         
607         case PB_ATYPE_POINTER:
608             return decode_pointer_field(stream, wire_type, iter);
609         
610         case PB_ATYPE_CALLBACK:
611             return decode_callback_field(stream, wire_type, iter);
612         
613         default:
614             PB_RETURN_ERROR(stream, "invalid field type");
615     }
616 }
617
618 /* Default handler for extension fields. Expects a pb_field_t structure
619  * in extension->type->arg. */
620 static bool checkreturn default_extension_decoder(pb_istream_t *stream,
621     pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type)
622 {
623     const pb_field_t *field = (const pb_field_t*)extension->type->arg;
624     pb_field_iter_t iter;
625     
626     if (field->tag != tag)
627         return true;
628     
629     /* Fake a field iterator for the extension field.
630      * It is not actually safe to advance this iterator, but decode_field
631      * will not even try to. */
632     (void)pb_field_iter_begin(&iter, field, extension->dest);
633     iter.pData = extension->dest;
634     iter.pSize = &extension->found;
635     
636     return decode_field(stream, wire_type, &iter);
637 }
638
639 /* Try to decode an unknown field as an extension field. Tries each extension
640  * decoder in turn, until one of them handles the field or loop ends. */
641 static bool checkreturn decode_extension(pb_istream_t *stream,
642     uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter)
643 {
644     pb_extension_t *extension = *(pb_extension_t* const *)iter->pData;
645     size_t pos = stream->bytes_left;
646     
647     while (extension != NULL && pos == stream->bytes_left)
648     {
649         bool status;
650         if (extension->type->decode)
651             status = extension->type->decode(stream, extension, tag, wire_type);
652         else
653             status = default_extension_decoder(stream, extension, tag, wire_type);
654
655         if (!status)
656             return false;
657         
658         extension = extension->next;
659     }
660     
661     return true;
662 }
663
664 /* Step through the iterator until an extension field is found or until all
665  * entries have been checked. There can be only one extension field per
666  * message. Returns false if no extension field is found. */
667 static bool checkreturn find_extension_field(pb_field_iter_t *iter)
668 {
669     const pb_field_t *start = iter->pos;
670     
671     do {
672         if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION)
673             return true;
674         (void)pb_field_iter_next(iter);
675     } while (iter->pos != start);
676     
677     return false;
678 }
679
680 /* Initialize message fields to default values, recursively */
681 static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct)
682 {
683     pb_field_iter_t iter;
684
685     if (!pb_field_iter_begin(&iter, fields, dest_struct))
686         return; /* Empty message type */
687     
688     do
689     {
690         pb_type_t type;
691         type = iter.pos->type;
692         
693         if (PB_ATYPE(type) == PB_ATYPE_STATIC)
694         {
695             if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL)
696             {
697                 /* Set has_field to false. Still initialize the optional field
698                  * itself also. */
699                 *(bool*)iter.pSize = false;
700             }
701             else if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
702             {
703                 /* Set array count to 0, no need to initialize contents. */
704                 *(pb_size_t*)iter.pSize = 0;
705                 continue;
706             }
707             
708             if (PB_LTYPE(iter.pos->type) == PB_LTYPE_SUBMESSAGE)
709             {
710                 /* Initialize submessage to defaults */
711                 pb_message_set_to_defaults((const pb_field_t *) iter.pos->ptr, iter.pData);
712             }
713             else if (iter.pos->ptr != NULL)
714             {
715                 /* Initialize to default value */
716                 memcpy(iter.pData, iter.pos->ptr, iter.pos->data_size);
717             }
718             else
719             {
720                 /* Initialize to zeros */
721                 memset(iter.pData, 0, iter.pos->data_size);
722             }
723         }
724         else if (PB_ATYPE(type) == PB_ATYPE_POINTER)
725         {
726             /* Initialize the pointer to NULL. */
727             *(void**)iter.pData = NULL;
728             
729             /* Initialize array count to 0. */
730             if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
731             {
732                 *(pb_size_t*)iter.pSize = 0;
733             }
734         }
735         else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
736         {
737             /* Don't overwrite callback */
738         }
739     } while (pb_field_iter_next(&iter));
740 }
741
742 /*********************
743  * Decode all fields *
744  *********************/
745
746 bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
747 {
748     uint8_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 7) / 8] = {0, 0, 0, 0, 0, 0, 0, 0};
749     uint32_t extension_range_start = 0;
750     pb_field_iter_t iter;
751     
752     /* Return value ignored, as empty message types will be correctly handled by
753      * pb_field_iter_find() anyway. */
754     (void)pb_field_iter_begin(&iter, fields, dest_struct);
755     
756     while (stream->bytes_left)
757     {
758         uint32_t tag;
759         pb_wire_type_t wire_type;
760         bool eof;
761         
762         if (!pb_decode_tag(stream, &wire_type, &tag, &eof))
763         {
764             if (eof)
765                 break;
766             else
767                 return false;
768         }
769         
770         if (!pb_field_iter_find(&iter, tag))
771         {
772             /* No match found, check if it matches an extension. */
773             if (tag >= extension_range_start)
774             {
775                 if (!find_extension_field(&iter))
776                     extension_range_start = (uint32_t)-1;
777                 else
778                     extension_range_start = iter.pos->tag;
779                 
780                 if (tag >= extension_range_start)
781                 {
782                     size_t pos = stream->bytes_left;
783                 
784                     if (!decode_extension(stream, tag, wire_type, &iter))
785                         return false;
786                     
787                     if (pos != stream->bytes_left)
788                     {
789                         /* The field was handled */
790                         continue;                    
791                     }
792                 }
793             }
794         
795             /* No match found, skip data */
796             if (!pb_skip_field(stream, wire_type))
797                 return false;
798             continue;
799         }
800         
801         if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED
802             && iter.required_field_index < PB_MAX_REQUIRED_FIELDS)
803         {
804             fields_seen[iter.required_field_index >> 3] |= (uint8_t)(1 << (iter.required_field_index & 7));
805         }
806             
807         if (!decode_field(stream, wire_type, &iter))
808             return false;
809     }
810     
811     /* Check that all required fields were present. */
812     {
813         /* First figure out the number of required fields by
814          * seeking to the end of the field array. Usually we
815          * are already close to end after decoding.
816          */
817         unsigned req_field_count;
818         pb_type_t last_type;
819         unsigned i;
820         do {
821             req_field_count = iter.required_field_index;
822             last_type = iter.pos->type;
823         } while (pb_field_iter_next(&iter));
824         
825         /* Fixup if last field was also required. */
826         if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0)
827             req_field_count++;
828         
829         /* Check the whole bytes */
830         for (i = 0; i < (req_field_count >> 3); i++)
831         {
832             if (fields_seen[i] != 0xFF)
833                 PB_RETURN_ERROR(stream, "missing required field");
834         }
835         
836         /* Check the remaining bits */
837         if (fields_seen[req_field_count >> 3] != (0xFF >> (8 - (req_field_count & 7))))
838             PB_RETURN_ERROR(stream, "missing required field");
839     }
840     
841     return true;
842 }
843
844 bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
845 {
846     bool status;
847     pb_message_set_to_defaults(fields, dest_struct);
848     status = pb_decode_noinit(stream, fields, dest_struct);
849     
850 #ifdef PB_ENABLE_MALLOC
851     if (!status)
852         pb_release(fields, dest_struct);
853 #endif
854     
855     return status;
856 }
857
858 bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
859 {
860     pb_istream_t substream;
861     bool status;
862     
863     if (!pb_make_string_substream(stream, &substream))
864         return false;
865     
866     status = pb_decode(&substream, fields, dest_struct);
867     pb_close_string_substream(stream, &substream);
868     return status;
869 }
870
871 #ifdef PB_ENABLE_MALLOC
872 void pb_release(const pb_field_t fields[], void *dest_struct)
873 {
874     pb_field_iter_t iter;
875     
876     if (!pb_field_iter_begin(&iter, fields, dest_struct))
877         return; /* Empty message type */
878     
879     do
880     {
881         pb_type_t type;
882         type = iter.pos->type;
883     
884         if (PB_ATYPE(type) == PB_ATYPE_POINTER)
885         {
886             if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&
887                 (PB_LTYPE(type) == PB_LTYPE_STRING ||
888                  PB_LTYPE(type) == PB_LTYPE_BYTES))
889             {
890                 /* Release entries in repeated string or bytes array */
891                 void **pItem = *(void***)iter.pData;
892                 pb_size_t count = *(pb_size_t*)iter.pSize;
893                 while (count--)
894                 {
895                     pb_free(*pItem);
896                     *pItem++ = NULL;
897                 }
898             }
899             else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)
900             {
901                 /* Release fields in submessages */
902                 void *pItem = *(void**)iter.pData;
903                 pb_size_t count = (pItem ? 1 : 0);
904                 
905                 if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
906                 {
907                     count = *(pb_size_t*)iter.pSize;   
908                 }
909                 
910                 while (count--)
911                 {
912                     pb_release((const pb_field_t*)iter.pos->ptr, pItem);
913                     pItem = (uint8_t*)pItem + iter.pos->data_size;
914                 }
915             }
916             
917             /* Release main item */
918             pb_free(*(void**)iter.pData);
919             *(void**)iter.pData = NULL;
920         }
921     } while (pb_field_iter_next(&iter));
922 }
923 #endif
924
925 /* Field decoders */
926
927 bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest)
928 {
929     uint64_t value;
930     if (!pb_decode_varint(stream, &value))
931         return false;
932     
933     if (value & 1)
934         *dest = (int64_t)(~(value >> 1));
935     else
936         *dest = (int64_t)(value >> 1);
937     
938     return true;
939 }
940
941 bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
942 {
943     #ifdef __BIG_ENDIAN__
944     uint8_t *bytes = (uint8_t*)dest;
945     uint8_t lebytes[4];
946     
947     if (!pb_read(stream, lebytes, 4))
948         return false;
949     
950     bytes[0] = lebytes[3];
951     bytes[1] = lebytes[2];
952     bytes[2] = lebytes[1];
953     bytes[3] = lebytes[0];
954     return true;
955     #else
956     return pb_read(stream, (uint8_t*)dest, 4);
957     #endif   
958 }
959
960 bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
961 {
962     #ifdef __BIG_ENDIAN__
963     uint8_t *bytes = (uint8_t*)dest;
964     uint8_t lebytes[8];
965     
966     if (!pb_read(stream, lebytes, 8))
967         return false;
968     
969     bytes[0] = lebytes[7];
970     bytes[1] = lebytes[6];
971     bytes[2] = lebytes[5];
972     bytes[3] = lebytes[4];
973     bytes[4] = lebytes[3];
974     bytes[5] = lebytes[2];
975     bytes[6] = lebytes[1];
976     bytes[7] = lebytes[0];
977     return true;
978     #else
979     return pb_read(stream, (uint8_t*)dest, 8);
980     #endif   
981 }
982
983 static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
984 {
985     uint64_t value;
986     if (!pb_decode_varint(stream, &value))
987         return false;
988     
989     switch (field->data_size)
990     {
991         case 1: *(int8_t*)dest = (int8_t)value; break;
992         case 2: *(int16_t*)dest = (int16_t)value; break;
993         case 4: *(int32_t*)dest = (int32_t)value; break;
994         case 8: *(int64_t*)dest = (int64_t)value; break;
995         default: PB_RETURN_ERROR(stream, "invalid data_size");
996     }
997     
998     return true;
999 }
1000
1001 static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1002 {
1003     uint64_t value;
1004     if (!pb_decode_varint(stream, &value))
1005         return false;
1006     
1007     switch (field->data_size)
1008     {
1009         case 4: *(uint32_t*)dest = (uint32_t)value; break;
1010         case 8: *(uint64_t*)dest = value; break;
1011         default: PB_RETURN_ERROR(stream, "invalid data_size");
1012     }
1013     
1014     return true;
1015 }
1016
1017 static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1018 {
1019     int64_t value;
1020     if (!pb_decode_svarint(stream, &value))
1021         return false;
1022     
1023     switch (field->data_size)
1024     {
1025         case 4: *(int32_t*)dest = (int32_t)value; break;
1026         case 8: *(int64_t*)dest = value; break;
1027         default: PB_RETURN_ERROR(stream, "invalid data_size");
1028     }
1029     
1030     return true;
1031 }
1032
1033 static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)
1034 {
1035     UNUSED(field);
1036     return pb_decode_fixed32(stream, dest);
1037 }
1038
1039 static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)
1040 {
1041     UNUSED(field);
1042     return pb_decode_fixed64(stream, dest);
1043 }
1044
1045 static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
1046 {
1047     uint32_t size;
1048     pb_bytes_array_t *bdest;
1049     
1050     if (!pb_decode_varint32(stream, &size))
1051         return false;
1052     
1053     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1054     {
1055 #ifndef PB_ENABLE_MALLOC
1056         PB_RETURN_ERROR(stream, "no malloc support");
1057 #else
1058         if (!allocate_field(stream, dest, PB_BYTES_ARRAY_T_ALLOCSIZE(size), 1))
1059             return false;
1060         bdest = *(pb_bytes_array_t**)dest;
1061 #endif
1062     }
1063     else
1064     {
1065         if (PB_BYTES_ARRAY_T_ALLOCSIZE(size) > field->data_size)
1066             PB_RETURN_ERROR(stream, "bytes overflow");
1067         bdest = (pb_bytes_array_t*)dest;
1068     }
1069     
1070     if (size > PB_SIZE_MAX)
1071     {
1072         PB_RETURN_ERROR(stream, "bytes overflow");
1073     }
1074
1075     bdest->size = (pb_size_t)size;
1076     return pb_read(stream, bdest->bytes, size);
1077 }
1078
1079 static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
1080 {
1081     uint32_t size;
1082     size_t alloc_size;
1083     bool status;
1084     if (!pb_decode_varint32(stream, &size))
1085         return false;
1086     
1087     /* Space for null terminator */
1088     alloc_size = size + 1;
1089     
1090     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1091     {
1092 #ifndef PB_ENABLE_MALLOC
1093         PB_RETURN_ERROR(stream, "no malloc support");
1094 #else
1095         if (!allocate_field(stream, dest, alloc_size, 1))
1096             return false;
1097         dest = *(void**)dest;
1098 #endif
1099     }
1100     else
1101     {
1102         if (alloc_size > field->data_size)
1103             PB_RETURN_ERROR(stream, "string overflow");
1104     }
1105     
1106     status = pb_read(stream, (uint8_t*)dest, size);
1107     *((uint8_t*)dest + size) = 0;
1108     return status;
1109 }
1110
1111 static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
1112 {
1113     bool status;
1114     pb_istream_t substream;
1115     const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;
1116     
1117     if (!pb_make_string_substream(stream, &substream))
1118         return false;
1119     
1120     if (field->ptr == NULL)
1121         PB_RETURN_ERROR(stream, "invalid field descriptor");
1122     
1123     /* New array entries need to be initialized, while required and optional
1124      * submessages have already been initialized in the top-level pb_decode. */
1125     if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
1126         status = pb_decode(&substream, submsg_fields, dest);
1127     else
1128         status = pb_decode_noinit(&substream, submsg_fields, dest);
1129     
1130     pb_close_string_substream(stream, &substream);
1131     return status;
1132 }