Add support for POINTER type in extensions
[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     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
654     {
655         /* For pointer extensions, the pointer is stored directly
656          * in the extension structure. This avoids having an extra
657          * indirection. */
658         iter.pData = &extension->dest;
659     }
660     
661     return decode_field(stream, wire_type, &iter);
662 }
663
664 /* Try to decode an unknown field as an extension field. Tries each extension
665  * decoder in turn, until one of them handles the field or loop ends. */
666 static bool checkreturn decode_extension(pb_istream_t *stream,
667     uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter)
668 {
669     pb_extension_t *extension = *(pb_extension_t* const *)iter->pData;
670     size_t pos = stream->bytes_left;
671     
672     while (extension != NULL && pos == stream->bytes_left)
673     {
674         bool status;
675         if (extension->type->decode)
676             status = extension->type->decode(stream, extension, tag, wire_type);
677         else
678             status = default_extension_decoder(stream, extension, tag, wire_type);
679
680         if (!status)
681             return false;
682         
683         extension = extension->next;
684     }
685     
686     return true;
687 }
688
689 /* Step through the iterator until an extension field is found or until all
690  * entries have been checked. There can be only one extension field per
691  * message. Returns false if no extension field is found. */
692 static bool checkreturn find_extension_field(pb_field_iter_t *iter)
693 {
694     const pb_field_t *start = iter->pos;
695     
696     do {
697         if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION)
698             return true;
699         (void)pb_field_iter_next(iter);
700     } while (iter->pos != start);
701     
702     return false;
703 }
704
705 /* Initialize message fields to default values, recursively */
706 static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct)
707 {
708     pb_field_iter_t iter;
709
710     if (!pb_field_iter_begin(&iter, fields, dest_struct))
711         return; /* Empty message type */
712     
713     do
714     {
715         pb_type_t type;
716         type = iter.pos->type;
717         
718         if (PB_ATYPE(type) == PB_ATYPE_STATIC)
719         {
720             if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL)
721             {
722                 /* Set has_field to false. Still initialize the optional field
723                  * itself also. */
724                 *(bool*)iter.pSize = false;
725             }
726             else if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
727             {
728                 /* Set array count to 0, no need to initialize contents. */
729                 *(pb_size_t*)iter.pSize = 0;
730                 continue;
731             }
732             
733             if (PB_LTYPE(iter.pos->type) == PB_LTYPE_SUBMESSAGE)
734             {
735                 /* Initialize submessage to defaults */
736                 pb_message_set_to_defaults((const pb_field_t *) iter.pos->ptr, iter.pData);
737             }
738             else if (iter.pos->ptr != NULL)
739             {
740                 /* Initialize to default value */
741                 memcpy(iter.pData, iter.pos->ptr, iter.pos->data_size);
742             }
743             else
744             {
745                 /* Initialize to zeros */
746                 memset(iter.pData, 0, iter.pos->data_size);
747             }
748         }
749         else if (PB_ATYPE(type) == PB_ATYPE_POINTER)
750         {
751             /* Initialize the pointer to NULL. */
752             *(void**)iter.pData = NULL;
753             
754             /* Initialize array count to 0. */
755             if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
756             {
757                 *(pb_size_t*)iter.pSize = 0;
758             }
759         }
760         else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
761         {
762             /* Don't overwrite callback */
763         }
764     } while (pb_field_iter_next(&iter));
765 }
766
767 /*********************
768  * Decode all fields *
769  *********************/
770
771 bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
772 {
773     uint8_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 7) / 8] = {0, 0, 0, 0, 0, 0, 0, 0};
774     uint32_t extension_range_start = 0;
775     pb_field_iter_t iter;
776     
777     /* Return value ignored, as empty message types will be correctly handled by
778      * pb_field_iter_find() anyway. */
779     (void)pb_field_iter_begin(&iter, fields, dest_struct);
780     
781     while (stream->bytes_left)
782     {
783         uint32_t tag;
784         pb_wire_type_t wire_type;
785         bool eof;
786         
787         if (!pb_decode_tag(stream, &wire_type, &tag, &eof))
788         {
789             if (eof)
790                 break;
791             else
792                 return false;
793         }
794         
795         if (!pb_field_iter_find(&iter, tag))
796         {
797             /* No match found, check if it matches an extension. */
798             if (tag >= extension_range_start)
799             {
800                 if (!find_extension_field(&iter))
801                     extension_range_start = (uint32_t)-1;
802                 else
803                     extension_range_start = iter.pos->tag;
804                 
805                 if (tag >= extension_range_start)
806                 {
807                     size_t pos = stream->bytes_left;
808                 
809                     if (!decode_extension(stream, tag, wire_type, &iter))
810                         return false;
811                     
812                     if (pos != stream->bytes_left)
813                     {
814                         /* The field was handled */
815                         continue;                    
816                     }
817                 }
818             }
819         
820             /* No match found, skip data */
821             if (!pb_skip_field(stream, wire_type))
822                 return false;
823             continue;
824         }
825         
826         if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED
827             && iter.required_field_index < PB_MAX_REQUIRED_FIELDS)
828         {
829             fields_seen[iter.required_field_index >> 3] |= (uint8_t)(1 << (iter.required_field_index & 7));
830         }
831             
832         if (!decode_field(stream, wire_type, &iter))
833             return false;
834     }
835     
836     /* Check that all required fields were present. */
837     {
838         /* First figure out the number of required fields by
839          * seeking to the end of the field array. Usually we
840          * are already close to end after decoding.
841          */
842         unsigned req_field_count;
843         pb_type_t last_type;
844         unsigned i;
845         do {
846             req_field_count = iter.required_field_index;
847             last_type = iter.pos->type;
848         } while (pb_field_iter_next(&iter));
849         
850         /* Fixup if last field was also required. */
851         if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0)
852             req_field_count++;
853         
854         /* Check the whole bytes */
855         for (i = 0; i < (req_field_count >> 3); i++)
856         {
857             if (fields_seen[i] != 0xFF)
858                 PB_RETURN_ERROR(stream, "missing required field");
859         }
860         
861         /* Check the remaining bits */
862         if (fields_seen[req_field_count >> 3] != (0xFF >> (8 - (req_field_count & 7))))
863             PB_RETURN_ERROR(stream, "missing required field");
864     }
865     
866     return true;
867 }
868
869 bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
870 {
871     bool status;
872     pb_message_set_to_defaults(fields, dest_struct);
873     status = pb_decode_noinit(stream, fields, dest_struct);
874     
875 #ifdef PB_ENABLE_MALLOC
876     if (!status)
877         pb_release(fields, dest_struct);
878 #endif
879     
880     return status;
881 }
882
883 bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
884 {
885     pb_istream_t substream;
886     bool status;
887     
888     if (!pb_make_string_substream(stream, &substream))
889         return false;
890     
891     status = pb_decode(&substream, fields, dest_struct);
892     pb_close_string_substream(stream, &substream);
893     return status;
894 }
895
896 #ifdef PB_ENABLE_MALLOC
897 static void pb_release_single_field(const pb_field_iter_t *iter)
898 {
899     pb_type_t type;
900     type = iter->pos->type;
901
902     if (PB_ATYPE(type) == PB_ATYPE_POINTER)
903     {
904         if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&
905             (PB_LTYPE(type) == PB_LTYPE_STRING ||
906              PB_LTYPE(type) == PB_LTYPE_BYTES))
907         {
908             /* Release entries in repeated string or bytes array */
909             void **pItem = *(void***)iter->pData;
910             pb_size_t count = *(pb_size_t*)iter->pSize;
911             while (count--)
912             {
913                 pb_free(*pItem);
914                 *pItem++ = NULL;
915             }
916             *(pb_size_t*)iter->pSize = 0;
917         }
918         else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)
919         {
920             /* Release fields in submessages */
921             void *pItem = *(void**)iter->pData;
922             if (pItem)
923             {
924                 pb_size_t count = 1;
925                 
926                 if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
927                 {
928                     count = *(pb_size_t*)iter->pSize;
929                     *(pb_size_t*)iter->pSize = 0;
930                 }
931                 
932                 while (count--)
933                 {
934                     pb_release((const pb_field_t*)iter->pos->ptr, pItem);
935                     pItem = (uint8_t*)pItem + iter->pos->data_size;
936                 }
937             }
938         }
939         
940         /* Release main item */
941         pb_free(*(void**)iter->pData);
942         *(void**)iter->pData = NULL;
943     }
944 }
945
946 void pb_release(const pb_field_t fields[], void *dest_struct)
947 {
948     pb_field_iter_t iter;
949     
950     if (!pb_field_iter_begin(&iter, fields, dest_struct))
951         return; /* Empty message type */
952     
953     do
954     {
955         pb_release_single_field(&iter);
956     } while (pb_field_iter_next(&iter));
957 }
958 #endif
959
960 /* Field decoders */
961
962 bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest)
963 {
964     uint64_t value;
965     if (!pb_decode_varint(stream, &value))
966         return false;
967     
968     if (value & 1)
969         *dest = (int64_t)(~(value >> 1));
970     else
971         *dest = (int64_t)(value >> 1);
972     
973     return true;
974 }
975
976 bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
977 {
978     #ifdef __BIG_ENDIAN__
979     uint8_t *bytes = (uint8_t*)dest;
980     uint8_t lebytes[4];
981     
982     if (!pb_read(stream, lebytes, 4))
983         return false;
984     
985     bytes[0] = lebytes[3];
986     bytes[1] = lebytes[2];
987     bytes[2] = lebytes[1];
988     bytes[3] = lebytes[0];
989     return true;
990     #else
991     return pb_read(stream, (uint8_t*)dest, 4);
992     #endif   
993 }
994
995 bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
996 {
997     #ifdef __BIG_ENDIAN__
998     uint8_t *bytes = (uint8_t*)dest;
999     uint8_t lebytes[8];
1000     
1001     if (!pb_read(stream, lebytes, 8))
1002         return false;
1003     
1004     bytes[0] = lebytes[7];
1005     bytes[1] = lebytes[6];
1006     bytes[2] = lebytes[5];
1007     bytes[3] = lebytes[4];
1008     bytes[4] = lebytes[3];
1009     bytes[5] = lebytes[2];
1010     bytes[6] = lebytes[1];
1011     bytes[7] = lebytes[0];
1012     return true;
1013     #else
1014     return pb_read(stream, (uint8_t*)dest, 8);
1015     #endif   
1016 }
1017
1018 static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1019 {
1020     uint64_t value;
1021     if (!pb_decode_varint(stream, &value))
1022         return false;
1023     
1024     switch (field->data_size)
1025     {
1026         case 1: *(int8_t*)dest = (int8_t)value; break;
1027         case 2: *(int16_t*)dest = (int16_t)value; break;
1028         case 4: *(int32_t*)dest = (int32_t)value; break;
1029         case 8: *(int64_t*)dest = (int64_t)value; break;
1030         default: PB_RETURN_ERROR(stream, "invalid data_size");
1031     }
1032     
1033     return true;
1034 }
1035
1036 static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1037 {
1038     uint64_t value;
1039     if (!pb_decode_varint(stream, &value))
1040         return false;
1041     
1042     switch (field->data_size)
1043     {
1044         case 4: *(uint32_t*)dest = (uint32_t)value; break;
1045         case 8: *(uint64_t*)dest = value; break;
1046         default: PB_RETURN_ERROR(stream, "invalid data_size");
1047     }
1048     
1049     return true;
1050 }
1051
1052 static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1053 {
1054     int64_t value;
1055     if (!pb_decode_svarint(stream, &value))
1056         return false;
1057     
1058     switch (field->data_size)
1059     {
1060         case 4: *(int32_t*)dest = (int32_t)value; break;
1061         case 8: *(int64_t*)dest = value; break;
1062         default: PB_RETURN_ERROR(stream, "invalid data_size");
1063     }
1064     
1065     return true;
1066 }
1067
1068 static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)
1069 {
1070     PB_UNUSED(field);
1071     return pb_decode_fixed32(stream, dest);
1072 }
1073
1074 static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)
1075 {
1076     PB_UNUSED(field);
1077     return pb_decode_fixed64(stream, dest);
1078 }
1079
1080 static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
1081 {
1082     uint32_t size;
1083     size_t alloc_size;
1084     pb_bytes_array_t *bdest;
1085     
1086     if (!pb_decode_varint32(stream, &size))
1087         return false;
1088     
1089     if (size > PB_SIZE_MAX)
1090         PB_RETURN_ERROR(stream, "bytes overflow");
1091     
1092     alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size);
1093     if (size > alloc_size)
1094         PB_RETURN_ERROR(stream, "size too large");
1095     
1096     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1097     {
1098 #ifndef PB_ENABLE_MALLOC
1099         PB_RETURN_ERROR(stream, "no malloc support");
1100 #else
1101         if (!allocate_field(stream, dest, alloc_size, 1))
1102             return false;
1103         bdest = *(pb_bytes_array_t**)dest;
1104 #endif
1105     }
1106     else
1107     {
1108         if (alloc_size > field->data_size)
1109             PB_RETURN_ERROR(stream, "bytes overflow");
1110         bdest = (pb_bytes_array_t*)dest;
1111     }
1112
1113     bdest->size = (pb_size_t)size;
1114     return pb_read(stream, bdest->bytes, size);
1115 }
1116
1117 static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
1118 {
1119     uint32_t size;
1120     size_t alloc_size;
1121     bool status;
1122     if (!pb_decode_varint32(stream, &size))
1123         return false;
1124     
1125     /* Space for null terminator */
1126     alloc_size = size + 1;
1127     
1128     if (alloc_size < size)
1129         PB_RETURN_ERROR(stream, "size too large");
1130     
1131     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1132     {
1133 #ifndef PB_ENABLE_MALLOC
1134         PB_RETURN_ERROR(stream, "no malloc support");
1135 #else
1136         if (!allocate_field(stream, dest, alloc_size, 1))
1137             return false;
1138         dest = *(void**)dest;
1139 #endif
1140     }
1141     else
1142     {
1143         if (alloc_size > field->data_size)
1144             PB_RETURN_ERROR(stream, "string overflow");
1145     }
1146     
1147     status = pb_read(stream, (uint8_t*)dest, size);
1148     *((uint8_t*)dest + size) = 0;
1149     return status;
1150 }
1151
1152 static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
1153 {
1154     bool status;
1155     pb_istream_t substream;
1156     const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;
1157     
1158     if (!pb_make_string_substream(stream, &substream))
1159         return false;
1160     
1161     if (field->ptr == NULL)
1162         PB_RETURN_ERROR(stream, "invalid field descriptor");
1163     
1164     /* New array entries need to be initialized, while required and optional
1165      * submessages have already been initialized in the top-level pb_decode. */
1166     if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
1167         status = pb_decode(&substream, submsg_fields, dest);
1168     else
1169         status = pb_decode_noinit(&substream, submsg_fields, dest);
1170     
1171     pb_close_string_substream(stream, &substream);
1172     return status;
1173 }