protobuf-c.c 73.1 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
/*
 * 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
43 44
 * even on 64-bit platforms (uint64_size, PaddleMobile__Framework__uint64_pack,
 * PaddleMobile__Framework__parse_uint64).
45 46 47 48
 *
 * \todo Use size_t consistently.
 */

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

#include "protobuf-c.h"

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

#define PROTOBUF_C__ASSERT_NOT_REACHED() assert(0)

/* Workaround for Microsoft compilers. */
#ifdef _MSC_VER
61
#define inline __inline
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
#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. */
82
#define MAX_UINT64_ENCODED_SIZE 10
83 84

#ifndef PROTOBUF_C_UNPACK_ERROR
85
#define PROTOBUF_C_UNPACK_ERROR(...)
86 87
#endif

88
const char PaddleMobile__Framework__protobuf_c_empty_string[] = "";
89 90

/**
91
 * Internal `PaddleMobile__Framework__ProtobufCMessage` manipulation macro.
92
 *
93 94
 * Base macro for manipulating a `PaddleMobile__Framework__ProtobufCMessage`.
 * Used by STRUCT_MEMBER() and STRUCT_MEMBER_PTR().
95 96
 */
#define STRUCT_MEMBER_P(struct_p, struct_offset) \
97
  ((void *)((uint8_t *)(struct_p) + (struct_offset)))
98 99

/**
100 101
 * Return field in a `PaddleMobile__Framework__ProtobufCMessage` based on
 * offset.
102
 *
103 104
 * Take a pointer to a `PaddleMobile__Framework__ProtobufCMessage` and find the
 * field at the offset. Cast it to the passed type.
105 106
 */
#define STRUCT_MEMBER(member_type, struct_p, struct_offset) \
107
  (*(member_type *)STRUCT_MEMBER_P((struct_p), (struct_offset)))
108 109

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

/* Assertions for magic numbers. */

#define ASSERT_IS_ENUM_DESCRIPTOR(desc) \
122
  assert((desc)->magic == PROTOBUF_C__ENUM_DESCRIPTOR_MAGIC)
123 124

#define ASSERT_IS_MESSAGE_DESCRIPTOR(desc) \
125
  assert((desc)->magic == PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC)
126 127

#define ASSERT_IS_MESSAGE(message) \
128
  ASSERT_IS_MESSAGE_DESCRIPTOR((message)->descriptor)
129 130

#define ASSERT_IS_SERVICE_DESCRIPTOR(desc) \
131
  assert((desc)->magic == PROTOBUF_C__SERVICE_DESCRIPTOR_MAGIC)
132 133 134 135 136

/**@}*/

/* --- version --- */

137 138 139
const char *PaddleMobile__Framework__protobuf_c_version(void) {
  return PROTOBUF_C_VERSION;
}
140

141 142 143
uint32_t PaddleMobile__Framework__protobuf_c_version_number(void) {
  return PROTOBUF_C_VERSION_NUMBER;
}
144 145 146

/* --- allocator --- */

147 148
static void *PaddleMobile__Framework__system_alloc(void *allocator_data,
                                                   size_t size) {
149
  return malloc(size);
150 151
}

152 153 154 155
static void PaddleMobile__Framework__system_free(void *allocator_data,
                                                 void *data) {
  free(data);
}
156

157 158
static inline void *PaddleMobile__Framework__do_alloc(
    PaddleMobile__Framework__ProtobufCAllocator *allocator, size_t size) {
159
  return allocator->alloc(allocator->allocator_data, size);
160 161
}

162 163
static inline void PaddleMobile__Framework__do_free(
    PaddleMobile__Framework__ProtobufCAllocator *allocator, void *data) {
164
  if (data != NULL) allocator->free(allocator->allocator_data, data);
165 166 167 168
}

/*
 * This allocator uses the system's malloc() and free(). It is the default
169 170
 * allocator used if NULL is passed as the
 * PaddleMobile__Framework__ProtobufCAllocator to an exported function.
171
 */
172 173 174
static PaddleMobile__Framework__ProtobufCAllocator protobuf_c__allocator = {
    .alloc = &PaddleMobile__Framework__system_alloc,
    .free = &PaddleMobile__Framework__system_free,
175
    .allocator_data = NULL,
176 177 178 179
};

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

180 181 182 183 184
void PaddleMobile__Framework__protobuf_c_buffer_simple_append(
    PaddleMobile__Framework__ProtobufCBuffer *buffer, size_t len,
    const uint8_t *data) {
  PaddleMobile__Framework__ProtobufCBufferSimple *simp =
      (PaddleMobile__Framework__ProtobufCBufferSimple *)buffer;
185 186 187
  size_t new_len = simp->len + len;

  if (new_len > simp->alloced) {
188
    PaddleMobile__Framework__ProtobufCAllocator *allocator = simp->allocator;
189 190 191 192 193
    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;
194
    new_data = PaddleMobile__Framework__do_alloc(allocator, new_alloced);
195 196 197
    if (!new_data) return;
    memcpy(new_data, simp->data, simp->len);
    if (simp->must_free_data)
198
      PaddleMobile__Framework__do_free(allocator, simp->data);
199 200 201 202 203 204 205
    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;
206 207 208
}

/**
209 210
 * \defgroup packedsz
 * PaddleMobile__Framework__protobuf_c_message_get_packed_size() implementation
211
 *
212 213
 * Routines mainly used by
 * PaddleMobile__Framework__protobuf_c_message_get_packed_size().
214 215 216 217 218 219 220 221 222 223 224 225 226 227
 *
 * \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.
 */
228 229 230 231 232 233 234 235 236 237 238 239
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;
  }
240 241 242 243 244 245 246 247 248 249 250
}

/**
 * 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.
 */
251 252 253 254 255 256 257 258 259 260 261 262
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;
  }
263 264 265 266 267 268 269 270 271 272 273
}

/**
 * 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.
 */
274 275 276 277 278 279 280 281 282 283 284 285 286 287
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;
  }
288 289 290 291 292 293 294 295 296 297 298
}

/**
 * Return the ZigZag-encoded 32-bit unsigned integer form of a 32-bit signed
 * integer.
 *
 * \param v
 *      Value to encode.
 * \return
 *      ZigZag encoded integer.
 */
299 300 301 302 303
static inline uint32_t zigzag32(int32_t v) {
  if (v < 0)
    return (-(uint32_t)v) * 2 - 1;
  else
    return (uint32_t)(v)*2;
304 305 306 307 308 309 310 311 312 313 314 315
}

/**
 * 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.
 */
316
static inline size_t sint32_size(int32_t v) { return uint32_size(zigzag32(v)); }
317 318 319 320 321 322 323 324 325 326

