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