Home | History | Annotate | Download | only in src
      1 // Copyright 2008, Google Inc.
      2 // All rights reserved.
      3 //
      4 // Redistribution and use in source and binary forms, with or without
      5 // modification, are permitted provided that the following conditions are
      6 // met:
      7 //
      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
     13 // distribution.
     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.
     17 //
     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.
     29 //
     30 // Author: wan (at) google.com (Zhanyong Wan)
     31 
     32 #include <gtest/internal/gtest-port.h>
     33 
     34 #include <limits.h>
     35 #include <stdlib.h>
     36 #include <stdio.h>
     37 
     38 #if GTEST_OS_WINDOWS_MOBILE
     39 #include <windows.h>  // For TerminateProcess()
     40 #elif GTEST_OS_WINDOWS
     41 #include <io.h>
     42 #include <sys/stat.h>
     43 #else
     44 #include <unistd.h>
     45 #endif  // GTEST_OS_WINDOWS_MOBILE
     46 
     47 #if GTEST_OS_MAC
     48 #include <mach/mach_init.h>
     49 #include <mach/task.h>
     50 #include <mach/vm_map.h>
     51 #endif  // GTEST_OS_MAC
     52 
     53 #include <gtest/gtest-spi.h>
     54 #include <gtest/gtest-message.h>
     55 #include <gtest/internal/gtest-string.h>
     56 
     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
     61 // his code.
     62 #define GTEST_IMPLEMENTATION_ 1
     63 #include "src/gtest-internal-inl.h"
     64 #undef GTEST_IMPLEMENTATION_
     65 
     66 namespace testing {
     67 namespace internal {
     68 
     69 #if defined(_MSC_VER) || defined(__BORLANDC__)
     70 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
     71 const int kStdOutFileno = 1;
     72 const int kStdErrFileno = 2;
     73 #else
     74 const int kStdOutFileno = STDOUT_FILENO;
     75 const int kStdErrFileno = STDERR_FILENO;
     76 #endif  // _MSC_VER
     77 
     78 #if GTEST_OS_MAC
     79 
     80 // Returns the number of threads running in the process, or 0 to indicate that
     81 // we cannot detect it.
     82 size_t GetThreadCount() {
     83   const task_t task = mach_task_self();
     84   mach_msg_type_number_t thread_count;
     85   thread_act_array_t thread_list;
     86   const kern_return_t status = task_threads(task, &thread_list, &thread_count);
     87   if (status == KERN_SUCCESS) {
     88     // task_threads allocates resources in thread_list and we need to free them
     89     // to avoid leaks.
     90     vm_deallocate(task,
     91                   reinterpret_cast<vm_address_t>(thread_list),
     92                   sizeof(thread_t) * thread_count);
     93     return static_cast<size_t>(thread_count);
     94   } else {
     95     return 0;
     96   }
     97 }
     98 
     99 #else
    100 
    101 size_t GetThreadCount() {
    102   // There's no portable way to detect the number of threads, so we just
    103   // return 0 to indicate that we cannot detect it.
    104   return 0;
    105 }
    106 
    107 #endif  // GTEST_OS_MAC
    108 
    109 #if GTEST_USES_POSIX_RE
    110 
    111 // Implements RE.  Currently only needed for death tests.
    112 
    113 RE::~RE() {
    114   if (is_valid_) {
    115     // regfree'ing an invalid regex might crash because the content
    116     // of the regex is undefined. Since the regex's are essentially
    117     // the same, one cannot be valid (or invalid) without the other
    118     // being so too.
    119     regfree(&partial_regex_);
    120     regfree(&full_regex_);
    121   }
    122   free(const_cast<char*>(pattern_));
    123 }
    124 
    125 // Returns true iff regular expression re matches the entire str.
    126 bool RE::FullMatch(const char* str, const RE& re) {
    127   if (!re.is_valid_) return false;
    128 
    129   regmatch_t match;
    130   return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
    131 }
    132 
    133 // Returns true iff regular expression re matches a substring of str
    134 // (including str itself).
    135 bool RE::PartialMatch(const char* str, const RE& re) {
    136   if (!re.is_valid_) return false;
    137 
    138   regmatch_t match;
    139   return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
    140 }
    141 
    142 // Initializes an RE from its string representation.
    143 void RE::Init(const char* regex) {
    144   pattern_ = posix::StrDup(regex);
    145 
    146   // Reserves enough bytes to hold the regular expression used for a
    147   // full match.
    148   const size_t full_regex_len = strlen(regex) + 10;
    149   char* const full_pattern = new char[full_regex_len];
    150 
    151   snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
    152   is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
    153   // We want to call regcomp(&partial_regex_, ...) even if the
    154   // previous expression returns false.  Otherwise partial_regex_ may
    155   // not be properly initialized can may cause trouble when it's
    156   // freed.
    157   //
    158   // Some implementation of POSIX regex (e.g. on at least some
    159   // versions of Cygwin) doesn't accept the empty string as a valid
    160   // regex.  We change it to an equivalent form "()" to be safe.
    161   if (is_valid_) {
    162     const char* const partial_regex = (*regex == '\0') ? "()" : regex;
    163     is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
    164   }
    165   EXPECT_TRUE(is_valid_)
    166       << "Regular expression \"" << regex
    167       << "\" is not a valid POSIX Extended regular expression.";
    168 
    169   delete[] full_pattern;
    170 }
    171 
    172 #elif GTEST_USES_SIMPLE_RE
    173 
    174 // Returns true iff ch appears anywhere in str (excluding the
    175 // terminating '\0' character).
    176 bool IsInSet(char ch, const char* str) {
    177   return ch != '\0' && strchr(str, ch) != NULL;
    178 }
    179 
    180 // Returns true iff ch belongs to the given classification.  Unlike
    181 // similar functions in <ctype.h>, these aren't affected by the
    182 // current locale.
    183 bool IsDigit(char ch) { return '0' <= ch && ch <= '9'; }
    184 bool IsPunct(char ch) {
    185   return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
    186 }
    187 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
    188 bool IsWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
    189 bool IsWordChar(char ch) {
    190   return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
    191       ('0' <= ch && ch <= '9') || ch == '_';
    192 }
    193 
    194 // Returns true iff "\\c" is a supported escape sequence.
    195 bool IsValidEscape(char c) {
    196   return (IsPunct(c) || IsInSet(c, "dDfnrsStvwW"));
    197 }
    198 
    199 // Returns true iff the given atom (specified by escaped and pattern)
    200 // matches ch.  The result is undefined if the atom is invalid.
    201 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
    202   if (escaped) {  // "\\p" where p is pattern_char.
    203     switch (pattern_char) {
    204       case 'd': return IsDigit(ch);
    205       case 'D': return !IsDigit(ch);
    206       case 'f': return ch == '\f';
    207       case 'n': return ch == '\n';
    208       case 'r': return ch == '\r';
    209       case 's': return IsWhiteSpace(ch);
    210       case 'S': return !IsWhiteSpace(ch);
    211       case 't': return ch == '\t';
    212       case 'v': return ch == '\v';
    213       case 'w': return IsWordChar(ch);
    214       case 'W': return !IsWordChar(ch);
    215     }
    216     return IsPunct(pattern_char) && pattern_char == ch;
    217   }
    218 
    219   return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
    220 }
    221 
    222 // Helper function used by ValidateRegex() to format error messages.
    223 String FormatRegexSyntaxError(const char* regex, int index) {
    224   return (Message() << "Syntax error at index " << index
    225           << " in simple regular expression \"" << regex << "\": ").GetString();
    226 }
    227 
    228 // Generates non-fatal failures and returns false if regex is invalid;
    229 // otherwise returns true.
    230 bool ValidateRegex(const char* regex) {
    231   if (regex == NULL) {
    232     // TODO(wan (at) google.com): fix the source file location in the
    233     // assertion failures to match where the regex is used in user
    234     // code.
    235     ADD_FAILURE() << "NULL is not a valid simple regular expression.";
    236     return false;
    237   }
    238 
    239   bool is_valid = true;
    240 
    241   // True iff ?, *, or + can follow the previous atom.
    242   bool prev_repeatable = false;
    243   for (int i = 0; regex[i]; i++) {
    244     if (regex[i] == '\\') {  // An escape sequence
    245       i++;
    246       if (regex[i] == '\0') {
    247         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
    248                       << "'\\' cannot appear at the end.";
    249         return false;
    250       }
    251 
    252       if (!IsValidEscape(regex[i])) {
    253         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
    254                       << "invalid escape sequence \"\\" << regex[i] << "\".";
    255         is_valid = false;
    256       }
    257       prev_repeatable = true;
    258     } else {  // Not an escape sequence.
    259       const char ch = regex[i];
    260 
    261       if (ch == '^' && i > 0) {
    262         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
    263                       << "'^' can only appear at the beginning.";
    264         is_valid = false;
    265       } else if (ch == '$' && regex[i + 1] != '\0') {
    266         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
    267                       << "'$' can only appear at the end.";
    268         is_valid = false;
    269       } else if (IsInSet(ch, "()[]{}|")) {
    270         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
    271                       << "'" << ch << "' is unsupported.";
    272         is_valid = false;
    273       } else if (IsRepeat(ch) && !prev_repeatable) {
    274         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
    275                       << "'" << ch << "' can only follow a repeatable token.";
    276         is_valid = false;
    277       }
    278 
    279       prev_repeatable = !IsInSet(ch, "^$?*+");
    280     }
    281   }
    282 
    283   return is_valid;
    284 }
    285 
    286 // Matches a repeated regex atom followed by a valid simple regular
    287 // expression.  The regex atom is defined as c if escaped is false,
    288 // or \c otherwise.  repeat is the repetition meta character (?, *,
    289 // or +).  The behavior is undefined if str contains too many
    290 // characters to be indexable by size_t, in which case the test will
    291 // probably time out anyway.  We are fine with this limitation as
    292 // std::string has it too.
    293 bool MatchRepetitionAndRegexAtHead(
    294     bool escaped, char c, char repeat, const char* regex,
    295     const char* str) {
    296   const size_t min_count = (repeat == '+') ? 1 : 0;
    297   const size_t max_count = (repeat == '?') ? 1 :
    298       static_cast<size_t>(-1) - 1;
    299   // We cannot call numeric_limits::max() as it conflicts with the
    300   // max() macro on Windows.
    301 
    302   for (size_t i = 0; i <= max_count; ++i) {
    303     // We know that the atom matches each of the first i characters in str.
    304     if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
    305       // We have enough matches at the head, and the tail matches too.
    306       // Since we only care about *whether* the pattern matches str
    307       // (as opposed to *how* it matches), there is no need to find a
    308       // greedy match.
    309       return true;
    310     }
    311     if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
    312       return false;
    313   }
    314   return false;
    315 }
    316 
    317 // Returns true iff regex matches a prefix of str.  regex must be a
    318 // valid simple regular expression and not start with "^", or the
    319 // result is undefined.
    320 bool MatchRegexAtHead(const char* regex, const char* str) {
    321   if (*regex == '\0')  // An empty regex matches a prefix of anything.
    322     return true;
    323 
    324   // "$" only matches the end of a string.  Note that regex being
    325   // valid guarantees that there's nothing after "$" in it.
    326   if (*regex == '$')
    327     return *str == '\0';
    328 
    329   // Is the first thing in regex an escape sequence?
    330   const bool escaped = *regex == '\\';
    331   if (escaped)
    332     ++regex;
    333   if (IsRepeat(regex[1])) {
    334     // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
    335     // here's an indirect recursion.  It terminates as the regex gets
    336     // shorter in each recursion.
    337     return MatchRepetitionAndRegexAtHead(
    338         escaped, regex[0], regex[1], regex + 2, str);
    339   } else {
    340     // regex isn't empty, isn't "$", and doesn't start with a
    341     // repetition.  We match the first atom of regex with the first
    342     // character of str and recurse.
    343     return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
    344         MatchRegexAtHead(regex + 1, str + 1);
    345   }
    346 }
    347 
    348 // Returns true iff regex matches any substring of str.  regex must be
    349 // a valid simple regular expression, or the result is undefined.
    350 //
    351 // The algorithm is recursive, but the recursion depth doesn't exceed
    352 // the regex length, so we won't need to worry about running out of
    353 // stack space normally.  In rare cases the time complexity can be
    354 // exponential with respect to the regex length + the string length,
    355 // but usually it's must faster (often close to linear).
    356 bool MatchRegexAnywhere(const char* regex, const char* str) {
    357   if (regex == NULL || str == NULL)
    358     return false;
    359 
    360   if (*regex == '^')
    361     return MatchRegexAtHead(regex + 1, str);
    362 
    363   // A successful match can be anywhere in str.
    364   do {
    365     if (MatchRegexAtHead(regex, str))
    366       return true;
    367   } while (*str++ != '\0');
    368   return false;
    369 }
    370 
    371 // Implements the RE class.
    372 
    373 RE::~RE() {
    374   free(const_cast<char*>(pattern_));
    375   free(const_cast<char*>(full_pattern_));
    376 }
    377 
    378 // Returns true iff regular expression re matches the entire str.
    379 bool RE::FullMatch(const char* str, const RE& re) {
    380   return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
    381 }
    382 
    383 // Returns true iff regular expression re matches a substring of str
    384 // (including str itself).
    385 bool RE::PartialMatch(const char* str, const RE& re) {
    386   return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
    387 }
    388 
    389 // Initializes an RE from its string representation.
    390 void RE::Init(const char* regex) {
    391   pattern_ = full_pattern_ = NULL;
    392   if (regex != NULL) {
    393     pattern_ = posix::StrDup(regex);
    394   }
    395 
    396   is_valid_ = ValidateRegex(regex);
    397   if (!is_valid_) {
    398     // No need to calculate the full pattern when the regex is invalid.
    399     return;
    400   }
    401 
    402   const size_t len = strlen(regex);
    403   // Reserves enough bytes to hold the regular expression used for a
    404   // full match: we need space to prepend a '^', append a '$', and
    405   // terminate the string with '\0'.
    406   char* buffer = static_cast<char*>(malloc(len + 3));
    407   full_pattern_ = buffer;
    408 
    409   if (*regex != '^')
    410     *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.
    411 
    412   // We don't use snprintf or strncpy, as they trigger a warning when
    413   // compiled with VC++ 8.0.
    414   memcpy(buffer, regex, len);
    415   buffer += len;
    416 
    417   if (len == 0 || regex[len - 1] != '$')
    418     *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.
    419 
    420   *buffer = '\0';
    421 }
    422 
    423 #endif  // GTEST_USES_POSIX_RE
    424 
    425 
    426 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
    427     : severity_(severity) {
    428   const char* const marker =
    429       severity == GTEST_INFO ?    "[  INFO ]" :
    430       severity == GTEST_WARNING ? "[WARNING]" :
    431       severity == GTEST_ERROR ?   "[ ERROR ]" : "[ FATAL ]";
    432   GetStream() << ::std::endl << marker << " "
    433               << FormatFileLocation(file, line).c_str() << ": ";
    434 }
    435 
    436 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
    437 GTestLog::~GTestLog() {
    438   GetStream() << ::std::endl;
    439   if (severity_ == GTEST_FATAL) {
    440     fflush(stderr);
    441     posix::Abort();
    442   }
    443 }
    444 // Disable Microsoft deprecation warnings for POSIX functions called from
    445 // this class (creat, dup, dup2, and close)
    446 #ifdef _MSC_VER
    447 #pragma warning(push)
    448 #pragma warning(disable: 4996)
    449 #endif  // _MSC_VER
    450 
    451 #if GTEST_HAS_STREAM_REDIRECTION_
    452 
    453 // Object that captures an output stream (stdout/stderr).
    454 class CapturedStream {
    455  public:
    456   // The ctor redirects the stream to a temporary file.
    457   CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
    458 #if GTEST_OS_WINDOWS
    459     char temp_dir_path[MAX_PATH + 1] = { '\0' };  // NOLINT
    460     char temp_file_path[MAX_PATH + 1] = { '\0' };  // NOLINT
    461 
    462     ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
    463     const UINT success = ::GetTempFileNameA(temp_dir_path,
    464                                             "gtest_redir",
    465                                             0,  // Generate unique file name.
    466                                             temp_file_path);
    467     GTEST_CHECK_(success != 0)
    468         << "Unable to create a temporary file in " << temp_dir_path;
    469     const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
    470     GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
    471                                     << temp_file_path;
    472     filename_ = temp_file_path;
    473 #else
    474     // There's no guarantee that a test has write access to the
    475     // current directory, so we create the temporary file in the /tmp
    476     // directory instead.
    477     char name_template[] = "/tmp/captured_stream.XXXXXX";
    478     const int captured_fd = mkstemp(name_template);
    479     filename_ = name_template;
    480 #endif  // GTEST_OS_WINDOWS
    481     fflush(NULL);
    482     dup2(captured_fd, fd_);
    483     close(captured_fd);
    484   }
    485 
    486   ~CapturedStream() {
    487     remove(filename_.c_str());
    488   }
    489 
    490   String GetCapturedString() {
    491     if (uncaptured_fd_ != -1) {
    492       // Restores the original stream.
    493       fflush(NULL);
    494       dup2(uncaptured_fd_, fd_);
    495       close(uncaptured_fd_);
    496       uncaptured_fd_ = -1;
    497     }
    498 
    499     FILE* const file = posix::FOpen(filename_.c_str(), "r");
    500     const String content = ReadEntireFile(file);
    501     posix::FClose(file);
    502     return content;
    503   }
    504 
    505  private:
    506   // Reads the entire content of a file as a String.
    507   static String ReadEntireFile(FILE* file);
    508 
    509   // Returns the size (in bytes) of a file.
    510   static size_t GetFileSize(FILE* file);
    511 
    512   const int fd_;  // A stream to capture.
    513   int uncaptured_fd_;
    514   // Name of the temporary file holding the stderr output.
    515   ::std::string filename_;
    516 
    517   GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
    518 };
    519 
    520 // Returns the size (in bytes) of a file.
    521 size_t CapturedStream::GetFileSize(FILE* file) {
    522   fseek(file, 0, SEEK_END);
    523   return static_cast<size_t>(ftell(file));
    524 }
    525 
    526 // Reads the entire content of a file as a string.
    527 String CapturedStream::ReadEntireFile(FILE* file) {
    528   const size_t file_size = GetFileSize(file);
    529   char* const buffer = new char[file_size];
    530 
    531   size_t bytes_last_read = 0;  // # of bytes read in the last fread()
    532   size_t bytes_read = 0;       // # of bytes read so far
    533 
    534   fseek(file, 0, SEEK_SET);
    535 
    536   // Keeps reading the file until we cannot read further or the
    537   // pre-determined file size is reached.
    538   do {
    539     bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
    540     bytes_read += bytes_last_read;
    541   } while (bytes_last_read > 0 && bytes_read < file_size);
    542 
    543   const String content(buffer, bytes_read);
    544   delete[] buffer;
    545 
    546   return content;
    547 }
    548 
    549 #ifdef _MSC_VER
    550 #pragma warning(pop)
    551 #endif  // _MSC_VER
    552 
    553 static CapturedStream* g_captured_stderr = NULL;
    554 static CapturedStream* g_captured_stdout = NULL;
    555 
    556 // Starts capturing an output stream (stdout/stderr).
    557 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
    558   if (*stream != NULL) {
    559     GTEST_LOG_(FATAL) << "Only one " << stream_name
    560                       << " capturer can exist at a time.";
    561   }
    562   *stream = new CapturedStream(fd);
    563 }
    564 
    565 // Stops capturing the output stream and returns the captured string.
    566 String GetCapturedStream(CapturedStream** captured_stream) {
    567   const String content = (*captured_stream)->GetCapturedString();
    568 
    569   delete *captured_stream;
    570   *captured_stream = NULL;
    571 
    572   return content;
    573 }
    574 
    575 // Starts capturing stdout.
    576 void CaptureStdout() {
    577   CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
    578 }
    579 
    580 // Starts capturing stderr.
    581 void CaptureStderr() {
    582   CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
    583 }
    584 
    585 // Stops capturing stdout and returns the captured string.
    586 String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); }
    587 
    588 // Stops capturing stderr and returns the captured string.
    589 String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); }
    590 
    591 #endif  // GTEST_HAS_STREAM_REDIRECTION_
    592 
    593 #if GTEST_HAS_DEATH_TEST
    594 
    595 // A copy of all command line arguments.  Set by InitGoogleTest().
    596 ::std::vector<String> g_argvs;
    597 
    598 // Returns the command line as a vector of strings.
    599 const ::std::vector<String>& GetArgvs() { return g_argvs; }
    600 
    601 #endif  // GTEST_HAS_DEATH_TEST
    602 
    603 #if GTEST_OS_WINDOWS_MOBILE
    604 namespace posix {
    605 void Abort() {
    606   DebugBreak();
    607   TerminateProcess(GetCurrentProcess(), 1);
    608 }
    609 }  // namespace posix
    610 #endif  // GTEST_OS_WINDOWS_MOBILE
    611 
    612 // Returns the name of the environment variable corresponding to the
    613 // given flag.  For example, FlagToEnvVar("foo") will return
    614 // "GTEST_FOO" in the open-source version.
    615 static String FlagToEnvVar(const char* flag) {
    616   const String full_flag =
    617       (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
    618 
    619   Message env_var;
    620   for (size_t i = 0; i != full_flag.length(); i++) {
    621     env_var << static_cast<char>(toupper(full_flag.c_str()[i]));
    622   }
    623 
    624   return env_var.GetString();
    625 }
    626 
    627 // Parses 'str' for a 32-bit signed integer.  If successful, writes
    628 // the result to *value and returns true; otherwise leaves *value
    629 // unchanged and returns false.
    630 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
    631   // Parses the environment variable as a decimal integer.
    632   char* end = NULL;
    633   const long long_value = strtol(str, &end, 10);  // NOLINT
    634 
    635   // Has strtol() consumed all characters in the string?
    636   if (*end != '\0') {
    637     // No - an invalid character was encountered.
    638     Message msg;
    639     msg << "WARNING: " << src_text
    640         << " is expected to be a 32-bit integer, but actually"
    641         << " has value \"" << str << "\".\n";
    642     printf("%s", msg.GetString().c_str());
    643     fflush(stdout);
    644     return false;
    645   }
    646 
    647   // Is the parsed value in the range of an Int32?
    648   const Int32 result = static_cast<Int32>(long_value);
    649   if (long_value == LONG_MAX || long_value == LONG_MIN ||
    650       // The parsed value overflows as a long.  (strtol() returns
    651       // LONG_MAX or LONG_MIN when the input overflows.)
    652       result != long_value
    653       // The parsed value overflows as an Int32.
    654       ) {
    655     Message msg;
    656     msg << "WARNING: " << src_text
    657         << " is expected to be a 32-bit integer, but actually"
    658         << " has value " << str << ", which overflows.\n";
    659     printf("%s", msg.GetString().c_str());
    660     fflush(stdout);
    661     return false;
    662   }
    663 
    664   *value = result;
    665   return true;
    666 }
    667 
    668 // Reads and returns the Boolean environment variable corresponding to
    669 // the given flag; if it's not set, returns default_value.
    670 //
    671 // The value is considered true iff it's not "0".
    672 bool BoolFromGTestEnv(const char* flag, bool default_value) {
    673   const String env_var = FlagToEnvVar(flag);
    674   const char* const string_value = posix::GetEnv(env_var.c_str());
    675   return string_value == NULL ?
    676       default_value : strcmp(string_value, "0") != 0;
    677 }
    678 
    679 // Reads and returns a 32-bit integer stored in the environment
    680 // variable corresponding to the given flag; if it isn't set or
    681 // doesn't represent a valid 32-bit integer, returns default_value.
    682 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
    683   const String env_var = FlagToEnvVar(flag);
    684   const char* const string_value = posix::GetEnv(env_var.c_str());
    685   if (string_value == NULL) {
    686     // The environment variable is not set.
    687     return default_value;
    688   }
    689 
    690   Int32 result = default_value;
    691   if (!ParseInt32(Message() << "Environment variable " << env_var,
    692                   string_value, &result)) {
    693     printf("The default value %s is used.\n",
    694            (Message() << default_value).GetString().c_str());
    695     fflush(stdout);
    696     return default_value;
    697   }
    698 
    699   return result;
    700 }
    701 
    702 // Reads and returns the string environment variable corresponding to
    703 // the given flag; if it's not set, returns default_value.
    704 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
    705   const String env_var = FlagToEnvVar(flag);
    706   const char* const value = posix::GetEnv(env_var.c_str());
    707   return value == NULL ? default_value : value;
    708 }
    709 
    710 }  // namespace internal
    711 }  // namespace testing
    712