/**
 * 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.
 */
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
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;
  }
345 346 347 348 349 350 351 352 353 354 355
}

/**
 * Return the ZigZag-encoded 64-bit unsigned integer form of a 64-bit signed
 * integer.
 *
 * \param v
 *      Value to encode.
 * \return
 *      ZigZag encoded integer.
 */
356 357 358 359 360
static inline uint64_t zigzag64(int64_t v) {
  if (v < 0)
    return (-(uint64_t)v) * 2 - 1;
  else
    return (uint64_t)(v)*2;
361 362 363 364 365 366 367 368 369 370 371 372
}

/**
 * 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.
 */
373
static inline size_t sint64_size(int64_t v) { return uint64_size(zigzag64(v)); }
374 375 376 377 378 379 380 381 382 383 384 385

/**
 * 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.
 */
386 387 388
static size_t PaddleMobile__Framework__required_field_get_packed_size(
    const PaddleMobile__Framework__ProtobufCFieldDescriptor *field,
    const void *member) {
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 415 416 417 418 419 420 421
  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: {
422 423
      size_t len =
          ((const PaddleMobile__Framework__ProtobufCBinaryData *)member)->len;
424 425 426
      return rv + uint32_size(len) + len;
    }
    case PROTOBUF_C_TYPE_MESSAGE: {
427 428 429 430 431
      const PaddleMobile__Framework__ProtobufCMessage *msg =
          *(PaddleMobile__Framework__ProtobufCMessage *const *)member;
      size_t subrv =
          msg ? PaddleMobile__Framework__protobuf_c_message_get_packed_size(msg)
              : 0;
432 433 434 435 436
      return rv + uint32_size(subrv) + subrv;
    }
  }
  PROTOBUF_C__ASSERT_NOT_REACHED();
  return 0;
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
}

/**
 * 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.
 */
453 454 455
static size_t PaddleMobile__Framework__oneof_field_get_packed_size(
    const PaddleMobile__Framework__ProtobufCFieldDescriptor *field,
    uint32_t oneof_case, const void *member) {
456 457 458 459 460 461 462 463
  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;
  }
464
  return PaddleMobile__Framework__required_field_get_packed_size(field, member);
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
}

/**
 * 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.
 */
481 482 483
static size_t PaddleMobile__Framework__optional_field_get_packed_size(
    const PaddleMobile__Framework__ProtobufCFieldDescriptor *field,
    const protobuf_c_boolean has, const void *member) {
484 485 486 487 488 489 490
  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;
  }
491
  return PaddleMobile__Framework__required_field_get_packed_size(field, member);
492 493
}

494 495 496
static protobuf_c_boolean PaddleMobile__Framework__field_is_zeroish(
    const PaddleMobile__Framework__ProtobufCFieldDescriptor *field,
    const void *member) {
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
  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;
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
}

/**
 * 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.
 */
553 554 555 556 557
static size_t PaddleMobile__Framework__unlabeled_field_get_packed_size(
    const PaddleMobile__Framework__ProtobufCFieldDescriptor *field,
    const void *member) {
  if (PaddleMobile__Framework__field_is_zeroish(field, member)) return 0;
  return PaddleMobile__Framework__required_field_get_packed_size(field, member);
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
}

/**
 * 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.
 */
574 575 576
static size_t PaddleMobile__Framework__repeated_field_get_packed_size(
    const PaddleMobile__Framework__ProtobufCFieldDescriptor *field,
    size_t count, const void *member) {
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 616 617 618 619 620 621 622 623 624
  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++) {
625 626
        size_t len =
            ((PaddleMobile__Framework__ProtobufCBinaryData *)array)[i].len;
627 628 629 630 631 632
        rv += uint32_size(len) + len;
      }
      break;
    case PROTOBUF_C_TYPE_MESSAGE:
      for (i = 0; i < count; i++) {
        size_t len =
633 634
            PaddleMobile__Framework__protobuf_c_message_get_packed_size(
                ((PaddleMobile__Framework__ProtobufCMessage **)array)[i]);
635 636 637 638 639 640 641 642
        rv += uint32_size(len) + len;
      }
      break;
  }

  if (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED))
    header_size += uint32_size(rv);
  return header_size + rv;
643 644 645 646 647 648 649 650 651 652 653 654
}

/**
 * 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.
 */
655 656
static inline size_t PaddleMobile__Framework__unknown_field_get_packed_size(
    const PaddleMobile__Framework__ProtobufCMessageUnknownField *field) {
657
  return get_tag_size(field->tag) + field->len;
658 659 660 661 662 663 664
}

/**@}*/

/*
 * Calculate the serialized size of the message.
 */
665 666
size_t PaddleMobile__Framework__protobuf_c_message_get_packed_size(
    const PaddleMobile__Framework__ProtobufCMessage *message) {
667 668 669 670 671
  unsigned i;
  size_t rv = 0;

  ASSERT_IS_MESSAGE(message);
  for (i = 0; i < message->descriptor->n_fields; i++) {
672 673
    const PaddleMobile__Framework__ProtobufCFieldDescriptor *field =
        message->descriptor->fields + i;
674 675 676 677
    const void *member = ((const char *)message) + field->offset;
    const void *qmember = ((const char *)message) + field->quantifier_offset;

    if (field->label == PROTOBUF_C_LABEL_REQUIRED) {
678 679
      rv += PaddleMobile__Framework__required_field_get_packed_size(field,
                                                                    member);
680 681 682
    } else if ((field->label == PROTOBUF_C_LABEL_OPTIONAL ||
                field->label == PROTOBUF_C_LABEL_NONE) &&
               (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF))) {
683 684
      rv += PaddleMobile__Framework__oneof_field_get_packed_size(
          field, *(const uint32_t *)qmember, member);
685
    } else if (field->label == PROTOBUF_C_LABEL_OPTIONAL) {
686
      rv += PaddleMobile__Framework__optional_field_get_packed_size(
687 688
          field, *(protobuf_c_boolean *)qmember, member);
    } else if (field->label == PROTOBUF_C_LABEL_NONE) {
689 690
      rv += PaddleMobile__Framework__unlabeled_field_get_packed_size(field,
                                                                     member);
691
    } else {
692 693
      rv += PaddleMobile__Framework__repeated_field_get_packed_size(
          field, *(const size_t *)qmember, member);
694 695 696
    }
  }
  for (i = 0; i < message->n_unknown_fields; i++)
697 698
    rv += PaddleMobile__Framework__unknown_field_get_packed_size(
        &message->unknown_fields[i]);
699
  return rv;
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
}

/**
 * \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`.
 */
