The following issues were found

ruby/src/main/java/com/google/protobuf/jruby/RubyEnumBuilderContext.java
5 issues
Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 89

                      return context.nil;
    }

    private EnumDescriptorProto.Builder builder;
    private RubyFileBuilderContext fileBuilderContext;
}

            

Reported by PMD.

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

Line: 90

                  }

    private EnumDescriptorProto.Builder builder;
    private RubyFileBuilderContext fileBuilderContext;
}

            

Reported by PMD.

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

Line: 90

                  }

    private EnumDescriptorProto.Builder builder;
    private RubyFileBuilderContext fileBuilderContext;
}

            

Reported by PMD.

Found 'DU'-anomaly for variable 'cEnumBuilderContext' (lines '51'-'58').
Error

Line: 51

              public class RubyEnumBuilderContext extends RubyObject {
    public static void createRubyEnumBuilderContext(Ruby runtime) {
        RubyModule internal = runtime.getClassFromPath("Google::Protobuf::Internal");
        RubyClass cEnumBuilderContext = internal.defineClassUnder("EnumBuilderContext", runtime.getObject(), new ObjectAllocator() {
            @Override
            public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
                return new RubyEnumBuilderContext(runtime, klazz);
            }
        });

            

Reported by PMD.

Found 'DU'-anomaly for variable 'cEnumBuilderContext' (lines '51'-'58').
Error

Line: 51

              public class RubyEnumBuilderContext extends RubyObject {
    public static void createRubyEnumBuilderContext(Ruby runtime) {
        RubyModule internal = runtime.getClassFromPath("Google::Protobuf::Internal");
        RubyClass cEnumBuilderContext = internal.defineClassUnder("EnumBuilderContext", runtime.getObject(), new ObjectAllocator() {
            @Override
            public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
                return new RubyEnumBuilderContext(runtime, klazz);
            }
        });

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java
5 issues
JUnit tests should include assert() or fail()
Design

Line: 49

              public class ByteBufferWriterTest {

  @Test
  public void testHeapBuffer() throws IOException {
    // Test a small and large buffer.
    testWrite(ByteBuffer.allocate(100));
    testWrite(ByteBuffer.allocate(1024 * 100));
  }


            

Reported by PMD.

JUnit tests should include assert() or fail()
Design

Line: 56

                }

  @Test
  public void testDirectBuffer() throws IOException {
    // Test a small and large buffer.
    testWrite(ByteBuffer.allocateDirect(100));
    testWrite(ByteBuffer.allocateDirect(1024 * 100));
  }


            

Reported by PMD.

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

Line: 62

                  testWrite(ByteBuffer.allocateDirect(1024 * 100));
  }

  private void testWrite(ByteBuffer buffer) throws IOException {
    fillRandom(buffer);
    ByteArrayOutputStream os = new ByteArrayOutputStream(buffer.remaining());
    ByteBufferWriter.write(buffer, os);
    assertThat(buffer.position()).isEqualTo(0);
    assertThat(Arrays.equals(toArray(buffer), os.toByteArray())).isTrue();

            

Reported by PMD.

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

Line: 66

                  fillRandom(buffer);
    ByteArrayOutputStream os = new ByteArrayOutputStream(buffer.remaining());
    ByteBufferWriter.write(buffer, os);
    assertThat(buffer.position()).isEqualTo(0);
    assertThat(Arrays.equals(toArray(buffer), os.toByteArray())).isTrue();
  }

  private void fillRandom(ByteBuffer buf) {
    byte[] bytes = new byte[buf.remaining()];

            

Reported by PMD.

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

Line: 67

                  ByteArrayOutputStream os = new ByteArrayOutputStream(buffer.remaining());
    ByteBufferWriter.write(buffer, os);
    assertThat(buffer.position()).isEqualTo(0);
    assertThat(Arrays.equals(toArray(buffer), os.toByteArray())).isTrue();
  }

  private void fillRandom(ByteBuffer buf) {
    byte[] bytes = new byte[buf.remaining()];
    new Random().nextBytes(bytes);

            

Reported by PMD.

src/google/protobuf/io/tokenizer_unittest.cc
5 issues
syntax error
Error

Line: 248

                  {".", Tokenizer::TYPE_SYMBOL},
};

TEST_2D(TokenizerTest, SimpleTokens, kSimpleTokenCases, kBlockSizes) {
  // Set up the tokenizer.
  TestInputStream input(kSimpleTokenCases_case.input.data(),
                        kSimpleTokenCases_case.input.size(), kBlockSizes_case);
  TestErrorCollector error_collector;
  Tokenizer tokenizer(&input, &error_collector);

            

Reported by Cppcheck.

syntax error
Error

Line: 428

                   }},
};

