Skip to content

Commit

Permalink
Make sure ephemeral module caches are created inside $TMPDIR.
Browse files Browse the repository at this point in the history
RELNOTES: None.
PiperOrigin-RevId: 253584868
  • Loading branch information
allevato authored and swiple-rules-gardener committed Jun 17, 2019
1 parent f059804 commit d0e5f4f
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions tools/common/temp_file.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,17 @@ class TempFile {
// form used by `mkstemp`). The file will automatically be deleted when the
// object goes out of scope.
static std::unique_ptr<TempFile> Create(const std::string &path_template) {
size_t size = path_template.size() + 1;
const char *tmpDir = getenv("TMPDIR");
if (!tmpDir) {
tmpDir = "/tmp";
}
size_t size = strlen(tmpDir) + path_template.size() + 2;
std::unique_ptr<char[]> path(new char[size]);
snprintf(path.get(), size, "%s", path_template.c_str());
snprintf(path.get(), size, "%s/%s", tmpDir, path_template.c_str());

if (mkstemp(path.get()) == -1) {
std::cerr << "Failed to create temporary file: " << strerror(errno)
<< "\n";
std::cerr << "Failed to create temporary file '" << path.get() << "': "
<< strerror(errno) << "\n";
return nullptr;
}
return std::unique_ptr<TempFile>(new TempFile(path.get()));
Expand Down Expand Up @@ -69,13 +73,17 @@ class TempDirectory {
// the object goes out of scope.
static std::unique_ptr<TempDirectory> Create(
const std::string &path_template) {
size_t size = path_template.size() + 1;
const char *tmpDir = getenv("TMPDIR");
if (!tmpDir) {
tmpDir = "/tmp";
}
size_t size = strlen(tmpDir) + path_template.size() + 2;
std::unique_ptr<char[]> path(new char[size]);
snprintf(path.get(), size, "%s", path_template.c_str());
snprintf(path.get(), size, "%s/%s", tmpDir, path_template.c_str());

if (mkdtemp(path.get()) == nullptr) {
std::cerr << "Failed to create temporary directory: " << strerror(errno)
<< "\n";
std::cerr << "Failed to create temporary directory '" << path.get()
<< "': " << strerror(errno) << "\n";
return nullptr;
}
return std::unique_ptr<TempDirectory>(new TempDirectory(path.get()));
Expand Down

0 comments on commit d0e5f4f

Please sign in to comment.