Implement support for oneofs (C unions).
[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         {
752             /* Set array count to 0, no need to initialize contents. */
753             *(pb_size_t*)iter->pSize = 0;
754             init_data = false;
755         }
756         
757         if (init_data)
758         {
759             if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE)
760             {
761                 /* Initialize submessage to defaults */
762                 pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, iter->pData);
763             }
764             else if (iter->pos->ptr != NULL)
765             {
766                 /* Initialize to default value */
767                 memcpy(iter->pData, iter->pos->ptr, iter->pos->data_size);
768             }
769             else
770             {
771                 /* Initialize to zeros */
772                 memset(iter->pData, 0, iter->pos->data_size);
773             }
774         }
775     }
776     else if (PB_ATYPE(type) == PB_ATYPE_POINTER)
777     {
778         /* Initialize the pointer to NULL. */
779         *(void**)iter->pData = NULL;
780         
781         /* Initialize array count to 0. */
782         if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
783         {
784             *(pb_size_t*)iter->pSize = 0;
785         }
786     }
787     else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
788     {
789         /* Don't overwrite callback */
790     }
791 }
792
793 static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct)
794 {
795     pb_field_iter_t iter;
796
797     if (!pb_field_iter_begin(&iter, fields, dest_struct))
798         return; /* Empty message type */
799     
800     do
801     {
802         pb_field_set_to_default(&iter);
803     } while (pb_field_iter_next(&iter));
804 }
805
806 /*********************
807  * Decode all fields *
808  *********************/
809
810 bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
811 {
812     uint8_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 7) / 8] = {0, 0, 0, 0, 0, 0, 0, 0};
813     uint32_t extension_range_start = 0;
814     pb_field_iter_t iter;
815     
816     /* Return value ignored, as empty message types will be correctly handled by
817      * pb_field_iter_find() anyway. */
818     (void)pb_field_iter_begin(&iter, fields, dest_struct);
819     
820     while (stream->bytes_left)
821     {
822         uint32_t tag;
823         pb_wire_type_t wire_type;
824         bool eof;
825         
826         if (!pb_decode_tag(stream, &wire_type, &tag, &eof))
827         {
828             if (eof)
829                 break;
830             else
831                 return false;
832         }
833         
834         if (!pb_field_iter_find(&iter, tag))
835         {
836             /* No match found, check if it matches an extension. */
837             if (tag >= extension_range_start)
838             {
839                 if (!find_extension_field(&iter))
840                     extension_range_start = (uint32_t)-1;
841                 else
842                     extension_range_start = iter.pos->tag;
843                 
844                 if (tag >= extension_range_start)
845                 {
846                     size_t pos = stream->bytes_left;
847                 
848                     if (!decode_extension(stream, tag, wire_type, &iter))
849                         return false;
850                     
851                     if (pos != stream->bytes_left)
852                     {
853                         /* The field was handled */
854                         continue;                    
855                     }
856                 }
857             }
858         
859             /* No match found, skip data */
860             if (!pb_skip_field(stream, wire_type))
861                 return false;
862             continue;
863         }
864         
865         if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED
866             && iter.required_field_index < PB_MAX_REQUIRED_FIELDS)
867         {
868             fields_seen[iter.required_field_index >> 3] |= (uint8_t)(1 << (iter.required_field_index & 7));
869         }
870             
871         if (!decode_field(stream, wire_type, &iter))
872             return false;
873     }
874     
875     /* Check that all required fields were present. */
876     {
877         /* First figure out the number of required fields by
878          * seeking to the end of the field array. Usually we
879          * are already close to end after decoding.
880          */
881         unsigned req_field_count;
882         pb_type_t last_type;
883         unsigned i;
884         do {
885             req_field_count = iter.required_field_index;
886             last_type = iter.pos->type;
887         } while (pb_field_iter_next(&iter));
888         
889         /* Fixup if last field was also required. */
890         if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0)
891             req_field_count++;
892         
893         /* Check the whole bytes */
894         for (i = 0; i < (req_field_count >> 3); i++)
895         {
896             if (fields_seen[i] != 0xFF)
897                 PB_RETURN_ERROR(stream, "missing required field");
898         }
899         
900         /* Check the remaining bits */
901         if (fields_seen[req_field_count >> 3] != (0xFF >> (8 - (req_field_count & 7))))
902             PB_RETURN_ERROR(stream, "missing required field");
903     }
904     
905     return true;
906 }
907
908 bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
909 {
910     bool status;
911     pb_message_set_to_defaults(fields, dest_struct);
912     status = pb_decode_noinit(stream, fields, dest_struct);
913     
914 #ifdef PB_ENABLE_MALLOC
915     if (!status)
916         pb_release(fields, dest_struct);
917 #endif
918     
919     return status;
920 }
921
922 bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
923 {
924     pb_istream_t substream;
925     bool status;
926     
927     if (!pb_make_string_substream(stream, &substream))
928         return false;
929     
930     status = pb_decode(&substream, fields, dest_struct);
931     pb_close_string_substream(stream, &substream);
932     return status;
933 }
934
935 #ifdef PB_ENABLE_MALLOC
936 static void pb_release_single_field(const pb_field_iter_t *iter)
937 {
938     pb_type_t type;
939     type = iter->pos->type;
940
941     /* Release anything contained inside an extension or submsg.
942      * This has to be done even if the submsg itself is statically
943      * allocated. */
944     if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
945     {
946         /* Release fields from all extensions in the linked list */
947         pb_extension_t *ext = *(pb_extension_t**)iter->pData;
948         while (ext != NULL)
949         {
950             pb_field_iter_t ext_iter;
951             iter_from_extension(&ext_iter, ext);
952             pb_release_single_field(&ext_iter);
953             ext = ext->next;
954         }
955     }
956     else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)
957     {
958         /* Release fields in submessage or submsg array */
959         void *pItem = iter->pData;
960         pb_size_t count = 1;
961         
962         if (PB_ATYPE(type) == PB_ATYPE_POINTER)
963         {
964             pItem = *(void**)iter->pData;
965         }
966         
967         if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
968         {
969             count = *(pb_size_t*)iter->pSize;
970         }
971         
972         if (pItem)
973         {
974             while (count--)
975             {
976                 pb_release((const pb_field_t*)iter->pos->ptr, pItem);
977                 pItem = (uint8_t*)pItem + iter->pos->data_size;
978             }
979         }
980     }
981     
982     if (PB_ATYPE(type) == PB_ATYPE_POINTER)
983     {
984         if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&
985             (PB_LTYPE(type) == PB_LTYPE_STRING ||
986              PB_LTYPE(type) == PB_LTYPE_BYTES))
987         {
988             /* Release entries in repeated string or bytes array */
989             void **pItem = *(void***)iter->pData;
990             pb_size_t count = *(pb_size_t*)iter->pSize;
991             while (count--)
992             {
993                 pb_free(*pItem);
994                 *pItem++ = NULL;
995             }
996         }
997         
998         if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
999         {
1000             /* We are going to release the array, so set the size to 0 */
1001             *(pb_size_t*)iter->pSize = 0;
1002         }
1003         
1004         /* Release main item */
1005         pb_free(*(void**)iter->pData);
1006         *(void**)iter->pData = NULL;
1007     }
1008 }
1009
1010 void pb_release(const pb_field_t fields[], void *dest_struct)
1011 {
1012     pb_field_iter_t iter;
1013     
1014     if (!pb_field_iter_begin(&iter, fields, dest_struct))
1015         return; /* Empty message type */
1016     
1017     do
1018     {
1019         pb_release_single_field(&iter);
1020     } while (pb_field_iter_next(&iter));
1021 }
1022 #endif
1023
1024 /* Field decoders */
1025
1026 bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest)
1027 {
1028     uint64_t value;
1029     if (!pb_decode_varint(stream, &value))
1030         return false;
1031     
1032     if (value & 1)
1033         *dest = (int64_t)(~(value >> 1));
1034     else
1035         *dest = (int64_t)(value >> 1);
1036     
1037     return true;
1038 }
1039
1040 bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
1041 {
1042     #ifdef __BIG_ENDIAN__
1043     uint8_t *bytes = (uint8_t*)dest;
1044     uint8_t lebytes[4];
1045     
1046     if (!pb_read(stream, lebytes, 4))
1047         return false;
1048     
1049     bytes[0] = lebytes[3];
1050     bytes[1] = lebytes[2];
1051     bytes[2] = lebytes[1];
1052     bytes[3] = lebytes[0];
1053     return true;
1054     #else
1055     return pb_read(stream, (uint8_t*)dest, 4);
1056     #endif   
1057 }
1058
1059 bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
1060 {
1061     #ifdef __BIG_ENDIAN__
1062     uint8_t *bytes = (uint8_t*)dest;
1063     uint8_t lebytes[8];
1064     
1065     if (!pb_read(stream, lebytes, 8))
1066         return false;
1067     
1068     bytes[0] = lebytes[7];
1069     bytes[1] = lebytes[6];
1070     bytes[2] = lebytes[5];
1071     bytes[3] = lebytes[4];
1072     bytes[4] = lebytes[3];
1073     bytes[5] = lebytes[2];
1074     bytes[6] = lebytes[1];
1075     bytes[7] = lebytes[0];
1076     return true;
1077     #else
1078     return pb_read(stream, (uint8_t*)dest, 8);
1079     #endif   
1080 }
1081
1082 static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1083 {
1084     uint64_t value;
1085     int64_t svalue;
1086     int64_t clamped;
1087     if (!pb_decode_varint(stream, &value))
1088         return false;
1089     
1090     /* See issue 97: Google's C++ protobuf allows negative varint values to
1091      * be cast as int32_t, instead of the int64_t that should be used when
1092      * encoding. Previous nanopb versions had a bug in encoding. In order to
1093      * not break decoding of such messages, we cast <=32 bit fields to
1094      * int32_t first to get the sign correct.
1095      */
1096     if (field->data_size == 8)
1097         svalue = (int64_t)value;
1098     else
1099         svalue = (int32_t)value;
1100
1101     switch (field->data_size)
1102     {
1103         case 1: clamped = *(int8_t*)dest = (int8_t)svalue; break;
1104         case 2: clamped = *(int16_t*)dest = (int16_t)svalue; break;
1105         case 4: clamped = *(int32_t*)dest = (int32_t)svalue; break;
1106         case 8: clamped = *(int64_t*)dest = svalue; break;
1107         default: PB_RETURN_ERROR(stream, "invalid data_size");
1108     }
1109
1110     if (clamped != svalue)
1111         PB_RETURN_ERROR(stream, "integer too large");
1112     
1113     return true;
1114 }
1115
1116 static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1117 {
1118     uint64_t value, clamped;
1119     if (!pb_decode_varint(stream, &value))
1120         return false;
1121     
1122     switch (field->data_size)
1123     {
1124         case 1: clamped = *(uint8_t*)dest = (uint8_t)value; break;
1125         case 2: clamped = *(uint16_t*)dest = (uint16_t)value; break;
1126         case 4: clamped = *(uint32_t*)dest = (uint32_t)value; break;
1127         case 8: clamped = *(uint64_t*)dest = value; break;
1128         default: PB_RETURN_ERROR(stream, "invalid data_size");
1129     }
1130     
1131     if (clamped != value)
1132         PB_RETURN_ERROR(stream, "integer too large");
1133
1134     return true;
1135 }
1136
1137 static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1138 {
1139     int64_t value, clamped;
1140     if (!pb_decode_svarint(stream, &value))
1141         return false;
1142     
1143     switch (field->data_size)
1144     {
1145         case 1: clamped = *(int8_t*)dest = (int8_t)value; break;
1146         case 2: clamped = *(int16_t*)dest = (int16_t)value; break;
1147         case 4: clamped = *(int32_t*)dest = (int32_t)value; break;
1148         case 8: clamped = *(int64_t*)dest = value; break;
1149         default: PB_RETURN_ERROR(stream, "invalid data_size");
1150     }
1151
1152     if (clamped != value)
1153         PB_RETURN_ERROR(stream, "integer too large");
1154     
1155     return true;
1156 }
1157
1158 static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)
1159 {
1160     PB_UNUSED(field);
1161     return pb_decode_fixed32(stream, dest);
1162 }
1163
1164 static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)
1165 {
1166     PB_UNUSED(field);
1167     return pb_decode_fixed64(stream, dest);
1168 }
1169
1170 static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
1171 {
1172     uint32_t size;
1173     size_t alloc_size;
1174     pb_bytes_array_t *bdest;
1175     
1176     if (!pb_decode_varint32(stream, &size))
1177         return false;
1178     
1179     if (size > PB_SIZE_MAX)
1180         PB_RETURN_ERROR(stream, "bytes overflow");
1181     
1182     alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size);
1183     if (size > alloc_size)
1184         PB_RETURN_ERROR(stream, "size too large");
1185     
1186     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1187     {
1188 #ifndef PB_ENABLE_MALLOC
1189         PB_RETURN_ERROR(stream, "no malloc support");
1190 #else
1191         if (!allocate_field(stream, dest, alloc_size, 1))
1192             return false;
1193         bdest = *(pb_bytes_array_t**)dest;
1194 #endif
1195     }
1196     else
1197     {
1198         if (alloc_size > field->data_size)
1199             PB_RETURN_ERROR(stream, "bytes overflow");
1200         bdest = (pb_bytes_array_t*)dest;
1201     }
1202
1203     bdest->size = (pb_size_t)size;
1204     return pb_read(stream, bdest->bytes, size);
1205 }
1206
1207 static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
1208 {
1209     uint32_t size;
1210     size_t alloc_size;
1211     bool status;
1212     if (!pb_decode_varint32(stream, &size))
1213         return false;
1214     
1215     /* Space for null terminator */
1216     alloc_size = size + 1;
1217     
1218     if (alloc_size < size)
1219         PB_RETURN_ERROR(stream, "size too large");
1220     
1221     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1222     {
1223 #ifndef PB_ENABLE_MALLOC
1224         PB_RETURN_ERROR(stream, "no malloc support");
1225 #else
1226         if (!allocate_field(stream, dest, alloc_size, 1))
1227             return false;
1228         dest = *(void**)dest;
1229 #endif
1230     }
1231     else
1232     {
1233         if (alloc_size > field->data_size)
1234             PB_RETURN_ERROR(stream, "string overflow");
1235     }
1236     
1237     status = pb_read(stream, (uint8_t*)dest, size);
1238     *((uint8_t*)dest + size) = 0;
1239     return status;
1240 }
1241
1242 static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
1243 {
1244     bool status;
1245     pb_istream_t substream;
1246     const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;
1247     
1248     if (!pb_make_string_substream(stream, &substream))
1249         return false;
1250     
1251     if (field->ptr == NULL)
1252         PB_RETURN_ERROR(stream, "invalid field descriptor");
1253     
1254     /* New array entries need to be initialized, while required and optional
1255      * submessages have already been initialized in the top-level pb_decode. */
1256     if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
1257         status = pb_decode(&substream, submsg_fields, dest);
1258     else
1259         status = pb_decode_noinit(&substream, submsg_fields, dest);
1260     
1261     pb_close_string_substream(stream, &substream);
1262     return status;
1263 }