1 /* pb_decode.c -- decode a protobuf using minimal resources
3 * 2011 Petteri Aimonen <jpa@kapsi.fi>
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.
10 #if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)
13 #define checkreturn __attribute__((warn_unused_result))
16 #define NANOPB_INTERNALS
18 #include "pb_decode.h"
20 /* --- Function pointers to field decoders ---
21 * Order in the array must match pb_action_t LTYPE numbering.
23 typedef bool (*pb_decoder_t)(pb_istream_t *stream, const pb_field_t *field, void *dest) checkreturn;
24 static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = {
36 /*******************************
37 * pb_istream_t implementation *
38 *******************************/
40 static bool checkreturn buf_read(pb_istream_t *stream, uint8_t *buf, size_t count)
42 uint8_t *source = (uint8_t*)stream->state;
43 stream->state = source + count;
54 bool checkreturn pb_read(pb_istream_t *stream, uint8_t *buf, size_t count)
56 #ifndef PB_BUFFER_ONLY
57 if (buf == NULL && stream->callback != buf_read)
59 /* Skip input bytes */
63 if (!pb_read(stream, tmp, 16))
69 return pb_read(stream, tmp, count);
73 if (stream->bytes_left < count)
74 PB_RETURN_ERROR(stream, "end-of-stream");
76 #ifndef PB_BUFFER_ONLY
77 if (!stream->callback(stream, buf, count))
78 PB_RETURN_ERROR(stream, "io error");
80 if (!buf_read(stream, buf, count))
84 stream->bytes_left -= count;
88 pb_istream_t pb_istream_from_buffer(uint8_t *buf, size_t bufsize)
92 stream.callback = NULL;
94 stream.callback = &buf_read;
97 stream.bytes_left = bufsize;
104 /********************
106 ********************/
108 static bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest)
113 if (!pb_read(stream, &byte, 1))
118 /* Quick case, 1 byte value */
125 result = byte & 0x7F;
130 PB_RETURN_ERROR(stream, "varint overflow");
132 if (!pb_read(stream, &byte, 1))
135 result |= (uint32_t)(byte & 0x7F) << bitpos;
136 bitpos = (uint8_t)(bitpos + 7);
137 } while (byte & 0x80);
144 bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest)
153 PB_RETURN_ERROR(stream, "varint overflow");
155 if (!pb_read(stream, &byte, 1))
158 result |= (uint64_t)(byte & 0x7F) << bitpos;
159 bitpos = (uint8_t)(bitpos + 7);
160 } while (byte & 0x80);
166 bool checkreturn pb_skip_varint(pb_istream_t *stream)
171 if (!pb_read(stream, &byte, 1))
173 } while (byte & 0x80);
177 bool checkreturn pb_skip_string(pb_istream_t *stream)
180 if (!pb_decode_varint32(stream, &length))
183 return pb_read(stream, NULL, length);
186 bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof)
190 *wire_type = (pb_wire_type_t) 0;
193 if (!pb_decode_varint32(stream, &temp))
195 if (stream->bytes_left == 0)
203 *eof = true; /* Special feature: allow 0-terminated messages. */
208 *wire_type = (pb_wire_type_t)(temp & 7);
212 bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type)
216 case PB_WT_VARINT: return pb_skip_varint(stream);
217 case PB_WT_64BIT: return pb_read(stream, NULL, 8);
218 case PB_WT_STRING: return pb_skip_string(stream);
219 case PB_WT_32BIT: return pb_read(stream, NULL, 4);
220 default: PB_RETURN_ERROR(stream, "invalid wire_type");
224 /* Read a raw value to buffer, for the purpose of passing it to callback as
225 * a substream. Size is maximum size on call, and actual size on return.
227 static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, uint8_t *buf, size_t *size)
229 size_t max_size = *size;
237 if (*size > max_size) return false;
238 if (!pb_read(stream, buf, 1)) return false;
239 } while (*buf++ & 0x80);
244 return pb_read(stream, buf, 8);
248 return pb_read(stream, buf, 4);
250 default: PB_RETURN_ERROR(stream, "invalid wire_type");
254 /* Decode string length from stream and return a substream with limited length.
255 * Remember to close the substream using pb_close_string_substream().
257 bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream)
260 if (!pb_decode_varint32(stream, &size))
263 *substream = *stream;
264 if (substream->bytes_left < size)
265 PB_RETURN_ERROR(stream, "parent stream too short");
267 substream->bytes_left = size;
268 stream->bytes_left -= size;
272 void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream)
274 stream->state = substream->state;
277 stream->errmsg = substream->errmsg;
281 /* Iterator for pb_field_t list */
283 const pb_field_t *start; /* Start of the pb_field_t array */
284 const pb_field_t *pos; /* Current position of the iterator */
285 unsigned field_index; /* Zero-based index of the field. */
286 unsigned required_field_index; /* Zero-based index that counts only the required fields */
287 void *dest_struct; /* Pointer to the destination structure to decode to */
288 void *pData; /* Pointer where to store current field value */
289 void *pSize; /* Pointer where to store the size of current array field */
290 } pb_field_iterator_t;
292 static void pb_field_init(pb_field_iterator_t *iter, const pb_field_t *fields, void *dest_struct)
294 iter->start = iter->pos = fields;
295 iter->field_index = 0;
296 iter->required_field_index = 0;
297 iter->pData = (char*)dest_struct + iter->pos->data_offset;
298 iter->pSize = (char*)iter->pData + iter->pos->size_offset;
299 iter->dest_struct = dest_struct;
302 static bool pb_field_next(pb_field_iterator_t *iter)
304 bool notwrapped = true;
305 size_t prev_size = iter->pos->data_size;
307 if (PB_ATYPE(iter->pos->type) == PB_ATYPE_STATIC &&
308 PB_HTYPE(iter->pos->type) == PB_HTYPE_REPEATED)
310 prev_size *= iter->pos->array_size;
313 if (iter->pos->tag == 0)
314 return false; /* Only happens with empty message types */
316 if (PB_HTYPE(iter->pos->type) == PB_HTYPE_REQUIRED)
317 iter->required_field_index++;
321 if (iter->pos->tag == 0)
323 iter->pos = iter->start;
324 iter->field_index = 0;
325 iter->required_field_index = 0;
326 iter->pData = iter->dest_struct;
331 iter->pData = (char*)iter->pData + prev_size + iter->pos->data_offset;
332 iter->pSize = (char*)iter->pData + iter->pos->size_offset;
336 static bool checkreturn pb_field_find(pb_field_iterator_t *iter, uint32_t tag)
338 unsigned start = iter->field_index;
341 if (iter->pos->tag == tag &&
342 PB_LTYPE(iter->pos->type) != PB_LTYPE_EXTENSION)
347 } while (iter->field_index != start);
352 /*************************
353 * Decode a single field *
354 *************************/
356 static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
361 type = iter->pos->type;
362 func = PB_DECODERS[PB_LTYPE(type)];
364 switch (PB_HTYPE(type))
366 case PB_HTYPE_REQUIRED:
367 return func(stream, iter->pos, iter->pData);
369 case PB_HTYPE_OPTIONAL:
370 *(bool*)iter->pSize = true;
371 return func(stream, iter->pos, iter->pData);
373 case PB_HTYPE_REPEATED:
374 if (wire_type == PB_WT_STRING
375 && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
379 size_t *size = (size_t*)iter->pSize;
380 pb_istream_t substream;
381 if (!pb_make_string_substream(stream, &substream))
384 while (substream.bytes_left && *size < iter->pos->array_size)
386 void *pItem = (uint8_t*)iter->pData + iter->pos->data_size * (*size);
387 if (!func(&substream, iter->pos, pItem))
394 pb_close_string_substream(stream, &substream);
396 if (substream.bytes_left != 0)
397 PB_RETURN_ERROR(stream, "array overflow");
404 size_t *size = (size_t*)iter->pSize;
405 void *pItem = (uint8_t*)iter->pData + iter->pos->data_size * (*size);
406 if (*size >= iter->pos->array_size)
407 PB_RETURN_ERROR(stream, "array overflow");
410 return func(stream, iter->pos, pItem);
414 PB_RETURN_ERROR(stream, "invalid field type");
418 static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
420 pb_callback_t *pCallback = (pb_callback_t*)iter->pData;
422 #ifdef PB_OLD_CALLBACK_STYLE
423 void *arg = pCallback->arg;
425 void **arg = &(pCallback->arg);
428 if (pCallback->funcs.decode == NULL)
429 return pb_skip_field(stream, wire_type);
431 if (wire_type == PB_WT_STRING)
433 pb_istream_t substream;
435 if (!pb_make_string_substream(stream, &substream))
440 if (!pCallback->funcs.decode(&substream, iter->pos, arg))
441 PB_RETURN_ERROR(stream, "callback failed");
442 } while (substream.bytes_left);
444 pb_close_string_substream(stream, &substream);
449 /* Copy the single scalar value to stack.
450 * This is required so that we can limit the stream length,
451 * which in turn allows to use same callback for packed and
452 * not-packed fields. */
453 pb_istream_t substream;
455 size_t size = sizeof(buffer);
457 if (!read_raw_value(stream, wire_type, buffer, &size))
459 substream = pb_istream_from_buffer(buffer, size);
461 return pCallback->funcs.decode(&substream, iter->pos, arg);
465 static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
467 switch (PB_ATYPE(iter->pos->type))
469 case PB_ATYPE_STATIC:
470 return decode_static_field(stream, wire_type, iter);
472 case PB_ATYPE_CALLBACK:
473 return decode_callback_field(stream, wire_type, iter);
476 PB_RETURN_ERROR(stream, "invalid field type");
480 /* Default handler for extension fields. Expects a pb_field_t structure
481 * in extension->type->arg. */
482 static bool checkreturn default_extension_decoder(pb_istream_t *stream,
483 pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type)
485 const pb_field_t *field = (const pb_field_t*)extension->type->arg;
486 pb_field_iterator_t iter;
489 if (field->tag != tag)
494 iter.field_index = 0;
495 iter.required_field_index = 0;
496 iter.dest_struct = extension->dest;
497 iter.pData = extension->dest;
500 return decode_field(stream, wire_type, &iter);
503 /* Try to decode an unknown field as an extension field. Tries each extension
504 * decoder in turn, until one of them handles the field or loop ends. */
505 static bool checkreturn decode_extension(pb_istream_t *stream,
506 uint32_t tag, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
508 pb_extension_t *extension = *(pb_extension_t* const *)iter->pData;
509 size_t pos = stream->bytes_left;
511 while (extension && pos == stream->bytes_left)
514 if (extension->type->decode)
515 status = extension->type->decode(stream, extension, tag, wire_type);
517 status = default_extension_decoder(stream, extension, tag, wire_type);
522 extension = extension->next;
528 /* Step through the iterator until an extension field is found or until all
529 * entries have been checked. There can be only one extension field per
530 * message. Returns false if no extension field is found. */
531 static bool checkreturn find_extension_field(pb_field_iterator_t *iter)
533 unsigned start = iter->field_index;
536 if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION)
539 } while (iter->field_index != start);
544 /* Initialize message fields to default values, recursively */
545 static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct)
547 pb_field_iterator_t iter;
548 pb_field_init(&iter, fields, dest_struct);
550 /* Initialize size/has fields and apply default values */
554 type = iter.pos->type;
556 if (iter.pos->tag == 0)
559 if (PB_ATYPE(type) == PB_ATYPE_STATIC)
561 /* Initialize the size field for optional/repeated fields to 0. */
562 if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL)
564 *(bool*)iter.pSize = false;
566 else if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
568 *(size_t*)iter.pSize = 0;
569 continue; /* Array is empty, no need to initialize contents */
572 /* Initialize field contents to default value */
573 if (PB_LTYPE(iter.pos->type) == PB_LTYPE_SUBMESSAGE)
575 pb_message_set_to_defaults((const pb_field_t *) iter.pos->ptr, iter.pData);
577 else if (iter.pos->ptr != NULL)
579 memcpy(iter.pData, iter.pos->ptr, iter.pos->data_size);
583 memset(iter.pData, 0, iter.pos->data_size);
586 else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
588 continue; /* Don't overwrite callback */
590 } while (pb_field_next(&iter));
593 /*********************
594 * Decode all fields *
595 *********************/
597 bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
599 uint8_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 7) / 8] = {0}; /* Used to check for required fields */
600 uint32_t extension_range_start = 0;
601 pb_field_iterator_t iter;
603 pb_field_init(&iter, fields, dest_struct);
605 while (stream->bytes_left)
608 pb_wire_type_t wire_type;
611 if (!pb_decode_tag(stream, &wire_type, &tag, &eof))
619 if (!pb_field_find(&iter, tag))
621 /* No match found, check if it matches an extension. */
622 if (tag >= extension_range_start)
624 if (!find_extension_field(&iter))
625 extension_range_start = (uint32_t)-1;
627 extension_range_start = iter.pos->tag;
629 if (tag >= extension_range_start)
631 size_t pos = stream->bytes_left;
633 if (!decode_extension(stream, tag, wire_type, &iter))
636 if (pos != stream->bytes_left)
638 /* The field was handled */
644 /* No match found, skip data */
645 if (!pb_skip_field(stream, wire_type))
650 if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED
651 && iter.required_field_index < PB_MAX_REQUIRED_FIELDS)
653 fields_seen[iter.required_field_index >> 3] |= (uint8_t)(1 << (iter.required_field_index & 7));
656 if (!decode_field(stream, wire_type, &iter))
660 /* Check that all required fields were present. */
662 /* First figure out the number of required fields by
663 * seeking to the end of the field array. Usually we
664 * are already close to end after decoding.
666 unsigned req_field_count;
670 req_field_count = iter.required_field_index;
671 last_type = iter.pos->type;
672 } while (pb_field_next(&iter));
674 /* Fixup if last field was also required. */
675 if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag)
678 /* Check the whole bytes */
679 for (i = 0; i < (req_field_count >> 3); i++)
681 if (fields_seen[i] != 0xFF)
682 PB_RETURN_ERROR(stream, "missing required field");
685 /* Check the remaining bits */
686 if (fields_seen[req_field_count >> 3] != (0xFF >> (8 - (req_field_count & 7))))
687 PB_RETURN_ERROR(stream, "missing required field");
693 bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
695 pb_message_set_to_defaults(fields, dest_struct);
696 return pb_decode_noinit(stream, fields, dest_struct);
699 bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
701 pb_istream_t substream;
704 if (!pb_make_string_substream(stream, &substream))
707 status = pb_decode(&substream, fields, dest_struct);
708 pb_close_string_substream(stream, &substream);
714 bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest)
717 if (!pb_decode_varint(stream, &value))
721 *dest = (int64_t)(~(value >> 1));
723 *dest = (int64_t)(value >> 1);
728 bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
730 #ifdef __BIG_ENDIAN__
731 uint8_t *bytes = (uint8_t*)dest;
734 if (!pb_read(stream, lebytes, 4))
737 bytes[0] = lebytes[3];
738 bytes[1] = lebytes[2];
739 bytes[2] = lebytes[1];
740 bytes[3] = lebytes[0];
743 return pb_read(stream, (uint8_t*)dest, 4);
747 bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
749 #ifdef __BIG_ENDIAN__
750 uint8_t *bytes = (uint8_t*)dest;
753 if (!pb_read(stream, lebytes, 8))
756 bytes[0] = lebytes[7];
757 bytes[1] = lebytes[6];
758 bytes[2] = lebytes[5];
759 bytes[3] = lebytes[4];
760 bytes[4] = lebytes[3];
761 bytes[5] = lebytes[2];
762 bytes[6] = lebytes[1];
763 bytes[7] = lebytes[0];
766 return pb_read(stream, (uint8_t*)dest, 8);
770 bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
773 if (!pb_decode_varint(stream, &value))
776 switch (field->data_size)
778 case 1: *(uint8_t*)dest = (uint8_t)value; break;
779 case 2: *(uint16_t*)dest = (uint16_t)value; break;
780 case 4: *(uint32_t*)dest = (uint32_t)value; break;
781 case 8: *(uint64_t*)dest = value; break;
782 default: PB_RETURN_ERROR(stream, "invalid data_size");
788 bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
791 if (!pb_decode_svarint(stream, &value))
794 switch (field->data_size)
796 case 4: *(int32_t*)dest = (int32_t)value; break;
797 case 8: *(int64_t*)dest = value; break;
798 default: PB_RETURN_ERROR(stream, "invalid data_size");
804 bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)
807 return pb_decode_fixed32(stream, dest);
810 bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)
813 return pb_decode_fixed64(stream, dest);
816 bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
818 pb_bytes_array_t *x = (pb_bytes_array_t*)dest;
821 if (!pb_decode_varint32(stream, &temp))
825 /* Check length, noting the space taken by the size_t header. */
826 if (x->size > field->data_size - offsetof(pb_bytes_array_t, bytes))
827 PB_RETURN_ERROR(stream, "bytes overflow");
829 return pb_read(stream, x->bytes, x->size);
832 bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
836 if (!pb_decode_varint32(stream, &size))
839 /* Check length, noting the null terminator */
840 if (size + 1 > field->data_size)
841 PB_RETURN_ERROR(stream, "string overflow");
843 status = pb_read(stream, (uint8_t*)dest, size);
844 *((uint8_t*)dest + size) = 0;
848 bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
851 pb_istream_t substream;
852 const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;
854 if (!pb_make_string_substream(stream, &substream))
857 if (field->ptr == NULL)
858 PB_RETURN_ERROR(stream, "invalid field descriptor");
860 /* New array entries need to be initialized, while required and optional
861 * submessages have already been initialized in the top-level pb_decode. */
862 if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
863 status = pb_decode(&substream, submsg_fields, dest);
865 status = pb_decode_noinit(&substream, submsg_fields, dest);
867 pb_close_string_substream(stream, &substream);