1 // Copyright 2005, 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 //
  31 // The Google C++ Testing and Mocking Framework (Google Test)
  32 
  33 #include "gtest/gtest.h"
  34 #include "gtest/internal/custom/gtest.h"
  35 #include "gtest/gtest-spi.h"
  36 
  37 #include <assert.h>
  38 #include <ctype.h>
  39 #include <math.h>
  40 #include <stdarg.h>
  41 #include <stdio.h>
  42 #include <stdlib.h>
  43 #include <time.h>
  44 #include <wchar.h>
  45 #include <wctype.h>
  46 
  47 #include <algorithm>
  48 #include <iomanip>
  49 #include <limits>
  50 #include <list>
  51 #include <map>
  52 #include <ostream>  // NOLINT
  53 #include <sstream>
  54 #include <vector>
  55 #if defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140
  56 #pragma error_messages(off, SEC_NULL_PTR_DEREF)
  57 #endif
  58 
  59 #if GTEST_OS_LINUX
  60 
  61 // FIXME: Use autoconf to detect availability of
  62 // gettimeofday().
  63 # define GTEST_HAS_GETTIMEOFDAY_ 1
  64 
  65 # include <fcntl.h>  // NOLINT
  66 # include <limits.h>  // NOLINT
  67 # include <sched.h>  // NOLINT
  68 // Declares vsnprintf().  This header is not available on Windows.
  69 # include <strings.h>  // NOLINT
  70 # include <sys/mman.h>  // NOLINT
  71 # include <sys/time.h>  // NOLINT
  72 # include <unistd.h>  // NOLINT
  73 # include <string>
  74 
  75 #elif GTEST_OS_SYMBIAN
  76 # define GTEST_HAS_GETTIMEOFDAY_ 1
  77 # include <sys/time.h>  // NOLINT
  78 
  79 #elif GTEST_OS_ZOS
  80 # define GTEST_HAS_GETTIMEOFDAY_ 1
  81 # include <sys/time.h>  // NOLINT
  82 
  83 // On z/OS we additionally need strings.h for strcasecmp.
  84 # include <strings.h>  // NOLINT
  85 
  86 #elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
  87 
  88 # include <windows.h>  // NOLINT
  89 # undef min
  90 
  91 #elif GTEST_OS_WINDOWS  // We are on Windows proper.
  92 
  93 # include <io.h>  // NOLINT
  94 # include <sys/timeb.h>  // NOLINT
  95 # include <sys/types.h>  // NOLINT
  96 # include <sys/stat.h>  // NOLINT
  97 
  98 # if GTEST_OS_WINDOWS_MINGW
  99 // MinGW has gettimeofday() but not _ftime64().
 100 // FIXME: Use autoconf to detect availability of
 101 //   gettimeofday().
 102 // FIXME: There are other ways to get the time on
 103 //   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
 104 //   supports these.  consider using them instead.
 105 #  define GTEST_HAS_GETTIMEOFDAY_ 1
 106 #  include <sys/time.h>  // NOLINT
 107 # endif  // GTEST_OS_WINDOWS_MINGW
 108 
 109 // cpplint thinks that the header is already included, so we want to
 110 // silence it.
 111 # include <windows.h>  // NOLINT
 112 # undef min
 113 
 114 #else
 115 
 116 // Assume other platforms have gettimeofday().
 117 // FIXME: Use autoconf to detect availability of
 118 //   gettimeofday().
 119 # define GTEST_HAS_GETTIMEOFDAY_ 1
 120 
 121 // cpplint thinks that the header is already included, so we want to
 122 // silence it.
 123 # include <sys/time.h>  // NOLINT
 124 # include <unistd.h>  // NOLINT
 125 
 126 #endif  // GTEST_OS_LINUX
 127 
 128 #if GTEST_HAS_EXCEPTIONS
 129 # include <stdexcept>
 130 #endif
 131 
 132 #if GTEST_CAN_STREAM_RESULTS_
 133 # include <arpa/inet.h>  // NOLINT
 134 # include <netdb.h>  // NOLINT
 135 # include <sys/socket.h>  // NOLINT
 136 # include <sys/types.h>  // NOLINT
 137 #endif
 138 
 139 #include "src/gtest-internal-inl.h"
 140 
 141 #if GTEST_OS_WINDOWS
 142 # define vsnprintf _vsnprintf
 143 #endif  // GTEST_OS_WINDOWS
 144 
 145 #if GTEST_OS_MAC
 146 #ifndef GTEST_OS_IOS
 147 #include <crt_externs.h>
 148 #endif
 149 #endif
 150 
 151 #if GTEST_HAS_ABSL
 152 #include "absl/debugging/failure_signal_handler.h"
 153 #include "absl/debugging/stacktrace.h"
 154 #include "absl/debugging/symbolize.h"
 155 #include "absl/strings/str_cat.h"
 156 #endif  // GTEST_HAS_ABSL
 157 
 158 namespace testing {
 159 
 160 using internal::CountIf;
 161 using internal::ForEach;
 162 using internal::GetElementOr;
 163 using internal::Shuffle;
 164 
 165 // Constants.
 166 
 167 // A test whose test case name or test name matches this filter is
 168 // disabled and not run.
 169 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
 170 
 171 // A test case whose name matches this filter is considered a death
 172 // test case and will be run before test cases whose name doesn't
 173 // match this filter.
 174 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
 175 
 176 // A test filter that matches everything.
 177 static const char kUniversalFilter[] = "*";
 178 
 179 // The default output format.
 180 static const char kDefaultOutputFormat[] = "xml";
 181 // The default output file.
 182 static const char kDefaultOutputFile[] = "test_detail";
 183 
 184 // The environment variable name for the test shard index.
 185 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
 186 // The environment variable name for the total number of test shards.
 187 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
 188 // The environment variable name for the test shard status file.
 189 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
 190 
 191 namespace internal {
 192 
 193 // The text used in failure messages to indicate the start of the
 194 // stack trace.
 195 const char kStackTraceMarker[] = "\nStack trace:\n";
 196 
 197 // g_help_flag is true iff the --help flag or an equivalent form is
 198 // specified on the command line.
 199 bool g_help_flag = false;
 200 
 201 // Utilty function to Open File for Writing
 202 static FILE* OpenFileForWriting(const std::string& output_file) {
 203   FILE* fileout = NULL;
 204   FilePath output_file_path(output_file);
 205   FilePath output_dir(output_file_path.RemoveFileName());
 206 
 207   if (output_dir.CreateDirectoriesRecursively()) {
 208     fileout = posix::FOpen(output_file.c_str(), "w");
 209   }
 210   if (fileout == NULL) {
 211     GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
 212   }
 213   return fileout;
 214 }
 215 
 216 }  // namespace internal
 217 
 218 // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
 219 // environment variable.
 220 static const char* GetDefaultFilter() {
 221   const char* const testbridge_test_only =
 222       internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
 223   if (testbridge_test_only != NULL) {
 224     return testbridge_test_only;
 225   }
 226   return kUniversalFilter;
 227 }
 228 
 229 GTEST_DEFINE_bool_(
 230     also_run_disabled_tests,
 231     internal::BoolFromGTestEnv("also_run_disabled_tests", false),
 232     "Run disabled tests too, in addition to the tests normally being run.");
 233 
 234 GTEST_DEFINE_bool_(
 235     break_on_failure,
 236     internal::BoolFromGTestEnv("break_on_failure", false),
 237     "True iff a failed assertion should be a debugger break-point.");
 238 
 239 GTEST_DEFINE_bool_(
 240     catch_exceptions,
 241     internal::BoolFromGTestEnv("catch_exceptions", true),
 242     "True iff " GTEST_NAME_
 243     " should catch exceptions and treat them as test failures.");
 244 
 245 GTEST_DEFINE_string_(
 246     color,
 247     internal::StringFromGTestEnv("color", "auto"),
 248     "Whether to use colors in the output.  Valid values: yes, no, "
 249     "and auto.  'auto' means to use colors if the output is "
 250     "being sent to a terminal and the TERM environment variable "
 251     "is set to a terminal type that supports colors.");
 252 
 253 GTEST_DEFINE_string_(
 254     filter,
 255     internal::StringFromGTestEnv("filter", GetDefaultFilter()),
 256     "A colon-separated list of glob (not regex) patterns "
 257     "for filtering the tests to run, optionally followed by a "
 258     "'-' and a : separated list of negative patterns (tests to "
 259     "exclude).  A test is run if it matches one of the positive "
 260     "patterns and does not match any of the negative patterns.");
 261 
 262 GTEST_DEFINE_bool_(
 263     install_failure_signal_handler,
 264     internal::BoolFromGTestEnv("install_failure_signal_handler", false),
 265     "If true and supported on the current platform, " GTEST_NAME_ " should "
 266     "install a signal handler that dumps debugging information when fatal "
 267     "signals are raised.");
 268 
 269 GTEST_DEFINE_bool_(list_tests, false,
 270                    "List all tests without running them.");
 271 
 272 // The net priority order after flag processing is thus:
 273 //   --gtest_output command line flag
 274 //   GTEST_OUTPUT environment variable
 275 //   XML_OUTPUT_FILE environment variable
 276 //   ''
 277 GTEST_DEFINE_string_(
 278     output,
 279     internal::StringFromGTestEnv("output",
 280       internal::OutputFlagAlsoCheckEnvVar().c_str()),
 281     "A format (defaults to \"xml\" but can be specified to be \"json\"), "
 282     "optionally followed by a colon and an output file name or directory. "
 283     "A directory is indicated by a trailing pathname separator. "
 284     "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
 285     "If a directory is specified, output files will be created "
 286     "within that directory, with file-names based on the test "
 287     "executable's name and, if necessary, made unique by adding "
 288     "digits.");
 289 
 290 GTEST_DEFINE_bool_(
 291     print_time,
 292     internal::BoolFromGTestEnv("print_time", true),
 293     "True iff " GTEST_NAME_
 294     " should display elapsed time in text output.");
 295 
 296 GTEST_DEFINE_bool_(
 297     print_utf8,
 298     internal::BoolFromGTestEnv("print_utf8", true),
 299     "True iff " GTEST_NAME_
 300     " prints UTF8 characters as text.");
 301 
 302 GTEST_DEFINE_int32_(
 303     random_seed,
 304     internal::Int32FromGTestEnv("random_seed", 0),
 305     "Random number seed to use when shuffling test orders.  Must be in range "
 306     "[1, 99999], or 0 to use a seed based on the current time.");
 307 
 308 GTEST_DEFINE_int32_(
 309     repeat,
 310     internal::Int32FromGTestEnv("repeat", 1),
 311     "How many times to repeat each test.  Specify a negative number "
 312     "for repeating forever.  Useful for shaking out flaky tests.");
 313 
 314 GTEST_DEFINE_bool_(
 315     show_internal_stack_frames, false,
 316     "True iff " GTEST_NAME_ " should include internal stack frames when "
 317     "printing test failure stack traces.");
 318 
 319 GTEST_DEFINE_bool_(
 320     shuffle,
 321     internal::BoolFromGTestEnv("shuffle", false),
 322     "True iff " GTEST_NAME_
 323     " should randomize tests' order on every run.");
 324 
 325 GTEST_DEFINE_int32_(
 326     stack_trace_depth,
 327     internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
 328     "The maximum number of stack frames to print when an "
 329     "assertion fails.  The valid range is 0 through 100, inclusive.");
 330 
 331 GTEST_DEFINE_string_(
 332     stream_result_to,
 333     internal::StringFromGTestEnv("stream_result_to", ""),
 334     "This flag specifies the host name and the port number on which to stream "
 335     "test results. Example: \"localhost:555\". The flag is effective only on "
 336     "Linux.");
 337 
 338 GTEST_DEFINE_bool_(
 339     throw_on_failure,
 340     internal::BoolFromGTestEnv("throw_on_failure", false),
 341     "When this flag is specified, a failed assertion will throw an exception "
 342     "if exceptions are enabled or exit the program with a non-zero code "
 343     "otherwise. For use with an external test framework.");
 344 
 345 #if GTEST_USE_OWN_FLAGFILE_FLAG_
 346 GTEST_DEFINE_string_(
 347     flagfile,
 348     internal::StringFromGTestEnv("flagfile", ""),
 349     "This flag specifies the flagfile to read command-line flags from.");
 350 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
 351 
 352 namespace internal {
 353 
 354 // Generates a random number from [0, range), using a Linear
 355 // Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
 356 // than kMaxRange.
 357 UInt32 Random::Generate(UInt32 range) {
 358   // These constants are the same as are used in glibc's rand(3).
 359   // Use wider types than necessary to prevent unsigned overflow diagnostics.
 360   state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange;
 361 
 362   GTEST_CHECK_(range > 0)
 363       << "Cannot generate a number in the range [0, 0).";
 364   GTEST_CHECK_(range <= kMaxRange)
 365       << "Generation of a number in [0, " << range << ") was requested, "
 366       << "but this can only generate numbers in [0, " << kMaxRange << ").";
 367 
 368   // Converting via modulus introduces a bit of downward bias, but
 369   // it's simple, and a linear congruential generator isn't too good
 370   // to begin with.
 371   return state_ % range;
 372 }
 373 
 374 // GTestIsInitialized() returns true iff the user has initialized
 375 // Google Test.  Useful for catching the user mistake of not initializing
 376 // Google Test before calling RUN_ALL_TESTS().
 377 static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
 378 
 379 // Iterates over a vector of TestCases, keeping a running sum of the
 380 // results of calling a given int-returning method on each.
 381 // Returns the sum.
 382 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
 383                                int (TestCase::*method)() const) {
 384   int sum = 0;
 385   for (size_t i = 0; i < case_list.size(); i++) {
 386     sum += (case_list[i]->*method)();
 387   }
 388   return sum;
 389 }
 390 
 391 // Returns true iff the test case passed.
 392 static bool TestCasePassed(const TestCase* test_case) {
 393   return test_case->should_run() && test_case->Passed();
 394 }
 395 
 396 // Returns true iff the test case failed.
 397 static bool TestCaseFailed(const TestCase* test_case) {
 398   return test_case->should_run() && test_case->Failed();
 399 }
 400 
 401 // Returns true iff test_case contains at least one test that should
 402 // run.
 403 static bool ShouldRunTestCase(const TestCase* test_case) {
 404   return test_case->should_run();
 405 }
 406 
 407 // AssertHelper constructor.
 408 AssertHelper::AssertHelper(TestPartResult::Type type,
 409                            const char* file,
 410                            int line,
 411                            const char* message)
 412     : data_(new AssertHelperData(type, file, line, message)) {
 413 }
 414 
 415 AssertHelper::~AssertHelper() {
 416   delete data_;
 417 }
 418 
 419 // Message assignment, for assertion streaming support.
 420 void AssertHelper::operator=(const Message& message) const {
 421   UnitTest::GetInstance()->
 422     AddTestPartResult(data_->type, data_->file, data_->line,
 423                       AppendUserMessage(data_->message, message),
 424                       UnitTest::GetInstance()->impl()
 425                       ->CurrentOsStackTraceExceptTop(1)
 426                       // Skips the stack frame for this function itself.
 427                       );  // NOLINT
 428 }
 429 
 430 // Mutex for linked pointers.
 431 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
 432 
 433 // A copy of all command line arguments.  Set by InitGoogleTest().
 434 static ::std::vector<std::string> g_argvs;
 435 
 436 ::std::vector<std::string> GetArgvs() {
 437 #if defined(GTEST_CUSTOM_GET_ARGVS_)
 438   // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
 439   // ::string. This code converts it to the appropriate type.
 440   const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
 441   return ::std::vector<std::string>(custom.begin(), custom.end());
 442 #else   // defined(GTEST_CUSTOM_GET_ARGVS_)
 443   return g_argvs;
 444 #endif  // defined(GTEST_CUSTOM_GET_ARGVS_)
 445 }
 446 
 447 // Returns the current application's name, removing directory path if that
 448 // is present.
 449 FilePath GetCurrentExecutableName() {
 450   FilePath result;
 451 
 452 #if GTEST_OS_WINDOWS
 453   result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
 454 #else
 455   result.Set(FilePath(GetArgvs()[0]));
 456 #endif  // GTEST_OS_WINDOWS
 457 
 458   return result.RemoveDirectoryName();
 459 }
 460 
 461 // Functions for processing the gtest_output flag.
 462 
 463 // Returns the output format, or "" for normal printed output.
 464 std::string UnitTestOptions::GetOutputFormat() {
 465   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
 466   const char* const colon = strchr(gtest_output_flag, ':');
 467   return (colon == NULL) ?
 468       std::string(gtest_output_flag) :
 469       std::string(gtest_output_flag, colon - gtest_output_flag);
 470 }
 471 
 472 // Returns the name of the requested output file, or the default if none
 473 // was explicitly specified.
 474 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
 475   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
 476 
 477   std::string format = GetOutputFormat();
 478   if (format.empty())
 479     format = std::string(kDefaultOutputFormat);
 480 
 481   const char* const colon = strchr(gtest_output_flag, ':');
 482   if (colon == NULL)
 483     return internal::FilePath::MakeFileName(
 484         internal::FilePath(
 485             UnitTest::GetInstance()->original_working_dir()),
 486         internal::FilePath(kDefaultOutputFile), 0,
 487         format.c_str()).string();
 488 
 489   internal::FilePath output_name(colon + 1);
 490   if (!output_name.IsAbsolutePath())
 491     // FIXME: on Windows \some\path is not an absolute
 492     // path (as its meaning depends on the current drive), yet the
 493     // following logic for turning it into an absolute path is wrong.
 494     // Fix it.
 495     output_name = internal::FilePath::ConcatPaths(
 496         internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
 497         internal::FilePath(colon + 1));
 498 
 499   if (!output_name.IsDirectory())
 500     return output_name.string();
 501 
 502   internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
 503       output_name, internal::GetCurrentExecutableName(),
 504       GetOutputFormat().c_str()));
 505   return result.string();
 506 }
 507 
 508 // Returns true iff the wildcard pattern matches the string.  The
 509 // first ':' or '\0' character in pattern marks the end of it.
 510 //
 511 // This recursive algorithm isn't very efficient, but is clear and
 512 // works well enough for matching test names, which are short.
 513 bool UnitTestOptions::PatternMatchesString(const char *pattern,
 514                                            const char *str) {
 515   switch (*pattern) {
 516     case '\0':
 517     case ':':  // Either ':' or '\0' marks the end of the pattern.
 518       return *str == '\0';
 519     case '?':  // Matches any single character.
 520       return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
 521     case '*':  // Matches any string (possibly empty) of characters.
 522       return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
 523           PatternMatchesString(pattern + 1, str);
 524     default:  // Non-special character.  Matches itself.
 525       return *pattern == *str &&
 526           PatternMatchesString(pattern + 1, str + 1);
 527   }
 528 }
 529 
 530 bool UnitTestOptions::MatchesFilter(
 531     const std::string& name, const char* filter) {
 532   const char *cur_pattern = filter;
 533   for (;;) {
 534     if (PatternMatchesString(cur_pattern, name.c_str())) {
 535       return true;
 536     }
 537 
 538     // Finds the next pattern in the filter.
 539     cur_pattern = strchr(cur_pattern, ':');
 540 
 541     // Returns if no more pattern can be found.
 542     if (cur_pattern == NULL) {
 543       return false;
 544     }
 545 
 546     // Skips the pattern separater (the ':' character).
 547     cur_pattern++;
 548   }
 549 }
 550 
 551 // Returns true iff the user-specified filter matches the test case
 552 // name and the test name.
 553 bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
 554                                         const std::string &test_name) {
 555   const std::string& full_name = test_case_name + "." + test_name.c_str();
 556 
 557   // Split --gtest_filter at '-', if there is one, to separate into
 558   // positive filter and negative filter portions
 559   const char* const p = GTEST_FLAG(filter).c_str();
 560   const char* const dash = strchr(p, '-');
 561   std::string positive;
 562   std::string negative;
 563   if (dash == NULL) {
 564     positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
 565     negative = "";
 566   } else {
 567     positive = std::string(p, dash);   // Everything up to the dash
 568     negative = std::string(dash + 1);  // Everything after the dash
 569     if (positive.empty()) {
 570       // Treat '-test1' as the same as '*-test1'
 571       positive = kUniversalFilter;
 572     }
 573   }
 574 
 575   // A filter is a colon-separated list of patterns.  It matches a
 576   // test if any pattern in it matches the test.
 577   return (MatchesFilter(full_name, positive.c_str()) &&
 578           !MatchesFilter(full_name, negative.c_str()));
 579 }
 580 
 581 #if GTEST_HAS_SEH
 582 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
 583 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
 584 // This function is useful as an __except condition.
 585 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
 586   // Google Test should handle a SEH exception if:
 587   //   1. the user wants it to, AND
 588   //   2. this is not a breakpoint exception, AND
 589   //   3. this is not a C++ exception (VC++ implements them via SEH,
 590   //      apparently).
 591   //
 592   // SEH exception code for C++ exceptions.
 593   // (see http://support.microsoft.com/kb/185294 for more information).
 594   const DWORD kCxxExceptionCode = 0xe06d7363;
 595 
 596   bool should_handle = true;
 597 
 598   if (!GTEST_FLAG(catch_exceptions))
 599     should_handle = false;
 600   else if (exception_code == EXCEPTION_BREAKPOINT)
 601     should_handle = false;
 602   else if (exception_code == kCxxExceptionCode)
 603     should_handle = false;
 604 
 605   return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
 606 }
 607 #endif  // GTEST_HAS_SEH
 608 
 609 }  // namespace internal
 610 
 611 // The c'tor sets this object as the test part result reporter used by
 612 // Google Test.  The 'result' parameter specifies where to report the
 613 // results. Intercepts only failures from the current thread.
 614 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
 615     TestPartResultArray* result)
 616     : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
 617       result_(result) {
 618   Init();
 619 }
 620 
 621 // The c'tor sets this object as the test part result reporter used by
 622 // Google Test.  The 'result' parameter specifies where to report the
 623 // results.
 624 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
 625     InterceptMode intercept_mode, TestPartResultArray* result)
 626     : intercept_mode_(intercept_mode),
 627       result_(result) {
 628   Init();
 629 }
 630 
 631 void ScopedFakeTestPartResultReporter::Init() {
 632   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
 633   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
 634     old_reporter_ = impl->GetGlobalTestPartResultReporter();
 635     impl->SetGlobalTestPartResultReporter(this);
 636   } else {
 637     old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
 638     impl->SetTestPartResultReporterForCurrentThread(this);
 639   }
 640 }
 641 
 642 // The d'tor restores the test part result reporter used by Google Test
 643 // before.
 644 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
 645   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
 646   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
 647     impl->SetGlobalTestPartResultReporter(old_reporter_);
 648   } else {
 649     impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
 650   }
 651 }
 652 
 653 // Increments the test part result count and remembers the result.
 654 // This method is from the TestPartResultReporterInterface interface.
 655 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
 656     const TestPartResult& result) {
 657   result_->Append(result);
 658 }
 659 
 660 namespace internal {
 661 
 662 // Returns the type ID of ::testing::Test.  We should always call this
 663 // instead of GetTypeId< ::testing::Test>() to get the type ID of
 664 // testing::Test.  This is to work around a suspected linker bug when
 665 // using Google Test as a framework on Mac OS X.  The bug causes
 666 // GetTypeId< ::testing::Test>() to return different values depending
 667 // on whether the call is from the Google Test framework itself or
 668 // from user test code.  GetTestTypeId() is guaranteed to always
 669 // return the same value, as it always calls GetTypeId<>() from the
 670 // gtest.cc, which is within the Google Test framework.
 671 TypeId GetTestTypeId() {
 672   return GetTypeId<Test>();
 673 }
 674 
 675 // The value of GetTestTypeId() as seen from within the Google Test
 676 // library.  This is solely for testing GetTestTypeId().
 677 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
 678 
 679 // This predicate-formatter checks that 'results' contains a test part
 680 // failure of the given type and that the failure message contains the
 681 // given substring.
 682 static AssertionResult HasOneFailure(const char* /* results_expr */,
 683                                      const char* /* type_expr */,
 684                                      const char* /* substr_expr */,
 685                                      const TestPartResultArray& results,
 686                                      TestPartResult::Type type,
 687                                      const std::string& substr) {
 688   const std::string expected(type == TestPartResult::kFatalFailure ?
 689                         "1 fatal failure" :
 690                         "1 non-fatal failure");
 691   Message msg;
 692   if (results.size() != 1) {
 693     msg << "Expected: " << expected << "\n"
 694         << "  Actual: " << results.size() << " failures";
 695     for (int i = 0; i < results.size(); i++) {
 696       msg << "\n" << results.GetTestPartResult(i);
 697     }
 698     return AssertionFailure() << msg;
 699   }
 700 
 701   const TestPartResult& r = results.GetTestPartResult(0);
 702   if (r.type() != type) {
 703     return AssertionFailure() << "Expected: " << expected << "\n"
 704                               << "  Actual:\n"
 705                               << r;
 706   }
 707 
 708   if (strstr(r.message(), substr.c_str()) == NULL) {
 709     return AssertionFailure() << "Expected: " << expected << " containing \""
 710                               << substr << "\"\n"
 711                               << "  Actual:\n"
 712                               << r;
 713   }
 714 
 715   return AssertionSuccess();
 716 }
 717 
 718 // The constructor of SingleFailureChecker remembers where to look up
 719 // test part results, what type of failure we expect, and what
 720 // substring the failure message should contain.
 721 SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
 722                                            TestPartResult::Type type,
 723                                            const std::string& substr)
 724     : results_(results), type_(type), substr_(substr) {}
 725 
 726 // The destructor of SingleFailureChecker verifies that the given
 727 // TestPartResultArray contains exactly one failure that has the given
 728 // type and contains the given substring.  If that's not the case, a
 729 // non-fatal failure will be generated.
 730 SingleFailureChecker::~SingleFailureChecker() {
 731   EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
 732 }
 733 
 734 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
 735     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
 736 
 737 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
 738     const TestPartResult& result) {
 739   unit_test_->current_test_result()->AddTestPartResult(result);
 740   unit_test_->listeners()->repeater()->OnTestPartResult(result);
 741 }
 742 
 743 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
 744     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
 745 
 746 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
 747     const TestPartResult& result) {
 748   unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
 749 }
 750 
 751 // Returns the global test part result reporter.
 752 TestPartResultReporterInterface*
 753 UnitTestImpl::GetGlobalTestPartResultReporter() {
 754   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
 755   return global_test_part_result_repoter_;
 756 }
 757 
 758 // Sets the global test part result reporter.
 759 void UnitTestImpl::SetGlobalTestPartResultReporter(
 760     TestPartResultReporterInterface* reporter) {
 761   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
 762   global_test_part_result_repoter_ = reporter;
 763 }
 764 
 765 // Returns the test part result reporter for the current thread.
 766 TestPartResultReporterInterface*
 767 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
 768   return per_thread_test_part_result_reporter_.get();
 769 }
 770 
 771 // Sets the test part result reporter for the current thread.
 772 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
 773     TestPartResultReporterInterface* reporter) {
 774   per_thread_test_part_result_reporter_.set(reporter);
 775 }
 776 
 777 // Gets the number of successful test cases.
 778 int UnitTestImpl::successful_test_case_count() const {
 779   return CountIf(test_cases_, TestCasePassed);
 780 }
 781 
 782 // Gets the number of failed test cases.
 783 int UnitTestImpl::failed_test_case_count() const {
 784   return CountIf(test_cases_, TestCaseFailed);
 785 }
 786 
 787 // Gets the number of all test cases.
 788 int UnitTestImpl::total_test_case_count() const {
 789   return static_cast<int>(test_cases_.size());
 790 }
 791 
 792 // Gets the number of all test cases that contain at least one test
 793 // that should run.
 794 int UnitTestImpl::test_case_to_run_count() const {
 795   return CountIf(test_cases_, ShouldRunTestCase);
 796 }
 797 
 798 // Gets the number of successful tests.
 799 int UnitTestImpl::successful_test_count() const {
 800   return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
 801 }
 802 
 803 // Gets the number of failed tests.
 804 int UnitTestImpl::failed_test_count() const {
 805   return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
 806 }
 807 
 808 // Gets the number of disabled tests that will be reported in the XML report.
 809 int UnitTestImpl::reportable_disabled_test_count() const {
 810   return SumOverTestCaseList(test_cases_,
 811                              &TestCase::reportable_disabled_test_count);
 812 }
 813 
 814 // Gets the number of disabled tests.
 815 int UnitTestImpl::disabled_test_count() const {
 816   return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
 817 }
 818 
 819 // Gets the number of tests to be printed in the XML report.
 820 int UnitTestImpl::reportable_test_count() const {
 821   return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
 822 }
 823 
 824 // Gets the number of all tests.
 825 int UnitTestImpl::total_test_count() const {
 826   return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
 827 }
 828 
 829 // Gets the number of tests that should run.
 830 int UnitTestImpl::test_to_run_count() const {
 831   return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
 832 }
 833 
 834 // Returns the current OS stack trace as an std::string.
 835 //
 836 // The maximum number of stack frames to be included is specified by
 837 // the gtest_stack_trace_depth flag.  The skip_count parameter
 838 // specifies the number of top frames to be skipped, which doesn't
 839 // count against the number of frames to be included.
 840 //
 841 // For example, if Foo() calls Bar(), which in turn calls
 842 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
 843 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
 844 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
 845   return os_stack_trace_getter()->CurrentStackTrace(
 846       static_cast<int>(GTEST_FLAG(stack_trace_depth)),
 847       skip_count + 1
 848       // Skips the user-specified number of frames plus this function
 849       // itself.
 850       );  // NOLINT
 851 }
 852 
 853 // Returns the current time in milliseconds.
 854 TimeInMillis GetTimeInMillis() {
 855 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
 856   // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
 857   // http://analogous.blogspot.com/2005/04/epoch.html
 858   const TimeInMillis kJavaEpochToWinFileTimeDelta =
 859     static_cast<TimeInMillis>(116444736UL) * 100000UL;
 860   const DWORD kTenthMicrosInMilliSecond = 10000;
 861 
 862   SYSTEMTIME now_systime;
 863   FILETIME now_filetime;
 864   ULARGE_INTEGER now_int64;
 865   // FIXME: Shouldn't this just use
 866   //   GetSystemTimeAsFileTime()?
 867   GetSystemTime(&now_systime);
 868   if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
 869     now_int64.LowPart = now_filetime.dwLowDateTime;
 870     now_int64.HighPart = now_filetime.dwHighDateTime;
 871     now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
 872       kJavaEpochToWinFileTimeDelta;
 873     return now_int64.QuadPart;
 874   }
 875   return 0;
 876 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
 877   __timeb64 now;
 878 
 879   // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
 880   // (deprecated function) there.
 881   // FIXME: Use GetTickCount()?  Or use
 882   //   SystemTimeToFileTime()
 883   GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
 884   _ftime64(&now);
 885   GTEST_DISABLE_MSC_DEPRECATED_POP_()
 886 
 887   return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
 888 #elif GTEST_HAS_GETTIMEOFDAY_
 889   struct timeval now;
 890   gettimeofday(&now, NULL);
 891   return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
 892 #else
 893 # error "Don't know how to get the current time on your system."
 894 #endif
 895 }
 896 
 897 // Utilities
 898 
 899 // class String.
 900 
 901 #if GTEST_OS_WINDOWS_MOBILE
 902 // Creates a UTF-16 wide string from the given ANSI string, allocating
 903 // memory using new. The caller is responsible for deleting the return
 904 // value using delete[]. Returns the wide string, or NULL if the
 905 // input is NULL.
 906 LPCWSTR String::AnsiToUtf16(const char* ansi) {
 907   if (!ansi) return NULL;
 908   const int length = strlen(ansi);
 909   const int unicode_length =
 910       MultiByteToWideChar(CP_ACP, 0, ansi, length,
 911                           NULL, 0);
 912   WCHAR* unicode = new WCHAR[unicode_length + 1];
 913   MultiByteToWideChar(CP_ACP, 0, ansi, length,
 914                       unicode, unicode_length);
 915   unicode[unicode_length] = 0;
 916   return unicode;
 917 }
 918 
 919 // Creates an ANSI string from the given wide string, allocating
 920 // memory using new. The caller is responsible for deleting the return
 921 // value using delete[]. Returns the ANSI string, or NULL if the
 922 // input is NULL.
 923 const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
 924   if (!utf16_str) return NULL;
 925   const int ansi_length =
 926       WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
 927                           NULL, 0, NULL, NULL);
 928   char* ansi = new char[ansi_length + 1];
 929   WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
 930                       ansi, ansi_length, NULL, NULL);
 931   ansi[ansi_length] = 0;
 932   return ansi;
 933 }
 934 
 935 #endif  // GTEST_OS_WINDOWS_MOBILE
 936 
 937 // Compares two C strings.  Returns true iff they have the same content.
 938 //
 939 // Unlike strcmp(), this function can handle NULL argument(s).  A NULL
 940 // C string is considered different to any non-NULL C string,
 941 // including the empty string.
 942 bool String::CStringEquals(const char * lhs, const char * rhs) {
 943   if ( lhs == NULL ) return rhs == NULL;
 944 
 945   if ( rhs == NULL ) return false;
 946 
 947   return strcmp(lhs, rhs) == 0;
 948 }
 949 
 950 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
 951 
 952 // Converts an array of wide chars to a narrow string using the UTF-8
 953 // encoding, and streams the result to the given Message object.
 954 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
 955                                      Message* msg) {
 956   for (size_t i = 0; i != length; ) {  // NOLINT
 957     if (wstr[i] != L'\0') {
 958       *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
 959       while (i != length && wstr[i] != L'\0')
 960         i++;
 961     } else {
 962       *msg << '\0';
 963       i++;
 964     }
 965   }
 966 }
 967 
 968 #endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
 969 
 970 void SplitString(const ::std::string& str, char delimiter,
 971                  ::std::vector< ::std::string>* dest) {
 972   ::std::vector< ::std::string> parsed;
 973   ::std::string::size_type pos = 0;
 974   while (::testing::internal::AlwaysTrue()) {
 975     const ::std::string::size_type colon = str.find(delimiter, pos);
 976     if (colon == ::std::string::npos) {
 977       parsed.push_back(str.substr(pos));
 978       break;
 979     } else {
 980       parsed.push_back(str.substr(pos, colon - pos));
 981       pos = colon + 1;
 982     }
 983   }
 984   dest->swap(parsed);
 985 }
 986 
 987 }  // namespace internal
 988 
 989 // Constructs an empty Message.
 990 // We allocate the stringstream separately because otherwise each use of
 991 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
 992 // stack frame leading to huge stack frames in some cases; gcc does not reuse
 993 // the stack space.
 994 Message::Message() : ss_(new ::std::stringstream) {
 995   // By default, we want there to be enough precision when printing
 996   // a double to a Message.
 997   *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
 998 }
 999 
