1 // Copyright 2008, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Author: wan@google.com (Zhanyong Wan)
32 #include <gtest/internal/gtest-port.h>
43 #endif // GTEST_OS_WINDOWS
45 #if GTEST_USES_SIMPLE_RE
50 #include <windows.h> // For TerminateProcess()
53 #include <gtest/gtest-spi.h>
54 #include <gtest/gtest-message.h>
55 #include <gtest/internal/gtest-string.h>
57 // Indicates that this translation unit is part of Google Test's
58 // implementation. It must come before gtest-internal-inl.h is
59 // included, or there will be a compiler error. This trick is to
60 // prevent a user from accidentally including gtest-internal-inl.h in
62 #define GTEST_IMPLEMENTATION_ 1
63 #include "gtest/internal/gtest-internal-inl.h"
64 #undef GTEST_IMPLEMENTATION_
70 // Microsoft does not provide a definition of STDERR_FILENO.
71 const int kStdErrFileno = 2;
73 const int kStdErrFileno = STDERR_FILENO;
74 #endif // GTEST_OS_WINDOWS
76 #if GTEST_USES_POSIX_RE
78 // Implements RE. Currently only needed for death tests.
81 regfree(&partial_regex_);
82 regfree(&full_regex_);
83 free(const_cast<char*>(pattern_));
86 // Returns true iff regular expression re matches the entire str.
87 bool RE::FullMatch(const char* str, const RE& re) {
88 if (!re.is_valid_) return false;
91 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
94 // Returns true iff regular expression re matches a substring of str
95 // (including str itself).
96 bool RE::PartialMatch(const char* str, const RE& re) {
97 if (!re.is_valid_) return false;
100 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
103 // Initializes an RE from its string representation.
104 void RE::Init(const char* regex) {
105 pattern_ = strdup(regex);
107 // Reserves enough bytes to hold the regular expression used for a
109 const size_t full_regex_len = strlen(regex) + 10;
110 char* const full_pattern = new char[full_regex_len];
112 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
113 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
114 // We want to call regcomp(&partial_regex_, ...) even if the
115 // previous expression returns false. Otherwise partial_regex_ may
116 // not be properly initialized can may cause trouble when it's
119 // Some implementation of POSIX regex (e.g. on at least some
120 // versions of Cygwin) doesn't accept the empty string as a valid
121 // regex. We change it to an equivalent form "()" to be safe.
122 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
123 is_valid_ = (regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0)
125 EXPECT_TRUE(is_valid_)
126 << "Regular expression \"" << regex
127 << "\" is not a valid POSIX Extended regular expression.";
129 delete[] full_pattern;
132 #elif GTEST_USES_SIMPLE_RE
134 // Returns true iff ch appears anywhere in str (excluding the
135 // terminating '\0' character).
136 bool IsInSet(char ch, const char* str) {
137 return ch != '\0' && strchr(str, ch) != NULL;
140 // Returns true iff ch belongs to the given classification. Unlike
141 // similar functions in <ctype.h>, these aren't affected by the
143 bool IsDigit(char ch) { return '0' <= ch && ch <= '9'; }
144 bool IsPunct(char ch) {
145 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
147 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
148 bool IsWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
149 bool IsWordChar(char ch) {
150 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
151 ('0' <= ch && ch <= '9') || ch == '_';
154 // Returns true iff "\\c" is a supported escape sequence.
155 bool IsValidEscape(char c) {
156 return (IsPunct(c) || IsInSet(c, "dDfnrsStvwW"));
159 // Returns true iff the given atom (specified by escaped and pattern)
160 // matches ch. The result is undefined if the atom is invalid.
161 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
162 if (escaped) { // "\\p" where p is pattern_char.
163 switch (pattern_char) {
164 case 'd': return IsDigit(ch);
165 case 'D': return !IsDigit(ch);
166 case 'f': return ch == '\f';
167 case 'n': return ch == '\n';
168 case 'r': return ch == '\r';
169 case 's': return IsWhiteSpace(ch);
170 case 'S': return !IsWhiteSpace(ch);
171 case 't': return ch == '\t';
172 case 'v': return ch == '\v';
173 case 'w': return IsWordChar(ch);
174 case 'W': return !IsWordChar(ch);
176 return IsPunct(pattern_char) && pattern_char == ch;
179 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
182 // Helper function used by ValidateRegex() to format error messages.
183 String FormatRegexSyntaxError(const char* regex, int index) {
184 return (Message() << "Syntax error at index " << index
185 << " in simple regular expression \"" << regex << "\": ").GetString();
188 // Generates non-fatal failures and returns false if regex is invalid;
189 // otherwise returns true.
190 bool ValidateRegex(const char* regex) {
192 // TODO(wan@google.com): fix the source file location in the
193 // assertion failures to match where the regex is used in user
195 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
199 bool is_valid = true;
201 // True iff ?, *, or + can follow the previous atom.
202 bool prev_repeatable = false;
203 for (int i = 0; regex[i]; i++) {
204 if (regex[i] == '\\') { // An escape sequence
206 if (regex[i] == '\0') {
207 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
208 << "'\\' cannot appear at the end.";
212 if (!IsValidEscape(regex[i])) {
213 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
214 << "invalid escape sequence \"\\" << regex[i] << "\".";
217 prev_repeatable = true;
218 } else { // Not an escape sequence.
219 const char ch = regex[i];
221 if (ch == '^' && i > 0) {
222 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
223 << "'^' can only appear at the beginning.";
225 } else if (ch == '$' && regex[i + 1] != '\0') {
226 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
227 << "'$' can only appear at the end.";
229 } else if (IsInSet(ch, "()[]{}|")) {
230 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
231 << "'" << ch << "' is unsupported.";
233 } else if (IsRepeat(ch) && !prev_repeatable) {
234 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
235 << "'" << ch << "' can only follow a repeatable token.";
239 prev_repeatable = !IsInSet(ch, "^$?*+");
246 // Matches a repeated regex atom followed by a valid simple regular
247 // expression. The regex atom is defined as c if escaped is false,
248 // or \c otherwise. repeat is the repetition meta character (?, *,
249 // or +). The behavior is undefined if str contains too many
250 // characters to be indexable by size_t, in which case the test will
251 // probably time out anyway. We are fine with this limitation as
252 // std::string has it too.
253 bool MatchRepetitionAndRegexAtHead(
254 bool escaped, char c, char repeat, const char* regex,
256 const size_t min_count = (repeat == '+') ? 1 : 0;
257 const size_t max_count = (repeat == '?') ? 1 :
258 static_cast<size_t>(-1) - 1;
259 // We cannot call numeric_limits::max() as it conflicts with the
260 // max() macro on Windows.
262 for (size_t i = 0; i <= max_count; ++i) {
263 // We know that the atom matches each of the first i characters in str.
264 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
265 // We have enough matches at the head, and the tail matches too.
266 // Since we only care about *whether* the pattern matches str
267 // (as opposed to *how* it matches), there is no need to find a
271 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
277 // Returns true iff regex matches a prefix of str. regex must be a
278 // valid simple regular expression and not start with "^", or the
279 // result is undefined.
280 bool MatchRegexAtHead(const char* regex, const char* str) {
281 if (*regex == '\0') // An empty regex matches a prefix of anything.
284 // "$" only matches the end of a string. Note that regex being
285 // valid guarantees that there's nothing after "$" in it.
289 // Is the first thing in regex an escape sequence?
290 const bool escaped = *regex == '\\';
293 if (IsRepeat(regex[1])) {
294 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
295 // here's an indirect recursion. It terminates as the regex gets
296 // shorter in each recursion.
297 return MatchRepetitionAndRegexAtHead(
298 escaped, regex[0], regex[1], regex + 2, str);
300 // regex isn't empty, isn't "$", and doesn't start with a
301 // repetition. We match the first atom of regex with the first
302 // character of str and recurse.
303 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
304 MatchRegexAtHead(regex + 1, str + 1);
308 // Returns true iff regex matches any substring of str. regex must be
309 // a valid simple regular expression, or the result is undefined.
311 // The algorithm is recursive, but the recursion depth doesn't exceed
312 // the regex length, so we won't need to worry about running out of
313 // stack space normally. In rare cases the time complexity can be
314 // exponential with respect to the regex length + the string length,
315 // but usually it's must faster (often close to linear).
316 bool MatchRegexAnywhere(const char* regex, const char* str) {
317 if (regex == NULL || str == NULL)
321 return MatchRegexAtHead(regex + 1, str);
323 // A successful match can be anywhere in str.
325 if (MatchRegexAtHead(regex, str))
327 } while (*str++ != '\0');
331 // Implements the RE class.
334 free(const_cast<char*>(pattern_));
335 free(const_cast<char*>(full_pattern_));
338 // Returns true iff regular expression re matches the entire str.
339 bool RE::FullMatch(const char* str, const RE& re) {
340 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
343 // Returns true iff regular expression re matches a substring of str
344 // (including str itself).
345 bool RE::PartialMatch(const char* str, const RE& re) {
346 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
349 // Initializes an RE from its string representation.
350 void RE::Init(const char* regex) {
351 pattern_ = full_pattern_ = NULL;
354 pattern_ = _strdup(regex);
356 pattern_ = strdup(regex);
360 is_valid_ = ValidateRegex(regex);
362 // No need to calculate the full pattern when the regex is invalid.
366 const size_t len = strlen(regex);
367 // Reserves enough bytes to hold the regular expression used for a
368 // full match: we need space to prepend a '^', append a '$', and
369 // terminate the string with '\0'.
370 char* buffer = static_cast<char*>(malloc(len + 3));
371 full_pattern_ = buffer;
374 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
376 // We don't use snprintf or strncpy, as they trigger a warning when
377 // compiled with VC++ 8.0.
378 memcpy(buffer, regex, len);
381 if (len == 0 || regex[len - 1] != '$')
382 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
387 #endif // GTEST_USES_POSIX_RE
389 // Logs a message at the given severity level.
390 void GTestLog(GTestLogSeverity severity, const char* file,
391 int line, const char* msg) {
392 const char* const marker =
393 severity == GTEST_INFO ? "[ INFO ]" :
394 severity == GTEST_WARNING ? "[WARNING]" :
395 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
396 fprintf(stderr, "\n%s %s:%d: %s\n", marker, file, line, msg);
397 if (severity == GTEST_FATAL) {
398 fflush(NULL); // abort() is not guaranteed to flush open file streams.
403 #if GTEST_HAS_STD_STRING
405 // Disable Microsoft deprecation warnings for POSIX functions called from
406 // this class (creat, dup, dup2, and close)
408 #pragma warning(push)
409 #pragma warning(disable: 4996)
412 // Defines the stderr capturer.
414 class CapturedStderr {
416 // The ctor redirects stderr to a temporary file.
418 uncaptured_fd_ = dup(kStdErrFileno);
421 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
422 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
424 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
425 ::GetTempFileNameA(temp_dir_path, "gtest_redir", 0, temp_file_path);
426 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
427 filename_ = temp_file_path;
429 // There's no guarantee that a test has write access to the
430 // current directory, so we create the temporary file in the /tmp
431 // directory instead.
432 char name_template[] = "/tmp/captured_stderr.XXXXXX";
433 const int captured_fd = mkstemp(name_template);
434 filename_ = name_template;
435 #endif // GTEST_OS_WINDOWS
437 dup2(captured_fd, kStdErrFileno);
442 remove(filename_.c_str());
445 // Stops redirecting stderr.
447 // Restores the original stream.
449 dup2(uncaptured_fd_, kStdErrFileno);
450 close(uncaptured_fd_);
454 // Returns the name of the temporary file holding the stderr output.
455 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
457 ::std::string filename() const { return filename_; }
461 ::std::string filename_;
468 static CapturedStderr* g_captured_stderr = NULL;
470 // Returns the size (in bytes) of a file.
471 static size_t GetFileSize(FILE * file) {
472 fseek(file, 0, SEEK_END);
473 return static_cast<size_t>(ftell(file));
476 // Reads the entire content of a file as a string.
477 static ::std::string ReadEntireFile(FILE * file) {
478 const size_t file_size = GetFileSize(file);
479 char* const buffer = new char[file_size];
481 size_t bytes_last_read = 0; // # of bytes read in the last fread()
482 size_t bytes_read = 0; // # of bytes read so far
484 fseek(file, 0, SEEK_SET);
486 // Keeps reading the file until we cannot read further or the
487 // pre-determined file size is reached.
489 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
490 bytes_read += bytes_last_read;
491 } while (bytes_last_read > 0 && bytes_read < file_size);
493 const ::std::string content(buffer, buffer+bytes_read);
499 // Starts capturing stderr.
500 void CaptureStderr() {
501 if (g_captured_stderr != NULL) {
502 GTEST_LOG_(FATAL, "Only one stderr capturer can exist at one time.");
504 g_captured_stderr = new CapturedStderr;
507 // Stops capturing stderr and returns the captured string.
508 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can
510 ::std::string GetCapturedStderr() {
511 g_captured_stderr->StopCapture();
513 // Disables Microsoft deprecation warning for fopen and fclose.
515 #pragma warning(push)
516 #pragma warning(disable: 4996)
518 FILE* const file = fopen(g_captured_stderr->filename().c_str(), "r");
519 const ::std::string content = ReadEntireFile(file);
525 delete g_captured_stderr;
526 g_captured_stderr = NULL;
531 #endif // GTEST_HAS_STD_STRING
533 #if GTEST_HAS_DEATH_TEST
535 // A copy of all command line arguments. Set by InitGoogleTest().
536 ::std::vector<String> g_argvs;
538 // Returns the command line as a vector of strings.
539 const ::std::vector<String>& GetArgvs() { return g_argvs; }
541 #endif // GTEST_HAS_DEATH_TEST
546 TerminateProcess(GetCurrentProcess(), 1);
550 // Returns the name of the environment variable corresponding to the
551 // given flag. For example, FlagToEnvVar("foo") will return
552 // "GTEST_FOO" in the open-source version.
553 static String FlagToEnvVar(const char* flag) {
554 const String full_flag =
555 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
558 for (int i = 0; i != full_flag.GetLength(); i++) {
559 env_var << static_cast<char>(toupper(full_flag.c_str()[i]));
562 return env_var.GetString();
565 // Parses 'str' for a 32-bit signed integer. If successful, writes
566 // the result to *value and returns true; otherwise leaves *value
567 // unchanged and returns false.
568 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
569 // Parses the environment variable as a decimal integer.
571 const long long_value = strtol(str, &end, 10); // NOLINT
573 // Has strtol() consumed all characters in the string?
575 // No - an invalid character was encountered.
577 msg << "WARNING: " << src_text
578 << " is expected to be a 32-bit integer, but actually"
579 << " has value \"" << str << "\".\n";
580 printf("%s", msg.GetString().c_str());
585 // Is the parsed value in the range of an Int32?
586 const Int32 result = static_cast<Int32>(long_value);
587 if (long_value == LONG_MAX || long_value == LONG_MIN ||
588 // The parsed value overflows as a long. (strtol() returns
589 // LONG_MAX or LONG_MIN when the input overflows.)
591 // The parsed value overflows as an Int32.
594 msg << "WARNING: " << src_text
595 << " is expected to be a 32-bit integer, but actually"
596 << " has value " << str << ", which overflows.\n";
597 printf("%s", msg.GetString().c_str());
606 // Reads and returns the Boolean environment variable corresponding to
607 // the given flag; if it's not set, returns default_value.
609 // The value is considered true iff it's not "0".
610 bool BoolFromGTestEnv(const char* flag, bool default_value) {
611 const String env_var = FlagToEnvVar(flag);
612 const char* const string_value = GetEnv(env_var.c_str());
613 return string_value == NULL ?
614 default_value : strcmp(string_value, "0") != 0;
617 // Reads and returns a 32-bit integer stored in the environment
618 // variable corresponding to the given flag; if it isn't set or
619 // doesn't represent a valid 32-bit integer, returns default_value.
620 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
621 const String env_var = FlagToEnvVar(flag);
622 const char* const string_value = GetEnv(env_var.c_str());
623 if (string_value == NULL) {
624 // The environment variable is not set.
625 return default_value;
628 Int32 result = default_value;
629 if (!ParseInt32(Message() << "Environment variable " << env_var,
630 string_value, &result)) {
631 printf("The default value %s is used.\n",
632 (Message() << default_value).GetString().c_str());
634 return default_value;
640 // Reads and returns the string environment variable corresponding to
641 // the given flag; if it's not set, returns default_value.
642 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
643 const String env_var = FlagToEnvVar(flag);
644 const char* const value = GetEnv(env_var.c_str());
645 return value == NULL ? default_value : value;
648 } // namespace internal
649 } // namespace testing