The following issues were found

java/core/src/main/java/com/google/protobuf/NewInstanceSchemas.java
4 issues
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: 33

              
package com.google.protobuf;

final class NewInstanceSchemas {
  private static final NewInstanceSchema FULL_SCHEMA = loadSchemaForFullRuntime();
  private static final NewInstanceSchema LITE_SCHEMA = new NewInstanceSchemaLite();

  static NewInstanceSchema full() {
    return FULL_SCHEMA;

            

Reported by PMD.

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

Line: 48

                private static NewInstanceSchema loadSchemaForFullRuntime() {
    try {
      Class<?> clazz = Class.forName("com.google.protobuf.NewInstanceSchemaFull");
      return (NewInstanceSchema) clazz.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
      return null;
    }
  }
}

            

Reported by PMD.

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

Line: 48

                private static NewInstanceSchema loadSchemaForFullRuntime() {
    try {
      Class<?> clazz = Class.forName("com.google.protobuf.NewInstanceSchemaFull");
      return (NewInstanceSchema) clazz.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
      return null;
    }
  }
}

            

Reported by PMD.

Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block
Design

Line: 49

                  try {
      Class<?> clazz = Class.forName("com.google.protobuf.NewInstanceSchemaFull");
      return (NewInstanceSchema) clazz.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
      return null;
    }
  }
}

            

Reported by PMD.

java/core/src/main/java/com/google/protobuf/MapFieldSchemas.java
4 issues
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: 33

              
package com.google.protobuf;

final class MapFieldSchemas {
  private static final MapFieldSchema FULL_SCHEMA = loadSchemaForFullRuntime();
  private static final MapFieldSchema LITE_SCHEMA = new MapFieldSchemaLite();

  static MapFieldSchema full() {
    return FULL_SCHEMA;

            

Reported by PMD.

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

Line: 48

                private static MapFieldSchema loadSchemaForFullRuntime() {
    try {
      Class<?> clazz = Class.forName("com.google.protobuf.MapFieldSchemaFull");
      return (MapFieldSchema) clazz.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
      return null;
    }
  }
}

            

Reported by PMD.

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

Line: 48

                private static MapFieldSchema loadSchemaForFullRuntime() {
    try {
      Class<?> clazz = Class.forName("com.google.protobuf.MapFieldSchemaFull");
      return (MapFieldSchema) clazz.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
      return null;
    }
  }
}

            

Reported by PMD.

Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block
Design

Line: 49

                  try {
      Class<?> clazz = Class.forName("com.google.protobuf.MapFieldSchemaFull");
      return (MapFieldSchema) clazz.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
      return null;
    }
  }
}

            

Reported by PMD.

java/core/src/main/java/com/google/protobuf/MapFieldSchemaLite.java
4 issues
Potential violation of Law of Demeter (method chain calls)
Design

