Skip to content

Commit b3541c3

Browse files
authored
Merge pull request #4789 from vicentebolea/fix-testutils
tests: sanitize path before removal
2 parents 15d9242 + cb4e336 commit b3541c3

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

testing/adios2/engine/TestHelpers.h

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,23 +14,58 @@
1414
#include <cstdint>
1515
#include <cstdlib>
1616
#include <limits>
17+
#include <regex>
1718
#include <string>
1819
#include <vector>
1920

2021
#ifdef _MSC_VER
2122
#define NOMINMAX
2223
#endif
2324

25+
// Include appropriate headers based on the operating system
26+
#ifdef _WIN32
27+
#include <direct.h>
28+
#define GetCurrentDir _getcwd
29+
#else
30+
#include <unistd.h>
31+
#define GetCurrentDir getcwd
32+
#endif
33+
34+
std::string get_current_dir()
35+
{
36+
char buff[FILENAME_MAX]; // FILENAME_MAX is a platform-specific macro for buffer size
37+
if (GetCurrentDir(buff, FILENAME_MAX) != NULL)
38+
{
39+
return std::string(buff);
40+
}
41+
else
42+
{
43+
// Handle error (e.g., buffer too small)
44+
return std::string("");
45+
}
46+
}
47+
2448
// Helper function to cleanup test files/directories
2549
inline void CleanupTestFiles(const std::string &path)
2650
{
51+
// CWD is the build_dir, we will only remove child dirs of the build_dir
52+
if (path.find(get_current_dir()) == std::string::npos)
53+
{
54+
return;
55+
}
56+
57+
// Allows: alphanumeric, spaces, hyphens, underscores, periods, forward/backslashes
58+
std::regex valid_chars("[^a-zA-Z0-9 ._/\\\\-:]");
59+
std::string safe_path = std::regex_replace(path, valid_chars, "");
60+
2761
#ifdef _WIN32
2862
// Windows: use rmdir for directories, del for files
2963
// Try rmdir first (for .bp directories), fall back to del (for files)
30-
std::string cmd = "rmdir /s /q \"" + path + "\" 2>nul || del /q \"" + path + "\" 2>nul";
64+
std::string cmd =
65+
"rmdir /s /q \"" + safe_path + "\" 2>nul || del /q \"" + safe_path + "\" 2>nul";
3166
#else
3267
// Unix/Linux/macOS: use rm -rf
33-
std::string cmd = "rm -rf " + path;
68+
std::string cmd = "rm -rf " + safe_path;
3469
#endif
3570
int rc = std::system(cmd.c_str());
3671

0 commit comments

Comments
 (0)