722 723
static inline size_t PaddleMobile__Framework__uint32_pack(uint32_t value,
                                                          uint8_t *out) {
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
  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;
745 746 747
}

/**
H
hjchen2 已提交
748 749
 * Pack a 64-bit unsigned integer using base-128 varint encoding and return the
 * number of bytes written.
750
 *
H
hjchen2 已提交
751 752 753 754
 * \param value
 *      Value to encode.
 * \param[out] out
 *      Packed value.
755
 * \return
H
hjchen2 已提交
756
 *      Number of bytes written to `out`.
757
 */
758 759
static size_t PaddleMobile__Framework__uint64_pack(uint64_t value,
                                                   uint8_t *out) {
H
hjchen2 已提交
760 761 762 763
  uint32_t hi = (uint32_t)(value >> 32);
  uint32_t lo = (uint32_t)value;
  unsigned rv;

764
  if (hi == 0) return PaddleMobile__Framework__uint32_pack((uint32_t)lo, out);
H
hjchen2 已提交
765 766 767 768 769 770 771
  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;
772
  } else {
H
hjchen2 已提交
773 774
    out[4] = ((hi & 7) << 4) | (lo >> 28) | 0x80;
    hi >>= 3;
775
  }
H
hjchen2 已提交
776 777 778 779 780 781 782
  rv = 5;
  while (hi >= 128) {
    out[rv++] = hi | 0x80;
    hi >>= 7;
  }
  out[rv++] = hi;
  return rv;
783 784 785
}

/**
786 787
 * Pack a PaddleMobile__Framework__ProtobufCBinaryData and return the number of
 * bytes written. The output includes a length delimiter.
788
 *
H
hjchen2 已提交
789
 * \param bd
790
 *      PaddleMobile__Framework__ProtobufCBinaryData to encode.
H
hjchen2 已提交
791 792
 * \param[out] out
 *      Packed value.
793
 * \return
H
hjchen2 已提交
794
 *      Number of bytes written to `out`.
795
 */
796 797
static inline size_t PaddleMobile__Framework__binary_data_pack(
    const PaddleMobile__Framework__ProtobufCBinaryData *bd, uint8_t *out) {
H
hjchen2 已提交
798
  size_t len = bd->len;
799
  size_t rv = PaddleMobile__Framework__uint32_pack(len, out);
H
hjchen2 已提交
800 801
  memcpy(out + rv, bd->data, len);
  return rv + len;
802 803 804
}

/**
H
hjchen2 已提交
805
 * Pack a field tag.
806
 *
H
hjchen2 已提交
807 808
 * Wire-type will be added in required_field_pack().
 *
809
 * \todo Just call PaddleMobile__Framework__uint64_pack on 64-bit platforms.
H
hjchen2 已提交
810 811 812 813 814
 *
 * \param id
 *      Tag value to encode.
 * \param[out] out
 *      Packed value.
815
 * \return
H
hjchen2 已提交
816
 *      Number of bytes written to `out`.
817
 */
818
static size_t PaddleMobile__Framework__tag_pack(uint32_t id, uint8_t *out) {
H
hjchen2 已提交
819
  if (id < (1UL << (32 - 3)))
820
    return PaddleMobile__Framework__uint32_pack(id << 3, out);
H
hjchen2 已提交
821
  else
822
    return PaddleMobile__Framework__uint64_pack(((uint64_t)id) << 3, out);
823 824 825
}

/**
H
hjchen2 已提交
826
 * Given a field type, return the in-memory size.
827
 *
H
hjchen2 已提交
828 829 830 831
 * \todo Implement as a table lookup.
 *
 * \param type
 *      Field type.
832
 * \return
H
hjchen2 已提交
833
 *      Size of the field.
834
 */
835 836
static inline size_t PaddleMobile__Framework__sizeof_elt_in_repeated_array(
    PaddleMobile__Framework__ProtobufCType type) {
H
hjchen2 已提交
837 838 839 840
  switch (type) {
    case PROTOBUF_C_TYPE_SINT32:
    case PROTOBUF_C_TYPE_INT32:
    case PROTOBUF_C_TYPE_UINT32:
841 842 843 844
    case PROTOBUF_C_TYPE_SFIXED32:
    case PROTOBUF_C_TYPE_FIXED32:
    case PROTOBUF_C_TYPE_FLOAT:
    case PROTOBUF_C_TYPE_ENUM:
H
hjchen2 已提交
845
      return 4;
846 847 848
    case PROTOBUF_C_TYPE_SINT64:
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_UINT64:
H
hjchen2 已提交
849 850 851 852
    case PROTOBUF_C_TYPE_SFIXED64:
    case PROTOBUF_C_TYPE_FIXED64:
    case PROTOBUF_C_TYPE_DOUBLE:
      return 8;
853
    case PROTOBUF_C_TYPE_BOOL:
H
hjchen2 已提交
854 855 856 857 858
      return sizeof(protobuf_c_boolean);
    case PROTOBUF_C_TYPE_STRING:
    case PROTOBUF_C_TYPE_MESSAGE:
      return sizeof(void *);
    case PROTOBUF_C_TYPE_BYTES:
859
      return sizeof(PaddleMobile__Framework__ProtobufCBinaryData);
860
  }
H
hjchen2 已提交
861 862
  PROTOBUF_C__ASSERT_NOT_REACHED();
  return 0;
863 864
}

865 866 867
static inline int PaddleMobile__Framework__int_range_lookup(
    unsigned n_ranges, const PaddleMobile__Framework__ProtobufCIntRange *ranges,
    int value) {
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
  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;
}

900 901 902
static size_t PaddleMobile__Framework__parse_tag_and_wiretype(
    size_t len, const uint8_t *data, uint32_t *tag_out,
    PaddleMobile__Framework__ProtobufCWireType *wiretype_out) {
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
  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 */
924 925 926 927
}

/* sizeof(ScannedMember) must be <= (1UL<<BOUND_SIZEOF_SCANNED_MEMBER_LOG2) */
#define BOUND_SIZEOF_SCANNED_MEMBER_LOG2 5
928
typedef struct PaddleMobile__Framework___ScannedMember ScannedMember;
929
/** Field as it's being read. */
930 931 932 933 934 935 936 937
struct PaddleMobile__Framework___ScannedMember {
  uint32_t tag;              /**< Field tag. */
  uint8_t wire_type;         /**< Field type. */
  uint8_t length_prefix_len; /**< Prefix length. */
  const PaddleMobile__Framework__ProtobufCFieldDescriptor
      *field;          /**< Field descriptor. */
  size_t len;          /**< Field length. */
  const uint8_t *data; /**< Pointer to field data. */
938 939
};

