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