1 // Copyright 2018 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "chrome/chrome_cleaner/os/initializer.h"
6 
7 #include <utility>
8 
9 #include "base/command_line.h"
10 #include "base/logging.h"
11 #include "base/rand_util.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/synchronization/waitable_event.h"
14 #include "base/win/scoped_handle.h"
15 #include "base/win/win_util.h"
16 #include "chrome/chrome_cleaner/constants/chrome_cleaner_switches.h"
17 #include "chrome/chrome_cleaner/os/disk_util.h"
18 #include "chrome/chrome_cleaner/os/pre_fetched_paths.h"
19 
20 namespace chrome_cleaner {
21 
22 namespace {
23 
SignalInitializationDone()24 std::unique_ptr<base::WaitableEvent> SignalInitializationDone() {
25   base::win::ScopedHandle init_done_notifier;
26 
27   base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
28   uint32_t handle = 0;
29   if (command_line->HasSwitch(kInitDoneNotifierSwitch) &&
30       base::StringToUint(
31           command_line->GetSwitchValueNative(kInitDoneNotifierSwitch),
32           &handle)) {
33     init_done_notifier.Set(base::win::Uint32ToHandle(handle));
34   }
35 
36   std::unique_ptr<base::WaitableEvent> notifier_event;
37   if (init_done_notifier.IsValid()) {
38     notifier_event.reset(
39         new base::WaitableEvent(std::move(init_done_notifier)));
40 
41     // Wake up the test that is waiting on this event.
42     notifier_event->Signal();
43   }
44   return notifier_event;
45 }
46 
47 }  // namespace
48 
InitializeOSUtils()49 bool InitializeOSUtils() {
50   chrome_cleaner::InitializeDiskUtil();
51 
52   if (!chrome_cleaner::PreFetchedPaths::GetInstance()->Initialize()) {
53     LOG(ERROR) << "PreFetchedPaths failed to initialize";
54     return false;
55   }
56 
57   // Call into the random number generator to initialize it. This must be done
58   // once before lowering the token in the sandbox target process.
59   ANALYZER_ALLOW_UNUSED(base::RandUint64());
60 
61   return true;
62 }
63 
NotifyInitializationDone()64 void NotifyInitializationDone() {
65   SignalInitializationDone();
66 }
67 
NotifyInitializationDoneForTesting()68 void NotifyInitializationDoneForTesting() {
69   std::unique_ptr<base::WaitableEvent> notifier_event =
70       SignalInitializationDone();
71 
72   if (notifier_event) {
73     // The event has ResetPolicy AUTOMATIC, so after the test is woken up it is
74     // immediately reset. Wait at most 5 seconds for the test to signal that
75     // it's ready using the same event before continuing. If the test takes
76     // longer than that stop waiting to prevent hangs.
77     notifier_event->TimedWait(base::TimeDelta::FromSeconds(5));
78   }
79 }
80 
81 }  // namespace chrome_cleaner
82