Skip to content

Commit

Permalink
Cleanup test File utilities (#1989)
Browse files Browse the repository at this point in the history
### Issues:
Addresses: P168988559

### Description of changes: 
* Only use move semantic for `TemporaryFile` and `ScopedFD`.
* Set umask prior to creating temporary file.

By submitting this pull request, I confirm that my contribution is made
under the terms of the Apache 2.0 license and the ISC license.
  • Loading branch information
justsmth authored Nov 13, 2024
1 parent 3aa32cc commit 9d702ec
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
2 changes: 2 additions & 0 deletions crypto/test/file_util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,9 @@ bool TemporaryFile::Init(bssl::Span<const uint8_t> content) {
#else
std::string path = temp_dir + "bssl_tmp_file.XXXXXX";
// TODO(davidben): Use |path.data()| when we require C++17.
mode_t prev_umask = umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
int fd = mkstemp(&path[0]);
umask(prev_umask);
if (fd < 0) {
perror("Could not create temporary file");
return false;
Expand Down
12 changes: 9 additions & 3 deletions crypto/test/file_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,15 @@ class ScopedFD {
explicit ScopedFD(int fd) : fd_(fd) {}
~ScopedFD() { reset(); }

ScopedFD(ScopedFD &&other) { *this = std::move(other); }
ScopedFD &operator=(ScopedFD other) {
ScopedFD(ScopedFD &&other) noexcept { *this = std::move(other); }
ScopedFD &operator=(ScopedFD&& other) {
reset(other.release());
return *this;
}

ScopedFD(const ScopedFD &other) = delete;
ScopedFD &operator=(ScopedFD& other) = delete;

bool is_valid() const { return fd_ >= 0; }
int get() const { return fd_; }

Expand Down Expand Up @@ -85,7 +88,7 @@ class TemporaryFile {
TemporaryFile() = default;
~TemporaryFile();

TemporaryFile(TemporaryFile &other) { *this = std::move(other); }
TemporaryFile(TemporaryFile&& other) noexcept { *this = std::move(other); }
TemporaryFile& operator=(TemporaryFile&&other) {
// Ensure |path_| is empty so it doesn't try to delete the File.
auto old_other_path = other.path_;
Expand All @@ -94,6 +97,9 @@ class TemporaryFile {
return *this;
}

TemporaryFile(const TemporaryFile&) = delete;
TemporaryFile& operator=(const TemporaryFile&) = delete;

// Init initializes the temporary file with the specified content. It returns
// true on success and false on error. On error, callers should call
// |IgnoreTempFileErrors| to determine whether to ignore the error.
Expand Down

0 comments on commit 9d702ec

Please sign in to comment.