protobuf-c.c 100.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
/*
 * Copyright (c) 2008-2015, Dave Benson and the protobuf-c authors.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*! \file
 * Support library for `protoc-c` generated code.
 *
 * This file implements the public API used by the code generated
 * by `protoc-c`.
 *
 * \authors Dave Benson and the protobuf-c authors
 *
 * \copyright 2008-2014. Licensed under the terms of the [BSD-2-Clause] license.
 */

/**
 * \todo 64-BIT OPTIMIZATION: certain implementations use 32-bit math
 * even on 64-bit platforms (uint64_size, uint64_pack, parse_uint64).
 *
 * \todo Use size_t consistently.
 */

48 49
#include <stdlib.h> /* for malloc, free */
#include <string.h> /* for strcmp, strlen, memcpy, memmove, memset */
50 51 52

#include "protobuf-c.h"

53 54
#define TRUE 1
#define FALSE 0
55 56 57 58 59

#define PROTOBUF_C__ASSERT_NOT_REACHED() assert(0)

/* Workaround for Microsoft compilers. */
#ifdef _MSC_VER
60
#define inline __inline
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
#endif

/**
 * \defgroup internal Internal functions and macros
 *
 * These are not exported by the library but are useful to developers working
 * on `libprotobuf-c` itself.
 */

/**
 * \defgroup macros Utility macros for manipulating structures
 *
 * Macros and constants used to manipulate the base "classes" generated by
 * `protobuf-c`. They also define limits and check correctness.
 *
 * \ingroup internal
 * @{
 */

/** The maximum length of a 64-bit integer in varint encoding. */
81
#define MAX_UINT64_ENCODED_SIZE 10
82 83

#ifndef PROTOBUF_C_UNPACK_ERROR
84
#define PROTOBUF_C_UNPACK_ERROR(...)
85 86 87 88 89 90 91 92 93 94 95
#endif

const char protobuf_c_empty_string[] = "";

/**
 * Internal `ProtobufCMessage` manipulation macro.
 *
 * Base macro for manipulating a `ProtobufCMessage`. Used by STRUCT_MEMBER() and
 * STRUCT_MEMBER_PTR().
 */
#define STRUCT_MEMBER_P(struct_p, struct_offset) \
96
  ((void *)((uint8_t *)(struct_p) + (struct_offset)))
97 98 99 100 101 102 103 104

/**
 * Return field in a `ProtobufCMessage` based on offset.
 *
 * Take a pointer to a `ProtobufCMessage` and find the field at the offset.
 * Cast it to the passed type.
 */
#define STRUCT_MEMBER(member_type, struct_p, struct_offset) \
105
  (*(member_type *)STRUCT_MEMBER_P((struct_p), (struct_offset)))
106 107 108 109 110 111 112 113

/**
 * Return field in a `ProtobufCMessage` based on offset.
 *
 * Take a pointer to a `ProtobufCMessage` and find the field at the offset. Cast
 * it to a pointer to the passed type.
 */
#define STRUCT_MEMBER_PTR(member_type, struct_p, struct_offset) \
114
  ((member_type *)STRUCT_MEMBER_P((struct_p), (struct_offset)))
115 116 117 118

/* Assertions for magic numbers. */

#define ASSERT_IS_ENUM_DESCRIPTOR(desc) \
119
  assert((desc)->magic == PROTOBUF_C__ENUM_DESCRIPTOR_MAGIC)
120 121

#define ASSERT_IS_MESSAGE_DESCRIPTOR(desc) \
122
  assert((desc)->magic == PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC)
123 124

#define ASSERT_IS_MESSAGE(message) \
125
  ASSERT_IS_MESSAGE_DESCRIPTOR((message)->descriptor)
126 127

#define ASSERT_IS_SERVICE_DESCRIPTOR(desc) \
128
  assert((desc)->magic == PROTOBUF_C__SERVICE_DESCRIPTOR_MAGIC)
129 130 131 132 133

/**@}*/

/* --- version --- */

134
const char *protobuf_c_version(void) { return PROTOBUF_C_VERSION; }
135

136
uint32_t protobuf_c_version_number(void) { return PROTOBUF_C_VERSION_NUMBER; }
137 138 139

/* --- allocator --- */

140 141
static void *system_alloc(void *allocator_data, size_t size) {
  return malloc(size);
142 143
}

144
static void system_free(void *allocator_data, void *data) { free(data); }
145

146 147
static inline void *do_alloc(ProtobufCAllocator *allocator, size_t size) {
  return allocator->alloc(allocator->allocator_data, size);
148 149
}

150 151
static inline void do_free(ProtobufCAllocator *allocator, void *data) {
  if (data != NULL) allocator->free(allocator->allocator_data, data);
152 153 154 155 156 157 158 159
}

/*
 * This allocator uses the system's malloc() and free(). It is the default
 * allocator used if NULL is passed as the ProtobufCAllocator to an exported
 * function.
 */
static ProtobufCAllocator protobuf_c__allocator = {
160 161 162
    .alloc = &system_alloc,
    .free = &system_free,
    .allocator_data = NULL,
163 164 165 166
};

/* === buffer-simple === */

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
void protobuf_c_buffer_simple_append(ProtobufCBuffer *buffer, size_t len,
                                     const uint8_t *data) {
  ProtobufCBufferSimple *simp = (ProtobufCBufferSimple *)buffer;
  size_t new_len = simp->len + len;

  if (new_len > simp->alloced) {
    ProtobufCAllocator *allocator = simp->allocator;
    size_t new_alloced = simp->alloced * 2;
    uint8_t *new_data;

    if (allocator == NULL) allocator = &protobuf_c__allocator;
    while (new_alloced < new_len) new_alloced += new_alloced;
    new_data = do_alloc(allocator, new_alloced);
    if (!new_data) return;
    memcpy(new_data, simp->data, simp->len);
    if (simp->must_free_data)
      do_free(allocator, simp->data);
    else
      simp->must_free_data = TRUE;
    simp->data = new_data;
    simp->alloced = new_alloced;
  }
  memcpy(simp->data + simp->len, data, len);
  simp->len = new_len;
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
}

/**
 * \defgroup packedsz protobuf_c_message_get_packed_size() implementation
 *
 * Routines mainly used by protobuf_c_message_get_packed_size().
 *
 * \ingroup internal
 * @{
 */

/**
 * Return the number of bytes required to store the tag for the field. Includes
 * 3 bits for the wire-type, and a single bit that denotes the end-of-tag.
 *
 * \param number
 *      Field tag to encode.
 * \return
 *      Number of bytes required.
 */
211 212 213 214 215 216 217 218 219 220 221 222
static inline size_t get_tag_size(uint32_t number) {
  if (number < (1UL << 4)) {
    return 1;
  } else if (number < (1UL << 11)) {
    return 2;
  } else if (number < (1UL << 18)) {
    return 3;
  } else if (number < (1UL << 25)) {
    return 4;
  } else {
    return 5;
  }
223 224 225 226 227 228 229 230 231 232 233
}

/**
 * Return the number of bytes required to store a variable-length unsigned
 * 32-bit integer in base-128 varint encoding.
 *
 * \param v
 *      Value to encode.
 * \return
 *      Number of bytes required.
 */
234 235 236 237 238 239 240 241 242 243 244 245
static inline size_t uint32_size(uint32_t v) {
  if (v < (1UL << 7)) {
    return 1;
  } else if (v < (1UL << 14)) {
    return 2;
  } else if (v < (1UL << 21)) {
    return 3;
  } else if (v < (1UL << 28)) {
    return 4;
  } else {
    return 5;
  }
246 247 248 249 250 251 252 253 254 255 256
}

/**
 * Return the number of bytes required to store a variable-length signed 32-bit
 * integer in base-128 varint encoding.
 *
 * \param v
 *      Value to encode.
 * \return
 *      Number of bytes required.
 */
257 258 259 260 261 262 263 264 265 266 267 268 269 270
static inline size_t int32_size(int32_t v) {
  if (v < 0) {
    return 10;
  } else if (v < (1L << 7)) {
    return 1;
  } else if (v < (1L << 14)) {
    return 2;
  } else if (v < (1L << 21)) {
    return 3;
  } else if (v < (1L << 28)) {
    return 4;
  } else {
    return 5;
  }
271 272 273 274 275 276 277 278 279 280 281
}

/**
 * Return the ZigZag-encoded 32-bit unsigned integer form of a 32-bit signed
 * integer.
 *
 * \param v
 *      Value to encode.
 * \return
 *      ZigZag encoded integer.
 */
282 283 284 285 286
static inline uint32_t zigzag32(int32_t v) {
  if (v < 0)
    return (-(uint32_t)v) * 2 - 1;
  else
    return (uint32_t)(v)*2;
287 288 289 290 291 292 293 294 295 296 297 298
}

/**
 * Return the number of bytes required to store a signed 32-bit integer,
 * converted to an unsigned 32-bit integer with ZigZag encoding, using base-128
 * varint encoding.
 *
 * \param v
 *      Value to encode.
 * \return
 *      Number of bytes required.
 */
299
static inline size_t sint32_size(int32_t v) { return uint32_size(zigzag32(v)); }
300 301 302 303 304 305 306 307 308 309

/**
 * Return the number of bytes required to store a 64-bit unsigned integer in
 * base-128 varint encoding.
 *
 * \param v
 *      Value to encode.
 * \return
 *      Number of bytes required.
 */
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
static inline size_t uint64_size(uint64_t v) {
  uint32_t upper_v = (uint32_t)(v >> 32);

  if (upper_v == 0) {
    return uint32_size((uint32_t)v);
  } else if (upper_v < (1UL << 3)) {
    return 5;
  } else if (upper_v < (1UL << 10)) {
    return 6;
  } else if (upper_v < (1UL << 17)) {
    return 7;
  } else if (upper_v < (1UL << 24)) {
    return 8;
  } else if (upper_v < (1UL << 31)) {
    return 9;
  } else {
    return 10;
  }
328 329 330 331 332 333 334 335 336 337 338
}

/**
 * Return the ZigZag-encoded 64-bit unsigned integer form of a 64-bit signed
 * integer.
 *
 * \param v
 *      Value to encode.
 * \return
 *      ZigZag encoded integer.
 */
339 340 341 342 343
static inline uint64_t zigzag64(int64_t v) {
  if (v < 0)
    return (-(uint64_t)v) * 2 - 1;
  else
    return (uint64_t)(v)*2;
344 345 346 347 348 349 350 351 352 353 354 355
}

/**
 * Return the number of bytes required to store a signed 64-bit integer,
 * converted to an unsigned 64-bit integer with ZigZag encoding, using base-128
 * varint encoding.
 *
 * \param v
 *      Value to encode.
 * \return
 *      Number of bytes required.
 */
356
static inline size_t sint64_size(int64_t v) { return uint64_size(zigzag64(v)); }
357 358 359 360 361 362 363 364 365 366 367 368

/**
 * Calculate the serialized size of a single required message field, including
 * the space needed by the preceding tag.
 *
 * \param field
 *      Field descriptor for member.
 * \param member
 *      Field to encode.
 * \return
 *      Number of bytes required.
 */
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
static size_t required_field_get_packed_size(
    const ProtobufCFieldDescriptor *field, const void *member) {
  size_t rv = get_tag_size(field->id);

  switch (field->type) {
    case PROTOBUF_C_TYPE_SINT32:
      return rv + sint32_size(*(const int32_t *)member);
    case PROTOBUF_C_TYPE_ENUM:
    case PROTOBUF_C_TYPE_INT32:
      return rv + int32_size(*(const int32_t *)member);
    case PROTOBUF_C_TYPE_UINT32:
      return rv + uint32_size(*(const uint32_t *)member);
    case PROTOBUF_C_TYPE_SINT64:
      return rv + sint64_size(*(const int64_t *)member);
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_UINT64:
      return rv + uint64_size(*(const uint64_t *)member);
    case PROTOBUF_C_TYPE_SFIXED32:
    case PROTOBUF_C_TYPE_FIXED32:
      return rv + 4;
    case PROTOBUF_C_TYPE_SFIXED64:
    case PROTOBUF_C_TYPE_FIXED64:
      return rv + 8;
    case PROTOBUF_C_TYPE_BOOL:
      return rv + 1;
    case PROTOBUF_C_TYPE_FLOAT:
      return rv + 4;
    case PROTOBUF_C_TYPE_DOUBLE:
      return rv + 8;
    case PROTOBUF_C_TYPE_STRING: {
      const char *str = *(char *const *)member;
      size_t len = str ? strlen(str) : 0;
      return rv + uint32_size(len) + len;
    }
    case PROTOBUF_C_TYPE_BYTES: {
      size_t len = ((const ProtobufCBinaryData *)member)->len;
      return rv + uint32_size(len) + len;
    }
    case PROTOBUF_C_TYPE_MESSAGE: {
      const ProtobufCMessage *msg = *(ProtobufCMessage *const *)member;
      size_t subrv = msg ? protobuf_c_message_get_packed_size(msg) : 0;
      return rv + uint32_size(subrv) + subrv;
    }
  }
  PROTOBUF_C__ASSERT_NOT_REACHED();
  return 0;
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
}

/**
 * Calculate the serialized size of a single oneof message field, including
 * the space needed by the preceding tag. Returns 0 if the oneof field isn't
 * selected or is not set.
 *
 * \param field
 *      Field descriptor for member.
 * \param oneof_case
 *      Enum value that selects the field in the oneof.
 * \param member
 *      Field to encode.
 * \return
 *      Number of bytes required.
 */
431 432 433 434 435 436 437 438 439 440 441 442
static size_t oneof_field_get_packed_size(const ProtobufCFieldDescriptor *field,
                                          uint32_t oneof_case,
                                          const void *member) {
  if (oneof_case != field->id) {
    return 0;
  }
  if (field->type == PROTOBUF_C_TYPE_MESSAGE ||
      field->type == PROTOBUF_C_TYPE_STRING) {
    const void *ptr = *(const void *const *)member;
    if (ptr == NULL || ptr == field->default_value) return 0;
  }
  return required_field_get_packed_size(field, member);
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
}

