gtest-port.cc revision fc2de66453b0669c09eaca643b07d34443858b6f
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 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 74namespace testing { 75namespace internal { 76 77#if defined(_MSC_VER) || defined(__BORLANDC__) 78// MSVC and C++Builder do not provide a definition of STDERR_FILENO. 79const int kStdOutFileno = 1; 80const int kStdErrFileno = 2; 81#else 82const int kStdOutFileno = STDOUT_FILENO; 83const 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. 90size_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. 111size_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 129size_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 141RE::~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. 154bool 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). 163bool 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. 171void 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). 204bool 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. 211bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } 212bool IsAsciiPunct(char ch) { 213 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); 214} 215bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } 216bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } 217bool 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. 223bool 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. 229bool 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. 251std::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. 258bool ValidateRegex(const char* regex) { 259 if (regex == NULL) { 260 // TODO(wan@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. 321bool 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. 348bool 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). 384bool 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 401RE::~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. 407bool 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). 413bool 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. 418void 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 453const 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. 457GTEST_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(). 475GTEST_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 486GTestLog::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. 497GTestLog::~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). 514class 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// END android-changed 555# else 556 // There's no guarantee that a test has write access to the current 557 // directory, so we create the temporary file in the /tmp directory 558 // instead. We use /tmp on most systems, and /sdcard on Android. 559 // That's because Android doesn't have /tmp. 560# if GTEST_OS_LINUX_ANDROID 561 // Note: Android applications are expected to call the framework's 562 // Context.getExternalStorageDirectory() method through JNI to get 563 // the location of the world-writable SD Card directory. However, 564 // this requires a Context handle, which cannot be retrieved 565 // globally from native code. Doing so also precludes running the 566 // code as part of a regular standalone executable, which doesn't 567 // run in a Dalvik process (e.g. when running it through 'adb shell'). 568 // 569 // The location /sdcard is directly accessible from native code 570 // and is the only location (unofficially) supported by the Android 571 // team. It's generally a symlink to the real SD Card mount point 572 // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or 573 // other OEM-customized locations. Never rely on these, and always 574 // use /sdcard. 575 char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX"; 576# else 577 char name_template[] = "/tmp/captured_stream.XXXXXX"; 578# endif // GTEST_OS_LINUX_ANDROID 579 const int captured_fd = mkstemp(name_template); 580 filename_ = name_template; 581# endif // GTEST_OS_WINDOWS 582 fflush(NULL); 583 dup2(captured_fd, fd_); 584 close(captured_fd); 585 } 586 587 ~CapturedStream() { 588 remove(filename_.c_str()); 589 } 590 591 std::string GetCapturedString() { 592 if (uncaptured_fd_ != -1) { 593 // Restores the original stream. 594 fflush(NULL); 595 dup2(uncaptured_fd_, fd_); 596 close(uncaptured_fd_); 597 uncaptured_fd_ = -1; 598 } 599 600 FILE* const file = posix::FOpen(filename_.c_str(), "r"); 601// BEGIN android-changed 602 GTEST_CHECK_(file != NULL) << "Unable to open temporary file " 603 << filename_.c_str() << ": " 604 << strerror(errno); 605// END android-changed 606 const std::string content = ReadEntireFile(file); 607 posix::FClose(file); 608 return content; 609 } 610 611 private: 612 // Reads the entire content of a file as an std::string. 613 static std::string ReadEntireFile(FILE* file); 614 615 // Returns the size (in bytes) of a file. 616 static size_t GetFileSize(FILE* file); 617 618 const int fd_; // A stream to capture. 619 int uncaptured_fd_; 620 // Name of the temporary file holding the stderr output. 621 ::std::string filename_; 622 623 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); 624}; 625 626// Returns the size (in bytes) of a file. 627size_t CapturedStream::GetFileSize(FILE* file) { 628 fseek(file, 0, SEEK_END); 629 return static_cast<size_t>(ftell(file)); 630} 631 632// Reads the entire content of a file as a string. 633std::string CapturedStream::ReadEntireFile(FILE* file) { 634 const size_t file_size = GetFileSize(file); 635 char* const buffer = new char[file_size]; 636 637 size_t bytes_last_read = 0; // # of bytes read in the last fread() 638 size_t bytes_read = 0; // # of bytes read so far 639 640 fseek(file, 0, SEEK_SET); 641 642 // Keeps reading the file until we cannot read further or the 643 // pre-determined file size is reached. 644 do { 645 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); 646 bytes_read += bytes_last_read; 647 } while (bytes_last_read > 0 && bytes_read < file_size); 648 649 const std::string content(buffer, bytes_read); 650 delete[] buffer; 651 652 return content; 653} 654 655# ifdef _MSC_VER 656# pragma warning(pop) 657# endif // _MSC_VER 658 659static CapturedStream* g_captured_stderr = NULL; 660static CapturedStream* g_captured_stdout = NULL; 661 662// Starts capturing an output stream (stdout/stderr). 663void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { 664 if (*stream != NULL) { 665 GTEST_LOG_(FATAL) << "Only one " << stream_name 666 << " capturer can exist at a time."; 667 } 668 *stream = new CapturedStream(fd); 669} 670 671// Stops capturing the output stream and returns the captured string. 672std::string GetCapturedStream(CapturedStream** captured_stream) { 673 const std::string content = (*captured_stream)->GetCapturedString(); 674 675 delete *captured_stream; 676 *captured_stream = NULL; 677 678 return content; 679} 680 681// Starts capturing stdout. 682void CaptureStdout() { 683 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); 684} 685 686// Starts capturing stderr. 687void CaptureStderr() { 688 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); 689} 690 691// Stops capturing stdout and returns the captured string. 692std::string GetCapturedStdout() { 693 return GetCapturedStream(&g_captured_stdout); 694} 695 696// Stops capturing stderr and returns the captured string. 697std::string GetCapturedStderr() { 698 return GetCapturedStream(&g_captured_stderr); 699} 700 701#endif // GTEST_HAS_STREAM_REDIRECTION 702 703#if GTEST_HAS_DEATH_TEST 704 705// A copy of all command line arguments. Set by InitGoogleTest(). 706::std::vector<testing::internal::string> g_argvs; 707 708static const ::std::vector<testing::internal::string>* g_injected_test_argvs = 709 NULL; // Owned. 710 711void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) { 712 if (g_injected_test_argvs != argvs) 713 delete g_injected_test_argvs; 714 g_injected_test_argvs = argvs; 715} 716 717const ::std::vector<testing::internal::string>& GetInjectableArgvs() { 718 if (g_injected_test_argvs != NULL) { 719 return *g_injected_test_argvs; 720 } 721 return g_argvs; 722} 723#endif // GTEST_HAS_DEATH_TEST 724 725#if GTEST_OS_WINDOWS_MOBILE 726namespace posix { 727void Abort() { 728 DebugBreak(); 729 TerminateProcess(GetCurrentProcess(), 1); 730} 731} // namespace posix 732#endif // GTEST_OS_WINDOWS_MOBILE 733 734// Returns the name of the environment variable corresponding to the 735// given flag. For example, FlagToEnvVar("foo") will return 736// "GTEST_FOO" in the open-source version. 737static std::string FlagToEnvVar(const char* flag) { 738 const std::string full_flag = 739 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); 740 741 Message env_var; 742 for (size_t i = 0; i != full_flag.length(); i++) { 743 env_var << ToUpper(full_flag.c_str()[i]); 744 } 745 746 return env_var.GetString(); 747} 748 749// Parses 'str' for a 32-bit signed integer. If successful, writes 750// the result to *value and returns true; otherwise leaves *value 751// unchanged and returns false. 752bool ParseInt32(const Message& src_text, const char* str, Int32* value) { 753 // Parses the environment variable as a decimal integer. 754 char* end = NULL; 755 const long long_value = strtol(str, &end, 10); // NOLINT 756 757 // Has strtol() consumed all characters in the string? 758 if (*end != '\0') { 759 // No - an invalid character was encountered. 760 Message msg; 761 msg << "WARNING: " << src_text 762 << " is expected to be a 32-bit integer, but actually" 763 << " has value \"" << str << "\".\n"; 764 printf("%s", msg.GetString().c_str()); 765 fflush(stdout); 766 return false; 767 } 768 769 // Is the parsed value in the range of an Int32? 770 const Int32 result = static_cast<Int32>(long_value); 771 if (long_value == LONG_MAX || long_value == LONG_MIN || 772 // The parsed value overflows as a long. (strtol() returns 773 // LONG_MAX or LONG_MIN when the input overflows.) 774 result != long_value 775 // The parsed value overflows as an Int32. 776 ) { 777 Message msg; 778 msg << "WARNING: " << src_text 779 << " is expected to be a 32-bit integer, but actually" 780 << " has value " << str << ", which overflows.\n"; 781 printf("%s", msg.GetString().c_str()); 782 fflush(stdout); 783 return false; 784 } 785 786 *value = result; 787 return true; 788} 789 790// Reads and returns the Boolean environment variable corresponding to 791// the given flag; if it's not set, returns default_value. 792// 793// The value is considered true iff it's not "0". 794bool BoolFromGTestEnv(const char* flag, bool default_value) { 795 const std::string env_var = FlagToEnvVar(flag); 796 const char* const string_value = posix::GetEnv(env_var.c_str()); 797 return string_value == NULL ? 798 default_value : strcmp(string_value, "0") != 0; 799} 800 801// Reads and returns a 32-bit integer stored in the environment 802// variable corresponding to the given flag; if it isn't set or 803// doesn't represent a valid 32-bit integer, returns default_value. 804Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { 805 const std::string env_var = FlagToEnvVar(flag); 806 const char* const string_value = posix::GetEnv(env_var.c_str()); 807 if (string_value == NULL) { 808 // The environment variable is not set. 809 return default_value; 810 } 811 812 Int32 result = default_value; 813 if (!ParseInt32(Message() << "Environment variable " << env_var, 814 string_value, &result)) { 815 printf("The default value %s is used.\n", 816 (Message() << default_value).GetString().c_str()); 817 fflush(stdout); 818 return default_value; 819 } 820 821 return result; 822} 823 824// Reads and returns the string environment variable corresponding to 825// the given flag; if it's not set, returns default_value. 826const char* StringFromGTestEnv(const char* flag, const char* default_value) { 827 const std::string env_var = FlagToEnvVar(flag); 828 const char* const value = posix::GetEnv(env_var.c_str()); 829 return value == NULL ? default_value : value; 830} 831 832} // namespace internal 833} // namespace testing 834