940 941
static inline uint32_t PaddleMobile__Framework__scan_length_prefixed_data(
    size_t len, const uint8_t *data, size_t *prefix_len_out) {
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
  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;
}

966 967
static size_t PaddleMobile__Framework__max_b128_numbers(size_t len,
                                                        const uint8_t *data) {
968 969 970 971
  size_t rv = 0;
  while (len--)
    if ((*data++ & 0x80) == 0) ++rv;
  return rv;
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
}

/**@}*/

/**
 * 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.
 */
990 991 992 993
static protobuf_c_boolean PaddleMobile__Framework__merge_messages(
    PaddleMobile__Framework__ProtobufCMessage *earlier_msg,
    PaddleMobile__Framework__ProtobufCMessage *latter_msg,
    PaddleMobile__Framework__ProtobufCAllocator *allocator) {
994
  unsigned i;
995 996
  const PaddleMobile__Framework__ProtobufCFieldDescriptor *fields =
      latter_msg->descriptor->fields;
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
  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 */
1011 1012 1013
          size_t el_size =
              PaddleMobile__Framework__sizeof_elt_in_repeated_array(
                  fields[i].type);
1014 1015
          uint8_t *new_field;

1016 1017
          new_field = PaddleMobile__Framework__do_alloc(
              allocator, (*n_earlier + *n_latter) * el_size);
1018 1019 1020 1021 1022 1023
          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);

1024 1025
          PaddleMobile__Framework__do_free(allocator, *p_latter);
          PaddleMobile__Framework__do_free(allocator, *p_earlier);
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
          *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) {
1039
      const PaddleMobile__Framework__ProtobufCFieldDescriptor *field;
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
      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 */
1052
          int field_index = PaddleMobile__Framework__int_range_lookup(
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
              latter_msg->descriptor->n_field_ranges,
              latter_msg->descriptor->field_ranges, *earlier_case_p);
          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: {
1070 1071 1072 1073
          PaddleMobile__Framework__ProtobufCMessage *em =
              *(PaddleMobile__Framework__ProtobufCMessage **)earlier_elem;
          PaddleMobile__Framework__ProtobufCMessage *lm =
              *(PaddleMobile__Framework__ProtobufCMessage **)latter_elem;
1074 1075
          if (em != NULL) {
            if (lm != NULL) {
1076 1077
              if (!PaddleMobile__Framework__merge_messages(em, lm, allocator))
                return FALSE;
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
              /* Already merged */
              need_to_merge = FALSE;
            } else {
              /* Zero copy the message */
              need_to_merge = TRUE;
            }
          }
          break;
        }
        case PROTOBUF_C_TYPE_BYTES: {
1088 1089 1090 1091 1092 1093 1094 1095
          uint8_t *e_data =
              ((PaddleMobile__Framework__ProtobufCBinaryData *)earlier_elem)
                  ->data;
          uint8_t *l_data =
              ((PaddleMobile__Framework__ProtobufCBinaryData *)latter_elem)
                  ->data;
          const PaddleMobile__Framework__ProtobufCBinaryData *d_bd =
              (PaddleMobile__Framework__ProtobufCBinaryData *)def_val;
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119

          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) {
1120 1121
        size_t el_size =
            PaddleMobile__Framework__sizeof_elt_in_repeated_array(field->type);
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
        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;
1142 1143 1144 1145 1146 1147 1148 1149
}

/**
 * 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
1150
 * PaddleMobile__Framework__parse_packed_repeated_member().
1151
 */
1152 1153 1154
static protobuf_c_boolean PaddleMobile__Framework__count_packed_elements(
    PaddleMobile__Framework__ProtobufCType type, size_t len,
    const uint8_t *data, size_t *count_out) {
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
  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:
1183
      *count_out = PaddleMobile__Framework__max_b128_numbers(len, data);
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
      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;
  }
}

1198 1199
static inline uint32_t PaddleMobile__Framework__parse_uint32(
    unsigned len, const uint8_t *data) {
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
  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;
}

1214 1215 1216
static inline uint32_t PaddleMobile__Framework__parse_int32(
    unsigned len, const uint8_t *data) {
  return PaddleMobile__Framework__parse_uint32(len, data);
1217 1218 1219 1220 1221 1222 1223 1224 1225
}

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

1226 1227
static inline uint32_t PaddleMobile__Framework__parse_fixed_uint32(
    const uint8_t *data) {
1228
#if !defined(WORDS_BIGENDIAN)
1229 1230 1231
  uint32_t t;
  memcpy(&t, data, 4);
  return t;
1232
#else
1233 1234
  return data[0] | ((uint32_t)(data[1]) << 8) | ((uint32_t)(data[2]) << 16) |
         ((uint32_t)(data[3]) << 24);
1235 1236 1237
#endif
}

1238 1239
static uint64_t PaddleMobile__Framework__parse_uint64(unsigned len,
                                                      const uint8_t *data) {
1240 1241 1242
  unsigned shift, i;
  uint64_t rv;

1243
  if (len < 5) return PaddleMobile__Framework__parse_uint32(len, data);
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
  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;
}

1254
static inline int64_t PaddleMobile__Framework__unzigzag64(uint64_t v) {
1255 1256 1257 1258 1259 1260
  if (v & 1)
    return -(v >> 1) - 1;
  else
    return v >> 1;
}

1261 1262
static inline uint64_t PaddleMobile__Framework__parse_fixed_uint64(
    const uint8_t *data) {
1263
#if !defined(WORDS_BIGENDIAN)
1264 1265 1266
  uint64_t t;
  memcpy(&t, data, 8);
  return t;
1267
#else
1268 1269 1270
  return (uint64_t)PaddleMobile__Framework__parse_fixed_uint32(data) |
         (((uint64_t)PaddleMobile__Framework__parse_fixed_uint32(data + 4))
          << 32);
1271 1272 1273
#endif
}

1274 1275
static protobuf_c_boolean PaddleMobile__Framework__parse_boolean(
    unsigned len, const uint8_t *data) {
1276 1277 1278 1279 1280 1281
  unsigned i;
  for (i = 0; i < len; i++)
    if (data[i] & 0x7f) return TRUE;
  return FALSE;
}

