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