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