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