Proyectos de Subversion Iphone Microlearning

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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, pb_byte_t *buf, size_t count);
27
static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size);
28
static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
29
static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
30
static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
31
static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension);
32
static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type);
33
static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter);
34
static bool checkreturn find_extension_field(pb_field_iter_t *iter);
35
static void pb_field_set_to_default(pb_field_iter_t *iter);
36
static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct);
37
static bool checkreturn pb_dec_bool(pb_istream_t *stream, const pb_field_t *field, void *dest);
38
static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest);
39
static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof);
40
static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
41
static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
42
static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest);
43
static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest);
44
static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest);
45
static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest);
46
static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest);
47
static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest);
48
static bool checkreturn pb_skip_varint(pb_istream_t *stream);
49
static bool checkreturn pb_skip_string(pb_istream_t *stream);
50
 
51
#ifdef PB_ENABLE_MALLOC
52
static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size);
53
static bool checkreturn pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter);
54
static void pb_release_single_field(const pb_field_iter_t *iter);
55
#endif
56
 
57
#ifdef PB_WITHOUT_64BIT
58
#define pb_int64_t int32_t
59
#define pb_uint64_t uint32_t
60
#else
61
#define pb_int64_t int64_t
62
#define pb_uint64_t uint64_t
63
#endif
64
 
65
/* --- Function pointers to field decoders ---
66
 * Order in the array must match pb_action_t LTYPE numbering.
67
 */
68
static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = {
69
    &pb_dec_bool,
70
    &pb_dec_varint,
71
    &pb_dec_uvarint,
72
    &pb_dec_svarint,
73
    &pb_dec_fixed32,
74
    &pb_dec_fixed64,
75
 
76
    &pb_dec_bytes,
77
    &pb_dec_string,
78
    &pb_dec_submessage,
79
    NULL, /* extensions */
80
    &pb_dec_fixed_length_bytes
81
};
82
 
83
/*******************************
84
 * pb_istream_t implementation *
85
 *******************************/
86
 
87
static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count)
88
{
89
    size_t i;
90
    const pb_byte_t *source = (const pb_byte_t*)stream->state;
91
    stream->state = (pb_byte_t*)stream->state + count;
92
 
93
    if (buf != NULL)
94
    {
95
        for (i = 0; i < count; i++)
96
            buf[i] = source[i];
97
    }
98
 
99
    return true;
100
}
101
 
102
bool checkreturn pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count)
103
{
104
    if (count == 0)
105
        return true;
106
 
107
#ifndef PB_BUFFER_ONLY
108
	if (buf == NULL && stream->callback != buf_read)
109
	{
110
		/* Skip input bytes */
111
		pb_byte_t tmp[16];
112
		while (count > 16)
113
		{
114
			if (!pb_read(stream, tmp, 16))
115
				return false;
116
 
117
			count -= 16;
118
		}
119
 
120
		return pb_read(stream, tmp, count);
121
	}
122
#endif
123
 
124
    if (stream->bytes_left < count)
125
        PB_RETURN_ERROR(stream, "end-of-stream");
126
 
127
#ifndef PB_BUFFER_ONLY
128
    if (!stream->callback(stream, buf, count))
129
        PB_RETURN_ERROR(stream, "io error");
130
#else
131
    if (!buf_read(stream, buf, count))
132
        return false;
133
#endif
134
 
135
    stream->bytes_left -= count;
136
    return true;
137
}
138
 
139
/* Read a single byte from input stream. buf may not be NULL.
140
 * This is an optimization for the varint decoding. */
141
static bool checkreturn pb_readbyte(pb_istream_t *stream, pb_byte_t *buf)
142
{
143
    if (stream->bytes_left == 0)
144
        PB_RETURN_ERROR(stream, "end-of-stream");
145
 
146
#ifndef PB_BUFFER_ONLY
147
    if (!stream->callback(stream, buf, 1))
148
        PB_RETURN_ERROR(stream, "io error");
149
#else
150
    *buf = *(const pb_byte_t*)stream->state;
151
    stream->state = (pb_byte_t*)stream->state + 1;
152
#endif
153
 
154
    stream->bytes_left--;
155
 
156
    return true;
157
}
158
 
159
pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize)
160
{
161
    pb_istream_t stream;
162
    /* Cast away the const from buf without a compiler error.  We are
163
     * careful to use it only in a const manner in the callbacks.
164
     */
165
    union {
166
        void *state;
167
        const void *c_state;
168
    } state;
169
#ifdef PB_BUFFER_ONLY
170
    stream.callback = NULL;
171
#else
172
    stream.callback = &buf_read;
173
#endif
174
    state.c_state = buf;
175
    stream.state = state.state;
176
    stream.bytes_left = bufsize;
177
#ifndef PB_NO_ERRMSG
178
    stream.errmsg = NULL;
179
#endif
180
    return stream;
181
}
182
 
183
/********************
184
 * Helper functions *
185
 ********************/
186
 
187
static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof)
188
{
189
    pb_byte_t byte;
190
    uint32_t result;
191
 
192
    if (!pb_readbyte(stream, &byte))
193
    {
194
        if (stream->bytes_left == 0)
195
        {
196
            if (eof)
197
            {
198
                *eof = true;
199
            }
200
        }
201
 
202
        return false;
203
    }
204
 
205
    if ((byte & 0x80) == 0)
206
    {
207
        /* Quick case, 1 byte value */
208
        result = byte;
209
    }
210
    else
211
    {
212
        /* Multibyte case */
213
        uint_fast8_t bitpos = 7;
214
        result = byte & 0x7F;
215
 
216
        do
217
        {
218
            if (!pb_readbyte(stream, &byte))
219
                return false;
220
 
221
            if (bitpos >= 32)
222
            {
223
                /* Note: The varint could have trailing 0x80 bytes, or 0xFF for negative. */
224
                uint8_t sign_extension = (bitpos < 63) ? 0xFF : 0x01;
225
 
226
                if ((byte & 0x7F) != 0x00 && ((result >> 31) == 0 || byte != sign_extension))
227
                {
228
                    PB_RETURN_ERROR(stream, "varint overflow");
229
                }
230
            }
231
            else
232
            {
233
                result |= (uint32_t)(byte & 0x7F) << bitpos;
234
            }
235
            bitpos = (uint_fast8_t)(bitpos + 7);
236
        } while (byte & 0x80);
237
 
238
        if (bitpos == 35 && (byte & 0x70) != 0)
239
        {
240
            /* The last byte was at bitpos=28, so only bottom 4 bits fit. */
241
            PB_RETURN_ERROR(stream, "varint overflow");
242
        }
243
   }
244
 
245
   *dest = result;
246
   return true;
247
}
248
 
