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