1282 1283 1284
static protobuf_c_boolean PaddleMobile__Framework__parse_required_member(
    ScannedMember *scanned_member, void *member,
    PaddleMobile__Framework__ProtobufCAllocator *allocator,
1285 1286 1287
    protobuf_c_boolean maybe_clear) {
  unsigned len = scanned_member->len;
  const uint8_t *data = scanned_member->data;
1288 1289
  PaddleMobile__Framework__ProtobufCWireType wire_type =
      scanned_member->wire_type;
1290 1291 1292 1293 1294

  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;
1295
      *(int32_t *)member = PaddleMobile__Framework__parse_int32(len, data);
1296 1297 1298
      return TRUE;
    case PROTOBUF_C_TYPE_UINT32:
      if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return FALSE;
1299
      *(uint32_t *)member = PaddleMobile__Framework__parse_uint32(len, data);
1300 1301 1302
      return TRUE;
    case PROTOBUF_C_TYPE_SINT32:
      if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return FALSE;
1303 1304
      *(int32_t *)member =
          unzigzag32(PaddleMobile__Framework__parse_uint32(len, data));
1305 1306 1307 1308 1309
      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;
1310
      *(uint32_t *)member = PaddleMobile__Framework__parse_fixed_uint32(data);
1311 1312 1313 1314
      return TRUE;
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_UINT64:
      if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return FALSE;
1315
      *(uint64_t *)member = PaddleMobile__Framework__parse_uint64(len, data);
1316 1317 1318
      return TRUE;
    case PROTOBUF_C_TYPE_SINT64:
      if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return FALSE;
1319 1320
      *(int64_t *)member = PaddleMobile__Framework__unzigzag64(
          PaddleMobile__Framework__parse_uint64(len, data));
1321 1322 1323 1324 1325
      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;
1326
      *(uint64_t *)member = PaddleMobile__Framework__parse_fixed_uint64(data);
1327 1328
      return TRUE;
    case PROTOBUF_C_TYPE_BOOL:
1329 1330
      *(protobuf_c_boolean *)member =
          PaddleMobile__Framework__parse_boolean(len, data);
1331 1332 1333 1334 1335 1336 1337 1338 1339
      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;
1340 1341
        if (*pstr != NULL && *pstr != def)
          PaddleMobile__Framework__do_free(allocator, *pstr);
1342
      }
1343
      *pstr = PaddleMobile__Framework__do_alloc(allocator, len - pref_len + 1);
1344 1345 1346 1347 1348 1349
      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: {
1350 1351
      PaddleMobile__Framework__ProtobufCBinaryData *bd = member;
      const PaddleMobile__Framework__ProtobufCBinaryData *def_bd;
1352 1353 1354 1355 1356 1357 1358
      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)) {
1359
        PaddleMobile__Framework__do_free(allocator, bd->data);
1360 1361
      }
      if (len - pref_len > 0) {
1362
        bd->data = PaddleMobile__Framework__do_alloc(allocator, len - pref_len);
1363 1364 1365 1366 1367 1368 1369 1370 1371
        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: {
1372 1373 1374
      PaddleMobile__Framework__ProtobufCMessage **pmessage = member;
      PaddleMobile__Framework__ProtobufCMessage *subm;
      const PaddleMobile__Framework__ProtobufCMessage *def_mess;
1375 1376 1377 1378 1379 1380
      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;
1381 1382 1383
      subm = PaddleMobile__Framework__protobuf_c_message_unpack(
          scanned_member->field->descriptor, allocator, len - pref_len,
          data + pref_len);
1384 1385 1386

      if (maybe_clear && *pmessage != NULL && *pmessage != def_mess) {
        if (subm != NULL)
1387 1388
          merge_successful = PaddleMobile__Framework__merge_messages(
              *pmessage, subm, allocator);
1389
        /* Delete the previous message */
1390 1391
        PaddleMobile__Framework__protobuf_c_message_free_unpacked(*pmessage,
                                                                  allocator);
1392 1393 1394 1395 1396 1397 1398 1399 1400
      }
      *pmessage = subm;
      if (subm == NULL || !merge_successful) return FALSE;
      return TRUE;
    }
  }
  return FALSE;
}

1401 1402 1403 1404
static protobuf_c_boolean PaddleMobile__Framework__parse_oneof_member(
    ScannedMember *scanned_member, void *member,
    PaddleMobile__Framework__ProtobufCMessage *message,
    PaddleMobile__Framework__ProtobufCAllocator *allocator) {
1405 1406 1407 1408 1409 1410
  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 */
1411 1412 1413 1414
    int field_index = PaddleMobile__Framework__int_range_lookup(
        message->descriptor->n_field_ranges, message->descriptor->field_ranges,
        *oneof_case);
    const PaddleMobile__Framework__ProtobufCFieldDescriptor *old_field =
1415
        message->descriptor->fields + field_index;
1416 1417
    size_t el_size =
        PaddleMobile__Framework__sizeof_elt_in_repeated_array(old_field->type);
1418 1419 1420 1421 1422

    switch (old_field->type) {
      case PROTOBUF_C_TYPE_STRING: {
        char **pstr = member;
        const char *def = old_field->default_value;
1423 1424
        if (*pstr != NULL && *pstr != def)
          PaddleMobile__Framework__do_free(allocator, *pstr);
1425 1426 1427
        break;
      }
      case PROTOBUF_C_TYPE_BYTES: {
1428 1429 1430
        PaddleMobile__Framework__ProtobufCBinaryData *bd = member;
        const PaddleMobile__Framework__ProtobufCBinaryData *def_bd =
            old_field->default_value;
1431
        if (bd->data != NULL && (def_bd == NULL || bd->data != def_bd->data)) {
1432
          PaddleMobile__Framework__do_free(allocator, bd->data);
1433 1434 1435 1436
        }
        break;
      }
      case PROTOBUF_C_TYPE_MESSAGE: {
1437 1438 1439
        PaddleMobile__Framework__ProtobufCMessage **pmessage = member;
        const PaddleMobile__Framework__ProtobufCMessage *def_mess =
            old_field->default_value;
1440
        if (*pmessage != NULL && *pmessage != def_mess)
1441 1442
          PaddleMobile__Framework__protobuf_c_message_free_unpacked(*pmessage,
                                                                    allocator);
1443 1444 1445 1446 1447 1448 1449 1450
        break;
      }
      default:
        break;
    }

    memset(member, 0, el_size);
  }
1451 1452
  if (!PaddleMobile__Framework__parse_required_member(scanned_member, member,
                                                      allocator, TRUE))
1453 1454 1455 1456 1457 1458
    return FALSE;

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

1459 1460 1461 1462 1463 1464
static protobuf_c_boolean PaddleMobile__Framework__parse_optional_member(
    ScannedMember *scanned_member, void *member,
    PaddleMobile__Framework__ProtobufCMessage *message,
    PaddleMobile__Framework__ProtobufCAllocator *allocator) {
  if (!PaddleMobile__Framework__parse_required_member(scanned_member, member,
                                                      allocator, TRUE))
1465 1466 1467 1468 1469 1470 1471
    return FALSE;
  if (scanned_member->field->quantifier_offset != 0)
    STRUCT_MEMBER(protobuf_c_boolean, message,
                  scanned_member->field->quantifier_offset) = TRUE;
  return TRUE;
}