249
bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest)
250
{
251
    return pb_decode_varint32_eof(stream, dest, NULL);
252
}
253
 
254
#ifndef PB_WITHOUT_64BIT
255
bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest)
256
{
257
    pb_byte_t byte;
258
    uint_fast8_t bitpos = 0;
259
    uint64_t result = 0;
260
 
261
    do
262
    {
263
        if (bitpos >= 64)
264
            PB_RETURN_ERROR(stream, "varint overflow");
265
 
266
        if (!pb_readbyte(stream, &byte))
267
            return false;
268
 
269
        result |= (uint64_t)(byte & 0x7F) << bitpos;
270
        bitpos = (uint_fast8_t)(bitpos + 7);
271
    } while (byte & 0x80);
272
 
273
    *dest = result;
274
    return true;
275
}
276
#endif
277
 
278
bool checkreturn pb_skip_varint(pb_istream_t *stream)
279
{
280
    pb_byte_t byte;
281
    do
282
    {
283
        if (!pb_read(stream, &byte, 1))
284
            return false;
285
    } while (byte & 0x80);
286
    return true;
287
}
288
 
289
bool checkreturn pb_skip_string(pb_istream_t *stream)
290
{
291
    uint32_t length;
292
    if (!pb_decode_varint32(stream, &length))
293
        return false;
294
 
295
    return pb_read(stream, NULL, length);
296
}
297
 
298
bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof)
299
{
300
    uint32_t temp;
301
    *eof = false;
302
    *wire_type = (pb_wire_type_t) 0;
303
    *tag = 0;
304
 
305
    if (!pb_decode_varint32_eof(stream, &temp, eof))
306
    {
307
        return false;
308
    }
309
 
310
    if (temp == 0)
311
    {
312
        *eof = true; /* Special feature: allow 0-terminated messages. */
313
        return false;
314
    }
315
 
316
    *tag = temp >> 3;
317
    *wire_type = (pb_wire_type_t)(temp & 7);
318
    return true;
319
}
320
 
321
bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type)
322
{
323
    switch (wire_type)
324
    {
325
        case PB_WT_VARINT: return pb_skip_varint(stream);
326
        case PB_WT_64BIT: return pb_read(stream, NULL, 8);
327
        case PB_WT_STRING: return pb_skip_string(stream);
328
        case PB_WT_32BIT: return pb_read(stream, NULL, 4);
329
        default: PB_RETURN_ERROR(stream, "invalid wire_type");
330
    }
331
}
332
 
333
/* Read a raw value to buffer, for the purpose of passing it to callback as
334
 * a substream. Size is maximum size on call, and actual size on return.
335
 */
336
static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size)
337
{
338
    size_t max_size = *size;
339
    switch (wire_type)
340
    {
341
        case PB_WT_VARINT:
342
            *size = 0;
343
            do
344
            {
345
                (*size)++;
346
                if (*size > max_size) return false;
347
                if (!pb_read(stream, buf, 1)) return false;
348
            } while (*buf++ & 0x80);
349
            return true;
350
 
351
        case PB_WT_64BIT:
352
            *size = 8;
353
            return pb_read(stream, buf, 8);
354
 
355
        case PB_WT_32BIT:
356
            *size = 4;
357
            return pb_read(stream, buf, 4);
358
 
359
        case PB_WT_STRING:
360
            /* Calling read_raw_value with a PB_WT_STRING is an error.
361
             * Explicitly handle this case and fallthrough to default to avoid
362
             * compiler warnings.
363
             */
364
 
365
        default: PB_RETURN_ERROR(stream, "invalid wire_type");
366
    }
367
}
368
 
369
/* Decode string length from stream and return a substream with limited length.
370
 * Remember to close the substream using pb_close_string_substream().
371
 */
372
bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream)
373
{
374
    uint32_t size;
375
    if (!pb_decode_varint32(stream, &size))
376
        return false;
377
 
378
    *substream = *stream;
379
    if (substream->bytes_left < size)
380
        PB_RETURN_ERROR(stream, "parent stream too short");
381
 
382
    substream->bytes_left = size;
383
    stream->bytes_left -= size;
384
    return true;
385
}
386
 
387
bool checkreturn pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream)
388
{
389
    if (substream->bytes_left) {
390
        if (!pb_read(substream, NULL, substream->bytes_left))
391
            return false;
392
    }
393
 
394
    stream->state = substream->state;
395
 
396
#ifndef PB_NO_ERRMSG
397
    stream->errmsg = substream->errmsg;
398
#endif
399
    return true;
400
}
401
 
402
/*************************
403
 * Decode a single field *
404
 *************************/
405
 
406
static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
407
{
408
    pb_type_t type;
409
    pb_decoder_t func;
410
 
411
    type = iter->pos->type;
412
    func = PB_DECODERS[PB_LTYPE(type)];
413
 
414
    switch (PB_HTYPE(type))
415
    {
416
        case PB_HTYPE_REQUIRED:
417
            return func(stream, iter->pos, iter->pData);
418
 
419
        case PB_HTYPE_OPTIONAL:
420
            if (iter->pSize != iter->pData)
421
                *(bool*)iter->pSize = true;
422
            return func(stream, iter->pos, iter->pData);
423
 
424
        case PB_HTYPE_REPEATED:
425
            if (wire_type == PB_WT_STRING
426
                && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
427
            {
428
                /* Packed array */
429
                bool status = true;
430
                pb_size_t *size = (pb_size_t*)iter->pSize;
431
 
432
                pb_istream_t substream;
433
                if (!pb_make_string_substream(stream, &substream))
434
                    return false;
435
 
436
                while (substream.bytes_left > 0 && *size < iter->pos->array_size)
437
                {
438
                    void *pItem = (char*)iter->pData + iter->pos->data_size * (*size);
439
                    if (!func(&substream, iter->pos, pItem))
440
                    {
441
                        status = false;
442
                        break;
443
                    }
444
                    (*size)++;
445
                }
446
 
447
                if (substream.bytes_left != 0)
448
                    PB_RETURN_ERROR(stream, "array overflow");
449
                if (!pb_close_string_substream(stream, &substream))
450
                    return false;
451
 
452
                return status;
453
            }
454
            else
455
            {
456
                /* Repeated field */
457
                pb_size_t *size = (pb_size_t*)iter->pSize;
458
                char *pItem = (char*)iter->pData + iter->pos->data_size * (*size);
459
 
460
                if ((*size)++ >= iter->pos->array_size)
461
                    PB_RETURN_ERROR(stream, "array overflow");
462
 
463
                return func(stream, iter->pos, pItem);
464
            }
465
 
466
        case PB_HTYPE_ONEOF:
467
            if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&
468
                *(pb_size_t*)iter->pSize != iter->pos->tag)
469
            {
470
                /* We memset to zero so that any callbacks are set to NULL.
471
                 * This is because the callbacks might otherwise have values
472
                 * from some other union field. */
473
                memset(iter->pData, 0, iter->pos->data_size);
474
                pb_message_set_to_defaults((const pb_field_t*)iter->pos->ptr, iter->pData);
475
            }
476
            *(pb_size_t*)iter->pSize = iter->pos->tag;
477
 
478
            return func(stream, iter->pos, iter->pData);
479
 
480
        default:
481
            PB_RETURN_ERROR(stream, "invalid field type");
482
    }
483
}
484
 
