Coverage Report

Created: 2026-10-31 06:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/nanopb/pb_encode.c
Line
Count
Source
1
/* pb_encode.c -- encode a protobuf using minimal resources
2
 *
3
 * 2011 Petteri Aimonen <jpa@kapsi.fi>
4
 */
5
6
#include "pb.h"
7
#include "pb_encode.h"
8
#include "pb_common.h"
9
10
/* Use the GCC warn_unused_result attribute to check that all return values
11
 * are propagated correctly. On other compilers, gcc before 3.4.0 and iar
12
 * before 9.40.1 just ignore the annotation.
13
 */
14
#if (defined(__GNUC__) && ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))) || \
15
    (defined(__IAR_SYSTEMS_ICC__) && (__VER__ >= 9040001))
16
    #define checkreturn __attribute__((warn_unused_result))
17
#else
18
    #define checkreturn
19
#endif
20
21
/**************************************
22
 * Declarations internal to this file *
23
 **************************************/
24
static bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count);
25
static bool checkreturn encode_array(pb_ostream_t *stream, pb_field_iter_t *field);
26
static bool checkreturn pb_check_proto3_default_value(const pb_field_iter_t *field);
27
static bool checkreturn encode_basic_field(pb_ostream_t *stream, const pb_field_iter_t *field);
28
static bool checkreturn encode_callback_field(pb_ostream_t *stream, const pb_field_iter_t *field);
29
static bool checkreturn encode_field(pb_ostream_t *stream, pb_field_iter_t *field);
30
static pb_noinline bool checkreturn encode_extension_field(pb_ostream_t *stream, const pb_field_iter_t *field);
31
static bool checkreturn default_extension_encoder(pb_ostream_t *stream, const pb_extension_t *extension);
32
static bool checkreturn pb_encode_varint_32(pb_ostream_t *stream, uint32_t low, uint32_t high);
33
static bool checkreturn pb_enc_bool(pb_ostream_t *stream, const pb_field_iter_t *field);
34
static bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_field_iter_t *field);
35
static bool checkreturn pb_enc_fixed(pb_ostream_t *stream, const pb_field_iter_t *field);
36
static bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_iter_t *field);
37
static bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_field_iter_t *field);
38
static bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb_field_iter_t *field);
39
static bool checkreturn pb_enc_fixed_length_bytes(pb_ostream_t *stream, const pb_field_iter_t *field);
40
41
#ifdef PB_WITHOUT_64BIT
42
#define pb_int64_t int32_t
43
#define pb_uint64_t uint32_t
44
#else
45
7.04M
#define pb_int64_t int64_t
46
17.4M
#define pb_uint64_t uint64_t
47
#endif
48
49
/*******************************
50
 * pb_ostream_t implementation *
51
 *******************************/
52
53
static bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count)
54
36.1M
{
55
36.1M
    pb_byte_t *dest = (pb_byte_t*)stream->state;
56
36.1M
    stream->state = dest + count;
57
58
    /* Skip the copy if buf is NULL. Callers should not invoke this with NULL,
59
     * but pb_write may pass NULL for sizing passes. Some compilers
60
     * (e.g. picolibc/arm-zephyr-eabi GCC 12.2) emit a -Wnonnull warning
61
     * against memcpy's nonnull argument even though count would be 0 in
62
     * that case. See #1141.
63
     */
64
36.1M
    if (buf != NULL)
65
36.1M
    {
66
36.1M
        memcpy(dest, buf, count * sizeof(pb_byte_t));
67
36.1M
    }
68
69
36.1M
    return true;
70
36.1M
}
71
72
pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize)
73
3.16k
{
74
3.16k
    pb_ostream_t stream;
75
#ifdef PB_BUFFER_ONLY
76
    /* In PB_BUFFER_ONLY configuration the callback pointer is just int*.
77
     * NULL pointer marks a sizing field, so put a non-NULL value to mark a buffer stream.
78
     */
79
    static const int marker = 0;
80
    stream.callback = &marker;
81
#else
82
3.16k
    stream.callback = &buf_write;
83
3.16k
#endif
84
3.16k
    stream.state = buf;
85
3.16k
    stream.max_size = bufsize;
86
3.16k
    stream.bytes_written = 0;
87
3.16k
#ifndef PB_NO_ERRMSG
88
3.16k
    stream.errmsg = NULL;
89
3.16k
#endif
90
3.16k
    return stream;
91
3.16k
}
92
93
bool checkreturn pb_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count)
94
40.2M
{
95
40.2M
    if (count > 0 && stream->callback != NULL)
96
36.1M
    {
97
36.1M
        if (stream->bytes_written + count < stream->bytes_written ||
98
36.1M
            stream->bytes_written + count > stream->max_size)
99
200
        {
100
200
            PB_RETURN_ERROR(stream, "stream full");
101
200
        }
102
103
#ifdef PB_BUFFER_ONLY
104
        if (!buf_write(stream, buf, count))
105
            PB_RETURN_ERROR(stream, "io error");
106
#else        
107
36.1M
        if (!stream->callback(stream, buf, count))
108
0
            PB_RETURN_ERROR(stream, "io error");
109
36.1M
#endif
110
36.1M
    }
111
    
112
40.2M
    stream->bytes_written += count;
113
40.2M
    return true;
114
40.2M
}
115
116
/*************************
117
 * Encode a single field *
118
 *************************/