/**
 * Calculate the serialized size of a single optional message field, including
 * the space needed by the preceding tag. Returns 0 if the optional field isn't
 * set.
 *
 * \param field
 *      Field descriptor for member.
 * \param has
 *      True if the field exists, false if not.
 * \param member
 *      Field to encode.
 * \return
 *      Number of bytes required.
 */
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
static size_t optional_field_get_packed_size(
    const ProtobufCFieldDescriptor *field, const protobuf_c_boolean has,
    const void *member) {
  if (field->type == PROTOBUF_C_TYPE_MESSAGE ||
      field->type == PROTOBUF_C_TYPE_STRING) {
    const void *ptr = *(const void *const *)member;
    if (ptr == NULL || ptr == field->default_value) return 0;
  } else {
    if (!has) return 0;
  }
  return required_field_get_packed_size(field, member);
}

static protobuf_c_boolean field_is_zeroish(
    const ProtobufCFieldDescriptor *field, const void *member) {
  protobuf_c_boolean ret = FALSE;

  switch (field->type) {
    case PROTOBUF_C_TYPE_BOOL:
      ret = (0 == *(const protobuf_c_boolean *)member);
      break;
    case PROTOBUF_C_TYPE_ENUM:
    case PROTOBUF_C_TYPE_SINT32:
    case PROTOBUF_C_TYPE_INT32:
    case PROTOBUF_C_TYPE_UINT32:
    case PROTOBUF_C_TYPE_SFIXED32:
    case PROTOBUF_C_TYPE_FIXED32:
      ret = (0 == *(const uint32_t *)member);
      break;
    case PROTOBUF_C_TYPE_SINT64:
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_UINT64:
    case PROTOBUF_C_TYPE_SFIXED64:
    case PROTOBUF_C_TYPE_FIXED64:
      ret = (0 == *(const uint64_t *)member);
      break;
    case PROTOBUF_C_TYPE_FLOAT:
      ret = (0 == *(const float *)member);
      break;
    case PROTOBUF_C_TYPE_DOUBLE:
      ret = (0 == *(const double *)member);
      break;
    case PROTOBUF_C_TYPE_STRING:
      ret = (NULL == *(const char *const *)member) ||
            ('\0' == **(const char *const *)member);
      break;
    case PROTOBUF_C_TYPE_BYTES:
    case PROTOBUF_C_TYPE_MESSAGE:
      ret = (NULL == *(const void *const *)member);
      break;
    default:
      ret = TRUE;
      break;
  }

  return ret;
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
}

/**
 * Calculate the serialized size of a single unlabeled message field, including
 * the space needed by the preceding tag. Returns 0 if the field isn't set or
 * if it is set to a "zeroish" value (null pointer or 0 for numerical values).
 * Unlabeled fields are supported only in proto3.
 *
 * \param field
 *      Field descriptor for member.
 * \param member
 *      Field to encode.
 * \return
 *      Number of bytes required.
 */
530 531 532 533
static size_t unlabeled_field_get_packed_size(
    const ProtobufCFieldDescriptor *field, const void *member) {
  if (field_is_zeroish(field, member)) return 0;
  return required_field_get_packed_size(field, member);
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
}

/**
 * Calculate the serialized size of repeated message fields, which may consist
 * of any number of values (including 0). Includes the space needed by the
 * preceding tags (as needed).
 *
 * \param field
 *      Field descriptor for member.
 * \param count
 *      Number of repeated field members.
 * \param member
 *      Field to encode.
 * \return
 *      Number of bytes required.
 */
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
static size_t repeated_field_get_packed_size(
    const ProtobufCFieldDescriptor *field, size_t count, const void *member) {
  size_t header_size;
  size_t rv = 0;
  unsigned i;
  void *array = *(void *const *)member;

  if (count == 0) return 0;
  header_size = get_tag_size(field->id);
  if (0 == (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED)) header_size *= count;

  switch (field->type) {
    case PROTOBUF_C_TYPE_SINT32:
      for (i = 0; i < count; i++) rv += sint32_size(((int32_t *)array)[i]);
      break;
    case PROTOBUF_C_TYPE_ENUM:
    case PROTOBUF_C_TYPE_INT32:
      for (i = 0; i < count; i++) rv += int32_size(((int32_t *)array)[i]);
      break;
    case PROTOBUF_C_TYPE_UINT32:
      for (i = 0; i < count; i++) rv += uint32_size(((uint32_t *)array)[i]);
      break;
    case PROTOBUF_C_TYPE_SINT64:
      for (i = 0; i < count; i++) rv += sint64_size(((int64_t *)array)[i]);
      break;
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_UINT64:
      for (i = 0; i < count; i++) rv += uint64_size(((uint64_t *)array)[i]);
      break;
    case PROTOBUF_C_TYPE_SFIXED32:
    case PROTOBUF_C_TYPE_FIXED32:
    case PROTOBUF_C_TYPE_FLOAT:
      rv += 4 * count;
      break;
    case PROTOBUF_C_TYPE_SFIXED64:
    case PROTOBUF_C_TYPE_FIXED64:
    case PROTOBUF_C_TYPE_DOUBLE:
      rv += 8 * count;
      break;
    case PROTOBUF_C_TYPE_BOOL:
      rv += count;
      break;
    case PROTOBUF_C_TYPE_STRING:
      for (i = 0; i < count; i++) {
        size_t len = strlen(((char **)array)[i]);
        rv += uint32_size(len) + len;
      }
      break;
    case PROTOBUF_C_TYPE_BYTES:
      for (i = 0; i < count; i++) {
        size_t len = ((ProtobufCBinaryData *)array)[i].len;
        rv += uint32_size(len) + len;
      }
      break;
    case PROTOBUF_C_TYPE_MESSAGE:
      for (i = 0; i < count; i++) {
        size_t len =
            protobuf_c_message_get_packed_size(((ProtobufCMessage **)array)[i]);
        rv += uint32_size(len) + len;
      }
      break;
  }

  if (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED))
    header_size += uint32_size(rv);
  return header_size + rv;
616 617 618 619 620 621 622 623 624 625 626 627
}

/**
 * Calculate the serialized size of an unknown field, i.e. one that is passed
 * through mostly uninterpreted. This is required for forward compatibility if
 * new fields are added to the message descriptor.
 *
 * \param field
 *      Unknown field type.
 * \return
 *      Number of bytes required.
 */
628 629 630
static inline size_t unknown_field_get_packed_size(
    const ProtobufCMessageUnknownField *field) {
  return get_tag_size(field->tag) + field->len;
631 632 633 634 635 636 637
}

/**@}*/

/*
 * Calculate the serialized size of the message.
 */
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
size_t protobuf_c_message_get_packed_size(const ProtobufCMessage *message) {
  unsigned i;
  size_t rv = 0;

  ASSERT_IS_MESSAGE(message);
  for (i = 0; i < message->descriptor->n_fields; i++) {
    const ProtobufCFieldDescriptor *field = message->descriptor->fields + i;
    const void *member = ((const char *)message) + field->offset;
    const void *qmember = ((const char *)message) + field->quantifier_offset;

    if (field->label == PROTOBUF_C_LABEL_REQUIRED) {
      rv += required_field_get_packed_size(field, member);
    } else if ((field->label == PROTOBUF_C_LABEL_OPTIONAL ||
                field->label == PROTOBUF_C_LABEL_NONE) &&
               (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF))) {
      rv += oneof_field_get_packed_size(field, *(const uint32_t *)qmember,
                                        member);
    } else if (field->label == PROTOBUF_C_LABEL_OPTIONAL) {
      rv += optional_field_get_packed_size(
          field, *(protobuf_c_boolean *)qmember, member);
    } else if (field->label == PROTOBUF_C_LABEL_NONE) {
      rv += unlabeled_field_get_packed_size(field, member);
    } else {
      rv += repeated_field_get_packed_size(field, *(const size_t *)qmember,
                                           member);
    }
  }
  for (i = 0; i < message->n_unknown_fields; i++)
    rv += unknown_field_get_packed_size(&message->unknown_fields[i]);
  return rv;
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
}

/**
 * \defgroup pack protobuf_c_message_pack() implementation
 *
 * Routines mainly used by protobuf_c_message_pack().
 *
 * \ingroup internal
 * @{
 */

/**
 * Pack an unsigned 32-bit integer in base-128 varint encoding and return the
 * number of bytes written, which must be 5 or less.
 *
 * \param value
 *      Value to encode.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
static inline size_t uint32_pack(uint32_t value, uint8_t *out) {
  unsigned rv = 0;

  if (value >= 0x80) {
    out[rv++] = value | 0x80;
    value >>= 7;
    if (value >= 0x80) {
      out[rv++] = value | 0x80;
      value >>= 7;
      if (value >= 0x80) {
        out[rv++] = value | 0x80;
        value >>= 7;
        if (value >= 0x80) {
          out[rv++] = value | 0x80;
          value >>= 7;
        }
      }
    }
  }
  /* assert: value<128 */
  out[rv++] = value;
  return rv;
712 713 714 715 716 717 718 719 720 721 722 723 724
}

/**
 * Pack a signed 32-bit integer and return the number of bytes written.
 * Negative numbers are encoded as two's complement 64-bit integers.
 *
 * \param value
 *      Value to encode.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
725 726 727 728 729 730 731 732 733 734 735 736 737
static inline size_t int32_pack(int32_t value, uint8_t *out) {
  if (value < 0) {
    out[0] = value | 0x80;
    out[1] = (value >> 7) | 0x80;
    out[2] = (value >> 14) | 0x80;
    out[3] = (value >> 21) | 0x80;
    out[4] = (value >> 28) | 0x80;
    out[5] = out[6] = out[7] = out[8] = 0xff;
    out[9] = 0x01;
    return 10;
  } else {
    return uint32_pack(value, out);
  }
738 739 740 741 742 743 744 745 746 747 748 749 750
}

/**
 * Pack a signed 32-bit integer using ZigZag encoding and return the number of
 * bytes written.
 *
 * \param value
 *      Value to encode.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
751 752
static inline size_t sint32_pack(int32_t value, uint8_t *out) {
  return uint32_pack(zigzag32(value), out);
753 754 755 756 757 758 759 760 761 762 763 764 765
}

/**
 * Pack a 64-bit unsigned integer using base-128 varint encoding and return the
 * number of bytes written.
 *
 * \param value
 *      Value to encode.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
static size_t uint64_pack(uint64_t value, uint8_t *out) {
  uint32_t hi = (uint32_t)(value >> 32);
  uint32_t lo = (uint32_t)value;
  unsigned rv;

  if (hi == 0) return uint32_pack((uint32_t)lo, out);
  out[0] = (lo) | 0x80;
  out[1] = (lo >> 7) | 0x80;
  out[2] = (lo >> 14) | 0x80;
  out[3] = (lo >> 21) | 0x80;
  if (hi < 8) {
    out[4] = (hi << 4) | (lo >> 28);
    return 5;
  } else {
    out[4] = ((hi & 7) << 4) | (lo >> 28) | 0x80;
    hi >>= 3;
  }
  rv = 5;
  while (hi >= 128) {
    out[rv++] = hi | 0x80;
    hi >>= 7;
  }
  out[rv++] = hi;
  return rv;
790 791 792 793 794 795 796 797 798 799 800 801 802
}

/**
 * Pack a 64-bit signed integer in ZigZag encoding and return the number of
 * bytes written.
 *
 * \param value
 *      Value to encode.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
803 804
static inline size_t sint64_pack(int64_t value, uint8_t *out) {
  return uint64_pack(zigzag64(value), out);
805 806 807 808 809 810 811 812 813 814 815 816 817
}

/**
 * Pack a 32-bit quantity in little-endian byte order. Used for protobuf wire
 * types fixed32, sfixed32, float. Similar to "htole32".
 *
 * \param value
 *      Value to encode.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
818
static inline size_t fixed32_pack(uint32_t value, void *out) {
819
#if !defined(WORDS_BIGENDIAN)
820
  memcpy(out, &value, 4);
821
#else
822
  uint8_t *buf = out;
823

824 825 826 827
  buf[0] = value;
  buf[1] = value >> 8;
  buf[2] = value >> 16;
  buf[3] = value >> 24;
828
#endif
829
  return 4;
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
}

/**
 * Pack a 64-bit quantity in little-endian byte order. Used for protobuf wire
 * types fixed64, sfixed64, double. Similar to "htole64".
 *
 * \todo The big-endian impl is really only good for 32-bit machines, a 64-bit
 * version would be appreciated, plus a way to decide to use 64-bit math where
 * convenient.
 *
 * \param value
 *      Value to encode.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
847
static inline size_t fixed64_pack(uint64_t value, void *out) {
848
#if !defined(WORDS_BIGENDIAN)
849
  memcpy(out, &value, 8);
850
#else
851 852
  fixed32_pack(value, out);
  fixed32_pack(value >> 32, ((char *)out) + 4);
853
#endif
854
  return 8;
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
}

/**
 * Pack a boolean value as an integer and return the number of bytes written.
 *
 * \todo Perhaps on some platforms *out = !!value would be a better impl, b/c
 * that is idiomatic C++ in some STL implementations.
 *
 * \param value
 *      Value to encode.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
870 871 872
static inline size_t boolean_pack(protobuf_c_boolean value, uint8_t *out) {
  *out = value ? TRUE : FALSE;
  return 1;
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
}

/**
 * Pack a NUL-terminated C string and return the number of bytes written. The
 * output includes a length delimiter.
 *
 * The NULL pointer is treated as an empty string. This isn't really necessary,
 * but it allows people to leave required strings blank. (See Issue #13 in the
 * bug tracker for a little more explanation).
 *
 * \param str
 *      String to encode.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
890 891 892 893 894 895 896 897 898 899
static inline size_t string_pack(const char *str, uint8_t *out) {
  if (str == NULL) {
    out[0] = 0;
    return 1;
  } else {
    size_t len = strlen(str);
    size_t rv = uint32_pack(len, out);
    memcpy(out + rv, str, len);
    return rv + len;
  }
900 901 902 903 904 905 906 907 908 909 910 911 912
}

/**
 * Pack a ProtobufCBinaryData and return the number of bytes written. The output
 * includes a length delimiter.
 *
 * \param bd
 *      ProtobufCBinaryData to encode.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
913 914 915 916 917 918
static inline size_t binary_data_pack(const ProtobufCBinaryData *bd,
                                      uint8_t *out) {
  size_t len = bd->len;
  size_t rv = uint32_pack(len, out);
  memcpy(out + rv, bd->data, len);
  return rv + len;
919 920 921 922 923 924 925 926 927 928 929 930 931
}

/**
 * Pack a ProtobufCMessage and return the number of bytes written. The output
 * includes a length delimiter.
 *
 * \param message
 *      ProtobufCMessage object to pack.
 * \param[out] out
 *      Packed message.
 * \return
 *      Number of bytes written to `out`.
 */
