Avoid unnecessary looping in required fields check.
[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 /* The warn_unused_result attribute appeared first in gcc-3.4.0 */
7 #if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)
8     #define checkreturn
9 #else
10     /* Verify that we remember to check all return values for proper error propagation */
11     #define checkreturn __attribute__((warn_unused_result))
12 #endif
13
14 #define NANOPB_INTERNALS
15 #include "pb.h"
16 #include "pb_decode.h"
17 #include <string.h>
18
19 typedef bool (*pb_decoder_t)(pb_istream_t *stream, const pb_field_t *field, void *dest) checkreturn;
20
21 /* --- Function pointers to field decoders ---
22  * Order in the array must match pb_action_t LTYPE numbering.
23  */
24 static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = {
25     &pb_dec_varint,
26     &pb_dec_svarint,
27     &pb_dec_fixed32,
28     &pb_dec_fixed64,
29     
30     &pb_dec_bytes,
31     &pb_dec_string,
32     &pb_dec_submessage
33 };
34
35 /**************
36  * pb_istream *
37  **************/
38
39 static bool checkreturn buf_read(pb_istream_t *stream, uint8_t *buf, size_t count)
40 {
41     uint8_t *source = (uint8_t*)stream->state;
42     stream->state = source + count;
43     
44     if (buf != NULL)
45     {
46         while (count--)
47             *buf++ = *source++;
48     }
49     
50     return true;
51 }
52
53 bool checkreturn pb_read(pb_istream_t *stream, uint8_t *buf, size_t count)
54 {
55 #ifndef PB_BUFFER_ONLY
56         if (buf == NULL && stream->callback != buf_read)
57         {
58                 /* Skip input bytes */
59                 uint8_t tmp[16];
60                 while (count > 16)
61                 {
62                         if (!pb_read(stream, tmp, 16))
63                                 return false;
64                         
65                         count -= 16;
66                 }
67                 
68                 return pb_read(stream, tmp, count);
69         }
70 #endif
71
72     if (stream->bytes_left < count)
73         PB_RETURN_ERROR(stream, "end-of-stream");
74     
75 #ifndef PB_BUFFER_ONLY
76     if (!stream->callback(stream, buf, count))
77         PB_RETURN_ERROR(stream, "io error");
78 #else
79     if (!buf_read(stream, buf, count))
80         return false;
81 #endif
82     
83     stream->bytes_left -= count;
84     return true;
85 }
86
87 pb_istream_t pb_istream_from_buffer(uint8_t *buf, size_t bufsize)
88 {
89     pb_istream_t stream;
90 #ifdef PB_BUFFER_ONLY
91     stream.callback = NULL;
92 #else
93     stream.callback = &buf_read;
94 #endif
95     stream.state = buf;
96     stream.bytes_left = bufsize;
97 #ifndef PB_NO_ERRMSG
98     stream.errmsg = NULL;
99 #endif
100     return stream;
101 }
102
103 /********************
104  * Helper functions *
105  ********************/
106
107 static bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest)
108 {
109     uint8_t byte;
110     int bitpos = 0;
111     *dest = 0;
112     
113     while (bitpos < 32 && pb_read(stream, &byte, 1))
114     {
115         *dest |= (uint32_t)(byte & 0x7F) << bitpos;
116         bitpos += 7;
117         
118         if (!(byte & 0x80))
119             return true;
120     }
121     
122     PB_RETURN_ERROR(stream, "varint overflow");
123 }
124
125 bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest)
126 {
127     uint8_t byte;
128     int bitpos = 0;
129     *dest = 0;
130     
131     while (bitpos < 64 && pb_read(stream, &byte, 1))
132     {
133         *dest |= (uint64_t)(byte & 0x7F) << bitpos;
134         bitpos += 7;
135         
136         if (!(byte & 0x80))
137             return true;
138     }
139     
140     PB_RETURN_ERROR(stream, "varint overflow");
141 }
142
143 bool checkreturn pb_skip_varint(pb_istream_t *stream)
144 {
145     uint8_t byte;
146     do
147     {
148         if (!pb_read(stream, &byte, 1))
149             return false;
150     } while (byte & 0x80);
151     return true;
152 }
153
154 bool checkreturn pb_skip_string(pb_istream_t *stream)
155 {
156     uint32_t length;
157     if (!pb_decode_varint32(stream, &length))
158         return false;
159     
160     return pb_read(stream, NULL, length);
161 }
162
163 bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof)
164 {
165     uint32_t temp;
166     *eof = false;
167     *wire_type = (pb_wire_type_t) 0;
168     *tag = 0;
169     
170     if (!pb_decode_varint32(stream, &temp))
171     {
172         if (stream->bytes_left == 0)
173             *eof = true;
174
175         return false;
176     }
177     
178     if (temp == 0)
179     {
180         *eof = true; /* Special feature: allow 0-terminated messages. */
181         return false;
182     }
183     
184     *tag = temp >> 3;
185     *wire_type = (pb_wire_type_t)(temp & 7);
186     return true;
187 }
188
189 bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type)
190 {
191     switch (wire_type)
192     {
193         case PB_WT_VARINT: return pb_skip_varint(stream);
194         case PB_WT_64BIT: return pb_read(stream, NULL, 8);
195         case PB_WT_STRING: return pb_skip_string(stream);
196         case PB_WT_32BIT: return pb_read(stream, NULL, 4);
197         default: PB_RETURN_ERROR(stream, "invalid wire_type");
198     }
199 }
200
201 /* Read a raw value to buffer, for the purpose of passing it to callback as
202  * a substream. Size is maximum size on call, and actual size on return.
203  */
204 static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, uint8_t *buf, size_t *size)
205 {
206     size_t max_size = *size;
207     switch (wire_type)
208     {
209         case PB_WT_VARINT:
210             *size = 0;
211             do
212             {
213                 (*size)++;
214                 if (*size > max_size) return false;
215                 if (!pb_read(stream, buf, 1)) return false;
216             } while (*buf++ & 0x80);
217             return true;
218             
219         case PB_WT_64BIT:
220             *size = 8;
221             return pb_read(stream, buf, 8);
222         
223         case PB_WT_32BIT:
224             *size = 4;
225             return pb_read(stream, buf, 4);
226         
227         default: PB_RETURN_ERROR(stream, "invalid wire_type");
228     }
229 }
230
231 /* Decode string length from stream and return a substream with limited length.
232  * Remember to close the substream using pb_close_string_substream().
233  */
234 bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream)
235 {
236     uint32_t size;
237     if (!pb_decode_varint32(stream, &size))
238         return false;
239     
240     *substream = *stream;
241     if (substream->bytes_left < size)
242         PB_RETURN_ERROR(stream, "parent stream too short");
243     
244     substream->bytes_left = size;
245     stream->bytes_left -= size;
246     return true;
247 }
248
249 void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream)
250 {
251     stream->state = substream->state;
252
253 #ifndef PB_NO_ERRMSG
254     stream->errmsg = substream->errmsg;
255 #endif
256 }
257
258 /* Iterator for pb_field_t list */
259 typedef struct {
260     const pb_field_t *start; /* Start of the pb_field_t array */
261     const pb_field_t *current; /* Current position of the iterator */
262     int field_index; /* Zero-based index of the field. */
263     int required_field_index; /* Zero-based index that counts only the required fields */
264     void *dest_struct; /* Pointer to the destination structure to decode to */
265     void *pData; /* Pointer where to store current field value */
266     void *pSize; /* Pointer where to store the size of current array field */
267 } pb_field_iterator_t;
268
269 static void pb_field_init(pb_field_iterator_t *iter, const pb_field_t *fields, void *dest_struct)
270 {
271     iter->start = iter->current = fields;
272     iter->field_index = 0;
273     iter->required_field_index = 0;
274     iter->pData = (char*)dest_struct + iter->current->data_offset;
275     iter->pSize = (char*)iter->pData + iter->current->size_offset;
276     iter->dest_struct = dest_struct;
277 }
278
279 static bool pb_field_next(pb_field_iterator_t *iter)
280 {
281     bool notwrapped = true;
282     size_t prev_size = iter->current->data_size;
283     
284     if (PB_HTYPE(iter->current->type) == PB_HTYPE_ARRAY)
285         prev_size *= iter->current->array_size;
286     
287     if (PB_HTYPE(iter->current->type) == PB_HTYPE_REQUIRED)
288         iter->required_field_index++;
289     
290     iter->current++;
291     iter->field_index++;
292     if (iter->current->tag == 0)
293     {
294         iter->current = iter->start;
295         iter->field_index = 0;
296         iter->required_field_index = 0;
297         iter->pData = iter->dest_struct;
298         prev_size = 0;
299         notwrapped = false;
300     }
301     
302     iter->pData = (char*)iter->pData + prev_size + iter->current->data_offset;
303     iter->pSize = (char*)iter->pData + iter->current->size_offset;
304     return notwrapped;
305 }
306
307 static bool checkreturn pb_field_find(pb_field_iterator_t *iter, uint32_t tag)
308 {
309     int start = iter->field_index;
310     
311     do {
312         if (iter->current->tag == tag)
313             return true;
314         pb_field_next(iter);
315     } while (iter->field_index != start);
316     
317     return false;
318 }
319
320 /*************************
321  * Decode a single field *
322  *************************/
323
324 static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
325 {
326     pb_decoder_t func = PB_DECODERS[PB_LTYPE(iter->current->type)];
327     
328     switch (PB_HTYPE(iter->current->type))
329     {
330         case PB_HTYPE_REQUIRED:
331             return func(stream, iter->current, iter->pData);
332             
333         case PB_HTYPE_OPTIONAL:
334             *(bool*)iter->pSize = true;
335             return func(stream, iter->current, iter->pData);
336     
337         case PB_HTYPE_ARRAY:
338             if (wire_type == PB_WT_STRING
339                 && PB_LTYPE(iter->current->type) <= PB_LTYPE_LAST_PACKABLE)
340             {
341                 /* Packed array */
342                 bool status;
343                 size_t *size = (size_t*)iter->pSize;
344                 pb_istream_t substream;
345                 if (!pb_make_string_substream(stream, &substream))
346                     return false;
347                 
348                 while (substream.bytes_left && *size < iter->current->array_size)
349                 {
350                     void *pItem = (uint8_t*)iter->pData + iter->current->data_size * (*size);
351                     if (!func(&substream, iter->current, pItem))
352                         return false;
353                     (*size)++;
354                 }
355                 status = (substream.bytes_left == 0);
356                 pb_close_string_substream(stream, &substream);
357                 return status;
358             }
359             else
360             {
361                 /* Repeated field */
362                 size_t *size = (size_t*)iter->pSize;
363                 void *pItem = (uint8_t*)iter->pData + iter->current->data_size * (*size);
364                 if (*size >= iter->current->array_size)
365                     PB_RETURN_ERROR(stream, "array overflow");
366                 
367                 (*size)++;
368                 return func(stream, iter->current, pItem);
369             }
370         
371         case PB_HTYPE_CALLBACK:
372         {
373             pb_callback_t *pCallback = (pb_callback_t*)iter->pData;
374             
375             if (pCallback->funcs.decode == NULL)
376                 return pb_skip_field(stream, wire_type);
377             
378             if (wire_type == PB_WT_STRING)
379             {
380                 pb_istream_t substream;
381                 
382                 if (!pb_make_string_substream(stream, &substream))
383                     return false;
384                 
385                 while (substream.bytes_left)
386                 {
387                     if (!pCallback->funcs.decode(&substream, iter->current, pCallback->arg))
388                         PB_RETURN_ERROR(stream, "callback failed");
389                 }
390                 
391                 pb_close_string_substream(stream, &substream);
392                 return true;
393             }
394             else
395             {
396                 /* Copy the single scalar value to stack.
397                  * This is required so that we can limit the stream length,
398                  * which in turn allows to use same callback for packed and
399                  * not-packed fields. */
400                 pb_istream_t substream;
401                 uint8_t buffer[10];
402                 size_t size = sizeof(buffer);
403                 
404                 if (!read_raw_value(stream, wire_type, buffer, &size))
405                     return false;
406                 substream = pb_istream_from_buffer(buffer, size);
407                 
408                 return pCallback->funcs.decode(&substream, iter->current, pCallback->arg);
409             }
410         }
411         
412         default:
413             PB_RETURN_ERROR(stream, "invalid field type");
414     }
415 }
416
417 /* Initialize message fields to default values, recursively */
418 static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct)
419 {
420     pb_field_iterator_t iter;
421     pb_field_init(&iter, fields, dest_struct);
422     
423     /* Initialize size/has fields and apply default values */
424     do
425     {
426         if (iter.current->tag == 0)
427             continue;
428         
429         /* Initialize the size field for optional/repeated fields to 0. */
430         if (PB_HTYPE(iter.current->type) == PB_HTYPE_OPTIONAL)
431         {
432             *(bool*)iter.pSize = false;
433         }
434         else if (PB_HTYPE(iter.current->type) == PB_HTYPE_ARRAY)
435         {
436             *(size_t*)iter.pSize = 0;
437             continue; /* Array is empty, no need to initialize contents */
438         }
439         
440         /* Initialize field contents to default value */
441         if (PB_HTYPE(iter.current->type) == PB_HTYPE_CALLBACK)
442         {
443             continue; /* Don't overwrite callback */
444         }
445         else if (PB_LTYPE(iter.current->type) == PB_LTYPE_SUBMESSAGE)
446         {
447             pb_message_set_to_defaults((const pb_field_t *) iter.current->ptr, iter.pData);
448         }
449         else if (iter.current->ptr != NULL)
450         {
451             memcpy(iter.pData, iter.current->ptr, iter.current->data_size);
452         }
453         else
454         {
455             memset(iter.pData, 0, iter.current->data_size);
456         }
457     } while (pb_field_next(&iter));
458 }
459
460 /*********************
461  * Decode all fields *
462  *********************/
463
464 bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
465 {
466     uint8_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 7) / 8] = {0}; /* Used to check for required fields */
467     pb_field_iterator_t iter;
468     
469     pb_field_init(&iter, fields, dest_struct);
470     
471     while (stream->bytes_left)
472     {
473         uint32_t tag;
474         pb_wire_type_t wire_type;
475         bool eof;
476         
477         if (!pb_decode_tag(stream, &wire_type, &tag, &eof))
478         {
479             if (eof)
480                 break;
481             else
482                 return false;
483         }
484         
485         if (!pb_field_find(&iter, tag))
486         {
487             /* No match found, skip data */
488             if (!pb_skip_field(stream, wire_type))
489                 return false;
490             continue;
491         }
492         
493         if (PB_HTYPE(iter.current->type) == PB_HTYPE_REQUIRED
494             && iter.required_field_index < PB_MAX_REQUIRED_FIELDS)
495         {
496             fields_seen[iter.required_field_index >> 3] |= (uint8_t)(1 << (iter.required_field_index & 7));
497         }
498             
499         if (!decode_field(stream, wire_type, &iter))
500             return false;
501     }
502     
503     /* Check that all required fields were present. */
504     {
505         /* First figure out the number of required fields by
506          * seeking to the end of the field array. Usually we
507          * are already close to end after decoding.
508          */
509         int req_field_count;
510         uint8_t last_type;
511         int i;
512         do {
513             req_field_count = iter.required_field_index;
514             last_type = iter.current->type;
515         } while (pb_field_next(&iter));
516         
517         /* Fixup if last field was also required. */
518         if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED)
519             req_field_count++;
520         
521         /* Check the whole bytes */
522         for (i = 0; i < (req_field_count >> 3); i++)
523         {
524             if (fields_seen[i] != 0xFF)
525                 PB_RETURN_ERROR(stream, "missing required field");
526         }
527         
528         /* Check the remaining bits */
529         if (fields_seen[req_field_count >> 3] != (0xFF >> (8 - (req_field_count & 7))))
530             PB_RETURN_ERROR(stream, "missing required field");
531     }
532     
533     return true;
534 }
535
536 bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
537 {
538     pb_message_set_to_defaults(fields, dest_struct);
539     return pb_decode_noinit(stream, fields, dest_struct);
540 }
541
542 /* Field decoders */
543
544 bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest)
545 {
546     uint64_t value;
547     if (!pb_decode_varint(stream, &value))
548         return false;
549     
550     if (value & 1)
551         *dest = (int64_t)(~(value >> 1));
552     else
553         *dest = (int64_t)(value >> 1);
554     
555     return true;
556 }
557
558 bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
559 {
560     #ifdef __BIG_ENDIAN__
561     uint8_t *bytes = (uint8_t*)dest;
562     uint8_t lebytes[4];
563     
564     if (!pb_read(stream, lebytes, 4))
565         return false;
566     
567     bytes[0] = lebytes[3];
568     bytes[1] = lebytes[2];
569     bytes[2] = lebytes[1];
570     bytes[3] = lebytes[0];
571     return true;
572     #else
573     return pb_read(stream, (uint8_t*)dest, 4);
574     #endif   
575 }
576
577 bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
578 {
579     #ifdef __BIG_ENDIAN__
580     uint8_t *bytes = (uint8_t*)dest;
581     uint8_t lebytes[8];
582     
583     if (!pb_read(stream, lebytes, 8))
584         return false;
585     
586     bytes[0] = lebytes[7];
587     bytes[1] = lebytes[6];
588     bytes[2] = lebytes[5];
589     bytes[3] = lebytes[4];
590     bytes[4] = lebytes[3];
591     bytes[5] = lebytes[2];
592     bytes[6] = lebytes[1];
593     bytes[7] = lebytes[0];
594     return true;
595     #else
596     return pb_read(stream, (uint8_t*)dest, 8);
597     #endif   
598 }
599
600 bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
601 {
602     uint64_t value;
603     bool status = pb_decode_varint(stream, &value);
604     
605     switch (field->data_size)
606     {
607         case 1: *(uint8_t*)dest = (uint8_t)value; break;
608         case 2: *(uint16_t*)dest = (uint16_t)value; break;
609         case 4: *(uint32_t*)dest = (uint32_t)value; break;
610         case 8: *(uint64_t*)dest = value; break;
611         default: PB_RETURN_ERROR(stream, "invalid data_size");
612     }
613     
614     return status;
615 }
616
617 bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
618 {
619     int64_t value;
620     bool status = pb_decode_svarint(stream, &value);
621     
622     switch (field->data_size)
623     {
624         case 4: *(int32_t*)dest = (int32_t)value; break;
625         case 8: *(int64_t*)dest = value; break;
626         default: PB_RETURN_ERROR(stream, "invalid data_size");
627     }
628     
629     return status;
630 }
631
632 bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)
633 {
634     UNUSED(field);
635     return pb_decode_fixed32(stream, dest);
636 }
637
638 bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)
639 {
640     UNUSED(field);
641     return pb_decode_fixed64(stream, dest);
642 }
643
644 bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
645 {
646     pb_bytes_array_t *x = (pb_bytes_array_t*)dest;
647     
648     uint32_t temp;
649     if (!pb_decode_varint32(stream, &temp))
650         return false;
651     x->size = temp;
652     
653     /* Check length, noting the space taken by the size_t header. */
654     if (x->size > field->data_size - offsetof(pb_bytes_array_t, bytes))
655         PB_RETURN_ERROR(stream, "bytes overflow");
656     
657     return pb_read(stream, x->bytes, x->size);
658 }
659
660 bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
661 {
662     uint32_t size;
663     bool status;
664     if (!pb_decode_varint32(stream, &size))
665         return false;
666     
667     /* Check length, noting the null terminator */
668     if (size + 1 > field->data_size)
669         PB_RETURN_ERROR(stream, "string overflow");
670     
671     status = pb_read(stream, (uint8_t*)dest, size);
672     *((uint8_t*)dest + size) = 0;
673     return status;
674 }
675
676 bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
677 {
678     bool status;
679     pb_istream_t substream;
680     const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;
681     
682     if (!pb_make_string_substream(stream, &substream))
683         return false;
684     
685     if (field->ptr == NULL)
686         PB_RETURN_ERROR(stream, "invalid field descriptor");
687     
688     /* New array entries need to be initialized, while required and optional
689      * submessages have already been initialized in the top-level pb_decode. */
690     if (PB_HTYPE(field->type) == PB_HTYPE_ARRAY)
691         status = pb_decode(&substream, submsg_fields, dest);
692     else
693         status = pb_decode_noinit(&substream, submsg_fields, dest);
694     
695     pb_close_string_substream(stream, &substream);
696     return status;
697 }