Line: 66

              
  @Override
  public Object newMapField(Object unused) {
    return MapFieldLite.emptyMapField().mutableCopy();
  }

  @Override
  public Object mergeFrom(Object destMapField, Object srcMapField) {
    return mergeFromLite(destMapField, srcMapField);

            

Reported by PMD.

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

Line: 78

                private static <K, V> MapFieldLite<K, V> mergeFromLite(Object destMapField, Object srcMapField) {
    MapFieldLite<K, V> mine = (MapFieldLite<K, V>) destMapField;
    MapFieldLite<K, V> other = (MapFieldLite<K, V>) srcMapField;
    if (!other.isEmpty()) {
      if (!mine.isMutable()) {
        mine = mine.mutableCopy();
      }
      mine.mergeFrom(other);
    }

            

Reported by PMD.

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

Line: 98

                  MapFieldLite<K, V> mapFieldLite = (MapFieldLite<K, V>) mapField;
    MapEntryLite<K, V> defaultEntryLite = (MapEntryLite<K, V>) defaultEntry;

    if (mapFieldLite.isEmpty()) {
      return 0;
    }
    int size = 0;
    for (Map.Entry<K, V> entry : mapFieldLite.entrySet()) {
      size += defaultEntryLite.computeMessageSize(fieldNumber, entry.getKey(), entry.getValue());

            

Reported by PMD.

Found 'DU'-anomaly for variable 'defaultEntryLite' (lines '96'-'106').
Error

Line: 96

                private static <K, V> int getSerializedSizeLite(
      int fieldNumber, Object mapField, Object defaultEntry) {
    MapFieldLite<K, V> mapFieldLite = (MapFieldLite<K, V>) mapField;
    MapEntryLite<K, V> defaultEntryLite = (MapEntryLite<K, V>) defaultEntry;

    if (mapFieldLite.isEmpty()) {
      return 0;
    }
    int size = 0;

            

Reported by PMD.

java/core/src/main/java/com/google/protobuf/MapFieldSchemaFull.java
4 issues
Potential violation of Law of Demeter (object not created locally)
Design

Line: 77

                private static <K, V> Object mergeFromFull(Object destMapField, Object srcMapField) {
    MapField<K, V> mine = (MapField<K, V>) destMapField;
    MapField<K, V> other = (MapField<K, V>) srcMapField;
    if (!mine.isMutable()) {
      mine.copy();
    }
    mine.mergeFrom(other);
    return mine;
  }

            

Reported by PMD.

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

Line: 80

                  if (!mine.isMutable()) {
      mine.copy();
    }
    mine.mergeFrom(other);
    return mine;
  }

  @Override
  public int getSerializedSize(int number, Object mapField, Object mapDefaultEntry) {

            

Reported by PMD.

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

Line: 99

              
    Map<K, V> map = ((MapField<K, V>) mapField).getMap();
    MapEntry<K, V> defaultEntry = (MapEntry<K, V>) defaultEntryObject;
    if (map.isEmpty()) {
      return 0;
    }
    int size = 0;
    for (Map.Entry<K, V> entry : map.entrySet()) {
      size +=

            

Reported by PMD.

Found 'DU'-anomaly for variable 'defaultEntry' (lines '98'-'111').
Error

Line: 98

                  }

    Map<K, V> map = ((MapField<K, V>) mapField).getMap();
    MapEntry<K, V> defaultEntry = (MapEntry<K, V>) defaultEntryObject;
    if (map.isEmpty()) {
      return 0;
    }
    int size = 0;
    for (Map.Entry<K, V> entry : map.entrySet()) {

            

Reported by PMD.

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

Line: 91 Column: 29 CWE codes: 120

              
JsonObjectWriter* JsonObjectWriter::RenderInt32(StringPiece name,
                                                int32_t value) {
  return RenderSimple(name, StrCat(value));
}

JsonObjectWriter* JsonObjectWriter::RenderUint32(StringPiece name,
                                                 uint32_t value) {
  return RenderSimple(name, StrCat(value));

            

Reported by FlawFinder.

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

Line: 96 Column: 29 CWE codes: 120

              
JsonObjectWriter* JsonObjectWriter::RenderUint32(StringPiece name,
                                                 uint32_t value) {
  return RenderSimple(name, StrCat(value));
}

JsonObjectWriter* JsonObjectWriter::RenderInt64(StringPiece name,
                                                int64_t value) {
  WritePrefix(name);

            

Reported by FlawFinder.

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

Line: 103 Column: 18 CWE codes: 120

                                                              int64_t value) {
  WritePrefix(name);
  WriteChar('"');
  WriteRawString(StrCat(value));
  WriteChar('"');
  return this;
}

JsonObjectWriter* JsonObjectWriter::RenderUint64(StringPiece name,

            

Reported by FlawFinder.

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

Line: 112 Column: 18 CWE codes: 120

                                                               uint64_t value) {
  WritePrefix(name);
  WriteChar('"');
  WriteRawString(StrCat(value));
  WriteChar('"');
  return this;
}

JsonObjectWriter* JsonObjectWriter::RenderDouble(StringPiece name,

            

Reported by FlawFinder.

src/google/protobuf/io/printer.cc
4 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

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

                  // Data exceeds space in the buffer.  Copy what we can and request a
    // new buffer.
    if (buffer_size_ > 0) {
      memcpy(buffer_, data, buffer_size_);
      offset_ += buffer_size_;
      data += buffer_size_;
      size -= buffer_size_;
    }
    void* void_buffer;

            

Reported by FlawFinder.

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

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

                }

  // Buffer is big enough to receive the data; copy it.
  memcpy(buffer_, data, size);
  buffer_ += size;
  buffer_size_ -= size;
  offset_ += size;
}


            

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: 115 Column: 14 CWE codes: 126

              
void Printer::Print(const std::map<std::string, std::string>& variables,
                    const char* text) {
  int size = strlen(text);
  int pos = 0;  // The number of bytes we've written so far.
  substitutions_.clear();
  line_start_variables_.clear();

  for (int i = 0; i < size; 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: 203 Column: 18 CWE codes: 126

              
void Printer::PrintRaw(const char* data) {
  if (failed_) return;
  WriteRaw(data, strlen(data));
}

void Printer::WriteRaw(const char* data, int size) {
  if (failed_) return;
  if (size == 0) return;

            

Reported by FlawFinder.

java/core/src/main/java/com/google/protobuf/GeneratedMessageInfoFactory.java
4 issues
A class which only has private constructors should be final
Design

Line: 35

              
/** A factory for message info that is generated into the message itself. */
@ExperimentalApi
class GeneratedMessageInfoFactory implements MessageInfoFactory {

  private static final GeneratedMessageInfoFactory instance = new GeneratedMessageInfoFactory();

  // Disallow construction - it's a singleton.
  private GeneratedMessageInfoFactory() {}

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 62

                        messageType.asSubclass(GeneratedMessageLite.class))
          .buildMessageInfo();
    } catch (Exception e) {
      throw new RuntimeException("Unable to get message info for " + messageType.getName(), e);
    }
  }
}

            

Reported by PMD.

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

Line: 58

                  }

    try {
      return (MessageInfo) GeneratedMessageLite.getDefaultInstance(
          messageType.asSubclass(GeneratedMessageLite.class))
          .buildMessageInfo();
    } catch (Exception e) {
      throw new RuntimeException("Unable to get message info for " + messageType.getName(), e);
    }

            

Reported by PMD.

Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block
Design

Line: 61

                    return (MessageInfo) GeneratedMessageLite.getDefaultInstance(
          messageType.asSubclass(GeneratedMessageLite.class))
          .buildMessageInfo();
    } catch (Exception e) {
      throw new RuntimeException("Unable to get message info for " + messageType.getName(), e);
    }
  }
}

            

Reported by PMD.

src/google/protobuf/util/json_util_test.cc
4 issues
syntax error
Error

Line: 89

                std::unique_ptr<TypeResolver> resolver_;
};