TEST_2D(TokenizerTest, MultipleTokens, kMultiTokenCases, kBlockSizes) {
  // Set up the tokenizer.
  TestInputStream input(kMultiTokenCases_case.input.data(),
                        kMultiTokenCases_case.input.size(), kBlockSizes_case);
  TestErrorCollector error_collector;
  Tokenizer tokenizer(&input, &error_collector);

            

Reported by Cppcheck.

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: 295 Column: 31 CWE codes: 126

              
  // Set up the tokenizer.
  const char* text = "1f 2.5f 6e3f 7F";
  TestInputStream input(text, strlen(text), kBlockSizes_case);
  TestErrorCollector error_collector;
  Tokenizer tokenizer(&input, &error_collector);
  tokenizer.set_allow_f_after_float(true);

  // Advance through tokens and check that they are parsed as expected.

            

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: 496 Column: 31 CWE codes: 126

                                               "*",   "grault", "*", "/",   "garply"};

  // Set up the tokenizer.
  TestInputStream input(text, strlen(text), kBlockSizes_case);
  TestErrorCollector error_collector;
  Tokenizer tokenizer(&input, &error_collector);
  tokenizer.set_comment_style(Tokenizer::SH_COMMENT_STYLE);

  // Advance through tokens and check that they are parsed as expected.

            

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: 952 Column: 13 CWE codes: 126

                }

  // Only "foo" should have been read.
  EXPECT_EQ(strlen("foo"), input.ByteCount());
}


}  // namespace
}  // namespace io

            

Reported by FlawFinder.

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

Line: 46

               *
 * <p>This implementation assumes all subclasses are array based, supporting random access.
 */
abstract class AbstractProtobufList<E> extends AbstractList<E> implements ProtobufList<E> {

  protected static final int DEFAULT_CAPACITY = 10;

  /** Whether or not this list is modifiable. */
  private boolean isMutable;

            

Reported by PMD.

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

Line: 51

                protected static final int DEFAULT_CAPACITY = 10;

  /** Whether or not this list is modifiable. */
  private boolean isMutable;

  /** Constructs a mutable list by default. */
  AbstractProtobufList() {
    isMutable = true;
  }

            

Reported by PMD.

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

Line: 75

              
    List<?> other = (List<?>) o;
    final int size = size();
    if (size != other.size()) {
      return false;
    }
    for (int i = 0; i < size; i++) {
      if (!get(i).equals(other.get(i))) {
        return false;

            

Reported by PMD.

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

Line: 79

                    return false;
    }
    for (int i = 0; i < size; i++) {
      if (!get(i).equals(other.get(i))) {
        return false;
      }
    }
    return true;
  }

            

Reported by PMD.

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

Line: 91

                  final int size = size();
    int hashCode = 1;
    for (int i = 0; i < size; i++) {
      hashCode = (31 * hashCode) + get(i).hashCode();
    }
    return hashCode;
  }

  @Override

            

Reported by PMD.

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

              #define lseek(fd, offset, origin) ((off_t)-1)
// 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::open;
using google::protobuf::io::win32::read;
using google::protobuf::io::win32::write;
#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: 65 Column: 36 CWE codes: 362

              // them like we do below.
using google::protobuf::io::win32::access;
using google::protobuf::io::win32::close;
using google::protobuf::io::win32::open;
using google::protobuf::io::win32::read;
using google::protobuf::io::win32::write;
#endif

namespace {

            

Reported by FlawFinder.

read - Check buffer boundaries if used in a loop including recursive loops
Security

Line: 66 Column: 36 CWE codes: 120 20

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

namespace {


            

Reported by FlawFinder.

read - Check buffer boundaries if used in a loop including recursive loops
Security

Line: 142 Column: 14 CWE codes: 120 20

              
  int result;
  do {
    result = read(file_, buffer, size);
  } while (result < 0 && errno == EINTR);