932 933 934 935 936 937 938 939 940 941 942
static inline size_t prefixed_message_pack(const ProtobufCMessage *message,
                                           uint8_t *out) {
  if (message == NULL) {
    out[0] = 0;
    return 1;
  } else {
    size_t rv = protobuf_c_message_pack(message, out + 1);
    uint32_t rv_packed_size = uint32_size(rv);
    if (rv_packed_size != 1) memmove(out + rv_packed_size, out + 1, rv);
    return uint32_pack(rv, out) + rv;
  }
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
}

/**
 * Pack a field tag.
 *
 * Wire-type will be added in required_field_pack().
 *
 * \todo Just call uint64_pack on 64-bit platforms.
 *
 * \param id
 *      Tag value to encode.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
959 960 961 962 963
static size_t tag_pack(uint32_t id, uint8_t *out) {
  if (id < (1UL << (32 - 3)))
    return uint32_pack(id << 3, out);
  else
    return uint64_pack(((uint64_t)id) << 3, out);
964 965 966 967 968 969 970 971 972 973 974 975 976 977
}

/**
 * Pack a required field and return the number of bytes written.
 *
 * \param field
 *      Field descriptor.
 * \param member
 *      The field member.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
static size_t required_field_pack(const ProtobufCFieldDescriptor *field,
                                  const void *member, uint8_t *out) {
  size_t rv = tag_pack(field->id, out);

  switch (field->type) {
    case PROTOBUF_C_TYPE_SINT32:
      out[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;
      return rv + sint32_pack(*(const int32_t *)member, out + rv);
    case PROTOBUF_C_TYPE_ENUM:
    case PROTOBUF_C_TYPE_INT32:
      out[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;
      return rv + int32_pack(*(const int32_t *)member, out + rv);
    case PROTOBUF_C_TYPE_UINT32:
      out[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;
      return rv + uint32_pack(*(const uint32_t *)member, out + rv);
    case PROTOBUF_C_TYPE_SINT64:
      out[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;
      return rv + sint64_pack(*(const int64_t *)member, out + rv);
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_UINT64:
      out[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;
      return rv + uint64_pack(*(const uint64_t *)member, out + rv);
    case PROTOBUF_C_TYPE_SFIXED32:
    case PROTOBUF_C_TYPE_FIXED32:
    case PROTOBUF_C_TYPE_FLOAT:
      out[0] |= PROTOBUF_C_WIRE_TYPE_32BIT;
      return rv + fixed32_pack(*(const uint32_t *)member, out + rv);
    case PROTOBUF_C_TYPE_SFIXED64:
    case PROTOBUF_C_TYPE_FIXED64:
    case PROTOBUF_C_TYPE_DOUBLE:
      out[0] |= PROTOBUF_C_WIRE_TYPE_64BIT;
      return rv + fixed64_pack(*(const uint64_t *)member, out + rv);
    case PROTOBUF_C_TYPE_BOOL:
      out[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;
      return rv + boolean_pack(*(const protobuf_c_boolean *)member, out + rv);
    case PROTOBUF_C_TYPE_STRING:
      out[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;
      return rv + string_pack(*(char *const *)member, out + rv);
    case PROTOBUF_C_TYPE_BYTES:
      out[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;
      return rv +
             binary_data_pack((const ProtobufCBinaryData *)member, out + rv);
    case PROTOBUF_C_TYPE_MESSAGE:
      out[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;
      return rv + prefixed_message_pack(*(ProtobufCMessage *const *)member,
                                        out + rv);
  }
  PROTOBUF_C__ASSERT_NOT_REACHED();
  return 0;
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
}

/**
 * Pack a oneof field and return the number of bytes written. Only packs the
 * field that is selected by the case enum.
 *
 * \param field
 *      Field descriptor.
 * \param oneof_case
 *      Enum value that selects the field in the oneof.
 * \param member
 *      The field member.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
static size_t oneof_field_pack(const ProtobufCFieldDescriptor *field,
                               uint32_t oneof_case, const void *member,
                               uint8_t *out) {
  if (oneof_case != field->id) {
    return 0;
  }
  if (field->type == PROTOBUF_C_TYPE_MESSAGE ||
      field->type == PROTOBUF_C_TYPE_STRING) {
    const void *ptr = *(const void *const *)member;
    if (ptr == NULL || ptr == field->default_value) return 0;
  }
  return required_field_pack(field, member, out);
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
}

/**
 * Pack an optional field and return the number of bytes written.
 *
 * \param field
 *      Field descriptor.
 * \param has
 *      Whether the field is set.
 * \param member
 *      The field member.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
static size_t optional_field_pack(const ProtobufCFieldDescriptor *field,
                                  const protobuf_c_boolean has,
                                  const void *member, uint8_t *out) {
  if (field->type == PROTOBUF_C_TYPE_MESSAGE ||
      field->type == PROTOBUF_C_TYPE_STRING) {
    const void *ptr = *(const void *const *)member;
    if (ptr == NULL || ptr == field->default_value) return 0;
  } else {
    if (!has) return 0;
  }
  return required_field_pack(field, member, out);
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
}

/**
 * Pack an unlabeled field and return the number of bytes written.
 *
 * \param field
 *      Field descriptor.
 * \param member
 *      The field member.
 * \param[out] out
 *      Packed value.
 * \return
 *      Number of bytes written to `out`.
 */
1097 1098 1099 1100
static size_t unlabeled_field_pack(const ProtobufCFieldDescriptor *field,
                                   const void *member, uint8_t *out) {
  if (field_is_zeroish(field, member)) return 0;
  return required_field_pack(field, member, out);
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
}

/**
 * Given a field type, return the in-memory size.
 *
 * \todo Implement as a table lookup.
 *
 * \param type
 *      Field type.
 * \return
 *      Size of the field.
 */
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
static inline size_t sizeof_elt_in_repeated_array(ProtobufCType type) {
  switch (type) {
    case PROTOBUF_C_TYPE_SINT32:
    case PROTOBUF_C_TYPE_INT32:
    case PROTOBUF_C_TYPE_UINT32:
    case PROTOBUF_C_TYPE_SFIXED32:
    case PROTOBUF_C_TYPE_FIXED32:
    case PROTOBUF_C_TYPE_FLOAT:
    case PROTOBUF_C_TYPE_ENUM:
      return 4;
    case PROTOBUF_C_TYPE_SINT64:
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_UINT64:
    case PROTOBUF_C_TYPE_SFIXED64:
    case PROTOBUF_C_TYPE_FIXED64:
    case PROTOBUF_C_TYPE_DOUBLE:
      return 8;
    case PROTOBUF_C_TYPE_BOOL:
      return sizeof(protobuf_c_boolean);
    case PROTOBUF_C_TYPE_STRING:
    case PROTOBUF_C_TYPE_MESSAGE:
      return sizeof(void *);
    case PROTOBUF_C_TYPE_BYTES:
      return sizeof(ProtobufCBinaryData);
  }
  PROTOBUF_C__ASSERT_NOT_REACHED();
  return 0;
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
}

/**
 * Pack an array of 32-bit quantities.
 *
 * \param[out] out
 *      Destination.
 * \param[in] in
 *      Source.
 * \param[in] n
 *      Number of elements in the source array.
 */
1152 1153
static void copy_to_little_endian_32(void *out, const void *in,
                                     const unsigned n) {
1154
#if !defined(WORDS_BIGENDIAN)
1155
  memcpy(out, in, n * 4);
1156
#else
1157 1158 1159
  unsigned i;
  const uint32_t *ini = in;
  for (i = 0; i < n; i++) fixed32_pack(ini[i], (uint32_t *)out + i);
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
#endif
}

/**
 * Pack an array of 64-bit quantities.
 *
 * \param[out] out
 *      Destination.
 * \param[in] in
 *      Source.
 * \param[in] n
 *      Number of elements in the source array.
 */
1173 1174
static void copy_to_little_endian_64(void *out, const void *in,
                                     const unsigned n) {
1175
#if !defined(WORDS_BIGENDIAN)
1176
  memcpy(out, in, n * 8);
1177
#else
1178 1179 1180
  unsigned i;
  const uint64_t *ini = in;
  for (i = 0; i < n; i++) fixed64_pack(ini[i], (uint64_t *)out + i);
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
#endif
}

/**
 * Get the minimum number of bytes required to pack a field value of a
 * particular type.
 *
 * \param type
 *      Field type.
 * \return
 *      Number of bytes.
 */
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
static unsigned get_type_min_size(ProtobufCType type) {
  if (type == PROTOBUF_C_TYPE_SFIXED32 || type == PROTOBUF_C_TYPE_FIXED32 ||
      type == PROTOBUF_C_TYPE_FLOAT) {
    return 4;
  }
  if (type == PROTOBUF_C_TYPE_SFIXED64 || type == PROTOBUF_C_TYPE_FIXED64 ||
      type == PROTOBUF_C_TYPE_DOUBLE) {
    return 8;
  }
  return 1;
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
}

/**
 * Packs the elements of a repeated field and returns the serialised field and
 * its length.
 *
 * \param field
 *      Field descriptor.
 * \param count
 *      Number of elements in the repeated field array.
 * \param member
 *      Pointer to the elements for this repeated field.
 * \param[out] out
 *      Serialised representation of the repeated field.
 * \return
 *      Number of bytes serialised to `out`.
 */
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
static size_t repeated_field_pack(const ProtobufCFieldDescriptor *field,
                                  size_t count, const void *member,
                                  uint8_t *out) {
  void *array = *(void *const *)member;
  unsigned i;

  if (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED)) {
    unsigned header_len;
    unsigned len_start;
    unsigned min_length;
    unsigned payload_len;
    unsigned length_size_min;
    unsigned actual_length_size;
    uint8_t *payload_at;

    if (count == 0) return 0;
    header_len = tag_pack(field->id, out);
    out[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;
    len_start = header_len;
    min_length = get_type_min_size(field->type) * count;
    length_size_min = uint32_size(min_length);
    header_len += length_size_min;
    payload_at = out + header_len;

    switch (field->type) {
      case PROTOBUF_C_TYPE_SFIXED32:
      case PROTOBUF_C_TYPE_FIXED32:
      case PROTOBUF_C_TYPE_FLOAT:
        copy_to_little_endian_32(payload_at, array, count);
        payload_at += count * 4;
        break;
      case PROTOBUF_C_TYPE_SFIXED64:
      case PROTOBUF_C_TYPE_FIXED64:
      case PROTOBUF_C_TYPE_DOUBLE:
        copy_to_little_endian_64(payload_at, array, count);
        payload_at += count * 8;
        break;
      case PROTOBUF_C_TYPE_ENUM:
      case PROTOBUF_C_TYPE_INT32: {
        const int32_t *arr = (const int32_t *)array;
        for (i = 0; i < count; i++)
          payload_at += int32_pack(arr[i], payload_at);
        break;
      }
      case PROTOBUF_C_TYPE_SINT32: {
        const int32_t *arr = (const int32_t *)array;
        for (i = 0; i < count; i++)
          payload_at += sint32_pack(arr[i], payload_at);
        break;
      }
      case PROTOBUF_C_TYPE_SINT64: {
        const int64_t *arr = (const int64_t *)array;
        for (i = 0; i < count; i++)
          payload_at += sint64_pack(arr[i], payload_at);
        break;
      }
      case PROTOBUF_C_TYPE_UINT32: {
        const uint32_t *arr = (const uint32_t *)array;
        for (i = 0; i < count; i++)
          payload_at += uint32_pack(arr[i], payload_at);
        break;
      }
      case PROTOBUF_C_TYPE_INT64:
      case PROTOBUF_C_TYPE_UINT64: {
        const uint64_t *arr = (const uint64_t *)array;
        for (i = 0; i < count; i++)
          payload_at += uint64_pack(arr[i], payload_at);
        break;
      }
      case PROTOBUF_C_TYPE_BOOL: {
        const protobuf_c_boolean *arr = (const protobuf_c_boolean *)array;
        for (i = 0; i < count; i++)
          payload_at += boolean_pack(arr[i], payload_at);
        break;
      }
      default:
        PROTOBUF_C__ASSERT_NOT_REACHED();
    }

    payload_len = payload_at - (out + header_len);
    actual_length_size = uint32_size(payload_len);
    if (length_size_min != actual_length_size) {
      assert(actual_length_size == length_size_min + 1);
      memmove(out + header_len + 1, out + header_len, payload_len);
      header_len++;
    }
    uint32_pack(payload_len, out + len_start);
    return header_len + payload_len;
  } else {
    /* not "packed" cased */
    /* CONSIDER: optimize this case a bit (by putting the loop inside the
     * switch) */
    size_t rv = 0;
    unsigned siz = sizeof_elt_in_repeated_array(field->type);

    for (i = 0; i < count; i++) {
      rv += required_field_pack(field, array, out + rv);
      array = (char *)array + siz;
    }
    return rv;
  }
}

static size_t unknown_field_pack(const ProtobufCMessageUnknownField *field,
                                 uint8_t *out) {
  size_t rv = tag_pack(field->tag, out);
  out[0] |= field->wire_type;
  memcpy(out + rv, field->data, field->len);
  return rv + field->len;
1329 1330 1331 1332
}

/**@}*/

