The following issues were found

java/core/src/main/java/com/google/protobuf/UnknownFieldSetSchema.java
9 issues
This class has too many methods, consider refactoring it.
Design

Line: 35

              
import java.io.IOException;

class UnknownFieldSetSchema extends UnknownFieldSchema<UnknownFieldSet, UnknownFieldSet.Builder> {

  private final boolean proto3;

  public UnknownFieldSetSchema(boolean proto3) {
    this.proto3 = proto3;

            

Reported by PMD.

Perhaps 'proto3' could be replaced by a local variable.
Design

Line: 37

              
class UnknownFieldSetSchema extends UnknownFieldSchema<UnknownFieldSet, UnknownFieldSet.Builder> {

  private final boolean proto3;

  public UnknownFieldSetSchema(boolean proto3) {
    this.proto3 = proto3;
  }


            

Reported by PMD.

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

Line: 37

              
class UnknownFieldSetSchema extends UnknownFieldSchema<UnknownFieldSet, UnknownFieldSet.Builder> {

  private final boolean proto3;

  public UnknownFieldSetSchema(boolean proto3) {
    this.proto3 = proto3;
  }


            

Reported by PMD.

Avoid unused private fields such as 'proto3'.
Design

Line: 37

              
class UnknownFieldSetSchema extends UnknownFieldSchema<UnknownFieldSet, UnknownFieldSet.Builder> {

  private final boolean proto3;

  public UnknownFieldSetSchema(boolean proto3) {
    this.proto3 = proto3;
  }


            

Reported by PMD.

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

Line: 55

              
  @Override
  void addVarint(UnknownFieldSet.Builder fields, int number, long value) {
    fields.mergeField(number, UnknownFieldSet.Field.newBuilder().addVarint(value).build());
  }

  @Override
  void addFixed32(UnknownFieldSet.Builder fields, int number, int value) {
    fields.mergeField(number, UnknownFieldSet.Field.newBuilder().addFixed32(value).build());

            

Reported by PMD.

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

Line: 60

              
  @Override
  void addFixed32(UnknownFieldSet.Builder fields, int number, int value) {
    fields.mergeField(number, UnknownFieldSet.Field.newBuilder().addFixed32(value).build());
  }

  @Override
  void addFixed64(UnknownFieldSet.Builder fields, int number, long value) {
    fields.mergeField(number, UnknownFieldSet.Field.newBuilder().addFixed64(value).build());

            

Reported by PMD.

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

Line: 65

              
  @Override
  void addFixed64(UnknownFieldSet.Builder fields, int number, long value) {
    fields.mergeField(number, UnknownFieldSet.Field.newBuilder().addFixed64(value).build());
  }

  @Override
  void addLengthDelimited(UnknownFieldSet.Builder fields, int number, ByteString value) {
    fields.mergeField(number, UnknownFieldSet.Field.newBuilder().addLengthDelimited(value).build());

            

Reported by PMD.

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

Line: 70

              
  @Override
  void addLengthDelimited(UnknownFieldSet.Builder fields, int number, ByteString value) {
    fields.mergeField(number, UnknownFieldSet.Field.newBuilder().addLengthDelimited(value).build());
  }

  @Override
  void addGroup(UnknownFieldSet.Builder fields, int number, UnknownFieldSet subFieldSet) {
    fields.mergeField(number, UnknownFieldSet.Field.newBuilder().addGroup(subFieldSet).build());

            

Reported by PMD.

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

Line: 75

              
  @Override
  void addGroup(UnknownFieldSet.Builder fields, int number, UnknownFieldSet subFieldSet) {
    fields.mergeField(number, UnknownFieldSet.Field.newBuilder().addGroup(subFieldSet).build());
  }

  @Override
  UnknownFieldSet toImmutable(UnknownFieldSet.Builder fields) {
    return fields.build();

            

Reported by PMD.

src/google/protobuf/repeated_field_unittest.cc
8 issues
syntax error
Error

Line: 68

              using ::protobuf_unittest::TestAllTypes;
using ::testing::ElementsAre;

TEST(RepeatedField, ConstInit) {
  PROTOBUF_CONSTINIT static RepeatedField<int> field{};  // NOLINT
  EXPECT_TRUE(field.empty());
}

// Test operations on a small RepeatedField.

            

Reported by Cppcheck.

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

Line: 2102 Column: 27 CWE codes: 120

                TestAllTypes goldenproto;
  for (int i = 0; i < 10; ++i) {
    std::string* new_data = new std::string;
    *new_data = "name-" + StrCat(i);
    data.push_back(new_data);

    new_data = goldenproto.add_repeated_string();
    *new_data = "name-" + StrCat(i);
  }

            

Reported by FlawFinder.

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

Line: 2106 Column: 27 CWE codes: 120

                  data.push_back(new_data);

    new_data = goldenproto.add_repeated_string();
    *new_data = "name-" + StrCat(i);
  }
  TestAllTypes testproto;
  std::copy(data.begin(), data.end(),
            AllocatedRepeatedPtrFieldBackInserter(
                testproto.mutable_repeated_string()));

            

Reported by FlawFinder.

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

Line: 2139 Column: 27 CWE codes: 120

                auto* goldenproto = Arena::CreateMessage<TestAllTypes>(&arena);
  for (int i = 0; i < 10; ++i) {
    auto* new_data = goldenproto->add_repeated_string();
    *new_data = "name-" + StrCat(i);
    data.push_back(new_data);
  }
  auto* testproto = Arena::CreateMessage<TestAllTypes>(&arena);
  std::copy(data.begin(), data.end(),
            UnsafeArenaAllocatedRepeatedPtrFieldBackInserter(

            

Reported by FlawFinder.

equal - Function does not check the second iterator for over-read conditions
Security

Line: 2032 Column: 20 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

              };

TEST_F(RepeatedFieldInsertionIteratorsTest, Fibonacci) {
  EXPECT_TRUE(std::equal(fibonacci.begin(), fibonacci.end(),
                         protobuffer.repeated_int32().begin()));
  EXPECT_TRUE(std::equal(protobuffer.repeated_int32().begin(),
                         protobuffer.repeated_int32().end(),
                         fibonacci.begin()));
}

            

Reported by FlawFinder.

equal - Function does not check the second iterator for over-read conditions
Security

Line: 2034 Column: 20 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

              TEST_F(RepeatedFieldInsertionIteratorsTest, Fibonacci) {
  EXPECT_TRUE(std::equal(fibonacci.begin(), fibonacci.end(),
                         protobuffer.repeated_int32().begin()));
  EXPECT_TRUE(std::equal(protobuffer.repeated_int32().begin(),
                         protobuffer.repeated_int32().end(),
                         fibonacci.begin()));
}

TEST_F(RepeatedFieldInsertionIteratorsTest, Halves) {

            

Reported by FlawFinder.

equal - Function does not check the second iterator for over-read conditions
Security

Line: 2040 Column: 20 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

              }

TEST_F(RepeatedFieldInsertionIteratorsTest, Halves) {
  EXPECT_TRUE(std::equal(halves.begin(), halves.end(),
                         protobuffer.repeated_double().begin()));
  EXPECT_TRUE(std::equal(protobuffer.repeated_double().begin(),
                         protobuffer.repeated_double().end(), halves.begin()));
}


            

Reported by FlawFinder.

equal - Function does not check the second iterator for over-read conditions
Security

Line: 2042 Column: 20 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

              TEST_F(RepeatedFieldInsertionIteratorsTest, Halves) {
  EXPECT_TRUE(std::equal(halves.begin(), halves.end(),
                         protobuffer.repeated_double().begin()));
  EXPECT_TRUE(std::equal(protobuffer.repeated_double().begin(),
                         protobuffer.repeated_double().end(), halves.begin()));
}

TEST_F(RepeatedFieldInsertionIteratorsTest, Words) {
  ASSERT_EQ(words.size(), protobuffer.repeated_string_size());

            

Reported by FlawFinder.

src/google/protobuf/util/internal/field_mask_utility.cc
8 issues
StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 59 Column: 12 CWE codes: 120

                }
  // If the segment is a map key, appends it to the prefix without the ".".
  if (HasPrefixString(segment, "[\"")) {
    return StrCat(prefix, segment);
  }
  return StrCat(prefix, ".", segment);
}

}  // namespace

            

Reported by FlawFinder.

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

Line: 61 Column: 10 CWE codes: 120

                if (HasPrefixString(segment, "[\"")) {
    return StrCat(prefix, segment);
  }
  return StrCat(prefix, ".", segment);
}

}  // namespace

std::string ConvertFieldMaskPath(const StringPiece path,

            

Reported by FlawFinder.

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

Line: 137 Column: 45 CWE codes: 120

                      }
        // Un-escaped '"' must be followed with a ']'.
        if (i >= length - 1 || paths[i + 1] != ']') {
          return util::InvalidArgumentError(StrCat(
              "Invalid FieldMask '", paths,
              "'. Map keys should be represented as [\"some_key\"]."));
        }
        // The end of the map key ("\"]") has been found.
        in_map_key = false;

            

Reported by FlawFinder.

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

Line: 148 Column: 45 CWE codes: 120

                      // Checks whether the key ends at the end of a path segment.
        if (i < length - 1 && paths[i + 1] != '.' && paths[i + 1] != ',' &&
            paths[i + 1] != ')' && paths[i + 1] != '(') {
          return util::InvalidArgumentError(StrCat(
              "Invalid FieldMask '", paths,
              "'. Map keys should be at the end of a path segment."));
        }
        is_escaping = false;
        continue;

            

Reported by FlawFinder.

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

Line: 159 Column: 45 CWE codes: 120

                    // We are not in a map key, look for the start of one.
      if (paths[i] == '[') {
        if (i >= length - 1 || paths[i + 1] != '\"') {
          return util::InvalidArgumentError(StrCat(
              "Invalid FieldMask '", paths,
              "'. Map keys should be represented as [\"some_key\"]."));
        }
        // "[\"" starts a map key.
        in_map_key = true;

            

Reported by FlawFinder.

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

Line: 195 Column: 13 CWE codes: 120

                  if (i < length && paths[i] == ')') {
      if (prefix.empty()) {
        return util::InvalidArgumentError(
            StrCat("Invalid FieldMask '", paths,
                         "'. Cannot find matching '(' for all ')'."));
      }
      prefix.pop();
    }
    previous_position = i + 1;

            

Reported by FlawFinder.

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

Line: 204 Column: 9 CWE codes: 120

                }
  if (in_map_key) {
    return util::InvalidArgumentError(
        StrCat("Invalid FieldMask '", paths,
                     "'. Cannot find matching ']' for all '['."));
  }
  if (!prefix.empty()) {
    return util::InvalidArgumentError(
        StrCat("Invalid FieldMask '", paths,

            

Reported by FlawFinder.

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

Line: 209 Column: 9 CWE codes: 120

                }
  if (!prefix.empty()) {
    return util::InvalidArgumentError(
        StrCat("Invalid FieldMask '", paths,
                     "'. Cannot find matching ')' for all '('."));
  }
  return util::Status();
}


            

Reported by FlawFinder.

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

Line: 54

              
  // Defines a mapping between each field's descriptor to the list of locations where
  // its value(s) were was encountered.
  private Map<FieldDescriptor, List<TextFormatParseLocation>> locationsFromField;

  // Defines a mapping between a field's descriptor to a list of TextFormatParseInfoTrees for
  // sub message location information.
  Map<FieldDescriptor, List<TextFormatParseInfoTree>> subtreesFromField;


            

Reported by PMD.

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

Line: 54

              
  // Defines a mapping between each field's descriptor to the list of locations where
  // its value(s) were was encountered.
  private Map<FieldDescriptor, List<TextFormatParseLocation>> locationsFromField;

  // Defines a mapping between a field's descriptor to a list of TextFormatParseInfoTrees for
  // sub message location information.
  Map<FieldDescriptor, List<TextFormatParseInfoTree>> subtreesFromField;


            

Reported by PMD.

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

Line: 58

              
  // Defines a mapping between a field's descriptor to a list of TextFormatParseInfoTrees for
  // sub message location information.
  Map<FieldDescriptor, List<TextFormatParseInfoTree>> subtreesFromField;

  /**
   * Construct a {@code TextFormatParseInfoTree}.
   *
   * @param locationsFromField a map of fields to location in the source code

            

Reported by PMD.

Avoid instantiating new objects inside loops
Performance

Line: 81

                  Map<FieldDescriptor, List<TextFormatParseInfoTree>> subs =
        new HashMap<FieldDescriptor, List<TextFormatParseInfoTree>>();
    for (Entry<FieldDescriptor, List<Builder>> kv : subtreeBuildersFromField.entrySet()) {
      List<TextFormatParseInfoTree> submessagesOfField = new ArrayList<TextFormatParseInfoTree>();
      for (Builder subBuilder : kv.getValue()) {
        submessagesOfField.add(subBuilder.build());
      }
      subs.put(kv.getKey(), Collections.unmodifiableList(submessagesOfField));
    }

            

Reported by PMD.

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

Line: 163

                /** Builder for a {@link TextFormatParseInfoTree}. */
  public static class Builder {

    private Map<FieldDescriptor, List<TextFormatParseLocation>> locationsFromField;

    // Defines a mapping between a field's descriptor to a list of ParseInfoTrees builders for
    // sub message location information.
    private Map<FieldDescriptor, List<Builder>> subtreeBuildersFromField;


            

Reported by PMD.

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

Line: 163

                /** Builder for a {@link TextFormatParseInfoTree}. */
  public static class Builder {

    private Map<FieldDescriptor, List<TextFormatParseLocation>> locationsFromField;

    // Defines a mapping between a field's descriptor to a list of ParseInfoTrees builders for
    // sub message location information.
    private Map<FieldDescriptor, List<Builder>> subtreeBuildersFromField;


            

Reported by PMD.

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

Line: 167

              
    // Defines a mapping between a field's descriptor to a list of ParseInfoTrees builders for
    // sub message location information.
    private Map<FieldDescriptor, List<Builder>> subtreeBuildersFromField;

    /** Create a root level {@ParseInfoTree} builder. */
    private Builder() {
      locationsFromField = new HashMap<FieldDescriptor, List<TextFormatParseLocation>>();
      subtreeBuildersFromField = new HashMap<FieldDescriptor, List<Builder>>();

            

Reported by PMD.

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

Line: 167

              
    // Defines a mapping between a field's descriptor to a list of ParseInfoTrees builders for
    // sub message location information.
    private Map<FieldDescriptor, List<Builder>> subtreeBuildersFromField;

    /** Create a root level {@ParseInfoTree} builder. */
    private Builder() {
      locationsFromField = new HashMap<FieldDescriptor, List<TextFormatParseLocation>>();
      subtreeBuildersFromField = new HashMap<FieldDescriptor, List<Builder>>();

            

Reported by PMD.

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

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

                  if (PROTOBUF_PREDICT_FALSE(end_ - ptr < size)) {
      return WriteRawFallback(data, size, ptr);
    }
    std::memcpy(ptr, data, size);
    return ptr + size;
  }
  // Writes the buffer specified by data, size to the stream. Possibly by
  // aliasing the buffer (ie. not copying the data). The caller is responsible
  // to make sure the buffer is alive for the duration of the

            

Reported by FlawFinder.

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

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

                  }
    ptr = UnsafeVarint((num << 3) | 2, ptr);
    *ptr++ = static_cast<uint8_t>(size);
    std::memcpy(ptr, s.data(), size);
    return ptr + size;
  }
  uint8_t* WriteBytesMaybeAliased(uint32_t num, const std::string& s, uint8_t* ptr) {
    return WriteStringMaybeAliased(num, s, ptr);
  }

            

Reported by FlawFinder.

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

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

                  }
    ptr = UnsafeVarint((num << 3) | 2, ptr);
    *ptr++ = static_cast<uint8_t>(size);
    std::memcpy(ptr, s.data(), size);
    return ptr + size;
  }
  template <typename T>
  uint8_t* WriteBytes(uint32_t num, const T& s, uint8_t* ptr) {
    return WriteString(num, s, ptr);

            

Reported by FlawFinder.

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

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

              inline const uint8_t* CodedInputStream::ReadLittleEndian32FromArray(
    const uint8_t* buffer, uint32_t* value) {
#if defined(PROTOBUF_LITTLE_ENDIAN)
  memcpy(value, buffer, sizeof(*value));
  return buffer + sizeof(*value);
#else
  *value = (static_cast<uint32_t>(buffer[0])) |
           (static_cast<uint32_t>(buffer[1]) << 8) |
           (static_cast<uint32_t>(buffer[2]) << 16) |

            

Reported by FlawFinder.

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

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

              inline const uint8_t* CodedInputStream::ReadLittleEndian64FromArray(
    const uint8_t* buffer, uint64_t* value) {
#if defined(PROTOBUF_LITTLE_ENDIAN)
  memcpy(value, buffer, sizeof(*value));
  return buffer + sizeof(*value);
#else
  uint32_t part0 = (static_cast<uint32_t>(buffer[0])) |
                 (static_cast<uint32_t>(buffer[1]) << 8) |
                 (static_cast<uint32_t>(buffer[2]) << 16) |

            

Reported by FlawFinder.

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

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

              inline uint8_t* CodedOutputStream::WriteLittleEndian32ToArray(uint32_t value,
                                                            uint8_t* target) {
#if defined(PROTOBUF_LITTLE_ENDIAN)
  memcpy(target, &value, sizeof(value));
#else
  target[0] = static_cast<uint8_t>(value);
  target[1] = static_cast<uint8_t>(value >> 8);
  target[2] = static_cast<uint8_t>(value >> 16);
  target[3] = static_cast<uint8_t>(value >> 24);

            

Reported by FlawFinder.

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

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

              inline uint8_t* CodedOutputStream::WriteLittleEndian64ToArray(uint64_t value,
                                                            uint8_t* target) {
#if defined(PROTOBUF_LITTLE_ENDIAN)
  memcpy(target, &value, sizeof(value));
#else
  uint32_t part0 = static_cast<uint32_t>(value);
  uint32_t part1 = static_cast<uint32_t>(value >> 32);

  target[0] = static_cast<uint8_t>(part0);

            

Reported by FlawFinder.

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

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

              
inline uint8_t* CodedOutputStream::WriteRawToArray(const void* data, int size,
                                                 uint8_t* target) {
  memcpy(target, data, size);
  return target + size;
}

inline uint8_t* CodedOutputStream::WriteStringToArray(const std::string& str,
                                                    uint8_t* target) {

            

Reported by FlawFinder.

src/google/protobuf/stubs/stringprintf.cc
8 issues
va_list 'backup_ap' used before va_start() was called.
Error

Line: 66 CWE codes: 664

                // the data in it upon use.  The fix is to make a copy
  // of the structure before using it and use that copy instead.
  va_list backup_ap;
  va_copy(backup_ap, ap);
  int result = vsnprintf(space, kSpaceLength, format, backup_ap);
  va_end(backup_ap);

  if (result < kSpaceLength) {
    if (result >= 0) {

            

Reported by Cppcheck.

va_list 'backup_ap' used before va_start() was called.
Error

Line: 67 CWE codes: 664

                // of the structure before using it and use that copy instead.
  va_list backup_ap;
  va_copy(backup_ap, ap);
  int result = vsnprintf(space, kSpaceLength, format, backup_ap);
  va_end(backup_ap);

  if (result < kSpaceLength) {
    if (result >= 0) {
      // Normal case -- everything fit.

            

Reported by Cppcheck.

va_list 'backup_ap' used before va_start() was called.
Error

Line: 68 CWE codes: 664

                va_list backup_ap;
  va_copy(backup_ap, ap);
  int result = vsnprintf(space, kSpaceLength, format, backup_ap);
  va_end(backup_ap);

  if (result < kSpaceLength) {
    if (result >= 0) {
      // Normal case -- everything fit.
      dst->append(space, result);

            

Reported by Cppcheck.

vsnprintf - If format strings can be influenced by an attacker, they can be exploited, and note that sprintf variations do not always \0-terminate
Security

Line: 67 Column: 16 CWE codes: 134
Suggestion: Use a constant for the format specification

                // of the structure before using it and use that copy instead.
  va_list backup_ap;
  va_copy(backup_ap, ap);
  int result = vsnprintf(space, kSpaceLength, format, backup_ap);
  va_end(backup_ap);

  if (result < kSpaceLength) {
    if (result >= 0) {
      // Normal case -- everything fit.

            

Reported by FlawFinder.

vsnprintf - If format strings can be influenced by an attacker, they can be exploited, and note that sprintf variations do not always \0-terminate
Security

Line: 81 Column: 16 CWE codes: 134
Suggestion: Use a constant for the format specification

                    // Error or MSVC running out of space.  MSVC 8.0 and higher
      // can be asked about space needed with the special idiom below:
      va_copy(backup_ap, ap);
      result = vsnprintf(nullptr, 0, format, backup_ap);
      va_end(backup_ap);
    }

    if (result < 0) {
      // Just an error.

            

Reported by FlawFinder.

vsnprintf - If format strings can be influenced by an attacker, they can be exploited, and note that sprintf variations do not always \0-terminate
Security

Line: 98 Column: 12 CWE codes: 134
Suggestion: Use a constant for the format specification

              
  // Restore the va_list before we use it again
  va_copy(backup_ap, ap);
  result = vsnprintf(buf, length, format, backup_ap);
  va_end(backup_ap);

  if (result >= 0 && result < length) {
    // It fit
    dst->append(buf, result);

            

Reported by FlawFinder.

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

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

              void StringAppendV(std::string* dst, const char* format, va_list ap) {
  // First try with a small fixed size buffer
  static const int kSpaceLength = 1024;
  char space[kSpaceLength];

  // It's possible for methods that use a va_list to invalidate
  // the data in it upon use.  The fix is to make a copy
  // of the structure before using it and use that copy instead.
  va_list backup_ap;

            

Reported by FlawFinder.

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

Line: 139 Column: 14 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

              // An empty block of zero for filler arguments.  This is const so that if
// printf tries to write to it (via %n) then the program gets a SIGSEGV
// and we can fix the problem or protect against an attack.
static const char string_printf_empty_block[256] = { '\0' };

std::string StringPrintfVector(const char* format,
                               const std::vector<std::string>& v) {
  GOOGLE_CHECK_LE(v.size(), kStringPrintfVectorMaxArgs)
      << "StringPrintfVector currently only supports up to "

            

Reported by FlawFinder.

php/ext/google/protobuf/names.c
8 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

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

                  sink->size = new_size;
  }

  memcpy(sink->ptr + sink->len, ptr, len);
  sink->len += len;

  return len;
}


            

Reported by FlawFinder.

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

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

              static bool is_reserved(const char *segment, int length) {
  bool result;
  char* lower = calloc(1, length + 1);
  memcpy(lower, segment, length);
  int i = 0;
  while(lower[i]) {
    lower[i] = nolocale_tolower(lower[i]);
    i++;
  }

            

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: 137 Column: 48 CWE codes: 126

                                      const char *package_name,
                        stringsink *classname) {
  if (prefix_given != NULL && strcmp(prefix_given, "") != 0) {
    stringsink_string(classname, prefix_given, strlen(prefix_given));
  } else {
    if (is_reserved(segment, length)) {
      if (package_name != NULL &&
          strcmp("google.protobuf", package_name) == 0) {
        stringsink_string(classname, "GPB", 3);

            

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: 164 Column: 9 CWE codes: 126

              static void fill_namespace(const char *package, const char *php_namespace,
                           stringsink *classname) {
  if (php_namespace != NULL) {
    if (strlen(php_namespace) != 0) {
      stringsink_string(classname, php_namespace, strlen(php_namespace));
      stringsink_string(classname, "\\", 1);
    }
  } else if (package != NULL) {
    int i = 0, j = 0;

            

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: 165 Column: 51 CWE codes: 126

                                         stringsink *classname) {
  if (php_namespace != NULL) {
    if (strlen(php_namespace) != 0) {
      stringsink_string(classname, php_namespace, strlen(php_namespace));
      stringsink_string(classname, "\\", 1);
    }
  } else if (package != NULL) {
    int i = 0, j = 0;
    size_t package_len = strlen(package);

            

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: 170 Column: 26 CWE codes: 126

                  }
  } else if (package != NULL) {
    int i = 0, j = 0;
    size_t package_len = strlen(package);
    while (i < package_len) {
      j = i;
      while (j < package_len && package[j] != '.') {
        j++;
      }

            

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: 190 Column: 26 CWE codes: 126

                                         stringsink *classname) {
  int classname_start = 0;
  if (package != NULL) {
    size_t package_len = strlen(package);
    classname_start = package_len == 0 ? 0 : package_len + 1;
  }
  size_t fullname_len = strlen(fullname);

  int i = classname_start, j;

            

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: 193 Column: 25 CWE codes: 126

                  size_t package_len = strlen(package);
    classname_start = package_len == 0 ? 0 : package_len + 1;
  }
  size_t fullname_len = strlen(fullname);

  int i = classname_start, j;
  while (i < fullname_len) {
    j = i;
    while (j < fullname_len && fullname[j] != '.') {

            

Reported by FlawFinder.

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

Line: 44

                private Utf8Utils() {}

  static class MaxCodePoint {
    final int value;

    /**
     * Convert the input string to a code point. Accepts regular decimal numerals, hex strings, and
     * some symbolic names meaningful to humans.
     */

            

Reported by PMD.

New exception is thrown in catch block, original stack trace may be lost
Design

Line: 71

                        // Mostly 4-byte UTF-8 sequences - "rare exotic" text
          return Character.MAX_CODE_POINT;
        } else {
          throw new IllegalArgumentException("Can't decode codepoint " + userFriendly);
        }
      }
    }

    public static MaxCodePoint valueOf(String userFriendly) {

            

Reported by PMD.

Avoid instantiating new objects inside loops
Performance

Line: 167

                  final Random rnd = new Random(seed);
    String[] strings = new String[stringCount];
    for (int i = 0; i < stringCount; i++) {
      StringBuilder sb = new StringBuilder();
      for (int j = 0; j < charCount; j++) {
        int codePoint;
        do {
          codePoint = rnd.nextInt(distribution[3]);
          if (codePoint < distribution[0]) {

            

Reported by PMD.

Found 'DU'-anomaly for variable 'rnd' (lines '119'-'125').
Error

Line: 119

                 */
  static String[] randomStrings(int stringCount, int charCount, MaxCodePoint maxCodePoint) {
    final long seed = 99;
    final Random rnd = new Random(seed);
    String[] strings = new String[stringCount];
    for (int i = 0; i < stringCount; i++) {
      strings[i] = randomString(rnd, charCount, maxCodePoint);
    }
    return strings;

            

Reported by PMD.

Found 'DD'-anomaly for variable 'strings' (lines '120'-'122').
Error

Line: 120

                static String[] randomStrings(int stringCount, int charCount, MaxCodePoint maxCodePoint) {
    final long seed = 99;
    final Random rnd = new Random(seed);
    String[] strings = new String[stringCount];
    for (int i = 0; i < stringCount; i++) {
      strings[i] = randomString(rnd, charCount, maxCodePoint);
    }
    return strings;
  }

            

Reported by PMD.

Found 'DD'-anomaly for variable 'strings' (lines '122'-'122').
Error

Line: 122

                  final Random rnd = new Random(seed);
    String[] strings = new String[stringCount];
    for (int i = 0; i < stringCount; i++) {
      strings[i] = randomString(rnd, charCount, maxCodePoint);
    }
    return strings;
  }

  /**

            

Reported by PMD.

Found 'DD'-anomaly for variable 'strings' (lines '165'-'189').
Error

Line: 165

                  }
    final long seed = 99;
    final Random rnd = new Random(seed);
    String[] strings = new String[stringCount];
    for (int i = 0; i < stringCount; i++) {
      StringBuilder sb = new StringBuilder();
      for (int j = 0; j < charCount; j++) {
        int codePoint;
        do {

            

Reported by PMD.

Found 'DD'-anomaly for variable 'strings' (lines '189'-'189').
Error

Line: 189

                      } while (Utf8Utils.isSurrogate(codePoint));
        sb.appendCodePoint(codePoint);
      }
      strings[i] = sb.toString();
    }
    return strings;
  }
}

            

Reported by PMD.

src/google/protobuf/util/message_differencer.cc
8 issues
Uninitialized variable: differencer
Error

Line: 259 CWE codes: 908

                                              const Message& message2) {
  MessageDifferencer differencer;

  return differencer.Compare(message1, message2);
}

bool MessageDifferencer::Equivalent(const Message& message1,
                                    const Message& message2) {
  MessageDifferencer differencer;

            

Reported by Cppcheck.

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

Line: 1975 Column: 26 CWE codes: 120

                      continue;
      }
    } else {
      printer_->PrintRaw(StrCat(specific_field.unknown_field_number));
    }
    if (left_side && specific_field.index >= 0) {
      printer_->Print("[$name$]", "name", StrCat(specific_field.index));
    }
    if (!left_side && specific_field.new_index >= 0) {

            

Reported by FlawFinder.

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

Line: 1978 Column: 43 CWE codes: 120

                    printer_->PrintRaw(StrCat(specific_field.unknown_field_number));
    }
    if (left_side && specific_field.index >= 0) {
      printer_->Print("[$name$]", "name", StrCat(specific_field.index));
    }
    if (!left_side && specific_field.new_index >= 0) {
      printer_->Print("[$name$]", "name",
                      StrCat(specific_field.new_index));
    }

            

Reported by FlawFinder.

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

Line: 1982 Column: 23 CWE codes: 120

                  }
    if (!left_side && specific_field.new_index >= 0) {
      printer_->Print("[$name$]", "name",
                      StrCat(specific_field.new_index));
    }
  }
}



            

Reported by FlawFinder.

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

Line: 2048 Column: 16 CWE codes: 120

                std::string output;
  switch (unknown_field->type()) {
    case UnknownField::TYPE_VARINT:
      output = StrCat(unknown_field->varint());
      break;
    case UnknownField::TYPE_FIXED32:
      output = StrCat(
          "0x", strings::Hex(unknown_field->fixed32(), strings::ZERO_PAD_8));
      break;

            

Reported by FlawFinder.

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

Line: 2051 Column: 16 CWE codes: 120

                    output = StrCat(unknown_field->varint());
      break;
    case UnknownField::TYPE_FIXED32:
      output = StrCat(
          "0x", strings::Hex(unknown_field->fixed32(), strings::ZERO_PAD_8));
      break;
    case UnknownField::TYPE_FIXED64:
      output = StrCat(
          "0x", strings::Hex(unknown_field->fixed64(), strings::ZERO_PAD_16));

            

Reported by FlawFinder.

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

Line: 2055 Column: 16 CWE codes: 120

                        "0x", strings::Hex(unknown_field->fixed32(), strings::ZERO_PAD_8));
      break;
    case UnknownField::TYPE_FIXED64:
      output = StrCat(
          "0x", strings::Hex(unknown_field->fixed64(), strings::ZERO_PAD_16));
      break;
    case UnknownField::TYPE_LENGTH_DELIMITED:
      output = StringPrintf(
          "\"%s\"", CEscape(unknown_field->length_delimited()).c_str());

            

Reported by FlawFinder.

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

Line: 2102 Column: 24 CWE codes: 120

                  if (key_string.empty()) {
      key_string = "''";
    }
    printer_->PrintRaw(StrCat("[", key_string, "]"));
  }
}

void MessageDifferencer::StreamReporter::ReportAdded(
    const Message& message1, const Message& message2,

            

Reported by FlawFinder.

java/core/src/main/java/com/google/protobuf/AllocatedBuffer.java
8 issues
The class 'AllocatedBuffer' has a Modified Cyclomatic Complexity of 3 (Highest = 11).
Design

Line: 42

               * at least one of {@link #hasArray()} or {@link #hasNioBuffer()} will be {@code true}.
 */
@ExperimentalApi
abstract class AllocatedBuffer {
  /**
   * Indicates whether this buffer contains a backing {@link ByteBuffer} (i.e. it is safe to call
   * {@link #nioBuffer()}).
   */
  public abstract boolean hasNioBuffer();

            

Reported by PMD.

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

Line: 42

               * at least one of {@link #hasArray()} or {@link #hasNioBuffer()} will be {@code true}.
 */
@ExperimentalApi
abstract class AllocatedBuffer {
  /**
   * Indicates whether this buffer contains a backing {@link ByteBuffer} (i.e. it is safe to call
   * {@link #nioBuffer()}).
   */
  public abstract boolean hasNioBuffer();

            

Reported by PMD.

The class 'AllocatedBuffer' has a Standard Cyclomatic Complexity of 3 (Highest = 11).
Design

Line: 42

               * at least one of {@link #hasArray()} or {@link #hasNioBuffer()} will be {@code true}.
 */
@ExperimentalApi
abstract class AllocatedBuffer {
  /**
   * Indicates whether this buffer contains a backing {@link ByteBuffer} (i.e. it is safe to call
   * {@link #nioBuffer()}).
   */
  public abstract boolean hasNioBuffer();

            

Reported by PMD.

The method 'wrap' has a Standard Cyclomatic Complexity of 10.
Design

Line: 153

                 * Creates a new {@link AllocatedBuffer} that is backed by the given {@link ByteBuffer}. The
   * returned buffer will have {@link #hasNioBuffer} == {@code true}.
   */
  public static AllocatedBuffer wrap(final ByteBuffer buffer) {
    checkNotNull(buffer, "buffer");

    return new AllocatedBuffer() {

      @Override

            

Reported by PMD.

The method 'wrap' has a Modified Cyclomatic Complexity of 10.
Design

Line: 153

                 * Creates a new {@link AllocatedBuffer} that is backed by the given {@link ByteBuffer}. The
   * returned buffer will have {@link #hasNioBuffer} == {@code true}.
   */
  public static AllocatedBuffer wrap(final ByteBuffer buffer) {
    checkNotNull(buffer, "buffer");

    return new AllocatedBuffer() {

      @Override

            

Reported by PMD.

The method 'wrapNoCheck' has a Standard Cyclomatic Complexity of 11.
Design

Line: 206

                  };
  }

  private static AllocatedBuffer wrapNoCheck(
      final byte[] bytes, final int offset, final int length) {
    return new AllocatedBuffer() {
      // Relative to offset.
      private int position;


            

Reported by PMD.

The method 'wrapNoCheck' has a Modified Cyclomatic Complexity of 11.
Design

Line: 206

                  };
  }

  private static AllocatedBuffer wrapNoCheck(
      final byte[] bytes, final int offset, final int length) {
    return new AllocatedBuffer() {
      // Relative to offset.
      private int position;


            

Reported by PMD.

Field position has the same name as a method
Error

Line: 210

                    final byte[] bytes, final int offset, final int length) {
    return new AllocatedBuffer() {
      // Relative to offset.
      private int position;

      @Override
      public boolean hasNioBuffer() {
        return false;
      }

            

Reported by PMD.