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