119
120
/* Read a bool value without causing undefined behavior even if the value
121
 * is invalid. See issue #434 and
122
 * https://stackoverflow.com/questions/27661768/weird-results-for-conditional
123
 */
124
static bool safe_read_bool(const void *pSize)
125
9.25k
{
126
9.25k
    const char *p = (const char *)pSize;
127
9.25k
    size_t i;
128
16.7k
    for (i = 0; i < sizeof(bool); i++)
129
9.25k
    {
130
9.25k
        if (p[i] != 0)
131
1.73k
            return true;
132
9.25k
    }
133
7.52k
    return false;
134
9.25k
}
135
136
/* Encode a static array. Handles the size calculations and possible packing. */
137
static bool checkreturn encode_array(pb_ostream_t *stream, pb_field_iter_t *field)
138
5.45k
{
139
5.45k
    pb_size_t i;
140
5.45k
    pb_size_t count;
141
5.45k
#ifndef PB_ENCODE_ARRAYS_UNPACKED
142
5.45k
    size_t size;
143
5.45k
#endif
144
145
5.45k
    count = *(pb_size_t*)field->pSize;
146
147
5.45k
    if (count == 0)
148
0
        return true;
149
150
5.45k
    if (PB_ATYPE(field->type) != PB_ATYPE_POINTER && count > field->array_size)
151
0
        PB_RETURN_ERROR(stream, "array max size exceeded");
152
    
153
5.45k
#ifndef PB_ENCODE_ARRAYS_UNPACKED
154
    /* We always pack arrays if the datatype allows it. */
155
5.45k
    if (PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE)
156
2.42k
    {
157
2.42k
        if (!pb_encode_tag(stream, PB_WT_STRING, field->tag))
158
1
            return false;
159
        
160
        /* Determine the total size of packed array. */
161
2.41k
        if (PB_LTYPE(field->type) == PB_LTYPE_FIXED32)
162
372
        {
163
372
            size = 4 * (size_t)count;
164
372
        }
165
2.04k
        else if (PB_LTYPE(field->type) == PB_LTYPE_FIXED64)
166
217
        {
167
217
            size = 8 * (size_t)count;
168
217
        }
169
1.83k
        else
170
1.83k
        { 
171
1.83k
            pb_ostream_t sizestream = PB_OSTREAM_SIZING;
172
1.83k
            void *pData_orig = field->pData;
173
3.80M
            for (i = 0; i < count; i++)
174
3.80M
            {
175
3.80M
                if (!pb_enc_varint(&sizestream, field))
176
0
                    PB_RETURN_ERROR(stream, PB_GET_ERROR(&sizestream));
177
3.80M
                field->pData = (char*)field->pData + field->data_size;
178
3.80M
            }
179
1.83k
            field->pData = pData_orig;
180
1.83k
            size = sizestream.bytes_written;
181
1.83k
        }
182
        
183
2.41k
        if (!pb_encode_varint(stream, (pb_uint64_t)size))
184
3
            return false;
185
        
186
2.41k
        if (stream->callback == NULL)
187
0
            return pb_write(stream, NULL, size); /* Just sizing.. */
188
        
189
        /* Write the data */
190
3.79M
        for (i = 0; i < count; i++)
191
3.79M
        {
192
3.79M
            if (PB_LTYPE(field->type) == PB_LTYPE_FIXED32 || PB_LTYPE(field->type) == PB_LTYPE_FIXED64)
193
10.8k
            {
194
10.8k
                if (!pb_enc_fixed(stream, field))
195
3
                    return false;
196
10.8k
            }
197
3.78M
            else
198
3.78M
            {
199
3.78M
                if (!pb_enc_varint(stream, field))
200
6
                    return false;
201
3.78M
            }
202
203
3.79M
            field->pData = (char*)field->pData + field->data_size;
204
3.79M
        }
205
2.41k
    }
206
3.03k
    else /* Unpacked fields */
207
3.03k
#endif
208
3.03k
    {
209
10.6M
        for (i = 0; i < count; i++)
210
10.6M
        {
211
            /* Normally the data is stored directly in the array entries, but
212
             * for pointer-type string and bytes fields, the array entries are
213
             * actually pointers themselves also. So we have to dereference once
214
             * more to get to the actual data. */
215
10.6M
            if (PB_ATYPE(field->type) == PB_ATYPE_POINTER &&
216
10.6M
                (PB_LTYPE(field->type) == PB_LTYPE_STRING ||
217
10.6M
                 PB_LTYPE(field->type) == PB_LTYPE_BYTES))
218
97.0k
            {
219
97.0k
                bool status;
220
97.0k
                void *pData_orig = field->pData;
221
97.0k
                field->pData = *(void* const*)field->pData;
222
223
97.0k
                if (!field->pData)
224
0
                {
225
                    /* Null pointer in array is treated as empty string / bytes */
226
0
                    status = pb_encode_tag_for_field(stream, field) &&
227
0
                             pb_encode_varint(stream, 0);
228
0
                }
229
97.0k
                else
230
97.0k
                {
231
97.0k
                    status = encode_basic_field(stream, field);
232
97.0k
                }
233
234
97.0k
                field->pData = pData_orig;
235
236
97.0k
                if (!status)
237
3
                    return false;
238
97.0k
            }
239
10.5M
            else
240
10.5M
            {
241
10.5M
                if (!encode_basic_field(stream, field))
242
13
                    return false;
243
10.5M
            }
244
10.6M
            field->pData = (char*)field->pData + field->data_size;
245
10.6M
        }
246
3.03k
    }
247
    
248
5.42k
    return true;
249
5.45k
}
250
251
/* In proto3, all fields are optional and are only encoded if their value is "non-zero".
252
 * This function implements the check for the zero value. */
