summaryrefslogtreecommitdiffstats
path: root/components/browser_watcher/window_hang_monitor_win_unittest.cc
blob: ada914f76ae82f50f85b4287086d2aca7cf424cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/browser_watcher/window_hang_monitor_win.h"

#include <vector>

#include "base/base_switches.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/process/launch.h"
#include "base/process/process.h"
#include "base/process/process_handle.h"
#include "base/run_loop.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/multiprocess_test.h"
#include "base/threading/thread.h"
#include "base/win/message_window.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"

namespace browser_watcher {

namespace {

// Simulates a process that never opens a window.
MULTIPROCESS_TEST_MAIN(NoWindowChild) {
  ::Sleep(INFINITE);
  return 0;
}

// Manages a WindowHangMonitor that lives on a background thread.
class HangMonitorThread {
 public:
  // Instantiates the background thread.
  HangMonitorThread()
      : event_received_(false, false),
        event_(WindowHangMonitor::WINDOW_NOT_FOUND),
        thread_("HangMonitorThread") {}

  ~HangMonitorThread() {
    if (hang_monitor_.get())
      DestroyWatcher();
  }

  // Starts the background thread and the monitor to observe the window named
  // |window_name| in |process|. Blocks until the monitor has been initialized.
  bool Start(base::Process process, const base::string16& window_name) {
    if (!thread_.StartWithOptions(
            base::Thread::Options(base::MessageLoop::TYPE_UI, 0))) {
      return false;
    }

    base::WaitableEvent complete(false, false);
    if (!thread_.task_runner()->PostTask(
            FROM_HERE, base::Bind(&HangMonitorThread::StartupOnThread,
                                  base::Unretained(this), window_name,
                                  base::Passed(process.Pass()),
                                  base::Unretained(&complete)))) {
      return false;
    }

    complete.Wait();

    return true;
  }

  // Returns true if a window event is detected within |timeout|.
  bool TimedWaitForEvent(base::TimeDelta timeout) {
    return event_received_.TimedWait(timeout);
  }

  // Blocks indefinitely for a window event and returns it.
  WindowHangMonitor::WindowEvent WaitForEvent() {
    event_received_.Wait();
    return event_;
  }

  // Destroys the monitor and stops the background thread. Blocks until the
  // operation completes.
  void DestroyWatcher() {
    thread_.task_runner()->PostTask(
        FROM_HERE, base::Bind(&HangMonitorThread::ShutdownOnThread,
                              base::Unretained(this)));
    // This will block until the above-posted task completes.
    thread_.Stop();
  }

 private:
  // Invoked when the monitor signals an event. Unblocks a call to
  // TimedWaitForEvent or WaitForEvent.
  void EventCallback(WindowHangMonitor::WindowEvent event) {
    if (event_received_.IsSignaled())
      ADD_FAILURE() << "Multiple calls to EventCallback.";
    event_ = event;
    event_received_.Signal();
  }

  // Initializes the WindowHangMonitor to observe the window named |window_name|
  // in |process|. Signals |complete| when done.
  void StartupOnThread(const base::string16& window_name,
                       base::Process process,
                       base::WaitableEvent* complete) {
    hang_monitor_.reset(new WindowHangMonitor(
        base::TimeDelta::FromMilliseconds(100),
        base::TimeDelta::FromMilliseconds(100),
        base::Bind(&HangMonitorThread::EventCallback, base::Unretained(this))));
    hang_monitor_->Initialize(process.Pass(), window_name);
    complete->Signal();
  }

  // Destroys the WindowHangMonitor.
  void ShutdownOnThread() { hang_monitor_.reset(); }

  // The detected event. Invalid if |event_received_| has not been signaled.
  WindowHangMonitor::WindowEvent event_;
  // Indicates that |event_| has been assigned in response to a callback from
  // the WindowHangMonitor.
  base::WaitableEvent event_received_;
  // The WindowHangMonitor under test.
  scoped_ptr<WindowHangMonitor> hang_monitor_;
  // The background thread.
  base::Thread thread_;

