The following issues were found

java/core/src/main/java/com/google/protobuf/LazyFieldLite.java
21 issues
Avoid throwing null pointer exceptions.
Design

Line: 435

              
  private static void checkArguments(ExtensionRegistryLite extensionRegistry, ByteString bytes) {
    if (extensionRegistry == null) {
      throw new NullPointerException("found null ExtensionRegistry");
    }
    if (bytes == null) {
      throw new NullPointerException("found null ByteString");
    }
  }

            

Reported by PMD.

Avoid throwing null pointer exceptions.
Design

Line: 438

                    throw new NullPointerException("found null ExtensionRegistry");
    }
    if (bytes == null) {
      throw new NullPointerException("found null ByteString");
    }
  }
}

            

Reported by PMD.

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

Line: 56

               *
 * @author xiangl@google.com (Xiang Li)
 */
public class LazyFieldLite {
  private static final ExtensionRegistryLite EMPTY_REGISTRY =
      ExtensionRegistryLite.getEmptyRegistry();

  /*
   * The value associated with the LazyFieldLite object is stored in one or more of the following

            

Reported by PMD.

Avoid unused private fields such as 'EMPTY_REGISTRY'.
Design

Line: 57

               * @author xiangl@google.com (Xiang Li)
 */
public class LazyFieldLite {
  private static final ExtensionRegistryLite EMPTY_REGISTRY =
      ExtensionRegistryLite.getEmptyRegistry();

  /*
   * The value associated with the LazyFieldLite object is stored in one or more of the following
   * three fields (delayedBytes, value, memoizedBytes). They should together be interpreted as

            

Reported by PMD.

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

Line: 94

                 * <p>When delayedBytes is non-null then {@code extensionRegistry} is required to also be
   * non-null. {@code value} and {@code memoizedBytes} will be initialized lazily.
   */
  private ByteString delayedBytes;

  /**
   * An {@code ExtensionRegistryLite} for parsing bytes. It is non-null on a best-effort basis. It
   * is only guaranteed to be non-null if this message was initialized using bytes and an {@code
   * ExtensionRegistry}. If it directly had a value set then it will be null, unless it has been

            

Reported by PMD.

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

Line: 102

                 * ExtensionRegistry}. If it directly had a value set then it will be null, unless it has been
   * merged with another {@code LazyFieldLite} that had an {@code ExtensionRegistry}.
   */
  private ExtensionRegistryLite extensionRegistry;

  /**
   * The parsed value. When this is null and a caller needs access to the MessageLite value, then
   * {@code delayedBytes} will be parsed lazily at that time.
   */

            

Reported by PMD.

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

Line: 115

                 * not have to recompute its return-value on each invocation. TODO(yatin): Figure out whether this
   * optimization is actually necessary.
   */
  private volatile ByteString memoizedBytes;

  /** Constructs a LazyFieldLite with bytes that will be parsed lazily. */
  public LazyFieldLite(ExtensionRegistryLite extensionRegistry, ByteString bytes) {
    checkArguments(extensionRegistry, bytes);
    this.extensionRegistry = extensionRegistry;

            

Reported by PMD.

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

Line: 156

                  MessageLite value1 = value;
    MessageLite value2 = other.value;
    if (value1 == null && value2 == null) {
      return toByteString().equals(other.toByteString());
    } else if (value1 != null && value2 != null) {
      return value1.equals(value2);
    } else if (value1 != null) {
      return value1.equals(other.getValue(value1.getDefaultInstanceForType()));
    } else {

            

Reported by PMD.

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

Line: 162

                  } else if (value1 != null) {
      return value1.equals(other.getValue(value1.getDefaultInstanceForType()));
    } else {
      return getValue(value2.getDefaultInstanceForType()).equals(value2);
    }
  }

