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 // Provides a way to handle exceptions that happen while a WindowProc is
6 // running. The behavior of exceptions generated inside a WindowProc is OS
7 // dependent, but it is possible that the OS just ignores the exception and
8 // continues execution, which leads to unpredictable behavior for Chrome.
9
10 #ifndef BASE_WIN_WRAPPED_WINDOW_PROC_H_
11 #define BASE_WIN_WRAPPED_WINDOW_PROC_H_
12
13 #include <windows.h>
14
15 #include "base/base_export.h"
16
17 namespace base {
18 namespace win {
19
20 // An exception filter for a WindowProc. The return value determines how the
21 // exception should be handled, following standard SEH rules. However, the
22 // expected behavior for this function is to not return, instead of returning
23 // EXCEPTION_EXECUTE_HANDLER or similar, given that in general we are not
24 // prepared to handle exceptions.
25 using WinProcExceptionFilter = int __cdecl (*)(EXCEPTION_POINTERS* info);
26
27 // Sets the filter to deal with exceptions inside a WindowProc. Returns the old
28 // exception filter, if any.
29 // This function should be called before any window is created.
30 BASE_EXPORT WinProcExceptionFilter
31 SetWinProcExceptionFilter(WinProcExceptionFilter filter);
32
33 // Calls the registered exception filter.
34 BASE_EXPORT int CallExceptionFilter(EXCEPTION_POINTERS* info);
35
36 // Initializes the WNDCLASSEX structure |*class_out| to be passed to
37 // RegisterClassEx() making sure that it is associated with the module
38 // containing the window procedure.
39 BASE_EXPORT void InitializeWindowClass(const wchar_t* class_name,
40 WNDPROC window_proc,
41 UINT style,
42 int class_extra,
43 int window_extra,
44 HCURSOR cursor,
45 HBRUSH background,
46 const wchar_t* menu_name,
47 HICON large_icon,
48 HICON small_icon,
49 WNDCLASSEX* class_out);
50
51 // Wrapper that supplies a standard exception frame for the provided WindowProc.
52 // The normal usage is something like this:
53 //
54 // LRESULT CALLBACK MyWinProc(HWND hwnd, UINT message,
55 // WPARAM wparam, LPARAM lparam) {
56 // // Do Something.
57 // }
58 //
59 // ...
60 //
61 // WNDCLASSEX wc = {0};
62 // wc.lpfnWndProc = WrappedWindowProc<MyWinProc>;
63 // wc.lpszClassName = class_name;
64 // ...
65 // RegisterClassEx(&wc);
66 //
67 // CreateWindowW(class_name, window_name, ...
68 //
69 template <WNDPROC proc>
70 LRESULT CALLBACK
WrappedWindowProc(HWND hwnd,UINT message,WPARAM wparam,LPARAM lparam)71 WrappedWindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
72 LRESULT rv = 0;
73 __try {
74 rv = proc(hwnd, message, wparam, lparam);
75 } __except (CallExceptionFilter(GetExceptionInformation())) {
76 }
77 return rv;
78 }
79
80 } // namespace win
81 } // namespace base
82
83 #endif // BASE_WIN_WRAPPED_WINDOW_PROC_H_
84