485
#ifdef PB_ENABLE_MALLOC
486
/* Allocate storage for the field and store the pointer at iter->pData.
487
 * array_size is the number of entries to reserve in an array.
488
 * Zero size is not allowed, use pb_free() for releasing.
489
 */
490
static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size)
491
{
492
    void *ptr = *(void**)pData;
493
 
494
    if (data_size == 0 || array_size == 0)
495
        PB_RETURN_ERROR(stream, "invalid size");
496
 
497
#ifdef __AVR__
498
    /* Workaround for AVR libc bug 53284: http://savannah.nongnu.org/bugs/?53284
499
     * Realloc to size of 1 byte can cause corruption of the malloc structures.
500
     */
501
    if (data_size == 1 && array_size == 1)
502
    {
503
        data_size = 2;
504
    }
505
#endif
506
 
507
    /* Check for multiplication overflows.
508
     * This code avoids the costly division if the sizes are small enough.
509
     * Multiplication is safe as long as only half of bits are set
510
     * in either multiplicand.
511
     */
512
    {
513
        const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4);
514
        if (data_size >= check_limit || array_size >= check_limit)
515
        {
516
            const size_t size_max = (size_t)-1;
517
            if (size_max / array_size < data_size)
518
            {
519
                PB_RETURN_ERROR(stream, "size too large");
520
            }
521
        }
522
    }
523
 
524
    /* Allocate new or expand previous allocation */
525
    /* Note: on failure the old pointer will remain in the structure,
526
     * the message must be freed by caller also on error return. */
527
    ptr = pb_realloc(ptr, array_size * data_size);
528
    if (ptr == NULL)
529
        PB_RETURN_ERROR(stream, "realloc failed");
530
 
531
    *(void**)pData = ptr;
532
    return true;
533
}
534
 
535
/* Clear a newly allocated item in case it contains a pointer, or is a submessage. */
536
static void initialize_pointer_field(void *pItem, pb_field_iter_t *iter)
537
{
538
    if (PB_LTYPE(iter->pos->type) == PB_LTYPE_STRING ||
539
        PB_LTYPE(iter->pos->type) == PB_LTYPE_BYTES)
540
    {
541
        *(void**)pItem = NULL;
542
    }
543
    else if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE)
544
    {
545
        /* We memset to zero so that any callbacks are set to NULL.
546
         * Then set any default values. */
547
        memset(pItem, 0, iter->pos->data_size);
548
        pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, pItem);
549
    }
550
}
551
#endif
552
 
553
static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
554
{
555
#ifndef PB_ENABLE_MALLOC
556
    PB_UNUSED(wire_type);
557
    PB_UNUSED(iter);
558
    PB_RETURN_ERROR(stream, "no malloc support");
559
#else
560
    pb_type_t type;
561
    pb_decoder_t func;
562
 
563
    type = iter->pos->type;
564
    func = PB_DECODERS[PB_LTYPE(type)];
565
 
566
    switch (PB_HTYPE(type))
567
    {
568
        case PB_HTYPE_REQUIRED:
569
        case PB_HTYPE_OPTIONAL:
570
        case PB_HTYPE_ONEOF:
571
            if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&
572
                *(void**)iter->pData != NULL)
573
            {
574
                /* Duplicate field, have to release the old allocation first. */
575
                pb_release_single_field(iter);
576
            }
577
 
578
            if (PB_HTYPE(type) == PB_HTYPE_ONEOF)
579
            {
580
                *(pb_size_t*)iter->pSize = iter->pos->tag;
581
            }
582
 
583
            if (PB_LTYPE(type) == PB_LTYPE_STRING ||
584
                PB_LTYPE(type) == PB_LTYPE_BYTES)
585
            {
586
                return func(stream, iter->pos, iter->pData);
587
            }
588
            else
589
            {
590
                if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))
591
                    return false;
592
 
593
                initialize_pointer_field(*(void**)iter->pData, iter);
594
                return func(stream, iter->pos, *(void**)iter->pData);
595
            }
596
 
597
        case PB_HTYPE_REPEATED:
598
            if (wire_type == PB_WT_STRING
599
                && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
600
            {
601
                /* Packed array, multiple items come in at once. */
602
                bool status = true;
603
                pb_size_t *size = (pb_size_t*)iter->pSize;
604
                size_t allocated_size = *size;
605
                void *pItem;
606
                pb_istream_t substream;
607
 
608
                if (!pb_make_string_substream(stream, &substream))
609
                    return false;
610
 
611
                while (substream.bytes_left)
612
                {
613
                    if (*size == PB_SIZE_MAX)
614
                    {
615
#ifndef PB_NO_ERRMSG
616
                        stream->errmsg = "too many array entries";
617
#endif
618
                        status = false;
619
                        break;
620
                    }
621
 
622
                    if ((size_t)*size + 1 > allocated_size)
623
                    {
624
                        /* Allocate more storage. This tries to guess the
625
                         * number of remaining entries. Round the division
626
                         * upwards. */
627
                        size_t remain = (substream.bytes_left - 1) / iter->pos->data_size + 1;
628
                        if (remain < PB_SIZE_MAX - allocated_size)
629
                            allocated_size += remain;
630
                        else
631
                            allocated_size += 1;
632
 
633
                        if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))
634
                        {
635
                            status = false;
636
                            break;
637
                        }
638
                    }
639
 
640
                    /* Decode the array entry */
641
                    pItem = *(char**)iter->pData + iter->pos->data_size * (*size);
642
                    initialize_pointer_field(pItem, iter);
643
                    if (!func(&substream, iter->pos, pItem))
644
                    {
645
                        status = false;
646
                        break;
647
                    }
648
 
649
                    (*size)++;
650
                }
