The following issues were found

caffe2/operators/text_file_reader_utils.cc
2 issues
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: 89 Column: 9 CWE codes: 362

              
FileReader::FileReader(const std::string& path, size_t bufferSize)
    : bufferSize_(bufferSize), buffer_(new char[bufferSize]) {
  fd_ = open(path.c_str(), O_RDONLY, 0777);
  if (fd_ < 0) {
    throw std::runtime_error(
        "Error opening file for reading: " + std::string(std::strerror(errno)) +
        " Path=" + path);
  }

            

Reported by FlawFinder.

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

Line: 112 Column: 18 CWE codes: 120 20

              
void FileReader::operator()(CharRange& range) {
  char* buffer = buffer_.get();
  auto numRead = read(fd_, buffer, bufferSize_);
  if (numRead == -1) {
    throw std::runtime_error(
        "Error reading file: " + std::string(std::strerror(errno)));
  }
  if (numRead == 0) {

            

Reported by FlawFinder.

caffe2/operators/text_file_reader_utils_test.cc
2 issues
tmpnam - Temporary file race condition
Security

Line: 104 Column: 24 CWE codes: 377

                  EXPECT_EQ(0, bt.endDelim());
  }

  char* tmpname = std::tmpnam(nullptr);
  std::ofstream outFile;
  outFile.open(tmpname);
  outFile << ch;
  outFile.close();
  for (int numPasses = 1; numPasses <= 2; ++numPasses) {

            

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: 106 Column: 11 CWE codes: 362

              
  char* tmpname = std::tmpnam(nullptr);
  std::ofstream outFile;
  outFile.open(tmpname);
  outFile << ch;
  outFile.close();
  for (int numPasses = 1; numPasses <= 2; ++numPasses) {
    FileReader fr(tmpname, 5);
    BufferedTokenizer fileTokenizer(tokenizer, &fr, numPasses);

            

Reported by FlawFinder.

caffe2/opt/onnxifi_transformer.cc
2 issues
char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

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

              
  constexpr size_t ll = 1024;
  // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays)
  char buf[ll];
  size_t len = ll;
  if (onnxGetOptionFunctionPointer != nullptr &&
      (*onnxGetOptionFunctionPointer)(option.c_str(), buf, &len) ==
          ONNXIFI_STATUS_SUCCESS) {
    return std::string(buf, len);

            

Reported by FlawFinder.

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

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

                // Try to find a backend that support Caffe2 proto. Note that this is quite
  // opportunistic as we don't officially support Caffe2 proto.
  // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays)
  char buf[kBufferSize];
  // NOLINTNEXTLINE(clang-diagnostic-sign-compare)
  for (int i = 0; i < backend_ids_.size(); ++i) {
    size_t len = kBufferSize;
    auto ret = lib_->onnxGetBackendInfo(
        backend_ids_[i], ONNXIFI_BACKEND_DEVICE, buf, &len);

            

Reported by FlawFinder.

caffe2/perfkernels/math_cpu_avx2.cc
2 issues
random - This function is not sufficiently random for security-related functions such as key and nonce creation
Security

Line: 25 Column: 10 CWE codes: 327
Suggestion: Use a more secure technique for acquiring random values

                  uint8_t* output_data,
    uint64_t input_size,
    uint64_t bitwidth,
    bool random,
    const float* random_buffer) {
  __m256i shuffle_mask_v = _mm256_set_epi8(
      // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-avoid-magic-numbers,cppcoreguidelines-narrowing-conversions)
      0xff,
      // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-avoid-magic-numbers,cppcoreguidelines-narrowing-conversions)

            

Reported by FlawFinder.

random - This function is not sufficiently random for security-related functions such as key and nonce creation
Security

Line: 111 Column: 7 CWE codes: 327
Suggestion: Use a more secure technique for acquiring random values

                float gap_inverse = 1. / (gap + QEPSILON);
  uint8_t max_q = (1 << bitwidth) - 1;
  uint64_t bit_start = 0;
  if (random) {
    for (uint64_t start = 0; start < input_size; start += segment_size) {
      uint64_t stride = start + segment_size <= input_size ? segment_size
                                                           : input_size - start;
      uint64_t i = 0;
      constexpr int VLEN = 8;

            

Reported by FlawFinder.

caffe2/python/fakelowp/init_shared_libs.py
2 issues
Too many arguments for format string
Error

Line: 8 Column: 11

              
if 'OSS_ONNXIFI_LIB' in os.environ:
    lib = os.environ['OSS_ONNXIFI_LIB']
    print("Loading ONNXIFI lib: ".format(lib))
    ctypes.CDLL(lib, ctypes.RTLD_GLOBAL)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              

import ctypes
import os

if 'OSS_ONNXIFI_LIB' in os.environ:
    lib = os.environ['OSS_ONNXIFI_LIB']
    print("Loading ONNXIFI lib: ".format(lib))
    ctypes.CDLL(lib, ctypes.RTLD_GLOBAL)

            

Reported by Pylint.

caffe2/python/helpers/array_helpers.py
2 issues
Unused argument 'model'
Error

Line: 22 Column: 18

                  )[0]


def depth_concat(model, blobs_in, blob_out, **kwargs):
    """The old depth concat function - we should move to use concat."""
    print("DepthConcat is deprecated. use Concat instead.")
    return concat(blobs_in, blob_out, **kwargs)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              ## @package arra_helpers
# Module caffe2.python.helpers.array_helpers






def concat(model, blobs_in, blob_out, **kwargs):

            

Reported by Pylint.

caffe2/python/helpers/dropout.py
2 issues
Missing module docstring
Error

Line: 1 Column: 1

              ## @package dropout
# Module caffe2.python.helpers.dropout






def dropout(model, blob_in, blob_out, use_cudnn=False, **kwargs):

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 15
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      kwargs['engine'] = 'CUDNN'
    else:
        kwargs['engine'] = 'DEFAULT'
    assert 'is_test' in kwargs, "Argument 'is_test' is required"
    return model.net.Dropout(
        blob_in, [blob_out, "_" + blob_out + "_mask"], **kwargs)[0]

            

Reported by Bandit.

caffe2/python/helpers/nonlinearity.py
2 issues
Unused argument 'kwargs'
Error

Line: 11 Column: 1

              from caffe2.python import core


def prelu(model, blob_in, blob_out, num_channels=1, slope_init=None,
          **kwargs):
    """PRelu"""
    slope_init = (
        slope_init if slope_init else ('ConstantFill', {'value': 0.25}))
    if model.init_params:

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              ## @package nonlinearity
# Module caffe2.python.helpers.nonlinearity





from caffe2.python import core


            

Reported by Pylint.

caffe2/opt/onnxifi_op.cc
1 issues
mismatch - Function does not check the second iterator for over-read conditions
Security

Line: 345 Column: 52 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

                }

  if (dim_size > 0) {
    output_reshape_info.fast_path[currentIndex] = !mismatch;
  } else {
    output_reshape_info.fast_path[currentIndex] = false;
  }
}


            

Reported by FlawFinder.

caffe2/opt/custom/in_batch_broadcast_test.cc
1 issues
syntax error
Error

Line: 72

                return info;
}

TEST(InBatchBroadcast, main) {
  NetDef net;
  net.add_op()->CopyFrom(
      CreateOperatorDef("FloatToHalf", "", {"blob"}, {"blob_half"}, {}));
  ShapeInfoMap shape_map;
  shape_map.emplace(

            

Reported by Cppcheck.