uTL
micro Template library
gtest-all.cc
Go to the documentation of this file.
1 // Copyright 2008, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 //
31 // Google C++ Testing and Mocking Framework (Google Test)
32 //
33 // Sometimes it's desirable to build Google Test by compiling a single file.
34 // This file serves this purpose.
35 
36 // This line ensures that gtest.h can be compiled on its own, even
37 // when it's fused.
38 #include "gtest.h"
39 
40 // The following lines pull in the real gtest *.cc files.
41 // Copyright 2005, Google Inc.
42 // All rights reserved.
43 //
44 // Redistribution and use in source and binary forms, with or without
45 // modification, are permitted provided that the following conditions are
46 // met:
47 //
48 // * Redistributions of source code must retain the above copyright
49 // notice, this list of conditions and the following disclaimer.
50 // * Redistributions in binary form must reproduce the above
51 // copyright notice, this list of conditions and the following disclaimer
52 // in the documentation and/or other materials provided with the
53 // distribution.
54 // * Neither the name of Google Inc. nor the names of its
55 // contributors may be used to endorse or promote products derived from
56 // this software without specific prior written permission.
57 //
58 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
59 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
60 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
61 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
62 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
63 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
64 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
65 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
66 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
67 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
68 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
69 
70 //
71 // The Google C++ Testing and Mocking Framework (Google Test)
72 
73 // Copyright 2007, Google Inc.
74 // All rights reserved.
75 //
76 // Redistribution and use in source and binary forms, with or without
77 // modification, are permitted provided that the following conditions are
78 // met:
79 //
80 // * Redistributions of source code must retain the above copyright
81 // notice, this list of conditions and the following disclaimer.
82 // * Redistributions in binary form must reproduce the above
83 // copyright notice, this list of conditions and the following disclaimer
84 // in the documentation and/or other materials provided with the
85 // distribution.
86 // * Neither the name of Google Inc. nor the names of its
87 // contributors may be used to endorse or promote products derived from
88 // this software without specific prior written permission.
89 //
90 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
91 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
92 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
93 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
94 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
95 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
96 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
97 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
98 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
99 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
100 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
101 
102 //
103 // Utilities for testing Google Test itself and code that uses Google Test
104 // (e.g. frameworks built on top of Google Test).
105 
106 // GOOGLETEST_CM0004 DO NOT DELETE
107 
108 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
109 #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
110 
111 
113 /* class A needs to have dll-interface to be used by clients of class B */)
114 
115 namespace testing {
116 
117 // This helper class can be used to mock out Google Test failure reporting
118 // so that we can test Google Test or code that builds on Google Test.
119 //
120 // An object of this class appends a TestPartResult object to the
121 // TestPartResultArray object given in the constructor whenever a Google Test
122 // failure is reported. It can either intercept only failures that are
123 // generated in the same thread that created this object or it can intercept
124 // all generated failures. The scope of this mock object can be controlled with
125 // the second argument to the two arguments constructor.
126 class GTEST_API_ ScopedFakeTestPartResultReporter
127  : public TestPartResultReporterInterface {
128  public:
129  // The two possible mocking modes of this object.
130  enum InterceptMode {
131  INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
132  INTERCEPT_ALL_THREADS // Intercepts all failures.
133  };
134 
135  // The c'tor sets this object as the test part result reporter used
136  // by Google Test. The 'result' parameter specifies where to report the
137  // results. This reporter will only catch failures generated in the current
138  // thread. DEPRECATED
139  explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
140 
141  // Same as above, but you can choose the interception scope of this object.
142  ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
143  TestPartResultArray* result);
144 
145  // The d'tor restores the previous test part result reporter.
146  ~ScopedFakeTestPartResultReporter() override;
147 
148  // Appends the TestPartResult object to the TestPartResultArray
149  // received in the constructor.
150  //
151  // This method is from the TestPartResultReporterInterface
152  // interface.
153  void ReportTestPartResult(const TestPartResult& result) override;
154 
155  private:
156  void Init();
157 
158  const InterceptMode intercept_mode_;
159  TestPartResultReporterInterface* old_reporter_;
160  TestPartResultArray* const result_;
161 
162  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
163 };
164 
165 namespace internal {
166 
167 // A helper class for implementing EXPECT_FATAL_FAILURE() and
168 // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
169 // TestPartResultArray contains exactly one failure that has the given
170 // type and contains the given substring. If that's not the case, a
171 // non-fatal failure will be generated.
172 class GTEST_API_ SingleFailureChecker {
173  public:
174  // The constructor remembers the arguments.
175  SingleFailureChecker(const TestPartResultArray* results,
176  TestPartResult::Type type, const std::string& substr);
177  ~SingleFailureChecker();
178  private:
179  const TestPartResultArray* const results_;
180  const TestPartResult::Type type_;
181  const std::string substr_;
182 
183  GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
184 };
185 
186 } // namespace internal
187 
188 } // namespace testing
189 
191 
192 // A set of macros for testing Google Test assertions or code that's expected
193 // to generate Google Test fatal failures. It verifies that the given
194 // statement will cause exactly one fatal Google Test failure with 'substr'
195 // being part of the failure message.
196 //
197 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
198 // affects and considers failures generated in the current thread and
199 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
200 //
201 // The verification of the assertion is done correctly even when the statement
202 // throws an exception or aborts the current function.
203 //
204 // Known restrictions:
205 // - 'statement' cannot reference local non-static variables or
206 // non-static members of the current object.
207 // - 'statement' cannot return a value.
208 // - You cannot stream a failure message to this macro.
209 //
210 // Note that even though the implementations of the following two
211 // macros are much alike, we cannot refactor them to use a common
212 // helper macro, due to some peculiarity in how the preprocessor
213 // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
214 // gtest_unittest.cc will fail to compile if we do that.
215 #define EXPECT_FATAL_FAILURE(statement, substr) \
216  do { \
217  class GTestExpectFatalFailureHelper {\
218  public:\
219  static void Execute() { statement; }\
220  };\
221  ::testing::TestPartResultArray gtest_failures;\
222  ::testing::internal::SingleFailureChecker gtest_checker(\
223  &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
224  {\
225  ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
226  ::testing::ScopedFakeTestPartResultReporter:: \
227  INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
228  GTestExpectFatalFailureHelper::Execute();\
229  }\
230  } while (::testing::internal::AlwaysFalse())
231 
232 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
233  do { \
234  class GTestExpectFatalFailureHelper {\
235  public:\
236  static void Execute() { statement; }\
237  };\
238  ::testing::TestPartResultArray gtest_failures;\
239  ::testing::internal::SingleFailureChecker gtest_checker(\
240  &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
241  {\
242  ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
243  ::testing::ScopedFakeTestPartResultReporter:: \
244  INTERCEPT_ALL_THREADS, &gtest_failures);\
245  GTestExpectFatalFailureHelper::Execute();\
246  }\
247  } while (::testing::internal::AlwaysFalse())
248 
249 // A macro for testing Google Test assertions or code that's expected to
250 // generate Google Test non-fatal failures. It asserts that the given
251 // statement will cause exactly one non-fatal Google Test failure with 'substr'
252 // being part of the failure message.
253 //
254 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
255 // affects and considers failures generated in the current thread and
256 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
257 //
258 // 'statement' is allowed to reference local variables and members of
259 // the current object.
260 //
261 // The verification of the assertion is done correctly even when the statement
262 // throws an exception or aborts the current function.
263 //
264 // Known restrictions:
265 // - You cannot stream a failure message to this macro.
266 //
267 // Note that even though the implementations of the following two
268 // macros are much alike, we cannot refactor them to use a common
269 // helper macro, due to some peculiarity in how the preprocessor
270 // works. If we do that, the code won't compile when the user gives
271 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
272 // expands to code containing an unprotected comma. The
273 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
274 // catches that.
275 //
276 // For the same reason, we have to write
277 // if (::testing::internal::AlwaysTrue()) { statement; }
278 // instead of
279 // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
280 // to avoid an MSVC warning on unreachable code.
281 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
282  do {\
283  ::testing::TestPartResultArray gtest_failures;\
284  ::testing::internal::SingleFailureChecker gtest_checker(\
285  &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
286  (substr));\
287  {\
288  ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
289  ::testing::ScopedFakeTestPartResultReporter:: \
290  INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
291  if (::testing::internal::AlwaysTrue()) { statement; }\
292  }\
293  } while (::testing::internal::AlwaysFalse())
294 
295 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
296  do {\
297  ::testing::TestPartResultArray gtest_failures;\
298  ::testing::internal::SingleFailureChecker gtest_checker(\
299  &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
300  (substr));\
301  {\
302  ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
303  ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
304  &gtest_failures);\
305  if (::testing::internal::AlwaysTrue()) { statement; }\
306  }\
307  } while (::testing::internal::AlwaysFalse())
308 
309 #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
310 
311 #include <ctype.h>
312 #include <math.h>
313 #include <stdarg.h>
314 #include <stdio.h>
315 #include <stdlib.h>
316 #include <time.h>
317 #include <wchar.h>
318 #include <wctype.h>
319 
320 #include <algorithm>
321 #include <iomanip>
322 #include <limits>
323 #include <list>
324 #include <map>
325 #include <ostream> // NOLINT
326 #include <sstream>
327 #include <vector>
328 
329 #if GTEST_OS_LINUX
330 
331 # define GTEST_HAS_GETTIMEOFDAY_ 1
332 
333 # include <fcntl.h> // NOLINT
334 # include <limits.h> // NOLINT
335 # include <sched.h> // NOLINT
336 // Declares vsnprintf(). This header is not available on Windows.
337 # include <strings.h> // NOLINT
338 # include <sys/mman.h> // NOLINT
339 # include <sys/time.h> // NOLINT
340 # include <unistd.h> // NOLINT
341 # include <string>
342 
343 #elif GTEST_OS_ZOS
344 # define GTEST_HAS_GETTIMEOFDAY_ 1
345 # include <sys/time.h> // NOLINT
346 
347 // On z/OS we additionally need strings.h for strcasecmp.
348 # include <strings.h> // NOLINT
349 
350 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
351 
352 # include <windows.h> // NOLINT
353 # undef min
354 
355 #elif GTEST_OS_WINDOWS // We are on Windows proper.
356 
357 # include <io.h> // NOLINT
358 # include <sys/timeb.h> // NOLINT
359 # include <sys/types.h> // NOLINT
360 # include <sys/stat.h> // NOLINT
361 
362 # if GTEST_OS_WINDOWS_MINGW
363 // MinGW has gettimeofday() but not _ftime64().
364 # define GTEST_HAS_GETTIMEOFDAY_ 1
365 # include <sys/time.h> // NOLINT
366 # endif // GTEST_OS_WINDOWS_MINGW
367 
368 // cpplint thinks that the header is already included, so we want to
369 // silence it.
370 # include <windows.h> // NOLINT
371 # undef min
372 
373 #else
374 
375 // Assume other platforms have gettimeofday().
376 # define GTEST_HAS_GETTIMEOFDAY_ 1
377 
378 // cpplint thinks that the header is already included, so we want to
379 // silence it.
380 # include <sys/time.h> // NOLINT
381 # include <unistd.h> // NOLINT
382 
383 #endif // GTEST_OS_LINUX
384 
385 #if GTEST_HAS_EXCEPTIONS
386 # include <stdexcept>
387 #endif
388 
389 #if GTEST_CAN_STREAM_RESULTS_
390 # include <arpa/inet.h> // NOLINT
391 # include <netdb.h> // NOLINT
392 # include <sys/socket.h> // NOLINT
393 # include <sys/types.h> // NOLINT
394 #endif
395 
396 // Copyright 2005, Google Inc.
397 // All rights reserved.
398 //
399 // Redistribution and use in source and binary forms, with or without
400 // modification, are permitted provided that the following conditions are
401 // met:
402 //
403 // * Redistributions of source code must retain the above copyright
404 // notice, this list of conditions and the following disclaimer.
405 // * Redistributions in binary form must reproduce the above
406 // copyright notice, this list of conditions and the following disclaimer
407 // in the documentation and/or other materials provided with the
408 // distribution.
409 // * Neither the name of Google Inc. nor the names of its
410 // contributors may be used to endorse or promote products derived from
411 // this software without specific prior written permission.
412 //
413 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
414 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
415 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
416 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
417 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
418 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
419 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
420 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
421 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
422 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
423 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
424 
425 // Utility functions and classes used by the Google C++ testing framework.//
426 // This file contains purely Google Test's internal implementation. Please
427 // DO NOT #INCLUDE IT IN A USER PROGRAM.
428 
429 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
430 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
431 
432 #ifndef _WIN32_WCE
433 # include <errno.h>
434 #endif // !_WIN32_WCE
435 #include <stddef.h>
436 #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
437 #include <string.h> // For memmove.
438 
439 #include <algorithm>
440 #include <memory>
441 #include <string>
442 #include <vector>
443 
444 
445 #if GTEST_CAN_STREAM_RESULTS_
446 # include <arpa/inet.h> // NOLINT
447 # include <netdb.h> // NOLINT
448 #endif
449 
450 #if GTEST_OS_WINDOWS
451 # include <windows.h> // NOLINT
452 #endif // GTEST_OS_WINDOWS
453 
454 
456 /* class A needs to have dll-interface to be used by clients of class B */)
457 
458 namespace testing {
459 
460 // Declares the flags.
461 //
462 // We don't want the users to modify this flag in the code, but want
463 // Google Test's own unit tests to be able to access it. Therefore we
464 // declare it here as opposed to in gtest.h.
465 GTEST_DECLARE_bool_(death_test_use_fork);
466 
467 namespace internal {
468 
469 // The value of GetTestTypeId() as seen from within the Google Test
470 // library. This is solely for testing GetTestTypeId().
471 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
472 
473 // Names of the flags (needed for parsing Google Test flags).
474 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
475 const char kBreakOnFailureFlag[] = "break_on_failure";
476 const char kCatchExceptionsFlag[] = "catch_exceptions";
477 const char kColorFlag[] = "color";
478 const char kFilterFlag[] = "filter";
479 const char kListTestsFlag[] = "list_tests";
480 const char kOutputFlag[] = "output";
481 const char kPrintTimeFlag[] = "print_time";
482 const char kPrintUTF8Flag[] = "print_utf8";
483 const char kRandomSeedFlag[] = "random_seed";
484 const char kRepeatFlag[] = "repeat";
485 const char kShuffleFlag[] = "shuffle";
486 const char kStackTraceDepthFlag[] = "stack_trace_depth";
487 const char kStreamResultToFlag[] = "stream_result_to";
488 const char kThrowOnFailureFlag[] = "throw_on_failure";
489 const char kFlagfileFlag[] = "flagfile";
490 
491 // A valid random seed must be in [1, kMaxRandomSeed].
492 const int kMaxRandomSeed = 99999;
493 
494 // g_help_flag is true iff the --help flag or an equivalent form is
495 // specified on the command line.
496 GTEST_API_ extern bool g_help_flag;
497 
498 // Returns the current time in milliseconds.
499 GTEST_API_ TimeInMillis GetTimeInMillis();
500 
501 // Returns true iff Google Test should use colors in the output.
502 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
503 
504 // Formats the given time in milliseconds as seconds.
505 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
506 
507 // Converts the given time in milliseconds to a date string in the ISO 8601
508 // format, without the timezone information. N.B.: due to the use the
509 // non-reentrant localtime() function, this function is not thread safe. Do
510 // not use it in any code that can be called from multiple threads.
511 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
512 
513 // Parses a string for an Int32 flag, in the form of "--flag=value".
514 //
515 // On success, stores the value of the flag in *value, and returns
516 // true. On failure, returns false without changing *value.
517 GTEST_API_ bool ParseInt32Flag(
518  const char* str, const char* flag, Int32* value);
519 
520 // Returns a random seed in range [1, kMaxRandomSeed] based on the
521 // given --gtest_random_seed flag value.
522 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
523  const unsigned int raw_seed = (random_seed_flag == 0) ?
524  static_cast<unsigned int>(GetTimeInMillis()) :
525  static_cast<unsigned int>(random_seed_flag);
526 
527  // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
528  // it's easy to type.
529  const int normalized_seed =
530  static_cast<int>((raw_seed - 1U) %
531  static_cast<unsigned int>(kMaxRandomSeed)) + 1;
532  return normalized_seed;
533 }
534 
535 // Returns the first valid random seed after 'seed'. The behavior is
536 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
537 // considered to be 1.
538 inline int GetNextRandomSeed(int seed) {
539  GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
540  << "Invalid random seed " << seed << " - must be in [1, "
541  << kMaxRandomSeed << "].";
542  const int next_seed = seed + 1;
543  return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
544 }
545 
546 // This class saves the values of all Google Test flags in its c'tor, and
547 // restores them in its d'tor.
548 class GTestFlagSaver {
549  public:
550  // The c'tor.
551  GTestFlagSaver() {
552  also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
553  break_on_failure_ = GTEST_FLAG(break_on_failure);
554  catch_exceptions_ = GTEST_FLAG(catch_exceptions);
555  color_ = GTEST_FLAG(color);
556  death_test_style_ = GTEST_FLAG(death_test_style);
557  death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
558  filter_ = GTEST_FLAG(filter);
559  internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
560  list_tests_ = GTEST_FLAG(list_tests);
561  output_ = GTEST_FLAG(output);
562  print_time_ = GTEST_FLAG(print_time);
563  print_utf8_ = GTEST_FLAG(print_utf8);
564  random_seed_ = GTEST_FLAG(random_seed);
565  repeat_ = GTEST_FLAG(repeat);
566  shuffle_ = GTEST_FLAG(shuffle);
567  stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
568  stream_result_to_ = GTEST_FLAG(stream_result_to);
569  throw_on_failure_ = GTEST_FLAG(throw_on_failure);
570  }
571 
572  // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
573  ~GTestFlagSaver() {
574  GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
575  GTEST_FLAG(break_on_failure) = break_on_failure_;
576  GTEST_FLAG(catch_exceptions) = catch_exceptions_;
577  GTEST_FLAG(color) = color_;
578  GTEST_FLAG(death_test_style) = death_test_style_;
579  GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
580  GTEST_FLAG(filter) = filter_;
581  GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
582  GTEST_FLAG(list_tests) = list_tests_;
583  GTEST_FLAG(output) = output_;
584  GTEST_FLAG(print_time) = print_time_;
585  GTEST_FLAG(print_utf8) = print_utf8_;
586  GTEST_FLAG(random_seed) = random_seed_;
587  GTEST_FLAG(repeat) = repeat_;
588  GTEST_FLAG(shuffle) = shuffle_;
589  GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
590  GTEST_FLAG(stream_result_to) = stream_result_to_;
591  GTEST_FLAG(throw_on_failure) = throw_on_failure_;
592  }
593 
594  private:
595  // Fields for saving the original values of flags.
596  bool also_run_disabled_tests_;
597  bool break_on_failure_;
598  bool catch_exceptions_;
599  std::string color_;
600  std::string death_test_style_;
601  bool death_test_use_fork_;
602  std::string filter_;
603  std::string internal_run_death_test_;
604  bool list_tests_;
605  std::string output_;
606  bool print_time_;
607  bool print_utf8_;
608  internal::Int32 random_seed_;
609  internal::Int32 repeat_;
610  bool shuffle_;
611  internal::Int32 stack_trace_depth_;
612  std::string stream_result_to_;
613  bool throw_on_failure_;
615 
616 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
617 // code_point parameter is of type UInt32 because wchar_t may not be
618 // wide enough to contain a code point.
619 // If the code_point is not a valid Unicode code point
620 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
621 // to "(Invalid Unicode 0xXXXXXXXX)".
622 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
623 
624 // Converts a wide string to a narrow string in UTF-8 encoding.
625 // The wide string is assumed to have the following encoding:
626 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
627 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
628 // Parameter str points to a null-terminated wide string.
629 // Parameter num_chars may additionally limit the number
630 // of wchar_t characters processed. -1 is used when the entire string
631 // should be processed.
632 // If the string contains code points that are not valid Unicode code points
633 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
634 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
635 // and contains invalid UTF-16 surrogate pairs, values in those pairs
636 // will be encoded as individual Unicode characters from Basic Normal Plane.
637 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
638 
639 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
640 // if the variable is present. If a file already exists at this location, this
641 // function will write over it. If the variable is present, but the file cannot
642 // be created, prints an error and exits.
643 void WriteToShardStatusFileIfNeeded();
644 
645 // Checks whether sharding is enabled by examining the relevant
646 // environment variable values. If the variables are present,
647 // but inconsistent (e.g., shard_index >= total_shards), prints
648 // an error and exits. If in_subprocess_for_death_test, sharding is
649 // disabled because it must only be applied to the original test
650 // process. Otherwise, we could filter out death tests we intended to execute.
651 GTEST_API_ bool ShouldShard(const char* total_shards_str,
652  const char* shard_index_str,
653  bool in_subprocess_for_death_test);
654 
655 // Parses the environment variable var as an Int32. If it is unset,
656 // returns default_val. If it is not an Int32, prints an error and
657 // and aborts.
658 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
659 
660 // Given the total number of shards, the shard index, and the test id,
661 // returns true iff the test should be run on this shard. The test id is
662 // some arbitrary but unique non-negative integer assigned to each test
663 // method. Assumes that 0 <= shard_index < total_shards.
664 GTEST_API_ bool ShouldRunTestOnShard(
665  int total_shards, int shard_index, int test_id);
666 
667 // STL container utilities.
668 
669 // Returns the number of elements in the given container that satisfy
670 // the given predicate.
671 template <class Container, typename Predicate>
672 inline int CountIf(const Container& c, Predicate predicate) {
673  // Implemented as an explicit loop since std::count_if() in libCstd on
674  // Solaris has a non-standard signature.
675  int count = 0;
676  for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
677  if (predicate(*it))
678  ++count;
679  }
680  return count;
681 }
682 
683 // Applies a function/functor to each element in the container.
684 template <class Container, typename Functor>
685 void ForEach(const Container& c, Functor functor) {
686  std::for_each(c.begin(), c.end(), functor);
687 }
688 
689 // Returns the i-th element of the vector, or default_value if i is not
690 // in range [0, v.size()).
691 template <typename E>
692 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
693  return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
694 }
695 
696 // Performs an in-place shuffle of a range of the vector's elements.
697 // 'begin' and 'end' are element indices as an STL-style range;
698 // i.e. [begin, end) are shuffled, where 'end' == size() means to
699 // shuffle to the end of the vector.
700 template <typename E>
701 void ShuffleRange(internal::Random* random, int begin, int end,
702  std::vector<E>* v) {
703  const int size = static_cast<int>(v->size());
704  GTEST_CHECK_(0 <= begin && begin <= size)
705  << "Invalid shuffle range start " << begin << ": must be in range [0, "
706  << size << "].";
707  GTEST_CHECK_(begin <= end && end <= size)
708  << "Invalid shuffle range finish " << end << ": must be in range ["
709  << begin << ", " << size << "].";
710 
711  // Fisher-Yates shuffle, from
712  // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
713  for (int range_width = end - begin; range_width >= 2; range_width--) {
714  const int last_in_range = begin + range_width - 1;
715  const int selected = begin + random->Generate(range_width);
716  std::swap((*v)[selected], (*v)[last_in_range]);
717  }
718 }
719 
720 // Performs an in-place shuffle of the vector's elements.
721 template <typename E>
722 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
723  ShuffleRange(random, 0, static_cast<int>(v->size()), v);
724 }
725 
726 // A function for deleting an object. Handy for being used as a
727 // functor.
728 template <typename T>
729 static void Delete(T* x) {
730  delete x;
731 }
732 
733 // A predicate that checks the key of a TestProperty against a known key.
734 //
735 // TestPropertyKeyIs is copyable.
736 class TestPropertyKeyIs {
737  public:
738  // Constructor.
739  //
740  // TestPropertyKeyIs has NO default constructor.
741  explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
742 
743  // Returns true iff the test name of test property matches on key_.
744  bool operator()(const TestProperty& test_property) const {
745  return test_property.key() == key_;
746  }
747 
748  private:
749  std::string key_;
750 };
751 
752 // Class UnitTestOptions.
753 //
754 // This class contains functions for processing options the user
755 // specifies when running the tests. It has only static members.
756 //
757 // In most cases, the user can specify an option using either an
758 // environment variable or a command line flag. E.g. you can set the
759 // test filter using either GTEST_FILTER or --gtest_filter. If both
760 // the variable and the flag are present, the latter overrides the
761 // former.
762 class GTEST_API_ UnitTestOptions {
763  public:
764  // Functions for processing the gtest_output flag.
765 
766  // Returns the output format, or "" for normal printed output.
767  static std::string GetOutputFormat();
768 
769  // Returns the absolute path of the requested output file, or the
770  // default (test_detail.xml in the original working directory) if
771  // none was explicitly specified.
772  static std::string GetAbsolutePathToOutputFile();
773 
774  // Functions for processing the gtest_filter flag.
775 
776  // Returns true iff the wildcard pattern matches the string. The
777  // first ':' or '\0' character in pattern marks the end of it.
778  //
779  // This recursive algorithm isn't very efficient, but is clear and
780  // works well enough for matching test names, which are short.
781  static bool PatternMatchesString(const char *pattern, const char *str);
782 
783  // Returns true iff the user-specified filter matches the test suite
784  // name and the test name.
785  static bool FilterMatchesTest(const std::string& test_suite_name,
786  const std::string& test_name);
787 
788 #if GTEST_OS_WINDOWS
789  // Function for supporting the gtest_catch_exception flag.
790 
791  // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
792  // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
793  // This function is useful as an __except condition.
794  static int GTestShouldProcessSEH(DWORD exception_code);
795 #endif // GTEST_OS_WINDOWS
796 
797  // Returns true if "name" matches the ':' separated list of glob-style
798  // filters in "filter".
799  static bool MatchesFilter(const std::string& name, const char* filter);
800 };
801 
802 // Returns the current application's name, removing directory path if that
803 // is present. Used by UnitTestOptions::GetOutputFile.
804 GTEST_API_ FilePath GetCurrentExecutableName();
805 
806 // The role interface for getting the OS stack trace as a string.
807 class OsStackTraceGetterInterface {
808  public:
809  OsStackTraceGetterInterface() {}
810  virtual ~OsStackTraceGetterInterface() {}
811 
812  // Returns the current OS stack trace as an std::string. Parameters:
813  //
814  // max_depth - the maximum number of stack frames to be included
815  // in the trace.
816  // skip_count - the number of top frames to be skipped; doesn't count
817  // against max_depth.
818  virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
819 
820  // UponLeavingGTest() should be called immediately before Google Test calls
821  // user code. It saves some information about the current stack that
822  // CurrentStackTrace() will use to find and hide Google Test stack frames.
823  virtual void UponLeavingGTest() = 0;
824 
825  // This string is inserted in place of stack frames that are part of
826  // Google Test's implementation.
827  static const char* const kElidedFramesMarker;
828 
829  private:
830  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
831 };
832 
833 // A working implementation of the OsStackTraceGetterInterface interface.
834 class OsStackTraceGetter : public OsStackTraceGetterInterface {
835  public:
836  OsStackTraceGetter() {}
837 
838  std::string CurrentStackTrace(int max_depth, int skip_count) override;
839  void UponLeavingGTest() override;
840 
841  private:
842 #if GTEST_HAS_ABSL
843  Mutex mutex_; // Protects all internal state.
844 
845  // We save the stack frame below the frame that calls user code.
846  // We do this because the address of the frame immediately below
847  // the user code changes between the call to UponLeavingGTest()
848  // and any calls to the stack trace code from within the user code.
849  void* caller_frame_ = nullptr;
850 #endif // GTEST_HAS_ABSL
851 
852  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
853 };
854 
855 // Information about a Google Test trace point.
856 struct TraceInfo {
857  const char* file;
858  int line;
859  std::string message;
860 };
861 
862 // This is the default global test part result reporter used in UnitTestImpl.
863 // This class should only be used by UnitTestImpl.
864 class DefaultGlobalTestPartResultReporter
865  : public TestPartResultReporterInterface {
866  public:
867  explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
868  // Implements the TestPartResultReporterInterface. Reports the test part
869  // result in the current test.
870  void ReportTestPartResult(const TestPartResult& result) override;
871 
872  private:
873  UnitTestImpl* const unit_test_;
874 
875  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
876 };
877 
878 // This is the default per thread test part result reporter used in
879 // UnitTestImpl. This class should only be used by UnitTestImpl.
880 class DefaultPerThreadTestPartResultReporter
881  : public TestPartResultReporterInterface {
882  public:
883  explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
884  // Implements the TestPartResultReporterInterface. The implementation just
885  // delegates to the current global test part result reporter of *unit_test_.
886  void ReportTestPartResult(const TestPartResult& result) override;
887 
888  private:
889  UnitTestImpl* const unit_test_;
890 
891  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
892 };
893 
894 // The private implementation of the UnitTest class. We don't protect
895 // the methods under a mutex, as this class is not accessible by a
896 // user and the UnitTest class that delegates work to this class does
897 // proper locking.
898 class GTEST_API_ UnitTestImpl {
899  public:
900  explicit UnitTestImpl(UnitTest* parent);
901  virtual ~UnitTestImpl();
902 
903  // There are two different ways to register your own TestPartResultReporter.
904  // You can register your own repoter to listen either only for test results
905  // from the current thread or for results from all threads.
906  // By default, each per-thread test result repoter just passes a new
907  // TestPartResult to the global test result reporter, which registers the
908  // test part result for the currently running test.
909 
910  // Returns the global test part result reporter.
911  TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
912 
913  // Sets the global test part result reporter.
914  void SetGlobalTestPartResultReporter(
915  TestPartResultReporterInterface* reporter);
916 
917  // Returns the test part result reporter for the current thread.
918  TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
919 
920  // Sets the test part result reporter for the current thread.
921  void SetTestPartResultReporterForCurrentThread(
922  TestPartResultReporterInterface* reporter);
923 
924  // Gets the number of successful test suites.
925  int successful_test_suite_count() const;
926 
927  // Gets the number of failed test suites.
928  int failed_test_suite_count() const;
929 
930  // Gets the number of all test suites.
931  int total_test_suite_count() const;
932 
933  // Gets the number of all test suites that contain at least one test
934  // that should run.
935  int test_suite_to_run_count() const;
936 
937  // Gets the number of successful tests.
938  int successful_test_count() const;
939 
940  // Gets the number of skipped tests.
941  int skipped_test_count() const;
942 
943  // Gets the number of failed tests.
944  int failed_test_count() const;
945 
946  // Gets the number of disabled tests that will be reported in the XML report.
947  int reportable_disabled_test_count() const;
948 
949  // Gets the number of disabled tests.
950  int disabled_test_count() const;
951 
952  // Gets the number of tests to be printed in the XML report.
953  int reportable_test_count() const;
954 
955  // Gets the number of all tests.
956  int total_test_count() const;
957 
958  // Gets the number of tests that should run.
959  int test_to_run_count() const;
960 
961  // Gets the time of the test program start, in ms from the start of the
962  // UNIX epoch.
963  TimeInMillis start_timestamp() const { return start_timestamp_; }
964 
965  // Gets the elapsed time, in milliseconds.
966  TimeInMillis elapsed_time() const { return elapsed_time_; }
967 
968  // Returns true iff the unit test passed (i.e. all test suites passed).
969  bool Passed() const { return !Failed(); }
970 
971  // Returns true iff the unit test failed (i.e. some test suite failed
972  // or something outside of all tests failed).
973  bool Failed() const {
974  return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();
975  }
976 
977  // Gets the i-th test suite among all the test suites. i can range from 0 to
978  // total_test_suite_count() - 1. If i is not in that range, returns NULL.
979  const TestSuite* GetTestSuite(int i) const {
980  const int index = GetElementOr(test_suite_indices_, i, -1);
981  return index < 0 ? nullptr : test_suites_[i];
982  }
983 
984  // Legacy API is deprecated but still available
985 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
986  const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }
987 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
988 
989  // Gets the i-th test suite among all the test suites. i can range from 0 to
990  // total_test_suite_count() - 1. If i is not in that range, returns NULL.
991  TestSuite* GetMutableSuiteCase(int i) {
992  const int index = GetElementOr(test_suite_indices_, i, -1);
993  return index < 0 ? nullptr : test_suites_[index];
994  }
995 
996  // Provides access to the event listener list.
997  TestEventListeners* listeners() { return &listeners_; }
998 
999  // Returns the TestResult for the test that's currently running, or
1000  // the TestResult for the ad hoc test if no test is running.
1001  TestResult* current_test_result();
1002 
1003  // Returns the TestResult for the ad hoc test.
1004  const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1005 
1006  // Sets the OS stack trace getter.
1007  //
1008  // Does nothing if the input and the current OS stack trace getter
1009  // are the same; otherwise, deletes the old getter and makes the
1010  // input the current getter.
1011  void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1012 
1013  // Returns the current OS stack trace getter if it is not NULL;
1014  // otherwise, creates an OsStackTraceGetter, makes it the current
1015  // getter, and returns it.
1016  OsStackTraceGetterInterface* os_stack_trace_getter();
1017 
1018  // Returns the current OS stack trace as an std::string.
1019  //
1020  // The maximum number of stack frames to be included is specified by
1021  // the gtest_stack_trace_depth flag. The skip_count parameter
1022  // specifies the number of top frames to be skipped, which doesn't
1023  // count against the number of frames to be included.
1024  //
1025  // For example, if Foo() calls Bar(), which in turn calls
1026  // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1027  // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1028  std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
1029 
1030  // Finds and returns a TestSuite with the given name. If one doesn't
1031  // exist, creates one and returns it.
1032  //
1033  // Arguments:
1034  //
1035  // test_suite_name: name of the test suite
1036  // type_param: the name of the test's type parameter, or NULL if
1037  // this is not a typed or a type-parameterized test.
1038  // set_up_tc: pointer to the function that sets up the test suite
1039  // tear_down_tc: pointer to the function that tears down the test suite
1040  TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,
1041  internal::SetUpTestSuiteFunc set_up_tc,
1042  internal::TearDownTestSuiteFunc tear_down_tc);
1043 
1044 // Legacy API is deprecated but still available
1045 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1046  TestCase* GetTestCase(const char* test_case_name, const char* type_param,
1047  internal::SetUpTestSuiteFunc set_up_tc,
1048  internal::TearDownTestSuiteFunc tear_down_tc) {
1049  return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);
1050  }
1051 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
1052 
1053  // Adds a TestInfo to the unit test.
1054  //
1055  // Arguments:
1056  //
1057  // set_up_tc: pointer to the function that sets up the test suite
1058  // tear_down_tc: pointer to the function that tears down the test suite
1059  // test_info: the TestInfo object
1060  void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
1061  internal::TearDownTestSuiteFunc tear_down_tc,
1062  TestInfo* test_info) {
1063  // In order to support thread-safe death tests, we need to
1064  // remember the original working directory when the test program
1065  // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1066  // the user may have changed the current directory before calling
1067  // RUN_ALL_TESTS(). Therefore we capture the current directory in
1068  // AddTestInfo(), which is called to register a TEST or TEST_F
1069  // before main() is reached.
1070  if (original_working_dir_.IsEmpty()) {
1071  original_working_dir_.Set(FilePath::GetCurrentDir());
1072  GTEST_CHECK_(!original_working_dir_.IsEmpty())
1073  << "Failed to get the current working directory.";
1074  }
1075 
1076  GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
1077  set_up_tc, tear_down_tc)
1078  ->AddTestInfo(test_info);
1079  }
1080 
1081  // Returns ParameterizedTestSuiteRegistry object used to keep track of
1082  // value-parameterized tests and instantiate and register them.
1083  internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {
1084  return parameterized_test_registry_;
1085  }
1086 
1087  // Sets the TestSuite object for the test that's currently running.
1088  void set_current_test_suite(TestSuite* a_current_test_suite) {
1089  current_test_suite_ = a_current_test_suite;
1090  }
1091 
1092  // Sets the TestInfo object for the test that's currently running. If
1093  // current_test_info is NULL, the assertion results will be stored in
1094  // ad_hoc_test_result_.
1095  void set_current_test_info(TestInfo* a_current_test_info) {
1096  current_test_info_ = a_current_test_info;
1097  }
1098 
1099  // Registers all parameterized tests defined using TEST_P and
1100  // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter
1101  // combination. This method can be called more then once; it has guards
1102  // protecting from registering the tests more then once. If
1103  // value-parameterized tests are disabled, RegisterParameterizedTests is
1104  // present but does nothing.
1105  void RegisterParameterizedTests();
1106 
1107  // Runs all tests in this UnitTest object, prints the result, and
1108  // returns true if all tests are successful. If any exception is
1109  // thrown during a test, this test is considered to be failed, but
1110  // the rest of the tests will still be run.
1111  bool RunAllTests();
1112 
1113  // Clears the results of all tests, except the ad hoc tests.
1114  void ClearNonAdHocTestResult() {
1115  ForEach(test_suites_, TestSuite::ClearTestSuiteResult);
1116  }
1117 
1118  // Clears the results of ad-hoc test assertions.
1119  void ClearAdHocTestResult() {
1120  ad_hoc_test_result_.Clear();
1121  }
1122 
1123  // Adds a TestProperty to the current TestResult object when invoked in a
1124  // context of a test or a test suite, or to the global property set. If the
1125  // result already contains a property with the same key, the value will be
1126  // updated.
1127  void RecordProperty(const TestProperty& test_property);
1128 
1129  enum ReactionToSharding {
1130  HONOR_SHARDING_PROTOCOL,
1131  IGNORE_SHARDING_PROTOCOL
1132  };
1133 
1134  // Matches the full name of each test against the user-specified
1135  // filter to decide whether the test should run, then records the
1136  // result in each TestSuite and TestInfo object.
1137  // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1138  // based on sharding variables in the environment.
1139  // Returns the number of tests that should run.
1140  int FilterTests(ReactionToSharding shard_tests);
1141 
1142  // Prints the names of the tests matching the user-specified filter flag.
1143  void ListTestsMatchingFilter();
1144 
1145  const TestSuite* current_test_suite() const { return current_test_suite_; }
1146  TestInfo* current_test_info() { return current_test_info_; }
1147  const TestInfo* current_test_info() const { return current_test_info_; }
1148 
1149  // Returns the vector of environments that need to be set-up/torn-down
1150  // before/after the tests are run.
1151  std::vector<Environment*>& environments() { return environments_; }
1152 
1153  // Getters for the per-thread Google Test trace stack.
1154  std::vector<TraceInfo>& gtest_trace_stack() {
1155  return *(gtest_trace_stack_.pointer());
1156  }
1157  const std::vector<TraceInfo>& gtest_trace_stack() const {
1158  return gtest_trace_stack_.get();
1159  }
1160 
1161 #if GTEST_HAS_DEATH_TEST
1162  void InitDeathTestSubprocessControlInfo() {
1163  internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1164  }
1165  // Returns a pointer to the parsed --gtest_internal_run_death_test
1166  // flag, or NULL if that flag was not specified.
1167  // This information is useful only in a death test child process.
1168  // Must not be called before a call to InitGoogleTest.
1169  const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1170  return internal_run_death_test_flag_.get();
1171  }
1172 
1173  // Returns a pointer to the current death test factory.
1174  internal::DeathTestFactory* death_test_factory() {
1175  return death_test_factory_.get();
1176  }
1177 
1178  void SuppressTestEventsIfInSubprocess();
1179 
1180  friend class ReplaceDeathTestFactory;
1181 #endif // GTEST_HAS_DEATH_TEST
1182 
1183  // Initializes the event listener performing XML output as specified by
1184  // UnitTestOptions. Must not be called before InitGoogleTest.
1185  void ConfigureXmlOutput();
1186 
1187 #if GTEST_CAN_STREAM_RESULTS_
1188  // Initializes the event listener for streaming test results to a socket.
1189  // Must not be called before InitGoogleTest.
1190  void ConfigureStreamingOutput();
1191 #endif
1192 
1193  // Performs initialization dependent upon flag values obtained in
1194  // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1195  // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1196  // this function is also called from RunAllTests. Since this function can be
1197  // called more than once, it has to be idempotent.
1198  void PostFlagParsingInit();
1199 
1200  // Gets the random seed used at the start of the current test iteration.
1201  int random_seed() const { return random_seed_; }
1202 
1203  // Gets the random number generator.
1204  internal::Random* random() { return &random_; }
1205 
1206  // Shuffles all test suites, and the tests within each test suite,
1207  // making sure that death tests are still run first.
1208  void ShuffleTests();
1209 
1210  // Restores the test suites and tests to their order before the first shuffle.
1211  void UnshuffleTests();
1212 
1213  // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1214  // UnitTest::Run() starts.
1215  bool catch_exceptions() const { return catch_exceptions_; }
1216 
1217  private:
1218  friend class ::testing::UnitTest;
1219 
1220  // Used by UnitTest::Run() to capture the state of
1221  // GTEST_FLAG(catch_exceptions) at the moment it starts.
1222  void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1223 
1224  // The UnitTest object that owns this implementation object.
1225  UnitTest* const parent_;
1226 
1227  // The working directory when the first TEST() or TEST_F() was
1228  // executed.
1229  internal::FilePath original_working_dir_;
1230 
1231  // The default test part result reporters.
1232  DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1233  DefaultPerThreadTestPartResultReporter
1234  default_per_thread_test_part_result_reporter_;
1235 
1236  // Points to (but doesn't own) the global test part result reporter.
1237  TestPartResultReporterInterface* global_test_part_result_repoter_;
1238 
1239  // Protects read and write access to global_test_part_result_reporter_.
1240  internal::Mutex global_test_part_result_reporter_mutex_;
1241 
1242  // Points to (but doesn't own) the per-thread test part result reporter.
1243  internal::ThreadLocal<TestPartResultReporterInterface*>
1244  per_thread_test_part_result_reporter_;
1245 
1246  // The vector of environments that need to be set-up/torn-down
1247  // before/after the tests are run.
1248  std::vector<Environment*> environments_;
1249 
1250  // The vector of TestSuites in their original order. It owns the
1251  // elements in the vector.
1252  std::vector<TestSuite*> test_suites_;
1253 
1254  // Provides a level of indirection for the test suite list to allow
1255  // easy shuffling and restoring the test suite order. The i-th
1256  // element of this vector is the index of the i-th test suite in the
1257  // shuffled order.
1258  std::vector<int> test_suite_indices_;
1259 
1260  // ParameterizedTestRegistry object used to register value-parameterized
1261  // tests.
1262  internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
1263 
1264  // Indicates whether RegisterParameterizedTests() has been called already.
1265  bool parameterized_tests_registered_;
1266 
1267  // Index of the last death test suite registered. Initially -1.
1268  int last_death_test_suite_;
1269 
1270  // This points to the TestSuite for the currently running test. It
1271  // changes as Google Test goes through one test suite after another.
1272  // When no test is running, this is set to NULL and Google Test
1273  // stores assertion results in ad_hoc_test_result_. Initially NULL.
1274  TestSuite* current_test_suite_;
1275 
1276  // This points to the TestInfo for the currently running test. It
1277  // changes as Google Test goes through one test after another. When
1278  // no test is running, this is set to NULL and Google Test stores
1279  // assertion results in ad_hoc_test_result_. Initially NULL.
1280  TestInfo* current_test_info_;
1281 
1282  // Normally, a user only writes assertions inside a TEST or TEST_F,
1283  // or inside a function called by a TEST or TEST_F. Since Google
1284  // Test keeps track of which test is current running, it can
1285  // associate such an assertion with the test it belongs to.
1286  //
1287  // If an assertion is encountered when no TEST or TEST_F is running,
1288  // Google Test attributes the assertion result to an imaginary "ad hoc"
1289  // test, and records the result in ad_hoc_test_result_.
1290  TestResult ad_hoc_test_result_;
1291 
1292  // The list of event listeners that can be used to track events inside
1293  // Google Test.
1294  TestEventListeners listeners_;
1295 
1296  // The OS stack trace getter. Will be deleted when the UnitTest
1297  // object is destructed. By default, an OsStackTraceGetter is used,
1298  // but the user can set this field to use a custom getter if that is
1299  // desired.
1300  OsStackTraceGetterInterface* os_stack_trace_getter_;
1301 
1302  // True iff PostFlagParsingInit() has been called.
1303  bool post_flag_parse_init_performed_;
1304 
1305  // The random number seed used at the beginning of the test run.
1306  int random_seed_;
1307 
1308  // Our random number generator.
1309  internal::Random random_;
1310 
1311  // The time of the test program start, in ms from the start of the
1312  // UNIX epoch.
1313  TimeInMillis start_timestamp_;
1314 
1315  // How long the test took to run, in milliseconds.
1316  TimeInMillis elapsed_time_;
1317 
1318 #if GTEST_HAS_DEATH_TEST
1319  // The decomposed components of the gtest_internal_run_death_test flag,
1320  // parsed when RUN_ALL_TESTS is called.
1321  std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1322  std::unique_ptr<internal::DeathTestFactory> death_test_factory_;
1323 #endif // GTEST_HAS_DEATH_TEST
1324 
1325  // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1326  internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1327 
1328  // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1329  // starts.
1330  bool catch_exceptions_;
1331 
1332  GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1333 }; // class UnitTestImpl
1334 
1335 // Convenience function for accessing the global UnitTest
1336 // implementation object.
1337 inline UnitTestImpl* GetUnitTestImpl() {
1338  return UnitTest::GetInstance()->impl();
1339 }
1340 
1341 #if GTEST_USES_SIMPLE_RE
1342 
1343 // Internal helper functions for implementing the simple regular
1344 // expression matcher.
1345 GTEST_API_ bool IsInSet(char ch, const char* str);
1346 GTEST_API_ bool IsAsciiDigit(char ch);
1347 GTEST_API_ bool IsAsciiPunct(char ch);
1348 GTEST_API_ bool IsRepeat(char ch);
1349 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1350 GTEST_API_ bool IsAsciiWordChar(char ch);
1351 GTEST_API_ bool IsValidEscape(char ch);
1352 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1353 GTEST_API_ bool ValidateRegex(const char* regex);
1354 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1355 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1356  bool escaped, char ch, char repeat, const char* regex, const char* str);
1357 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1358 
1359 #endif // GTEST_USES_SIMPLE_RE
1360 
1361 // Parses the command line for Google Test flags, without initializing
1362 // other parts of Google Test.
1363 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1364 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1365 
1366 #if GTEST_HAS_DEATH_TEST
1367 
1368 // Returns the message describing the last system error, regardless of the
1369 // platform.
1370 GTEST_API_ std::string GetLastErrnoDescription();
1371 
1372 // Attempts to parse a string into a positive integer pointed to by the
1373 // number parameter. Returns true if that is possible.
1374 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1375 // it here.
1376 template <typename Integer>
1377 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1378  // Fail fast if the given string does not begin with a digit;
1379  // this bypasses strtoXXX's "optional leading whitespace and plus
1380  // or minus sign" semantics, which are undesirable here.
1381  if (str.empty() || !IsDigit(str[0])) {
1382  return false;
1383  }
1384  errno = 0;
1385 
1386  char* end;
1387  // BiggestConvertible is the largest integer type that system-provided
1388  // string-to-number conversion routines can return.
1389 
1390 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1391 
1392  // MSVC and C++ Builder define __int64 instead of the standard long long.
1393  typedef unsigned __int64 BiggestConvertible;
1394  const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1395 
1396 # else
1397 
1398  typedef unsigned long long BiggestConvertible; // NOLINT
1399  const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1400 
1401 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1402 
1403  const bool parse_success = *end == '\0' && errno == 0;
1404 
1405  GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1406 
1407  const Integer result = static_cast<Integer>(parsed);
1408  if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1409  *number = result;
1410  return true;
1411  }
1412  return false;
1413 }
1414 #endif // GTEST_HAS_DEATH_TEST
1415 
1416 // TestResult contains some private methods that should be hidden from
1417 // Google Test user but are required for testing. This class allow our tests
1418 // to access them.
1419 //
1420 // This class is supplied only for the purpose of testing Google Test's own
1421 // constructs. Do not use it in user tests, either directly or indirectly.
1422 class TestResultAccessor {
1423  public:
1424  static void RecordProperty(TestResult* test_result,
1425  const std::string& xml_element,
1426  const TestProperty& property) {
1427  test_result->RecordProperty(xml_element, property);
1428  }
1429 
1430  static void ClearTestPartResults(TestResult* test_result) {
1431  test_result->ClearTestPartResults();
1432  }
1433 
1434  static const std::vector<testing::TestPartResult>& test_part_results(
1435  const TestResult& test_result) {
1436  return test_result.test_part_results();
1437  }
1438 };
1439 
1440 #if GTEST_CAN_STREAM_RESULTS_
1441 
1442 // Streams test results to the given port on the given host machine.
1443 class StreamingListener : public EmptyTestEventListener {
1444  public:
1445  // Abstract base class for writing strings to a socket.
1446  class AbstractSocketWriter {
1447  public:
1448  virtual ~AbstractSocketWriter() {}
1449 
1450  // Sends a string to the socket.
1451  virtual void Send(const std::string& message) = 0;
1452 
1453  // Closes the socket.
1454  virtual void CloseConnection() {}
1455 
1456  // Sends a string and a newline to the socket.
1457  void SendLn(const std::string& message) { Send(message + "\n"); }
1458  };
1459 
1460  // Concrete class for actually writing strings to a socket.
1461  class SocketWriter : public AbstractSocketWriter {
1462  public:
1463  SocketWriter(const std::string& host, const std::string& port)
1464  : sockfd_(-1), host_name_(host), port_num_(port) {
1465  MakeConnection();
1466  }
1467 
1468  ~SocketWriter() override {
1469  if (sockfd_ != -1)
1470  CloseConnection();
1471  }
1472 
1473  // Sends a string to the socket.
1474  void Send(const std::string& message) override {
1475  GTEST_CHECK_(sockfd_ != -1)
1476  << "Send() can be called only when there is a connection.";
1477 
1478  const int len = static_cast<int>(message.length());
1479  if (write(sockfd_, message.c_str(), len) != len) {
1480  GTEST_LOG_(WARNING)
1481  << "stream_result_to: failed to stream to "
1482  << host_name_ << ":" << port_num_;
1483  }
1484  }
1485 
1486  private:
1487  // Creates a client socket and connects to the server.
1488  void MakeConnection();
1489 
1490  // Closes the socket.
1491  void CloseConnection() override {
1492  GTEST_CHECK_(sockfd_ != -1)
1493  << "CloseConnection() can be called only when there is a connection.";
1494 
1495  close(sockfd_);
1496  sockfd_ = -1;
1497  }
1498 
1499  int sockfd_; // socket file descriptor
1500  const std::string host_name_;
1501  const std::string port_num_;
1502 
1503  GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1504  }; // class SocketWriter
1505 
1506  // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1507  static std::string UrlEncode(const char* str);
1508 
1509  StreamingListener(const std::string& host, const std::string& port)
1510  : socket_writer_(new SocketWriter(host, port)) {
1511  Start();
1512  }
1513 
1514  explicit StreamingListener(AbstractSocketWriter* socket_writer)
1515  : socket_writer_(socket_writer) { Start(); }
1516 
1517  void OnTestProgramStart(const UnitTest& /* unit_test */) override {
1518  SendLn("event=TestProgramStart");
1519  }
1520 
1521  void OnTestProgramEnd(const UnitTest& unit_test) override {
1522  // Note that Google Test current only report elapsed time for each
1523  // test iteration, not for the entire test program.
1524  SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1525 
1526  // Notify the streaming server to stop.
1527  socket_writer_->CloseConnection();
1528  }
1529 
1530  void OnTestIterationStart(const UnitTest& /* unit_test */,
1531  int iteration) override {
1532  SendLn("event=TestIterationStart&iteration=" +
1533  StreamableToString(iteration));
1534  }
1535 
1536  void OnTestIterationEnd(const UnitTest& unit_test,
1537  int /* iteration */) override {
1538  SendLn("event=TestIterationEnd&passed=" +
1539  FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1540  StreamableToString(unit_test.elapsed_time()) + "ms");
1541  }
1542 
1543  // Note that "event=TestCaseStart" is a wire format and has to remain
1544  // "case" for compatibilty
1545  void OnTestCaseStart(const TestCase& test_case) override {
1546  SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1547  }
1548 
1549  // Note that "event=TestCaseEnd" is a wire format and has to remain
1550  // "case" for compatibilty
1551  void OnTestCaseEnd(const TestCase& test_case) override {
1552  SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
1553  "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
1554  "ms");
1555  }
1556 
1557  void OnTestStart(const TestInfo& test_info) override {
1558  SendLn(std::string("event=TestStart&name=") + test_info.name());
1559  }
1560 
1561  void OnTestEnd(const TestInfo& test_info) override {
1562  SendLn("event=TestEnd&passed=" +
1563  FormatBool((test_info.result())->Passed()) +
1564  "&elapsed_time=" +
1565  StreamableToString((test_info.result())->elapsed_time()) + "ms");
1566  }
1567 
1568  void OnTestPartResult(const TestPartResult& test_part_result) override {
1569  const char* file_name = test_part_result.file_name();
1570  if (file_name == nullptr) file_name = "";
1571  SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1572  "&line=" + StreamableToString(test_part_result.line_number()) +
1573  "&message=" + UrlEncode(test_part_result.message()));
1574  }
1575 
1576  private:
1577  // Sends the given message and a newline to the socket.
1578  void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
1579 
1580  // Called at the start of streaming to notify the receiver what
1581  // protocol we are using.
1582  void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1583 
1584  std::string FormatBool(bool value) { return value ? "1" : "0"; }
1585 
1586  const std::unique_ptr<AbstractSocketWriter> socket_writer_;
1587 
1588  GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1589 }; // class StreamingListener
1590 
1591 #endif // GTEST_CAN_STREAM_RESULTS_
1592 
1593 } // namespace internal
1594 } // namespace testing
1595 
1597 
1598 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1599 
1600 #if GTEST_OS_WINDOWS
1601 # define vsnprintf _vsnprintf
1602 #endif // GTEST_OS_WINDOWS
1603 
1604 #if GTEST_OS_MAC
1605 #ifndef GTEST_OS_IOS
1606 #include <crt_externs.h>
1607 #endif
1608 #endif
1609 
1610 #if GTEST_HAS_ABSL
1611 #include "absl/debugging/failure_signal_handler.h"
1612 #include "absl/debugging/stacktrace.h"
1613 #include "absl/debugging/symbolize.h"
1614 #include "absl/strings/str_cat.h"
1615 #endif // GTEST_HAS_ABSL
1616 
1617 namespace testing {
1618 
1619 using internal::CountIf;
1620 using internal::ForEach;
1621 using internal::GetElementOr;
1622 using internal::Shuffle;
1623 
1624 // Constants.
1625 
1626 // A test whose test suite name or test name matches this filter is
1627 // disabled and not run.
1628 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1629 
1630 // A test suite whose name matches this filter is considered a death
1631 // test suite and will be run before test suites whose name doesn't
1632 // match this filter.
1633 static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
1634 
1635 // A test filter that matches everything.
1636 static const char kUniversalFilter[] = "*";
1637 
1638 // The default output format.
1639 static const char kDefaultOutputFormat[] = "xml";
1640 // The default output file.
1641 static const char kDefaultOutputFile[] = "test_detail";
1642 
1643 // The environment variable name for the test shard index.
1644 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1645 // The environment variable name for the total number of test shards.
1646 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1647 // The environment variable name for the test shard status file.
1648 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1649 
1650 namespace internal {
1651 
1652 // The text used in failure messages to indicate the start of the
1653 // stack trace.
1654 const char kStackTraceMarker[] = "\nStack trace:\n";
1655 
1656 // g_help_flag is true iff the --help flag or an equivalent form is
1657 // specified on the command line.
1658 bool g_help_flag = false;
1659 
1660 // Utilty function to Open File for Writing
1661 static FILE* OpenFileForWriting(const std::string& output_file) {
1662  FILE* fileout = nullptr;
1663  FilePath output_file_path(output_file);
1664  FilePath output_dir(output_file_path.RemoveFileName());
1665 
1666  if (output_dir.CreateDirectoriesRecursively()) {
1667  fileout = posix::FOpen(output_file.c_str(), "w");
1668  }
1669  if (fileout == nullptr) {
1670  GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
1671  }
1672  return fileout;
1673 }
1674 
1675 } // namespace internal
1676 
1677 // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
1678 // environment variable.
1679 static const char* GetDefaultFilter() {
1680  const char* const testbridge_test_only =
1681  internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
1682  if (testbridge_test_only != nullptr) {
1683  return testbridge_test_only;
1684  }
1685  return kUniversalFilter;
1686 }
1687 
1689  also_run_disabled_tests,
1690  internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1691  "Run disabled tests too, in addition to the tests normally being run.");
1692 
1694  break_on_failure,
1695  internal::BoolFromGTestEnv("break_on_failure", false),
1696  "True iff a failed assertion should be a debugger break-point.");
1697 
1699  catch_exceptions,
1700  internal::BoolFromGTestEnv("catch_exceptions", true),
1701  "True iff " GTEST_NAME_
1702  " should catch exceptions and treat them as test failures.");
1703 
1705  color,
1706  internal::StringFromGTestEnv("color", "auto"),
1707  "Whether to use colors in the output. Valid values: yes, no, "
1708  "and auto. 'auto' means to use colors if the output is "
1709  "being sent to a terminal and the TERM environment variable "
1710  "is set to a terminal type that supports colors.");
1711 
1713  filter,
1714  internal::StringFromGTestEnv("filter", GetDefaultFilter()),
1715  "A colon-separated list of glob (not regex) patterns "
1716  "for filtering the tests to run, optionally followed by a "
1717  "'-' and a : separated list of negative patterns (tests to "
1718  "exclude). A test is run if it matches one of the positive "
1719  "patterns and does not match any of the negative patterns.");
1720 
1722  install_failure_signal_handler,
1723  internal::BoolFromGTestEnv("install_failure_signal_handler", false),
1724  "If true and supported on the current platform, " GTEST_NAME_ " should "
1725  "install a signal handler that dumps debugging information when fatal "
1726  "signals are raised.");
1727 
1728 GTEST_DEFINE_bool_(list_tests, false,
1729  "List all tests without running them.");
1730 
1731 // The net priority order after flag processing is thus:
1732 // --gtest_output command line flag
1733 // GTEST_OUTPUT environment variable
1734 // XML_OUTPUT_FILE environment variable
1735 // ''
1737  output,
1740  "A format (defaults to \"xml\" but can be specified to be \"json\"), "
1741  "optionally followed by a colon and an output file name or directory. "
1742  "A directory is indicated by a trailing pathname separator. "
1743  "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1744  "If a directory is specified, output files will be created "
1745  "within that directory, with file-names based on the test "
1746  "executable's name and, if necessary, made unique by adding "
1747  "digits.");
1748 
1750  print_time,
1751  internal::BoolFromGTestEnv("print_time", true),
1752  "True iff " GTEST_NAME_
1753  " should display elapsed time in text output.");
1754 
1756  print_utf8,
1757  internal::BoolFromGTestEnv("print_utf8", true),
1758  "True iff " GTEST_NAME_
1759  " prints UTF8 characters as text.");
1760 
1762  random_seed,
1763  internal::Int32FromGTestEnv("random_seed", 0),
1764  "Random number seed to use when shuffling test orders. Must be in range "
1765  "[1, 99999], or 0 to use a seed based on the current time.");
1766 
1768  repeat,
1769  internal::Int32FromGTestEnv("repeat", 1),
1770  "How many times to repeat each test. Specify a negative number "
1771  "for repeating forever. Useful for shaking out flaky tests.");
1772 
1774  show_internal_stack_frames, false,
1775  "True iff " GTEST_NAME_ " should include internal stack frames when "
1776  "printing test failure stack traces.");
1777 
1779  shuffle,
1780  internal::BoolFromGTestEnv("shuffle", false),
1781  "True iff " GTEST_NAME_
1782  " should randomize tests' order on every run.");
1783 
1785  stack_trace_depth,
1786  internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1787  "The maximum number of stack frames to print when an "
1788  "assertion fails. The valid range is 0 through 100, inclusive.");
1789 
1791  stream_result_to,
1792  internal::StringFromGTestEnv("stream_result_to", ""),
1793  "This flag specifies the host name and the port number on which to stream "
1794  "test results. Example: \"localhost:555\". The flag is effective only on "
1795  "Linux.");
1796 
1798  throw_on_failure,
1799  internal::BoolFromGTestEnv("throw_on_failure", false),
1800  "When this flag is specified, a failed assertion will throw an exception "
1801  "if exceptions are enabled or exit the program with a non-zero code "
1802  "otherwise. For use with an external test framework.");
1803 
1804 #if GTEST_USE_OWN_FLAGFILE_FLAG_
1806  flagfile,
1807  internal::StringFromGTestEnv("flagfile", ""),
1808  "This flag specifies the flagfile to read command-line flags from.");
1809 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
1810 
1811 namespace internal {
1812 
1813 // Generates a random number from [0, range), using a Linear
1814 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1815 // than kMaxRange.
1817  // These constants are the same as are used in glibc's rand(3).
1818  // Use wider types than necessary to prevent unsigned overflow diagnostics.
1819  state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange;
1820 
1821  GTEST_CHECK_(range > 0)
1822  << "Cannot generate a number in the range [0, 0).";
1823  GTEST_CHECK_(range <= kMaxRange)
1824  << "Generation of a number in [0, " << range << ") was requested, "
1825  << "but this can only generate numbers in [0, " << kMaxRange << ").";
1826 
1827  // Converting via modulus introduces a bit of downward bias, but
1828  // it's simple, and a linear congruential generator isn't too good
1829  // to begin with.
1830  return state_ % range;
1831 }
1832 
1833 // GTestIsInitialized() returns true iff the user has initialized
1834 // Google Test. Useful for catching the user mistake of not initializing
1835 // Google Test before calling RUN_ALL_TESTS().
1836 static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
1837 
1838 // Iterates over a vector of TestSuites, keeping a running sum of the
1839 // results of calling a given int-returning method on each.
1840 // Returns the sum.
1841 static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
1842  int (TestSuite::*method)() const) {
1843  int sum = 0;
1844  for (size_t i = 0; i < case_list.size(); i++) {
1845  sum += (case_list[i]->*method)();
1846  }
1847  return sum;
1848 }
1849 
1850 // Returns true iff the test suite passed.
1851 static bool TestSuitePassed(const TestSuite* test_suite) {
1852  return test_suite->should_run() && test_suite->Passed();
1853 }
1854 
1855 // Returns true iff the test suite failed.
1856 static bool TestSuiteFailed(const TestSuite* test_suite) {
1857  return test_suite->should_run() && test_suite->Failed();
1858 }
1859 
1860 // Returns true iff test_suite contains at least one test that should
1861 // run.
1862 static bool ShouldRunTestSuite(const TestSuite* test_suite) {
1863  return test_suite->should_run();
1864 }
1865 
1866 // AssertHelper constructor.
1867 AssertHelper::AssertHelper(TestPartResult::Type type,
1868  const char* file,
1869  int line,
1870  const char* message)
1871  : data_(new AssertHelperData(type, file, line, message)) {
1872 }
1873 
1874 AssertHelper::~AssertHelper() {
1875  delete data_;
1876 }
1877 
1878 // Message assignment, for assertion streaming support.
1879 void AssertHelper::operator=(const Message& message) const {
1880  UnitTest::GetInstance()->
1881  AddTestPartResult(data_->type, data_->file, data_->line,
1882  AppendUserMessage(data_->message, message),
1883  UnitTest::GetInstance()->impl()
1884  ->CurrentOsStackTraceExceptTop(1)
1885  // Skips the stack frame for this function itself.
1886  ); // NOLINT
1887 }
1888 
1889 // A copy of all command line arguments. Set by InitGoogleTest().
1890 static ::std::vector<std::string> g_argvs;
1891 
1892 ::std::vector<std::string> GetArgvs() {
1893 #if defined(GTEST_CUSTOM_GET_ARGVS_)
1894  // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
1895  // ::string. This code converts it to the appropriate type.
1896  const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
1897  return ::std::vector<std::string>(custom.begin(), custom.end());
1898 #else // defined(GTEST_CUSTOM_GET_ARGVS_)
1899  return g_argvs;
1900 #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
1901 }
1902 
1903 // Returns the current application's name, removing directory path if that
1904 // is present.
1905 FilePath GetCurrentExecutableName() {
1906  FilePath result;
1907 
1908 #if GTEST_OS_WINDOWS || GTEST_OS_OS2
1909  result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
1910 #else
1911  result.Set(FilePath(GetArgvs()[0]));
1912 #endif // GTEST_OS_WINDOWS
1913 
1914  return result.RemoveDirectoryName();
1915 }
1916 
1917 // Functions for processing the gtest_output flag.
1918 
1919 // Returns the output format, or "" for normal printed output.
1920 std::string UnitTestOptions::GetOutputFormat() {
1921  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1922  const char* const colon = strchr(gtest_output_flag, ':');
1923  return (colon == nullptr)
1924  ? std::string(gtest_output_flag)
1925  : std::string(gtest_output_flag, colon - gtest_output_flag);
1926 }
1927 
1928 // Returns the name of the requested output file, or the default if none
1929 // was explicitly specified.
1930 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
1931  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1932 
1933  std::string format = GetOutputFormat();
1934  if (format.empty())
1935  format = std::string(kDefaultOutputFormat);
1936 
1937  const char* const colon = strchr(gtest_output_flag, ':');
1938  if (colon == nullptr)
1939  return internal::FilePath::MakeFileName(
1940  internal::FilePath(
1941  UnitTest::GetInstance()->original_working_dir()),
1942  internal::FilePath(kDefaultOutputFile), 0,
1943  format.c_str()).string();
1944 
1945  internal::FilePath output_name(colon + 1);
1946  if (!output_name.IsAbsolutePath())
1947  output_name = internal::FilePath::ConcatPaths(
1948  internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1949  internal::FilePath(colon + 1));
1950 
1951  if (!output_name.IsDirectory())
1952  return output_name.string();
1953 
1954  internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1955  output_name, internal::GetCurrentExecutableName(),
1956  GetOutputFormat().c_str()));
1957  return result.string();
1958 }
1959 
1960 // Returns true iff the wildcard pattern matches the string. The
1961 // first ':' or '\0' character in pattern marks the end of it.
1962 //
1963 // This recursive algorithm isn't very efficient, but is clear and
1964 // works well enough for matching test names, which are short.
1965 bool UnitTestOptions::PatternMatchesString(const char *pattern,
1966  const char *str) {
1967  switch (*pattern) {
1968  case '\0':
1969  case ':': // Either ':' or '\0' marks the end of the pattern.
1970  return *str == '\0';
1971  case '?': // Matches any single character.
1972  return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1973  case '*': // Matches any string (possibly empty) of characters.
1974  return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1975  PatternMatchesString(pattern + 1, str);
1976  default: // Non-special character. Matches itself.
1977  return *pattern == *str &&
1978  PatternMatchesString(pattern + 1, str + 1);
1979  }
1980 }
1981 
1982 bool UnitTestOptions::MatchesFilter(
1983  const std::string& name, const char* filter) {
1984  const char *cur_pattern = filter;
1985  for (;;) {
1986  if (PatternMatchesString(cur_pattern, name.c_str())) {
1987  return true;
1988  }
1989 
1990  // Finds the next pattern in the filter.
1991  cur_pattern = strchr(cur_pattern, ':');
1992 
1993  // Returns if no more pattern can be found.
1994  if (cur_pattern == nullptr) {
1995  return false;
1996  }
1997 
1998  // Skips the pattern separater (the ':' character).
1999  cur_pattern++;
2000  }
2001 }
2002 
2003 // Returns true iff the user-specified filter matches the test suite
2004 // name and the test name.
2005 bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
2006  const std::string& test_name) {
2007  const std::string& full_name = test_suite_name + "." + test_name.c_str();
2008 
2009  // Split --gtest_filter at '-', if there is one, to separate into
2010  // positive filter and negative filter portions
2011  const char* const p = GTEST_FLAG(filter).c_str();
2012  const char* const dash = strchr(p, '-');
2013  std::string positive;
2014  std::string negative;
2015  if (dash == nullptr) {
2016  positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
2017  negative = "";
2018  } else {
2019  positive = std::string(p, dash); // Everything up to the dash
2020  negative = std::string(dash + 1); // Everything after the dash
2021  if (positive.empty()) {
2022  // Treat '-test1' as the same as '*-test1'
2023  positive = kUniversalFilter;
2024  }
2025  }
2026 
2027  // A filter is a colon-separated list of patterns. It matches a
2028  // test if any pattern in it matches the test.
2029  return (MatchesFilter(full_name, positive.c_str()) &&
2030  !MatchesFilter(full_name, negative.c_str()));
2031 }
2032 
2033 #if GTEST_HAS_SEH
2034 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
2035 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
2036 // This function is useful as an __except condition.
2037 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
2038  // Google Test should handle a SEH exception if:
2039  // 1. the user wants it to, AND
2040  // 2. this is not a breakpoint exception, AND
2041  // 3. this is not a C++ exception (VC++ implements them via SEH,
2042  // apparently).
2043  //
2044  // SEH exception code for C++ exceptions.
2045  // (see http://support.microsoft.com/kb/185294 for more information).
2046  const DWORD kCxxExceptionCode = 0xe06d7363;
2047 
2048  bool should_handle = true;
2049 
2050  if (!GTEST_FLAG(catch_exceptions))
2051  should_handle = false;
2052  else if (exception_code == EXCEPTION_BREAKPOINT)
2053  should_handle = false;
2054  else if (exception_code == kCxxExceptionCode)
2055  should_handle = false;
2056 
2057  return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2058 }
2059 #endif // GTEST_HAS_SEH
2060 
2061 } // namespace internal
2062 
2063 // The c'tor sets this object as the test part result reporter used by
2064 // Google Test. The 'result' parameter specifies where to report the
2065 // results. Intercepts only failures from the current thread.
2066 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2067  TestPartResultArray* result)
2068  : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2069  result_(result) {
2070  Init();
2071 }
2072 
2073 // The c'tor sets this object as the test part result reporter used by
2074 // Google Test. The 'result' parameter specifies where to report the
2075 // results.
2076 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2077  InterceptMode intercept_mode, TestPartResultArray* result)
2078  : intercept_mode_(intercept_mode),
2079  result_(result) {
2080  Init();
2081 }
2082 
2083 void ScopedFakeTestPartResultReporter::Init() {
2084  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2085  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2086  old_reporter_ = impl->GetGlobalTestPartResultReporter();
2087  impl->SetGlobalTestPartResultReporter(this);
2088  } else {
2089  old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2090  impl->SetTestPartResultReporterForCurrentThread(this);
2091  }
2092 }
2093 
2094 // The d'tor restores the test part result reporter used by Google Test
2095 // before.
2096 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2097  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2098  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2099  impl->SetGlobalTestPartResultReporter(old_reporter_);
2100  } else {
2101  impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2102  }
2103 }
2104 
2105 // Increments the test part result count and remembers the result.
2106 // This method is from the TestPartResultReporterInterface interface.
2107 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2108  const TestPartResult& result) {
2109  result_->Append(result);
2110 }
2111 
2112 namespace internal {
2113 
2114 // Returns the type ID of ::testing::Test. We should always call this
2115 // instead of GetTypeId< ::testing::Test>() to get the type ID of
2116 // testing::Test. This is to work around a suspected linker bug when
2117 // using Google Test as a framework on Mac OS X. The bug causes
2118 // GetTypeId< ::testing::Test>() to return different values depending
2119 // on whether the call is from the Google Test framework itself or
2120 // from user test code. GetTestTypeId() is guaranteed to always
2121 // return the same value, as it always calls GetTypeId<>() from the
2122 // gtest.cc, which is within the Google Test framework.
2124  return GetTypeId<Test>();
2125 }
2126 
2127 // The value of GetTestTypeId() as seen from within the Google Test
2128 // library. This is solely for testing GetTestTypeId().
2129 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
2130 
2131 // This predicate-formatter checks that 'results' contains a test part
2132 // failure of the given type and that the failure message contains the
2133 // given substring.
2134 static AssertionResult HasOneFailure(const char* /* results_expr */,
2135  const char* /* type_expr */,
2136  const char* /* substr_expr */,
2137  const TestPartResultArray& results,
2138  TestPartResult::Type type,
2139  const std::string& substr) {
2140  const std::string expected(type == TestPartResult::kFatalFailure ?
2141  "1 fatal failure" :
2142  "1 non-fatal failure");
2143  Message msg;
2144  if (results.size() != 1) {
2145  msg << "Expected: " << expected << "\n"
2146  << " Actual: " << results.size() << " failures";
2147  for (int i = 0; i < results.size(); i++) {
2148  msg << "\n" << results.GetTestPartResult(i);
2149  }
2150  return AssertionFailure() << msg;
2151  }
2152 
2153  const TestPartResult& r = results.GetTestPartResult(0);
2154  if (r.type() != type) {
2155  return AssertionFailure() << "Expected: " << expected << "\n"
2156  << " Actual:\n"
2157  << r;
2158  }
2159 
2160  if (strstr(r.message(), substr.c_str()) == nullptr) {
2161  return AssertionFailure() << "Expected: " << expected << " containing \""
2162  << substr << "\"\n"
2163  << " Actual:\n"
2164  << r;
2165  }
2166 
2167  return AssertionSuccess();
2168 }
2169 
2170 // The constructor of SingleFailureChecker remembers where to look up
2171 // test part results, what type of failure we expect, and what
2172 // substring the failure message should contain.
2173 SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
2174  TestPartResult::Type type,
2175  const std::string& substr)
2176  : results_(results), type_(type), substr_(substr) {}
2177 
2178 // The destructor of SingleFailureChecker verifies that the given
2179 // TestPartResultArray contains exactly one failure that has the given
2180 // type and contains the given substring. If that's not the case, a
2181 // non-fatal failure will be generated.
2182 SingleFailureChecker::~SingleFailureChecker() {
2183  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2184 }
2185 
2186 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2187  UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2188 
2189 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2190  const TestPartResult& result) {
2191  unit_test_->current_test_result()->AddTestPartResult(result);
2192  unit_test_->listeners()->repeater()->OnTestPartResult(result);
2193 }
2194 
2195 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2196  UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2197 
2198 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2199  const TestPartResult& result) {
2200  unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2201 }
2202 
2203 // Returns the global test part result reporter.
2204 TestPartResultReporterInterface*
2205 UnitTestImpl::GetGlobalTestPartResultReporter() {
2206  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2207  return global_test_part_result_repoter_;
2208 }
2209 
2210 // Sets the global test part result reporter.
2211 void UnitTestImpl::SetGlobalTestPartResultReporter(
2212  TestPartResultReporterInterface* reporter) {
2213  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2214  global_test_part_result_repoter_ = reporter;
2215 }
2216 
2217 // Returns the test part result reporter for the current thread.
2218 TestPartResultReporterInterface*
2219 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2220  return per_thread_test_part_result_reporter_.get();
2221 }
2222 
2223 // Sets the test part result reporter for the current thread.
2224 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2225  TestPartResultReporterInterface* reporter) {
2226  per_thread_test_part_result_reporter_.set(reporter);
2227 }
2228 
2229 // Gets the number of successful test suites.
2230 int UnitTestImpl::successful_test_suite_count() const {
2231  return CountIf(test_suites_, TestSuitePassed);
2232 }
2233 
2234 // Gets the number of failed test suites.
2235 int UnitTestImpl::failed_test_suite_count() const {
2236  return CountIf(test_suites_, TestSuiteFailed);
2237 }
2238 
2239 // Gets the number of all test suites.
2240 int UnitTestImpl::total_test_suite_count() const {
2241  return static_cast<int>(test_suites_.size());
2242 }
2243 
2244 // Gets the number of all test suites that contain at least one test
2245 // that should run.
2246 int UnitTestImpl::test_suite_to_run_count() const {
2247  return CountIf(test_suites_, ShouldRunTestSuite);
2248 }
2249 
2250 // Gets the number of successful tests.
2251 int UnitTestImpl::successful_test_count() const {
2252  return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
2253 }
2254 
2255 // Gets the number of skipped tests.
2256 int UnitTestImpl::skipped_test_count() const {
2257  return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
2258 }
2259 
2260 // Gets the number of failed tests.
2261 int UnitTestImpl::failed_test_count() const {
2262  return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
2263 }
2264 
2265 // Gets the number of disabled tests that will be reported in the XML report.
2266 int UnitTestImpl::reportable_disabled_test_count() const {
2267  return SumOverTestSuiteList(test_suites_,
2268  &TestSuite::reportable_disabled_test_count);
2269 }
2270 
2271 // Gets the number of disabled tests.
2272 int UnitTestImpl::disabled_test_count() const {
2273  return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
2274 }
2275 
2276 // Gets the number of tests to be printed in the XML report.
2277 int UnitTestImpl::reportable_test_count() const {
2278  return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
2279 }
2280 
2281 // Gets the number of all tests.
2282 int UnitTestImpl::total_test_count() const {
2283  return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
2284 }
2285 
2286 // Gets the number of tests that should run.
2287 int UnitTestImpl::test_to_run_count() const {
2288  return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
2289 }
2290 
2291 // Returns the current OS stack trace as an std::string.
2292 //
2293 // The maximum number of stack frames to be included is specified by
2294 // the gtest_stack_trace_depth flag. The skip_count parameter
2295 // specifies the number of top frames to be skipped, which doesn't
2296 // count against the number of frames to be included.
2297 //
2298 // For example, if Foo() calls Bar(), which in turn calls
2299 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2300 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
2301 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2302  return os_stack_trace_getter()->CurrentStackTrace(
2303  static_cast<int>(GTEST_FLAG(stack_trace_depth)),
2304  skip_count + 1
2305  // Skips the user-specified number of frames plus this function
2306  // itself.
2307  ); // NOLINT
2308 }
2309 
2310 // Returns the current time in milliseconds.
2311 TimeInMillis GetTimeInMillis() {
2312 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2313  // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2314  // http://analogous.blogspot.com/2005/04/epoch.html
2315  const TimeInMillis kJavaEpochToWinFileTimeDelta =
2316  static_cast<TimeInMillis>(116444736UL) * 100000UL;
2317  const DWORD kTenthMicrosInMilliSecond = 10000;
2318 
2319  SYSTEMTIME now_systime;
2320  FILETIME now_filetime;
2321  ULARGE_INTEGER now_int64;
2322  GetSystemTime(&now_systime);
2323  if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2324  now_int64.LowPart = now_filetime.dwLowDateTime;
2325  now_int64.HighPart = now_filetime.dwHighDateTime;
2326  now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2327  kJavaEpochToWinFileTimeDelta;
2328  return now_int64.QuadPart;
2329  }
2330  return 0;
2331 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2332  __timeb64 now;
2333 
2334  // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2335  // (deprecated function) there.
2337  _ftime64(&now);
2339 
2340  return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2341 #elif GTEST_HAS_GETTIMEOFDAY_
2342  struct timeval now;
2343  gettimeofday(&now, nullptr);
2344  return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2345 #else
2346 # error "Don't know how to get the current time on your system."
2347 #endif
2348 }
2349 
2350 // Utilities
2351 
2352 // class String.
2353 
2354 #if GTEST_OS_WINDOWS_MOBILE
2355 // Creates a UTF-16 wide string from the given ANSI string, allocating
2356 // memory using new. The caller is responsible for deleting the return
2357 // value using delete[]. Returns the wide string, or NULL if the
2358 // input is NULL.
2359 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2360  if (!ansi) return nullptr;
2361  const int length = strlen(ansi);
2362  const int unicode_length =
2363  MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
2364  WCHAR* unicode = new WCHAR[unicode_length + 1];
2365  MultiByteToWideChar(CP_ACP, 0, ansi, length,
2366  unicode, unicode_length);
2367  unicode[unicode_length] = 0;
2368  return unicode;
2369 }
2370 
2371 // Creates an ANSI string from the given wide string, allocating
2372 // memory using new. The caller is responsible for deleting the return
2373 // value using delete[]. Returns the ANSI string, or NULL if the
2374 // input is NULL.
2375 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2376  if (!utf16_str) return nullptr;
2377  const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
2378  0, nullptr, nullptr);
2379  char* ansi = new char[ansi_length + 1];
2380  WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
2381  nullptr);
2382  ansi[ansi_length] = 0;
2383  return ansi;
2384 }
2385 
2386 #endif // GTEST_OS_WINDOWS_MOBILE
2387 
2388 // Compares two C strings. Returns true iff they have the same content.
2389 //
2390 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
2391 // C string is considered different to any non-NULL C string,
2392 // including the empty string.
2393 bool String::CStringEquals(const char * lhs, const char * rhs) {
2394  if (lhs == nullptr) return rhs == nullptr;
2395 
2396  if (rhs == nullptr) return false;
2397 
2398  return strcmp(lhs, rhs) == 0;
2399 }
2400 
2401 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2402 
2403 // Converts an array of wide chars to a narrow string using the UTF-8
2404 // encoding, and streams the result to the given Message object.
2405 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2406  Message* msg) {
2407  for (size_t i = 0; i != length; ) { // NOLINT
2408  if (wstr[i] != L'\0') {
2409  *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2410  while (i != length && wstr[i] != L'\0')
2411  i++;
2412  } else {
2413  *msg << '\0';
2414  i++;
2415  }
2416  }
2417 }
2418 
2419 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2420 
2421 void SplitString(const ::std::string& str, char delimiter,
2422  ::std::vector< ::std::string>* dest) {
2423  ::std::vector< ::std::string> parsed;
2424  ::std::string::size_type pos = 0;
2425  while (::testing::internal::AlwaysTrue()) {
2426  const ::std::string::size_type colon = str.find(delimiter, pos);
2427  if (colon == ::std::string::npos) {
2428  parsed.push_back(str.substr(pos));
2429  break;
2430  } else {
2431  parsed.push_back(str.substr(pos, colon - pos));
2432  pos = colon + 1;
2433  }
2434  }
2435  dest->swap(parsed);
2436 }
2437 
2438 } // namespace internal
2439 
2440 // Constructs an empty Message.
2441 // We allocate the stringstream separately because otherwise each use of
2442 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2443 // stack frame leading to huge stack frames in some cases; gcc does not reuse
2444 // the stack space.
2445 Message::Message() : ss_(new ::std::stringstream) {
2446  // By default, we want there to be enough precision when printing
2447  // a double to a Message.
2448  *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2449 }
2450 
2451 // These two overloads allow streaming a wide C string to a Message
2452 // using the UTF-8 encoding.
2453 Message& Message::operator <<(const wchar_t* wide_c_str) {
2454  return *this << internal::String::ShowWideCString(wide_c_str);
2455 }
2456 Message& Message::operator <<(wchar_t* wide_c_str) {
2457  return *this << internal::String::ShowWideCString(wide_c_str);
2458 }
2459 
2460 #if GTEST_HAS_STD_WSTRING
2461 // Converts the given wide string to a narrow string using the UTF-8
2462 // encoding, and streams the result to this Message object.
2464  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2465  return *this;
2466 }
2467 #endif // GTEST_HAS_STD_WSTRING
2468 
2469 #if GTEST_HAS_GLOBAL_WSTRING
2470 // Converts the given wide string to a narrow string using the UTF-8
2471 // encoding, and streams the result to this Message object.
2472 Message& Message::operator <<(const ::wstring& wstr) {
2473  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2474  return *this;
2475 }
2476 #endif // GTEST_HAS_GLOBAL_WSTRING
2477 
2478 // Gets the text streamed to this object so far as an std::string.
2479 // Each '\0' character in the buffer is replaced with "\\0".
2480 std::string Message::GetString() const {
2481  return internal::StringStreamToString(ss_.get());
2482 }
2483 
2484 // AssertionResult constructors.
2485 // Used in EXPECT_TRUE/FALSE(assertion_result).
2486 AssertionResult::AssertionResult(const AssertionResult& other)
2487  : success_(other.success_),
2488  message_(other.message_.get() != nullptr
2489  ? new ::std::string(*other.message_)
2490  : static_cast< ::std::string*>(nullptr)) {}
2491 
2492 // Swaps two AssertionResults.
2493 void AssertionResult::swap(AssertionResult& other) {
2494  using std::swap;
2495  swap(success_, other.success_);
2496  swap(message_, other.message_);
2497 }
2498 
2499 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2500 AssertionResult AssertionResult::operator!() const {
2501  AssertionResult negation(!success_);
2502  if (message_.get() != nullptr) negation << *message_;
2503  return negation;
2504 }
2505 
2506 // Makes a successful assertion result.
2507 AssertionResult AssertionSuccess() {
2508  return AssertionResult(true);
2509 }
2510 
2511 // Makes a failed assertion result.
2512 AssertionResult AssertionFailure() {
2513  return AssertionResult(false);
2514 }
2515 
2516 // Makes a failed assertion result with the given failure message.
2517 // Deprecated; use AssertionFailure() << message.
2518 AssertionResult AssertionFailure(const Message& message) {
2519  return AssertionFailure() << message;
2520 }
2521 
2522 namespace internal {
2523 
2524 namespace edit_distance {
2525 std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
2526  const std::vector<size_t>& right) {
2527  std::vector<std::vector<double> > costs(
2528  left.size() + 1, std::vector<double>(right.size() + 1));
2529  std::vector<std::vector<EditType> > best_move(
2530  left.size() + 1, std::vector<EditType>(right.size() + 1));
2531 
2532  // Populate for empty right.
2533  for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
2534  costs[l_i][0] = static_cast<double>(l_i);
2535  best_move[l_i][0] = kRemove;
2536  }
2537  // Populate for empty left.
2538  for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
2539  costs[0][r_i] = static_cast<double>(r_i);
2540  best_move[0][r_i] = kAdd;
2541  }
2542 
2543  for (size_t l_i = 0; l_i < left.size(); ++l_i) {
2544  for (size_t r_i = 0; r_i < right.size(); ++r_i) {
2545  if (left[l_i] == right[r_i]) {
2546  // Found a match. Consume it.
2547  costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
2548  best_move[l_i + 1][r_i + 1] = kMatch;
2549  continue;
2550  }
2551 
2552  const double add = costs[l_i + 1][r_i];
2553  const double remove = costs[l_i][r_i + 1];
2554  const double replace = costs[l_i][r_i];
2555  if (add < remove && add < replace) {
2556  costs[l_i + 1][r_i + 1] = add + 1;
2557  best_move[l_i + 1][r_i + 1] = kAdd;
2558  } else if (remove < add && remove < replace) {
2559  costs[l_i + 1][r_i + 1] = remove + 1;
2560  best_move[l_i + 1][r_i + 1] = kRemove;
2561  } else {
2562  // We make replace a little more expensive than add/remove to lower
2563  // their priority.
2564  costs[l_i + 1][r_i + 1] = replace + 1.00001;
2565  best_move[l_i + 1][r_i + 1] = kReplace;
2566  }
2567  }
2568  }
2569 
2570  // Reconstruct the best path. We do it in reverse order.
2571  std::vector<EditType> best_path;
2572  for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
2573  EditType move = best_move[l_i][r_i];
2574  best_path.push_back(move);
2575  l_i -= move != kAdd;
2576  r_i -= move != kRemove;
2577  }
2578  std::reverse(best_path.begin(), best_path.end());
2579  return best_path;
2580 }
2581 
2582 namespace {
2583 
2584 // Helper class to convert string into ids with deduplication.
2585 class InternalStrings {
2586  public:
2587  size_t GetId(const std::string& str) {
2588  IdMap::iterator it = ids_.find(str);
2589  if (it != ids_.end()) return it->second;
2590  size_t id = ids_.size();
2591  return ids_[str] = id;
2592  }
2593 
2594  private:
2595  typedef std::map<std::string, size_t> IdMap;
2596  IdMap ids_;
2597 };
2598 
2599 } // namespace
2600 
2601 std::vector<EditType> CalculateOptimalEdits(
2602  const std::vector<std::string>& left,
2603  const std::vector<std::string>& right) {
2604  std::vector<size_t> left_ids, right_ids;
2605  {
2606  InternalStrings intern_table;
2607  for (size_t i = 0; i < left.size(); ++i) {
2608  left_ids.push_back(intern_table.GetId(left[i]));
2609  }
2610  for (size_t i = 0; i < right.size(); ++i) {
2611  right_ids.push_back(intern_table.GetId(right[i]));
2612  }
2613  }
2614  return CalculateOptimalEdits(left_ids, right_ids);
2615 }
2616 
2617 namespace {
2618 
2619 // Helper class that holds the state for one hunk and prints it out to the
2620 // stream.
2621 // It reorders adds/removes when possible to group all removes before all
2622 // adds. It also adds the hunk header before printint into the stream.
2623 class Hunk {
2624  public:
2625  Hunk(size_t left_start, size_t right_start)
2626  : left_start_(left_start),
2627  right_start_(right_start),
2628  adds_(),
2629  removes_(),
2630  common_() {}
2631 
2632  void PushLine(char edit, const char* line) {
2633  switch (edit) {
2634  case ' ':
2635  ++common_;
2636  FlushEdits();
2637  hunk_.push_back(std::make_pair(' ', line));
2638  break;
2639  case '-':
2640  ++removes_;
2641  hunk_removes_.push_back(std::make_pair('-', line));
2642  break;
2643  case '+':
2644  ++adds_;
2645  hunk_adds_.push_back(std::make_pair('+', line));
2646  break;
2647  }
2648  }
2649 
2650  void PrintTo(std::ostream* os) {
2651  PrintHeader(os);
2652  FlushEdits();
2653  for (std::list<std::pair<char, const char*> >::const_iterator it =
2654  hunk_.begin();
2655  it != hunk_.end(); ++it) {
2656  *os << it->first << it->second << "\n";
2657  }
2658  }
2659 
2660  bool has_edits() const { return adds_ || removes_; }
2661 
2662  private:
2663  void FlushEdits() {
2664  hunk_.splice(hunk_.end(), hunk_removes_);
2665  hunk_.splice(hunk_.end(), hunk_adds_);
2666  }
2667 
2668  // Print a unified diff header for one hunk.
2669  // The format is
2670  // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
2671  // where the left/right parts are omitted if unnecessary.
2672  void PrintHeader(std::ostream* ss) const {
2673  *ss << "@@ ";
2674  if (removes_) {
2675  *ss << "-" << left_start_ << "," << (removes_ + common_);
2676  }
2677  if (removes_ && adds_) {
2678  *ss << " ";
2679  }
2680  if (adds_) {
2681  *ss << "+" << right_start_ << "," << (adds_ + common_);
2682  }
2683  *ss << " @@\n";
2684  }
2685 
2686  size_t left_start_, right_start_;
2687  size_t adds_, removes_, common_;
2688  std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
2689 };
2690 
2691 } // namespace
2692 
2693 // Create a list of diff hunks in Unified diff format.
2694 // Each hunk has a header generated by PrintHeader above plus a body with
2695 // lines prefixed with ' ' for no change, '-' for deletion and '+' for
2696 // addition.
2697 // 'context' represents the desired unchanged prefix/suffix around the diff.
2698 // If two hunks are close enough that their contexts overlap, then they are
2699 // joined into one hunk.
2700 std::string CreateUnifiedDiff(const std::vector<std::string>& left,
2701  const std::vector<std::string>& right,
2702  size_t context) {
2703  const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
2704 
2705  size_t l_i = 0, r_i = 0, edit_i = 0;
2706  std::stringstream ss;
2707  while (edit_i < edits.size()) {
2708  // Find first edit.
2709  while (edit_i < edits.size() && edits[edit_i] == kMatch) {
2710  ++l_i;
2711  ++r_i;
2712  ++edit_i;
2713  }
2714 
2715  // Find the first line to include in the hunk.
2716  const size_t prefix_context = std::min(l_i, context);
2717  Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
2718  for (size_t i = prefix_context; i > 0; --i) {
2719  hunk.PushLine(' ', left[l_i - i].c_str());
2720  }
2721 
2722  // Iterate the edits until we found enough suffix for the hunk or the input
2723  // is over.
2724  size_t n_suffix = 0;
2725  for (; edit_i < edits.size(); ++edit_i) {
2726  if (n_suffix >= context) {
2727  // Continue only if the next hunk is very close.
2728  std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
2729  while (it != edits.end() && *it == kMatch) ++it;
2730  if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
2731  // There is no next edit or it is too far away.
2732  break;
2733  }
2734  }
2735 
2736  EditType edit = edits[edit_i];
2737  // Reset count when a non match is found.
2738  n_suffix = edit == kMatch ? n_suffix + 1 : 0;
2739 
2740  if (edit == kMatch || edit == kRemove || edit == kReplace) {
2741  hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
2742  }
2743  if (edit == kAdd || edit == kReplace) {
2744  hunk.PushLine('+', right[r_i].c_str());
2745  }
2746 
2747  // Advance indices, depending on edit type.
2748  l_i += edit != kAdd;
2749  r_i += edit != kRemove;
2750  }
2751 
2752  if (!hunk.has_edits()) {
2753  // We are done. We don't want this hunk.
2754  break;
2755  }
2756 
2757  hunk.PrintTo(&ss);
2758  }
2759  return ss.str();
2760 }
2761 
2762 } // namespace edit_distance
2763 
2764 namespace {
2765 
2766 // The string representation of the values received in EqFailure() are already
2767 // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
2768 // characters the same.
2769 std::vector<std::string> SplitEscapedString(const std::string& str) {
2770  std::vector<std::string> lines;
2771  size_t start = 0, end = str.size();
2772  if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
2773  ++start;
2774  --end;
2775  }
2776  bool escaped = false;
2777  for (size_t i = start; i + 1 < end; ++i) {
2778  if (escaped) {
2779  escaped = false;
2780  if (str[i] == 'n') {
2781  lines.push_back(str.substr(start, i - start - 1));
2782  start = i + 1;
2783  }
2784  } else {
2785  escaped = str[i] == '\\';
2786  }
2787  }
2788  lines.push_back(str.substr(start, end - start));
2789  return lines;
2790 }
2791 
2792 } // namespace
2793 
2794 // Constructs and returns the message for an equality assertion
2795 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2796 //
2797 // The first four parameters are the expressions used in the assertion
2798 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2799 // where foo is 5 and bar is 6, we have:
2800 //
2801 // lhs_expression: "foo"
2802 // rhs_expression: "bar"
2803 // lhs_value: "5"
2804 // rhs_value: "6"
2805 //
2806 // The ignoring_case parameter is true iff the assertion is a
2807 // *_STRCASEEQ*. When it's true, the string "Ignoring case" will
2808 // be inserted into the message.
2809 AssertionResult EqFailure(const char* lhs_expression,
2810  const char* rhs_expression,
2811  const std::string& lhs_value,
2812  const std::string& rhs_value,
2813  bool ignoring_case) {
2814  Message msg;
2815  msg << "Expected equality of these values:";
2816  msg << "\n " << lhs_expression;
2817  if (lhs_value != lhs_expression) {
2818  msg << "\n Which is: " << lhs_value;
2819  }
2820  msg << "\n " << rhs_expression;
2821  if (rhs_value != rhs_expression) {
2822  msg << "\n Which is: " << rhs_value;
2823  }
2824 
2825  if (ignoring_case) {
2826  msg << "\nIgnoring case";
2827  }
2828 
2829  if (!lhs_value.empty() && !rhs_value.empty()) {
2830  const std::vector<std::string> lhs_lines =
2831  SplitEscapedString(lhs_value);
2832  const std::vector<std::string> rhs_lines =
2833  SplitEscapedString(rhs_value);
2834  if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
2835  msg << "\nWith diff:\n"
2836  << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
2837  }
2838  }
2839 
2840  return AssertionFailure() << msg;
2841 }
2842 
2843 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
2845  const AssertionResult& assertion_result,
2846  const char* expression_text,
2847  const char* actual_predicate_value,
2848  const char* expected_predicate_value) {
2849  const char* actual_message = assertion_result.message();
2850  Message msg;
2851  msg << "Value of: " << expression_text
2852  << "\n Actual: " << actual_predicate_value;
2853  if (actual_message[0] != '\0')
2854  msg << " (" << actual_message << ")";
2855  msg << "\nExpected: " << expected_predicate_value;
2856  return msg.GetString();
2857 }
2858 
2859 // Helper function for implementing ASSERT_NEAR.
2860 AssertionResult DoubleNearPredFormat(const char* expr1,
2861  const char* expr2,
2862  const char* abs_error_expr,
2863  double val1,
2864  double val2,
2865  double abs_error) {
2866  const double diff = fabs(val1 - val2);
2867  if (diff <= abs_error) return AssertionSuccess();
2868 
2869  return AssertionFailure()
2870  << "The difference between " << expr1 << " and " << expr2
2871  << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2872  << expr1 << " evaluates to " << val1 << ",\n"
2873  << expr2 << " evaluates to " << val2 << ", and\n"
2874  << abs_error_expr << " evaluates to " << abs_error << ".";
2875 }
2876 
2877 
2878 // Helper template for implementing FloatLE() and DoubleLE().
2879 template <typename RawType>
2880 AssertionResult FloatingPointLE(const char* expr1,
2881  const char* expr2,
2882  RawType val1,
2883  RawType val2) {
2884  // Returns success if val1 is less than val2,
2885  if (val1 < val2) {
2886  return AssertionSuccess();
2887  }
2888 
2889  // or if val1 is almost equal to val2.
2890  const FloatingPoint<RawType> lhs(val1), rhs(val2);
2891  if (lhs.AlmostEquals(rhs)) {
2892  return AssertionSuccess();
2893  }
2894 
2895  // Note that the above two checks will both fail if either val1 or
2896  // val2 is NaN, as the IEEE floating-point standard requires that
2897  // any predicate involving a NaN must return false.
2898 
2899  ::std::stringstream val1_ss;
2900  val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2901  << val1;
2902 
2903  ::std::stringstream val2_ss;
2904  val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2905  << val2;
2906 
2907  return AssertionFailure()
2908  << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2909  << " Actual: " << StringStreamToString(&val1_ss) << " vs "
2910  << StringStreamToString(&val2_ss);
2911 }
2912 
2913 } // namespace internal
2914 
2915 // Asserts that val1 is less than, or almost equal to, val2. Fails
2916 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2917 AssertionResult FloatLE(const char* expr1, const char* expr2,
2918  float val1, float val2) {
2919  return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2920 }
2921 
2922 // Asserts that val1 is less than, or almost equal to, val2. Fails
2923 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2924 AssertionResult DoubleLE(const char* expr1, const char* expr2,
2925  double val1, double val2) {
2926  return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2927 }
2928 
2929 namespace internal {
2930 
2931 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2932 // arguments.
2933 AssertionResult CmpHelperEQ(const char* lhs_expression,
2934  const char* rhs_expression,
2935  BiggestInt lhs,
2936  BiggestInt rhs) {
2937  if (lhs == rhs) {
2938  return AssertionSuccess();
2939  }
2940 
2941  return EqFailure(lhs_expression,
2942  rhs_expression,
2945  false);
2946 }
2947 
2948 // A macro for implementing the helper functions needed to implement
2949 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2950 // just to avoid copy-and-paste of similar code.
2951 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2952 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2953  BiggestInt val1, BiggestInt val2) {\
2954  if (val1 op val2) {\
2955  return AssertionSuccess();\
2956  } else {\
2957  return AssertionFailure() \
2958  << "Expected: (" << expr1 << ") " #op " (" << expr2\
2959  << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2960  << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2961  }\
2962 }
2963 
2964 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2965 // enum arguments.
2966 GTEST_IMPL_CMP_HELPER_(NE, !=)
2967 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2968 // enum arguments.
2969 GTEST_IMPL_CMP_HELPER_(LE, <=)
2970 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2971 // enum arguments.
2972 GTEST_IMPL_CMP_HELPER_(LT, < )
2973 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2974 // enum arguments.
2975 GTEST_IMPL_CMP_HELPER_(GE, >=)
2976 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2977 // enum arguments.
2978 GTEST_IMPL_CMP_HELPER_(GT, > )
2979 
2980 #undef GTEST_IMPL_CMP_HELPER_
2981 
2982 // The helper function for {ASSERT|EXPECT}_STREQ.
2983 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
2984  const char* rhs_expression,
2985  const char* lhs,
2986  const char* rhs) {
2987  if (String::CStringEquals(lhs, rhs)) {
2988  return AssertionSuccess();
2989  }
2990 
2991  return EqFailure(lhs_expression,
2992  rhs_expression,
2993  PrintToString(lhs),
2994  PrintToString(rhs),
2995  false);
2996 }
2997 
2998 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
2999 AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
3000  const char* rhs_expression,
3001  const char* lhs,
3002  const char* rhs) {
3003  if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
3004  return AssertionSuccess();
3005  }
3006 
3007  return EqFailure(lhs_expression,
3008  rhs_expression,
3009  PrintToString(lhs),
3010  PrintToString(rhs),
3011  true);
3012 }
3013 
3014 // The helper function for {ASSERT|EXPECT}_STRNE.
3015 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3016  const char* s2_expression,
3017  const char* s1,
3018  const char* s2) {
3019  if (!String::CStringEquals(s1, s2)) {
3020  return AssertionSuccess();
3021  } else {
3022  return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3023  << s2_expression << "), actual: \""
3024  << s1 << "\" vs \"" << s2 << "\"";
3025  }
3026 }
3027 
3028 // The helper function for {ASSERT|EXPECT}_STRCASENE.
3029 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
3030  const char* s2_expression,
3031  const char* s1,
3032  const char* s2) {
3033  if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
3034  return AssertionSuccess();
3035  } else {
3036  return AssertionFailure()
3037  << "Expected: (" << s1_expression << ") != ("
3038  << s2_expression << ") (ignoring case), actual: \""
3039  << s1 << "\" vs \"" << s2 << "\"";
3040  }
3041 }
3042 
3043 } // namespace internal
3044 
3045 namespace {
3046 
3047 // Helper functions for implementing IsSubString() and IsNotSubstring().
3048 
3049 // This group of overloaded functions return true iff needle is a
3050 // substring of haystack. NULL is considered a substring of itself
3051 // only.
3052 
3053 bool IsSubstringPred(const char* needle, const char* haystack) {
3054  if (needle == nullptr || haystack == nullptr) return needle == haystack;
3055 
3056  return strstr(haystack, needle) != nullptr;
3057 }
3058 
3059 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
3060  if (needle == nullptr || haystack == nullptr) return needle == haystack;
3061 
3062  return wcsstr(haystack, needle) != nullptr;
3063 }
3064 
3065 // StringType here can be either ::std::string or ::std::wstring.
3066 template <typename StringType>
3067 bool IsSubstringPred(const StringType& needle,
3068  const StringType& haystack) {
3069  return haystack.find(needle) != StringType::npos;
3070 }
3071 
3072 // This function implements either IsSubstring() or IsNotSubstring(),
3073 // depending on the value of the expected_to_be_substring parameter.
3074 // StringType here can be const char*, const wchar_t*, ::std::string,
3075 // or ::std::wstring.
3076 template <typename StringType>
3077 AssertionResult IsSubstringImpl(
3078  bool expected_to_be_substring,
3079  const char* needle_expr, const char* haystack_expr,
3080  const StringType& needle, const StringType& haystack) {
3081  if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
3082  return AssertionSuccess();
3083 
3084  const bool is_wide_string = sizeof(needle[0]) > 1;
3085  const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
3086  return AssertionFailure()
3087  << "Value of: " << needle_expr << "\n"
3088  << " Actual: " << begin_string_quote << needle << "\"\n"
3089  << "Expected: " << (expected_to_be_substring ? "" : "not ")
3090  << "a substring of " << haystack_expr << "\n"
3091  << "Which is: " << begin_string_quote << haystack << "\"";
3092 }
3093 
3094 } // namespace
3095 
3096 // IsSubstring() and IsNotSubstring() check whether needle is a
3097 // substring of haystack (NULL is considered a substring of itself
3098 // only), and return an appropriate error message when they fail.
3099 
3100 AssertionResult IsSubstring(
3101  const char* needle_expr, const char* haystack_expr,
3102  const char* needle, const char* haystack) {
3103  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3104 }
3105 
3106 AssertionResult IsSubstring(
3107  const char* needle_expr, const char* haystack_expr,
3108  const wchar_t* needle, const wchar_t* haystack) {
3109  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3110 }
3111 
3112 AssertionResult IsNotSubstring(
3113  const char* needle_expr, const char* haystack_expr,
3114  const char* needle, const char* haystack) {
3115  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3116 }
3117 
3118 AssertionResult IsNotSubstring(
3119  const char* needle_expr, const char* haystack_expr,
3120  const wchar_t* needle, const wchar_t* haystack) {
3121  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3122 }
3123 
3124 AssertionResult IsSubstring(
3125  const char* needle_expr, const char* haystack_expr,
3126  const ::std::string& needle, const ::std::string& haystack) {
3127  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3128 }
3129 
3130 AssertionResult IsNotSubstring(
3131  const char* needle_expr, const char* haystack_expr,
3132  const ::std::string& needle, const ::std::string& haystack) {
3133  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3134 }
3135 
3136 #if GTEST_HAS_STD_WSTRING
3137 AssertionResult IsSubstring(
3138  const char* needle_expr, const char* haystack_expr,
3139  const ::std::wstring& needle, const ::std::wstring& haystack) {
3140  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3141 }
3142 
3143 AssertionResult IsNotSubstring(
3144  const char* needle_expr, const char* haystack_expr,
3145  const ::std::wstring& needle, const ::std::wstring& haystack) {
3146  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3147 }
3148 #endif // GTEST_HAS_STD_WSTRING
3149 
3150 namespace internal {
3151 
3152 #if GTEST_OS_WINDOWS
3153 
3154 namespace {
3155 
3156 // Helper function for IsHRESULT{SuccessFailure} predicates
3157 AssertionResult HRESULTFailureHelper(const char* expr,
3158  const char* expected,
3159  long hr) { // NOLINT
3160 # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
3161 
3162  // Windows CE doesn't support FormatMessage.
3163  const char error_text[] = "";
3164 
3165 # else
3166 
3167  // Looks up the human-readable system message for the HRESULT code
3168  // and since we're not passing any params to FormatMessage, we don't
3169  // want inserts expanded.
3170  const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
3171  FORMAT_MESSAGE_IGNORE_INSERTS;
3172  const DWORD kBufSize = 4096;
3173  // Gets the system's human readable message string for this HRESULT.
3174  char error_text[kBufSize] = { '\0' };
3175  DWORD message_length = ::FormatMessageA(kFlags,
3176  0, // no source, we're asking system
3177  hr, // the error
3178  0, // no line width restrictions
3179  error_text, // output buffer
3180  kBufSize, // buf size
3181  nullptr); // no arguments for inserts
3182  // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
3183  for (; message_length && IsSpace(error_text[message_length - 1]);
3184  --message_length) {
3185  error_text[message_length - 1] = '\0';
3186  }
3187 
3188 # endif // GTEST_OS_WINDOWS_MOBILE
3189 
3190  const std::string error_hex("0x" + String::FormatHexInt(hr));
3191  return ::testing::AssertionFailure()
3192  << "Expected: " << expr << " " << expected << ".\n"
3193  << " Actual: " << error_hex << " " << error_text << "\n";
3194 }
3195 
3196 } // namespace
3197 
3198 AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
3199  if (SUCCEEDED(hr)) {
3200  return AssertionSuccess();
3201  }
3202  return HRESULTFailureHelper(expr, "succeeds", hr);
3203 }
3204 
3205 AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
3206  if (FAILED(hr)) {
3207  return AssertionSuccess();
3208  }
3209  return HRESULTFailureHelper(expr, "fails", hr);
3210 }
3211 
3212 #endif // GTEST_OS_WINDOWS
3213 
3214 // Utility functions for encoding Unicode text (wide strings) in
3215 // UTF-8.
3216 
3217 // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
3218 // like this:
3219 //
3220 // Code-point length Encoding
3221 // 0 - 7 bits 0xxxxxxx
3222 // 8 - 11 bits 110xxxxx 10xxxxxx
3223 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
3224 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
3225 
3226 // The maximum code-point a one-byte UTF-8 sequence can represent.
3227 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
3228 
3229 // The maximum code-point a two-byte UTF-8 sequence can represent.
3230 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
3231 
3232 // The maximum code-point a three-byte UTF-8 sequence can represent.
3233 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
3234 
3235 // The maximum code-point a four-byte UTF-8 sequence can represent.
3236 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
3237 
3238 // Chops off the n lowest bits from a bit pattern. Returns the n
3239 // lowest bits. As a side effect, the original bit pattern will be
3240 // shifted to the right by n bits.
3241 inline UInt32 ChopLowBits(UInt32* bits, int n) {
3242  const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
3243  *bits >>= n;
3244  return low_bits;
3245 }
3246 
3247 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
3248 // code_point parameter is of type UInt32 because wchar_t may not be
3249 // wide enough to contain a code point.
3250 // If the code_point is not a valid Unicode code point
3251 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
3252 // to "(Invalid Unicode 0xXXXXXXXX)".
3253 std::string CodePointToUtf8(UInt32 code_point) {
3254  if (code_point > kMaxCodePoint4) {
3255  return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
3256  }
3257 
3258  char str[5]; // Big enough for the largest valid code point.
3259  if (code_point <= kMaxCodePoint1) {
3260  str[1] = '\0';
3261  str[0] = static_cast<char>(code_point); // 0xxxxxxx
3262  } else if (code_point <= kMaxCodePoint2) {
3263  str[2] = '\0';
3264  str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3265  str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
3266  } else if (code_point <= kMaxCodePoint3) {
3267  str[3] = '\0';
3268  str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3269  str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3270  str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
3271  } else { // code_point <= kMaxCodePoint4
3272  str[4] = '\0';
3273  str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3274  str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3275  str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3276  str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
3277  }
3278  return str;
3279 }
3280 
3281 // The following two functions only make sense if the system
3282 // uses UTF-16 for wide string encoding. All supported systems
3283 // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
3284 
3285 // Determines if the arguments constitute UTF-16 surrogate pair
3286 // and thus should be combined into a single Unicode code point
3287 // using CreateCodePointFromUtf16SurrogatePair.
3288 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
3289  return sizeof(wchar_t) == 2 &&
3290  (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
3291 }
3292 
3293 // Creates a Unicode code point from UTF16 surrogate pair.
3294 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
3295  wchar_t second) {
3296  const UInt32 mask = (1 << 10) - 1;
3297  return (sizeof(wchar_t) == 2) ?
3298  (((first & mask) << 10) | (second & mask)) + 0x10000 :
3299  // This function should not be called when the condition is
3300  // false, but we provide a sensible default in case it is.
3301  static_cast<UInt32>(first);
3302 }
3303 
3304 // Converts a wide string to a narrow string in UTF-8 encoding.
3305 // The wide string is assumed to have the following encoding:
3306 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
3307 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
3308 // Parameter str points to a null-terminated wide string.
3309 // Parameter num_chars may additionally limit the number
3310 // of wchar_t characters processed. -1 is used when the entire string
3311 // should be processed.
3312 // If the string contains code points that are not valid Unicode code points
3313 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
3314 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
3315 // and contains invalid UTF-16 surrogate pairs, values in those pairs
3316 // will be encoded as individual Unicode characters from Basic Normal Plane.
3317 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
3318  if (num_chars == -1)
3319  num_chars = static_cast<int>(wcslen(str));
3320 
3321  ::std::stringstream stream;
3322  for (int i = 0; i < num_chars; ++i) {
3323  UInt32 unicode_code_point;
3324 
3325  if (str[i] == L'\0') {
3326  break;
3327  } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
3328  unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
3329  str[i + 1]);
3330  i++;
3331  } else {
3332  unicode_code_point = static_cast<UInt32>(str[i]);
3333  }
3334 
3335  stream << CodePointToUtf8(unicode_code_point);
3336  }
3337  return StringStreamToString(&stream);
3338 }
3339 
3340 // Converts a wide C string to an std::string using the UTF-8 encoding.
3341 // NULL will be converted to "(null)".
3342 std::string String::ShowWideCString(const wchar_t * wide_c_str) {
3343  if (wide_c_str == nullptr) return "(null)";
3344 
3345  return internal::WideStringToUtf8(wide_c_str, -1);
3346 }
3347 
3348 // Compares two wide C strings. Returns true iff they have the same
3349 // content.
3350 //
3351 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
3352 // C string is considered different to any non-NULL C string,
3353 // including the empty string.
3354 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
3355  if (lhs == nullptr) return rhs == nullptr;
3356 
3357  if (rhs == nullptr) return false;
3358 
3359  return wcscmp(lhs, rhs) == 0;
3360 }
3361 
3362 // Helper function for *_STREQ on wide strings.
3363 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
3364  const char* rhs_expression,
3365  const wchar_t* lhs,
3366  const wchar_t* rhs) {
3367  if (String::WideCStringEquals(lhs, rhs)) {
3368  return AssertionSuccess();
3369  }
3370 
3371  return EqFailure(lhs_expression,
3372  rhs_expression,
3373  PrintToString(lhs),
3374  PrintToString(rhs),
3375  false);
3376 }
3377 
3378 // Helper function for *_STRNE on wide strings.
3379 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3380  const char* s2_expression,
3381  const wchar_t* s1,
3382  const wchar_t* s2) {
3383  if (!String::WideCStringEquals(s1, s2)) {
3384  return AssertionSuccess();
3385  }
3386 
3387  return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3388  << s2_expression << "), actual: "
3389  << PrintToString(s1)
3390  << " vs " << PrintToString(s2);
3391 }
3392 
3393 // Compares two C strings, ignoring case. Returns true iff they have
3394 // the same content.
3395 //
3396 // Unlike strcasecmp(), this function can handle NULL argument(s). A
3397 // NULL C string is considered different to any non-NULL C string,
3398 // including the empty string.
3399 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
3400  if (lhs == nullptr) return rhs == nullptr;
3401  if (rhs == nullptr) return false;
3402  return posix::StrCaseCmp(lhs, rhs) == 0;
3403 }
3404 
3405  // Compares two wide C strings, ignoring case. Returns true iff they
3406  // have the same content.
3407  //
3408  // Unlike wcscasecmp(), this function can handle NULL argument(s).
3409  // A NULL C string is considered different to any non-NULL wide C string,
3410  // including the empty string.
3411  // NB: The implementations on different platforms slightly differ.
3412  // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3413  // environment variable. On GNU platform this method uses wcscasecmp
3414  // which compares according to LC_CTYPE category of the current locale.
3415  // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3416  // current locale.
3417 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3418  const wchar_t* rhs) {
3419  if (lhs == nullptr) return rhs == nullptr;
3420 
3421  if (rhs == nullptr) return false;
3422 
3423 #if GTEST_OS_WINDOWS
3424  return _wcsicmp(lhs, rhs) == 0;
3425 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3426  return wcscasecmp(lhs, rhs) == 0;
3427 #else
3428  // Android, Mac OS X and Cygwin don't define wcscasecmp.
3429  // Other unknown OSes may not define it either.
3430  wint_t left, right;
3431  do {
3432  left = towlower(*lhs++);
3433  right = towlower(*rhs++);
3434  } while (left && left == right);
3435  return left == right;
3436 #endif // OS selector
3437 }
3438 
3439 // Returns true iff str ends with the given suffix, ignoring case.
3440 // Any string is considered to end with an empty suffix.
3441 bool String::EndsWithCaseInsensitive(
3442  const std::string& str, const std::string& suffix) {
3443  const size_t str_len = str.length();
3444  const size_t suffix_len = suffix.length();
3445  return (str_len >= suffix_len) &&
3446  CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3447  suffix.c_str());
3448 }
3449 
3450 // Formats an int value as "%02d".
3451 std::string String::FormatIntWidth2(int value) {
3452  std::stringstream ss;
3453  ss << std::setfill('0') << std::setw(2) << value;
3454  return ss.str();
3455 }
3456 
3457 // Formats an int value as "%X".
3458 std::string String::FormatHexInt(int value) {
3459  std::stringstream ss;
3460  ss << std::hex << std::uppercase << value;
3461  return ss.str();
3462 }
3463 
3464 // Formats a byte as "%02X".
3465 std::string String::FormatByte(unsigned char value) {
3466  std::stringstream ss;
3467  ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3468  << static_cast<unsigned int>(value);
3469  return ss.str();
3470 }
3471 
3472 // Converts the buffer in a stringstream to an std::string, converting NUL
3473 // bytes to "\\0" along the way.
3474 std::string StringStreamToString(::std::stringstream* ss) {
3475  const ::std::string& str = ss->str();
3476  const char* const start = str.c_str();
3477  const char* const end = start + str.length();
3478 
3479  std::string result;
3480  result.reserve(2 * (end - start));
3481  for (const char* ch = start; ch != end; ++ch) {
3482  if (*ch == '\0') {
3483  result += "\\0"; // Replaces NUL with "\\0";
3484  } else {
3485  result += *ch;
3486  }
3487  }
3488 
3489  return result;
3490 }
3491 
3492 // Appends the user-supplied message to the Google-Test-generated message.
3493 std::string AppendUserMessage(const std::string& gtest_msg,
3494  const Message& user_msg) {
3495  // Appends the user message if it's non-empty.
3496  const std::string user_msg_string = user_msg.GetString();
3497  if (user_msg_string.empty()) {
3498  return gtest_msg;
3499  }
3500 
3501  return gtest_msg + "\n" + user_msg_string;
3502 }
3503 
3504 } // namespace internal
3505 
3506 // class TestResult
3507 
3508 // Creates an empty TestResult.
3509 TestResult::TestResult()
3510  : death_test_count_(0),
3511  elapsed_time_(0) {
3512 }
3513 
3514 // D'tor.
3515 TestResult::~TestResult() {
3516 }
3517 
3518 // Returns the i-th test part result among all the results. i can
3519 // range from 0 to total_part_count() - 1. If i is not in that range,
3520 // aborts the program.
3521 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3522  if (i < 0 || i >= total_part_count())
3524  return test_part_results_.at(i);
3525 }
3526 
3527 // Returns the i-th test property. i can range from 0 to
3528 // test_property_count() - 1. If i is not in that range, aborts the
3529 // program.
3530 const TestProperty& TestResult::GetTestProperty(int i) const {
3531  if (i < 0 || i >= test_property_count())
3533  return test_properties_.at(i);
3534 }
3535 
3536 // Clears the test part results.
3537 void TestResult::ClearTestPartResults() {
3538  test_part_results_.clear();
3539 }
3540 
3541 // Adds a test part result to the list.
3542 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3543  test_part_results_.push_back(test_part_result);
3544 }
3545 
3546 // Adds a test property to the list. If a property with the same key as the
3547 // supplied property is already represented, the value of this test_property
3548 // replaces the old value for that key.
3549 void TestResult::RecordProperty(const std::string& xml_element,
3550  const TestProperty& test_property) {
3551  if (!ValidateTestProperty(xml_element, test_property)) {
3552  return;
3553  }
3554  internal::MutexLock lock(&test_properites_mutex_);
3555  const std::vector<TestProperty>::iterator property_with_matching_key =
3556  std::find_if(test_properties_.begin(), test_properties_.end(),
3557  internal::TestPropertyKeyIs(test_property.key()));
3558  if (property_with_matching_key == test_properties_.end()) {
3559  test_properties_.push_back(test_property);
3560  return;
3561  }
3562  property_with_matching_key->SetValue(test_property.value());
3563 }
3564 
3565 // The list of reserved attributes used in the <testsuites> element of XML
3566 // output.
3567 static const char* const kReservedTestSuitesAttributes[] = {
3568  "disabled",
3569  "errors",
3570  "failures",
3571  "name",
3572  "random_seed",
3573  "tests",
3574  "time",
3575  "timestamp"
3576 };
3577 
3578 // The list of reserved attributes used in the <testsuite> element of XML
3579 // output.
3580 static const char* const kReservedTestSuiteAttributes[] = {
3581  "disabled",
3582  "errors",
3583  "failures",
3584  "name",
3585  "tests",
3586  "time"
3587 };
3588 
3589 // The list of reserved attributes used in the <testcase> element of XML output.
3590 static const char* const kReservedTestCaseAttributes[] = {
3591  "classname", "name", "status", "time",
3592  "type_param", "value_param", "file", "line"};
3593 
3594 template <int kSize>
3595 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3596  return std::vector<std::string>(array, array + kSize);
3597 }
3598 
3599 static std::vector<std::string> GetReservedAttributesForElement(
3600  const std::string& xml_element) {
3601  if (xml_element == "testsuites") {
3602  return ArrayAsVector(kReservedTestSuitesAttributes);
3603  } else if (xml_element == "testsuite") {
3604  return ArrayAsVector(kReservedTestSuiteAttributes);
3605  } else if (xml_element == "testcase") {
3606  return ArrayAsVector(kReservedTestCaseAttributes);
3607  } else {
3608  GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3609  }
3610  // This code is unreachable but some compilers may not realizes that.
3611  return std::vector<std::string>();
3612 }
3613 
3614 static std::string FormatWordList(const std::vector<std::string>& words) {
3615  Message word_list;
3616  for (size_t i = 0; i < words.size(); ++i) {
3617  if (i > 0 && words.size() > 2) {
3618  word_list << ", ";
3619  }
3620  if (i == words.size() - 1) {
3621  word_list << "and ";
3622  }
3623  word_list << "'" << words[i] << "'";
3624  }
3625  return word_list.GetString();
3626 }
3627 
3628 static bool ValidateTestPropertyName(
3629  const std::string& property_name,
3630  const std::vector<std::string>& reserved_names) {
3631  if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3632  reserved_names.end()) {
3633  ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3634  << " (" << FormatWordList(reserved_names)
3635  << " are reserved by " << GTEST_NAME_ << ")";
3636  return false;
3637  }
3638  return true;
3639 }
3640 
3641 // Adds a failure if the key is a reserved attribute of the element named
3642 // xml_element. Returns true if the property is valid.
3643 bool TestResult::ValidateTestProperty(const std::string& xml_element,
3644  const TestProperty& test_property) {
3645  return ValidateTestPropertyName(test_property.key(),
3646  GetReservedAttributesForElement(xml_element));
3647 }
3648 
3649 // Clears the object.
3650 void TestResult::Clear() {
3651  test_part_results_.clear();
3652  test_properties_.clear();
3653  death_test_count_ = 0;
3654  elapsed_time_ = 0;
3655 }
3656 
3657 // Returns true off the test part was skipped.
3658 static bool TestPartSkipped(const TestPartResult& result) {
3659  return result.skipped();
3660 }
3661 
3662 // Returns true iff the test was skipped.
3663 bool TestResult::Skipped() const {
3664  return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
3665 }
3666 
3667 // Returns true iff the test failed.
3668 bool TestResult::Failed() const {
3669  for (int i = 0; i < total_part_count(); ++i) {
3670  if (GetTestPartResult(i).failed())
3671  return true;
3672  }
3673  return false;
3674 }
3675 
3676 // Returns true iff the test part fatally failed.
3677 static bool TestPartFatallyFailed(const TestPartResult& result) {
3678  return result.fatally_failed();
3679 }
3680 
3681 // Returns true iff the test fatally failed.
3682 bool TestResult::HasFatalFailure() const {
3683  return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3684 }
3685 
3686 // Returns true iff the test part non-fatally failed.
3687 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3688  return result.nonfatally_failed();
3689 }
3690 
3691 // Returns true iff the test has a non-fatal failure.
3692 bool TestResult::HasNonfatalFailure() const {
3693  return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3694 }
3695 
3696 // Gets the number of all test parts. This is the sum of the number
3697 // of successful test parts and the number of failed test parts.
3698 int TestResult::total_part_count() const {
3699  return static_cast<int>(test_part_results_.size());
3700 }
3701 
3702 // Returns the number of the test properties.
3703 int TestResult::test_property_count() const {
3704  return static_cast<int>(test_properties_.size());
3705 }
3706 
3707 // class Test
3708 
3709 // Creates a Test object.
3710 
3711 // The c'tor saves the states of all flags.
3712 Test::Test()
3713  : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
3714 }
3715 
3716 // The d'tor restores the states of all flags. The actual work is
3717 // done by the d'tor of the gtest_flag_saver_ field, and thus not
3718 // visible here.
3719 Test::~Test() {
3720 }
3721 
3722 // Sets up the test fixture.
3723 //
3724 // A sub-class may override this.
3725 void Test::SetUp() {
3726 }
3727 
3728 // Tears down the test fixture.
3729 //
3730 // A sub-class may override this.
3731 void Test::TearDown() {
3732 }
3733 
3734 // Allows user supplied key value pairs to be recorded for later output.
3735 void Test::RecordProperty(const std::string& key, const std::string& value) {
3736  UnitTest::GetInstance()->RecordProperty(key, value);
3737 }
3738 
3739 // Allows user supplied key value pairs to be recorded for later output.
3740 void Test::RecordProperty(const std::string& key, int value) {
3741  Message value_message;
3742  value_message << value;
3743  RecordProperty(key, value_message.GetString().c_str());
3744 }
3745 
3746 namespace internal {
3747 
3748 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3749  const std::string& message) {
3750  // This function is a friend of UnitTest and as such has access to
3751  // AddTestPartResult.
3752  UnitTest::GetInstance()->AddTestPartResult(
3753  result_type,
3754  nullptr, // No info about the source file where the exception occurred.
3755  -1, // We have no info on which line caused the exception.
3756  message,
3757  ""); // No stack trace, either.
3758 }
3759 
3760 } // namespace internal
3761 
3762 // Google Test requires all tests in the same test suite to use the same test
3763 // fixture class. This function checks if the current test has the
3764 // same fixture class as the first test in the current test suite. If
3765 // yes, it returns true; otherwise it generates a Google Test failure and
3766 // returns false.
3767 bool Test::HasSameFixtureClass() {
3768  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3769  const TestSuite* const test_suite = impl->current_test_suite();
3770 
3771  // Info about the first test in the current test suite.
3772  const TestInfo* const first_test_info = test_suite->test_info_list()[0];
3773  const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3774  const char* const first_test_name = first_test_info->name();
3775 
3776  // Info about the current test.
3777  const TestInfo* const this_test_info = impl->current_test_info();
3778  const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3779  const char* const this_test_name = this_test_info->name();
3780 
3781  if (this_fixture_id != first_fixture_id) {
3782  // Is the first test defined using TEST?
3783  const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3784  // Is this test defined using TEST?
3785  const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3786 
3787  if (first_is_TEST || this_is_TEST) {
3788  // Both TEST and TEST_F appear in same test suite, which is incorrect.
3789  // Tell the user how to fix this.
3790 
3791  // Gets the name of the TEST and the name of the TEST_F. Note
3792  // that first_is_TEST and this_is_TEST cannot both be true, as
3793  // the fixture IDs are different for the two tests.
3794  const char* const TEST_name =
3795  first_is_TEST ? first_test_name : this_test_name;
3796  const char* const TEST_F_name =
3797  first_is_TEST ? this_test_name : first_test_name;
3798 
3799  ADD_FAILURE()
3800  << "All tests in the same test suite must use the same test fixture\n"
3801  << "class, so mixing TEST_F and TEST in the same test suite is\n"
3802  << "illegal. In test suite " << this_test_info->test_suite_name()
3803  << ",\n"
3804  << "test " << TEST_F_name << " is defined using TEST_F but\n"
3805  << "test " << TEST_name << " is defined using TEST. You probably\n"
3806  << "want to change the TEST to TEST_F or move it to another test\n"
3807  << "case.";
3808  } else {
3809  // Two fixture classes with the same name appear in two different
3810  // namespaces, which is not allowed. Tell the user how to fix this.
3811  ADD_FAILURE()
3812  << "All tests in the same test suite must use the same test fixture\n"
3813  << "class. However, in test suite "
3814  << this_test_info->test_suite_name() << ",\n"
3815  << "you defined test " << first_test_name << " and test "
3816  << this_test_name << "\n"
3817  << "using two different test fixture classes. This can happen if\n"
3818  << "the two classes are from different namespaces or translation\n"
3819  << "units and have the same name. You should probably rename one\n"
3820  << "of the classes to put the tests into different test suites.";
3821  }
3822  return false;
3823  }
3824 
3825  return true;
3826 }
3827 
3828 #if GTEST_HAS_SEH
3829 
3830 // Adds an "exception thrown" fatal failure to the current test. This
3831 // function returns its result via an output parameter pointer because VC++
3832 // prohibits creation of objects with destructors on stack in functions
3833 // using __try (see error C2712).
3834 static std::string* FormatSehExceptionMessage(DWORD exception_code,
3835  const char* location) {
3836  Message message;
3837  message << "SEH exception with code 0x" << std::setbase(16) <<
3838  exception_code << std::setbase(10) << " thrown in " << location << ".";
3839 
3840  return new std::string(message.GetString());
3841 }
3842 
3843 #endif // GTEST_HAS_SEH
3844 
3845 namespace internal {
3846 
3847 #if GTEST_HAS_EXCEPTIONS
3848 
3849 // Adds an "exception thrown" fatal failure to the current test.
3850 static std::string FormatCxxExceptionMessage(const char* description,
3851  const char* location) {
3852  Message message;
3853  if (description != nullptr) {
3854  message << "C++ exception with description \"" << description << "\"";
3855  } else {
3856  message << "Unknown C++ exception";
3857  }
3858  message << " thrown in " << location << ".";
3859 
3860  return message.GetString();
3861 }
3862 
3863 static std::string PrintTestPartResultToString(
3864  const TestPartResult& test_part_result);
3865 
3866 GoogleTestFailureException::GoogleTestFailureException(
3867  const TestPartResult& failure)
3868  : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3869 
3870 #endif // GTEST_HAS_EXCEPTIONS
3871 
3872 // We put these helper functions in the internal namespace as IBM's xlC
3873 // compiler rejects the code if they were declared static.
3874 
3875 // Runs the given method and handles SEH exceptions it throws, when
3876 // SEH is supported; returns the 0-value for type Result in case of an
3877 // SEH exception. (Microsoft compilers cannot handle SEH and C++
3878 // exceptions in the same function. Therefore, we provide a separate
3879 // wrapper function for handling SEH exceptions.)
3880 template <class T, typename Result>
3881 Result HandleSehExceptionsInMethodIfSupported(
3882  T* object, Result (T::*method)(), const char* location) {
3883 #if GTEST_HAS_SEH
3884  __try {
3885  return (object->*method)();
3886  } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
3887  GetExceptionCode())) {
3888  // We create the exception message on the heap because VC++ prohibits
3889  // creation of objects with destructors on stack in functions using __try
3890  // (see error C2712).
3891  std::string* exception_message = FormatSehExceptionMessage(
3892  GetExceptionCode(), location);
3893  internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3894  *exception_message);
3895  delete exception_message;
3896  return static_cast<Result>(0);
3897  }
3898 #else
3899  (void)location;
3900  return (object->*method)();
3901 #endif // GTEST_HAS_SEH
3902 }
3903 
3904 // Runs the given method and catches and reports C++ and/or SEH-style
3905 // exceptions, if they are supported; returns the 0-value for type
3906 // Result in case of an SEH exception.
3907 template <class T, typename Result>
3908 Result HandleExceptionsInMethodIfSupported(
3909  T* object, Result (T::*method)(), const char* location) {
3910  // NOTE: The user code can affect the way in which Google Test handles
3911  // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3912  // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3913  // after the exception is caught and either report or re-throw the
3914  // exception based on the flag's value:
3915  //
3916  // try {
3917  // // Perform the test method.
3918  // } catch (...) {
3919  // if (GTEST_FLAG(catch_exceptions))
3920  // // Report the exception as failure.
3921  // else
3922  // throw; // Re-throws the original exception.
3923  // }
3924  //
3925  // However, the purpose of this flag is to allow the program to drop into
3926  // the debugger when the exception is thrown. On most platforms, once the
3927  // control enters the catch block, the exception origin information is
3928  // lost and the debugger will stop the program at the point of the
3929  // re-throw in this function -- instead of at the point of the original
3930  // throw statement in the code under test. For this reason, we perform
3931  // the check early, sacrificing the ability to affect Google Test's
3932  // exception handling in the method where the exception is thrown.
3933  if (internal::GetUnitTestImpl()->catch_exceptions()) {
3934 #if GTEST_HAS_EXCEPTIONS
3935  try {
3936  return HandleSehExceptionsInMethodIfSupported(object, method, location);
3937  } catch (const AssertionException&) { // NOLINT
3938  // This failure was reported already.
3939  } catch (const internal::GoogleTestFailureException&) { // NOLINT
3940  // This exception type can only be thrown by a failed Google
3941  // Test assertion with the intention of letting another testing
3942  // framework catch it. Therefore we just re-throw it.
3943  throw;
3944  } catch (const std::exception& e) { // NOLINT
3945  internal::ReportFailureInUnknownLocation(
3946  TestPartResult::kFatalFailure,
3947  FormatCxxExceptionMessage(e.what(), location));
3948  } catch (...) { // NOLINT
3949  internal::ReportFailureInUnknownLocation(
3950  TestPartResult::kFatalFailure,
3951  FormatCxxExceptionMessage(nullptr, location));
3952  }
3953  return static_cast<Result>(0);
3954 #else
3955  return HandleSehExceptionsInMethodIfSupported(object, method, location);
3956 #endif // GTEST_HAS_EXCEPTIONS
3957  } else {
3958  return (object->*method)();
3959  }
3960 }
3961 
3962 } // namespace internal
3963 
3964 // Runs the test and updates the test result.
3965 void Test::Run() {
3966  if (!HasSameFixtureClass()) return;
3967 
3968  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3969  impl->os_stack_trace_getter()->UponLeavingGTest();
3970  internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3971  // We will run the test only if SetUp() was successful and didn't call
3972  // GTEST_SKIP().
3973  if (!HasFatalFailure() && !IsSkipped()) {
3974  impl->os_stack_trace_getter()->UponLeavingGTest();
3975  internal::HandleExceptionsInMethodIfSupported(
3976  this, &Test::TestBody, "the test body");
3977  }
3978 
3979  // However, we want to clean up as much as possible. Hence we will
3980  // always call TearDown(), even if SetUp() or the test body has
3981  // failed.
3982  impl->os_stack_trace_getter()->UponLeavingGTest();
3983  internal::HandleExceptionsInMethodIfSupported(
3984  this, &Test::TearDown, "TearDown()");
3985 }
3986 
3987 // Returns true iff the current test has a fatal failure.
3988 bool Test::HasFatalFailure() {
3989  return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3990 }
3991 
3992 // Returns true iff the current test has a non-fatal failure.
3993 bool Test::HasNonfatalFailure() {
3994  return internal::GetUnitTestImpl()->current_test_result()->
3995  HasNonfatalFailure();
3996 }
3997 
3998 // Returns true iff the current test was skipped.
3999 bool Test::IsSkipped() {
4000  return internal::GetUnitTestImpl()->current_test_result()->Skipped();
4001 }
4002 
4003 // class TestInfo
4004 
4005 // Constructs a TestInfo object. It assumes ownership of the test factory
4006 // object.
4007 TestInfo::TestInfo(const std::string& a_test_suite_name,
4008  const std::string& a_name, const char* a_type_param,
4009  const char* a_value_param,
4010  internal::CodeLocation a_code_location,
4011  internal::TypeId fixture_class_id,
4012  internal::TestFactoryBase* factory)
4013  : test_suite_name_(a_test_suite_name),
4014  name_(a_name),
4015  type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
4016  value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
4017  location_(a_code_location),
4018  fixture_class_id_(fixture_class_id),
4019  should_run_(false),
4020  is_disabled_(false),
4021  matches_filter_(false),
4022  factory_(factory),
4023  result_() {}
4024 
4025 // Destructs a TestInfo object.
4026 TestInfo::~TestInfo() { delete factory_; }
4027 
4028 namespace internal {
4029 
4030 // Creates a new TestInfo object and registers it with Google Test;
4031 // returns the created object.
4032 //
4033 // Arguments:
4034 //
4035 // test_suite_name: name of the test suite
4036 // name: name of the test
4037 // type_param: the name of the test's type parameter, or NULL if
4038 // this is not a typed or a type-parameterized test.
4039 // value_param: text representation of the test's value parameter,
4040 // or NULL if this is not a value-parameterized test.
4041 // code_location: code location where the test is defined
4042 // fixture_class_id: ID of the test fixture class
4043 // set_up_tc: pointer to the function that sets up the test suite
4044 // tear_down_tc: pointer to the function that tears down the test suite
4045 // factory: pointer to the factory that creates a test object.
4046 // The newly created TestInfo instance will assume
4047 // ownership of the factory object.
4048 TestInfo* MakeAndRegisterTestInfo(
4049  const char* test_suite_name, const char* name, const char* type_param,
4050  const char* value_param, CodeLocation code_location,
4051  TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
4052  TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
4053  TestInfo* const test_info =
4054  new TestInfo(test_suite_name, name, type_param, value_param,
4055  code_location, fixture_class_id, factory);
4056  GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
4057  return test_info;
4058 }
4059 
4060 void ReportInvalidTestSuiteType(const char* test_suite_name,
4061  CodeLocation code_location) {
4062  Message errors;
4063  errors
4064  << "Attempted redefinition of test suite " << test_suite_name << ".\n"
4065  << "All tests in the same test suite must use the same test fixture\n"
4066  << "class. However, in test suite " << test_suite_name << ", you tried\n"
4067  << "to define a test using a fixture class different from the one\n"
4068  << "used earlier. This can happen if the two fixture classes are\n"
4069  << "from different namespaces and have the same name. You should\n"
4070  << "probably rename one of the classes to put the tests into different\n"
4071  << "test suites.";
4072 
4073  GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
4074  code_location.line)
4075  << " " << errors.GetString();
4076 }
4077 } // namespace internal
4078 
4079 namespace {
4080 
4081 // A predicate that checks the test name of a TestInfo against a known
4082 // value.
4083 //
4084 // This is used for implementation of the TestSuite class only. We put
4085 // it in the anonymous namespace to prevent polluting the outer
4086 // namespace.
4087 //
4088 // TestNameIs is copyable.
4089 class TestNameIs {
4090  public:
4091  // Constructor.
4092  //
4093  // TestNameIs has NO default constructor.
4094  explicit TestNameIs(const char* name)
4095  : name_(name) {}
4096 
4097  // Returns true iff the test name of test_info matches name_.
4098  bool operator()(const TestInfo * test_info) const {
4099  return test_info && test_info->name() == name_;
4100  }
4101 
4102  private:
4103  std::string name_;
4104 };
4105 
4106 } // namespace
4107 
4108 namespace internal {
4109 
4110 // This method expands all parameterized tests registered with macros TEST_P
4111 // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
4112 // This will be done just once during the program runtime.
4113 void UnitTestImpl::RegisterParameterizedTests() {
4114  if (!parameterized_tests_registered_) {
4115  parameterized_test_registry_.RegisterTests();
4116  parameterized_tests_registered_ = true;
4117  }
4118 }
4119 
4120 } // namespace internal
4121 
4122 // Creates the test object, runs it, records its result, and then
4123 // deletes it.
4124 void TestInfo::Run() {
4125  if (!should_run_) return;
4126 
4127  // Tells UnitTest where to store test result.
4128  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4129  impl->set_current_test_info(this);
4130 
4131  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4132 
4133  // Notifies the unit test event listeners that a test is about to start.
4134  repeater->OnTestStart(*this);
4135 
4136  const TimeInMillis start = internal::GetTimeInMillis();
4137 
4138  impl->os_stack_trace_getter()->UponLeavingGTest();
4139 
4140  // Creates the test object.
4141  Test* const test = internal::HandleExceptionsInMethodIfSupported(
4142  factory_, &internal::TestFactoryBase::CreateTest,
4143  "the test fixture's constructor");
4144 
4145  // Runs the test if the constructor didn't generate a fatal failure or invoke
4146  // GTEST_SKIP().
4147  // Note that the object will not be null
4148  if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
4149  // This doesn't throw as all user code that can throw are wrapped into
4150  // exception handling code.
4151  test->Run();
4152  }
4153 
4154  // Deletes the test object.
4155  impl->os_stack_trace_getter()->UponLeavingGTest();
4156  internal::HandleExceptionsInMethodIfSupported(
4157  test, &Test::DeleteSelf_, "the test fixture's destructor");
4158 
4159  result_.set_elapsed_time(internal::GetTimeInMillis() - start);
4160 
4161  // Notifies the unit test event listener that a test has just finished.
4162  repeater->OnTestEnd(*this);
4163 
4164  // Tells UnitTest to stop associating assertion results to this
4165  // test.
4166  impl->set_current_test_info(nullptr);
4167 }
4168 
4169 // class TestSuite
4170 
4171 // Gets the number of successful tests in this test suite.
4172 int TestSuite::successful_test_count() const {
4173  return CountIf(test_info_list_, TestPassed);
4174 }
4175 
4176 // Gets the number of successful tests in this test suite.
4177 int TestSuite::skipped_test_count() const {
4178  return CountIf(test_info_list_, TestSkipped);
4179 }
4180 
4181 // Gets the number of failed tests in this test suite.
4182 int TestSuite::failed_test_count() const {
4183  return CountIf(test_info_list_, TestFailed);
4184 }
4185 
4186 // Gets the number of disabled tests that will be reported in the XML report.
4187 int TestSuite::reportable_disabled_test_count() const {
4188  return CountIf(test_info_list_, TestReportableDisabled);
4189 }
4190 
4191 // Gets the number of disabled tests in this test suite.
4192 int TestSuite::disabled_test_count() const {
4193  return CountIf(test_info_list_, TestDisabled);
4194 }
4195 
4196 // Gets the number of tests to be printed in the XML report.
4197 int TestSuite::reportable_test_count() const {
4198  return CountIf(test_info_list_, TestReportable);
4199 }
4200 
4201 // Get the number of tests in this test suite that should run.
4202 int TestSuite::test_to_run_count() const {
4203  return CountIf(test_info_list_, ShouldRunTest);
4204 }
4205 
4206 // Gets the number of all tests.
4207 int TestSuite::total_test_count() const {
4208  return static_cast<int>(test_info_list_.size());
4209 }
4210 
4211 // Creates a TestSuite with the given name.
4212 //
4213 // Arguments:
4214 //
4215 // name: name of the test suite
4216 // a_type_param: the name of the test suite's type parameter, or NULL if
4217 // this is not a typed or a type-parameterized test suite.
4218 // set_up_tc: pointer to the function that sets up the test suite
4219 // tear_down_tc: pointer to the function that tears down the test suite
4220 TestSuite::TestSuite(const char* a_name, const char* a_type_param,
4221  internal::SetUpTestSuiteFunc set_up_tc,
4222  internal::TearDownTestSuiteFunc tear_down_tc)
4223  : name_(a_name),
4224  type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
4225  set_up_tc_(set_up_tc),
4226  tear_down_tc_(tear_down_tc),
4227  should_run_(false),
4228  elapsed_time_(0) {}
4229 
4230 // Destructor of TestSuite.
4231 TestSuite::~TestSuite() {
4232  // Deletes every Test in the collection.
4233  ForEach(test_info_list_, internal::Delete<TestInfo>);
4234 }
4235 
4236 // Returns the i-th test among all the tests. i can range from 0 to
4237 // total_test_count() - 1. If i is not in that range, returns NULL.
4238 const TestInfo* TestSuite::GetTestInfo(int i) const {
4239  const int index = GetElementOr(test_indices_, i, -1);
4240  return index < 0 ? nullptr : test_info_list_[index];
4241 }
4242 
4243 // Returns the i-th test among all the tests. i can range from 0 to
4244 // total_test_count() - 1. If i is not in that range, returns NULL.
4245 TestInfo* TestSuite::GetMutableTestInfo(int i) {
4246  const int index = GetElementOr(test_indices_, i, -1);
4247  return index < 0 ? nullptr : test_info_list_[index];
4248 }
4249 
4250 // Adds a test to this test suite. Will delete the test upon
4251 // destruction of the TestSuite object.
4252 void TestSuite::AddTestInfo(TestInfo* test_info) {
4253  test_info_list_.push_back(test_info);
4254  test_indices_.push_back(static_cast<int>(test_indices_.size()));
4255 }
4256 
4257 // Runs every test in this TestSuite.
4258 void TestSuite::Run() {
4259  if (!should_run_) return;
4260 
4261  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4262  impl->set_current_test_suite(this);
4263 
4264  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4265 
4266  // Call both legacy and the new API
4267  repeater->OnTestSuiteStart(*this);
4268 // Legacy API is deprecated but still available
4269 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
4270  repeater->OnTestCaseStart(*this);
4271 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
4272 
4273  impl->os_stack_trace_getter()->UponLeavingGTest();
4274  internal::HandleExceptionsInMethodIfSupported(
4275  this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
4276 
4277  const internal::TimeInMillis start = internal::GetTimeInMillis();
4278  for (int i = 0; i < total_test_count(); i++) {
4279  GetMutableTestInfo(i)->Run();
4280  }
4281  elapsed_time_ = internal::GetTimeInMillis() - start;
4282 
4283  impl->os_stack_trace_getter()->UponLeavingGTest();
4284  internal::HandleExceptionsInMethodIfSupported(
4285  this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()");
4286 
4287  // Call both legacy and the new API
4288  repeater->OnTestSuiteEnd(*this);
4289 // Legacy API is deprecated but still available
4290 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
4291  repeater->OnTestCaseEnd(*this);
4292 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
4293 
4294  impl->set_current_test_suite(nullptr);
4295 }
4296 
4297 // Clears the results of all tests in this test suite.
4298 void TestSuite::ClearResult() {
4299  ad_hoc_test_result_.Clear();
4300  ForEach(test_info_list_, TestInfo::ClearTestResult);
4301 }
4302 
4303 // Shuffles the tests in this test suite.
4304 void TestSuite::ShuffleTests(internal::Random* random) {
4305  Shuffle(random, &test_indices_);
4306 }
4307 
4308 // Restores the test order to before the first shuffle.
4309 void TestSuite::UnshuffleTests() {
4310  for (size_t i = 0; i < test_indices_.size(); i++) {
4311  test_indices_[i] = static_cast<int>(i);
4312  }
4313 }
4314 
4315 // Formats a countable noun. Depending on its quantity, either the
4316 // singular form or the plural form is used. e.g.
4317 //
4318 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
4319 // FormatCountableNoun(5, "book", "books") returns "5 books".
4320 static std::string FormatCountableNoun(int count,
4321  const char * singular_form,
4322  const char * plural_form) {
4323  return internal::StreamableToString(count) + " " +
4324  (count == 1 ? singular_form : plural_form);
4325 }
4326 
4327 // Formats the count of tests.
4328 static std::string FormatTestCount(int test_count) {
4329  return FormatCountableNoun(test_count, "test", "tests");
4330 }
4331 
4332 // Formats the count of test suites.
4333 static std::string FormatTestSuiteCount(int test_suite_count) {
4334  return FormatCountableNoun(test_suite_count, "test suite", "test suites");
4335 }
4336 
4337 // Converts a TestPartResult::Type enum to human-friendly string
4338 // representation. Both kNonFatalFailure and kFatalFailure are translated
4339 // to "Failure", as the user usually doesn't care about the difference
4340 // between the two when viewing the test result.
4341 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
4342  switch (type) {
4343  case TestPartResult::kSkip:
4344  return "Skipped";
4345  case TestPartResult::kSuccess:
4346  return "Success";
4347 
4348  case TestPartResult::kNonFatalFailure:
4349  case TestPartResult::kFatalFailure:
4350 #ifdef _MSC_VER
4351  return "error: ";
4352 #else
4353  return "Failure\n";
4354 #endif
4355  default:
4356  return "Unknown result type";
4357  }
4358 }
4359 
4360 namespace internal {
4361 
4362 // Prints a TestPartResult to an std::string.
4363 static std::string PrintTestPartResultToString(
4364  const TestPartResult& test_part_result) {
4365  return (Message()
4366  << internal::FormatFileLocation(test_part_result.file_name(),
4367  test_part_result.line_number())
4368  << " " << TestPartResultTypeToString(test_part_result.type())
4369  << test_part_result.message()).GetString();
4370 }
4371 
4372 // Prints a TestPartResult.
4373 static void PrintTestPartResult(const TestPartResult& test_part_result) {
4374  const std::string& result =
4375  PrintTestPartResultToString(test_part_result);
4376  printf("%s\n", result.c_str());
4377  fflush(stdout);
4378  // If the test program runs in Visual Studio or a debugger, the
4379  // following statements add the test part result message to the Output
4380  // window such that the user can double-click on it to jump to the
4381  // corresponding source code location; otherwise they do nothing.
4382 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4383  // We don't call OutputDebugString*() on Windows Mobile, as printing
4384  // to stdout is done by OutputDebugString() there already - we don't
4385  // want the same message printed twice.
4386  ::OutputDebugStringA(result.c_str());
4387  ::OutputDebugStringA("\n");
4388 #endif
4389 }
4390 
4391 // class PrettyUnitTestResultPrinter
4392 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4393  !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
4394 
4395 // Returns the character attribute for the given color.
4396 static WORD GetColorAttribute(GTestColor color) {
4397  switch (color) {
4398  case COLOR_RED: return FOREGROUND_RED;
4399  case COLOR_GREEN: return FOREGROUND_GREEN;
4400  case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
4401  default: return 0;
4402  }
4403 }
4404 
4405 static int GetBitOffset(WORD color_mask) {
4406  if (color_mask == 0) return 0;
4407 
4408  int bitOffset = 0;
4409  while ((color_mask & 1) == 0) {
4410  color_mask >>= 1;
4411  ++bitOffset;
4412  }
4413  return bitOffset;
4414 }
4415 
4416 static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
4417  // Let's reuse the BG
4418  static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
4419  BACKGROUND_RED | BACKGROUND_INTENSITY;
4420  static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
4421  FOREGROUND_RED | FOREGROUND_INTENSITY;
4422  const WORD existing_bg = old_color_attrs & background_mask;
4423 
4424  WORD new_color =
4425  GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
4426  static const int bg_bitOffset = GetBitOffset(background_mask);
4427  static const int fg_bitOffset = GetBitOffset(foreground_mask);
4428 
4429  if (((new_color & background_mask) >> bg_bitOffset) ==
4430  ((new_color & foreground_mask) >> fg_bitOffset)) {
4431  new_color ^= FOREGROUND_INTENSITY; // invert intensity
4432  }
4433  return new_color;
4434 }
4435 
4436 #else
4437 
4438 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
4439 // an invalid input.
4440 static const char* GetAnsiColorCode(GTestColor color) {
4441  switch (color) {
4442  case COLOR_RED: return "1";
4443  case COLOR_GREEN: return "2";
4444  case COLOR_YELLOW: return "3";
4445  default:
4446  return nullptr;
4447  };
4448 }
4449 
4450 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4451 
4452 // Returns true iff Google Test should use colors in the output.
4453 bool ShouldUseColor(bool stdout_is_tty) {
4454  const char* const gtest_color = GTEST_FLAG(color).c_str();
4455 
4456  if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
4457 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
4458  // On Windows the TERM variable is usually not set, but the
4459  // console there does support colors.
4460  return stdout_is_tty;
4461 #else
4462  // On non-Windows platforms, we rely on the TERM variable.
4463  const char* const term = posix::GetEnv("TERM");
4464  const bool term_supports_color =
4465  String::CStringEquals(term, "xterm") ||
4466  String::CStringEquals(term, "xterm-color") ||
4467  String::CStringEquals(term, "xterm-256color") ||
4468  String::CStringEquals(term, "screen") ||
4469  String::CStringEquals(term, "screen-256color") ||
4470  String::CStringEquals(term, "tmux") ||
4471  String::CStringEquals(term, "tmux-256color") ||
4472  String::CStringEquals(term, "rxvt-unicode") ||
4473  String::CStringEquals(term, "rxvt-unicode-256color") ||
4474  String::CStringEquals(term, "linux") ||
4475  String::CStringEquals(term, "cygwin");
4476  return stdout_is_tty && term_supports_color;
4477 #endif // GTEST_OS_WINDOWS
4478  }
4479 
4480  return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4481  String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4482  String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4483  String::CStringEquals(gtest_color, "1");
4484  // We take "yes", "true", "t", and "1" as meaning "yes". If the
4485  // value is neither one of these nor "auto", we treat it as "no" to
4486  // be conservative.
4487 }
4488 
4489 // Helpers for printing colored strings to stdout. Note that on Windows, we
4490 // cannot simply emit special characters and have the terminal change colors.
4491 // This routine must actually emit the characters rather than return a string
4492 // that would be colored when printed, as can be done on Linux.
4493 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
4494  va_list args;
4495  va_start(args, fmt);
4496 
4497 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
4498  GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
4499  const bool use_color = AlwaysFalse();
4500 #else
4501  static const bool in_color_mode =
4502  ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
4503  const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
4504 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
4505 
4506  if (!use_color) {
4507  vprintf(fmt, args);
4508  va_end(args);
4509  return;
4510  }
4511 
4512 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4513  !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
4514  const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4515 
4516  // Gets the current text color.
4517  CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4518  GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4519  const WORD old_color_attrs = buffer_info.wAttributes;
4520  const WORD new_color = GetNewColor(color, old_color_attrs);
4521 
4522  // We need to flush the stream buffers into the console before each
4523  // SetConsoleTextAttribute call lest it affect the text that is already
4524  // printed but has not yet reached the console.
4525  fflush(stdout);
4526  SetConsoleTextAttribute(stdout_handle, new_color);
4527 
4528  vprintf(fmt, args);
4529 
4530  fflush(stdout);
4531  // Restores the text color.
4532  SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4533 #else
4534  printf("\033[0;3%sm", GetAnsiColorCode(color));
4535  vprintf(fmt, args);
4536  printf("\033[m"); // Resets the terminal to default.
4537 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4538  va_end(args);
4539 }
4540 
4541 // Text printed in Google Test's text output and --gtest_list_tests
4542 // output to label the type parameter and value parameter for a test.
4543 static const char kTypeParamLabel[] = "TypeParam";
4544 static const char kValueParamLabel[] = "GetParam()";
4545 
4546 static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4547  const char* const type_param = test_info.type_param();
4548  const char* const value_param = test_info.value_param();
4549 
4550  if (type_param != nullptr || value_param != nullptr) {
4551  printf(", where ");
4552  if (type_param != nullptr) {
4553  printf("%s = %s", kTypeParamLabel, type_param);
4554  if (value_param != nullptr) printf(" and ");
4555  }
4556  if (value_param != nullptr) {
4557  printf("%s = %s", kValueParamLabel, value_param);
4558  }
4559  }
4560 }
4561 
4562 // This class implements the TestEventListener interface.
4563 //
4564 // Class PrettyUnitTestResultPrinter is copyable.
4565 class PrettyUnitTestResultPrinter : public TestEventListener {
4566  public:
4567  PrettyUnitTestResultPrinter() {}
4568  static void PrintTestName(const char* test_suite, const char* test) {
4569  printf("%s.%s", test_suite, test);
4570  }
4571 
4572  // The following methods override what's in the TestEventListener class.
4573  void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
4574  void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
4575  void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
4576  void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
4577  void OnTestCaseStart(const TestSuite& test_suite) override;
4578  void OnTestStart(const TestInfo& test_info) override;
4579  void OnTestPartResult(const TestPartResult& result) override;
4580  void OnTestEnd(const TestInfo& test_info) override;
4581  void OnTestCaseEnd(const TestSuite& test_suite) override;
4582  void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
4583  void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
4584  void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
4585  void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
4586 
4587  private:
4588  static void PrintFailedTests(const UnitTest& unit_test);
4589  static void PrintSkippedTests(const UnitTest& unit_test);
4590 };
4591 
4592  // Fired before each iteration of tests starts.
4593 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4594  const UnitTest& unit_test, int iteration) {
4595  if (GTEST_FLAG(repeat) != 1)
4596  printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4597 
4598  const char* const filter = GTEST_FLAG(filter).c_str();
4599 
4600  // Prints the filter if it's not *. This reminds the user that some
4601  // tests may be skipped.
4602  if (!String::CStringEquals(filter, kUniversalFilter)) {
4603  ColoredPrintf(COLOR_YELLOW,
4604  "Note: %s filter = %s\n", GTEST_NAME_, filter);
4605  }
4606 
4607  if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4608  const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4609  ColoredPrintf(COLOR_YELLOW,
4610  "Note: This is test shard %d of %s.\n",
4611  static_cast<int>(shard_index) + 1,
4612  internal::posix::GetEnv(kTestTotalShards));
4613  }
4614 
4615  if (GTEST_FLAG(shuffle)) {
4616  ColoredPrintf(COLOR_YELLOW,
4617  "Note: Randomizing tests' orders with a seed of %d .\n",
4618  unit_test.random_seed());
4619  }
4620 
4621  ColoredPrintf(COLOR_GREEN, "[==========] ");
4622  printf("Running %s from %s.\n",
4623  FormatTestCount(unit_test.test_to_run_count()).c_str(),
4624  FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
4625  fflush(stdout);
4626 }
4627 
4628 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4629  const UnitTest& /*unit_test*/) {
4630  ColoredPrintf(COLOR_GREEN, "[----------] ");
4631  printf("Global test environment set-up.\n");
4632  fflush(stdout);
4633 }
4634 
4635 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestSuite& test_suite) {
4636  const std::string counts =
4637  FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
4638  ColoredPrintf(COLOR_GREEN, "[----------] ");
4639  printf("%s from %s", counts.c_str(), test_suite.name());
4640  if (test_suite.type_param() == nullptr) {
4641  printf("\n");
4642  } else {
4643  printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
4644  }
4645  fflush(stdout);
4646 }
4647 
4648 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4649  ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
4650  PrintTestName(test_info.test_suite_name(), test_info.name());
4651  printf("\n");
4652  fflush(stdout);
4653 }
4654 
4655 // Called after an assertion failure.
4656 void PrettyUnitTestResultPrinter::OnTestPartResult(
4657  const TestPartResult& result) {
4658  switch (result.type()) {
4659  // If the test part succeeded, or was skipped,
4660  // we don't need to do anything.
4661  case TestPartResult::kSkip:
4662  case TestPartResult::kSuccess:
4663  return;
4664  default:
4665  // Print failure message from the assertion
4666  // (e.g. expected this and got that).
4667  PrintTestPartResult(result);
4668  fflush(stdout);
4669  }
4670 }
4671 
4672 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4673  if (test_info.result()->Passed()) {
4674  ColoredPrintf(COLOR_GREEN, "[ OK ] ");
4675  } else if (test_info.result()->Skipped()) {
4676  ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
4677  } else {
4678  ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4679  }
4680  PrintTestName(test_info.test_suite_name(), test_info.name());
4681  if (test_info.result()->Failed())
4682  PrintFullTestCommentIfPresent(test_info);
4683 
4684  if (GTEST_FLAG(print_time)) {
4685  printf(" (%s ms)\n", internal::StreamableToString(
4686  test_info.result()->elapsed_time()).c_str());
4687  } else {
4688  printf("\n");
4689  }
4690  fflush(stdout);
4691 }
4692 
4693 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestSuite& test_suite) {
4694  if (!GTEST_FLAG(print_time)) return;
4695 
4696  const std::string counts =
4697  FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
4698  ColoredPrintf(COLOR_GREEN, "[----------] ");
4699  printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
4700  internal::StreamableToString(test_suite.elapsed_time()).c_str());
4701  fflush(stdout);
4702 }
4703 
4704 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4705  const UnitTest& /*unit_test*/) {
4706  ColoredPrintf(COLOR_GREEN, "[----------] ");
4707  printf("Global test environment tear-down\n");
4708  fflush(stdout);
4709 }
4710 
4711 // Internal helper for printing the list of failed tests.
4712 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4713  const int failed_test_count = unit_test.failed_test_count();
4714  if (failed_test_count == 0) {
4715  return;
4716  }
4717 
4718  for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4719  const TestSuite& test_suite = *unit_test.GetTestSuite(i);
4720  if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
4721  continue;
4722  }
4723  for (int j = 0; j < test_suite.total_test_count(); ++j) {
4724  const TestInfo& test_info = *test_suite.GetTestInfo(j);
4725  if (!test_info.should_run() || !test_info.result()->Failed()) {
4726  continue;
4727  }
4728  ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4729  printf("%s.%s", test_suite.name(), test_info.name());
4730  PrintFullTestCommentIfPresent(test_info);
4731  printf("\n");
4732  }
4733  }
4734 }
4735 
4736 // Internal helper for printing the list of skipped tests.
4737 void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
4738  const int skipped_test_count = unit_test.skipped_test_count();
4739  if (skipped_test_count == 0) {
4740  return;
4741  }
4742 
4743  for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4744  const TestSuite& test_suite = *unit_test.GetTestSuite(i);
4745  if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
4746  continue;
4747  }
4748  for (int j = 0; j < test_suite.total_test_count(); ++j) {
4749  const TestInfo& test_info = *test_suite.GetTestInfo(j);
4750  if (!test_info.should_run() || !test_info.result()->Skipped()) {
4751  continue;
4752  }
4753  ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
4754  printf("%s.%s", test_suite.name(), test_info.name());
4755  printf("\n");
4756  }
4757  }
4758 }
4759 
4760 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4761  int /*iteration*/) {
4762  ColoredPrintf(COLOR_GREEN, "[==========] ");
4763  printf("%s from %s ran.",
4764  FormatTestCount(unit_test.test_to_run_count()).c_str(),
4765  FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
4766  if (GTEST_FLAG(print_time)) {
4767  printf(" (%s ms total)",
4768  internal::StreamableToString(unit_test.elapsed_time()).c_str());
4769  }
4770  printf("\n");
4771  ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
4772  printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4773 
4774  const int skipped_test_count = unit_test.skipped_test_count();
4775  if (skipped_test_count > 0) {
4776  ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
4777  printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
4778  PrintSkippedTests(unit_test);
4779  }
4780 
4781  int num_failures = unit_test.failed_test_count();
4782  if (!unit_test.Passed()) {
4783  const int failed_test_count = unit_test.failed_test_count();
4784  ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4785  printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4786  PrintFailedTests(unit_test);
4787  printf("\n%2d FAILED %s\n", num_failures,
4788  num_failures == 1 ? "TEST" : "TESTS");
4789  }
4790 
4791  int num_disabled = unit_test.reportable_disabled_test_count();
4792  if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4793  if (!num_failures) {
4794  printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4795  }
4796  ColoredPrintf(COLOR_YELLOW,
4797  " YOU HAVE %d DISABLED %s\n\n",
4798  num_disabled,
4799  num_disabled == 1 ? "TEST" : "TESTS");
4800  }
4801  // Ensure that Google Test output is printed before, e.g., heapchecker output.
4802  fflush(stdout);
4803 }
4804 
4805 // End PrettyUnitTestResultPrinter
4806 
4807 // class TestEventRepeater
4808 //
4809 // This class forwards events to other event listeners.
4810 class TestEventRepeater : public TestEventListener {
4811  public:
4812  TestEventRepeater() : forwarding_enabled_(true) {}
4813  ~TestEventRepeater() override;
4814  void Append(TestEventListener *listener);
4815  TestEventListener* Release(TestEventListener* listener);
4816 
4817  // Controls whether events will be forwarded to listeners_. Set to false
4818  // in death test child processes.
4819  bool forwarding_enabled() const { return forwarding_enabled_; }
4820  void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4821 
4822  void OnTestProgramStart(const UnitTest& unit_test) override;
4823  void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
4824  void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
4825  void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
4826 // Legacy API is deprecated but still available
4827 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
4828  void OnTestCaseStart(const TestSuite& parameter) override;
4829 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
4830  void OnTestSuiteStart(const TestSuite& parameter) override;
4831  void OnTestStart(const TestInfo& test_info) override;
4832  void OnTestPartResult(const TestPartResult& result) override;
4833  void OnTestEnd(const TestInfo& test_info) override;
4834 // Legacy API is deprecated but still available
4835 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
4836  void OnTestCaseEnd(const TestSuite& parameter) override;
4837 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
4838  void OnTestSuiteEnd(const TestSuite& parameter) override;
4839  void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
4840  void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
4841  void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
4842  void OnTestProgramEnd(const UnitTest& unit_test) override;
4843 
4844  private:
4845  // Controls whether events will be forwarded to listeners_. Set to false
4846  // in death test child processes.
4847  bool forwarding_enabled_;
4848  // The list of listeners that receive events.
4849  std::vector<TestEventListener*> listeners_;
4850 
4851  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4852 };
4853 
4854 TestEventRepeater::~TestEventRepeater() {
4855  ForEach(listeners_, Delete<TestEventListener>);
4856 }
4857 
4858 void TestEventRepeater::Append(TestEventListener *listener) {
4859  listeners_.push_back(listener);
4860 }
4861 
4862 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4863  for (size_t i = 0; i < listeners_.size(); ++i) {
4864  if (listeners_[i] == listener) {
4865  listeners_.erase(listeners_.begin() + i);
4866  return listener;
4867  }
4868  }
4869 
4870  return nullptr;
4871 }
4872 
4873 // Since most methods are very similar, use macros to reduce boilerplate.
4874 // This defines a member that forwards the call to all listeners.
4875 #define GTEST_REPEATER_METHOD_(Name, Type) \
4876 void TestEventRepeater::Name(const Type& parameter) { \
4877  if (forwarding_enabled_) { \
4878  for (size_t i = 0; i < listeners_.size(); i++) { \
4879  listeners_[i]->Name(parameter); \
4880  } \
4881  } \
4882 }
4883 // This defines a member that forwards the call to all listeners in reverse
4884 // order.
4885 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4886 void TestEventRepeater::Name(const Type& parameter) { \
4887  if (forwarding_enabled_) { \
4888  for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4889  listeners_[i]->Name(parameter); \
4890  } \
4891  } \
4892 }
4893 
4894 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4895 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4896 // Legacy API is deprecated but still available
4897 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4898 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
4899 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4900 GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
4901 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4902 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4903 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4904 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4905 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4906 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4907 // Legacy API is deprecated but still available
4908 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4909 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
4910 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4911 GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
4912 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4913 
4914 #undef GTEST_REPEATER_METHOD_
4915 #undef GTEST_REVERSE_REPEATER_METHOD_
4916 
4917 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4918  int iteration) {
4919  if (forwarding_enabled_) {
4920  for (size_t i = 0; i < listeners_.size(); i++) {
4921  listeners_[i]->OnTestIterationStart(unit_test, iteration);
4922  }
4923  }
4924 }
4925 
4926 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4927  int iteration) {
4928  if (forwarding_enabled_) {
4929  for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4930  listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4931  }
4932  }
4933 }
4934 
4935 // End TestEventRepeater
4936 
4937 // This class generates an XML output file.
4938 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4939  public:
4940  explicit XmlUnitTestResultPrinter(const char* output_file);
4941 
4942  void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
4943  void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);
4944 
4945  // Prints an XML summary of all unit tests.
4946  static void PrintXmlTestsList(std::ostream* stream,
4947  const std::vector<TestSuite*>& test_suites);
4948 
4949  private:
4950  // Is c a whitespace character that is normalized to a space character
4951  // when it appears in an XML attribute value?
4952  static bool IsNormalizableWhitespace(char c) {
4953  return c == 0x9 || c == 0xA || c == 0xD;
4954  }
4955 
4956  // May c appear in a well-formed XML document?
4957  static bool IsValidXmlCharacter(char c) {
4958  return IsNormalizableWhitespace(c) || c >= 0x20;
4959  }
4960 
4961  // Returns an XML-escaped copy of the input string str. If
4962  // is_attribute is true, the text is meant to appear as an attribute
4963  // value, and normalizable whitespace is preserved by replacing it
4964  // with character references.
4965  static std::string EscapeXml(const std::string& str, bool is_attribute);
4966 
4967  // Returns the given string with all characters invalid in XML removed.
4968  static std::string RemoveInvalidXmlCharacters(const std::string& str);
4969 
4970  // Convenience wrapper around EscapeXml when str is an attribute value.
4971  static std::string EscapeXmlAttribute(const std::string& str) {
4972  return EscapeXml(str, true);
4973  }
4974 
4975  // Convenience wrapper around EscapeXml when str is not an attribute value.
4976  static std::string EscapeXmlText(const char* str) {
4977  return EscapeXml(str, false);
4978  }
4979 
4980  // Verifies that the given attribute belongs to the given element and
4981  // streams the attribute as XML.
4982  static void OutputXmlAttribute(std::ostream* stream,
4983  const std::string& element_name,
4984  const std::string& name,
4985  const std::string& value);
4986 
4987  // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4988  static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4989 
4990  // Streams an XML representation of a TestInfo object.
4991  static void OutputXmlTestInfo(::std::ostream* stream,
4992  const char* test_suite_name,
4993  const TestInfo& test_info);
4994 
4995  // Prints an XML representation of a TestSuite object
4996  static void PrintXmlTestSuite(::std::ostream* stream,
4997  const TestSuite& test_suite);
4998 
4999  // Prints an XML summary of unit_test to output stream out.
5000  static void PrintXmlUnitTest(::std::ostream* stream,
5001  const UnitTest& unit_test);
5002 
5003  // Produces a string representing the test properties in a result as space
5004  // delimited XML attributes based on the property key="value" pairs.
5005  // When the std::string is not empty, it includes a space at the beginning,
5006  // to delimit this attribute from prior attributes.
5007  static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
5008 
5009  // Streams an XML representation of the test properties of a TestResult
5010  // object.
5011  static void OutputXmlTestProperties(std::ostream* stream,
5012  const TestResult& result);
5013 
5014  // The output file.
5015  const std::string output_file_;
5016 
5017  GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
5018 };
5019 
5020 // Creates a new XmlUnitTestResultPrinter.
5021 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
5022  : output_file_(output_file) {
5023  if (output_file_.empty()) {
5024  GTEST_LOG_(FATAL) << "XML output file may not be null";
5025  }
5026 }
5027 
5028 // Called after the unit test ends.
5029 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5030  int /*iteration*/) {
5031  FILE* xmlout = OpenFileForWriting(output_file_);
5032  std::stringstream stream;
5033  PrintXmlUnitTest(&stream, unit_test);
5034  fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
5035  fclose(xmlout);
5036 }
5037 
5038 void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
5039  const std::vector<TestSuite*>& test_suites) {
5040  FILE* xmlout = OpenFileForWriting(output_file_);
5041  std::stringstream stream;
5042  PrintXmlTestsList(&stream, test_suites);
5043  fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
5044  fclose(xmlout);
5045 }
5046 
5047 // Returns an XML-escaped copy of the input string str. If is_attribute
5048 // is true, the text is meant to appear as an attribute value, and
5049 // normalizable whitespace is preserved by replacing it with character
5050 // references.
5051 //
5052 // Invalid XML characters in str, if any, are stripped from the output.
5053 // It is expected that most, if not all, of the text processed by this
5054 // module will consist of ordinary English text.
5055 // If this module is ever modified to produce version 1.1 XML output,
5056 // most invalid characters can be retained using character references.
5057 std::string XmlUnitTestResultPrinter::EscapeXml(
5058  const std::string& str, bool is_attribute) {
5059  Message m;
5060 
5061  for (size_t i = 0; i < str.size(); ++i) {
5062  const char ch = str[i];
5063  switch (ch) {
5064  case '<':
5065  m << "&lt;";
5066  break;
5067  case '>':
5068  m << "&gt;";
5069  break;
5070  case '&':
5071  m << "&amp;";
5072  break;
5073  case '\'':
5074  if (is_attribute)
5075  m << "&apos;";
5076  else
5077  m << '\'';
5078  break;
5079  case '"':
5080  if (is_attribute)
5081  m << "&quot;";
5082  else
5083  m << '"';
5084  break;
5085  default:
5086  if (IsValidXmlCharacter(ch)) {
5087  if (is_attribute && IsNormalizableWhitespace(ch))
5088  m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
5089  << ";";
5090  else
5091  m << ch;
5092  }
5093  break;
5094  }
5095  }
5096 
5097  return m.GetString();
5098 }
5099 
5100 // Returns the given string with all characters invalid in XML removed.
5101 // Currently invalid characters are dropped from the string. An
5102 // alternative is to replace them with certain characters such as . or ?.
5103 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
5104  const std::string& str) {
5105  std::string output;
5106  output.reserve(str.size());
5107  for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
5108  if (IsValidXmlCharacter(*it))
5109  output.push_back(*it);
5110 
5111  return output;
5112 }
5113 
5114 // The following routines generate an XML representation of a UnitTest
5115 // object.
5116 // GOOGLETEST_CM0009 DO NOT DELETE
5117 //
5118 // This is how Google Test concepts map to the DTD:
5119 //
5120 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
5121 // <testsuite name="testcase-name"> <-- corresponds to a TestSuite object
5122 // <testcase name="test-name"> <-- corresponds to a TestInfo object
5123 // <failure message="...">...</failure>
5124 // <failure message="...">...</failure>
5125 // <failure message="...">...</failure>
5126 // <-- individual assertion failures
5127 // </testcase>
5128 // </testsuite>
5129 // </testsuites>
5130 
5131 // Formats the given time in milliseconds as seconds.
5132 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
5133  ::std::stringstream ss;
5134  ss << (static_cast<double>(ms) * 1e-3);
5135  return ss.str();
5136 }
5137 
5138 static bool PortableLocaltime(time_t seconds, struct tm* out) {
5139 #if defined(_MSC_VER)
5140  return localtime_s(out, &seconds) == 0;
5141 #elif defined(__MINGW32__) || defined(__MINGW64__)
5142  // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
5143  // Windows' localtime(), which has a thread-local tm buffer.
5144  struct tm* tm_ptr = localtime(&seconds); // NOLINT
5145  if (tm_ptr == nullptr) return false;
5146  *out = *tm_ptr;
5147  return true;
5148 #else
5149  return localtime_r(&seconds, out) != nullptr;
5150 #endif
5151 }
5152 
5153 // Converts the given epoch time in milliseconds to a date string in the ISO
5154 // 8601 format, without the timezone information.
5155 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
5156  struct tm time_struct;
5157  if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5158  return "";
5159  // YYYY-MM-DDThh:mm:ss
5160  return StreamableToString(time_struct.tm_year + 1900) + "-" +
5161  String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5162  String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5163  String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5164  String::FormatIntWidth2(time_struct.tm_min) + ":" +
5165  String::FormatIntWidth2(time_struct.tm_sec);
5166 }
5167 
5168 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
5169 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
5170  const char* data) {
5171  const char* segment = data;
5172  *stream << "<![CDATA[";
5173  for (;;) {
5174  const char* const next_segment = strstr(segment, "]]>");
5175  if (next_segment != nullptr) {
5176  stream->write(
5177  segment, static_cast<std::streamsize>(next_segment - segment));
5178  *stream << "]]>]]&gt;<![CDATA[";
5179  segment = next_segment + strlen("]]>");
5180  } else {
5181  *stream << segment;
5182  break;
5183  }
5184  }
5185  *stream << "]]>";
5186 }
5187 
5188 void XmlUnitTestResultPrinter::OutputXmlAttribute(
5189  std::ostream* stream,
5190  const std::string& element_name,
5191  const std::string& name,
5192  const std::string& value) {
5193  const std::vector<std::string>& allowed_names =
5194  GetReservedAttributesForElement(element_name);
5195 
5196  GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5197  allowed_names.end())
5198  << "Attribute " << name << " is not allowed for element <" << element_name
5199  << ">.";
5200 
5201  *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
5202 }
5203 
5204 // Prints an XML representation of a TestInfo object.
5205 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
5206  const char* test_suite_name,
5207  const TestInfo& test_info) {
5208  const TestResult& result = *test_info.result();
5209  const std::string kTestsuite = "testcase";
5210 
5211  if (test_info.is_in_another_shard()) {
5212  return;
5213  }
5214 
5215  *stream << " <testcase";
5216  OutputXmlAttribute(stream, kTestsuite, "name", test_info.name());
5217 
5218  if (test_info.value_param() != nullptr) {
5219  OutputXmlAttribute(stream, kTestsuite, "value_param",
5220  test_info.value_param());
5221  }
5222  if (test_info.type_param() != nullptr) {
5223  OutputXmlAttribute(stream, kTestsuite, "type_param",
5224  test_info.type_param());
5225  }
5226  if (GTEST_FLAG(list_tests)) {
5227  OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
5228  OutputXmlAttribute(stream, kTestsuite, "line",
5229  StreamableToString(test_info.line()));
5230  *stream << " />\n";
5231  return;
5232  }
5233 
5234  OutputXmlAttribute(
5235  stream, kTestsuite, "status",
5236  result.Skipped() ? "skipped" : test_info.should_run() ? "run" : "notrun");
5237  OutputXmlAttribute(stream, kTestsuite, "time",
5238  FormatTimeInMillisAsSeconds(result.elapsed_time()));
5239  OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
5240 
5241  int failures = 0;
5242  for (int i = 0; i < result.total_part_count(); ++i) {
5243  const TestPartResult& part = result.GetTestPartResult(i);
5244  if (part.failed()) {
5245  if (++failures == 1) {
5246  *stream << ">\n";
5247  }
5248  const std::string location =
5250  part.line_number());
5251  const std::string summary = location + "\n" + part.summary();
5252  *stream << " <failure message=\""
5253  << EscapeXmlAttribute(summary.c_str())
5254  << "\" type=\"\">";
5255  const std::string detail = location + "\n" + part.message();
5256  OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
5257  *stream << "</failure>\n";
5258  }
5259  }
5260 
5261  if (failures == 0 && result.test_property_count() == 0) {
5262  *stream << " />\n";
5263  } else {
5264  if (failures == 0) {
5265  *stream << ">\n";
5266  }
5267  OutputXmlTestProperties(stream, result);
5268  *stream << " </testcase>\n";
5269  }
5270 }
5271 
5272 // Prints an XML representation of a TestSuite object
5273 void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
5274  const TestSuite& test_suite) {
5275  const std::string kTestsuite = "testsuite";
5276  *stream << " <" << kTestsuite;
5277  OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
5278  OutputXmlAttribute(stream, kTestsuite, "tests",
5279  StreamableToString(test_suite.reportable_test_count()));
5280  if (!GTEST_FLAG(list_tests)) {
5281  OutputXmlAttribute(stream, kTestsuite, "failures",
5282  StreamableToString(test_suite.failed_test_count()));
5283  OutputXmlAttribute(
5284  stream, kTestsuite, "disabled",
5285  StreamableToString(test_suite.reportable_disabled_test_count()));
5286  OutputXmlAttribute(stream, kTestsuite, "errors", "0");
5287  OutputXmlAttribute(stream, kTestsuite, "time",
5288  FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
5289  *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
5290  }
5291  *stream << ">\n";
5292  for (int i = 0; i < test_suite.total_test_count(); ++i) {
5293  if (test_suite.GetTestInfo(i)->is_reportable())
5294  OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
5295  }
5296  *stream << " </" << kTestsuite << ">\n";
5297 }
5298 
5299 // Prints an XML summary of unit_test to output stream out.
5300 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
5301  const UnitTest& unit_test) {
5302  const std::string kTestsuites = "testsuites";
5303 
5304  *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5305  *stream << "<" << kTestsuites;
5306 
5307  OutputXmlAttribute(stream, kTestsuites, "tests",
5308  StreamableToString(unit_test.reportable_test_count()));
5309  OutputXmlAttribute(stream, kTestsuites, "failures",
5310  StreamableToString(unit_test.failed_test_count()));
5311  OutputXmlAttribute(
5312  stream, kTestsuites, "disabled",
5313  StreamableToString(unit_test.reportable_disabled_test_count()));
5314  OutputXmlAttribute(stream, kTestsuites, "errors", "0");
5315  OutputXmlAttribute(
5316  stream, kTestsuites, "timestamp",
5317  FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
5318  OutputXmlAttribute(stream, kTestsuites, "time",
5319  FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
5320 
5321  if (GTEST_FLAG(shuffle)) {
5322  OutputXmlAttribute(stream, kTestsuites, "random_seed",
5323  StreamableToString(unit_test.random_seed()));
5324  }
5325  *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
5326 
5327  OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5328  *stream << ">\n";
5329 
5330  for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5331  if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
5332  PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
5333  }
5334  *stream << "</" << kTestsuites << ">\n";
5335 }
5336 
5337 void XmlUnitTestResultPrinter::PrintXmlTestsList(
5338  std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
5339  const std::string kTestsuites = "testsuites";
5340 
5341  *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5342  *stream << "<" << kTestsuites;
5343 
5344  int total_tests = 0;
5345  for (auto test_suite : test_suites) {
5346  total_tests += test_suite->total_test_count();
5347  }
5348  OutputXmlAttribute(stream, kTestsuites, "tests",
5349  StreamableToString(total_tests));
5350  OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5351  *stream << ">\n";
5352 
5353  for (auto test_suite : test_suites) {
5354  PrintXmlTestSuite(stream, *test_suite);
5355  }
5356  *stream << "</" << kTestsuites << ">\n";
5357 }
5358 
5359 // Produces a string representing the test properties in a result as space
5360 // delimited XML attributes based on the property key="value" pairs.
5361 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
5362  const TestResult& result) {
5363  Message attributes;
5364  for (int i = 0; i < result.test_property_count(); ++i) {
5365  const TestProperty& property = result.GetTestProperty(i);
5366  attributes << " " << property.key() << "="
5367  << "\"" << EscapeXmlAttribute(property.value()) << "\"";
5368  }
5369  return attributes.GetString();
5370 }
5371 
5372 void XmlUnitTestResultPrinter::OutputXmlTestProperties(
5373  std::ostream* stream, const TestResult& result) {
5374  const std::string kProperties = "properties";
5375  const std::string kProperty = "property";
5376 
5377  if (result.test_property_count() <= 0) {
5378  return;
5379  }
5380 
5381  *stream << "<" << kProperties << ">\n";
5382  for (int i = 0; i < result.test_property_count(); ++i) {
5383  const TestProperty& property = result.GetTestProperty(i);
5384  *stream << "<" << kProperty;
5385  *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
5386  *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
5387  *stream << "/>\n";
5388  }
5389  *stream << "</" << kProperties << ">\n";
5390 }
5391 
5392 // End XmlUnitTestResultPrinter
5393 
5394 // This class generates an JSON output file.
5395 class JsonUnitTestResultPrinter : public EmptyTestEventListener {
5396  public:
5397  explicit JsonUnitTestResultPrinter(const char* output_file);
5398 
5399  void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
5400 
5401  // Prints an JSON summary of all unit tests.
5402  static void PrintJsonTestList(::std::ostream* stream,
5403  const std::vector<TestSuite*>& test_suites);
5404 
5405  private:
5406  // Returns an JSON-escaped copy of the input string str.
5407  static std::string EscapeJson(const std::string& str);
5408 
5411  static void OutputJsonKey(std::ostream* stream,
5412  const std::string& element_name,
5413  const std::string& name,
5414  const std::string& value,
5415  const std::string& indent,
5416  bool comma = true);
5417  static void OutputJsonKey(std::ostream* stream,
5418  const std::string& element_name,
5419  const std::string& name,
5420  int value,
5421  const std::string& indent,
5422  bool comma = true);
5423 
5424  // Streams a JSON representation of a TestInfo object.
5425  static void OutputJsonTestInfo(::std::ostream* stream,
5426  const char* test_suite_name,
5427  const TestInfo& test_info);
5428 
5429  // Prints a JSON representation of a TestSuite object
5430  static void PrintJsonTestSuite(::std::ostream* stream,
5431  const TestSuite& test_suite);
5432 
5433  // Prints a JSON summary of unit_test to output stream out.
5434  static void PrintJsonUnitTest(::std::ostream* stream,
5435  const UnitTest& unit_test);
5436 
5437  // Produces a string representing the test properties in a result as
5438  // a JSON dictionary.
5439  static std::string TestPropertiesAsJson(const TestResult& result,
5440  const std::string& indent);
5441 
5442  // The output file.
5443  const std::string output_file_;
5444 
5445  GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
5446 };
5447 
5448 // Creates a new JsonUnitTestResultPrinter.
5449 JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
5450  : output_file_(output_file) {
5451  if (output_file_.empty()) {
5452  GTEST_LOG_(FATAL) << "JSON output file may not be null";
5453  }
5454 }
5455 
5456 void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
5457  int /*iteration*/) {
5458  FILE* jsonout = OpenFileForWriting(output_file_);
5459  std::stringstream stream;
5460  PrintJsonUnitTest(&stream, unit_test);
5461  fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
5462  fclose(jsonout);
5463 }
5464 
5465 // Returns an JSON-escaped copy of the input string str.
5466 std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
5467  Message m;
5468 
5469  for (size_t i = 0; i < str.size(); ++i) {
5470  const char ch = str[i];
5471  switch (ch) {
5472  case '\\':
5473  case '"':
5474  case '/':
5475  m << '\\' << ch;
5476  break;
5477  case '\b':
5478  m << "\\b";
5479  break;
5480  case '\t':
5481  m << "\\t";
5482  break;
5483  case '\n':
5484  m << "\\n";
5485  break;
5486  case '\f':
5487  m << "\\f";
5488  break;
5489  case '\r':
5490  m << "\\r";
5491  break;
5492  default:
5493  if (ch < ' ') {
5494  m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
5495  } else {
5496  m << ch;
5497  }
5498  break;
5499  }
5500  }
5501 
5502  return m.GetString();
5503 }
5504 
5505 // The following routines generate an JSON representation of a UnitTest
5506 // object.
5507 
5508 // Formats the given time in milliseconds as seconds.
5509 static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
5510  ::std::stringstream ss;
5511  ss << (static_cast<double>(ms) * 1e-3) << "s";
5512  return ss.str();
5513 }
5514 
5515 // Converts the given epoch time in milliseconds to a date string in the
5516 // RFC3339 format, without the timezone information.
5517 static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
5518  struct tm time_struct;
5519  if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5520  return "";
5521  // YYYY-MM-DDThh:mm:ss
5522  return StreamableToString(time_struct.tm_year + 1900) + "-" +
5523  String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5524  String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5525  String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5526  String::FormatIntWidth2(time_struct.tm_min) + ":" +
5527  String::FormatIntWidth2(time_struct.tm_sec) + "Z";
5528 }
5529 
5530 static inline std::string Indent(int width) {
5531  return std::string(width, ' ');
5532 }
5533 
5534 void JsonUnitTestResultPrinter::OutputJsonKey(
5535  std::ostream* stream,
5536  const std::string& element_name,
5537  const std::string& name,
5538  const std::string& value,
5539  const std::string& indent,
5540  bool comma) {
5541  const std::vector<std::string>& allowed_names =
5542  GetReservedAttributesForElement(element_name);
5543 
5544  GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5545  allowed_names.end())
5546  << "Key \"" << name << "\" is not allowed for value \"" << element_name
5547  << "\".";
5548 
5549  *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
5550  if (comma)
5551  *stream << ",\n";
5552 }
5553 
5554 void JsonUnitTestResultPrinter::OutputJsonKey(
5555  std::ostream* stream,
5556  const std::string& element_name,
5557  const std::string& name,
5558  int value,
5559  const std::string& indent,
5560  bool comma) {
5561  const std::vector<std::string>& allowed_names =
5562  GetReservedAttributesForElement(element_name);
5563 
5564  GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5565  allowed_names.end())
5566  << "Key \"" << name << "\" is not allowed for value \"" << element_name
5567  << "\".";
5568 
5569  *stream << indent << "\"" << name << "\": " << StreamableToString(value);
5570  if (comma)
5571  *stream << ",\n";
5572 }
5573 
5574 // Prints a JSON representation of a TestInfo object.
5575 void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
5576  const char* test_suite_name,
5577  const TestInfo& test_info) {
5578  const TestResult& result = *test_info.result();
5579  const std::string kTestsuite = "testcase";
5580  const std::string kIndent = Indent(10);
5581 
5582  *stream << Indent(8) << "{\n";
5583  OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent);
5584 
5585  if (test_info.value_param() != nullptr) {
5586  OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(),
5587  kIndent);
5588  }
5589  if (test_info.type_param() != nullptr) {
5590  OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
5591  kIndent);
5592  }
5593  if (GTEST_FLAG(list_tests)) {
5594  OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
5595  OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
5596  *stream << "\n" << Indent(8) << "}";
5597  return;
5598  }
5599 
5600  OutputJsonKey(
5601  stream, kTestsuite, "status",
5602  result.Skipped() ? "SKIPPED" : test_info.should_run() ? "RUN" : "NOTRUN",
5603  kIndent);
5604  OutputJsonKey(stream, kTestsuite, "time",
5605  FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
5606  OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent,
5607  false);
5608  *stream << TestPropertiesAsJson(result, kIndent);
5609 
5610  int failures = 0;
5611  for (int i = 0; i < result.total_part_count(); ++i) {
5612  const TestPartResult& part = result.GetTestPartResult(i);
5613  if (part.failed()) {
5614  *stream << ",\n";
5615  if (++failures == 1) {
5616  *stream << kIndent << "\"" << "failures" << "\": [\n";
5617  }
5618  const std::string location =
5620  part.line_number());
5621  const std::string message = EscapeJson(location + "\n" + part.message());
5622  *stream << kIndent << " {\n"
5623  << kIndent << " \"failure\": \"" << message << "\",\n"
5624  << kIndent << " \"type\": \"\"\n"
5625  << kIndent << " }";
5626  }
5627  }
5628 
5629  if (failures > 0)
5630  *stream << "\n" << kIndent << "]";
5631  *stream << "\n" << Indent(8) << "}";
5632 }
5633 
5634 // Prints an JSON representation of a TestSuite object
5635 void JsonUnitTestResultPrinter::PrintJsonTestSuite(
5636  std::ostream* stream, const TestSuite& test_suite) {
5637  const std::string kTestsuite = "testsuite";
5638  const std::string kIndent = Indent(6);
5639 
5640  *stream << Indent(4) << "{\n";
5641  OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
5642  OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
5643  kIndent);
5644  if (!GTEST_FLAG(list_tests)) {
5645  OutputJsonKey(stream, kTestsuite, "failures",
5646  test_suite.failed_test_count(), kIndent);
5647  OutputJsonKey(stream, kTestsuite, "disabled",
5648  test_suite.reportable_disabled_test_count(), kIndent);
5649  OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
5650  OutputJsonKey(stream, kTestsuite, "time",
5651  FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
5652  kIndent, false);
5653  *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
5654  << ",\n";
5655  }
5656 
5657  *stream << kIndent << "\"" << kTestsuite << "\": [\n";
5658 
5659  bool comma = false;
5660  for (int i = 0; i < test_suite.total_test_count(); ++i) {
5661  if (test_suite.GetTestInfo(i)->is_reportable()) {
5662  if (comma) {
5663  *stream << ",\n";
5664  } else {
5665  comma = true;
5666  }
5667  OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
5668  }
5669  }
5670  *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
5671 }
5672 
5673 // Prints a JSON summary of unit_test to output stream out.
5674 void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
5675  const UnitTest& unit_test) {
5676  const std::string kTestsuites = "testsuites";
5677  const std::string kIndent = Indent(2);
5678  *stream << "{\n";
5679 
5680  OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
5681  kIndent);
5682  OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
5683  kIndent);
5684  OutputJsonKey(stream, kTestsuites, "disabled",
5685  unit_test.reportable_disabled_test_count(), kIndent);
5686  OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
5687  if (GTEST_FLAG(shuffle)) {
5688  OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
5689  kIndent);
5690  }
5691  OutputJsonKey(stream, kTestsuites, "timestamp",
5692  FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
5693  kIndent);
5694  OutputJsonKey(stream, kTestsuites, "time",
5695  FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
5696  false);
5697 
5698  *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
5699  << ",\n";
5700 
5701  OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
5702  *stream << kIndent << "\"" << kTestsuites << "\": [\n";
5703 
5704  bool comma = false;
5705  for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5706  if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
5707  if (comma) {
5708  *stream << ",\n";
5709  } else {
5710  comma = true;
5711  }
5712  PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
5713  }
5714  }
5715 
5716  *stream << "\n" << kIndent << "]\n" << "}\n";
5717 }
5718 
5719 void JsonUnitTestResultPrinter::PrintJsonTestList(
5720  std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
5721  const std::string kTestsuites = "testsuites";
5722  const std::string kIndent = Indent(2);
5723  *stream << "{\n";
5724  int total_tests = 0;
5725  for (auto test_suite : test_suites) {
5726  total_tests += test_suite->total_test_count();
5727  }
5728  OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
5729 
5730  OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
5731  *stream << kIndent << "\"" << kTestsuites << "\": [\n";
5732 
5733  for (size_t i = 0; i < test_suites.size(); ++i) {
5734  if (i != 0) {
5735  *stream << ",\n";
5736  }
5737  PrintJsonTestSuite(stream, *test_suites[i]);
5738  }
5739 
5740  *stream << "\n"
5741  << kIndent << "]\n"
5742  << "}\n";
5743 }
5744 // Produces a string representing the test properties in a result as
5745 // a JSON dictionary.
5746 std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
5747  const TestResult& result, const std::string& indent) {
5748  Message attributes;
5749  for (int i = 0; i < result.test_property_count(); ++i) {
5750  const TestProperty& property = result.GetTestProperty(i);
5751  attributes << ",\n" << indent << "\"" << property.key() << "\": "
5752  << "\"" << EscapeJson(property.value()) << "\"";
5753  }
5754  return attributes.GetString();
5755 }
5756 
5757 // End JsonUnitTestResultPrinter
5758 
5759 #if GTEST_CAN_STREAM_RESULTS_
5760 
5761 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
5762 // replaces them by "%xx" where xx is their hexadecimal value. For
5763 // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
5764 // in both time and space -- important as the input str may contain an
5765 // arbitrarily long test failure message and stack trace.
5766 std::string StreamingListener::UrlEncode(const char* str) {
5767  std::string result;
5768  result.reserve(strlen(str) + 1);
5769  for (char ch = *str; ch != '\0'; ch = *++str) {
5770  switch (ch) {
5771  case '%':
5772  case '=':
5773  case '&':
5774  case '\n':
5775  result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
5776  break;
5777  default:
5778  result.push_back(ch);
5779  break;
5780  }
5781  }
5782  return result;
5783 }
5784 
5785 void StreamingListener::SocketWriter::MakeConnection() {
5786  GTEST_CHECK_(sockfd_ == -1)
5787  << "MakeConnection() can't be called when there is already a connection.";
5788 
5789  addrinfo hints;
5790  memset(&hints, 0, sizeof(hints));
5791  hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
5792  hints.ai_socktype = SOCK_STREAM;
5793  addrinfo* servinfo = nullptr;
5794 
5795  // Use the getaddrinfo() to get a linked list of IP addresses for
5796  // the given host name.
5797  const int error_num = getaddrinfo(
5798  host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
5799  if (error_num != 0) {
5800  GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
5801  << gai_strerror(error_num);
5802  }
5803 
5804  // Loop through all the results and connect to the first we can.
5805  for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
5806  cur_addr = cur_addr->ai_next) {
5807  sockfd_ = socket(
5808  cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
5809  if (sockfd_ != -1) {
5810  // Connect the client socket to the server socket.
5811  if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
5812  close(sockfd_);
5813  sockfd_ = -1;
5814  }
5815  }
5816  }
5817 
5818  freeaddrinfo(servinfo); // all done with this structure
5819 
5820  if (sockfd_ == -1) {
5821  GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
5822  << host_name_ << ":" << port_num_;
5823  }
5824 }
5825 
5826 // End of class Streaming Listener
5827 #endif // GTEST_CAN_STREAM_RESULTS__
5828 
5829 // class OsStackTraceGetter
5830 
5831 const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
5832  "... " GTEST_NAME_ " internal frames ...";
5833 
5834 std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
5835  GTEST_LOCK_EXCLUDED_(mutex_) {
5836 #if GTEST_HAS_ABSL
5837  std::string result;
5838 
5839  if (max_depth <= 0) {
5840  return result;
5841  }
5842 
5843  max_depth = std::min(max_depth, kMaxStackTraceDepth);
5844 
5845  std::vector<void*> raw_stack(max_depth);
5846  // Skips the frames requested by the caller, plus this function.
5847  const int raw_stack_size =
5848  absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
5849 
5850  void* caller_frame = nullptr;
5851  {
5852  MutexLock lock(&mutex_);
5853  caller_frame = caller_frame_;
5854  }
5855 
5856  for (int i = 0; i < raw_stack_size; ++i) {
5857  if (raw_stack[i] == caller_frame &&
5858  !GTEST_FLAG(show_internal_stack_frames)) {
5859  // Add a marker to the trace and stop adding frames.
5860  absl::StrAppend(&result, kElidedFramesMarker, "\n");
5861  break;
5862  }
5863 
5864  char tmp[1024];
5865  const char* symbol = "(unknown)";
5866  if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
5867  symbol = tmp;
5868  }
5869 
5870  char line[1024];
5871  snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
5872  result += line;
5873  }
5874 
5875  return result;
5876 
5877 #else // !GTEST_HAS_ABSL
5878  static_cast<void>(max_depth);
5879  static_cast<void>(skip_count);
5880  return "";
5881 #endif // GTEST_HAS_ABSL
5882 }
5883 
5884 void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
5885 #if GTEST_HAS_ABSL
5886  void* caller_frame = nullptr;
5887  if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
5888  caller_frame = nullptr;
5889  }
5890 
5891  MutexLock lock(&mutex_);
5892  caller_frame_ = caller_frame;
5893 #endif // GTEST_HAS_ABSL
5894 }
5895 
5896 // A helper class that creates the premature-exit file in its
5897 // constructor and deletes the file in its destructor.
5898 class ScopedPrematureExitFile {
5899  public:
5900  explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
5901  : premature_exit_filepath_(premature_exit_filepath ?
5902  premature_exit_filepath : "") {
5903  // If a path to the premature-exit file is specified...
5904  if (!premature_exit_filepath_.empty()) {
5905  // create the file with a single "0" character in it. I/O
5906  // errors are ignored as there's nothing better we can do and we
5907  // don't want to fail the test because of this.
5908  FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
5909  fwrite("0", 1, 1, pfile);
5910  fclose(pfile);
5911  }
5912  }
5913 
5914  ~ScopedPrematureExitFile() {
5915  if (!premature_exit_filepath_.empty()) {
5916  int retval = remove(premature_exit_filepath_.c_str());
5917  if (retval) {
5918  GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
5919  << premature_exit_filepath_ << "\" with error "
5920  << retval;
5921  }
5922  }
5923  }
5924 
5925  private:
5926  const std::string premature_exit_filepath_;
5927 
5928  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
5929 };
5930 
5931 } // namespace internal
5932 
5933 // class TestEventListeners
5934 
5935 TestEventListeners::TestEventListeners()
5936  : repeater_(new internal::TestEventRepeater()),
5937  default_result_printer_(nullptr),
5938  default_xml_generator_(nullptr) {}
5939 
5940 TestEventListeners::~TestEventListeners() { delete repeater_; }
5941 
5942 // Returns the standard listener responsible for the default console
5943 // output. Can be removed from the listeners list to shut down default
5944 // console output. Note that removing this object from the listener list
5945 // with Release transfers its ownership to the user.
5946 void TestEventListeners::Append(TestEventListener* listener) {
5947  repeater_->Append(listener);
5948 }
5949 
5950 // Removes the given event listener from the list and returns it. It then
5951 // becomes the caller's responsibility to delete the listener. Returns
5952 // NULL if the listener is not found in the list.
5953 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5954  if (listener == default_result_printer_)
5955  default_result_printer_ = nullptr;
5956  else if (listener == default_xml_generator_)
5957  default_xml_generator_ = nullptr;
5958  return repeater_->Release(listener);
5959 }
5960 
5961 // Returns repeater that broadcasts the TestEventListener events to all
5962 // subscribers.
5963 TestEventListener* TestEventListeners::repeater() { return repeater_; }
5964 
5965 // Sets the default_result_printer attribute to the provided listener.
5966 // The listener is also added to the listener list and previous
5967 // default_result_printer is removed from it and deleted. The listener can
5968 // also be NULL in which case it will not be added to the list. Does
5969 // nothing if the previous and the current listener objects are the same.
5970 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5971  if (default_result_printer_ != listener) {
5972  // It is an error to pass this method a listener that is already in the
5973  // list.
5974  delete Release(default_result_printer_);
5975  default_result_printer_ = listener;
5976  if (listener != nullptr) Append(listener);
5977  }
5978 }
5979 
5980 // Sets the default_xml_generator attribute to the provided listener. The
5981 // listener is also added to the listener list and previous
5982 // default_xml_generator is removed from it and deleted. The listener can
5983 // also be NULL in which case it will not be added to the list. Does
5984 // nothing if the previous and the current listener objects are the same.
5985 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5986  if (default_xml_generator_ != listener) {
5987  // It is an error to pass this method a listener that is already in the
5988  // list.
5989  delete Release(default_xml_generator_);
5990  default_xml_generator_ = listener;
5991  if (listener != nullptr) Append(listener);
5992  }
5993 }
5994 
5995 // Controls whether events will be forwarded by the repeater to the
5996 // listeners in the list.
5997 bool TestEventListeners::EventForwardingEnabled() const {
5998  return repeater_->forwarding_enabled();
5999 }
6000 
6001 void TestEventListeners::SuppressEventForwarding() {
6002  repeater_->set_forwarding_enabled(false);
6003 }
6004 
6005 // class UnitTest
6006 
6007 // Gets the singleton UnitTest object. The first time this method is
6008 // called, a UnitTest object is constructed and returned. Consecutive
6009 // calls will return the same object.
6010 //
6011 // We don't protect this under mutex_ as a user is not supposed to
6012 // call this before main() starts, from which point on the return
6013 // value will never change.
6014 UnitTest* UnitTest::GetInstance() {
6015  // CodeGear C++Builder insists on a public destructor for the
6016  // default implementation. Use this implementation to keep good OO
6017  // design with private destructor.
6018 
6019 #if defined(__BORLANDC__)
6020  static UnitTest* const instance = new UnitTest;
6021  return instance;
6022 #else
6023  static UnitTest instance;
6024  return &instance;
6025 #endif // defined(__BORLANDC__)
6026 }
6027 
6028 // Gets the number of successful test suites.
6029 int UnitTest::successful_test_suite_count() const {
6030  return impl()->successful_test_suite_count();
6031 }
6032 
6033 // Gets the number of failed test suites.
6034 int UnitTest::failed_test_suite_count() const {
6035  return impl()->failed_test_suite_count();
6036 }
6037 
6038 // Gets the number of all test suites.
6039 int UnitTest::total_test_suite_count() const {
6040  return impl()->total_test_suite_count();
6041 }
6042 
6043 // Gets the number of all test suites that contain at least one test
6044 // that should run.
6045 int UnitTest::test_suite_to_run_count() const {
6046  return impl()->test_suite_to_run_count();
6047 }
6048 
6049 // Legacy API is deprecated but still available
6050 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6051 int UnitTest::successful_test_case_count() const {
6052  return impl()->successful_test_suite_count();
6053 }
6054 int UnitTest::failed_test_case_count() const {
6055  return impl()->failed_test_suite_count();
6056 }
6057 int UnitTest::total_test_case_count() const {
6058  return impl()->total_test_suite_count();
6059 }
6060 int UnitTest::test_case_to_run_count() const {
6061  return impl()->test_suite_to_run_count();
6062 }
6063 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6064 
6065 // Gets the number of successful tests.
6066 int UnitTest::successful_test_count() const {
6067  return impl()->successful_test_count();
6068 }
6069 
6070 // Gets the number of skipped tests.
6071 int UnitTest::skipped_test_count() const {
6072  return impl()->skipped_test_count();
6073 }
6074 
6075 // Gets the number of failed tests.
6076 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
6077 
6078 // Gets the number of disabled tests that will be reported in the XML report.
6079 int UnitTest::reportable_disabled_test_count() const {
6080  return impl()->reportable_disabled_test_count();
6081 }
6082 
6083 // Gets the number of disabled tests.
6084 int UnitTest::disabled_test_count() const {
6085  return impl()->disabled_test_count();
6086 }
6087 
6088 // Gets the number of tests to be printed in the XML report.
6089 int UnitTest::reportable_test_count() const {
6090  return impl()->reportable_test_count();
6091 }
6092 
6093 // Gets the number of all tests.
6094 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
6095 
6096 // Gets the number of tests that should run.
6097 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
6098 
6099 // Gets the time of the test program start, in ms from the start of the
6100 // UNIX epoch.
6101 internal::TimeInMillis UnitTest::start_timestamp() const {
6102  return impl()->start_timestamp();
6103 }
6104 
6105 // Gets the elapsed time, in milliseconds.
6106 internal::TimeInMillis UnitTest::elapsed_time() const {
6107  return impl()->elapsed_time();
6108 }
6109 
6110 // Returns true iff the unit test passed (i.e. all test suites passed).
6111 bool UnitTest::Passed() const { return impl()->Passed(); }
6112 
6113 // Returns true iff the unit test failed (i.e. some test suite failed
6114 // or something outside of all tests failed).
6115 bool UnitTest::Failed() const { return impl()->Failed(); }
6116 
6117 // Gets the i-th test suite among all the test suites. i can range from 0 to
6118 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
6119 const TestSuite* UnitTest::GetTestSuite(int i) const {
6120  return impl()->GetTestSuite(i);
6121 }
6122 
6123 // Legacy API is deprecated but still available
6124 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6125 const TestCase* UnitTest::GetTestCase(int i) const {
6126  return impl()->GetTestCase(i);
6127 }
6128 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6129 
6130 // Returns the TestResult containing information on test failures and
6131 // properties logged outside of individual test suites.
6132 const TestResult& UnitTest::ad_hoc_test_result() const {
6133  return *impl()->ad_hoc_test_result();
6134 }
6135 
6136 // Gets the i-th test suite among all the test suites. i can range from 0 to
6137 // total_test_suite_count() - 1. If i is not in that range, returns NULL.
6138 TestSuite* UnitTest::GetMutableTestSuite(int i) {
6139  return impl()->GetMutableSuiteCase(i);
6140 }
6141 
6142 // Returns the list of event listeners that can be used to track events
6143 // inside Google Test.
6144 TestEventListeners& UnitTest::listeners() {
6145  return *impl()->listeners();
6146 }
6147 
6148 // Registers and returns a global test environment. When a test
6149 // program is run, all global test environments will be set-up in the
6150 // order they were registered. After all tests in the program have
6151 // finished, all global test environments will be torn-down in the
6152 // *reverse* order they were registered.
6153 //
6154 // The UnitTest object takes ownership of the given environment.
6155 //
6156 // We don't protect this under mutex_, as we only support calling it
6157 // from the main thread.
6158 Environment* UnitTest::AddEnvironment(Environment* env) {
6159  if (env == nullptr) {
6160  return nullptr;
6161  }
6162 
6163  impl_->environments().push_back(env);
6164  return env;
6165 }
6166 
6167 // Adds a TestPartResult to the current TestResult object. All Google Test
6168 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
6169 // this to report their results. The user code should use the
6170 // assertion macros instead of calling this directly.
6171 void UnitTest::AddTestPartResult(
6172  TestPartResult::Type result_type,
6173  const char* file_name,
6174  int line_number,
6175  const std::string& message,
6176  const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
6177  Message msg;
6178  msg << message;
6179 
6180  internal::MutexLock lock(&mutex_);
6181  if (impl_->gtest_trace_stack().size() > 0) {
6182  msg << "\n" << GTEST_NAME_ << " trace:";
6183 
6184  for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
6185  i > 0; --i) {
6186  const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
6187  msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
6188  << " " << trace.message;
6189  }
6190  }
6191 
6192  if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
6193  msg << internal::kStackTraceMarker << os_stack_trace;
6194  }
6195 
6196  const TestPartResult result = TestPartResult(
6197  result_type, file_name, line_number, msg.GetString().c_str());
6198  impl_->GetTestPartResultReporterForCurrentThread()->
6199  ReportTestPartResult(result);
6200 
6201  if (result_type != TestPartResult::kSuccess &&
6202  result_type != TestPartResult::kSkip) {
6203  // gtest_break_on_failure takes precedence over
6204  // gtest_throw_on_failure. This allows a user to set the latter
6205  // in the code (perhaps in order to use Google Test assertions
6206  // with another testing framework) and specify the former on the
6207  // command line for debugging.
6208  if (GTEST_FLAG(break_on_failure)) {
6209 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6210  // Using DebugBreak on Windows allows gtest to still break into a debugger
6211  // when a failure happens and both the --gtest_break_on_failure and
6212  // the --gtest_catch_exceptions flags are specified.
6213  DebugBreak();
6214 #elif (!defined(__native_client__)) && \
6215  ((defined(__clang__) || defined(__GNUC__)) && \
6216  (defined(__x86_64__) || defined(__i386__)))
6217  // with clang/gcc we can achieve the same effect on x86 by invoking int3
6218  asm("int3");
6219 #else
6220  // Dereference nullptr through a volatile pointer to prevent the compiler
6221  // from removing. We use this rather than abort() or __builtin_trap() for
6222  // portability: some debuggers don't correctly trap abort().
6223  *static_cast<volatile int*>(nullptr) = 1;
6224 #endif // GTEST_OS_WINDOWS
6225  } else if (GTEST_FLAG(throw_on_failure)) {
6226 #if GTEST_HAS_EXCEPTIONS
6227  throw internal::GoogleTestFailureException(result);
6228 #else
6229  // We cannot call abort() as it generates a pop-up in debug mode
6230  // that cannot be suppressed in VC 7.1 or below.
6231  exit(1);
6232 #endif
6233  }
6234  }
6235 }
6236 
6237 // Adds a TestProperty to the current TestResult object when invoked from
6238 // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
6239 // from SetUpTestSuite or TearDownTestSuite, or to the global property set
6240 // when invoked elsewhere. If the result already contains a property with
6241 // the same key, the value will be updated.
6242 void UnitTest::RecordProperty(const std::string& key,
6243  const std::string& value) {
6244  impl_->RecordProperty(TestProperty(key, value));
6245 }
6246 
6247 // Runs all tests in this UnitTest object and prints the result.
6248 // Returns 0 if successful, or 1 otherwise.
6249 //
6250 // We don't protect this under mutex_, as we only support calling it
6251 // from the main thread.
6252 int UnitTest::Run() {
6253  const bool in_death_test_child_process =
6254  internal::GTEST_FLAG(internal_run_death_test).length() > 0;
6255 
6256  // Google Test implements this protocol for catching that a test
6257  // program exits before returning control to Google Test:
6258  //
6259  // 1. Upon start, Google Test creates a file whose absolute path
6260  // is specified by the environment variable
6261  // TEST_PREMATURE_EXIT_FILE.
6262  // 2. When Google Test has finished its work, it deletes the file.
6263  //
6264  // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
6265  // running a Google-Test-based test program and check the existence
6266  // of the file at the end of the test execution to see if it has
6267  // exited prematurely.
6268 
6269  // If we are in the child process of a death test, don't
6270  // create/delete the premature exit file, as doing so is unnecessary
6271  // and will confuse the parent process. Otherwise, create/delete
6272  // the file upon entering/leaving this function. If the program
6273  // somehow exits before this function has a chance to return, the
6274  // premature-exit file will be left undeleted, causing a test runner
6275  // that understands the premature-exit-file protocol to report the
6276  // test as having failed.
6277  const internal::ScopedPrematureExitFile premature_exit_file(
6278  in_death_test_child_process
6279  ? nullptr
6280  : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
6281 
6282  // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
6283  // used for the duration of the program.
6284  impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
6285 
6286 #if GTEST_OS_WINDOWS
6287  // Either the user wants Google Test to catch exceptions thrown by the
6288  // tests or this is executing in the context of death test child
6289  // process. In either case the user does not want to see pop-up dialogs
6290  // about crashes - they are expected.
6291  if (impl()->catch_exceptions() || in_death_test_child_process) {
6292 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
6293  // SetErrorMode doesn't exist on CE.
6294  SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
6295  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
6296 # endif // !GTEST_OS_WINDOWS_MOBILE
6297 
6298 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
6299  // Death test children can be terminated with _abort(). On Windows,
6300  // _abort() can show a dialog with a warning message. This forces the
6301  // abort message to go to stderr instead.
6302  _set_error_mode(_OUT_TO_STDERR);
6303 # endif
6304 
6305 # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
6306  // In the debug version, Visual Studio pops up a separate dialog
6307  // offering a choice to debug the aborted program. We need to suppress
6308  // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
6309  // executed. Google Test will notify the user of any unexpected
6310  // failure via stderr.
6311  if (!GTEST_FLAG(break_on_failure))
6312  _set_abort_behavior(
6313  0x0, // Clear the following flags:
6314  _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
6315 # endif
6316  }
6317 #endif // GTEST_OS_WINDOWS
6318 
6319  return internal::HandleExceptionsInMethodIfSupported(
6320  impl(),
6321  &internal::UnitTestImpl::RunAllTests,
6322  "auxiliary test code (environments or event listeners)") ? 0 : 1;
6323 }
6324 
6325 // Returns the working directory when the first TEST() or TEST_F() was
6326 // executed.
6327 const char* UnitTest::original_working_dir() const {
6328  return impl_->original_working_dir_.c_str();
6329 }
6330 
6331 // Returns the TestSuite object for the test that's currently running,
6332 // or NULL if no test is running.
6333 const TestSuite* UnitTest::current_test_suite() const
6334  GTEST_LOCK_EXCLUDED_(mutex_) {
6335  internal::MutexLock lock(&mutex_);
6336  return impl_->current_test_suite();
6337 }
6338 
6339 // Legacy API is still available but deprecated
6340 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
6341 const TestCase* UnitTest::current_test_case() const
6342  GTEST_LOCK_EXCLUDED_(mutex_) {
6343  internal::MutexLock lock(&mutex_);
6344  return impl_->current_test_suite();
6345 }
6346 #endif
6347 
6348 // Returns the TestInfo object for the test that's currently running,
6349 // or NULL if no test is running.
6350 const TestInfo* UnitTest::current_test_info() const
6351  GTEST_LOCK_EXCLUDED_(mutex_) {
6352  internal::MutexLock lock(&mutex_);
6353  return impl_->current_test_info();
6354 }
6355 
6356 // Returns the random seed used at the start of the current test run.
6357 int UnitTest::random_seed() const { return impl_->random_seed(); }
6358 
6359 // Returns ParameterizedTestSuiteRegistry object used to keep track of
6360 // value-parameterized tests and instantiate and register them.
6361 internal::ParameterizedTestSuiteRegistry&
6362 UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
6363  return impl_->parameterized_test_registry();
6364 }
6365 
6366 // Creates an empty UnitTest.
6367 UnitTest::UnitTest() {
6368  impl_ = new internal::UnitTestImpl(this);
6369 }
6370 
6371 // Destructor of UnitTest.
6372 UnitTest::~UnitTest() {
6373  delete impl_;
6374 }
6375 
6376 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
6377 // Google Test trace stack.
6378 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
6379  GTEST_LOCK_EXCLUDED_(mutex_) {
6380  internal::MutexLock lock(&mutex_);
6381  impl_->gtest_trace_stack().push_back(trace);
6382 }
6383 
6384 // Pops a trace from the per-thread Google Test trace stack.
6385 void UnitTest::PopGTestTrace()
6386  GTEST_LOCK_EXCLUDED_(mutex_) {
6387  internal::MutexLock lock(&mutex_);
6388  impl_->gtest_trace_stack().pop_back();
6389 }
6390 
6391 namespace internal {
6392 
6393 UnitTestImpl::UnitTestImpl(UnitTest* parent)
6394  : parent_(parent),
6395  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
6396  default_global_test_part_result_reporter_(this),
6397  default_per_thread_test_part_result_reporter_(this),
6398  GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
6399  &default_global_test_part_result_reporter_),
6400  per_thread_test_part_result_reporter_(
6401  &default_per_thread_test_part_result_reporter_),
6402  parameterized_test_registry_(),
6403  parameterized_tests_registered_(false),
6404  last_death_test_suite_(-1),
6405  current_test_suite_(nullptr),
6406  current_test_info_(nullptr),
6407  ad_hoc_test_result_(),
6408  os_stack_trace_getter_(nullptr),
6409  post_flag_parse_init_performed_(false),
6410  random_seed_(0), // Will be overridden by the flag before first use.
6411  random_(0), // Will be reseeded before first use.
6412  start_timestamp_(0),
6413  elapsed_time_(0),
6414 #if GTEST_HAS_DEATH_TEST
6415  death_test_factory_(new DefaultDeathTestFactory),
6416 #endif
6417  // Will be overridden by the flag before first use.
6418  catch_exceptions_(false) {
6419  listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
6420 }
6421 
6422 UnitTestImpl::~UnitTestImpl() {
6423  // Deletes every TestSuite.
6424  ForEach(test_suites_, internal::Delete<TestSuite>);
6425 
6426  // Deletes every Environment.
6427  ForEach(environments_, internal::Delete<Environment>);
6428 
6429  delete os_stack_trace_getter_;
6430 }
6431 
6432 // Adds a TestProperty to the current TestResult object when invoked in a
6433 // context of a test, to current test suite's ad_hoc_test_result when invoke
6434 // from SetUpTestSuite/TearDownTestSuite, or to the global property set
6435 // otherwise. If the result already contains a property with the same key,
6436 // the value will be updated.
6437 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
6438  std::string xml_element;
6439  TestResult* test_result; // TestResult appropriate for property recording.
6440 
6441  if (current_test_info_ != nullptr) {
6442  xml_element = "testcase";
6443  test_result = &(current_test_info_->result_);
6444  } else if (current_test_suite_ != nullptr) {
6445  xml_element = "testsuite";
6446  test_result = &(current_test_suite_->ad_hoc_test_result_);
6447  } else {
6448  xml_element = "testsuites";
6449  test_result = &ad_hoc_test_result_;
6450  }
6451  test_result->RecordProperty(xml_element, test_property);
6452 }
6453 
6454 #if GTEST_HAS_DEATH_TEST
6455 // Disables event forwarding if the control is currently in a death test
6456 // subprocess. Must not be called before InitGoogleTest.
6457 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
6458  if (internal_run_death_test_flag_.get() != nullptr)
6459  listeners()->SuppressEventForwarding();
6460 }
6461 #endif // GTEST_HAS_DEATH_TEST
6462 
6463 // Initializes event listeners performing XML output as specified by
6464 // UnitTestOptions. Must not be called before InitGoogleTest.
6465 void UnitTestImpl::ConfigureXmlOutput() {
6466  const std::string& output_format = UnitTestOptions::GetOutputFormat();
6467  if (output_format == "xml") {
6468  listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
6469  UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
6470  } else if (output_format == "json") {
6471  listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
6472  UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
6473  } else if (output_format != "") {
6474  GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
6475  << output_format << "\" ignored.";
6476  }
6477 }
6478 
6479 #if GTEST_CAN_STREAM_RESULTS_
6480 // Initializes event listeners for streaming test results in string form.
6481 // Must not be called before InitGoogleTest.
6482 void UnitTestImpl::ConfigureStreamingOutput() {
6483  const std::string& target = GTEST_FLAG(stream_result_to);
6484  if (!target.empty()) {
6485  const size_t pos = target.find(':');
6486  if (pos != std::string::npos) {
6487  listeners()->Append(new StreamingListener(target.substr(0, pos),
6488  target.substr(pos+1)));
6489  } else {
6490  GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
6491  << "\" ignored.";
6492  }
6493  }
6494 }
6495 #endif // GTEST_CAN_STREAM_RESULTS_
6496 
6497 // Performs initialization dependent upon flag values obtained in
6498 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
6499 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
6500 // this function is also called from RunAllTests. Since this function can be
6501 // called more than once, it has to be idempotent.
6502 void UnitTestImpl::PostFlagParsingInit() {
6503  // Ensures that this function does not execute more than once.
6504  if (!post_flag_parse_init_performed_) {
6505  post_flag_parse_init_performed_ = true;
6506 
6507 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
6508  // Register to send notifications about key process state changes.
6509  listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
6510 #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
6511 
6512 #if GTEST_HAS_DEATH_TEST
6513  InitDeathTestSubprocessControlInfo();
6514  SuppressTestEventsIfInSubprocess();
6515 #endif // GTEST_HAS_DEATH_TEST
6516 
6517  // Registers parameterized tests. This makes parameterized tests
6518  // available to the UnitTest reflection API without running
6519  // RUN_ALL_TESTS.
6520  RegisterParameterizedTests();
6521 
6522  // Configures listeners for XML output. This makes it possible for users
6523  // to shut down the default XML output before invoking RUN_ALL_TESTS.
6524  ConfigureXmlOutput();
6525 
6526 #if GTEST_CAN_STREAM_RESULTS_
6527  // Configures listeners for streaming test results to the specified server.
6528  ConfigureStreamingOutput();
6529 #endif // GTEST_CAN_STREAM_RESULTS_
6530 
6531 #if GTEST_HAS_ABSL
6532  if (GTEST_FLAG(install_failure_signal_handler)) {
6533  absl::FailureSignalHandlerOptions options;
6534  absl::InstallFailureSignalHandler(options);
6535  }
6536 #endif // GTEST_HAS_ABSL
6537  }
6538 }
6539 
6540 // A predicate that checks the name of a TestSuite against a known
6541 // value.
6542 //
6543 // This is used for implementation of the UnitTest class only. We put
6544 // it in the anonymous namespace to prevent polluting the outer
6545 // namespace.
6546 //
6547 // TestSuiteNameIs is copyable.
6548 class TestSuiteNameIs {
6549  public:
6550  // Constructor.
6551  explicit TestSuiteNameIs(const std::string& name) : name_(name) {}
6552 
6553  // Returns true iff the name of test_suite matches name_.
6554  bool operator()(const TestSuite* test_suite) const {
6555  return test_suite != nullptr &&
6556  strcmp(test_suite->name(), name_.c_str()) == 0;
6557  }
6558 
6559  private:
6560  std::string name_;
6561 };
6562 
6563 // Finds and returns a TestSuite with the given name. If one doesn't
6564 // exist, creates one and returns it. It's the CALLER'S
6565 // RESPONSIBILITY to ensure that this function is only called WHEN THE
6566 // TESTS ARE NOT SHUFFLED.
6567 //
6568 // Arguments:
6569 //
6570 // test_suite_name: name of the test suite
6571 // type_param: the name of the test suite's type parameter, or NULL if
6572 // this is not a typed or a type-parameterized test suite.
6573 // set_up_tc: pointer to the function that sets up the test suite
6574 // tear_down_tc: pointer to the function that tears down the test suite
6575 TestSuite* UnitTestImpl::GetTestSuite(
6576  const char* test_suite_name, const char* type_param,
6577  internal::SetUpTestSuiteFunc set_up_tc,
6578  internal::TearDownTestSuiteFunc tear_down_tc) {
6579  // Can we find a TestSuite with the given name?
6580  const auto test_suite =
6581  std::find_if(test_suites_.rbegin(), test_suites_.rend(),
6582  TestSuiteNameIs(test_suite_name));
6583 
6584  if (test_suite != test_suites_.rend()) return *test_suite;
6585 
6586  // No. Let's create one.
6587  auto* const new_test_suite =
6588  new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
6589 
6590  // Is this a death test suite?
6591  if (internal::UnitTestOptions::MatchesFilter(test_suite_name,
6592  kDeathTestSuiteFilter)) {
6593  // Yes. Inserts the test suite after the last death test suite
6594  // defined so far. This only works when the test suites haven't
6595  // been shuffled. Otherwise we may end up running a death test
6596  // after a non-death test.
6597  ++last_death_test_suite_;
6598  test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
6599  new_test_suite);
6600  } else {
6601  // No. Appends to the end of the list.
6602  test_suites_.push_back(new_test_suite);
6603  }
6604 
6605  test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
6606  return new_test_suite;
6607 }
6608 
6609 // Helpers for setting up / tearing down the given environment. They
6610 // are for use in the ForEach() function.
6611 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
6612 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
6613 
6614 // Runs all tests in this UnitTest object, prints the result, and
6615 // returns true if all tests are successful. If any exception is
6616 // thrown during a test, the test is considered to be failed, but the
6617 // rest of the tests will still be run.
6618 //
6619 // When parameterized tests are enabled, it expands and registers
6620 // parameterized tests first in RegisterParameterizedTests().
6621 // All other functions called from RunAllTests() may safely assume that
6622 // parameterized tests are ready to be counted and run.
6623 bool UnitTestImpl::RunAllTests() {
6624  // True iff Google Test is initialized before RUN_ALL_TESTS() is called.
6625  const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
6626 
6627  // Do not run any test if the --help flag was specified.
6628  if (g_help_flag)
6629  return true;
6630 
6631  // Repeats the call to the post-flag parsing initialization in case the
6632  // user didn't call InitGoogleTest.
6633  PostFlagParsingInit();
6634 
6635  // Even if sharding is not on, test runners may want to use the
6636  // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
6637  // protocol.
6638  internal::WriteToShardStatusFileIfNeeded();
6639 
6640  // True iff we are in a subprocess for running a thread-safe-style
6641  // death test.
6642  bool in_subprocess_for_death_test = false;
6643 
6644 #if GTEST_HAS_DEATH_TEST
6645  in_subprocess_for_death_test =
6646  (internal_run_death_test_flag_.get() != nullptr);
6647 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6648  if (in_subprocess_for_death_test) {
6649  GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
6650  }
6651 # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6652 #endif // GTEST_HAS_DEATH_TEST
6653 
6654  const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
6655  in_subprocess_for_death_test);
6656 
6657  // Compares the full test names with the filter to decide which
6658  // tests to run.
6659  const bool has_tests_to_run = FilterTests(should_shard
6660  ? HONOR_SHARDING_PROTOCOL
6661  : IGNORE_SHARDING_PROTOCOL) > 0;
6662 
6663  // Lists the tests and exits if the --gtest_list_tests flag was specified.
6664  if (GTEST_FLAG(list_tests)) {
6665  // This must be called *after* FilterTests() has been called.
6666  ListTestsMatchingFilter();
6667  return true;
6668  }
6669 
6670  random_seed_ = GTEST_FLAG(shuffle) ?
6671  GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
6672 
6673  // True iff at least one test has failed.
6674  bool failed = false;
6675 
6676  TestEventListener* repeater = listeners()->repeater();
6677 
6678  start_timestamp_ = GetTimeInMillis();
6679  repeater->OnTestProgramStart(*parent_);
6680 
6681  // How many times to repeat the tests? We don't want to repeat them
6682  // when we are inside the subprocess of a death test.
6683  const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
6684  // Repeats forever if the repeat count is negative.
6685  const bool forever = repeat < 0;
6686  for (int i = 0; forever || i != repeat; i++) {
6687  // We want to preserve failures generated by ad-hoc test
6688  // assertions executed before RUN_ALL_TESTS().
6689  ClearNonAdHocTestResult();
6690 
6691  const TimeInMillis start = GetTimeInMillis();
6692 
6693  // Shuffles test suites and tests if requested.
6694  if (has_tests_to_run && GTEST_FLAG(shuffle)) {
6695  random()->Reseed(random_seed_);
6696  // This should be done before calling OnTestIterationStart(),
6697  // such that a test event listener can see the actual test order
6698  // in the event.
6699  ShuffleTests();
6700  }
6701 
6702  // Tells the unit test event listeners that the tests are about to start.
6703  repeater->OnTestIterationStart(*parent_, i);
6704 
6705  // Runs each test suite if there is at least one test to run.
6706  if (has_tests_to_run) {
6707  // Sets up all environments beforehand.
6708  repeater->OnEnvironmentsSetUpStart(*parent_);
6709  ForEach(environments_, SetUpEnvironment);
6710  repeater->OnEnvironmentsSetUpEnd(*parent_);
6711 
6712  // Runs the tests only if there was no fatal failure during global
6713  // set-up.
6714  if (!Test::HasFatalFailure()) {
6715  for (int test_index = 0; test_index < total_test_suite_count();
6716  test_index++) {
6717  GetMutableSuiteCase(test_index)->Run();
6718  }
6719  }
6720 
6721  // Tears down all environments in reverse order afterwards.
6722  repeater->OnEnvironmentsTearDownStart(*parent_);
6723  std::for_each(environments_.rbegin(), environments_.rend(),
6724  TearDownEnvironment);
6725  repeater->OnEnvironmentsTearDownEnd(*parent_);
6726  }
6727 
6728  elapsed_time_ = GetTimeInMillis() - start;
6729 
6730  // Tells the unit test event listener that the tests have just finished.
6731  repeater->OnTestIterationEnd(*parent_, i);
6732 
6733  // Gets the result and clears it.
6734  if (!Passed()) {
6735  failed = true;
6736  }
6737 
6738  // Restores the original test order after the iteration. This
6739  // allows the user to quickly repro a failure that happens in the
6740  // N-th iteration without repeating the first (N - 1) iterations.
6741  // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
6742  // case the user somehow changes the value of the flag somewhere
6743  // (it's always safe to unshuffle the tests).
6744  UnshuffleTests();
6745 
6746  if (GTEST_FLAG(shuffle)) {
6747  // Picks a new random seed for each iteration.
6748  random_seed_ = GetNextRandomSeed(random_seed_);
6749  }
6750  }
6751 
6752  repeater->OnTestProgramEnd(*parent_);
6753 
6754  if (!gtest_is_initialized_before_run_all_tests) {
6755  ColoredPrintf(
6756  COLOR_RED,
6757  "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
6758  "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
6759  "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
6760  " will start to enforce the valid usage. "
6761  "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
6762 #if GTEST_FOR_GOOGLE_
6763  ColoredPrintf(COLOR_RED,
6764  "For more details, see http://wiki/Main/ValidGUnitMain.\n");
6765 #endif // GTEST_FOR_GOOGLE_
6766  }
6767 
6768  return !failed;
6769 }
6770 
6771 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
6772 // if the variable is present. If a file already exists at this location, this
6773 // function will write over it. If the variable is present, but the file cannot
6774 // be created, prints an error and exits.
6775 void WriteToShardStatusFileIfNeeded() {
6776  const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
6777  if (test_shard_file != nullptr) {
6778  FILE* const file = posix::FOpen(test_shard_file, "w");
6779  if (file == nullptr) {
6780  ColoredPrintf(COLOR_RED,
6781  "Could not write to the test shard status file \"%s\" "
6782  "specified by the %s environment variable.\n",
6783  test_shard_file, kTestShardStatusFile);
6784  fflush(stdout);
6785  exit(EXIT_FAILURE);
6786  }
6787  fclose(file);
6788  }
6789 }
6790 
6791 // Checks whether sharding is enabled by examining the relevant
6792 // environment variable values. If the variables are present,
6793 // but inconsistent (i.e., shard_index >= total_shards), prints
6794 // an error and exits. If in_subprocess_for_death_test, sharding is
6795 // disabled because it must only be applied to the original test
6796 // process. Otherwise, we could filter out death tests we intended to execute.
6797 bool ShouldShard(const char* total_shards_env,
6798  const char* shard_index_env,
6799  bool in_subprocess_for_death_test) {
6800  if (in_subprocess_for_death_test) {
6801  return false;
6802  }
6803 
6804  const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
6805  const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
6806 
6807  if (total_shards == -1 && shard_index == -1) {
6808  return false;
6809  } else if (total_shards == -1 && shard_index != -1) {
6810  const Message msg = Message()
6811  << "Invalid environment variables: you have "
6812  << kTestShardIndex << " = " << shard_index
6813  << ", but have left " << kTestTotalShards << " unset.\n";
6814  ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
6815  fflush(stdout);
6816  exit(EXIT_FAILURE);
6817  } else if (total_shards != -1 && shard_index == -1) {
6818  const Message msg = Message()
6819  << "Invalid environment variables: you have "
6820  << kTestTotalShards << " = " << total_shards
6821  << ", but have left " << kTestShardIndex << " unset.\n";
6822  ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
6823  fflush(stdout);
6824  exit(EXIT_FAILURE);
6825  } else if (shard_index < 0 || shard_index >= total_shards) {
6826  const Message msg = Message()
6827  << "Invalid environment variables: we require 0 <= "
6828  << kTestShardIndex << " < " << kTestTotalShards
6829  << ", but you have " << kTestShardIndex << "=" << shard_index
6830  << ", " << kTestTotalShards << "=" << total_shards << ".\n";
6831  ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
6832  fflush(stdout);
6833  exit(EXIT_FAILURE);
6834  }
6835 
6836  return total_shards > 1;
6837 }
6838 
6839 // Parses the environment variable var as an Int32. If it is unset,
6840 // returns default_val. If it is not an Int32, prints an error
6841 // and aborts.
6842 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
6843  const char* str_val = posix::GetEnv(var);
6844  if (str_val == nullptr) {
6845  return default_val;
6846  }
6847 
6848  Int32 result;
6849  if (!ParseInt32(Message() << "The value of environment variable " << var,
6850  str_val, &result)) {
6851  exit(EXIT_FAILURE);
6852  }
6853  return result;
6854 }
6855 
6856 // Given the total number of shards, the shard index, and the test id,
6857 // returns true iff the test should be run on this shard. The test id is
6858 // some arbitrary but unique non-negative integer assigned to each test
6859 // method. Assumes that 0 <= shard_index < total_shards.
6860 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
6861  return (test_id % total_shards) == shard_index;
6862 }
6863 
6864 // Compares the name of each test with the user-specified filter to
6865 // decide whether the test should be run, then records the result in
6866 // each TestSuite and TestInfo object.
6867 // If shard_tests == true, further filters tests based on sharding
6868 // variables in the environment - see
6869 // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
6870 // . Returns the number of tests that should run.
6871 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
6872  const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
6873  Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
6874  const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
6875  Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
6876 
6877  // num_runnable_tests are the number of tests that will
6878  // run across all shards (i.e., match filter and are not disabled).
6879  // num_selected_tests are the number of tests to be run on
6880  // this shard.
6881  int num_runnable_tests = 0;
6882  int num_selected_tests = 0;
6883  for (auto* test_suite : test_suites_) {
6884  const std::string& test_suite_name = test_suite->name();
6885  test_suite->set_should_run(false);
6886 
6887  for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6888  TestInfo* const test_info = test_suite->test_info_list()[j];
6889  const std::string test_name(test_info->name());
6890  // A test is disabled if test suite name or test name matches
6891  // kDisableTestFilter.
6892  const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
6893  test_suite_name, kDisableTestFilter) ||
6894  internal::UnitTestOptions::MatchesFilter(
6895  test_name, kDisableTestFilter);
6896  test_info->is_disabled_ = is_disabled;
6897 
6898  const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
6899  test_suite_name, test_name);
6900  test_info->matches_filter_ = matches_filter;
6901 
6902  const bool is_runnable =
6903  (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
6904  matches_filter;
6905 
6906  const bool is_in_another_shard =
6907  shard_tests != IGNORE_SHARDING_PROTOCOL &&
6908  !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
6909  test_info->is_in_another_shard_ = is_in_another_shard;
6910  const bool is_selected = is_runnable && !is_in_another_shard;
6911 
6912  num_runnable_tests += is_runnable;
6913  num_selected_tests += is_selected;
6914 
6915  test_info->should_run_ = is_selected;
6916  test_suite->set_should_run(test_suite->should_run() || is_selected);
6917  }
6918  }
6919  return num_selected_tests;
6920 }
6921 
6922 // Prints the given C-string on a single line by replacing all '\n'
6923 // characters with string "\\n". If the output takes more than
6924 // max_length characters, only prints the first max_length characters
6925 // and "...".
6926 static void PrintOnOneLine(const char* str, int max_length) {
6927  if (str != nullptr) {
6928  for (int i = 0; *str != '\0'; ++str) {
6929  if (i >= max_length) {
6930  printf("...");
6931  break;
6932  }
6933  if (*str == '\n') {
6934  printf("\\n");
6935  i += 2;
6936  } else {
6937  printf("%c", *str);
6938  ++i;
6939  }
6940  }
6941  }
6942 }
6943 
6944 // Prints the names of the tests matching the user-specified filter flag.
6945 void UnitTestImpl::ListTestsMatchingFilter() {
6946  // Print at most this many characters for each type/value parameter.
6947  const int kMaxParamLength = 250;
6948 
6949  for (auto* test_suite : test_suites_) {
6950  bool printed_test_suite_name = false;
6951 
6952  for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6953  const TestInfo* const test_info = test_suite->test_info_list()[j];
6954  if (test_info->matches_filter_) {
6955  if (!printed_test_suite_name) {
6956  printed_test_suite_name = true;
6957  printf("%s.", test_suite->name());
6958  if (test_suite->type_param() != nullptr) {
6959  printf(" # %s = ", kTypeParamLabel);
6960  // We print the type parameter on a single line to make
6961  // the output easy to parse by a program.
6962  PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
6963  }
6964  printf("\n");
6965  }
6966  printf(" %s", test_info->name());
6967  if (test_info->value_param() != nullptr) {
6968  printf(" # %s = ", kValueParamLabel);
6969  // We print the value parameter on a single line to make the
6970  // output easy to parse by a program.
6971  PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6972  }
6973  printf("\n");
6974  }
6975  }
6976  }
6977  fflush(stdout);
6978  const std::string& output_format = UnitTestOptions::GetOutputFormat();
6979  if (output_format == "xml" || output_format == "json") {
6980  FILE* fileout = OpenFileForWriting(
6981  UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
6982  std::stringstream stream;
6983  if (output_format == "xml") {
6984  XmlUnitTestResultPrinter(
6985  UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6986  .PrintXmlTestsList(&stream, test_suites_);
6987  } else if (output_format == "json") {
6988  JsonUnitTestResultPrinter(
6989  UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6990  .PrintJsonTestList(&stream, test_suites_);
6991  }
6992  fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
6993  fclose(fileout);
6994  }
6995 }
6996 
6997 // Sets the OS stack trace getter.
6998 //
6999 // Does nothing if the input and the current OS stack trace getter are
7000 // the same; otherwise, deletes the old getter and makes the input the
7001 // current getter.
7002 void UnitTestImpl::set_os_stack_trace_getter(
7003  OsStackTraceGetterInterface* getter) {
7004  if (os_stack_trace_getter_ != getter) {
7005  delete os_stack_trace_getter_;
7006  os_stack_trace_getter_ = getter;
7007  }
7008 }
7009 
7010 // Returns the current OS stack trace getter if it is not NULL;
7011 // otherwise, creates an OsStackTraceGetter, makes it the current
7012 // getter, and returns it.
7013 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
7014  if (os_stack_trace_getter_ == nullptr) {
7015 #ifdef GTEST_OS_STACK_TRACE_GETTER_
7016  os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
7017 #else
7018  os_stack_trace_getter_ = new OsStackTraceGetter;
7019 #endif // GTEST_OS_STACK_TRACE_GETTER_
7020  }
7021 
7022  return os_stack_trace_getter_;
7023 }
7024 
7025 // Returns the most specific TestResult currently running.
7026 TestResult* UnitTestImpl::current_test_result() {
7027  if (current_test_info_ != nullptr) {
7028  return &current_test_info_->result_;
7029  }
7030  if (current_test_suite_ != nullptr) {
7031  return &current_test_suite_->ad_hoc_test_result_;
7032  }
7033  return &ad_hoc_test_result_;
7034 }
7035 
7036 // Shuffles all test suites, and the tests within each test suite,
7037 // making sure that death tests are still run first.
7038 void UnitTestImpl::ShuffleTests() {
7039  // Shuffles the death test suites.
7040  ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
7041 
7042  // Shuffles the non-death test suites.
7043  ShuffleRange(random(), last_death_test_suite_ + 1,
7044  static_cast<int>(test_suites_.size()), &test_suite_indices_);
7045 
7046  // Shuffles the tests inside each test suite.
7047  for (auto& test_suite : test_suites_) {
7048  test_suite->ShuffleTests(random());
7049  }
7050 }
7051 
7052 // Restores the test suites and tests to their order before the first shuffle.
7053 void UnitTestImpl::UnshuffleTests() {
7054  for (size_t i = 0; i < test_suites_.size(); i++) {
7055  // Unshuffles the tests in each test suite.
7056  test_suites_[i]->UnshuffleTests();
7057  // Resets the index of each test suite.
7058  test_suite_indices_[i] = static_cast<int>(i);
7059  }
7060 }
7061 
7062 // Returns the current OS stack trace as an std::string.
7063 //
7064 // The maximum number of stack frames to be included is specified by
7065 // the gtest_stack_trace_depth flag. The skip_count parameter
7066 // specifies the number of top frames to be skipped, which doesn't
7067 // count against the number of frames to be included.
7068 //
7069 // For example, if Foo() calls Bar(), which in turn calls
7070 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
7071 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
7072 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
7073  int skip_count) {
7074  // We pass skip_count + 1 to skip this wrapper function in addition
7075  // to what the user really wants to skip.
7076  return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
7077 }
7078 
7079 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
7080 // suppress unreachable code warnings.
7081 namespace {
7082 class ClassUniqueToAlwaysTrue {};
7083 }
7084 
7085 bool IsTrue(bool condition) { return condition; }
7086 
7087 bool AlwaysTrue() {
7088 #if GTEST_HAS_EXCEPTIONS
7089  // This condition is always false so AlwaysTrue() never actually throws,
7090  // but it makes the compiler think that it may throw.
7091  if (IsTrue(false))
7092  throw ClassUniqueToAlwaysTrue();
7093 #endif // GTEST_HAS_EXCEPTIONS
7094  return true;
7095 }
7096 
7097 // If *pstr starts with the given prefix, modifies *pstr to be right
7098 // past the prefix and returns true; otherwise leaves *pstr unchanged
7099 // and returns false. None of pstr, *pstr, and prefix can be NULL.
7100 bool SkipPrefix(const char* prefix, const char** pstr) {
7101  const size_t prefix_len = strlen(prefix);
7102  if (strncmp(*pstr, prefix, prefix_len) == 0) {
7103  *pstr += prefix_len;
7104  return true;
7105  }
7106  return false;
7107 }
7108 
7109 // Parses a string as a command line flag. The string should have
7110 // the format "--flag=value". When def_optional is true, the "=value"
7111 // part can be omitted.
7112 //
7113 // Returns the value of the flag, or NULL if the parsing failed.
7114 static const char* ParseFlagValue(const char* str, const char* flag,
7115  bool def_optional) {
7116  // str and flag must not be NULL.
7117  if (str == nullptr || flag == nullptr) return nullptr;
7118 
7119  // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
7120  const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
7121  const size_t flag_len = flag_str.length();
7122  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
7123 
7124  // Skips the flag name.
7125  const char* flag_end = str + flag_len;
7126 
7127  // When def_optional is true, it's OK to not have a "=value" part.
7128  if (def_optional && (flag_end[0] == '\0')) {
7129  return flag_end;
7130  }
7131 
7132  // If def_optional is true and there are more characters after the
7133  // flag name, or if def_optional is false, there must be a '=' after
7134  // the flag name.
7135  if (flag_end[0] != '=') return nullptr;
7136 
7137  // Returns the string after "=".
7138  return flag_end + 1;
7139 }
7140 
7141 // Parses a string for a bool flag, in the form of either
7142 // "--flag=value" or "--flag".
7143 //
7144 // In the former case, the value is taken as true as long as it does
7145 // not start with '0', 'f', or 'F'.
7146 //
7147 // In the latter case, the value is taken as true.
7148 //
7149 // On success, stores the value of the flag in *value, and returns
7150 // true. On failure, returns false without changing *value.
7151 static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
7152  // Gets the value of the flag as a string.
7153  const char* const value_str = ParseFlagValue(str, flag, true);
7154 
7155  // Aborts if the parsing failed.
7156  if (value_str == nullptr) return false;
7157 
7158  // Converts the string value to a bool.
7159  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
7160  return true;
7161 }
7162 
7163 // Parses a string for an Int32 flag, in the form of
7164 // "--flag=value".
7165 //
7166 // On success, stores the value of the flag in *value, and returns
7167 // true. On failure, returns false without changing *value.
7168 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
7169  // Gets the value of the flag as a string.
7170  const char* const value_str = ParseFlagValue(str, flag, false);
7171 
7172  // Aborts if the parsing failed.
7173  if (value_str == nullptr) return false;
7174 
7175  // Sets *value to the value of the flag.
7176  return ParseInt32(Message() << "The value of flag --" << flag,
7177  value_str, value);
7178 }
7179 
7180 // Parses a string for a string flag, in the form of
7181 // "--flag=value".
7182 //
7183 // On success, stores the value of the flag in *value, and returns
7184 // true. On failure, returns false without changing *value.
7185 template <typename String>
7186 static bool ParseStringFlag(const char* str, const char* flag, String* value) {
7187  // Gets the value of the flag as a string.
7188  const char* const value_str = ParseFlagValue(str, flag, false);
7189 
7190  // Aborts if the parsing failed.
7191  if (value_str == nullptr) return false;
7192 
7193  // Sets *value to the value of the flag.
7194  *value = value_str;
7195  return true;
7196 }
7197 
7198 // Determines whether a string has a prefix that Google Test uses for its
7199 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
7200 // If Google Test detects that a command line flag has its prefix but is not
7201 // recognized, it will print its help message. Flags starting with
7202 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
7203 // internal flags and do not trigger the help message.
7204 static bool HasGoogleTestFlagPrefix(const char* str) {
7205  return (SkipPrefix("--", &str) ||
7206  SkipPrefix("-", &str) ||
7207  SkipPrefix("/", &str)) &&
7208  !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
7209  (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
7211 }
7212 
7213 // Prints a string containing code-encoded text. The following escape
7214 // sequences can be used in the string to control the text color:
7215 //
7216 // @@ prints a single '@' character.
7217 // @R changes the color to red.
7218 // @G changes the color to green.
7219 // @Y changes the color to yellow.
7220 // @D changes to the default terminal text color.
7221 //
7222 static void PrintColorEncoded(const char* str) {
7223  GTestColor color = COLOR_DEFAULT; // The current color.
7224 
7225  // Conceptually, we split the string into segments divided by escape
7226  // sequences. Then we print one segment at a time. At the end of
7227  // each iteration, the str pointer advances to the beginning of the
7228  // next segment.
7229  for (;;) {
7230  const char* p = strchr(str, '@');
7231  if (p == nullptr) {
7232  ColoredPrintf(color, "%s", str);
7233  return;
7234  }
7235 
7236  ColoredPrintf(color, "%s", std::string(str, p).c_str());
7237 
7238  const char ch = p[1];
7239  str = p + 2;
7240  if (ch == '@') {
7241  ColoredPrintf(color, "@");
7242  } else if (ch == 'D') {
7243  color = COLOR_DEFAULT;
7244  } else if (ch == 'R') {
7245  color = COLOR_RED;
7246  } else if (ch == 'G') {
7247  color = COLOR_GREEN;
7248  } else if (ch == 'Y') {
7249  color = COLOR_YELLOW;
7250  } else {
7251  --str;
7252  }
7253  }
7254 }
7255 
7256 static const char kColorEncodedHelpMessage[] =
7257 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
7258 "following command line flags to control its behavior:\n"
7259 "\n"
7260 "Test Selection:\n"
7261 " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
7262 " List the names of all tests instead of running them. The name of\n"
7263 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
7264 " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
7265  "[@G-@YNEGATIVE_PATTERNS]@D\n"
7266 " Run only the tests whose name matches one of the positive patterns but\n"
7267 " none of the negative patterns. '?' matches any single character; '*'\n"
7268 " matches any substring; ':' separates two patterns.\n"
7269 " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
7270 " Run all disabled tests too.\n"
7271 "\n"
7272 "Test Execution:\n"
7273 " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
7274 " Run the tests repeatedly; use a negative count to repeat forever.\n"
7275 " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
7276 " Randomize tests' orders on every iteration.\n"
7277 " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
7278 " Random number seed to use for shuffling test orders (between 1 and\n"
7279 " 99999, or 0 to use a seed based on the current time).\n"
7280 "\n"
7281 "Test Output:\n"
7282 " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
7283 " Enable/disable colored output. The default is @Gauto@D.\n"
7284 " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
7285 " Don't print the elapsed time of each test.\n"
7286 " @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
7287  GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
7288 " Generate a JSON or XML report in the given directory or with the given\n"
7289 " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
7290 # if GTEST_CAN_STREAM_RESULTS_
7291 " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
7292 " Stream test results to the given server.\n"
7293 # endif // GTEST_CAN_STREAM_RESULTS_
7294 "\n"
7295 "Assertion Behavior:\n"
7296 # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
7297 " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
7298 " Set the default death test style.\n"
7299 # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
7300 " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
7301 " Turn assertion failures into debugger break-points.\n"
7302 " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
7303 " Turn assertion failures into C++ exceptions for use by an external\n"
7304 " test framework.\n"
7305 " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
7306 " Do not report exceptions as test failures. Instead, allow them\n"
7307 " to crash the program or throw a pop-up (on Windows).\n"
7308 "\n"
7309 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
7310  "the corresponding\n"
7311 "environment variable of a flag (all letters in upper-case). For example, to\n"
7312 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
7313  "color=no@D or set\n"
7314 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
7315 "\n"
7316 "For more information, please read the " GTEST_NAME_ " documentation at\n"
7317 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
7318 "(not one in your own code or tests), please report it to\n"
7319 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
7320 
7321 static bool ParseGoogleTestFlag(const char* const arg) {
7322  return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
7323  &GTEST_FLAG(also_run_disabled_tests)) ||
7324  ParseBoolFlag(arg, kBreakOnFailureFlag,
7325  &GTEST_FLAG(break_on_failure)) ||
7326  ParseBoolFlag(arg, kCatchExceptionsFlag,
7327  &GTEST_FLAG(catch_exceptions)) ||
7328  ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
7329  ParseStringFlag(arg, kDeathTestStyleFlag,
7330  &GTEST_FLAG(death_test_style)) ||
7331  ParseBoolFlag(arg, kDeathTestUseFork,
7332  &GTEST_FLAG(death_test_use_fork)) ||
7333  ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
7334  ParseStringFlag(arg, kInternalRunDeathTestFlag,
7335  &GTEST_FLAG(internal_run_death_test)) ||
7336  ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
7337  ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
7338  ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
7339  ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
7340  ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
7341  ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
7342  ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
7343  ParseInt32Flag(arg, kStackTraceDepthFlag,
7344  &GTEST_FLAG(stack_trace_depth)) ||
7345  ParseStringFlag(arg, kStreamResultToFlag,
7346  &GTEST_FLAG(stream_result_to)) ||
7347  ParseBoolFlag(arg, kThrowOnFailureFlag,
7348  &GTEST_FLAG(throw_on_failure));
7349 }
7350 
7351 #if GTEST_USE_OWN_FLAGFILE_FLAG_
7352 static void LoadFlagsFromFile(const std::string& path) {
7353  FILE* flagfile = posix::FOpen(path.c_str(), "r");
7354  if (!flagfile) {
7355  GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
7356  << "\"";
7357  }
7358  std::string contents(ReadEntireFile(flagfile));
7359  posix::FClose(flagfile);
7360  std::vector<std::string> lines;
7361  SplitString(contents, '\n', &lines);
7362  for (size_t i = 0; i < lines.size(); ++i) {
7363  if (lines[i].empty())
7364  continue;
7365  if (!ParseGoogleTestFlag(lines[i].c_str()))
7366  g_help_flag = true;
7367  }
7368 }
7369 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
7370 
7371 // Parses the command line for Google Test flags, without initializing
7372 // other parts of Google Test. The type parameter CharType can be
7373 // instantiated to either char or wchar_t.
7374 template <typename CharType>
7375 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
7376  for (int i = 1; i < *argc; i++) {
7377  const std::string arg_string = StreamableToString(argv[i]);
7378  const char* const arg = arg_string.c_str();
7379 
7380  using internal::ParseBoolFlag;
7381  using internal::ParseInt32Flag;
7382  using internal::ParseStringFlag;
7383 
7384  bool remove_flag = false;
7385  if (ParseGoogleTestFlag(arg)) {
7386  remove_flag = true;
7387 #if GTEST_USE_OWN_FLAGFILE_FLAG_
7388  } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
7389  LoadFlagsFromFile(GTEST_FLAG(flagfile));
7390  remove_flag = true;
7391 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
7392  } else if (arg_string == "--help" || arg_string == "-h" ||
7393  arg_string == "-?" || arg_string == "/?" ||
7394  HasGoogleTestFlagPrefix(arg)) {
7395  // Both help flag and unrecognized Google Test flags (excluding
7396  // internal ones) trigger help display.
7397  g_help_flag = true;
7398  }
7399 
7400  if (remove_flag) {
7401  // Shift the remainder of the argv list left by one. Note
7402  // that argv has (*argc + 1) elements, the last one always being
7403  // NULL. The following loop moves the trailing NULL element as
7404  // well.
7405  for (int j = i; j != *argc; j++) {
7406  argv[j] = argv[j + 1];
7407  }
7408 
7409  // Decrements the argument count.
7410  (*argc)--;
7411 
7412  // We also need to decrement the iterator as we just removed
7413  // an element.
7414  i--;
7415  }
7416  }
7417 
7418  if (g_help_flag) {
7419  // We print the help here instead of in RUN_ALL_TESTS(), as the
7420  // latter may not be called at all if the user is using Google
7421  // Test with another testing framework.
7422  PrintColorEncoded(kColorEncodedHelpMessage);
7423  }
7424 }
7425 
7426 // Parses the command line for Google Test flags, without initializing
7427 // other parts of Google Test.
7428 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
7429  ParseGoogleTestFlagsOnlyImpl(argc, argv);
7430 
7431  // Fix the value of *_NSGetArgc() on macOS, but iff
7432  // *_NSGetArgv() == argv
7433  // Only applicable to char** version of argv
7434 #if GTEST_OS_MAC
7435 #ifndef GTEST_OS_IOS
7436  if (*_NSGetArgv() == argv) {
7437  *_NSGetArgc() = *argc;
7438  }
7439 #endif
7440 #endif
7441 }
7442 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
7443  ParseGoogleTestFlagsOnlyImpl(argc, argv);
7444 }
7445 
7446 // The internal implementation of InitGoogleTest().
7447 //
7448 // The type parameter CharType can be instantiated to either char or
7449 // wchar_t.
7450 template <typename CharType>
7451 void InitGoogleTestImpl(int* argc, CharType** argv) {
7452  // We don't want to run the initialization code twice.
7453  if (GTestIsInitialized()) return;
7454 
7455  if (*argc <= 0) return;
7456 
7457  g_argvs.clear();
7458  for (int i = 0; i != *argc; i++) {
7459  g_argvs.push_back(StreamableToString(argv[i]));
7460  }
7461 
7462 #if GTEST_HAS_ABSL
7463  absl::InitializeSymbolizer(g_argvs[0].c_str());
7464 #endif // GTEST_HAS_ABSL
7465 
7466  ParseGoogleTestFlagsOnly(argc, argv);
7467  GetUnitTestImpl()->PostFlagParsingInit();
7468 }
7469 
7470 } // namespace internal
7471 
7472 // Initializes Google Test. This must be called before calling
7473 // RUN_ALL_TESTS(). In particular, it parses a command line for the
7474 // flags that Google Test recognizes. Whenever a Google Test flag is
7475 // seen, it is removed from argv, and *argc is decremented.
7476 //
7477 // No value is returned. Instead, the Google Test flag variables are
7478 // updated.
7479 //
7480 // Calling the function for the second time has no user-visible effect.
7481 void InitGoogleTest(int* argc, char** argv) {
7482 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7483  GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
7484 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7485  internal::InitGoogleTestImpl(argc, argv);
7486 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7487 }
7488 
7489 // This overloaded version can be used in Windows programs compiled in
7490 // UNICODE mode.
7491 void InitGoogleTest(int* argc, wchar_t** argv) {
7492 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7493  GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
7494 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7495  internal::InitGoogleTestImpl(argc, argv);
7496 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
7497 }
7498 
7499 std::string TempDir() {
7500 #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
7501  return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
7502 #endif
7503 
7504 #if GTEST_OS_WINDOWS_MOBILE
7505  return "\\temp\\";
7506 #elif GTEST_OS_WINDOWS
7507  const char* temp_dir = internal::posix::GetEnv("TEMP");
7508  if (temp_dir == nullptr || temp_dir[0] == '\0')
7509  return "\\temp\\";
7510  else if (temp_dir[strlen(temp_dir) - 1] == '\\')
7511  return temp_dir;
7512  else
7513  return std::string(temp_dir) + "\\";
7514 #elif GTEST_OS_LINUX_ANDROID
7515  return "/sdcard/";
7516 #else
7517  return "/tmp/";
7518 #endif // GTEST_OS_WINDOWS_MOBILE
7519 }
7520 
7521 // Class ScopedTrace
7522 
7523 // Pushes the given source file location and message onto a per-thread
7524 // trace stack maintained by Google Test.
7525 void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
7526  internal::TraceInfo trace;
7527  trace.file = file;
7528  trace.line = line;
7529  trace.message.swap(message);
7530 
7531  UnitTest::GetInstance()->PushGTestTrace(trace);
7532 }
7533 
7534 // Pops the info pushed by the c'tor.
7535 ScopedTrace::~ScopedTrace()
7536  GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
7537  UnitTest::GetInstance()->PopGTestTrace();
7538 }
7539 
7540 } // namespace testing
7541 // Copyright 2005, Google Inc.
7542 // All rights reserved.
7543 //
7544 // Redistribution and use in source and binary forms, with or without
7545 // modification, are permitted provided that the following conditions are
7546 // met:
7547 //
7548 // * Redistributions of source code must retain the above copyright
7549 // notice, this list of conditions and the following disclaimer.
7550 // * Redistributions in binary form must reproduce the above
7551 // copyright notice, this list of conditions and the following disclaimer
7552 // in the documentation and/or other materials provided with the
7553 // distribution.
7554 // * Neither the name of Google Inc. nor the names of its
7555 // contributors may be used to endorse or promote products derived from
7556 // this software without specific prior written permission.
7557 //
7558 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7559 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7560 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7561 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7562 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7563 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7564 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7565 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7566 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7567 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7568 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7569 
7570 //
7571 // This file implements death tests.
7572 
7573 
7574 #include <utility>
7575 
7576 
7577 #if GTEST_HAS_DEATH_TEST
7578 
7579 # if GTEST_OS_MAC
7580 # include <crt_externs.h>
7581 # endif // GTEST_OS_MAC
7582 
7583 # include <errno.h>
7584 # include <fcntl.h>
7585 # include <limits.h>
7586 
7587 # if GTEST_OS_LINUX
7588 # include <signal.h>
7589 # endif // GTEST_OS_LINUX
7590 
7591 # include <stdarg.h>
7592 
7593 # if GTEST_OS_WINDOWS
7594 # include <windows.h>
7595 # else
7596 # include <sys/mman.h>
7597 # include <sys/wait.h>
7598 # endif // GTEST_OS_WINDOWS
7599 
7600 # if GTEST_OS_QNX
7601 # include <spawn.h>
7602 # endif // GTEST_OS_QNX
7603 
7604 # if GTEST_OS_FUCHSIA
7605 # include <lib/fdio/io.h>
7606 # include <lib/fdio/spawn.h>
7607 # include <lib/fdio/util.h>
7608 # include <lib/zx/socket.h>
7609 # include <lib/zx/port.h>
7610 # include <lib/zx/process.h>
7611 # include <zircon/processargs.h>
7612 # include <zircon/syscalls.h>
7613 # include <zircon/syscalls/policy.h>
7614 # include <zircon/syscalls/port.h>
7615 # endif // GTEST_OS_FUCHSIA
7616 
7617 #endif // GTEST_HAS_DEATH_TEST
7618 
7619 
7620 namespace testing {
7621 
7622 // Constants.
7623 
7624 // The default death test style.
7625 //
7626 // This is defined in internal/gtest-port.h as "fast", but can be overridden by
7627 // a definition in internal/custom/gtest-port.h. The recommended value, which is
7628 // used internally at Google, is "threadsafe".
7629 static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
7630 
7632  death_test_style,
7633  internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
7634  "Indicates how to run a death test in a forked child process: "
7635  "\"threadsafe\" (child process re-executes the test binary "
7636  "from the beginning, running only the specific death test) or "
7637  "\"fast\" (child process runs the death test immediately "
7638  "after forking).");
7639 
7641  death_test_use_fork,
7642  internal::BoolFromGTestEnv("death_test_use_fork", false),
7643  "Instructs to use fork()/_exit() instead of clone() in death tests. "
7644  "Ignored and always uses fork() on POSIX systems where clone() is not "
7645  "implemented. Useful when running under valgrind or similar tools if "
7646  "those do not support clone(). Valgrind 3.3.1 will just fail if "
7647  "it sees an unsupported combination of clone() flags. "
7648  "It is not recommended to use this flag w/o valgrind though it will "
7649  "work in 99% of the cases. Once valgrind is fixed, this flag will "
7650  "most likely be removed.");
7651 
7652 namespace internal {
7654  internal_run_death_test, "",
7655  "Indicates the file, line number, temporal index of "
7656  "the single death test to run, and a file descriptor to "
7657  "which a success code may be sent, all separated by "
7658  "the '|' characters. This flag is specified if and only if the current "
7659  "process is a sub-process launched for running a thread-safe "
7660  "death test. FOR INTERNAL USE ONLY.");
7661 } // namespace internal
7662 
7663 #if GTEST_HAS_DEATH_TEST
7664 
7665 namespace internal {
7666 
7667 // Valid only for fast death tests. Indicates the code is running in the
7668 // child process of a fast style death test.
7669 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7670 static bool g_in_fast_death_test_child = false;
7671 # endif
7672 
7673 // Returns a Boolean value indicating whether the caller is currently
7674 // executing in the context of the death test child process. Tools such as
7675 // Valgrind heap checkers may need this to modify their behavior in death
7676 // tests. IMPORTANT: This is an internal utility. Using it may break the
7677 // implementation of death tests. User code MUST NOT use it.
7678 bool InDeathTestChild() {
7679 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7680 
7681  // On Windows and Fuchsia, death tests are thread-safe regardless of the value
7682  // of the death_test_style flag.
7683  return !GTEST_FLAG(internal_run_death_test).empty();
7684 
7685 # else
7686 
7687  if (GTEST_FLAG(death_test_style) == "threadsafe")
7688  return !GTEST_FLAG(internal_run_death_test).empty();
7689  else
7690  return g_in_fast_death_test_child;
7691 #endif
7692 }
7693 
7694 } // namespace internal
7695 
7696 // ExitedWithCode constructor.
7697 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
7698 }
7699 
7700 // ExitedWithCode function-call operator.
7701 bool ExitedWithCode::operator()(int exit_status) const {
7702 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7703 
7704  return exit_status == exit_code_;
7705 
7706 # else
7707 
7708  return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
7709 
7710 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7711 }
7712 
7713 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7714 // KilledBySignal constructor.
7715 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
7716 }
7717 
7718 // KilledBySignal function-call operator.
7719 bool KilledBySignal::operator()(int exit_status) const {
7720 # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7721  {
7722  bool result;
7723  if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
7724  return result;
7725  }
7726  }
7727 # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7728  return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
7729 }
7730 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7731 
7732 namespace internal {
7733 
7734 // Utilities needed for death tests.
7735 
7736 // Generates a textual description of a given exit code, in the format
7737 // specified by wait(2).
7738 static std::string ExitSummary(int exit_code) {
7739  Message m;
7740 
7741 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7742 
7743  m << "Exited with exit status " << exit_code;
7744 
7745 # else
7746 
7747  if (WIFEXITED(exit_code)) {
7748  m << "Exited with exit status " << WEXITSTATUS(exit_code);
7749  } else if (WIFSIGNALED(exit_code)) {
7750  m << "Terminated by signal " << WTERMSIG(exit_code);
7751  }
7752 # ifdef WCOREDUMP
7753  if (WCOREDUMP(exit_code)) {
7754  m << " (core dumped)";
7755  }
7756 # endif
7757 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
7758 
7759  return m.GetString();
7760 }
7761 
7762 // Returns true if exit_status describes a process that was terminated
7763 // by a signal, or exited normally with a nonzero exit code.
7764 bool ExitedUnsuccessfully(int exit_status) {
7765  return !ExitedWithCode(0)(exit_status);
7766 }
7767 
7768 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7769 // Generates a textual failure message when a death test finds more than
7770 // one thread running, or cannot determine the number of threads, prior
7771 // to executing the given statement. It is the responsibility of the
7772 // caller not to pass a thread_count of 1.
7773 static std::string DeathTestThreadWarning(size_t thread_count) {
7774  Message msg;
7775  msg << "Death tests use fork(), which is unsafe particularly"
7776  << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
7777  if (thread_count == 0) {
7778  msg << "couldn't detect the number of threads.";
7779  } else {
7780  msg << "detected " << thread_count << " threads.";
7781  }
7782  msg << " See "
7783  "https://github.com/google/googletest/blob/master/googletest/docs/"
7784  "advanced.md#death-tests-and-threads"
7785  << " for more explanation and suggested solutions, especially if"
7786  << " this is the last message you see before your test times out.";
7787  return msg.GetString();
7788 }
7789 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
7790 
7791 // Flag characters for reporting a death test that did not die.
7792 static const char kDeathTestLived = 'L';
7793 static const char kDeathTestReturned = 'R';
7794 static const char kDeathTestThrew = 'T';
7795 static const char kDeathTestInternalError = 'I';
7796 
7797 #if GTEST_OS_FUCHSIA
7798 
7799 // File descriptor used for the pipe in the child process.
7800 static const int kFuchsiaReadPipeFd = 3;
7801 
7802 #endif
7803 
7804 // An enumeration describing all of the possible ways that a death test can
7805 // conclude. DIED means that the process died while executing the test
7806 // code; LIVED means that process lived beyond the end of the test code;
7807 // RETURNED means that the test statement attempted to execute a return
7808 // statement, which is not allowed; THREW means that the test statement
7809 // returned control by throwing an exception. IN_PROGRESS means the test
7810 // has not yet concluded.
7811 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
7812 
7813 // Routine for aborting the program which is safe to call from an
7814 // exec-style death test child process, in which case the error
7815 // message is propagated back to the parent process. Otherwise, the
7816 // message is simply printed to stderr. In either case, the program
7817 // then exits with status 1.
7818 static void DeathTestAbort(const std::string& message) {
7819  // On a POSIX system, this function may be called from a threadsafe-style
7820  // death test child process, which operates on a very small stack. Use
7821  // the heap for any additional non-minuscule memory requirements.
7822  const InternalRunDeathTestFlag* const flag =
7823  GetUnitTestImpl()->internal_run_death_test_flag();
7824  if (flag != nullptr) {
7825  FILE* parent = posix::FDOpen(flag->write_fd(), "w");
7826  fputc(kDeathTestInternalError, parent);
7827  fprintf(parent, "%s", message.c_str());
7828  fflush(parent);
7829  _exit(1);
7830  } else {
7831  fprintf(stderr, "%s", message.c_str());
7832  fflush(stderr);
7833  posix::Abort();
7834  }
7835 }
7836 
7837 // A replacement for CHECK that calls DeathTestAbort if the assertion
7838 // fails.
7839 # define GTEST_DEATH_TEST_CHECK_(expression) \
7840  do { \
7841  if (!::testing::internal::IsTrue(expression)) { \
7842  DeathTestAbort( \
7843  ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7844  + ::testing::internal::StreamableToString(__LINE__) + ": " \
7845  + #expression); \
7846  } \
7847  } while (::testing::internal::AlwaysFalse())
7848 
7849 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
7850 // evaluating any system call that fulfills two conditions: it must return
7851 // -1 on failure, and set errno to EINTR when it is interrupted and
7852 // should be tried again. The macro expands to a loop that repeatedly
7853 // evaluates the expression as long as it evaluates to -1 and sets
7854 // errno to EINTR. If the expression evaluates to -1 but errno is
7855 // something other than EINTR, DeathTestAbort is called.
7856 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
7857  do { \
7858  int gtest_retval; \
7859  do { \
7860  gtest_retval = (expression); \
7861  } while (gtest_retval == -1 && errno == EINTR); \
7862  if (gtest_retval == -1) { \
7863  DeathTestAbort( \
7864  ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7865  + ::testing::internal::StreamableToString(__LINE__) + ": " \
7866  + #expression + " != -1"); \
7867  } \
7868  } while (::testing::internal::AlwaysFalse())
7869 
7870 // Returns the message describing the last system error in errno.
7871 std::string GetLastErrnoDescription() {
7872  return errno == 0 ? "" : posix::StrError(errno);
7873 }
7874 
7875 // This is called from a death test parent process to read a failure
7876 // message from the death test child process and log it with the FATAL
7877 // severity. On Windows, the message is read from a pipe handle. On other
7878 // platforms, it is read from a file descriptor.
7879 static void FailFromInternalError(int fd) {
7880  Message error;
7881  char buffer[256];
7882  int num_read;
7883 
7884  do {
7885  while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
7886  buffer[num_read] = '\0';
7887  error << buffer;
7888  }
7889  } while (num_read == -1 && errno == EINTR);
7890 
7891  if (num_read == 0) {
7892  GTEST_LOG_(FATAL) << error.GetString();
7893  } else {
7894  const int last_error = errno;
7895  GTEST_LOG_(FATAL) << "Error while reading death test internal: "
7896  << GetLastErrnoDescription() << " [" << last_error << "]";
7897  }
7898 }
7899 
7900 // Death test constructor. Increments the running death test count
7901 // for the current test.
7902 DeathTest::DeathTest() {
7903  TestInfo* const info = GetUnitTestImpl()->current_test_info();
7904  if (info == nullptr) {
7905  DeathTestAbort("Cannot run a death test outside of a TEST or "
7906  "TEST_F construct");
7907  }
7908 }
7909 
7910 // Creates and returns a death test by dispatching to the current
7911 // death test factory.
7912 bool DeathTest::Create(const char* statement,
7913  Matcher<const std::string&> matcher, const char* file,
7914  int line, DeathTest** test) {
7915  return GetUnitTestImpl()->death_test_factory()->Create(
7916  statement, std::move(matcher), file, line, test);
7917 }
7918 
7919 const char* DeathTest::LastMessage() {
7920  return last_death_test_message_.c_str();
7921 }
7922 
7923 void DeathTest::set_last_death_test_message(const std::string& message) {
7924  last_death_test_message_ = message;
7925 }
7926 
7927 std::string DeathTest::last_death_test_message_;
7928 
7929 // Provides cross platform implementation for some death functionality.
7930 class DeathTestImpl : public DeathTest {
7931  protected:
7932  DeathTestImpl(const char* a_statement, Matcher<const std::string&> matcher)
7933  : statement_(a_statement),
7934  matcher_(std::move(matcher)),
7935  spawned_(false),
7936  status_(-1),
7937  outcome_(IN_PROGRESS),
7938  read_fd_(-1),
7939  write_fd_(-1) {}
7940 
7941  // read_fd_ is expected to be closed and cleared by a derived class.
7942  ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
7943 
7944  void Abort(AbortReason reason) override;
7945  bool Passed(bool status_ok) override;
7946 
7947  const char* statement() const { return statement_; }
7948  bool spawned() const { return spawned_; }
7949  void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
7950  int status() const { return status_; }
7951  void set_status(int a_status) { status_ = a_status; }
7952  DeathTestOutcome outcome() const { return outcome_; }
7953  void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
7954  int read_fd() const { return read_fd_; }
7955  void set_read_fd(int fd) { read_fd_ = fd; }
7956  int write_fd() const { return write_fd_; }
7957  void set_write_fd(int fd) { write_fd_ = fd; }
7958 
7959  // Called in the parent process only. Reads the result code of the death
7960  // test child process via a pipe, interprets it to set the outcome_
7961  // member, and closes read_fd_. Outputs diagnostics and terminates in
7962  // case of unexpected codes.
7963  void ReadAndInterpretStatusByte();
7964 
7965  // Returns stderr output from the child process.
7966  virtual std::string GetErrorLogs();
7967 
7968  private:
7969  // The textual content of the code this object is testing. This class
7970  // doesn't own this string and should not attempt to delete it.
7971  const char* const statement_;
7972  // A matcher that's expected to match the stderr output by the child process.
7973  Matcher<const std::string&> matcher_;
7974  // True if the death test child process has been successfully spawned.
7975  bool spawned_;
7976  // The exit status of the child process.
7977  int status_;
7978  // How the death test concluded.
7979  DeathTestOutcome outcome_;
7980  // Descriptor to the read end of the pipe to the child process. It is
7981  // always -1 in the child process. The child keeps its write end of the
7982  // pipe in write_fd_.
7983  int read_fd_;
7984  // Descriptor to the child's write end of the pipe to the parent process.
7985  // It is always -1 in the parent process. The parent keeps its end of the
7986  // pipe in read_fd_.
7987  int write_fd_;
7988 };
7989 
7990 // Called in the parent process only. Reads the result code of the death
7991 // test child process via a pipe, interprets it to set the outcome_
7992 // member, and closes read_fd_. Outputs diagnostics and terminates in
7993 // case of unexpected codes.
7994 void DeathTestImpl::ReadAndInterpretStatusByte() {
7995  char flag;
7996  int bytes_read;
7997 
7998  // The read() here blocks until data is available (signifying the
7999  // failure of the death test) or until the pipe is closed (signifying
8000  // its success), so it's okay to call this in the parent before
8001  // the child process has exited.
8002  do {
8003  bytes_read = posix::Read(read_fd(), &flag, 1);
8004  } while (bytes_read == -1 && errno == EINTR);
8005 
8006  if (bytes_read == 0) {
8007  set_outcome(DIED);
8008  } else if (bytes_read == 1) {
8009  switch (flag) {
8010  case kDeathTestReturned:
8011  set_outcome(RETURNED);
8012  break;
8013  case kDeathTestThrew:
8014  set_outcome(THREW);
8015  break;
8016  case kDeathTestLived:
8017  set_outcome(LIVED);
8018  break;
8019  case kDeathTestInternalError:
8020  FailFromInternalError(read_fd()); // Does not return.
8021  break;
8022  default:
8023  GTEST_LOG_(FATAL) << "Death test child process reported "
8024  << "unexpected status byte ("
8025  << static_cast<unsigned int>(flag) << ")";
8026  }
8027  } else {
8028  GTEST_LOG_(FATAL) << "Read from death test child process failed: "
8029  << GetLastErrnoDescription();
8030  }
8031  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
8032  set_read_fd(-1);
8033 }
8034 
8035 std::string DeathTestImpl::GetErrorLogs() {
8036  return GetCapturedStderr();
8037 }
8038 
8039 // Signals that the death test code which should have exited, didn't.
8040 // Should be called only in a death test child process.
8041 // Writes a status byte to the child's status file descriptor, then
8042 // calls _exit(1).
8043 void DeathTestImpl::Abort(AbortReason reason) {
8044  // The parent process considers the death test to be a failure if
8045  // it finds any data in our pipe. So, here we write a single flag byte
8046  // to the pipe, then exit.
8047  const char status_ch =
8048  reason == TEST_DID_NOT_DIE ? kDeathTestLived :
8049  reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
8050 
8051  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
8052  // We are leaking the descriptor here because on some platforms (i.e.,
8053  // when built as Windows DLL), destructors of global objects will still
8054  // run after calling _exit(). On such systems, write_fd_ will be
8055  // indirectly closed from the destructor of UnitTestImpl, causing double
8056  // close if it is also closed here. On debug configurations, double close
8057  // may assert. As there are no in-process buffers to flush here, we are
8058  // relying on the OS to close the descriptor after the process terminates
8059  // when the destructors are not run.
8060  _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
8061 }
8062 
8063 // Returns an indented copy of stderr output for a death test.
8064 // This makes distinguishing death test output lines from regular log lines
8065 // much easier.
8066 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
8067  ::std::string ret;
8068  for (size_t at = 0; ; ) {
8069  const size_t line_end = output.find('\n', at);
8070  ret += "[ DEATH ] ";
8071  if (line_end == ::std::string::npos) {
8072  ret += output.substr(at);
8073  break;
8074  }
8075  ret += output.substr(at, line_end + 1 - at);
8076  at = line_end + 1;
8077  }
8078  return ret;
8079 }
8080 
8081 // Assesses the success or failure of a death test, using both private
8082 // members which have previously been set, and one argument:
8083 //
8084 // Private data members:
8085 // outcome: An enumeration describing how the death test
8086 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
8087 // fails in the latter three cases.
8088 // status: The exit status of the child process. On *nix, it is in the
8089 // in the format specified by wait(2). On Windows, this is the
8090 // value supplied to the ExitProcess() API or a numeric code
8091 // of the exception that terminated the program.
8092 // matcher_: A matcher that's expected to match the stderr output by the child
8093 // process.
8094 //
8095 // Argument:
8096 // status_ok: true if exit_status is acceptable in the context of
8097 // this particular death test, which fails if it is false
8098 //
8099 // Returns true iff all of the above conditions are met. Otherwise, the
8100 // first failing condition, in the order given above, is the one that is
8101 // reported. Also sets the last death test message string.
8102 bool DeathTestImpl::Passed(bool status_ok) {
8103  if (!spawned())
8104  return false;
8105 
8106  const std::string error_message = GetErrorLogs();
8107 
8108  bool success = false;
8109  Message buffer;
8110 
8111  buffer << "Death test: " << statement() << "\n";
8112  switch (outcome()) {
8113  case LIVED:
8114  buffer << " Result: failed to die.\n"
8115  << " Error msg:\n" << FormatDeathTestOutput(error_message);
8116  break;
8117  case THREW:
8118  buffer << " Result: threw an exception.\n"
8119  << " Error msg:\n" << FormatDeathTestOutput(error_message);
8120  break;
8121  case RETURNED:
8122  buffer << " Result: illegal return in test statement.\n"
8123  << " Error msg:\n" << FormatDeathTestOutput(error_message);
8124  break;
8125  case DIED:
8126  if (status_ok) {
8127  if (matcher_.Matches(error_message)) {
8128  success = true;
8129  } else {
8130  std::ostringstream stream;
8131  matcher_.DescribeTo(&stream);
8132  buffer << " Result: died but not with expected error.\n"
8133  << " Expected: " << stream.str() << "\n"
8134  << "Actual msg:\n"
8135  << FormatDeathTestOutput(error_message);
8136  }
8137  } else {
8138  buffer << " Result: died but not with expected exit code:\n"
8139  << " " << ExitSummary(status()) << "\n"
8140  << "Actual msg:\n" << FormatDeathTestOutput(error_message);
8141  }
8142  break;
8143  case IN_PROGRESS:
8144  default:
8145  GTEST_LOG_(FATAL)
8146  << "DeathTest::Passed somehow called before conclusion of test";
8147  }
8148 
8149  DeathTest::set_last_death_test_message(buffer.GetString());
8150  return success;
8151 }
8152 
8153 # if GTEST_OS_WINDOWS
8154 // WindowsDeathTest implements death tests on Windows. Due to the
8155 // specifics of starting new processes on Windows, death tests there are
8156 // always threadsafe, and Google Test considers the
8157 // --gtest_death_test_style=fast setting to be equivalent to
8158 // --gtest_death_test_style=threadsafe there.
8159 //
8160 // A few implementation notes: Like the Linux version, the Windows
8161 // implementation uses pipes for child-to-parent communication. But due to
8162 // the specifics of pipes on Windows, some extra steps are required:
8163 //
8164 // 1. The parent creates a communication pipe and stores handles to both
8165 // ends of it.
8166 // 2. The parent starts the child and provides it with the information
8167 // necessary to acquire the handle to the write end of the pipe.
8168 // 3. The child acquires the write end of the pipe and signals the parent
8169 // using a Windows event.
8170 // 4. Now the parent can release the write end of the pipe on its side. If
8171 // this is done before step 3, the object's reference count goes down to
8172 // 0 and it is destroyed, preventing the child from acquiring it. The
8173 // parent now has to release it, or read operations on the read end of
8174 // the pipe will not return when the child terminates.
8175 // 5. The parent reads child's output through the pipe (outcome code and
8176 // any possible error messages) from the pipe, and its stderr and then
8177 // determines whether to fail the test.
8178 //
8179 // Note: to distinguish Win32 API calls from the local method and function
8180 // calls, the former are explicitly resolved in the global namespace.
8181 //
8182 class WindowsDeathTest : public DeathTestImpl {
8183  public:
8184  WindowsDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
8185  const char* file, int line)
8186  : DeathTestImpl(a_statement, std::move(matcher)),
8187  file_(file),
8188  line_(line) {}
8189 
8190  // All of these virtual functions are inherited from DeathTest.
8191  virtual int Wait();
8192  virtual TestRole AssumeRole();
8193 
8194  private:
8195  // The name of the file in which the death test is located.
8196  const char* const file_;
8197  // The line number on which the death test is located.
8198  const int line_;
8199  // Handle to the write end of the pipe to the child process.
8200  AutoHandle write_handle_;
8201  // Child process handle.
8202  AutoHandle child_handle_;
8203  // Event the child process uses to signal the parent that it has
8204  // acquired the handle to the write end of the pipe. After seeing this
8205  // event the parent can release its own handles to make sure its
8206  // ReadFile() calls return when the child terminates.
8207  AutoHandle event_handle_;
8208 };
8209 
8210 // Waits for the child in a death test to exit, returning its exit
8211 // status, or 0 if no child process exists. As a side effect, sets the
8212 // outcome data member.
8213 int WindowsDeathTest::Wait() {
8214  if (!spawned())
8215  return 0;
8216 
8217  // Wait until the child either signals that it has acquired the write end
8218  // of the pipe or it dies.
8219  const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
8220  switch (::WaitForMultipleObjects(2,
8221  wait_handles,
8222  FALSE, // Waits for any of the handles.
8223  INFINITE)) {
8224  case WAIT_OBJECT_0:
8225  case WAIT_OBJECT_0 + 1:
8226  break;
8227  default:
8228  GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
8229  }
8230 
8231  // The child has acquired the write end of the pipe or exited.
8232  // We release the handle on our side and continue.
8233  write_handle_.Reset();
8234  event_handle_.Reset();
8235 
8236  ReadAndInterpretStatusByte();
8237 
8238  // Waits for the child process to exit if it haven't already. This
8239  // returns immediately if the child has already exited, regardless of
8240  // whether previous calls to WaitForMultipleObjects synchronized on this
8241  // handle or not.
8242  GTEST_DEATH_TEST_CHECK_(
8243  WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
8244  INFINITE));
8245  DWORD status_code;
8246  GTEST_DEATH_TEST_CHECK_(
8247  ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
8248  child_handle_.Reset();
8249  set_status(static_cast<int>(status_code));
8250  return status();
8251 }
8252 
8253 // The AssumeRole process for a Windows death test. It creates a child
8254 // process with the same executable as the current process to run the
8255 // death test. The child process is given the --gtest_filter and
8256 // --gtest_internal_run_death_test flags such that it knows to run the
8257 // current death test only.
8258 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
8259  const UnitTestImpl* const impl = GetUnitTestImpl();
8260  const InternalRunDeathTestFlag* const flag =
8261  impl->internal_run_death_test_flag();
8262  const TestInfo* const info = impl->current_test_info();
8263  const int death_test_index = info->result()->death_test_count();
8264 
8265  if (flag != nullptr) {
8266  // ParseInternalRunDeathTestFlag() has performed all the necessary
8267  // processing.
8268  set_write_fd(flag->write_fd());
8269  return EXECUTE_TEST;
8270  }
8271 
8272  // WindowsDeathTest uses an anonymous pipe to communicate results of
8273  // a death test.
8274  SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
8275  nullptr, TRUE};
8276  HANDLE read_handle, write_handle;
8277  GTEST_DEATH_TEST_CHECK_(
8278  ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
8279  0) // Default buffer size.
8280  != FALSE);
8281  set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
8282  O_RDONLY));
8283  write_handle_.Reset(write_handle);
8284  event_handle_.Reset(::CreateEvent(
8285  &handles_are_inheritable,
8286  TRUE, // The event will automatically reset to non-signaled state.
8287  FALSE, // The initial state is non-signalled.
8288  nullptr)); // The even is unnamed.
8289  GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr);
8290  const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
8291  kFilterFlag + "=" + info->test_suite_name() +
8292  "." + info->name();
8293  const std::string internal_flag =
8294  std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
8295  "=" + file_ + "|" + StreamableToString(line_) + "|" +
8296  StreamableToString(death_test_index) + "|" +
8297  StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
8298  // size_t has the same width as pointers on both 32-bit and 64-bit
8299  // Windows platforms.
8300  // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
8301  "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
8302  "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
8303 
8304  char executable_path[_MAX_PATH + 1]; // NOLINT
8305  GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr,
8306  executable_path,
8307  _MAX_PATH));
8308 
8309  std::string command_line =
8310  std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
8311  internal_flag + "\"";
8312 
8313  DeathTest::set_last_death_test_message("");
8314 
8315  CaptureStderr();
8316  // Flush the log buffers since the log streams are shared with the child.
8317  FlushInfoLog();
8318 
8319  // The child process will share the standard handles with the parent.
8320  STARTUPINFOA startup_info;
8321  memset(&startup_info, 0, sizeof(STARTUPINFO));
8322  startup_info.dwFlags = STARTF_USESTDHANDLES;
8323  startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
8324  startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
8325  startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
8326 
8327  PROCESS_INFORMATION process_info;
8328  GTEST_DEATH_TEST_CHECK_(
8329  ::CreateProcessA(
8330  executable_path, const_cast<char*>(command_line.c_str()),
8331  nullptr, // Retuned process handle is not inheritable.
8332  nullptr, // Retuned thread handle is not inheritable.
8333  TRUE, // Child inherits all inheritable handles (for write_handle_).
8334  0x0, // Default creation flags.
8335  nullptr, // Inherit the parent's environment.
8336  UnitTest::GetInstance()->original_working_dir(), &startup_info,
8337  &process_info) != FALSE);
8338  child_handle_.Reset(process_info.hProcess);
8339  ::CloseHandle(process_info.hThread);
8340  set_spawned(true);
8341  return OVERSEE_TEST;
8342 }
8343 
8344 # elif GTEST_OS_FUCHSIA
8345 
8346 class FuchsiaDeathTest : public DeathTestImpl {
8347  public:
8348  FuchsiaDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
8349  const char* file, int line)
8350  : DeathTestImpl(a_statement, std::move(matcher)),
8351  file_(file),
8352  line_(line) {}
8353 
8354  // All of these virtual functions are inherited from DeathTest.
8355  int Wait() override;
8356  TestRole AssumeRole() override;
8357  std::string GetErrorLogs() override;
8358 
8359  private:
8360  // The name of the file in which the death test is located.
8361  const char* const file_;
8362  // The line number on which the death test is located.
8363  const int line_;
8364  // The stderr data captured by the child process.
8365  std::string captured_stderr_;
8366 
8367  zx::process child_process_;
8368  zx::port port_;
8369  zx::socket stderr_socket_;
8370 };
8371 
8372 // Utility class for accumulating command-line arguments.
8373 class Arguments {
8374  public:
8375  Arguments() { args_.push_back(nullptr); }
8376 
8377  ~Arguments() {
8378  for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
8379  ++i) {
8380  free(*i);
8381  }
8382  }
8383  void AddArgument(const char* argument) {
8384  args_.insert(args_.end() - 1, posix::StrDup(argument));
8385  }
8386 
8387  template <typename Str>
8388  void AddArguments(const ::std::vector<Str>& arguments) {
8389  for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
8390  i != arguments.end();
8391  ++i) {
8392  args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
8393  }
8394  }
8395  char* const* Argv() {
8396  return &args_[0];
8397  }
8398 
8399  int size() {
8400  return args_.size() - 1;
8401  }
8402 
8403  private:
8404  std::vector<char*> args_;
8405 };
8406 
8407 // Waits for the child in a death test to exit, returning its exit
8408 // status, or 0 if no child process exists. As a side effect, sets the
8409 // outcome data member.
8410 int FuchsiaDeathTest::Wait() {
8411  const int kProcessKey = 0;
8412  const int kSocketKey = 1;
8413 
8414  if (!spawned())
8415  return 0;
8416 
8417  // Register to wait for the child process to terminate.
8418  zx_status_t status_zx;
8419  status_zx = child_process_.wait_async(
8420  port_, kProcessKey, ZX_PROCESS_TERMINATED, ZX_WAIT_ASYNC_ONCE);
8421  GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8422  // Register to wait for the socket to be readable or closed.
8423  status_zx = stderr_socket_.wait_async(
8424  port_, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED,
8425  ZX_WAIT_ASYNC_REPEATING);
8426  GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8427 
8428  bool process_terminated = false;
8429  bool socket_closed = false;
8430  do {
8431  zx_port_packet_t packet = {};
8432  status_zx = port_.wait(zx::time::infinite(), &packet);
8433  GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8434 
8435  if (packet.key == kProcessKey) {
8436  if (ZX_PKT_IS_EXCEPTION(packet.type)) {
8437  // Process encountered an exception. Kill it directly rather than
8438  // letting other handlers process the event. We will get a second
8439  // kProcessKey event when the process actually terminates.
8440  status_zx = child_process_.kill();
8441  GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8442  } else {
8443  // Process terminated.
8444  GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
8445  GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
8446  process_terminated = true;
8447  }
8448  } else if (packet.key == kSocketKey) {
8449  GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_REP(packet.type));
8450  if (packet.signal.observed & ZX_SOCKET_READABLE) {
8451  // Read data from the socket.
8452  constexpr size_t kBufferSize = 1024;
8453  do {
8454  size_t old_length = captured_stderr_.length();
8455  size_t bytes_read = 0;
8456  captured_stderr_.resize(old_length + kBufferSize);
8457  status_zx = stderr_socket_.read(
8458  0, &captured_stderr_.front() + old_length, kBufferSize,
8459  &bytes_read);
8460  captured_stderr_.resize(old_length + bytes_read);
8461  } while (status_zx == ZX_OK);
8462  if (status_zx == ZX_ERR_PEER_CLOSED) {
8463  socket_closed = true;
8464  } else {
8465  GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);
8466  }
8467  } else {
8468  GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);
8469  socket_closed = true;
8470  }
8471  }
8472  } while (!process_terminated && !socket_closed);
8473 
8474  ReadAndInterpretStatusByte();
8475 
8476  zx_info_process_t buffer;
8477  status_zx = child_process_.get_info(
8478  ZX_INFO_PROCESS, &buffer, sizeof(buffer), nullptr, nullptr);
8479  GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8480 
8481  GTEST_DEATH_TEST_CHECK_(buffer.exited);
8482  set_status(buffer.return_code);
8483  return status();
8484 }
8485 
8486 // The AssumeRole process for a Fuchsia death test. It creates a child
8487 // process with the same executable as the current process to run the
8488 // death test. The child process is given the --gtest_filter and
8489 // --gtest_internal_run_death_test flags such that it knows to run the
8490 // current death test only.
8491 DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
8492  const UnitTestImpl* const impl = GetUnitTestImpl();
8493  const InternalRunDeathTestFlag* const flag =
8494  impl->internal_run_death_test_flag();
8495  const TestInfo* const info = impl->current_test_info();
8496  const int death_test_index = info->result()->death_test_count();
8497 
8498  if (flag != nullptr) {
8499  // ParseInternalRunDeathTestFlag() has performed all the necessary
8500  // processing.
8501  set_write_fd(kFuchsiaReadPipeFd);
8502  return EXECUTE_TEST;
8503  }
8504 
8505  // Flush the log buffers since the log streams are shared with the child.
8506  FlushInfoLog();
8507 
8508  // Build the child process command line.
8509  const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
8510  kFilterFlag + "=" + info->test_suite_name() +
8511  "." + info->name();
8512  const std::string internal_flag =
8513  std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
8514  + file_ + "|"
8515  + StreamableToString(line_) + "|"
8516  + StreamableToString(death_test_index);
8517  Arguments args;
8518  args.AddArguments(GetInjectableArgvs());
8519  args.AddArgument(filter_flag.c_str());
8520  args.AddArgument(internal_flag.c_str());
8521 
8522  // Build the pipe for communication with the child.
8523  zx_status_t status;
8524  zx_handle_t child_pipe_handle;
8525  uint32_t type;
8526  status = fdio_pipe_half(&child_pipe_handle, &type);
8527  GTEST_DEATH_TEST_CHECK_(status >= 0);
8528  set_read_fd(status);
8529 
8530  // Set the pipe handle for the child.
8531  fdio_spawn_action_t spawn_actions[2] = {};
8532  fdio_spawn_action_t* add_handle_action = &spawn_actions[0];
8533  add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;
8534  add_handle_action->h.id = PA_HND(type, kFuchsiaReadPipeFd);
8535  add_handle_action->h.handle = child_pipe_handle;
8536 
8537  // Create a socket pair will be used to receive the child process' stderr.
8538  zx::socket stderr_producer_socket;
8539  status =
8540  zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
8541  GTEST_DEATH_TEST_CHECK_(status >= 0);
8542  int stderr_producer_fd = -1;
8543  zx_handle_t producer_handle[1] = { stderr_producer_socket.release() };
8544  uint32_t producer_handle_type[1] = { PA_FDIO_SOCKET };
8545  status = fdio_create_fd(
8546  producer_handle, producer_handle_type, 1, &stderr_producer_fd);
8547  GTEST_DEATH_TEST_CHECK_(status >= 0);
8548 
8549  // Make the stderr socket nonblocking.
8550  GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);
8551 
8552  fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];
8553  add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;
8554  add_stderr_action->fd.local_fd = stderr_producer_fd;
8555  add_stderr_action->fd.target_fd = STDERR_FILENO;
8556 
8557  // Create a child job.
8558  zx_handle_t child_job = ZX_HANDLE_INVALID;
8559  status = zx_job_create(zx_job_default(), 0, & child_job);
8560  GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8561  zx_policy_basic_t policy;
8562  policy.condition = ZX_POL_NEW_ANY;
8563  policy.policy = ZX_POL_ACTION_ALLOW;
8564  status = zx_job_set_policy(
8565  child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);
8566  GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8567 
8568  // Create an exception port and attach it to the |child_job|, to allow
8569  // us to suppress the system default exception handler from firing.
8570  status = zx::port::create(0, &port_);
8571  GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8572  status = zx_task_bind_exception_port(
8573  child_job, port_.get(), 0 /* key */, 0 /*options */);
8574  GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8575 
8576  // Spawn the child process.
8577  status = fdio_spawn_etc(
8578  child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr,
8579  2, spawn_actions, child_process_.reset_and_get_address(), nullptr);
8580  GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8581 
8582  set_spawned(true);
8583  return OVERSEE_TEST;
8584 }
8585 
8586 std::string FuchsiaDeathTest::GetErrorLogs() {
8587  return captured_stderr_;
8588 }
8589 
8590 #else // We are neither on Windows, nor on Fuchsia.
8591 
8592 // ForkingDeathTest provides implementations for most of the abstract
8593 // methods of the DeathTest interface. Only the AssumeRole method is
8594 // left undefined.
8595 class ForkingDeathTest : public DeathTestImpl {
8596  public:
8597  ForkingDeathTest(const char* statement, Matcher<const std::string&> matcher);
8598 
8599  // All of these virtual functions are inherited from DeathTest.
8600  int Wait() override;
8601 
8602  protected:
8603  void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
8604 
8605  private:
8606  // PID of child process during death test; 0 in the child process itself.
8607  pid_t child_pid_;
8608 };
8609 
8610 // Constructs a ForkingDeathTest.
8611 ForkingDeathTest::ForkingDeathTest(const char* a_statement,
8612  Matcher<const std::string&> matcher)
8613  : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}
8614 
8615 // Waits for the child in a death test to exit, returning its exit
8616 // status, or 0 if no child process exists. As a side effect, sets the
8617 // outcome data member.
8618 int ForkingDeathTest::Wait() {
8619  if (!spawned())
8620  return 0;
8621 
8622  ReadAndInterpretStatusByte();
8623 
8624  int status_value;
8625  GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
8626  set_status(status_value);
8627  return status_value;
8628 }
8629 
8630 // A concrete death test class that forks, then immediately runs the test
8631 // in the child process.
8632 class NoExecDeathTest : public ForkingDeathTest {
8633  public:
8634  NoExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher)
8635  : ForkingDeathTest(a_statement, std::move(matcher)) {}
8636  TestRole AssumeRole() override;
8637 };
8638 
8639 // The AssumeRole process for a fork-and-run death test. It implements a
8640 // straightforward fork, with a simple pipe to transmit the status byte.
8641 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
8642  const size_t thread_count = GetThreadCount();
8643  if (thread_count != 1) {
8644  GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
8645  }
8646 
8647  int pipe_fd[2];
8648  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
8649 
8650  DeathTest::set_last_death_test_message("");
8651  CaptureStderr();
8652  // When we fork the process below, the log file buffers are copied, but the
8653  // file descriptors are shared. We flush all log files here so that closing
8654  // the file descriptors in the child process doesn't throw off the
8655  // synchronization between descriptors and buffers in the parent process.
8656  // This is as close to the fork as possible to avoid a race condition in case
8657  // there are multiple threads running before the death test, and another
8658  // thread writes to the log file.
8659  FlushInfoLog();
8660 
8661  const pid_t child_pid = fork();
8662  GTEST_DEATH_TEST_CHECK_(child_pid != -1);
8663  set_child_pid(child_pid);
8664  if (child_pid == 0) {
8665  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
8666  set_write_fd(pipe_fd[1]);
8667  // Redirects all logging to stderr in the child process to prevent
8668  // concurrent writes to the log files. We capture stderr in the parent
8669  // process and append the child process' output to a log.
8670  LogToStderr();
8671  // Event forwarding to the listeners of event listener API mush be shut
8672  // down in death test subprocesses.
8673  GetUnitTestImpl()->listeners()->SuppressEventForwarding();
8674  g_in_fast_death_test_child = true;
8675  return EXECUTE_TEST;
8676  } else {
8677  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
8678  set_read_fd(pipe_fd[0]);
8679  set_spawned(true);
8680  return OVERSEE_TEST;
8681  }
8682 }
8683 
8684 // A concrete death test class that forks and re-executes the main
8685 // program from the beginning, with command-line flags set that cause
8686 // only this specific death test to be run.
8687 class ExecDeathTest : public ForkingDeathTest {
8688  public:
8689  ExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
8690  const char* file, int line)
8691  : ForkingDeathTest(a_statement, std::move(matcher)),
8692  file_(file),
8693  line_(line) {}
8694  TestRole AssumeRole() override;
8695 
8696  private:
8697  static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
8698  ::std::vector<std::string> args = GetInjectableArgvs();
8699 # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
8700  ::std::vector<std::string> extra_args =
8701  GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
8702  args.insert(args.end(), extra_args.begin(), extra_args.end());
8703 # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
8704  return args;
8705  }
8706  // The name of the file in which the death test is located.
8707  const char* const file_;
8708  // The line number on which the death test is located.
8709  const int line_;
8710 };
8711 
8712 // Utility class for accumulating command-line arguments.
8713 class Arguments {
8714  public:
8715  Arguments() { args_.push_back(nullptr); }
8716 
8717  ~Arguments() {
8718  for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
8719  ++i) {
8720  free(*i);
8721  }
8722  }
8723  void AddArgument(const char* argument) {
8724  args_.insert(args_.end() - 1, posix::StrDup(argument));
8725  }
8726 
8727  template <typename Str>
8728  void AddArguments(const ::std::vector<Str>& arguments) {
8729  for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
8730  i != arguments.end();
8731  ++i) {
8732  args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
8733  }
8734  }
8735  char* const* Argv() {
8736  return &args_[0];
8737  }
8738 
8739  private:
8740  std::vector<char*> args_;
8741 };
8742 
8743 // A struct that encompasses the arguments to the child process of a
8744 // threadsafe-style death test process.
8745 struct ExecDeathTestArgs {
8746  char* const* argv; // Command-line arguments for the child's call to exec
8747  int close_fd; // File descriptor to close; the read end of a pipe
8748 };
8749 
8750 # if GTEST_OS_MAC
8751 inline char** GetEnviron() {
8752  // When Google Test is built as a framework on MacOS X, the environ variable
8753  // is unavailable. Apple's documentation (man environ) recommends using
8754  // _NSGetEnviron() instead.
8755  return *_NSGetEnviron();
8756 }
8757 # else
8758 // Some POSIX platforms expect you to declare environ. extern "C" makes
8759 // it reside in the global namespace.
8760 extern "C" char** environ;
8761 inline char** GetEnviron() { return environ; }
8762 # endif // GTEST_OS_MAC
8763 
8764 # if !GTEST_OS_QNX
8765 // The main function for a threadsafe-style death test child process.
8766 // This function is called in a clone()-ed process and thus must avoid
8767 // any potentially unsafe operations like malloc or libc functions.
8768 static int ExecDeathTestChildMain(void* child_arg) {
8769  ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
8770  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
8771 
8772  // We need to execute the test program in the same environment where
8773  // it was originally invoked. Therefore we change to the original
8774  // working directory first.
8775  const char* const original_dir =
8777  // We can safely call chdir() as it's a direct system call.
8778  if (chdir(original_dir) != 0) {
8779  DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
8780  GetLastErrnoDescription());
8781  return EXIT_FAILURE;
8782  }
8783 
8784  // We can safely call execve() as it's a direct system call. We
8785  // cannot use execvp() as it's a libc function and thus potentially
8786  // unsafe. Since execve() doesn't search the PATH, the user must
8787  // invoke the test program via a valid path that contains at least
8788  // one path separator.
8789  execve(args->argv[0], args->argv, GetEnviron());
8790  DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
8791  original_dir + " failed: " +
8792  GetLastErrnoDescription());
8793  return EXIT_FAILURE;
8794 }
8795 # endif // !GTEST_OS_QNX
8796 
8797 # if GTEST_HAS_CLONE
8798 // Two utility routines that together determine the direction the stack
8799 // grows.
8800 // This could be accomplished more elegantly by a single recursive
8801 // function, but we want to guard against the unlikely possibility of
8802 // a smart compiler optimizing the recursion away.
8803 //
8804 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
8805 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
8806 // correct answer.
8807 static void StackLowerThanAddress(const void* ptr,
8808  bool* result) GTEST_NO_INLINE_;
8809 static void StackLowerThanAddress(const void* ptr, bool* result) {
8810  int dummy;
8811  *result = (&dummy < ptr);
8812 }
8813 
8814 // Make sure AddressSanitizer does not tamper with the stack here.
8816 static bool StackGrowsDown() {
8817  int dummy;
8818  bool result;
8819  StackLowerThanAddress(&dummy, &result);
8820  return result;
8821 }
8822 # endif // GTEST_HAS_CLONE
8823 
8824 // Spawns a child process with the same executable as the current process in
8825 // a thread-safe manner and instructs it to run the death test. The
8826 // implementation uses fork(2) + exec. On systems where clone(2) is
8827 // available, it is used instead, being slightly more thread-safe. On QNX,
8828 // fork supports only single-threaded environments, so this function uses
8829 // spawn(2) there instead. The function dies with an error message if
8830 // anything goes wrong.
8831 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
8832  ExecDeathTestArgs args = { argv, close_fd };
8833  pid_t child_pid = -1;
8834 
8835 # if GTEST_OS_QNX
8836  // Obtains the current directory and sets it to be closed in the child
8837  // process.
8838  const int cwd_fd = open(".", O_RDONLY);
8839  GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
8840  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
8841  // We need to execute the test program in the same environment where
8842  // it was originally invoked. Therefore we change to the original
8843  // working directory first.
8844  const char* const original_dir =
8846  // We can safely call chdir() as it's a direct system call.
8847  if (chdir(original_dir) != 0) {
8848  DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
8849  GetLastErrnoDescription());
8850  return EXIT_FAILURE;
8851  }
8852 
8853  int fd_flags;
8854  // Set close_fd to be closed after spawn.
8855  GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
8856  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
8857  fd_flags | FD_CLOEXEC));
8858  struct inheritance inherit = {0};
8859  // spawn is a system call.
8860  child_pid =
8861  spawn(args.argv[0], 0, nullptr, &inherit, args.argv, GetEnviron());
8862  // Restores the current working directory.
8863  GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
8864  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
8865 
8866 # else // GTEST_OS_QNX
8867 # if GTEST_OS_LINUX
8868  // When a SIGPROF signal is received while fork() or clone() are executing,
8869  // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
8870  // it after the call to fork()/clone() is complete.
8871  struct sigaction saved_sigprof_action;
8872  struct sigaction ignore_sigprof_action;
8873  memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
8874  sigemptyset(&ignore_sigprof_action.sa_mask);
8875  ignore_sigprof_action.sa_handler = SIG_IGN;
8876  GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
8877  SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
8878 # endif // GTEST_OS_LINUX
8879 
8880 # if GTEST_HAS_CLONE
8881  const bool use_fork = GTEST_FLAG(death_test_use_fork);
8882 
8883  if (!use_fork) {
8884  static const bool stack_grows_down = StackGrowsDown();
8885  const size_t stack_size = getpagesize();
8886  // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
8887  void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE,
8888  MAP_ANON | MAP_PRIVATE, -1, 0);
8889  GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
8890 
8891  // Maximum stack alignment in bytes: For a downward-growing stack, this
8892  // amount is subtracted from size of the stack space to get an address
8893  // that is within the stack space and is aligned on all systems we care
8894  // about. As far as I know there is no ABI with stack alignment greater
8895  // than 64. We assume stack and stack_size already have alignment of
8896  // kMaxStackAlignment.
8897  const size_t kMaxStackAlignment = 64;
8898  void* const stack_top =
8899  static_cast<char*>(stack) +
8900  (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
8901  GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
8902  reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
8903 
8904  child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
8905 
8906  GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
8907  }
8908 # else
8909  const bool use_fork = true;
8910 # endif // GTEST_HAS_CLONE
8911 
8912  if (use_fork && (child_pid = fork()) == 0) {
8913  ExecDeathTestChildMain(&args);
8914  _exit(0);
8915  }
8916 # endif // GTEST_OS_QNX
8917 # if GTEST_OS_LINUX
8918  GTEST_DEATH_TEST_CHECK_SYSCALL_(
8919  sigaction(SIGPROF, &saved_sigprof_action, nullptr));
8920 # endif // GTEST_OS_LINUX
8921 
8922  GTEST_DEATH_TEST_CHECK_(child_pid != -1);
8923  return child_pid;
8924 }
8925 
8926 // The AssumeRole process for a fork-and-exec death test. It re-executes the
8927 // main program from the beginning, setting the --gtest_filter
8928 // and --gtest_internal_run_death_test flags to cause only the current
8929 // death test to be re-run.
8930 DeathTest::TestRole ExecDeathTest::AssumeRole() {
8931  const UnitTestImpl* const impl = GetUnitTestImpl();
8932  const InternalRunDeathTestFlag* const flag =
8933  impl->internal_run_death_test_flag();
8934  const TestInfo* const info = impl->current_test_info();
8935  const int death_test_index = info->result()->death_test_count();
8936 
8937  if (flag != nullptr) {
8938  set_write_fd(flag->write_fd());
8939  return EXECUTE_TEST;
8940  }
8941 
8942  int pipe_fd[2];
8943  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
8944  // Clear the close-on-exec flag on the write end of the pipe, lest
8945  // it be closed when the child process does an exec:
8946  GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
8947 
8948  const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
8949  kFilterFlag + "=" + info->test_suite_name() +
8950  "." + info->name();
8951  const std::string internal_flag =
8952  std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
8953  + file_ + "|" + StreamableToString(line_) + "|"
8954  + StreamableToString(death_test_index) + "|"
8955  + StreamableToString(pipe_fd[1]);
8956  Arguments args;
8957  args.AddArguments(GetArgvsForDeathTestChildProcess());
8958  args.AddArgument(filter_flag.c_str());
8959  args.AddArgument(internal_flag.c_str());
8960 
8961  DeathTest::set_last_death_test_message("");
8962 
8963  CaptureStderr();
8964  // See the comment in NoExecDeathTest::AssumeRole for why the next line
8965  // is necessary.
8966  FlushInfoLog();
8967 
8968  const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
8969  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
8970  set_child_pid(child_pid);
8971  set_read_fd(pipe_fd[0]);
8972  set_spawned(true);
8973  return OVERSEE_TEST;
8974 }
8975 
8976 # endif // !GTEST_OS_WINDOWS
8977 
8978 // Creates a concrete DeathTest-derived class that depends on the
8979 // --gtest_death_test_style flag, and sets the pointer pointed to
8980 // by the "test" argument to its address. If the test should be
8981 // skipped, sets that pointer to NULL. Returns true, unless the
8982 // flag is set to an invalid value.
8983 bool DefaultDeathTestFactory::Create(const char* statement,
8984  Matcher<const std::string&> matcher,
8985  const char* file, int line,
8986  DeathTest** test) {
8987  UnitTestImpl* const impl = GetUnitTestImpl();
8988  const InternalRunDeathTestFlag* const flag =
8989  impl->internal_run_death_test_flag();
8990  const int death_test_index = impl->current_test_info()
8991  ->increment_death_test_count();
8992 
8993  if (flag != nullptr) {
8994  if (death_test_index > flag->index()) {
8995  DeathTest::set_last_death_test_message(
8996  "Death test count (" + StreamableToString(death_test_index)
8997  + ") somehow exceeded expected maximum ("
8998  + StreamableToString(flag->index()) + ")");
8999  return false;
9000  }
9001 
9002  if (!(flag->file() == file && flag->line() == line &&
9003  flag->index() == death_test_index)) {
9004  *test = nullptr;
9005  return true;
9006  }
9007  }
9008 
9009 # if GTEST_OS_WINDOWS
9010 
9011  if (GTEST_FLAG(death_test_style) == "threadsafe" ||
9012  GTEST_FLAG(death_test_style) == "fast") {
9013  *test = new WindowsDeathTest(statement, std::move(matcher), file, line);
9014  }
9015 
9016 # elif GTEST_OS_FUCHSIA
9017 
9018  if (GTEST_FLAG(death_test_style) == "threadsafe" ||
9019  GTEST_FLAG(death_test_style) == "fast") {
9020  *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);
9021  }
9022 
9023 # else
9024 
9025  if (GTEST_FLAG(death_test_style) == "threadsafe") {
9026  *test = new ExecDeathTest(statement, std::move(matcher), file, line);
9027  } else if (GTEST_FLAG(death_test_style) == "fast") {
9028  *test = new NoExecDeathTest(statement, std::move(matcher));
9029  }
9030 
9031 # endif // GTEST_OS_WINDOWS
9032 
9033  else { // NOLINT - this is more readable than unbalanced brackets inside #if.
9034  DeathTest::set_last_death_test_message(
9035  "Unknown death test style \"" + GTEST_FLAG(death_test_style)
9036  + "\" encountered");
9037  return false;
9038  }
9039 
9040  return true;
9041 }
9042 
9043 # if GTEST_OS_WINDOWS
9044 // Recreates the pipe and event handles from the provided parameters,
9045 // signals the event, and returns a file descriptor wrapped around the pipe
9046 // handle. This function is called in the child process only.
9047 static int GetStatusFileDescriptor(unsigned int parent_process_id,
9048  size_t write_handle_as_size_t,
9049  size_t event_handle_as_size_t) {
9050  AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
9051  FALSE, // Non-inheritable.
9052  parent_process_id));
9053  if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
9054  DeathTestAbort("Unable to open parent process " +
9055  StreamableToString(parent_process_id));
9056  }
9057 
9058  GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
9059 
9060  const HANDLE write_handle =
9061  reinterpret_cast<HANDLE>(write_handle_as_size_t);
9062  HANDLE dup_write_handle;
9063 
9064  // The newly initialized handle is accessible only in the parent
9065  // process. To obtain one accessible within the child, we need to use
9066  // DuplicateHandle.
9067  if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
9068  ::GetCurrentProcess(), &dup_write_handle,
9069  0x0, // Requested privileges ignored since
9070  // DUPLICATE_SAME_ACCESS is used.
9071  FALSE, // Request non-inheritable handler.
9072  DUPLICATE_SAME_ACCESS)) {
9073  DeathTestAbort("Unable to duplicate the pipe handle " +
9074  StreamableToString(write_handle_as_size_t) +
9075  " from the parent process " +
9076  StreamableToString(parent_process_id));
9077  }
9078 
9079  const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
9080  HANDLE dup_event_handle;
9081 
9082  if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
9083  ::GetCurrentProcess(), &dup_event_handle,
9084  0x0,
9085  FALSE,
9086  DUPLICATE_SAME_ACCESS)) {
9087  DeathTestAbort("Unable to duplicate the event handle " +
9088  StreamableToString(event_handle_as_size_t) +
9089  " from the parent process " +
9090  StreamableToString(parent_process_id));
9091  }
9092 
9093  const int write_fd =
9094  ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
9095  if (write_fd == -1) {
9096  DeathTestAbort("Unable to convert pipe handle " +
9097  StreamableToString(write_handle_as_size_t) +
9098  " to a file descriptor");
9099  }
9100 
9101  // Signals the parent that the write end of the pipe has been acquired
9102  // so the parent can release its own write end.
9103  ::SetEvent(dup_event_handle);
9104 
9105  return write_fd;
9106 }
9107 # endif // GTEST_OS_WINDOWS
9108 
9109 // Returns a newly created InternalRunDeathTestFlag object with fields
9110 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
9111 // the flag is specified; otherwise returns NULL.
9112 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
9113  if (GTEST_FLAG(internal_run_death_test) == "") return nullptr;
9114 
9115  // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
9116  // can use it here.
9117  int line = -1;
9118  int index = -1;
9119  ::std::vector< ::std::string> fields;
9120  SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
9121  int write_fd = -1;
9122 
9123 # if GTEST_OS_WINDOWS
9124 
9125  unsigned int parent_process_id = 0;
9126  size_t write_handle_as_size_t = 0;
9127  size_t event_handle_as_size_t = 0;
9128 
9129  if (fields.size() != 6
9130  || !ParseNaturalNumber(fields[1], &line)
9131  || !ParseNaturalNumber(fields[2], &index)
9132  || !ParseNaturalNumber(fields[3], &parent_process_id)
9133  || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
9134  || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
9135  DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
9136  GTEST_FLAG(internal_run_death_test));
9137  }
9138  write_fd = GetStatusFileDescriptor(parent_process_id,
9139  write_handle_as_size_t,
9140  event_handle_as_size_t);
9141 
9142 # elif GTEST_OS_FUCHSIA
9143 
9144  if (fields.size() != 3
9145  || !ParseNaturalNumber(fields[1], &line)
9146  || !ParseNaturalNumber(fields[2], &index)) {
9147  DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9148  + GTEST_FLAG(internal_run_death_test));
9149  }
9150 
9151 # else
9152 
9153  if (fields.size() != 4
9154  || !ParseNaturalNumber(fields[1], &line)
9155  || !ParseNaturalNumber(fields[2], &index)
9156  || !ParseNaturalNumber(fields[3], &write_fd)) {
9157  DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
9158  + GTEST_FLAG(internal_run_death_test));
9159  }
9160 
9161 # endif // GTEST_OS_WINDOWS
9162 
9163  return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
9164 }
9165 
9166 } // namespace internal
9167 
9168 #endif // GTEST_HAS_DEATH_TEST
9169 
9170 } // namespace testing
9171 // Copyright 2008, Google Inc.
9172 // All rights reserved.
9173 //
9174 // Redistribution and use in source and binary forms, with or without
9175 // modification, are permitted provided that the following conditions are
9176 // met:
9177 //
9178 // * Redistributions of source code must retain the above copyright
9179 // notice, this list of conditions and the following disclaimer.
9180 // * Redistributions in binary form must reproduce the above
9181 // copyright notice, this list of conditions and the following disclaimer
9182 // in the documentation and/or other materials provided with the
9183 // distribution.
9184 // * Neither the name of Google Inc. nor the names of its
9185 // contributors may be used to endorse or promote products derived from
9186 // this software without specific prior written permission.
9187 //
9188 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9189 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9190 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9191 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9192 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9193 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9194 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9195 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9196 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9197 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9198 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9199 
9200 
9201 #include <stdlib.h>
9202 
9203 #if GTEST_OS_WINDOWS_MOBILE
9204 # include <windows.h>
9205 #elif GTEST_OS_WINDOWS
9206 # include <direct.h>
9207 # include <io.h>
9208 #else
9209 # include <limits.h>
9210 # include <climits> // Some Linux distributions define PATH_MAX here.
9211 #endif // GTEST_OS_WINDOWS_MOBILE
9212 
9213 
9214 #if GTEST_OS_WINDOWS
9215 # define GTEST_PATH_MAX_ _MAX_PATH
9216 #elif defined(PATH_MAX)
9217 # define GTEST_PATH_MAX_ PATH_MAX
9218 #elif defined(_XOPEN_PATH_MAX)
9219 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
9220 #else
9221 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
9222 #endif // GTEST_OS_WINDOWS
9223 
9224 namespace testing {
9225 namespace internal {
9226 
9227 #if GTEST_OS_WINDOWS
9228 // On Windows, '\\' is the standard path separator, but many tools and the
9229 // Windows API also accept '/' as an alternate path separator. Unless otherwise
9230 // noted, a file path can contain either kind of path separators, or a mixture
9231 // of them.
9232 const char kPathSeparator = '\\';
9233 const char kAlternatePathSeparator = '/';
9234 const char kAlternatePathSeparatorString[] = "/";
9235 # if GTEST_OS_WINDOWS_MOBILE
9236 // Windows CE doesn't have a current directory. You should not use
9237 // the current directory in tests on Windows CE, but this at least
9238 // provides a reasonable fallback.
9239 const char kCurrentDirectoryString[] = "\\";
9240 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
9241 const DWORD kInvalidFileAttributes = 0xffffffff;
9242 # else
9243 const char kCurrentDirectoryString[] = ".\\";
9244 # endif // GTEST_OS_WINDOWS_MOBILE
9245 #else
9246 const char kPathSeparator = '/';
9247 const char kCurrentDirectoryString[] = "./";
9248 #endif // GTEST_OS_WINDOWS
9249 
9250 // Returns whether the given character is a valid path separator.
9251 static bool IsPathSeparator(char c) {
9252 #if GTEST_HAS_ALT_PATH_SEP_
9253  return (c == kPathSeparator) || (c == kAlternatePathSeparator);
9254 #else
9255  return c == kPathSeparator;
9256 #endif
9257 }
9258 
9259 // Returns the current working directory, or "" if unsuccessful.
9260 FilePath FilePath::GetCurrentDir() {
9261 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
9262  // Windows CE doesn't have a current directory, so we just return
9263  // something reasonable.
9264  return FilePath(kCurrentDirectoryString);
9265 #elif GTEST_OS_WINDOWS
9266  char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
9267  return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
9268 #else
9269  char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
9270  char* result = getcwd(cwd, sizeof(cwd));
9271 # if GTEST_OS_NACL
9272  // getcwd will likely fail in NaCl due to the sandbox, so return something
9273  // reasonable. The user may have provided a shim implementation for getcwd,
9274  // however, so fallback only when failure is detected.
9275  return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
9276 # endif // GTEST_OS_NACL
9277  return FilePath(result == nullptr ? "" : cwd);
9278 #endif // GTEST_OS_WINDOWS_MOBILE
9279 }
9280 
9281 // Returns a copy of the FilePath with the case-insensitive extension removed.
9282 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
9283 // FilePath("dir/file"). If a case-insensitive extension is not
9284 // found, returns a copy of the original FilePath.
9285 FilePath FilePath::RemoveExtension(const char* extension) const {
9286  const std::string dot_extension = std::string(".") + extension;
9287  if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
9288  return FilePath(pathname_.substr(
9289  0, pathname_.length() - dot_extension.length()));
9290  }
9291  return *this;
9292 }
9293 
9294 // Returns a pointer to the last occurrence of a valid path separator in
9295 // the FilePath. On Windows, for example, both '/' and '\' are valid path
9296 // separators. Returns NULL if no path separator was found.
9297 const char* FilePath::FindLastPathSeparator() const {
9298  const char* const last_sep = strrchr(c_str(), kPathSeparator);
9299 #if GTEST_HAS_ALT_PATH_SEP_
9300  const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
9301  // Comparing two pointers of which only one is NULL is undefined.
9302  if (last_alt_sep != nullptr &&
9303  (last_sep == nullptr || last_alt_sep > last_sep)) {
9304  return last_alt_sep;
9305  }
9306 #endif
9307  return last_sep;
9308 }
9309 
9310 // Returns a copy of the FilePath with the directory part removed.
9311 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
9312 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
9313 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
9314 // returns an empty FilePath ("").
9315 // On Windows platform, '\' is the path separator, otherwise it is '/'.
9316 FilePath FilePath::RemoveDirectoryName() const {
9317  const char* const last_sep = FindLastPathSeparator();
9318  return last_sep ? FilePath(last_sep + 1) : *this;
9319 }
9320 
9321 // RemoveFileName returns the directory path with the filename removed.
9322 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
9323 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
9324 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
9325 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
9326 // On Windows platform, '\' is the path separator, otherwise it is '/'.
9327 FilePath FilePath::RemoveFileName() const {
9328  const char* const last_sep = FindLastPathSeparator();
9329  std::string dir;
9330  if (last_sep) {
9331  dir = std::string(c_str(), last_sep + 1 - c_str());
9332  } else {
9334  }
9335  return FilePath(dir);
9336 }
9337 
9338 // Helper functions for naming files in a directory for xml output.
9339 
9340 // Given directory = "dir", base_name = "test", number = 0,
9341 // extension = "xml", returns "dir/test.xml". If number is greater
9342 // than zero (e.g., 12), returns "dir/test_12.xml".
9343 // On Windows platform, uses \ as the separator rather than /.
9344 FilePath FilePath::MakeFileName(const FilePath& directory,
9345  const FilePath& base_name,
9346  int number,
9347  const char* extension) {
9348  std::string file;
9349  if (number == 0) {
9350  file = base_name.string() + "." + extension;
9351  } else {
9352  file = base_name.string() + "_" + StreamableToString(number)
9353  + "." + extension;
9354  }
9355  return ConcatPaths(directory, FilePath(file));
9356 }
9357 
9358 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
9359 // On Windows, uses \ as the separator rather than /.
9360 FilePath FilePath::ConcatPaths(const FilePath& directory,
9361  const FilePath& relative_path) {
9362  if (directory.IsEmpty())
9363  return relative_path;
9364  const FilePath dir(directory.RemoveTrailingPathSeparator());
9365  return FilePath(dir.string() + kPathSeparator + relative_path.string());
9366 }
9367 
9368 // Returns true if pathname describes something findable in the file-system,
9369 // either a file, directory, or whatever.
9370 bool FilePath::FileOrDirectoryExists() const {
9371 #if GTEST_OS_WINDOWS_MOBILE
9372  LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
9373  const DWORD attributes = GetFileAttributes(unicode);
9374  delete [] unicode;
9375  return attributes != kInvalidFileAttributes;
9376 #else
9377  posix::StatStruct file_stat;
9378  return posix::Stat(pathname_.c_str(), &file_stat) == 0;
9379 #endif // GTEST_OS_WINDOWS_MOBILE
9380 }
9381 
9382 // Returns true if pathname describes a directory in the file-system
9383 // that exists.
9384 bool FilePath::DirectoryExists() const {
9385  bool result = false;
9386 #if GTEST_OS_WINDOWS
9387  // Don't strip off trailing separator if path is a root directory on
9388  // Windows (like "C:\\").
9389  const FilePath& path(IsRootDirectory() ? *this :
9390  RemoveTrailingPathSeparator());
9391 #else
9392  const FilePath& path(*this);
9393 #endif
9394 
9395 #if GTEST_OS_WINDOWS_MOBILE
9396  LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
9397  const DWORD attributes = GetFileAttributes(unicode);
9398  delete [] unicode;
9399  if ((attributes != kInvalidFileAttributes) &&
9400  (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
9401  result = true;
9402  }
9403 #else
9404  posix::StatStruct file_stat;
9405  result = posix::Stat(path.c_str(), &file_stat) == 0 &&
9406  posix::IsDir(file_stat);
9407 #endif // GTEST_OS_WINDOWS_MOBILE
9408 
9409  return result;
9410 }
9411 
9412 // Returns true if pathname describes a root directory. (Windows has one
9413 // root directory per disk drive.)
9414 bool FilePath::IsRootDirectory() const {
9415 #if GTEST_OS_WINDOWS
9416  return pathname_.length() == 3 && IsAbsolutePath();
9417 #else
9418  return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
9419 #endif
9420 }
9421 
9422 // Returns true if pathname describes an absolute path.
9423 bool FilePath::IsAbsolutePath() const {
9424  const char* const name = pathname_.c_str();
9425 #if GTEST_OS_WINDOWS
9426  return pathname_.length() >= 3 &&
9427  ((name[0] >= 'a' && name[0] <= 'z') ||
9428  (name[0] >= 'A' && name[0] <= 'Z')) &&
9429  name[1] == ':' &&
9430  IsPathSeparator(name[2]);
9431 #else
9432  return IsPathSeparator(name[0]);
9433 #endif
9434 }
9435 
9436 // Returns a pathname for a file that does not currently exist. The pathname
9437 // will be directory/base_name.extension or
9438 // directory/base_name_<number>.extension if directory/base_name.extension
9439 // already exists. The number will be incremented until a pathname is found
9440 // that does not already exist.
9441 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
9442 // There could be a race condition if two or more processes are calling this
9443 // function at the same time -- they could both pick the same filename.
9444 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
9445  const FilePath& base_name,
9446  const char* extension) {
9447  FilePath full_pathname;
9448  int number = 0;
9449  do {
9450  full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
9451  } while (full_pathname.FileOrDirectoryExists());
9452  return full_pathname;
9453 }
9454 
9455 // Returns true if FilePath ends with a path separator, which indicates that
9456 // it is intended to represent a directory. Returns false otherwise.
9457 // This does NOT check that a directory (or file) actually exists.
9458 bool FilePath::IsDirectory() const {
9459  return !pathname_.empty() &&
9460  IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
9461 }
9462 
9463 // Create directories so that path exists. Returns true if successful or if
9464 // the directories already exist; returns false if unable to create directories
9465 // for any reason.
9466 bool FilePath::CreateDirectoriesRecursively() const {
9467  if (!this->IsDirectory()) {
9468  return false;
9469  }
9470 
9471  if (pathname_.length() == 0 || this->DirectoryExists()) {
9472  return true;
9473  }
9474 
9475  const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
9476  return parent.CreateDirectoriesRecursively() && this->CreateFolder();
9477 }
9478 
9479 // Create the directory so that path exists. Returns true if successful or
9480 // if the directory already exists; returns false if unable to create the
9481 // directory for any reason, including if the parent directory does not
9482 // exist. Not named "CreateDirectory" because that's a macro on Windows.
9483 bool FilePath::CreateFolder() const {
9484 #if GTEST_OS_WINDOWS_MOBILE
9485  FilePath removed_sep(this->RemoveTrailingPathSeparator());
9486  LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
9487  int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
9488  delete [] unicode;
9489 #elif GTEST_OS_WINDOWS
9490  int result = _mkdir(pathname_.c_str());
9491 #else
9492  int result = mkdir(pathname_.c_str(), 0777);
9493 #endif // GTEST_OS_WINDOWS_MOBILE
9494 
9495  if (result == -1) {
9496  return this->DirectoryExists(); // An error is OK if the directory exists.
9497  }
9498  return true; // No error.
9499 }
9500 
9501 // If input name has a trailing separator character, remove it and return the
9502 // name, otherwise return the name string unmodified.
9503 // On Windows platform, uses \ as the separator, other platforms use /.
9504 FilePath FilePath::RemoveTrailingPathSeparator() const {
9505  return IsDirectory()
9506  ? FilePath(pathname_.substr(0, pathname_.length() - 1))
9507  : *this;
9508 }
9509 
9510 // Removes any redundant separators that might be in the pathname.
9511 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
9512 // redundancies that might be in a pathname involving "." or "..".
9513 void FilePath::Normalize() {
9514  if (pathname_.c_str() == nullptr) {
9515  pathname_ = "";
9516  return;
9517  }
9518  const char* src = pathname_.c_str();
9519  char* const dest = new char[pathname_.length() + 1];
9520  char* dest_ptr = dest;
9521  memset(dest_ptr, 0, pathname_.length() + 1);
9522 
9523  while (*src != '\0') {
9524  *dest_ptr = *src;
9525  if (!IsPathSeparator(*src)) {
9526  src++;
9527  } else {
9528 #if GTEST_HAS_ALT_PATH_SEP_
9529  if (*dest_ptr == kAlternatePathSeparator) {
9530  *dest_ptr = kPathSeparator;
9531  }
9532 #endif
9533  while (IsPathSeparator(*src))
9534  src++;
9535  }
9536  dest_ptr++;
9537  }
9538  *dest_ptr = '\0';
9539  pathname_ = dest;
9540  delete[] dest;
9541 }
9542 
9543 } // namespace internal
9544 } // namespace testing
9545 // Copyright 2007, Google Inc.
9546 // All rights reserved.
9547 //
9548 // Redistribution and use in source and binary forms, with or without
9549 // modification, are permitted provided that the following conditions are
9550 // met:
9551 //
9552 // * Redistributions of source code must retain the above copyright
9553 // notice, this list of conditions and the following disclaimer.
9554 // * Redistributions in binary form must reproduce the above
9555 // copyright notice, this list of conditions and the following disclaimer
9556 // in the documentation and/or other materials provided with the
9557 // distribution.
9558 // * Neither the name of Google Inc. nor the names of its
9559 // contributors may be used to endorse or promote products derived from
9560 // this software without specific prior written permission.
9561 //
9562 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9563 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9564 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9565 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9566 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9567 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9568 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9569 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9570 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9571 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9572 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9573 
9574 // The Google C++ Testing and Mocking Framework (Google Test)
9575 //
9576 // This file implements just enough of the matcher interface to allow
9577 // EXPECT_DEATH and friends to accept a matcher argument.
9578 
9579 
9580 #include <string>
9581 
9582 namespace testing {
9583 
9584 // Constructs a matcher that matches a const std::string& whose value is
9585 // equal to s.
9586 Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); }
9587 
9588 #if GTEST_HAS_GLOBAL_STRING
9589 // Constructs a matcher that matches a const std::string& whose value is
9590 // equal to s.
9591 Matcher<const std::string&>::Matcher(const ::string& s) {
9592  *this = Eq(static_cast<std::string>(s));
9593 }
9594 #endif // GTEST_HAS_GLOBAL_STRING
9595 
9596 // Constructs a matcher that matches a const std::string& whose value is
9597 // equal to s.
9598 Matcher<const std::string&>::Matcher(const char* s) {
9599  *this = Eq(std::string(s));
9600 }
9601 
9602 // Constructs a matcher that matches a std::string whose value is equal to
9603 // s.
9604 Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }
9605 
9606 #if GTEST_HAS_GLOBAL_STRING
9607 // Constructs a matcher that matches a std::string whose value is equal to
9608 // s.
9609 Matcher<std::string>::Matcher(const ::string& s) {
9610  *this = Eq(static_cast<std::string>(s));
9611 }
9612 #endif // GTEST_HAS_GLOBAL_STRING
9613 
9614 // Constructs a matcher that matches a std::string whose value is equal to
9615 // s.
9616 Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }
9617 
9618 #if GTEST_HAS_GLOBAL_STRING
9619 // Constructs a matcher that matches a const ::string& whose value is
9620 // equal to s.
9621 Matcher<const ::string&>::Matcher(const std::string& s) {
9622  *this = Eq(static_cast<::string>(s));
9623 }
9624 
9625 // Constructs a matcher that matches a const ::string& whose value is
9626 // equal to s.
9627 Matcher<const ::string&>::Matcher(const ::string& s) { *this = Eq(s); }
9628 
9629 // Constructs a matcher that matches a const ::string& whose value is
9630 // equal to s.
9631 Matcher<const ::string&>::Matcher(const char* s) { *this = Eq(::string(s)); }
9632 
9633 // Constructs a matcher that matches a ::string whose value is equal to s.
9634 Matcher<::string>::Matcher(const std::string& s) {
9635  *this = Eq(static_cast<::string>(s));
9636 }
9637 
9638 // Constructs a matcher that matches a ::string whose value is equal to s.
9639 Matcher<::string>::Matcher(const ::string& s) { *this = Eq(s); }
9640 
9641 // Constructs a matcher that matches a string whose value is equal to s.
9642 Matcher<::string>::Matcher(const char* s) { *this = Eq(::string(s)); }
9643 #endif // GTEST_HAS_GLOBAL_STRING
9644 
9645 #if GTEST_HAS_ABSL
9646 // Constructs a matcher that matches a const absl::string_view& whose value is
9647 // equal to s.
9648 Matcher<const absl::string_view&>::Matcher(const std::string& s) {
9649  *this = Eq(s);
9650 }
9651 
9652 #if GTEST_HAS_GLOBAL_STRING
9653 // Constructs a matcher that matches a const absl::string_view& whose value is
9654 // equal to s.
9655 Matcher<const absl::string_view&>::Matcher(const ::string& s) { *this = Eq(s); }
9656 #endif // GTEST_HAS_GLOBAL_STRING
9657 
9658 // Constructs a matcher that matches a const absl::string_view& whose value is
9659 // equal to s.
9660 Matcher<const absl::string_view&>::Matcher(const char* s) {
9661  *this = Eq(std::string(s));
9662 }
9663 
9664 // Constructs a matcher that matches a const absl::string_view& whose value is
9665 // equal to s.
9666 Matcher<const absl::string_view&>::Matcher(absl::string_view s) {
9667  *this = Eq(std::string(s));
9668 }
9669 
9670 // Constructs a matcher that matches a absl::string_view whose value is equal to
9671 // s.
9672 Matcher<absl::string_view>::Matcher(const std::string& s) { *this = Eq(s); }
9673 
9674 #if GTEST_HAS_GLOBAL_STRING
9675 // Constructs a matcher that matches a absl::string_view whose value is equal to
9676 // s.
9677 Matcher<absl::string_view>::Matcher(const ::string& s) { *this = Eq(s); }
9678 #endif // GTEST_HAS_GLOBAL_STRING
9679 
9680 // Constructs a matcher that matches a absl::string_view whose value is equal to
9681 // s.
9682 Matcher<absl::string_view>::Matcher(const char* s) {
9683  *this = Eq(std::string(s));
9684 }
9685 
9686 // Constructs a matcher that matches a absl::string_view whose value is equal to
9687 // s.
9688 Matcher<absl::string_view>::Matcher(absl::string_view s) {
9689  *this = Eq(std::string(s));
9690 }
9691 #endif // GTEST_HAS_ABSL
9692 
9693 } // namespace testing
9694 // Copyright 2008, Google Inc.
9695 // All rights reserved.
9696 //
9697 // Redistribution and use in source and binary forms, with or without
9698 // modification, are permitted provided that the following conditions are
9699 // met:
9700 //
9701 // * Redistributions of source code must retain the above copyright
9702 // notice, this list of conditions and the following disclaimer.
9703 // * Redistributions in binary form must reproduce the above
9704 // copyright notice, this list of conditions and the following disclaimer
9705 // in the documentation and/or other materials provided with the
9706 // distribution.
9707 // * Neither the name of Google Inc. nor the names of its
9708 // contributors may be used to endorse or promote products derived from
9709 // this software without specific prior written permission.
9710 //
9711 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9712 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9713 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9714 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9715 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9716 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9717 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9718 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9719 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9720 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9721 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9722 
9723 
9724 
9725 #include <limits.h>
9726 #include <stdio.h>
9727 #include <stdlib.h>
9728 #include <string.h>
9729 #include <fstream>
9730 #include <memory>
9731 
9732 #if GTEST_OS_WINDOWS
9733 # include <windows.h>
9734 # include <io.h>
9735 # include <sys/stat.h>
9736 # include <map> // Used in ThreadLocal.
9737 # ifdef _MSC_VER
9738 # include <crtdbg.h>
9739 # endif // _MSC_VER
9740 #else
9741 # include <unistd.h>
9742 #endif // GTEST_OS_WINDOWS
9743 
9744 #if GTEST_OS_MAC
9745 # include <mach/mach_init.h>
9746 # include <mach/task.h>
9747 # include <mach/vm_map.h>
9748 #endif // GTEST_OS_MAC
9749 
9750 #if GTEST_OS_QNX
9751 # include <devctl.h>
9752 # include <fcntl.h>
9753 # include <sys/procfs.h>
9754 #endif // GTEST_OS_QNX
9755 
9756 #if GTEST_OS_AIX
9757 # include <procinfo.h>
9758 # include <sys/types.h>
9759 #endif // GTEST_OS_AIX
9760 
9761 #if GTEST_OS_FUCHSIA
9762 # include <zircon/process.h>
9763 # include <zircon/syscalls.h>
9764 #endif // GTEST_OS_FUCHSIA
9765 
9766 
9767 namespace testing {
9768 namespace internal {
9769 
9770 #if defined(_MSC_VER) || defined(__BORLANDC__)
9771 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
9772 const int kStdOutFileno = 1;
9773 const int kStdErrFileno = 2;
9774 #else
9775 const int kStdOutFileno = STDOUT_FILENO;
9776 const int kStdErrFileno = STDERR_FILENO;
9777 #endif // _MSC_VER
9778 
9779 #if GTEST_OS_LINUX
9780 
9781 namespace {
9782 template <typename T>
9783 T ReadProcFileField(const std::string& filename, int field) {
9784  std::string dummy;
9785  std::ifstream file(filename.c_str());
9786  while (field-- > 0) {
9787  file >> dummy;
9788  }
9789  T output = 0;
9790  file >> output;
9791  return output;
9792 }
9793 } // namespace
9794 
9795 // Returns the number of active threads, or 0 when there is an error.
9796 size_t GetThreadCount() {
9797  const std::string filename =
9798  (Message() << "/proc/" << getpid() << "/stat").GetString();
9799  return ReadProcFileField<int>(filename, 19);
9800 }
9801 
9802 #elif GTEST_OS_MAC
9803 
9804 size_t GetThreadCount() {
9805  const task_t task = mach_task_self();
9806  mach_msg_type_number_t thread_count;
9807  thread_act_array_t thread_list;
9808  const kern_return_t status = task_threads(task, &thread_list, &thread_count);
9809  if (status == KERN_SUCCESS) {
9810  // task_threads allocates resources in thread_list and we need to free them
9811  // to avoid leaks.
9812  vm_deallocate(task,
9813  reinterpret_cast<vm_address_t>(thread_list),
9814  sizeof(thread_t) * thread_count);
9815  return static_cast<size_t>(thread_count);
9816  } else {
9817  return 0;
9818  }
9819 }
9820 
9821 #elif GTEST_OS_QNX
9822 
9823 // Returns the number of threads running in the process, or 0 to indicate that
9824 // we cannot detect it.
9825 size_t GetThreadCount() {
9826  const int fd = open("/proc/self/as", O_RDONLY);
9827  if (fd < 0) {
9828  return 0;
9829  }
9830  procfs_info process_info;
9831  const int status =
9832  devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);
9833  close(fd);
9834  if (status == EOK) {
9835  return static_cast<size_t>(process_info.num_threads);
9836  } else {
9837  return 0;
9838  }
9839 }
9840 
9841 #elif GTEST_OS_AIX
9842 
9843 size_t GetThreadCount() {
9844  struct procentry64 entry;
9845  pid_t pid = getpid();
9846  int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);
9847  if (status == 1) {
9848  return entry.pi_thcount;
9849  } else {
9850  return 0;
9851  }
9852 }
9853 
9854 #elif GTEST_OS_FUCHSIA
9855 
9856 size_t GetThreadCount() {
9857  int dummy_buffer;
9858  size_t avail;
9859  zx_status_t status = zx_object_get_info(
9860  zx_process_self(),
9861  ZX_INFO_PROCESS_THREADS,
9862  &dummy_buffer,
9863  0,
9864  nullptr,
9865  &avail);
9866  if (status == ZX_OK) {
9867  return avail;
9868  } else {
9869  return 0;
9870  }
9871 }
9872 
9873 #else
9874 
9875 size_t GetThreadCount() {
9876  // There's no portable way to detect the number of threads, so we just
9877  // return 0 to indicate that we cannot detect it.
9878  return 0;
9879 }
9880 
9881 #endif // GTEST_OS_LINUX
9882 
9883 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
9884 
9885 void SleepMilliseconds(int n) {
9886  ::Sleep(n);
9887 }
9888 
9889 AutoHandle::AutoHandle()
9890  : handle_(INVALID_HANDLE_VALUE) {}
9891 
9892 AutoHandle::AutoHandle(Handle handle)
9893  : handle_(handle) {}
9894 
9895 AutoHandle::~AutoHandle() {
9896  Reset();
9897 }
9898 
9899 AutoHandle::Handle AutoHandle::Get() const {
9900  return handle_;
9901 }
9902 
9903 void AutoHandle::Reset() {
9904  Reset(INVALID_HANDLE_VALUE);
9905 }
9906 
9907 void AutoHandle::Reset(HANDLE handle) {
9908  // Resetting with the same handle we already own is invalid.
9909  if (handle_ != handle) {
9910  if (IsCloseable()) {
9911  ::CloseHandle(handle_);
9912  }
9913  handle_ = handle;
9914  } else {
9915  GTEST_CHECK_(!IsCloseable())
9916  << "Resetting a valid handle to itself is likely a programmer error "
9917  "and thus not allowed.";
9918  }
9919 }
9920 
9921 bool AutoHandle::IsCloseable() const {
9922  // Different Windows APIs may use either of these values to represent an
9923  // invalid handle.
9924  return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
9925 }
9926 
9927 Notification::Notification()
9928  : event_(::CreateEvent(nullptr, // Default security attributes.
9929  TRUE, // Do not reset automatically.
9930  FALSE, // Initially unset.
9931  nullptr)) { // Anonymous event.
9932  GTEST_CHECK_(event_.Get() != nullptr);
9933 }
9934 
9935 void Notification::Notify() {
9936  GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
9937 }
9938 
9939 void Notification::WaitForNotification() {
9940  GTEST_CHECK_(
9941  ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
9942 }
9943 
9944 Mutex::Mutex()
9945  : owner_thread_id_(0),
9946  type_(kDynamic),
9947  critical_section_init_phase_(0),
9948  critical_section_(new CRITICAL_SECTION) {
9949  ::InitializeCriticalSection(critical_section_);
9950 }
9951 
9952 Mutex::~Mutex() {
9953  // Static mutexes are leaked intentionally. It is not thread-safe to try
9954  // to clean them up.
9955  if (type_ == kDynamic) {
9956  ::DeleteCriticalSection(critical_section_);
9957  delete critical_section_;
9958  critical_section_ = nullptr;
9959  }
9960 }
9961 
9962 void Mutex::Lock() {
9963  ThreadSafeLazyInit();
9964  ::EnterCriticalSection(critical_section_);
9965  owner_thread_id_ = ::GetCurrentThreadId();
9966 }
9967 
9968 void Mutex::Unlock() {
9969  ThreadSafeLazyInit();
9970  // We don't protect writing to owner_thread_id_ here, as it's the
9971  // caller's responsibility to ensure that the current thread holds the
9972  // mutex when this is called.
9973  owner_thread_id_ = 0;
9974  ::LeaveCriticalSection(critical_section_);
9975 }
9976 
9977 // Does nothing if the current thread holds the mutex. Otherwise, crashes
9978 // with high probability.
9979 void Mutex::AssertHeld() {
9980  ThreadSafeLazyInit();
9981  GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
9982  << "The current thread is not holding the mutex @" << this;
9983 }
9984 
9985 namespace {
9986 
9987 // Use the RAII idiom to flag mem allocs that are intentionally never
9988 // deallocated. The motivation is to silence the false positive mem leaks
9989 // that are reported by the debug version of MS's CRT which can only detect
9990 // if an alloc is missing a matching deallocation.
9991 // Example:
9992 // MemoryIsNotDeallocated memory_is_not_deallocated;
9993 // critical_section_ = new CRITICAL_SECTION;
9994 //
9995 class MemoryIsNotDeallocated
9996 {
9997  public:
9998  MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
9999 #ifdef _MSC_VER
10000  old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
10001  // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
10002  // doesn't report mem leak if there's no matching deallocation.
10003  _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
10004 #endif // _MSC_VER
10005  }
10006 
10007  ~MemoryIsNotDeallocated() {
10008 #ifdef _MSC_VER
10009  // Restore the original _CRTDBG_ALLOC_MEM_DF flag
10010  _CrtSetDbgFlag(old_crtdbg_flag_);
10011 #endif // _MSC_VER
10012  }
10013 
10014  private:
10015  int old_crtdbg_flag_;
10016 
10017  GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
10018 };
10019 
10020 } // namespace
10021 
10022 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
10023 void Mutex::ThreadSafeLazyInit() {
10024  // Dynamic mutexes are initialized in the constructor.
10025  if (type_ == kStatic) {
10026  switch (
10027  ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
10028  case 0:
10029  // If critical_section_init_phase_ was 0 before the exchange, we
10030  // are the first to test it and need to perform the initialization.
10031  owner_thread_id_ = 0;
10032  {
10033  // Use RAII to flag that following mem alloc is never deallocated.
10034  MemoryIsNotDeallocated memory_is_not_deallocated;
10035  critical_section_ = new CRITICAL_SECTION;
10036  }
10037  ::InitializeCriticalSection(critical_section_);
10038  // Updates the critical_section_init_phase_ to 2 to signal
10039  // initialization complete.
10040  GTEST_CHECK_(::InterlockedCompareExchange(
10041  &critical_section_init_phase_, 2L, 1L) ==
10042  1L);
10043  break;
10044  case 1:
10045  // Somebody else is already initializing the mutex; spin until they
10046  // are done.
10047  while (::InterlockedCompareExchange(&critical_section_init_phase_,
10048  2L,
10049  2L) != 2L) {
10050  // Possibly yields the rest of the thread's time slice to other
10051  // threads.
10052  ::Sleep(0);
10053  }
10054  break;
10055 
10056  case 2:
10057  break; // The mutex is already initialized and ready for use.
10058 
10059  default:
10060  GTEST_CHECK_(false)
10061  << "Unexpected value of critical_section_init_phase_ "
10062  << "while initializing a static mutex.";
10063  }
10064  }
10065 }
10066 
10067 namespace {
10068 
10069 class ThreadWithParamSupport : public ThreadWithParamBase {
10070  public:
10071  static HANDLE CreateThread(Runnable* runnable,
10072  Notification* thread_can_start) {
10073  ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
10074  DWORD thread_id;
10075  HANDLE thread_handle = ::CreateThread(
10076  nullptr, // Default security.
10077  0, // Default stack size.
10078  &ThreadWithParamSupport::ThreadMain,
10079  param, // Parameter to ThreadMainStatic
10080  0x0, // Default creation flags.
10081  &thread_id); // Need a valid pointer for the call to work under Win98.
10082  GTEST_CHECK_(thread_handle != nullptr)
10083  << "CreateThread failed with error " << ::GetLastError() << ".";
10084  if (thread_handle == nullptr) {
10085  delete param;
10086  }
10087  return thread_handle;
10088  }
10089 
10090  private:
10091  struct ThreadMainParam {
10092  ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
10093  : runnable_(runnable),
10094  thread_can_start_(thread_can_start) {
10095  }
10096  std::unique_ptr<Runnable> runnable_;
10097  // Does not own.
10098  Notification* thread_can_start_;
10099  };
10100 
10101  static DWORD WINAPI ThreadMain(void* ptr) {
10102  // Transfers ownership.
10103  std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
10104  if (param->thread_can_start_ != nullptr)
10105  param->thread_can_start_->WaitForNotification();
10106  param->runnable_->Run();
10107  return 0;
10108  }
10109 
10110  // Prohibit instantiation.
10111  ThreadWithParamSupport();
10112 
10113  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
10114 };
10115 
10116 } // namespace
10117 
10118 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
10119  Notification* thread_can_start)
10120  : thread_(ThreadWithParamSupport::CreateThread(runnable,
10121  thread_can_start)) {
10122 }
10123 
10124 ThreadWithParamBase::~ThreadWithParamBase() {
10125  Join();
10126 }
10127 
10128 void ThreadWithParamBase::Join() {
10129  GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
10130  << "Failed to join the thread with error " << ::GetLastError() << ".";
10131 }
10132 
10133 // Maps a thread to a set of ThreadIdToThreadLocals that have values
10134 // instantiated on that thread and notifies them when the thread exits. A
10135 // ThreadLocal instance is expected to persist until all threads it has
10136 // values on have terminated.
10137 class ThreadLocalRegistryImpl {
10138  public:
10139  // Registers thread_local_instance as having value on the current thread.
10140  // Returns a value that can be used to identify the thread from other threads.
10141  static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
10142  const ThreadLocalBase* thread_local_instance) {
10143  DWORD current_thread = ::GetCurrentThreadId();
10144  MutexLock lock(&mutex_);
10145  ThreadIdToThreadLocals* const thread_to_thread_locals =
10146  GetThreadLocalsMapLocked();
10147  ThreadIdToThreadLocals::iterator thread_local_pos =
10148  thread_to_thread_locals->find(current_thread);
10149  if (thread_local_pos == thread_to_thread_locals->end()) {
10150  thread_local_pos = thread_to_thread_locals->insert(
10151  std::make_pair(current_thread, ThreadLocalValues())).first;
10152  StartWatcherThreadFor(current_thread);
10153  }
10154  ThreadLocalValues& thread_local_values = thread_local_pos->second;
10155  ThreadLocalValues::iterator value_pos =
10156  thread_local_values.find(thread_local_instance);
10157  if (value_pos == thread_local_values.end()) {
10158  value_pos =
10159  thread_local_values
10160  .insert(std::make_pair(
10161  thread_local_instance,
10162  std::shared_ptr<ThreadLocalValueHolderBase>(
10163  thread_local_instance->NewValueForCurrentThread())))
10164  .first;
10165  }
10166  return value_pos->second.get();
10167  }
10168 
10169  static void OnThreadLocalDestroyed(
10170  const ThreadLocalBase* thread_local_instance) {
10171  std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
10172  // Clean up the ThreadLocalValues data structure while holding the lock, but
10173  // defer the destruction of the ThreadLocalValueHolderBases.
10174  {
10175  MutexLock lock(&mutex_);
10176  ThreadIdToThreadLocals* const thread_to_thread_locals =
10177  GetThreadLocalsMapLocked();
10178  for (ThreadIdToThreadLocals::iterator it =
10179  thread_to_thread_locals->begin();
10180  it != thread_to_thread_locals->end();
10181  ++it) {
10182  ThreadLocalValues& thread_local_values = it->second;
10183  ThreadLocalValues::iterator value_pos =
10184  thread_local_values.find(thread_local_instance);
10185  if (value_pos != thread_local_values.end()) {
10186  value_holders.push_back(value_pos->second);
10187  thread_local_values.erase(value_pos);
10188  // This 'if' can only be successful at most once, so theoretically we
10189  // could break out of the loop here, but we don't bother doing so.
10190  }
10191  }
10192  }
10193  // Outside the lock, let the destructor for 'value_holders' deallocate the
10194  // ThreadLocalValueHolderBases.
10195  }
10196 
10197  static void OnThreadExit(DWORD thread_id) {
10198  GTEST_CHECK_(thread_id != 0) << ::GetLastError();
10199  std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
10200  // Clean up the ThreadIdToThreadLocals data structure while holding the
10201  // lock, but defer the destruction of the ThreadLocalValueHolderBases.
10202  {
10203  MutexLock lock(&mutex_);
10204  ThreadIdToThreadLocals* const thread_to_thread_locals =
10205  GetThreadLocalsMapLocked();
10206  ThreadIdToThreadLocals::iterator thread_local_pos =
10207  thread_to_thread_locals->find(thread_id);
10208  if (thread_local_pos != thread_to_thread_locals->end()) {
10209  ThreadLocalValues& thread_local_values = thread_local_pos->second;
10210  for (ThreadLocalValues::iterator value_pos =
10211  thread_local_values.begin();
10212  value_pos != thread_local_values.end();
10213  ++value_pos) {
10214  value_holders.push_back(value_pos->second);
10215  }
10216  thread_to_thread_locals->erase(thread_local_pos);
10217  }
10218  }
10219  // Outside the lock, let the destructor for 'value_holders' deallocate the
10220  // ThreadLocalValueHolderBases.
10221  }
10222 
10223  private:
10224  // In a particular thread, maps a ThreadLocal object to its value.
10225  typedef std::map<const ThreadLocalBase*,
10226  std::shared_ptr<ThreadLocalValueHolderBase> >
10227  ThreadLocalValues;
10228  // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
10229  // thread's ID.
10230  typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
10231 
10232  // Holds the thread id and thread handle that we pass from
10233  // StartWatcherThreadFor to WatcherThreadFunc.
10234  typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
10235 
10236  static void StartWatcherThreadFor(DWORD thread_id) {
10237  // The returned handle will be kept in thread_map and closed by
10238  // watcher_thread in WatcherThreadFunc.
10239  HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
10240  FALSE,
10241  thread_id);
10242  GTEST_CHECK_(thread != nullptr);
10243  // We need to pass a valid thread ID pointer into CreateThread for it
10244  // to work correctly under Win98.
10245  DWORD watcher_thread_id;
10246  HANDLE watcher_thread = ::CreateThread(
10247  nullptr, // Default security.
10248  0, // Default stack size
10249  &ThreadLocalRegistryImpl::WatcherThreadFunc,
10250  reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
10251  CREATE_SUSPENDED, &watcher_thread_id);
10252  GTEST_CHECK_(watcher_thread != nullptr);
10253  // Give the watcher thread the same priority as ours to avoid being
10254  // blocked by it.
10255  ::SetThreadPriority(watcher_thread,
10256  ::GetThreadPriority(::GetCurrentThread()));
10257  ::ResumeThread(watcher_thread);
10258  ::CloseHandle(watcher_thread);
10259  }
10260 
10261  // Monitors exit from a given thread and notifies those
10262  // ThreadIdToThreadLocals about thread termination.
10263  static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
10264  const ThreadIdAndHandle* tah =
10265  reinterpret_cast<const ThreadIdAndHandle*>(param);
10266  GTEST_CHECK_(
10267  ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
10268  OnThreadExit(tah->first);
10269  ::CloseHandle(tah->second);
10270  delete tah;
10271  return 0;
10272  }
10273 
10274  // Returns map of thread local instances.
10275  static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
10276  mutex_.AssertHeld();
10277  MemoryIsNotDeallocated memory_is_not_deallocated;
10278  static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
10279  return map;
10280  }
10281 
10282  // Protects access to GetThreadLocalsMapLocked() and its return value.
10283  static Mutex mutex_;
10284  // Protects access to GetThreadMapLocked() and its return value.
10285  static Mutex thread_map_mutex_;
10286 };
10287 
10288 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
10289 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
10290 
10291 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
10292  const ThreadLocalBase* thread_local_instance) {
10293  return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
10294  thread_local_instance);
10295 }
10296 
10297 void ThreadLocalRegistry::OnThreadLocalDestroyed(
10298  const ThreadLocalBase* thread_local_instance) {
10299  ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
10300 }
10301 
10302 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
10303 
10304 #if GTEST_USES_POSIX_RE
10305 
10306 // Implements RE. Currently only needed for death tests.
10307 
10308 RE::~RE() {
10309  if (is_valid_) {
10310  // regfree'ing an invalid regex might crash because the content
10311  // of the regex is undefined. Since the regex's are essentially
10312  // the same, one cannot be valid (or invalid) without the other
10313  // being so too.
10314  regfree(&partial_regex_);
10315  regfree(&full_regex_);
10316  }
10317  free(const_cast<char*>(pattern_));
10318 }
10319 
10320 // Returns true iff regular expression re matches the entire str.
10321 bool RE::FullMatch(const char* str, const RE& re) {
10322  if (!re.is_valid_) return false;
10323 
10324  regmatch_t match;
10325  return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
10326 }
10327 
10328 // Returns true iff regular expression re matches a substring of str
10329 // (including str itself).
10330 bool RE::PartialMatch(const char* str, const RE& re) {
10331  if (!re.is_valid_) return false;
10332 
10333  regmatch_t match;
10334  return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
10335 }
10336 
10337 // Initializes an RE from its string representation.
10338 void RE::Init(const char* regex) {
10339  pattern_ = posix::StrDup(regex);
10340 
10341  // Reserves enough bytes to hold the regular expression used for a
10342  // full match.
10343  const size_t full_regex_len = strlen(regex) + 10;
10344  char* const full_pattern = new char[full_regex_len];
10345 
10346  snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
10347  is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
10348  // We want to call regcomp(&partial_regex_, ...) even if the
10349  // previous expression returns false. Otherwise partial_regex_ may
10350  // not be properly initialized can may cause trouble when it's
10351  // freed.
10352  //
10353  // Some implementation of POSIX regex (e.g. on at least some
10354  // versions of Cygwin) doesn't accept the empty string as a valid
10355  // regex. We change it to an equivalent form "()" to be safe.
10356  if (is_valid_) {
10357  const char* const partial_regex = (*regex == '\0') ? "()" : regex;
10358  is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
10359  }
10360  EXPECT_TRUE(is_valid_)
10361  << "Regular expression \"" << regex
10362  << "\" is not a valid POSIX Extended regular expression.";
10363 
10364  delete[] full_pattern;
10365 }
10366 
10367 #elif GTEST_USES_SIMPLE_RE
10368 
10369 // Returns true iff ch appears anywhere in str (excluding the
10370 // terminating '\0' character).
10371 bool IsInSet(char ch, const char* str) {
10372  return ch != '\0' && strchr(str, ch) != nullptr;
10373 }
10374 
10375 // Returns true iff ch belongs to the given classification. Unlike
10376 // similar functions in <ctype.h>, these aren't affected by the
10377 // current locale.
10378 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
10379 bool IsAsciiPunct(char ch) {
10380  return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
10381 }
10382 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
10383 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
10384 bool IsAsciiWordChar(char ch) {
10385  return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
10386  ('0' <= ch && ch <= '9') || ch == '_';
10387 }
10388 
10389 // Returns true iff "\\c" is a supported escape sequence.
10390 bool IsValidEscape(char c) {
10391  return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
10392 }
10393 
10394 // Returns true iff the given atom (specified by escaped and pattern)
10395 // matches ch. The result is undefined if the atom is invalid.
10396 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
10397  if (escaped) { // "\\p" where p is pattern_char.
10398  switch (pattern_char) {
10399  case 'd': return IsAsciiDigit(ch);
10400  case 'D': return !IsAsciiDigit(ch);
10401  case 'f': return ch == '\f';
10402  case 'n': return ch == '\n';
10403  case 'r': return ch == '\r';
10404  case 's': return IsAsciiWhiteSpace(ch);
10405  case 'S': return !IsAsciiWhiteSpace(ch);
10406  case 't': return ch == '\t';
10407  case 'v': return ch == '\v';
10408  case 'w': return IsAsciiWordChar(ch);
10409  case 'W': return !IsAsciiWordChar(ch);
10410  }
10411  return IsAsciiPunct(pattern_char) && pattern_char == ch;
10412  }
10413 
10414  return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
10415 }
10416 
10417 // Helper function used by ValidateRegex() to format error messages.
10418 static std::string FormatRegexSyntaxError(const char* regex, int index) {
10419  return (Message() << "Syntax error at index " << index
10420  << " in simple regular expression \"" << regex << "\": ").GetString();
10421 }
10422 
10423 // Generates non-fatal failures and returns false if regex is invalid;
10424 // otherwise returns true.
10425 bool ValidateRegex(const char* regex) {
10426  if (regex == nullptr) {
10427  ADD_FAILURE() << "NULL is not a valid simple regular expression.";
10428  return false;
10429  }
10430 
10431  bool is_valid = true;
10432 
10433  // True iff ?, *, or + can follow the previous atom.
10434  bool prev_repeatable = false;
10435  for (int i = 0; regex[i]; i++) {
10436  if (regex[i] == '\\') { // An escape sequence
10437  i++;
10438  if (regex[i] == '\0') {
10439  ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
10440  << "'\\' cannot appear at the end.";
10441  return false;
10442  }
10443 
10444  if (!IsValidEscape(regex[i])) {
10445  ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
10446  << "invalid escape sequence \"\\" << regex[i] << "\".";
10447  is_valid = false;
10448  }
10449  prev_repeatable = true;
10450  } else { // Not an escape sequence.
10451  const char ch = regex[i];
10452 
10453  if (ch == '^' && i > 0) {
10454  ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10455  << "'^' can only appear at the beginning.";
10456  is_valid = false;
10457  } else if (ch == '$' && regex[i + 1] != '\0') {
10458  ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10459  << "'$' can only appear at the end.";
10460  is_valid = false;
10461  } else if (IsInSet(ch, "()[]{}|")) {
10462  ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10463  << "'" << ch << "' is unsupported.";
10464  is_valid = false;
10465  } else if (IsRepeat(ch) && !prev_repeatable) {
10466  ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10467  << "'" << ch << "' can only follow a repeatable token.";
10468  is_valid = false;
10469  }
10470 
10471  prev_repeatable = !IsInSet(ch, "^$?*+");
10472  }
10473  }
10474 
10475  return is_valid;
10476 }
10477 
10478 // Matches a repeated regex atom followed by a valid simple regular
10479 // expression. The regex atom is defined as c if escaped is false,
10480 // or \c otherwise. repeat is the repetition meta character (?, *,
10481 // or +). The behavior is undefined if str contains too many
10482 // characters to be indexable by size_t, in which case the test will
10483 // probably time out anyway. We are fine with this limitation as
10484 // std::string has it too.
10485 bool MatchRepetitionAndRegexAtHead(
10486  bool escaped, char c, char repeat, const char* regex,
10487  const char* str) {
10488  const size_t min_count = (repeat == '+') ? 1 : 0;
10489  const size_t max_count = (repeat == '?') ? 1 :
10490  static_cast<size_t>(-1) - 1;
10491  // We cannot call numeric_limits::max() as it conflicts with the
10492  // max() macro on Windows.
10493 
10494  for (size_t i = 0; i <= max_count; ++i) {
10495  // We know that the atom matches each of the first i characters in str.
10496  if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
10497  // We have enough matches at the head, and the tail matches too.
10498  // Since we only care about *whether* the pattern matches str
10499  // (as opposed to *how* it matches), there is no need to find a
10500  // greedy match.
10501  return true;
10502  }
10503  if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
10504  return false;
10505  }
10506  return false;
10507 }
10508 
10509 // Returns true iff regex matches a prefix of str. regex must be a
10510 // valid simple regular expression and not start with "^", or the
10511 // result is undefined.
10512 bool MatchRegexAtHead(const char* regex, const char* str) {
10513  if (*regex == '\0') // An empty regex matches a prefix of anything.
10514  return true;
10515 
10516  // "$" only matches the end of a string. Note that regex being
10517  // valid guarantees that there's nothing after "$" in it.
10518  if (*regex == '$')
10519  return *str == '\0';
10520 
10521  // Is the first thing in regex an escape sequence?
10522  const bool escaped = *regex == '\\';
10523  if (escaped)
10524  ++regex;
10525  if (IsRepeat(regex[1])) {
10526  // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
10527  // here's an indirect recursion. It terminates as the regex gets
10528  // shorter in each recursion.
10529  return MatchRepetitionAndRegexAtHead(
10530  escaped, regex[0], regex[1], regex + 2, str);
10531  } else {
10532  // regex isn't empty, isn't "$", and doesn't start with a
10533  // repetition. We match the first atom of regex with the first
10534  // character of str and recurse.
10535  return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
10536  MatchRegexAtHead(regex + 1, str + 1);
10537  }
10538 }
10539 
10540 // Returns true iff regex matches any substring of str. regex must be
10541 // a valid simple regular expression, or the result is undefined.
10542 //
10543 // The algorithm is recursive, but the recursion depth doesn't exceed
10544 // the regex length, so we won't need to worry about running out of
10545 // stack space normally. In rare cases the time complexity can be
10546 // exponential with respect to the regex length + the string length,
10547 // but usually it's must faster (often close to linear).
10548 bool MatchRegexAnywhere(const char* regex, const char* str) {
10549  if (regex == nullptr || str == nullptr) return false;
10550 
10551  if (*regex == '^')
10552  return MatchRegexAtHead(regex + 1, str);
10553 
10554  // A successful match can be anywhere in str.
10555  do {
10556  if (MatchRegexAtHead(regex, str))
10557  return true;
10558  } while (*str++ != '\0');
10559  return false;
10560 }
10561 
10562 // Implements the RE class.
10563 
10564 RE::~RE() {
10565  free(const_cast<char*>(pattern_));
10566  free(const_cast<char*>(full_pattern_));
10567 }
10568 
10569 // Returns true iff regular expression re matches the entire str.
10570 bool RE::FullMatch(const char* str, const RE& re) {
10571  return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
10572 }
10573 
10574 // Returns true iff regular expression re matches a substring of str
10575 // (including str itself).
10576 bool RE::PartialMatch(const char* str, const RE& re) {
10577  return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
10578 }
10579 
10580 // Initializes an RE from its string representation.
10581 void RE::Init(const char* regex) {
10582  pattern_ = full_pattern_ = nullptr;
10583  if (regex != nullptr) {
10584  pattern_ = posix::StrDup(regex);
10585  }
10586 
10587  is_valid_ = ValidateRegex(regex);
10588  if (!is_valid_) {
10589  // No need to calculate the full pattern when the regex is invalid.
10590  return;
10591  }
10592 
10593  const size_t len = strlen(regex);
10594  // Reserves enough bytes to hold the regular expression used for a
10595  // full match: we need space to prepend a '^', append a '$', and
10596  // terminate the string with '\0'.
10597  char* buffer = static_cast<char*>(malloc(len + 3));
10598  full_pattern_ = buffer;
10599 
10600  if (*regex != '^')
10601  *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
10602 
10603  // We don't use snprintf or strncpy, as they trigger a warning when
10604  // compiled with VC++ 8.0.
10605  memcpy(buffer, regex, len);
10606  buffer += len;
10607 
10608  if (len == 0 || regex[len - 1] != '$')
10609  *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
10610 
10611  *buffer = '\0';
10612 }
10613 
10614 #endif // GTEST_USES_POSIX_RE
10615 
10616 const char kUnknownFile[] = "unknown file";
10617 
10618 // Formats a source file path and a line number as they would appear
10619 // in an error message from the compiler used to compile this code.
10620 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
10621  const std::string file_name(file == nullptr ? kUnknownFile : file);
10622 
10623  if (line < 0) {
10624  return file_name + ":";
10625  }
10626 #ifdef _MSC_VER
10627  return file_name + "(" + StreamableToString(line) + "):";
10628 #else
10629  return file_name + ":" + StreamableToString(line) + ":";
10630 #endif // _MSC_VER
10631 }
10632 
10633 // Formats a file location for compiler-independent XML output.
10634 // Although this function is not platform dependent, we put it next to
10635 // FormatFileLocation in order to contrast the two functions.
10636 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
10637 // to the file location it produces, unlike FormatFileLocation().
10639  const char* file, int line) {
10640  const std::string file_name(file == nullptr ? kUnknownFile : file);
10641 
10642  if (line < 0)
10643  return file_name;
10644  else
10645  return file_name + ":" + StreamableToString(line);
10646 }
10647 
10648 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
10649  : severity_(severity) {
10650  const char* const marker =
10651  severity == GTEST_INFO ? "[ INFO ]" :
10652  severity == GTEST_WARNING ? "[WARNING]" :
10653  severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
10654  GetStream() << ::std::endl << marker << " "
10655  << FormatFileLocation(file, line).c_str() << ": ";
10656 }
10657 
10658 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
10660  GetStream() << ::std::endl;
10661  if (severity_ == GTEST_FATAL) {
10662  fflush(stderr);
10663  posix::Abort();
10664  }
10665 }
10666 
10667 // Disable Microsoft deprecation warnings for POSIX functions called from
10668 // this class (creat, dup, dup2, and close)
10670 
10671 #if GTEST_HAS_STREAM_REDIRECTION
10672 
10673 // Object that captures an output stream (stdout/stderr).
10675  public:
10676  // The ctor redirects the stream to a temporary file.
10677  explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
10678 # if GTEST_OS_WINDOWS
10679  char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
10680  char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
10681 
10682  ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
10683  const UINT success = ::GetTempFileNameA(temp_dir_path,
10684  "gtest_redir",
10685  0, // Generate unique file name.
10686  temp_file_path);
10687  GTEST_CHECK_(success != 0)
10688  << "Unable to create a temporary file in " << temp_dir_path;
10689  const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
10690  GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
10691  << temp_file_path;
10692  filename_ = temp_file_path;
10693 # else
10694  // There's no guarantee that a test has write access to the current
10695  // directory, so we create the temporary file in the /tmp directory
10696  // instead. We use /tmp on most systems, and /sdcard on Android.
10697  // That's because Android doesn't have /tmp.
10698 # if GTEST_OS_LINUX_ANDROID
10699  // Note: Android applications are expected to call the framework's
10700  // Context.getExternalStorageDirectory() method through JNI to get
10701  // the location of the world-writable SD Card directory. However,
10702  // this requires a Context handle, which cannot be retrieved
10703  // globally from native code. Doing so also precludes running the
10704  // code as part of a regular standalone executable, which doesn't
10705  // run in a Dalvik process (e.g. when running it through 'adb shell').
10706  //
10707  // The location /sdcard is directly accessible from native code
10708  // and is the only location (unofficially) supported by the Android
10709  // team. It's generally a symlink to the real SD Card mount point
10710  // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
10711  // other OEM-customized locations. Never rely on these, and always
10712  // use /sdcard.
10713  char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
10714 # else
10715  char name_template[] = "/tmp/captured_stream.XXXXXX";
10716 # endif // GTEST_OS_LINUX_ANDROID
10717  const int captured_fd = mkstemp(name_template);
10718  filename_ = name_template;
10719 # endif // GTEST_OS_WINDOWS
10720  fflush(nullptr);
10721  dup2(captured_fd, fd_);
10722  close(captured_fd);
10723  }
10724 
10726  remove(filename_.c_str());
10727  }
10728 
10730  if (uncaptured_fd_ != -1) {
10731  // Restores the original stream.
10732  fflush(nullptr);
10733  dup2(uncaptured_fd_, fd_);
10734  close(uncaptured_fd_);
10735  uncaptured_fd_ = -1;
10736  }
10737 
10738  FILE* const file = posix::FOpen(filename_.c_str(), "r");
10739  const std::string content = ReadEntireFile(file);
10740  posix::FClose(file);
10741  return content;
10742  }
10743 
10744  private:
10745  const int fd_; // A stream to capture.
10746  int uncaptured_fd_;
10747  // Name of the temporary file holding the stderr output.
10748  ::std::string filename_;
10749 
10750  GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
10751 };
10752 
10754 
10755 static CapturedStream* g_captured_stderr = nullptr;
10756 static CapturedStream* g_captured_stdout = nullptr;
10757 
10758 // Starts capturing an output stream (stdout/stderr).
10759 static void CaptureStream(int fd, const char* stream_name,
10760  CapturedStream** stream) {
10761  if (*stream != nullptr) {
10762  GTEST_LOG_(FATAL) << "Only one " << stream_name
10763  << " capturer can exist at a time.";
10764  }
10765  *stream = new CapturedStream(fd);
10766 }
10767 
10768 // Stops capturing the output stream and returns the captured string.
10769 static std::string GetCapturedStream(CapturedStream** captured_stream) {
10770  const std::string content = (*captured_stream)->GetCapturedString();
10771 
10772  delete *captured_stream;
10773  *captured_stream = nullptr;
10774 
10775  return content;
10776 }
10777 
10778 // Starts capturing stdout.
10780  CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
10781 }
10782 
10783 // Starts capturing stderr.
10785  CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
10786 }
10787 
10788 // Stops capturing stdout and returns the captured string.
10790  return GetCapturedStream(&g_captured_stdout);
10791 }
10792 
10793 // Stops capturing stderr and returns the captured string.
10795  return GetCapturedStream(&g_captured_stderr);
10796 }
10797 
10798 #endif // GTEST_HAS_STREAM_REDIRECTION
10799 
10800 
10801 
10802 
10803 
10804 size_t GetFileSize(FILE* file) {
10805  fseek(file, 0, SEEK_END);
10806  return static_cast<size_t>(ftell(file));
10807 }
10808 
10810  const size_t file_size = GetFileSize(file);
10811  char* const buffer = new char[file_size];
10812 
10813  size_t bytes_last_read = 0; // # of bytes read in the last fread()
10814  size_t bytes_read = 0; // # of bytes read so far
10815 
10816  fseek(file, 0, SEEK_SET);
10817 
10818  // Keeps reading the file until we cannot read further or the
10819  // pre-determined file size is reached.
10820  do {
10821  bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
10822  bytes_read += bytes_last_read;
10823  } while (bytes_last_read > 0 && bytes_read < file_size);
10824 
10825  const std::string content(buffer, bytes_read);
10826  delete[] buffer;
10827 
10828  return content;
10829 }
10830 
10831 #if GTEST_HAS_DEATH_TEST
10832 static const std::vector<std::string>* g_injected_test_argvs =
10833  nullptr; // Owned.
10834 
10835 std::vector<std::string> GetInjectableArgvs() {
10836  if (g_injected_test_argvs != nullptr) {
10837  return *g_injected_test_argvs;
10838  }
10839  return GetArgvs();
10840 }
10841 
10842 void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
10843  if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
10844  g_injected_test_argvs = new_argvs;
10845 }
10846 
10847 void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
10848  SetInjectableArgvs(
10849  new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
10850 }
10851 
10852 #if GTEST_HAS_GLOBAL_STRING
10853 void SetInjectableArgvs(const std::vector< ::string>& new_argvs) {
10854  SetInjectableArgvs(
10855  new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
10856 }
10857 #endif // GTEST_HAS_GLOBAL_STRING
10858 
10859 void ClearInjectableArgvs() {
10860  delete g_injected_test_argvs;
10861  g_injected_test_argvs = nullptr;
10862 }
10863 #endif // GTEST_HAS_DEATH_TEST
10864 
10865 #if GTEST_OS_WINDOWS_MOBILE
10866 namespace posix {
10867 void Abort() {
10868  DebugBreak();
10869  TerminateProcess(GetCurrentProcess(), 1);
10870 }
10871 } // namespace posix
10872 #endif // GTEST_OS_WINDOWS_MOBILE
10873 
10874 // Returns the name of the environment variable corresponding to the
10875 // given flag. For example, FlagToEnvVar("foo") will return
10876 // "GTEST_FOO" in the open-source version.
10877 static std::string FlagToEnvVar(const char* flag) {
10878  const std::string full_flag =
10879  (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
10880 
10881  Message env_var;
10882  for (size_t i = 0; i != full_flag.length(); i++) {
10883  env_var << ToUpper(full_flag.c_str()[i]);
10884  }
10885 
10886  return env_var.GetString();
10887 }
10888 
10889 // Parses 'str' for a 32-bit signed integer. If successful, writes
10890 // the result to *value and returns true; otherwise leaves *value
10891 // unchanged and returns false.
10892 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
10893  // Parses the environment variable as a decimal integer.
10894  char* end = nullptr;
10895  const long long_value = strtol(str, &end, 10); // NOLINT
10896 
10897  // Has strtol() consumed all characters in the string?
10898  if (*end != '\0') {
10899  // No - an invalid character was encountered.
10900  Message msg;
10901  msg << "WARNING: " << src_text
10902  << " is expected to be a 32-bit integer, but actually"
10903  << " has value \"" << str << "\".\n";
10904  printf("%s", msg.GetString().c_str());
10905  fflush(stdout);
10906  return false;
10907  }
10908 
10909  // Is the parsed value in the range of an Int32?
10910  const Int32 result = static_cast<Int32>(long_value);
10911  if (long_value == LONG_MAX || long_value == LONG_MIN ||
10912  // The parsed value overflows as a long. (strtol() returns
10913  // LONG_MAX or LONG_MIN when the input overflows.)
10914  result != long_value
10915  // The parsed value overflows as an Int32.
10916  ) {
10917  Message msg;
10918  msg << "WARNING: " << src_text
10919  << " is expected to be a 32-bit integer, but actually"
10920  << " has value " << str << ", which overflows.\n";
10921  printf("%s", msg.GetString().c_str());
10922  fflush(stdout);
10923  return false;
10924  }
10925 
10926  *value = result;
10927  return true;
10928 }
10929 
10930 // Reads and returns the Boolean environment variable corresponding to
10931 // the given flag; if it's not set, returns default_value.
10932 //
10933 // The value is considered true iff it's not "0".
10934 bool BoolFromGTestEnv(const char* flag, bool default_value) {
10935 #if defined(GTEST_GET_BOOL_FROM_ENV_)
10936  return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
10937 #else
10938  const std::string env_var = FlagToEnvVar(flag);
10939  const char* const string_value = posix::GetEnv(env_var.c_str());
10940  return string_value == nullptr ? default_value
10941  : strcmp(string_value, "0") != 0;
10942 #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
10943 }
10944 
10945 // Reads and returns a 32-bit integer stored in the environment
10946 // variable corresponding to the given flag; if it isn't set or
10947 // doesn't represent a valid 32-bit integer, returns default_value.
10948 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
10949 #if defined(GTEST_GET_INT32_FROM_ENV_)
10950  return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
10951 #else
10952  const std::string env_var = FlagToEnvVar(flag);
10953  const char* const string_value = posix::GetEnv(env_var.c_str());
10954  if (string_value == nullptr) {
10955  // The environment variable is not set.
10956  return default_value;
10957  }
10958 
10959  Int32 result = default_value;
10960  if (!ParseInt32(Message() << "Environment variable " << env_var,
10961  string_value, &result)) {
10962  printf("The default value %s is used.\n",
10963  (Message() << default_value).GetString().c_str());
10964  fflush(stdout);
10965  return default_value;
10966  }
10967 
10968  return result;
10969 #endif // defined(GTEST_GET_INT32_FROM_ENV_)
10970 }
10971 
10972 // As a special case for the 'output' flag, if GTEST_OUTPUT is not
10973 // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
10974 // system. The value of XML_OUTPUT_FILE is a filename without the
10975 // "xml:" prefix of GTEST_OUTPUT.
10976 // Note that this is meant to be called at the call site so it does
10977 // not check that the flag is 'output'
10978 // In essence this checks an env variable called XML_OUTPUT_FILE
10979 // and if it is set we prepend "xml:" to its value, if it not set we return ""
10981  std::string default_value_for_output_flag = "";
10982  const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
10983  if (nullptr != xml_output_file_env) {
10984  default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
10985  }
10986  return default_value_for_output_flag;
10987 }
10988 
10989 // Reads and returns the string environment variable corresponding to
10990 // the given flag; if it's not set, returns default_value.
10991 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
10992 #if defined(GTEST_GET_STRING_FROM_ENV_)
10993  return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
10994 #else
10995  const std::string env_var = FlagToEnvVar(flag);
10996  const char* const value = posix::GetEnv(env_var.c_str());
10997  return value == nullptr ? default_value : value;
10998 #endif // defined(GTEST_GET_STRING_FROM_ENV_)
10999 }
11000 
11001 } // namespace internal
11002 } // namespace testing
11003 // Copyright 2007, Google Inc.
11004 // All rights reserved.
11005 //
11006 // Redistribution and use in source and binary forms, with or without
11007 // modification, are permitted provided that the following conditions are
11008 // met:
11009 //
11010 // * Redistributions of source code must retain the above copyright
11011 // notice, this list of conditions and the following disclaimer.
11012 // * Redistributions in binary form must reproduce the above
11013 // copyright notice, this list of conditions and the following disclaimer
11014 // in the documentation and/or other materials provided with the
11015 // distribution.
11016 // * Neither the name of Google Inc. nor the names of its
11017 // contributors may be used to endorse or promote products derived from
11018 // this software without specific prior written permission.
11019 //
11020 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11021 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11022 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11023 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11024 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11025 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11026 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11027 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11028 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11029 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11030 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11031 
11032 
11033 // Google Test - The Google C++ Testing and Mocking Framework
11034 //
11035 // This file implements a universal value printer that can print a
11036 // value of any type T:
11037 //
11038 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
11039 //
11040 // It uses the << operator when possible, and prints the bytes in the
11041 // object otherwise. A user can override its behavior for a class
11042 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
11043 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
11044 // defines Foo.
11045 
11046 #include <stdio.h>
11047 #include <cctype>
11048 #include <cwchar>
11049 #include <ostream> // NOLINT
11050 #include <string>
11051 
11052 namespace testing {
11053 
11054 namespace {
11055 
11056 using ::std::ostream;
11057 
11058 // Prints a segment of bytes in the given object.
11062 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
11063  size_t count, ostream* os) {
11064  char text[5] = "";
11065  for (size_t i = 0; i != count; i++) {
11066  const size_t j = start + i;
11067  if (i != 0) {
11068  // Organizes the bytes into groups of 2 for easy parsing by
11069  // human.
11070  if ((j % 2) == 0)
11071  *os << ' ';
11072  else
11073  *os << '-';
11074  }
11075  GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
11076  *os << text;
11077  }
11078 }
11079 
11080 // Prints the bytes in the given value to the given ostream.
11081 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
11082  ostream* os) {
11083  // Tells the user how big the object is.
11084  *os << count << "-byte object <";
11085 
11086  const size_t kThreshold = 132;
11087  const size_t kChunkSize = 64;
11088  // If the object size is bigger than kThreshold, we'll have to omit
11089  // some details by printing only the first and the last kChunkSize
11090  // bytes.
11091  if (count < kThreshold) {
11092  PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
11093  } else {
11094  PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
11095  *os << " ... ";
11096  // Rounds up to 2-byte boundary.
11097  const size_t resume_pos = (count - kChunkSize + 1)/2*2;
11098  PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
11099  }
11100  *os << ">";
11101 }
11102 
11103 } // namespace
11104 
11105 namespace internal2 {
11106 
11107 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
11108 // given object. The delegation simplifies the implementation, which
11109 // uses the << operator and thus is easier done outside of the
11110 // ::testing::internal namespace, which contains a << operator that
11111 // sometimes conflicts with the one in STL.
11112 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
11113  ostream* os) {
11114  PrintBytesInObjectToImpl(obj_bytes, count, os);
11115 }
11116 
11117 } // namespace internal2
11118 
11119 namespace internal {
11120 
11121 // Depending on the value of a char (or wchar_t), we print it in one
11122 // of three formats:
11123 // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
11124 // - as a hexadecimal escape sequence (e.g. '\x7F'), or
11125 // - as a special escape sequence (e.g. '\r', '\n').
11130 };
11131 
11132 // Returns true if c is a printable ASCII character. We test the
11133 // value of c directly instead of calling isprint(), which is buggy on
11134 // Windows Mobile.
11135 inline bool IsPrintableAscii(wchar_t c) {
11136  return 0x20 <= c && c <= 0x7E;
11137 }
11138 
11139 // Prints a wide or narrow char c as a character literal without the
11140 // quotes, escaping it when necessary; returns how c was formatted.
11141 // The template argument UnsignedChar is the unsigned version of Char,
11142 // which is the type of c.
11143 template <typename UnsignedChar, typename Char>
11144 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
11145  switch (static_cast<wchar_t>(c)) {
11146  case L'\0':
11147  *os << "\\0";
11148  break;
11149  case L'\'':
11150  *os << "\\'";
11151  break;
11152  case L'\\':
11153  *os << "\\\\";
11154  break;
11155  case L'\a':
11156  *os << "\\a";
11157  break;
11158  case L'\b':
11159  *os << "\\b";
11160  break;
11161  case L'\f':
11162  *os << "\\f";
11163  break;
11164  case L'\n':
11165  *os << "\\n";
11166  break;
11167  case L'\r':
11168  *os << "\\r";
11169  break;
11170  case L'\t':
11171  *os << "\\t";
11172  break;
11173  case L'\v':
11174  *os << "\\v";
11175  break;
11176  default:
11177  if (IsPrintableAscii(c)) {
11178  *os << static_cast<char>(c);
11179  return kAsIs;
11180  } else {
11181  ostream::fmtflags flags = os->flags();
11182  *os << "\\x" << std::hex << std::uppercase
11183  << static_cast<int>(static_cast<UnsignedChar>(c));
11184  os->flags(flags);
11185  return kHexEscape;
11186  }
11187  }
11188  return kSpecialEscape;
11189 }
11190 
11191 // Prints a wchar_t c as if it's part of a string literal, escaping it when
11192 // necessary; returns how c was formatted.
11193 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
11194  switch (c) {
11195  case L'\'':
11196  *os << "'";
11197  return kAsIs;
11198  case L'"':
11199  *os << "\\\"";
11200  return kSpecialEscape;
11201  default:
11202  return PrintAsCharLiteralTo<wchar_t>(c, os);
11203  }
11204 }
11205 
11206 // Prints a char c as if it's part of a string literal, escaping it when
11207 // necessary; returns how c was formatted.
11208 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
11209  return PrintAsStringLiteralTo(
11210  static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
11211 }
11212 
11213 // Prints a wide or narrow character c and its code. '\0' is printed
11214 // as "'\\0'", other unprintable characters are also properly escaped
11215 // using the standard C++ escape sequence. The template argument
11216 // UnsignedChar is the unsigned version of Char, which is the type of c.
11217 template <typename UnsignedChar, typename Char>
11218 void PrintCharAndCodeTo(Char c, ostream* os) {
11219  // First, print c as a literal in the most readable form we can find.
11220  *os << ((sizeof(c) > 1) ? "L'" : "'");
11221  const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
11222  *os << "'";
11223 
11224  // To aid user debugging, we also print c's code in decimal, unless
11225  // it's 0 (in which case c was printed as '\\0', making the code
11226  // obvious).
11227  if (c == 0)
11228  return;
11229  *os << " (" << static_cast<int>(c);
11230 
11231  // For more convenience, we print c's code again in hexadecimal,
11232  // unless c was already printed in the form '\x##' or the code is in
11233  // [1, 9].
11234  if (format == kHexEscape || (1 <= c && c <= 9)) {
11235  // Do nothing.
11236  } else {
11237  *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
11238  }
11239  *os << ")";
11240 }
11241 
11242 void PrintTo(unsigned char c, ::std::ostream* os) {
11243  PrintCharAndCodeTo<unsigned char>(c, os);
11244 }
11245 void PrintTo(signed char c, ::std::ostream* os) {
11246  PrintCharAndCodeTo<unsigned char>(c, os);
11247 }
11248 
11249 // Prints a wchar_t as a symbol if it is printable or as its internal
11250 // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
11251 void PrintTo(wchar_t wc, ostream* os) {
11252  PrintCharAndCodeTo<wchar_t>(wc, os);
11253 }
11254 
11255 // Prints the given array of characters to the ostream. CharType must be either
11256 // char or wchar_t.
11257 // The array starts at begin, the length is len, it may include '\0' characters
11258 // and may not be NUL-terminated.
11259 template <typename CharType>
11263 static CharFormat PrintCharsAsStringTo(
11264  const CharType* begin, size_t len, ostream* os) {
11265  const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
11266  *os << kQuoteBegin;
11267  bool is_previous_hex = false;
11268  CharFormat print_format = kAsIs;
11269  for (size_t index = 0; index < len; ++index) {
11270  const CharType cur = begin[index];
11271  if (is_previous_hex && IsXDigit(cur)) {
11272  // Previous character is of '\x..' form and this character can be
11273  // interpreted as another hexadecimal digit in its number. Break string to
11274  // disambiguate.
11275  *os << "\" " << kQuoteBegin;
11276  }
11277  is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
11278  // Remember if any characters required hex escaping.
11279  if (is_previous_hex) {
11280  print_format = kHexEscape;
11281  }
11282  }
11283  *os << "\"";
11284  return print_format;
11285 }
11286 
11287 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
11288 // 'begin'. CharType must be either char or wchar_t.
11289 template <typename CharType>
11293 static void UniversalPrintCharArray(
11294  const CharType* begin, size_t len, ostream* os) {
11295  // The code
11296  // const char kFoo[] = "foo";
11297  // generates an array of 4, not 3, elements, with the last one being '\0'.
11298  //
11299  // Therefore when printing a char array, we don't print the last element if
11300  // it's '\0', such that the output matches the string literal as it's
11301  // written in the source code.
11302  if (len > 0 && begin[len - 1] == '\0') {
11303  PrintCharsAsStringTo(begin, len - 1, os);
11304  return;
11305  }
11306 
11307  // If, however, the last element in the array is not '\0', e.g.
11308  // const char kFoo[] = { 'f', 'o', 'o' };
11309  // we must print the entire array. We also print a message to indicate
11310  // that the array is not NUL-terminated.
11311  PrintCharsAsStringTo(begin, len, os);
11312  *os << " (no terminating NUL)";
11313 }
11314 
11315 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
11316 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
11317  UniversalPrintCharArray(begin, len, os);
11318 }
11319 
11320 // Prints a (const) wchar_t array of 'len' elements, starting at address
11321 // 'begin'.
11322 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
11323  UniversalPrintCharArray(begin, len, os);
11324 }
11325 
11326 // Prints the given C string to the ostream.
11327 void PrintTo(const char* s, ostream* os) {
11328  if (s == nullptr) {
11329  *os << "NULL";
11330  } else {
11331  *os << ImplicitCast_<const void*>(s) << " pointing to ";
11332  PrintCharsAsStringTo(s, strlen(s), os);
11333  }
11334 }
11335 
11336 // MSVC compiler can be configured to define whar_t as a typedef
11337 // of unsigned short. Defining an overload for const wchar_t* in that case
11338 // would cause pointers to unsigned shorts be printed as wide strings,
11339 // possibly accessing more memory than intended and causing invalid
11340 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
11341 // wchar_t is implemented as a native type.
11342 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
11343 // Prints the given wide C string to the ostream.
11344 void PrintTo(const wchar_t* s, ostream* os) {
11345  if (s == nullptr) {
11346  *os << "NULL";
11347  } else {
11348  *os << ImplicitCast_<const void*>(s) << " pointing to ";
11349  PrintCharsAsStringTo(s, wcslen(s), os);
11350  }
11351 }
11352 #endif // wchar_t is native
11353 
11354 namespace {
11355 
11356 bool ContainsUnprintableControlCodes(const char* str, size_t length) {
11357  const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
11358 
11359  for (size_t i = 0; i < length; i++) {
11360  unsigned char ch = *s++;
11361  if (std::iscntrl(ch)) {
11362  switch (ch) {
11363  case '\t':
11364  case '\n':
11365  case '\r':
11366  break;
11367  default:
11368  return true;
11369  }
11370  }
11371  }
11372  return false;
11373 }
11374 
11375 bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
11376 
11377 bool IsValidUTF8(const char* str, size_t length) {
11378  const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
11379 
11380  for (size_t i = 0; i < length;) {
11381  unsigned char lead = s[i++];
11382 
11383  if (lead <= 0x7f) {
11384  continue; // single-byte character (ASCII) 0..7F
11385  }
11386  if (lead < 0xc2) {
11387  return false; // trail byte or non-shortest form
11388  } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
11389  ++i; // 2-byte character
11390  } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
11391  IsUTF8TrailByte(s[i]) &&
11392  IsUTF8TrailByte(s[i + 1]) &&
11393  // check for non-shortest form and surrogate
11394  (lead != 0xe0 || s[i] >= 0xa0) &&
11395  (lead != 0xed || s[i] < 0xa0)) {
11396  i += 2; // 3-byte character
11397  } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
11398  IsUTF8TrailByte(s[i]) &&
11399  IsUTF8TrailByte(s[i + 1]) &&
11400  IsUTF8TrailByte(s[i + 2]) &&
11401  // check for non-shortest form
11402  (lead != 0xf0 || s[i] >= 0x90) &&
11403  (lead != 0xf4 || s[i] < 0x90)) {
11404  i += 3; // 4-byte character
11405  } else {
11406  return false;
11407  }
11408  }
11409  return true;
11410 }
11411 
11412 void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
11413  if (!ContainsUnprintableControlCodes(str, length) &&
11414  IsValidUTF8(str, length)) {
11415  *os << "\n As Text: \"" << str << "\"";
11416  }
11417 }
11418 
11419 } // anonymous namespace
11420 
11421 // Prints a ::string object.
11422 #if GTEST_HAS_GLOBAL_STRING
11423 void PrintStringTo(const ::string& s, ostream* os) {
11424  if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
11425  if (GTEST_FLAG(print_utf8)) {
11426  ConditionalPrintAsText(s.data(), s.size(), os);
11427  }
11428  }
11429 }
11430 #endif // GTEST_HAS_GLOBAL_STRING
11431 
11432 void PrintStringTo(const ::std::string& s, ostream* os) {
11433  if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
11434  if (GTEST_FLAG(print_utf8)) {
11435  ConditionalPrintAsText(s.data(), s.size(), os);
11436  }
11437  }
11438 }
11439 
11440 // Prints a ::wstring object.
11441 #if GTEST_HAS_GLOBAL_WSTRING
11442 void PrintWideStringTo(const ::wstring& s, ostream* os) {
11443  PrintCharsAsStringTo(s.data(), s.size(), os);
11444 }
11445 #endif // GTEST_HAS_GLOBAL_WSTRING
11446 
11447 #if GTEST_HAS_STD_WSTRING
11449  PrintCharsAsStringTo(s.data(), s.size(), os);
11450 }
11451 #endif // GTEST_HAS_STD_WSTRING
11452 
11453 } // namespace internal
11454 
11455 } // namespace testing
11456 // Copyright 2008, Google Inc.
11457 // All rights reserved.
11458 //
11459 // Redistribution and use in source and binary forms, with or without
11460 // modification, are permitted provided that the following conditions are
11461 // met:
11462 //
11463 // * Redistributions of source code must retain the above copyright
11464 // notice, this list of conditions and the following disclaimer.
11465 // * Redistributions in binary form must reproduce the above
11466 // copyright notice, this list of conditions and the following disclaimer
11467 // in the documentation and/or other materials provided with the
11468 // distribution.
11469 // * Neither the name of Google Inc. nor the names of its
11470 // contributors may be used to endorse or promote products derived from
11471 // this software without specific prior written permission.
11472 //
11473 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11474 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11475 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11476 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11477 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11478 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11479 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11480 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11481 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11482 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11483 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11484 
11485 //
11486 // The Google C++ Testing and Mocking Framework (Google Test)
11487 
11488 
11489 namespace testing {
11490 
11491 using internal::GetUnitTestImpl;
11492 
11493 // Gets the summary of the failure message by omitting the stack trace
11494 // in it.
11495 std::string TestPartResult::ExtractSummary(const char* message) {
11496  const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
11497  return stack_trace == nullptr ? message : std::string(message, stack_trace);
11498 }
11499 
11500 // Prints a TestPartResult object.
11501 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
11502  return os << result.file_name() << ":" << result.line_number() << ": "
11503  << (result.type() == TestPartResult::kSuccess
11504  ? "Success"
11505  : result.type() == TestPartResult::kSkip
11506  ? "Skipped"
11507  : result.type() == TestPartResult::kFatalFailure
11508  ? "Fatal failure"
11509  : "Non-fatal failure")
11510  << ":\n"
11511  << result.message() << std::endl;
11512 }
11513 
11514 // Appends a TestPartResult to the array.
11515 void TestPartResultArray::Append(const TestPartResult& result) {
11516  array_.push_back(result);
11517 }
11518 
11519 // Returns the TestPartResult at the given index (0-based).
11520 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
11521  if (index < 0 || index >= size()) {
11522  printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
11524  }
11525 
11526  return array_[index];
11527 }
11528 
11529 // Returns the number of TestPartResult objects in the array.
11530 int TestPartResultArray::size() const {
11531  return static_cast<int>(array_.size());
11532 }
11533 
11534 namespace internal {
11535 
11536 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
11537  : has_new_fatal_failure_(false),
11538  original_reporter_(GetUnitTestImpl()->
11539  GetTestPartResultReporterForCurrentThread()) {
11540  GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
11541 }
11542 
11543 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
11544  GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
11545  original_reporter_);
11546 }
11547 
11548 void HasNewFatalFailureHelper::ReportTestPartResult(
11549  const TestPartResult& result) {
11550  if (result.fatally_failed())
11551  has_new_fatal_failure_ = true;
11552  original_reporter_->ReportTestPartResult(result);
11553 }
11554 
11555 } // namespace internal
11556 
11557 } // namespace testing
11558 // Copyright 2008 Google Inc.
11559 // All Rights Reserved.
11560 //
11561 // Redistribution and use in source and binary forms, with or without
11562 // modification, are permitted provided that the following conditions are
11563 // met:
11564 //
11565 // * Redistributions of source code must retain the above copyright
11566 // notice, this list of conditions and the following disclaimer.
11567 // * Redistributions in binary form must reproduce the above
11568 // copyright notice, this list of conditions and the following disclaimer
11569 // in the documentation and/or other materials provided with the
11570 // distribution.
11571 // * Neither the name of Google Inc. nor the names of its
11572 // contributors may be used to endorse or promote products derived from
11573 // this software without specific prior written permission.
11574 //
11575 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11576 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11577 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11578 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11579 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11580 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11581 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11582 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11583 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11584 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11585 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11586 
11587 
11588 
11589 
11590 namespace testing {
11591 namespace internal {
11592 
11593 #if GTEST_HAS_TYPED_TEST_P
11594 
11595 // Skips to the first non-space char in str. Returns an empty string if str
11596 // contains only whitespace characters.
11597 static const char* SkipSpaces(const char* str) {
11598  while (IsSpace(*str))
11599  str++;
11600  return str;
11601 }
11602 
11603 static std::vector<std::string> SplitIntoTestNames(const char* src) {
11604  std::vector<std::string> name_vec;
11605  src = SkipSpaces(src);
11606  for (; src != nullptr; src = SkipComma(src)) {
11607  name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
11608  }
11609  return name_vec;
11610 }
11611 
11612 // Verifies that registered_tests match the test names in
11613 // registered_tests_; returns registered_tests if successful, or
11614 // aborts the program otherwise.
11615 const char* TypedTestSuitePState::VerifyRegisteredTestNames(
11616  const char* file, int line, const char* registered_tests) {
11617  typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
11618  registered_ = true;
11619 
11620  std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
11621 
11622  Message errors;
11623 
11624  std::set<std::string> tests;
11625  for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
11626  name_it != name_vec.end(); ++name_it) {
11627  const std::string& name = *name_it;
11628  if (tests.count(name) != 0) {
11629  errors << "Test " << name << " is listed more than once.\n";
11630  continue;
11631  }
11632 
11633  bool found = false;
11634  for (RegisteredTestIter it = registered_tests_.begin();
11635  it != registered_tests_.end();
11636  ++it) {
11637  if (name == it->first) {
11638  found = true;
11639  break;
11640  }
11641  }
11642 
11643  if (found) {
11644  tests.insert(name);
11645  } else {
11646  errors << "No test named " << name
11647  << " can be found in this test suite.\n";
11648  }
11649  }
11650 
11651  for (RegisteredTestIter it = registered_tests_.begin();
11652  it != registered_tests_.end();
11653  ++it) {
11654  if (tests.count(it->first) == 0) {
11655  errors << "You forgot to list test " << it->first << ".\n";
11656  }
11657  }
11658 
11659  const std::string& errors_str = errors.GetString();
11660  if (errors_str != "") {
11661  fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
11662  errors_str.c_str());
11663  fflush(stderr);
11664  posix::Abort();
11665  }
11666 
11667  return registered_tests;
11668 }
11669 
11670 #endif // GTEST_HAS_TYPED_TEST_P
11671 
11672 } // namespace internal
11673 } // namespace testing
bool IsXDigit(char ch)
Definition: gtest.h:2251
void PrintCharAndCodeTo(Char c, ostream *os)
Definition: gtest-all.cc:11218
GTEST_API_ AssertionResult DoubleLE(const char *expr1, const char *expr2, double val1, double val2)
GTEST_API_ bool AlwaysTrue()
std::string GetCapturedStdout()
Definition: gtest-all.cc:10789
GTEST_API_ AssertionResult DoubleNearPredFormat(const char *expr1, const char *expr2, const char *abs_error_expr, double val1, double val2, double abs_error)
std::string GetCapturedStderr()
Definition: gtest-all.cc:10794
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(UnitTest *unit_test, int skip_count)
void(*)() SetUpTestSuiteFunc
Definition: gtest.h:6926
#define GTEST_INIT_GOOGLE_TEST_NAME_
Definition: gtest.h:522
GTEST_API_ bool SkipPrefix(const char *prefix, const char **pstr)
#define GTEST_DEFINE_int32_(name, default_val, doc)
Definition: gtest.h:2505
#define GTEST_FLAG_PREFIX_DASH_
Definition: gtest.h:515
int FClose(FILE *fp)
Definition: gtest.h:2358
#define GTEST_PATH_MAX_
Definition: gtest-all.cc:9221
size_t GetThreadCount()
Definition: gtest-all.cc:9875
#define GTEST_NO_INLINE_
Definition: gtest.h:1009
eval< filter_impl::filter_< List, Pred, typelist<> > > filter
Definition: typelist.h:800
AssertionResult CmpHelperEQ(const char *lhs_expression, const char *rhs_expression, const T1 &lhs, const T2 &rhs)
Definition: gtest.h:16111
#define GTEST_DEV_EMAIL_
Definition: gtest.h:513
GTEST_API_ bool IsTrue(bool condition)
::std::string PrintToString(const T &value)
Definition: gtest.h:8969
std::string ReadEntireFile(FILE *file)
Definition: gtest-all.cc:10809
#define GTEST_DISABLE_MSC_DEPRECATED_POP_()
Definition: gtest.h:561
GTEST_API_ AssertionResult CmpHelperSTRNE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
bool BoolFromGTestEnv(const char *flag, bool default_value)
Definition: gtest-all.cc:10934
GTEST_API_ AssertionResult IsSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
GTEST_API_ ::std::string FormatFileLocation(const char *file, int line)
Definition: gtest-all.cc:10620
int IsATTY(int fd)
Definition: gtest.h:2323
::std::string string
Definition: gtest.h:1115
#define GTEST_SNPRINTF_
Definition: gtest.h:2410
Int32 Int32FromGTestEnv(const char *flag, Int32 default_value)
Definition: gtest-all.cc:10948
#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
Definition: gtest.h:1031
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251) namespace testing
Definition: gtest-all.cc:112
GTEST_API_ std::vector< EditType > CalculateOptimalEdits(const std::vector< size_t > &left, const std::vector< size_t > &right)
#define GTEST_DEFAULT_DEATH_TEST_STYLE
Definition: gtest.h:1002
bool ParseInt32(const Message &src_text, const char *str, Int32 *value)
Definition: gtest-all.cc:10892
size_< List::size()> size
Definition: typelist.h:129
::std::wstring wstring
Definition: gtest.h:1121
bool IsDigit(char ch)
Definition: gtest.h:2239
int Stat(const char *path, StatStruct *buf)
Definition: gtest.h:2324
#define GTEST_PATH_SEP_
Definition: gtest.h:2221
GTEST_API_ AssertionResult IsNotSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
at_c< List, N::type::value > at
Definition: typelist.h:253
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251) namespace testing
Definition: gtest-all.cc:190
eval< reverse_impl::reverse_< List > > reverse
Definition: typelist.h:479
repeat_c< N::type::value, Ts... > repeat
Definition: typelist.h:161
const char * GetEnv(const char *name)
Definition: gtest.h:2369
void PrintStringTo(const ::std::string &s, ostream *os)
Definition: gtest-all.cc:11432
std::string FormatForComparisonFailureMessage(const T1 &value, const T2 &)
Definition: gtest.h:8416
#define GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
Definition: gtest.h:559
TypeWithSize< 8 >::Int TimeInMillis
Definition: gtest.h:2479
eval< replace_if< List, same_as< T >, U > > replace
Definition: typelist.h:848
GTEST_API_ AssertionResult EqFailure(const char *expected_expression, const char *actual_expression, const std::string &expected_value, const std::string &actual_value, bool ignoring_case)
find_if< List, same_as< T > > find
Definition: typelist.h:663
std::ostream & operator<<(std::ostream &os, const TestPartResult &result)
Definition: gtest-all.cc:11501
const char kCurrentDirectoryString[]
Definition: gtest-all.cc:9247
#define GTEST_DECLARE_bool_(name)
Definition: gtest.h:2496
size_t GetFileSize(FILE *file)
Definition: gtest-all.cc:10804
std::string StreamableToString(const T &streamable)
Definition: gtest.h:2769
count_if< List, same_as< T > > count
Definition: typelist.h:761
#define GTEST_LOG_(severity)
Definition: gtest.h:1246
#define GTEST_API_
Definition: gtest.h:998
TypeWithSize< 4 >::UInt UInt32
Definition: gtest.h:2476
const void * TypeId
Definition: gtest.h:6854
const char * StringFromGTestEnv(const char *flag, const char *default_value)
Definition: gtest-all.cc:10991
int Write(int fd, const void *buf, unsigned int count)
Definition: gtest.h:2363
void PrintBytesInObjectTo(const unsigned char *obj_bytes, size_t count, ostream *os)
Definition: gtest-all.cc:11112
GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
TypeWithSize< 4 >::Int Int32
Definition: gtest.h:2475
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)
bool IsSpace(char ch)
Definition: gtest.h:2245
integral_< decltype(_Tp1()+_Tp2()), _Tp1()+_Tp2() > add
Addition.
Definition: operations.h:144
GTEST_API_ const char * fmt
Definition: gtest.h:16430
GTEST_API_ std::string TempDir()
void PrintTo(const wchar_t *s, ostream *os)
Definition: gtest-all.cc:11344
GTEST_API_ const char kStackTraceMarker[]
GTEST_DEFINE_string_(death_test_style, internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), "Indicates how to run a death test in a forked child process: " "\hreadsafe\(child process re-executes the test binary " "from the beginning, running only the specific death test) or " "\ast\(child process runs the death test immediately " "after forking).")
::std::ostream & GetStream()
Definition: gtest.h:1236
GTEST_DEFINE_string_(internal_run_death_test, "", "Indicates the file, line number, temporal index of " "the single death test to run, and a file descriptor to " "which a success code may be sent, all separated by " "the '|' characters. This flag is specified if and only if the current " "process is a sub-process launched for running a thread-safe " "death test. FOR INTERNAL USE ONLY.")
#define GTEST_IMPL_CMP_HELPER_(op_name, op)
#define GTEST_FLAG(name)
Definition: gtest.h:2485
GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
void(*)() TearDownTestSuiteFunc
Definition: gtest.h:6927
struct stat StatStruct
Definition: gtest.h:2320
GTEST_API_ void InitGoogleTest(int *argc, char **argv)
#define GTEST_REPEATER_METHOD_(Name, Type)
void LogToStderr()
Definition: gtest.h:1250
GTEST_API_ std::vector< std::string > GetArgvs()
GTEST_API_ TestInfo * MakeAndRegisterTestInfo(const char *test_suite_name, const char *name, const char *type_param, const char *value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, TearDownTestSuiteFunc tear_down_tc, TestFactoryBase *factory)
int Read(int fd, void *buf, unsigned int count)
Definition: gtest.h:2360
_utlConcept Predicate
Definition: stl.h:759
#define GTEST_CHECK_(condition)
Definition: gtest.h:1270
bool AlwaysFalse()
Definition: gtest.h:7260
GTestMutexLock MutexLock
Definition: gtest.h:2162
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3)
Definition: gtest.h:14846
int StrCaseCmp(const char *s1, const char *s2)
Definition: gtest.h:2325
static const UInt32 kMaxRange
Definition: gtest.h:7278
long long BiggestInt
Definition: gtest.h:2223
#define GTEST_NAME_
Definition: gtest.h:517
bool IsDir(const StatStruct &st)
Definition: gtest.h:2330
bool IsPrintableAscii(wchar_t c)
Definition: gtest-all.cc:11135
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)
Definition: gtest.h:927
#define GTEST_FLAG_PREFIX_UPPER_
Definition: gtest.h:516
void PrintTo(unsigned char c, ::std::ostream *os)
Definition: gtest-all.cc:11242
int FileNo(FILE *file)
Definition: gtest.h:2322
GTEST_API_ std::string GetBoolAssertionFailureMessage(const AssertionResult &assertion_result, const char *expression_text, const char *actual_predicate_value, const char *expected_predicate_value)
GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char *file, int line)
Definition: gtest-all.cc:10638
FILE * FOpen(const char *path, const char *mode)
Definition: gtest.h:2349
int Close(int fd)
Definition: gtest.h:2366
const char kUnknownFile[]
Definition: gtest-all.cc:10616
#define GTEST_FLAG_PREFIX_
Definition: gtest.h:514
GTEST_DEFINE_bool_(death_test_use_fork, internal::BoolFromGTestEnv("death_test_use_fork", false), "Instructs to use fork()/_exit() instead of clone() in death tests. " "Ignored and always uses fork() on POSIX systems where clone() is not " "implemented. Useful when running under valgrind or similar tools if " "those do not support clone(). Valgrind 3.3.1 will just fail if " "it sees an unsupported combination of clone() flags. " "It is not recommended to use this flag w/o valgrind though it will " "work in 99% of the cases. Once valgrind is fixed, this flag will " "most likely be removed.")
void UniversalPrintArray(const char *begin, size_t len, ostream *os)
Definition: gtest-all.cc:11316
const char * original_working_dir() const
eval< find_if_impl::find_if_< List, Pred, 0 > > find_if
Definition: typelist.h:657
GTEST_API_ void ReportInvalidTestSuiteType(const char *test_suite_name, CodeLocation code_location)
GTEST_API_ std::string AppendUserMessage(const std::string &gtest_msg, const Message &user_msg)
UInt32 Generate(UInt32 range)
GTEST_API_ AssertionResult CmpHelperSTREQ(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
char ToUpper(char ch)
Definition: gtest.h:2262
GTEST_API_ AssertionResult FloatLE(const char *expr1, const char *expr2, float val1, float val2)
AssertHelper(TestPartResult::Type type, const char *file, int line, const char *message)
#define GTEST_ATTRIBUTE_UNUSED_
Definition: gtest.h:899
void FlushInfoLog()
Definition: gtest.h:1251
#define GTEST_LOCK_EXCLUDED_(locks)
Definition: gtest.h:2515
const int kStdErrFileno
Definition: gtest-all.cc:9776
void PrintWideStringTo(const ::std::wstring &s, ostream *os)
Definition: gtest-all.cc:11448
const int kStdOutFileno
Definition: gtest-all.cc:9775
#define EXPECT_TRUE(condition)
Definition: gtest.h:16584
#define ADD_FAILURE()
Definition: gtest.h:16533
#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
Definition: gtest.h:1043
#define GTEST_FLAG_SAVER_
Definition: gtest.h:2493
GTEST_API_ std::string CreateUnifiedDiff(const std::vector< std::string > &left, const std::vector< std::string > &right, size_t context=2)
void swap(array< _Tp, _Nm > &lhs, array< _Tp, _Nm > &rhs) noexcept(noexcept(lhs.swap(rhs)))
Definition: array.h:214
FILE * FDOpen(int fd, const char *mode)
Definition: gtest.h:2356
static UnitTest * GetInstance()
#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
Definition: gtest.h:1055
char * StrDup(const char *src)
Definition: gtest.h:2328
const char * StrError(int errnum)
Definition: gtest.h:2367
std::string OutputFlagAlsoCheckEnvVar()
Definition: gtest-all.cc:10980
GTEST_API_ TypeId GetTestTypeId()
#define GTEST_PROJECT_URL_
Definition: gtest.h:518
std::string StripTrailingSpaces(std::string str)
Definition: gtest.h:2266
bool_< List::empty()> empty
Definition: typelist.h:140
std::string GetString() const
const char kPathSeparator
Definition: gtest-all.cc:9246
constexpr _Tp & get(array< _Tp, _Nm > &arr) noexcept
Definition: array.h:220