  DISALLOW_COPY_AND_ASSIGN(HangMonitorThread);
};

class WindowHangMonitorTest : public testing::Test {
 public:
  WindowHangMonitorTest()
      : ping_event_(false, false),
        pings_(0),
        window_thread_("WindowHangMonitorTest window_thread") {}

  void SetUp() override {
    // Pick a window name unique to this process.
    window_name_ = base::StringPrintf(L"WindowHanMonitorTest-%d",
                                      base::GetCurrentProcId());
    ASSERT_TRUE(window_thread_.StartWithOptions(
        base::Thread::Options(base::MessageLoop::TYPE_UI, 0)));
  }

  void TearDown() override {
    DeleteMessageWindow();
    window_thread_.Stop();
  }

  void CreateMessageWindow() {
    bool succeeded = false;
    base::WaitableEvent created(true, false);
    ASSERT_TRUE(window_thread_.task_runner()->PostTask(
        FROM_HERE,
        base::Bind(&WindowHangMonitorTest::CreateMessageWindowInWorkerThread,
                   base::Unretained(this), window_name_, &succeeded,
                   &created)));
    created.Wait();
    ASSERT_TRUE(succeeded);
  }

  void DeleteMessageWindow() {
    base::WaitableEvent deleted(true, false);
    window_thread_.task_runner()->PostTask(
        FROM_HERE,
        base::Bind(&WindowHangMonitorTest::DeleteMessageWindowInWorkerThread,
                   base::Unretained(this), &deleted));
    deleted.Wait();
  }

  void WaitForPing() {
    while (true) {
      {
        base::AutoLock auto_lock(ping_lock_);
        if (pings_) {
          ping_event_.Reset();
          --pings_;
          return;
        }
      }
      ping_event_.Wait();
    }
  }

  HangMonitorThread& monitor_thread() { return monitor_thread_; }

  const base::win::MessageWindow* message_window() const {
    return message_window_.get();
  }

  const base::string16& window_name() const { return window_name_; }

  base::Thread* window_thread() { return &window_thread_; }

 private:
  bool MessageCallback(UINT message,
                       WPARAM wparam,
                       LPARAM lparam,
                       LRESULT* result) {
    EXPECT_EQ(window_thread_.message_loop(), base::MessageLoop::current());
    if (message == WM_NULL) {
      base::AutoLock auto_lock(ping_lock_);
      ++pings_;
      ping_event_.Signal();
    }

    return false;  // Pass through to DefWindowProc.
  }

  void CreateMessageWindowInWorkerThread(const base::string16& name,
                                         bool* success,
                                         base::WaitableEvent* created) {
    message_window_.reset(new base::win::MessageWindow);
    *success = message_window_->CreateNamed(
        base::Bind(&WindowHangMonitorTest::MessageCallback,
                   base::Unretained(this)),
        name);
    created->Signal();
  }

  void DeleteMessageWindowInWorkerThread(base::WaitableEvent* deleted) {
    message_window_.reset();
    if (deleted)
      deleted->Signal();
  }

  HangMonitorThread monitor_thread_;
  scoped_ptr<base::win::MessageWindow> message_window_;
  base::string16 window_name_;
  base::Lock ping_lock_;
  base::WaitableEvent ping_event_;
  size_t pings_;
  base::Thread window_thread_;