651
                if (!pb_close_string_substream(stream, &substream))
652
                    return false;
653
 
654
                return status;
655
            }
656
            else
657
            {
658
                /* Normal repeated field, i.e. only one item at a time. */
659
                pb_size_t *size = (pb_size_t*)iter->pSize;
660
                void *pItem;
661
 
662
                if (*size == PB_SIZE_MAX)
663
                    PB_RETURN_ERROR(stream, "too many array entries");
664
 
665
                if (!allocate_field(stream, iter->pData, iter->pos->data_size, (size_t)(*size + 1)))
666
                    return false;
667
 
668
                pItem = *(char**)iter->pData + iter->pos->data_size * (*size);
669
                (*size)++;
670
                initialize_pointer_field(pItem, iter);
671
                return func(stream, iter->pos, pItem);
672
            }
673
 
674
        default:
675
            PB_RETURN_ERROR(stream, "invalid field type");
676
    }
677
#endif
678
}
679
 
680
static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
681
{
682
    pb_callback_t *pCallback = (pb_callback_t*)iter->pData;
683
#ifdef PB_OLD_CALLBACK_STYLE
684
    void *arg;
685
#else
686
    void **arg;
687
#endif
688
 
689
    if (pCallback == NULL || pCallback->funcs.decode == NULL)
690
        return pb_skip_field(stream, wire_type);
691
 
692
#ifdef PB_OLD_CALLBACK_STYLE
693
    arg = pCallback->arg;
694
#else
695
    arg = &(pCallback->arg);
696
#endif
697
 
698
    if (wire_type == PB_WT_STRING)
699
    {
700
        pb_istream_t substream;
701
 
702
        if (!pb_make_string_substream(stream, &substream))
703
            return false;
704
 
705
        do
706
        {
707
            if (!pCallback->funcs.decode(&substream, iter->pos, arg))
708
                PB_RETURN_ERROR(stream, "callback failed");
709
        } while (substream.bytes_left);
710
 
711
        if (!pb_close_string_substream(stream, &substream))
712
            return false;
713
 
714
        return true;
715
    }
716
    else
717
    {
718
        /* Copy the single scalar value to stack.
719
         * This is required so that we can limit the stream length,
720
         * which in turn allows to use same callback for packed and
721
         * not-packed fields. */
722
        pb_istream_t substream;
723
        pb_byte_t buffer[10];
724
        size_t size = sizeof(buffer);
725
 
726
        if (!read_raw_value(stream, wire_type, buffer, &size))
727
            return false;
728
        substream = pb_istream_from_buffer(buffer, size);
729
 
730
        return pCallback->funcs.decode(&substream, iter->pos, arg);
731
    }
732
}
733
 
734
static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
735
{
736
#ifdef PB_ENABLE_MALLOC
737
    /* When decoding an oneof field, check if there is old data that must be
738
     * released first. */
739
    if (PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF)
740
    {
741
        if (!pb_release_union_field(stream, iter))
742
            return false;
743
    }
744
#endif
745
 
746
    switch (PB_ATYPE(iter->pos->type))
747
    {
748
        case PB_ATYPE_STATIC:
749
            return decode_static_field(stream, wire_type, iter);
750
 
751
        case PB_ATYPE_POINTER:
752
            return decode_pointer_field(stream, wire_type, iter);
753
 
754
        case PB_ATYPE_CALLBACK:
755
            return decode_callback_field(stream, wire_type, iter);
756
 
757
        default:
758
            PB_RETURN_ERROR(stream, "invalid field type");
759
    }
760
}
761
 
762
static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension)
763
{
764
    /* Fake a field iterator for the extension field.
765
     * It is not actually safe to advance this iterator, but decode_field
766
     * will not even try to. */
767
    const pb_field_t *field = (const pb_field_t*)extension->type->arg;
768
    (void)pb_field_iter_begin(iter, field, extension->dest);
769
    iter->pData = extension->dest;
770
    iter->pSize = &extension->found;
771
 
772
    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
773
    {
774
        /* For pointer extensions, the pointer is stored directly
775
         * in the extension structure. This avoids having an extra
776
         * indirection. */
777
        iter->pData = &extension->dest;
778
    }
779
}
780
 
781
/* Default handler for extension fields. Expects a pb_field_t structure
782
 * in extension->type->arg. */
783
static bool checkreturn default_extension_decoder(pb_istream_t *stream,
784
    pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type)
785
{
786
    const pb_field_t *field = (const pb_field_t*)extension->type->arg;
787
    pb_field_iter_t iter;
788
 
789
    if (field->tag != tag)
790
        return true;
791
 
792
    iter_from_extension(&iter, extension);
793
    extension->found = true;
794
    return decode_field(stream, wire_type, &iter);
795
}
796
 
797
/* Try to decode an unknown field as an extension field. Tries each extension
798
 * decoder in turn, until one of them handles the field or loop ends. */
799
static bool checkreturn decode_extension(pb_istream_t *stream,
800
    uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter)
801
{
802
    pb_extension_t *extension = *(pb_extension_t* const *)iter->pData;
803
    size_t pos = stream->bytes_left;
804
 
805
    while (extension != NULL && pos == stream->bytes_left)
806
    {
807
        bool status;
808
        if (extension->type->decode)
809
            status = extension->type->decode(stream, extension, tag, wire_type);
810
        else
811
            status = default_extension_decoder(stream, extension, tag, wire_type);
812
 
813
        if (!status)
814
            return false;
815
 
816
        extension = extension->next;
817
    }
818
 
819
    return true;
820
}
821
 
822
/* Step through the iterator until an extension field is found or until all
823
 * entries have been checked. There can be only one extension field per
824
 * message. Returns false if no extension field is found. */
825
static bool checkreturn find_extension_field(pb_field_iter_t *iter)
826
{
827
    const pb_field_t *start = iter->pos;
828
 
829
    do {
830
        if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION)
831
            return true;
832
        (void)pb_field_iter_next(iter);
833
    } while (iter->pos != start);
834
 
835
    return false;
836
}
837
 