253
static bool checkreturn pb_check_proto3_default_value(const pb_field_iter_t *field)
254
0
{
255
0
    pb_type_t type = field->type;
256
257
0
    if (PB_ATYPE(type) == PB_ATYPE_STATIC)
258
0
    {
259
0
        if (PB_HTYPE(type) == PB_HTYPE_REQUIRED)
260
0
        {
261
            /* Required proto2 fields inside proto3 submessage, pretty rare case */
262
0
            return false;
263
0
        }
264
0
        else if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
265
0
        {
266
            /* Repeated fields inside proto3 submessage: present if count != 0 */
267
0
            return *(const pb_size_t*)field->pSize == 0;
268
0
        }
269
0
        else if (PB_HTYPE(type) == PB_HTYPE_ONEOF)
270
0
        {
271
            /* Oneof fields */
272
0
            return *(const pb_size_t*)field->pSize == 0;
273
0
        }
274
0
        else if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL && field->pSize != NULL)
275
0
        {
276
            /* Proto2 optional fields inside proto3 message, or proto3
277
             * submessage fields. */
278
0
            return safe_read_bool(field->pSize) == false;
279
0
        }
280
0
        else if (field->descriptor->default_value)
281
0
        {
282
            /* Proto3 messages do not have default values, but proto2 messages
283
             * can contain optional fields without has_fields (generator option 'proto3').
284
             * In this case they must always be encoded, to make sure that the
285
             * non-zero default value is overwritten.
286
             */
287
0
            return false;
288
0
        }
289
290
        /* Rest is proto3 singular fields */
291
0
        if (PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
292
0
        {
293
            /* Simple integer / float fields */
294
0
            pb_size_t i;
295
0
            const char *p = (const char*)field->pData;
296
0
            for (i = 0; i < field->data_size; i++)
297
0
            {
298
0
                if (p[i] != 0)
299
0
                {
300
0
                    return false;
301
0
                }
302
0
            }
303
304
0
            return true;
305
0
        }
306
0
        else if (PB_LTYPE(type) == PB_LTYPE_BYTES)
307
0
        {
308
0
            const pb_bytes_array_t *bytes = (const pb_bytes_array_t*)field->pData;
309
0
            return bytes->size == 0;
310
0
        }
311
0
        else if (PB_LTYPE(type) == PB_LTYPE_STRING)
312
0
        {
313
0
            return *(const char*)field->pData == '\0';
314
0
        }
315
0
        else if (PB_LTYPE(type) == PB_LTYPE_FIXED_LENGTH_BYTES)
316
0
        {
317
            /* Fixed length bytes is only empty if its length is fixed
318
             * as 0. Which would be pretty strange, but we can check
319
             * it anyway. */
320
0
            return field->data_size == 0;
321
0
        }
322
0
        else if (PB_LTYPE_IS_SUBMSG(type))
323
0
        {
324
            /* Check all fields in the submessage to find if any of them
325
             * are non-zero. The comparison cannot be done byte-per-byte
326
             * because the C struct may contain padding bytes that must
327
             * be skipped. Note that usually proto3 submessages have
328
             * a separate has_field that is checked earlier in this if.
329
             */
330
0
            pb_field_iter_t iter;
331
0
            if (pb_field_iter_begin(&iter, field->submsg_desc, field->pData))
332
0
            {
333
0
                do
334
0
                {
335
0
                    if (!pb_check_proto3_default_value(&iter))
336
0
                    {
337
0
                        return false;
338
0
                    }
339
0
                } while (pb_field_iter_next(&iter));
340
0
            }
341
0
            return true;
342
0
        }
343
0
    }
344
0
    else if (PB_ATYPE(type) == PB_ATYPE_POINTER)
345
0
    {
346
0
        return field->pData == NULL;
347
0
    }
348
0
    else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
349
0
    {
350
0
        if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
351
0
        {
352
0
            const pb_extension_t *extension = *(const pb_extension_t* const *)field->pData;
353
0
            return extension == NULL;
354
0
        }
355
0
        else if (field->descriptor->field_callback == pb_default_field_callback)
356
0
        {
357
0
            pb_callback_t *pCallback = (pb_callback_t*)field->pData;
358
0
            return pCallback->funcs.encode == NULL;
359
0
        }
360
0
        else
361
0
        {
362
0
            return field->descriptor->field_callback == NULL;
363
0
        }
364
0
    }
365
366
0
    return false; /* Not typically reached, safe default for weird special cases. */
367
0
}
368
369
/* Encode a field with static or pointer allocation, i.e. one whose data
370
 * is available to the encoder directly. */
