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