The following issues were found

torch/csrc/api/src/nn/module.cpp
3 issues
read - Check buffer boundaries if used in a loop including recursive loops
Security

Line: 284 Column: 13 CWE codes: 120 20

              
void Module::load(serialize::InputArchive& archive) {
  for (auto& parameter : named_parameters(/*recurse=*/false)) {
    archive.read(parameter.key(), parameter.value());
  }
  for (auto& buffer : named_buffers(/*recurse=*/false)) {
    archive.read(buffer.key(), buffer.value(), /*is_buffer=*/true);
  }
  for (const auto& child : children_) {

            

Reported by FlawFinder.

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

Line: 287 Column: 13 CWE codes: 120 20

                  archive.read(parameter.key(), parameter.value());
  }
  for (auto& buffer : named_buffers(/*recurse=*/false)) {
    archive.read(buffer.key(), buffer.value(), /*is_buffer=*/true);
  }
  for (const auto& child : children_) {
    if (child.value()->is_serializable()) {
      serialize::InputArchive child_archive;
      archive.read(child.key(), child_archive);

            

Reported by FlawFinder.

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

Line: 292 Column: 15 CWE codes: 120 20

                for (const auto& child : children_) {
    if (child.value()->is_serializable()) {
      serialize::InputArchive child_archive;
      archive.read(child.key(), child_archive);
      child.value()->load(child_archive);
    }
  }
}


            

Reported by FlawFinder.

torch/csrc/jit/frontend/strtod.cpp
3 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

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

                  }

    c = copy;
    memcpy(c, digits_pos, decimal_point_pos - digits_pos);
    c += decimal_point_pos - digits_pos;
    memcpy(c, &decimal_point, 1);
    c += 1;
    memcpy(c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
    c += end - (decimal_point_pos + 1);

            

Reported by FlawFinder.

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

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

                  c = copy;
    memcpy(c, digits_pos, decimal_point_pos - digits_pos);
    c += decimal_point_pos - digits_pos;
    memcpy(c, &decimal_point, 1);
    c += 1;
    memcpy(c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
    c += end - (decimal_point_pos + 1);
    *c = 0;


            

Reported by FlawFinder.

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

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

                  c += decimal_point_pos - digits_pos;
    memcpy(c, &decimal_point, 1);
    c += 1;
    memcpy(c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
    c += end - (decimal_point_pos + 1);
    *c = 0;

    val = strtod(copy, &fail_pos);


            

Reported by FlawFinder.

torch/csrc/jit/serialization/export_module.cpp
3 issues
setstate - This function is not sufficiently random for security-related functions such as key and nonce creation
Security

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

                  Function& setstate = type->getMethod("__setstate__");
    const auto qn =
        type_name_uniquer_.getUniqueName(obj->type()).qualifiedName() + "." +
        setstate.name();
    if (qn_cache.find(qn) != qn_cache.end()) {
      return;
    }
    if (setstate.isGraphFunction()) {
      auto func_tuple = getFunctionTuple(

            

Reported by FlawFinder.

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

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

                  if (qn_cache.find(qn) != qn_cache.end()) {
      return;
    }
    if (setstate.isGraphFunction()) {
      auto func_tuple = getFunctionTuple(
          module, setstate, debug_info_recorder, qn, type_name_uniquer_);
      elements.push_back(func_tuple.first);
      qn_cache.emplace(qn);
      debug_info_elements.push_back(func_tuple.second);

            

Reported by FlawFinder.

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

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

                  }
    if (setstate.isGraphFunction()) {
      auto func_tuple = getFunctionTuple(
          module, setstate, debug_info_recorder, qn, type_name_uniquer_);
      elements.push_back(func_tuple.first);
      qn_cache.emplace(qn);
      debug_info_elements.push_back(func_tuple.second);
    }
  } else {

            

Reported by FlawFinder.

torch/csrc/jit/serialization/unpickler.h
3 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

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

                  T item;
    if (sizeof(T) <= buffer_remaining_) {
      // Fast path: entirely from buffer.
      memcpy(&item, buffer_.data() + buffer_pos_, sizeof(T));
      buffer_remaining_ -= sizeof(T);
      buffer_pos_ += sizeof(T);
    } else {
      // Don't over-template the slow path, to avoid code size bloat.
      readSlowWithBuffer(reinterpret_cast<char*>(&item), sizeof(T));

            

Reported by FlawFinder.

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

Line: 90 Column: 5 CWE codes: 120 20

                // No arguments ensures that a template argument must be specified
  // so that the number of bytes read / type read is explicit
  template <typename T>
  T read() {
    T item;
    if (sizeof(T) <= buffer_remaining_) {
      // Fast path: entirely from buffer.
      memcpy(&item, buffer_.data() + buffer_pos_, sizeof(T));
      buffer_remaining_ -= sizeof(T);

            

Reported by FlawFinder.

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

Line: 116 Column: 38 CWE codes: 120 20

              #endif
  PickleOpCode readInstruction();
  PickleOpCode readOpCode() {
    return static_cast<PickleOpCode>(read<uint8_t>());
  }
  std::string readString();
  void readList(IValue list_ivalue);
  void setInput(size_t memo_id);
  void run();

            

Reported by FlawFinder.

torch/csrc/jit/tensorexpr/hash_provider.h
3 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

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

                  // memcpy as type punning. Should be optimized out.
    // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
    int64_t n;
    std::memcpy(&n, &d, sizeof d);
    return te_hash(n);
  }

  size_t te_hash(float d) {
    // memcpy as type punning. Should be optimized out.

            

Reported by FlawFinder.

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

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

                  // memcpy as type punning. Should be optimized out.
    // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
    int32_t n;
    std::memcpy(&n, &d, sizeof d);
    return te_hash(n);
  }

  size_t te_hash(at::Half d) {
    // memcpy as type punning. Should be optimized out.

            

Reported by FlawFinder.

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

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

                  // memcpy as type punning. Should be optimized out.
    // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
    int16_t n;
    std::memcpy(&n, &d, sizeof d);
    return te_hash(n);
  }
};

} // namespace tensorexpr

            

Reported by FlawFinder.

torch/csrc/jit/tensorexpr/kernel.cpp
3 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: 81 Column: 42 CWE codes: 807 20
Suggestion: Check environment variables carefully before using them

              }

bool fallbackAllowed() {
  static const char* enable_c_str = std::getenv("PYTORCH_TENSOREXPR_FALLBACK");
  if (!enable_c_str) {
    return fallback_allowed;
  }
  if (std::string(enable_c_str) == "0") {
    return false;

            

Reported by FlawFinder.

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: 92 Column: 42 CWE codes: 807 20
Suggestion: Check environment variables carefully before using them

              }

bool fallbackEnforced() {
  static const char* enable_c_str = std::getenv("PYTORCH_TENSOREXPR_FALLBACK");
  if (tensorexpr::getTEGenerateBlockCode()) {
    return false;
  }
  if (!enable_c_str) {
    return fallback_allowed;

            

Reported by FlawFinder.

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: 107 Column: 12 CWE codes: 807 20
Suggestion: Check environment variables carefully before using them

              
bool dontUseLLVMFlag() {
  static const char* enable_c_str =
      std::getenv("PYTORCH_TENSOREXPR_DONT_USE_LLVM");
  if (!enable_c_str) {
    return false;
  }
  return std::string(enable_c_str) == "1";
}

            

Reported by FlawFinder.

torch/csrc/tensor/python_tensor.cpp
3 issues
char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

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

                THPLayout* layout;
  bool is_cuda;
  // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,cppcoreguidelines-avoid-magic-numbers,modernize-avoid-c-arrays)
  char name[64];
  int backend;
  int scalar_type;

  Backend get_backend() const {
    return static_cast<Backend>(backend);

            

Reported by FlawFinder.

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

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

                // we need to initialize as many types as there are VariableType instances.
  // We copy the basic object fields from a prototype definition and initialize
  // the remaining fields below.
  memcpy(&type, &tensor_type_prototype, sizeof(PyTypeObject));
  // Subclassing from torch.<ScalarType>Tensor isn't supported.
  // (Py_TPFLAGS_BASETYPE omitted). Subclassing torch.Tensor still allowed.
  type.tp_flags = Py_TPFLAGS_DEFAULT;
  type.tp_name = name;
  type.tp_new = Tensor_new;

            

Reported by FlawFinder.

strncpy - Easily used incorrectly; doesn't always \0-terminate or check for invalid pointers [MS-banned]
Security

Line: 234 Column: 3 CWE codes: 120

              
static void set_name(PyTensorType& type_obj, const std::string& name) {
  size_t n = sizeof(type_obj.name);
  strncpy(type_obj.name, name.c_str(), n);
  type_obj.name[n - 1] = '\0';
}

static THPObjectPtr get_tensor_dict() {
  auto torch = THPObjectPtr(PyImport_ImportModule("torch"));

            

Reported by FlawFinder.

torch/csrc/utils.cpp
3 issues
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: 152 Column: 3 CWE codes: 134
Suggestion: Use a constant for the format specification

                va_list fmt_args;

  va_start(fmt_args, format);
  vsnprintf(buffer, ERROR_BUFFER_SIZE, format, fmt_args);
  va_end(fmt_args);
  PyErr_SetString(PyExc_RuntimeError, buffer);
}

void THPUtils_addPyMethodDefs(std::vector<PyMethodDef>& vector, PyMethodDef* methods)

            

Reported by FlawFinder.

strcpy - Does not check for buffer overflows when copying to destination [MS-banned]
Security

Line: 311 Column: 3 CWE codes: 120
Suggestion: Consider using snprintf, strcpy_s, or strlcpy (warning: strncpy easily misused)

                  goto error;
  }
  // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.strcpy)
  strcpy(result, buf);
  Py_XDECREF(pytensor);
  Py_XDECREF(repr);
  PyGILState_Release(gil);
  return result;


            

Reported by FlawFinder.

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

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

              {
  static const size_t ERROR_BUFFER_SIZE = 1000;
  // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays)
  char buffer[ERROR_BUFFER_SIZE];
  va_list fmt_args;

  va_start(fmt_args, format);
  vsnprintf(buffer, ERROR_BUFFER_SIZE, format, fmt_args);
  va_end(fmt_args);

            

Reported by FlawFinder.

torch/csrc/utils/python_arg_parser.cpp
3 issues
Using pointer to temporary.
Error

Line: 243 CWE codes: 562

                    }
    }
    const std::string& tmp = ss.str();
    PyErr_SetString(PyExc_TypeError, tmp.c_str());
    throw python_error();
  }
  return ret.release().ptr();
}


            

Reported by Cppcheck.

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

Line: 115 Column: 12 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 bracket = type_str.find('[');
  if (bracket != std::string::npos) {
    auto size_str = type_str.substr(bracket + 1, type_str.length() - bracket - 2);
    size = atoi(size_str.c_str());
    type_str = type_str.substr(0, bracket);
  }

  auto name_str = fmt.substr(space + 1);
  auto it = type_map.find(type_str);

            

Reported by FlawFinder.

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

Line: 651 Column: 19 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)

                    throw std::runtime_error("default value for Tensor must be none, got: " + str);
    }
  } else if (type_ == ParameterType::INT64) {
    default_int = atol(str.c_str());
  } else if (type_ == ParameterType::BOOL) {
    default_bool = (str == "True" || str == "true");
  } else if (type_ == ParameterType::DOUBLE) {
    default_double = atof(str.c_str());
  } else if (type_ == ParameterType::COMPLEX) {

            

Reported by FlawFinder.

torch/cuda/amp/__init__.py
3 issues
Unable to import '__init__.autocast_mode'
Error

Line: 1 Column: 1

              from .autocast_mode import autocast, custom_fwd, custom_bwd  # noqa: F401
from .grad_scaler import GradScaler  # noqa: F401

            

Reported by Pylint.

Unable to import '__init__.grad_scaler'
Error

Line: 2 Column: 1

              from .autocast_mode import autocast, custom_fwd, custom_bwd  # noqa: F401
from .grad_scaler import GradScaler  # noqa: F401

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from .autocast_mode import autocast, custom_fwd, custom_bwd  # noqa: F401
from .grad_scaler import GradScaler  # noqa: F401

            

Reported by Pylint.