  if (result < 0) {
    // Read error (not EOF).
    errno_ = errno;

            

Reported by FlawFinder.

read - Check buffer boundaries if used in a loop including recursive loops
Security

Line: 272 Column: 11 CWE codes: 120 20

              
int IstreamInputStream::CopyingIstreamInputStream::Read(void* buffer,
                                                        int size) {
  input_->read(reinterpret_cast<char*>(buffer), size);
  int result = input_->gcount();
  if (result == 0 && input_->fail() && !input_->eof()) {
    return -1;
  }
  return result;

            

Reported by FlawFinder.

java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java
5 issues
The class 'UnmodifiableLazyStringList' has a Modified Cyclomatic Complexity of 2 (Highest = 10).
Design

Line: 47

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

  private final LazyStringList list;

  public UnmodifiableLazyStringList(LazyStringList list) {

            

Reported by PMD.

The class 'UnmodifiableLazyStringList' has a Standard Cyclomatic Complexity of 2 (Highest = 10).
Design

Line: 47

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

  private final LazyStringList list;

  public UnmodifiableLazyStringList(LazyStringList list) {

            

Reported by PMD.

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

Line: 50

              public class UnmodifiableLazyStringList extends AbstractList<String>
    implements LazyStringList, RandomAccess {

  private final LazyStringList list;

  public UnmodifiableLazyStringList(LazyStringList list) {
    this.list = list;
  }


            

Reported by PMD.

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

Line: 112

                }

  @Override
  public ListIterator<String> listIterator(final int index) {
    return new ListIterator<String>() {
      ListIterator<String> iter = list.listIterator(index);

      @Override
      public boolean hasNext() {

            

Reported by PMD.

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

Line: 112

                }

  @Override
  public ListIterator<String> listIterator(final int index) {
    return new ListIterator<String>() {
      ListIterator<String> iter = list.listIterator(index);

      @Override
      public boolean hasNext() {

            

Reported by PMD.

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

Line: 269

                      throw new IllegalArgumentException("readPrimitiveField() cannot handle enums.");
    }

    throw new RuntimeException("There is no way to get here, but the compiler thinks otherwise.");
  }
}

            

Reported by PMD.

The class 'WireFormat' has a Standard Cyclomatic Complexity of 5 (Highest = 19).
Design

Line: 45

               *
 * @author kenton@google.com Kenton Varda
 */
public final class WireFormat {
  // Do not allow instantiation.
  private WireFormat() {}

  static final int FIXED32_SIZE = 4;
  static final int FIXED64_SIZE = 8;

            

Reported by PMD.

The method 'readPrimitiveField(CodedInputStream, FieldType, Utf8Validation)' has a cyclomatic complexity of 23.
Design

Line: 225

                 * @return An object representing the field's value, of the exact type which would be returned by
   *     {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
   */
  static Object readPrimitiveField(
      CodedInputStream input, FieldType type, Utf8Validation utf8Validation) throws IOException {
    switch (type) {
      case DOUBLE:
        return input.readDouble();
      case FLOAT:

            

Reported by PMD.

The method 'readPrimitiveField' has a Standard Cyclomatic Complexity of 19.
Design

Line: 225

                 * @return An object representing the field's value, of the exact type which would be returned by
   *     {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
   */
  static Object readPrimitiveField(
      CodedInputStream input, FieldType type, Utf8Validation utf8Validation) throws IOException {
    switch (type) {
      case DOUBLE:
        return input.readDouble();
      case FLOAT:

            

Reported by PMD.

java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java
4 issues
The class 'TextFormatEscaper' has a Standard Cyclomatic Complexity of 4 (Highest = 13).
Design

Line: 34

              package com.google.protobuf;

/** Provide text format escaping support for proto2 instances. */
final class TextFormatEscaper {
  private TextFormatEscaper() {}

  private interface ByteSequence {
    int size();


            

Reported by PMD.

The method 'escapeBytes' has a Standard Cyclomatic Complexity of 13.
Design

Line: 49

                 * escaped, as well as backslash, single-quote, and double-quote characters. Characters for which
   * no defined short-hand escape sequence is defined will be escaped using 3-digit octal sequences.
   */
  static String escapeBytes(final ByteSequence input) {
    final StringBuilder builder = new StringBuilder(input.size());
    for (int i = 0; i < input.size(); i++) {
      final byte b = input.byteAt(i);
      switch (b) {
          // Java does not recognize \a or \v, apparently.

            

Reported by PMD.

The method 'escapeBytes(ByteSequence)' has a cyclomatic complexity of 14.
Design

Line: 49

                 * escaped, as well as backslash, single-quote, and double-quote characters. Characters for which
   * no defined short-hand escape sequence is defined will be escaped using 3-digit octal sequences.
   */
  static String escapeBytes(final ByteSequence input) {
    final StringBuilder builder = new StringBuilder(input.size());
    for (int i = 0; i < input.size(); i++) {
      final byte b = input.byteAt(i);
      switch (b) {
          // Java does not recognize \a or \v, apparently.

            

Reported by PMD.

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

Line: 150

              
  /** Escape double quotes and backslashes in a String for unicode output of a message. */
  static String escapeDoubleQuotesAndBackslashes(final String input) {
    return input.replace("\\", "\\\\").replace("\"", "\\\"");
  }
}

            

Reported by PMD.

python/google/protobuf/pyext/cpp_message.py
4 issues
No name '_message' in module 'google.protobuf.pyext'
Error

Line: 39 Column: 1

              
__author__ = 'tibell@google.com (Johan Tibell)'

from google.protobuf.pyext import _message


class GeneratedProtocolMessageType(_message.MessageMeta):

  """Metaclass for protocol message classes created at runtime from Descriptors.

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 42 Column: 1

              from google.protobuf.pyext import _message


class GeneratedProtocolMessageType(_message.MessageMeta):

  """Metaclass for protocol message classes created at runtime from Descriptors.

  The protocol compiler currently uses this metaclass to create protocol
  message classes at runtime.  Clients can also manually create their own

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 44 Column: 1

              
class GeneratedProtocolMessageType(_message.MessageMeta):

  """Metaclass for protocol message classes created at runtime from Descriptors.

  The protocol compiler currently uses this metaclass to create protocol
  message classes at runtime.  Clients can also manually create their own
  classes at runtime, as in this example:


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 65 Column: 1

              
  # Must be consistent with the protocol-compiler code in
  # proto2/compiler/internal/generator.*.
  _DESCRIPTOR_KEY = 'DESCRIPTOR'

            

Reported by Pylint.

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

Line: 480 Column: 23 CWE codes: 120

                const google::protobuf::Type* type = LookupType(field);
  if (type == nullptr) {
    ++invalid_depth_;
    InvalidName(name, StrCat("Missing descriptor for field: ",
                                   field->type_url()));
    return this;
  }

  return StartObjectField(*field, *type);

            

Reported by FlawFinder.

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

Line: 523 Column: 23 CWE codes: 120

                const google::protobuf::Type* type = LookupType(field);
  if (type == nullptr) {
    ++invalid_depth_;
    InvalidName(name, StrCat("Missing descriptor for field: ",
                                   field->type_url()));
    return this;
  }

  return StartListField(*field, *type);

            

Reported by FlawFinder.

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

Line: 554 Column: 23 CWE codes: 120

              
  const google::protobuf::Type* type = LookupType(field);
  if (type == nullptr) {
    InvalidName(name, StrCat("Missing descriptor for field: ",
                                   field->type_url()));
    return this;
  }

  return RenderPrimitiveField(*field, *type, data);

            

Reported by FlawFinder.

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

Line: 570 Column: 11 CWE codes: 120

                  if (element_->IsOneofIndexTaken(field.oneof_index())) {
      InvalidValue(
          "oneof",
          StrCat(
              "oneof field '", element_->type().oneofs(field.oneof_index() - 1),
              "' is already set. Cannot set '", unnormalized_name, "'"));
      return false;
    }
    element_->TakeOneofIndex(field.oneof_index());

            

Reported by FlawFinder.