1472 1473 1474 1475 1476 1477
static protobuf_c_boolean PaddleMobile__Framework__parse_repeated_member(
    ScannedMember *scanned_member, void *member,
    PaddleMobile__Framework__ProtobufCMessage *message,
    PaddleMobile__Framework__ProtobufCAllocator *allocator) {
  const PaddleMobile__Framework__ProtobufCFieldDescriptor *field =
      scanned_member->field;
1478
  size_t *p_n = STRUCT_MEMBER_PTR(size_t, message, field->quantifier_offset);
1479 1480
  size_t siz =
      PaddleMobile__Framework__sizeof_elt_in_repeated_array(field->type);
1481 1482
  char *array = *(char **)member;

1483 1484
  if (!PaddleMobile__Framework__parse_required_member(
          scanned_member, array + siz * (*p_n), allocator, FALSE)) {
1485 1486 1487 1488 1489 1490
    return FALSE;
  }
  *p_n += 1;
  return TRUE;
}

1491 1492
static unsigned PaddleMobile__Framework__scan_varint(unsigned len,
                                                     const uint8_t *data) {
1493 1494 1495 1496 1497 1498 1499 1500
  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;
}

1501 1502 1503 1504 1505
static protobuf_c_boolean PaddleMobile__Framework__parse_packed_repeated_member(
    ScannedMember *scanned_member, void *member,
    PaddleMobile__Framework__ProtobufCMessage *message) {
  const PaddleMobile__Framework__ProtobufCFieldDescriptor *field =
      scanned_member->field;
1506
  size_t *p_n = STRUCT_MEMBER_PTR(size_t, message, field->quantifier_offset);
1507 1508
  size_t siz =
      PaddleMobile__Framework__sizeof_elt_in_repeated_array(field->type);
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
  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;
1520
#if !defined(WORDS_BIGENDIAN)
1521
      goto no_unpacking_needed;
1522
#else
1523
      for (i = 0; i < count; i++) {
1524 1525
        ((uint32_t *)array)[i] =
            PaddleMobile__Framework__parse_fixed_uint32(at);
1526 1527 1528
        at += 4;
      }
      break;
1529
#endif
1530 1531 1532 1533
    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;
1534
#if !defined(WORDS_BIGENDIAN)
1535
      goto no_unpacking_needed;
1536
#else
1537
      for (i = 0; i < count; i++) {
1538 1539
        ((uint64_t *)array)[i] =
            PaddleMobile__Framework__parse_fixed_uint64(at);
1540 1541 1542
        at += 8;
      }
      break;
1543
#endif
1544 1545 1546
    case PROTOBUF_C_TYPE_ENUM:
    case PROTOBUF_C_TYPE_INT32:
      while (rem > 0) {
1547
        unsigned s = PaddleMobile__Framework__scan_varint(rem, at);
1548 1549 1550 1551
        if (s == 0) {
          PROTOBUF_C_UNPACK_ERROR("bad packed-repeated int32 value");
          return FALSE;
        }
1552 1553
        ((int32_t *)array)[count++] =
            PaddleMobile__Framework__parse_int32(s, at);
1554 1555 1556 1557 1558 1559
        at += s;
        rem -= s;
      }
      break;
    case PROTOBUF_C_TYPE_SINT32:
      while (rem > 0) {
1560
        unsigned s = PaddleMobile__Framework__scan_varint(rem, at);
1561 1562 1563 1564
        if (s == 0) {
          PROTOBUF_C_UNPACK_ERROR("bad packed-repeated sint32 value");
          return FALSE;
        }
1565 1566
        ((int32_t *)array)[count++] =
            unzigzag32(PaddleMobile__Framework__parse_uint32(s, at));
1567 1568 1569 1570 1571 1572
        at += s;
        rem -= s;
      }
      break;
    case PROTOBUF_C_TYPE_UINT32:
      while (rem > 0) {
1573
        unsigned s = PaddleMobile__Framework__scan_varint(rem, at);
1574 1575 1576 1577
        if (s == 0) {
          PROTOBUF_C_UNPACK_ERROR("bad packed-repeated enum or uint32 value");
          return FALSE;
        }
1578 1579
        ((uint32_t *)array)[count++] =
            PaddleMobile__Framework__parse_uint32(s, at);
1580 1581 1582 1583 1584 1585 1586
        at += s;
        rem -= s;
      }
      break;

    case PROTOBUF_C_TYPE_SINT64:
      while (rem > 0) {
1587
        unsigned s = PaddleMobile__Framework__scan_varint(rem, at);
1588 1589 1590 1591
        if (s == 0) {
          PROTOBUF_C_UNPACK_ERROR("bad packed-repeated sint64 value");
          return FALSE;
        }
1592 1593
        ((int64_t *)array)[count++] = PaddleMobile__Framework__unzigzag64(
            PaddleMobile__Framework__parse_uint64(s, at));
1594 1595 1596 1597 1598 1599 1600
        at += s;
        rem -= s;
      }
      break;
    case PROTOBUF_C_TYPE_INT64:
    case PROTOBUF_C_TYPE_UINT64:
      while (rem > 0) {
1601
        unsigned s = PaddleMobile__Framework__scan_varint(rem, at);
1602 1603 1604 1605
        if (s == 0) {
          PROTOBUF_C_UNPACK_ERROR("bad packed-repeated int64/uint64 value");
          return FALSE;
        }
1606 1607
        ((int64_t *)array)[count++] =
            PaddleMobile__Framework__parse_uint64(s, at);
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
        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;
1627 1628 1629

#if !defined(WORDS_BIGENDIAN)
no_unpacking_needed:
1630 1631 1632
  memcpy(array, at, count * siz);
  *p_n += count;
  return TRUE;
1633 1634 1635
#endif
}

1636 1637
static protobuf_c_boolean PaddleMobile__Framework__is_packable_type(
    PaddleMobile__Framework__ProtobufCType type) {
1638 1639 1640 1641
  return type != PROTOBUF_C_TYPE_STRING && type != PROTOBUF_C_TYPE_BYTES &&
         type != PROTOBUF_C_TYPE_MESSAGE;
}

1642 1643 1644 1645 1646 1647
static protobuf_c_boolean PaddleMobile__Framework__parse_member(
    ScannedMember *scanned_member,
    PaddleMobile__Framework__ProtobufCMessage *message,
    PaddleMobile__Framework__ProtobufCAllocator *allocator) {
  const PaddleMobile__Framework__ProtobufCFieldDescriptor *field =
      scanned_member->field;
1648 1649 1650
  void *member;

  if (field == NULL) {
1651
    PaddleMobile__Framework__ProtobufCMessageUnknownField *ufield =
1652 1653 1654 1655
        message->unknown_fields + (message->n_unknown_fields++);
    ufield->tag = scanned_member->tag;
    ufield->wire_type = scanned_member->wire_type;
    ufield->len = scanned_member->len;
1656 1657
    ufield->data =
        PaddleMobile__Framework__do_alloc(allocator, scanned_member->len);
1658 1659 1660 1661 1662 1663 1664
    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:
1665 1666
      return PaddleMobile__Framework__parse_required_member(
          scanned_member, member, allocator, TRUE);
1667 1668 1669
    case PROTOBUF_C_LABEL_OPTIONAL:
    case PROTOBUF_C_LABEL_NONE:
      if (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_ONEOF)) {
1670 1671
        return PaddleMobile__Framework__parse_oneof_member(
            scanned_member, member, message, allocator);
1672
      } else {
1673 1674
        return PaddleMobile__Framework__parse_optional_member(
            scanned_member, member, message, allocator);
1675 1676 1677 1678
      }
    case PROTOBUF_C_LABEL_REPEATED:
      if (scanned_member->wire_type == PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED &&
          (0 != (field->flags & PROTOBUF_C_FIELD_FLAG_PACKED) ||
1679 1680 1681
           PaddleMobile__Framework__is_packable_type(field->type))) {
        return PaddleMobile__Framework__parse_packed_repeated_member(
            scanned_member, member, message);
1682
      } else {
1683 1684
        return PaddleMobile__Framework__parse_repeated_member(
            scanned_member, member, message, allocator);
1685 1686 1687 1688
      }
  }
  PROTOBUF_C__ASSERT_NOT_REACHED();
  return 0;
1689 1690 1691 1692 1693 1694 1695 1696 1697
}