1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
size_t protobuf_c_message_pack(const ProtobufCMessage *message, uint8_t *out) {
  unsigned i;
  size_t rv = 0;

  ASSERT_IS_MESSAGE(message);
  for (i = 0; i < message->descriptor->n_fields; i++) {
    const ProtobufCFieldDescriptor *field = message->descriptor->fields + i;
    const void *member = ((const char *)message) + field->offset;

    /*
     * It doesn't hurt to compute qmember (a pointer to the
     * quantifier field of the structure), but the pointer is only
     * valid if the field is:
     *  - a repeated field, or
     *  - a field that is part of a oneof
     *  - an optional field that isn't a pointer type
     * (Meaning: not a message or a string).
     */
    const void *qmember = ((const char *)message) + field->quantifier_offset;

    if (field->label == PROTOBUF_C_LABEL_REQUIRED) {
      rv += required_field_pack(field, member, out + rv);
    } else if ((field->label == PROTOBUF_C_LABEL_OPTIONAL ||
                field->label == PROTOBUF_C_LABEL_NONE) &&
               (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF))) {
      rv +=
          oneof_field_pack(field, *(const uint32_t *)qmember, member, out + rv);
    } else if (field->label == PROTOBUF_C_LABEL_OPTIONAL) {
      rv += optional_field_pack(field, *(const protobuf_c_boolean *)qmember,
                                member, out + rv);
    } else if (field->label == PROTOBUF_C_LABEL_NONE) {
      rv += unlabeled_field_pack(field, member, out + rv);
    } else {
      rv += repeated_field_pack(field, *(const size_t *)qmember, member,
                                out + rv);
    }
  }
  for (i = 0; i < message->n_unknown_fields; i++)
    rv += unknown_field_pack(&message->unknown_fields[i], out + rv);
  return rv;
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
}

/**
 * \defgroup packbuf protobuf_c_message_pack_to_buffer() implementation
 *
 * Routines mainly used by protobuf_c_message_pack_to_buffer().
 *
 * \ingroup internal
 * @{
 */

/**
 * Pack a required field to a virtual buffer.
 *
 * \param field
 *      Field descriptor.
 * \param member
 *      The element to be packed.
 * \param[out] buffer
 *      Virtual buffer to append data to.
 * \return
 *      Number of bytes packed.
 */
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
static size_t required_field_pack_to_buffer(
    const ProtobufCFieldDescriptor *field, const void *member,
    ProtobufCBuffer *buffer) {
  size_t rv;
  uint8_t scratch[MAX_UINT64_ENCODED_SIZE * 2];

  rv = tag_pack(field->id, scratch);
  switch (field->type) {
    case PROTOBUF_C_TYPE_SINT32:
      scratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;
      rv += sint32_pack(*(const int32_t *)member, scratch + rv);
      buffer->append(buffer, rv, scratch);
      break;
    case PROTOBUF_C_TYPE_ENUM:
    case PROTOBUF_C_TYPE_INT32:
      scratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;
      rv += int32_pack(*(const int32_t *)member, scratch + rv);
      buffer->append(buffer, rv, scratch);
      break;
    case PROTOBUF_C_TYPE_UINT32:
      scratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;
      rv += uint32_pack(*(const uint32_t *)member, scratch + rv);
      buffer->append(buffer, rv, scratch);
      break;
    case PROTOBUF_C_TYPE_SINT64:
      scratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;
      rv += sint64_pack(*(const int64_t *)member, scratch + rv);
      buffer->append(buffer, rv, scratch);
      break;
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_UINT64:
      scratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;
      rv += uint64_pack(*(const uint64_t *)member, scratch + rv);
      buffer->append(buffer, rv, scratch);
      break;
    case PROTOBUF_C_TYPE_SFIXED32:
    case PROTOBUF_C_TYPE_FIXED32:
    case PROTOBUF_C_TYPE_FLOAT:
      scratch[0] |= PROTOBUF_C_WIRE_TYPE_32BIT;
      rv += fixed32_pack(*(const uint32_t *)member, scratch + rv);
      buffer->append(buffer, rv, scratch);
      break;
    case PROTOBUF_C_TYPE_SFIXED64:
    case PROTOBUF_C_TYPE_FIXED64:
    case PROTOBUF_C_TYPE_DOUBLE:
      scratch[0] |= PROTOBUF_C_WIRE_TYPE_64BIT;
      rv += fixed64_pack(*(const uint64_t *)member, scratch + rv);
      buffer->append(buffer, rv, scratch);
      break;
    case PROTOBUF_C_TYPE_BOOL:
      scratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT;
      rv += boolean_pack(*(const protobuf_c_boolean *)member, scratch + rv);
      buffer->append(buffer, rv, scratch);
      break;
    case PROTOBUF_C_TYPE_STRING: {
      const char *str = *(char *const *)member;
      size_t sublen = str ? strlen(str) : 0;

      scratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;
      rv += uint32_pack(sublen, scratch + rv);
      buffer->append(buffer, rv, scratch);
      buffer->append(buffer, sublen, (const uint8_t *)str);
      rv += sublen;
      break;
    }
    case PROTOBUF_C_TYPE_BYTES: {
      const ProtobufCBinaryData *bd = ((const ProtobufCBinaryData *)member);
      size_t sublen = bd->len;

      scratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;
      rv += uint32_pack(sublen, scratch + rv);
      buffer->append(buffer, rv, scratch);
      buffer->append(buffer, sublen, bd->data);
      rv += sublen;
      break;
    }
    case PROTOBUF_C_TYPE_MESSAGE: {
      uint8_t simple_buffer_scratch[256];
      size_t sublen;
      const ProtobufCMessage *msg = *(ProtobufCMessage *const *)member;
      ProtobufCBufferSimple simple_buffer =
          PROTOBUF_C_BUFFER_SIMPLE_INIT(simple_buffer_scratch);

      scratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;
      if (msg == NULL)
        sublen = 0;
      else
        sublen = protobuf_c_message_pack_to_buffer(msg, &simple_buffer.base);
      rv += uint32_pack(sublen, scratch + rv);
      buffer->append(buffer, rv, scratch);
      buffer->append(buffer, sublen, simple_buffer.data);
      rv += sublen;
      PROTOBUF_C_BUFFER_SIMPLE_CLEAR(&simple_buffer);
      break;
    }
    default:
      PROTOBUF_C__ASSERT_NOT_REACHED();
  }
  return rv;
1495 1496 1497
}

/**
1498 1499
 * Pack a oneof field to a buffer. Only packs the field that is selected by the
 * case enum.
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
 *
 * \param field
 *      Field descriptor.
 * \param oneof_case
 *      Enum value that selects the field in the oneof.
 * \param member
 *      The element to be packed.
 * \param[out] buffer
 *      Virtual buffer to append data to.
 * \return
 *      Number of bytes serialised to `buffer`.
 */
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
static size_t oneof_field_pack_to_buffer(const ProtobufCFieldDescriptor *field,
                                         uint32_t oneof_case,
                                         const void *member,
                                         ProtobufCBuffer *buffer) {
  if (oneof_case != field->id) {
    return 0;
  }
  if (field->type == PROTOBUF_C_TYPE_MESSAGE ||
      field->type == PROTOBUF_C_TYPE_STRING) {
    const void *ptr = *(const void *const *)member;
    if (ptr == NULL || ptr == field->default_value) return 0;
  }
  return required_field_pack_to_buffer(field, member, buffer);
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
}

/**
 * Pack an optional field to a buffer.
 *
 * \param field
 *      Field descriptor.
 * \param has
 *      Whether the field is set.
 * \param member
 *      The element to be packed.
 * \param[out] buffer
 *      Virtual buffer to append data to.
 * \return
 *      Number of bytes serialised to `buffer`.
 */
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
static size_t optional_field_pack_to_buffer(
    const ProtobufCFieldDescriptor *field, const protobuf_c_boolean has,
    const void *member, ProtobufCBuffer *buffer) {
  if (field->type == PROTOBUF_C_TYPE_MESSAGE ||
      field->type == PROTOBUF_C_TYPE_STRING) {
    const void *ptr = *(const void *const *)member;
    if (ptr == NULL || ptr == field->default_value) return 0;
  } else {
    if (!has) return 0;
  }
  return required_field_pack_to_buffer(field, member, buffer);
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
}

/**
 * Pack an unlabeled field to a buffer.
 *
 * \param field
 *      Field descriptor.
 * \param member
 *      The element to be packed.
 * \param[out] buffer
 *      Virtual buffer to append data to.
 * \return
 *      Number of bytes serialised to `buffer`.
 */
1566 1567 1568 1569 1570
static size_t unlabeled_field_pack_to_buffer(
    const ProtobufCFieldDescriptor *field, const void *member,
    ProtobufCBuffer *buffer) {
  if (field_is_zeroish(field, member)) return 0;
  return required_field_pack_to_buffer(field, member, buffer);
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
}

/**
 * Get the packed size of an array of same field type.
 *
 * \param field
 *      Field descriptor.
 * \param count
 *      Number of elements of this type.
 * \param array
 *      The elements to get the size of.
 * \return
 *      Number of bytes required.
 */
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
static size_t get_packed_payload_length(const ProtobufCFieldDescriptor *field,
                                        unsigned count, const void *array) {
  unsigned rv = 0;
  unsigned i;

  switch (field->type) {
    case PROTOBUF_C_TYPE_SFIXED32:
    case PROTOBUF_C_TYPE_FIXED32:
    case PROTOBUF_C_TYPE_FLOAT:
      return count * 4;
    case PROTOBUF_C_TYPE_SFIXED64:
    case PROTOBUF_C_TYPE_FIXED64:
    case PROTOBUF_C_TYPE_DOUBLE:
      return count * 8;
    case PROTOBUF_C_TYPE_ENUM:
    case PROTOBUF_C_TYPE_INT32: {
      const int32_t *arr = (const int32_t *)array;
      for (i = 0; i < count; i++) rv += int32_size(arr[i]);
      break;
    }
    case PROTOBUF_C_TYPE_SINT32: {
      const int32_t *arr = (const int32_t *)array;
      for (i = 0; i < count; i++) rv += sint32_size(arr[i]);
      break;
    }
    case PROTOBUF_C_TYPE_UINT32: {
      const uint32_t *arr = (const uint32_t *)array;
      for (i = 0; i < count; i++) rv += uint32_size(arr[i]);
      break;
    }
    case PROTOBUF_C_TYPE_SINT64: {
      const int64_t *arr = (const int64_t *)array;
      for (i = 0; i < count; i++) rv += sint64_size(arr[i]);
      break;
    }
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_UINT64: {
      const uint64_t *arr = (const uint64_t *)array;
      for (i = 0; i < count; i++) rv += uint64_size(arr[i]);
      break;
    }
    case PROTOBUF_C_TYPE_BOOL:
      return count;
    default:
      PROTOBUF_C__ASSERT_NOT_REACHED();
  }
  return rv;
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
}

/**
 * Pack an array of same field type to a virtual buffer.
 *
 * \param field
 *      Field descriptor.
 * \param count
 *      Number of elements of this type.
 * \param array
 *      The elements to get the size of.
 * \param[out] buffer
 *      Virtual buffer to append data to.
 * \return
 *      Number of bytes packed.
 */
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
static size_t pack_buffer_packed_payload(const ProtobufCFieldDescriptor *field,
                                         unsigned count, const void *array,
                                         ProtobufCBuffer *buffer) {
  uint8_t scratch[16];
  size_t rv = 0;
  unsigned i;

  switch (field->type) {
    case PROTOBUF_C_TYPE_SFIXED32:
    case PROTOBUF_C_TYPE_FIXED32:
    case PROTOBUF_C_TYPE_FLOAT:
1659
#if !defined(WORDS_BIGENDIAN)
1660 1661
      rv = count * 4;
      goto no_packing_needed;
1662
#else
1663 1664 1665 1666 1667 1668
      for (i = 0; i < count; i++) {
        unsigned len = fixed32_pack(((uint32_t *)array)[i], scratch);
        buffer->append(buffer, len, scratch);
        rv += len;
      }
      break;
1669
#endif
1670 1671 1672
    case PROTOBUF_C_TYPE_SFIXED64:
    case PROTOBUF_C_TYPE_FIXED64:
    case PROTOBUF_C_TYPE_DOUBLE:
1673
#if !defined(WORDS_BIGENDIAN)
1674 1675
      rv = count * 8;
      goto no_packing_needed;
1676
#else
1677 1678 1679 1680 1681 1682
      for (i = 0; i < count; i++) {
        unsigned len = fixed64_pack(((uint64_t *)array)[i], scratch);
        buffer->append(buffer, len, scratch);
        rv += len;
      }
      break;
1683
#endif
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
    case PROTOBUF_C_TYPE_ENUM:
    case PROTOBUF_C_TYPE_INT32:
      for (i = 0; i < count; i++) {
        unsigned len = int32_pack(((int32_t *)array)[i], scratch);
        buffer->append(buffer, len, scratch);
        rv += len;
      }
      break;
    case PROTOBUF_C_TYPE_SINT32:
      for (i = 0; i < count; i++) {
        unsigned len = sint32_pack(((int32_t *)array)[i], scratch);
        buffer->append(buffer, len, scratch);
        rv += len;
      }
      break;
    case PROTOBUF_C_TYPE_UINT32:
      for (i = 0; i < count; i++) {
        unsigned len = uint32_pack(((uint32_t *)array)[i], scratch);
        buffer->append(buffer, len, scratch);
        rv += len;
      }
      break;
    case PROTOBUF_C_TYPE_SINT64:
      for (i = 0; i < count; i++) {
        unsigned len = sint64_pack(((int64_t *)array)[i], scratch);
        buffer->append(buffer, len, scratch);
        rv += len;
      }
      break;
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_UINT64:
      for (i = 0; i < count; i++) {
        unsigned len = uint64_pack(((uint64_t *)array)[i], scratch);
        buffer->append(buffer, len, scratch);
        rv += len;
      }
      break;
    case PROTOBUF_C_TYPE_BOOL:
      for (i = 0; i < count; i++) {
        unsigned len = boolean_pack(((protobuf_c_boolean *)array)[i], scratch);
        buffer->append(buffer, len, scratch);
        rv += len;
      }
      return count;
    default:
      PROTOBUF_C__ASSERT_NOT_REACHED();
  }
  return rv;
1732 1733 1734

#if !defined(WORDS_BIGENDIAN)
no_packing_needed:
1735 1736
  buffer->append(buffer, rv, array);
  return rv;
1737 1738 1739
#endif
}