371
static bool checkreturn encode_basic_field(pb_ostream_t *stream, const pb_field_iter_t *field)
372
10.9M
{
373
10.9M
    if (!field->pData)
374
0
    {
375
        /* Missing pointer field */
376
0
        return true;
377
0
    }
378
379
10.9M
    if (!pb_encode_tag_for_field(stream, field))
380
73
        return false;
381
382
10.9M
    switch (PB_LTYPE(field->type))
383
10.9M
    {
384
3.24k
        case PB_LTYPE_BOOL:
385
3.24k
            return pb_enc_bool(stream, field);
386
387
125k
        case PB_LTYPE_VARINT:
388
172k
        case PB_LTYPE_UVARINT:
389
190k
        case PB_LTYPE_SVARINT:
390
190k
            return pb_enc_varint(stream, field);
391
392
17.0k
        case PB_LTYPE_FIXED32:
393
26.8k
        case PB_LTYPE_FIXED64:
394
26.8k
            return pb_enc_fixed(stream, field);
395
396
89.6k
        case PB_LTYPE_BYTES:
397
89.6k
            return pb_enc_bytes(stream, field);
398
399
63.5k
        case PB_LTYPE_STRING:
400
63.5k
            return pb_enc_string(stream, field);
401
402
54.0k
        case PB_LTYPE_SUBMESSAGE:
403
54.0k
        case PB_LTYPE_SUBMSG_W_CB:
404
54.0k
            return pb_enc_submessage(stream, field);
405
406
10.5M
        case PB_LTYPE_FIXED_LENGTH_BYTES:
407
10.5M
            return pb_enc_fixed_length_bytes(stream, field);
408
409
0
        default:
410
0
            PB_RETURN_ERROR(stream, "invalid field type");
411
10.9M
    }
412
10.9M
}
413
414
/* Encode a field with callback semantics. This means that a user function is
415
 * called to provide and encode the actual data. */
416
static bool checkreturn encode_callback_field(pb_ostream_t *stream, const pb_field_iter_t *field)
417
133
{
418
133
    if (field->descriptor->field_callback != NULL)
419
133
    {
420
133
        if (!field->descriptor->field_callback(NULL, stream, field))
421
0
            PB_RETURN_ERROR(stream, "callback error");
422
133
    }
423
133
    return true;
424
133
}
425
426
/* Encode a single field of any callback, pointer or static type. */
427
static bool checkreturn encode_field(pb_ostream_t *stream, pb_field_iter_t *field)
428
495k
{
429
    /* Check field presence */
430
495k
    if (PB_HTYPE(field->type) == PB_HTYPE_ONEOF)
431
21.6k
    {
432
21.6k
        if (*(const pb_size_t*)field->pSize != field->tag)
433
21.0k
        {
434
            /* Different type oneof field */
435
21.0k
            return true;
436
21.0k
        }
437
21.6k
    }
438
473k
    else if (PB_HTYPE(field->type) == PB_HTYPE_OPTIONAL)
439
117k
    {
440
117k
        if (field->pSize)
441
6.01k
        {
442
6.01k
            if (safe_read_bool(field->pSize) == false)
443
5.81k
            {
444
                /* Missing optional field */
445
5.81k
                return true;
446
5.81k
            }
447
6.01k
        }
448
111k
        else if (PB_ATYPE(field->type) == PB_ATYPE_STATIC)
449
0
        {
450
            /* Proto3 singular field */
451
0
            if (pb_check_proto3_default_value(field))
452
0
                return true;
453
0
        }
454
117k
    }
455
456
468k
    if (!field->pData)
457
163k
    {
458
163k
        if (PB_HTYPE(field->type) == PB_HTYPE_REQUIRED)
459
0
            PB_RETURN_ERROR(stream, "missing required field");
460
461
        /* Pointer field set to NULL */
462
163k
        return true;
463
163k
    }
464
465
    /* Then encode field contents */
466
305k
    if (PB_ATYPE(field->type) == PB_ATYPE_CALLBACK)
467
133
    {
468
133
        return encode_callback_field(stream, field);
469
133
    }
470
305k
    else if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
471
5.45k
    {
472
5.45k
        return encode_array(stream, field);
473
5.45k
    }
474
299k
    else
475
299k
    {
476
299k
        return encode_basic_field(stream, field);
477
299k
    }
478
305k
}
479
480
/* Default handler for extension fields. Expects to have a pb_msgdesc_t
481
 * pointer in the extension->type->arg field, pointing to a message with
482
 * only one field in it.  */
483
static bool checkreturn default_extension_encoder(pb_ostream_t *stream, const pb_extension_t *extension)
484
3.03k
{
485
3.03k
    pb_field_iter_t iter;
486
487
3.03k
    if (!pb_field_iter_begin_extension_const(&iter, extension))
488
0
        PB_RETURN_ERROR(stream, "invalid extension");
489
490
3.03k
    return encode_field(stream, &iter);
491
3.03k
}
492
493
494
/* Walk through all the registered extensions and give them a chance
495
 * to encode themselves. */
496
static pb_noinline bool checkreturn encode_extension_field(pb_ostream_t *stream, const pb_field_iter_t *field)
497
3.03k
{
498
3.03k
    const pb_extension_t *extension = *(const pb_extension_t* const *)field->pData;
499
500
6.02k
    while (extension)
501
3.03k
    {
502
3.03k
        bool status;
503
3.03k
        if (extension->type->encode)
504
0
            status = extension->type->encode(stream, extension);
505
3.03k
        else
506
3.03k
            status = default_extension_encoder(stream, extension);
507
508
3.03k
        if (!status)
509
44
            return false;
510
        
511
2.99k
        extension = extension->next;
512
2.99k
    }
513
    
514
2.99k
    return true;
515
3.03k
}
516
517
/*********************
518
 * Encode all fields *
519
 *********************/