TEST_F(JsonUtilTest, TestWhitespaces) {
  TestMessage m;
  m.mutable_message_value();

  JsonPrintOptions options;
  EXPECT_EQ("{\"messageValue\":{}}", ToJson(m, options));

            

Reported by Cppcheck.

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

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

                // run faster.
  static const int kSkippedPatternCount = 7;

  char buffer[kOutputBufferLength];
  for (int split_pattern = 0; split_pattern < (1 << (kOutputBufferLength - 1));
       split_pattern += kSkippedPatternCount) {
    // Split the buffer into small segments according to the split_pattern.
    std::list<Segment> segments;
    int segment_start = 0;

            

Reported by FlawFinder.

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

Line: 643 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_F(JsonUtilTest, TestWrongJsonInput) {
  const char json[] = "{\"unknown_field\":\"some_value\"}";
  io::ArrayInputStream input_stream(json, strlen(json));
  char proto_buffer[10000];
  io::ArrayOutputStream output_stream(proto_buffer, sizeof(proto_buffer));
  std::string message_type = "type.googleapis.com/proto3.TestMessage";
  TypeResolver* resolver = NewTypeResolverForDescriptorPool(
      "type.googleapis.com", DescriptorPool::generated_pool());


            

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: 642 Column: 43 CWE codes: 126

              
TEST_F(JsonUtilTest, TestWrongJsonInput) {
  const char json[] = "{\"unknown_field\":\"some_value\"}";
  io::ArrayInputStream input_stream(json, strlen(json));
  char proto_buffer[10000];
  io::ArrayOutputStream output_stream(proto_buffer, sizeof(proto_buffer));
  std::string message_type = "type.googleapis.com/proto3.TestMessage";
  TypeResolver* resolver = NewTypeResolverForDescriptorPool(
      "type.googleapis.com", DescriptorPool::generated_pool());

            

Reported by FlawFinder.

java/core/src/main/java/com/google/protobuf/ExtensionSchemas.java
4 issues
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: 33

              
package com.google.protobuf;

final class ExtensionSchemas {
  private static final ExtensionSchema<?> LITE_SCHEMA = new ExtensionSchemaLite();
  private static final ExtensionSchema<?> FULL_SCHEMA = loadSchemaForFullRuntime();

  private static ExtensionSchema<?> loadSchemaForFullRuntime() {
    try {

            

Reported by PMD.

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

Line: 40

                private static ExtensionSchema<?> loadSchemaForFullRuntime() {
    try {
      Class<?> clazz = Class.forName("com.google.protobuf.ExtensionSchemaFull");
      return (ExtensionSchema) clazz.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
      return null;
    }
  }


            

Reported by PMD.

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

Line: 40

                private static ExtensionSchema<?> loadSchemaForFullRuntime() {
    try {
      Class<?> clazz = Class.forName("com.google.protobuf.ExtensionSchemaFull");
      return (ExtensionSchema) clazz.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
      return null;
    }
  }


            

Reported by PMD.

Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block
Design

Line: 41

                  try {
      Class<?> clazz = Class.forName("com.google.protobuf.ExtensionSchemaFull");
      return (ExtensionSchema) clazz.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
      return null;
    }
  }

  static ExtensionSchema<?> lite() {

            

Reported by PMD.

src/google/protobuf/compiler/importer.cc
4 issues
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: 66 Column: 36 CWE codes: 362/367!
Suggestion: Set up the correct permissions (e.g., using setuid()) and try to open the file directly

              #ifdef _WIN32
// 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::open;
#endif

// Returns true if the text looks like a Windows-style absolute path, starting
// with a drive letter.  Example:  "C:\foo".  TODO(kenton):  Share this with

            

Reported by FlawFinder.

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: 420 Column: 11 CWE codes: 362/367!
Suggestion: Set up the correct permissions (e.g., using setuid()) and try to open the file directly

                for (int i = 0; i < mapping_index; i++) {
    if (ApplyMapping(*virtual_file, mappings_[i].virtual_path,
                     mappings_[i].disk_path, shadowing_disk_file)) {
      if (access(shadowing_disk_file->c_str(), F_OK) >= 0) {
        // File exists.
        return SHADOWED;
      }
    }
  }

            

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: 67 Column: 36 CWE codes: 362

              // 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::open;
#endif

// Returns true if the text looks like a Windows-style absolute path, starting
// with a drive letter.  Example:  "C:\foo".  TODO(kenton):  Share this with
// copy in command_line_interface.cc?

            

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: 511 Column: 23 CWE codes: 362

              #endif
  int file_descriptor;
  do {
    file_descriptor = open(filename.c_str(), O_RDONLY);
  } while (file_descriptor < 0 && errno == EINTR);
  if (file_descriptor >= 0) {
    io::FileInputStream* result = new io::FileInputStream(file_descriptor);
    result->SetCloseOnDelete(true);
    return result;

            

Reported by FlawFinder.