838
/* Initialize message fields to default values, recursively */
839
static void pb_field_set_to_default(pb_field_iter_t *iter)
840
{
841
    pb_type_t type;
842
    type = iter->pos->type;
843
 
844
    if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
845
    {
846
        pb_extension_t *ext = *(pb_extension_t* const *)iter->pData;
847
        while (ext != NULL)
848
        {
849
            pb_field_iter_t ext_iter;
850
            ext->found = false;
851
            iter_from_extension(&ext_iter, ext);
852
            pb_field_set_to_default(&ext_iter);
853
            ext = ext->next;
854
        }
855
    }
856
    else if (PB_ATYPE(type) == PB_ATYPE_STATIC)
857
    {
858
        bool init_data = true;
859
        if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL && iter->pSize != iter->pData)
860
        {
861
            /* Set has_field to false. Still initialize the optional field
862
             * itself also. */
863
            *(bool*)iter->pSize = false;
864
        }
865
        else if (PB_HTYPE(type) == PB_HTYPE_REPEATED ||
866
                 PB_HTYPE(type) == PB_HTYPE_ONEOF)
867
        {
868
            /* REPEATED: Set array count to 0, no need to initialize contents.
869
               ONEOF: Set which_field to 0. */
870
            *(pb_size_t*)iter->pSize = 0;
871
            init_data = false;
872
        }
873
 
874
        if (init_data)
875
        {
876
            if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE)
877
            {
878
                /* Initialize submessage to defaults */
879
                pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, iter->pData);
880
            }
881
            else if (iter->pos->ptr != NULL)
882
            {
883
                /* Initialize to default value */
884
                memcpy(iter->pData, iter->pos->ptr, iter->pos->data_size);
885
            }
886
            else
887
            {
888
                /* Initialize to zeros */
889
                memset(iter->pData, 0, iter->pos->data_size);
890
            }
891
        }
892
    }
893
    else if (PB_ATYPE(type) == PB_ATYPE_POINTER)
894
    {
895
        /* Initialize the pointer to NULL. */
896
        *(void**)iter->pData = NULL;
897
 
898
        /* Initialize array count to 0. */
899
        if (PB_HTYPE(type) == PB_HTYPE_REPEATED ||
900
            PB_HTYPE(type) == PB_HTYPE_ONEOF)
901
        {
902
            *(pb_size_t*)iter->pSize = 0;
903
        }
904
    }
905
    else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
906
    {
907
        /* Don't overwrite callback */
908
    }
909
}
910
 
911
static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct)
912
{
913
    pb_field_iter_t iter;
914
 
915
    if (!pb_field_iter_begin(&iter, fields, dest_struct))
916
        return; /* Empty message type */
917
 
918
    do
919
    {
920
        pb_field_set_to_default(&iter);
921
    } while (pb_field_iter_next(&iter));
922
}
923
 
924
/*********************
925
 * Decode all fields *
926
 *********************/
927
 
928
bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
929
{
930
    uint32_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 31) / 32] = {0, 0};
931
    const uint32_t allbits = ~(uint32_t)0;
932
    uint32_t extension_range_start = 0;
933
    pb_field_iter_t iter;
934
 
935
    /* 'fixed_count_field' and 'fixed_count_size' track position of a repeated fixed
936
     * count field. This can only handle _one_ repeated fixed count field that
937
     * is unpacked and unordered among other (non repeated fixed count) fields.
938
     */
939
    const pb_field_t *fixed_count_field = NULL;
940
    pb_size_t fixed_count_size = 0;
941
 
942
    /* Return value ignored, as empty message types will be correctly handled by
943
     * pb_field_iter_find() anyway. */
944
    (void)pb_field_iter_begin(&iter, fields, dest_struct);
945
 
946
    while (stream->bytes_left)
947
    {
948
        uint32_t tag;
949
        pb_wire_type_t wire_type;
950
        bool eof;
951
 
952
        if (!pb_decode_tag(stream, &wire_type, &tag, &eof))
953
        {
954
            if (eof)
955
                break;
956
            else
957
                return false;
958
        }
959
 
960
        if (!pb_field_iter_find(&iter, tag))
961
        {
962
            /* No match found, check if it matches an extension. */
963
            if (tag >= extension_range_start)
964
            {
965
                if (!find_extension_field(&iter))
966
                    extension_range_start = (uint32_t)-1;
967
                else
968
                    extension_range_start = iter.pos->tag;
969
 
970
                if (tag >= extension_range_start)
971
                {
972
                    size_t pos = stream->bytes_left;
973
 
974
                    if (!decode_extension(stream, tag, wire_type, &iter))
975
                        return false;
976
 
977
                    if (pos != stream->bytes_left)
978
                    {
979
                        /* The field was handled */
980
                        continue;
981
                    }
982
                }
983
            }
984
 
985
            /* No match found, skip data */
986
            if (!pb_skip_field(stream, wire_type))
987
                return false;
988
            continue;
989
        }
990
 
991
        /* If a repeated fixed count field was found, get size from
992
         * 'fixed_count_field' as there is no counter contained in the struct.
993
         */
994
        if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REPEATED
995
            && iter.pSize == iter.pData)
996
        {
997
            if (fixed_count_field != iter.pos) {
998
                /* If the new fixed count field does not match the previous one,
999
                 * check that the previous one is NULL or that it finished
1000
                 * receiving all the expected data.
1001
                 */
1002
                if (fixed_count_field != NULL &&
1003
                    fixed_count_size != fixed_count_field->array_size)
1004
                {
1005
                    PB_RETURN_ERROR(stream, "wrong size for fixed count field");
1006
                }
1007
 
1008
                fixed_count_field = iter.pos;
1009
                fixed_count_size = 0;
1010
            }
1011
 
1012
            iter.pSize = &fixed_count_size;
1013
        }
1014
 
1015
        if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED
1016
            && iter.required_field_index < PB_MAX_REQUIRED_FIELDS)
1017
        {
1018
            uint32_t tmp = ((uint32_t)1 << (iter.required_field_index & 31));
1019
            fields_seen[iter.required_field_index >> 5] |= tmp;
1020
        }
1021
 
1022
        if (!decode_field(stream, wire_type, &iter))
1023
            return false;
1024
    }
1025
 
1026
    /* Check that all elements of the last decoded fixed count field were present. */
1027
    if (fixed_count_field != NULL &&
1028
        fixed_count_size != fixed_count_field->array_size)
