The following issues were found

android/pytorch_android/src/main/cpp/pytorch_jni_common.h
2 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

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

              
  size_t read(uint64_t pos, void* buf, size_t n, const char* what = "")
      const override {
    memcpy(buf, (int8_t*)(data_) + pos, n);
    return n;
  }

  ~MemoryReadAdapter() {}


            

Reported by FlawFinder.

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

Line: 82 Column: 10 CWE codes: 120 20

                  return size_;
  }

  size_t read(uint64_t pos, void* buf, size_t n, const char* what = "")
      const override {
    memcpy(buf, (int8_t*)(data_) + pos, n);
    return n;
  }


            

Reported by FlawFinder.

android/pytorch_android/src/main/java/org/pytorch/Module.java
2 issues
Private field 'mNativePeer' could be made final; it is only initialized in the declaration or constructor.
Design

Line: 12

              /** Java wrapper for torch::jit::Module. */
public class Module {

  private INativePeer mNativePeer;

  /**
   * Loads a serialized TorchScript module from the specified path on the disk to run on specified
   * device.
   *

            

Reported by PMD.

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

Line: 12

              /** Java wrapper for torch::jit::Module. */
public class Module {

  private INativePeer mNativePeer;

  /**
   * Loads a serialized TorchScript module from the specified path on the disk to run on specified
   * device.
   *

            

Reported by PMD.

android/pytorch_android/src/main/java/org/pytorch/PyTorchAndroid.java
2 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: 8

              import com.facebook.soloader.nativeloader.NativeLoader;
import com.facebook.soloader.nativeloader.SystemDelegate;

public final class PyTorchAndroid {
  static {
    if (!NativeLoader.isInitialized()) {
      NativeLoader.init(new SystemDelegate());
    }
    NativeLoader.loadLibrary("pytorch_jni_lite");

            

Reported by PMD.

Avoid using Literals in Conditional Statements
Error

Line: 41

                 * @param numThreads number of threads, must be positive number.
   */
  public static void setNumThreads(int numThreads) {
    if (numThreads < 1) {
      throw new IllegalArgumentException("Number of threads cannot be less than 1");
    }

    nativeSetNumThreads(numThreads);
  }

            

Reported by PMD.

android/pytorch_android_torchvision/src/androidTest/java/org/pytorch/torchvision/TorchVisionInstrumentedTests.java
2 issues
Potential violation of Law of Demeter (object not created locally)
Design

Line: 22

                          bitmap,
            TensorImageUtils.TORCHVISION_NORM_MEAN_RGB,
            TensorImageUtils.TORCHVISION_NORM_STD_RGB);
    assertArrayEquals(new long[] {1l, 3l, 240l, 320l}, tensor.shape());
  }
}

            

Reported by PMD.

JUnit assertions should include a message
Design

Line: 22

                          bitmap,
            TensorImageUtils.TORCHVISION_NORM_MEAN_RGB,
            TensorImageUtils.TORCHVISION_NORM_STD_RGB);
    assertArrayEquals(new long[] {1l, 3l, 240l, 320l}, tensor.shape());
  }
}

            

Reported by PMD.

