1 //===----------------------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef TEST_SUPPORT_CHECK_ASSERTION_H
10 #define TEST_SUPPORT_CHECK_ASSERTION_H
18 #include <string_view>
24 #include "test_macros.h"
25 #include "test_allocator.h"
27 #ifndef _LIBCPP_VERSION
28 # error "This header may only be used for libc++ tests"
32 # error "C++11 or greater is required to use this header"
35 struct AssertionInfoMatcher
{
36 static const int any_line
= -1;
37 static constexpr const char* any_file
= "*";
38 static constexpr const char* any_msg
= "*";
40 constexpr AssertionInfoMatcher() : is_empty_(true), msg_(any_msg
, __builtin_strlen(any_msg
)), file_(any_file
, __builtin_strlen(any_file
)), line_(any_line
) { }
41 constexpr AssertionInfoMatcher(const char* msg
, const char* file
= any_file
, int line
= any_line
)
42 : is_empty_(false), msg_(msg
, __builtin_strlen(msg
)), file_(file
, __builtin_strlen(file
)), line_(line
) {}
44 bool Matches(char const* file
, int line
, char const* message
) const {
45 assert(!empty() && "empty matcher");
47 if (CheckLineMatches(line
) && CheckFileMatches(file
) && CheckMessageMatches(message
))
49 // Write to stdout because that's the file descriptor captured by the parent
51 std::printf("Failed to match assertion info!\n%s\nVS\n%s:%d (%s)\n", ToString().data(), file
, line
, message
);
55 std::string
ToString() const {
56 std::string result
= "msg = \""; result
+= msg_
; result
+= "\"\n";
57 result
+= "line = " + (line_
== any_line
? "'*'" : std::to_string(line_
)) + "\n";
58 result
+= "file = " + (file_
== any_file
? "'*'" : std::string(file_
));
62 bool empty() const { return is_empty_
; }
64 bool CheckLineMatches(int got_line
) const {
65 if (line_
== any_line
)
67 return got_line
== line_
;
70 bool CheckFileMatches(std::string_view got_file
) const {
71 assert(!empty() && "empty matcher");
72 if (file_
== any_file
)
74 std::size_t found_at
= got_file
.find(file_
);
75 if (found_at
== std::string_view::npos
)
77 // require the match start at the beginning of the file or immediately after
78 // a directory separator.
80 char last_char
= got_file
[found_at
- 1];
81 if (last_char
!= '/' && last_char
!= '\\')
84 // require the match goes until the end of the string.
85 return got_file
.substr(found_at
) == file_
;
88 bool CheckMessageMatches(std::string_view got_msg
) const {
89 assert(!empty() && "empty matcher");
92 std::size_t found_at
= got_msg
.find(msg_
);
93 if (found_at
== std::string_view::npos
)
100 std::string_view msg_
;
101 std::string_view file_
;
105 static constexpr AssertionInfoMatcher
AnyMatcher(AssertionInfoMatcher::any_msg
);
107 inline AssertionInfoMatcher
& GlobalMatcher() {
108 static AssertionInfoMatcher GMatch
;
114 RK_DidNotDie
, RK_MatchFound
, RK_MatchFailure
, RK_SetupFailure
, RK_Unknown
117 static const char* ResultKindToString(ResultKind RK
) {
118 #define CASE(K) case K: return #K
120 CASE(RK_MatchFailure
);
122 CASE(RK_SetupFailure
);
126 return "not a result kind";
129 static bool IsValidResultKind(int val
) {
130 return val
>= RK_DidNotDie
&& val
<= RK_Unknown
;
133 DeathTest(AssertionInfoMatcher
const& Matcher
) : matcher_(Matcher
) {}
135 template <class Func
>
136 ResultKind
Run(Func
&& f
) {
137 int pipe_res
= pipe(stdout_pipe_fd_
);
138 assert(pipe_res
!= -1 && "failed to create pipe");
139 pipe_res
= pipe(stderr_pipe_fd_
);
140 assert(pipe_res
!= -1 && "failed to create pipe");
141 pid_t child_pid
= fork();
142 assert(child_pid
!= -1 &&
143 "failed to fork a process to perform a death test");
144 child_pid_
= child_pid
;
145 if (child_pid_
== 0) {
146 RunForChild(std::forward
<Func
>(f
));
147 assert(false && "unreachable");
149 return RunForParent();
152 int getChildExitCode() const { return exit_code_
; }
153 std::string
const& getChildStdOut() const { return stdout_from_child_
; }
154 std::string
const& getChildStdErr() const { return stderr_from_child_
; }
156 template <class Func
>
157 TEST_NORETURN
void RunForChild(Func
&& f
) {
158 close(GetStdOutReadFD()); // don't need to read from the pipe in the child.
159 close(GetStdErrReadFD());
160 auto DupFD
= [](int DestFD
, int TargetFD
) {
161 int dup_result
= dup2(DestFD
, TargetFD
);
162 if (dup_result
== -1)
163 std::exit(RK_SetupFailure
);
165 DupFD(GetStdOutWriteFD(), STDOUT_FILENO
);
166 DupFD(GetStdErrWriteFD(), STDERR_FILENO
);
168 GlobalMatcher() = matcher_
;
170 std::exit(RK_DidNotDie
);
173 static std::string
ReadChildIOUntilEnd(int FD
) {
174 std::string error_msg
;
178 while ((num_read
= read(FD
, buffer
, 255)) > 0) {
179 buffer
[num_read
] = '\0';
182 } while (num_read
== -1 && errno
== EINTR
);
186 void CaptureIOFromChild() {
187 close(GetStdOutWriteFD()); // no need to write from the parent process
188 close(GetStdErrWriteFD());
189 stdout_from_child_
= ReadChildIOUntilEnd(GetStdOutReadFD());
190 stderr_from_child_
= ReadChildIOUntilEnd(GetStdErrReadFD());
191 close(GetStdOutReadFD());
192 close(GetStdErrReadFD());
195 ResultKind
RunForParent() {
196 CaptureIOFromChild();
199 pid_t result
= waitpid(child_pid_
, &status_value
, 0);
200 assert(result
!= -1 && "there is no child process to wait for");
202 if (WIFEXITED(status_value
)) {
203 exit_code_
= WEXITSTATUS(status_value
);
204 if (!IsValidResultKind(exit_code_
))
206 return static_cast<ResultKind
>(exit_code_
);
211 DeathTest(DeathTest
const&) = delete;
212 DeathTest
& operator=(DeathTest
const&) = delete;
214 int GetStdOutReadFD() const {
215 return stdout_pipe_fd_
[0];
218 int GetStdOutWriteFD() const {
219 return stdout_pipe_fd_
[1];
222 int GetStdErrReadFD() const {
223 return stderr_pipe_fd_
[0];
226 int GetStdErrWriteFD() const {
227 return stderr_pipe_fd_
[1];
230 AssertionInfoMatcher matcher_
;
231 pid_t child_pid_
= -1;
233 int stdout_pipe_fd_
[2];
234 int stderr_pipe_fd_
[2];
235 std::string stdout_from_child_
;
236 std::string stderr_from_child_
;
239 void std::__libcpp_verbose_abort(char const* format
, ...) {
240 // Extract information from the error message. This has to stay synchronized with
241 // how we format assertions in the library.
243 va_start(list
, format
);
244 char const* file
= va_arg(list
, char const*);
245 int line
= va_arg(list
, int);
246 char const* expression
= va_arg(list
, char const*); (void)expression
;
247 char const* message
= va_arg(list
, char const*);
250 if (GlobalMatcher().Matches(file
, line
, message
)) {
251 std::exit(DeathTest::RK_MatchFound
);
253 std::exit(DeathTest::RK_MatchFailure
);
256 template <class Func
>
257 inline bool ExpectDeath(const char* stmt
, Func
&& func
, AssertionInfoMatcher Matcher
) {
258 DeathTest
DT(Matcher
);
259 DeathTest::ResultKind RK
= DT
.Run(func
);
260 auto OnFailure
= [&](const char* msg
) {
261 std::fprintf(stderr
, "EXPECT_DEATH( %s ) failed! (%s)\n\n", stmt
, msg
);
262 if (RK
!= DeathTest::RK_Unknown
) {
263 std::fprintf(stderr
, "child exit code: %d\n", DT
.getChildExitCode());
265 if (!DT
.getChildStdErr().empty()) {
266 std::fprintf(stderr
, "---------- standard err ----------\n%s\n", DT
.getChildStdErr().c_str());
268 if (!DT
.getChildStdOut().empty()) {
269 std::fprintf(stderr
, "---------- standard out ----------\n%s\n", DT
.getChildStdOut().c_str());
274 case DeathTest::RK_MatchFound
:
276 case DeathTest::RK_SetupFailure
:
277 return OnFailure("child failed to setup test environment");
278 case DeathTest::RK_Unknown
:
279 return OnFailure("reason unknown");
280 case DeathTest::RK_DidNotDie
:
281 return OnFailure("child did not die");
282 case DeathTest::RK_MatchFailure
:
283 return OnFailure("matcher failed");
285 assert(false && "unreachable");
288 template <class Func
>
289 inline bool ExpectDeath(const char* stmt
, Func
&& func
) {
290 return ExpectDeath(stmt
, func
, AnyMatcher
);
293 /// Assert that the specified expression throws a libc++ debug exception.
294 #define EXPECT_DEATH(...) assert((ExpectDeath(#__VA_ARGS__, [&]() { __VA_ARGS__; } )))
296 #define EXPECT_DEATH_MATCHES(Matcher, ...) assert((ExpectDeath(#__VA_ARGS__, [&]() { __VA_ARGS__; }, Matcher)))
298 #define TEST_LIBCPP_ASSERT_FAILURE(expr, message) assert((ExpectDeath(#expr, [&]() { (void)(expr); }, AssertionInfoMatcher(message))))
300 #endif // TEST_SUPPORT_CHECK_ASSERTION_H