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