aten/src/ATen/CPUApplyUtils.h
2 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

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

                    : data_(tensor.data_ptr<T>()) {
    std::memset(counter_, 0, sizeof(int64_t) * N);
    if (tensor.dim() > 0) {
      std::memcpy(
          sizes_, tensor.sizes().data(), tensor.dim() * sizeof(int64_t));
      std::memcpy(
          strides_,
          tensor.strides().data(),
          tensor.dim() * sizeof(int64_t));

            

Reported by FlawFinder.

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

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

                  if (tensor.dim() > 0) {
      std::memcpy(
          sizes_, tensor.sizes().data(), tensor.dim() * sizeof(int64_t));
      std::memcpy(
          strides_,
          tensor.strides().data(),
          tensor.dim() * sizeof(int64_t));
    }
    dim_ = std::get<1>(collapse_dims(sizes_, strides_, tensor.ndimension()));

            

Reported by FlawFinder.

aten/src/ATen/MapAllocator.cpp
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: 257 Column: 19 CWE codes: 362

              
    if (!(flags_ & ALLOCATOR_MAPPED_FROMFD)) {
      if (flags_ & ALLOCATOR_MAPPED_SHARED) {
        if ((fd = open(filename_.c_str(), flags, (mode_t)0600)) == -1) {
          TORCH_INTERNAL_ASSERT(false, "unable to open file <", filename_, "> in read-write mode");
        }
      } else if (flags_ & ALLOCATOR_MAPPED_SHAREDMEM) {
#ifdef HAVE_SHM_OPEN
        if((fd = shm_open(filename_.c_str(), flags, (mode_t)0600)) == -1) {

            

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: 269 Column: 19 CWE codes: 362

                      TORCH_INTERNAL_ASSERT(false, "unable to open file <", filename_, "> in sharedmem mode, shm_open unavailable on this platform");
#endif
      } else {
        if ((fd = open(filename_.c_str(), O_RDONLY)) == -1) {
          TORCH_INTERNAL_ASSERT(false, "unable to open file <", filename_, "> in read-only mode");
        }
      }
    } else {
      fd = fd_;

            

Reported by FlawFinder.

aten/src/ATen/ParallelCommon.cpp
2 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: 24 Column: 28 CWE codes: 807 20
Suggestion: Check environment variables carefully before using them

              
const char* get_env_var(
    const char* var_name, const char* def_value = nullptr) {
  const char* value = std::getenv(var_name);
  return value ? value : def_value;
}

size_t get_env_num_threads(const char* var_name, size_t def_value = 0) {
  try {

            

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

              
size_t get_env_num_threads(const char* var_name, size_t def_value = 0) {
  try {
    if (auto* value = std::getenv(var_name)) {
      int nthreads = c10::stoi(value);
      TORCH_CHECK(nthreads > 0);
      return nthreads;
    }
  } catch (const std::exception& e) {

            

Reported by FlawFinder.

aten/src/ATen/core/Vitals.cpp
2 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: 44 Column: 14 CWE codes: 807 20
Suggestion: Check environment variables carefully before using them

                // If this is a performance hit, make `enabled` variable static
  // and return `const bool&` instead
  bool enabled = []() {
    auto e = getenv("TORCH_VITAL");
    if (e != nullptr) {
      return strlen(e) > 0;
    }
    return false;
  }();

            

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

                bool enabled = []() {
    auto e = getenv("TORCH_VITAL");
    if (e != nullptr) {
      return strlen(e) > 0;
    }
    return false;
  }();
  if (enabled) {
    VitalsAPI.vitals_enabled = true;

            

Reported by FlawFinder.

aten/src/ATen/cpu/vec/vec256/vec256_bfloat16.h
2 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

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

                }
  static Vectorized<BFloat16> loadu(const void* ptr, int16_t count) {
    __at_align__ int16_t tmp_values[size()];
    std::memcpy(tmp_values, ptr, count * sizeof(int16_t));
    return loadu(tmp_values);
  }
  void store(void* ptr, int count = size()) const {
    if (count == size()) {
      _mm256_storeu_si256(reinterpret_cast<__m256i*>(ptr), values);

            

Reported by FlawFinder.

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

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

                  } else if (count > 0) {
      __at_align__ int16_t tmp_values[size()];
      _mm256_storeu_si256(reinterpret_cast<__m256i*>(tmp_values), values);
      std::memcpy(ptr, tmp_values, count * sizeof(int16_t));
    }
  }
  template <int64_t mask>
  static Vectorized<BFloat16> blend(const Vectorized<BFloat16>& a, const Vectorized<BFloat16>& b) {
    __at_align__ int16_t tmp_values[size()];

            

Reported by FlawFinder.

aten/src/ATen/cpu/vec/vec256/vec256_complex_double.h
2 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

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

                  for (auto i = 0; i < 2*size(); ++i) {
      tmp_values[i] = 0.0;
    }
    std::memcpy(
        tmp_values,
        reinterpret_cast<const double*>(ptr),
        count * sizeof(c10::complex<double>));
    return _mm256_load_pd(tmp_values);
  }

            

Reported by FlawFinder.

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

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

                  } else if (count > 0) {
      double tmp_values[2*size()];
      _mm256_storeu_pd(reinterpret_cast<double*>(tmp_values), values);
      std::memcpy(ptr, tmp_values, count * sizeof(c10::complex<double>));
    }
  }
  const c10::complex<double>& operator[](int idx) const  = delete;
  c10::complex<double>& operator[](int idx) = delete;
  Vectorized<c10::complex<double>> map(c10::complex<double> (*const f)(const c10::complex<double> &)) const {

            

Reported by FlawFinder.