diff --git a/samples/common/sampleOptions.cpp b/samples/common/sampleOptions.cpp index 2ea4df9a..2e10ce85 100644 --- a/samples/common/sampleOptions.cpp +++ b/samples/common/sampleOptions.cpp @@ -1434,6 +1434,11 @@ void BuildOptions::parse(Arguments& arguments) if (getAndDelOption(arguments, "--saveEngine", engine)) { save = true; + // Validate that the engine file path is writable before doing expensive work + if (!canWriteFile(engine)) + { + throw std::invalid_argument(std::string("Cannot write engine file to path: ") + engine); + } } if (load && save) { diff --git a/samples/common/sampleUtils.cpp b/samples/common/sampleUtils.cpp index 1ffcc546..921759a8 100644 --- a/samples/common/sampleUtils.cpp +++ b/samples/common/sampleUtils.cpp @@ -775,4 +775,34 @@ std::vector sanitizeArgv(int32_t argc, char** argv) return sanitizedArgs; } +bool canWriteFile(std::string const& path) +{ + namespace fs = std::filesystem; + fs::path p(path); + fs::path dir = p.has_parent_path() ? p.parent_path() : fs::current_path(); + + // Check if the directory exists and is a directory + if (!fs::exists(dir) || !fs::is_directory(dir)) + { + return false; + } + + // Try to create a temporary file to test write permissions + fs::path const tempFilePath = dir / ".writetest.tmp"; + std::ofstream test(tempFilePath.string(), std::ios::out | std::ios::trunc); + if (!test.is_open()) + { + return false; + } + test << "test"; + bool const ok = test.good(); + test.close(); + + // Clean up the temporary file + std::error_code ec; + fs::remove(tempFilePath, ec); + + return ok; +} + } // namespace sample diff --git a/samples/common/sampleUtils.h b/samples/common/sampleUtils.h index 65cb6774..645c1e41 100644 --- a/samples/common/sampleUtils.h +++ b/samples/common/sampleUtils.h @@ -18,6 +18,7 @@ #ifndef TRT_SAMPLE_UTILS_H #define TRT_SAMPLE_UTILS_H +#include #include #include #include @@ -175,6 +176,11 @@ std::string sanitizeRemoteAutoTuningConfig(const std::string& config); //! @return Vector of sanitized argument strings std::vector sanitizeArgv(int32_t argc, char** argv); +//! Check if a file path is writable by testing write access to the parent directory +//! @param path The file path to check +//! @return true if the path is writable, false otherwise +bool canWriteFile(std::string const& path); + } // namespace sample #endif // TRT_SAMPLE_UTILS_H