1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
static size_t repeated_field_pack_to_buffer(
    const ProtobufCFieldDescriptor *field, unsigned count, const void *member,
    ProtobufCBuffer *buffer) {
  char *array = *(char *const *)member;

  if (count == 0) return 0;
  if (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED)) {
    uint8_t scratch[MAX_UINT64_ENCODED_SIZE * 2];
    size_t rv = tag_pack(field->id, scratch);
    size_t payload_len = get_packed_payload_length(field, count, array);
    size_t tmp;

    scratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;
    rv += uint32_pack(payload_len, scratch + rv);
    buffer->append(buffer, rv, scratch);
    tmp = pack_buffer_packed_payload(field, count, array, buffer);
    assert(tmp == payload_len);
    return rv + payload_len;
  } else {
    size_t siz;
    unsigned i;
    /* CONSIDER: optimize this case a bit (by putting the loop inside the
     * switch) */
    unsigned rv = 0;

    siz = sizeof_elt_in_repeated_array(field->type);
    for (i = 0; i < count; i++) {
      rv += required_field_pack_to_buffer(field, array, buffer);
      array += siz;
    }
    return rv;
  }
}

static size_t unknown_field_pack_to_buffer(
    const ProtobufCMessageUnknownField *field, ProtobufCBuffer *buffer) {
  uint8_t header[MAX_UINT64_ENCODED_SIZE];
  size_t rv = tag_pack(field->tag, header);

  header[0] |= field->wire_type;
  buffer->append(buffer, rv, header);
  buffer->append(buffer, field->len, field->data);
  return rv + field->len;
1783 1784 1785 1786
}

/**@}*/

1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
size_t protobuf_c_message_pack_to_buffer(const ProtobufCMessage *message,
                                         ProtobufCBuffer *buffer) {
  unsigned i;
  size_t rv = 0;

  ASSERT_IS_MESSAGE(message);
  for (i = 0; i < message->descriptor->n_fields; i++) {
    const ProtobufCFieldDescriptor *field = message->descriptor->fields + i;
    const void *member = ((const char *)message) + field->offset;
    const void *qmember = ((const char *)message) + field->quantifier_offset;

    if (field->label == PROTOBUF_C_LABEL_REQUIRED) {
      rv += required_field_pack_to_buffer(field, member, buffer);
    } else if ((field->label == PROTOBUF_C_LABEL_OPTIONAL ||
                field->label == PROTOBUF_C_LABEL_NONE) &&
               (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF))) {
      rv += oneof_field_pack_to_buffer(field, *(const uint32_t *)qmember,
                                       member, buffer);
    } else if (field->label == PROTOBUF_C_LABEL_OPTIONAL) {
      rv += optional_field_pack_to_buffer(
          field, *(const protobuf_c_boolean *)qmember, member, buffer);
    } else if (field->label == PROTOBUF_C_LABEL_NONE) {
      rv += unlabeled_field_pack_to_buffer(field, member, buffer);
    } else {
      rv += repeated_field_pack_to_buffer(field, *(const size_t *)qmember,
                                          member, buffer);
    }
  }
  for (i = 0; i < message->n_unknown_fields; i++)
    rv += unknown_field_pack_to_buffer(&message->unknown_fields[i], buffer);

  return rv;
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
}

/**
 * \defgroup unpack unpacking implementation
 *
 * Routines mainly used by the unpacking functions.
 *
 * \ingroup internal
 * @{
 */

1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
static inline int int_range_lookup(unsigned n_ranges,
                                   const ProtobufCIntRange *ranges, int value) {
  unsigned n;
  unsigned start;

  if (n_ranges == 0) return -1;
  start = 0;
  n = n_ranges;
  while (n > 1) {
    unsigned mid = start + n / 2;

    if (value < ranges[mid].start_value) {
      n = mid - start;
    } else if (value >=
               ranges[mid].start_value +
                   (int)(ranges[mid + 1].orig_index - ranges[mid].orig_index)) {
      unsigned new_start = mid + 1;
      n = start + n - new_start;
      start = new_start;
    } else
      return (value - ranges[mid].start_value) + ranges[mid].orig_index;
  }
  if (n > 0) {
    unsigned start_orig_index = ranges[start].orig_index;
    unsigned range_size = ranges[start + 1].orig_index - start_orig_index;

    if (ranges[start].start_value <= value &&
        value < (int)(ranges[start].start_value + range_size)) {
      return (value - ranges[start].start_value) + start_orig_index;
    }
  }
  return -1;
}

static size_t parse_tag_and_wiretype(size_t len, const uint8_t *data,
                                     uint32_t *tag_out,
                                     ProtobufCWireType *wiretype_out) {
  unsigned max_rv = len > 5 ? 5 : len;
  uint32_t tag = (data[0] & 0x7f) >> 3;
  unsigned shift = 4;
  unsigned rv;

  *wiretype_out = data[0] & 7;
  if ((data[0] & 0x80) == 0) {
    *tag_out = tag;
    return 1;
  }
  for (rv = 1; rv < max_rv; rv++) {
    if (data[rv] & 0x80) {
      tag |= (data[rv] & 0x7f) << shift;
      shift += 7;
    } else {
      tag |= data[rv] << shift;
      *tag_out = tag;
      return rv + 1;
    }
  }
  return 0; /* error: bad header */
1888 1889 1890 1891 1892 1893 1894
}

/* sizeof(ScannedMember) must be <= (1UL<<BOUND_SIZEOF_SCANNED_MEMBER_LOG2) */
#define BOUND_SIZEOF_SCANNED_MEMBER_LOG2 5
typedef struct _ScannedMember ScannedMember;
/** Field as it's being read. */
struct _ScannedMember {
1895 1896 1897 1898 1899 1900
  uint32_t tag;                          /**< Field tag. */
  uint8_t wire_type;                     /**< Field type. */
  uint8_t length_prefix_len;             /**< Prefix length. */
  const ProtobufCFieldDescriptor *field; /**< Field descriptor. */
  size_t len;                            /**< Field length. */
  const uint8_t *data;                   /**< Pointer to field data. */
1901 1902
};

1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
static inline uint32_t scan_length_prefixed_data(size_t len,
                                                 const uint8_t *data,
                                                 size_t *prefix_len_out) {
  unsigned hdr_max = len < 5 ? len : 5;
  unsigned hdr_len;
  uint32_t val = 0;
  unsigned i;
  unsigned shift = 0;

  for (i = 0; i < hdr_max; i++) {
    val |= (data[i] & 0x7f) << shift;
    shift += 7;
    if ((data[i] & 0x80) == 0) break;
  }
  if (i == hdr_max) {
    PROTOBUF_C_UNPACK_ERROR("error parsing length for length-prefixed data");
    return 0;
  }
  hdr_len = i + 1;
  *prefix_len_out = hdr_len;
  if (hdr_len + val > len) {
    PROTOBUF_C_UNPACK_ERROR("data too short after length-prefix of %u", val);
    return 0;
  }
  return hdr_len + val;
}

static size_t max_b128_numbers(size_t len, const uint8_t *data) {
  size_t rv = 0;
  while (len--)
    if ((*data++ & 0x80) == 0) ++rv;
  return rv;
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
}

/**@}*/

/**
 * Merge earlier message into a latter message.
 *
 * For numeric types and strings, if the same value appears multiple
 * times, the parser accepts the last value it sees. For embedded
 * message fields, the parser merges multiple instances of the same
 * field. That is, all singular scalar fields in the latter instance
 * replace those in the former, singular embedded messages are merged,
 * and repeated fields are concatenated.
 *
 * The earlier message should be freed after calling this function, as
 * some of its fields may have been reused and changed to their default
 * values during the merge.
 */
1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
static protobuf_c_boolean merge_messages(ProtobufCMessage *earlier_msg,
                                         ProtobufCMessage *latter_msg,
                                         ProtobufCAllocator *allocator) {
  unsigned i;
  const ProtobufCFieldDescriptor *fields = latter_msg->descriptor->fields;
  for (i = 0; i < latter_msg->descriptor->n_fields; i++) {
    if (fields[i].label == PROTOBUF_C_LABEL_REPEATED) {
      size_t *n_earlier =
          STRUCT_MEMBER_PTR(size_t, earlier_msg, fields[i].quantifier_offset);
      uint8_t **p_earlier =
          STRUCT_MEMBER_PTR(uint8_t *, earlier_msg, fields[i].offset);
      size_t *n_latter =
          STRUCT_MEMBER_PTR(size_t, latter_msg, fields[i].quantifier_offset);
      uint8_t **p_latter =
          STRUCT_MEMBER_PTR(uint8_t *, latter_msg, fields[i].offset);

      if (*n_earlier > 0) {
        if (*n_latter > 0) {
          /* Concatenate the repeated field */
          size_t el_size = sizeof_elt_in_repeated_array(fields[i].type);
          uint8_t *new_field;

          new_field = do_alloc(allocator, (*n_earlier + *n_latter) * el_size);
          if (!new_field) return FALSE;

          memcpy(new_field, *p_earlier, *n_earlier * el_size);
          memcpy(new_field + *n_earlier * el_size, *p_latter,
                 *n_latter * el_size);

          do_free(allocator, *p_latter);
          do_free(allocator, *p_earlier);
          *p_latter = new_field;
          *n_latter = *n_earlier + *n_latter;
        } else {
          /* Zero copy the repeated field from the earlier message */
          *n_latter = *n_earlier;
          *p_latter = *p_earlier;
        }
        /* Make sure the field does not get double freed */
        *n_earlier = 0;
        *p_earlier = 0;
      }
    } else if (fields[i].label == PROTOBUF_C_LABEL_OPTIONAL ||
               fields[i].label == PROTOBUF_C_LABEL_NONE) {
      const ProtobufCFieldDescriptor *field;
      uint32_t *earlier_case_p =
          STRUCT_MEMBER_PTR(uint32_t, earlier_msg, fields[i].quantifier_offset);
      uint32_t *latter_case_p =
          STRUCT_MEMBER_PTR(uint32_t, latter_msg, fields[i].quantifier_offset);
      protobuf_c_boolean need_to_merge = FALSE;
      void *earlier_elem;
      void *latter_elem;
      const void *def_val;

      if (fields[i].flags & PROTOBUF_C_FIELD_FLAG_ONEOF) {
        if (*latter_case_p == 0) {
          /* lookup correct oneof field */
          int field_index = int_range_lookup(
              latter_msg->descriptor->n_field_ranges,
              latter_msg->descriptor->field_ranges, *earlier_case_p);
          if (field_index < 0) return FALSE;
          field = latter_msg->descriptor->fields + field_index;
        } else {
          /* Oneof is present in the latter message, move on */
          continue;
        }
      } else {
        field = &fields[i];
      }

      earlier_elem = STRUCT_MEMBER_P(earlier_msg, field->offset);
      latter_elem = STRUCT_MEMBER_P(latter_msg, field->offset);
      def_val = field->default_value;

      switch (field->type) {
        case PROTOBUF_C_TYPE_MESSAGE: {
          ProtobufCMessage *em = *(ProtobufCMessage **)earlier_elem;
          ProtobufCMessage *lm = *(ProtobufCMessage **)latter_elem;
          if (em != NULL) {
            if (lm != NULL) {
              if (!merge_messages(em, lm, allocator)) return FALSE;
              /* Already merged */
              need_to_merge = FALSE;
            } else {
              /* Zero copy the message */
              need_to_merge = TRUE;
            }
          }
          break;
        }
        case PROTOBUF_C_TYPE_BYTES: {
          uint8_t *e_data = ((ProtobufCBinaryData *)earlier_elem)->data;
          uint8_t *l_data = ((ProtobufCBinaryData *)latter_elem)->data;
          const ProtobufCBinaryData *d_bd = (ProtobufCBinaryData *)def_val;

          need_to_merge =
              (e_data != NULL && (d_bd == NULL || e_data != d_bd->data)) &&
              (l_data == NULL || (d_bd != NULL && l_data == d_bd->data));
          break;
        }
        case PROTOBUF_C_TYPE_STRING: {
          char *e_str = *(char **)earlier_elem;
          char *l_str = *(char **)latter_elem;
          const char *d_str = def_val;

          need_to_merge = e_str != d_str && l_str == d_str;
          break;
        }
        default: {
          /* Could be has field or case enum, the logic is
           * equivalent, since 0 (FALSE) means not set for
           * oneof */
          need_to_merge = (*earlier_case_p != 0) && (*latter_case_p == 0);
          break;
        }
      }

      if (need_to_merge) {
        size_t el_size = sizeof_elt_in_repeated_array(field->type);
        memcpy(latter_elem, earlier_elem, el_size);
        /*
         * Reset the element from the old message to 0
         * to make sure earlier message deallocation
         * doesn't corrupt zero-copied data in the new
         * message, earlier message will be freed after
         * this function is called anyway
         */
        memset(earlier_elem, 0, el_size);

        if (field->quantifier_offset != 0) {
          /* Set the has field or the case enum,
           * if applicable */
          *latter_case_p = *earlier_case_p;
          *earlier_case_p = 0;
        }
      }
    }
  }
  return TRUE;
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
}

