2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/experimental/TestUtil.h>
20 #include <sys/types.h>
22 #include <boost/regex.hpp>
24 #include <folly/Exception.h>
25 #include <folly/File.h>
26 #include <folly/FileUtil.h>
27 #include <folly/Memory.h>
28 #include <folly/String.h>
29 #include <folly/portability/Fcntl.h>
32 #include <crtdbg.h> // @manual
40 fs::path generateUniquePath(fs::path path, StringPiece namePrefix) {
42 path = fs::temp_directory_path();
44 if (namePrefix.empty()) {
45 path /= fs::unique_path();
47 path /= fs::unique_path(
48 to<std::string>(namePrefix, ".%%%%-%%%%-%%%%-%%%%"));
55 TemporaryFile::TemporaryFile(StringPiece namePrefix,
58 bool closeOnDestruction)
60 closeOnDestruction_(closeOnDestruction),
62 path_(generateUniquePath(std::move(dir), namePrefix)) {
63 fd_ = open(path_.string().c_str(), O_RDWR | O_CREAT | O_EXCL, 0666);
64 checkUnixError(fd_, "open failed");
66 if (scope_ == Scope::UNLINK_IMMEDIATELY) {
67 boost::system::error_code ec;
68 fs::remove(path_, ec);
70 LOG(WARNING) << "unlink on construction failed: " << ec;
77 void TemporaryFile::close() {
78 if (::close(fd_) == -1) {
79 PLOG(ERROR) << "close failed";
84 const fs::path& TemporaryFile::path() const {
85 CHECK(scope_ != Scope::UNLINK_IMMEDIATELY);
86 DCHECK(!path_.empty());
90 TemporaryFile::~TemporaryFile() {
91 if (fd_ != -1 && closeOnDestruction_) {
92 if (::close(fd_) == -1) {
93 PLOG(ERROR) << "close failed";
97 // If we previously failed to unlink() (UNLINK_IMMEDIATELY), we'll
99 if (scope_ != Scope::PERMANENT && !path_.empty()) {
100 boost::system::error_code ec;
101 fs::remove(path_, ec);
103 LOG(WARNING) << "unlink on destruction failed: " << ec;
108 TemporaryDirectory::TemporaryDirectory(
109 StringPiece namePrefix,
113 path_(std::make_unique<fs::path>(
114 generateUniquePath(std::move(dir), namePrefix))) {
115 fs::create_directory(path());
118 TemporaryDirectory::~TemporaryDirectory() {
119 if (scope_ == Scope::DELETE_ON_DESTRUCTION && path_ != nullptr) {
120 boost::system::error_code ec;
121 fs::remove_all(path(), ec);
123 LOG(WARNING) << "recursive delete on destruction failed: " << ec;
128 ChangeToTempDir::ChangeToTempDir() : initialPath_(fs::current_path()) {
129 std::string p = dir_.path().string();
133 ChangeToTempDir::~ChangeToTempDir() {
134 std::string p = initialPath_.string();
140 SavedState disableInvalidParameters() {
143 ret.previousThreadLocalHandler = _set_thread_local_invalid_parameter_handler(
149 ret.previousCrtReportMode = _CrtSetReportMode(_CRT_ASSERT, 0);
157 void enableInvalidParameters(SavedState state) {
158 _set_thread_local_invalid_parameter_handler(
159 (_invalid_parameter_handler)state.previousThreadLocalHandler);
160 _CrtSetReportMode(_CRT_ASSERT, state.previousCrtReportMode);
163 void enableInvalidParameters(SavedState) {}
166 bool hasPCREPatternMatch(StringPiece pattern, StringPiece target) {
167 return boost::regex_match(
170 boost::regex(pattern.begin(), pattern.end())
174 bool hasNoPCREPatternMatch(StringPiece pattern, StringPiece target) {
175 return !hasPCREPatternMatch(pattern, target);
178 } // namespace detail
180 CaptureFD::CaptureFD(int fd, ChunkCob chunk_cob)
181 : chunkCob_(std::move(chunk_cob)), fd_(fd), readOffset_(0) {
182 oldFDCopy_ = dup(fd_);
183 PCHECK(oldFDCopy_ != -1) << "Could not copy FD " << fd_;
185 int file_fd = open(file_.path().string().c_str(), O_WRONLY|O_CREAT, 0600);
186 PCHECK(dup2(file_fd, fd_) != -1) << "Could not replace FD " << fd_
187 << " with " << file_fd;
188 PCHECK(close(file_fd) != -1) << "Could not close " << file_fd;
191 void CaptureFD::release() {
192 if (oldFDCopy_ != fd_) {
193 readIncremental(); // Feed chunkCob_
194 PCHECK(dup2(oldFDCopy_, fd_) != -1) << "Could not restore old FD "
195 << oldFDCopy_ << " into " << fd_;
196 PCHECK(close(oldFDCopy_) != -1) << "Could not close " << oldFDCopy_;
197 oldFDCopy_ = fd_; // Make this call idempotent
201 CaptureFD::~CaptureFD() {
205 std::string CaptureFD::read() const {
206 std::string contents;
207 std::string filename = file_.path().string();
208 PCHECK(folly::readFile(filename.c_str(), contents));
212 std::string CaptureFD::readIncremental() {
213 std::string filename = file_.path().string();
214 // Yes, I know that I could just keep the file open instead. So sue me.
215 folly::File f(openNoInt(filename.c_str(), O_RDONLY), true);
216 auto size = size_t(lseek(f.fd(), 0, SEEK_END) - readOffset_);
217 std::unique_ptr<char[]> buf(new char[size]);
218 auto bytes_read = folly::preadFull(f.fd(), buf.get(), size, readOffset_);
219 PCHECK(ssize_t(size) == bytes_read);
220 readOffset_ += off_t(size);
221 chunkCob_(StringPiece(buf.get(), buf.get() + size));
222 return std::string(buf.get(), size);