The following issues were found

java/core/src/main/java/com/google/protobuf/LazyField.java
11 issues
Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 52

                 * Carry a message's default instance which is used by {@code hashCode()}, {@code equals()}, and
   * {@code toString()}.
   */
  private final MessageLite defaultInstance;

  public LazyField(
      MessageLite defaultInstance, ExtensionRegistryLite extensionRegistry, ByteString bytes) {
    super(extensionRegistry, bytes);


            

Reported by PMD.

Use equals() to compare object references.
Error

Line: 63

              
  @Override
  public boolean containsDefaultInstance() {
    return super.containsDefaultInstance() || value == defaultInstance;
  }

  public MessageLite getValue() {
    return getValue(defaultInstance);
  }

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 72

              
  @Override
  public int hashCode() {
    return getValue().hashCode();
  }

  @Override
  public boolean equals(Object obj) {
    return getValue().equals(obj);

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 77

              
  @Override
  public boolean equals(Object obj) {
    return getValue().equals(obj);
  }

  @Override
  public String toString() {
    return getValue().toString();

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 82

              
  @Override
  public String toString() {
    return getValue().toString();
  }

  // ====================================================

  /**

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 92

                 * from FieldSet.
   */
  static class LazyEntry<K> implements Entry<K, Object> {
    private Entry<K, LazyField> entry;

    private LazyEntry(Entry<K, LazyField> entry) {
      this.entry = entry;
    }


            

Reported by PMD.

Private field 'entry' could be made final; it is only initialized in the declaration or constructor.
Design

Line: 92

                 * from FieldSet.
   */
  static class LazyEntry<K> implements Entry<K, Object> {
    private Entry<K, LazyField> entry;

    private LazyEntry(Entry<K, LazyField> entry) {
      this.entry = entry;
    }


            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 109

                    if (field == null) {
        return null;
      }
      return field.getValue();
    }

    public LazyField getField() {
      return entry.getValue();
    }

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 128

                }

  static class LazyIterator<K> implements Iterator<Entry<K, Object>> {
    private Iterator<Entry<K, Object>> iterator;

    public LazyIterator(Iterator<Entry<K, Object>> iterator) {
      this.iterator = iterator;
    }


            

Reported by PMD.

Private field 'iterator' could be made final; it is only initialized in the declaration or constructor.
Design

Line: 128

                }

  static class LazyIterator<K> implements Iterator<Entry<K, Object>> {
    private Iterator<Entry<K, Object>> iterator;

    public LazyIterator(Iterator<Entry<K, Object>> iterator) {
      this.iterator = iterator;
    }


            

Reported by PMD.

src/google/protobuf/text_format_unittest.cc
11 issues
syntax error
Error

Line: 128

              };
std::string TextFormatExtensionsTest::static_proto_debug_string_;

TEST_F(TextFormatTest, Basic) {
  TestUtil::SetAllFields(&proto_);
  EXPECT_EQ(proto_debug_string_, proto_.DebugString());
}

TEST_F(TextFormatExtensionsTest, Extensions) {

            

Reported by Cppcheck.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 453 Column: 12 CWE codes: 120

              class CustomUInt32FieldValuePrinter : public TextFormat::FieldValuePrinter {
 public:
  virtual std::string PrintUInt32(uint32 val) const {
    return StrCat(FieldValuePrinter::PrintUInt32(val), "u");
  }
};

TEST_F(TextFormatTest, DefaultCustomFieldPrinter) {
  protobuf_unittest::TestAllTypes message;

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 477 Column: 12 CWE codes: 120

              class CustomInt32FieldValuePrinter : public TextFormat::FieldValuePrinter {
 public:
  virtual std::string PrintInt32(int32 val) const {
    return StrCat("value-is(", FieldValuePrinter::PrintInt32(val), ")");
  }
};

TEST_F(TextFormatTest, FieldSpecificCustomPrinter) {
  protobuf_unittest::TestAllTypes message;

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 528 Column: 12 CWE codes: 120

              class CustomMessageFieldValuePrinter : public TextFormat::FieldValuePrinter {
 public:
  virtual std::string PrintInt32(int32 v) const {
    return StrCat(FieldValuePrinter::PrintInt32(v), "  # x",
                        strings::Hex(v));
  }

  virtual std::string PrintMessageStart(const Message& message, int field_index,
                                        int field_count,

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 538 Column: 12 CWE codes: 120

                  if (single_line_mode) {
      return " { ";
    }
    return StrCat(" {  # ", message.GetDescriptor()->name(), ": ",
                        field_index, "\n");
  }
};

TEST_F(TextFormatTest, CustomPrinterForComments) {

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 628 Column: 12 CWE codes: 120

                virtual std::string PrintMessageStart(const Message& message, int field_index,
                                        int field_count,
                                        bool single_line_comment) const {
    return StrCat(" {  # 1\n", "  # 2\n");
  }
};

TEST_F(TextFormatTest, CustomPrinterForMultilineComments) {
  protobuf_unittest::TestAllTypes message;

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1394 Column: 15 CWE codes: 120

                  parser_.RecordErrorsTo(&error_collector);
    EXPECT_EQ(expected_result, parser_.ParseFromString(input, proto))
        << input << " -> " << proto->DebugString();
    EXPECT_EQ(StrCat(line, ":", col, ": ", message, "\n"),
              error_collector.text_);
    parser_.RecordErrorsTo(nullptr);
  }

  void ExpectSuccessAndTree(const std::string& input, Message* proto,

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1629 Column: 16 CWE codes: 120

                // enum
  EXPECT_FIELD(nested_enum, unittest::TestAllTypes::BAR, "BAR");
  EXPECT_FIELD(nested_enum, unittest::TestAllTypes::BAZ,
               StrCat(unittest::TestAllTypes::BAZ));
  EXPECT_INVALID(nested_enum, "FOOBAR");

  // message
  EXPECT_TRUE(TextFormat::ParseFieldValueFromString(
      "<bb:12>", d->FindFieldByName("optional_nested_message"), message.get()));

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1917 Column: 32 CWE codes: 120

                const char* format = "[$0]";
  std::string input = "\"test_value\"";
  for (int i = 0; i < 99; ++i) input = strings::Substitute(format, input);
  std::string not_deep_input = StrCat("unknown_nested_array: ", input);

  parser_.AllowUnknownField(true);
  parser_.SetRecursionLimit(100);

  unittest::NestedTestAllTypes message;

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1926 Column: 28 CWE codes: 120

                ExpectSuccessAndTree(not_deep_input, &message, nullptr);

  input = strings::Substitute(format, input);
  std::string deep_input = StrCat("unknown_nested_array: ", input);
  ExpectMessage(
      deep_input,
      "WARNING:Message type \"protobuf_unittest.NestedTestAllTypes\" has no "
      "field named \"unknown_nested_array\".\n1:123: Message is too deep, the "
      "parser exceeded the configured recursion limit of 100.",

            

Reported by FlawFinder.

java/core/src/test/java/com/google/protobuf/PackedFieldTest.java
11 issues
Potential violation of Law of Demeter (method chain calls)
Design

Line: 202

                @Test
  public void testPackedGeneratedMessage() throws Exception {
    TestAllTypes message = TestAllTypes.parseFrom(expectedPackedRawBytes);
    assertThat(message.toByteString()).isEqualTo(expectedPackedRawBytes);
  }

  @Test
  public void testPackedDynamicMessageSerialize() throws Exception {
    DynamicMessage message =

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 202

                @Test
  public void testPackedGeneratedMessage() throws Exception {
    TestAllTypes message = TestAllTypes.parseFrom(expectedPackedRawBytes);
    assertThat(message.toByteString()).isEqualTo(expectedPackedRawBytes);
  }

  @Test
  public void testPackedDynamicMessageSerialize() throws Exception {
    DynamicMessage message =

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 209

                public void testPackedDynamicMessageSerialize() throws Exception {
    DynamicMessage message =
        DynamicMessage.parseFrom(TestAllTypes.getDescriptor(), expectedPackedRawBytes);
    assertThat(message.toByteString()).isEqualTo(expectedPackedRawBytes);
  }

  @Test
  public void testUnpackedGeneratedMessage() throws Exception {
    TestUnpackedTypes message = TestUnpackedTypes.parseFrom(expectedUnpackedRawBytes);

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 209

                public void testPackedDynamicMessageSerialize() throws Exception {
    DynamicMessage message =
        DynamicMessage.parseFrom(TestAllTypes.getDescriptor(), expectedPackedRawBytes);
    assertThat(message.toByteString()).isEqualTo(expectedPackedRawBytes);
  }

  @Test
  public void testUnpackedGeneratedMessage() throws Exception {
    TestUnpackedTypes message = TestUnpackedTypes.parseFrom(expectedUnpackedRawBytes);

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 215

                @Test
  public void testUnpackedGeneratedMessage() throws Exception {
    TestUnpackedTypes message = TestUnpackedTypes.parseFrom(expectedUnpackedRawBytes);
    assertThat(message.toByteString()).isEqualTo(expectedUnpackedRawBytes);
  }

  @Test
  public void testUnPackedDynamicMessageSerialize() throws Exception {
    DynamicMessage message =

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 215

                @Test
  public void testUnpackedGeneratedMessage() throws Exception {
    TestUnpackedTypes message = TestUnpackedTypes.parseFrom(expectedUnpackedRawBytes);
    assertThat(message.toByteString()).isEqualTo(expectedUnpackedRawBytes);
  }

  @Test
  public void testUnPackedDynamicMessageSerialize() throws Exception {
    DynamicMessage message =

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 222

                public void testUnPackedDynamicMessageSerialize() throws Exception {
    DynamicMessage message =
        DynamicMessage.parseFrom(TestUnpackedTypes.getDescriptor(), expectedUnpackedRawBytes);
    assertThat(message.toByteString()).isEqualTo(expectedUnpackedRawBytes);
  }

  // Make sure we haven't screwed up the code generation for packing fields by default.
  @Test
  public void testPackedSerialization() throws Exception {

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 222

                public void testUnPackedDynamicMessageSerialize() throws Exception {
    DynamicMessage message =
        DynamicMessage.parseFrom(TestUnpackedTypes.getDescriptor(), expectedUnpackedRawBytes);
    assertThat(message.toByteString()).isEqualTo(expectedUnpackedRawBytes);
  }

  // Make sure we haven't screwed up the code generation for packing fields by default.
  @Test
  public void testPackedSerialization() throws Exception {

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 234

                          .addRepeatedNestedEnum(NestedEnum.BAR)
            .build();

    CodedInputStream in = CodedInputStream.newInstance(message.toByteArray());

    while (!in.isAtEnd()) {
      int tag = in.readTag();
      assertThat(WireFormat.getTagWireType(tag)).isEqualTo(WireFormat.WIRETYPE_LENGTH_DELIMITED);
      in.skipField(tag);

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 236

              
    CodedInputStream in = CodedInputStream.newInstance(message.toByteArray());

    while (!in.isAtEnd()) {
      int tag = in.readTag();
      assertThat(WireFormat.getTagWireType(tag)).isEqualTo(WireFormat.WIRETYPE_LENGTH_DELIMITED);
      in.skipField(tag);
    }
  }

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/ExperimentalTestDataProvider.java
11 issues
Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 39

              public final class ExperimentalTestDataProvider {
  private static final Random RANDOM = new Random(100);

  private final Varint32Provider varint32s = new Varint32Provider();
  private final Varint64Provider varint64s = new Varint64Provider();
  private final int stringLength;

  public ExperimentalTestDataProvider(int stringLength) {
    this.stringLength = stringLength;

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 40

                private static final Random RANDOM = new Random(100);

  private final Varint32Provider varint32s = new Varint32Provider();
  private final Varint64Provider varint64s = new Varint64Provider();
  private final int stringLength;

  public ExperimentalTestDataProvider(int stringLength) {
    this.stringLength = stringLength;
  }

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 41

              
  private final Varint32Provider varint32s = new Varint32Provider();
  private final Varint64Provider varint64s = new Varint64Provider();
  private final int stringLength;

  public ExperimentalTestDataProvider(int stringLength) {
    this.stringLength = stringLength;
  }


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 111

                   * The index into the {@link #VALUES} array that identifies the list of samples currently being
     * iterated over.
     */
    private int listIndex;

    /** The index of the next sample within a list. */
    private int sampleIndex;

    /** The number of successive samples that have been taken from the current list. */

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 114

                  private int listIndex;

    /** The index of the next sample within a list. */
    private int sampleIndex;

    /** The number of successive samples that have been taken from the current list. */
    private int samplesTaken;

    public int getInt() {

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 117

                  private int sampleIndex;

    /** The number of successive samples that have been taken from the current list. */
    private int samplesTaken;

    public int getInt() {
      if (samplesTaken++ > NUM_SAMPLES[listIndex]) {
        // Done taking samples from this list. Go to the next one.
        listIndex = (listIndex + 1) % VALUES.length;

            

Reported by PMD.

Avoid assignments in operands
Error

Line: 120

                  private int samplesTaken;

    public int getInt() {
      if (samplesTaken++ > NUM_SAMPLES[listIndex]) {
        // Done taking samples from this list. Go to the next one.
        listIndex = (listIndex + 1) % VALUES.length;
        sampleIndex = 0;
        samplesTaken = 0;
      }

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 164

                   * The index into the {@link #VALUES} array that identifies the list of samples currently being
     * iterated over.
     */
    private int listIndex;

    /** The index of the next sample within a list. */
    private int sampleIndex;

    /** The number of successive samples that have been taken from the current list. */

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 167

                  private int listIndex;

    /** The index of the next sample within a list. */
    private int sampleIndex;

    /** The number of successive samples that have been taken from the current list. */
    private int samplesTaken;

    public long getLong() {

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 170

                  private int sampleIndex;

    /** The number of successive samples that have been taken from the current list. */
    private int samplesTaken;

    public long getLong() {
      if (samplesTaken++ > NUM_SAMPLES[listIndex]) {
        // Done taking samples from this list. Go to the next one.
        listIndex = (listIndex + 1) % VALUES.length;

            

Reported by PMD.

src/google/protobuf/parse_context.h
11 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 239 Column: 12 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                    if (aliasing_ == kOnPatch) aliasing_ = kNoDelta;
      return flat.data();
    } else {
      std::memcpy(buffer_, flat.data(), flat.size());
      limit_ = 0;
      limit_end_ = buffer_end_ = buffer_ + flat.size();
      next_chunk_ = nullptr;
      if (aliasing_ == kOnPatch) {
        aliasing_ = reinterpret_cast<std::uintptr_t>(flat.data()) -

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 269 Column: 3 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                int size_;
  int limit_;  // relative to buffer_end_;
  io::ZeroCopyInputStream* zcis_ = nullptr;
  char buffer_[2 * kSlopBytes] = {};
  enum { kNoAliasing = 0, kOnPatch = 1, kNoDelta = 2 };
  std::uintptr_t aliasing_ = kNoAliasing;
  // This variable is used to communicate how the parse ended, in order to
  // completely verify the parsed data. A wire-format parse can end because of
  // one of the following conditions:

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 454 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                  return *ptr == static_cast<char>(tag);
  } else {
    static_assert(tag < 128 * 128, "We only expect tags for 1 or 2 bytes");
    char buf[2] = {static_cast<char>(tag | 0x80), static_cast<char>(tag >> 7)};
    return std::memcmp(ptr, buf, 2) == 0;
  }
}

template <int>

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 471 Column: 10 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

              struct EndianHelper<2> {
  static uint16_t Load(const void* p) {
    uint16_t tmp;
    std::memcpy(&tmp, p, 2);
#ifndef PROTOBUF_LITTLE_ENDIAN
    tmp = bswap_16(tmp);
#endif
    return tmp;
  }

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 483 Column: 10 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

              struct EndianHelper<4> {
  static uint32_t Load(const void* p) {
    uint32_t tmp;
    std::memcpy(&tmp, p, 4);
#ifndef PROTOBUF_LITTLE_ENDIAN
    tmp = bswap_32(tmp);
#endif
    return tmp;
  }

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 495 Column: 10 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

              struct EndianHelper<8> {
  static uint64_t Load(const void* p) {
    uint64_t tmp;
    std::memcpy(&tmp, p, 8);
#ifndef PROTOBUF_LITTLE_ENDIAN
    tmp = bswap_64(tmp);
#endif
    return tmp;
  }

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 507 Column: 3 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

              T UnalignedLoad(const char* p) {
  auto tmp = EndianHelper<sizeof(T)>::Load(p);
  T res;
  memcpy(&res, &tmp, sizeof(T));
  return res;
}

PROTOBUF_EXPORT
std::pair<const char*, uint32_t> VarintParseSlow32(const char* p, uint32_t res);

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 696 Column: 10 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  int block_size = num * sizeof(T);
    auto dst = out->AddNAlreadyReserved(num);
#ifdef PROTOBUF_LITTLE_ENDIAN
    std::memcpy(dst, ptr, block_size);
#else
    for (int i = 0; i < num; i++)
      dst[i] = UnalignedLoad<T>(ptr + i * sizeof(T));
#endif
    size -= block_size;

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 714 Column: 8 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                int block_size = num * sizeof(T);
  auto dst = out->AddNAlreadyReserved(num);
#ifdef PROTOBUF_LITTLE_ENDIAN
  std::memcpy(dst, ptr, block_size);
#else
  for (int i = 0; i < num; i++) dst[i] = UnalignedLoad<T>(ptr + i * sizeof(T));
#endif
  ptr += block_size;
  if (size != block_size) return nullptr;

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 748 Column: 7 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                    // The current buffer contains all the information needed, we don't need
      // to flip buffers. However we must parse from a buffer with enough space
      // so we are not prone to a buffer overflow.
      char buf[kSlopBytes + 10] = {};
      std::memcpy(buf, buffer_end_, kSlopBytes);
      GOOGLE_CHECK_LE(size - chunk_size, kSlopBytes);
      auto end = buf + (size - chunk_size);
      auto res = ReadPackedVarintArray(buf + overrun, end, add);
      if (res == nullptr || res != end) return nullptr;

            

Reported by FlawFinder.

java/core/src/main/java/com/google/protobuf/MapEntryLite.java
10 issues
Avoid throwing raw exception types.
Design

Line: 133

                    case ENUM:
        return (T) (java.lang.Integer) input.readEnum();
      case GROUP:
        throw new RuntimeException("Groups are not allowed in maps.");
      default:
        return (T) FieldSet.readPrimitiveField(input, type, true);
    }
  }


            

Reported by PMD.

The class 'Metadata' is suspected to be a Data Class (WOC=0.000%, NOPA=4, NOAM=0, WMC=1)
Design

Line: 47

               */
public class MapEntryLite<K, V> {

  static class Metadata<K, V> {
    public final WireFormat.FieldType keyType;
    public final K defaultKey;
    public final WireFormat.FieldType valueType;
    public final V defaultValue;


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 48

              public class MapEntryLite<K, V> {

  static class Metadata<K, V> {
    public final WireFormat.FieldType keyType;
    public final K defaultKey;
    public final WireFormat.FieldType valueType;
    public final V defaultValue;

    public Metadata(

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 49

              
  static class Metadata<K, V> {
    public final WireFormat.FieldType keyType;
    public final K defaultKey;
    public final WireFormat.FieldType valueType;
    public final V defaultValue;

    public Metadata(
        WireFormat.FieldType keyType,

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 50

                static class Metadata<K, V> {
    public final WireFormat.FieldType keyType;
    public final K defaultKey;
    public final WireFormat.FieldType valueType;
    public final V defaultValue;

    public Metadata(
        WireFormat.FieldType keyType,
        K defaultKey,

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 51

                  public final WireFormat.FieldType keyType;
    public final K defaultKey;
    public final WireFormat.FieldType valueType;
    public final V defaultValue;

    public Metadata(
        WireFormat.FieldType keyType,
        K defaultKey,
        WireFormat.FieldType valueType,

            

Reported by PMD.

Potential violation of Law of Demeter (static property access)
Design

Line: 181

                    if (tag == 0) {
        break;
      }
      if (tag == WireFormat.makeTag(KEY_FIELD_NUMBER, metadata.keyType.getWireType())) {
        key = parseField(input, extensionRegistry, metadata.keyType, key);
      } else if (tag == WireFormat.makeTag(VALUE_FIELD_NUMBER, metadata.valueType.getWireType())) {
        value = parseField(input, extensionRegistry, metadata.valueType, value);
      } else {
        if (!input.skipField(tag)) {

            

Reported by PMD.

Potential violation of Law of Demeter (static property access)
Design

Line: 183

                    }
      if (tag == WireFormat.makeTag(KEY_FIELD_NUMBER, metadata.keyType.getWireType())) {
        key = parseField(input, extensionRegistry, metadata.keyType, key);
      } else if (tag == WireFormat.makeTag(VALUE_FIELD_NUMBER, metadata.valueType.getWireType())) {
        value = parseField(input, extensionRegistry, metadata.valueType, value);
      } else {
        if (!input.skipField(tag)) {
          break;
        }

            

Reported by PMD.

Potential violation of Law of Demeter (static property access)
Design

Line: 211

                    if (tag == 0) {
        break;
      }
      if (tag == WireFormat.makeTag(KEY_FIELD_NUMBER, metadata.keyType.getWireType())) {
        key = parseField(input, extensionRegistry, metadata.keyType, key);
      } else if (tag == WireFormat.makeTag(VALUE_FIELD_NUMBER, metadata.valueType.getWireType())) {
        value = parseField(input, extensionRegistry, metadata.valueType, value);
      } else {
        if (!input.skipField(tag)) {

            

Reported by PMD.

Potential violation of Law of Demeter (static property access)
Design

Line: 213

                    }
      if (tag == WireFormat.makeTag(KEY_FIELD_NUMBER, metadata.keyType.getWireType())) {
        key = parseField(input, extensionRegistry, metadata.keyType, key);
      } else if (tag == WireFormat.makeTag(VALUE_FIELD_NUMBER, metadata.valueType.getWireType())) {
        value = parseField(input, extensionRegistry, metadata.valueType, value);
      } else {
        if (!input.skipField(tag)) {
          break;
        }

            

Reported by PMD.

python/google/protobuf/reflection.py
10 issues
Access to a protected member _GENERATED_PROTOCOL_MESSAGE_TYPE of a client class
Error

Line: 56 Column: 32

              
# The type of all Message classes.
# Part of the public interface, but normally only used by message factories.
GeneratedProtocolMessageType = message_factory._GENERATED_PROTOCOL_MESSAGE_TYPE

MESSAGE_CLASS_CACHE = {}


# Deprecated. Please NEVER use reflection.ParseMessage().

            

Reported by Pylint.

Function name "ParseMessage" doesn't conform to snake_case naming style
Error

Line: 62 Column: 1

              

# Deprecated. Please NEVER use reflection.ParseMessage().
def ParseMessage(descriptor, byte_str):
  """Generate a new Message instance from this Descriptor and a byte string.

  DEPRECATED: ParseMessage is deprecated because it is using MakeClass().
  Please use MessageFactory.GetPrototype() instead.


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 63 Column: 1

              
# Deprecated. Please NEVER use reflection.ParseMessage().
def ParseMessage(descriptor, byte_str):
  """Generate a new Message instance from this Descriptor and a byte string.

  DEPRECATED: ParseMessage is deprecated because it is using MakeClass().
  Please use MessageFactory.GetPrototype() instead.

  Args:

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 75 Column: 1

                Returns:
    Newly created protobuf Message object.
  """
  result_class = MakeClass(descriptor)
  new_msg = result_class()
  new_msg.ParseFromString(byte_str)
  return new_msg



            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 76 Column: 1

                  Newly created protobuf Message object.
  """
  result_class = MakeClass(descriptor)
  new_msg = result_class()
  new_msg.ParseFromString(byte_str)
  return new_msg


# Deprecated. Please NEVER use reflection.MakeClass().

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 77 Column: 1

                """
  result_class = MakeClass(descriptor)
  new_msg = result_class()
  new_msg.ParseFromString(byte_str)
  return new_msg


# Deprecated. Please NEVER use reflection.MakeClass().
def MakeClass(descriptor):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 78 Column: 1

                result_class = MakeClass(descriptor)
  new_msg = result_class()
  new_msg.ParseFromString(byte_str)
  return new_msg


# Deprecated. Please NEVER use reflection.MakeClass().
def MakeClass(descriptor):
  """Construct a class object for a protobuf described by descriptor.

            

Reported by Pylint.

Function name "MakeClass" doesn't conform to snake_case naming style
Error

Line: 82 Column: 1

              

# Deprecated. Please NEVER use reflection.MakeClass().
def MakeClass(descriptor):
  """Construct a class object for a protobuf described by descriptor.

  DEPRECATED: use MessageFactory.GetPrototype() instead.

  Args:

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 83 Column: 1

              
# Deprecated. Please NEVER use reflection.MakeClass().
def MakeClass(descriptor):
  """Construct a class object for a protobuf described by descriptor.

  DEPRECATED: use MessageFactory.GetPrototype() instead.

  Args:
    descriptor: A descriptor.Descriptor object describing the protobuf.

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 95 Column: 1

                # Original implementation leads to duplicate message classes, which won't play
  # well with extensions. Message factory info is also missing.
  # Redirect to message_factory.
  return symbol_database.Default().GetPrototype(descriptor)

            

Reported by Pylint.

src/google/protobuf/descriptor.cc
10 issues
Uninitialized variable: to_use
Error

Line: 828 CWE codes: 908

                    rollback_info_.push_back({to_use, 1});
    }

    void* p = to_use->Allocate(size, tag);
    if (to_relocate != nullptr) {
      RelocateToUsedList(to_relocate);
    }
    return p;
  }

            

Reported by Cppcheck.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1566 Column: 9 CWE codes: 120

                  EnumValueDescriptor* result = tables->Allocate<EnumValueDescriptor>();
    result->all_names_ = tables->AllocateStringArray(
        enum_value_name,
        StrCat(parent->full_name(), ".", enum_value_name));
    result->number_ = number;
    result->type_ = parent;
    result->options_ = &EnumValueOptions::default_instance();
    InsertIfNotPresent(&unknown_enum_values_by_number_,
                            std::make_pair(parent, number), result);

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1744 Column: 23 CWE codes: 120

                if (scope.empty()) {
    result.array[1] = name;
  } else {
    result.array[1] = StrCat(scope, ".", name);
  }
  int index = 2;
  if (lower_eq_name) {
    result.lowercase_index = 0;
  } else {

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 2476 Column: 14 CWE codes: 120

                GOOGLE_CHECK(has_default_value()) << "No default value";
  switch (cpp_type()) {
    case CPPTYPE_INT32:
      return StrCat(default_value_int32_t());
      break;
    case CPPTYPE_INT64:
      return StrCat(default_value_int64_t());
      break;
    case CPPTYPE_UINT32:

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 2479 Column: 14 CWE codes: 120

                    return StrCat(default_value_int32_t());
      break;
    case CPPTYPE_INT64:
      return StrCat(default_value_int64_t());
      break;
    case CPPTYPE_UINT32:
      return StrCat(default_value_uint32_t());
      break;
    case CPPTYPE_UINT64:

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 2482 Column: 14 CWE codes: 120

                    return StrCat(default_value_int64_t());
      break;
    case CPPTYPE_UINT32:
      return StrCat(default_value_uint32_t());
      break;
    case CPPTYPE_UINT64:
      return StrCat(default_value_uint64_t());
      break;
    case CPPTYPE_FLOAT:

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 2485 Column: 14 CWE codes: 120

                    return StrCat(default_value_uint32_t());
      break;
    case CPPTYPE_UINT64:
      return StrCat(default_value_uint64_t());
      break;
    case CPPTYPE_FLOAT:
      return SimpleFtoa(default_value_float());
      break;
    case CPPTYPE_DOUBLE:

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 3193 Column: 23 CWE codes: 120

                  field_type = FieldTypeNameDebugString();
  }

  std::string label = StrCat(kLabelToName[this->label()], " ");

  // Label is omitted for maps, oneof, and plain proto3 fields.
  if (is_map() || real_containing_oneof() ||
      (is_optional() && !has_optional_keyword())) {
    label.clear();

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 4420 Column: 7 CWE codes: 120

              
  // Create the placeholders.
  FileDescriptor* placeholder_file = NewPlaceholderFileWithMutexHeld(
      StrCat(placeholder_full_name, ".placeholder.proto"));
  placeholder_file->package_ = placeholder_package;

  if (placeholder_type == PLACEHOLDER_ENUM) {
    placeholder_file->enum_type_count_ = 1;
    placeholder_file->enum_types_ = tables_->AllocateArray<EnumDescriptor>(1);

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 5090 Column: 41 CWE codes: 120

                  return tables_->AllocateStringArray(proto_name, proto_name);
  } else {
    return tables_->AllocateStringArray(proto_name,
                                        StrCat(scope, ".", proto_name));
  }
}

void DescriptorBuilder::BuildMessage(const DescriptorProto& proto,
                                     const Descriptor* parent,

            

Reported by FlawFinder.

src/google/protobuf/compiler/cpp/cpp_helpers.cc
10 issues
StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 352 Column: 12 CWE codes: 120

              
std::string ExtensionName(const FieldDescriptor* d) {
  if (const Descriptor* scope = d->extension_scope())
    return StrCat(ClassName(scope), "::", ResolveKeyword(d->name()));
  return ResolveKeyword(d->name());
}

std::string QualifiedExtensionName(const FieldDescriptor* d,
                                   const Options& options) {

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 501 Column: 21 CWE codes: 120

                  // This field's camelcase name is not unique.  As a hack, add the field
    // number to the constant name.  This makes the constant rather useless,
    // but what can we do?
    result += "_" + StrCat(field->number());
  }

  return result;
}


            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 637 Column: 12 CWE codes: 120

                if (number == std::numeric_limits<int32_t>::min()) {
    // This needs to be special-cased, see explanation here:
    // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52661
    return StrCat(number + 1, " - 1");
  } else {
    return StrCat(number);
  }
}


            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 639 Column: 12 CWE codes: 120

                  // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52661
    return StrCat(number + 1, " - 1");
  } else {
    return StrCat(number);
  }
}

static std::string Int64ToString(int64_t number) {
  if (number == std::numeric_limits<int64_t>::min()) {

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 647 Column: 12 CWE codes: 120

                if (number == std::numeric_limits<int64_t>::min()) {
    // This needs to be special-cased, see explanation here:
    // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52661
    return StrCat("int64_t{", number + 1, "} - 1");
  }
  return StrCat("int64_t{", number, "}");
}

static std::string UInt64ToString(uint64_t number) {

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 649 Column: 10 CWE codes: 120

                  // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52661
    return StrCat("int64_t{", number + 1, "} - 1");
  }
  return StrCat("int64_t{", number, "}");
}

static std::string UInt64ToString(uint64_t number) {
  return StrCat("uint64_t{", number, "u}");
}

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 653 Column: 10 CWE codes: 120

              }

static std::string UInt64ToString(uint64_t number) {
  return StrCat("uint64_t{", number, "u}");
}

std::string DefaultValue(const FieldDescriptor* field) {
  return DefaultValue(Options(), field);
}

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 665 Column: 14 CWE codes: 120

                  case FieldDescriptor::CPPTYPE_INT32:
      return Int32ToString(field->default_value_int32());
    case FieldDescriptor::CPPTYPE_UINT32:
      return StrCat(field->default_value_uint32()) + "u";
    case FieldDescriptor::CPPTYPE_INT64:
      return Int64ToString(field->default_value_int64());
    case FieldDescriptor::CPPTYPE_UINT64:
      return UInt64ToString(field->default_value_uint64());
    case FieldDescriptor::CPPTYPE_DOUBLE: {

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 750 Column: 12 CWE codes: 120

                                                   const std::string& name,
                                     const Options& options) {
  if (file->package().empty()) {
    return StrCat("::", name);
  }
  return StrCat(Namespace(file, options), "::", name);
}

// Escape C++ trigraphs by escaping question marks to \?

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 752 Column: 10 CWE codes: 120

                if (file->package().empty()) {
    return StrCat("::", name);
  }
  return StrCat(Namespace(file, options), "::", name);
}

// Escape C++ trigraphs by escaping question marks to \?
std::string EscapeTrigraphs(const std::string& to_escape) {
  return StringReplace(to_escape, "?", "\\?", true);

            

Reported by FlawFinder.

java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java
10 issues
Overridable method 'addAll' called during object construction
Error

Line: 89

              
  public LazyStringArrayList(LazyStringList from) {
    list = new ArrayList<Object>(from.size());
    addAll(from);
  }

  public LazyStringArrayList(List<String> from) {
    this(new ArrayList<Object>(from));
  }

            

Reported by PMD.

This class has too many methods, consider refactoring it.
Design

Line: 62

               * @author jonp@google.com (Jon Perlow)
 */
public class LazyStringArrayList extends AbstractProtobufList<String>
    implements LazyStringList, RandomAccess {

  private static final LazyStringArrayList EMPTY_LIST = new LazyStringArrayList();

  static {
    EMPTY_LIST.makeImmutable();

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 77

                // For compatibility with older runtimes.
  public static final LazyStringList EMPTY = EMPTY_LIST;

  private final List<Object> list;

  public LazyStringArrayList() {
    this(DEFAULT_CAPACITY);
  }


            

Reported by PMD.

Avoid using implementation types like 'ArrayList'; use the interface instead
Design

Line: 96

                  this(new ArrayList<Object>(from));
  }

  private LazyStringArrayList(ArrayList<Object> list) {
    this.list = list;
  }

  @Override
  public LazyStringArrayList mutableCopyWithCapacity(int capacity) {

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 117

                    return (String) o;
    } else if (o instanceof ByteString) {
      ByteString bs = (ByteString) o;
      String s = bs.toStringUtf8();
      if (bs.isValidUtf8()) {
        list.set(index, s);
      }
      return s;
    } else {

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 118

                  } else if (o instanceof ByteString) {
      ByteString bs = (ByteString) o;
      String s = bs.toStringUtf8();
      if (bs.isValidUtf8()) {
        list.set(index, s);
      }
      return s;
    } else {
      byte[] ba = (byte[]) o;

            

Reported by PMD.

Use equals() to compare object references.
Error

Line: 238

                public ByteString getByteString(int index) {
    Object o = list.get(index);
    ByteString b = asByteString(o);
    if (b != o) {
      list.set(index, b);
    }
    return b;
  }


            

Reported by PMD.

Use equals() to compare object references.
Error

Line: 248

                public byte[] getByteArray(int index) {
    Object o = list.get(index);
    byte[] b = asByteArray(o);
    if (b != o) {
      list.set(index, b);
    }
    return b;
  }


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 325

                }

  private static class ByteArrayListView extends AbstractList<byte[]> implements RandomAccess {
    private final LazyStringArrayList list;

    ByteArrayListView(LazyStringArrayList list) {
      this.list = list;
    }


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 368

                }

  private static class ByteStringListView extends AbstractList<ByteString> implements RandomAccess {
    private final LazyStringArrayList list;

    ByteStringListView(LazyStringArrayList list) {
      this.list = list;
    }


            

Reported by PMD.