520
521
bool checkreturn pb_encode(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct)
522
111k
{
523
111k
    pb_field_iter_t iter;
524
111k
    if (!pb_field_iter_begin_const(&iter, fields, src_struct))
525
34.3k
        return true; /* Empty message type */
526
    
527
495k
    do {
528
495k
        if (PB_LTYPE(iter.type) == PB_LTYPE_EXTENSION)
529
3.03k
        {
530
            /* Special case for the extension field placeholder */
531
3.03k
            if (!encode_extension_field(stream, &iter))
532
44
                return false;
533
3.03k
        }
534
492k
        else
535
492k
        {
536
            /* Regular field */
537
492k
            if (!encode_field(stream, &iter))
538
193
                return false;
539
492k
        }
540
495k
    } while (pb_field_iter_next(&iter));
541
    
542
76.7k
    return true;
543
76.9k
}
544
545
bool checkreturn pb_encode_ex(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct, unsigned int flags)
546
0
{
547
0
  if ((flags & PB_ENCODE_DELIMITED) != 0)
548
0
  {
549
0
    return pb_encode_submessage(stream, fields, src_struct);
550
0
  }
551
0
  else if ((flags & PB_ENCODE_NULLTERMINATED) != 0)
552
0
  {
553
0
    const pb_byte_t zero = 0;
554
555
0
    if (!pb_encode(stream, fields, src_struct))
556
0
        return false;
557
558
0
    return pb_write(stream, &zero, 1);
559
0
  }
560
0
  else
561
0
  {
562
0
    return pb_encode(stream, fields, src_struct);
563
0
  }
564
0
}
565
566
bool pb_get_encoded_size(size_t *size, const pb_msgdesc_t *fields, const void *src_struct)
567
0
{
568
0
    pb_ostream_t stream = PB_OSTREAM_SIZING;
569
    
570
0
    if (!pb_encode(&stream, fields, src_struct))
571
0
        return false;
572
    
573
0
    *size = stream.bytes_written;
574
0
    return true;
575
0
}
576
577
/********************
578
 * Helper functions *
579
 ********************/
