The following issues were found

aten/src/ATen/native/vulkan/api/Resource.cpp
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: 92 Column: 43 CWE codes: 362/367!
Suggestion: Set up the correct permissions (e.g., using setuid()) and try to open the file directly

              
void* map(
    const Resource::Memory& memory,
    const Resource::Memory::Access::Flags access) {
  void* data = nullptr;
  VK_CHECK(vmaMapMemory(memory.allocator, memory.allocation, &data));

  if (access & Resource::Memory::Access::Read) {
    // Call will be ignored by implementation if the memory type this allocation

            

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

                void* data = nullptr;
  VK_CHECK(vmaMapMemory(memory.allocator, memory.allocation, &data));

  if (access & Resource::Memory::Access::Read) {
    // Call will be ignored by implementation if the memory type this allocation
    // belongs to is not HOST_VISIBLE or is HOST_COHERENT, which is the behavior
    // we want.
    VK_CHECK(vmaInvalidateAllocation(
        memory.allocator, memory.allocation, 0u, VK_WHOLE_SIZE));

            

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

              Resource::Memory::Scope::Scope(
    const VmaAllocator allocator,
    const VmaAllocation allocation,
    const Access::Flags access)
  : allocator_(allocator),
    allocation_(allocation),
    access_(access) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
      allocator,

            

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

                  const Access::Flags access)
  : allocator_(allocator),
    allocation_(allocation),
    access_(access) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
      allocator,
      "Invalid VMA (Vulkan Memory Allocator) allocator!");

  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(

            

Reported by FlawFinder.

caffe2/python/dyndep.py
4 issues
Missing module docstring
Error

Line: 1 Column: 1

              ## @package dyndep
# Module caffe2.python.dyndep





import ctypes
import os

            

Reported by Pylint.

Function name "InitOpsLibrary" doesn't conform to snake_case naming style
Error

Line: 14 Column: 1

              from caffe2.python import core, extension_loader


def InitOpsLibrary(name, trigger_lazy=True):
    """Loads a dynamic library that contains custom operators into Caffe2.

    Since Caffe2 uses static variable registration, you can optionally load a
    separate .so file that contains custom operators and registers that into
    the caffe2 core binary. In C++, this is usually done by either declaring

            

Reported by Pylint.

Function name "GetImportedOpsLibraries" doesn't conform to snake_case naming style
Error

Line: 42 Column: 1

              dll_lock = Lock()


def GetImportedOpsLibraries():
    return _IMPORTED_DYNDEPS


def _init_impl(path, trigger_lazy=True):
    with dll_lock:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 42 Column: 1

              dll_lock = Lock()


def GetImportedOpsLibraries():
    return _IMPORTED_DYNDEPS


def _init_impl(path, trigger_lazy=True):
    with dll_lock:

            

Reported by Pylint.

c10/util/tempfile.h
4 issues
getenv - Environment variables are untrustable input if they can be set by an attacker. They can have any content and length, and the same variable can be set more than once
Security

Line: 38 Column: 28 CWE codes: 807 20
Suggestion: Check environment variables carefully before using them

              
  std::string tmp_directory = "/tmp";
  for (const char* variable : env_variables) {
    if (const char* path = getenv(variable)) {
      tmp_directory = path;
      break;
    }
  }


            

Reported by FlawFinder.

tmpnam - Temporary file race condition
Security

Line: 133 Column: 24 CWE codes: 377

              inline c10::optional<TempFile> try_make_tempfile(
    std::string name_prefix = "torch-file-") {
#if defined(_WIN32)
  return TempFile{std::tmpnam(nullptr)};
#else
  std::vector<char> filename = detail::make_filename(std::move(name_prefix));
  const int fd = mkstemp(filename.data());
  if (fd == -1) {
    return c10::nullopt;

            

Reported by FlawFinder.

tmpnam - Temporary file race condition
Security

Line: 169 Column: 32 CWE codes: 377

                  std::string name_prefix = "torch-dir-") {
#if defined(_WIN32)
  while (true) {
    const char* dirname = std::tmpnam(nullptr);
    if (!dirname) {
      return c10::nullopt;
    }
    if (CreateDirectoryA(dirname, NULL)) {
      return TempDir(dirname);

            

Reported by FlawFinder.

mkstemp - Potential for temporary file vulnerability in some circumstances. Some older Unix-like systems create temp files with permission to write by all by default, so be sure to set the umask to override this. Also, some older Unix systems might fail to use O_EXCL when opening the file, so make sure that O_EXCL is used by the library
Security

Line: 136 Column: 18 CWE codes: 377

                return TempFile{std::tmpnam(nullptr)};
#else
  std::vector<char> filename = detail::make_filename(std::move(name_prefix));
  const int fd = mkstemp(filename.data());
  if (fd == -1) {
    return c10::nullopt;
  }
  // Don't make the string from string(filename.begin(), filename.end(), or
  // there will be a trailing '\0' at the end.

            

Reported by FlawFinder.

caffe2/python/layers/batch_mse_loss.py
4 issues
Missing module docstring
Error

Line: 1 Column: 1

              ## @package batch_mse_loss
# Module caffe2.python.layers.batch_mse_loss





from caffe2.python import core, schema
from caffe2.python.layers.layers import (

            

Reported by Pylint.

Missing class docstring
Error

Line: 18 Column: 1

              import numpy as np


class BatchMSELoss(ModelLayer):

    def __init__(self, model, input_record, name='batch_mse_loss', **kwargs):
        super(BatchMSELoss, self).__init__(model, name, input_record, **kwargs)

        assert schema.is_schema_subset(

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 21 Column: 9

              class BatchMSELoss(ModelLayer):

    def __init__(self, model, input_record, name='batch_mse_loss', **kwargs):
        super(BatchMSELoss, self).__init__(model, name, input_record, **kwargs)

        assert schema.is_schema_subset(
            schema.Struct(
                ('label', schema.Scalar()),
                ('prediction', schema.Scalar())

            

Reported by Pylint.

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

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

                  def __init__(self, model, input_record, name='batch_mse_loss', **kwargs):
        super(BatchMSELoss, self).__init__(model, name, input_record, **kwargs)

        assert schema.is_schema_subset(
            schema.Struct(
                ('label', schema.Scalar()),
                ('prediction', schema.Scalar())
            ),
            input_record

            

Reported by Bandit.

caffe2/mobile/contrib/libvulkan-stub/include/vulkan/vulkan.h
4 issues
char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 1629 Column: 5 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

                  uint32_t                            vendorID;
    uint32_t                            deviceID;
    VkPhysicalDeviceType                deviceType;
    char                                deviceName[VK_MAX_PHYSICAL_DEVICE_NAME_SIZE];
    uint8_t                             pipelineCacheUUID[VK_UUID_SIZE];
    VkPhysicalDeviceLimits              limits;
    VkPhysicalDeviceSparseProperties    sparseProperties;
} VkPhysicalDeviceProperties;


            

Reported by FlawFinder.

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

Line: 1683 Column: 5 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

              } VkDeviceCreateInfo;

typedef struct VkExtensionProperties {
    char        extensionName[VK_MAX_EXTENSION_NAME_SIZE];
    uint32_t    specVersion;
} VkExtensionProperties;

typedef struct VkLayerProperties {
    char        layerName[VK_MAX_EXTENSION_NAME_SIZE];

            

Reported by FlawFinder.

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

Line: 1688 Column: 5 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

              } VkExtensionProperties;

typedef struct VkLayerProperties {
    char        layerName[VK_MAX_EXTENSION_NAME_SIZE];
    uint32_t    specVersion;
    uint32_t    implementationVersion;
    char        description[VK_MAX_DESCRIPTION_SIZE];
} VkLayerProperties;


            

Reported by FlawFinder.

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

Line: 1691 Column: 5 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

                  char        layerName[VK_MAX_EXTENSION_NAME_SIZE];
    uint32_t    specVersion;
    uint32_t    implementationVersion;
    char        description[VK_MAX_DESCRIPTION_SIZE];
} VkLayerProperties;

typedef struct VkSubmitInfo {
    VkStructureType                sType;
    const void*                    pNext;

            

Reported by FlawFinder.

aten/src/ATen/native/cpu/Unfold2d.cpp
4 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

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

                                        dst + (size_t)y * output_width,
                          0,
                          sizeof(scalar_t) * lpad);
                    memcpy(
                        dst + (size_t)y * output_width + lpad,
                        src + (size_t)iy * input_width + ix + lpad,
                        sizeof(scalar_t) * (output_width - rpad - lpad));
                    if (rpad > 0)
                      memset(

            

Reported by FlawFinder.

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

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

                                        0,
                          sizeof(scalar_t) * 1);
                    else
                      memcpy(
                          dst + (size_t)y * output_width + x,
                          src + (size_t)iy * input_width + ix,
                          sizeof(scalar_t) * (1));
                  }
                }

            

Reported by FlawFinder.

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

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

                            iy = (int64_t)y * dH + kh;
              ix = 0 + kw;
              if (dW == 1)
                memcpy(
                    dst + (size_t)y * output_width,
                    src + (size_t)iy * input_width + ix,
                    sizeof(scalar_t) * output_width);
              else {
                for (x = 0; x < output_width; x++)

            

Reported by FlawFinder.

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

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

                                  sizeof(scalar_t) * output_width);
              else {
                for (x = 0; x < output_width; x++)
                  memcpy(
                      dst + (size_t)y * output_width + x,
                      src + (size_t)iy * input_width + ix + (int64_t)x * dW,
                      sizeof(scalar_t) * (1));
              }
            }

            

Reported by FlawFinder.

aten/src/ATen/native/cpu/SumKernel.cpp
4 issues
char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 426 Column: 5 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

              template <typename acc_t, typename VecLoadPolicy, typename ScalarLoadPolicy, typename StorePolicy>
void vectorized_inner_sum(
    // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
    char * C10_RESTRICT data[2], int64_t outer_stride, int64_t out_stride,
    int64_t size0, int64_t size1) {
  using vacc_t = Vectorized<acc_t>;
  constexpr int64_t vec_stride = VecLoadPolicy::memsize();
  constexpr int64_t scalar_stride = ScalarLoadPolicy::memsize();
  constexpr int64_t vec_numel = vec_stride / scalar_stride;

            

Reported by FlawFinder.

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

Line: 456 Column: 5 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

              template <typename acc_t, typename LoadPolicy, typename StorePolicy>
void scalar_inner_sum(
    // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
    char * C10_RESTRICT data[2], int64_t in_strides[2], int64_t out_stride,
    int64_t size0, int64_t size1) {
  for (int64_t j = 0; j < size1; ++j) {
    const auto *row_in = data[1] + j * in_strides[1];
    auto ans = row_sum<acc_t, LoadPolicy>(row_in, in_strides[0], size0);
    store<StorePolicy>(data[0], out_stride, j, ans);

            

Reported by FlawFinder.

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

Line: 468 Column: 5 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

              template <typename acc_t, typename VecLoadPolicy, typename ScalarLoadPolicy, typename StorePolicy>
void vectorized_outer_sum(
    // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
    char * C10_RESTRICT data[2], int64_t inner_stride, int64_t out_stride,
    int64_t size0, int64_t size1) {
  using vacc_t = Vectorized<acc_t>;
  constexpr int64_t scalar_stride = ScalarLoadPolicy::memsize();
  constexpr int64_t vec_stride = VecLoadPolicy::memsize();
  constexpr int64_t nrows = 4;

            

Reported by FlawFinder.

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

Line: 507 Column: 5 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

              template <typename acc_t, typename LoadPolicy, typename StorePolicy>
void scalar_outer_sum(
    // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
    char * C10_RESTRICT data[2], int64_t in_strides[2], int64_t out_stride,
    int64_t size0, int64_t size1) {
  constexpr int64_t nrows = 4;
  int64_t j = 0;
  for (; j + (nrows - 1) < size1; j += nrows) {
    const auto *row_in = data[1] + j * in_strides[1];

            

Reported by FlawFinder.

caffe2/python/mkl_test_util.py
4 issues
Unable to import 'hypothesis.strategies'
Error

Line: 14 Column: 1

              


import hypothesis.strategies as st

from caffe2.proto import caffe2_pb2
from caffe2.python import workspace
from caffe2.python import hypothesis_test_util as hu


            

Reported by Pylint.

Module 'caffe2.python._import_c_extension' has no 'has_mkldnn' member
Error

Line: 24 Column: 17

              gpu_do = hu.gpu_do
mkl_do = caffe2_pb2.DeviceOption(device_type=caffe2_pb2.MKLDNN)
device_options = hu.device_options + (
    [mkl_do] if workspace.C.has_mkldnn else [])


def device_checker_device_options():
    return st.just(device_options)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 27 Column: 1

                  [mkl_do] if workspace.C.has_mkldnn else [])


def device_checker_device_options():
    return st.just(device_options)


def gradient_checker_device_option():
    return st.sampled_from(device_options)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 31 Column: 1

                  return st.just(device_options)


def gradient_checker_device_option():
    return st.sampled_from(device_options)


gcs = dict(
    gc=gradient_checker_device_option(),

            

Reported by Pylint.

binaries/make_cifar_db.cc
4 issues
char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

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

                std::ifstream data_file(filename.c_str(),
      std::ios::in | std::ios::binary);
  CAFFE_ENFORCE(data_file, "Unable to open file ", filename);
  char str_buffer[kCIFARImageNBytes];
  int label_value;
  std::unique_ptr<db::Transaction> transaction(db->NewTransaction());
  for (int itemid = 0; itemid < num_items; ++itemid) {
    ReadImage(&data_file, &label_value, str_buffer);
    data->set_byte_data(str_buffer, kCIFARImageNBytes);

            

Reported by FlawFinder.

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

Line: 62 Column: 11 CWE codes: 120 20

                char label_char;
  if (FLAGS_is_cifar100) {
    // Skip the coarse label.
    file->read(&label_char, 1);
  }
  file->read(&label_char, 1);
  *label = label_char;
  // Yes, there are better ways to do it, like in-place swap... but I am too
  // lazy so let's just write it in a memory-wasteful way.

            

Reported by FlawFinder.

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

Line: 64 Column: 9 CWE codes: 120 20

                  // Skip the coarse label.
    file->read(&label_char, 1);
  }
  file->read(&label_char, 1);
  *label = label_char;
  // Yes, there are better ways to do it, like in-place swap... but I am too
  // lazy so let's just write it in a memory-wasteful way.
  std::array<char, kCIFARImageNBytes> channel_first_storage;
  file->read(channel_first_storage.data(), kCIFARImageNBytes);

            

Reported by FlawFinder.

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

Line: 69 Column: 9 CWE codes: 120 20

                // Yes, there are better ways to do it, like in-place swap... but I am too
  // lazy so let's just write it in a memory-wasteful way.
  std::array<char, kCIFARImageNBytes> channel_first_storage;
  file->read(channel_first_storage.data(), kCIFARImageNBytes);
  for (int c = 0; c < 3; ++c) {
    for (int i = 0; i < kCIFARSize * kCIFARSize; ++i) {
      buffer[i * 3 + c] =
          channel_first_storage[c * kCIFARSize * kCIFARSize + i];
    }

            

Reported by FlawFinder.

aten/src/ATen/test/native_test.cpp
4 issues
atol - Unless checked, the resulting number can exceed the expected range
Security

Line: 13 Column: 44 CWE codes: 190
Suggestion: If source untrusted, check both minimum and maximum, even if the input had no minus sign (large numbers can roll over into negative number; consider saving to an unsigned value if that is intended)

                ASSERT_TRUE(t1.is_same_size(t2)); \
  ASSERT_TRUE(t1.allclose(t2));

#define ASSERT_ALLCLOSE_TOLERANCES(t1, t2, atol, rtol) \
  ASSERT_TRUE(t1.is_same_size(t2));                    \
  ASSERT_TRUE(t1.allclose(t2, atol, rtol));

void requireEqualTensorList(TensorList t1, TensorList t2) {
  ASSERT_EQ(t1.size(), t2.size());

            

Reported by FlawFinder.

atol - Unless checked, the resulting number can exceed the expected range
Security

Line: 15 Column: 31 CWE codes: 190
Suggestion: If source untrusted, check both minimum and maximum, even if the input had no minus sign (large numbers can roll over into negative number; consider saving to an unsigned value if that is intended)

              
#define ASSERT_ALLCLOSE_TOLERANCES(t1, t2, atol, rtol) \
  ASSERT_TRUE(t1.is_same_size(t2));                    \
  ASSERT_TRUE(t1.allclose(t2, atol, rtol));

void requireEqualTensorList(TensorList t1, TensorList t2) {
  ASSERT_EQ(t1.size(), t2.size());
  for (size_t i = 0; i < t1.size(); ++i) {
    ASSERT_EQUAL(t1[i], t2[i]);

            

Reported by FlawFinder.

atol - Unless checked, the resulting number can exceed the expected range
Security

Line: 183 Column: 50 CWE codes: 190
Suggestion: If source untrusted, check both minimum and maximum, even if the input had no minus sign (large numbers can roll over into negative number; consider saving to an unsigned value if that is intended)

                auto acc_result = d5Acc.view({24, 2, 3})
                        .bmm(d2Acc.expand({24, 3, 4}))
                        .view({3, 2, 4, 2, 4});
  ASSERT_ALLCLOSE_TOLERANCES(result, acc_result, atol, rtol);
  ASSERT_ALLCLOSE(
      d2o.matmul(d5),
      d2o.expand({24, 4, 2}).bmm(d5.view({24, 2, 3})).view({3, 2, 4, 4, 3}));

  // > 2-d, > 2-d

            

Reported by FlawFinder.

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

Line: 7 Column: 45 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

              
using namespace at;

#define ASSERT_EQUAL(t1, t2) ASSERT_TRUE(t1.equal(t2));

#define ASSERT_ALLCLOSE(t1, t2)     \
  ASSERT_TRUE(t1.is_same_size(t2)); \
  ASSERT_TRUE(t1.allclose(t2));


            

Reported by FlawFinder.