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