  DISALLOW_COPY_AND_ASSIGN(WindowHangMonitorTest);
};

}  // namespace

TEST_F(WindowHangMonitorTest, NoWindow) {
  base::CommandLine child_command_line =
      base::GetMultiProcessTestChildBaseCommandLine();
  child_command_line.AppendSwitchASCII(switches::kTestChildProcess,
                                       "NoWindowChild");
  base::Process process =
      base::LaunchProcess(child_command_line, base::LaunchOptions());
  ASSERT_TRUE(process.IsValid());

  base::ScopedClosureRunner terminate_process_runner(
      base::Bind(base::IgnoreResult(&base::Process::Terminate),
                 base::Unretained(&process), 1, true));

  monitor_thread().Start(process.Duplicate(), window_name());

  ASSERT_FALSE(monitor_thread().TimedWaitForEvent(
      base::TimeDelta::FromMilliseconds(150)));

  terminate_process_runner.Reset();

  ASSERT_EQ(WindowHangMonitor::WINDOW_NOT_FOUND,
            monitor_thread().WaitForEvent());

  ASSERT_FALSE(monitor_thread().TimedWaitForEvent(
      base::TimeDelta::FromMilliseconds(150)));
}

TEST_F(WindowHangMonitorTest, WindowBeforeWatcher) {
  CreateMessageWindow();

  monitor_thread().Start(base::Process::Current(), window_name());

  WaitForPing();

  ASSERT_FALSE(monitor_thread().TimedWaitForEvent(
      base::TimeDelta::FromMilliseconds(150)));
}

TEST_F(WindowHangMonitorTest, WindowBeforeDestroy) {
  CreateMessageWindow();

  monitor_thread().Start(base::Process::Current(), window_name());

  WaitForPing();

  ASSERT_FALSE(monitor_thread().TimedWaitForEvent(
      base::TimeDelta::FromMilliseconds(150)));

  monitor_thread().DestroyWatcher();

  ASSERT_FALSE(monitor_thread().TimedWaitForEvent(base::TimeDelta()));
}

TEST_F(WindowHangMonitorTest, NoWindowBeforeDestroy) {
  monitor_thread().Start(base::Process::Current(), window_name());

  ASSERT_FALSE(monitor_thread().TimedWaitForEvent(
      base::TimeDelta::FromMilliseconds(150)));
  monitor_thread().DestroyWatcher();

  ASSERT_FALSE(monitor_thread().TimedWaitForEvent(base::TimeDelta()));
}

TEST_F(WindowHangMonitorTest, WatcherBeforeWindow) {
  monitor_thread().Start(base::Process::Current(), window_name());

  ASSERT_FALSE(monitor_thread().TimedWaitForEvent(
      base::TimeDelta::FromMilliseconds(150)));

  CreateMessageWindow();

  WaitForPing();

  ASSERT_FALSE(monitor_thread().TimedWaitForEvent(
      base::TimeDelta::FromMilliseconds(150)));
}

TEST_F(WindowHangMonitorTest, DetectsWindowDisappearance) {
  CreateMessageWindow();

  monitor_thread().Start(base::Process::Current(), window_name());

  WaitForPing();

  DeleteMessageWindow();

  ASSERT_EQ(WindowHangMonitor::WINDOW_VANISHED,
            monitor_thread().WaitForEvent());

  ASSERT_FALSE(monitor_thread().TimedWaitForEvent(
      base::TimeDelta::FromMilliseconds(150)));
}

TEST_F(WindowHangMonitorTest, DetectsWindowNameChange) {
  // This test changes the title of the message window as a proxy for what
  // happens if the window handle is reused for a different purpose. The latter
  // is impossible to test in a deterministic fashion.
  CreateMessageWindow();

  monitor_thread().Start(base::Process::Current(), window_name());

  ASSERT_FALSE(monitor_thread().TimedWaitForEvent(
      base::TimeDelta::FromMilliseconds(150)));

  ASSERT_TRUE(::SetWindowText(message_window()->hwnd(), L"Gonsky"));

  ASSERT_EQ(WindowHangMonitor::WINDOW_VANISHED,
            monitor_thread().WaitForEvent());
}

TEST_F(WindowHangMonitorTest, DetectsWindowHang) {
  CreateMessageWindow();

  monitor_thread().Start(base::Process::Current(), window_name());

  ASSERT_FALSE(monitor_thread().TimedWaitForEvent(
      base::TimeDelta::FromMilliseconds(150)));

  // Block the worker thread.
  base::WaitableEvent hang(true, false);

  window_thread()->message_loop_proxy()->PostTask(
      FROM_HERE,
      base::Bind(&base::WaitableEvent::Wait, base::Unretained(&hang)));

  EXPECT_EQ(WindowHangMonitor::WINDOW_HUNG,
            monitor_thread().WaitForEvent());

  // Unblock the worker thread.
  hang.Signal();

  ASSERT_FALSE(monitor_thread().TimedWaitForEvent(
      base::TimeDelta::FromMilliseconds(150)));
}

}  // namespace browser_watcher