/**
 * 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).
 */
1698 1699 1700
static void PaddleMobile__Framework__message_init_generic(
    const PaddleMobile__Framework__ProtobufCMessageDescriptor *desc,
    PaddleMobile__Framework__ProtobufCMessage *message) {
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 1732
  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:
1733 1734
          memcpy(field, dv,
                 sizeof(PaddleMobile__Framework__ProtobufCBinaryData));
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
          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;
      }
    }
  }
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
}

/**@}*/

/*
 * 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.
 */
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
#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)))

1778 1779 1780 1781 1782 1783
PaddleMobile__Framework__ProtobufCMessage *
PaddleMobile__Framework__protobuf_c_message_unpack(
    const PaddleMobile__Framework__ProtobufCMessageDescriptor *desc,
    PaddleMobile__Framework__ProtobufCAllocator *allocator, size_t len,
    const uint8_t *data) {
  PaddleMobile__Framework__ProtobufCMessage *rv;
1784 1785
  size_t rem = len;
  const uint8_t *at = data;
1786 1787
  const PaddleMobile__Framework__ProtobufCFieldDescriptor *last_field =
      desc->fields + 0;
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
  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;

1813
  rv = PaddleMobile__Framework__do_alloc(allocator, desc->sizeof_message);
1814 1815 1816 1817 1818
  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)) {
1819 1820
    required_fields_bitmap = PaddleMobile__Framework__do_alloc(
        allocator, required_fields_bitmap_len);
1821
    if (!required_fields_bitmap) {
1822
      PaddleMobile__Framework__do_free(allocator, rv);
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
      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)
1836
    PaddleMobile__Framework__protobuf_c_message_init(desc, rv);
1837
  else
1838
    PaddleMobile__Framework__message_init_generic(desc, rv);
1839 1840 1841

  while (rem > 0) {
    uint32_t tag;
1842 1843 1844 1845
    PaddleMobile__Framework__ProtobufCWireType wire_type;
    size_t used = PaddleMobile__Framework__parse_tag_and_wiretype(rem, at, &tag,
                                                                  &wire_type);
    const PaddleMobile__Framework__ProtobufCFieldDescriptor *field;
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
    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 */
1859 1860
      int field_index = PaddleMobile__Framework__int_range_lookup(
          desc->n_field_ranges, desc->field_ranges, tag);
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 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
      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;

1910 1911
        tmp.len = PaddleMobile__Framework__scan_length_prefixed_data(rem, at,
                                                                     &pref_len);
1912
        if (tmp.len == 0) {
1913 1914
          /* NOTE: PaddleMobile__Framework__scan_length_prefixed_data calls
           * UNPACK_ERROR */
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
          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);
1946 1947
      scanned_member_slabs[which_slab] =
          PaddleMobile__Framework__do_alloc(allocator, size);
1948 1949 1950 1951 1952 1953 1954 1955 1956
      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) ||
1957
           PaddleMobile__Framework__is_packable_type(field->type))) {
1958
        size_t count;
1959 1960 1961
        if (!PaddleMobile__Framework__count_packed_elements(
                field->type, tmp.len - tmp.length_prefix_len,
                tmp.data + tmp.length_prefix_len, &count)) {
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
          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++) {
1978 1979
    const PaddleMobile__Framework__ProtobufCFieldDescriptor *field =
        desc->fields + f;
1980
    if (field->label == PROTOBUF_C_LABEL_REPEATED) {
1981 1982
      size_t siz =
          PaddleMobile__Framework__sizeof_elt_in_repeated_array(field->type);
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
      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; \
  }
1995
        a = PaddleMobile__Framework__do_alloc(allocator, siz * n);
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
        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;
      }
    }
  }
2011 2012
#undef CLEAR_REMAINING_N_PTRS

2013 2014
  /* allocate space for unknown fields */
  if (n_unknown) {
2015 2016 2017 2018
    rv->unknown_fields = PaddleMobile__Framework__do_alloc(
        allocator,
        n_unknown *
            sizeof(PaddleMobile__Framework__ProtobufCMessageUnknownField));
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
    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++) {
2029
      if (!PaddleMobile__Framework__parse_member(slab + j, rv, allocator)) {
2030 2031 2032 2033 2034 2035 2036 2037 2038
        PROTOBUF_C_UNPACK_ERROR(
            "error parsing member %s of %s",
            slab->field ? slab->field->name : "*unknown-field*", desc->name);
        goto error_cleanup;
      }
    }
  }

  /* cleanup */
2039 2040
  for (j = 1; j <= which_slab; j++)
    PaddleMobile__Framework__do_free(allocator, scanned_member_slabs[j]);
2041
  if (required_fields_bitmap_alloced)
2042
    PaddleMobile__Framework__do_free(allocator, required_fields_bitmap);
2043
  return rv;
2044 2045

