1 //===----------------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifndef TEST_SUPPORT_CHECK_ASSERTION_H 10 #define TEST_SUPPORT_CHECK_ASSERTION_H 11 12 #include <cassert> 13 #include <cstddef> 14 #include <cstdio> 15 #include <cstdlib> 16 #include <string> 17 #include <string_view> 18 #include <utility> 19 20 #include <unistd.h> 21 #include <errno.h> 22 #include <sys/wait.h> 23 #include "test_macros.h" 24 #include "test_allocator.h" 25 26 #ifndef _LIBCPP_VERSION 27 # error "This header may only be used for libc++ tests" 28 #endif 29 30 #if TEST_STD_VER < 11 31 # error "C++11 or greater is required to use this header" 32 #endif 33 34 struct AssertionInfoMatcher { 35 static const int any_line = -1; 36 static constexpr const char* any_file = "*"; 37 static constexpr const char* any_msg = "*"; 38 39 constexpr AssertionInfoMatcher() : is_empty_(true), msg_(any_msg, __builtin_strlen(any_msg)), file_(any_file, __builtin_strlen(any_file)), line_(any_line) { } 40 constexpr AssertionInfoMatcher(const char* msg, const char* file = any_file, int line = any_line) 41 : is_empty_(false), msg_(msg, __builtin_strlen(msg)), file_(file, __builtin_strlen(file)), line_(line) {} 42 43 bool Matches(char const* file, int line, char const* message) const { 44 assert(!empty() && "empty matcher"); 45 46 if (CheckLineMatches(line) && CheckFileMatches(file) && CheckMessageMatches(message)) 47 return true; 48 // Write to stdout because that's the file descriptor captured by the parent 49 // process. 50 std::printf("Failed to match assertion info!\n%s\nVS\n%s:%d (%s)\n", ToString().data(), file, line, message); 51 return false; 52 } 53 54 std::string ToString() const { 55 std::string result = "msg = \""; result += msg_; result += "\"\n"; 56 result += "line = " + (line_ == any_line ? "'*'" : std::to_string(line_)) + "\n"; 57 result += "file = " + (file_ == any_file ? "'*'" : std::string(file_)); 58 return result; 59 } 60 61 bool empty() const { return is_empty_; } 62 private: 63 bool CheckLineMatches(int got_line) const { 64 if (line_ == any_line) 65 return true; 66 return got_line == line_; 67 } 68 69 bool CheckFileMatches(std::string_view got_file) const { 70 assert(!empty() && "empty matcher"); 71 if (file_ == any_file) 72 return true; 73 std::size_t found_at = got_file.find(file_); 74 if (found_at == std::string_view::npos) 75 return false; 76 // require the match start at the beginning of the file or immediately after 77 // a directory separator. 78 if (found_at != 0) { 79 char last_char = got_file[found_at - 1]; 80 if (last_char != '/' && last_char != '\\') 81 return false; 82 } 83 // require the match goes until the end of the string. 84 return got_file.substr(found_at) == file_; 85 } 86 87 bool CheckMessageMatches(std::string_view got_msg) const { 88 assert(!empty() && "empty matcher"); 89 if (msg_ == any_msg) 90 return true; 91 std::size_t found_at = got_msg.find(msg_); 92 if (found_at == std::string_view::npos) 93 return false; 94 // Allow any match 95 return true; 96 } 97 private: 98 bool is_empty_; 99 std::string_view msg_; 100 std::string_view file_; 101 int line_; 102 }; 103 104 static constexpr AssertionInfoMatcher AnyMatcher(AssertionInfoMatcher::any_msg); 105 106 inline AssertionInfoMatcher& GlobalMatcher() { 107 static AssertionInfoMatcher GMatch; 108 return GMatch; 109 } 110 111 struct DeathTest { 112 enum ResultKind { 113 RK_DidNotDie, RK_MatchFound, RK_MatchFailure, RK_SetupFailure, RK_Unknown 114 }; 115 116 static const char* ResultKindToString(ResultKind RK) { 117 #define CASE(K) case K: return #K 118 switch (RK) { 119 CASE(RK_MatchFailure); 120 CASE(RK_DidNotDie); 121 CASE(RK_SetupFailure); 122 CASE(RK_MatchFound); 123 CASE(RK_Unknown); 124 } 125 return "not a result kind"; 126 } 127 128 static bool IsValidResultKind(int val) { 129 return val >= RK_DidNotDie && val <= RK_Unknown; 130 } 131 132 DeathTest(AssertionInfoMatcher const& Matcher) : matcher_(Matcher) {} 133 134 template <class Func> 135 ResultKind Run(Func&& f) { 136 int pipe_res = pipe(stdout_pipe_fd_); 137 assert(pipe_res != -1 && "failed to create pipe"); 138 pipe_res = pipe(stderr_pipe_fd_); 139 assert(pipe_res != -1 && "failed to create pipe"); 140 pid_t child_pid = fork(); 141 assert(child_pid != -1 && 142 "failed to fork a process to perform a death test"); 143 child_pid_ = child_pid; 144 if (child_pid_ == 0) { 145 RunForChild(std::forward<Func>(f)); 146 assert(false && "unreachable"); 147 } 148 return RunForParent(); 149 } 150 151 int getChildExitCode() const { return exit_code_; } 152 std::string const& getChildStdOut() const { return stdout_from_child_; } 153 std::string const& getChildStdErr() const { return stderr_from_child_; } 154 private: 155 template <class Func> 156 TEST_NORETURN void RunForChild(Func&& f) { 157 close(GetStdOutReadFD()); // don't need to read from the pipe in the child. 158 close(GetStdErrReadFD()); 159 auto DupFD = [](int DestFD, int TargetFD) { 160 int dup_result = dup2(DestFD, TargetFD); 161 if (dup_result == -1) 162 std::exit(RK_SetupFailure); 163 }; 164 DupFD(GetStdOutWriteFD(), STDOUT_FILENO); 165 DupFD(GetStdErrWriteFD(), STDERR_FILENO); 166 167 GlobalMatcher() = matcher_; 168 f(); 169 std::exit(RK_DidNotDie); 170 } 171 172 static std::string ReadChildIOUntilEnd(int FD) { 173 std::string error_msg; 174 char buffer[256]; 175 int num_read; 176 do { 177 while ((num_read = read(FD, buffer, 255)) > 0) { 178 buffer[num_read] = '\0'; 179 error_msg += buffer; 180 } 181 } while (num_read == -1 && errno == EINTR); 182 return error_msg; 183 } 184 185 void CaptureIOFromChild() { 186 close(GetStdOutWriteFD()); // no need to write from the parent process 187 close(GetStdErrWriteFD()); 188 stdout_from_child_ = ReadChildIOUntilEnd(GetStdOutReadFD()); 189 stderr_from_child_ = ReadChildIOUntilEnd(GetStdErrReadFD()); 190 close(GetStdOutReadFD()); 191 close(GetStdErrReadFD()); 192 } 193 194 ResultKind RunForParent() { 195 CaptureIOFromChild(); 196 197 int status_value; 198 pid_t result = waitpid(child_pid_, &status_value, 0); 199 assert(result != -1 && "there is no child process to wait for"); 200 201 if (WIFEXITED(status_value)) { 202 exit_code_ = WEXITSTATUS(status_value); 203 if (!IsValidResultKind(exit_code_)) 204 return RK_Unknown; 205 return static_cast<ResultKind>(exit_code_); 206 } 207 return RK_Unknown; 208 } 209 210 DeathTest(DeathTest const&) = delete; 211 DeathTest& operator=(DeathTest const&) = delete; 212 213 int GetStdOutReadFD() const { 214 return stdout_pipe_fd_[0]; 215 } 216 217 int GetStdOutWriteFD() const { 218 return stdout_pipe_fd_[1]; 219 } 220 221 int GetStdErrReadFD() const { 222 return stderr_pipe_fd_[0]; 223 } 224 225 int GetStdErrWriteFD() const { 226 return stderr_pipe_fd_[1]; 227 } 228 private: 229 AssertionInfoMatcher matcher_; 230 pid_t child_pid_ = -1; 231 int exit_code_ = -1; 232 int stdout_pipe_fd_[2]; 233 int stderr_pipe_fd_[2]; 234 std::string stdout_from_child_; 235 std::string stderr_from_child_; 236 }; 237 238 void std::__libcpp_assertion_handler(char const* file, int line, char const* /*expression*/, char const* message) { 239 assert(!GlobalMatcher().empty()); 240 if (GlobalMatcher().Matches(file, line, message)) { 241 std::exit(DeathTest::RK_MatchFound); 242 } 243 std::exit(DeathTest::RK_MatchFailure); 244 } 245 246 template <class Func> 247 inline bool ExpectDeath(const char* stmt, Func&& func, AssertionInfoMatcher Matcher) { 248 DeathTest DT(Matcher); 249 DeathTest::ResultKind RK = DT.Run(func); 250 auto OnFailure = [&](const char* msg) { 251 std::fprintf(stderr, "EXPECT_DEATH( %s ) failed! (%s)\n\n", stmt, msg); 252 if (RK != DeathTest::RK_Unknown) { 253 std::fprintf(stderr, "child exit code: %d\n", DT.getChildExitCode()); 254 } 255 if (!DT.getChildStdErr().empty()) { 256 std::fprintf(stderr, "---------- standard err ----------\n%s\n", DT.getChildStdErr().c_str()); 257 } 258 if (!DT.getChildStdOut().empty()) { 259 std::fprintf(stderr, "---------- standard out ----------\n%s\n", DT.getChildStdOut().c_str()); 260 } 261 return false; 262 }; 263 switch (RK) { 264 case DeathTest::RK_MatchFound: 265 return true; 266 case DeathTest::RK_SetupFailure: 267 return OnFailure("child failed to setup test environment"); 268 case DeathTest::RK_Unknown: 269 return OnFailure("reason unknown"); 270 case DeathTest::RK_DidNotDie: 271 return OnFailure("child did not die"); 272 case DeathTest::RK_MatchFailure: 273 return OnFailure("matcher failed"); 274 } 275 assert(false && "unreachable"); 276 } 277 278 template <class Func> 279 inline bool ExpectDeath(const char* stmt, Func&& func) { 280 return ExpectDeath(stmt, func, AnyMatcher); 281 } 282 283 /// Assert that the specified expression throws a libc++ debug exception. 284 #define EXPECT_DEATH(...) assert((ExpectDeath(#__VA_ARGS__, [&]() { __VA_ARGS__; } ))) 285 286 #define EXPECT_DEATH_MATCHES(Matcher, ...) assert((ExpectDeath(#__VA_ARGS__, [&]() { __VA_ARGS__; }, Matcher))) 287 288 #define TEST_LIBCPP_ASSERT_FAILURE(expr, message) assert((ExpectDeath(#expr, [&]() { (void)(expr); }, AssertionInfoMatcher(message)))) 289 290 #endif // TEST_SUPPORT_CHECK_ASSERTION_H 291