1000 // These two overloads allow streaming a wide C string to a Message
1001 // using the UTF-8 encoding.
1002 Message& Message::operator <<(const wchar_t* wide_c_str) {
1003   return *this << internal::String::ShowWideCString(wide_c_str);
1004 }
1005 Message& Message::operator <<(wchar_t* wide_c_str) {
1006   return *this << internal::String::ShowWideCString(wide_c_str);
1007 }
1008 
1009 #if GTEST_HAS_STD_WSTRING
1010 // Converts the given wide string to a narrow string using the UTF-8
1011 // encoding, and streams the result to this Message object.
1012 Message& Message::operator <<(const ::std::wstring& wstr) {
1013   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
1014   return *this;
1015 }
1016 #endif  // GTEST_HAS_STD_WSTRING
1017 
1018 #if GTEST_HAS_GLOBAL_WSTRING
1019 // Converts the given wide string to a narrow string using the UTF-8
1020 // encoding, and streams the result to this Message object.
1021 Message& Message::operator <<(const ::wstring& wstr) {
1022   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
1023   return *this;
1024 }
1025 #endif  // GTEST_HAS_GLOBAL_WSTRING
1026 
1027 // Gets the text streamed to this object so far as an std::string.
1028 // Each '\0' character in the buffer is replaced with "\\0".
1029 std::string Message::GetString() const {
1030   return internal::StringStreamToString(ss_.get());
1031 }
1032 
1033 // AssertionResult constructors.
1034 // Used in EXPECT_TRUE/FALSE(assertion_result).
1035 AssertionResult::AssertionResult(const AssertionResult& other)
1036     : success_(other.success_),
1037       message_(other.message_.get() != NULL ?
1038                new ::std::string(*other.message_) :
1039                static_cast< ::std::string*>(NULL)) {
1040 }
1041 
1042 // Swaps two AssertionResults.
1043 void AssertionResult::swap(AssertionResult& other) {
1044   using std::swap;
1045   swap(success_, other.success_);
1046   swap(message_, other.message_);
1047 }
1048 
1049 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
1050 AssertionResult AssertionResult::operator!() const {
1051   AssertionResult negation(!success_);
1052   if (message_.get() != NULL)
1053     negation << *message_;
1054   return negation;
1055 }
1056 
1057 // Makes a successful assertion result.
1058 AssertionResult AssertionSuccess() {
1059   return AssertionResult(true);
1060 }
1061 
1062 // Makes a failed assertion result.
1063 AssertionResult AssertionFailure() {
1064   return AssertionResult(false);
1065 }
1066 
1067 // Makes a failed assertion result with the given failure message.
1068 // Deprecated; use AssertionFailure() << message.
1069 AssertionResult AssertionFailure(const Message& message) {
1070   return AssertionFailure() << message;
1071 }
1072 
1073 namespace internal {
1074 
1075 namespace edit_distance {
1076 std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
1077                                             const std::vector<size_t>& right) {
1078   std::vector<std::vector<double> > costs(
1079       left.size() + 1, std::vector<double>(right.size() + 1));
1080   std::vector<std::vector<EditType> > best_move(
1081       left.size() + 1, std::vector<EditType>(right.size() + 1));
1082 
1083   // Populate for empty right.
1084   for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
1085     costs[l_i][0] = static_cast<double>(l_i);
1086     best_move[l_i][0] = kRemove;
1087   }
1088   // Populate for empty left.
1089   for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
1090     costs[0][r_i] = static_cast<double>(r_i);
1091     best_move[0][r_i] = kAdd;
1092   }
1093 
1094   for (size_t l_i = 0; l_i < left.size(); ++l_i) {
1095     for (size_t r_i = 0; r_i < right.size(); ++r_i) {
1096       if (left[l_i] == right[r_i]) {
1097         // Found a match. Consume it.
1098         costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
1099         best_move[l_i + 1][r_i + 1] = kMatch;
1100         continue;
1101       }
1102 
1103       const double add = costs[l_i + 1][r_i];
1104       const double remove = costs[l_i][r_i + 1];
1105       const double replace = costs[l_i][r_i];
1106       if (add < remove && add < replace) {
1107         costs[l_i + 1][r_i + 1] = add + 1;
1108         best_move[l_i + 1][r_i + 1] = kAdd;
1109       } else if (remove < add && remove < replace) {
1110         costs[l_i + 1][r_i + 1] = remove + 1;
1111         best_move[l_i + 1][r_i + 1] = kRemove;
1112       } else {
1113         // We make replace a little more expensive than add/remove to lower
1114         // their priority.
1115         costs[l_i + 1][r_i + 1] = replace + 1.00001;
1116         best_move[l_i + 1][r_i + 1] = kReplace;
1117       }
1118     }
1119   }
1120 
1121   // Reconstruct the best path. We do it in reverse order.
1122   std::vector<EditType> best_path;
1123   for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
1124     EditType move = best_move[l_i][r_i];
1125     best_path.push_back(move);
1126     l_i -= move != kAdd;
1127     r_i -= move != kRemove;
1128   }
1129   std::reverse(best_path.begin(), best_path.end());
1130   return best_path;
1131 }
1132 
1133 namespace {
1134 
1135 // Helper class to convert string into ids with deduplication.
1136 class InternalStrings {
1137  public:
1138   size_t GetId(const std::string& str) {
1139     IdMap::iterator it = ids_.find(str);
1140     if (it != ids_.end()) return it->second;
1141     size_t id = ids_.size();
1142     return ids_[str] = id;
1143   }
1144 
1145  private:
1146   typedef std::map<std::string, size_t> IdMap;
1147   IdMap ids_;
1148 };
1149 
1150 }  // namespace
1151 
1152 std::vector<EditType> CalculateOptimalEdits(
1153     const std::vector<std::string>& left,
1154     const std::vector<std::string>& right) {
1155   std::vector<size_t> left_ids, right_ids;
1156   {
1157     InternalStrings intern_table;
1158     for (size_t i = 0; i < left.size(); ++i) {
1159       left_ids.push_back(intern_table.GetId(left[i]));
1160     }
1161     for (size_t i = 0; i < right.size(); ++i) {
1162       right_ids.push_back(intern_table.GetId(right[i]));
1163     }
1164   }
1165   return CalculateOptimalEdits(left_ids, right_ids);
1166 }
1167 
1168 namespace {
1169 
1170 // Helper class that holds the state for one hunk and prints it out to the
1171 // stream.
1172 // It reorders adds/removes when possible to group all removes before all
1173 // adds. It also adds the hunk header before printint into the stream.
1174 class Hunk {
1175  public:
1176   Hunk(size_t left_start, size_t right_start)
1177       : left_start_(left_start),
1178         right_start_(right_start),
1179         adds_(),
1180         removes_(),
1181         common_() {}
1182 
1183   void PushLine(char edit, const char* line) {
1184     switch (edit) {
1185       case ' ':
1186         ++common_;
1187         FlushEdits();
1188         hunk_.push_back(std::make_pair(' ', line));
1189         break;
1190       case '-':
1191         ++removes_;
1192         hunk_removes_.push_back(std::make_pair('-', line));
1193         break;
1194       case '+':
1195         ++adds_;
1196         hunk_adds_.push_back(std::make_pair('+', line));
1197         break;
1198     }
1199   }
1200 
1201   void PrintTo(std::ostream* os) {
1202     PrintHeader(os);
1203     FlushEdits();
1204     for (std::list<std::pair<char, const char*> >::const_iterator it =
1205              hunk_.begin();
1206          it != hunk_.end(); ++it) {
1207       *os << it->first << it->second << "\n";
1208     }
1209   }
1210 
1211   bool has_edits() const { return adds_ || removes_; }
1212 
1213  private:
1214   void FlushEdits() {
1215     hunk_.splice(hunk_.end(), hunk_removes_);
1216     hunk_.splice(hunk_.end(), hunk_adds_);
1217   }
1218 
1219   // Print a unified diff header for one hunk.
1220   // The format is
1221   //   "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
1222   // where the left/right parts are omitted if unnecessary.
1223   void PrintHeader(std::ostream* ss) const {
1224     *ss << "@@ ";
1225     if (removes_) {
1226       *ss << "-" << left_start_ << "," << (removes_ + common_);
1227     }
1228     if (removes_ && adds_) {
1229       *ss << " ";
1230     }
1231     if (adds_) {
1232       *ss << "+" << right_start_ << "," << (adds_ + common_);
1233     }
1234     *ss << " @@\n";
1235   }
1236 
1237   size_t left_start_, right_start_;
1238   size_t adds_, removes_, common_;
1239   std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
1240 };
1241 
1242 }  // namespace
1243 
1244 // Create a list of diff hunks in Unified diff format.
1245 // Each hunk has a header generated by PrintHeader above plus a body with
1246 // lines prefixed with ' ' for no change, '-' for deletion and '+' for
1247 // addition.
1248 // 'context' represents the desired unchanged prefix/suffix around the diff.
1249 // If two hunks are close enough that their contexts overlap, then they are
1250 // joined into one hunk.
1251 std::string CreateUnifiedDiff(const std::vector<std::string>& left,
1252                               const std::vector<std::string>& right,
1253                               size_t context) {
1254   const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
1255 
1256   size_t l_i = 0, r_i = 0, edit_i = 0;
1257   std::stringstream ss;
1258   while (edit_i < edits.size()) {
1259     // Find first edit.
1260     while (edit_i < edits.size() && edits[edit_i] == kMatch) {
1261       ++l_i;
1262       ++r_i;
1263       ++edit_i;
1264     }
1265 
1266     // Find the first line to include in the hunk.
1267     const size_t prefix_context = std::min(l_i, context);
1268     Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
1269     for (size_t i = prefix_context; i > 0; --i) {
1270       hunk.PushLine(' ', left[l_i - i].c_str());
1271     }
1272 
1273     // Iterate the edits until we found enough suffix for the hunk or the input
1274     // is over.
1275     size_t n_suffix = 0;
1276     for (; edit_i < edits.size(); ++edit_i) {
1277       if (n_suffix >= context) {
1278         // Continue only if the next hunk is very close.
1279         std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
1280         while (it != edits.end() && *it == kMatch) ++it;
1281         if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
1282           // There is no next edit or it is too far away.
1283           break;
1284         }
1285       }
1286 
1287       EditType edit = edits[edit_i];
1288       // Reset count when a non match is found.
1289       n_suffix = edit == kMatch ? n_suffix + 1 : 0;
1290 
1291       if (edit == kMatch || edit == kRemove || edit == kReplace) {
1292         hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
1293       }
1294       if (edit == kAdd || edit == kReplace) {
1295         hunk.PushLine('+', right[r_i].c_str());
1296       }
1297 
1298       // Advance indices, depending on edit type.
1299       l_i += edit != kAdd;
1300       r_i += edit != kRemove;
1301     }
1302 
1303     if (!hunk.has_edits()) {
1304       // We are done. We don't want this hunk.
1305       break;
1306     }
1307 
1308     hunk.PrintTo(&ss);
1309   }
1310   return ss.str();
1311 }
1312 
1313 }  // namespace edit_distance
1314 
1315 namespace {
1316 
1317 // The string representation of the values received in EqFailure() are already
1318 // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
1319 // characters the same.
1320 std::vector<std::string> SplitEscapedString(const std::string& str) {
1321   std::vector<std::string> lines;
1322   size_t start = 0, end = str.size();
1323   if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
1324     ++start;
1325     --end;
1326   }
1327   bool escaped = false;
1328   for (size_t i = start; i + 1 < end; ++i) {
1329     if (escaped) {
1330       escaped = false;
1331       if (str[i] == 'n') {
1332         lines.push_back(str.substr(start, i - start - 1));
1333         start = i + 1;
1334       }
1335     } else {
1336       escaped = str[i] == '\\';
1337     }
1338   }
1339   lines.push_back(str.substr(start, end - start));
1340   return lines;
1341 }
1342 
1343 }  // namespace
1344 
1345 // Constructs and returns the message for an equality assertion
1346 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
1347 //
1348 // The first four parameters are the expressions used in the assertion
1349 // and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
1350 // where foo is 5 and bar is 6, we have:
1351 //
1352 //   lhs_expression: "foo"
1353 //   rhs_expression: "bar"
1354 //   lhs_value:      "5"
1355 //   rhs_value:      "6"
1356 //
1357 // The ignoring_case parameter is true iff the assertion is a
1358 // *_STRCASEEQ*.  When it's true, the string "Ignoring case" will
1359 // be inserted into the message.
1360 AssertionResult EqFailure(const char* lhs_expression,
1361                           const char* rhs_expression,
1362                           const std::string& lhs_value,
1363                           const std::string& rhs_value,
1364                           bool ignoring_case) {
1365   Message msg;
1366   msg << "Expected equality of these values:";
1367   msg << "\n  " << lhs_expression;
1368   if (lhs_value != lhs_expression) {
1369     msg << "\n    Which is: " << lhs_value;
1370   }
1371   msg << "\n  " << rhs_expression;
1372   if (rhs_value != rhs_expression) {
1373     msg << "\n    Which is: " << rhs_value;
1374   }
1375 
1376   if (ignoring_case) {
1377     msg << "\nIgnoring case";
1378   }
1379 
1380   if (!lhs_value.empty() && !rhs_value.empty()) {
1381     const std::vector<std::string> lhs_lines =
1382         SplitEscapedString(lhs_value);
1383     const std::vector<std::string> rhs_lines =
1384         SplitEscapedString(rhs_value);
1385     if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
1386       msg << "\nWith diff:\n"
1387           << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
1388     }
1389   }
1390 
1391   return AssertionFailure() << msg;
1392 }
1393 
1394 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1395 std::string GetBoolAssertionFailureMessage(
1396     const AssertionResult& assertion_result,
1397     const char* expression_text,
1398     const char* actual_predicate_value,
1399     const char* expected_predicate_value) {
1400   const char* actual_message = assertion_result.message();
1401   Message msg;
1402   msg << "Value of: " << expression_text
1403       << "\n  Actual: " << actual_predicate_value;
1404   if (actual_message[0] != '\0')
1405     msg << " (" << actual_message << ")";
1406   msg << "\nExpected: " << expected_predicate_value;
1407   return msg.GetString();
1408 }
1409 
1410 // Helper function for implementing ASSERT_NEAR.
1411 AssertionResult DoubleNearPredFormat(const char* expr1,
1412                                      const char* expr2,
1413                                      const char* abs_error_expr,
1414                                      double val1,
1415                                      double val2,
1416                                      double abs_error) {
1417   const double diff = fabs(val1 - val2);
1418   if (diff <= abs_error) return AssertionSuccess();
1419 
1420   // FIXME: do not print the value of an expression if it's
1421   // already a literal.
1422   return AssertionFailure()
1423       << "The difference between " << expr1 << " and " << expr2
1424       << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1425       << expr1 << " evaluates to " << val1 << ",\n"
1426       << expr2 << " evaluates to " << val2 << ", and\n"
1427       << abs_error_expr << " evaluates to " << abs_error << ".";
1428 }
1429 
1430 
1431 // Helper template for implementing FloatLE() and DoubleLE().
1432 template <typename RawType>
1433 AssertionResult FloatingPointLE(const char* expr1,
1434                                 const char* expr2,
1435                                 RawType val1,
1436                                 RawType val2) {
1437   // Returns success if val1 is less than val2,
1438   if (val1 < val2) {
1439     return AssertionSuccess();
1440   }
1441 
1442   // or if val1 is almost equal to val2.
1443   const FloatingPoint<RawType> lhs(val1), rhs(val2);
1444   if (lhs.AlmostEquals(rhs)) {
1445     return AssertionSuccess();
1446   }
1447 
1448   // Note that the above two checks will both fail if either val1 or
1449   // val2 is NaN, as the IEEE floating-point standard requires that
1450   // any predicate involving a NaN must return false.
1451 
1452   ::std::stringstream val1_ss;
1453   val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1454           << val1;
1455 
1456   ::std::stringstream val2_ss;
1457   val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1458           << val2;
1459 
1460   return AssertionFailure()
1461       << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1462       << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
1463       << StringStreamToString(&val2_ss);
1464 }
1465 
1466 }  // namespace internal
1467 
1468 // Asserts that val1 is less than, or almost equal to, val2.  Fails
1469 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
1470 AssertionResult FloatLE(const char* expr1, const char* expr2,
1471                         float val1, float val2) {
1472   return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1473 }
1474 
1475 // Asserts that val1 is less than, or almost equal to, val2.  Fails
1476 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
1477 AssertionResult DoubleLE(const char* expr1, const char* expr2,
1478                          double val1, double val2) {
1479   return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1480 }
1481 
1482 namespace internal {
1483 
1484 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
1485 // arguments.
1486 AssertionResult CmpHelperEQ(const char* lhs_expression,
1487                             const char* rhs_expression,
1488                             BiggestInt lhs,
1489                             BiggestInt rhs) {
1490   if (lhs == rhs) {
1491     return AssertionSuccess();
1492   }
1493 
1494   return EqFailure(lhs_expression,
1495                    rhs_expression,
1496                    FormatForComparisonFailureMessage(lhs, rhs),
1497                    FormatForComparisonFailureMessage(rhs, lhs),
1498                    false);
1499 }
1500 
1501 // A macro for implementing the helper functions needed to implement
1502 // ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
1503 // just to avoid copy-and-paste of similar code.
1504 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1505 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1506                                    BiggestInt val1, BiggestInt val2) {\
1507   if (val1 op val2) {\
1508     return AssertionSuccess();\
1509   } else {\
1510     return AssertionFailure() \
1511         << "Expected: (" << expr1 << ") " #op " (" << expr2\
1512         << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1513         << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1514   }\
1515 }
1516 
1517 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
1518 // enum arguments.
1519 GTEST_IMPL_CMP_HELPER_(NE, !=)
1520 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
1521 // enum arguments.
1522 GTEST_IMPL_CMP_HELPER_(LE, <=)
1523 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
1524 // enum arguments.
1525 GTEST_IMPL_CMP_HELPER_(LT, < )
1526 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
1527 // enum arguments.
1528 GTEST_IMPL_CMP_HELPER_(GE, >=)
1529 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
1530 // enum arguments.
1531 GTEST_IMPL_CMP_HELPER_(GT, > )
1532 
1533 #undef GTEST_IMPL_CMP_HELPER_
1534 
1535 // The helper function for {ASSERT|EXPECT}_STREQ.
1536 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
1537                                const char* rhs_expression,
1538                                const char* lhs,
1539                                const char* rhs) {
1540   if (String::CStringEquals(lhs, rhs)) {
1541     return AssertionSuccess();
1542   }
1543 
1544   return EqFailure(lhs_expression,
1545                    rhs_expression,
1546                    PrintToString(lhs),
1547                    PrintToString(rhs),
1548                    false);
1549 }
1550 
1551 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1552 AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
1553                                    const char* rhs_expression,
1554                                    const char* lhs,
1555                                    const char* rhs) {
1556   if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
1557     return AssertionSuccess();
1558   }
1559 
1560   return EqFailure(lhs_expression,
1561                    rhs_expression,
1562                    PrintToString(lhs),
1563                    PrintToString(rhs),
1564                    true);
1565 }
1566 
1567 // The helper function for {ASSERT|EXPECT}_STRNE.
1568 AssertionResult CmpHelperSTRNE(const char* s1_expression,
1569                                const char* s2_expression,
1570                                const char* s1,
1571                                const char* s2) {
1572   if (!String::CStringEquals(s1, s2)) {
1573     return AssertionSuccess();
1574   } else {
1575     return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
1576                               << s2_expression << "), actual: \""
1577                               << s1 << "\" vs \"" << s2 << "\"";
1578   }
1579 }
1580 
1581 // The helper function for {ASSERT|EXPECT}_STRCASENE.
1582 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1583                                    const char* s2_expression,
1584                                    const char* s1,
1585                                    const char* s2) {
1586   if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1587     return AssertionSuccess();
1588   } else {
1589     return AssertionFailure()
1590         << "Expected: (" << s1_expression << ") != ("
1591         << s2_expression << ") (ignoring case), actual: \""
1592         << s1 << "\" vs \"" << s2 << "\"";
1593   }
1594 }
1595 
1596 }  // namespace internal
1597 
1598 namespace {
1599 
1600 // Helper functions for implementing IsSubString() and IsNotSubstring().
1601 
1602 // This group of overloaded functions return true iff needle is a
1603 // substring of haystack.  NULL is considered a substring of itself
1604 // only.
1605 
1606 bool IsSubstringPred(const char* needle, const char* haystack) {
1607   if (needle == NULL || haystack == NULL)
1608     return needle == haystack;
1609 
1610   return strstr(haystack, needle) != NULL;
1611 }
1612 
1613 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1614   if (needle == NULL || haystack == NULL)
1615     return needle == haystack;
1616 
1617   return wcsstr(haystack, needle) != NULL;
1618 }
1619 
1620 // StringType here can be either ::std::string or ::std::wstring.
1621 template <typename StringType>
1622 bool IsSubstringPred(const StringType& needle,
1623                      const StringType& haystack) {
1624   return haystack.find(needle) != StringType::npos;
1625 }
1626 
1627 // This function implements either IsSubstring() or IsNotSubstring(),
1628 // depending on the value of the expected_to_be_substring parameter.
1629 // StringType here can be const char*, const wchar_t*, ::std::string,
1630 // or ::std::wstring.
1631 template <typename StringType>
1632 AssertionResult IsSubstringImpl(
1633     bool expected_to_be_substring,
1634     const char* needle_expr, const char* haystack_expr,
1635     const StringType& needle, const StringType& haystack) {
1636   if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1637     return AssertionSuccess();
1638 
1639   const bool is_wide_string = sizeof(needle[0]) > 1;
1640   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1641   return AssertionFailure()
1642       << "Value of: " << needle_expr << "\n"
1643       << "  Actual: " << begin_string_quote << needle << "\"\n"
1644       << "Expected: " << (expected_to_be_substring ? "" : "not ")
1645       << "a substring of " << haystack_expr << "\n"
1646       << "Which is: " << begin_string_quote << haystack << "\"";
1647 }
1648 
1649 }  // namespace
1650 
1651 // IsSubstring() and IsNotSubstring() check whether needle is a
1652 // substring of haystack (NULL is considered a substring of itself
1653 // only), and return an appropriate error message when they fail.
1654 
1655 AssertionResult IsSubstring(
1656     const char* needle_expr, const char* haystack_expr,
1657     const char* needle, const char* haystack) {
1658   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1659 }
1660 
1661 AssertionResult IsSubstring(
1662     const char* needle_expr, const char* haystack_expr,
1663     const wchar_t* needle, const wchar_t* haystack) {
1664   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1665 }
1666 
1667 AssertionResult IsNotSubstring(
1668     const char* needle_expr, const char* haystack_expr,
1669     const char* needle, const char* haystack) {
1670   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1671 }
1672 
1673 AssertionResult IsNotSubstring(
1674     const char* needle_expr, const char* haystack_expr,
1675     const wchar_t* needle, const wchar_t* haystack) {
1676   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1677 }
1678 
1679 AssertionResult IsSubstring(
1680     const char* needle_expr, const char* haystack_expr,
1681     const ::std::string& needle, const ::std::string& haystack) {
1682   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1683 }
1684 
1685 AssertionResult IsNotSubstring(
1686     const char* needle_expr, const char* haystack_expr,
1687     const ::std::string& needle, const ::std::string& haystack) {
1688   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1689 }
1690 
1691 #if GTEST_HAS_STD_WSTRING
1692 AssertionResult IsSubstring(
1693     const char* needle_expr, const char* haystack_expr,
1694     const ::std::wstring& needle, const ::std::wstring& haystack) {
1695   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1696 }
1697 
1698 AssertionResult IsNotSubstring(
1699     const char* needle_expr, const char* haystack_expr,
1700     const ::std::wstring& needle, const ::std::wstring& haystack) {
1701   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1702 }
1703 #endif  // GTEST_HAS_STD_WSTRING
1704 
1705 namespace internal {
1706 
1707 #if GTEST_OS_WINDOWS
1708 
1709 namespace {
1710 
1711 // Helper function for IsHRESULT{SuccessFailure} predicates
1712 AssertionResult HRESULTFailureHelper(const char* expr,
1713                                      const char* expected,
1714                                      long hr) {  // NOLINT
1715 # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
1716 
1717   // Windows CE doesn't support FormatMessage.
1718   const char error_text[] = "";
1719 
1720 # else
1721 
1722   // Looks up the human-readable system message for the HRESULT code
1723   // and since we're not passing any params to FormatMessage, we don't
1724   // want inserts expanded.
1725   const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1726                        FORMAT_MESSAGE_IGNORE_INSERTS;
1727   const DWORD kBufSize = 4096;
1728   // Gets the system's human readable message string for this HRESULT.
1729   char error_text[kBufSize] = { '\0' };
1730   DWORD message_length = ::FormatMessageA(kFlags,
1731                                           0,  // no source, we're asking system
1732                                           hr,  // the error
1733                                           0,  // no line width restrictions
1734                                           error_text,  // output buffer
1735                                           kBufSize,  // buf size
1736                                           NULL);  // no arguments for inserts
1737   // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
1738   for (; message_length && IsSpace(error_text[message_length - 1]);
1739           --message_length) {
1740     error_text[message_length - 1] = '\0';
1741   }
1742 
1743 # endif  // GTEST_OS_WINDOWS_MOBILE
1744 
1745   const std::string error_hex("0x" + String::FormatHexInt(hr));
1746   return ::testing::AssertionFailure()
1747       << "Expected: " << expr << " " << expected << ".\n"
1748       << "  Actual: " << error_hex << " " << error_text << "\n";
1749 }
1750 
1751 }  // namespace
1752 
1753 AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
1754   if (SUCCEEDED(hr)) {
1755     return AssertionSuccess();
1756   }
1757   return HRESULTFailureHelper(expr, "succeeds", hr);
1758 }
1759 
1760 AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
1761   if (FAILED(hr)) {
1762     return AssertionSuccess();
1763   }
1764   return HRESULTFailureHelper(expr, "fails", hr);
1765 }
1766 
1767 #endif  // GTEST_OS_WINDOWS
1768 
1769 // Utility functions for encoding Unicode text (wide strings) in
1770 // UTF-8.
1771 
1772 // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
1773 // like this:
1774 //
1775 // Code-point length   Encoding
1776 //   0 -  7 bits       0xxxxxxx
1777 //   8 - 11 bits       110xxxxx 10xxxxxx
1778 //  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
1779 //  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1780 
1781 // The maximum code-point a one-byte UTF-8 sequence can represent.
1782 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
1783 
1784 // The maximum code-point a two-byte UTF-8 sequence can represent.
1785 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1786 
1787 // The maximum code-point a three-byte UTF-8 sequence can represent.
1788 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1789 
1790 // The maximum code-point a four-byte UTF-8 sequence can represent.
1791 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1792 
1793 // Chops off the n lowest bits from a bit pattern.  Returns the n
1794 // lowest bits.  As a side effect, the original bit pattern will be
1795 // shifted to the right by n bits.
1796 inline UInt32 ChopLowBits(UInt32* bits, int n) {
1797   const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1798   *bits >>= n;
1799   return low_bits;
1800 }
1801 
1802 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
1803 // code_point parameter is of type UInt32 because wchar_t may not be
1804 // wide enough to contain a code point.
1805 // If the code_point is not a valid Unicode code point
1806 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
1807 // to "(Invalid Unicode 0xXXXXXXXX)".
1808 std::string CodePointToUtf8(UInt32 code_point) {
1809   if (code_point > kMaxCodePoint4) {
1810     return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
1811   }
1812 
1813   char str[5];  // Big enough for the largest valid code point.
1814   if (code_point <= kMaxCodePoint1) {
1815     str[1] = '\0';
1816     str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
1817   } else if (code_point <= kMaxCodePoint2) {
1818     str[2] = '\0';
1819     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1820     str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
1821   } else if (code_point <= kMaxCodePoint3) {
1822     str[3] = '\0';
1823     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1824     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1825     str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
1826   } else {  // code_point <= kMaxCodePoint4
1827     str[4] = '\0';
1828     str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1829     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1830     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1831     str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
1832   }
1833   return str;
1834 }
1835 
1836 // The following two functions only make sense if the system
1837 // uses UTF-16 for wide string encoding. All supported systems
1838 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
1839 
1840 // Determines if the arguments constitute UTF-16 surrogate pair
1841 // and thus should be combined into a single Unicode code point
1842 // using CreateCodePointFromUtf16SurrogatePair.
1843 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
1844   return sizeof(wchar_t) == 2 &&
1845       (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
1846 }
1847 
1848 // Creates a Unicode code point from UTF16 surrogate pair.
1849 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
1850                                                     wchar_t second) {
1851   const UInt32 mask = (1 << 10) - 1;
1852   return (sizeof(wchar_t) == 2) ?
1853       (((first & mask) << 10) | (second & mask)) + 0x10000 :
1854       // This function should not be called when the condition is
1855       // false, but we provide a sensible default in case it is.
1856       static_cast<UInt32>(first);
1857 }
1858 
1859 // Converts a wide string to a narrow string in UTF-8 encoding.
1860 // The wide string is assumed to have the following encoding:
1861 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
1862 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1863 // Parameter str points to a null-terminated wide string.
1864 // Parameter num_chars may additionally limit the number
1865 // of wchar_t characters processed. -1 is used when the entire string
1866 // should be processed.
1867 // If the string contains code points that are not valid Unicode code points
1868 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1869 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1870 // and contains invalid UTF-16 surrogate pairs, values in those pairs
1871 // will be encoded as individual Unicode characters from Basic Normal Plane.
1872 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
1873   if (num_chars == -1)
1874     num_chars = static_cast<int>(wcslen(str));
1875 
1876   ::std::stringstream stream;
1877   for (int i = 0; i < num_chars; ++i) {
1878     UInt32 unicode_code_point;
1879 
1880     if (str[i] == L'\0') {
1881       break;
1882     } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
1883       unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
1884                                                                  str[i + 1]);
1885       i++;
1886     } else {
1887       unicode_code_point = static_cast<UInt32>(str[i]);
1888     }
1889 
1890     stream << CodePointToUtf8(unicode_code_point);
1891   }
1892   return StringStreamToString(&stream);
1893 }
1894 
1895 // Converts a wide C string to an std::string using the UTF-8 encoding.
1896 // NULL will be converted to "(null)".
1897 std::string String::ShowWideCString(const wchar_t * wide_c_str) {
1898   if (wide_c_str == NULL)  return "(null)";
1899 
1900   return internal::WideStringToUtf8(wide_c_str, -1);
1901 }
1902 
1903 // Compares two wide C strings.  Returns true iff they have the same
1904 // content.
1905 //
1906 // Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
1907 // C string is considered different to any non-NULL C string,
1908 // including the empty string.
1909 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1910   if (lhs == NULL) return rhs == NULL;
1911 
1912   if (rhs == NULL) return false;
1913 
1914   return wcscmp(lhs, rhs) == 0;
1915 }
1916 
1917 // Helper function for *_STREQ on wide strings.
1918 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
1919                                const char* rhs_expression,
1920                                const wchar_t* lhs,
1921                                const wchar_t* rhs) {
1922   if (String::WideCStringEquals(lhs, rhs)) {
1923     return AssertionSuccess();
1924   }
1925 
1926   return EqFailure(lhs_expression,
1927                    rhs_expression,
1928                    PrintToString(lhs),
1929                    PrintToString(rhs),
1930                    false);
1931 }
1932 
1933 // Helper function for *_STRNE on wide strings.
1934 AssertionResult CmpHelperSTRNE(const char* s1_expression,
1935                                const char* s2_expression,
1936                                const wchar_t* s1,
1937                                const wchar_t* s2) {
1938   if (!String::WideCStringEquals(s1, s2)) {
1939     return AssertionSuccess();
1940   }
1941 
1942   return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
1943                             << s2_expression << "), actual: "
1944                             << PrintToString(s1)
1945                             << " vs " << PrintToString(s2);
1946 }
1947 
1948 // Compares two C strings, ignoring case.  Returns true iff they have
1949 // the same content.
1950 //
1951 // Unlike strcasecmp(), this function can handle NULL argument(s).  A
1952 // NULL C string is considered different to any non-NULL C string,
1953 // including the empty string.
1954 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
1955   if (lhs == NULL)
1956     return rhs == NULL;
1957   if (rhs == NULL)
1958     return false;
1959   return posix::StrCaseCmp(lhs, rhs) == 0;
1960 }
1961 
1962   // Compares two wide C strings, ignoring case.  Returns true iff they
1963   // have the same content.
1964   //
1965   // Unlike wcscasecmp(), this function can handle NULL argument(s).
1966   // A NULL C string is considered different to any non-NULL wide C string,
1967   // including the empty string.
1968   // NB: The implementations on different platforms slightly differ.
1969   // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
1970   // environment variable. On GNU platform this method uses wcscasecmp
1971   // which compares according to LC_CTYPE category of the current locale.
1972   // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
1973   // current locale.
1974 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
1975                                               const wchar_t* rhs) {
1976   if (lhs == NULL) return rhs == NULL;
1977 
1978   if (rhs == NULL) return false;
1979 
1980 #if GTEST_OS_WINDOWS
1981   return _wcsicmp(lhs, rhs) == 0;
1982 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
1983   return wcscasecmp(lhs, rhs) == 0;
1984 #else
1985   // Android, Mac OS X and Cygwin don't define wcscasecmp.
1986   // Other unknown OSes may not define it either.
1987   wint_t left, right;
1988   do {
1989     left = towlower(*lhs++);
1990     right = towlower(*rhs++);
1991   } while (left && left == right);
1992   return left == right;
1993 #endif  // OS selector
1994 }
1995 
1996 // Returns true iff str ends with the given suffix, ignoring case.
1997 // Any string is considered to end with an empty suffix.
1998 bool String::EndsWithCaseInsensitive(
1999     const std::string& str, const std::string& suffix) {
2000   const size_t str_len = str.length();
2001   const size_t suffix_len = suffix.length();
2002   return (str_len >= suffix_len) &&
2003          CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
2004                                       suffix.c_str());
2005 }
2006 
2007 // Formats an int value as "%02d".
2008 std::string String::FormatIntWidth2(int value) {
2009   std::stringstream ss;
2010   ss << std::setfill('0') << std::setw(2) << value;
2011   return ss.str();
2012 }
2013 
2014 // Formats an int value as "%X".
2015 std::string String::FormatHexInt(int value) {
2016   std::stringstream ss;
2017   ss << std::hex << std::uppercase << value;
2018   return ss.str();
2019 }
2020 
2021 // Formats a byte as "%02X".
2022 std::string String::FormatByte(unsigned char value) {
2023   std::stringstream ss;
2024   ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
2025      << static_cast<unsigned int>(value);
2026   return ss.str();
2027 }
2028 
2029 // Converts the buffer in a stringstream to an std::string, converting NUL
2030 // bytes to "\\0" along the way.
2031 std::string StringStreamToString(::std::stringstream* ss) {
2032   const ::std::string& str = ss->str();
2033   const char* const start = str.c_str();
2034   const char* const end = start + str.length();
2035 
2036   std::string result;
2037   result.reserve(2 * (end - start));
2038   for (const char* ch = start; ch != end; ++ch) {
2039     if (*ch == '\0') {
2040       result += "\\0";  // Replaces NUL with "\\0";
2041     } else {
2042       result += *ch;
2043     }
2044   }
2045 
2046   return result;
2047 }
2048 
2049 // Appends the user-supplied message to the Google-Test-generated message.
2050 std::string AppendUserMessage(const std::string& gtest_msg,
2051                               const Message& user_msg) {
2052   // Appends the user message if it's non-empty.
2053   const std::string user_msg_string = user_msg.GetString();
2054   if (user_msg_string.empty()) {
2055     return gtest_msg;
2056   }
2057 
2058   return gtest_msg + "\n" + user_msg_string;
2059 }
2060 
2061 }  // namespace internal
2062 
2063 // class TestResult
2064 
2065 // Creates an empty TestResult.
2066 TestResult::TestResult()
2067     : death_test_count_(0),
2068       elapsed_time_(0) {
2069 }
2070 
2071 // D'tor.
2072 TestResult::~TestResult() {
2073 }
2074 
2075 // Returns the i-th test part result among all the results. i can
2076 // range from 0 to total_part_count() - 1. If i is not in that range,
2077 // aborts the program.
2078 const TestPartResult& TestResult::GetTestPartResult(int i) const {
2079   if (i < 0 || i >= total_part_count())
2080     internal::posix::Abort();
2081   return test_part_results_.at(i);
2082 }
2083 
2084 // Returns the i-th test property. i can range from 0 to
2085 // test_property_count() - 1. If i is not in that range, aborts the
2086 // program.
2087 const TestProperty& TestResult::GetTestProperty(int i) const {
2088   if (i < 0 || i >= test_property_count())
2089     internal::posix::Abort();
2090   return test_properties_.at(i);
2091 }
2092 
2093 // Clears the test part results.
2094 void TestResult::ClearTestPartResults() {
2095   test_part_results_.clear();
2096 }
2097 
2098 // Adds a test part result to the list.
2099 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
2100   test_part_results_.push_back(test_part_result);
2101 }
2102 
2103 // Adds a test property to the list. If a property with the same key as the
2104 // supplied property is already represented, the value of this test_property
2105 // replaces the old value for that key.
2106 void TestResult::RecordProperty(const std::string& xml_element,
2107                                 const TestProperty& test_property) {
2108   if (!ValidateTestProperty(xml_element, test_property)) {
2109     return;
2110   }
2111   internal::MutexLock lock(&test_properites_mutex_);
2112   const std::vector<TestProperty>::iterator property_with_matching_key =
2113       std::find_if(test_properties_.begin(), test_properties_.end(),
2114                    internal::TestPropertyKeyIs(test_property.key()));
2115   if (property_with_matching_key == test_properties_.end()) {
2116     test_properties_.push_back(test_property);
2117     return;
2118   }
2119   property_with_matching_key->SetValue(test_property.value());
2120 }
2121 
2122 // The list of reserved attributes used in the <testsuites> element of XML
2123 // output.
2124 static const char* const kReservedTestSuitesAttributes[] = {
2125   "disabled",
2126   "errors",
2127   "failures",
2128   "name",
2129   "random_seed",
2130   "tests",
2131   "time",
2132   "timestamp"
2133 };
2134 
2135 // The list of reserved attributes used in the <testsuite> element of XML
2136 // output.
2137 static const char* const kReservedTestSuiteAttributes[] = {
2138   "disabled",
2139   "errors",
2140   "failures",
2141   "name",
2142   "tests",
2143   "time"
2144 };
2145 
2146 // The list of reserved attributes used in the <testcase> element of XML output.
2147 static const char* const kReservedTestCaseAttributes[] = {
2148     "classname",  "name",        "status", "time",
2149     "type_param", "value_param", "file",   "line"};
2150 
2151 template <int kSize>
2152 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
2153   return std::vector<std::string>(array, array + kSize);
2154 }
2155 
2156 static std::vector<std::string> GetReservedAttributesForElement(
2157     const std::string& xml_element) {
2158   if (xml_element == "testsuites") {
2159     return ArrayAsVector(kReservedTestSuitesAttributes);
2160   } else if (xml_element == "testsuite") {
2161     return ArrayAsVector(kReservedTestSuiteAttributes);
2162   } else if (xml_element == "testcase") {
2163     return ArrayAsVector(kReservedTestCaseAttributes);
2164   } else {
2165     GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
2166   }
2167   // This code is unreachable but some compilers may not realizes that.
2168   return std::vector<std::string>();
2169 }
2170 
2171 static std::string FormatWordList(const std::vector<std::string>& words) {
2172   Message word_list;
2173   for (size_t i = 0; i < words.size(); ++i) {
2174     if (i > 0 && words.size() > 2) {
2175       word_list << ", ";
2176     }
2177     if (i == words.size() - 1) {
2178       word_list << "and ";
2179     }
2180     word_list << "'" << words[i] << "'";
2181   }
2182   return word_list.GetString();
2183 }
2184 
2185 static bool ValidateTestPropertyName(
2186     const std::string& property_name,
2187     const std::vector<std::string>& reserved_names) {
2188   if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
2189           reserved_names.end()) {
2190     ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
2191                   << " (" << FormatWordList(reserved_names)
2192                   << " are reserved by " << GTEST_NAME_ << ")";
2193     return false;
2194   }
2195   return true;
2196 }
2197 
2198 // Adds a failure if the key is a reserved attribute of the element named
2199 // xml_element.  Returns true if the property is valid.
2200 bool TestResult::ValidateTestProperty(const std::string& xml_element,
2201                                       const TestProperty& test_property) {
2202   return ValidateTestPropertyName(test_property.key(),
2203                                   GetReservedAttributesForElement(xml_element));
2204 }
2205 
2206 // Clears the object.
2207 void TestResult::Clear() {
2208   test_part_results_.clear();
2209   test_properties_.clear();
2210   death_test_count_ = 0;
2211   elapsed_time_ = 0;
2212 }
2213 
2214 // Returns true iff the test failed.
2215 bool TestResult::Failed() const {
2216   for (int i = 0; i < total_part_count(); ++i) {
2217     if (GetTestPartResult(i).failed())
2218       return true;
2219   }
2220   return false;
2221 }
2222 
2223 // Returns true iff the test part fatally failed.
2224 static bool TestPartFatallyFailed(const TestPartResult& result) {
2225   return result.fatally_failed();
2226 }
2227 
2228 // Returns true iff the test fatally failed.
2229 bool TestResult::HasFatalFailure() const {
2230   return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
2231 }
2232 
2233 // Returns true iff the test part non-fatally failed.
2234 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
2235   return result.nonfatally_failed();
2236 }
2237 
2238 // Returns true iff the test has a non-fatal failure.
2239 bool TestResult::HasNonfatalFailure() const {
2240   return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
2241 }
2242 
2243 // Gets the number of all test parts.  This is the sum of the number
2244 // of successful test parts and the number of failed test parts.
2245 int TestResult::total_part_count() const {
2246   return static_cast<int>(test_part_results_.size());
2247 }
2248 
2249 // Returns the number of the test properties.
2250 int TestResult::test_property_count() const {
2251   return static_cast<int>(test_properties_.size());
2252 }
2253 
2254 // class Test
2255 
2256 // Creates a Test object.
2257 
2258 // The c'tor saves the states of all flags.
2259 Test::Test()
2260     : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
2261 }
2262 
2263 // The d'tor restores the states of all flags.  The actual work is
2264 // done by the d'tor of the gtest_flag_saver_ field, and thus not
2265 // visible here.
2266 Test::~Test() {
2267 }
2268 
2269 // Sets up the test fixture.
2270 //
2271 // A sub-class may override this.
2272 void Test::SetUp() {
2273 }
2274 
2275 // Tears down the test fixture.
2276 //
2277 // A sub-class may override this.
2278 void Test::TearDown() {
2279 }
2280 
2281 // Allows user supplied key value pairs to be recorded for later output.
2282 void Test::RecordProperty(const std::string& key, const std::string& value) {
2283   UnitTest::GetInstance()->RecordProperty(key, value);
2284 }
2285 
2286 // Allows user supplied key value pairs to be recorded for later output.
2287 void Test::RecordProperty(const std::string& key, int value) {
2288   Message value_message;
2289   value_message << value;
2290   RecordProperty(key, value_message.GetString().c_str());
2291 }
2292 
2293 namespace internal {
2294 
2295 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
2296                                     const std::string& message) {
2297   // This function is a friend of UnitTest and as such has access to
2298   // AddTestPartResult.
2299   UnitTest::GetInstance()->AddTestPartResult(
2300       result_type,
2301       NULL,  // No info about the source file where the exception occurred.
2302       -1,    // We have no info on which line caused the exception.
2303       message,
2304       "");   // No stack trace, either.
2305 }
2306 
2307 }  // namespace internal
2308 
2309 // Google Test requires all tests in the same test case to use the same test
2310 // fixture class.  This function checks if the current test has the
2311 // same fixture class as the first test in the current test case.  If
2312 // yes, it returns true; otherwise it generates a Google Test failure and
2313 // returns false.
2314 bool Test::HasSameFixtureClass() {
2315   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2316   const TestCase* const test_case = impl->current_test_case();
2317 
2318   // Info about the first test in the current test case.
2319   const TestInfo* const first_test_info = test_case->test_info_list()[0];
2320   const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
2321   const char* const first_test_name = first_test_info->name();
2322 
2323   // Info about the current test.
2324   const TestInfo* const this_test_info = impl->current_test_info();
2325   const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
2326   const char* const this_test_name = this_test_info->name();
2327 
2328   if (this_fixture_id != first_fixture_id) {
2329     // Is the first test defined using TEST?
2330     const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
2331     // Is this test defined using TEST?
2332     const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
2333 
2334     if (first_is_TEST || this_is_TEST) {
2335       // Both TEST and TEST_F appear in same test case, which is incorrect.
2336       // Tell the user how to fix this.
2337 
2338       // Gets the name of the TEST and the name of the TEST_F.  Note
2339       // that first_is_TEST and this_is_TEST cannot both be true, as
2340       // the fixture IDs are different for the two tests.
2341       const char* const TEST_name =
2342           first_is_TEST ? first_test_name : this_test_name;
2343       const char* const TEST_F_name =
2344           first_is_TEST ? this_test_name : first_test_name;
2345 
2346       ADD_FAILURE()
2347           << "All tests in the same test case must use the same test fixture\n"
2348           << "class, so mixing TEST_F and TEST in the same test case is\n"
2349           << "illegal.  In test case " << this_test_info->test_case_name()
2350           << ",\n"
2351           << "test " << TEST_F_name << " is defined using TEST_F but\n"
2352           << "test " << TEST_name << " is defined using TEST.  You probably\n"
2353           << "want to change the TEST to TEST_F or move it to another test\n"
2354           << "case.";
2355     } else {
2356       // Two fixture classes with the same name appear in two different
2357       // namespaces, which is not allowed. Tell the user how to fix this.
2358       ADD_FAILURE()
2359           << "All tests in the same test case must use the same test fixture\n"
2360           << "class.  However, in test case "
2361           << this_test_info->test_case_name() << ",\n"
2362           << "you defined test " << first_test_name
2363           << " and test " << this_test_name << "\n"
2364           << "using two different test fixture classes.  This can happen if\n"
2365           << "the two classes are from different namespaces or translation\n"
2366           << "units and have the same name.  You should probably rename one\n"
2367           << "of the classes to put the tests into different test cases.";
2368     }
2369     return false;
2370   }
2371 
2372   return true;
2373 }
2374 
2375 #if GTEST_HAS_SEH
2376 
2377 // Adds an "exception thrown" fatal failure to the current test.  This
2378 // function returns its result via an output parameter pointer because VC++
2379 // prohibits creation of objects with destructors on stack in functions
2380 // using __try (see error C2712).
2381 static std::string* FormatSehExceptionMessage(DWORD exception_code,
2382                                               const char* location) {
2383   Message message;
2384   message << "SEH exception with code 0x" << std::setbase(16) <<
2385     exception_code << std::setbase(10) << " thrown in " << location << ".";
2386 
2387   return new std::string(message.GetString());
2388 }
2389 
2390 #endif  // GTEST_HAS_SEH
2391 
2392 namespace internal {
2393 
2394 #if GTEST_HAS_EXCEPTIONS
2395 
2396 // Adds an "exception thrown" fatal failure to the current test.
2397 static std::string FormatCxxExceptionMessage(const char* description,
2398                                              const char* location) {
2399   Message message;
2400   if (description != NULL) {
2401     message << "C++ exception with description \"" << description << "\"";
2402   } else {
2403     message << "Unknown C++ exception";
2404   }
2405   message << " thrown in " << location << ".";
2406 
2407   return message.GetString();
2408 }
2409 
2410 static std::string PrintTestPartResultToString(
2411     const TestPartResult& test_part_result);
2412 
2413 GoogleTestFailureException::GoogleTestFailureException(
2414     const TestPartResult& failure)
2415     : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
2416 
2417 #endif  // GTEST_HAS_EXCEPTIONS
2418 
2419 // We put these helper functions in the internal namespace as IBM's xlC
2420 // compiler rejects the code if they were declared static.
2421 
2422 // Runs the given method and handles SEH exceptions it throws, when
2423 // SEH is supported; returns the 0-value for type Result in case of an
2424 // SEH exception.  (Microsoft compilers cannot handle SEH and C++
2425 // exceptions in the same function.  Therefore, we provide a separate
2426 // wrapper function for handling SEH exceptions.)
2427 template <class T, typename Result>
2428 Result HandleSehExceptionsInMethodIfSupported(
2429     T* object, Result (T::*method)(), const char* location) {
2430 #if GTEST_HAS_SEH
2431   __try {
2432     return (object->*method)();
2433   } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
2434       GetExceptionCode())) {
2435     // We create the exception message on the heap because VC++ prohibits
2436     // creation of objects with destructors on stack in functions using __try
2437     // (see error C2712).
2438     std::string* exception_message = FormatSehExceptionMessage(
2439         GetExceptionCode(), location);
2440     internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
2441                                              *exception_message);
2442     delete exception_message;
2443     return static_cast<Result>(0);
2444   }
2445 #else
2446   (void)location;
2447   return (object->*method)();
2448 #endif  // GTEST_HAS_SEH
2449 }
2450 
2451 // Runs the given method and catches and reports C++ and/or SEH-style
2452 // exceptions, if they are supported; returns the 0-value for type
2453 // Result in case of an SEH exception.
2454 template <class T, typename Result>
2455 Result HandleExceptionsInMethodIfSupported(
2456     T* object, Result (T::*method)(), const char* location) {
2457   // NOTE: The user code can affect the way in which Google Test handles
2458   // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
2459   // RUN_ALL_TESTS() starts. It is technically possible to check the flag
2460   // after the exception is caught and either report or re-throw the
2461   // exception based on the flag's value:
2462   //
2463   // try {
2464   //   // Perform the test method.
2465   // } catch (...) {
2466   //   if (GTEST_FLAG(catch_exceptions))
2467   //     // Report the exception as failure.
2468   //   else
2469   //     throw;  // Re-throws the original exception.
2470   // }
2471   //
2472   // However, the purpose of this flag is to allow the program to drop into
2473   // the debugger when the exception is thrown. On most platforms, once the
2474   // control enters the catch block, the exception origin information is
2475   // lost and the debugger will stop the program at the point of the
2476   // re-throw in this function -- instead of at the point of the original
2477   // throw statement in the code under test.  For this reason, we perform
2478   // the check early, sacrificing the ability to affect Google Test's
2479   // exception handling in the method where the exception is thrown.
2480   if (internal::GetUnitTestImpl()->catch_exceptions()) {
2481 #if GTEST_HAS_EXCEPTIONS
2482     try {
2483       return HandleSehExceptionsInMethodIfSupported(object, method, location);
2484     } catch (const AssertionException&) {  // NOLINT
2485       // This failure was reported already.
2486     } catch (const internal::GoogleTestFailureException&) {  // NOLINT
2487       // This exception type can only be thrown by a failed Google
2488       // Test assertion with the intention of letting another testing
2489       // framework catch it.  Therefore we just re-throw it.
2490       throw;
2491     } catch (const std::exception& e) {  // NOLINT
2492       internal::ReportFailureInUnknownLocation(
2493           TestPartResult::kFatalFailure,
2494           FormatCxxExceptionMessage(e.what(), location));
2495     } catch (...) {  // NOLINT
2496       internal::ReportFailureInUnknownLocation(
2497           TestPartResult::kFatalFailure,
2498           FormatCxxExceptionMessage(NULL, location));
2499     }
2500     return static_cast<Result>(0);
2501 #else
2502     return HandleSehExceptionsInMethodIfSupported(object, method, location);
2503 #endif  // GTEST_HAS_EXCEPTIONS
2504   } else {
2505     return (object->*method)();
2506   }
2507 }
2508 
2509 }  // namespace internal
2510 
2511 // Runs the test and updates the test result.
2512 void Test::Run() {
2513   if (!HasSameFixtureClass()) return;
2514 
2515   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2516   impl->os_stack_trace_getter()->UponLeavingGTest();
2517   internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
2518   // We will run the test only if SetUp() was successful.
2519   if (!HasFatalFailure()) {
2520     impl->os_stack_trace_getter()->UponLeavingGTest();
2521     internal::HandleExceptionsInMethodIfSupported(
2522         this, &Test::TestBody, "the test body");
2523   }
2524 
2525   // However, we want to clean up as much as possible.  Hence we will
2526   // always call TearDown(), even if SetUp() or the test body has
2527   // failed.
2528   impl->os_stack_trace_getter()->UponLeavingGTest();
2529   internal::HandleExceptionsInMethodIfSupported(
2530       this, &Test::TearDown, "TearDown()");
2531 }
2532 
2533 // Returns true iff the current test has a fatal failure.
2534 bool Test::HasFatalFailure() {
2535   return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2536 }
2537 
2538 // Returns true iff the current test has a non-fatal failure.
2539 bool Test::HasNonfatalFailure() {
2540   return internal::GetUnitTestImpl()->current_test_result()->
2541       HasNonfatalFailure();
2542 }
2543 
2544 // class TestInfo
2545 
2546 // Constructs a TestInfo object. It assumes ownership of the test factory
2547 // object.
2548 TestInfo::TestInfo(const std::string& a_test_case_name,
2549                    const std::string& a_name,
2550                    const char* a_type_param,
2551                    const char* a_value_param,
2552                    internal::CodeLocation a_code_location,
2553                    internal::TypeId fixture_class_id,
2554                    internal::TestFactoryBase* factory)
2555     : test_case_name_(a_test_case_name),
2556       name_(a_name),
2557       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
2558       value_param_(a_value_param ? new std::string(a_value_param) : NULL),
2559       location_(a_code_location),
2560       fixture_class_id_(fixture_class_id),
2561       should_run_(false),
2562       is_disabled_(false),
2563       matches_filter_(false),
2564       factory_(factory),
2565       result_() {}
2566 
2567 // Destructs a TestInfo object.
2568 TestInfo::~TestInfo() { delete factory_; }
2569 
2570 namespace internal {
2571 
2572 // Creates a new TestInfo object and registers it with Google Test;
2573 // returns the created object.
2574 //
2575 // Arguments:
2576 //
2577 //   test_case_name:   name of the test case
2578 //   name:             name of the test
2579 //   type_param:       the name of the test's type parameter, or NULL if
2580 //                     this is not a typed or a type-parameterized test.
2581 //   value_param:      text representation of the test's value parameter,
2582 //                     or NULL if this is not a value-parameterized test.
2583 //   code_location:    code location where the test is defined
2584 //   fixture_class_id: ID of the test fixture class
2585 //   set_up_tc:        pointer to the function that sets up the test case
2586 //   tear_down_tc:     pointer to the function that tears down the test case
2587 //   factory:          pointer to the factory that creates a test object.
2588 //                     The newly created TestInfo instance will assume
2589 //                     ownership of the factory object.
2590 TestInfo* MakeAndRegisterTestInfo(
2591     const char* test_case_name,
2592     const char* name,
2593     const char* type_param,
2594     const char* value_param,
2595     CodeLocation code_location,
2596     TypeId fixture_class_id,
2597     SetUpTestCaseFunc set_up_tc,
2598     TearDownTestCaseFunc tear_down_tc,
2599     TestFactoryBase* factory) {
2600   TestInfo* const test_info =
2601       new TestInfo(test_case_name, name, type_param, value_param,
2602                    code_location, fixture_class_id, factory);
2603   GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2604   return test_info;
2605 }
2606 
2607 void ReportInvalidTestCaseType(const char* test_case_name,
2608                                CodeLocation code_location) {
2609   Message errors;
2610   errors
2611       << "Attempted redefinition of test case " << test_case_name << ".\n"
2612       << "All tests in the same test case must use the same test fixture\n"
2613       << "class.  However, in test case " << test_case_name << ", you tried\n"
2614       << "to define a test using a fixture class different from the one\n"
2615       << "used earlier. This can happen if the two fixture classes are\n"
2616       << "from different namespaces and have the same name. You should\n"
2617       << "probably rename one of the classes to put the tests into different\n"
2618       << "test cases.";
2619 
2620   GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
2621                                           code_location.line)
2622                     << " " << errors.GetString();
2623 }
2624 }  // namespace internal
2625 
2626 namespace {
2627 
2628 // A predicate that checks the test name of a TestInfo against a known
2629 // value.
2630 //
2631 // This is used for implementation of the TestCase class only.  We put
2632 // it in the anonymous namespace to prevent polluting the outer
2633 // namespace.
2634 //
2635 // TestNameIs is copyable.
2636 class TestNameIs {
2637  public:
2638   // Constructor.
2639   //
2640   // TestNameIs has NO default constructor.
2641   explicit TestNameIs(const char* name)
2642       : name_(name) {}
2643 
2644   // Returns true iff the test name of test_info matches name_.
2645   bool operator()(const TestInfo * test_info) const {
2646     return test_info && test_info->name() == name_;
2647   }
2648 
2649  private:
2650   std::string name_;
2651 };
2652 
2653 }  // namespace
2654 
2655 namespace internal {
2656 
2657 // This method expands all parameterized tests registered with macros TEST_P
2658 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
2659 // This will be done just once during the program runtime.
2660 void UnitTestImpl::RegisterParameterizedTests() {
2661   if (!parameterized_tests_registered_) {
2662     parameterized_test_registry_.RegisterTests();
2663     parameterized_tests_registered_ = true;
2664   }
2665 }
2666 
2667 }  // namespace internal
2668 
2669 // Creates the test object, runs it, records its result, and then
2670 // deletes it.
2671 void TestInfo::Run() {
2672   if (!should_run_) return;
2673 
2674   // Tells UnitTest where to store test result.
2675   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2676   impl->set_current_test_info(this);
2677 
2678   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2679 
2680   // Notifies the unit test event listeners that a test is about to start.
2681   repeater->OnTestStart(*this);
2682 
2683   const TimeInMillis start = internal::GetTimeInMillis();
2684 
2685   impl->os_stack_trace_getter()->UponLeavingGTest();
2686 
2687   // Creates the test object.
2688   Test* const test = internal::HandleExceptionsInMethodIfSupported(
2689       factory_, &internal::TestFactoryBase::CreateTest,
2690       "the test fixture's constructor");
2691 
2692   // Runs the test if the constructor didn't generate a fatal failure.
2693   // Note that the object will not be null
2694   if (!Test::HasFatalFailure()) {
2695     // This doesn't throw as all user code that can throw are wrapped into
2696     // exception handling code.
2697     test->Run();
2698   }
2699 
2700     // Deletes the test object.
2701     impl->os_stack_trace_getter()->UponLeavingGTest();
2702     internal::HandleExceptionsInMethodIfSupported(
2703         test, &Test::DeleteSelf_, "the test fixture's destructor");
2704 
2705   result_.set_elapsed_time(internal::GetTimeInMillis() - start);
2706 
2707   // Notifies the unit test event listener that a test has just finished.
2708   repeater->OnTestEnd(*this);
2709 
2710   // Tells UnitTest to stop associating assertion results to this
2711   // test.
2712   impl->set_current_test_info(NULL);
2713 }
2714 
2715 // class TestCase
2716 
2717 // Gets the number of successful tests in this test case.
2718 int TestCase::successful_test_count() const {
2719   return CountIf(test_info_list_, TestPassed);
2720 }
2721 
2722 // Gets the number of failed tests in this test case.
2723 int TestCase::failed_test_count() const {
2724   return CountIf(test_info_list_, TestFailed);
2725 }
2726 
2727 // Gets the number of disabled tests that will be reported in the XML report.
2728 int TestCase::reportable_disabled_test_count() const {
2729   return CountIf(test_info_list_, TestReportableDisabled);
2730 }
2731 
2732 // Gets the number of disabled tests in this test case.
2733 int TestCase::disabled_test_count() const {
2734   return CountIf(test_info_list_, TestDisabled);
2735 }
2736 
2737 // Gets the number of tests to be printed in the XML report.
2738 int TestCase::reportable_test_count() const {
2739   return CountIf(test_info_list_, TestReportable);
2740 }
2741 
2742 // Get the number of tests in this test case that should run.
2743 int TestCase::test_to_run_count() const {
2744   return CountIf(test_info_list_, ShouldRunTest);
2745 }
2746 
2747 // Gets the number of all tests.
2748 int TestCase::total_test_count() const {
2749   return static_cast<int>(test_info_list_.size());
2750 }
2751 
2752 // Creates a TestCase with the given name.
2753 //
2754 // Arguments:
2755 //
2756 //   name:         name of the test case
2757 //   a_type_param: the name of the test case's type parameter, or NULL if
2758 //                 this is not a typed or a type-parameterized test case.
2759 //   set_up_tc:    pointer to the function that sets up the test case
2760 //   tear_down_tc: pointer to the function that tears down the test case
2761 TestCase::TestCase(const char* a_name, const char* a_type_param,
2762                    Test::SetUpTestCaseFunc set_up_tc,
2763                    Test::TearDownTestCaseFunc tear_down_tc)
2764     : name_(a_name),
2765       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
2766       set_up_tc_(set_up_tc),
2767       tear_down_tc_(tear_down_tc),
2768       should_run_(false),
2769       elapsed_time_(0) {
2770 }
2771 
2772 // Destructor of TestCase.
2773 TestCase::~TestCase() {
2774   // Deletes every Test in the collection.
2775   ForEach(test_info_list_, internal::Delete<TestInfo>);
2776 }
2777 
2778 // Returns the i-th test among all the tests. i can range from 0 to
2779 // total_test_count() - 1. If i is not in that range, returns NULL.
2780 const TestInfo* TestCase::GetTestInfo(int i) const {
2781   const int index = GetElementOr(test_indices_, i, -1);
2782   return index < 0 ? NULL : test_info_list_[index];
2783 }
2784 
2785 // Returns the i-th test among all the tests. i can range from 0 to
2786 // total_test_count() - 1. If i is not in that range, returns NULL.
2787 TestInfo* TestCase::GetMutableTestInfo(int i) {
2788   const int index = GetElementOr(test_indices_, i, -1);
2789   return index < 0 ? NULL : test_info_list_[index];
2790 }
2791 
2792 // Adds a test to this test case.  Will delete the test upon
2793 // destruction of the TestCase object.
2794 void TestCase::AddTestInfo(TestInfo * test_info) {
2795   test_info_list_.push_back(test_info);
2796   test_indices_.push_back(static_cast<int>(test_indices_.size()));
2797 }
2798 
2799 // Runs every test in this TestCase.
2800 void TestCase::Run() {
2801   if (!should_run_) return;
2802 
2803   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2804   impl->set_current_test_case(this);
2805 
2806   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2807 
2808   repeater->OnTestCaseStart(*this);
2809   impl->os_stack_trace_getter()->UponLeavingGTest();
2810   internal::HandleExceptionsInMethodIfSupported(
2811       this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
2812 
2813   const internal::TimeInMillis start = internal::GetTimeInMillis();
2814   for (int i = 0; i < total_test_count(); i++) {
2815     GetMutableTestInfo(i)->Run();
2816   }
2817   elapsed_time_ = internal::GetTimeInMillis() - start;
2818 
2819   impl->os_stack_trace_getter()->UponLeavingGTest();
2820   internal::HandleExceptionsInMethodIfSupported(
2821       this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
2822 
2823   repeater->OnTestCaseEnd(*this);
2824   impl->set_current_test_case(NULL);
2825 }
2826 
2827 // Clears the results of all tests in this test case.
2828 void TestCase::ClearResult() {
2829   ad_hoc_test_result_.Clear();
2830   ForEach(test_info_list_, TestInfo::ClearTestResult);
2831 }
2832 
2833 // Shuffles the tests in this test case.
2834 void TestCase::ShuffleTests(internal::Random* random) {
2835   Shuffle(random, &test_indices_);
2836 }
2837 
2838 // Restores the test order to before the first shuffle.
2839 void TestCase::UnshuffleTests() {
2840   for (size_t i = 0; i < test_indices_.size(); i++) {
2841     test_indices_[i] = static_cast<int>(i);
2842   }
2843 }
2844 
2845 // Formats a countable noun.  Depending on its quantity, either the
2846 // singular form or the plural form is used. e.g.
2847 //
2848 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2849 // FormatCountableNoun(5, "book", "books") returns "5 books".
2850 static std::string FormatCountableNoun(int count,
2851                                        const char * singular_form,
2852                                        const char * plural_form) {
2853   return internal::StreamableToString(count) + " " +
2854       (count == 1 ? singular_form : plural_form);
2855 }
2856 
2857 // Formats the count of tests.
2858 static std::string FormatTestCount(int test_count) {
2859   return FormatCountableNoun(test_count, "test", "tests");
2860 }
2861 
2862 // Formats the count of test cases.
2863 static std::string FormatTestCaseCount(int test_case_count) {
2864   return FormatCountableNoun(test_case_count, "test case", "test cases");
2865 }
2866 
2867 // Converts a TestPartResult::Type enum to human-friendly string
2868 // representation.  Both kNonFatalFailure and kFatalFailure are translated
2869 // to "Failure", as the user usually doesn't care about the difference
2870 // between the two when viewing the test result.
2871 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
2872   switch (type) {
2873     case TestPartResult::kSuccess:
2874       return "Success";
2875 
2876     case TestPartResult::kNonFatalFailure:
2877     case TestPartResult::kFatalFailure:
2878 #ifdef _MSC_VER
2879       return "error: ";
2880 #else
2881       return "Failure\n";
2882 #endif
2883     default:
2884       return "Unknown result type";
2885   }
2886 }
2887 
2888 namespace internal {
2889 
2890 // Prints a TestPartResult to an std::string.
2891 static std::string PrintTestPartResultToString(
2892     const TestPartResult& test_part_result) {
2893   return (Message()
2894           << internal::FormatFileLocation(test_part_result.file_name(),
2895                                           test_part_result.line_number())
2896           << " " << TestPartResultTypeToString(test_part_result.type())
2897           << test_part_result.message()).GetString();
2898 }
2899 
2900 // Prints a TestPartResult.
2901 static void PrintTestPartResult(const TestPartResult& test_part_result) {
2902   const std::string& result =
2903       PrintTestPartResultToString(test_part_result);
2904   printf("%s\n", result.c_str());
2905   fflush(stdout);
2906   // If the test program runs in Visual Studio or a debugger, the
2907   // following statements add the test part result message to the Output
2908   // window such that the user can double-click on it to jump to the
2909   // corresponding source code location; otherwise they do nothing.
2910 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2911   // We don't call OutputDebugString*() on Windows Mobile, as printing
2912   // to stdout is done by OutputDebugString() there already - we don't
2913   // want the same message printed twice.
2914   ::OutputDebugStringA(result.c_str());
2915   ::OutputDebugStringA("\n");
2916 #endif
2917 }
2918 
2919 // class PrettyUnitTestResultPrinter
2920 
2921 enum GTestColor {
2922   COLOR_DEFAULT,
2923   COLOR_RED,
2924   COLOR_GREEN,
2925   COLOR_YELLOW
2926 };
2927 
2928 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
2929     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
2930 
2931 // Returns the character attribute for the given color.
2932 static WORD GetColorAttribute(GTestColor color) {
2933   switch (color) {
2934     case COLOR_RED:    return FOREGROUND_RED;
2935     case COLOR_GREEN:  return FOREGROUND_GREEN;
2936     case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
2937     default:           return 0;
2938   }
2939 }
2940 
2941 static int GetBitOffset(WORD color_mask) {
2942   if (color_mask == 0) return 0;
2943 
2944   int bitOffset = 0;
2945   while ((color_mask & 1) == 0) {
2946     color_mask >>= 1;
2947     ++bitOffset;
2948   }
2949   return bitOffset;
2950 }
2951 
2952 static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
2953   // Let's reuse the BG
2954   static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
2955                                       BACKGROUND_RED | BACKGROUND_INTENSITY;
2956   static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
2957                                       FOREGROUND_RED | FOREGROUND_INTENSITY;
2958   const WORD existing_bg = old_color_attrs & background_mask;
2959 
2960   WORD new_color =
2961       GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
2962   static const int bg_bitOffset = GetBitOffset(background_mask);
2963   static const int fg_bitOffset = GetBitOffset(foreground_mask);
2964 
2965   if (((new_color & background_mask) >> bg_bitOffset) ==
2966       ((new_color & foreground_mask) >> fg_bitOffset)) {
2967     new_color ^= FOREGROUND_INTENSITY;  // invert intensity
2968   }
2969   return new_color;
2970 }
2971 
2972 #else
2973 
2974 // Returns the ANSI color code for the given color.  COLOR_DEFAULT is
2975 // an invalid input.
2976 static const char* GetAnsiColorCode(GTestColor color) {
2977   switch (color) {
2978     case COLOR_RED:     return "1";
2979     case COLOR_GREEN:   return "2";
2980     case COLOR_YELLOW:  return "3";
2981     default:            return NULL;
2982   };
2983 }
2984 
2985 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2986 
2987 // Returns true iff Google Test should use colors in the output.
2988 bool ShouldUseColor(bool stdout_is_tty) {
2989   const char* const gtest_color = GTEST_FLAG(color).c_str();
2990 
2991   if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
2992 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
2993     // On Windows the TERM variable is usually not set, but the
2994     // console there does support colors.
2995     return stdout_is_tty;
2996 #else
2997     // On non-Windows platforms, we rely on the TERM variable.
2998     const char* const term = posix::GetEnv("TERM");
2999     const bool term_supports_color =
3000         String::CStringEquals(term, "xterm") ||
3001         String::CStringEquals(term, "xterm-color") ||
3002         String::CStringEquals(term, "xterm-256color") ||
3003         String::CStringEquals(term, "screen") ||
3004         String::CStringEquals(term, "screen-256color") ||
3005         String::CStringEquals(term, "tmux") ||
3006         String::CStringEquals(term, "tmux-256color") ||
3007         String::CStringEquals(term, "rxvt-unicode") ||
3008         String::CStringEquals(term, "rxvt-unicode-256color") ||
3009         String::CStringEquals(term, "linux") ||
3010         String::CStringEquals(term, "cygwin");
3011     return stdout_is_tty && term_supports_color;
3012 #endif  // GTEST_OS_WINDOWS
3013   }
3014 
3015   return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
3016       String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
3017       String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
3018       String::CStringEquals(gtest_color, "1");
3019   // We take "yes", "true", "t", and "1" as meaning "yes".  If the
3020   // value is neither one of these nor "auto", we treat it as "no" to
3021   // be conservative.
3022 }
3023 
3024 // Helpers for printing colored strings to stdout. Note that on Windows, we
3025 // cannot simply emit special characters and have the terminal change colors.
3026 // This routine must actually emit the characters rather than return a string
3027 // that would be colored when printed, as can be done on Linux.
3028 static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
3029   va_list args;
3030   va_start(args, fmt);
3031 
3032 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \
3033     GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
3034   const bool use_color = AlwaysFalse();
3035 #else
3036   static const bool in_color_mode =
3037       ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
3038   const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
3039 #endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3040   // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
3041 
3042   if (!use_color) {
3043     vprintf(fmt, args);
3044     va_end(args);
3045     return;
3046   }
3047 
3048 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
3049     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
3050   const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3051 
3052   // Gets the current text color.
3053   CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3054   GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3055   const WORD old_color_attrs = buffer_info.wAttributes;
3056   const WORD new_color = GetNewColor(color, old_color_attrs);
3057 
3058   // We need to flush the stream buffers into the console before each
3059   // SetConsoleTextAttribute call lest it affect the text that is already
3060   // printed but has not yet reached the console.
3061   fflush(stdout);
3062   SetConsoleTextAttribute(stdout_handle, new_color);
3063 
3064   vprintf(fmt, args);
3065 
3066   fflush(stdout);
3067   // Restores the text color.
3068   SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3069 #else
3070   printf("\033[0;3%sm", GetAnsiColorCode(color));
3071   vprintf(fmt, args);
3072   printf("\033[m");  // Resets the terminal to default.
3073 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3074   va_end(args);
3075 }
3076 
3077 // Text printed in Google Test's text output and --gtest_list_tests
3078 // output to label the type parameter and value parameter for a test.
3079 static const char kTypeParamLabel[] = "TypeParam";
3080 static const char kValueParamLabel[] = "GetParam()";
3081 
3082 static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
3083   const char* const type_param = test_info.type_param();
3084   const char* const value_param = test_info.value_param();
3085 
3086   if (type_param != NULL || value_param != NULL) {
3087     printf(", where ");
3088     if (type_param != NULL) {
3089       printf("%s = %s", kTypeParamLabel, type_param);
3090       if (value_param != NULL)
3091         printf(" and ");
3092     }
3093     if (value_param != NULL) {
3094       printf("%s = %s", kValueParamLabel, value_param);
3095     }
3096   }
3097 }
3098 
3099 // This class implements the TestEventListener interface.
3100 //
3101 // Class PrettyUnitTestResultPrinter is copyable.
3102 class PrettyUnitTestResultPrinter : public TestEventListener {
3103  public:
3104   PrettyUnitTestResultPrinter() {}
3105   static void PrintTestName(const char * test_case, const char * test) {
3106     printf("%s.%s", test_case, test);
3107   }
3108 
3109   // The following methods override what's in the TestEventListener class.
3110   virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
3111   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
3112   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
3113   virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
3114   virtual void OnTestCaseStart(const TestCase& test_case);
3115   virtual void OnTestStart(const TestInfo& test_info);
3116   virtual void OnTestPartResult(const TestPartResult& result);
3117   virtual void OnTestEnd(const TestInfo& test_info);
3118   virtual void OnTestCaseEnd(const TestCase& test_case);
3119   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
3120   virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
3121   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3122   virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
3123 
3124  private:
3125   static void PrintFailedTests(const UnitTest& unit_test);
3126 };
3127 
3128   // Fired before each iteration of tests starts.
3129 void PrettyUnitTestResultPrinter::OnTestIterationStart(
3130     const UnitTest& unit_test, int iteration) {
3131   if (GTEST_FLAG(repeat) != 1)
3132     printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
3133 
3134   const char* const filter = GTEST_FLAG(filter).c_str();
3135 
3136   // Prints the filter if it's not *.  This reminds the user that some
3137   // tests may be skipped.
3138   if (!String::CStringEquals(filter, kUniversalFilter)) {
3139     ColoredPrintf(COLOR_YELLOW,
3140                   "Note: %s filter = %s\n", GTEST_NAME_, filter);
3141   }
3142 
3143   if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
3144     const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
3145     ColoredPrintf(COLOR_YELLOW,
3146                   "Note: This is test shard %d of %s.\n",
3147                   static_cast<int>(shard_index) + 1,
3148                   internal::posix::GetEnv(kTestTotalShards));
3149   }
3150 
3151   if (GTEST_FLAG(shuffle)) {
3152     ColoredPrintf(COLOR_YELLOW,
3153                   "Note: Randomizing tests' orders with a seed of %d .\n",
3154                   unit_test.random_seed());
3155   }
3156 
3157   ColoredPrintf(COLOR_GREEN,  "[==========] ");
3158   printf("Running %s from %s.\n",
3159          FormatTestCount(unit_test.test_to_run_count()).c_str(),
3160          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
3161   fflush(stdout);
3162 }
3163 
3164 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
3165     const UnitTest& /*unit_test*/) {
3166   ColoredPrintf(COLOR_GREEN,  "[----------] ");
3167   printf("Global test environment set-up.\n");
3168   fflush(stdout);
3169 }
3170 
3171 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
3172   const std::string counts =
3173       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
3174   ColoredPrintf(COLOR_GREEN, "[----------] ");
3175   printf("%s from %s", counts.c_str(), test_case.name());
3176   if (test_case.type_param() == NULL) {
3177     printf("\n");
3178   } else {
3179     printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
3180   }
3181   fflush(stdout);
3182 }
3183 
3184 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
3185   ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
3186   PrintTestName(test_info.test_case_name(), test_info.name());
3187   printf("\n");
3188   fflush(stdout);
3189 }
3190 
3191 // Called after an assertion failure.
3192 void PrettyUnitTestResultPrinter::OnTestPartResult(
3193     const TestPartResult& result) {
3194   // If the test part succeeded, we don't need to do anything.
3195   if (result.type() == TestPartResult::kSuccess)
3196     return;
3197 
3198   // Print failure message from the assertion (e.g. expected this and got that).
3199   PrintTestPartResult(result);
3200   fflush(stdout);
3201 }
3202 
3203 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
3204   if (test_info.result()->Passed()) {
3205     ColoredPrintf(COLOR_GREEN, "[       OK ] ");
3206   } else {
3207     ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
3208   }
3209   PrintTestName(test_info.test_case_name(), test_info.name());
3210   if (test_info.result()->Failed())
3211     PrintFullTestCommentIfPresent(test_info);
3212 
3213   if (GTEST_FLAG(print_time)) {
3214     printf(" (%s ms)\n", internal::StreamableToString(
3215            test_info.result()->elapsed_time()).c_str());
3216   } else {
3217     printf("\n");
3218   }
3219   fflush(stdout);
3220 }
3221 
3222 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
3223   if (!GTEST_FLAG(print_time)) return;
3224 
3225   const std::string counts =
3226       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
3227   ColoredPrintf(COLOR_GREEN, "[----------] ");
3228   printf("%s from %s (%s ms total)\n\n",
3229          counts.c_str(), test_case.name(),
3230          internal::StreamableToString(test_case.elapsed_time()).c_str());
3231   fflush(stdout);
3232 }
3233 
3234 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
3235     const UnitTest& /*unit_test*/) {
3236   ColoredPrintf(COLOR_GREEN,  "[----------] ");
3237   printf("Global test environment tear-down\n");
3238   fflush(stdout);
3239 }
3240 
3241 // Internal helper for printing the list of failed tests.
3242 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
3243   const int failed_test_count = unit_test.failed_test_count();
3244   if (failed_test_count == 0) {
3245     return;
3246   }
3247 
3248   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
3249     const TestCase& test_case = *unit_test.GetTestCase(i);
3250     if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
3251       continue;
3252     }
3253     for (int j = 0; j < test_case.total_test_count(); ++j) {
3254       const TestInfo& test_info = *test_case.GetTestInfo(j);
3255       if (!test_info.should_run() || test_info.result()->Passed()) {
3256         continue;
3257       }
3258       ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
3259       printf("%s.%s", test_case.name(), test_info.name());
3260       PrintFullTestCommentIfPresent(test_info);
3261       printf("\n");
3262     }
3263   }
3264 }
3265 
3266 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3267                                                      int /*iteration*/) {
3268   ColoredPrintf(COLOR_GREEN,  "[==========] ");
3269   printf("%s from %s ran.",
3270          FormatTestCount(unit_test.test_to_run_count()).c_str(),
3271          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
3272   if (GTEST_FLAG(print_time)) {
3273     printf(" (%s ms total)",
3274            internal::StreamableToString(unit_test.elapsed_time()).c_str());
3275   }
3276   printf("\n");
3277   ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
3278   printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
3279 
3280   int num_failures = unit_test.failed_test_count();
3281   if (!unit_test.Passed()) {
3282     const int failed_test_count = unit_test.failed_test_count();
3283     ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
3284     printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
3285     PrintFailedTests(unit_test);
3286     printf("\n%2d FAILED %s\n", num_failures,
3287                         num_failures == 1 ? "TEST" : "TESTS");
3288   }
3289 
3290   int num_disabled = unit_test.reportable_disabled_test_count();
3291   if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
3292     if (!num_failures) {
3293       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
3294     }
3295     ColoredPrintf(COLOR_YELLOW,
3296                   "  YOU HAVE %d DISABLED %s\n\n",
3297                   num_disabled,
3298                   num_disabled == 1 ? "TEST" : "TESTS");
3299   }
3300   // Ensure that Google Test output is printed before, e.g., heapchecker output.
3301   fflush(stdout);
3302 }
3303 
3304 // End PrettyUnitTestResultPrinter
3305 
3306 // class TestEventRepeater
3307 //
3308 // This class forwards events to other event listeners.
3309 class TestEventRepeater : public TestEventListener {
3310  public:
3311   TestEventRepeater() : forwarding_enabled_(true) {}
3312   virtual ~TestEventRepeater();
3313   void Append(TestEventListener *listener);
3314   TestEventListener* Release(TestEventListener* listener);
3315 
3316   // Controls whether events will be forwarded to listeners_. Set to false
3317   // in death test child processes.
3318   bool forwarding_enabled() const { return forwarding_enabled_; }
3319   void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
3320 
3321   virtual void OnTestProgramStart(const UnitTest& unit_test);
3322   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
3323   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
3324   virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
3325   virtual void OnTestCaseStart(const TestCase& test_case);
3326   virtual void OnTestStart(const TestInfo& test_info);
3327   virtual void OnTestPartResult(const TestPartResult& result);
3328   virtual void OnTestEnd(const TestInfo& test_info);
3329   virtual void OnTestCaseEnd(const TestCase& test_case);
3330   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
3331   virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
3332   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3333   virtual void OnTestProgramEnd(const UnitTest& unit_test);
3334 
3335  private:
3336   // Controls whether events will be forwarded to listeners_. Set to false
3337   // in death test child processes.
3338   bool forwarding_enabled_;
3339   // The list of listeners that receive events.
3340   std::vector<TestEventListener*> listeners_;
3341 
3342   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
3343 };
3344 
3345 TestEventRepeater::~TestEventRepeater() {
3346   ForEach(listeners_, Delete<TestEventListener>);
3347 }
3348 
3349 void TestEventRepeater::Append(TestEventListener *listener) {
3350   listeners_.push_back(listener);
3351 }
3352 
3353 // FIXME: Factor the search functionality into Vector::Find.
3354 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
3355   for (size_t i = 0; i < listeners_.size(); ++i) {
3356     if (listeners_[i] == listener) {
3357       listeners_.erase(listeners_.begin() + i);
3358       return listener;
3359     }
3360   }
3361 
3362   return NULL;
3363 }
3364 
3365 // Since most methods are very similar, use macros to reduce boilerplate.
3366 // This defines a member that forwards the call to all listeners.
3367 #define GTEST_REPEATER_METHOD_(Name, Type) \
3368 void TestEventRepeater::Name(const Type& parameter) { \
3369   if (forwarding_enabled_) { \
3370     for (size_t i = 0; i < listeners_.size(); i++) { \
3371       listeners_[i]->Name(parameter); \
3372     } \
3373   } \
3374 }
3375 // This defines a member that forwards the call to all listeners in reverse
3376 // order.
3377 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
3378 void TestEventRepeater::Name(const Type& parameter) { \
3379   if (forwarding_enabled_) { \
3380     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
3381       listeners_[i]->Name(parameter); \
3382     } \
3383   } \
3384 }
3385 
3386 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
3387 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
3388 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
3389 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
3390 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
3391 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
3392 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
3393 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
3394 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
3395 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
3396 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
3397 
3398 #undef GTEST_REPEATER_METHOD_
3399 #undef GTEST_REVERSE_REPEATER_METHOD_
3400 
3401 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
3402                                              int iteration) {
3403   if (forwarding_enabled_) {
3404     for (size_t i = 0; i < listeners_.size(); i++) {
3405       listeners_[i]->OnTestIterationStart(unit_test, iteration);
3406     }
3407   }
3408 }
3409 
3410 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
3411                                            int iteration) {
3412   if (forwarding_enabled_) {
3413     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
3414       listeners_[i]->OnTestIterationEnd(unit_test, iteration);
3415     }
3416   }
3417 }
3418 
3419 // End TestEventRepeater
3420 
3421 // This class generates an XML output file.
3422 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
3423  public:
3424   explicit XmlUnitTestResultPrinter(const char* output_file);
3425 
3426   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3427   void ListTestsMatchingFilter(const std::vector<TestCase*>& test_cases);
3428 
3429   // Prints an XML summary of all unit tests.
3430   static void PrintXmlTestsList(std::ostream* stream,
3431                                 const std::vector<TestCase*>& test_cases);
3432 
3433  private:
3434   // Is c a whitespace character that is normalized to a space character
3435   // when it appears in an XML attribute value?
3436   static bool IsNormalizableWhitespace(char c) {
3437     return c == 0x9 || c == 0xA || c == 0xD;
3438   }
3439 
3440   // May c appear in a well-formed XML document?
3441   static bool IsValidXmlCharacter(char c) {
3442     return IsNormalizableWhitespace(c) || c >= 0x20;
3443   }
3444 
3445   // Returns an XML-escaped copy of the input string str.  If
3446   // is_attribute is true, the text is meant to appear as an attribute
3447   // value, and normalizable whitespace is preserved by replacing it
3448   // with character references.
3449   static std::string EscapeXml(const std::string& str, bool is_attribute);
3450 
3451   // Returns the given string with all characters invalid in XML removed.
3452   static std::string RemoveInvalidXmlCharacters(const std::string& str);
3453 
3454   // Convenience wrapper around EscapeXml when str is an attribute value.
3455   static std::string EscapeXmlAttribute(const std::string& str) {
3456     return EscapeXml(str, true);
3457   }
3458 
3459   // Convenience wrapper around EscapeXml when str is not an attribute value.
3460   static std::string EscapeXmlText(const char* str) {
3461     return EscapeXml(str, false);
3462   }
3463 
3464   // Verifies that the given attribute belongs to the given element and
3465   // streams the attribute as XML.
3466   static void OutputXmlAttribute(std::ostream* stream,
3467                                  const std::string& element_name,
3468                                  const std::string& name,
3469                                  const std::string& value);
3470 
3471   // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3472   static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
3473 
3474   // Streams an XML representation of a TestInfo object.
3475   static void OutputXmlTestInfo(::std::ostream* stream,
3476                                 const char* test_case_name,
3477                                 const TestInfo& test_info);
3478 
3479   // Prints an XML representation of a TestCase object
3480   static void PrintXmlTestCase(::std::ostream* stream,
3481                                const TestCase& test_case);
3482 
3483   // Prints an XML summary of unit_test to output stream out.
3484   static void PrintXmlUnitTest(::std::ostream* stream,
3485                                const UnitTest& unit_test);
3486 
3487   // Produces a string representing the test properties in a result as space
3488   // delimited XML attributes based on the property key="value" pairs.
3489   // When the std::string is not empty, it includes a space at the beginning,
3490   // to delimit this attribute from prior attributes.
3491   static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
3492 
3493   // Streams an XML representation of the test properties of a TestResult
3494   // object.
3495   static void OutputXmlTestProperties(std::ostream* stream,
3496                                       const TestResult& result);
3497 
3498   // The output file.
3499   const std::string output_file_;
3500 
3501   GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
3502 };
3503 
3504 // Creates a new XmlUnitTestResultPrinter.
3505 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
3506     : output_file_(output_file) {
3507   if (output_file_.empty()) {
3508     GTEST_LOG_(FATAL) << "XML output file may not be null";
3509   }
3510 }
3511 
3512 // Called after the unit test ends.
3513 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3514                                                   int /*iteration*/) {
3515   FILE* xmlout = OpenFileForWriting(output_file_);
3516   std::stringstream stream;
3517   PrintXmlUnitTest(&stream, unit_test);
3518   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
3519   fclose(xmlout);
3520 }
3521 
3522 void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
3523     const std::vector<TestCase*>& test_cases) {
3524   FILE* xmlout = OpenFileForWriting(output_file_);
3525   std::stringstream stream;
3526   PrintXmlTestsList(&stream, test_cases);
3527   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
3528   fclose(xmlout);
3529 }
3530 
3531 // Returns an XML-escaped copy of the input string str.  If is_attribute
3532 // is true, the text is meant to appear as an attribute value, and
3533 // normalizable whitespace is preserved by replacing it with character
3534 // references.
3535 //
3536 // Invalid XML characters in str, if any, are stripped from the output.
3537 // It is expected that most, if not all, of the text processed by this
3538 // module will consist of ordinary English text.
3539 // If this module is ever modified to produce version 1.1 XML output,
3540 // most invalid characters can be retained using character references.
3541 // FIXME: It might be nice to have a minimally invasive, human-readable
3542 // escaping scheme for invalid characters, rather than dropping them.
3543 std::string XmlUnitTestResultPrinter::EscapeXml(
3544     const std::string& str, bool is_attribute) {
3545   Message m;
3546 
3547   for (size_t i = 0; i < str.size(); ++i) {
3548     const char ch = str[i];
3549     switch (ch) {
3550       case '<':
3551         m << "&lt;";
3552         break;
3553       case '>':
3554         m << "&gt;";
3555         break;
3556       case '&':
3557         m << "&amp;";
3558         break;
3559       case '\'':
3560         if (is_attribute)
3561           m << "&apos;";
3562         else
3563           m << '\'';
3564         break;
3565       case '"':
3566         if (is_attribute)
3567           m << "&quot;";
3568         else
3569           m << '"';
3570         break;
3571       default:
3572         if (IsValidXmlCharacter(ch)) {
3573           if (is_attribute && IsNormalizableWhitespace(ch))
3574             m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
3575               << ";";
3576           else
3577             m << ch;
3578         }
3579         break;
3580     }
3581   }
3582 
3583   return m.GetString();
3584 }
3585 
3586 // Returns the given string with all characters invalid in XML removed.
3587 // Currently invalid characters are dropped from the string. An
3588 // alternative is to replace them with certain characters such as . or ?.
3589 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
3590     const std::string& str) {
3591   std::string output;
3592   output.reserve(str.size());
3593   for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
3594     if (IsValidXmlCharacter(*it))
3595       output.push_back(*it);
3596 
3597   return output;
3598 }
3599 
3600 // The following routines generate an XML representation of a UnitTest
3601 // object.
3602 // GOOGLETEST_CM0009 DO NOT DELETE
3603 //
3604 // This is how Google Test concepts map to the DTD:
3605 //
3606 // <testsuites name="AllTests">        <-- corresponds to a UnitTest object
3607 //   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
3608 //     <testcase name="test-name">     <-- corresponds to a TestInfo object
3609 //       <failure message="...">...</failure>
3610 //       <failure message="...">...</failure>
3611 //       <failure message="...">...</failure>
3612 //                                     <-- individual assertion failures
3613 //     </testcase>
3614 //   </testsuite>
3615 // </testsuites>
3616 
3617 // Formats the given time in milliseconds as seconds.
3618 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
3619   ::std::stringstream ss;
3620   ss << (static_cast<double>(ms) * 1e-3);
3621   return ss.str();
3622 }
3623 
3624 static bool PortableLocaltime(time_t seconds, struct tm* out) {
3625 #if defined(_MSC_VER)
3626   return localtime_s(out, &seconds) == 0;
3627 #elif defined(__MINGW32__) || defined(__MINGW64__)
3628   // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
3629   // Windows' localtime(), which has a thread-local tm buffer.
3630   struct tm* tm_ptr = localtime(&seconds);  // NOLINT
3631   if (tm_ptr == NULL)
3632     return false;
3633   *out = *tm_ptr;
3634   return true;
3635 #else
3636   return localtime_r(&seconds, out) != NULL;
3637 #endif
3638 }
3639 
3640 // Converts the given epoch time in milliseconds to a date string in the ISO
3641 // 8601 format, without the timezone information.
3642 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
3643   struct tm time_struct;
3644   if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
3645     return "";
3646   // YYYY-MM-DDThh:mm:ss
3647   return StreamableToString(time_struct.tm_year + 1900) + "-" +
3648       String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
3649       String::FormatIntWidth2(time_struct.tm_mday) + "T" +
3650       String::FormatIntWidth2(time_struct.tm_hour) + ":" +
3651       String::FormatIntWidth2(time_struct.tm_min) + ":" +
3652       String::FormatIntWidth2(time_struct.tm_sec);
3653 }
3654 
3655 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3656 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
3657                                                      const char* data) {
3658   const char* segment = data;
3659   *stream << "<![CDATA[";
3660   for (;;) {
3661     const char* const next_segment = strstr(segment, "]]>");
3662     if (next_segment != NULL) {
3663       stream->write(
3664           segment, static_cast<std::streamsize>(next_segment - segment));
3665       *stream << "]]>]]&gt;<![CDATA[";
3666       segment = next_segment + strlen("]]>");
3667     } else {
3668       *stream << segment;
3669       break;
3670     }
3671   }
3672   *stream << "]]>";
3673 }
3674 
3675 void XmlUnitTestResultPrinter::OutputXmlAttribute(
3676     std::ostream* stream,
3677     const std::string& element_name,
3678     const std::string& name,
3679     const std::string& value) {
3680   const std::vector<std::string>& allowed_names =
3681       GetReservedAttributesForElement(element_name);
3682 
3683   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
3684                    allowed_names.end())
3685       << "Attribute " << name << " is not allowed for element <" << element_name
3686       << ">.";
3687 
3688   *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
3689 }
3690 
3691 // Prints an XML representation of a TestInfo object.
3692 // FIXME: There is also value in printing properties with the plain printer.
3693 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
3694                                                  const char* test_case_name,
3695                                                  const TestInfo& test_info) {
3696   const TestResult& result = *test_info.result();
3697   const std::string kTestcase = "testcase";
3698 
3699   if (test_info.is_in_another_shard()) {
3700     return;
3701   }
3702 
3703   *stream << "    <testcase";
3704   OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
3705 
3706   if (test_info.value_param() != NULL) {
3707     OutputXmlAttribute(stream, kTestcase, "value_param",
3708                        test_info.value_param());
3709   }
3710   if (test_info.type_param() != NULL) {
3711     OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
3712   }
3713   if (GTEST_FLAG(list_tests)) {
3714     OutputXmlAttribute(stream, kTestcase, "file", test_info.file());
3715     OutputXmlAttribute(stream, kTestcase, "line",
3716                        StreamableToString(test_info.line()));
3717     *stream << " />\n";
3718     return;
3719   }
3720 
3721   OutputXmlAttribute(stream, kTestcase, "status",
3722                      test_info.should_run() ? "run" : "notrun");
3723   OutputXmlAttribute(stream, kTestcase, "time",
3724                      FormatTimeInMillisAsSeconds(result.elapsed_time()));
3725   OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
3726 
3727   int failures = 0;
3728   for (int i = 0; i < result.total_part_count(); ++i) {
3729     const TestPartResult& part = result.GetTestPartResult(i);
3730     if (part.failed()) {
3731       if (++failures == 1) {
3732         *stream << ">\n";
3733       }
3734       const std::string location =
3735           internal::FormatCompilerIndependentFileLocation(part.file_name(),
3736                                                           part.line_number());
3737       const std::string summary = location + "\n" + part.summary();
3738       *stream << "      <failure message=\""
3739               << EscapeXmlAttribute(summary.c_str())
3740               << "\" type=\"\">";
3741       const std::string detail = location + "\n" + part.message();
3742       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
3743       *stream << "</failure>\n";
3744     }
3745   }
3746 
3747   if (failures == 0 && result.test_property_count() == 0) {
3748     *stream << " />\n";
3749   } else {
3750     if (failures == 0) {
3751       *stream << ">\n";
3752     }
3753     OutputXmlTestProperties(stream, result);
3754     *stream << "    </testcase>\n";
3755   }
3756 }
3757 
3758 // Prints an XML representation of a TestCase object
3759 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
3760                                                 const TestCase& test_case) {
3761   const std::string kTestsuite = "testsuite";
3762   *stream << "  <" << kTestsuite;
3763   OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
3764   OutputXmlAttribute(stream, kTestsuite, "tests",
3765                      StreamableToString(test_case.reportable_test_count()));
3766   if (!GTEST_FLAG(list_tests)) {
3767     OutputXmlAttribute(stream, kTestsuite, "failures",
3768                        StreamableToString(test_case.failed_test_count()));
3769     OutputXmlAttribute(
3770         stream, kTestsuite, "disabled",
3771         StreamableToString(test_case.reportable_disabled_test_count()));
3772     OutputXmlAttribute(stream, kTestsuite, "errors", "0");
3773     OutputXmlAttribute(stream, kTestsuite, "time",
3774                        FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
3775     *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result());
3776   }
3777   *stream << ">\n";
3778   for (int i = 0; i < test_case.total_test_count(); ++i) {
3779     if (test_case.GetTestInfo(i)->is_reportable())
3780       OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
3781   }
3782   *stream << "  </" << kTestsuite << ">\n";
3783 }
3784 
3785 // Prints an XML summary of unit_test to output stream out.
3786 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
3787                                                 const UnitTest& unit_test) {
3788   const std::string kTestsuites = "testsuites";
3789 
3790   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
3791   *stream << "<" << kTestsuites;
3792 
3793   OutputXmlAttribute(stream, kTestsuites, "tests",
3794                      StreamableToString(unit_test.reportable_test_count()));
3795   OutputXmlAttribute(stream, kTestsuites, "failures",
3796                      StreamableToString(unit_test.failed_test_count()));
3797   OutputXmlAttribute(
3798       stream, kTestsuites, "disabled",
3799       StreamableToString(unit_test.reportable_disabled_test_count()));
3800   OutputXmlAttribute(stream, kTestsuites, "errors", "0");
3801   OutputXmlAttribute(
3802       stream, kTestsuites, "timestamp",
3803       FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
3804   OutputXmlAttribute(stream, kTestsuites, "time",
3805                      FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
3806 
3807   if (GTEST_FLAG(shuffle)) {
3808     OutputXmlAttribute(stream, kTestsuites, "random_seed",
3809                        StreamableToString(unit_test.random_seed()));
3810   }
3811   *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
3812 
3813   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
3814   *stream << ">\n";
3815 
3816   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
3817     if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
3818       PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
3819   }
3820   *stream << "</" << kTestsuites << ">\n";
3821 }
3822 
3823 void XmlUnitTestResultPrinter::PrintXmlTestsList(
3824     std::ostream* stream, const std::vector<TestCase*>& test_cases) {
3825   const std::string kTestsuites = "testsuites";
3826 
3827   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
3828   *stream << "<" << kTestsuites;
3829 
3830   int total_tests = 0;
3831   for (size_t i = 0; i < test_cases.size(); ++i) {
3832     total_tests += test_cases[i]->total_test_count();
3833   }
3834   OutputXmlAttribute(stream, kTestsuites, "tests",
3835                      StreamableToString(total_tests));
3836   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
3837   *stream << ">\n";
3838 
3839   for (size_t i = 0; i < test_cases.size(); ++i) {
3840     PrintXmlTestCase(stream, *test_cases[i]);
3841   }
3842   *stream << "</" << kTestsuites << ">\n";
3843 }
3844 
3845 // Produces a string representing the test properties in a result as space
3846 // delimited XML attributes based on the property key="value" pairs.
3847 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3848     const TestResult& result) {
3849   Message attributes;
3850   for (int i = 0; i < result.test_property_count(); ++i) {
3851     const TestProperty& property = result.GetTestProperty(i);
3852     attributes << " " << property.key() << "="
3853         << "\"" << EscapeXmlAttribute(property.value()) << "\"";
3854   }
3855   return attributes.GetString();
3856 }
3857 
3858 void XmlUnitTestResultPrinter::OutputXmlTestProperties(
3859     std::ostream* stream, const TestResult& result) {
3860   const std::string kProperties = "properties";
3861   const std::string kProperty = "property";
3862 
3863   if (result.test_property_count() <= 0) {
3864     return;
3865   }
3866 
3867   *stream << "<" << kProperties << ">\n";
3868   for (int i = 0; i < result.test_property_count(); ++i) {
3869     const TestProperty& property = result.GetTestProperty(i);
3870     *stream << "<" << kProperty;
3871     *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
3872     *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
3873     *stream << "/>\n";
3874   }
3875   *stream << "</" << kProperties << ">\n";
3876 }
3877 
3878 // End XmlUnitTestResultPrinter
3879 
3880 // This class generates an JSON output file.
3881 class JsonUnitTestResultPrinter : public EmptyTestEventListener {
3882  public:
3883   explicit JsonUnitTestResultPrinter(const char* output_file);
3884 
3885   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3886 
3887   // Prints an JSON summary of all unit tests.
3888   static void PrintJsonTestList(::std::ostream* stream,
3889                                 const std::vector<TestCase*>& test_cases);
3890 
3891  private:
3892   // Returns an JSON-escaped copy of the input string str.
3893   static std::string EscapeJson(const std::string& str);
3894 
3895   //// Verifies that the given attribute belongs to the given element and
3896   //// streams the attribute as JSON.
3897   static void OutputJsonKey(std::ostream* stream,
3898                             const std::string& element_name,
3899                             const std::string& name,
3900                             const std::string& value,
3901                             const std::string& indent,
3902                             bool comma = true);
3903   static void OutputJsonKey(std::ostream* stream,
3904                             const std::string& element_name,
3905                             const std::string& name,
3906                             int value,
3907                             const std::string& indent,
3908                             bool comma = true);
3909 
3910   // Streams a JSON representation of a TestInfo object.
3911   static void OutputJsonTestInfo(::std::ostream* stream,
3912                                  const char* test_case_name,
3913                                  const TestInfo& test_info);
3914 
3915   // Prints a JSON representation of a TestCase object
3916   static void PrintJsonTestCase(::std::ostream* stream,
3917                                 const TestCase& test_case);
3918 
3919   // Prints a JSON summary of unit_test to output stream out.
3920   static void PrintJsonUnitTest(::std::ostream* stream,
3921                                 const UnitTest& unit_test);
3922 
3923   // Produces a string representing the test properties in a result as
3924   // a JSON dictionary.
3925   static std::string TestPropertiesAsJson(const TestResult& result,
3926                                           const std::string& indent);
3927 
3928   // The output file.
3929   const std::string output_file_;
3930 
3931   GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
3932 };
3933 
3934 // Creates a new JsonUnitTestResultPrinter.
3935 JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
3936     : output_file_(output_file) {
3937   if (output_file_.empty()) {
3938     GTEST_LOG_(FATAL) << "JSON output file may not be null";
3939   }
3940 }
3941 
3942 void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3943                                                   int /*iteration*/) {
3944   FILE* jsonout = OpenFileForWriting(output_file_);
3945   std::stringstream stream;
3946   PrintJsonUnitTest(&stream, unit_test);
3947   fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
3948   fclose(jsonout);
3949 }
3950 
3951 // Returns an JSON-escaped copy of the input string str.
3952 std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
3953   Message m;
3954 
3955   for (size_t i = 0; i < str.size(); ++i) {
3956     const char ch = str[i];
3957     switch (ch) {
3958       case '\\':
3959       case '"':
3960       case '/':
3961         m << '\\' << ch;
3962         break;
3963       case '\b':
3964         m << "\\b";
3965         break;
3966       case '\t':
3967         m << "\\t";
3968         break;
3969       case '\n':
3970         m << "\\n";
3971         break;
3972       case '\f':
3973         m << "\\f";
3974         break;
3975       case '\r':
3976         m << "\\r";
3977         break;
3978       default:
3979         if (ch < ' ') {
3980           m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
3981         } else {
3982           m << ch;
3983         }
3984         break;
3985     }
3986   }
3987 
3988   return m.GetString();
3989 }
3990 
3991 // The following routines generate an JSON representation of a UnitTest
3992 // object.
3993 
3994 // Formats the given time in milliseconds as seconds.
3995 static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
3996   ::std::stringstream ss;
3997   ss << (static_cast<double>(ms) * 1e-3) << "s";
3998   return ss.str();
3999 }
4000 
4001 // Converts the given epoch time in milliseconds to a date string in the
4002 // RFC3339 format, without the timezone information.
4003 static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
4004   struct tm time_struct;
4005   if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
4006     return "";
4007   // YYYY-MM-DDThh:mm:ss
4008   return StreamableToString(time_struct.tm_year + 1900) + "-" +
4009       String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
4010       String::FormatIntWidth2(time_struct.tm_mday) + "T" +
4011       String::FormatIntWidth2(time_struct.tm_hour) + ":" +
4012       String::FormatIntWidth2(time_struct.tm_min) + ":" +
4013       String::FormatIntWidth2(time_struct.tm_sec) + "Z";
4014 }
4015 
4016 static inline std::string Indent(int width) {
4017   return std::string(width, ' ');
4018 }
4019 
4020 void JsonUnitTestResultPrinter::OutputJsonKey(
4021     std::ostream* stream,
4022     const std::string& element_name,
4023     const std::string& name,
4024     const std::string& value,
4025     const std::string& indent,
4026     bool comma) {
4027   const std::vector<std::string>& allowed_names =
4028       GetReservedAttributesForElement(element_name);
4029 
4030   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4031                    allowed_names.end())
4032       << "Key \"" << name << "\" is not allowed for value \"" << element_name
4033       << "\".";
4034 
4035   *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
4036   if (comma)
4037     *stream << ",\n";
4038 }
4039 
4040 void JsonUnitTestResultPrinter::OutputJsonKey(
4041     std::ostream* stream,
4042     const std::string& element_name,
4043     const std::string& name,
4044     int value,
4045     const std::string& indent,
4046     bool comma) {
4047   const std::vector<std::string>& allowed_names =
4048       GetReservedAttributesForElement(element_name);
4049 
4050   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4051                    allowed_names.end())
4052       << "Key \"" << name << "\" is not allowed for value \"" << element_name
4053       << "\".";
4054 
4055   *stream << indent << "\"" << name << "\": " << StreamableToString(value);
4056   if (comma)
4057     *stream << ",\n";
4058 }
4059 
4060 // Prints a JSON representation of a TestInfo object.
4061 void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
4062                                                    const char* test_case_name,
4063                                                    const TestInfo& test_info) {
4064   const TestResult& result = *test_info.result();
4065   const std::string kTestcase = "testcase";
4066   const std::string kIndent = Indent(10);
4067 
4068   *stream << Indent(8) << "{\n";
4069   OutputJsonKey(stream, kTestcase, "name", test_info.name(), kIndent);
4070 
4071   if (test_info.value_param() != NULL) {
4072     OutputJsonKey(stream, kTestcase, "value_param",
4073                   test_info.value_param(), kIndent);
4074   }
4075   if (test_info.type_param() != NULL) {
4076     OutputJsonKey(stream, kTestcase, "type_param", test_info.type_param(),
4077                   kIndent);
4078   }
4079   if (GTEST_FLAG(list_tests)) {
4080     OutputJsonKey(stream, kTestcase, "file", test_info.file(), kIndent);
4081     OutputJsonKey(stream, kTestcase, "line", test_info.line(), kIndent, false);
4082     *stream << "\n" << Indent(8) << "}";
4083     return;
4084   }
4085 
4086   OutputJsonKey(stream, kTestcase, "status",
4087                 test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
4088   OutputJsonKey(stream, kTestcase, "time",
4089                 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
4090   OutputJsonKey(stream, kTestcase, "classname", test_case_name, kIndent, false);
4091   *stream << TestPropertiesAsJson(result, kIndent);
4092 
4093   int failures = 0;
4094   for (int i = 0; i < result.total_part_count(); ++i) {
4095     const TestPartResult& part = result.GetTestPartResult(i);
4096     if (part.failed()) {
4097       *stream << ",\n";
4098       if (++failures == 1) {
4099         *stream << kIndent << "\"" << "failures" << "\": [\n";
4100       }
4101       const std::string location =
4102           internal::FormatCompilerIndependentFileLocation(part.file_name(),
4103                                                           part.line_number());
4104       const std::string message = EscapeJson(location + "\n" + part.message());
4105       *stream << kIndent << "  {\n"
4106               << kIndent << "    \"failure\": \"" << message << "\",\n"
4107               << kIndent << "    \"type\": \"\"\n"
4108               << kIndent << "  }";
4109     }
4110   }
4111 
4112   if (failures > 0)
4113     *stream << "\n" << kIndent << "]";
4114   *stream << "\n" << Indent(8) << "}";
4115 }
4116 
4117 // Prints an JSON representation of a TestCase object
4118 void JsonUnitTestResultPrinter::PrintJsonTestCase(std::ostream* stream,
4119                                                   const TestCase& test_case) {
4120   const std::string kTestsuite = "testsuite";
4121   const std::string kIndent = Indent(6);
4122 
4123   *stream << Indent(4) << "{\n";
4124   OutputJsonKey(stream, kTestsuite, "name", test_case.name(), kIndent);
4125   OutputJsonKey(stream, kTestsuite, "tests", test_case.reportable_test_count(),
4126                 kIndent);
4127   if (!GTEST_FLAG(list_tests)) {
4128     OutputJsonKey(stream, kTestsuite, "failures", test_case.failed_test_count(),
4129                   kIndent);
4130     OutputJsonKey(stream, kTestsuite, "disabled",
4131                   test_case.reportable_disabled_test_count(), kIndent);
4132     OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
4133     OutputJsonKey(stream, kTestsuite, "time",
4134                   FormatTimeInMillisAsDuration(test_case.elapsed_time()),
4135                   kIndent, false);
4136     *stream << TestPropertiesAsJson(test_case.ad_hoc_test_result(), kIndent)
4137             << ",\n";
4138   }
4139 
4140   *stream << kIndent << "\"" << kTestsuite << "\": [\n";
4141 
4142   bool comma = false;
4143   for (int i = 0; i < test_case.total_test_count(); ++i) {
4144     if (test_case.GetTestInfo(i)->is_reportable()) {
4145       if (comma) {
4146         *stream << ",\n";
4147       } else {
4148         comma = true;
4149       }
4150       OutputJsonTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
4151     }
4152   }
4153   *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
4154 }
4155 
4156 // Prints a JSON summary of unit_test to output stream out.
4157 void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
4158                                                   const UnitTest& unit_test) {
4159   const std::string kTestsuites = "testsuites";
4160   const std::string kIndent = Indent(2);
4161   *stream << "{\n";
4162 
4163   OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
4164                 kIndent);
4165   OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
4166                 kIndent);
4167   OutputJsonKey(stream, kTestsuites, "disabled",
4168                 unit_test.reportable_disabled_test_count(), kIndent);
4169   OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
4170   if (GTEST_FLAG(shuffle)) {
4171     OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
4172                   kIndent);
4173   }
4174   OutputJsonKey(stream, kTestsuites, "timestamp",
4175                 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
4176                 kIndent);
4177   OutputJsonKey(stream, kTestsuites, "time",
4178                 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
4179                 false);
4180 
4181   *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
4182           << ",\n";
4183 
4184   OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
4185   *stream << kIndent << "\"" << kTestsuites << "\": [\n";
4186 
4187   bool comma = false;
4188   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4189     if (unit_test.GetTestCase(i)->reportable_test_count() > 0) {
4190       if (comma) {
4191         *stream << ",\n";
4192       } else {
4193         comma = true;
4194       }
4195       PrintJsonTestCase(stream, *unit_test.GetTestCase(i));
4196     }
4197   }
4198 
4199   *stream << "\n" << kIndent << "]\n" << "}\n";
4200 }
4201 
4202 void JsonUnitTestResultPrinter::PrintJsonTestList(
4203     std::ostream* stream, const std::vector<TestCase*>& test_cases) {
4204   const std::string kTestsuites = "testsuites";
4205   const std::string kIndent = Indent(2);
4206   *stream << "{\n";
4207   int total_tests = 0;
4208   for (size_t i = 0; i < test_cases.size(); ++i) {
4209     total_tests += test_cases[i]->total_test_count();
4210   }
4211   OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
4212 
4213   OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
4214   *stream << kIndent << "\"" << kTestsuites << "\": [\n";
4215 
4216   for (size_t i = 0; i < test_cases.size(); ++i) {
4217     if (i != 0) {
4218       *stream << ",\n";
4219     }
4220     PrintJsonTestCase(stream, *test_cases[i]);
4221   }
4222 
4223   *stream << "\n"
4224           << kIndent << "]\n"
4225           << "}\n";
4226 }
4227 // Produces a string representing the test properties in a result as
4228 // a JSON dictionary.
4229 std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
4230     const TestResult& result, const std::string& indent) {
4231   Message attributes;
4232   for (int i = 0; i < result.test_property_count(); ++i) {
4233     const TestProperty& property = result.GetTestProperty(i);
4234     attributes << ",\n" << indent << "\"" << property.key() << "\": "
4235                << "\"" << EscapeJson(property.value()) << "\"";
4236   }
4237   return attributes.GetString();
4238 }
4239 
4240 // End JsonUnitTestResultPrinter
4241 
4242 #if GTEST_CAN_STREAM_RESULTS_
4243 
4244 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4245 // replaces them by "%xx" where xx is their hexadecimal value. For
4246 // example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
4247 // in both time and space -- important as the input str may contain an
4248 // arbitrarily long test failure message and stack trace.
4249 std::string StreamingListener::UrlEncode(const char* str) {
4250   std::string result;
4251   result.reserve(strlen(str) + 1);
4252   for (char ch = *str; ch != '\0'; ch = *++str) {
4253     switch (ch) {
4254       case '%':
4255       case '=':
4256       case '&':
4257       case '\n':
4258         result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
4259         break;
4260       default:
4261         result.push_back(ch);
4262         break;
4263     }
4264   }
4265   return result;
4266 }
4267 
4268 void StreamingListener::SocketWriter::MakeConnection() {
4269   GTEST_CHECK_(sockfd_ == -1)
4270       << "MakeConnection() can't be called when there is already a connection.";
4271 
4272   addrinfo hints;
4273   memset(&hints, 0, sizeof(hints));
4274   hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
4275   hints.ai_socktype = SOCK_STREAM;
4276   addrinfo* servinfo = NULL;
4277 
4278   // Use the getaddrinfo() to get a linked list of IP addresses for
4279   // the given host name.
4280   const int error_num = getaddrinfo(
4281       host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4282   if (error_num != 0) {
4283     GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
4284                         << gai_strerror(error_num);
4285   }
4286 
4287   // Loop through all the results and connect to the first we can.
4288   for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
4289        cur_addr = cur_addr->ai_next) {
4290     sockfd_ = socket(
4291         cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
4292     if (sockfd_ != -1) {
4293       // Connect the client socket to the server socket.
4294       if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4295         close(sockfd_);
4296         sockfd_ = -1;
4297       }
4298     }
4299   }
4300 
4301   freeaddrinfo(servinfo);  // all done with this structure
4302 
4303   if (sockfd_ == -1) {
4304     GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
4305                         << host_name_ << ":" << port_num_;
4306   }
4307 }
4308 
4309 // End of class Streaming Listener
4310 #endif  // GTEST_CAN_STREAM_RESULTS__
4311 
4312 // class OsStackTraceGetter
4313 
4314 const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
4315     "... " GTEST_NAME_ " internal frames ...";
4316 
4317 std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
4318     GTEST_LOCK_EXCLUDED_(mutex_) {
4319 #if GTEST_HAS_ABSL
4320   std::string result;
4321 
4322   if (max_depth <= 0) {
4323     return result;
4324   }
4325 
4326   max_depth = std::min(max_depth, kMaxStackTraceDepth);
4327 
4328   std::vector<void*> raw_stack(max_depth);
4329   // Skips the frames requested by the caller, plus this function.
4330   const int raw_stack_size =
4331       absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
4332 
4333   void* caller_frame = nullptr;
4334   {
4335     MutexLock lock(&mutex_);
4336     caller_frame = caller_frame_;
4337   }
4338 
4339   for (int i = 0; i < raw_stack_size; ++i) {
4340     if (raw_stack[i] == caller_frame &&
4341         !GTEST_FLAG(show_internal_stack_frames)) {
4342       // Add a marker to the trace and stop adding frames.
4343       absl::StrAppend(&result, kElidedFramesMarker, "\n");
4344       break;
4345     }
4346 
4347     char tmp[1024];
4348     const char* symbol = "(unknown)";
4349     if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
4350       symbol = tmp;
4351     }
4352 
4353     char line[1024];
4354     snprintf(line, sizeof(line), "  %p: %s\n", raw_stack[i], symbol);
4355     result += line;
4356   }
4357 
4358   return result;
4359 
4360 #else  // !GTEST_HAS_ABSL
4361   static_cast<void>(max_depth);
4362   static_cast<void>(skip_count);
4363   return "";
4364 #endif  // GTEST_HAS_ABSL
4365 }
4366 
4367 void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
4368 #if GTEST_HAS_ABSL
4369   void* caller_frame = nullptr;
4370   if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
4371     caller_frame = nullptr;
4372   }
4373 
4374   MutexLock lock(&mutex_);
4375   caller_frame_ = caller_frame;
4376 #endif  // GTEST_HAS_ABSL
4377 }
4378 
4379 // A helper class that creates the premature-exit file in its
4380 // constructor and deletes the file in its destructor.
4381 class ScopedPrematureExitFile {
4382  public:
4383   explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
4384       : premature_exit_filepath_(premature_exit_filepath ?
4385                                  premature_exit_filepath : "") {
4386     // If a path to the premature-exit file is specified...
4387     if (!premature_exit_filepath_.empty()) {
4388       // create the file with a single "0" character in it.  I/O
4389       // errors are ignored as there's nothing better we can do and we
4390       // don't want to fail the test because of this.
4391       FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
4392       size_t cnt= fwrite("0", 1, 1, pfile);
4393       assert(cnt == (size_t)1);
4394       fclose(pfile);
4395     }
4396   }
4397 
4398   ~ScopedPrematureExitFile() {
4399     if (!premature_exit_filepath_.empty()) {
4400       int retval = remove(premature_exit_filepath_.c_str());
4401       if (retval) {
4402         GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
4403                           << premature_exit_filepath_ << "\" with error "
4404                           << retval;
4405       }
4406     }
4407   }
4408 
4409  private:
4410   const std::string premature_exit_filepath_;
4411 
4412   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
4413 };
4414 
4415 }  // namespace internal
4416 
4417 // class TestEventListeners
4418 
4419 TestEventListeners::TestEventListeners()
4420     : repeater_(new internal::TestEventRepeater()),
4421       default_result_printer_(NULL),
4422       default_xml_generator_(NULL) {
4423 }
4424 
4425 TestEventListeners::~TestEventListeners() { delete repeater_; }
4426 
4427 // Returns the standard listener responsible for the default console
4428 // output.  Can be removed from the listeners list to shut down default
4429 // console output.  Note that removing this object from the listener list
4430 // with Release transfers its ownership to the user.
4431 void TestEventListeners::Append(TestEventListener* listener) {
4432   repeater_->Append(listener);
4433 }
4434 
4435 // Removes the given event listener from the list and returns it.  It then
4436 // becomes the caller's responsibility to delete the listener. Returns
4437 // NULL if the listener is not found in the list.
4438 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
4439   if (listener == default_result_printer_)
4440     default_result_printer_ = NULL;
4441   else if (listener == default_xml_generator_)
4442     default_xml_generator_ = NULL;
4443   return repeater_->Release(listener);
4444 }
4445 
4446 // Returns repeater that broadcasts the TestEventListener events to all
4447 // subscribers.
4448 TestEventListener* TestEventListeners::repeater() { return repeater_; }
4449 
4450 // Sets the default_result_printer attribute to the provided listener.
4451 // The listener is also added to the listener list and previous
4452 // default_result_printer is removed from it and deleted. The listener can
4453 // also be NULL in which case it will not be added to the list. Does
4454 // nothing if the previous and the current listener objects are the same.
4455 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
4456   if (default_result_printer_ != listener) {
4457     // It is an error to pass this method a listener that is already in the
4458     // list.
4459     delete Release(default_result_printer_);
4460     default_result_printer_ = listener;
4461     if (listener != NULL)
4462       Append(listener);
4463   }
4464 }
4465 
4466 // Sets the default_xml_generator attribute to the provided listener.  The
4467 // listener is also added to the listener list and previous
4468 // default_xml_generator is removed from it and deleted. The listener can
4469 // also be NULL in which case it will not be added to the list. Does
4470 // nothing if the previous and the current listener objects are the same.
4471 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
4472   if (default_xml_generator_ != listener) {
4473     // It is an error to pass this method a listener that is already in the
4474     // list.
4475     delete Release(default_xml_generator_);
4476     default_xml_generator_ = listener;
4477     if (listener != NULL)
4478       Append(listener);
4479   }
4480 }
4481 
4482 // Controls whether events will be forwarded by the repeater to the
4483 // listeners in the list.
4484 bool TestEventListeners::EventForwardingEnabled() const {
4485   return repeater_->forwarding_enabled();
4486 }
4487 
4488 void TestEventListeners::SuppressEventForwarding() {
4489   repeater_->set_forwarding_enabled(false);
4490 }
4491 
4492 // class UnitTest
4493 
4494 // Gets the singleton UnitTest object.  The first time this method is
4495 // called, a UnitTest object is constructed and returned.  Consecutive
4496 // calls will return the same object.
4497 //
4498 // We don't protect this under mutex_ as a user is not supposed to
4499 // call this before main() starts, from which point on the return
4500 // value will never change.
4501 UnitTest* UnitTest::GetInstance() {
4502   // When compiled with MSVC 7.1 in optimized mode, destroying the
4503   // UnitTest object upon exiting the program messes up the exit code,
4504   // causing successful tests to appear failed.  We have to use a
4505   // different implementation in this case to bypass the compiler bug.
4506   // This implementation makes the compiler happy, at the cost of
4507   // leaking the UnitTest object.
4508 
4509   // CodeGear C++Builder insists on a public destructor for the
4510   // default implementation.  Use this implementation to keep good OO
4511   // design with private destructor.
4512 
4513 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4514   static UnitTest* const instance = new UnitTest;
4515   return instance;
4516 #else
4517   static UnitTest instance;
4518   return &instance;
4519 #endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4520 }
4521 
4522 // Gets the number of successful test cases.
4523 int UnitTest::successful_test_case_count() const {
4524   return impl()->successful_test_case_count();
4525 }
4526 
4527 // Gets the number of failed test cases.
4528 int UnitTest::failed_test_case_count() const {
4529   return impl()->failed_test_case_count();
4530 }
4531 
4532 // Gets the number of all test cases.
4533 int UnitTest::total_test_case_count() const {
4534   return impl()->total_test_case_count();
4535 }
4536 
4537 // Gets the number of all test cases that contain at least one test
4538 // that should run.
4539 int UnitTest::test_case_to_run_count() const {
4540   return impl()->test_case_to_run_count();
4541 }
4542 
4543 // Gets the number of successful tests.
4544 int UnitTest::successful_test_count() const {
4545   return impl()->successful_test_count();
4546 }
4547 
4548 // Gets the number of failed tests.
4549 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
4550 
4551 // Gets the number of disabled tests that will be reported in the XML report.
4552 int UnitTest::reportable_disabled_test_count() const {
4553   return impl()->reportable_disabled_test_count();
4554 }
4555 
4556 // Gets the number of disabled tests.
4557 int UnitTest::disabled_test_count() const {
4558   return impl()->disabled_test_count();
4559 }
4560 
4561 // Gets the number of tests to be printed in the XML report.
4562 int UnitTest::reportable_test_count() const {
4563   return impl()->reportable_test_count();
4564 }
4565 
4566 // Gets the number of all tests.
4567 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
4568 
4569 // Gets the number of tests that should run.
4570 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
4571 
4572 // Gets the time of the test program start, in ms from the start of the
4573 // UNIX epoch.
4574 internal::TimeInMillis UnitTest::start_timestamp() const {
4575     return impl()->start_timestamp();
4576 }
4577 
4578 // Gets the elapsed time, in milliseconds.
4579 internal::TimeInMillis UnitTest::elapsed_time() const {
4580   return impl()->elapsed_time();
4581 }
4582 
4583 // Returns true iff the unit test passed (i.e. all test cases passed).
4584 bool UnitTest::Passed() const { return impl()->Passed(); }
4585 
4586 // Returns true iff the unit test failed (i.e. some test case failed
4587 // or something outside of all tests failed).
4588 bool UnitTest::Failed() const { return impl()->Failed(); }
4589 
4590 // Gets the i-th test case among all the test cases. i can range from 0 to
4591 // total_test_case_count() - 1. If i is not in that range, returns NULL.
4592 const TestCase* UnitTest::GetTestCase(int i) const {
4593   return impl()->GetTestCase(i);
4594 }
4595 
4596 // Returns the TestResult containing information on test failures and
4597 // properties logged outside of individual test cases.
4598 const TestResult& UnitTest::ad_hoc_test_result() const {
4599   return *impl()->ad_hoc_test_result();
4600 }
4601 
4602 // Gets the i-th test case among all the test cases. i can range from 0 to
4603 // total_test_case_count() - 1. If i is not in that range, returns NULL.
4604 TestCase* UnitTest::GetMutableTestCase(int i) {
4605   return impl()->GetMutableTestCase(i);
4606 }
4607 
4608 // Returns the list of event listeners that can be used to track events
4609 // inside Google Test.
4610 TestEventListeners& UnitTest::listeners() {
4611   return *impl()->listeners();
4612 }
4613 
4614 // Registers and returns a global test environment.  When a test
4615 // program is run, all global test environments will be set-up in the
4616 // order they were registered.  After all tests in the program have
4617 // finished, all global test environments will be torn-down in the
4618 // *reverse* order they were registered.
4619 //
4620 // The UnitTest object takes ownership of the given environment.
4621 //
4622 // We don't protect this under mutex_, as we only support calling it
4623 // from the main thread.
4624 Environment* UnitTest::AddEnvironment(Environment* env) {
4625   if (env == NULL) {
4626     return NULL;
4627   }
4628 
4629   impl_->environments().push_back(env);
4630   return env;
4631 }
4632 
4633 // Adds a TestPartResult to the current TestResult object.  All Google Test
4634 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
4635 // this to report their results.  The user code should use the
4636 // assertion macros instead of calling this directly.
4637 void UnitTest::AddTestPartResult(
4638     TestPartResult::Type result_type,
4639     const char* file_name,
4640     int line_number,
4641     const std::string& message,
4642     const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
4643   Message msg;
4644   msg << message;
4645 
4646   internal::MutexLock lock(&mutex_);
4647   if (impl_->gtest_trace_stack().size() > 0) {
4648     msg << "\n" << GTEST_NAME_ << " trace:";
4649 
4650     for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
4651          i > 0; --i) {
4652       const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
4653       msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
4654           << " " << trace.message;
4655     }
4656   }
4657 
4658   if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
4659     msg << internal::kStackTraceMarker << os_stack_trace;
4660   }
4661 
4662   const TestPartResult result =
4663     TestPartResult(result_type, file_name, line_number,
4664                    msg.GetString().c_str());
4665   impl_->GetTestPartResultReporterForCurrentThread()->
4666       ReportTestPartResult(result);
4667 
4668   if (result_type != TestPartResult::kSuccess) {
4669     // gtest_break_on_failure takes precedence over
4670     // gtest_throw_on_failure.  This allows a user to set the latter
4671     // in the code (perhaps in order to use Google Test assertions
4672     // with another testing framework) and specify the former on the
4673     // command line for debugging.
4674     if (GTEST_FLAG(break_on_failure)) {
4675 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4676       // Using DebugBreak on Windows allows gtest to still break into a debugger
4677       // when a failure happens and both the --gtest_break_on_failure and
4678       // the --gtest_catch_exceptions flags are specified.
4679       DebugBreak();
4680 #elif (!defined(__native_client__)) &&            \
4681     ((defined(__clang__) || defined(__GNUC__)) && \
4682      (defined(__x86_64__) || defined(__i386__)))
4683       // with clang/gcc we can achieve the same effect on x86 by invoking int3
4684       asm("int3");
4685 #else
4686       // Dereference NULL through a volatile pointer to prevent the compiler
4687       // from removing. We use this rather than abort() or __builtin_trap() for
4688       // portability: Symbian doesn't implement abort() well, and some debuggers
4689       // don't correctly trap abort().
4690       *static_cast<volatile int*>(NULL) = 1;
4691 #endif  // GTEST_OS_WINDOWS
4692     } else if (GTEST_FLAG(throw_on_failure)) {
4693 #if GTEST_HAS_EXCEPTIONS
4694       throw internal::GoogleTestFailureException(result);
4695 #else
4696       // We cannot call abort() as it generates a pop-up in debug mode
4697       // that cannot be suppressed in VC 7.1 or below.
4698       exit(1);
4699 #endif
4700     }
4701   }
4702 }
4703 
4704 // Adds a TestProperty to the current TestResult object when invoked from
4705 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
4706 // from SetUpTestCase or TearDownTestCase, or to the global property set
4707 // when invoked elsewhere.  If the result already contains a property with
4708 // the same key, the value will be updated.
4709 void UnitTest::RecordProperty(const std::string& key,
4710                               const std::string& value) {
4711   impl_->RecordProperty(TestProperty(key, value));
4712 }
4713 
4714 // Runs all tests in this UnitTest object and prints the result.
4715 // Returns 0 if successful, or 1 otherwise.
4716 //
4717 // We don't protect this under mutex_, as we only support calling it
4718 // from the main thread.
4719 int UnitTest::Run() {
4720   const bool in_death_test_child_process =
4721       internal::GTEST_FLAG(internal_run_death_test).length() > 0;
4722 
4723   // Google Test implements this protocol for catching that a test
4724   // program exits before returning control to Google Test:
4725   //
4726   //   1. Upon start, Google Test creates a file whose absolute path
4727   //      is specified by the environment variable
4728   //      TEST_PREMATURE_EXIT_FILE.
4729   //   2. When Google Test has finished its work, it deletes the file.
4730   //
4731   // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
4732   // running a Google-Test-based test program and check the existence
4733   // of the file at the end of the test execution to see if it has
4734   // exited prematurely.
4735 
4736   // If we are in the child process of a death test, don't
4737   // create/delete the premature exit file, as doing so is unnecessary
4738   // and will confuse the parent process.  Otherwise, create/delete
4739   // the file upon entering/leaving this function.  If the program
4740   // somehow exits before this function has a chance to return, the
4741   // premature-exit file will be left undeleted, causing a test runner
4742   // that understands the premature-exit-file protocol to report the
4743   // test as having failed.
4744   const internal::ScopedPrematureExitFile premature_exit_file(
4745       in_death_test_child_process ?
4746       NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
4747 
4748   // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
4749   // used for the duration of the program.
4750   impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
4751 
4752 #if GTEST_OS_WINDOWS
4753   // Either the user wants Google Test to catch exceptions thrown by the
4754   // tests or this is executing in the context of death test child
4755   // process. In either case the user does not want to see pop-up dialogs
4756   // about crashes - they are expected.
4757   if (impl()->catch_exceptions() || in_death_test_child_process) {
4758 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4759     // SetErrorMode doesn't exist on CE.
4760     SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
4761                  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
4762 # endif  // !GTEST_OS_WINDOWS_MOBILE
4763 
4764 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
4765     // Death test children can be terminated with _abort().  On Windows,
4766     // _abort() can show a dialog with a warning message.  This forces the
4767     // abort message to go to stderr instead.
4768     _set_error_mode(_OUT_TO_STDERR);
4769 # endif
4770 
4771 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
4772     // In the debug version, Visual Studio pops up a separate dialog
4773     // offering a choice to debug the aborted program. We need to suppress
4774     // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
4775     // executed. Google Test will notify the user of any unexpected
4776     // failure via stderr.
4777     //
4778     // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
4779     // Users of prior VC versions shall suffer the agony and pain of
4780     // clicking through the countless debug dialogs.
4781     // FIXME: find a way to suppress the abort dialog() in the
4782     // debug mode when compiled with VC 7.1 or lower.
4783     if (!GTEST_FLAG(break_on_failure))
4784       _set_abort_behavior(
4785           0x0,                                    // Clear the following flags:
4786           _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
4787 # endif
4788   }
4789 #endif  // GTEST_OS_WINDOWS
4790 
4791   return internal::HandleExceptionsInMethodIfSupported(
4792       impl(),
4793       &internal::UnitTestImpl::RunAllTests,
4794       "auxiliary test code (environments or event listeners)") ? 0 : 1;
4795 }
4796 
4797 // Returns the working directory when the first TEST() or TEST_F() was
4798 // executed.
4799 const char* UnitTest::original_working_dir() const {
4800   return impl_->original_working_dir_.c_str();
4801 }
4802 
4803 // Returns the TestCase object for the test that's currently running,
4804 // or NULL if no test is running.
4805 const TestCase* UnitTest::current_test_case() const
4806     GTEST_LOCK_EXCLUDED_(mutex_) {
4807   internal::MutexLock lock(&mutex_);
4808   return impl_->current_test_case();
4809 }
4810 
4811 // Returns the TestInfo object for the test that's currently running,
4812 // or NULL if no test is running.
4813 const TestInfo* UnitTest::current_test_info() const
4814     GTEST_LOCK_EXCLUDED_(mutex_) {
4815   internal::MutexLock lock(&mutex_);
4816   return impl_->current_test_info();
4817 }
4818 
4819 // Returns the random seed used at the start of the current test run.
4820 int UnitTest::random_seed() const { return impl_->random_seed(); }
4821 
4822 // Returns ParameterizedTestCaseRegistry object used to keep track of
4823 // value-parameterized tests and instantiate and register them.
4824 internal::ParameterizedTestCaseRegistry&
4825     UnitTest::parameterized_test_registry()
4826         GTEST_LOCK_EXCLUDED_(mutex_) {
4827   return impl_->parameterized_test_registry();
4828 }
4829 
4830 // Creates an empty UnitTest.
4831 UnitTest::UnitTest() {
4832   impl_ = new internal::UnitTestImpl(this);
4833 }
4834 
4835 // Destructor of UnitTest.
4836 UnitTest::~UnitTest() {
4837   delete impl_;
4838 }
4839 
4840 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
4841 // Google Test trace stack.
4842 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
4843     GTEST_LOCK_EXCLUDED_(mutex_) {
4844   internal::MutexLock lock(&mutex_);
4845   impl_->gtest_trace_stack().push_back(trace);
4846 }
4847 
4848 // Pops a trace from the per-thread Google Test trace stack.
4849 void UnitTest::PopGTestTrace()
4850     GTEST_LOCK_EXCLUDED_(mutex_) {
4851   internal::MutexLock lock(&mutex_);
4852   impl_->gtest_trace_stack().pop_back();
4853 }
4854 
4855 namespace internal {
4856 
4857 UnitTestImpl::UnitTestImpl(UnitTest* parent)
4858     : parent_(parent),
4859       GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
4860       default_global_test_part_result_reporter_(this),
4861       default_per_thread_test_part_result_reporter_(this),
4862       GTEST_DISABLE_MSC_WARNINGS_POP_()
4863       global_test_part_result_repoter_(
4864           &default_global_test_part_result_reporter_),
4865       per_thread_test_part_result_reporter_(
4866           &default_per_thread_test_part_result_reporter_),
4867       parameterized_test_registry_(),
4868       parameterized_tests_registered_(false),
4869       last_death_test_case_(-1),
4870       current_test_case_(NULL),
4871       current_test_info_(NULL),
4872       ad_hoc_test_result_(),
4873       os_stack_trace_getter_(NULL),
4874       post_flag_parse_init_performed_(false),
4875       random_seed_(0),  // Will be overridden by the flag before first use.
4876       random_(0),  // Will be reseeded before first use.
4877       start_timestamp_(0),
4878       elapsed_time_(0),
4879 #if GTEST_HAS_DEATH_TEST
4880       death_test_factory_(new DefaultDeathTestFactory),
4881 #endif
4882       // Will be overridden by the flag before first use.
4883       catch_exceptions_(false) {
4884   listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
4885 }
4886 
4887 UnitTestImpl::~UnitTestImpl() {
4888   // Deletes every TestCase.
4889   ForEach(test_cases_, internal::Delete<TestCase>);
4890 
4891   // Deletes every Environment.
4892   ForEach(environments_, internal::Delete<Environment>);
4893 
4894   delete os_stack_trace_getter_;
4895 }
4896 
4897 // Adds a TestProperty to the current TestResult object when invoked in a
4898 // context of a test, to current test case's ad_hoc_test_result when invoke
4899 // from SetUpTestCase/TearDownTestCase, or to the global property set
4900 // otherwise.  If the result already contains a property with the same key,
4901 // the value will be updated.
4902 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
4903   std::string xml_element;
4904   TestResult* test_result;  // TestResult appropriate for property recording.
4905 
4906   if (current_test_info_ != NULL) {
4907     xml_element = "testcase";
4908     test_result = &(current_test_info_->result_);
4909   } else if (current_test_case_ != NULL) {
4910     xml_element = "testsuite";
4911     test_result = &(current_test_case_->ad_hoc_test_result_);
4912   } else {
4913     xml_element = "testsuites";
4914     test_result = &ad_hoc_test_result_;
4915   }
4916   test_result->RecordProperty(xml_element, test_property);
4917 }
4918 
4919 #if GTEST_HAS_DEATH_TEST
4920 // Disables event forwarding if the control is currently in a death test
4921 // subprocess. Must not be called before InitGoogleTest.
4922 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
4923   if (internal_run_death_test_flag_.get() != NULL)
4924     listeners()->SuppressEventForwarding();
4925 }
4926 #endif  // GTEST_HAS_DEATH_TEST
4927 
4928 // Initializes event listeners performing XML output as specified by
4929 // UnitTestOptions. Must not be called before InitGoogleTest.
4930 void UnitTestImpl::ConfigureXmlOutput() {
4931   const std::string& output_format = UnitTestOptions::GetOutputFormat();
4932   if (output_format == "xml") {
4933     listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
4934         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
4935   } else if (output_format == "json") {
4936     listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
4937         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
4938   } else if (output_format != "") {
4939     GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
4940                         << output_format << "\" ignored.";
4941   }
4942 }
4943 
4944 #if GTEST_CAN_STREAM_RESULTS_
4945 // Initializes event listeners for streaming test results in string form.
4946 // Must not be called before InitGoogleTest.
4947 void UnitTestImpl::ConfigureStreamingOutput() {
4948   const std::string& target = GTEST_FLAG(stream_result_to);
4949   if (!target.empty()) {
4950     const size_t pos = target.find(':');
4951     if (pos != std::string::npos) {
4952       listeners()->Append(new StreamingListener(target.substr(0, pos),
4953                                                 target.substr(pos+1)));
4954     } else {
4955       GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
4956                           << "\" ignored.";
4957     }
4958   }
4959 }
4960 #endif  // GTEST_CAN_STREAM_RESULTS_
4961 
4962 // Performs initialization dependent upon flag values obtained in
4963 // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
4964 // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
4965 // this function is also called from RunAllTests.  Since this function can be
4966 // called more than once, it has to be idempotent.
4967 void UnitTestImpl::PostFlagParsingInit() {
4968   // Ensures that this function does not execute more than once.
4969   if (!post_flag_parse_init_performed_) {
4970     post_flag_parse_init_performed_ = true;
4971 
4972 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
4973     // Register to send notifications about key process state changes.
4974     listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
4975 #endif  // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
4976 
4977 #if GTEST_HAS_DEATH_TEST
4978     InitDeathTestSubprocessControlInfo();
4979     SuppressTestEventsIfInSubprocess();
4980 #endif  // GTEST_HAS_DEATH_TEST
4981 
4982     // Registers parameterized tests. This makes parameterized tests
4983     // available to the UnitTest reflection API without running
4984     // RUN_ALL_TESTS.
4985     RegisterParameterizedTests();
4986 
4987     // Configures listeners for XML output. This makes it possible for users
4988     // to shut down the default XML output before invoking RUN_ALL_TESTS.
4989     ConfigureXmlOutput();
4990 
4991 #if GTEST_CAN_STREAM_RESULTS_
4992     // Configures listeners for streaming test results to the specified server.
4993     ConfigureStreamingOutput();
4994 #endif  // GTEST_CAN_STREAM_RESULTS_
4995 
4996 #if GTEST_HAS_ABSL
4997     if (GTEST_FLAG(install_failure_signal_handler)) {
4998       absl::FailureSignalHandlerOptions options;
4999       absl::InstallFailureSignalHandler(options);
5000     }
5001 #endif  // GTEST_HAS_ABSL
5002   }
5003 }
5004 
5005 // A predicate that checks the name of a TestCase against a known
5006 // value.
5007 //
5008 // This is used for implementation of the UnitTest class only.  We put
5009 // it in the anonymous namespace to prevent polluting the outer
5010 // namespace.
5011 //
5012 // TestCaseNameIs is copyable.
5013 class TestCaseNameIs {
5014  public:
5015   // Constructor.
5016   explicit TestCaseNameIs(const std::string& name)
5017       : name_(name) {}
5018 
5019   // Returns true iff the name of test_case matches name_.
5020   bool operator()(const TestCase* test_case) const {
5021     return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5022   }
5023 
5024  private:
5025   std::string name_;
5026 };
5027 
5028 // Finds and returns a TestCase with the given name.  If one doesn't
5029 // exist, creates one and returns it.  It's the CALLER'S
5030 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5031 // TESTS ARE NOT SHUFFLED.
5032 //
5033 // Arguments:
5034 //
5035 //   test_case_name: name of the test case
5036 //   type_param:     the name of the test case's type parameter, or NULL if
5037 //                   this is not a typed or a type-parameterized test case.
5038 //   set_up_tc:      pointer to the function that sets up the test case
5039 //   tear_down_tc:   pointer to the function that tears down the test case
5040 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5041                                     const char* type_param,
5042                                     Test::SetUpTestCaseFunc set_up_tc,
5043                                     Test::TearDownTestCaseFunc tear_down_tc) {
5044   // Can we find a TestCase with the given name?
5045   const std::vector<TestCase*>::reverse_iterator test_case =
5046       std::find_if(test_cases_.rbegin(), test_cases_.rend(),
5047                    TestCaseNameIs(test_case_name));
5048 
5049   if (test_case != test_cases_.rend())
5050     return *test_case;
5051 
5052   // No.  Let's create one.
5053   TestCase* const new_test_case =
5054       new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5055 
5056   // Is this a death test case?
5057   if (internal::UnitTestOptions::MatchesFilter(test_case_name,
5058                                                kDeathTestCaseFilter)) {
5059     // Yes.  Inserts the test case after the last death test case
5060     // defined so far.  This only works when the test cases haven't
5061     // been shuffled.  Otherwise we may end up running a death test
5062     // after a non-death test.
5063     ++last_death_test_case_;
5064     test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5065                        new_test_case);
5066   } else {
5067     // No.  Appends to the end of the list.
5068     test_cases_.push_back(new_test_case);
5069   }
5070 
5071   test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5072   return new_test_case;
5073 }
5074 
5075 // Helpers for setting up / tearing down the given environment.  They
5076 // are for use in the ForEach() function.
5077 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5078 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5079 
5080 // Runs all tests in this UnitTest object, prints the result, and
5081 // returns true if all tests are successful.  If any exception is
5082 // thrown during a test, the test is considered to be failed, but the
5083 // rest of the tests will still be run.
5084 //
5085 // When parameterized tests are enabled, it expands and registers
5086 // parameterized tests first in RegisterParameterizedTests().
5087 // All other functions called from RunAllTests() may safely assume that
5088 // parameterized tests are ready to be counted and run.
5089 bool UnitTestImpl::RunAllTests() {
5090   // True iff Google Test is initialized before RUN_ALL_TESTS() is called.
5091   const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
5092 
5093   // Do not run any test if the --help flag was specified.
5094   if (g_help_flag)
5095     return true;
5096 
5097   // Repeats the call to the post-flag parsing initialization in case the
5098   // user didn't call InitGoogleTest.
5099   PostFlagParsingInit();
5100 
5101   // Even if sharding is not on, test runners may want to use the
5102   // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5103   // protocol.
5104   internal::WriteToShardStatusFileIfNeeded();
5105 
5106   // True iff we are in a subprocess for running a thread-safe-style
5107   // death test.
5108   bool in_subprocess_for_death_test = false;
5109 
5110 #if GTEST_HAS_DEATH_TEST
5111   in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5112 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5113   if (in_subprocess_for_death_test) {
5114     GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
5115   }
5116 # endif  // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5117 #endif  // GTEST_HAS_DEATH_TEST
5118 
5119   const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5120                                         in_subprocess_for_death_test);
5121 
5122   // Compares the full test names with the filter to decide which
5123   // tests to run.
5124   const bool has_tests_to_run = FilterTests(should_shard
5125                                               ? HONOR_SHARDING_PROTOCOL
5126                                               : IGNORE_SHARDING_PROTOCOL) > 0;
5127 
5128   // Lists the tests and exits if the --gtest_list_tests flag was specified.
5129   if (GTEST_FLAG(list_tests)) {
5130     // This must be called *after* FilterTests() has been called.
5131     ListTestsMatchingFilter();
5132     return true;
5133   }
5134 
5135   random_seed_ = GTEST_FLAG(shuffle) ?
5136       GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
5137 
5138   // True iff at least one test has failed.
5139   bool failed = false;
5140 
5141   TestEventListener* repeater = listeners()->repeater();
5142 
5143   start_timestamp_ = GetTimeInMillis();
5144   repeater->OnTestProgramStart(*parent_);
5145 
5146   // How many times to repeat the tests?  We don't want to repeat them
5147   // when we are inside the subprocess of a death test.
5148   const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
5149   // Repeats forever if the repeat count is negative.
5150   const bool forever = repeat < 0;
5151   for (int i = 0; forever || i != repeat; i++) {
5152     // We want to preserve failures generated by ad-hoc test
5153     // assertions executed before RUN_ALL_TESTS().
5154     ClearNonAdHocTestResult();
5155 
5156     const TimeInMillis start = GetTimeInMillis();
5157 
5158     // Shuffles test cases and tests if requested.
5159     if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5160       random()->Reseed(random_seed_);
5161       // This should be done before calling OnTestIterationStart(),
5162       // such that a test event listener can see the actual test order
5163       // in the event.
5164       ShuffleTests();
5165     }
5166 
5167     // Tells the unit test event listeners that the tests are about to start.
5168     repeater->OnTestIterationStart(*parent_, i);
5169 
5170     // Runs each test case if there is at least one test to run.
5171     if (has_tests_to_run) {
5172       // Sets up all environments beforehand.
5173       repeater->OnEnvironmentsSetUpStart(*parent_);
5174       ForEach(environments_, SetUpEnvironment);
5175       repeater->OnEnvironmentsSetUpEnd(*parent_);
5176 
5177       // Runs the tests only if there was no fatal failure during global
5178       // set-up.
5179       if (!Test::HasFatalFailure()) {
5180         for (int test_index = 0; test_index < total_test_case_count();
5181              test_index++) {
5182           GetMutableTestCase(test_index)->Run();
5183         }
5184       }
5185 
5186       // Tears down all environments in reverse order afterwards.
5187       repeater->OnEnvironmentsTearDownStart(*parent_);
5188       std::for_each(environments_.rbegin(), environments_.rend(),
5189                     TearDownEnvironment);
5190       repeater->OnEnvironmentsTearDownEnd(*parent_);
5191     }
5192 
5193     elapsed_time_ = GetTimeInMillis() - start;
5194 
5195     // Tells the unit test event listener that the tests have just finished.
5196     repeater->OnTestIterationEnd(*parent_, i);
5197 
5198     // Gets the result and clears it.
5199     if (!Passed()) {
5200       failed = true;
5201     }
5202 
5203     // Restores the original test order after the iteration.  This
5204     // allows the user to quickly repro a failure that happens in the
5205     // N-th iteration without repeating the first (N - 1) iterations.
5206     // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5207     // case the user somehow changes the value of the flag somewhere
5208     // (it's always safe to unshuffle the tests).
5209     UnshuffleTests();
5210 
5211     if (GTEST_FLAG(shuffle)) {
5212       // Picks a new random seed for each iteration.
5213       random_seed_ = GetNextRandomSeed(random_seed_);
5214     }
5215   }
5216 
5217   repeater->OnTestProgramEnd(*parent_);
5218 
5219   if (!gtest_is_initialized_before_run_all_tests) {
5220     ColoredPrintf(
5221         COLOR_RED,
5222         "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
5223         "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
5224         "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
5225         " will start to enforce the valid usage. "
5226         "Please fix it ASAP, or IT WILL START TO FAIL.\n");  // NOLINT
5227 #if GTEST_FOR_GOOGLE_
5228     ColoredPrintf(COLOR_RED,
5229                   "For more details, see http://wiki/Main/ValidGUnitMain.\n");
5230 #endif  // GTEST_FOR_GOOGLE_
5231   }
5232 
5233   return !failed;
5234 }
5235 
5236 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5237 // if the variable is present. If a file already exists at this location, this
5238 // function will write over it. If the variable is present, but the file cannot
5239 // be created, prints an error and exits.
5240 void WriteToShardStatusFileIfNeeded() {
5241   const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5242   if (test_shard_file != NULL) {
5243     FILE* const file = posix::FOpen(test_shard_file, "w");
5244     if (file == NULL) {
5245       ColoredPrintf(COLOR_RED,
5246                     "Could not write to the test shard status file \"%s\" "
5247                     "specified by the %s environment variable.\n",
5248                     test_shard_file, kTestShardStatusFile);
5249       fflush(stdout);
5250       exit(EXIT_FAILURE);
5251     }
5252     fclose(file);
5253   }
5254 }
5255 
5256 // Checks whether sharding is enabled by examining the relevant
5257 // environment variable values. If the variables are present,
5258 // but inconsistent (i.e., shard_index >= total_shards), prints
5259 // an error and exits. If in_subprocess_for_death_test, sharding is
5260 // disabled because it must only be applied to the original test
5261 // process. Otherwise, we could filter out death tests we intended to execute.
5262 bool ShouldShard(const char* total_shards_env,
5263                  const char* shard_index_env,
5264                  bool in_subprocess_for_death_test) {
5265   if (in_subprocess_for_death_test) {
5266     return false;
5267   }
5268 
5269   const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5270   const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5271 
5272   if (total_shards == -1 && shard_index == -1) {
5273     return false;
5274   } else if (total_shards == -1 && shard_index != -1) {
5275     const Message msg = Message()
5276       << "Invalid environment variables: you have "
5277       << kTestShardIndex << " = " << shard_index
5278       << ", but have left " << kTestTotalShards << " unset.\n";
5279     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5280     fflush(stdout);
5281     exit(EXIT_FAILURE);
5282   } else if (total_shards != -1 && shard_index == -1) {
5283     const Message msg = Message()
5284       << "Invalid environment variables: you have "
5285       << kTestTotalShards << " = " << total_shards
5286       << ", but have left " << kTestShardIndex << " unset.\n";
5287     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5288     fflush(stdout);
5289     exit(EXIT_FAILURE);
5290   } else if (shard_index < 0 || shard_index >= total_shards) {
5291     const Message msg = Message()
5292       << "Invalid environment variables: we require 0 <= "
5293       << kTestShardIndex << " < " << kTestTotalShards
5294       << ", but you have " << kTestShardIndex << "=" << shard_index
5295       << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5296     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5297     fflush(stdout);
5298     exit(EXIT_FAILURE);
5299   }
5300 
5301   return total_shards > 1;
5302 }
5303 
5304 // Parses the environment variable var as an Int32. If it is unset,
5305 // returns default_val. If it is not an Int32, prints an error
5306 // and aborts.
5307 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
5308   const char* str_val = posix::GetEnv(var);
5309   if (str_val == NULL) {
5310     return default_val;
5311   }
5312 
5313   Int32 result;
5314   if (!ParseInt32(Message() << "The value of environment variable " << var,
5315                   str_val, &result)) {
5316     exit(EXIT_FAILURE);
5317   }
5318   return result;
5319 }
5320 
5321 // Given the total number of shards, the shard index, and the test id,
5322 // returns true iff the test should be run on this shard. The test id is
5323 // some arbitrary but unique non-negative integer assigned to each test
5324 // method. Assumes that 0 <= shard_index < total_shards.
5325 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
5326   return (test_id % total_shards) == shard_index;
5327 }
5328 
5329 // Compares the name of each test with the user-specified filter to
5330 // decide whether the test should be run, then records the result in
5331 // each TestCase and TestInfo object.
5332 // If shard_tests == true, further filters tests based on sharding
5333 // variables in the environment - see
5334 // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
5335 // . Returns the number of tests that should run.
5336 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
5337   const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
5338       Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
5339   const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
5340       Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
5341 
5342   // num_runnable_tests are the number of tests that will
5343   // run across all shards (i.e., match filter and are not disabled).
5344   // num_selected_tests are the number of tests to be run on
5345   // this shard.
5346   int num_runnable_tests = 0;
5347   int num_selected_tests = 0;
5348   for (size_t i = 0; i < test_cases_.size(); i++) {
5349     TestCase* const test_case = test_cases_[i];
5350     const std::string &test_case_name = test_case->name();
5351     test_case->set_should_run(false);
5352 
5353     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5354       TestInfo* const test_info = test_case->test_info_list()[j];
5355       const std::string test_name(test_info->name());
5356       // A test is disabled if test case name or test name matches
5357       // kDisableTestFilter.
5358       const bool is_disabled =
5359           internal::UnitTestOptions::MatchesFilter(test_case_name,
5360                                                    kDisableTestFilter) ||
5361           internal::UnitTestOptions::MatchesFilter(test_name,
5362                                                    kDisableTestFilter);
5363       test_info->is_disabled_ = is_disabled;
5364 
5365       const bool matches_filter =
5366           internal::UnitTestOptions::FilterMatchesTest(test_case_name,
5367                                                        test_name);
5368       test_info->matches_filter_ = matches_filter;
5369 
5370       const bool is_runnable =
5371           (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5372           matches_filter;
5373 
5374       const bool is_in_another_shard =
5375           shard_tests != IGNORE_SHARDING_PROTOCOL &&
5376           !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
5377       test_info->is_in_another_shard_ = is_in_another_shard;
5378       const bool is_selected = is_runnable && !is_in_another_shard;
5379 
5380       num_runnable_tests += is_runnable;
5381       num_selected_tests += is_selected;
5382 
5383       test_info->should_run_ = is_selected;
5384       test_case->set_should_run(test_case->should_run() || is_selected);
5385     }
5386   }
5387   return num_selected_tests;
5388 }
5389 
5390 // Prints the given C-string on a single line by replacing all '\n'
5391 // characters with string "\\n".  If the output takes more than
5392 // max_length characters, only prints the first max_length characters
5393 // and "...".
5394 static void PrintOnOneLine(const char* str, int max_length) {
5395   if (str != NULL) {
5396     for (int i = 0; *str != '\0'; ++str) {
5397       if (i >= max_length) {
5398         printf("...");
5399         break;
5400       }
5401       if (*str == '\n') {
5402         printf("\\n");
5403         i += 2;
5404       } else {
5405         printf("%c", *str);
5406         ++i;
5407       }
5408     }
5409   }
5410 }
5411 
5412 // Prints the names of the tests matching the user-specified filter flag.
5413 void UnitTestImpl::ListTestsMatchingFilter() {
5414   // Print at most this many characters for each type/value parameter.
5415   const int kMaxParamLength = 250;
5416 
5417   for (size_t i = 0; i < test_cases_.size(); i++) {
5418     const TestCase* const test_case = test_cases_[i];
5419     bool printed_test_case_name = false;
5420 
5421     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5422       const TestInfo* const test_info =
5423           test_case->test_info_list()[j];
5424       if (test_info->matches_filter_) {
5425         if (!printed_test_case_name) {
5426           printed_test_case_name = true;
5427           printf("%s.", test_case->name());
5428           if (test_case->type_param() != NULL) {
5429             printf("  # %s = ", kTypeParamLabel);
5430             // We print the type parameter on a single line to make
5431             // the output easy to parse by a program.
5432             PrintOnOneLine(test_case->type_param(), kMaxParamLength);
5433           }
5434           printf("\n");
5435         }
5436         printf("  %s", test_info->name());
5437         if (test_info->value_param() != NULL) {
5438           printf("  # %s = ", kValueParamLabel);
5439           // We print the value parameter on a single line to make the
5440           // output easy to parse by a program.
5441           PrintOnOneLine(test_info->value_param(), kMaxParamLength);
5442         }
5443         printf("\n");
5444       }
5445     }
5446   }
5447   fflush(stdout);
5448   const std::string& output_format = UnitTestOptions::GetOutputFormat();
5449   if (output_format == "xml" || output_format == "json") {
5450     FILE* fileout = OpenFileForWriting(
5451         UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
5452     std::stringstream stream;
5453     if (output_format == "xml") {
5454       XmlUnitTestResultPrinter(
5455           UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
5456           .PrintXmlTestsList(&stream, test_cases_);
5457     } else if (output_format == "json") {
5458       JsonUnitTestResultPrinter(
5459           UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
5460           .PrintJsonTestList(&stream, test_cases_);
5461     }
5462     fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
5463     fclose(fileout);
5464   }
5465 }
5466 
5467 // Sets the OS stack trace getter.
5468 //
5469 // Does nothing if the input and the current OS stack trace getter are
5470 // the same; otherwise, deletes the old getter and makes the input the
5471 // current getter.
5472 void UnitTestImpl::set_os_stack_trace_getter(
5473     OsStackTraceGetterInterface* getter) {
5474   if (os_stack_trace_getter_ != getter) {
5475     delete os_stack_trace_getter_;
5476     os_stack_trace_getter_ = getter;
5477   }
5478 }
5479 
5480 // Returns the current OS stack trace getter if it is not NULL;
5481 // otherwise, creates an OsStackTraceGetter, makes it the current
5482 // getter, and returns it.
5483 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
5484   if (os_stack_trace_getter_ == NULL) {
5485 #ifdef GTEST_OS_STACK_TRACE_GETTER_
5486     os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
5487 #else
5488     os_stack_trace_getter_ = new OsStackTraceGetter;
5489 #endif  // GTEST_OS_STACK_TRACE_GETTER_
5490   }
5491 
5492   return os_stack_trace_getter_;
5493 }
5494 
5495 // Returns the most specific TestResult currently running.
5496 TestResult* UnitTestImpl::current_test_result() {
5497   if (current_test_info_ != NULL) {
5498     return &current_test_info_->result_;
5499   }
5500   if (current_test_case_ != NULL) {
5501     return &current_test_case_->ad_hoc_test_result_;
5502   }
5503   return &ad_hoc_test_result_;
5504 }
5505 
5506 // Shuffles all test cases, and the tests within each test case,
5507 // making sure that death tests are still run first.
5508 void UnitTestImpl::ShuffleTests() {
5509   // Shuffles the death test cases.
5510   ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
5511 
5512   // Shuffles the non-death test cases.
5513   ShuffleRange(random(), last_death_test_case_ + 1,
5514                static_cast<int>(test_cases_.size()), &test_case_indices_);
5515 
5516   // Shuffles the tests inside each test case.
5517   for (size_t i = 0; i < test_cases_.size(); i++) {
5518     test_cases_[i]->ShuffleTests(random());
5519   }
5520 }
5521 
5522 // Restores the test cases and tests to their order before the first shuffle.
5523 void UnitTestImpl::UnshuffleTests() {
5524   for (size_t i = 0; i < test_cases_.size(); i++) {
5525     // Unshuffles the tests in each test case.
5526     test_cases_[i]->UnshuffleTests();
5527     // Resets the index of each test case.
5528     test_case_indices_[i] = static_cast<int>(i);
5529   }
5530 }
5531 
5532 // Returns the current OS stack trace as an std::string.
5533 //
5534 // The maximum number of stack frames to be included is specified by
5535 // the gtest_stack_trace_depth flag.  The skip_count parameter
5536 // specifies the number of top frames to be skipped, which doesn't
5537 // count against the number of frames to be included.
5538 //
5539 // For example, if Foo() calls Bar(), which in turn calls
5540 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
5541 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
5542 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
5543                                             int skip_count) {
5544   // We pass skip_count + 1 to skip this wrapper function in addition
5545   // to what the user really wants to skip.
5546   return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
5547 }
5548 
5549 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
5550 // suppress unreachable code warnings.
5551 namespace {
5552 class ClassUniqueToAlwaysTrue {};
5553 }
5554 
5555 bool IsTrue(bool condition) { return condition; }
5556 
5557 bool AlwaysTrue() {
5558 #if GTEST_HAS_EXCEPTIONS
5559   // This condition is always false so AlwaysTrue() never actually throws,
5560   // but it makes the compiler think that it may throw.
5561   if (IsTrue(false))
5562     throw ClassUniqueToAlwaysTrue();
5563 #endif  // GTEST_HAS_EXCEPTIONS
5564   return true;
5565 }
5566 
5567 // If *pstr starts with the given prefix, modifies *pstr to be right
5568 // past the prefix and returns true; otherwise leaves *pstr unchanged
5569 // and returns false.  None of pstr, *pstr, and prefix can be NULL.
5570 bool SkipPrefix(const char* prefix, const char** pstr) {
5571   const size_t prefix_len = strlen(prefix);
5572   if (strncmp(*pstr, prefix, prefix_len) == 0) {
5573     *pstr += prefix_len;
5574     return true;
5575   }
5576   return false;
5577 }
5578 
5579 // Parses a string as a command line flag.  The string should have
5580 // the format "--flag=value".  When def_optional is true, the "=value"
5581 // part can be omitted.
5582 //
5583 // Returns the value of the flag, or NULL if the parsing failed.
5584 static const char* ParseFlagValue(const char* str, const char* flag,
5585                                   bool def_optional) {
5586   // str and flag must not be NULL.
5587   if (str == NULL || flag == NULL) return NULL;
5588 
5589   // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
5590   const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
5591   const size_t flag_len = flag_str.length();
5592   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
5593 
5594   // Skips the flag name.
5595   const char* flag_end = str + flag_len;
5596 
5597   // When def_optional is true, it's OK to not have a "=value" part.
5598   if (def_optional && (flag_end[0] == '\0')) {
5599     return flag_end;
5600   }
5601 
5602   // If def_optional is true and there are more characters after the
5603   // flag name, or if def_optional is false, there must be a '=' after
5604   // the flag name.
5605   if (flag_end[0] != '=') return NULL;
5606 
5607   // Returns the string after "=".
5608   return flag_end + 1;
5609 }
5610 
5611 // Parses a string for a bool flag, in the form of either
5612 // "--flag=value" or "--flag".
5613 //
5614 // In the former case, the value is taken as true as long as it does
5615 // not start with '0', 'f', or 'F'.
5616 //
5617 // In the latter case, the value is taken as true.
5618 //
5619 // On success, stores the value of the flag in *value, and returns
5620 // true.  On failure, returns false without changing *value.
5621 static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
5622   // Gets the value of the flag as a string.
5623   const char* const value_str = ParseFlagValue(str, flag, true);
5624 
5625   // Aborts if the parsing failed.
5626   if (value_str == NULL) return false;
5627 
5628   // Converts the string value to a bool.
5629   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
5630   return true;
5631 }
5632 
5633 // Parses a string for an Int32 flag, in the form of
5634 // "--flag=value".
5635 //
5636 // On success, stores the value of the flag in *value, and returns
5637 // true.  On failure, returns false without changing *value.
5638 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
5639   // Gets the value of the flag as a string.
5640   const char* const value_str = ParseFlagValue(str, flag, false);
5641 
5642   // Aborts if the parsing failed.
5643   if (value_str == NULL) return false;
5644 
5645   // Sets *value to the value of the flag.
5646   return ParseInt32(Message() << "The value of flag --" << flag,
5647                     value_str, value);
5648 }
5649 
5650 // Parses a string for a string flag, in the form of
5651 // "--flag=value".
5652 //
5653 // On success, stores the value of the flag in *value, and returns
5654 // true.  On failure, returns false without changing *value.
5655 template <typename String>
5656 /* static was removed to workaround SStudio bug 27279066 */
5657 bool ParseStringFlag(const char* str, const char* flag, String* value) {
5658   // Gets the value of the flag as a string.
5659   const char* const value_str = ParseFlagValue(str, flag, false);
5660 
5661   // Aborts if the parsing failed.
5662   if (value_str == NULL) return false;
5663 
5664   // Sets *value to the value of the flag.
5665   *value = value_str;
5666   return true;
5667 }
5668 
5669 // Determines whether a string has a prefix that Google Test uses for its
5670 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
5671 // If Google Test detects that a command line flag has its prefix but is not
5672 // recognized, it will print its help message. Flags starting with
5673 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
5674 // internal flags and do not trigger the help message.
5675 static bool HasGoogleTestFlagPrefix(const char* str) {
5676   return (SkipPrefix("--", &str) ||
5677           SkipPrefix("-", &str) ||
5678           SkipPrefix("/", &str)) &&
5679          !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
5680          (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
5681           SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
5682 }
5683 
5684 // Prints a string containing code-encoded text.  The following escape
5685 // sequences can be used in the string to control the text color:
5686 //
5687 //   @@    prints a single '@' character.
5688 //   @R    changes the color to red.
5689 //   @G    changes the color to green.
5690 //   @Y    changes the color to yellow.
5691 //   @D    changes to the default terminal text color.
5692 //
5693 // FIXME: Write tests for this once we add stdout
5694 // capturing to Google Test.
5695 static void PrintColorEncoded(const char* str) {
5696   GTestColor color = COLOR_DEFAULT;  // The current color.
5697 
5698   // Conceptually, we split the string into segments divided by escape
5699   // sequences.  Then we print one segment at a time.  At the end of
5700   // each iteration, the str pointer advances to the beginning of the
5701   // next segment.
5702   for (;;) {
5703     const char* p = strchr(str, '@');
5704     if (p == NULL) {
5705       ColoredPrintf(color, "%s", str);
5706       return;
5707     }
5708 
5709     ColoredPrintf(color, "%s", std::string(str, p).c_str());
5710 
5711     const char ch = p[1];
5712     str = p + 2;
5713     if (ch == '@') {
5714       ColoredPrintf(color, "@");
5715     } else if (ch == 'D') {
5716       color = COLOR_DEFAULT;
5717     } else if (ch == 'R') {
5718       color = COLOR_RED;
5719     } else if (ch == 'G') {
5720       color = COLOR_GREEN;
5721     } else if (ch == 'Y') {
5722       color = COLOR_YELLOW;
5723     } else {
5724       --str;
5725     }
5726   }
5727 }
5728 
5729 static const char kColorEncodedHelpMessage[] =
5730 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
5731 "following command line flags to control its behavior:\n"
5732 "\n"
5733 "Test Selection:\n"
5734 "  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
5735 "      List the names of all tests instead of running them. The name of\n"
5736 "      TEST(Foo, Bar) is \"Foo.Bar\".\n"
5737 "  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
5738     "[@G-@YNEGATIVE_PATTERNS]@D\n"
5739 "      Run only the tests whose name matches one of the positive patterns but\n"
5740 "      none of the negative patterns. '?' matches any single character; '*'\n"
5741 "      matches any substring; ':' separates two patterns.\n"
5742 "  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
5743 "      Run all disabled tests too.\n"
5744 "\n"
5745 "Test Execution:\n"
5746 "  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
5747 "      Run the tests repeatedly; use a negative count to repeat forever.\n"
5748 "  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
5749 "      Randomize tests' orders on every iteration.\n"
5750 "  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
5751 "      Random number seed to use for shuffling test orders (between 1 and\n"
5752 "      99999, or 0 to use a seed based on the current time).\n"
5753 "\n"
5754 "Test Output:\n"
5755 "  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
5756 "      Enable/disable colored output. The default is @Gauto@D.\n"
5757 "  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
5758 "      Don't print the elapsed time of each test.\n"
5759 "  @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
5760     GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
5761 "      Generate a JSON or XML report in the given directory or with the given\n"
5762 "      file name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
5763 # if GTEST_CAN_STREAM_RESULTS_
5764 "  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
5765 "      Stream test results to the given server.\n"
5766 # endif  // GTEST_CAN_STREAM_RESULTS_
5767 "\n"
5768 "Assertion Behavior:\n"
5769 # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5770 "  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
5771 "      Set the default death test style.\n"
5772 # endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5773 "  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
5774 "      Turn assertion failures into debugger break-points.\n"
5775 "  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
5776 "      Turn assertion failures into C++ exceptions for use by an external\n"
5777 "      test framework.\n"
5778 "  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
5779 "      Do not report exceptions as test failures. Instead, allow them\n"
5780 "      to crash the program or throw a pop-up (on Windows).\n"
5781 "\n"
5782 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
5783     "the corresponding\n"
5784 "environment variable of a flag (all letters in upper-case). For example, to\n"
5785 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
5786     "color=no@D or set\n"
5787 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
5788 "\n"
5789 "For more information, please read the " GTEST_NAME_ " documentation at\n"
5790 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
5791 "(not one in your own code or tests), please report it to\n"
5792 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
5793 
5794 static bool ParseGoogleTestFlag(const char* const arg) {
5795   return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
5796                        &GTEST_FLAG(also_run_disabled_tests)) ||
5797       ParseBoolFlag(arg, kBreakOnFailureFlag,
5798                     &GTEST_FLAG(break_on_failure)) ||
5799       ParseBoolFlag(arg, kCatchExceptionsFlag,
5800                     &GTEST_FLAG(catch_exceptions)) ||
5801       ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
5802       ParseStringFlag(arg, kDeathTestStyleFlag,
5803                       &GTEST_FLAG(death_test_style)) ||
5804       ParseBoolFlag(arg, kDeathTestUseFork,
5805                     &GTEST_FLAG(death_test_use_fork)) ||
5806       ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
5807       ParseStringFlag(arg, kInternalRunDeathTestFlag,
5808                       &GTEST_FLAG(internal_run_death_test)) ||
5809       ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
5810       ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
5811       ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
5812       ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
5813       ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
5814       ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
5815       ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
5816       ParseInt32Flag(arg, kStackTraceDepthFlag,
5817                      &GTEST_FLAG(stack_trace_depth)) ||
5818       ParseStringFlag(arg, kStreamResultToFlag,
5819                       &GTEST_FLAG(stream_result_to)) ||
5820       ParseBoolFlag(arg, kThrowOnFailureFlag,
5821                     &GTEST_FLAG(throw_on_failure));
5822 }
5823 
5824 #if GTEST_USE_OWN_FLAGFILE_FLAG_
5825 static void LoadFlagsFromFile(const std::string& path) {
5826   FILE* flagfile = posix::FOpen(path.c_str(), "r");
5827   if (!flagfile) {
5828     GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
5829                       << "\"";
5830   }
5831   std::string contents(ReadEntireFile(flagfile));
5832   posix::FClose(flagfile);
5833   std::vector<std::string> lines;
5834   SplitString(contents, '\n', &lines);
5835   for (size_t i = 0; i < lines.size(); ++i) {
5836     if (lines[i].empty())
5837       continue;
5838     if (!ParseGoogleTestFlag(lines[i].c_str()))
5839       g_help_flag = true;
5840   }
5841 }
5842 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
5843 
5844 // Parses the command line for Google Test flags, without initializing
5845 // other parts of Google Test.  The type parameter CharType can be
5846 // instantiated to either char or wchar_t.
5847 template <typename CharType>
5848 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
5849   for (int i = 1; i < *argc; i++) {
5850     const std::string arg_string = StreamableToString(argv[i]);
5851     const char* const arg = arg_string.c_str();
5852 
5853     using internal::ParseBoolFlag;
5854     using internal::ParseInt32Flag;
5855     using internal::ParseStringFlag;
5856 
5857     bool remove_flag = false;
5858     if (ParseGoogleTestFlag(arg)) {
5859       remove_flag = true;
5860 #if GTEST_USE_OWN_FLAGFILE_FLAG_
5861     } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
5862       LoadFlagsFromFile(GTEST_FLAG(flagfile));
5863       remove_flag = true;
5864 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
5865     } else if (arg_string == "--help" || arg_string == "-h" ||
5866                arg_string == "-?" || arg_string == "/?" ||
5867                HasGoogleTestFlagPrefix(arg)) {
5868       // Both help flag and unrecognized Google Test flags (excluding
5869       // internal ones) trigger help display.
5870       g_help_flag = true;
5871     }
5872 
5873     if (remove_flag) {
5874       // Shift the remainder of the argv list left by one.  Note
5875       // that argv has (*argc + 1) elements, the last one always being
5876       // NULL.  The following loop moves the trailing NULL element as
5877       // well.
5878       for (int j = i; j != *argc; j++) {
5879         argv[j] = argv[j + 1];
5880       }
5881 
5882       // Decrements the argument count.
5883       (*argc)--;
5884 
5885       // We also need to decrement the iterator as we just removed
5886       // an element.
5887       i--;
5888     }
5889   }
5890 
5891   if (g_help_flag) {
5892     // We print the help here instead of in RUN_ALL_TESTS(), as the
5893     // latter may not be called at all if the user is using Google
5894     // Test with another testing framework.
5895     PrintColorEncoded(kColorEncodedHelpMessage);
5896   }
5897 }
5898 
5899 // Parses the command line for Google Test flags, without initializing
5900 // other parts of Google Test.
5901 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
5902   ParseGoogleTestFlagsOnlyImpl(argc, argv);
5903 
5904   // Fix the value of *_NSGetArgc() on macOS, but iff
5905   // *_NSGetArgv() == argv
5906   // Only applicable to char** version of argv
5907 #if GTEST_OS_MAC
5908 #ifndef GTEST_OS_IOS
5909   if (*_NSGetArgv() == argv) {
5910     *_NSGetArgc() = *argc;
5911   }
5912 #endif
5913 #endif
5914 }
5915 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
5916   ParseGoogleTestFlagsOnlyImpl(argc, argv);
5917 }
5918 
5919 // The internal implementation of InitGoogleTest().
5920 //
5921 // The type parameter CharType can be instantiated to either char or
5922 // wchar_t.
5923 template <typename CharType>
5924 void InitGoogleTestImpl(int* argc, CharType** argv) {
5925   // We don't want to run the initialization code twice.
5926   if (GTestIsInitialized()) return;
5927 
5928   if (*argc <= 0) return;
5929 
5930   g_argvs.clear();
5931   for (int i = 0; i != *argc; i++) {
5932     g_argvs.push_back(StreamableToString(argv[i]));
5933   }
5934 
5935 #if GTEST_HAS_ABSL
5936   absl::InitializeSymbolizer(g_argvs[0].c_str());
5937 #endif  // GTEST_HAS_ABSL
5938 
5939   ParseGoogleTestFlagsOnly(argc, argv);
5940   GetUnitTestImpl()->PostFlagParsingInit();
5941 }
5942 
5943 }  // namespace internal
5944 
5945 // Initializes Google Test.  This must be called before calling
5946 // RUN_ALL_TESTS().  In particular, it parses a command line for the
5947 // flags that Google Test recognizes.  Whenever a Google Test flag is
5948 // seen, it is removed from argv, and *argc is decremented.
5949 //
5950 // No value is returned.  Instead, the Google Test flag variables are
5951 // updated.
5952 //
5953 // Calling the function for the second time has no user-visible effect.
5954 void InitGoogleTest(int* argc, char** argv) {
5955 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5956   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
5957 #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5958   internal::InitGoogleTestImpl(argc, argv);
5959 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5960 }
5961 
5962 // This overloaded version can be used in Windows programs compiled in
5963 // UNICODE mode.
5964 void InitGoogleTest(int* argc, wchar_t** argv) {
5965 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5966   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
5967 #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5968   internal::InitGoogleTestImpl(argc, argv);
5969 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5970 }
5971 
5972 std::string TempDir() {
5973 #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
5974   return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
5975 #endif
5976 
5977 #if GTEST_OS_WINDOWS_MOBILE
5978   return "\\temp\\";
5979 #elif GTEST_OS_WINDOWS
5980   const char* temp_dir = internal::posix::GetEnv("TEMP");
5981   if (temp_dir == NULL || temp_dir[0] == '\0')
5982     return "\\temp\\";
5983   else if (temp_dir[strlen(temp_dir) - 1] == '\\')
5984     return temp_dir;
5985   else
5986     return std::string(temp_dir) + "\\";
5987 #elif GTEST_OS_LINUX_ANDROID
5988   return "/sdcard/";
5989 #else
5990   return "/tmp/";
5991 #endif  // GTEST_OS_WINDOWS_MOBILE
5992 }
5993 
5994 // Class ScopedTrace
5995 
5996 // Pushes the given source file location and message onto a per-thread
5997 // trace stack maintained by Google Test.
5998 void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
5999   internal::TraceInfo trace;
6000   trace.file = file;
6001   trace.line = line;
6002   trace.message.swap(message);
6003 
6004   UnitTest::GetInstance()->PushGTestTrace(trace);
6005 }
6006 
6007 // Pops the info pushed by the c'tor.
6008 ScopedTrace::~ScopedTrace()
6009     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
6010   UnitTest::GetInstance()->PopGTestTrace();
6011 }
6012 
6013 }  // namespace testing