1029
    {
1030
        PB_RETURN_ERROR(stream, "wrong size for fixed count field");
1031
    }
1032
 
1033
    /* Check that all required fields were present. */
1034
    {
1035
        /* First figure out the number of required fields by
1036
         * seeking to the end of the field array. Usually we
1037
         * are already close to end after decoding.
1038
         */
1039
        unsigned req_field_count;
1040
        pb_type_t last_type;
1041
        unsigned i;
1042
        do {
1043
            req_field_count = iter.required_field_index;
1044
            last_type = iter.pos->type;
1045
        } while (pb_field_iter_next(&iter));
1046
 
1047
        /* Fixup if last field was also required. */
1048
        if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0)
1049
            req_field_count++;
1050
 
1051
        if (req_field_count > PB_MAX_REQUIRED_FIELDS)
1052
            req_field_count = PB_MAX_REQUIRED_FIELDS;
1053
 
1054
        if (req_field_count > 0)
1055
        {
1056
            /* Check the whole words */
1057
            for (i = 0; i < (req_field_count >> 5); i++)
1058
            {
1059
                if (fields_seen[i] != allbits)
1060
                    PB_RETURN_ERROR(stream, "missing required field");
1061
            }
1062
 
1063
            /* Check the remaining bits (if any) */
1064
            if ((req_field_count & 31) != 0)
1065
            {
1066
                if (fields_seen[req_field_count >> 5] !=
1067
                    (allbits >> (32 - (req_field_count & 31))))
1068
                {
1069
                    PB_RETURN_ERROR(stream, "missing required field");
1070
                }
1071
            }
1072
        }
1073
    }
1074
 
1075
    return true;
1076
}
1077
 
1078
bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
1079
{
1080
    bool status;
1081
    pb_message_set_to_defaults(fields, dest_struct);
1082
    status = pb_decode_noinit(stream, fields, dest_struct);
1083
 
1084
#ifdef PB_ENABLE_MALLOC
1085
    if (!status)
1086
        pb_release(fields, dest_struct);
1087
#endif
1088
 
1089
    return status;
1090
}
1091
 
1092
bool pb_decode_delimited_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
1093
{
1094
    pb_istream_t substream;
1095
    bool status;
1096
 
1097
    if (!pb_make_string_substream(stream, &substream))
1098
        return false;
1099
 
1100
    status = pb_decode_noinit(&substream, fields, dest_struct);
1101
 
1102
    if (!pb_close_string_substream(stream, &substream))
1103
        return false;
1104
    return status;
1105
}
1106
 
1107
bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
1108
{
1109
    pb_istream_t substream;
1110
    bool status;
1111
 
1112
    if (!pb_make_string_substream(stream, &substream))
1113
        return false;
1114
 
1115
    status = pb_decode(&substream, fields, dest_struct);
1116
 
1117
    if (!pb_close_string_substream(stream, &substream))
1118
        return false;
1119
    return status;
1120
}
1121
 
1122
bool pb_decode_nullterminated(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
1123
{
1124
    /* This behaviour will be separated in nanopb-0.4.0, see issue #278. */
1125
    return pb_decode(stream, fields, dest_struct);
1126
}
1127
 
1128
#ifdef PB_ENABLE_MALLOC
1129
/* Given an oneof field, if there has already been a field inside this oneof,
1130
 * release it before overwriting with a different one. */
1131
static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter)
1132
{
1133
    pb_size_t old_tag = *(pb_size_t*)iter->pSize; /* Previous which_ value */
1134
    pb_size_t new_tag = iter->pos->tag; /* New which_ value */
1135
 
1136
    if (old_tag == 0)
1137
        return true; /* Ok, no old data in union */
1138
 
1139
    if (old_tag == new_tag)
1140
        return true; /* Ok, old data is of same type => merge */
1141
 
1142
    /* Release old data. The find can fail if the message struct contains
1143
     * invalid data. */
1144
    if (!pb_field_iter_find(iter, old_tag))
1145
        PB_RETURN_ERROR(stream, "invalid union tag");
1146
 
1147
    pb_release_single_field(iter);
1148
 
1149
    /* Restore iterator to where it should be.
1150
     * This shouldn't fail unless the pb_field_t structure is corrupted. */
1151
    if (!pb_field_iter_find(iter, new_tag))
1152
        PB_RETURN_ERROR(stream, "iterator error");
1153
 
1154
    if (PB_ATYPE(iter->pos->type) == PB_ATYPE_POINTER)
1155
    {
1156
        /* Initialize the pointer to NULL to make sure it is valid
1157
         * even in case of error return. */
1158
        *(void**)iter->pData = NULL;
1159
    }
1160
 
1161
    return true;
1162
}
1163
 
1164
static void pb_release_single_field(const pb_field_iter_t *iter)
1165
{
1166
    pb_type_t type;
1167
    type = iter->pos->type;
1168
 
1169
    if (PB_HTYPE(type) == PB_HTYPE_ONEOF)
1170
    {
1171
        if (*(pb_size_t*)iter->pSize != iter->pos->tag)
1172
            return; /* This is not the current field in the union */
1173
    }
1174
 
1175
    /* Release anything contained inside an extension or submsg.
1176
     * This has to be done even if the submsg itself is statically
1177
     * allocated. */
1178
    if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
1179
    {
1180
        /* Release fields from all extensions in the linked list */
1181
        pb_extension_t *ext = *(pb_extension_t**)iter->pData;
1182
        while (ext != NULL)
1183
        {
1184
            pb_field_iter_t ext_iter;
1185
            iter_from_extension(&ext_iter, ext);
1186
            pb_release_single_field(&ext_iter);
1187
            ext = ext->next;
1188
        }
1189
    }
1190
    else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE && PB_ATYPE(type) != PB_ATYPE_CALLBACK)
1191
    {
1192
        /* Release fields in submessage or submsg array */
1193
        void *pItem = iter->pData;
1194
        pb_size_t count = 1;
1195
 
1196
        if (PB_ATYPE(type) == PB_ATYPE_POINTER)
1197
        {
1198
            pItem = *(void**)iter->pData;
1199
        }
1200
 
1201
        if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
1202
        {
1203
            if (PB_ATYPE(type) == PB_ATYPE_STATIC && iter->pSize == iter->pData) {
1204
                /* No _count field so use size of the array */
1205
                count = iter->pos->array_size;
1206
            } else {
1207
                count = *(pb_size_t*)iter->pSize;
1208
            }
1209
 
1210
            if (PB_ATYPE(type) == PB_ATYPE_STATIC && count > iter->pos->array_size)
1211
            {
1212
                /* Protect against corrupted _count fields */
1213
                count = iter->pos->array_size;
1214
            }
1215
        }
1216
 
1217
        if (pItem)
1218
        {
1219
            while (count--)
1220
            {
1221
                pb_release((const pb_field_t*)iter->pos->ptr, pItem);
1222
                pItem = (char*)pItem + iter->pos->data_size;
1223
            }
1224
        }
1225
    }
