1 // Copyright 2008, Google Inc. 2 // All rights reserved. 3 // 4 // Redistribution and use in source and binary forms, with or without 5 // modification, are permitted provided that the following conditions are 6 // met: 7 // 8 // * Redistributions of source code must retain the above copyright 9 // notice, this list of conditions and the following disclaimer. 10 // * Redistributions in binary form must reproduce the above 11 // copyright notice, this list of conditions and the following disclaimer 12 // in the documentation and/or other materials provided with the 13 // distribution. 14 // * Neither the name of Google Inc. nor the names of its 15 // contributors may be used to endorse or promote products derived from 16 // this software without specific prior written permission. 17 // 18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 // 30 // Author: wan (at) google.com (Zhanyong Wan) 31 32 #include <gtest/internal/gtest-port.h> 33 34 #include <limits.h> 35 #include <stdlib.h> 36 #include <stdio.h> 37 38 #if GTEST_OS_WINDOWS_MOBILE 39 #include <windows.h> // For TerminateProcess() 40 #elif GTEST_OS_WINDOWS 41 #include <io.h> 42 #include <sys/stat.h> 43 #else 44 #include <unistd.h> 45 #endif // GTEST_OS_WINDOWS_MOBILE 46 47 #if GTEST_OS_MAC 48 #include <mach/mach_init.h> 49 #include <mach/task.h> 50 #include <mach/vm_map.h> 51 #endif // GTEST_OS_MAC 52 53 #include <gtest/gtest-spi.h> 54 #include <gtest/gtest-message.h> 55 #include <gtest/internal/gtest-string.h> 56 57 // Indicates that this translation unit is part of Google Test's 58 // implementation. It must come before gtest-internal-inl.h is 59 // included, or there will be a compiler error. This trick is to 60 // prevent a user from accidentally including gtest-internal-inl.h in 61 // his code. 62 #define GTEST_IMPLEMENTATION_ 1 63 #include "src/gtest-internal-inl.h" 64 #undef GTEST_IMPLEMENTATION_ 65 66 namespace testing { 67 namespace internal { 68 69 #if defined(_MSC_VER) || defined(__BORLANDC__) 70 // MSVC and C++Builder do not provide a definition of STDERR_FILENO. 71 const int kStdErrFileno = 2; 72 #else 73 const int kStdErrFileno = STDERR_FILENO; 74 #endif // _MSC_VER 75 76 #if GTEST_OS_MAC 77 78 // Returns the number of threads running in the process, or 0 to indicate that 79 // we cannot detect it. 80 size_t GetThreadCount() { 81 const task_t task = mach_task_self(); 82 mach_msg_type_number_t thread_count; 83 thread_act_array_t thread_list; 84 const kern_return_t status = task_threads(task, &thread_list, &thread_count); 85 if (status == KERN_SUCCESS) { 86 // task_threads allocates resources in thread_list and we need to free them 87 // to avoid leaks. 88 vm_deallocate(task, 89 reinterpret_cast<vm_address_t>(thread_list), 90 sizeof(thread_t) * thread_count); 91 return static_cast<size_t>(thread_count); 92 } else { 93 return 0; 94 } 95 } 96 97 #else 98 99 size_t GetThreadCount() { 100 // There's no portable way to detect the number of threads, so we just 101 // return 0 to indicate that we cannot detect it. 102 return 0; 103 } 104 105 #endif // GTEST_OS_MAC 106 107 #if GTEST_USES_POSIX_RE 108 109 // Implements RE. Currently only needed for death tests. 110 111 RE::~RE() { 112 regfree(&partial_regex_); 113 regfree(&full_regex_); 114 free(const_cast<char*>(pattern_)); 115 } 116 117 // Returns true iff regular expression re matches the entire str. 118 bool RE::FullMatch(const char* str, const RE& re) { 119 if (!re.is_valid_) return false; 120 121 regmatch_t match; 122 return regexec(&re.full_regex_, str, 1, &match, 0) == 0; 123 } 124 125 // Returns true iff regular expression re matches a substring of str 126 // (including str itself). 127 bool RE::PartialMatch(const char* str, const RE& re) { 128 if (!re.is_valid_) return false; 129 130 regmatch_t match; 131 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; 132 } 133 134 // Initializes an RE from its string representation. 135 void RE::Init(const char* regex) { 136 pattern_ = posix::StrDup(regex); 137 138 // Reserves enough bytes to hold the regular expression used for a 139 // full match. 140 const size_t full_regex_len = strlen(regex) + 10; 141 char* const full_pattern = new char[full_regex_len]; 142 143 snprintf(full_pattern, full_regex_len, "^(%s)$", regex); 144 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; 145 // We want to call regcomp(&partial_regex_, ...) even if the 146 // previous expression returns false. Otherwise partial_regex_ may 147 // not be properly initialized can may cause trouble when it's 148 // freed. 149 // 150 // Some implementation of POSIX regex (e.g. on at least some 151 // versions of Cygwin) doesn't accept the empty string as a valid 152 // regex. We change it to an equivalent form "()" to be safe. 153 const char* const partial_regex = (*regex == '\0') ? "()" : regex; 154 is_valid_ = (regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0) 155 && is_valid_; 156 EXPECT_TRUE(is_valid_) 157 << "Regular expression \"" << regex 158 << "\" is not a valid POSIX Extended regular expression."; 159 160 delete[] full_pattern; 161 } 162 163 #elif GTEST_USES_SIMPLE_RE 164 165 // Returns true iff ch appears anywhere in str (excluding the 166 // terminating '\0' character). 167 bool IsInSet(char ch, const char* str) { 168 return ch != '\0' && strchr(str, ch) != NULL; 169 } 170 171 // Returns true iff ch belongs to the given classification. Unlike 172 // similar functions in <ctype.h>, these aren't affected by the 173 // current locale. 174 bool IsDigit(char ch) { return '0' <= ch && ch <= '9'; } 175 bool IsPunct(char ch) { 176 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); 177 } 178 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } 179 bool IsWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } 180 bool IsWordChar(char ch) { 181 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || 182 ('0' <= ch && ch <= '9') || ch == '_'; 183 } 184 185 // Returns true iff "\\c" is a supported escape sequence. 186 bool IsValidEscape(char c) { 187 return (IsPunct(c) || IsInSet(c, "dDfnrsStvwW")); 188 } 189 190 // Returns true iff the given atom (specified by escaped and pattern) 191 // matches ch. The result is undefined if the atom is invalid. 192 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { 193 if (escaped) { // "\\p" where p is pattern_char. 194 switch (pattern_char) { 195 case 'd': return IsDigit(ch); 196 case 'D': return !IsDigit(ch); 197 case 'f': return ch == '\f'; 198 case 'n': return ch == '\n'; 199 case 'r': return ch == '\r'; 200 case 's': return IsWhiteSpace(ch); 201 case 'S': return !IsWhiteSpace(ch); 202 case 't': return ch == '\t'; 203 case 'v': return ch == '\v'; 204 case 'w': return IsWordChar(ch); 205 case 'W': return !IsWordChar(ch); 206 } 207 return IsPunct(pattern_char) && pattern_char == ch; 208 } 209 210 return (pattern_char == '.' && ch != '\n') || pattern_char == ch; 211 } 212 213 // Helper function used by ValidateRegex() to format error messages. 214 String FormatRegexSyntaxError(const char* regex, int index) { 215 return (Message() << "Syntax error at index " << index 216 << " in simple regular expression \"" << regex << "\": ").GetString(); 217 } 218 219 // Generates non-fatal failures and returns false if regex is invalid; 220 // otherwise returns true. 221 bool ValidateRegex(const char* regex) { 222 if (regex == NULL) { 223 // TODO(wan (at) google.com): fix the source file location in the 224 // assertion failures to match where the regex is used in user 225 // code. 226 ADD_FAILURE() << "NULL is not a valid simple regular expression."; 227 return false; 228 } 229 230 bool is_valid = true; 231 232 // True iff ?, *, or + can follow the previous atom. 233 bool prev_repeatable = false; 234 for (int i = 0; regex[i]; i++) { 235 if (regex[i] == '\\') { // An escape sequence 236 i++; 237 if (regex[i] == '\0') { 238 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) 239 << "'\\' cannot appear at the end."; 240 return false; 241 } 242 243 if (!IsValidEscape(regex[i])) { 244 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) 245 << "invalid escape sequence \"\\" << regex[i] << "\"."; 246 is_valid = false; 247 } 248 prev_repeatable = true; 249 } else { // Not an escape sequence. 250 const char ch = regex[i]; 251 252 if (ch == '^' && i > 0) { 253 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) 254 << "'^' can only appear at the beginning."; 255 is_valid = false; 256 } else if (ch == '$' && regex[i + 1] != '\0') { 257 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) 258 << "'$' can only appear at the end."; 259 is_valid = false; 260 } else if (IsInSet(ch, "()[]{}|")) { 261 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) 262 << "'" << ch << "' is unsupported."; 263 is_valid = false; 264 } else if (IsRepeat(ch) && !prev_repeatable) { 265 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) 266 << "'" << ch << "' can only follow a repeatable token."; 267 is_valid = false; 268 } 269 270 prev_repeatable = !IsInSet(ch, "^$?*+"); 271 } 272 } 273 274 return is_valid; 275 } 276 277 // Matches a repeated regex atom followed by a valid simple regular 278 // expression. The regex atom is defined as c if escaped is false, 279 // or \c otherwise. repeat is the repetition meta character (?, *, 280 // or +). The behavior is undefined if str contains too many 281 // characters to be indexable by size_t, in which case the test will 282 // probably time out anyway. We are fine with this limitation as 283 // std::string has it too. 284 bool MatchRepetitionAndRegexAtHead( 285 bool escaped, char c, char repeat, const char* regex, 286 const char* str) { 287 const size_t min_count = (repeat == '+') ? 1 : 0; 288 const size_t max_count = (repeat == '?') ? 1 : 289 static_cast<size_t>(-1) - 1; 290 // We cannot call numeric_limits::max() as it conflicts with the 291 // max() macro on Windows. 292 293 for (size_t i = 0; i <= max_count; ++i) { 294 // We know that the atom matches each of the first i characters in str. 295 if (i >= min_count && MatchRegexAtHead(regex, str + i)) { 296 // We have enough matches at the head, and the tail matches too. 297 // Since we only care about *whether* the pattern matches str 298 // (as opposed to *how* it matches), there is no need to find a 299 // greedy match. 300 return true; 301 } 302 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) 303 return false; 304 } 305 return false; 306 } 307 308 // Returns true iff regex matches a prefix of str. regex must be a 309 // valid simple regular expression and not start with "^", or the 310 // result is undefined. 311 bool MatchRegexAtHead(const char* regex, const char* str) { 312 if (*regex == '\0') // An empty regex matches a prefix of anything. 313 return true; 314 315 // "$" only matches the end of a string. Note that regex being 316 // valid guarantees that there's nothing after "$" in it. 317 if (*regex == '$') 318 return *str == '\0'; 319 320 // Is the first thing in regex an escape sequence? 321 const bool escaped = *regex == '\\'; 322 if (escaped) 323 ++regex; 324 if (IsRepeat(regex[1])) { 325 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so 326 // here's an indirect recursion. It terminates as the regex gets 327 // shorter in each recursion. 328 return MatchRepetitionAndRegexAtHead( 329 escaped, regex[0], regex[1], regex + 2, str); 330 } else { 331 // regex isn't empty, isn't "$", and doesn't start with a 332 // repetition. We match the first atom of regex with the first 333 // character of str and recurse. 334 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && 335 MatchRegexAtHead(regex + 1, str + 1); 336 } 337 } 338 339 // Returns true iff regex matches any substring of str. regex must be 340 // a valid simple regular expression, or the result is undefined. 341 // 342 // The algorithm is recursive, but the recursion depth doesn't exceed 343 // the regex length, so we won't need to worry about running out of 344 // stack space normally. In rare cases the time complexity can be 345 // exponential with respect to the regex length + the string length, 346 // but usually it's must faster (often close to linear). 347 bool MatchRegexAnywhere(const char* regex, const char* str) { 348 if (regex == NULL || str == NULL) 349 return false; 350 351 if (*regex == '^') 352 return MatchRegexAtHead(regex + 1, str); 353 354 // A successful match can be anywhere in str. 355 do { 356 if (MatchRegexAtHead(regex, str)) 357 return true; 358 } while (*str++ != '\0'); 359 return false; 360 } 361 362 // Implements the RE class. 363 364 RE::~RE() { 365 free(const_cast<char*>(pattern_)); 366 free(const_cast<char*>(full_pattern_)); 367 } 368 369 // Returns true iff regular expression re matches the entire str. 370 bool RE::FullMatch(const char* str, const RE& re) { 371 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); 372 } 373 374 // Returns true iff regular expression re matches a substring of str 375 // (including str itself). 376 bool RE::PartialMatch(const char* str, const RE& re) { 377 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); 378 } 379 380 // Initializes an RE from its string representation. 381 void RE::Init(const char* regex) { 382 pattern_ = full_pattern_ = NULL; 383 if (regex != NULL) { 384 pattern_ = posix::StrDup(regex); 385 } 386 387 is_valid_ = ValidateRegex(regex); 388 if (!is_valid_) { 389 // No need to calculate the full pattern when the regex is invalid. 390 return; 391 } 392 393 const size_t len = strlen(regex); 394 // Reserves enough bytes to hold the regular expression used for a 395 // full match: we need space to prepend a '^', append a '$', and 396 // terminate the string with '\0'. 397 char* buffer = static_cast<char*>(malloc(len + 3)); 398 full_pattern_ = buffer; 399 400 if (*regex != '^') 401 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. 402 403 // We don't use snprintf or strncpy, as they trigger a warning when 404 // compiled with VC++ 8.0. 405 memcpy(buffer, regex, len); 406 buffer += len; 407 408 if (len == 0 || regex[len - 1] != '$') 409 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. 410 411 *buffer = '\0'; 412 } 413 414 #endif // GTEST_USES_POSIX_RE 415 416 417 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) 418 : severity_(severity) { 419 const char* const marker = 420 severity == GTEST_INFO ? "[ INFO ]" : 421 severity == GTEST_WARNING ? "[WARNING]" : 422 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; 423 GetStream() << ::std::endl << marker << " " 424 << FormatFileLocation(file, line).c_str() << ": "; 425 } 426 427 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. 428 GTestLog::~GTestLog() { 429 GetStream() << ::std::endl; 430 if (severity_ == GTEST_FATAL) { 431 fflush(stderr); 432 posix::Abort(); 433 } 434 } 435 // Disable Microsoft deprecation warnings for POSIX functions called from 436 // this class (creat, dup, dup2, and close) 437 #ifdef _MSC_VER 438 #pragma warning(push) 439 #pragma warning(disable: 4996) 440 #endif // _MSC_VER 441 442 // Defines the stderr capturer. 443 444 class CapturedStderr { 445 public: 446 // The ctor redirects stderr to a temporary file. 447 CapturedStderr() { 448 #if GTEST_OS_WINDOWS_MOBILE 449 // Not supported on Windows CE. 450 posix::Abort(); 451 #else 452 uncaptured_fd_ = dup(kStdErrFileno); 453 454 #if GTEST_OS_WINDOWS 455 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT 456 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT 457 458 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); 459 ::GetTempFileNameA(temp_dir_path, "gtest_redir", 0, temp_file_path); 460 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); 461 filename_ = temp_file_path; 462 #else 463 // There's no guarantee that a test has write access to the 464 // current directory, so we create the temporary file in the /tmp 465 // directory instead. 466 char name_template[] = "/tmp/captured_stderr.XXXXXX"; 467 const int captured_fd = mkstemp(name_template); 468 filename_ = name_template; 469 #endif // GTEST_OS_WINDOWS 470 fflush(NULL); 471 dup2(captured_fd, kStdErrFileno); 472 close(captured_fd); 473 #endif // GTEST_OS_WINDOWS_MOBILE 474 } 475 476 ~CapturedStderr() { 477 #if !GTEST_OS_WINDOWS_MOBILE 478 remove(filename_.c_str()); 479 #endif // !GTEST_OS_WINDOWS_MOBILE 480 } 481 482 // Stops redirecting stderr. 483 void StopCapture() { 484 #if !GTEST_OS_WINDOWS_MOBILE 485 // Restores the original stream. 486 fflush(NULL); 487 dup2(uncaptured_fd_, kStdErrFileno); 488 close(uncaptured_fd_); 489 uncaptured_fd_ = -1; 490 #endif // !GTEST_OS_WINDOWS_MOBILE 491 } 492 493 // Returns the name of the temporary file holding the stderr output. 494 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we 495 // can use it here. 496 ::std::string filename() const { return filename_; } 497 498 private: 499 int uncaptured_fd_; 500 ::std::string filename_; 501 }; 502 503 #ifdef _MSC_VER 504 #pragma warning(pop) 505 #endif // _MSC_VER 506 507 static CapturedStderr* g_captured_stderr = NULL; 508 509 // Returns the size (in bytes) of a file. 510 static size_t GetFileSize(FILE * file) { 511 fseek(file, 0, SEEK_END); 512 return static_cast<size_t>(ftell(file)); 513 } 514 515 // Reads the entire content of a file as a string. 516 static String ReadEntireFile(FILE * file) { 517 const size_t file_size = GetFileSize(file); 518 char* const buffer = new char[file_size]; 519 520 size_t bytes_last_read = 0; // # of bytes read in the last fread() 521 size_t bytes_read = 0; // # of bytes read so far 522 523 fseek(file, 0, SEEK_SET); 524 525 // Keeps reading the file until we cannot read further or the 526 // pre-determined file size is reached. 527 do { 528 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); 529 bytes_read += bytes_last_read; 530 } while (bytes_last_read > 0 && bytes_read < file_size); 531 532 const String content(buffer, bytes_read); 533 delete[] buffer; 534 535 return content; 536 } 537 538 // Starts capturing stderr. 539 void CaptureStderr() { 540 if (g_captured_stderr != NULL) { 541 GTEST_LOG_(FATAL) << "Only one stderr capturer can exist at one time."; 542 } 543 g_captured_stderr = new CapturedStderr; 544 } 545 546 // Stops capturing stderr and returns the captured string. 547 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can 548 // use it here. 549 String GetCapturedStderr() { 550 g_captured_stderr->StopCapture(); 551 552 FILE* const file = posix::FOpen(g_captured_stderr->filename().c_str(), "r"); 553 const String content = ReadEntireFile(file); 554 posix::FClose(file); 555 556 delete g_captured_stderr; 557 g_captured_stderr = NULL; 558 559 return content; 560 } 561 562 #if GTEST_HAS_DEATH_TEST 563 564 // A copy of all command line arguments. Set by InitGoogleTest(). 565 ::std::vector<String> g_argvs; 566 567 // Returns the command line as a vector of strings. 568 const ::std::vector<String>& GetArgvs() { return g_argvs; } 569 570 #endif // GTEST_HAS_DEATH_TEST 571 572 #if GTEST_OS_WINDOWS_MOBILE 573 namespace posix { 574 void Abort() { 575 DebugBreak(); 576 TerminateProcess(GetCurrentProcess(), 1); 577 } 578 } // namespace posix 579 #endif // GTEST_OS_WINDOWS_MOBILE 580 581 // Returns the name of the environment variable corresponding to the 582 // given flag. For example, FlagToEnvVar("foo") will return 583 // "GTEST_FOO" in the open-source version. 584 static String FlagToEnvVar(const char* flag) { 585 const String full_flag = 586 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); 587 588 Message env_var; 589 for (size_t i = 0; i != full_flag.length(); i++) { 590 env_var << static_cast<char>(toupper(full_flag.c_str()[i])); 591 } 592 593 return env_var.GetString(); 594 } 595 596 // Parses 'str' for a 32-bit signed integer. If successful, writes 597 // the result to *value and returns true; otherwise leaves *value 598 // unchanged and returns false. 599 bool ParseInt32(const Message& src_text, const char* str, Int32* value) { 600 // Parses the environment variable as a decimal integer. 601 char* end = NULL; 602 const long long_value = strtol(str, &end, 10); // NOLINT 603 604 // Has strtol() consumed all characters in the string? 605 if (*end != '\0') { 606 // No - an invalid character was encountered. 607 Message msg; 608 msg << "WARNING: " << src_text 609 << " is expected to be a 32-bit integer, but actually" 610 << " has value \"" << str << "\".\n"; 611 printf("%s", msg.GetString().c_str()); 612 fflush(stdout); 613 return false; 614 } 615 616 // Is the parsed value in the range of an Int32? 617 const Int32 result = static_cast<Int32>(long_value); 618 if (long_value == LONG_MAX || long_value == LONG_MIN || 619 // The parsed value overflows as a long. (strtol() returns 620 // LONG_MAX or LONG_MIN when the input overflows.) 621 result != long_value 622 // The parsed value overflows as an Int32. 623 ) { 624 Message msg; 625 msg << "WARNING: " << src_text 626 << " is expected to be a 32-bit integer, but actually" 627 << " has value " << str << ", which overflows.\n"; 628 printf("%s", msg.GetString().c_str()); 629 fflush(stdout); 630 return false; 631 } 632 633 *value = result; 634 return true; 635 } 636 637 // Reads and returns the Boolean environment variable corresponding to 638 // the given flag; if it's not set, returns default_value. 639 // 640 // The value is considered true iff it's not "0". 641 bool BoolFromGTestEnv(const char* flag, bool default_value) { 642 const String env_var = FlagToEnvVar(flag); 643 const char* const string_value = posix::GetEnv(env_var.c_str()); 644 return string_value == NULL ? 645 default_value : strcmp(string_value, "0") != 0; 646 } 647 648 // Reads and returns a 32-bit integer stored in the environment 649 // variable corresponding to the given flag; if it isn't set or 650 // doesn't represent a valid 32-bit integer, returns default_value. 651 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { 652 const String env_var = FlagToEnvVar(flag); 653 const char* const string_value = posix::GetEnv(env_var.c_str()); 654 if (string_value == NULL) { 655 // The environment variable is not set. 656 return default_value; 657 } 658 659 Int32 result = default_value; 660 if (!ParseInt32(Message() << "Environment variable " << env_var, 661 string_value, &result)) { 662 printf("The default value %s is used.\n", 663 (Message() << default_value).GetString().c_str()); 664 fflush(stdout); 665 return default_value; 666 } 667 668 return result; 669 } 670 671 // Reads and returns the string environment variable corresponding to 672 // the given flag; if it's not set, returns default_value. 673 const char* StringFromGTestEnv(const char* flag, const char* default_value) { 674 const String env_var = FlagToEnvVar(flag); 675 const char* const value = posix::GetEnv(env_var.c_str()); 676 return value == NULL ? default_value : value; 677 } 678 679 } // namespace internal 680 } // namespace testing 681