gtest-port.cc
Go to the documentation of this file.
00001 // Copyright 2008, Google Inc.
00002 // All rights reserved.
00003 //
00004 // Redistribution and use in source and binary forms, with or without
00005 // modification, are permitted provided that the following conditions are
00006 // met:
00007 //
00008 //     * Redistributions of source code must retain the above copyright
00009 // notice, this list of conditions and the following disclaimer.
00010 //     * Redistributions in binary form must reproduce the above
00011 // copyright notice, this list of conditions and the following disclaimer
00012 // in the documentation and/or other materials provided with the
00013 // distribution.
00014 //     * Neither the name of Google Inc. nor the names of its
00015 // contributors may be used to endorse or promote products derived from
00016 // this software without specific prior written permission.
00017 //
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 //
00030 // Author: wan@google.com (Zhanyong Wan)
00031 
00032 #include "gtest/internal/gtest-port.h"
00033 
00034 #include <limits.h>
00035 #include <stdlib.h>
00036 #include <stdio.h>
00037 #include <string.h>
00038 
00039 #if GTEST_OS_WINDOWS_MOBILE
00040 # include <windows.h>  // For TerminateProcess()
00041 #elif GTEST_OS_WINDOWS
00042 # include <io.h>
00043 # include <sys/stat.h>
00044 #else
00045 # include <unistd.h>
00046 #endif  // GTEST_OS_WINDOWS_MOBILE
00047 
00048 #if GTEST_OS_MAC
00049 # include <mach/mach_init.h>
00050 # include <mach/task.h>
00051 # include <mach/vm_map.h>
00052 #endif  // GTEST_OS_MAC
00053 
00054 #include "gtest/gtest-spi.h"
00055 #include "gtest/gtest-message.h"
00056 #include "gtest/internal/gtest-internal.h"
00057 #include "gtest/internal/gtest-string.h"
00058 
00059 // Indicates that this translation unit is part of Google Test's
00060 // implementation.  It must come before gtest-internal-inl.h is
00061 // included, or there will be a compiler error.  This trick is to
00062 // prevent a user from accidentally including gtest-internal-inl.h in
00063 // his code.
00064 #define GTEST_IMPLEMENTATION_ 1
00065 #include "src/gtest-internal-inl.h"
00066 #undef GTEST_IMPLEMENTATION_
00067 
00068 namespace testing {
00069 namespace internal {
00070 
00071 #if defined(_MSC_VER) || defined(__BORLANDC__)
00072 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
00073 const int kStdOutFileno = 1;
00074 const int kStdErrFileno = 2;
00075 #else
00076 const int kStdOutFileno = STDOUT_FILENO;
00077 const int kStdErrFileno = STDERR_FILENO;
00078 #endif  // _MSC_VER
00079 
00080 #if GTEST_OS_MAC
00081 
00082 // Returns the number of threads running in the process, or 0 to indicate that
00083 // we cannot detect it.
00084 size_t GetThreadCount() {
00085   const task_t task = mach_task_self();
00086   mach_msg_type_number_t thread_count;
00087   thread_act_array_t thread_list;
00088   const kern_return_t status = task_threads(task, &thread_list, &thread_count);
00089   if (status == KERN_SUCCESS) {
00090     // task_threads allocates resources in thread_list and we need to free them
00091     // to avoid leaks.
00092     vm_deallocate(task,
00093                   reinterpret_cast<vm_address_t>(thread_list),
00094                   sizeof(thread_t) * thread_count);
00095     return static_cast<size_t>(thread_count);
00096   } else {
00097     return 0;
00098   }
00099 }
00100 
00101 #else
00102 
00103 size_t GetThreadCount() {
00104   // There's no portable way to detect the number of threads, so we just
00105   // return 0 to indicate that we cannot detect it.
00106   return 0;
00107 }
00108 
00109 #endif  // GTEST_OS_MAC
00110 
00111 #if GTEST_USES_POSIX_RE
00112 
00113 // Implements RE.  Currently only needed for death tests.
00114 
00115 RE::~RE() {
00116   if (is_valid_) {
00117     // regfree'ing an invalid regex might crash because the content
00118     // of the regex is undefined. Since the regex's are essentially
00119     // the same, one cannot be valid (or invalid) without the other
00120     // being so too.
00121     regfree(&partial_regex_);
00122     regfree(&full_regex_);
00123   }
00124   free(const_cast<char*>(pattern_));
00125 }
00126 
00127 // Returns true iff regular expression re matches the entire str.
00128 bool RE::FullMatch(const char* str, const RE& re) {
00129   if (!re.is_valid_) return false;
00130 
00131   regmatch_t match;
00132   return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
00133 }
00134 
00135 // Returns true iff regular expression re matches a substring of str
00136 // (including str itself).
00137 bool RE::PartialMatch(const char* str, const RE& re) {
00138   if (!re.is_valid_) return false;
00139 
00140   regmatch_t match;
00141   return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
00142 }
00143 
00144 // Initializes an RE from its string representation.
00145 void RE::Init(const char* regex) {
00146   pattern_ = posix::StrDup(regex);
00147 
00148   // Reserves enough bytes to hold the regular expression used for a
00149   // full match.
00150   const size_t full_regex_len = strlen(regex) + 10;
00151   char* const full_pattern = new char[full_regex_len];
00152 
00153   snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
00154   is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
00155   // We want to call regcomp(&partial_regex_, ...) even if the
00156   // previous expression returns false.  Otherwise partial_regex_ may
00157   // not be properly initialized can may cause trouble when it's
00158   // freed.
00159   //
00160   // Some implementation of POSIX regex (e.g. on at least some
00161   // versions of Cygwin) doesn't accept the empty string as a valid
00162   // regex.  We change it to an equivalent form "()" to be safe.
00163   if (is_valid_) {
00164     const char* const partial_regex = (*regex == '\0') ? "()" : regex;
00165     is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
00166   }
00167   EXPECT_TRUE(is_valid_)
00168       << "Regular expression \"" << regex
00169       << "\" is not a valid POSIX Extended regular expression.";
00170 
00171   delete[] full_pattern;
00172 }
00173 
00174 #elif GTEST_USES_SIMPLE_RE
00175 
00176 // Returns true iff ch appears anywhere in str (excluding the
00177 // terminating '\0' character).
00178 bool IsInSet(char ch, const char* str) {
00179   return ch != '\0' && strchr(str, ch) != NULL;
00180 }
00181 
00182 // Returns true iff ch belongs to the given classification.  Unlike
00183 // similar functions in <ctype.h>, these aren't affected by the
00184 // current locale.
00185 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
00186 bool IsAsciiPunct(char ch) {
00187   return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
00188 }
00189 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
00190 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
00191 bool IsAsciiWordChar(char ch) {
00192   return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
00193       ('0' <= ch && ch <= '9') || ch == '_';
00194 }
00195 
00196 // Returns true iff "\\c" is a supported escape sequence.
00197 bool IsValidEscape(char c) {
00198   return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
00199 }
00200 
00201 // Returns true iff the given atom (specified by escaped and pattern)
00202 // matches ch.  The result is undefined if the atom is invalid.
00203 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
00204   if (escaped) {  // "\\p" where p is pattern_char.
00205     switch (pattern_char) {
00206       case 'd': return IsAsciiDigit(ch);
00207       case 'D': return !IsAsciiDigit(ch);
00208       case 'f': return ch == '\f';
00209       case 'n': return ch == '\n';
00210       case 'r': return ch == '\r';
00211       case 's': return IsAsciiWhiteSpace(ch);
00212       case 'S': return !IsAsciiWhiteSpace(ch);
00213       case 't': return ch == '\t';
00214       case 'v': return ch == '\v';
00215       case 'w': return IsAsciiWordChar(ch);
00216       case 'W': return !IsAsciiWordChar(ch);
00217     }
00218     return IsAsciiPunct(pattern_char) && pattern_char == ch;
00219   }
00220 
00221   return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
00222 }
00223 
00224 // Helper function used by ValidateRegex() to format error messages.
00225 String FormatRegexSyntaxError(const char* regex, int index) {
00226   return (Message() << "Syntax error at index " << index
00227           << " in simple regular expression \"" << regex << "\": ").GetString();
00228 }
00229 
00230 // Generates non-fatal failures and returns false if regex is invalid;
00231 // otherwise returns true.
00232 bool ValidateRegex(const char* regex) {
00233   if (regex == NULL) {
00234     // TODO(wan@google.com): fix the source file location in the
00235     // assertion failures to match where the regex is used in user
00236     // code.
00237     ADD_FAILURE() << "NULL is not a valid simple regular expression.";
00238     return false;
00239   }
00240 
00241   bool is_valid = true;
00242 
00243   // True iff ?, *, or + can follow the previous atom.
00244   bool prev_repeatable = false;
00245   for (int i = 0; regex[i]; i++) {
00246     if (regex[i] == '\\') {  // An escape sequence
00247       i++;
00248       if (regex[i] == '\0') {
00249         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
00250                       << "'\\' cannot appear at the end.";
00251         return false;
00252       }
00253 
00254       if (!IsValidEscape(regex[i])) {
00255         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
00256                       << "invalid escape sequence \"\\" << regex[i] << "\".";
00257         is_valid = false;
00258       }
00259       prev_repeatable = true;
00260     } else {  // Not an escape sequence.
00261       const char ch = regex[i];
00262 
00263       if (ch == '^' && i > 0) {
00264         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
00265                       << "'^' can only appear at the beginning.";
00266         is_valid = false;
00267       } else if (ch == '$' && regex[i + 1] != '\0') {
00268         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
00269                       << "'$' can only appear at the end.";
00270         is_valid = false;
00271       } else if (IsInSet(ch, "()[]{}|")) {
00272         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
00273                       << "'" << ch << "' is unsupported.";
00274         is_valid = false;
00275       } else if (IsRepeat(ch) && !prev_repeatable) {
00276         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
00277                       << "'" << ch << "' can only follow a repeatable token.";
00278         is_valid = false;
00279       }
00280 
00281       prev_repeatable = !IsInSet(ch, "^$?*+");
00282     }
00283   }
00284 
00285   return is_valid;
00286 }
00287 
00288 // Matches a repeated regex atom followed by a valid simple regular
00289 // expression.  The regex atom is defined as c if escaped is false,
00290 // or \c otherwise.  repeat is the repetition meta character (?, *,
00291 // or +).  The behavior is undefined if str contains too many
00292 // characters to be indexable by size_t, in which case the test will
00293 // probably time out anyway.  We are fine with this limitation as
00294 // std::string has it too.
00295 bool MatchRepetitionAndRegexAtHead(
00296     bool escaped, char c, char repeat, const char* regex,
00297     const char* str) {
00298   const size_t min_count = (repeat == '+') ? 1 : 0;
00299   const size_t max_count = (repeat == '?') ? 1 :
00300       static_cast<size_t>(-1) - 1;
00301   // We cannot call numeric_limits::max() as it conflicts with the
00302   // max() macro on Windows.
00303 
00304   for (size_t i = 0; i <= max_count; ++i) {
00305     // We know that the atom matches each of the first i characters in str.
00306     if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
00307       // We have enough matches at the head, and the tail matches too.
00308       // Since we only care about *whether* the pattern matches str
00309       // (as opposed to *how* it matches), there is no need to find a
00310       // greedy match.
00311       return true;
00312     }
00313     if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
00314       return false;
00315   }
00316   return false;
00317 }
00318 
00319 // Returns true iff regex matches a prefix of str.  regex must be a
00320 // valid simple regular expression and not start with "^", or the
00321 // result is undefined.
00322 bool MatchRegexAtHead(const char* regex, const char* str) {
00323   if (*regex == '\0')  // An empty regex matches a prefix of anything.
00324     return true;
00325 
00326   // "$" only matches the end of a string.  Note that regex being
00327   // valid guarantees that there's nothing after "$" in it.
00328   if (*regex == '$')
00329     return *str == '\0';
00330 
00331   // Is the first thing in regex an escape sequence?
00332   const bool escaped = *regex == '\\';
00333   if (escaped)
00334     ++regex;
00335   if (IsRepeat(regex[1])) {
00336     // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
00337     // here's an indirect recursion.  It terminates as the regex gets
00338     // shorter in each recursion.
00339     return MatchRepetitionAndRegexAtHead(
00340         escaped, regex[0], regex[1], regex + 2, str);
00341   } else {
00342     // regex isn't empty, isn't "$", and doesn't start with a
00343     // repetition.  We match the first atom of regex with the first
00344     // character of str and recurse.
00345     return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
00346         MatchRegexAtHead(regex + 1, str + 1);
00347   }
00348 }
00349 
00350 // Returns true iff regex matches any substring of str.  regex must be
00351 // a valid simple regular expression, or the result is undefined.
00352 //
00353 // The algorithm is recursive, but the recursion depth doesn't exceed
00354 // the regex length, so we won't need to worry about running out of
00355 // stack space normally.  In rare cases the time complexity can be
00356 // exponential with respect to the regex length + the string length,
00357 // but usually it's must faster (often close to linear).
00358 bool MatchRegexAnywhere(const char* regex, const char* str) {
00359   if (regex == NULL || str == NULL)
00360     return false;
00361 
00362   if (*regex == '^')
00363     return MatchRegexAtHead(regex + 1, str);
00364 
00365   // A successful match can be anywhere in str.
00366   do {
00367     if (MatchRegexAtHead(regex, str))
00368       return true;
00369   } while (*str++ != '\0');
00370   return false;
00371 }
00372 
00373 // Implements the RE class.
00374 
00375 RE::~RE() {
00376   free(const_cast<char*>(pattern_));
00377   free(const_cast<char*>(full_pattern_));
00378 }
00379 
00380 // Returns true iff regular expression re matches the entire str.
00381 bool RE::FullMatch(const char* str, const RE& re) {
00382   return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
00383 }
00384 
00385 // Returns true iff regular expression re matches a substring of str
00386 // (including str itself).
00387 bool RE::PartialMatch(const char* str, const RE& re) {
00388   return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
00389 }
00390 
00391 // Initializes an RE from its string representation.
00392 void RE::Init(const char* regex) {
00393   pattern_ = full_pattern_ = NULL;
00394   if (regex != NULL) {
00395     pattern_ = posix::StrDup(regex);
00396   }
00397 
00398   is_valid_ = ValidateRegex(regex);
00399   if (!is_valid_) {
00400     // No need to calculate the full pattern when the regex is invalid.
00401     return;
00402   }
00403 
00404   const size_t len = strlen(regex);
00405   // Reserves enough bytes to hold the regular expression used for a
00406   // full match: we need space to prepend a '^', append a '$', and
00407   // terminate the string with '\0'.
00408   char* buffer = static_cast<char*>(malloc(len + 3));
00409   full_pattern_ = buffer;
00410 
00411   if (*regex != '^')
00412     *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.
00413 
00414   // We don't use snprintf or strncpy, as they trigger a warning when
00415   // compiled with VC++ 8.0.
00416   memcpy(buffer, regex, len);
00417   buffer += len;
00418 
00419   if (len == 0 || regex[len - 1] != '$')
00420     *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.
00421 
00422   *buffer = '\0';
00423 }
00424 
00425 #endif  // GTEST_USES_POSIX_RE
00426 
00427 const char kUnknownFile[] = "unknown file";
00428 
00429 // Formats a source file path and a line number as they would appear
00430 // in an error message from the compiler used to compile this code.
00431 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
00432   const char* const file_name = file == NULL ? kUnknownFile : file;
00433 
00434   if (line < 0) {
00435     return String::Format("%s:", file_name).c_str();
00436   }
00437 #ifdef _MSC_VER
00438   return String::Format("%s(%d):", file_name, line).c_str();
00439 #else
00440   return String::Format("%s:%d:", file_name, line).c_str();
00441 #endif  // _MSC_VER
00442 }
00443 
00444 // Formats a file location for compiler-independent XML output.
00445 // Although this function is not platform dependent, we put it next to
00446 // FormatFileLocation in order to contrast the two functions.
00447 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
00448 // to the file location it produces, unlike FormatFileLocation().
00449 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
00450     const char* file, int line) {
00451   const char* const file_name = file == NULL ? kUnknownFile : file;
00452 
00453   if (line < 0)
00454     return file_name;
00455   else
00456     return String::Format("%s:%d", file_name, line).c_str();
00457 }
00458 
00459 
00460 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
00461     : severity_(severity) {
00462   const char* const marker =
00463       severity == GTEST_INFO ?    "[  INFO ]" :
00464       severity == GTEST_WARNING ? "[WARNING]" :
00465       severity == GTEST_ERROR ?   "[ ERROR ]" : "[ FATAL ]";
00466   GetStream() << ::std::endl << marker << " "
00467               << FormatFileLocation(file, line).c_str() << ": ";
00468 }
00469 
00470 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
00471 GTestLog::~GTestLog() {
00472   GetStream() << ::std::endl;
00473   if (severity_ == GTEST_FATAL) {
00474     fflush(stderr);
00475     posix::Abort();
00476   }
00477 }
00478 // Disable Microsoft deprecation warnings for POSIX functions called from
00479 // this class (creat, dup, dup2, and close)
00480 #ifdef _MSC_VER
00481 # pragma warning(push)
00482 # pragma warning(disable: 4996)
00483 #endif  // _MSC_VER
00484 
00485 #if GTEST_HAS_STREAM_REDIRECTION
00486 
00487 // Object that captures an output stream (stdout/stderr).
00488 class CapturedStream {
00489  public:
00490   // The ctor redirects the stream to a temporary file.
00491   CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
00492 
00493 # if GTEST_OS_WINDOWS
00494     char temp_dir_path[MAX_PATH + 1] = { '\0' };  // NOLINT
00495     char temp_file_path[MAX_PATH + 1] = { '\0' };  // NOLINT
00496 
00497     ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
00498     const UINT success = ::GetTempFileNameA(temp_dir_path,
00499                                             "gtest_redir",
00500                                             0,  // Generate unique file name.
00501                                             temp_file_path);
00502     GTEST_CHECK_(success != 0)
00503         << "Unable to create a temporary file in " << temp_dir_path;
00504     const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
00505     GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
00506                                     << temp_file_path;
00507     filename_ = temp_file_path;
00508 # else
00509     // There's no guarantee that a test has write access to the
00510     // current directory, so we create the temporary file in the /tmp
00511     // directory instead.
00512     char name_template[] = "/tmp/captured_stream.XXXXXX";
00513     const int captured_fd = mkstemp(name_template);
00514     filename_ = name_template;
00515 # endif  // GTEST_OS_WINDOWS
00516     fflush(NULL);
00517     dup2(captured_fd, fd_);
00518     close(captured_fd);
00519   }
00520 
00521   ~CapturedStream() {
00522     remove(filename_.c_str());
00523   }
00524 
00525   String GetCapturedString() {
00526     if (uncaptured_fd_ != -1) {
00527       // Restores the original stream.
00528       fflush(NULL);
00529       dup2(uncaptured_fd_, fd_);
00530       close(uncaptured_fd_);
00531       uncaptured_fd_ = -1;
00532     }
00533 
00534     FILE* const file = posix::FOpen(filename_.c_str(), "r");
00535     const String content = ReadEntireFile(file);
00536     posix::FClose(file);
00537     return content;
00538   }
00539 
00540  private:
00541   // Reads the entire content of a file as a String.
00542   static String ReadEntireFile(FILE* file);
00543 
00544   // Returns the size (in bytes) of a file.
00545   static size_t GetFileSize(FILE* file);
00546 
00547   const int fd_;  // A stream to capture.
00548   int uncaptured_fd_;
00549   // Name of the temporary file holding the stderr output.
00550   ::std::string filename_;
00551 
00552   GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
00553 };
00554 
00555 // Returns the size (in bytes) of a file.
00556 size_t CapturedStream::GetFileSize(FILE* file) {
00557   fseek(file, 0, SEEK_END);
00558   return static_cast<size_t>(ftell(file));
00559 }
00560 
00561 // Reads the entire content of a file as a string.
00562 String CapturedStream::ReadEntireFile(FILE* file) {
00563   const size_t file_size = GetFileSize(file);
00564   char* const buffer = new char[file_size];
00565 
00566   size_t bytes_last_read = 0;  // # of bytes read in the last fread()
00567   size_t bytes_read = 0;       // # of bytes read so far
00568 
00569   fseek(file, 0, SEEK_SET);
00570 
00571   // Keeps reading the file until we cannot read further or the
00572   // pre-determined file size is reached.
00573   do {
00574     bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
00575     bytes_read += bytes_last_read;
00576   } while (bytes_last_read > 0 && bytes_read < file_size);
00577 
00578   const String content(buffer, bytes_read);
00579   delete[] buffer;
00580 
00581   return content;
00582 }
00583 
00584 # ifdef _MSC_VER
00585 #  pragma warning(pop)
00586 # endif  // _MSC_VER
00587 
00588 static CapturedStream* g_captured_stderr = NULL;
00589 static CapturedStream* g_captured_stdout = NULL;
00590 
00591 // Starts capturing an output stream (stdout/stderr).
00592 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
00593   if (*stream != NULL) {
00594     GTEST_LOG_(FATAL) << "Only one " << stream_name
00595                       << " capturer can exist at a time.";
00596   }
00597   *stream = new CapturedStream(fd);
00598 }
00599 
00600 // Stops capturing the output stream and returns the captured string.
00601 String GetCapturedStream(CapturedStream** captured_stream) {
00602   const String content = (*captured_stream)->GetCapturedString();
00603 
00604   delete *captured_stream;
00605   *captured_stream = NULL;
00606 
00607   return content;
00608 }
00609 
00610 // Starts capturing stdout.
00611 void CaptureStdout() {
00612   CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
00613 }
00614 
00615 // Starts capturing stderr.
00616 void CaptureStderr() {
00617   CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
00618 }
00619 
00620 // Stops capturing stdout and returns the captured string.
00621 String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); }
00622 
00623 // Stops capturing stderr and returns the captured string.
00624 String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); }
00625 
00626 #endif  // GTEST_HAS_STREAM_REDIRECTION
00627 
00628 #if GTEST_HAS_DEATH_TEST
00629 
00630 // A copy of all command line arguments.  Set by InitGoogleTest().
00631 ::std::vector<String> g_argvs;
00632 
00633 // Returns the command line as a vector of strings.
00634 const ::std::vector<String>& GetArgvs() { return g_argvs; }
00635 
00636 #endif  // GTEST_HAS_DEATH_TEST
00637 
00638 #if GTEST_OS_WINDOWS_MOBILE
00639 namespace posix {
00640 void Abort() {
00641   DebugBreak();
00642   TerminateProcess(GetCurrentProcess(), 1);
00643 }
00644 }  // namespace posix
00645 #endif  // GTEST_OS_WINDOWS_MOBILE
00646 
00647 // Returns the name of the environment variable corresponding to the
00648 // given flag.  For example, FlagToEnvVar("foo") will return
00649 // "GTEST_FOO" in the open-source version.
00650 static String FlagToEnvVar(const char* flag) {
00651   const String full_flag =
00652       (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
00653 
00654   Message env_var;
00655   for (size_t i = 0; i != full_flag.length(); i++) {
00656     env_var << ToUpper(full_flag.c_str()[i]);
00657   }
00658 
00659   return env_var.GetString();
00660 }
00661 
00662 // Parses 'str' for a 32-bit signed integer.  If successful, writes
00663 // the result to *value and returns true; otherwise leaves *value
00664 // unchanged and returns false.
00665 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
00666   // Parses the environment variable as a decimal integer.
00667   char* end = NULL;
00668   const long long_value = strtol(str, &end, 10);  // NOLINT
00669 
00670   // Has strtol() consumed all characters in the string?
00671   if (*end != '\0') {
00672     // No - an invalid character was encountered.
00673     Message msg;
00674     msg << "WARNING: " << src_text
00675         << " is expected to be a 32-bit integer, but actually"
00676         << " has value \"" << str << "\".\n";
00677     printf("%s", msg.GetString().c_str());
00678     fflush(stdout);
00679     return false;
00680   }
00681 
00682   // Is the parsed value in the range of an Int32?
00683   const Int32 result = static_cast<Int32>(long_value);
00684   if (long_value == LONG_MAX || long_value == LONG_MIN ||
00685       // The parsed value overflows as a long.  (strtol() returns
00686       // LONG_MAX or LONG_MIN when the input overflows.)
00687       result != long_value
00688       // The parsed value overflows as an Int32.
00689       ) {
00690     Message msg;
00691     msg << "WARNING: " << src_text
00692         << " is expected to be a 32-bit integer, but actually"
00693         << " has value " << str << ", which overflows.\n";
00694     printf("%s", msg.GetString().c_str());
00695     fflush(stdout);
00696     return false;
00697   }
00698 
00699   *value = result;
00700   return true;
00701 }
00702 
00703 // Reads and returns the Boolean environment variable corresponding to
00704 // the given flag; if it's not set, returns default_value.
00705 //
00706 // The value is considered true iff it's not "0".
00707 bool BoolFromGTestEnv(const char* flag, bool default_value) {
00708   const String env_var = FlagToEnvVar(flag);
00709   const char* const string_value = posix::GetEnv(env_var.c_str());
00710   return string_value == NULL ?
00711       default_value : strcmp(string_value, "0") != 0;
00712 }
00713 
00714 // Reads and returns a 32-bit integer stored in the environment
00715 // variable corresponding to the given flag; if it isn't set or
00716 // doesn't represent a valid 32-bit integer, returns default_value.
00717 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
00718   const String env_var = FlagToEnvVar(flag);
00719   const char* const string_value = posix::GetEnv(env_var.c_str());
00720   if (string_value == NULL) {
00721     // The environment variable is not set.
00722     return default_value;
00723   }
00724 
00725   Int32 result = default_value;
00726   if (!ParseInt32(Message() << "Environment variable " << env_var,
00727                   string_value, &result)) {
00728     printf("The default value %s is used.\n",
00729            (Message() << default_value).GetString().c_str());
00730     fflush(stdout);
00731     return default_value;
00732   }
00733 
00734   return result;
00735 }
00736 
00737 // Reads and returns the string environment variable corresponding to
00738 // the given flag; if it's not set, returns default_value.
00739 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
00740   const String env_var = FlagToEnvVar(flag);
00741   const char* const value = posix::GetEnv(env_var.c_str());
00742   return value == NULL ? default_value : value;
00743 }
00744 
00745 }  // namespace internal
00746 }  // namespace testing


pcl
Author(s): Open Perception
autogenerated on Wed Aug 26 2015 15:24:39