• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 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 #include "base/win/message_window.h"
6 
7 #include <windows.h>
8 
9 #include <map>
10 #include <utility>
11 
12 #include "base/check.h"
13 #include "base/check_op.h"
14 #include "base/compiler_specific.h"
15 #include "base/lazy_instance.h"
16 #include "base/logging.h"
17 #include "base/memory/ptr_util.h"
18 #include "base/memory/raw_ref.h"
19 #include "base/no_destructor.h"
20 #include "base/process/memory.h"
21 #include "base/strings/string_util.h"
22 #include "base/thread_annotations.h"
23 #include "base/threading/thread_checker.h"
24 #include "base/threading/thread_local.h"
25 #include "base/win/current_module.h"
26 #include "base/win/resource_exhaustion.h"
27 #include "base/win/wrapped_window_proc.h"
28 
29 // To avoid conflicts with the macro from the Windows SDK...
30 #undef FindWindow
31 
32 const wchar_t kMessageWindowClassName[] = L"Chrome_MessageWindow";
33 
34 namespace {
35 
36 // This class can be accessed from multiple threads,
37 // this is handled by each thread having a different instance.
38 class MessageWindowMap {
39  public:
GetInstanceForCurrentThread()40   static MessageWindowMap& GetInstanceForCurrentThread() {
41     static base::NoDestructor<base::ThreadLocalOwnedPointer<MessageWindowMap>>
42         instance;
43     if (!instance->Get()) {
44       instance->Set(base::WrapUnique(new MessageWindowMap));
45     }
46     return *(instance->Get());
47   }
48 
49   MessageWindowMap(const MessageWindowMap&) = delete;
50   MessageWindowMap& operator=(const MessageWindowMap&) = delete;
51 
52   // Each key should only be inserted once.
Insert(HWND hwnd,base::win::MessageWindow & message_window)53   void Insert(HWND hwnd, base::win::MessageWindow& message_window) {
54     DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
55     CHECK(map_.emplace(hwnd, message_window).second);
56   }
57 
58   // Erase should only be called on an existing key.
Erase(HWND hwnd)59   void Erase(HWND hwnd) {
60     DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
61     // Check that exactly one element is erased from the map.
62     CHECK_EQ(map_.erase(hwnd), 1u);
63   }
64 
65   // Will return nullptr if `hwnd` is not in the map.
Get(HWND hwnd) const66   base::win::MessageWindow* Get(HWND hwnd) const {
67     DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
68     if (auto search = map_.find(hwnd); search != map_.end()) {
69       return &(search->second.get());
70     }
71     return nullptr;
72   }
73 
74  private:
75   MessageWindowMap() = default;
76   THREAD_CHECKER(thread_checker_);
77   std::map<HWND, const raw_ref<base::win::MessageWindow>> map_
78       GUARDED_BY_CONTEXT(thread_checker_);
79 };
80 
81 }  // namespace
82 
83 namespace base {
84 namespace win {
85 
86 // Used along with LazyInstance to register a window class for message-only
87 // windows created by MessageWindow.
88 class MessageWindow::WindowClass {
89  public:
90   WindowClass();
91 
92   WindowClass(const WindowClass&) = delete;
93   WindowClass& operator=(const WindowClass&) = delete;
94 
95   ~WindowClass();
96 
atom()97   ATOM atom() { return atom_; }
instance()98   HINSTANCE instance() { return instance_; }
99 
100  private:
101   ATOM atom_ = 0;
102   HINSTANCE instance_ = CURRENT_MODULE();
103 };
104 
105 static LazyInstance<MessageWindow::WindowClass>::DestructorAtExit
106     g_window_class = LAZY_INSTANCE_INITIALIZER;
107 
WindowClass()108 MessageWindow::WindowClass::WindowClass() {
109   WNDCLASSEX window_class;
110   window_class.cbSize = sizeof(window_class);
111   window_class.style = 0;
112   window_class.lpfnWndProc = &WrappedWindowProc<WindowProc>;
113   window_class.cbClsExtra = 0;
114   window_class.cbWndExtra = 0;
115   window_class.hInstance = instance_;
116   window_class.hIcon = nullptr;
117   window_class.hCursor = nullptr;
118   window_class.hbrBackground = nullptr;
119   window_class.lpszMenuName = nullptr;
120   window_class.lpszClassName = kMessageWindowClassName;
121   window_class.hIconSm = nullptr;
122   atom_ = RegisterClassEx(&window_class);
123   if (atom_ == 0) {
124     PLOG(ERROR)
125         << "Failed to register the window class for a message-only window";
126     OnResourceExhausted();
127   }
128 }
129 
~WindowClass()130 MessageWindow::WindowClass::~WindowClass() {
131   if (atom_ != 0) {
132     BOOL result = UnregisterClass(MAKEINTATOM(atom_), instance_);
133     // Hitting this DCHECK usually means that some MessageWindow objects were
134     // leaked. For example not calling
135     // ui::Clipboard::DestroyClipboardForCurrentThread() results in a leaked
136     // MessageWindow.
137     DCHECK(result);
138   }
139 }
140 
141 MessageWindow::MessageWindow() = default;
142 
~MessageWindow()143 MessageWindow::~MessageWindow() {
144   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
145 
146   if (window_ != nullptr) {
147     BOOL result = DestroyWindow(window_);
148     DCHECK(result);
149   }
150 }
151 
Create(MessageCallback message_callback)152 bool MessageWindow::Create(MessageCallback message_callback) {
153   return DoCreate(std::move(message_callback), nullptr);
154 }
155 
CreateNamed(MessageCallback message_callback,const std::wstring & window_name)156 bool MessageWindow::CreateNamed(MessageCallback message_callback,
157                                 const std::wstring& window_name) {
158   return DoCreate(std::move(message_callback), window_name.c_str());
159 }
160 
161 // static
FindWindow(const std::wstring & window_name)162 HWND MessageWindow::FindWindow(const std::wstring& window_name) {
163   return FindWindowEx(HWND_MESSAGE, nullptr, kMessageWindowClassName,
164                       window_name.c_str());
165 }
166 
DoCreate(MessageCallback message_callback,const wchar_t * window_name)167 bool MessageWindow::DoCreate(MessageCallback message_callback,
168                              const wchar_t* window_name) {
169   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
170   DCHECK(message_callback_.is_null());
171   DCHECK(!window_);
172 
173   message_callback_ = std::move(message_callback);
174 
175   WindowClass& window_class = g_window_class.Get();
176   window_ =
177       CreateWindow(MAKEINTATOM(window_class.atom()), window_name, 0, 0, 0, 0, 0,
178                    HWND_MESSAGE, nullptr, window_class.instance(), this);
179   if (!window_) {
180     if (::GetLastError() == ERROR_NOT_ENOUGH_MEMORY) {
181       base::TerminateBecauseOutOfMemory(0);
182     }
183     PLOG(ERROR) << "Failed to create a message-only window";
184     return false;
185   }
186 
187   return true;
188 }
189 
190 // static
WindowProc(HWND hwnd,UINT message,WPARAM wparam,LPARAM lparam)191 LRESULT CALLBACK MessageWindow::WindowProc(HWND hwnd,
192                                            UINT message,
193                                            WPARAM wparam,
194                                            LPARAM lparam) {
195   // This can be called from different threads for different windows,
196   // each thread has its own MessageWindowMap instance.
197   auto& message_window_map = MessageWindowMap::GetInstanceForCurrentThread();
198   MessageWindow* self = message_window_map.Get(hwnd);
199 
200   // CreateWindow will send a WM_CREATE message during window creation.
201   if (!self && message == WM_CREATE) [[unlikely]] {
202     CREATESTRUCT* const cs = reinterpret_cast<CREATESTRUCT*>(lparam);
203     self = reinterpret_cast<MessageWindow*>(cs->lpCreateParams);
204 
205     // Tell the MessageWindow instance the HWND that CreateWindow has produced.
206     self->window_ = hwnd;
207 
208     // Associate the MessageWindow instance with the HWND in the map.
209     message_window_map.Insert(hwnd, *self);
210   }
211 
212   if (!self) [[unlikely]] {
213     return DefWindowProc(hwnd, message, wparam, lparam);
214   }
215 
216   LRESULT message_result = {};
217   if (!self->message_callback_.Run(message, wparam, lparam, &message_result)) {
218     message_result = DefWindowProc(hwnd, message, wparam, lparam);
219   }
220 
221   if (message == WM_DESTROY) [[unlikely]] {
222     // Tell the MessageWindow instance that it no longer has an HWND.
223     self->window_ = nullptr;
224 
225     // Remove this HWND's MessageWindow from the map since it is going away.
226     message_window_map.Erase(hwnd);
227   }
228 
229   return message_result;
230 }
231 
232 }  // namespace win
233 }  // namespace base
234