• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9 
10 #include "base/test/test_suite.h"
11 
12 #include <signal.h>
13 
14 #include <algorithm>
15 #include <memory>
16 #include <string>
17 #include <string_view>
18 #include <vector>
19 
20 #include "base/at_exit.h"
21 #include "base/base_paths.h"
22 #include "base/base_switches.h"
23 #include "base/command_line.h"
24 #include "base/debug/asan_service.h"
25 #include "base/debug/debugger.h"
26 #include "base/debug/profiler.h"
27 #include "base/debug/stack_trace.h"
28 #include "base/feature_list.h"
29 #include "base/files/file_path.h"
30 #include "base/files/file_util.h"
31 #include "base/functional/bind.h"
32 #include "base/i18n/icu_util.h"
33 #include "base/i18n/rtl.h"
34 #include "base/logging.h"
35 #include "base/memory/ptr_util.h"
36 #include "base/memory/raw_ptr.h"
37 #include "base/metrics/statistics_recorder.h"
38 #include "base/no_destructor.h"
39 #include "base/path_service.h"
40 #include "base/process/launch.h"
41 #include "base/process/memory.h"
42 #include "base/process/process.h"
43 #include "base/process/process_handle.h"
44 #include "base/strings/strcat.h"
45 #include "base/strings/utf_string_conversions.h"
46 #include "base/task/thread_pool/thread_pool_instance.h"
47 #include "base/test/gtest_xml_unittest_result_printer.h"
48 #include "base/test/gtest_xml_util.h"
49 #include "base/test/icu_test_util.h"
50 #include "base/test/launcher/unit_test_launcher.h"
51 #include "base/test/mock_entropy_provider.h"
52 #include "base/test/multiprocess_test.h"
53 #include "base/test/scoped_feature_list.h"
54 #include "base/test/scoped_run_loop_timeout.h"
55 #include "base/test/test_suite_helper.h"
56 #include "base/test/test_switches.h"
57 #include "base/test/test_timeouts.h"
58 #include "base/threading/platform_thread.h"
59 #include "base/time/time.h"
60 #include "base/tracing_buildflags.h"
61 #include "build/build_config.h"
62 #include "partition_alloc/buildflags.h"
63 #include "testing/gmock/include/gmock/gmock.h"
64 #include "testing/gtest/include/gtest/gtest.h"
65 #include "testing/libfuzzer/fuzztest_init_helper.h"
66 #include "testing/multiprocess_func_list.h"
67 
68 #if BUILDFLAG(IS_APPLE)
69 #include "base/apple/scoped_nsautorelease_pool.h"
70 #endif  // BUILDFLAG(IS_APPLE)
71 
72 #if BUILDFLAG(IS_IOS)
73 #include "base/test/test_listener_ios.h"
74 #include "base/test/test_support_ios.h"
75 #else
76 #include "base/strings/string_util.h"
77 #include "third_party/icu/source/common/unicode/uloc.h"
78 #endif
79 
80 #if BUILDFLAG(IS_ANDROID)
81 #include "base/test/test_support_android.h"
82 #endif
83 
84 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
85 #include "third_party/test_fonts/fontconfig/fontconfig_util_linux.h"
86 #endif
87 
88 #if BUILDFLAG(IS_FUCHSIA)
89 #include "base/fuchsia/system_info.h"
90 #endif
91 
92 #if BUILDFLAG(IS_WIN)
93 #if defined(_DEBUG)
94 #include <crtdbg.h>
95 #endif  // _DEBUG
96 #include <windows.h>
97 
98 #include "base/debug/handle_hooks_win.h"
99 #endif  // BUILDFLAG(IS_WIN)
100 
101 #if PA_BUILDFLAG(USE_PARTITION_ALLOC)
102 #include "base/allocator/partition_alloc_support.h"
103 #endif  // PA_BUILDFLAG(USE_PARTITION_ALLOC)
104 
105 #if GTEST_HAS_DEATH_TEST
106 #include "base/gtest_prod_util.h"
107 #endif
108 
109 namespace base {
110 
111 namespace {
112 
113 // Returns true if the test is marked as "MAYBE_".
114 // When using different prefixes depending on platform, we use MAYBE_ and
115 // preprocessor directives to replace MAYBE_ with the target prefix.
IsMarkedMaybe(const testing::TestInfo & test)116 bool IsMarkedMaybe(const testing::TestInfo& test) {
117   return strncmp(test.name(), "MAYBE_", 6) == 0;
118 }
119 
120 class DisableMaybeTests : public testing::EmptyTestEventListener {
121  public:
OnTestStart(const testing::TestInfo & test_info)122   void OnTestStart(const testing::TestInfo& test_info) override {
123     ASSERT_FALSE(IsMarkedMaybe(test_info))
124         << "Probably the OS #ifdefs don't include all of the necessary "
125            "platforms.\nPlease ensure that no tests have the MAYBE_ prefix "
126            "after the code is preprocessed.";
127   }
128 };
129 
130 class ResetCommandLineBetweenTests : public testing::EmptyTestEventListener {
131  public:
ResetCommandLineBetweenTests()132   ResetCommandLineBetweenTests() : old_command_line_(CommandLine::NO_PROGRAM) {
133     // TODO(crbug.com/40053215): Remove this after A/B test is done.
134     // Workaround a test-specific race conditon with StatisticsRecorder lock
135     // initialization checking CommandLine by ensuring it's created here (when
136     // we start the test process), rather than in some arbitrary test. This
137     // prevents a race with OnTestEnd().
138     StatisticsRecorder::FindHistogram("Dummy");
139   }
140 
141   ResetCommandLineBetweenTests(const ResetCommandLineBetweenTests&) = delete;
142   ResetCommandLineBetweenTests& operator=(const ResetCommandLineBetweenTests&) =
143       delete;
144 
OnTestStart(const testing::TestInfo & test_info)145   void OnTestStart(const testing::TestInfo& test_info) override {
146     old_command_line_ = *CommandLine::ForCurrentProcess();
147   }
148 
OnTestEnd(const testing::TestInfo & test_info)149   void OnTestEnd(const testing::TestInfo& test_info) override {
150     *CommandLine::ForCurrentProcess() = old_command_line_;
151   }
152 
153  private:
154   CommandLine old_command_line_;
155 };
156 
157 // Initializes a base::test::ScopedFeatureList for each individual test, which
158 // involves a FeatureList and a FieldTrialList, such that unit test don't need
159 // to initialize them manually.
160 class FeatureListScopedToEachTest : public testing::EmptyTestEventListener {
161  public:
162   FeatureListScopedToEachTest() = default;
163   ~FeatureListScopedToEachTest() override = default;
164 
165   FeatureListScopedToEachTest(const FeatureListScopedToEachTest&) = delete;
166   FeatureListScopedToEachTest& operator=(const FeatureListScopedToEachTest&) =
167       delete;
168 
OnTestStart(const testing::TestInfo & test_info)169   void OnTestStart(const testing::TestInfo& test_info) override {
170     test::InitScopedFeatureListForTesting(scoped_feature_list_);
171 
172     // TODO(crbug.com/40255771): Enable PartitionAlloc in unittests with
173     // ASAN.
174 #if PA_BUILDFLAG(USE_PARTITION_ALLOC) && !defined(ADDRESS_SANITIZER)
175     allocator::PartitionAllocSupport::Get()->ReconfigureAfterFeatureListInit(
176         "",
177         /*configure_dangling_pointer_detector=*/true);
178 #endif
179   }
180 
OnTestEnd(const testing::TestInfo & test_info)181   void OnTestEnd(const testing::TestInfo& test_info) override {
182     scoped_feature_list_.Reset();
183   }
184 
185  private:
186   test::ScopedFeatureList scoped_feature_list_;
187 };
188 
189 class CheckForLeakedGlobals : public testing::EmptyTestEventListener {
190  public:
191   CheckForLeakedGlobals() = default;
192 
193   CheckForLeakedGlobals(const CheckForLeakedGlobals&) = delete;
194   CheckForLeakedGlobals& operator=(const CheckForLeakedGlobals&) = delete;
195 
196   // Check for leaks in individual tests.
OnTestStart(const testing::TestInfo & test)197   void OnTestStart(const testing::TestInfo& test) override {
198     feature_list_set_before_test_ = FeatureList::GetInstance();
199     thread_pool_set_before_test_ = ThreadPoolInstance::Get();
200   }
OnTestEnd(const testing::TestInfo & test)201   void OnTestEnd(const testing::TestInfo& test) override {
202     DCHECK_EQ(feature_list_set_before_test_, FeatureList::GetInstance())
203         << " in test " << test.test_suite_name() << "." << test.name();
204     DCHECK_EQ(thread_pool_set_before_test_, ThreadPoolInstance::Get())
205         << " in test " << test.test_suite_name() << "." << test.name();
206     feature_list_set_before_test_ = nullptr;
207     thread_pool_set_before_test_ = nullptr;
208   }
209 
210   // Check for leaks in test suites (consisting of one or more tests).
OnTestSuiteStart(const testing::TestSuite & test_suite)211   void OnTestSuiteStart(const testing::TestSuite& test_suite) override {
212     feature_list_set_before_suite_ = FeatureList::GetInstance();
213     thread_pool_set_before_suite_ = ThreadPoolInstance::Get();
214   }
OnTestSuiteEnd(const testing::TestSuite & test_suite)215   void OnTestSuiteEnd(const testing::TestSuite& test_suite) override {
216     DCHECK_EQ(feature_list_set_before_suite_, FeatureList::GetInstance())
217         << " in suite " << test_suite.name();
218     DCHECK_EQ(thread_pool_set_before_suite_, ThreadPoolInstance::Get())
219         << " in suite " << test_suite.name();
220     feature_list_set_before_suite_ = nullptr;
221     thread_pool_set_before_suite_ = nullptr;
222   }
223 
224  private:
225   raw_ptr<FeatureList, DanglingUntriaged> feature_list_set_before_test_ =
226       nullptr;
227   raw_ptr<FeatureList> feature_list_set_before_suite_ = nullptr;
228   raw_ptr<ThreadPoolInstance> thread_pool_set_before_test_ = nullptr;
229   raw_ptr<ThreadPoolInstance> thread_pool_set_before_suite_ = nullptr;
230 };
231 
232 // iOS: base::Process is not available.
233 // macOS: Tests may run at background priority locally (crbug.com/1358639#c6) or
234 // on bots (crbug.com/931721#c7).
235 #if !BUILDFLAG(IS_APPLE)
236 class CheckProcessPriority : public testing::EmptyTestEventListener {
237  public:
CheckProcessPriority()238   CheckProcessPriority() { CHECK(!IsProcessBackgrounded()); }
239 
240   CheckProcessPriority(const CheckProcessPriority&) = delete;
241   CheckProcessPriority& operator=(const CheckProcessPriority&) = delete;
242 
OnTestStart(const testing::TestInfo & test)243   void OnTestStart(const testing::TestInfo& test) override {
244     EXPECT_FALSE(IsProcessBackgrounded());
245   }
OnTestEnd(const testing::TestInfo & test)246   void OnTestEnd(const testing::TestInfo& test) override {
247     EXPECT_FALSE(IsProcessBackgrounded());
248   }
249 
250  private:
IsProcessBackgrounded() const251   bool IsProcessBackgrounded() const {
252     return Process::Current().GetPriority() == Process::Priority::kBestEffort;
253   }
254 };
255 #endif  // !BUILDFLAG(IS_APPLE)
256 
GetProfileName()257 const std::string& GetProfileName() {
258   static const NoDestructor<std::string> profile_name([] {
259     const CommandLine& command_line = *CommandLine::ForCurrentProcess();
260     if (command_line.HasSwitch(switches::kProfilingFile))
261       return command_line.GetSwitchValueASCII(switches::kProfilingFile);
262     else
263       return std::string("test-profile-{pid}");
264   }());
265   return *profile_name;
266 }
267 
InitializeLogging()268 void InitializeLogging() {
269 #if BUILDFLAG(IS_FUCHSIA)
270   constexpr auto kLoggingDest = logging::LOG_TO_STDERR;
271 #else
272   constexpr auto kLoggingDest =
273       logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR;
274 #endif
275   CHECK(logging::InitLogging({.logging_dest = kLoggingDest}));
276 
277   // We want process and thread IDs because we may have multiple processes.
278 #if BUILDFLAG(IS_ANDROID)
279   // To view log output with IDs and timestamps use "adb logcat -v threadtime".
280   logging::SetLogItems(false, false, false, false);
281 #else
282   // We want process and thread IDs because we may have multiple processes.
283   logging::SetLogItems(true, true, false, false);
284 #endif  // !BUILDFLAG(IS_ANDROID)
285 }
286 
287 #if BUILDFLAG(IS_WIN)
288 // Handlers for invalid parameter, pure call, and abort. They generate a
289 // breakpoint to ensure that we get a call stack on these failures.
290 // These functions should be written to be unique in order to avoid confusing
291 // call stacks from /OPT:ICF function folding. Printing a unique message or
292 // returning a unique value will do this. Note that for best results they need
293 // to be unique from *all* functions in Chrome.
InvalidParameter(const wchar_t * expression,const wchar_t * function,const wchar_t * file,unsigned int line,uintptr_t reserved)294 void InvalidParameter(const wchar_t* expression,
295                       const wchar_t* function,
296                       const wchar_t* file,
297                       unsigned int line,
298                       uintptr_t reserved) {
299   // CRT printed message is sufficient.
300   __debugbreak();
301   _exit(1);
302 }
303 
PureCall()304 void PureCall() {
305   fprintf(stderr, "Pure-virtual function call. Terminating.\n");
306   __debugbreak();
307   _exit(1);
308 }
309 
AbortHandler(int signal)310 void AbortHandler(int signal) {
311   // Print EOL after the CRT abort message.
312   fprintf(stderr, "\n");
313   __debugbreak();
314 }
315 #endif
316 
317 #if GTEST_HAS_DEATH_TEST
318 // Returns a friendly message to tell developers how to see the stack traces for
319 // unexpected crashes in death test child processes. Since death tests generate
320 // stack traces as a consequence of their expected crashes and stack traces are
321 // expensive to compute, stack traces in death test child processes are
322 // suppressed unless `--with-stack-traces` is on the command line.
GetStackTraceMessage()323 std::string GetStackTraceMessage() {
324   // When Google Test launches a "threadsafe" death test's child proc, it uses
325   // `--gtest_filter` to convey the test to be run. It appendeds it to the end
326   // of the command line, so Chromium's `CommandLine` will preserve only the
327   // value of interest.
328   auto filter_switch =
329       CommandLine::ForCurrentProcess()->GetSwitchValueNative("gtest_filter");
330   return StrCat({"Stack trace suppressed; retry with `--",
331                  switches::kWithDeathTestStackTraces, " --gtest_filter=",
332 #if BUILDFLAG(IS_WIN)
333                  WideToUTF8(filter_switch)
334 #else
335                  filter_switch
336 #endif
337                      ,
338                  "`."});
339 }
340 #endif  // GTEST_HAS_DEATH_TEST
341 
342 }  // namespace
343 
RunUnitTestsUsingBaseTestSuite(int argc,char ** argv)344 int RunUnitTestsUsingBaseTestSuite(int argc, char** argv) {
345   TestSuite test_suite(argc, argv);
346   return LaunchUnitTests(argc, argv,
347                          BindOnce(&TestSuite::Run, Unretained(&test_suite)));
348 }
349 
TestSuite(int argc,char ** argv)350 TestSuite::TestSuite(int argc, char** argv) : argc_(argc), argv_(argv) {
351   PreInitialize();
352 }
353 
354 #if BUILDFLAG(IS_WIN)
TestSuite(int argc,wchar_t ** argv)355 TestSuite::TestSuite(int argc, wchar_t** argv) : argc_(argc) {
356   argv_as_strings_.reserve(argc);
357   argv_as_pointers_.reserve(argc + 1);
358   std::for_each(argv, argv + argc, [this](wchar_t* arg) {
359     argv_as_strings_.push_back(WideToUTF8(arg));
360     // Have to use .data() here to get a mutable pointer.
361     argv_as_pointers_.push_back(argv_as_strings_.back().data());
362   });
363   // `argv` is specified as containing `argc + 1` pointers, of which the last is
364   // null.
365   argv_as_pointers_.push_back(nullptr);
366   argv_ = argv_as_pointers_.data();
367   PreInitialize();
368 }
369 #endif  // BUILDFLAG(IS_WIN)
370 
~TestSuite()371 TestSuite::~TestSuite() {
372   if (initialized_command_line_)
373     CommandLine::Reset();
374 }
375 
376 // Don't add additional code to this method.  Instead add it to
377 // Initialize().  See bug 6436.
Run()378 int TestSuite::Run() {
379 #if BUILDFLAG(IS_APPLE)
380   apple::ScopedNSAutoreleasePool scoped_pool;
381 #endif
382 
383   std::string client_func =
384       CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
385           switches::kTestChildProcess);
386 
387 #if BUILDFLAG(IS_FUCHSIA)
388   // Cache the system info so individual tests do not need to worry about it.
389   // Some ProcessUtilTest cases, which use kTestChildProcess, do not pass any
390   // services, so skip this if that switch was present.
391   // This must be called before Initialize() because, for example,
392   // content::ContentTestSuite::Initialize() may use the cached values.
393   if (client_func.empty())
394     CHECK(FetchAndCacheSystemInfo());
395 #endif
396 
397   Initialize();
398 
399   // Check to see if we are being run as a client process.
400   if (!client_func.empty())
401     return multi_process_function_list::InvokeChildProcessTest(client_func);
402 
403 #if BUILDFLAG(IS_IOS)
404   test_listener_ios::RegisterTestEndListener();
405 #endif
406 
407 #if BUILDFLAG(IS_LINUX)
408   // There's no standard way to opt processes into MTE on Linux just yet,
409   // so this call explicitly opts this test into synchronous MTE mode, where
410   // pointer mismatches are detected immediately.
411   ::partition_alloc::ChangeMemoryTaggingModeForCurrentThread(
412       ::partition_alloc::TagViolationReportingMode::kSynchronous);
413 #elif BUILDFLAG(IS_ANDROID)
414     // On Android, the tests are opted into synchronous MTE mode by the
415     // memtagMode attribute in an AndroidManifest.xml file or via an `am compat`
416     // command, so and explicit call to ChangeMemoryTaggingModeForCurrentThread
417     // is not needed.
418 #endif
419 
420   int result = RunAllTests();
421 
422 #if BUILDFLAG(IS_APPLE)
423   // This MUST happen before Shutdown() since Shutdown() tears down objects that
424   // Cocoa objects use to remove themselves as observers.
425   scoped_pool.Recycle();
426 #endif
427 
428   Shutdown();
429 
430   return result;
431 }
432 
DisableCheckForThreadAndProcessPriority()433 void TestSuite::DisableCheckForThreadAndProcessPriority() {
434   DCHECK(!is_initialized_);
435   check_for_thread_and_process_priority_ = false;
436 }
437 
DisableCheckForLeakedGlobals()438 void TestSuite::DisableCheckForLeakedGlobals() {
439   DCHECK(!is_initialized_);
440   check_for_leaked_globals_ = false;
441 }
442 
UnitTestAssertHandler(const char * file,int line,std::string_view summary,std::string_view stack_trace)443 void TestSuite::UnitTestAssertHandler(const char* file,
444                                       int line,
445                                       std::string_view summary,
446                                       std::string_view stack_trace) {
447 #if BUILDFLAG(IS_ANDROID)
448   // Correlating test stdio with logcat can be difficult, so we emit this
449   // helpful little hint about what was running.  Only do this for Android
450   // because other platforms don't separate out the relevant logs in the same
451   // way.
452   const ::testing::TestInfo* const test_info =
453       ::testing::UnitTest::GetInstance()->current_test_info();
454   if (test_info) {
455     LOG(ERROR) << "Currently running: " << test_info->test_suite_name() << "."
456                << test_info->name();
457     fflush(stderr);
458   }
459 #endif  // BUILDFLAG(IS_ANDROID)
460 
461   // XmlUnitTestResultPrinter inherits gtest format, where assert has summary
462   // and message. In GTest, summary is just a logged text, and message is a
463   // logged text, concatenated with stack trace of assert.
464   // Concatenate summary and stack_trace here, to pass it as a message.
465   if (printer_) {
466     const std::string summary_str(summary);
467     const std::string stack_trace_str = summary_str + std::string(stack_trace);
468     printer_->OnAssert(file, line, summary_str, stack_trace_str);
469   }
470 
471   // The logging system actually prints the message before calling the assert
472   // handler. Just exit now to avoid printing too many stack traces.
473   _exit(1);
474 }
475 
SuppressErrorDialogs()476 void TestSuite::SuppressErrorDialogs() {
477 #if BUILDFLAG(IS_WIN)
478   UINT new_flags =
479       SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX;
480 
481   // Preserve existing error mode, as discussed at
482   // http://blogs.msdn.com/oldnewthing/archive/2004/07/27/198410.aspx
483   UINT existing_flags = SetErrorMode(new_flags);
484   SetErrorMode(existing_flags | new_flags);
485 
486 #if defined(_DEBUG)
487   // Suppress the "Debug Assertion Failed" dialog.
488   // TODO(hbono): remove this code when gtest has it.
489   // http://groups.google.com/d/topic/googletestframework/OjuwNlXy5ac/discussion
490   _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
491   _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
492   _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
493   _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
494 #endif  // defined(_DEBUG)
495 
496   // See crbug.com/783040 for test code to trigger all of these failures.
497   _set_invalid_parameter_handler(InvalidParameter);
498   _set_purecall_handler(PureCall);
499   signal(SIGABRT, AbortHandler);
500 #endif  // BUILDFLAG(IS_WIN)
501 }
502 
Initialize()503 void TestSuite::Initialize() {
504   DCHECK(!is_initialized_);
505 
506   InitializeFromCommandLine(&argc_, argv_);
507 
508 #if GTEST_HAS_DEATH_TEST
509   if (::testing::internal::InDeathTestChild() &&
510       !CommandLine::ForCurrentProcess()->HasSwitch(
511           switches::kWithDeathTestStackTraces)) {
512     // For death tests using the "threadsafe" style (which includes all such
513     // tests on Windows and Fuchsia, and is the default for all Chromium tests
514     // on all platforms except Android; see `PreInitialize`),
515     //
516     // For more information, see
517     // https://github.com/google/googletest/blob/main/docs/advanced.md#death-test-styles.
518     debug::StackTrace::SuppressStackTracesWithMessageForTesting(
519         GetStackTraceMessage());
520   }
521 #endif
522 
523   // Logging must be initialized before any thread has a chance to call logging
524   // functions.
525   InitializeLogging();
526 
527   // The AsanService causes ASAN errors to emit additional information. It is
528   // helpful on its own. It is also required by ASAN BackupRefPtr when
529   // reconfiguring PartitionAlloc below.
530 #if defined(ADDRESS_SANITIZER)
531   base::debug::AsanService::GetInstance()->Initialize();
532 #endif
533 
534   // TODO(crbug.com/40250141): Enable BackupRefPtr in unittests on
535   // Android too. Same for ASAN.
536   // TODO(crbug.com/40255771): Enable PartitionAlloc in unittests with
537   // ASAN.
538 #if PA_BUILDFLAG(USE_PARTITION_ALLOC) && !defined(ADDRESS_SANITIZER)
539   allocator::PartitionAllocSupport::Get()->ReconfigureForTests();
540 #endif  // BUILDFLAG(IS_WIN)
541 
542   test::ScopedRunLoopTimeout::SetAddGTestFailureOnTimeout();
543 
544   const CommandLine* command_line = CommandLine::ForCurrentProcess();
545 #if !BUILDFLAG(IS_IOS)
546   if (command_line->HasSwitch(switches::kWaitForDebugger)) {
547     debug::WaitForDebugger(60, true);
548   }
549 #endif
550 
551 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
552   // Default the configurable DCHECK level to FATAL when running death tests'
553   // child process, so that they behave as expected.
554   // TODO(crbug.com/40120934): Remove this in favor of the codepath in
555   // FeatureList::SetInstance() when/if OnTestStart() TestEventListeners
556   // are fixed to be invoked in the child process as expected.
557   if (command_line->HasSwitch("gtest_internal_run_death_test"))
558     logging::LOGGING_DCHECK = logging::LOGGING_FATAL;
559 #endif  // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
560 
561 #if BUILDFLAG(IS_IOS)
562   InitIOSTestMessageLoop();
563 #endif  // BUILDFLAG(IS_IOS)
564 
565 #if BUILDFLAG(IS_ANDROID)
566   InitAndroidTestMessageLoop();
567 #endif  // else BUILDFLAG(IS_ANDROID)
568 
569   CHECK(debug::EnableInProcessStackDumping());
570 #if BUILDFLAG(IS_WIN)
571   RouteStdioToConsole(true);
572   // Make sure we run with high resolution timer to minimize differences
573   // between production code and test code.
574   Time::EnableHighResolutionTimer(true);
575 #endif  // BUILDFLAG(IS_WIN)
576 
577   // In some cases, we do not want to see standard error dialogs.
578   if (!debug::BeingDebugged() &&
579       !command_line->HasSwitch("show-error-dialogs")) {
580     SuppressErrorDialogs();
581     debug::SetSuppressDebugUI(true);
582     assert_handler_ = std::make_unique<logging::ScopedLogAssertHandler>(
583         BindRepeating(&TestSuite::UnitTestAssertHandler, Unretained(this)));
584   }
585 
586   // Child processes generally do not need ICU.
587   if (!command_line->HasSwitch("test-child-process")) {
588     test::InitializeICUForTesting();
589 
590     // A number of tests only work if the locale is en_US. This can be an issue
591     // on all platforms. To fix this we force the default locale to en_US. This
592     // does not affect tests that explicitly overrides the locale for testing.
593     // TODO(jshin): Should we set the locale via an OS X locale API here?
594     i18n::SetICUDefaultLocale("en_US");
595   }
596 
597 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
598   test_fonts::SetUpFontconfig();
599 #endif
600 
601   // Add TestEventListeners to enforce certain properties across tests.
602   testing::TestEventListeners& listeners =
603       testing::UnitTest::GetInstance()->listeners();
604   listeners.Append(new DisableMaybeTests);
605   listeners.Append(new ResetCommandLineBetweenTests);
606   listeners.Append(new FeatureListScopedToEachTest);
607   if (check_for_leaked_globals_)
608     listeners.Append(new CheckForLeakedGlobals);
609   if (check_for_thread_and_process_priority_) {
610 #if !BUILDFLAG(IS_APPLE)
611     listeners.Append(new CheckProcessPriority);
612 #endif
613   }
614 
615   AddTestLauncherResultPrinter();
616 
617   TestTimeouts::Initialize();
618 
619 #if BUILDFLAG(ENABLE_BASE_TRACING)
620   trace_to_file_.BeginTracingFromCommandLineOptions();
621 #endif  // BUILDFLAG(ENABLE_BASE_TRACING)
622 
623   debug::StartProfiling(GetProfileName());
624 
625   debug::VerifyDebugger();
626 
627   is_initialized_ = true;
628 }
629 
InitializeFromCommandLine(int * argc,char ** argv)630 void TestSuite::InitializeFromCommandLine(int* argc, char** argv) {
631   // CommandLine::Init() is called earlier from PreInitialize().
632   testing::InitGoogleTest(argc, argv);
633   testing::InitGoogleMock(argc, argv);
634   MaybeInitFuzztest(*argc, argv);
635 
636 #if BUILDFLAG(IS_IOS)
637   InitIOSArgs(*argc, argv);
638 #endif
639 }
640 
RunAllTests()641 int TestSuite::RunAllTests() {
642   return RUN_ALL_TESTS();
643 }
644 
Shutdown()645 void TestSuite::Shutdown() {
646   DCHECK(is_initialized_);
647 #if GTEST_HAS_DEATH_TEST
648   if (::testing::internal::InDeathTestChild()) {
649     debug::StackTrace::SuppressStackTracesWithMessageForTesting({});
650   }
651 #endif
652   debug::StopProfiling();
653 }
654 
PreInitialize()655 void TestSuite::PreInitialize() {
656   DCHECK(!is_initialized_);
657 
658 #if BUILDFLAG(IS_WIN)
659   base::debug::HandleHooks::PatchLoadedModules();
660 #endif  // BUILDFLAG(IS_WIN)
661 
662   // The default death_test_style of "fast" is a frequent source of subtle test
663   // flakiness. And on some platforms like macOS, use of system libraries after
664   // fork() but before exec() is unsafe. Using the threadsafe style by default
665   // alleviates these concerns.
666   //
667   // However, the threadsafe style does not work reliably on Android, so for
668   // that we will keep the default of "fast". For more information, see:
669   // https://crbug.com/41372437#comment12.
670   // TODO(https://crbug.com/41372437): Use "threadsafe" on Android once it is
671   // supported.
672 #if !BUILDFLAG(IS_ANDROID)
673   GTEST_FLAG_SET(death_test_style, "threadsafe");
674 #endif
675 
676 #if BUILDFLAG(IS_WIN)
677   GTEST_FLAG_SET(catch_exceptions, false);
678 #endif
679   EnableTerminationOnHeapCorruption();
680 #if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(USE_AURA)
681   // When calling native char conversion functions (e.g wrctomb) we need to
682   // have the locale set. In the absence of such a call the "C" locale is the
683   // default. In the gtk code (below) gtk_init() implicitly sets a locale.
684   setlocale(LC_ALL, "");
685   // We still need number to string conversions to be locale insensitive.
686   setlocale(LC_NUMERIC, "C");
687 #endif  // (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(USE_AURA)
688 
689   // On Android, AtExitManager is created in
690   // testing/android/native_test_wrapper.cc before main() is called.
691 #if !BUILDFLAG(IS_ANDROID)
692   at_exit_manager_ = std::make_unique<AtExitManager>();
693 #endif
694 
695   // This needs to be done during construction as some users of this class rely
696   // on the constructor to initialise the CommandLine.
697   initialized_command_line_ = CommandLine::Init(argc_, argv_);
698 
699   // Don't add additional code to this function.  Instead add it to
700   // Initialize().  See bug 6436.
701 }
702 
AddTestLauncherResultPrinter()703 void TestSuite::AddTestLauncherResultPrinter() {
704   // Only add the custom printer if requested.
705   if (!CommandLine::ForCurrentProcess()->HasSwitch(
706           switches::kTestLauncherOutput)) {
707     return;
708   }
709 
710   FilePath output_path(CommandLine::ForCurrentProcess()->GetSwitchValuePath(
711       switches::kTestLauncherOutput));
712 
713   // Do not add the result printer if output path already exists. It's an
714   // indicator there is a process printing to that file, and we're likely
715   // its child. Do not clobber the results in that case.
716   if (PathExists(output_path)) {
717     LOG(WARNING) << "Test launcher output path " << output_path.AsUTF8Unsafe()
718                  << " exists. Not adding test launcher result printer.";
719     return;
720   }
721 
722   printer_ = new XmlUnitTestResultPrinter;
723   CHECK(printer_->Initialize(output_path))
724       << "Output path is " << output_path.AsUTF8Unsafe()
725       << " and PathExists(output_path) is " << PathExists(output_path);
726   testing::TestEventListeners& listeners =
727       testing::UnitTest::GetInstance()->listeners();
728   listeners.Append(printer_);
729 }
730 
731 }  // namespace base
732