error_cleanup:
2046 2047 2048
  PaddleMobile__Framework__protobuf_c_message_free_unpacked(rv, allocator);
  for (j = 1; j <= which_slab; j++)
    PaddleMobile__Framework__do_free(allocator, scanned_member_slabs[j]);
2049
  if (required_fields_bitmap_alloced)
2050
    PaddleMobile__Framework__do_free(allocator, required_fields_bitmap);
2051
  return NULL;
2052 2053

error_cleanup_during_scan:
2054 2055 2056
  PaddleMobile__Framework__do_free(allocator, rv);
  for (j = 1; j <= which_slab; j++)
    PaddleMobile__Framework__do_free(allocator, scanned_member_slabs[j]);
2057
  if (required_fields_bitmap_alloced)
2058
    PaddleMobile__Framework__do_free(allocator, required_fields_bitmap);
2059 2060 2061
  return NULL;
}

2062 2063 2064 2065
void PaddleMobile__Framework__protobuf_c_message_free_unpacked(
    PaddleMobile__Framework__ProtobufCMessage *message,
    PaddleMobile__Framework__ProtobufCAllocator *allocator) {
  const PaddleMobile__Framework__ProtobufCMessageDescriptor *desc;
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 2092
  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;
2093 2094
          for (i = 0; i < n; i++)
            PaddleMobile__Framework__do_free(allocator, ((char **)arr)[i]);
2095 2096 2097
        } else if (desc->fields[f].type == PROTOBUF_C_TYPE_BYTES) {
          unsigned i;
          for (i = 0; i < n; i++)
2098 2099 2100
            PaddleMobile__Framework__do_free(
                allocator,
                ((PaddleMobile__Framework__ProtobufCBinaryData *)arr)[i].data);
2101 2102 2103
        } else if (desc->fields[f].type == PROTOBUF_C_TYPE_MESSAGE) {
          unsigned i;
          for (i = 0; i < n; i++)
2104 2105 2106
            PaddleMobile__Framework__protobuf_c_message_free_unpacked(
                ((PaddleMobile__Framework__ProtobufCMessage **)arr)[i],
                allocator);
2107
        }
2108
        PaddleMobile__Framework__do_free(allocator, arr);
2109 2110 2111 2112
      }
    } else if (desc->fields[f].type == PROTOBUF_C_TYPE_STRING) {
      char *str = STRUCT_MEMBER(char *, message, desc->fields[f].offset);

2113 2114
      if (str && str != desc->fields[f].default_value)
        PaddleMobile__Framework__do_free(allocator, str);
2115
    } else if (desc->fields[f].type == PROTOBUF_C_TYPE_BYTES) {
2116 2117 2118 2119
      void *data = STRUCT_MEMBER(PaddleMobile__Framework__ProtobufCBinaryData,
                                 message, desc->fields[f].offset)
                       .data;
      const PaddleMobile__Framework__ProtobufCBinaryData *default_bd;
2120 2121 2122

      default_bd = desc->fields[f].default_value;
      if (data != NULL && (default_bd == NULL || default_bd->data != data)) {
2123
        PaddleMobile__Framework__do_free(allocator, data);
2124 2125
      }
    } else if (desc->fields[f].type == PROTOBUF_C_TYPE_MESSAGE) {
2126
      PaddleMobile__Framework__ProtobufCMessage *sm;
2127

2128 2129
      sm = STRUCT_MEMBER(PaddleMobile__Framework__ProtobufCMessage *, message,
                         desc->fields[f].offset);
2130
      if (sm && sm != desc->fields[f].default_value)
2131 2132
        PaddleMobile__Framework__protobuf_c_message_free_unpacked(sm,
                                                                  allocator);
2133 2134 2135 2136
    }
  }

  for (f = 0; f < message->n_unknown_fields; f++)
2137 2138
    PaddleMobile__Framework__do_free(allocator,
                                     message->unknown_fields[f].data);
2139
  if (message->unknown_fields != NULL)
2140
    PaddleMobile__Framework__do_free(allocator, message->unknown_fields);
2141

2142
  PaddleMobile__Framework__do_free(allocator, message);
2143 2144
}

2145 2146 2147 2148 2149
void PaddleMobile__Framework__protobuf_c_message_init(
    const PaddleMobile__Framework__ProtobufCMessageDescriptor *descriptor,
    void *message) {
  descriptor->message_init(
      (PaddleMobile__Framework__ProtobufCMessage *)(message));
2150 2151
}

2152 2153
protobuf_c_boolean PaddleMobile__Framework__protobuf_c_message_check(
    const PaddleMobile__Framework__ProtobufCMessage *message) {
2154 2155 2156 2157 2158 2159 2160 2161
  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++) {
2162 2163 2164 2165
    const PaddleMobile__Framework__ProtobufCFieldDescriptor *f =
        message->descriptor->fields + i;
    PaddleMobile__Framework__ProtobufCType type = f->type;
    PaddleMobile__Framework__ProtobufCLabel label = f->label;
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
    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) {
2176 2177
        PaddleMobile__Framework__ProtobufCMessage **submessage =
            *(PaddleMobile__Framework__ProtobufCMessage ***)field;
2178 2179
        unsigned j;
        for (j = 0; j < *quantity; j++) {
2180 2181
          if (!PaddleMobile__Framework__protobuf_c_message_check(submessage[j]))
            return FALSE;
2182 2183 2184 2185 2186 2187 2188 2189
        }
      } 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) {
2190 2191
        PaddleMobile__Framework__ProtobufCBinaryData *bd =
            *(PaddleMobile__Framework__ProtobufCBinaryData **)field;
2192 2193 2194 2195 2196 2197 2198 2199 2200
        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) {
2201 2202
        PaddleMobile__Framework__ProtobufCMessage *submessage =
            *(PaddleMobile__Framework__ProtobufCMessage **)field;
2203
        if (label == PROTOBUF_C_LABEL_REQUIRED || submessage != NULL) {
2204 2205
          if (!PaddleMobile__Framework__protobuf_c_message_check(submessage))
            return FALSE;
2206 2207 2208 2209 2210 2211 2212
        }
      } 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);
2213
        PaddleMobile__Framework__ProtobufCBinaryData *bd = field;
2214 2215 2216 2217 2218 2219 2220 2221
        if (label == PROTOBUF_C_LABEL_REQUIRED || *has == TRUE) {
          if (bd->len > 0 && bd->data == NULL) return FALSE;
        }
      }
    }
  }

  return TRUE;
2222 2223 2224 2225
}

/* === services === */

2226 2227 2228
typedef void (*GenericHandler)(
    void *service, const PaddleMobile__Framework__ProtobufCMessage *input,
    ProtobufCClosure closure, void *closure_data);