/**
 * Count packed elements.
 *
 * Given a raw slab of packed-repeated values, determine the number of
 * elements. This function detects certain kinds of errors but not
 * others; the remaining error checking is done by
 * parse_packed_repeated_member().
 */
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
static protobuf_c_boolean count_packed_elements(ProtobufCType type, size_t len,
                                                const uint8_t *data,
                                                size_t *count_out) {
  switch (type) {
    case PROTOBUF_C_TYPE_SFIXED32:
    case PROTOBUF_C_TYPE_FIXED32:
    case PROTOBUF_C_TYPE_FLOAT:
      if (len % 4 != 0) {
        PROTOBUF_C_UNPACK_ERROR(
            "length must be a multiple of 4 for fixed-length 32-bit types");
        return FALSE;
      }
      *count_out = len / 4;
      return TRUE;
    case PROTOBUF_C_TYPE_SFIXED64:
    case PROTOBUF_C_TYPE_FIXED64:
    case PROTOBUF_C_TYPE_DOUBLE:
      if (len % 8 != 0) {
        PROTOBUF_C_UNPACK_ERROR(
            "length must be a multiple of 8 for fixed-length 64-bit types");
        return FALSE;
      }
      *count_out = len / 8;
      return TRUE;
    case PROTOBUF_C_TYPE_ENUM:
    case PROTOBUF_C_TYPE_INT32:
    case PROTOBUF_C_TYPE_SINT32:
    case PROTOBUF_C_TYPE_UINT32:
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_SINT64:
    case PROTOBUF_C_TYPE_UINT64:
      *count_out = max_b128_numbers(len, data);
      return TRUE;
    case PROTOBUF_C_TYPE_BOOL:
      *count_out = len;
      return TRUE;
    case PROTOBUF_C_TYPE_STRING:
    case PROTOBUF_C_TYPE_BYTES:
    case PROTOBUF_C_TYPE_MESSAGE:
    default:
      PROTOBUF_C_UNPACK_ERROR("bad protobuf-c type %u for packed-repeated",
                              type);
      return FALSE;
  }
}

static inline uint32_t parse_uint32(unsigned len, const uint8_t *data) {
  uint32_t rv = data[0] & 0x7f;
  if (len > 1) {
    rv |= ((uint32_t)(data[1] & 0x7f) << 7);
    if (len > 2) {
      rv |= ((uint32_t)(data[2] & 0x7f) << 14);
      if (len > 3) {
        rv |= ((uint32_t)(data[3] & 0x7f) << 21);
        if (len > 4) rv |= ((uint32_t)(data[4]) << 28);
      }
    }
  }
  return rv;
}

static inline uint32_t parse_int32(unsigned len, const uint8_t *data) {
  return parse_uint32(len, data);
}

static inline int32_t unzigzag32(uint32_t v) {
  if (v & 1)
    return -(v >> 1) - 1;
  else
    return v >> 1;
}

static inline uint32_t parse_fixed_uint32(const uint8_t *data) {
2175
#if !defined(WORDS_BIGENDIAN)
2176 2177 2178
  uint32_t t;
  memcpy(&t, data, 4);
  return t;
2179
#else
2180 2181
  return data[0] | ((uint32_t)(data[1]) << 8) | ((uint32_t)(data[2]) << 16) |
         ((uint32_t)(data[3]) << 24);
2182 2183 2184
#endif
}

2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
static uint64_t parse_uint64(unsigned len, const uint8_t *data) {
  unsigned shift, i;
  uint64_t rv;

  if (len < 5) return parse_uint32(len, data);
  rv = ((uint64_t)(data[0] & 0x7f)) | ((uint64_t)(data[1] & 0x7f) << 7) |
       ((uint64_t)(data[2] & 0x7f) << 14) | ((uint64_t)(data[3] & 0x7f) << 21);
  shift = 28;
  for (i = 4; i < len; i++) {
    rv |= (((uint64_t)(data[i] & 0x7f)) << shift);
    shift += 7;
  }
  return rv;
}

static inline int64_t unzigzag64(uint64_t v) {
  if (v & 1)
    return -(v >> 1) - 1;
  else
    return v >> 1;
}

static inline uint64_t parse_fixed_uint64(const uint8_t *data) {
2208
#if !defined(WORDS_BIGENDIAN)
2209 2210 2211
  uint64_t t;
  memcpy(&t, data, 8);
  return t;
2212
#else
2213 2214
  return (uint64_t)parse_fixed_uint32(data) |
         (((uint64_t)parse_fixed_uint32(data + 4)) << 32);
2215 2216 2217
#endif
}

2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
static protobuf_c_boolean parse_boolean(unsigned len, const uint8_t *data) {
  unsigned i;
  for (i = 0; i < len; i++)
    if (data[i] & 0x7f) return TRUE;
  return FALSE;
}

static protobuf_c_boolean parse_required_member(
    ScannedMember *scanned_member, void *member, ProtobufCAllocator *allocator,
    protobuf_c_boolean maybe_clear) {
  unsigned len = scanned_member->len;
  const uint8_t *data = scanned_member->data;
  ProtobufCWireType wire_type = scanned_member->wire_type;

  switch (scanned_member->field->type) {
    case PROTOBUF_C_TYPE_ENUM:
    case PROTOBUF_C_TYPE_INT32:
      if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return FALSE;
      *(int32_t *)member = parse_int32(len, data);
      return TRUE;
    case PROTOBUF_C_TYPE_UINT32:
      if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return FALSE;
      *(uint32_t *)member = parse_uint32(len, data);
      return TRUE;
    case PROTOBUF_C_TYPE_SINT32:
      if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return FALSE;
      *(int32_t *)member = unzigzag32(parse_uint32(len, data));
      return TRUE;
    case PROTOBUF_C_TYPE_SFIXED32:
    case PROTOBUF_C_TYPE_FIXED32:
    case PROTOBUF_C_TYPE_FLOAT:
      if (wire_type != PROTOBUF_C_WIRE_TYPE_32BIT) return FALSE;
      *(uint32_t *)member = parse_fixed_uint32(data);
      return TRUE;
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_UINT64:
      if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return FALSE;
      *(uint64_t *)member = parse_uint64(len, data);
      return TRUE;
    case PROTOBUF_C_TYPE_SINT64:
      if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return FALSE;
      *(int64_t *)member = unzigzag64(parse_uint64(len, data));
      return TRUE;
    case PROTOBUF_C_TYPE_SFIXED64:
    case PROTOBUF_C_TYPE_FIXED64:
    case PROTOBUF_C_TYPE_DOUBLE:
      if (wire_type != PROTOBUF_C_WIRE_TYPE_64BIT) return FALSE;
      *(uint64_t *)member = parse_fixed_uint64(data);
      return TRUE;
    case PROTOBUF_C_TYPE_BOOL:
      *(protobuf_c_boolean *)member = parse_boolean(len, data);
      return TRUE;
    case PROTOBUF_C_TYPE_STRING: {
      char **pstr = member;
      unsigned pref_len = scanned_member->length_prefix_len;

      if (wire_type != PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED) return FALSE;

      if (maybe_clear && *pstr != NULL) {
        const char *def = scanned_member->field->default_value;
        if (*pstr != NULL && *pstr != def) do_free(allocator, *pstr);
      }
      *pstr = do_alloc(allocator, len - pref_len + 1);
      if (*pstr == NULL) return FALSE;
      memcpy(*pstr, data + pref_len, len - pref_len);
      (*pstr)[len - pref_len] = 0;
      return TRUE;
    }
    case PROTOBUF_C_TYPE_BYTES: {
      ProtobufCBinaryData *bd = member;
      const ProtobufCBinaryData *def_bd;
      unsigned pref_len = scanned_member->length_prefix_len;

      if (wire_type != PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED) return FALSE;

      def_bd = scanned_member->field->default_value;
      if (maybe_clear && bd->data != NULL &&
          (def_bd == NULL || bd->data != def_bd->data)) {
        do_free(allocator, bd->data);
      }
      if (len - pref_len > 0) {
        bd->data = do_alloc(allocator, len - pref_len);
        if (bd->data == NULL) return FALSE;
        memcpy(bd->data, data + pref_len, len - pref_len);
      } else {
        bd->data = NULL;
      }
      bd->len = len - pref_len;
      return TRUE;
    }
    case PROTOBUF_C_TYPE_MESSAGE: {
      ProtobufCMessage **pmessage = member;
      ProtobufCMessage *subm;
      const ProtobufCMessage *def_mess;
      protobuf_c_boolean merge_successful = TRUE;
      unsigned pref_len = scanned_member->length_prefix_len;

      if (wire_type != PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED) return FALSE;

      def_mess = scanned_member->field->default_value;
      subm =
          protobuf_c_message_unpack(scanned_member->field->descriptor,
                                    allocator, len - pref_len, data + pref_len);

      if (maybe_clear && *pmessage != NULL && *pmessage != def_mess) {
        if (subm != NULL)
          merge_successful = merge_messages(*pmessage, subm, allocator);
        /* Delete the previous message */
        protobuf_c_message_free_unpacked(*pmessage, allocator);
      }
      *pmessage = subm;
      if (subm == NULL || !merge_successful) return FALSE;
      return TRUE;
    }
  }
  return FALSE;
}

static protobuf_c_boolean parse_oneof_member(ScannedMember *scanned_member,
                                             void *member,
                                             ProtobufCMessage *message,
                                             ProtobufCAllocator *allocator) {
  uint32_t *oneof_case = STRUCT_MEMBER_PTR(
      uint32_t, message, scanned_member->field->quantifier_offset);

  /* If we have already parsed a member of this oneof, free it. */
  if (*oneof_case != 0) {
    /* lookup field */
    int field_index =
        int_range_lookup(message->descriptor->n_field_ranges,
                         message->descriptor->field_ranges, *oneof_case);
    if (field_index < 0) return FALSE;
    const ProtobufCFieldDescriptor *old_field =
        message->descriptor->fields + field_index;
    size_t el_size = sizeof_elt_in_repeated_array(old_field->type);

    switch (old_field->type) {
      case PROTOBUF_C_TYPE_STRING: {
        char **pstr = member;
        const char *def = old_field->default_value;
        if (*pstr != NULL && *pstr != def) do_free(allocator, *pstr);
        break;
      }
      case PROTOBUF_C_TYPE_BYTES: {
        ProtobufCBinaryData *bd = member;
        const ProtobufCBinaryData *def_bd = old_field->default_value;
        if (bd->data != NULL && (def_bd == NULL || bd->data != def_bd->data)) {
          do_free(allocator, bd->data);
        }
        break;
      }
      case PROTOBUF_C_TYPE_MESSAGE: {
        ProtobufCMessage **pmessage = member;
        const ProtobufCMessage *def_mess = old_field->default_value;
        if (*pmessage != NULL && *pmessage != def_mess)
          protobuf_c_message_free_unpacked(*pmessage, allocator);
        break;
      }
      default:
        break;
    }

    memset(member, 0, el_size);
  }
  if (!parse_required_member(scanned_member, member, allocator, TRUE))
    return FALSE;

  *oneof_case = scanned_member->tag;
  return TRUE;
}

static protobuf_c_boolean parse_optional_member(ScannedMember *scanned_member,
                                                void *member,
                                                ProtobufCMessage *message,
                                                ProtobufCAllocator *allocator) {
  if (!parse_required_member(scanned_member, member, allocator, TRUE))
    return FALSE;
  if (scanned_member->field->quantifier_offset != 0)
    STRUCT_MEMBER(protobuf_c_boolean, message,
                  scanned_member->field->quantifier_offset) = TRUE;
  return TRUE;
}

static protobuf_c_boolean parse_repeated_member(ScannedMember *scanned_member,
                                                void *member,
                                                ProtobufCMessage *message,
                                                ProtobufCAllocator *allocator) {
  const ProtobufCFieldDescriptor *field = scanned_member->field;
  size_t *p_n = STRUCT_MEMBER_PTR(size_t, message, field->quantifier_offset);
  size_t siz = sizeof_elt_in_repeated_array(field->type);
  char *array = *(char **)member;

  if (!parse_required_member(scanned_member, array + siz * (*p_n), allocator,
                             FALSE)) {
    return FALSE;
  }
  *p_n += 1;
  return TRUE;
}

static unsigned scan_varint(unsigned len, const uint8_t *data) {
  unsigned i;
  if (len > 10) len = 10;
  for (i = 0; i < len; i++)
    if ((data[i] & 0x80) == 0) break;
  if (i == len) return 0;
  return i + 1;
}

static protobuf_c_boolean parse_packed_repeated_member(
    ScannedMember *scanned_member, void *member, ProtobufCMessage *message) {
  const ProtobufCFieldDescriptor *field = scanned_member->field;
  size_t *p_n = STRUCT_MEMBER_PTR(size_t, message, field->quantifier_offset);
  size_t siz = sizeof_elt_in_repeated_array(field->type);
  void *array = *(char **)member + siz * (*p_n);
  const uint8_t *at = scanned_member->data + scanned_member->length_prefix_len;
  size_t rem = scanned_member->len - scanned_member->length_prefix_len;
  size_t count = 0;
  unsigned i;

  switch (field->type) {
    case PROTOBUF_C_TYPE_SFIXED32:
    case PROTOBUF_C_TYPE_FIXED32:
    case PROTOBUF_C_TYPE_FLOAT:
      count = (scanned_member->len - scanned_member->length_prefix_len) / 4;
2443
#if !defined(WORDS_BIGENDIAN)
2444
      goto no_unpacking_needed;
2445
#else
2446 2447 2448 2449 2450
      for (i = 0; i < count; i++) {
        ((uint32_t *)array)[i] = parse_fixed_uint32(at);
        at += 4;
      }
      break;
2451
#endif
2452 2453 2454 2455
    case PROTOBUF_C_TYPE_SFIXED64:
    case PROTOBUF_C_TYPE_FIXED64:
    case PROTOBUF_C_TYPE_DOUBLE:
      count = (scanned_member->len - scanned_member->length_prefix_len) / 8;
2456
#if !defined(WORDS_BIGENDIAN)
2457
      goto no_unpacking_needed;
2458
#else
2459 2460 2461 2462 2463
      for (i = 0; i < count; i++) {
        ((uint64_t *)array)[i] = parse_fixed_uint64(at);
        at += 8;
      }
      break;
2464
#endif
2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542
    case PROTOBUF_C_TYPE_ENUM:
    case PROTOBUF_C_TYPE_INT32:
      while (rem > 0) {
        unsigned s = scan_varint(rem, at);
        if (s == 0) {
          PROTOBUF_C_UNPACK_ERROR("bad packed-repeated int32 value");
          return FALSE;
        }
        ((int32_t *)array)[count++] = parse_int32(s, at);
        at += s;
        rem -= s;
      }
      break;
    case PROTOBUF_C_TYPE_SINT32:
      while (rem > 0) {
        unsigned s = scan_varint(rem, at);
        if (s == 0) {
          PROTOBUF_C_UNPACK_ERROR("bad packed-repeated sint32 value");
          return FALSE;
        }
        ((int32_t *)array)[count++] = unzigzag32(parse_uint32(s, at));
        at += s;
        rem -= s;
      }
      break;
    case PROTOBUF_C_TYPE_UINT32:
      while (rem > 0) {
        unsigned s = scan_varint(rem, at);
        if (s == 0) {
          PROTOBUF_C_UNPACK_ERROR("bad packed-repeated enum or uint32 value");
          return FALSE;
        }
        ((uint32_t *)array)[count++] = parse_uint32(s, at);
        at += s;
        rem -= s;
      }
      break;

    case PROTOBUF_C_TYPE_SINT64:
      while (rem > 0) {
        unsigned s = scan_varint(rem, at);
        if (s == 0) {
          PROTOBUF_C_UNPACK_ERROR("bad packed-repeated sint64 value");
          return FALSE;
        }
        ((int64_t *)array)[count++] = unzigzag64(parse_uint64(s, at));
        at += s;
        rem -= s;
      }
      break;
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_UINT64:
      while (rem > 0) {
        unsigned s = scan_varint(rem, at);
        if (s == 0) {
          PROTOBUF_C_UNPACK_ERROR("bad packed-repeated int64/uint64 value");
          return FALSE;
        }
        ((int64_t *)array)[count++] = parse_uint64(s, at);
        at += s;
        rem -= s;
      }
      break;
    case PROTOBUF_C_TYPE_BOOL:
      count = rem;
      for (i = 0; i < count; i++) {
        if (at[i] > 1) {
          PROTOBUF_C_UNPACK_ERROR("bad packed-repeated boolean value");
          return FALSE;
        }
        ((protobuf_c_boolean *)array)[i] = at[i];
      }
      break;
    default:
      PROTOBUF_C__ASSERT_NOT_REACHED();
  }
  *p_n += count;
  return TRUE;
2543 2544 2545

#if !defined(WORDS_BIGENDIAN)
no_unpacking_needed:
2546 2547 2548
  memcpy(array, at, count * siz);
  *p_n += count;
  return TRUE;
2549 2550 2551
#endif
}

