Sort #include lines
[folly.git] / folly / experimental / TestUtil.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <folly/experimental/TestUtil.h>
18
19 #include <sys/stat.h>
20 #include <sys/types.h>
21
22 #include <boost/regex.hpp>
23
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>
30
31 #ifdef _WIN32
32 #include <crtdbg.h> // @manual
33 #endif
34
35 namespace folly {
36 namespace test {
37
38 namespace {
39
40 fs::path generateUniquePath(fs::path path, StringPiece namePrefix) {
41   if (path.empty()) {
42     path = fs::temp_directory_path();
43   }
44   if (namePrefix.empty()) {
45     path /= fs::unique_path();
46   } else {
47     path /= fs::unique_path(
48         to<std::string>(namePrefix, ".%%%%-%%%%-%%%%-%%%%"));
49   }
50   return path;
51 }
52
53 }  // namespace
54
55 TemporaryFile::TemporaryFile(StringPiece namePrefix,
56                              fs::path dir,
57                              Scope scope,
58                              bool closeOnDestruction)
59   : scope_(scope),
60     closeOnDestruction_(closeOnDestruction),
61     fd_(-1),
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");
65
66   if (scope_ == Scope::UNLINK_IMMEDIATELY) {
67     boost::system::error_code ec;
68     fs::remove(path_, ec);
69     if (ec) {
70       LOG(WARNING) << "unlink on construction failed: " << ec;
71     } else {
72       path_.clear();
73     }
74   }
75 }
76
77 const fs::path& TemporaryFile::path() const {
78   CHECK(scope_ != Scope::UNLINK_IMMEDIATELY);
79   DCHECK(!path_.empty());
80   return path_;
81 }
82
83 TemporaryFile::~TemporaryFile() {
84   if (fd_ != -1 && closeOnDestruction_) {
85     if (close(fd_) == -1) {
86       PLOG(ERROR) << "close failed";
87     }
88   }
89
90   // If we previously failed to unlink() (UNLINK_IMMEDIATELY), we'll
91   // try again here.
92   if (scope_ != Scope::PERMANENT && !path_.empty()) {
93     boost::system::error_code ec;
94     fs::remove(path_, ec);
95     if (ec) {
96       LOG(WARNING) << "unlink on destruction failed: " << ec;
97     }
98   }
99 }
100
101 TemporaryDirectory::TemporaryDirectory(
102     StringPiece namePrefix,
103     fs::path dir,
104     Scope scope)
105     : scope_(scope),
106       path_(std::make_unique<fs::path>(
107           generateUniquePath(std::move(dir), namePrefix))) {
108   fs::create_directory(path());
109 }
110
111 TemporaryDirectory::~TemporaryDirectory() {
112   if (scope_ == Scope::DELETE_ON_DESTRUCTION && path_ != nullptr) {
113     boost::system::error_code ec;
114     fs::remove_all(path(), ec);
115     if (ec) {
116       LOG(WARNING) << "recursive delete on destruction failed: " << ec;
117     }
118   }
119 }
120
121 ChangeToTempDir::ChangeToTempDir() : initialPath_(fs::current_path()) {
122   std::string p = dir_.path().string();
123   ::chdir(p.c_str());
124 }
125
126 ChangeToTempDir::~ChangeToTempDir() {
127   std::string p = initialPath_.string();
128   ::chdir(p.c_str());
129 }
130
131 namespace detail {
132
133 SavedState disableInvalidParameters() {
134 #ifdef _WIN32
135   SavedState ret;
136   ret.previousThreadLocalHandler = _set_thread_local_invalid_parameter_handler(
137       [](const wchar_t*,
138          const wchar_t*,
139          const wchar_t*,
140          unsigned int,
141          uintptr_t) {});
142   ret.previousCrtReportMode = _CrtSetReportMode(_CRT_ASSERT, 0);
143   return ret;
144 #else
145   return SavedState();
146 #endif
147 }
148
149 #ifdef _WIN32
150 void enableInvalidParameters(SavedState state) {
151   _set_thread_local_invalid_parameter_handler(
152       (_invalid_parameter_handler)state.previousThreadLocalHandler);
153   _CrtSetReportMode(_CRT_ASSERT, state.previousCrtReportMode);
154 }
155 #else
156 void enableInvalidParameters(SavedState) {}
157 #endif
158
159 bool hasPCREPatternMatch(StringPiece pattern, StringPiece target) {
160   return boost::regex_match(
161     target.begin(),
162     target.end(),
163     boost::regex(pattern.begin(), pattern.end())
164   );
165 }
166
167 bool hasNoPCREPatternMatch(StringPiece pattern, StringPiece target) {
168   return !hasPCREPatternMatch(pattern, target);
169 }
170
171 }  // namespace detail
172
173 CaptureFD::CaptureFD(int fd, ChunkCob chunk_cob)
174     : chunkCob_(std::move(chunk_cob)), fd_(fd), readOffset_(0) {
175   oldFDCopy_ = dup(fd_);
176   PCHECK(oldFDCopy_ != -1) << "Could not copy FD " << fd_;
177
178   int file_fd = open(file_.path().string().c_str(), O_WRONLY|O_CREAT, 0600);
179   PCHECK(dup2(file_fd, fd_) != -1) << "Could not replace FD " << fd_
180     << " with " << file_fd;
181   PCHECK(close(file_fd) != -1) << "Could not close " << file_fd;
182 }
183
184 void CaptureFD::release() {
185   if (oldFDCopy_ != fd_) {
186     readIncremental();  // Feed chunkCob_
187     PCHECK(dup2(oldFDCopy_, fd_) != -1) << "Could not restore old FD "
188       << oldFDCopy_ << " into " << fd_;
189     PCHECK(close(oldFDCopy_) != -1) << "Could not close " << oldFDCopy_;
190     oldFDCopy_ = fd_;  // Make this call idempotent
191   }
192 }
193
194 CaptureFD::~CaptureFD() {
195   release();
196 }
197
198 std::string CaptureFD::read() const {
199   std::string contents;
200   std::string filename = file_.path().string();
201   PCHECK(folly::readFile(filename.c_str(), contents));
202   return contents;
203 }
204
205 std::string CaptureFD::readIncremental() {
206   std::string filename = file_.path().string();
207   // Yes, I know that I could just keep the file open instead. So sue me.
208   folly::File f(openNoInt(filename.c_str(), O_RDONLY), true);
209   auto size = size_t(lseek(f.fd(), 0, SEEK_END) - readOffset_);
210   std::unique_ptr<char[]> buf(new char[size]);
211   auto bytes_read = folly::preadFull(f.fd(), buf.get(), size, readOffset_);
212   PCHECK(ssize_t(size) == bytes_read);
213   readOffset_ += off_t(size);
214   chunkCob_(StringPiece(buf.get(), buf.get() + size));
215   return std::string(buf.get(), size);
216 }
217
218 }  // namespace test
219 }  // namespace folly