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