1 /* pb_decode.c -- decode a protobuf using minimal resources
3 * 2011 Petteri Aimonen <jpa@kapsi.fi>
6 /* The warn_unused_result attribute appeared first in gcc-3.4.0 */
7 #if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)
10 /* Verify that we remember to check all return values for proper error propagation */
11 #define checkreturn __attribute__((warn_unused_result))
14 #define NANOPB_INTERNALS
16 #include "pb_decode.h"
18 typedef bool (*pb_decoder_t)(pb_istream_t *stream, const pb_field_t *field, void *dest) checkreturn;
20 /* --- Function pointers to field decoders ---
21 * Order in the array must match pb_action_t LTYPE numbering.
23 static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = {
39 static bool checkreturn buf_read(pb_istream_t *stream, uint8_t *buf, size_t count)
41 uint8_t *source = (uint8_t*)stream->state;
42 stream->state = source + count;
53 bool checkreturn pb_read(pb_istream_t *stream, uint8_t *buf, size_t count)
55 #ifndef PB_BUFFER_ONLY
56 if (buf == NULL && stream->callback != buf_read)
58 /* Skip input bytes */
62 if (!pb_read(stream, tmp, 16))
68 return pb_read(stream, tmp, count);
72 if (stream->bytes_left < count)
73 PB_RETURN_ERROR(stream, "end-of-stream");
75 #ifndef PB_BUFFER_ONLY
76 if (!stream->callback(stream, buf, count))
77 PB_RETURN_ERROR(stream, "io error");
79 if (!buf_read(stream, buf, count))
83 stream->bytes_left -= count;
87 pb_istream_t pb_istream_from_buffer(uint8_t *buf, size_t bufsize)
91 stream.callback = NULL;
93 stream.callback = &buf_read;
96 stream.bytes_left = bufsize;
103 /********************
105 ********************/
107 static bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest)
112 if (!pb_read(stream, &byte, 1))
117 /* Quick case, 1 byte value */
124 result = byte & 0x7F;
129 PB_RETURN_ERROR(stream, "varint overflow");
131 if (!pb_read(stream, &byte, 1))
134 result |= (uint32_t)(byte & 0x7F) << bitpos;
135 bitpos = (uint8_t)(bitpos + 7);
136 } while (byte & 0x80);
143 bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest)
152 PB_RETURN_ERROR(stream, "varint overflow");
154 if (!pb_read(stream, &byte, 1))
157 result |= (uint64_t)(byte & 0x7F) << bitpos;
158 bitpos = (uint8_t)(bitpos + 7);
159 } while (byte & 0x80);
165 bool checkreturn pb_skip_varint(pb_istream_t *stream)
170 if (!pb_read(stream, &byte, 1))
172 } while (byte & 0x80);
176 bool checkreturn pb_skip_string(pb_istream_t *stream)
179 if (!pb_decode_varint32(stream, &length))
182 return pb_read(stream, NULL, length);
185 bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof)
189 *wire_type = (pb_wire_type_t) 0;
192 if (!pb_decode_varint32(stream, &temp))
194 if (stream->bytes_left == 0)
202 *eof = true; /* Special feature: allow 0-terminated messages. */
207 *wire_type = (pb_wire_type_t)(temp & 7);
211 bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type)
215 case PB_WT_VARINT: return pb_skip_varint(stream);
216 case PB_WT_64BIT: return pb_read(stream, NULL, 8);
217 case PB_WT_STRING: return pb_skip_string(stream);
218 case PB_WT_32BIT: return pb_read(stream, NULL, 4);
219 default: PB_RETURN_ERROR(stream, "invalid wire_type");
223 /* Read a raw value to buffer, for the purpose of passing it to callback as
224 * a substream. Size is maximum size on call, and actual size on return.
226 static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, uint8_t *buf, size_t *size)
228 size_t max_size = *size;
236 if (*size > max_size) return false;
237 if (!pb_read(stream, buf, 1)) return false;
238 } while (*buf++ & 0x80);
243 return pb_read(stream, buf, 8);
247 return pb_read(stream, buf, 4);
249 default: PB_RETURN_ERROR(stream, "invalid wire_type");
253 /* Decode string length from stream and return a substream with limited length.
254 * Remember to close the substream using pb_close_string_substream().
256 bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream)
259 if (!pb_decode_varint32(stream, &size))
262 *substream = *stream;
263 if (substream->bytes_left < size)
264 PB_RETURN_ERROR(stream, "parent stream too short");
266 substream->bytes_left = size;
267 stream->bytes_left -= size;
271 void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream)
273 stream->state = substream->state;
276 stream->errmsg = substream->errmsg;
280 /* Iterator for pb_field_t list */
282 const pb_field_t *start; /* Start of the pb_field_t array */
283 const pb_field_t *pos; /* Current position of the iterator */
284 unsigned field_index; /* Zero-based index of the field. */
285 unsigned required_field_index; /* Zero-based index that counts only the required fields */
286 void *dest_struct; /* Pointer to the destination structure to decode to */
287 void *pData; /* Pointer where to store current field value */
288 void *pSize; /* Pointer where to store the size of current array field */
289 } pb_field_iterator_t;
291 static void pb_field_init(pb_field_iterator_t *iter, const pb_field_t *fields, void *dest_struct)
293 iter->start = iter->pos = fields;
294 iter->field_index = 0;
295 iter->required_field_index = 0;
296 iter->pData = (char*)dest_struct + iter->pos->data_offset;
297 iter->pSize = (char*)iter->pData + iter->pos->size_offset;
298 iter->dest_struct = dest_struct;
301 static bool pb_field_next(pb_field_iterator_t *iter)
303 bool notwrapped = true;
304 size_t prev_size = iter->pos->data_size;
306 if (PB_ATYPE(iter->pos->type) == PB_ATYPE_STATIC &&
307 PB_HTYPE(iter->pos->type) == PB_HTYPE_REPEATED)
309 prev_size *= iter->pos->array_size;
312 if (iter->pos->tag == 0)
313 return false; /* Only happens with empty message types */
315 if (PB_HTYPE(iter->pos->type) == PB_HTYPE_REQUIRED)
316 iter->required_field_index++;
320 if (iter->pos->tag == 0)
322 iter->pos = iter->start;
323 iter->field_index = 0;
324 iter->required_field_index = 0;
325 iter->pData = iter->dest_struct;
330 iter->pData = (char*)iter->pData + prev_size + iter->pos->data_offset;
331 iter->pSize = (char*)iter->pData + iter->pos->size_offset;
335 static bool checkreturn pb_field_find(pb_field_iterator_t *iter, uint32_t tag)
337 unsigned start = iter->field_index;
340 if (iter->pos->tag == tag &&
341 PB_LTYPE(iter->pos->type) != PB_LTYPE_EXTENSION)
346 } while (iter->field_index != start);
351 /*************************
352 * Decode a single field *
353 *************************/
355 static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
360 type = iter->pos->type;
361 func = PB_DECODERS[PB_LTYPE(type)];
363 switch (PB_HTYPE(type))
365 case PB_HTYPE_REQUIRED:
366 return func(stream, iter->pos, iter->pData);
368 case PB_HTYPE_OPTIONAL:
369 *(bool*)iter->pSize = true;
370 return func(stream, iter->pos, iter->pData);
372 case PB_HTYPE_REPEATED:
373 if (wire_type == PB_WT_STRING
374 && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
378 size_t *size = (size_t*)iter->pSize;
379 pb_istream_t substream;
380 if (!pb_make_string_substream(stream, &substream))
383 while (substream.bytes_left && *size < iter->pos->array_size)
385 void *pItem = (uint8_t*)iter->pData + iter->pos->data_size * (*size);
386 if (!func(&substream, iter->pos, pItem))
393 pb_close_string_substream(stream, &substream);
395 if (substream.bytes_left != 0)
396 PB_RETURN_ERROR(stream, "array overflow");
403 size_t *size = (size_t*)iter->pSize;
404 void *pItem = (uint8_t*)iter->pData + iter->pos->data_size * (*size);
405 if (*size >= iter->pos->array_size)
406 PB_RETURN_ERROR(stream, "array overflow");
409 return func(stream, iter->pos, pItem);
413 PB_RETURN_ERROR(stream, "invalid field type");
417 static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
419 pb_callback_t *pCallback = (pb_callback_t*)iter->pData;
421 #ifdef PB_OLD_CALLBACK_STYLE
422 void *arg = pCallback->arg;
424 void **arg = &(pCallback->arg);
427 if (pCallback->funcs.decode == NULL)
428 return pb_skip_field(stream, wire_type);
430 if (wire_type == PB_WT_STRING)
432 pb_istream_t substream;
434 if (!pb_make_string_substream(stream, &substream))
439 if (!pCallback->funcs.decode(&substream, iter->pos, arg))
440 PB_RETURN_ERROR(stream, "callback failed");
441 } while (substream.bytes_left);
443 pb_close_string_substream(stream, &substream);
448 /* Copy the single scalar value to stack.
449 * This is required so that we can limit the stream length,
450 * which in turn allows to use same callback for packed and
451 * not-packed fields. */
452 pb_istream_t substream;
454 size_t size = sizeof(buffer);
456 if (!read_raw_value(stream, wire_type, buffer, &size))
458 substream = pb_istream_from_buffer(buffer, size);
460 return pCallback->funcs.decode(&substream, iter->pos, arg);
464 static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
466 switch (PB_ATYPE(iter->pos->type))
468 case PB_ATYPE_STATIC:
469 return decode_static_field(stream, wire_type, iter);
471 case PB_ATYPE_CALLBACK:
472 return decode_callback_field(stream, wire_type, iter);
475 PB_RETURN_ERROR(stream, "invalid field type");
479 /* Default handler for extension fields. Expects a pb_field_t structure
480 * in extension->type->arg. */
481 static bool checkreturn default_extension_handler(pb_istream_t *stream,
482 pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type)
484 const pb_field_t *field = (const pb_field_t*)extension->type->arg;
485 pb_field_iterator_t iter;
488 if (field->tag != tag)
493 iter.field_index = 0;
494 iter.required_field_index = 0;
495 iter.dest_struct = extension->dest;
496 iter.pData = extension->dest;
499 return decode_field(stream, wire_type, &iter);
502 /* Try to decode an unknown field as an extension field. Tries each extension
503 * decoder in turn, until one of them handles the field or loop ends. */
504 static bool checkreturn decode_extension(pb_istream_t *stream,
505 uint32_t tag, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
507 pb_extension_t *extension = *(pb_extension_t* const *)iter->pData;
508 size_t pos = stream->bytes_left;
510 while (extension && pos == stream->bytes_left)
513 if (extension->type->decode)
514 status = extension->type->decode(stream, extension, tag, wire_type);
516 status = default_extension_handler(stream, extension, tag, wire_type);
521 extension = extension->next;
527 /* Step through the iterator until an extension field is found or until all
528 * entries have been checked. There can be only one extension field per
529 * message. Returns false if no extension field is found. */
530 static bool checkreturn find_extension_field(pb_field_iterator_t *iter)
532 unsigned start = iter->field_index;
535 if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION)
538 } while (iter->field_index != start);
543 /* Initialize message fields to default values, recursively */
544 static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct)
546 pb_field_iterator_t iter;
547 pb_field_init(&iter, fields, dest_struct);
549 /* Initialize size/has fields and apply default values */
553 type = iter.pos->type;
555 if (iter.pos->tag == 0)
558 if (PB_ATYPE(type) == PB_ATYPE_STATIC)
560 /* Initialize the size field for optional/repeated fields to 0. */
561 if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL)
563 *(bool*)iter.pSize = false;
565 else if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
567 *(size_t*)iter.pSize = 0;
568 continue; /* Array is empty, no need to initialize contents */
571 /* Initialize field contents to default value */
572 if (PB_LTYPE(iter.pos->type) == PB_LTYPE_SUBMESSAGE)
574 pb_message_set_to_defaults((const pb_field_t *) iter.pos->ptr, iter.pData);
576 else if (iter.pos->ptr != NULL)
578 memcpy(iter.pData, iter.pos->ptr, iter.pos->data_size);
582 memset(iter.pData, 0, iter.pos->data_size);
585 else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
587 continue; /* Don't overwrite callback */
589 } while (pb_field_next(&iter));
592 /*********************
593 * Decode all fields *
594 *********************/
596 bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
598 uint8_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 7) / 8] = {0}; /* Used to check for required fields */
599 uint32_t extension_range_start = 0;
600 pb_field_iterator_t iter;
602 pb_field_init(&iter, fields, dest_struct);
604 while (stream->bytes_left)
607 pb_wire_type_t wire_type;
610 if (!pb_decode_tag(stream, &wire_type, &tag, &eof))
618 if (!pb_field_find(&iter, tag))
620 /* No match found, check if it matches an extension. */
621 if (tag >= extension_range_start)
623 if (!find_extension_field(&iter))
624 extension_range_start = (uint32_t)-1;
626 extension_range_start = iter.pos->tag;
628 if (tag >= extension_range_start)
630 size_t pos = stream->bytes_left;
632 if (!decode_extension(stream, tag, wire_type, &iter))
635 if (pos != stream->bytes_left)
637 /* The field was handled */
643 /* No match found, skip data */
644 if (!pb_skip_field(stream, wire_type))
649 if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED
650 && iter.required_field_index < PB_MAX_REQUIRED_FIELDS)
652 fields_seen[iter.required_field_index >> 3] |= (uint8_t)(1 << (iter.required_field_index & 7));
655 if (!decode_field(stream, wire_type, &iter))
659 /* Check that all required fields were present. */
661 /* First figure out the number of required fields by
662 * seeking to the end of the field array. Usually we
663 * are already close to end after decoding.
665 unsigned req_field_count;
669 req_field_count = iter.required_field_index;
670 last_type = iter.pos->type;
671 } while (pb_field_next(&iter));
673 /* Fixup if last field was also required. */
674 if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag)
677 /* Check the whole bytes */
678 for (i = 0; i < (req_field_count >> 3); i++)
680 if (fields_seen[i] != 0xFF)
681 PB_RETURN_ERROR(stream, "missing required field");
684 /* Check the remaining bits */
685 if (fields_seen[req_field_count >> 3] != (0xFF >> (8 - (req_field_count & 7))))
686 PB_RETURN_ERROR(stream, "missing required field");
692 bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
694 pb_message_set_to_defaults(fields, dest_struct);
695 return pb_decode_noinit(stream, fields, dest_struct);
698 bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
700 pb_istream_t substream;
703 if (!pb_make_string_substream(stream, &substream))
706 status = pb_decode(&substream, fields, dest_struct);
707 pb_close_string_substream(stream, &substream);
713 bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest)
716 if (!pb_decode_varint(stream, &value))
720 *dest = (int64_t)(~(value >> 1));
722 *dest = (int64_t)(value >> 1);
727 bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
729 #ifdef __BIG_ENDIAN__
730 uint8_t *bytes = (uint8_t*)dest;
733 if (!pb_read(stream, lebytes, 4))
736 bytes[0] = lebytes[3];
737 bytes[1] = lebytes[2];
738 bytes[2] = lebytes[1];
739 bytes[3] = lebytes[0];
742 return pb_read(stream, (uint8_t*)dest, 4);
746 bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
748 #ifdef __BIG_ENDIAN__
749 uint8_t *bytes = (uint8_t*)dest;
752 if (!pb_read(stream, lebytes, 8))
755 bytes[0] = lebytes[7];
756 bytes[1] = lebytes[6];
757 bytes[2] = lebytes[5];
758 bytes[3] = lebytes[4];
759 bytes[4] = lebytes[3];
760 bytes[5] = lebytes[2];
761 bytes[6] = lebytes[1];
762 bytes[7] = lebytes[0];
765 return pb_read(stream, (uint8_t*)dest, 8);
769 bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
772 if (!pb_decode_varint(stream, &value))
775 switch (field->data_size)
777 case 1: *(uint8_t*)dest = (uint8_t)value; break;
778 case 2: *(uint16_t*)dest = (uint16_t)value; break;
779 case 4: *(uint32_t*)dest = (uint32_t)value; break;
780 case 8: *(uint64_t*)dest = value; break;
781 default: PB_RETURN_ERROR(stream, "invalid data_size");
787 bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
790 if (!pb_decode_svarint(stream, &value))
793 switch (field->data_size)
795 case 4: *(int32_t*)dest = (int32_t)value; break;
796 case 8: *(int64_t*)dest = value; break;
797 default: PB_RETURN_ERROR(stream, "invalid data_size");
803 bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)
806 return pb_decode_fixed32(stream, dest);
809 bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)
812 return pb_decode_fixed64(stream, dest);
815 bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
817 pb_bytes_array_t *x = (pb_bytes_array_t*)dest;
820 if (!pb_decode_varint32(stream, &temp))
824 /* Check length, noting the space taken by the size_t header. */
825 if (x->size > field->data_size - offsetof(pb_bytes_array_t, bytes))
826 PB_RETURN_ERROR(stream, "bytes overflow");
828 return pb_read(stream, x->bytes, x->size);
831 bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
835 if (!pb_decode_varint32(stream, &size))
838 /* Check length, noting the null terminator */
839 if (size + 1 > field->data_size)
840 PB_RETURN_ERROR(stream, "string overflow");
842 status = pb_read(stream, (uint8_t*)dest, size);
843 *((uint8_t*)dest + size) = 0;
847 bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
850 pb_istream_t substream;
851 const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;
853 if (!pb_make_string_substream(stream, &substream))
856 if (field->ptr == NULL)
857 PB_RETURN_ERROR(stream, "invalid field descriptor");
859 /* New array entries need to be initialized, while required and optional
860 * submessages have already been initialized in the top-level pb_decode. */
861 if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
862 status = pb_decode(&substream, submsg_fields, dest);
864 status = pb_decode_noinit(&substream, submsg_fields, dest);
866 pb_close_string_substream(stream, &substream);