580
581
/* This function avoids 64-bit shifts as they are quite slow on many platforms. */
582
static bool checkreturn pb_encode_varint_32(pb_ostream_t *stream, uint32_t low, uint32_t high)
583
12.8M
{
584
12.8M
    size_t i = 0;
585
12.8M
    pb_byte_t buffer[10];
586
12.8M
    pb_byte_t byte = (pb_byte_t)(low & 0x7F);
587
12.8M
    low >>= 7;
588
589
28.3M
    while (i < 4 && (low != 0 || high != 0))
590
15.5M
    {
591
15.5M
        byte |= 0x80;
592
15.5M
        buffer[i++] = byte;
593
15.5M
        byte = (pb_byte_t)(low & 0x7F);
594
15.5M
        low >>= 7;
595
15.5M
    }
596
597
12.8M
    if (high)
598
749k
    {
599
749k
        byte = (pb_byte_t)(byte | ((high & 0x07) << 4));
600
749k
        high >>= 3;
601
602
3.93M
        while (high)
603
3.18M
        {
604
3.18M
            byte |= 0x80;
605
3.18M
            buffer[i++] = byte;
606
3.18M
            byte = (pb_byte_t)(high & 0x7F);
607
3.18M
            high >>= 7;
608
3.18M
        }
609
749k
    }
610
611
12.8M
    buffer[i++] = byte;
612
613
12.8M
    return pb_write(stream, buffer, i);
614
12.8M
}
615
616
bool checkreturn pb_encode_varint(pb_ostream_t *stream, pb_uint64_t value)
617
29.5M
{
618
29.5M
    if (value <= 0x7F)
619
16.7M
    {
620
        /* Fast path: single byte */
621
16.7M
        pb_byte_t byte = (pb_byte_t)value;
622
16.7M
        return pb_write(stream, &byte, 1);
623
16.7M
    }
624
12.8M
    else
625
12.8M
    {
626
#ifdef PB_WITHOUT_64BIT
627
        return pb_encode_varint_32(stream, value, 0);
628
#else
629
12.8M
        return pb_encode_varint_32(stream, (uint32_t)value, (uint32_t)(value >> 32));
630
12.8M
#endif
631
12.8M
    }
632
29.5M
}
633
634
bool checkreturn pb_encode_svarint(pb_ostream_t *stream, pb_int64_t value)
635
2.88M
{
636
2.88M
    pb_uint64_t zigzagged;
637
2.88M
    pb_uint64_t mask = ((pb_uint64_t)-1) >> 1; /* Satisfy clang -fsanitize=integer */
638
2.88M
    if (value < 0)
639
352k
        zigzagged = ~(((pb_uint64_t)value & mask) << 1);
640
2.53M
    else
641
2.53M
        zigzagged = (pb_uint64_t)value << 1;
642
    
643
2.88M
    return pb_encode_varint(stream, zigzagged);
644
2.88M
}
645
646
bool checkreturn pb_encode_fixed32(pb_ostream_t *stream, const void *value)
647
22.0k
{
648
22.0k
#if defined(PB_LITTLE_ENDIAN_8BIT) && PB_LITTLE_ENDIAN_8BIT == 1
649
    /* Fast path if we know that we're on little endian */
650
22.0k
    return pb_write(stream, (const pb_byte_t*)value, 4);
651
#else
652
    uint32_t val = *(const uint32_t*)value;
653
    pb_byte_t bytes[4];
654
    bytes[0] = (pb_byte_t)(val & 0xFF);
655
    bytes[1] = (pb_byte_t)((val >> 8) & 0xFF);
656
    bytes[2] = (pb_byte_t)((val >> 16) & 0xFF);
657
    bytes[3] = (pb_byte_t)((val >> 24) & 0xFF);
658
    return pb_write(stream, bytes, 4);
659
#endif
660
22.0k
}
661
662
#ifndef PB_WITHOUT_64BIT
663
bool checkreturn pb_encode_fixed64(pb_ostream_t *stream, const void *value)
664
15.6k
{
665
15.6k
#if defined(PB_LITTLE_ENDIAN_8BIT) && PB_LITTLE_ENDIAN_8BIT == 1
666
    /* Fast path if we know that we're on little endian */
667
15.6k
    return pb_write(stream, (const pb_byte_t*)value, 8);
668
#else
669
    uint64_t val = *(const uint64_t*)value;
670
    pb_byte_t bytes[8];
671
    bytes[0] = (pb_byte_t)(val & 0xFF);
672
    bytes[1] = (pb_byte_t)((val >> 8) & 0xFF);
673
    bytes[2] = (pb_byte_t)((val >> 16) & 0xFF);
674
    bytes[3] = (pb_byte_t)((val >> 24) & 0xFF);
675
    bytes[4] = (pb_byte_t)((val >> 32) & 0xFF);
676
    bytes[5] = (pb_byte_t)((val >> 40) & 0xFF);
677
    bytes[6] = (pb_byte_t)((val >> 48) & 0xFF);
678
    bytes[7] = (pb_byte_t)((val >> 56) & 0xFF);
679
    return pb_write(stream, bytes, 8);
680
#endif
681
15.6k
}
682
#endif
683
684
bool checkreturn pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, uint32_t field_number)
685
10.9M
{
686
10.9M
    pb_uint64_t tag = ((pb_uint64_t)field_number << 3) | wiretype;
687
10.9M
    return pb_encode_varint(stream, tag);
688
10.9M
}
689
690
bool pb_encode_tag_for_field ( pb_ostream_t* stream, const pb_field_iter_t* field )
691
10.9M
{
692
10.9M
    pb_wire_type_t wiretype;
693
10.9M
    switch (PB_LTYPE(field->type))
694
10.9M
    {
695
3.24k
        case PB_LTYPE_BOOL:
696
129k
        case PB_LTYPE_VARINT:
697
175k
        case PB_LTYPE_UVARINT:
698
194k
        case PB_LTYPE_SVARINT:
699
194k
            wiretype = PB_WT_VARINT;
700
194k
            break;
701
        
702
17.0k
        case PB_LTYPE_FIXED32:
703
17.0k
            wiretype = PB_WT_32BIT;
704
17.0k
            break;
705
        
706
9.72k
        case PB_LTYPE_FIXED64:
707
9.72k
            wiretype = PB_WT_64BIT;
708
9.72k
            break;
709
        
710
89.6k
        case PB_LTYPE_BYTES:
711
153k
        case PB_LTYPE_STRING:
712
207k
        case PB_LTYPE_SUBMESSAGE:
713
207k
        case PB_LTYPE_SUBMSG_W_CB:
714
10.7M
        case PB_LTYPE_FIXED_LENGTH_BYTES:
715
10.7M
            wiretype = PB_WT_STRING;
716
10.7M
            break;
717
        
718
0
        default:
719
0
            PB_RETURN_ERROR(stream, "invalid field type");
720
10.9M
    }
721
    
722
10.9M
    return pb_encode_tag(stream, wiretype, field->tag);
723
10.9M
}
724
725
bool checkreturn pb_encode_string(pb_ostream_t *stream, const pb_byte_t *buffer, size_t size)
726
10.7M
{
727
10.7M
    if (!pb_encode_varint(stream, (pb_uint64_t)size))
728
7
        return false;
729
    
730
10.7M
    return pb_write(stream, buffer, size);
731
10.7M
}
732
733
bool checkreturn pb_encode_submessage(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct)
734
54.0k
{
735
    /* First calculate the message size using a non-writing substream. */
736
54.0k
    pb_ostream_t substream = PB_OSTREAM_SIZING;
737
54.0k
#if !defined(PB_NO_ENCODE_SIZE_CHECK) || PB_NO_ENCODE_SIZE_CHECK == 0
738
54.0k
    bool status;
739
54.0k
    size_t size;
740
54.0k
#endif
741
    
742
54.0k
    if (!pb_encode(&substream, fields, src_struct))
743
0
    {
744
0
#ifndef PB_NO_ERRMSG
745
0
        stream->errmsg = substream.errmsg;
746
0
#endif
747
0
        return false;
748
0
    }
749
    
750
54.0k
    if (!pb_encode_varint(stream, (pb_uint64_t)substream.bytes_written))
751
27
        return false;
752
    
753
54.0k
    if (stream->callback == NULL)
754
0
        return pb_write(stream, NULL, substream.bytes_written); /* Just sizing */
755
    
756
54.0k
    if (stream->bytes_written + substream.bytes_written > stream->max_size)
757
37
        PB_RETURN_ERROR(stream, "stream full");
758
        
759
#if defined(PB_NO_ENCODE_SIZE_CHECK) && PB_NO_ENCODE_SIZE_CHECK == 1
760
    return pb_encode(stream, fields, src_struct);
761
#else
762
54.0k
    size = substream.bytes_written;
763
    /* Use a substream to verify that a callback doesn't write more than
764
     * what it did the first time. */
765
54.0k
    substream.callback = stream->callback;
766
54.0k
    substream.state = stream->state;
767
54.0k
    substream.max_size = size;
768
54.0k
    substream.bytes_written = 0;
769
54.0k
#ifndef PB_NO_ERRMSG
770
54.0k
    substream.errmsg = NULL;
771
54.0k
#endif
772
    
773
54.0k
    status = pb_encode(&substream, fields, src_struct);
774
    
775
54.0k
    stream->bytes_written += substream.bytes_written;
776
54.0k
    stream->state = substream.state;
777
54.0k
#ifndef PB_NO_ERRMSG
778
54.0k
    stream->errmsg = substream.errmsg;
779
54.0k
#endif
780
    
781
54.0k
    if (substream.bytes_written != size)
782
0
        PB_RETURN_ERROR(stream, "submsg size changed");
783
784
54.0k
    return status;
785
54.0k
#endif
786
54.0k
}
787
788
/* Field encoders */
789
790
static bool checkreturn pb_enc_bool(pb_ostream_t *stream, const pb_field_iter_t *field)
791
3.24k
{
792
3.24k
    uint32_t value = safe_read_bool(field->pData) ? 1 : 0;
793
3.24k
    PB_UNUSED(field);
794
3.24k
    return pb_encode_varint(stream, value);
795
3.24k
}
796
797
static bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_field_iter_t *field)
798
7.77M
{
799
7.77M
    if (PB_LTYPE(field->type) == PB_LTYPE_UVARINT)
800
734k
    {
801
        /* Perform unsigned integer extension */
802
734k
        pb_uint64_t value = 0;
803
804
734k
        if (field->data_size == sizeof(uint_least8_t))
805
6.14k
            value = *(const uint_least8_t*)field->pData;
806
728k
        else if (field->data_size == sizeof(uint_least16_t))
807
6.14k
            value = *(const uint_least16_t*)field->pData;
808
722k
        else if (field->data_size == sizeof(uint32_t))
809
261k
            value = *(const uint32_t*)field->pData;
810
460k
        else if (field->data_size == sizeof(pb_uint64_t))
811
460k
            value = *(const pb_uint64_t*)field->pData;
812
0
        else
813
0
            PB_RETURN_ERROR(stream, "invalid data_size");
814
815
734k
        return pb_encode_varint(stream, value);
816
734k
    }
817
7.04M
    else
818
7.04M
    {
819
        /* Perform signed integer extension */
820
7.04M
        pb_int64_t value = 0;
821
822
7.04M
        if (field->data_size == sizeof(int_least8_t))
823
1.14M
            value = *(const int_least8_t*)field->pData;
824
5.89M
        else if (field->data_size == sizeof(int_least16_t))
825
12.2k
            value = *(const int_least16_t*)field->pData;
826
5.88M
        else if (field->data_size == sizeof(int32_t))
827
2.73M
            value = *(const int32_t*)field->pData;
828
3.14M
        else if (field->data_size == sizeof(pb_int64_t))
829
3.14M
            value = *(const pb_int64_t*)field->pData;
830
0
        else
831
0
            PB_RETURN_ERROR(stream, "invalid data_size");
832
833
7.04M
        if (PB_LTYPE(field->type) == PB_LTYPE_SVARINT)
834
2.88M
            return pb_encode_svarint(stream, value);
835
#ifdef PB_WITHOUT_64BIT
836
        else if (value < 0)
837
            return pb_encode_varint_32(stream, (uint32_t)value, (uint32_t)-1);
838
#endif
839
4.16M
        else
840
4.16M
            return pb_encode_varint(stream, (pb_uint64_t)value);
841
842
7.04M
    }
843
7.77M
}
844
845
static bool checkreturn pb_enc_fixed(pb_ostream_t *stream, const pb_field_iter_t *field)
846
37.6k
{
847
#ifdef PB_CONVERT_DOUBLE_FLOAT
848
    if (field->data_size == sizeof(float) && PB_LTYPE(field->type) == PB_LTYPE_FIXED64)
849
    {
850
        return pb_encode_float_as_double(stream, *(float*)field->pData);
851
    }
852
#endif
853
854
37.6k
    if (field->data_size == sizeof(uint32_t))
855
22.0k
    {
856
22.0k
        return pb_encode_fixed32(stream, field->pData);
857
22.0k
    }
858
15.6k
#ifndef PB_WITHOUT_64BIT
859
15.6k
    else if (field->data_size == sizeof(uint64_t))
860
15.6k
    {
861
15.6k
        return pb_encode_fixed64(stream, field->pData);
862
15.6k
    }
863
0
#endif
864
0
    else
865
0
    {
866
0
        PB_RETURN_ERROR(stream, "invalid data_size");
867
0
    }
868
37.6k
}
869
870
static bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_iter_t *field)
871
89.6k
{
872
89.6k
    const pb_bytes_array_t *bytes = NULL;
873
874
89.6k
    bytes = (const pb_bytes_array_t*)field->pData;
875
    
876
89.6k
    if (bytes == NULL)
877
0
    {
878
        /* Treat null pointer as an empty bytes field */
879
0
        return pb_encode_string(stream, NULL, 0);
880
0
    }
881
    
882
89.6k
    if (PB_ATYPE(field->type) == PB_ATYPE_STATIC &&
883
0
        bytes->size > field->data_size - offsetof(pb_bytes_array_t, bytes))
884
0
    {
885
0
        PB_RETURN_ERROR(stream, "bytes size exceeded");
886
0
    }
887
    
888
89.6k
    return pb_encode_string(stream, bytes->bytes, (size_t)bytes->size);
889
89.6k
}
890
891
static bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_field_iter_t *field)
892
63.5k
{
893
63.5k
    size_t size = 0;
894
63.5k
    size_t max_size = (size_t)field->data_size;
895
63.5k
    const char *str = (const char*)field->pData;
896
    
897
63.5k
    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
898
63.3k
    {
899
63.3k
        max_size = (size_t)-1;
900
63.3k
    }
901
197
    else
902
197
    {
903
        /* pb_dec_string() assumes string fields end with a null
904
         * terminator when the type isn't PB_ATYPE_POINTER, so we
905
         * shouldn't allow more than max-1 bytes to be written to
906
         * allow space for the null terminator.
907
         */
908
197
        if (max_size == 0)
909
0
            PB_RETURN_ERROR(stream, "zero-length string");
910
911
197
        max_size -= 1;
912
197
    }
913
914
915
63.5k
    if (str == NULL)
916
0
    {
917
0
        size = 0; /* Treat null pointer as an empty string */
918
0
    }
919
63.5k
    else
920
63.5k
    {
921
63.5k
        const char *p = str;
922
923
        /* strnlen() is not always available, so just use a loop */
924
266k
        while (size < max_size && *p != '\0')
925
203k
        {
926
203k
            size++;
927
203k
            p++;
928
203k
        }
929
930
63.5k
        if (*p != '\0')
931
0
        {
932
0
            PB_RETURN_ERROR(stream, "unterminated string");
933
0
        }
934
63.5k
    }
935
936
#ifdef PB_VALIDATE_UTF8
937
    if (!pb_validate_utf8(str))
938
        PB_RETURN_ERROR(stream, "invalid utf8");
939
#endif
940
941
63.5k
    return pb_encode_string(stream, (const pb_byte_t*)str, size);
942
63.5k
}
943
944
static bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb_field_iter_t *field)
945
54.0k
{
946
54.0k
    if (field->submsg_desc == NULL)
947
0
        PB_RETURN_ERROR(stream, "invalid field descriptor");
948
949
54.0k
    if (PB_LTYPE(field->type) == PB_LTYPE_SUBMSG_W_CB && field->pSize != NULL)
950
0
    {
951
        /* Message callback is stored right before pSize. */
952
0
        pb_callback_t *callback = (pb_callback_t*)field->pSize - 1;
953
0
        if (callback->funcs.encode)
954
0
        {
955
0
            if (!callback->funcs.encode(stream, field, &callback->arg))
956
0
                return false;
957
0
        }
958
0
    }
959
    
960
54.0k
    return pb_encode_submessage(stream, field->submsg_desc, field->pData);
961
54.0k
}
962
963
static bool checkreturn pb_enc_fixed_length_bytes(pb_ostream_t *stream, const pb_field_iter_t *field)
964
10.5M
{
965
10.5M
    return pb_encode_string(stream, (const pb_byte_t*)field->pData, (size_t)field->data_size);
966
10.5M
}
967
968
#ifdef PB_CONVERT_DOUBLE_FLOAT
969
bool pb_encode_float_as_double(pb_ostream_t *stream, float value)
970
{
971
    union { float f; uint32_t i; } in;
972
    uint_least8_t sign;
973
    int exponent;
974
    uint64_t mantissa;
975
976
    in.f = value;
977
978
    /* Decompose input value */
979
    sign = (uint_least8_t)((in.i >> 31) & 1);
980
    exponent = (int)((in.i >> 23) & 0xFF) - 127;
981
    mantissa = in.i & 0x7FFFFF;
982
983
    if (exponent == 128)
984
    {
985
        /* Special value (NaN etc.) */
986
        exponent = 1024;
987
    }
988
    else if (exponent == -127)
989
    {
990
        if (!mantissa)
991
        {
992
            /* Zero */
993
            exponent = -1023;
994
        }
995
        else
996
        {
997
            /* Denormalized */
998
            mantissa <<= 1;
999
            while (!(mantissa & 0x800000))
1000
            {
1001
                mantissa <<= 1;
1002
                exponent--;
1003
            }
1004
            mantissa &= 0x7FFFFF;
1005
        }
1006
    }
1007
1008
    /* Combine fields */
1009
    mantissa <<= 29;
1010
    mantissa |= (uint64_t)(exponent + 1023) << 52;
1011
    mantissa |= (uint64_t)sign << 63;
1012
1013
    return pb_encode_fixed64(stream, &mantissa);
1014
}
1015
#endif