2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
static protobuf_c_boolean is_packable_type(ProtobufCType type) {
  return type != PROTOBUF_C_TYPE_STRING && type != PROTOBUF_C_TYPE_BYTES &&
         type != PROTOBUF_C_TYPE_MESSAGE;
}

static protobuf_c_boolean parse_member(ScannedMember *scanned_member,
                                       ProtobufCMessage *message,
                                       ProtobufCAllocator *allocator) {
  const ProtobufCFieldDescriptor *field = scanned_member->field;
  void *member;

  if (field == NULL) {
    ProtobufCMessageUnknownField *ufield =
        message->unknown_fields + (message->n_unknown_fields++);
    ufield->tag = scanned_member->tag;
    ufield->wire_type = scanned_member->wire_type;
    ufield->len = scanned_member->len;
    ufield->data = do_alloc(allocator, scanned_member->len);
    if (ufield->data == NULL) return FALSE;
    memcpy(ufield->data, scanned_member->data, ufield->len);
    return TRUE;
  }
  member = (char *)message + field->offset;
  switch (field->label) {
    case PROTOBUF_C_LABEL_REQUIRED:
      return parse_required_member(scanned_member, member, allocator, TRUE);
    case PROTOBUF_C_LABEL_OPTIONAL:
    case PROTOBUF_C_LABEL_NONE:
      if (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF)) {
        return parse_oneof_member(scanned_member, member, message, allocator);
      } else {
        return parse_optional_member(scanned_member, member, message,
                                     allocator);
      }
    case PROTOBUF_C_LABEL_REPEATED:
      if (scanned_member->wire_type == PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED &&
          (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED) ||
           is_packable_type(field->type))) {
        return parse_packed_repeated_member(scanned_member, member, message);
      } else {
        return parse_repeated_member(scanned_member, member, message,
                                     allocator);
      }
  }
  PROTOBUF_C__ASSERT_NOT_REACHED();
  return 0;
2598 2599 2600 2601 2602 2603 2604 2605 2606
}

/**
 * Initialise messages generated by old code.
 *
 * This function is used if desc->message_init == NULL (which occurs
 * for old code, and which would be useful to support allocating
 * descriptors dynamically).
 */
2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654
static void message_init_generic(const ProtobufCMessageDescriptor *desc,
                                 ProtobufCMessage *message) {
  unsigned i;

  memset(message, 0, desc->sizeof_message);
  message->descriptor = desc;
  for (i = 0; i < desc->n_fields; i++) {
    if (desc->fields[i].default_value != NULL &&
        desc->fields[i].label != PROTOBUF_C_LABEL_REPEATED) {
      void *field = STRUCT_MEMBER_P(message, desc->fields[i].offset);
      const void *dv = desc->fields[i].default_value;

      switch (desc->fields[i].type) {
        case PROTOBUF_C_TYPE_INT32:
        case PROTOBUF_C_TYPE_SINT32:
        case PROTOBUF_C_TYPE_SFIXED32:
        case PROTOBUF_C_TYPE_UINT32:
        case PROTOBUF_C_TYPE_FIXED32:
        case PROTOBUF_C_TYPE_FLOAT:
        case PROTOBUF_C_TYPE_ENUM:
          memcpy(field, dv, 4);
          break;
        case PROTOBUF_C_TYPE_INT64:
        case PROTOBUF_C_TYPE_SINT64:
        case PROTOBUF_C_TYPE_SFIXED64:
        case PROTOBUF_C_TYPE_UINT64:
        case PROTOBUF_C_TYPE_FIXED64:
        case PROTOBUF_C_TYPE_DOUBLE:
          memcpy(field, dv, 8);
          break;
        case PROTOBUF_C_TYPE_BOOL:
          memcpy(field, dv, sizeof(protobuf_c_boolean));
          break;
        case PROTOBUF_C_TYPE_BYTES:
          memcpy(field, dv, sizeof(ProtobufCBinaryData));
          break;

        case PROTOBUF_C_TYPE_STRING:
        case PROTOBUF_C_TYPE_MESSAGE:
          /*
           * The next line essentially implements a cast
           * from const, which is totally unavoidable.
           */
          *(const void **)field = dv;
          break;
      }
    }
  }
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
}

/**@}*/

/*
 * ScannedMember slabs (an unpacking implementation detail). Before doing real
 * unpacking, we first scan through the elements to see how many there are (for
 * repeated fields), and which field to use (for non-repeated fields given
 * twice).
 *
 * In order to avoid allocations for small messages, we keep a stack-allocated
 * slab of ScannedMembers of size FIRST_SCANNED_MEMBER_SLAB_SIZE (16). After we
 * fill that up, we allocate each slab twice as large as the previous one.
 */
#define FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2 4

/*
 * The number of slabs, including the stack-allocated ones; choose the number so
 * that we would overflow if we needed a slab larger than provided.
 */
2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
#define MAX_SCANNED_MEMBER_SLAB                                      \
  (sizeof(unsigned int) * 8 - 1 - BOUND_SIZEOF_SCANNED_MEMBER_LOG2 - \
   FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2)

#define REQUIRED_FIELD_BITMAP_SET(index) \
  (required_fields_bitmap[(index) / 8] |= (1UL << ((index) % 8)))

#define REQUIRED_FIELD_BITMAP_IS_SET(index) \
  (required_fields_bitmap[(index) / 8] & (1UL << ((index) % 8)))

ProtobufCMessage *protobuf_c_message_unpack(
    const ProtobufCMessageDescriptor *desc, ProtobufCAllocator *allocator,
    size_t len, const uint8_t *data) {
  ProtobufCMessage *rv;
  size_t rem = len;
  const uint8_t *at = data;
  const ProtobufCFieldDescriptor *last_field = desc->fields + 0;
  ScannedMember first_member_slab[1UL << FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2];

  /*
   * scanned_member_slabs[i] is an array of arrays of ScannedMember.
   * The first slab (scanned_member_slabs[0] is just a pointer to
   * first_member_slab), above. All subsequent slabs will be allocated
   * using the allocator.
   */
  ScannedMember *scanned_member_slabs[MAX_SCANNED_MEMBER_SLAB + 1];
  unsigned which_slab = 0;    /* the slab we are currently populating */
  unsigned in_slab_index = 0; /* number of members in the slab */
  size_t n_unknown = 0;
  unsigned f;
  unsigned j;
  unsigned i_slab;
  unsigned last_field_index = 0;
  unsigned required_fields_bitmap_len;
  unsigned char required_fields_bitmap_stack[16];
  unsigned char *required_fields_bitmap = required_fields_bitmap_stack;
  protobuf_c_boolean required_fields_bitmap_alloced = FALSE;

  ASSERT_IS_MESSAGE_DESCRIPTOR(desc);

  if (allocator == NULL) allocator = &protobuf_c__allocator;

  rv = do_alloc(allocator, desc->sizeof_message);
  if (!rv) return (NULL);
  scanned_member_slabs[0] = first_member_slab;

  required_fields_bitmap_len = (desc->n_fields + 7) / 8;
  if (required_fields_bitmap_len > sizeof(required_fields_bitmap_stack)) {
    required_fields_bitmap = do_alloc(allocator, required_fields_bitmap_len);
    if (!required_fields_bitmap) {
      do_free(allocator, rv);
      return (NULL);
    }
    required_fields_bitmap_alloced = TRUE;
  }
  memset(required_fields_bitmap, 0, required_fields_bitmap_len);

  /*
   * Generated code always defines "message_init". However, we provide a
   * fallback for (1) users of old protobuf-c generated-code that do not
   * provide the function, and (2) descriptors constructed from some other
   * source (most likely, direct construction from the .proto file).
   */
  if (desc->message_init != NULL)
    protobuf_c_message_init(desc, rv);
  else
    message_init_generic(desc, rv);

  while (rem > 0) {
    uint32_t tag;
    ProtobufCWireType wire_type;
    size_t used = parse_tag_and_wiretype(rem, at, &tag, &wire_type);
    const ProtobufCFieldDescriptor *field;
    ScannedMember tmp;

    if (used == 0) {
      PROTOBUF_C_UNPACK_ERROR("error parsing tag/wiretype at offset %u",
                              (unsigned)(at - data));
      goto error_cleanup_during_scan;
    }
    /*
     * \todo Consider optimizing for field[1].id == tag, if field[1]
     * exists!
     */
    if (last_field == NULL || last_field->id != tag) {
      /* lookup field */
      int field_index =
          int_range_lookup(desc->n_field_ranges, desc->field_ranges, tag);
      if (field_index < 0) {
        field = NULL;
        n_unknown++;
      } else {
        field = desc->fields + field_index;
        last_field = field;
        last_field_index = field_index;
      }
    } else {
      field = last_field;
    }

    if (field != NULL && field->label == PROTOBUF_C_LABEL_REQUIRED)
      REQUIRED_FIELD_BITMAP_SET(last_field_index);

    at += used;
    rem -= used;
    tmp.tag = tag;
    tmp.wire_type = wire_type;
    tmp.field = field;
    tmp.data = at;
    tmp.length_prefix_len = 0;

    switch (wire_type) {
      case PROTOBUF_C_WIRE_TYPE_VARINT: {
        unsigned max_len = rem < 10 ? rem : 10;
        unsigned i;

        for (i = 0; i < max_len; i++)
          if ((at[i] & 0x80) == 0) break;
        if (i == max_len) {
          PROTOBUF_C_UNPACK_ERROR("unterminated varint at offset %u",
                                  (unsigned)(at - data));
          goto error_cleanup_during_scan;
        }
        tmp.len = i + 1;
        break;
      }
      case PROTOBUF_C_WIRE_TYPE_64BIT:
        if (rem < 8) {
          PROTOBUF_C_UNPACK_ERROR("too short after 64bit wiretype at offset %u",
                                  (unsigned)(at - data));
          goto error_cleanup_during_scan;
        }
        tmp.len = 8;
        break;
      case PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED: {
        size_t pref_len;

        tmp.len = scan_length_prefixed_data(rem, at, &pref_len);
        if (tmp.len == 0) {
          /* NOTE: scan_length_prefixed_data calls UNPACK_ERROR */
          goto error_cleanup_during_scan;
        }
        tmp.length_prefix_len = pref_len;
        break;
      }
      case PROTOBUF_C_WIRE_TYPE_32BIT:
        if (rem < 4) {
          PROTOBUF_C_UNPACK_ERROR("too short after 32bit wiretype at offset %u",
                                  (unsigned)(at - data));
          goto error_cleanup_during_scan;
        }
        tmp.len = 4;
        break;
      default:
        PROTOBUF_C_UNPACK_ERROR("unsupported tag %u at offset %u", wire_type,
                                (unsigned)(at - data));
        goto error_cleanup_during_scan;
    }

    if (in_slab_index ==
        (1UL << (which_slab + FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2))) {
      size_t size;

      in_slab_index = 0;
      if (which_slab == MAX_SCANNED_MEMBER_SLAB) {
        PROTOBUF_C_UNPACK_ERROR("too many fields");
        goto error_cleanup_during_scan;
      }
      which_slab++;
      size = sizeof(ScannedMember)
             << (which_slab + FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2);
      scanned_member_slabs[which_slab] = do_alloc(allocator, size);
      if (scanned_member_slabs[which_slab] == NULL)
        goto error_cleanup_during_scan;
    }
    scanned_member_slabs[which_slab][in_slab_index++] = tmp;

    if (field != NULL && field->label == PROTOBUF_C_LABEL_REPEATED) {
      size_t *n = STRUCT_MEMBER_PTR(size_t, rv, field->quantifier_offset);
      if (wire_type == PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED &&
          (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED) ||
           is_packable_type(field->type))) {
        size_t count;
        if (!count_packed_elements(field->type, tmp.len - tmp.length_prefix_len,
                                   tmp.data + tmp.length_prefix_len, &count)) {
          PROTOBUF_C_UNPACK_ERROR("counting packed elements");
          goto error_cleanup_during_scan;
        }
        *n += count;
      } else {
        *n += 1;
      }
    }

    at += tmp.len;
    rem -= tmp.len;
  }

  /* allocate space for repeated fields, also check that all required fields
   * have been set */
  for (f = 0; f < desc->n_fields; f++) {
    const ProtobufCFieldDescriptor *field = desc->fields + f;
    if (field->label == PROTOBUF_C_LABEL_REPEATED) {
      size_t siz = sizeof_elt_in_repeated_array(field->type);
      size_t *n_ptr = STRUCT_MEMBER_PTR(size_t, rv, field->quantifier_offset);
      if (*n_ptr != 0) {
        unsigned n = *n_ptr;
        void *a;
        *n_ptr = 0;
        assert(rv->descriptor != NULL);
#define CLEAR_REMAINING_N_PTRS()                               \
  for (f++; f < desc->n_fields; f++) {                         \
    field = desc->fields + f;                                  \
    if (field->label == PROTOBUF_C_LABEL_REPEATED)             \
      STRUCT_MEMBER(size_t, rv, field->quantifier_offset) = 0; \
  }
        a = do_alloc(allocator, siz * n);
        if (!a) {
          CLEAR_REMAINING_N_PTRS();
          goto error_cleanup;
        }
        STRUCT_MEMBER(void *, rv, field->offset) = a;
      }
    } else if (field->label == PROTOBUF_C_LABEL_REQUIRED) {
      if (field->default_value == NULL && !REQUIRED_FIELD_BITMAP_IS_SET(f)) {
        CLEAR_REMAINING_N_PTRS();
        PROTOBUF_C_UNPACK_ERROR("message '%s': missing required field '%s'",
                                desc->name, field->name);
        goto error_cleanup;
      }
    }
  }
