michael@0: // Copyright 2008, Google Inc. michael@0: // All rights reserved. michael@0: // michael@0: // Redistribution and use in source and binary forms, with or without michael@0: // modification, are permitted provided that the following conditions are michael@0: // met: michael@0: // michael@0: // * Redistributions of source code must retain the above copyright michael@0: // notice, this list of conditions and the following disclaimer. michael@0: // * Redistributions in binary form must reproduce the above michael@0: // copyright notice, this list of conditions and the following disclaimer michael@0: // in the documentation and/or other materials provided with the michael@0: // distribution. michael@0: // * Neither the name of Google Inc. nor the names of its michael@0: // contributors may be used to endorse or promote products derived from michael@0: // this software without specific prior written permission. michael@0: // michael@0: // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS michael@0: // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT michael@0: // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR michael@0: // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT michael@0: // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, michael@0: // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT michael@0: // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, michael@0: // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY michael@0: // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT michael@0: // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE michael@0: // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. michael@0: // michael@0: // Author: wan@google.com (Zhanyong Wan) michael@0: michael@0: #include "gtest/internal/gtest-port.h" michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #if GTEST_OS_WINDOWS_MOBILE michael@0: # include // For TerminateProcess() michael@0: #elif GTEST_OS_WINDOWS michael@0: # include michael@0: # include michael@0: #else michael@0: # include michael@0: #endif // GTEST_OS_WINDOWS_MOBILE michael@0: michael@0: #if GTEST_OS_MAC michael@0: # include michael@0: # include michael@0: # include michael@0: #endif // GTEST_OS_MAC michael@0: michael@0: #if GTEST_OS_QNX michael@0: # include michael@0: # include michael@0: #endif // GTEST_OS_QNX michael@0: michael@0: #include "gtest/gtest-spi.h" michael@0: #include "gtest/gtest-message.h" michael@0: #include "gtest/internal/gtest-internal.h" michael@0: #include "gtest/internal/gtest-string.h" michael@0: michael@0: // Indicates that this translation unit is part of Google Test's michael@0: // implementation. It must come before gtest-internal-inl.h is michael@0: // included, or there will be a compiler error. This trick is to michael@0: // prevent a user from accidentally including gtest-internal-inl.h in michael@0: // his code. michael@0: #define GTEST_IMPLEMENTATION_ 1 michael@0: #include "src/gtest-internal-inl.h" michael@0: #undef GTEST_IMPLEMENTATION_ michael@0: michael@0: namespace testing { michael@0: namespace internal { michael@0: michael@0: #if defined(_MSC_VER) || defined(__BORLANDC__) michael@0: // MSVC and C++Builder do not provide a definition of STDERR_FILENO. michael@0: const int kStdOutFileno = 1; michael@0: const int kStdErrFileno = 2; michael@0: #else michael@0: const int kStdOutFileno = STDOUT_FILENO; michael@0: const int kStdErrFileno = STDERR_FILENO; michael@0: #endif // _MSC_VER michael@0: michael@0: #if GTEST_OS_MAC michael@0: michael@0: // Returns the number of threads running in the process, or 0 to indicate that michael@0: // we cannot detect it. michael@0: size_t GetThreadCount() { michael@0: const task_t task = mach_task_self(); michael@0: mach_msg_type_number_t thread_count; michael@0: thread_act_array_t thread_list; michael@0: const kern_return_t status = task_threads(task, &thread_list, &thread_count); michael@0: if (status == KERN_SUCCESS) { michael@0: // task_threads allocates resources in thread_list and we need to free them michael@0: // to avoid leaks. michael@0: vm_deallocate(task, michael@0: reinterpret_cast(thread_list), michael@0: sizeof(thread_t) * thread_count); michael@0: return static_cast(thread_count); michael@0: } else { michael@0: return 0; michael@0: } michael@0: } michael@0: michael@0: #elif GTEST_OS_QNX michael@0: michael@0: // Returns the number of threads running in the process, or 0 to indicate that michael@0: // we cannot detect it. michael@0: size_t GetThreadCount() { michael@0: const int fd = open("/proc/self/as", O_RDONLY); michael@0: if (fd < 0) { michael@0: return 0; michael@0: } michael@0: procfs_info process_info; michael@0: const int status = michael@0: devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL); michael@0: close(fd); michael@0: if (status == EOK) { michael@0: return static_cast(process_info.num_threads); michael@0: } else { michael@0: return 0; michael@0: } michael@0: } michael@0: michael@0: #else michael@0: michael@0: size_t GetThreadCount() { michael@0: // There's no portable way to detect the number of threads, so we just michael@0: // return 0 to indicate that we cannot detect it. michael@0: return 0; michael@0: } michael@0: michael@0: #endif // GTEST_OS_MAC michael@0: michael@0: #if GTEST_USES_POSIX_RE michael@0: michael@0: // Implements RE. Currently only needed for death tests. michael@0: michael@0: RE::~RE() { michael@0: if (is_valid_) { michael@0: // regfree'ing an invalid regex might crash because the content michael@0: // of the regex is undefined. Since the regex's are essentially michael@0: // the same, one cannot be valid (or invalid) without the other michael@0: // being so too. michael@0: regfree(&partial_regex_); michael@0: regfree(&full_regex_); michael@0: } michael@0: free(const_cast(pattern_)); michael@0: } michael@0: michael@0: // Returns true iff regular expression re matches the entire str. michael@0: bool RE::FullMatch(const char* str, const RE& re) { michael@0: if (!re.is_valid_) return false; michael@0: michael@0: regmatch_t match; michael@0: return regexec(&re.full_regex_, str, 1, &match, 0) == 0; michael@0: } michael@0: michael@0: // Returns true iff regular expression re matches a substring of str michael@0: // (including str itself). michael@0: bool RE::PartialMatch(const char* str, const RE& re) { michael@0: if (!re.is_valid_) return false; michael@0: michael@0: regmatch_t match; michael@0: return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; michael@0: } michael@0: michael@0: // Initializes an RE from its string representation. michael@0: void RE::Init(const char* regex) { michael@0: pattern_ = posix::StrDup(regex); michael@0: michael@0: // Reserves enough bytes to hold the regular expression used for a michael@0: // full match. michael@0: const size_t full_regex_len = strlen(regex) + 10; michael@0: char* const full_pattern = new char[full_regex_len]; michael@0: michael@0: snprintf(full_pattern, full_regex_len, "^(%s)$", regex); michael@0: is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; michael@0: // We want to call regcomp(&partial_regex_, ...) even if the michael@0: // previous expression returns false. Otherwise partial_regex_ may michael@0: // not be properly initialized can may cause trouble when it's michael@0: // freed. michael@0: // michael@0: // Some implementation of POSIX regex (e.g. on at least some michael@0: // versions of Cygwin) doesn't accept the empty string as a valid michael@0: // regex. We change it to an equivalent form "()" to be safe. michael@0: if (is_valid_) { michael@0: const char* const partial_regex = (*regex == '\0') ? "()" : regex; michael@0: is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; michael@0: } michael@0: EXPECT_TRUE(is_valid_) michael@0: << "Regular expression \"" << regex michael@0: << "\" is not a valid POSIX Extended regular expression."; michael@0: michael@0: delete[] full_pattern; michael@0: } michael@0: michael@0: #elif GTEST_USES_SIMPLE_RE michael@0: michael@0: // Returns true iff ch appears anywhere in str (excluding the michael@0: // terminating '\0' character). michael@0: bool IsInSet(char ch, const char* str) { michael@0: return ch != '\0' && strchr(str, ch) != NULL; michael@0: } michael@0: michael@0: // Returns true iff ch belongs to the given classification. Unlike michael@0: // similar functions in , these aren't affected by the michael@0: // current locale. michael@0: bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } michael@0: bool IsAsciiPunct(char ch) { michael@0: return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); michael@0: } michael@0: bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } michael@0: bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } michael@0: bool IsAsciiWordChar(char ch) { michael@0: return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || michael@0: ('0' <= ch && ch <= '9') || ch == '_'; michael@0: } michael@0: michael@0: // Returns true iff "\\c" is a supported escape sequence. michael@0: bool IsValidEscape(char c) { michael@0: return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); michael@0: } michael@0: michael@0: // Returns true iff the given atom (specified by escaped and pattern) michael@0: // matches ch. The result is undefined if the atom is invalid. michael@0: bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { michael@0: if (escaped) { // "\\p" where p is pattern_char. michael@0: switch (pattern_char) { michael@0: case 'd': return IsAsciiDigit(ch); michael@0: case 'D': return !IsAsciiDigit(ch); michael@0: case 'f': return ch == '\f'; michael@0: case 'n': return ch == '\n'; michael@0: case 'r': return ch == '\r'; michael@0: case 's': return IsAsciiWhiteSpace(ch); michael@0: case 'S': return !IsAsciiWhiteSpace(ch); michael@0: case 't': return ch == '\t'; michael@0: case 'v': return ch == '\v'; michael@0: case 'w': return IsAsciiWordChar(ch); michael@0: case 'W': return !IsAsciiWordChar(ch); michael@0: } michael@0: return IsAsciiPunct(pattern_char) && pattern_char == ch; michael@0: } michael@0: michael@0: return (pattern_char == '.' && ch != '\n') || pattern_char == ch; michael@0: } michael@0: michael@0: // Helper function used by ValidateRegex() to format error messages. michael@0: String FormatRegexSyntaxError(const char* regex, int index) { michael@0: return (Message() << "Syntax error at index " << index michael@0: << " in simple regular expression \"" << regex << "\": ").GetString(); michael@0: } michael@0: michael@0: // Generates non-fatal failures and returns false if regex is invalid; michael@0: // otherwise returns true. michael@0: bool ValidateRegex(const char* regex) { michael@0: if (regex == NULL) { michael@0: // TODO(wan@google.com): fix the source file location in the michael@0: // assertion failures to match where the regex is used in user michael@0: // code. michael@0: ADD_FAILURE() << "NULL is not a valid simple regular expression."; michael@0: return false; michael@0: } michael@0: michael@0: bool is_valid = true; michael@0: michael@0: // True iff ?, *, or + can follow the previous atom. michael@0: bool prev_repeatable = false; michael@0: for (int i = 0; regex[i]; i++) { michael@0: if (regex[i] == '\\') { // An escape sequence michael@0: i++; michael@0: if (regex[i] == '\0') { michael@0: ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) michael@0: << "'\\' cannot appear at the end."; michael@0: return false; michael@0: } michael@0: michael@0: if (!IsValidEscape(regex[i])) { michael@0: ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) michael@0: << "invalid escape sequence \"\\" << regex[i] << "\"."; michael@0: is_valid = false; michael@0: } michael@0: prev_repeatable = true; michael@0: } else { // Not an escape sequence. michael@0: const char ch = regex[i]; michael@0: michael@0: if (ch == '^' && i > 0) { michael@0: ADD_FAILURE() << FormatRegexSyntaxError(regex, i) michael@0: << "'^' can only appear at the beginning."; michael@0: is_valid = false; michael@0: } else if (ch == '$' && regex[i + 1] != '\0') { michael@0: ADD_FAILURE() << FormatRegexSyntaxError(regex, i) michael@0: << "'$' can only appear at the end."; michael@0: is_valid = false; michael@0: } else if (IsInSet(ch, "()[]{}|")) { michael@0: ADD_FAILURE() << FormatRegexSyntaxError(regex, i) michael@0: << "'" << ch << "' is unsupported."; michael@0: is_valid = false; michael@0: } else if (IsRepeat(ch) && !prev_repeatable) { michael@0: ADD_FAILURE() << FormatRegexSyntaxError(regex, i) michael@0: << "'" << ch << "' can only follow a repeatable token."; michael@0: is_valid = false; michael@0: } michael@0: michael@0: prev_repeatable = !IsInSet(ch, "^$?*+"); michael@0: } michael@0: } michael@0: michael@0: return is_valid; michael@0: } michael@0: michael@0: // Matches a repeated regex atom followed by a valid simple regular michael@0: // expression. The regex atom is defined as c if escaped is false, michael@0: // or \c otherwise. repeat is the repetition meta character (?, *, michael@0: // or +). The behavior is undefined if str contains too many michael@0: // characters to be indexable by size_t, in which case the test will michael@0: // probably time out anyway. We are fine with this limitation as michael@0: // std::string has it too. michael@0: bool MatchRepetitionAndRegexAtHead( michael@0: bool escaped, char c, char repeat, const char* regex, michael@0: const char* str) { michael@0: const size_t min_count = (repeat == '+') ? 1 : 0; michael@0: const size_t max_count = (repeat == '?') ? 1 : michael@0: static_cast(-1) - 1; michael@0: // We cannot call numeric_limits::max() as it conflicts with the michael@0: // max() macro on Windows. michael@0: michael@0: for (size_t i = 0; i <= max_count; ++i) { michael@0: // We know that the atom matches each of the first i characters in str. michael@0: if (i >= min_count && MatchRegexAtHead(regex, str + i)) { michael@0: // We have enough matches at the head, and the tail matches too. michael@0: // Since we only care about *whether* the pattern matches str michael@0: // (as opposed to *how* it matches), there is no need to find a michael@0: // greedy match. michael@0: return true; michael@0: } michael@0: if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) michael@0: return false; michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: // Returns true iff regex matches a prefix of str. regex must be a michael@0: // valid simple regular expression and not start with "^", or the michael@0: // result is undefined. michael@0: bool MatchRegexAtHead(const char* regex, const char* str) { michael@0: if (*regex == '\0') // An empty regex matches a prefix of anything. michael@0: return true; michael@0: michael@0: // "$" only matches the end of a string. Note that regex being michael@0: // valid guarantees that there's nothing after "$" in it. michael@0: if (*regex == '$') michael@0: return *str == '\0'; michael@0: michael@0: // Is the first thing in regex an escape sequence? michael@0: const bool escaped = *regex == '\\'; michael@0: if (escaped) michael@0: ++regex; michael@0: if (IsRepeat(regex[1])) { michael@0: // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so michael@0: // here's an indirect recursion. It terminates as the regex gets michael@0: // shorter in each recursion. michael@0: return MatchRepetitionAndRegexAtHead( michael@0: escaped, regex[0], regex[1], regex + 2, str); michael@0: } else { michael@0: // regex isn't empty, isn't "$", and doesn't start with a michael@0: // repetition. We match the first atom of regex with the first michael@0: // character of str and recurse. michael@0: return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && michael@0: MatchRegexAtHead(regex + 1, str + 1); michael@0: } michael@0: } michael@0: michael@0: // Returns true iff regex matches any substring of str. regex must be michael@0: // a valid simple regular expression, or the result is undefined. michael@0: // michael@0: // The algorithm is recursive, but the recursion depth doesn't exceed michael@0: // the regex length, so we won't need to worry about running out of michael@0: // stack space normally. In rare cases the time complexity can be michael@0: // exponential with respect to the regex length + the string length, michael@0: // but usually it's must faster (often close to linear). michael@0: bool MatchRegexAnywhere(const char* regex, const char* str) { michael@0: if (regex == NULL || str == NULL) michael@0: return false; michael@0: michael@0: if (*regex == '^') michael@0: return MatchRegexAtHead(regex + 1, str); michael@0: michael@0: // A successful match can be anywhere in str. michael@0: do { michael@0: if (MatchRegexAtHead(regex, str)) michael@0: return true; michael@0: } while (*str++ != '\0'); michael@0: return false; michael@0: } michael@0: michael@0: // Implements the RE class. michael@0: michael@0: RE::~RE() { michael@0: free(const_cast(pattern_)); michael@0: free(const_cast(full_pattern_)); michael@0: } michael@0: michael@0: // Returns true iff regular expression re matches the entire str. michael@0: bool RE::FullMatch(const char* str, const RE& re) { michael@0: return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); michael@0: } michael@0: michael@0: // Returns true iff regular expression re matches a substring of str michael@0: // (including str itself). michael@0: bool RE::PartialMatch(const char* str, const RE& re) { michael@0: return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); michael@0: } michael@0: michael@0: // Initializes an RE from its string representation. michael@0: void RE::Init(const char* regex) { michael@0: pattern_ = full_pattern_ = NULL; michael@0: if (regex != NULL) { michael@0: pattern_ = posix::StrDup(regex); michael@0: } michael@0: michael@0: is_valid_ = ValidateRegex(regex); michael@0: if (!is_valid_) { michael@0: // No need to calculate the full pattern when the regex is invalid. michael@0: return; michael@0: } michael@0: michael@0: const size_t len = strlen(regex); michael@0: // Reserves enough bytes to hold the regular expression used for a michael@0: // full match: we need space to prepend a '^', append a '$', and michael@0: // terminate the string with '\0'. michael@0: char* buffer = static_cast(malloc(len + 3)); michael@0: full_pattern_ = buffer; michael@0: michael@0: if (*regex != '^') michael@0: *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. michael@0: michael@0: // We don't use snprintf or strncpy, as they trigger a warning when michael@0: // compiled with VC++ 8.0. michael@0: memcpy(buffer, regex, len); michael@0: buffer += len; michael@0: michael@0: if (len == 0 || regex[len - 1] != '$') michael@0: *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. michael@0: michael@0: *buffer = '\0'; michael@0: } michael@0: michael@0: #endif // GTEST_USES_POSIX_RE michael@0: michael@0: const char kUnknownFile[] = "unknown file"; michael@0: michael@0: // Formats a source file path and a line number as they would appear michael@0: // in an error message from the compiler used to compile this code. michael@0: GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { michael@0: const char* const file_name = file == NULL ? kUnknownFile : file; michael@0: michael@0: if (line < 0) { michael@0: return String::Format("%s:", file_name).c_str(); michael@0: } michael@0: #ifdef _MSC_VER michael@0: return String::Format("%s(%d):", file_name, line).c_str(); michael@0: #else michael@0: return String::Format("%s:%d:", file_name, line).c_str(); michael@0: #endif // _MSC_VER michael@0: } michael@0: michael@0: // Formats a file location for compiler-independent XML output. michael@0: // Although this function is not platform dependent, we put it next to michael@0: // FormatFileLocation in order to contrast the two functions. michael@0: // Note that FormatCompilerIndependentFileLocation() does NOT append colon michael@0: // to the file location it produces, unlike FormatFileLocation(). michael@0: GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( michael@0: const char* file, int line) { michael@0: const char* const file_name = file == NULL ? kUnknownFile : file; michael@0: michael@0: if (line < 0) michael@0: return file_name; michael@0: else michael@0: return String::Format("%s:%d", file_name, line).c_str(); michael@0: } michael@0: michael@0: michael@0: GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) michael@0: : severity_(severity) { michael@0: const char* const marker = michael@0: severity == GTEST_INFO ? "[ INFO ]" : michael@0: severity == GTEST_WARNING ? "[WARNING]" : michael@0: severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; michael@0: GetStream() << ::std::endl << marker << " " michael@0: << FormatFileLocation(file, line).c_str() << ": "; michael@0: } michael@0: michael@0: // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. michael@0: GTestLog::~GTestLog() { michael@0: GetStream() << ::std::endl; michael@0: if (severity_ == GTEST_FATAL) { michael@0: fflush(stderr); michael@0: posix::Abort(); michael@0: } michael@0: } michael@0: // Disable Microsoft deprecation warnings for POSIX functions called from michael@0: // this class (creat, dup, dup2, and close) michael@0: #ifdef _MSC_VER michael@0: # pragma warning(push) michael@0: # pragma warning(disable: 4996) michael@0: #endif // _MSC_VER michael@0: michael@0: #if GTEST_HAS_STREAM_REDIRECTION michael@0: michael@0: // Object that captures an output stream (stdout/stderr). michael@0: class CapturedStream { michael@0: public: michael@0: // The ctor redirects the stream to a temporary file. michael@0: CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { michael@0: # if GTEST_OS_WINDOWS michael@0: char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT michael@0: char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT michael@0: michael@0: ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); michael@0: const UINT success = ::GetTempFileNameA(temp_dir_path, michael@0: "gtest_redir", michael@0: 0, // Generate unique file name. michael@0: temp_file_path); michael@0: GTEST_CHECK_(success != 0) michael@0: << "Unable to create a temporary file in " << temp_dir_path; michael@0: const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); michael@0: GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " michael@0: << temp_file_path; michael@0: filename_ = temp_file_path; michael@0: # else michael@0: // There's no guarantee that a test has write access to the current michael@0: // directory, so we create the temporary file in the /tmp directory instead. michael@0: // We use /tmp on most systems, and /mnt/sdcard on Android. That's because michael@0: // Android doesn't have /tmp. michael@0: # if GTEST_OS_LINUX_ANDROID michael@0: char name_template[] = "/mnt/sdcard/gtest_captured_stream.XXXXXX"; michael@0: # else michael@0: char name_template[] = "/tmp/captured_stream.XXXXXX"; michael@0: # endif // GTEST_OS_LINUX_ANDROID michael@0: const int captured_fd = mkstemp(name_template); michael@0: filename_ = name_template; michael@0: # endif // GTEST_OS_WINDOWS michael@0: fflush(NULL); michael@0: dup2(captured_fd, fd_); michael@0: close(captured_fd); michael@0: } michael@0: michael@0: ~CapturedStream() { michael@0: remove(filename_.c_str()); michael@0: } michael@0: michael@0: String GetCapturedString() { michael@0: if (uncaptured_fd_ != -1) { michael@0: // Restores the original stream. michael@0: fflush(NULL); michael@0: dup2(uncaptured_fd_, fd_); michael@0: close(uncaptured_fd_); michael@0: uncaptured_fd_ = -1; michael@0: } michael@0: michael@0: FILE* const file = posix::FOpen(filename_.c_str(), "r"); michael@0: const String content = ReadEntireFile(file); michael@0: posix::FClose(file); michael@0: return content; michael@0: } michael@0: michael@0: private: michael@0: // Reads the entire content of a file as a String. michael@0: static String ReadEntireFile(FILE* file); michael@0: michael@0: // Returns the size (in bytes) of a file. michael@0: static size_t GetFileSize(FILE* file); michael@0: michael@0: const int fd_; // A stream to capture. michael@0: int uncaptured_fd_; michael@0: // Name of the temporary file holding the stderr output. michael@0: ::std::string filename_; michael@0: michael@0: GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); michael@0: }; michael@0: michael@0: // Returns the size (in bytes) of a file. michael@0: size_t CapturedStream::GetFileSize(FILE* file) { michael@0: fseek(file, 0, SEEK_END); michael@0: return static_cast(ftell(file)); michael@0: } michael@0: michael@0: // Reads the entire content of a file as a string. michael@0: String CapturedStream::ReadEntireFile(FILE* file) { michael@0: const size_t file_size = GetFileSize(file); michael@0: char* const buffer = new char[file_size]; michael@0: michael@0: size_t bytes_last_read = 0; // # of bytes read in the last fread() michael@0: size_t bytes_read = 0; // # of bytes read so far michael@0: michael@0: fseek(file, 0, SEEK_SET); michael@0: michael@0: // Keeps reading the file until we cannot read further or the michael@0: // pre-determined file size is reached. michael@0: do { michael@0: bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); michael@0: bytes_read += bytes_last_read; michael@0: } while (bytes_last_read > 0 && bytes_read < file_size); michael@0: michael@0: const String content(buffer, bytes_read); michael@0: delete[] buffer; michael@0: michael@0: return content; michael@0: } michael@0: michael@0: # ifdef _MSC_VER michael@0: # pragma warning(pop) michael@0: # endif // _MSC_VER michael@0: michael@0: static CapturedStream* g_captured_stderr = NULL; michael@0: static CapturedStream* g_captured_stdout = NULL; michael@0: michael@0: // Starts capturing an output stream (stdout/stderr). michael@0: void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { michael@0: if (*stream != NULL) { michael@0: GTEST_LOG_(FATAL) << "Only one " << stream_name michael@0: << " capturer can exist at a time."; michael@0: } michael@0: *stream = new CapturedStream(fd); michael@0: } michael@0: michael@0: // Stops capturing the output stream and returns the captured string. michael@0: String GetCapturedStream(CapturedStream** captured_stream) { michael@0: const String content = (*captured_stream)->GetCapturedString(); michael@0: michael@0: delete *captured_stream; michael@0: *captured_stream = NULL; michael@0: michael@0: return content; michael@0: } michael@0: michael@0: // Starts capturing stdout. michael@0: void CaptureStdout() { michael@0: CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); michael@0: } michael@0: michael@0: // Starts capturing stderr. michael@0: void CaptureStderr() { michael@0: CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); michael@0: } michael@0: michael@0: // Stops capturing stdout and returns the captured string. michael@0: String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } michael@0: michael@0: // Stops capturing stderr and returns the captured string. michael@0: String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } michael@0: michael@0: #endif // GTEST_HAS_STREAM_REDIRECTION michael@0: michael@0: #if GTEST_HAS_DEATH_TEST michael@0: michael@0: // A copy of all command line arguments. Set by InitGoogleTest(). michael@0: ::std::vector g_argvs; michael@0: michael@0: static const ::std::vector* g_injected_test_argvs = michael@0: NULL; // Owned. michael@0: michael@0: void SetInjectableArgvs(const ::std::vector* argvs) { michael@0: if (g_injected_test_argvs != argvs) michael@0: delete g_injected_test_argvs; michael@0: g_injected_test_argvs = argvs; michael@0: } michael@0: michael@0: const ::std::vector& GetInjectableArgvs() { michael@0: if (g_injected_test_argvs != NULL) { michael@0: return *g_injected_test_argvs; michael@0: } michael@0: return g_argvs; michael@0: } michael@0: #endif // GTEST_HAS_DEATH_TEST michael@0: michael@0: #if GTEST_OS_WINDOWS_MOBILE michael@0: namespace posix { michael@0: void Abort() { michael@0: DebugBreak(); michael@0: TerminateProcess(GetCurrentProcess(), 1); michael@0: } michael@0: } // namespace posix michael@0: #endif // GTEST_OS_WINDOWS_MOBILE michael@0: michael@0: // Returns the name of the environment variable corresponding to the michael@0: // given flag. For example, FlagToEnvVar("foo") will return michael@0: // "GTEST_FOO" in the open-source version. michael@0: static String FlagToEnvVar(const char* flag) { michael@0: const String full_flag = michael@0: (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); michael@0: michael@0: Message env_var; michael@0: for (size_t i = 0; i != full_flag.length(); i++) { michael@0: env_var << ToUpper(full_flag.c_str()[i]); michael@0: } michael@0: michael@0: return env_var.GetString(); michael@0: } michael@0: michael@0: // Parses 'str' for a 32-bit signed integer. If successful, writes michael@0: // the result to *value and returns true; otherwise leaves *value michael@0: // unchanged and returns false. michael@0: bool ParseInt32(const Message& src_text, const char* str, Int32* value) { michael@0: // Parses the environment variable as a decimal integer. michael@0: char* end = NULL; michael@0: const long long_value = strtol(str, &end, 10); // NOLINT michael@0: michael@0: // Has strtol() consumed all characters in the string? michael@0: if (*end != '\0') { michael@0: // No - an invalid character was encountered. michael@0: Message msg; michael@0: msg << "WARNING: " << src_text michael@0: << " is expected to be a 32-bit integer, but actually" michael@0: << " has value \"" << str << "\".\n"; michael@0: printf("%s", msg.GetString().c_str()); michael@0: fflush(stdout); michael@0: return false; michael@0: } michael@0: michael@0: // Is the parsed value in the range of an Int32? michael@0: const Int32 result = static_cast(long_value); michael@0: if (long_value == LONG_MAX || long_value == LONG_MIN || michael@0: // The parsed value overflows as a long. (strtol() returns michael@0: // LONG_MAX or LONG_MIN when the input overflows.) michael@0: result != long_value michael@0: // The parsed value overflows as an Int32. michael@0: ) { michael@0: Message msg; michael@0: msg << "WARNING: " << src_text michael@0: << " is expected to be a 32-bit integer, but actually" michael@0: << " has value " << str << ", which overflows.\n"; michael@0: printf("%s", msg.GetString().c_str()); michael@0: fflush(stdout); michael@0: return false; michael@0: } michael@0: michael@0: *value = result; michael@0: return true; michael@0: } michael@0: michael@0: // Reads and returns the Boolean environment variable corresponding to michael@0: // the given flag; if it's not set, returns default_value. michael@0: // michael@0: // The value is considered true iff it's not "0". michael@0: bool BoolFromGTestEnv(const char* flag, bool default_value) { michael@0: const String env_var = FlagToEnvVar(flag); michael@0: const char* const string_value = posix::GetEnv(env_var.c_str()); michael@0: return string_value == NULL ? michael@0: default_value : strcmp(string_value, "0") != 0; michael@0: } michael@0: michael@0: // Reads and returns a 32-bit integer stored in the environment michael@0: // variable corresponding to the given flag; if it isn't set or michael@0: // doesn't represent a valid 32-bit integer, returns default_value. michael@0: Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { michael@0: const String env_var = FlagToEnvVar(flag); michael@0: const char* const string_value = posix::GetEnv(env_var.c_str()); michael@0: if (string_value == NULL) { michael@0: // The environment variable is not set. michael@0: return default_value; michael@0: } michael@0: michael@0: Int32 result = default_value; michael@0: if (!ParseInt32(Message() << "Environment variable " << env_var, michael@0: string_value, &result)) { michael@0: printf("The default value %s is used.\n", michael@0: (Message() << default_value).GetString().c_str()); michael@0: fflush(stdout); michael@0: return default_value; michael@0: } michael@0: michael@0: return result; michael@0: } michael@0: michael@0: // Reads and returns the string environment variable corresponding to michael@0: // the given flag; if it's not set, returns default_value. michael@0: const char* StringFromGTestEnv(const char* flag, const char* default_value) { michael@0: const String env_var = FlagToEnvVar(flag); michael@0: const char* const value = posix::GetEnv(env_var.c_str()); michael@0: return value == NULL ? default_value : value; michael@0: } michael@0: michael@0: } // namespace internal michael@0: } // namespace testing