1226
 
1227
    if (PB_ATYPE(type) == PB_ATYPE_POINTER)
1228
    {
1229
        if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&
1230
            (PB_LTYPE(type) == PB_LTYPE_STRING ||
1231
             PB_LTYPE(type) == PB_LTYPE_BYTES))
1232
        {
1233
            /* Release entries in repeated string or bytes array */
1234
            void **pItem = *(void***)iter->pData;
1235
            pb_size_t count = *(pb_size_t*)iter->pSize;
1236
            while (count--)
1237
            {
1238
                pb_free(*pItem);
1239
                *pItem++ = NULL;
1240
            }
1241
        }
1242
 
1243
        if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
1244
        {
1245
            /* We are going to release the array, so set the size to 0 */
1246
            *(pb_size_t*)iter->pSize = 0;
1247
        }
1248
 
1249
        /* Release main item */
1250
        pb_free(*(void**)iter->pData);
1251
        *(void**)iter->pData = NULL;
1252
    }
1253
}
1254
 
1255
void pb_release(const pb_field_t fields[], void *dest_struct)
1256
{
1257
    pb_field_iter_t iter;
1258
 
1259
    if (!dest_struct)
1260
        return; /* Ignore NULL pointers, similar to free() */
1261
 
1262
    if (!pb_field_iter_begin(&iter, fields, dest_struct))
1263
        return; /* Empty message type */
1264
 
1265
    do
1266
    {
1267
        pb_release_single_field(&iter);
1268
    } while (pb_field_iter_next(&iter));
1269
}
1270
#endif
1271
 
1272
/* Field decoders */
1273
 
1274
bool pb_decode_bool(pb_istream_t *stream, bool *dest)
1275
{
1276
    return pb_dec_bool(stream, NULL, (void*)dest);
1277
}
1278
 
1279
bool pb_decode_svarint(pb_istream_t *stream, pb_int64_t *dest)
1280
{
1281
    pb_uint64_t value;
1282
    if (!pb_decode_varint(stream, &value))
1283
        return false;
1284
 
1285
    if (value & 1)
1286
        *dest = (pb_int64_t)(~(value >> 1));
1287
    else
1288
        *dest = (pb_int64_t)(value >> 1);
1289
 
1290
    return true;
1291
}
1292
 
1293
bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
1294
{
1295
    pb_byte_t bytes[4];
1296
 
1297
    if (!pb_read(stream, bytes, 4))
1298
        return false;
1299
 
1300
    *(uint32_t*)dest = ((uint32_t)bytes[0] << 0) |
1301
                       ((uint32_t)bytes[1] << 8) |
1302
                       ((uint32_t)bytes[2] << 16) |
1303
                       ((uint32_t)bytes[3] << 24);
1304
    return true;
1305
}
1306
 
1307
#ifndef PB_WITHOUT_64BIT
1308
bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
1309
{
1310
    pb_byte_t bytes[8];
1311
 
1312
    if (!pb_read(stream, bytes, 8))
1313
        return false;
1314
 
1315
    *(uint64_t*)dest = ((uint64_t)bytes[0] << 0) |
1316
                       ((uint64_t)bytes[1] << 8) |
1317
                       ((uint64_t)bytes[2] << 16) |
1318
                       ((uint64_t)bytes[3] << 24) |
1319
                       ((uint64_t)bytes[4] << 32) |
1320
                       ((uint64_t)bytes[5] << 40) |
1321
                       ((uint64_t)bytes[6] << 48) |
1322
                       ((uint64_t)bytes[7] << 56);
1323
 
1324
    return true;
1325
}
1326
#endif
1327
 
1328
static bool checkreturn pb_dec_bool(pb_istream_t *stream, const pb_field_t *field, void *dest)
1329
{
1330
    uint32_t value;
1331
    PB_UNUSED(field);
1332
    if (!pb_decode_varint32(stream, &value))
1333
        return false;
1334
 
1335
    *(bool*)dest = (value != 0);
1336
    return true;
1337
}
1338
 
1339
static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1340
{
1341
    pb_uint64_t value;
1342
    pb_int64_t svalue;
1343
    pb_int64_t clamped;
1344
    if (!pb_decode_varint(stream, &value))
1345
        return false;
1346
 
1347
    /* See issue 97: Google's C++ protobuf allows negative varint values to
1348
     * be cast as int32_t, instead of the int64_t that should be used when
1349
     * encoding. Previous nanopb versions had a bug in encoding. In order to
1350
     * not break decoding of such messages, we cast <=32 bit fields to
1351
     * int32_t first to get the sign correct.
1352
     */
1353
    if (field->data_size == sizeof(pb_int64_t))
1354
        svalue = (pb_int64_t)value;
1355
    else
1356
        svalue = (int32_t)value;
1357
 
1358
    /* Cast to the proper field size, while checking for overflows */
1359
    if (field->data_size == sizeof(pb_int64_t))
1360
        clamped = *(pb_int64_t*)dest = svalue;
1361
    else if (field->data_size == sizeof(int32_t))
1362
        clamped = *(int32_t*)dest = (int32_t)svalue;
1363
    else if (field->data_size == sizeof(int_least16_t))
1364
        clamped = *(int_least16_t*)dest = (int_least16_t)svalue;
1365
    else if (field->data_size == sizeof(int_least8_t))
1366
        clamped = *(int_least8_t*)dest = (int_least8_t)svalue;
1367
    else
1368
        PB_RETURN_ERROR(stream, "invalid data_size");
1369
 
1370
    if (clamped != svalue)
1371
        PB_RETURN_ERROR(stream, "integer too large");
1372
 
1373
    return true;
1374
}
1375
 
