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
     39 #include <io.h>
     40 #include <sys/stat.h>
     41 #else
     42 #include <unistd.h>
     43 #endif  // GTEST_OS_WINDOWS
     44 
     45 #if GTEST_USES_SIMPLE_RE
     46 #include <string.h>
     47 #endif
     48 
     49 #ifdef _WIN32_WCE
     50 #include <windows.h>  // For TerminateProcess()
     51 #endif  // _WIN32_WCE
     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 GTEST_OS_WINDOWS
     70 // Microsoft does not provide a definition of STDERR_FILENO.
     71 const int kStdErrFileno = 2;
     72 #else
     73 const int kStdErrFileno = STDERR_FILENO;
     74 #endif  // GTEST_OS_WINDOWS
     75 
     76 #if GTEST_USES_POSIX_RE
     77 
     78 // Implements RE.  Currently only needed for death tests.
     79 
     80 RE::~RE() {
     81   regfree(&partial_regex_);
     82   regfree(&full_regex_);
     83   free(const_cast<char*>(pattern_));
     84 }
     85 
     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;
     89 
     90   regmatch_t match;
     91   return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
     92 }
     93 
     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;
     98 
     99   regmatch_t match;
    100   return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
    101 }
    102 
    103 // Initializes an RE from its string representation.
    104 void RE::Init(const char* regex) {
    105   pattern_ = strdup(regex);
    106 
    107   // Reserves enough bytes to hold the regular expression used for a
    108   // full match.
    109   const size_t full_regex_len = strlen(regex) + 10;
    110   char* const full_pattern = new char[full_regex_len];
    111 
    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
    117   // freed.
    118   //
    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)
    124       && is_valid_;
    125   EXPECT_TRUE(is_valid_)
    126       << "Regular expression \"" << regex
    127       << "\" is not a valid POSIX Extended regular expression.";
    128 
    129   delete[] full_pattern;
    130 }
    131 
    132 #elif GTEST_USES_SIMPLE_RE
    133 
    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;
    138 }
    139 
    140 // Returns true iff ch belongs to the given classification.  Unlike
    141 // similar functions in <ctype.h>, these aren't affected by the
    142 // current locale.
    143 bool IsDigit(char ch) { return '0' <= ch && ch <= '9'; }
    144 bool IsPunct(char ch) {
    145   return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
    146 }
    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 == '_';
    152 }
    153 
    154 // Returns true iff "\\c" is a supported escape sequence.
    155 bool IsValidEscape(char c) {
    156   return (IsPunct(c) || IsInSet(c, "dDfnrsStvwW"));
    157 }
    158 
    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);
    175     }
    176     return IsPunct(pattern_char) && pattern_char == ch;
    177   }
    178 
    179   return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
    180 }
    181 
    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();
    186 }
    187 
    188 // Generates non-fatal failures and returns false if regex is invalid;
    189 // otherwise returns true.
    190 bool ValidateRegex(const char* regex) {
    191   if (regex == NULL) {
    192     // TODO(wan (at) google.com): fix the source file location in the
    193     // assertion failures to match where the regex is used in user
    194     // code.
    195     ADD_FAILURE() << "NULL is not a valid simple regular expression.";
    196     return false;
    197   }
    198 
    199   bool is_valid = true;
    200 
    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
    205       i++;
    206       if (regex[i] == '\0') {
    207         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
    208                       << "'\\' cannot appear at the end.";
    209         return false;
    210       }
    211 
    212       if (!IsValidEscape(regex[i])) {
    213         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
    214                       << "invalid escape sequence \"\\" << regex[i] << "\".";
    215         is_valid = false;
    216       }
    217       prev_repeatable = true;
    218     } else {  // Not an escape sequence.
    219       const char ch = regex[i];
    220 
    221       if (ch == '^' && i > 0) {
    222         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
    223                       << "'^' can only appear at the beginning.";
    224         is_valid = false;
    225       } else if (ch == '$' && regex[i + 1] != '\0') {
    226         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
    227                       << "'$' can only appear at the end.";
    228         is_valid = false;
    229       } else if (IsInSet(ch, "()[]{}|")) {
    230         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
    231                       << "'" << ch << "' is unsupported.";
    232         is_valid = false;
    233       } else if (IsRepeat(ch) && !prev_repeatable) {
    234         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
    235                       << "'" << ch << "' can only follow a repeatable token.";
    236         is_valid = false;
    237       }
    238 
    239       prev_repeatable = !IsInSet(ch, "^$?*+");
    240     }
    241   }
    242 
    243   return is_valid;
    244 }
    245 
    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,
    255     const char* str) {
    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.
    261 
    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
    268       // greedy match.
    269       return true;
    270     }
    271     if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
    272       return false;
    273   }
    274   return false;
    275 }
    276 
    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.
    282     return true;
    283 
    284   // "$" only matches the end of a string.  Note that regex being
    285   // valid guarantees that there's nothing after "$" in it.
    286   if (*regex == '$')
    287     return *str == '\0';
    288 
    289   // Is the first thing in regex an escape sequence?
    290   const bool escaped = *regex == '\\';
    291   if (escaped)
    292     ++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);
    299   } else {
    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);
    305   }
    306 }
    307 
    308 // Returns true iff regex matches any substring of str.  regex must be
    309 // a valid simple regular expression, or the result is undefined.
    310 //
    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)
    318     return false;
    319 
    320   if (*regex == '^')
    321     return MatchRegexAtHead(regex + 1, str);
    322 
    323   // A successful match can be anywhere in str.
    324   do {
    325     if (MatchRegexAtHead(regex, str))
    326       return true;
    327   } while (*str++ != '\0');
    328   return false;
    329 }
    330 
    331 // Implements the RE class.
    332 
    333 RE::~RE() {
    334   free(const_cast<char*>(pattern_));
    335   free(const_cast<char*>(full_pattern_));
    336 }
    337 
    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);
    341 }
    342 
    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);
    347 }
    348 
    349 // Initializes an RE from its string representation.
    350 void RE::Init(const char* regex) {
    351   pattern_ = full_pattern_ = NULL;
    352   if (regex != NULL) {
    353 #if GTEST_OS_WINDOWS
    354     pattern_ = _strdup(regex);
    355 #else
    356     pattern_ = strdup(regex);
    357 #endif
    358   }
    359 
    360   is_valid_ = ValidateRegex(regex);
    361   if (!is_valid_) {
    362     // No need to calculate the full pattern when the regex is invalid.
    363     return;
    364   }
    365 
    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;
    372 
    373   if (*regex != '^')
    374     *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.
    375 
    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);
    379   buffer += len;
    380 
    381   if (len == 0 || regex[len - 1] != '$')
    382     *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.
    383 
    384   *buffer = '\0';
    385 }
    386 
    387 #endif  // GTEST_USES_POSIX_RE
    388 
    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.
    399     abort();
    400   }
    401 }
    402 
    403 #if GTEST_HAS_STD_STRING
    404 
    405 // Disable Microsoft deprecation warnings for POSIX functions called from
    406 // this class (creat, dup, dup2, and close)
    407 #ifdef _MSC_VER
    408 #pragma warning(push)
    409 #pragma warning(disable: 4996)
    410 #endif  // _MSC_VER
    411 
    412 // Defines the stderr capturer.
    413 
    414 class CapturedStderr {
    415  public:
    416   // The ctor redirects stderr to a temporary file.
    417   CapturedStderr() {
    418     uncaptured_fd_ = dup(kStdErrFileno);
    419 
    420 #if GTEST_OS_WINDOWS
    421     char temp_dir_path[MAX_PATH + 1] = { '\0' };  // NOLINT
    422     char temp_file_path[MAX_PATH + 1] = { '\0' };  // NOLINT
    423 
    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;
    428 #elif GTEST_OS_ANDROID
    429     char name_template[] = "/sdcard/captured_stderr.XXXXXX";
    430     const int captured_fd = mkstemp(name_template);
    431     filename_ = name_template;
    432 #else
    433     // There's no guarantee that a test has write access to the
    434     // current directory, so we create the temporary file in the /tmp
    435     // directory instead.
    436     char name_template[] = "/tmp/captured_stderr.XXXXXX";
    437     const int captured_fd = mkstemp(name_template);
    438     filename_ = name_template;
    439 #endif  // GTEST_OS_WINDOWS
    440     fflush(NULL);
    441     dup2(captured_fd, kStdErrFileno);
    442     close(captured_fd);
    443   }
    444 
    445   ~CapturedStderr() {
    446     remove(filename_.c_str());
    447   }
    448 
    449   // Stops redirecting stderr.
    450   void StopCapture() {
    451     // Restores the original stream.
    452     fflush(NULL);
    453     dup2(uncaptured_fd_, kStdErrFileno);
    454     close(uncaptured_fd_);
    455     uncaptured_fd_ = -1;
    456   }
    457 
    458   // Returns the name of the temporary file holding the stderr output.
    459   // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
    460   // can use it here.
    461   ::std::string filename() const { return filename_; }
    462 
    463  private:
    464   int uncaptured_fd_;
    465   ::std::string filename_;
    466 };
    467 
    468 #ifdef _MSC_VER
    469 #pragma warning(pop)
    470 #endif  // _MSC_VER
    471 
    472 static CapturedStderr* g_captured_stderr = NULL;
    473 
    474 // Returns the size (in bytes) of a file.
    475 static size_t GetFileSize(FILE * file) {
    476   fseek(file, 0, SEEK_END);
    477   return static_cast<size_t>(ftell(file));
    478 }
    479 
    480 // Reads the entire content of a file as a string.
    481 static ::std::string ReadEntireFile(FILE * file) {
    482   const size_t file_size = GetFileSize(file);
    483   char* const buffer = new char[file_size];
    484 
    485   size_t bytes_last_read = 0;  // # of bytes read in the last fread()
    486   size_t bytes_read = 0;       // # of bytes read so far
    487 
    488   fseek(file, 0, SEEK_SET);
    489 
    490   // Keeps reading the file until we cannot read further or the
    491   // pre-determined file size is reached.
    492   do {
    493     bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
    494     bytes_read += bytes_last_read;
    495   } while (bytes_last_read > 0 && bytes_read < file_size);
    496 
    497   const ::std::string content(buffer, buffer+bytes_read);
    498   delete[] buffer;
    499 
    500   return content;
    501 }
    502 
    503 // Starts capturing stderr.
    504 void CaptureStderr() {
    505   if (g_captured_stderr != NULL) {
    506     GTEST_LOG_(FATAL, "Only one stderr capturer can exist at one time.");
    507   }
    508   g_captured_stderr = new CapturedStderr;
    509 }
    510 
    511 // Stops capturing stderr and returns the captured string.
    512 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can
    513 // use it here.
    514 ::std::string GetCapturedStderr() {
    515   g_captured_stderr->StopCapture();
    516 
    517 // Disables Microsoft deprecation warning for fopen and fclose.
    518 #ifdef _MSC_VER
    519 #pragma warning(push)
    520 #pragma warning(disable: 4996)
    521 #endif  // _MSC_VER
    522   FILE* const file = fopen(g_captured_stderr->filename().c_str(), "r");
    523   const ::std::string content = ReadEntireFile(file);
    524   fclose(file);
    525 #ifdef _MSC_VER
    526 #pragma warning(pop)
    527 #endif  // _MSC_VER
    528 
    529   delete g_captured_stderr;
    530   g_captured_stderr = NULL;
    531 
    532   return content;
    533 }
    534 
    535 #endif  // GTEST_HAS_STD_STRING
    536 
    537 #if GTEST_HAS_DEATH_TEST
    538 
    539 // A copy of all command line arguments.  Set by InitGoogleTest().
    540 ::std::vector<String> g_argvs;
    541 
    542 // Returns the command line as a vector of strings.
    543 const ::std::vector<String>& GetArgvs() { return g_argvs; }
    544 
    545 #endif  // GTEST_HAS_DEATH_TEST
    546 
    547 #ifdef _WIN32_WCE
    548 void abort() {
    549   DebugBreak();
    550   TerminateProcess(GetCurrentProcess(), 1);
    551 }
    552 #endif  // _WIN32_WCE
    553 
    554 // Returns the name of the environment variable corresponding to the
    555 // given flag.  For example, FlagToEnvVar("foo") will return
    556 // "GTEST_FOO" in the open-source version.
    557 static String FlagToEnvVar(const char* flag) {
    558   const String full_flag =
    559       (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
    560 
    561   Message env_var;
    562   for (int i = 0; i != full_flag.GetLength(); i++) {
    563     env_var << static_cast<char>(toupper(full_flag.c_str()[i]));
    564   }
    565 
    566   return env_var.GetString();
    567 }
    568 
    569 // Parses 'str' for a 32-bit signed integer.  If successful, writes
    570 // the result to *value and returns true; otherwise leaves *value
    571 // unchanged and returns false.
    572 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
    573   // Parses the environment variable as a decimal integer.
    574   char* end = NULL;
    575   const long long_value = strtol(str, &end, 10);  // NOLINT
    576 
    577   // Has strtol() consumed all characters in the string?
    578   if (*end != '\0') {
    579     // No - an invalid character was encountered.
    580     Message msg;
    581     msg << "WARNING: " << src_text
    582         << " is expected to be a 32-bit integer, but actually"
    583         << " has value \"" << str << "\".\n";
    584     printf("%s", msg.GetString().c_str());
    585     fflush(stdout);
    586     return false;
    587   }
    588 
    589   // Is the parsed value in the range of an Int32?
    590   const Int32 result = static_cast<Int32>(long_value);
    591   if (long_value == LONG_MAX || long_value == LONG_MIN ||
    592       // The parsed value overflows as a long.  (strtol() returns
    593       // LONG_MAX or LONG_MIN when the input overflows.)
    594       result != long_value
    595       // The parsed value overflows as an Int32.
    596       ) {
    597     Message msg;
    598     msg << "WARNING: " << src_text
    599         << " is expected to be a 32-bit integer, but actually"
    600         << " has value " << str << ", which overflows.\n";
    601     printf("%s", msg.GetString().c_str());
    602     fflush(stdout);
    603     return false;
    604   }
    605 
    606   *value = result;
    607   return true;
    608 }
    609 
    610 // Reads and returns the Boolean environment variable corresponding to
    611 // the given flag; if it's not set, returns default_value.
    612 //
    613 // The value is considered true iff it's not "0".
    614 bool BoolFromGTestEnv(const char* flag, bool default_value) {
    615   const String env_var = FlagToEnvVar(flag);
    616   const char* const string_value = GetEnv(env_var.c_str());
    617   return string_value == NULL ?
    618       default_value : strcmp(string_value, "0") != 0;
    619 }
    620 
    621 // Reads and returns a 32-bit integer stored in the environment
    622 // variable corresponding to the given flag; if it isn't set or
    623 // doesn't represent a valid 32-bit integer, returns default_value.
    624 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
    625   const String env_var = FlagToEnvVar(flag);
    626   const char* const string_value = GetEnv(env_var.c_str());
    627   if (string_value == NULL) {
    628     // The environment variable is not set.
    629     return default_value;
    630   }
    631 
    632   Int32 result = default_value;
    633   if (!ParseInt32(Message() << "Environment variable " << env_var,
    634                   string_value, &result)) {
    635     printf("The default value %s is used.\n",
    636            (Message() << default_value).GetString().c_str());
    637     fflush(stdout);
    638     return default_value;
    639   }
    640 
    641   return result;
    642 }
    643 
    644 // Reads and returns the string environment variable corresponding to
    645 // the given flag; if it's not set, returns default_value.
    646 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
    647   const String env_var = FlagToEnvVar(flag);
    648   const char* const value = GetEnv(env_var.c_str());
    649   return value == NULL ? default_value : value;
    650 }
    651 
    652 }  // namespace internal
    653 }  // namespace testing
    654