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