1376
static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1377
{
1378
    pb_uint64_t value, clamped;
1379
    if (!pb_decode_varint(stream, &value))
1380
        return false;
1381
 
1382
    /* Cast to the proper field size, while checking for overflows */
1383
    if (field->data_size == sizeof(pb_uint64_t))
1384
        clamped = *(pb_uint64_t*)dest = value;
1385
    else if (field->data_size == sizeof(uint32_t))
1386
        clamped = *(uint32_t*)dest = (uint32_t)value;
1387
    else if (field->data_size == sizeof(uint_least16_t))
1388
        clamped = *(uint_least16_t*)dest = (uint_least16_t)value;
1389
    else if (field->data_size == sizeof(uint_least8_t))
1390
        clamped = *(uint_least8_t*)dest = (uint_least8_t)value;
1391
    else
1392
        PB_RETURN_ERROR(stream, "invalid data_size");
1393
 
1394
    if (clamped != value)
1395
        PB_RETURN_ERROR(stream, "integer too large");
1396
 
1397
    return true;
1398
}
1399
 
1400
static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
1401
{
1402
    pb_int64_t value, clamped;
1403
    if (!pb_decode_svarint(stream, &value))
1404
        return false;
1405
 
1406
    /* Cast to the proper field size, while checking for overflows */
1407
    if (field->data_size == sizeof(pb_int64_t))
1408
        clamped = *(pb_int64_t*)dest = value;
1409
    else if (field->data_size == sizeof(int32_t))
1410
        clamped = *(int32_t*)dest = (int32_t)value;
1411
    else if (field->data_size == sizeof(int_least16_t))
1412
        clamped = *(int_least16_t*)dest = (int_least16_t)value;
1413
    else if (field->data_size == sizeof(int_least8_t))
1414
        clamped = *(int_least8_t*)dest = (int_least8_t)value;
1415
    else
1416
        PB_RETURN_ERROR(stream, "invalid data_size");
1417
 
1418
    if (clamped != value)
1419
        PB_RETURN_ERROR(stream, "integer too large");
1420
 
1421
    return true;
1422
}
1423
 
1424
static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)
1425
{
1426
    PB_UNUSED(field);
1427
    return pb_decode_fixed32(stream, dest);
1428
}
1429
 
1430
static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)
1431
{
1432
    PB_UNUSED(field);
1433
#ifndef PB_WITHOUT_64BIT
1434
    return pb_decode_fixed64(stream, dest);
1435
#else
1436
    PB_UNUSED(dest);
1437
    PB_RETURN_ERROR(stream, "no 64bit support");
1438
#endif
1439
}
1440
 
1441
static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
1442
{
1443
    uint32_t size;
1444
    size_t alloc_size;
1445
    pb_bytes_array_t *bdest;
1446
 
1447
    if (!pb_decode_varint32(stream, &size))
1448
        return false;
1449
 
1450
    if (size > PB_SIZE_MAX)
1451
        PB_RETURN_ERROR(stream, "bytes overflow");
1452
 
1453
    alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size);
1454
    if (size > alloc_size)
1455
        PB_RETURN_ERROR(stream, "size too large");
1456
 
1457
    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1458
    {
1459
#ifndef PB_ENABLE_MALLOC
1460
        PB_RETURN_ERROR(stream, "no malloc support");
1461
#else
1462
        if (stream->bytes_left < size)
1463
            PB_RETURN_ERROR(stream, "end-of-stream");
1464
 
1465
        if (!allocate_field(stream, dest, alloc_size, 1))
1466
            return false;
1467
        bdest = *(pb_bytes_array_t**)dest;
1468
#endif
1469
    }
1470
    else
1471
    {
1472
        if (alloc_size > field->data_size)
1473
            PB_RETURN_ERROR(stream, "bytes overflow");
1474
        bdest = (pb_bytes_array_t*)dest;
1475
    }
1476
 
1477
    bdest->size = (pb_size_t)size;
1478
    return pb_read(stream, bdest->bytes, size);
1479
}
1480
 
1481
static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
1482
{
1483
    uint32_t size;
1484
    size_t alloc_size;
1485
    bool status;
1486
    if (!pb_decode_varint32(stream, &size))
1487
        return false;
1488
 
1489
    /* Space for null terminator */
1490
    alloc_size = size + 1;
1491
 
1492
    if (alloc_size < size)
1493
        PB_RETURN_ERROR(stream, "size too large");
1494
 
1495
    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
1496
    {
1497
#ifndef PB_ENABLE_MALLOC
1498
        PB_RETURN_ERROR(stream, "no malloc support");
1499
#else
1500
        if (stream->bytes_left < size)
1501
            PB_RETURN_ERROR(stream, "end-of-stream");
1502
 
1503
        if (!allocate_field(stream, dest, alloc_size, 1))
1504
            return false;
1505
        dest = *(void**)dest;
1506
#endif
1507
    }
1508
    else
1509
    {
1510
        if (alloc_size > field->data_size)
1511
            PB_RETURN_ERROR(stream, "string overflow");
1512
    }
1513
 
1514
    status = pb_read(stream, (pb_byte_t*)dest, size);
1515
    *((pb_byte_t*)dest + size) = 0;
1516
    return status;
1517
}
1518
 
1519
static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
1520
{
1521
    bool status;
1522
    pb_istream_t substream;
1523
    const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;
1524
 
1525
    if (!pb_make_string_substream(stream, &substream))
1526
        return false;
1527
 
1528
    if (field->ptr == NULL)
1529
        PB_RETURN_ERROR(stream, "invalid field descriptor");
1530
 
1531
    /* New array entries need to be initialized, while required and optional
1532
     * submessages have already been initialized in the top-level pb_decode. */
1533
    if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
1534
        status = pb_decode(&substream, submsg_fields, dest);
1535
    else
1536
        status = pb_decode_noinit(&substream, submsg_fields, dest);
1537
 
1538
    if (!pb_close_string_substream(stream, &substream))
1539
        return false;
1540
    return status;
1541
}
1542
 
1543
static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
1544
{
1545
    uint32_t size;
1546
 
1547
    if (!pb_decode_varint32(stream, &size))
1548
        return false;
1549
 
1550
    if (size > PB_SIZE_MAX)
1551
        PB_RETURN_ERROR(stream, "bytes overflow");
1552
 
1553
    if (size == 0)
1554
    {
1555
        /* As a special case, treat empty bytes string as all zeros for fixed_length_bytes. */
1556
        memset(dest, 0, field->data_size);
1557
        return true;
1558
    }
1559
 
1560
    if (size != field->data_size)
1561
        PB_RETURN_ERROR(stream, "incorrect fixed length bytes size");
1562
 
1563
    return pb_read(stream, (pb_byte_t*)dest, field->data_size);
1564
}