added iOS source code
[wl-app.git] / iOS / Pods / 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 > 0)
938         {
939             /* Check the whole words */
940             for (i = 0; i < (req_field_count >> 5); i++)
941             {
942                 if (fields_seen[i] != allbits)
943                     PB_RETURN_ERROR(stream, "missing required field");
944             }
945             
946             /* Check the remaining bits */
947             if (fields_seen[req_field_count >> 5] != (allbits >> (32 - (req_field_count & 31))))
948                 PB_RETURN_ERROR(stream, "missing required field");
949         }
950     }
951     
952     return true;
953 }
954
955 bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
956 {
957     bool status;
958     pb_message_set_to_defaults(fields, dest_struct);
959     status = pb_decode_noinit(stream, fields, dest_struct);
960     
961 #ifdef PB_ENABLE_MALLOC
962     if (!status)
963         pb_release(fields, dest_struct);
964 #endif
965     
966     return status;
967 }
968
969 bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
970 {
971     pb_istream_t substream;
972     bool status;
973     
974     if (!pb_make_string_substream(stream, &substream))
975         return false;
976     
977     status = pb_decode(&substream, fields, dest_struct);
978
979     if (!pb_close_string_substream(stream, &substream))
980         return false;
981     return status;
982 }
983
984 #ifdef PB_ENABLE_MALLOC
985 /* Given an oneof field, if there has already been a field inside this oneof,
986  * release it before overwriting with a different one. */
987 static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter)
988 {
989     pb_size_t old_tag = *(pb_size_t*)iter->pSize; /* Previous which_ value */
990     pb_size_t new_tag = iter->pos->tag; /* New which_ value */
991
992     if (old_tag == 0)
993         return true; /* Ok, no old data in union */
994
995     if (old_tag == new_tag)
996         return true; /* Ok, old data is of same type => merge */
997
998     /* Release old data. The find can fail if the message struct contains
999      * invalid data. */
1000     if (!pb_field_iter_find(iter, old_tag))
1001         PB_RETURN_ERROR(stream, "invalid union tag");
1002
1003     pb_release_single_field(iter);
1004
1005     /* Restore iterator to where it should be.
1006      * This shouldn't fail unless the pb_field_t structure is corrupted. */
1007     if (!pb_field_iter_find(iter, new_tag))
1008         PB_RETURN_ERROR(stream, "iterator error");
1009     
1010     return true;
1011 }
1012
1013 static void pb_release_single_field(const pb_field_iter_t *iter)
1014 {
1015     pb_type_t type;
1016     type = iter->pos->type;
1017
1018     if (PB_HTYPE(type) == PB_HTYPE_ONEOF)
1019     {
1020         if (*(pb_size_t*)iter->pSize != iter->pos->tag)
1021             return; /* This is not the current field in the union */
1022     }
1023
1024     /* Release anything contained inside an extension or submsg.
1025      * This has to be done even if the submsg itself is statically
1026      * allocated. */
1027     if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
1028     {
1029         /* Release fields from all extensions in the linked list */
1030         pb_extension_t *ext = *(pb_extension_t**)iter->pData;
1031         while (ext != NULL)
1032         {
1033             pb_field_iter_t ext_iter;
1034             iter_from_extension(&ext_iter, ext);
1035             pb_release_single_field(&ext_iter);
1036             ext = ext->next;
1037         }
1038     }
1039     else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)
1040     {
1041         /* Release fields in submessage or submsg array */
1042         void *pItem = iter->pData;
1043         pb_size_t count = 1;
1044         
1045         if (PB_ATYPE(type) == PB_ATYPE_POINTER)
1046         {
1047             pItem = *(void**)iter->pData;
1048         }
1049         
1050         if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
1051         {
1052             count = *(pb_size_t*)iter->pSize;
1053
1054             if (PB_ATYPE(type) == PB_ATYPE_STATIC && count > iter->pos->array_size)
1055             {
1056                 /* Protect against corrupted _count fields */
1057                 count = iter->pos->array_size;
1058             }
1059         }
1060         
1061         if (pItem)
1062         {
1063             while (count--)
1064             {
1065                 pb_release((const pb_field_t*)iter->pos->ptr, pItem);
1066                 pItem = (char*)pItem + iter->pos->data_size;
1067             }
1068         }
1069     }
1070     
1071     if (PB_ATYPE(type) == PB_ATYPE_POINTER)
1072     {
1073         if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&
1074             (PB_LTYPE(type) == PB_LTYPE_STRING ||
1075              PB_LTYPE(type) == PB_LTYPE_BYTES))
1076         {
1077             /* Release entries in repeated string or bytes array */
1078             void **pItem = *(void***)iter->pData;
1079             pb_size_t count = *(pb_size_t*)iter->pSize;
1080             while (count--)
1081             {
1082                 pb_free(*pItem);
1083                 *pItem++ = NULL;
1084             }
1085         }
1086         
1087         if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
1088         {
1089             /* We are going to release the array, so set the size to 0 */
1090             *(pb_size_t*)iter->pSize = 0;
1091         }
1092         
1093         /* Release main item */
1094         pb_free(*(void**)iter->pData);
1095         *(void**)iter->pData = NULL;
1096     }
1097 }
1098
1099 void pb_release(const pb_field_t fields[], void *dest_struct)
1100 {
1101     pb_field_iter_t iter;
1102     
1103     if (!dest_struct)
1104         return; /* Ignore NULL pointers, similar to free() */
1105
1106     if (!pb_field_iter_begin(&iter, fields, dest_struct))
1107         return; /* Empty message type */
1108     
1109     do
1110     {
1111         pb_release_single_field(&iter);
1112     } while (pb_field_iter_next(&iter));
1113 }
1114 #endif
1115
1116 /* Field decoders */
1117
1118 bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest)
1119 {
1120     uint64_t value;
1121     if (!pb_decode_varint(stream, &value))
1122         return false;
1123     
1124     if (value & 1)
1125         *dest = (int64_t)(~(value >> 1));
1126     else
1127         *dest = (int64_t)(value >> 1);
1128     
1129     return true;
1130 }
1131
1132 bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
1133 {
1134     pb_byte_t bytes[4];
1135
1136     if (!pb_read(stream, bytes, 4))
1137         return false;
1138     
1139     *(uint32_t*)dest = ((uint32_t)bytes[0] << 0) |
1140                        ((uint32_t)bytes[1] << 8) |
1141                        ((uint32_t)bytes[2] << 16) |
1142                        ((uint32_t)bytes[3] << 24);
1143     return true;
1144 }
1145
1146 bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
1147 {
1148     pb_byte_t bytes[8];
1149
1150     if (!pb_read(stream, bytes, 8))
1151         return false;
1152     
1153     *(uint64_t*)dest = ((uint64_t)bytes[0] << 0) |
1154                        ((uint64_t)bytes[1] << 8) |
1155                        ((uint64_t)bytes[2] << 16) |
1156                        ((uint64_t)bytes[3] << 24) |
1157                        ((uint64_t)bytes[4] << 32) |
1158                        ((uint64_t)bytes[5] << 40) |
1159                        ((uint64_t)bytes[6] << 48) |
1160                        ((uint64_t)bytes[7] << 56);
1161     
1162     return true;
1163 }
1164
1165 static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1166 {
1167     uint64_t value;
1168     int64_t svalue;
1169     int64_t clamped;
1170     if (!pb_decode_varint(stream, &value))
1171         return false;
1172     
1173     /* See issue 97: Google's C++ protobuf allows negative varint values to
1174      * be cast as int32_t, instead of the int64_t that should be used when
1175      * encoding. Previous nanopb versions had a bug in encoding. In order to
1176      * not break decoding of such messages, we cast <=32 bit fields to
1177      * int32_t first to get the sign correct.
1178      */
1179     if (field->data_size == sizeof(int64_t))
1180         svalue = (int64_t)value;
1181     else
1182         svalue = (int32_t)value;
1183
1184     /* Cast to the proper field size, while checking for overflows */
1185     if (field->data_size == sizeof(int64_t))
1186         clamped = *(int64_t*)dest = svalue;
1187     else if (field->data_size == sizeof(int32_t))
1188         clamped = *(int32_t*)dest = (int32_t)svalue;
1189     else if (field->data_size == sizeof(int_least16_t))
1190         clamped = *(int_least16_t*)dest = (int_least16_t)svalue;
1191     else if (field->data_size == sizeof(int_least8_t))
1192         clamped = *(int_least8_t*)dest = (int_least8_t)svalue;
1193     else
1194         PB_RETURN_ERROR(stream, "invalid data_size");
1195
1196     if (clamped != svalue)
1197         PB_RETURN_ERROR(stream, "integer too large");
1198     
1199     return true;
1200 }
1201
1202 static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1203 {
1204     uint64_t value, clamped;
1205     if (!pb_decode_varint(stream, &value))
1206         return false;
1207     
1208     /* Cast to the proper field size, while checking for overflows */
1209     if (field->data_size == sizeof(uint64_t))
1210         clamped = *(uint64_t*)dest = value;
1211     else if (field->data_size == sizeof(uint32_t))
1212         clamped = *(uint32_t*)dest = (uint32_t)value;
1213     else if (field->data_size == sizeof(uint_least16_t))
1214         clamped = *(uint_least16_t*)dest = (uint_least16_t)value;
1215     else if (field->data_size == sizeof(uint_least8_t))
1216         clamped = *(uint_least8_t*)dest = (uint_least8_t)value;
1217     else
1218         PB_RETURN_ERROR(stream, "invalid data_size");
1219     
1220     if (clamped != value)
1221         PB_RETURN_ERROR(stream, "integer too large");
1222
1223     return true;
1224 }
1225
1226 static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1227 {
1228     int64_t value, clamped;
1229     if (!pb_decode_svarint(stream, &value))
1230         return false;
1231     
1232     /* Cast to the proper field size, while checking for overflows */
1233     if (field->data_size == sizeof(int64_t))
1234         clamped = *(int64_t*)dest = value;
1235     else if (field->data_size == sizeof(int32_t))
1236         clamped = *(int32_t*)dest = (int32_t)value;
1237     else if (field->data_size == sizeof(int_least16_t))
1238         clamped = *(int_least16_t*)dest = (int_least16_t)value;
1239     else if (field->data_size == sizeof(int_least8_t))
1240         clamped = *(int_least8_t*)dest = (int_least8_t)value;
1241     else
1242         PB_RETURN_ERROR(stream, "invalid data_size");
1243
1244     if (clamped != value)
1245         PB_RETURN_ERROR(stream, "integer too large");
1246     
1247     return true;
1248 }
1249
1250 static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)
1251 {
1252     PB_UNUSED(field);
1253     return pb_decode_fixed32(stream, dest);
1254 }
1255
1256 static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)
1257 {
1258     PB_UNUSED(field);
1259     return pb_decode_fixed64(stream, dest);
1260 }
1261
1262 static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
1263 {
1264     uint32_t size;
1265     size_t alloc_size;
1266     pb_bytes_array_t *bdest;
1267     
1268     if (!pb_decode_varint32(stream, &size))
1269         return false;
1270     
1271     if (size > PB_SIZE_MAX)
1272         PB_RETURN_ERROR(stream, "bytes overflow");
1273     
1274     alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size);
1275     if (size > alloc_size)
1276         PB_RETURN_ERROR(stream, "size too large");
1277     
1278     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1279     {
1280 #ifndef PB_ENABLE_MALLOC
1281         PB_RETURN_ERROR(stream, "no malloc support");
1282 #else
1283         if (!allocate_field(stream, dest, alloc_size, 1))
1284             return false;
1285         bdest = *(pb_bytes_array_t**)dest;
1286 #endif
1287     }
1288     else
1289     {
1290         if (alloc_size > field->data_size)
1291             PB_RETURN_ERROR(stream, "bytes overflow");
1292         bdest = (pb_bytes_array_t*)dest;
1293     }
1294
1295     bdest->size = (pb_size_t)size;
1296     return pb_read(stream, bdest->bytes, size);
1297 }
1298
1299 static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
1300 {
1301     uint32_t size;
1302     size_t alloc_size;
1303     bool status;
1304     if (!pb_decode_varint32(stream, &size))
1305         return false;
1306     
1307     /* Space for null terminator */
1308     alloc_size = size + 1;
1309     
1310     if (alloc_size < size)
1311         PB_RETURN_ERROR(stream, "size too large");
1312     
1313     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1314     {
1315 #ifndef PB_ENABLE_MALLOC
1316         PB_RETURN_ERROR(stream, "no malloc support");
1317 #else
1318         if (!allocate_field(stream, dest, alloc_size, 1))
1319             return false;
1320         dest = *(void**)dest;
1321 #endif
1322     }
1323     else
1324     {
1325         if (alloc_size > field->data_size)
1326             PB_RETURN_ERROR(stream, "string overflow");
1327     }
1328     
1329     status = pb_read(stream, (pb_byte_t*)dest, size);
1330     *((pb_byte_t*)dest + size) = 0;
1331     return status;
1332 }
1333
1334 static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
1335 {
1336     bool status;
1337     pb_istream_t substream;
1338     const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;
1339     
1340     if (!pb_make_string_substream(stream, &substream))
1341         return false;
1342     
1343     if (field->ptr == NULL)
1344         PB_RETURN_ERROR(stream, "invalid field descriptor");
1345     
1346     /* New array entries need to be initialized, while required and optional
1347      * submessages have already been initialized in the top-level pb_decode. */
1348     if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
1349         status = pb_decode(&substream, submsg_fields, dest);
1350     else
1351         status = pb_decode_noinit(&substream, submsg_fields, dest);
1352     
1353     if (!pb_close_string_substream(stream, &substream))
1354         return false;
1355     return status;
1356 }
1357
1358 static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
1359 {
1360     uint32_t size;
1361
1362     if (!pb_decode_varint32(stream, &size))
1363         return false;
1364
1365     if (size > PB_SIZE_MAX)
1366         PB_RETURN_ERROR(stream, "bytes overflow");
1367
1368     if (size == 0)
1369     {
1370         /* As a special case, treat empty bytes string as all zeros for fixed_length_bytes. */
1371         memset(dest, 0, field->data_size);
1372         return true;
1373     }
1374
1375     if (size != field->data_size)
1376         PB_RETURN_ERROR(stream, "incorrect fixed length bytes size");
1377
1378     return pb_read(stream, (pb_byte_t*)dest, field->data_size);
1379 }