  @Override
  public int hashCode() {

            

Reported by PMD.

Use equals() to compare object references.
Error

Line: 178

                 * Determines whether this LazyFieldLite instance represents the default instance of this type.
   */
  public boolean containsDefaultInstance() {
    return memoizedBytes == ByteString.EMPTY
        || value == null && (delayedBytes == null || delayedBytes == ByteString.EMPTY);
  }

  /**
   * Clears the value state of this instance.

            

Reported by PMD.

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

Line: 216 Column: 14 CWE codes: 120

              
  switch (field.cpp_type()) {
    case FieldDescriptor::CPPTYPE_INT32:
      return StrCat(field.default_value_int32());
    case FieldDescriptor::CPPTYPE_UINT32:
      return StrCat(field.default_value_uint32());
    case FieldDescriptor::CPPTYPE_INT64:
      return StrCat(field.default_value_int64());
    case FieldDescriptor::CPPTYPE_UINT64:

            

Reported by FlawFinder.

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

Line: 218 Column: 14 CWE codes: 120

                  case FieldDescriptor::CPPTYPE_INT32:
      return StrCat(field.default_value_int32());
    case FieldDescriptor::CPPTYPE_UINT32:
      return StrCat(field.default_value_uint32());
    case FieldDescriptor::CPPTYPE_INT64:
      return StrCat(field.default_value_int64());
    case FieldDescriptor::CPPTYPE_UINT64:
      return StrCat(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: 220 Column: 14 CWE codes: 120

                  case FieldDescriptor::CPPTYPE_UINT32:
      return StrCat(field.default_value_uint32());
    case FieldDescriptor::CPPTYPE_INT64:
      return StrCat(field.default_value_int64());
    case FieldDescriptor::CPPTYPE_UINT64:
      return StrCat(field.default_value_uint64());
    case FieldDescriptor::CPPTYPE_DOUBLE: {
      double value = field.default_value_double();
      if (value == std::numeric_limits<double>::infinity()) {

            

Reported by FlawFinder.

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

Line: 222 Column: 14 CWE codes: 120

                  case FieldDescriptor::CPPTYPE_INT64:
      return StrCat(field.default_value_int64());
    case FieldDescriptor::CPPTYPE_UINT64:
      return StrCat(field.default_value_uint64());
    case FieldDescriptor::CPPTYPE_DOUBLE: {
      double value = field.default_value_double();
      if (value == std::numeric_limits<double>::infinity()) {
        // Python pre-2.6 on Windows does not parse "inf" correctly.  However,
        // a numeric literal that is too big for a double will become infinity.

            

Reported by FlawFinder.

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

Line: 258 Column: 14 CWE codes: 120

                  case FieldDescriptor::CPPTYPE_BOOL:
      return field.default_value_bool() ? "True" : "False";
    case FieldDescriptor::CPPTYPE_ENUM:
      return StrCat(field.default_value_enum()->number());
    case FieldDescriptor::CPPTYPE_STRING:
      return "b\"" + CEscape(field.default_value_string()) +
             (field.type() != FieldDescriptor::TYPE_STRING
                  ? "\""
                  : "\".decode('utf-8')");

            

Reported by FlawFinder.

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

Line: 498 Column: 21 CWE codes: 120

                for (int i = 0; i < top_level_enum_values.size(); ++i) {
    printer_->Print("$name$ = $value$\n", "name",
                    ResolveKeyword(top_level_enum_values[i].first), "value",
                    StrCat(top_level_enum_values[i].second));
  }
  printer_->Print("\n");
}

// Prints all enums contained in all message types in |file|.

            

Reported by FlawFinder.

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

Line: 578 Column: 21 CWE codes: 120

                  ToUpper(&constant_name);
    printer_->Print("$constant_name$ = $number$\n", "constant_name",
                    constant_name, "number",
                    StrCat(extension_field.number()));
    printer_->Print("$name$ = ", "name",
                    ResolveKeyword(extension_field.name()));
    PrintFieldDescriptor(extension_field, is_extension);
    printer_->Print("\n");
  }

            

Reported by FlawFinder.

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

Line: 625 Column: 16 CWE codes: 120

                m["name"] = descriptor.name();
  m["full_name"] = descriptor.full_name();
  m["file"] = kDescriptorKey;
  m["index"] = StrCat(descriptor.index());
  m["options_value"] = OptionsValue(options_string);
  const char required_function_arguments[] =
      "name='$name$',\n"
      "full_name='$full_name$',\n"
      "file=$file$,\n"

            

Reported by FlawFinder.

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

Line: 647 Column: 18 CWE codes: 120

                  m.clear();
    m["name"] = method->name();
    m["full_name"] = method->full_name();
    m["index"] = StrCat(method->index());
    m["serialized_options"] = CEscape(options_string);
    m["input_type"] = ModuleLevelDescriptorName(*(method->input_type()));
    m["output_type"] = ModuleLevelDescriptorName(*(method->output_type()));
    m["options_value"] = OptionsValue(options_string);
    printer_->Print("_descriptor.MethodDescriptor(\n");

            

Reported by FlawFinder.

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

Line: 775 Column: 52 CWE codes: 120

                for (int i = 0; i < message_descriptor.extension_range_count(); ++i) {
    const Descriptor::ExtensionRange* range =
        message_descriptor.extension_range(i);
    printer_->Print("($start$, $end$), ", "start", StrCat(range->start),
                    "end", StrCat(range->end));
  }
  printer_->Print("],\n");
  printer_->Print("oneofs=[\n");
  printer_->Indent();

            

Reported by FlawFinder.

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

Line: 73 Column: 16 CWE codes: 120

                if (options.field_listener_options.forbidden_field_listener_events.count(
          std::string(annotation_name)))
    return;
  (*variables)[StrCat("annotate_", annotation_name)] = strings::Substitute(
      StrCat(substitute_template_prefix, prepared_template, ");\n"),
      field_index, access_type);
}

std::string GenerateTemplateForOneofString(const FieldDescriptor* descriptor,

            

Reported by FlawFinder.

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

Line: 74 Column: 7 CWE codes: 120

                        std::string(annotation_name)))
    return;
  (*variables)[StrCat("annotate_", annotation_name)] = strings::Substitute(
      StrCat(substitute_template_prefix, prepared_template, ");\n"),
      field_index, access_type);
}

std::string GenerateTemplateForOneofString(const FieldDescriptor* descriptor,
                                           StringPiece proto_ns,

            

Reported by FlawFinder.

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

Line: 88 Column: 32 CWE codes: 120

                        : "$0";

  if (descriptor->default_value_string().empty()) {
    return strings::Substitute(StrCat("_internal_has_", field_name, "() ? ",
                                         field_pointer, ": nullptr"),
                            field_member);
  }

  if (descriptor->options().ctype() == google::protobuf::FieldOptions::STRING_PIECE) {

            

Reported by FlawFinder.

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

Line: 94 Column: 32 CWE codes: 120

                }

  if (descriptor->options().ctype() == google::protobuf::FieldOptions::STRING_PIECE) {
    return strings::Substitute(StrCat("_internal_has_", field_name, "() ? ",
                                         field_pointer, ": nullptr"),
                            field_member);
  }

  std::string default_value_pointer =

            

Reported by FlawFinder.

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

Line: 104 Column: 7 CWE codes: 120

                        ? "&$1.get()"
          : "&$1";
  return strings::Substitute(
      StrCat("_internal_has_", field_name, "() ? ", field_pointer, " : ",
                   default_value_pointer),
      field_member, MakeDefaultName(descriptor));
}

std::string GenerateTemplateForSingleString(const FieldDescriptor* descriptor,

            

Reported by FlawFinder.

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

Line: 112 Column: 12 CWE codes: 120

              std::string GenerateTemplateForSingleString(const FieldDescriptor* descriptor,
                                            StringPiece field_member) {
  if (descriptor->default_value_string().empty()) {
    return StrCat("&", field_member);
  }

  if (descriptor->options().ctype() == google::protobuf::FieldOptions::STRING) {
    return strings::Substitute(
        "$0.IsDefault(nullptr) ? &$1.get() : $0.GetPointer()", field_member,

            

Reported by FlawFinder.

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

Line: 121 Column: 10 CWE codes: 120

                      MakeDefaultName(descriptor));
  }

  return StrCat("&", field_member);
}

}  // namespace

void AddAccessorAnnotations(const FieldDescriptor* descriptor,

            

Reported by FlawFinder.

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

Line: 142 Column: 48 CWE codes: 120

                }
  if (options.annotate_accessor) {
    for (size_t i = 0; i < GOOGLE_ARRAYSIZE(kAccessorsAnnotations); ++i) {
      (*variables)[kAccessorsAnnotations[i]] = StrCat(
          "  ", FieldName(descriptor), "_AccessedNoStrip = true;\n");
    }
  }
  if (!options.field_listener_options.inject_field_listener_events) {
    return;

            

Reported by FlawFinder.

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

Line: 157 Column: 20 CWE codes: 120

                const google::protobuf::OneofDescriptor* oneof_member =
      descriptor->real_containing_oneof();
  if (oneof_member) {
    field_member = StrCat(oneof_member->name(), "_.", field_member);
  }
  const std::string proto_ns = (*variables)["proto_ns"];
  const std::string substitute_template_prefix = "  _tracker_.$1<$0>(this, ";
  std::string prepared_template;


            

Reported by FlawFinder.

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

Line: 192 Column: 25 CWE codes: 120

                        GenerateTemplateForSingleString(descriptor, field_member);
    }
  } else {
    prepared_template = StrCat("&", field_member);
  }
  if (descriptor->is_repeated() && !descriptor->is_map() &&
      descriptor->type() != FieldDescriptor::TYPE_MESSAGE &&
      descriptor->type() != FieldDescriptor::TYPE_GROUP) {
    prepared_flat_template = StrCat("&", field_member);

            

Reported by FlawFinder.

src/google/protobuf/io/printer_unittest.cc
20 issues
syntax error
Error

Line: 62

                EXPECT_TRUE(!printer.failed());
}

TEST(Printer, BasicPrinting) {
  char buffer[8192];

  for (int block_size = 1; block_size < 512; block_size *= 2) {
    ArrayOutputStream output(buffer, sizeof(buffer), block_size);


            

Reported by Cppcheck.

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

Line: 55 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

              // not.

TEST(Printer, EmptyPrinter) {
  char buffer[8192];
  const int block_size = 100;
  ArrayOutputStream output(buffer, GOOGLE_ARRAYSIZE(buffer), block_size);
  Printer printer(&output, '\0');
  EXPECT_TRUE(!printer.failed());
}

            

Reported by FlawFinder.

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

Line: 63 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

              }

TEST(Printer, BasicPrinting) {
  char buffer[8192];

  for (int block_size = 1; block_size < 512; block_size *= 2) {
    ArrayOutputStream output(buffer, sizeof(buffer), block_size);

    {

            

Reported by FlawFinder.

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

Line: 89 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

              }

TEST(Printer, WriteRaw) {
  char buffer[8192];

  for (int block_size = 1; block_size < 512; block_size *= 2) {
    ArrayOutputStream output(buffer, sizeof(buffer), block_size);

    {

            

Reported by FlawFinder.

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

Line: 118 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

              }

TEST(Printer, VariableSubstitution) {
  char buffer[8192];

  for (int block_size = 1; block_size < 512; block_size *= 2) {
    ArrayOutputStream output(buffer, sizeof(buffer), block_size);

    {

            

Reported by FlawFinder.

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

Line: 155 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

              }

TEST(Printer, InlineVariableSubstitution) {
  char buffer[8192];

  ArrayOutputStream output(buffer, sizeof(buffer));

  {
    Printer printer(&output, '$');

            

Reported by FlawFinder.

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

Line: 211 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

              };

TEST(Printer, AnnotateMap) {
  char buffer[8192];
  ArrayOutputStream output(buffer, sizeof(buffer));
  GeneratedCodeInfo info;
  AnnotationProtoCollector<GeneratedCodeInfo> info_collector(&info);
  {
    Printer printer(&output, '$', &info_collector);

            

Reported by FlawFinder.

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

Line: 254 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

              }

TEST(Printer, AnnotateInline) {
  char buffer[8192];
  ArrayOutputStream output(buffer, sizeof(buffer));
  GeneratedCodeInfo info;
  AnnotationProtoCollector<GeneratedCodeInfo> info_collector(&info);
  {
    Printer printer(&output, '$', &info_collector);

            

Reported by FlawFinder.

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

Line: 294 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

              }

TEST(Printer, AnnotateRange) {
  char buffer[8192];
  ArrayOutputStream output(buffer, sizeof(buffer));
  GeneratedCodeInfo info;
  AnnotationProtoCollector<GeneratedCodeInfo> info_collector(&info);
  {
    Printer printer(&output, '$', &info_collector);

            

Reported by FlawFinder.

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

Line: 318 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

              }

TEST(Printer, AnnotateEmptyRange) {
  char buffer[8192];
  ArrayOutputStream output(buffer, sizeof(buffer));
  GeneratedCodeInfo info;
  AnnotationProtoCollector<GeneratedCodeInfo> info_collector(&info);
  {
    Printer printer(&output, '$', &info_collector);

            

Reported by FlawFinder.

java/core/src/test/java/com/google/protobuf/EnumTest.java
20 issues
Unit tests should not contain more than 1 assert(s).
Design

Line: 47

              public class EnumTest {

  @Test
  public void testForNumber() {
    ForeignEnum e = ForeignEnum.forNumber(ForeignEnum.FOREIGN_BAR.getNumber());
    assertThat(e).isEqualTo(ForeignEnum.FOREIGN_BAR);

    e = ForeignEnum.forNumber(1000);
    assertThat(e).isNull();

            

Reported by PMD.

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

Line: 48

              
  @Test
  public void testForNumber() {
    ForeignEnum e = ForeignEnum.forNumber(ForeignEnum.FOREIGN_BAR.getNumber());
    assertThat(e).isEqualTo(ForeignEnum.FOREIGN_BAR);

    e = ForeignEnum.forNumber(1000);
    assertThat(e).isNull();
  }

            

Reported by PMD.

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

Line: 49

                @Test
  public void testForNumber() {
    ForeignEnum e = ForeignEnum.forNumber(ForeignEnum.FOREIGN_BAR.getNumber());
    assertThat(e).isEqualTo(ForeignEnum.FOREIGN_BAR);

    e = ForeignEnum.forNumber(1000);
    assertThat(e).isNull();
  }


            

Reported by PMD.

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

Line: 52

                  assertThat(e).isEqualTo(ForeignEnum.FOREIGN_BAR);

    e = ForeignEnum.forNumber(1000);
    assertThat(e).isNull();
  }

  @Test
  public void testForNumber_oneof() {
    TestAllTypes.OneofFieldCase e =

            

Reported by PMD.

Unit tests should not contain more than 1 assert(s).
Design

Line: 56

                }

  @Test
  public void testForNumber_oneof() {
    TestAllTypes.OneofFieldCase e =
        TestAllTypes.OneofFieldCase.forNumber(
            TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber());
    assertThat(e).isEqualTo(TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE);


            

Reported by PMD.

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

Line: 58

                @Test
  public void testForNumber_oneof() {
    TestAllTypes.OneofFieldCase e =
        TestAllTypes.OneofFieldCase.forNumber(
            TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber());
    assertThat(e).isEqualTo(TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE);

    e = TestAllTypes.OneofFieldCase.forNumber(1000);
    assertThat(e).isNull();

            

Reported by PMD.

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

Line: 59

                public void testForNumber_oneof() {
    TestAllTypes.OneofFieldCase e =
        TestAllTypes.OneofFieldCase.forNumber(
            TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber());
    assertThat(e).isEqualTo(TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE);

    e = TestAllTypes.OneofFieldCase.forNumber(1000);
    assertThat(e).isNull();
  }

            

Reported by PMD.

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

Line: 60

                  TestAllTypes.OneofFieldCase e =
        TestAllTypes.OneofFieldCase.forNumber(
            TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber());
    assertThat(e).isEqualTo(TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE);

    e = TestAllTypes.OneofFieldCase.forNumber(1000);
    assertThat(e).isNull();
  }


            

Reported by PMD.

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

Line: 62

                          TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber());
    assertThat(e).isEqualTo(TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE);

    e = TestAllTypes.OneofFieldCase.forNumber(1000);
    assertThat(e).isNull();
  }

  @Test
  public void testForNumberLite() {

            

Reported by PMD.

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

Line: 63

                  assertThat(e).isEqualTo(TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE);

    e = TestAllTypes.OneofFieldCase.forNumber(1000);
    assertThat(e).isNull();
  }

  @Test
  public void testForNumberLite() {
    ForeignEnumLite e = ForeignEnumLite.forNumber(ForeignEnumLite.FOREIGN_LITE_BAR.getNumber());

            

Reported by PMD.

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

Line: 408 Column: 11 CWE codes: 120

                    std::string snake_name = StripProto(
          GetSnakeFilename(scc->GetRepresentative()->file()->name()));
      (*long_name_dict)[scc->GetRepresentative()] =
          StrCat(snake_name, "_long_sccs_",
                 static_cast<uint64>((*long_name_dict).size()));
    }
    filename_base = (*long_name_dict)[scc->GetRepresentative()];
  }
  return options.output_dir + "/" + package_base + filename_base +

            

Reported by FlawFinder.

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

Line: 550 Column: 16 CWE codes: 120

                  for (int i = 0; i < parent_type->field_count(); i++) {
      if (parent_type->field(i)->type() == FieldDescriptor::TYPE_GROUP &&
          parent_type->field(i)->message_type() == containing_type) {
        return StrCat(field->number() - parent_type->field(i)->number());
      }
    }
  }
  return StrCat(field->number());
}

            

Reported by FlawFinder.

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

Line: 554 Column: 10 CWE codes: 120

                    }
    }
  }
  return StrCat(field->number());
}

std::string JSOneofIndex(const OneofDescriptor* oneof) {
  int index = -1;
  for (int i = 0; i < oneof->containing_type()->oneof_decl_count(); i++) {

            

Reported by FlawFinder.

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

Line: 574 Column: 10 CWE codes: 120

                    break;
    }
  }
  return StrCat(index);
}

// Decodes a codepoint in \x0000 -- \xFFFF.
uint16 DecodeUTF8Codepoint(uint8* bytes, size_t* length) {
  if (*length == 0) {

            

Reported by FlawFinder.

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

Line: 811 Column: 39 CWE codes: 120

              
  switch (field->cpp_type()) {
    case FieldDescriptor::CPPTYPE_INT32:
      return MaybeNumberString(field, StrCat(field->default_value_int32()));
    case FieldDescriptor::CPPTYPE_UINT32:
      // The original codegen is in Java, and Java protobufs store unsigned
      // integer values as signed integer values. In order to exactly match the
      // output, we need to reinterpret as base-2 signed. Ugh.
      return MaybeNumberString(

            

Reported by FlawFinder.

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

Line: 817 Column: 18 CWE codes: 120

                    // integer values as signed integer values. In order to exactly match the
      // output, we need to reinterpret as base-2 signed. Ugh.
      return MaybeNumberString(
          field, StrCat(static_cast<int32>(field->default_value_uint32())));
    case FieldDescriptor::CPPTYPE_INT64:
      return MaybeNumberString(field, StrCat(field->default_value_int64()));
    case FieldDescriptor::CPPTYPE_UINT64:
      // See above note for uint32 -- reinterpreting as signed.
      return MaybeNumberString(

            

Reported by FlawFinder.

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

Line: 819 Column: 39 CWE codes: 120

                    return MaybeNumberString(
          field, StrCat(static_cast<int32>(field->default_value_uint32())));
    case FieldDescriptor::CPPTYPE_INT64:
      return MaybeNumberString(field, StrCat(field->default_value_int64()));
    case FieldDescriptor::CPPTYPE_UINT64:
      // See above note for uint32 -- reinterpreting as signed.
      return MaybeNumberString(
          field, StrCat(static_cast<int64>(field->default_value_uint64())));
    case FieldDescriptor::CPPTYPE_ENUM:

            

Reported by FlawFinder.

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

Line: 823 Column: 18 CWE codes: 120

                  case FieldDescriptor::CPPTYPE_UINT64:
      // See above note for uint32 -- reinterpreting as signed.
      return MaybeNumberString(
          field, StrCat(static_cast<int64>(field->default_value_uint64())));
    case FieldDescriptor::CPPTYPE_ENUM:
      return StrCat(field->default_value_enum()->number());
    case FieldDescriptor::CPPTYPE_BOOL:
      return field->default_value_bool() ? "true" : "false";
    case FieldDescriptor::CPPTYPE_FLOAT:

            

Reported by FlawFinder.

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

Line: 825 Column: 14 CWE codes: 120

                    return MaybeNumberString(
          field, StrCat(static_cast<int64>(field->default_value_uint64())));
    case FieldDescriptor::CPPTYPE_ENUM:
      return StrCat(field->default_value_enum()->number());
    case FieldDescriptor::CPPTYPE_BOOL:
      return field->default_value_bool() ? "true" : "false";
    case FieldDescriptor::CPPTYPE_FLOAT:
      return FloatToString(field->default_value_float());
    case FieldDescriptor::CPPTYPE_DOUBLE:

            

Reported by FlawFinder.

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

Line: 1390 Column: 10 CWE codes: 120

                                                                   : kDefaultPivot;
  }

  return StrCat(pivot);
}

// Whether this field represents presence.  For fields with presence, we
// generate extra methods (clearFoo() and hasFoo()) for this field.
bool HasFieldPresence(const GeneratorOptions& options,

            

Reported by FlawFinder.

src/google/protobuf/io/zero_copy_stream_unittest.cc
19 issues
syntax error
Error

Line: 285

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

TEST_F(IoTest, ArrayIo) {
  const int kBufferSize = 256;
  uint8 buffer[kBufferSize];

  for (int i = 0; i < kBlockSizeCount; i++) {
    for (int j = 0; j < kBlockSizeCount; j++) {

            

Reported by Cppcheck.

access - This usually indicates a security flaw. If an attacker can change anything along the path between the call to access() and the file's actual use (e.g., by moving files), the attacker can exploit the race condition
Security

Line: 90 Column: 36 CWE codes: 362/367!
Suggestion: Set up the correct permissions (e.g., using setuid()) and try to open the file directly

              #define pipe(fds) _pipe(fds, 4096, O_BINARY)
// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
// them like we do below.
using google::protobuf::io::win32::access;
using google::protobuf::io::win32::close;
using google::protobuf::io::win32::mkdir;
using google::protobuf::io::win32::open;
#endif


            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 93 Column: 36 CWE codes: 362

              using google::protobuf::io::win32::access;
using google::protobuf::io::win32::close;
using google::protobuf::io::win32::mkdir;
using google::protobuf::io::win32::open;
#endif

#ifndef O_BINARY
#ifdef _O_BINARY
#define O_BINARY _O_BINARY

            

Reported by FlawFinder.

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

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

                  EXPECT_GT(out_size, 0);

    if (in_size <= out_size) {
      memcpy(out, in, in_size);
      output->BackUp(out_size - in_size);
      return true;
    }

    memcpy(out, in, out_size);

            

Reported by FlawFinder.

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

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

                    return true;
    }

    memcpy(out, in, out_size);
    in += out_size;
    in_size -= out_size;
  }
}


            

Reported by FlawFinder.

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

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

                  EXPECT_LT(repeated_zeros, MAX_REPEATED_ZEROS);

    if (out_size <= in_size) {
      memcpy(out, in, out_size);
      if (in_size > out_size) {
        input->BackUp(in_size - out_size);
      }
      return size;  // Copied all of it.
    }

            

Reported by FlawFinder.

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

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

                    return size;  // Copied all of it.
    }

    memcpy(out, in, in_size);
    out += in_size;
    out_size -= in_size;
  }
}


            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 744 Column: 11 CWE codes: 362

                  for (int j = 0; j < kBlockSizeCount; j++) {
      // Make a temporary file.
      int file =
          open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0777);
      ASSERT_GE(file, 0);

      {
        FileOutputStream output(file, kBlockSizes[i]);
        WriteStuff(&output);

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 841 Column: 11 CWE codes: 362

                  for (int j = 0; j < kBlockSizeCount; j++) {
      // Make a temporary file.
      int file =
          open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0777);
      ASSERT_GE(file, 0);
      {
        FileOutputStream output(file, kBlockSizes[i]);
        GzipOutputStream gzout(&output);
        WriteStuffLarge(&gzout);

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 318 Column: 35 CWE codes: 126

                    ArrayOutputStream* output =
          new ArrayOutputStream(buffer, kBufferSize, kBlockSizes[i]);
      CodedOutputStream* coded_output = new CodedOutputStream(output);
      coded_output->WriteVarint32(strlen(strA));
      coded_output->WriteRaw(strA, strlen(strA));
      delete coded_output;  // flush
      int64 pos = output->ByteCount();
      delete output;
      output = new ArrayOutputStream(buffer + pos, kBufferSize - pos,

            

Reported by FlawFinder.

java/core/src/test/java/com/google/protobuf/ExperimentalSerializationUtil.java
19 issues
Avoid throwing raw exception types.
Design

Line: 97

                    schema.makeImmutable(msg);
      return msg;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  /** Deserializes a lite message from the given byte array using fast path. */
  private static <T> T fromByteArrayFastPath(byte[] data, Class<T> messageType) {

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 110

                    schema.makeImmutable(msg);
      return msg;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}

            

Reported by PMD.

All methods are static. Consider using a utility class instead. Alternatively, you could add a private constructor or make the class abstract to silence this warning.
Design

Line: 38

              import java.util.Queue;

/** Utilities for serialization. */
public class ExperimentalSerializationUtil {

  /**
   * Serializes the given message to a byte array using {@link com.google.protobuf.BinaryWriter}.
   */
  public static <T> byte[] toByteArray(T msg) throws IOException {

            

Reported by PMD.

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

Line: 44

                 * Serializes the given message to a byte array using {@link com.google.protobuf.BinaryWriter}.
   */
  public static <T> byte[] toByteArray(T msg) throws IOException {
    return toByteArray(msg, Protobuf.getInstance().schemaFor(msg));
  }

  /**
   * Serializes the given message to a byte array using {@link com.google.protobuf.BinaryWriter}
   * with a customized Schema.

            

Reported by PMD.

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

Line: 55

                  BinaryWriter writer = BinaryWriter.newHeapInstance(BufferAllocator.unpooled());
    schema.writeTo(msg, writer);

    byte[] out = new byte[writer.getTotalBytesWritten()];
    int outPos = 0;
    Queue<AllocatedBuffer> buffers = writer.complete();
    while (true) {
      AllocatedBuffer buffer = buffers.poll();
      if (buffer == null) {

            

Reported by PMD.

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

Line: 57

              
    byte[] out = new byte[writer.getTotalBytesWritten()];
    int outPos = 0;
    Queue<AllocatedBuffer> buffers = writer.complete();
    while (true) {
      AllocatedBuffer buffer = buffers.poll();
      if (buffer == null) {
        break;
      }

            

Reported by PMD.

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

Line: 63

                    if (buffer == null) {
        break;
      }
      int length = buffer.limit() - buffer.position();
      System.arraycopy(
          buffer.array(), buffer.arrayOffset() + buffer.position(), out, outPos, length);
      outPos += length;
    }
    if (out.length != outPos) {

            

Reported by PMD.

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

Line: 63

                    if (buffer == null) {
        break;
      }
      int length = buffer.limit() - buffer.position();
      System.arraycopy(
          buffer.array(), buffer.arrayOffset() + buffer.position(), out, outPos, length);
      outPos += length;
    }
    if (out.length != outPos) {

            

Reported by PMD.

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

Line: 65

                    }
      int length = buffer.limit() - buffer.position();
      System.arraycopy(
          buffer.array(), buffer.arrayOffset() + buffer.position(), out, outPos, length);
      outPos += length;
    }
    if (out.length != outPos) {
      throw new IllegalArgumentException("Failed to serialize test message");
    }

            

Reported by PMD.

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

Line: 65

                    }
      int length = buffer.limit() - buffer.position();
      System.arraycopy(
          buffer.array(), buffer.arrayOffset() + buffer.position(), out, outPos, length);
      outPos += length;
    }
    if (out.length != outPos) {
      throw new IllegalArgumentException("Failed to serialize test message");
    }

            

Reported by PMD.

ruby/src/main/java/com/google/protobuf/jruby/RubyFieldDescriptor.java
18 issues
Potential violation of Law of Demeter (static property access)
Design

Line: 232

              
    protected void setDescriptor(ThreadContext context, FieldDescriptor descriptor, RubyDescriptorPool pool) {
        this.descriptor = descriptor;
        this.name = context.runtime.newString(descriptor.getName());
        this.pool = pool;
    }

    private void calculateLabel(ThreadContext context) {
        if (descriptor.isRepeated()) {

            

Reported by PMD.

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

Line: 238

              
    private void calculateLabel(ThreadContext context) {
        if (descriptor.isRepeated()) {
            this.label = context.runtime.newSymbol("repeated");
        } else if (descriptor.isOptional()) {
            this.label = context.runtime.newSymbol("optional");
        } else {
            this.label = context.nil;
        }

            

Reported by PMD.

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

Line: 240

                      if (descriptor.isRepeated()) {
            this.label = context.runtime.newSymbol("repeated");
        } else if (descriptor.isOptional()) {
            this.label = context.runtime.newSymbol("optional");
        } else {
            this.label = context.nil;
        }
    }


            

Reported by PMD.

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

Line: 249

                  private void calculateSubtype(ThreadContext context) {
        FieldDescriptor.Type fdType = descriptor.getType();
        if (fdType == FieldDescriptor.Type.MESSAGE) {
            RubyString messageName = context.runtime.newString(descriptor.getMessageType().getFullName());
            this.subtype = pool.lookup(context, messageName);
        } else if (fdType == FieldDescriptor.Type.ENUM) {
            RubyString enumName = context.runtime.newString(descriptor.getEnumType().getFullName());
            this.subtype = pool.lookup(context, enumName);
        } else {

            

Reported by PMD.

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

Line: 249

                  private void calculateSubtype(ThreadContext context) {
        FieldDescriptor.Type fdType = descriptor.getType();
        if (fdType == FieldDescriptor.Type.MESSAGE) {
            RubyString messageName = context.runtime.newString(descriptor.getMessageType().getFullName());
            this.subtype = pool.lookup(context, messageName);
        } else if (fdType == FieldDescriptor.Type.ENUM) {
            RubyString enumName = context.runtime.newString(descriptor.getEnumType().getFullName());
            this.subtype = pool.lookup(context, enumName);
        } else {

            

Reported by PMD.

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

Line: 252

                          RubyString messageName = context.runtime.newString(descriptor.getMessageType().getFullName());
            this.subtype = pool.lookup(context, messageName);
        } else if (fdType == FieldDescriptor.Type.ENUM) {
            RubyString enumName = context.runtime.newString(descriptor.getEnumType().getFullName());
            this.subtype = pool.lookup(context, enumName);
        } else {
            this.subtype = context.nil;
        }
    }

            

Reported by PMD.

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

Line: 252

                          RubyString messageName = context.runtime.newString(descriptor.getMessageType().getFullName());
            this.subtype = pool.lookup(context, messageName);
        } else if (fdType == FieldDescriptor.Type.ENUM) {
            RubyString enumName = context.runtime.newString(descriptor.getEnumType().getFullName());
            this.subtype = pool.lookup(context, enumName);
        } else {
            this.subtype = context.nil;
        }
    }

            

Reported by PMD.

Avoid unused private fields such as 'DOT'.
Design

Line: 259

                      }
    }

    private static final String DOT = ".";

    private FieldDescriptor descriptor;
    private IRubyObject name;
    private IRubyObject label;
    private IRubyObject number;

            

Reported by PMD.

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

Line: 261

              
    private static final String DOT = ".";

    private FieldDescriptor descriptor;
    private IRubyObject name;
    private IRubyObject label;
    private IRubyObject number;
    private IRubyObject subtype;
    private RubyDescriptorPool pool;

            

Reported by PMD.

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

Line: 262

                  private static final String DOT = ".";

    private FieldDescriptor descriptor;
    private IRubyObject name;
    private IRubyObject label;
    private IRubyObject number;
    private IRubyObject subtype;
    private RubyDescriptorPool pool;
}

            

Reported by PMD.

java/core/src/main/java/com/google/protobuf/FieldInfo.java
18 issues
Possible God Class (WMC=49, ATFD=8, TCC=30.484%)
Design

Line: 40

              
/** Information for a single field in a protobuf message class. */
@ExperimentalApi
final class FieldInfo implements Comparable<FieldInfo> {
  private final Field field;
  private final FieldType type;
  private final Class<?> messageClass; // The message type for repeated message fields.
  private final int fieldNumber;
  private final Field presenceField;

            

Reported by PMD.

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

Line: 40

              
/** Information for a single field in a protobuf message class. */
@ExperimentalApi
final class FieldInfo implements Comparable<FieldInfo> {
  private final Field field;
  private final FieldType type;
  private final Class<?> messageClass; // The message type for repeated message fields.
  private final int fieldNumber;
  private final Field presenceField;

            

Reported by PMD.

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

Line: 43

              final class FieldInfo implements Comparable<FieldInfo> {
  private final Field field;
  private final FieldType type;
  private final Class<?> messageClass; // The message type for repeated message fields.
  private final int fieldNumber;
  private final Field presenceField;
  private final int presenceMask;
  private final boolean required;
  private final boolean enforceUtf8;

            

Reported by PMD.

The String literal 'field' appears 8 times in this file; the first occurrence is on line 67
Error

Line: 67

                public static FieldInfo forField(
      Field field, int fieldNumber, FieldType fieldType, boolean enforceUtf8) {
    checkFieldNumber(fieldNumber);
    checkNotNull(field, "field");
    checkNotNull(fieldType, "fieldType");
    if (fieldType == FieldType.MESSAGE_LIST || fieldType == FieldType.GROUP_LIST) {
      throw new IllegalStateException("Shouldn't be called for repeated message fields.");
    }
    return new FieldInfo(

            

Reported by PMD.

The String literal 'fieldType' appears 6 times in this file; the first occurrence is on line 68
Error

Line: 68

                    Field field, int fieldNumber, FieldType fieldType, boolean enforceUtf8) {
    checkFieldNumber(fieldNumber);
    checkNotNull(field, "field");
    checkNotNull(fieldType, "fieldType");
    if (fieldType == FieldType.MESSAGE_LIST || fieldType == FieldType.GROUP_LIST) {
      throw new IllegalStateException("Shouldn't be called for repeated message fields.");
    }
    return new FieldInfo(
        field,

            

Reported by PMD.

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

Line: 450

                }

  /** A builder for {@link FieldInfo} instances. */
  public static final class Builder {
    private Field field;
    private FieldType type;
    private int fieldNumber;
    private Field presenceField;
    private int presenceMask;

            

Reported by PMD.

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

Line: 451

              
  /** A builder for {@link FieldInfo} instances. */
  public static final class Builder {
    private Field field;
    private FieldType type;
    private int fieldNumber;
    private Field presenceField;
    private int presenceMask;
    private boolean required;

            

Reported by PMD.

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

Line: 452

                /** A builder for {@link FieldInfo} instances. */
  public static final class Builder {
    private Field field;
    private FieldType type;
    private int fieldNumber;
    private Field presenceField;
    private int presenceMask;
    private boolean required;
    private boolean enforceUtf8;

            

Reported by PMD.

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

Line: 453

                public static final class Builder {
    private Field field;
    private FieldType type;
    private int fieldNumber;
    private Field presenceField;
    private int presenceMask;
    private boolean required;
    private boolean enforceUtf8;
    private OneofInfo oneof;

            

Reported by PMD.

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

Line: 454

                  private Field field;
    private FieldType type;
    private int fieldNumber;
    private Field presenceField;
    private int presenceMask;
    private boolean required;
    private boolean enforceUtf8;
    private OneofInfo oneof;
    private Class<?> oneofStoredType;

            

Reported by PMD.