Add 'CAN-binder/libs/nanopb/' from commit '278ffb890e3d8722e4c7d824baaf221a1e375fc4'
[apps/agl-service-can-low-level.git] / CAN-binder / libs / nanopb / 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 read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size);
28 static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
29 static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
30 static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
31 static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension);
32 static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type);
33 static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter);
34 static bool checkreturn find_extension_field(pb_field_iter_t *iter);
35 static void pb_field_set_to_default(pb_field_iter_t *iter);
36 static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct);
37 static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest);
38 static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
39 static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
40 static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest);
41 static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest);
42 static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest);
43 static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest);
44 static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest);
45 static bool checkreturn pb_dec_fixed_length_bytes(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_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 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 bool checkreturn pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream)
338 {
339     if (substream->bytes_left) {
340         if (!pb_read(substream, NULL, substream->bytes_left))
341             return false;
342     }
343
344     stream->state = substream->state;
345
346 #ifndef PB_NO_ERRMSG
347     stream->errmsg = substream->errmsg;
348 #endif
349     return true;
350 }
351
352 /*************************
353  * Decode a single field *
354  *************************/
355
356 static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
357 {
358     pb_type_t type;
359     pb_decoder_t func;
360     
361     type = iter->pos->type;
362     func = PB_DECODERS[PB_LTYPE(type)];
363
364     switch (PB_HTYPE(type))
365     {
366         case PB_HTYPE_REQUIRED:
367             return func(stream, iter->pos, iter->pData);
368             
369         case PB_HTYPE_OPTIONAL:
370             if (iter->pSize != iter->pData)
371                 *(bool*)iter->pSize = true;
372             return func(stream, iter->pos, iter->pData);
373     
374         case PB_HTYPE_REPEATED:
375             if (wire_type == PB_WT_STRING
376                 && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
377             {
378                 /* Packed array */
379                 bool status = true;
380                 pb_size_t *size = (pb_size_t*)iter->pSize;
381                 pb_istream_t substream;
382                 if (!pb_make_string_substream(stream, &substream))
383                     return false;
384                 
385                 while (substream.bytes_left > 0 && *size < iter->pos->array_size)
386                 {
387                     void *pItem = (char*)iter->pData + iter->pos->data_size * (*size);
388                     if (!func(&substream, iter->pos, pItem))
389                     {
390                         status = false;
391                         break;
392                     }
393                     (*size)++;
394                 }
395
396                 if (substream.bytes_left != 0)
397                     PB_RETURN_ERROR(stream, "array overflow");
398                 if (!pb_close_string_substream(stream, &substream))
399                     return false;
400
401                 return status;
402             }
403             else
404             {
405                 /* Repeated field */
406                 pb_size_t *size = (pb_size_t*)iter->pSize;
407                 void *pItem = (char*)iter->pData + iter->pos->data_size * (*size);
408                 if (*size >= iter->pos->array_size)
409                     PB_RETURN_ERROR(stream, "array overflow");
410                 
411                 (*size)++;
412                 return func(stream, iter->pos, pItem);
413             }
414
415         case PB_HTYPE_ONEOF:
416             *(pb_size_t*)iter->pSize = iter->pos->tag;
417             if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)
418             {
419                 /* We memset to zero so that any callbacks are set to NULL.
420                  * Then set any default values. */
421                 memset(iter->pData, 0, iter->pos->data_size);
422                 pb_message_set_to_defaults((const pb_field_t*)iter->pos->ptr, iter->pData);
423             }
424             return func(stream, iter->pos, iter->pData);
425
426         default:
427             PB_RETURN_ERROR(stream, "invalid field type");
428     }
429 }
430
431 #ifdef PB_ENABLE_MALLOC
432 /* Allocate storage for the field and store the pointer at iter->pData.
433  * array_size is the number of entries to reserve in an array.
434  * Zero size is not allowed, use pb_free() for releasing.
435  */
436 static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size)
437 {    
438     void *ptr = *(void**)pData;
439     
440     if (data_size == 0 || array_size == 0)
441         PB_RETURN_ERROR(stream, "invalid size");
442     
443     /* Check for multiplication overflows.
444      * This code avoids the costly division if the sizes are small enough.
445      * Multiplication is safe as long as only half of bits are set
446      * in either multiplicand.
447      */
448     {
449         const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4);
450         if (data_size >= check_limit || array_size >= check_limit)
451         {
452             const size_t size_max = (size_t)-1;
453             if (size_max / array_size < data_size)
454             {
455                 PB_RETURN_ERROR(stream, "size too large");
456             }
457         }
458     }
459     
460     /* Allocate new or expand previous allocation */
461     /* Note: on failure the old pointer will remain in the structure,
462      * the message must be freed by caller also on error return. */
463     ptr = pb_realloc(ptr, array_size * data_size);
464     if (ptr == NULL)
465         PB_RETURN_ERROR(stream, "realloc failed");
466     
467     *(void**)pData = ptr;
468     return true;
469 }
470
471 /* Clear a newly allocated item in case it contains a pointer, or is a submessage. */
472 static void initialize_pointer_field(void *pItem, pb_field_iter_t *iter)
473 {
474     if (PB_LTYPE(iter->pos->type) == PB_LTYPE_STRING ||
475         PB_LTYPE(iter->pos->type) == PB_LTYPE_BYTES)
476     {
477         *(void**)pItem = NULL;
478     }
479     else if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE)
480     {
481         pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, pItem);
482     }
483 }
484 #endif
485
486 static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
487 {
488 #ifndef PB_ENABLE_MALLOC
489     PB_UNUSED(wire_type);
490     PB_UNUSED(iter);
491     PB_RETURN_ERROR(stream, "no malloc support");
492 #else
493     pb_type_t type;
494     pb_decoder_t func;
495     
496     type = iter->pos->type;
497     func = PB_DECODERS[PB_LTYPE(type)];
498     
499     switch (PB_HTYPE(type))
500     {
501         case PB_HTYPE_REQUIRED:
502         case PB_HTYPE_OPTIONAL:
503         case PB_HTYPE_ONEOF:
504             if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&
505                 *(void**)iter->pData != NULL)
506             {
507                 /* Duplicate field, have to release the old allocation first. */
508                 pb_release_single_field(iter);
509             }
510         
511             if (PB_HTYPE(type) == PB_HTYPE_ONEOF)
512             {
513                 *(pb_size_t*)iter->pSize = iter->pos->tag;
514             }
515
516             if (PB_LTYPE(type) == PB_LTYPE_STRING ||
517                 PB_LTYPE(type) == PB_LTYPE_BYTES)
518             {
519                 return func(stream, iter->pos, iter->pData);
520             }
521             else
522             {
523                 if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))
524                     return false;
525                 
526                 initialize_pointer_field(*(void**)iter->pData, iter);
527                 return func(stream, iter->pos, *(void**)iter->pData);
528             }
529     
530         case PB_HTYPE_REPEATED:
531             if (wire_type == PB_WT_STRING
532                 && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
533             {
534                 /* Packed array, multiple items come in at once. */
535                 bool status = true;
536                 pb_size_t *size = (pb_size_t*)iter->pSize;
537                 size_t allocated_size = *size;
538                 void *pItem;
539                 pb_istream_t substream;
540                 
541                 if (!pb_make_string_substream(stream, &substream))
542                     return false;
543                 
544                 while (substream.bytes_left)
545                 {
546                     if ((size_t)*size + 1 > allocated_size)
547                     {
548                         /* Allocate more storage. This tries to guess the
549                          * number of remaining entries. Round the division
550                          * upwards. */
551                         allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1;
552                         
553                         if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))
554                         {
555                             status = false;
556                             break;
557                         }
558                     }
559
560                     /* Decode the array entry */
561                     pItem = *(char**)iter->pData + iter->pos->data_size * (*size);
562                     initialize_pointer_field(pItem, iter);
563                     if (!func(&substream, iter->pos, pItem))
564                     {
565                         status = false;
566                         break;
567                     }
568                     
569                     if (*size == PB_SIZE_MAX)
570                     {
571 #ifndef PB_NO_ERRMSG
572                         stream->errmsg = "too many array entries";
573 #endif
574                         status = false;
575                         break;
576                     }
577                     
578                     (*size)++;
579                 }
580                 if (!pb_close_string_substream(stream, &substream))
581                     return false;
582                 
583                 return status;
584             }
585             else
586             {
587                 /* Normal repeated field, i.e. only one item at a time. */
588                 pb_size_t *size = (pb_size_t*)iter->pSize;
589                 void *pItem;
590                 
591                 if (*size == PB_SIZE_MAX)
592                     PB_RETURN_ERROR(stream, "too many array entries");
593                 
594                 (*size)++;
595                 if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size))
596                     return false;
597             
598                 pItem = *(char**)iter->pData + iter->pos->data_size * (*size - 1);
599                 initialize_pointer_field(pItem, iter);
600                 return func(stream, iter->pos, pItem);
601             }
602
603         default:
604             PB_RETURN_ERROR(stream, "invalid field type");
605     }
606 #endif
607 }
608
609 static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
610 {
611     pb_callback_t *pCallback = (pb_callback_t*)iter->pData;
612     
613 #ifdef PB_OLD_CALLBACK_STYLE
614     void *arg = pCallback->arg;
615 #else
616     void **arg = &(pCallback->arg);
617 #endif
618     
619     if (pCallback->funcs.decode == NULL)
620         return pb_skip_field(stream, wire_type);
621     
622     if (wire_type == PB_WT_STRING)
623     {
624         pb_istream_t substream;
625         
626         if (!pb_make_string_substream(stream, &substream))
627             return false;
628         
629         do
630         {
631             if (!pCallback->funcs.decode(&substream, iter->pos, arg))
632                 PB_RETURN_ERROR(stream, "callback failed");
633         } while (substream.bytes_left);
634         
635         if (!pb_close_string_substream(stream, &substream))
636             return false;
637
638         return true;
639     }
640     else
641     {
642         /* Copy the single scalar value to stack.
643          * This is required so that we can limit the stream length,
644          * which in turn allows to use same callback for packed and
645          * not-packed fields. */
646         pb_istream_t substream;
647         pb_byte_t buffer[10];
648         size_t size = sizeof(buffer);
649         
650         if (!read_raw_value(stream, wire_type, buffer, &size))
651             return false;
652         substream = pb_istream_from_buffer(buffer, size);
653         
654         return pCallback->funcs.decode(&substream, iter->pos, arg);
655     }
656 }
657
658 static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
659 {
660 #ifdef PB_ENABLE_MALLOC
661     /* When decoding an oneof field, check if there is old data that must be
662      * released first. */
663     if (PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF)
664     {
665         if (!pb_release_union_field(stream, iter))
666             return false;
667     }
668 #endif
669
670     switch (PB_ATYPE(iter->pos->type))
671     {
672         case PB_ATYPE_STATIC:
673             return decode_static_field(stream, wire_type, iter);
674         
675         case PB_ATYPE_POINTER:
676             return decode_pointer_field(stream, wire_type, iter);
677         
678         case PB_ATYPE_CALLBACK:
679             return decode_callback_field(stream, wire_type, iter);
680         
681         default:
682             PB_RETURN_ERROR(stream, "invalid field type");
683     }
684 }
685
686 static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension)
687 {
688     /* Fake a field iterator for the extension field.
689      * It is not actually safe to advance this iterator, but decode_field
690      * will not even try to. */
691     const pb_field_t *field = (const pb_field_t*)extension->type->arg;
692     (void)pb_field_iter_begin(iter, field, extension->dest);
693     iter->pData = extension->dest;
694     iter->pSize = &extension->found;
695     
696     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
697     {
698         /* For pointer extensions, the pointer is stored directly
699          * in the extension structure. This avoids having an extra
700          * indirection. */
701         iter->pData = &extension->dest;
702     }
703 }
704
705 /* Default handler for extension fields. Expects a pb_field_t structure
706  * in extension->type->arg. */
707 static bool checkreturn default_extension_decoder(pb_istream_t *stream,
708     pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type)
709 {
710     const pb_field_t *field = (const pb_field_t*)extension->type->arg;
711     pb_field_iter_t iter;
712     
713     if (field->tag != tag)
714         return true;
715     
716     iter_from_extension(&iter, extension);
717     extension->found = true;
718     return decode_field(stream, wire_type, &iter);
719 }
720
721 /* Try to decode an unknown field as an extension field. Tries each extension
722  * decoder in turn, until one of them handles the field or loop ends. */
723 static bool checkreturn decode_extension(pb_istream_t *stream,
724     uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter)
725 {
726     pb_extension_t *extension = *(pb_extension_t* const *)iter->pData;
727     size_t pos = stream->bytes_left;
728     
729     while (extension != NULL && pos == stream->bytes_left)
730     {
731         bool status;
732         if (extension->type->decode)
733             status = extension->type->decode(stream, extension, tag, wire_type);
734         else
735             status = default_extension_decoder(stream, extension, tag, wire_type);
736
737         if (!status)
738             return false;
739         
740         extension = extension->next;
741     }
742     
743     return true;
744 }
745
746 /* Step through the iterator until an extension field is found or until all
747  * entries have been checked. There can be only one extension field per
748  * message. Returns false if no extension field is found. */
749 static bool checkreturn find_extension_field(pb_field_iter_t *iter)
750 {
751     const pb_field_t *start = iter->pos;
752     
753     do {
754         if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION)
755             return true;
756         (void)pb_field_iter_next(iter);
757     } while (iter->pos != start);
758     
759     return false;
760 }
761
762 /* Initialize message fields to default values, recursively */
763 static void pb_field_set_to_default(pb_field_iter_t *iter)
764 {
765     pb_type_t type;
766     type = iter->pos->type;
767     
768     if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
769     {
770         pb_extension_t *ext = *(pb_extension_t* const *)iter->pData;
771         while (ext != NULL)
772         {
773             pb_field_iter_t ext_iter;
774             ext->found = false;
775             iter_from_extension(&ext_iter, ext);
776             pb_field_set_to_default(&ext_iter);
777             ext = ext->next;
778         }
779     }
780     else if (PB_ATYPE(type) == PB_ATYPE_STATIC)
781     {
782         bool init_data = true;
783         if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL && iter->pSize != iter->pData)
784         {
785             /* Set has_field to false. Still initialize the optional field
786              * itself also. */
787             *(bool*)iter->pSize = false;
788         }
789         else if (PB_HTYPE(type) == PB_HTYPE_REPEATED ||
790                  PB_HTYPE(type) == PB_HTYPE_ONEOF)
791         {
792             /* REPEATED: Set array count to 0, no need to initialize contents.
793                ONEOF: Set which_field to 0. */
794             *(pb_size_t*)iter->pSize = 0;
795             init_data = false;
796         }
797
798         if (init_data)
799         {
800             if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE)
801             {
802                 /* Initialize submessage to defaults */
803                 pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, iter->pData);
804             }
805             else if (iter->pos->ptr != NULL)
806             {
807                 /* Initialize to default value */
808                 memcpy(iter->pData, iter->pos->ptr, iter->pos->data_size);
809             }
810             else
811             {
812                 /* Initialize to zeros */
813                 memset(iter->pData, 0, iter->pos->data_size);
814             }
815         }
816     }
817     else if (PB_ATYPE(type) == PB_ATYPE_POINTER)
818     {
819         /* Initialize the pointer to NULL. */
820         *(void**)iter->pData = NULL;
821         
822         /* Initialize array count to 0. */
823         if (PB_HTYPE(type) == PB_HTYPE_REPEATED ||
824             PB_HTYPE(type) == PB_HTYPE_ONEOF)
825         {
826             *(pb_size_t*)iter->pSize = 0;
827         }
828     }
829     else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
830     {
831         /* Don't overwrite callback */
832     }
833 }
834
835 static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct)
836 {
837     pb_field_iter_t iter;
838
839     if (!pb_field_iter_begin(&iter, fields, dest_struct))
840         return; /* Empty message type */
841     
842     do
843     {
844         pb_field_set_to_default(&iter);
845     } while (pb_field_iter_next(&iter));
846 }
847
848 /*********************
849  * Decode all fields *
850  *********************/
851
852 bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
853 {
854     uint32_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 31) / 32] = {0, 0};
855     const uint32_t allbits = ~(uint32_t)0;
856     uint32_t extension_range_start = 0;
857     pb_field_iter_t iter;
858     
859     /* Return value ignored, as empty message types will be correctly handled by
860      * pb_field_iter_find() anyway. */
861     (void)pb_field_iter_begin(&iter, fields, dest_struct);
862     
863     while (stream->bytes_left)
864     {
865         uint32_t tag;
866         pb_wire_type_t wire_type;
867         bool eof;
868         
869         if (!pb_decode_tag(stream, &wire_type, &tag, &eof))
870         {
871             if (eof)
872                 break;
873             else
874                 return false;
875         }
876         
877         if (!pb_field_iter_find(&iter, tag))
878         {
879             /* No match found, check if it matches an extension. */
880             if (tag >= extension_range_start)
881             {
882                 if (!find_extension_field(&iter))
883                     extension_range_start = (uint32_t)-1;
884                 else
885                     extension_range_start = iter.pos->tag;
886                 
887                 if (tag >= extension_range_start)
888                 {
889                     size_t pos = stream->bytes_left;
890                 
891                     if (!decode_extension(stream, tag, wire_type, &iter))
892                         return false;
893                     
894                     if (pos != stream->bytes_left)
895                     {
896                         /* The field was handled */
897                         continue;                    
898                     }
899                 }
900             }
901         
902             /* No match found, skip data */
903             if (!pb_skip_field(stream, wire_type))
904                 return false;
905             continue;
906         }
907         
908         if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED
909             && iter.required_field_index < PB_MAX_REQUIRED_FIELDS)
910         {
911             uint32_t tmp = ((uint32_t)1 << (iter.required_field_index & 31));
912             fields_seen[iter.required_field_index >> 5] |= tmp;
913         }
914             
915         if (!decode_field(stream, wire_type, &iter))
916             return false;
917     }
918     
919     /* Check that all required fields were present. */
920     {
921         /* First figure out the number of required fields by
922          * seeking to the end of the field array. Usually we
923          * are already close to end after decoding.
924          */
925         unsigned req_field_count;
926         pb_type_t last_type;
927         unsigned i;
928         do {
929             req_field_count = iter.required_field_index;
930             last_type = iter.pos->type;
931         } while (pb_field_iter_next(&iter));
932         
933         /* Fixup if last field was also required. */
934         if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0)
935             req_field_count++;
936         
937         if (req_field_count > PB_MAX_REQUIRED_FIELDS)
938             req_field_count = PB_MAX_REQUIRED_FIELDS;
939
940         if (req_field_count > 0)
941         {
942             /* Check the whole words */
943             for (i = 0; i < (req_field_count >> 5); i++)
944             {
945                 if (fields_seen[i] != allbits)
946                     PB_RETURN_ERROR(stream, "missing required field");
947             }
948             
949             /* Check the remaining bits (if any) */
950             if ((req_field_count & 31) != 0)
951             {
952                 if (fields_seen[req_field_count >> 5] !=
953                     (allbits >> (32 - (req_field_count & 31))))
954                 {
955                     PB_RETURN_ERROR(stream, "missing required field");
956                 }
957             }
958         }
959     }
960     
961     return true;
962 }
963
964 bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
965 {
966     bool status;
967     pb_message_set_to_defaults(fields, dest_struct);
968     status = pb_decode_noinit(stream, fields, dest_struct);
969     
970 #ifdef PB_ENABLE_MALLOC
971     if (!status)
972         pb_release(fields, dest_struct);
973 #endif
974     
975     return status;
976 }
977
978 bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
979 {
980     pb_istream_t substream;
981     bool status;
982     
983     if (!pb_make_string_substream(stream, &substream))
984         return false;
985     
986     status = pb_decode(&substream, fields, dest_struct);
987
988     if (!pb_close_string_substream(stream, &substream))
989         return false;
990     return status;
991 }
992
993 #ifdef PB_ENABLE_MALLOC
994 /* Given an oneof field, if there has already been a field inside this oneof,
995  * release it before overwriting with a different one. */
996 static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter)
997 {
998     pb_size_t old_tag = *(pb_size_t*)iter->pSize; /* Previous which_ value */
999     pb_size_t new_tag = iter->pos->tag; /* New which_ value */
1000
1001     if (old_tag == 0)
1002         return true; /* Ok, no old data in union */
1003
1004     if (old_tag == new_tag)
1005         return true; /* Ok, old data is of same type => merge */
1006
1007     /* Release old data. The find can fail if the message struct contains
1008      * invalid data. */
1009     if (!pb_field_iter_find(iter, old_tag))
1010         PB_RETURN_ERROR(stream, "invalid union tag");
1011
1012     pb_release_single_field(iter);
1013
1014     /* Restore iterator to where it should be.
1015      * This shouldn't fail unless the pb_field_t structure is corrupted. */
1016     if (!pb_field_iter_find(iter, new_tag))
1017         PB_RETURN_ERROR(stream, "iterator error");
1018     
1019     return true;
1020 }
1021
1022 static void pb_release_single_field(const pb_field_iter_t *iter)
1023 {
1024     pb_type_t type;
1025     type = iter->pos->type;
1026
1027     if (PB_HTYPE(type) == PB_HTYPE_ONEOF)
1028     {
1029         if (*(pb_size_t*)iter->pSize != iter->pos->tag)
1030             return; /* This is not the current field in the union */
1031     }
1032
1033     /* Release anything contained inside an extension or submsg.
1034      * This has to be done even if the submsg itself is statically
1035      * allocated. */
1036     if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
1037     {
1038         /* Release fields from all extensions in the linked list */
1039         pb_extension_t *ext = *(pb_extension_t**)iter->pData;
1040         while (ext != NULL)
1041         {
1042             pb_field_iter_t ext_iter;
1043             iter_from_extension(&ext_iter, ext);
1044             pb_release_single_field(&ext_iter);
1045             ext = ext->next;
1046         }
1047     }
1048     else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)
1049     {
1050         /* Release fields in submessage or submsg array */
1051         void *pItem = iter->pData;
1052         pb_size_t count = 1;
1053         
1054         if (PB_ATYPE(type) == PB_ATYPE_POINTER)
1055         {
1056             pItem = *(void**)iter->pData;
1057         }
1058         
1059         if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
1060         {
1061             count = *(pb_size_t*)iter->pSize;
1062
1063             if (PB_ATYPE(type) == PB_ATYPE_STATIC && count > iter->pos->array_size)
1064             {
1065                 /* Protect against corrupted _count fields */
1066                 count = iter->pos->array_size;
1067             }
1068         }
1069         
1070         if (pItem)
1071         {
1072             while (count--)
1073             {
1074                 pb_release((const pb_field_t*)iter->pos->ptr, pItem);
1075                 pItem = (char*)pItem + iter->pos->data_size;
1076             }
1077         }
1078     }
1079     
1080     if (PB_ATYPE(type) == PB_ATYPE_POINTER)
1081     {
1082         if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&
1083             (PB_LTYPE(type) == PB_LTYPE_STRING ||
1084              PB_LTYPE(type) == PB_LTYPE_BYTES))
1085         {
1086             /* Release entries in repeated string or bytes array */
1087             void **pItem = *(void***)iter->pData;
1088             pb_size_t count = *(pb_size_t*)iter->pSize;
1089             while (count--)
1090             {
1091                 pb_free(*pItem);
1092                 *pItem++ = NULL;
1093             }
1094         }
1095         
1096         if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
1097         {
1098             /* We are going to release the array, so set the size to 0 */
1099             *(pb_size_t*)iter->pSize = 0;
1100         }
1101         
1102         /* Release main item */
1103         pb_free(*(void**)iter->pData);
1104         *(void**)iter->pData = NULL;
1105     }
1106 }
1107
1108 void pb_release(const pb_field_t fields[], void *dest_struct)
1109 {
1110     pb_field_iter_t iter;
1111     
1112     if (!dest_struct)
1113         return; /* Ignore NULL pointers, similar to free() */
1114
1115     if (!pb_field_iter_begin(&iter, fields, dest_struct))
1116         return; /* Empty message type */
1117     
1118     do
1119     {
1120         pb_release_single_field(&iter);
1121     } while (pb_field_iter_next(&iter));
1122 }
1123 #endif
1124
1125 /* Field decoders */
1126
1127 bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest)
1128 {
1129     uint64_t value;
1130     if (!pb_decode_varint(stream, &value))
1131         return false;
1132     
1133     if (value & 1)
1134         *dest = (int64_t)(~(value >> 1));
1135     else
1136         *dest = (int64_t)(value >> 1);
1137     
1138     return true;
1139 }
1140
1141 bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
1142 {
1143     pb_byte_t bytes[4];
1144
1145     if (!pb_read(stream, bytes, 4))
1146         return false;
1147     
1148     *(uint32_t*)dest = ((uint32_t)bytes[0] << 0) |
1149                        ((uint32_t)bytes[1] << 8) |
1150                        ((uint32_t)bytes[2] << 16) |
1151                        ((uint32_t)bytes[3] << 24);
1152     return true;
1153 }
1154
1155 bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
1156 {
1157     pb_byte_t bytes[8];
1158
1159     if (!pb_read(stream, bytes, 8))
1160         return false;
1161     
1162     *(uint64_t*)dest = ((uint64_t)bytes[0] << 0) |
1163                        ((uint64_t)bytes[1] << 8) |
1164                        ((uint64_t)bytes[2] << 16) |
1165                        ((uint64_t)bytes[3] << 24) |
1166                        ((uint64_t)bytes[4] << 32) |
1167                        ((uint64_t)bytes[5] << 40) |
1168                        ((uint64_t)bytes[6] << 48) |
1169                        ((uint64_t)bytes[7] << 56);
1170     
1171     return true;
1172 }
1173
1174 static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1175 {
1176     uint64_t value;
1177     int64_t svalue;
1178     int64_t clamped;
1179     if (!pb_decode_varint(stream, &value))
1180         return false;
1181     
1182     /* See issue 97: Google's C++ protobuf allows negative varint values to
1183      * be cast as int32_t, instead of the int64_t that should be used when
1184      * encoding. Previous nanopb versions had a bug in encoding. In order to
1185      * not break decoding of such messages, we cast <=32 bit fields to
1186      * int32_t first to get the sign correct.
1187      */
1188     if (field->data_size == sizeof(int64_t))
1189         svalue = (int64_t)value;
1190     else
1191         svalue = (int32_t)value;
1192
1193     /* Cast to the proper field size, while checking for overflows */
1194     if (field->data_size == sizeof(int64_t))
1195         clamped = *(int64_t*)dest = svalue;
1196     else if (field->data_size == sizeof(int32_t))
1197         clamped = *(int32_t*)dest = (int32_t)svalue;
1198     else if (field->data_size == sizeof(int_least16_t))
1199         clamped = *(int_least16_t*)dest = (int_least16_t)svalue;
1200     else if (field->data_size == sizeof(int_least8_t))
1201         clamped = *(int_least8_t*)dest = (int_least8_t)svalue;
1202     else
1203         PB_RETURN_ERROR(stream, "invalid data_size");
1204
1205     if (clamped != svalue)
1206         PB_RETURN_ERROR(stream, "integer too large");
1207     
1208     return true;
1209 }
1210
1211 static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1212 {
1213     uint64_t value, clamped;
1214     if (!pb_decode_varint(stream, &value))
1215         return false;
1216     
1217     /* Cast to the proper field size, while checking for overflows */
1218     if (field->data_size == sizeof(uint64_t))
1219         clamped = *(uint64_t*)dest = value;
1220     else if (field->data_size == sizeof(uint32_t))
1221         clamped = *(uint32_t*)dest = (uint32_t)value;
1222     else if (field->data_size == sizeof(uint_least16_t))
1223         clamped = *(uint_least16_t*)dest = (uint_least16_t)value;
1224     else if (field->data_size == sizeof(uint_least8_t))
1225         clamped = *(uint_least8_t*)dest = (uint_least8_t)value;
1226     else
1227         PB_RETURN_ERROR(stream, "invalid data_size");
1228     
1229     if (clamped != value)
1230         PB_RETURN_ERROR(stream, "integer too large");
1231
1232     return true;
1233 }
1234
1235 static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1236 {
1237     int64_t value, clamped;
1238     if (!pb_decode_svarint(stream, &value))
1239         return false;
1240     
1241     /* Cast to the proper field size, while checking for overflows */
1242     if (field->data_size == sizeof(int64_t))
1243         clamped = *(int64_t*)dest = value;
1244     else if (field->data_size == sizeof(int32_t))
1245         clamped = *(int32_t*)dest = (int32_t)value;
1246     else if (field->data_size == sizeof(int_least16_t))
1247         clamped = *(int_least16_t*)dest = (int_least16_t)value;
1248     else if (field->data_size == sizeof(int_least8_t))
1249         clamped = *(int_least8_t*)dest = (int_least8_t)value;
1250     else
1251         PB_RETURN_ERROR(stream, "invalid data_size");
1252
1253     if (clamped != value)
1254         PB_RETURN_ERROR(stream, "integer too large");
1255     
1256     return true;
1257 }
1258
1259 static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)
1260 {
1261     PB_UNUSED(field);
1262     return pb_decode_fixed32(stream, dest);
1263 }
1264
1265 static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)
1266 {
1267     PB_UNUSED(field);
1268     return pb_decode_fixed64(stream, dest);
1269 }
1270
1271 static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
1272 {
1273     uint32_t size;
1274     size_t alloc_size;
1275     pb_bytes_array_t *bdest;
1276     
1277     if (!pb_decode_varint32(stream, &size))
1278         return false;
1279     
1280     if (size > PB_SIZE_MAX)
1281         PB_RETURN_ERROR(stream, "bytes overflow");
1282     
1283     alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size);
1284     if (size > alloc_size)
1285         PB_RETURN_ERROR(stream, "size too large");
1286     
1287     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1288     {
1289 #ifndef PB_ENABLE_MALLOC
1290         PB_RETURN_ERROR(stream, "no malloc support");
1291 #else
1292         if (!allocate_field(stream, dest, alloc_size, 1))
1293             return false;
1294         bdest = *(pb_bytes_array_t**)dest;
1295 #endif
1296     }
1297     else
1298     {
1299         if (alloc_size > field->data_size)
1300             PB_RETURN_ERROR(stream, "bytes overflow");
1301         bdest = (pb_bytes_array_t*)dest;
1302     }
1303
1304     bdest->size = (pb_size_t)size;
1305     return pb_read(stream, bdest->bytes, size);
1306 }
1307
1308 static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
1309 {
1310     uint32_t size;
1311     size_t alloc_size;
1312     bool status;
1313     if (!pb_decode_varint32(stream, &size))
1314         return false;
1315     
1316     /* Space for null terminator */
1317     alloc_size = size + 1;
1318     
1319     if (alloc_size < size)
1320         PB_RETURN_ERROR(stream, "size too large");
1321     
1322     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1323     {
1324 #ifndef PB_ENABLE_MALLOC
1325         PB_RETURN_ERROR(stream, "no malloc support");
1326 #else
1327         if (!allocate_field(stream, dest, alloc_size, 1))
1328             return false;
1329         dest = *(void**)dest;
1330 #endif
1331     }
1332     else
1333     {
1334         if (alloc_size > field->data_size)
1335             PB_RETURN_ERROR(stream, "string overflow");
1336     }
1337     
1338     status = pb_read(stream, (pb_byte_t*)dest, size);
1339     *((pb_byte_t*)dest + size) = 0;
1340     return status;
1341 }
1342
1343 static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
1344 {
1345     bool status;
1346     pb_istream_t substream;
1347     const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;
1348     
1349     if (!pb_make_string_substream(stream, &substream))
1350         return false;
1351     
1352     if (field->ptr == NULL)
1353         PB_RETURN_ERROR(stream, "invalid field descriptor");
1354     
1355     /* New array entries need to be initialized, while required and optional
1356      * submessages have already been initialized in the top-level pb_decode. */
1357     if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
1358         status = pb_decode(&substream, submsg_fields, dest);
1359     else
1360         status = pb_decode_noinit(&substream, submsg_fields, dest);
1361     
1362     if (!pb_close_string_substream(stream, &substream))
1363         return false;
1364     return status;
1365 }
1366
1367 static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
1368 {
1369     uint32_t size;
1370
1371     if (!pb_decode_varint32(stream, &size))
1372         return false;
1373
1374     if (size > PB_SIZE_MAX)
1375         PB_RETURN_ERROR(stream, "bytes overflow");
1376
1377     if (size == 0)
1378     {
1379         /* As a special case, treat empty bytes string as all zeros for fixed_length_bytes. */
1380         memset(dest, 0, field->data_size);
1381         return true;
1382     }
1383
1384     if (size != field->data_size)
1385         PB_RETURN_ERROR(stream, "incorrect fixed length bytes size");
1386
1387     return pb_read(stream, (pb_byte_t*)dest, field->data_size);
1388 }