2907 2908
#undef CLEAR_REMAINING_N_PTRS

2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936
  /* allocate space for unknown fields */
  if (n_unknown) {
    rv->unknown_fields =
        do_alloc(allocator, n_unknown * sizeof(ProtobufCMessageUnknownField));
    if (rv->unknown_fields == NULL) goto error_cleanup;
  }

  /* do real parsing */
  for (i_slab = 0; i_slab <= which_slab; i_slab++) {
    unsigned max =
        (i_slab == which_slab) ? in_slab_index : (1UL << (i_slab + 4));
    ScannedMember *slab = scanned_member_slabs[i_slab];

    for (j = 0; j < max; j++) {
      if (!parse_member(slab + j, rv, allocator)) {
        PROTOBUF_C_UNPACK_ERROR(
            "error parsing member %s of %s",
            slab->field ? slab->field->name : "*unknown-field*", desc->name);
        goto error_cleanup;
      }
    }
  }

  /* cleanup */
  for (j = 1; j <= which_slab; j++) do_free(allocator, scanned_member_slabs[j]);
  if (required_fields_bitmap_alloced)
    do_free(allocator, required_fields_bitmap);
  return rv;
2937 2938

error_cleanup:
2939 2940 2941 2942 2943
  protobuf_c_message_free_unpacked(rv, allocator);
  for (j = 1; j <= which_slab; j++) do_free(allocator, scanned_member_slabs[j]);
  if (required_fields_bitmap_alloced)
    do_free(allocator, required_fields_bitmap);
  return NULL;
2944 2945

error_cleanup_during_scan:
2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094
  do_free(allocator, rv);
  for (j = 1; j <= which_slab; j++) do_free(allocator, scanned_member_slabs[j]);
  if (required_fields_bitmap_alloced)
    do_free(allocator, required_fields_bitmap);
  return NULL;
}

void protobuf_c_message_free_unpacked(ProtobufCMessage *message,
                                      ProtobufCAllocator *allocator) {
  const ProtobufCMessageDescriptor *desc;
  unsigned f;

  if (message == NULL) return;

  desc = message->descriptor;

  ASSERT_IS_MESSAGE(message);

  if (allocator == NULL) allocator = &protobuf_c__allocator;
  message->descriptor = NULL;
  for (f = 0; f < desc->n_fields; f++) {
    if (0 != (desc->fields[f].flags & PROTOBUF_C_FIELD_FLAG_ONEOF) &&
        desc->fields[f].id !=
            STRUCT_MEMBER(uint32_t, message,
                          desc->fields[f].quantifier_offset)) {
      /* This is not the selected oneof, skip it */
      continue;
    }

    if (desc->fields[f].label == PROTOBUF_C_LABEL_REPEATED) {
      size_t n =
          STRUCT_MEMBER(size_t, message, desc->fields[f].quantifier_offset);
      void *arr = STRUCT_MEMBER(void *, message, desc->fields[f].offset);

      if (arr != NULL) {
        if (desc->fields[f].type == PROTOBUF_C_TYPE_STRING) {
          unsigned i;
          for (i = 0; i < n; i++) do_free(allocator, ((char **)arr)[i]);
        } else if (desc->fields[f].type == PROTOBUF_C_TYPE_BYTES) {
          unsigned i;
          for (i = 0; i < n; i++)
            do_free(allocator, ((ProtobufCBinaryData *)arr)[i].data);
        } else if (desc->fields[f].type == PROTOBUF_C_TYPE_MESSAGE) {
          unsigned i;
          for (i = 0; i < n; i++)
            protobuf_c_message_free_unpacked(((ProtobufCMessage **)arr)[i],
                                             allocator);
        }
        do_free(allocator, arr);
      }
    } else if (desc->fields[f].type == PROTOBUF_C_TYPE_STRING) {
      char *str = STRUCT_MEMBER(char *, message, desc->fields[f].offset);

      if (str && str != desc->fields[f].default_value) do_free(allocator, str);
    } else if (desc->fields[f].type == PROTOBUF_C_TYPE_BYTES) {
      void *data =
          STRUCT_MEMBER(ProtobufCBinaryData, message, desc->fields[f].offset)
              .data;
      const ProtobufCBinaryData *default_bd;

      default_bd = desc->fields[f].default_value;
      if (data != NULL && (default_bd == NULL || default_bd->data != data)) {
        do_free(allocator, data);
      }
    } else if (desc->fields[f].type == PROTOBUF_C_TYPE_MESSAGE) {
      ProtobufCMessage *sm;

      sm = STRUCT_MEMBER(ProtobufCMessage *, message, desc->fields[f].offset);
      if (sm && sm != desc->fields[f].default_value)
        protobuf_c_message_free_unpacked(sm, allocator);
    }
  }

  for (f = 0; f < message->n_unknown_fields; f++)
    do_free(allocator, message->unknown_fields[f].data);
  if (message->unknown_fields != NULL)
    do_free(allocator, message->unknown_fields);

  do_free(allocator, message);
}

void protobuf_c_message_init(const ProtobufCMessageDescriptor *descriptor,
                             void *message) {
  descriptor->message_init((ProtobufCMessage *)(message));
}

protobuf_c_boolean protobuf_c_message_check(const ProtobufCMessage *message) {
  unsigned i;

  if (!message || !message->descriptor ||
      message->descriptor->magic != PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC) {
    return FALSE;
  }

  for (i = 0; i < message->descriptor->n_fields; i++) {
    const ProtobufCFieldDescriptor *f = message->descriptor->fields + i;
    ProtobufCType type = f->type;
    ProtobufCLabel label = f->label;
    void *field = STRUCT_MEMBER_P(message, f->offset);

    if (label == PROTOBUF_C_LABEL_REPEATED) {
      size_t *quantity = STRUCT_MEMBER_P(message, f->quantifier_offset);

      if (*quantity > 0 && *(void **)field == NULL) {
        return FALSE;
      }

      if (type == PROTOBUF_C_TYPE_MESSAGE) {
        ProtobufCMessage **submessage = *(ProtobufCMessage ***)field;
        unsigned j;
        for (j = 0; j < *quantity; j++) {
          if (!protobuf_c_message_check(submessage[j])) return FALSE;
        }
      } else if (type == PROTOBUF_C_TYPE_STRING) {
        char **string = *(char ***)field;
        unsigned j;
        for (j = 0; j < *quantity; j++) {
          if (!string[j]) return FALSE;
        }
      } else if (type == PROTOBUF_C_TYPE_BYTES) {
        ProtobufCBinaryData *bd = *(ProtobufCBinaryData **)field;
        unsigned j;
        for (j = 0; j < *quantity; j++) {
          if (bd[j].len > 0 && bd[j].data == NULL) return FALSE;
        }
      }

    } else { /* PROTOBUF_C_LABEL_REQUIRED or PROTOBUF_C_LABEL_OPTIONAL */

      if (type == PROTOBUF_C_TYPE_MESSAGE) {
        ProtobufCMessage *submessage = *(ProtobufCMessage **)field;
        if (label == PROTOBUF_C_LABEL_REQUIRED || submessage != NULL) {
          if (!protobuf_c_message_check(submessage)) return FALSE;
        }
      } else if (type == PROTOBUF_C_TYPE_STRING) {
        char *string = *(char **)field;
        if (label == PROTOBUF_C_LABEL_REQUIRED && string == NULL) return FALSE;
      } else if (type == PROTOBUF_C_TYPE_BYTES) {
        protobuf_c_boolean *has =
            STRUCT_MEMBER_P(message, f->quantifier_offset);
        ProtobufCBinaryData *bd = field;
        if (label == PROTOBUF_C_LABEL_REQUIRED || *has == TRUE) {
          if (bd->len > 0 && bd->data == NULL) return FALSE;
        }
      }
    }
  }

  return TRUE;
3095 3096 3097 3098
}

/* === services === */

3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141
typedef void (*GenericHandler)(void *service, const ProtobufCMessage *input,
                               ProtobufCClosure closure, void *closure_data);
void protobuf_c_service_invoke_internal(ProtobufCService *service,
                                        unsigned method_index,
                                        const ProtobufCMessage *input,
                                        ProtobufCClosure closure,
                                        void *closure_data) {
  GenericHandler *handlers;
  GenericHandler handler;

  /*
   * Verify that method_index is within range. If this fails, you are
   * likely invoking a newly added method on an old service. (Although
   * other memory corruption bugs can cause this assertion too.)
   */
  assert(method_index < service->descriptor->n_methods);

  /*
   * Get the array of virtual methods (which are enumerated by the
   * generated code).
   */
  handlers = (GenericHandler *)(service + 1);

  /*
   * Get our method and invoke it.
   * \todo Seems like handler == NULL is a situation that needs handling.
   */
  handler = handlers[method_index];
  (*handler)(service, input, closure, closure_data);
}

void protobuf_c_service_generated_init(
    ProtobufCService *service, const ProtobufCServiceDescriptor *descriptor,
    ProtobufCServiceDestroy destroy) {
  ASSERT_IS_SERVICE_DESCRIPTOR(descriptor);
  service->descriptor = descriptor;
  service->destroy = destroy;
  service->invoke = protobuf_c_service_invoke_internal;
  memset(service + 1, 0, descriptor->n_methods * sizeof(GenericHandler));
}

void protobuf_c_service_destroy(ProtobufCService *service) {
  service->destroy(service);
3142 3143 3144 3145
}

/* --- querying the descriptors --- */

3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
const ProtobufCEnumValue *protobuf_c_enum_descriptor_get_value_by_name(
    const ProtobufCEnumDescriptor *desc, const char *name) {
  unsigned start = 0;
  unsigned count;

  if (desc == NULL || desc->values_by_name == NULL) return NULL;

  count = desc->n_value_names;

  while (count > 1) {
    unsigned mid = start + count / 2;
    int rv = strcmp(desc->values_by_name[mid].name, name);
    if (rv == 0)
      return desc->values + desc->values_by_name[mid].index;
    else if (rv < 0) {
      count = start + count - (mid + 1);
      start = mid + 1;
    } else
      count = mid - start;
  }
  if (count == 0) return NULL;
  if (strcmp(desc->values_by_name[start].name, name) == 0)
    return desc->values + desc->values_by_name[start].index;
  return NULL;
}

const ProtobufCEnumValue *protobuf_c_enum_descriptor_get_value(
    const ProtobufCEnumDescriptor *desc, int value) {
  int rv = int_range_lookup(desc->n_value_ranges, desc->value_ranges, value);
  if (rv < 0) return NULL;
  return desc->values + rv;
}

const ProtobufCFieldDescriptor *protobuf_c_message_descriptor_get_field_by_name(
    const ProtobufCMessageDescriptor *desc, const char *name) {
  unsigned start = 0;
  unsigned count;
  const ProtobufCFieldDescriptor *field;

  if (desc == NULL || desc->fields_sorted_by_name == NULL) return NULL;

  count = desc->n_fields;

  while (count > 1) {
    unsigned mid = start + count / 2;
    int rv;
    field = desc->fields + desc->fields_sorted_by_name[mid];
    rv = strcmp(field->name, name);
    if (rv == 0)
      return field;
    else if (rv < 0) {
      count = start + count - (mid + 1);
      start = mid + 1;
    } else
      count = mid - start;
  }
  if (count == 0) return NULL;
  field = desc->fields + desc->fields_sorted_by_name[start];
  if (strcmp(field->name, name) == 0) return field;
  return NULL;
}

const ProtobufCFieldDescriptor *protobuf_c_message_descriptor_get_field(
    const ProtobufCMessageDescriptor *desc, unsigned value) {
  int rv = int_range_lookup(desc->n_field_ranges, desc->field_ranges, value);
  if (rv < 0) return NULL;
  return desc->fields + rv;
3213 3214 3215
}

const ProtobufCMethodDescriptor *
3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243
protobuf_c_service_descriptor_get_method_by_name(
    const ProtobufCServiceDescriptor *desc, const char *name) {
  unsigned start = 0;
  unsigned count;

  if (desc == NULL || desc->method_indices_by_name == NULL) return NULL;

  count = desc->n_methods;

  while (count > 1) {
    unsigned mid = start + count / 2;
    unsigned mid_index = desc->method_indices_by_name[mid];
    const char *mid_name = desc->methods[mid_index].name;
    int rv = strcmp(mid_name, name);

    if (rv == 0) return desc->methods + desc->method_indices_by_name[mid];
    if (rv < 0) {
      count = start + count - (mid + 1);
      start = mid + 1;
    } else {
      count = mid - start;
    }
  }
  if (count == 0) return NULL;
  if (strcmp(desc->methods[desc->method_indices_by_name[start]].name, name) ==
      0)
    return desc->methods + desc->method_indices_by_name[start];
  return NULL;
3244
}