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 // =============================================================================
6 // PLEASE READ
7 //
8 // In general, you should not be adding stuff to this file.
9 //
10 // - If your thing is only used in one place, just put it in a reasonable
11 // location in or near that one place. It's nice you want people to be able
12 // to re-use your function, but realistically, if it hasn't been necessary
13 // before after so many years of development, it's probably not going to be
14 // used in other places in the future unless you know of them now.
15 //
16 // - If your thing is used by multiple callers and is UI-related, it should
17 // probably be in app/win/ instead. Try to put it in the most specific file
18 // possible (avoiding the *_util files when practical).
19 //
20 // =============================================================================
21
22 #ifndef BASE_WIN_WIN_UTIL_H_
23 #define BASE_WIN_WIN_UTIL_H_
24
25 #include <stdint.h>
26
27 #include <optional>
28 #include <string>
29 #include <string_view>
30 #include <vector>
31
32 #include "base/base_export.h"
33 #include "base/win/windows_types.h"
34
35 struct IPropertyStore;
36 struct _tagpropertykey;
37 using PROPERTYKEY = _tagpropertykey;
38 struct tagPOINTER_DEVICE_INFO;
39 using POINTER_DEVICE_INFO = tagPOINTER_DEVICE_INFO;
40
41 namespace base {
42
43 struct NativeLibraryLoadError;
44
45 namespace win {
46
HandleToUint32(HANDLE h)47 inline uint32_t HandleToUint32(HANDLE h) {
48 // Cast through uintptr_t and then unsigned int to make the truncation to
49 // 32 bits explicit. Handles are size of-pointer but are always 32-bit values.
50 // https://msdn.microsoft.com/en-us/library/aa384203(VS.85).aspx says:
51 // 64-bit versions of Windows use 32-bit handles for interoperability.
52 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h));
53 }
54
Uint32ToHandle(uint32_t h)55 inline HANDLE Uint32ToHandle(uint32_t h) {
56 return reinterpret_cast<HANDLE>(
57 static_cast<uintptr_t>(static_cast<int32_t>(h)));
58 }
59
60 // Returns the string representing the current user sid. Does not modify
61 // |user_sid| on failure.
62 BASE_EXPORT bool GetUserSidString(std::wstring* user_sid);
63
64 // Returns false if user account control (UAC) has been disabled with the
65 // EnableLUA registry flag. Returns true if user account control is enabled.
66 // NOTE: The EnableLUA registry flag, which is ignored on Windows XP
67 // machines, might still exist and be set to 0 (UAC disabled), in which case
68 // this function will return false. You should therefore check this flag only
69 // if the OS is Vista or later.
70 BASE_EXPORT bool UserAccountControlIsEnabled();
71
72 // Sets the boolean value for a given key in given IPropertyStore.
73 BASE_EXPORT bool SetBooleanValueForPropertyStore(
74 IPropertyStore* property_store,
75 const PROPERTYKEY& property_key,
76 bool property_bool_value);
77
78 // Sets the string value for a given key in given IPropertyStore.
79 BASE_EXPORT bool SetStringValueForPropertyStore(
80 IPropertyStore* property_store,
81 const PROPERTYKEY& property_key,
82 const wchar_t* property_string_value);
83
84 // Sets the CLSID value for a given key in a given IPropertyStore.
85 BASE_EXPORT bool SetClsidForPropertyStore(IPropertyStore* property_store,
86 const PROPERTYKEY& property_key,
87 const CLSID& property_clsid_value);
88
89 // Sets the application id in given IPropertyStore. The function is used to tag
90 // application/Chrome shortcuts, and set app details for Chrome windows.
91 BASE_EXPORT bool SetAppIdForPropertyStore(IPropertyStore* property_store,
92 const wchar_t* app_id);
93
94 // Adds the specified |command| using the specified |name| to the AutoRun key.
95 // |root_key| could be HKCU or HKLM or the root of any user hive.
96 BASE_EXPORT bool AddCommandToAutoRun(HKEY root_key,
97 const std::wstring& name,
98 const std::wstring& command);
99 // Removes the command specified by |name| from the AutoRun key. |root_key|
100 // could be HKCU or HKLM or the root of any user hive.
101 BASE_EXPORT bool RemoveCommandFromAutoRun(HKEY root_key,
102 const std::wstring& name);
103
104 // Reads the command specified by |name| from the AutoRun key. |root_key|
105 // could be HKCU or HKLM or the root of any user hive. Used for unit-tests.
106 BASE_EXPORT bool ReadCommandFromAutoRun(HKEY root_key,
107 const std::wstring& name,
108 std::wstring* command);
109
110 // Sets whether to crash the process during exit. This is inspected by DLLMain
111 // and used to intercept unexpected terminations of the process (via calls to
112 // exit(), abort(), _exit(), ExitProcess()) and convert them into crashes.
113 // Note that not all mechanisms for terminating the process are covered by
114 // this. In particular, TerminateProcess() is not caught.
115 BASE_EXPORT void SetShouldCrashOnProcessDetach(bool crash);
116 BASE_EXPORT bool ShouldCrashOnProcessDetach();
117
118 // Adjusts the abort behavior so that crash reports can be generated when the
119 // process is aborted.
120 BASE_EXPORT void SetAbortBehaviorForCrashReporting();
121
122 // Checks whether the supplied |hwnd| is in Windows 10 tablet mode. Will return
123 // false on versions below 10.
124 // While tablet mode isn't officially supported in Windows 11, the function will
125 // make an attempt to inspect other signals for tablet mode.
126 BASE_EXPORT bool IsWindows10OrGreaterTabletMode(HWND hwnd);
127
128 // A tablet is a device that is touch enabled and also is being used
129 // "like a tablet". This is used by the following:
130 // 1. Metrics: To gain insight into how users use Chrome.
131 // 2. Physical keyboard presence: If a device is in tablet mode, it means
132 // that there is no physical keyboard attached.
133 // This function optionally sets the |reason| parameter to determine as to why
134 // or why not a device was deemed to be a tablet.
135 // Returns true if the user has set Windows 10 in tablet mode.
136 BASE_EXPORT bool IsTabletDevice(std::string* reason, HWND hwnd);
137
138 // Return true if the device is physically used as a tablet independently of
139 // Windows tablet mode. It checks if the device:
140 // - Is running Windows 8 or newer,
141 // - Has a touch digitizer,
142 // - Is not docked,
143 // - Has a supported rotation sensor,
144 // - Is not in laptop mode,
145 // - prefers the mobile or slate power management profile (per OEM choice), and
146 // - Is in slate mode.
147 // This function optionally sets the |reason| parameter to determine as to why
148 // or why not a device was deemed to be a tablet.
149 BASE_EXPORT bool IsDeviceUsedAsATablet(std::string* reason);
150
151 // A slate is a touch device that may have a keyboard attached. This function
152 // returns true if a keyboard is attached and optionally will set the |reason|
153 // parameter to the detection method that was used to detect the keyboard.
154 BASE_EXPORT bool IsKeyboardPresentOnSlate(HWND hwnd, std::string* reason);
155
156 // Get the size of a struct up to and including the specified member.
157 // This is necessary to set compatible struct sizes for different versions
158 // of certain Windows APIs (e.g. SystemParametersInfo).
159 #define SIZEOF_STRUCT_WITH_SPECIFIED_LAST_MEMBER(struct_name, member) \
160 offsetof(struct_name, member) + \
161 (sizeof static_cast<struct_name*>(NULL)->member)
162
163 // Returns true if the machine is enrolled to a domain.
164 BASE_EXPORT bool IsEnrolledToDomain();
165
166 // Returns true if either the device is joined to Azure Active Directory (AD) or
167 // one or more Azure AD work accounts have been added on the device. This call
168 // trigger some I/O when loading netapi32.dll to determine the management state.
169 BASE_EXPORT bool IsJoinedToAzureAD();
170
171 // Returns true if the machine is being managed by an MDM system.
172 BASE_EXPORT bool IsDeviceRegisteredWithManagement();
173
174 // Returns true if the current process can make USER32 or GDI32 calls such as
175 // CreateWindow and CreateDC. Windows 8 and above allow the kernel component
176 // of these calls to be disabled (also known as win32k lockdown) which can
177 // cause undefined behaviour such as crashes. This function can be used to
178 // guard areas of code using these calls and provide a fallback path if
179 // necessary.
180 // Because they are not always needed (and not needed at all in processes that
181 // have the win32k lockdown), USER32 and GDI32 are delayloaded. Attempts to
182 // load them in those processes will cause a crash. Any code which uses USER32
183 // or GDI32 and may run in a locked-down process MUST be guarded using this
184 // method. Before the dlls were delayloaded, method calls into USER32 and GDI32
185 // did not work, so adding calls to this method to guard them simply avoids
186 // unnecessary method calls.
187 BASE_EXPORT bool IsUser32AndGdi32Available();
188
189 // Takes a snapshot of the modules loaded in the |process|. The returned
190 // HMODULEs are not add-ref'd, so they should not be closed and may be
191 // invalidated at any time (should a module be unloaded). |process| requires
192 // the PROCESS_QUERY_INFORMATION and PROCESS_VM_READ permissions.
193 BASE_EXPORT bool GetLoadedModulesSnapshot(HANDLE process,
194 std::vector<HMODULE>* snapshot);
195
196 // Adds or removes the MICROSOFT_TABLETPENSERVICE_PROPERTY property with the
197 // TABLET_DISABLE_FLICKS & TABLET_DISABLE_FLICKFALLBACKKEYS flags in order to
198 // disable pen flick gestures for the given HWND.
199 BASE_EXPORT void EnableFlicks(HWND hwnd);
200 BASE_EXPORT void DisableFlicks(HWND hwnd);
201
202 // Enable high-DPI support for the current process.
203 BASE_EXPORT void EnableHighDPISupport();
204
205 // Returns a string representation of |rguid|.
206 BASE_EXPORT std::wstring WStringFromGUID(const ::GUID& rguid);
207
208 // Attempts to pin user32.dll to ensure it remains loaded. If it isn't loaded
209 // yet, the module will first be loaded and then the pin will be attempted. If
210 // pinning is successful, returns true. If the module cannot be loaded and/or
211 // pinned, |error| is set and the method returns false.
212 BASE_EXPORT bool PinUser32(NativeLibraryLoadError* error = nullptr);
213
214 // Gets a pointer to a function within user32.dll, if available. If user32.dll
215 // cannot be loaded or the function cannot be found, this function returns
216 // nullptr and sets |error|. Once loaded, user32.dll is pinned, and therefore
217 // the function pointer returned by this function will never change and can be
218 // cached.
219 BASE_EXPORT void* GetUser32FunctionPointer(
220 const char* function_name,
221 NativeLibraryLoadError* error = nullptr);
222
223 // Returns the name of a desktop or a window station.
224 BASE_EXPORT std::wstring GetWindowObjectName(HANDLE handle);
225
226 // Gets information about the pointer device. When successful, updates `result`
227 // and returns true, otherwise returns false without modifying `result`.
228 // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getpointerdevice
229 BASE_EXPORT bool GetPointerDevice(HANDLE device, POINTER_DEVICE_INFO& result);
230
231 // Gets information about the pointer devices attached to the system.
232 // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getpointerdevices
233 BASE_EXPORT std::optional<std::vector<POINTER_DEVICE_INFO>> GetPointerDevices();
234
235 // Registers a window to process the WM_POINTERDEVICECHANGE event, and
236 // optionally WM_POINTERDEVICEINRANGE and WM_POINTERDEVICEOUTOFRANGE events when
237 // `notify_proximity_changes` is set.
238 // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerpointerdevicenotifications
239 BASE_EXPORT bool RegisterPointerDeviceNotifications(
240 HWND hwnd,
241 bool notify_proximity_changes = false);
242
243 // Checks if the calling thread is running under a desktop with the name
244 // given by |desktop_name|. |desktop_name| is ASCII case insensitive (non-ASCII
245 // characters will be compared with exact matches).
246 BASE_EXPORT bool IsRunningUnderDesktopName(std::wstring_view desktop_name);
247
248 // Returns true if current session is a remote session.
249 BASE_EXPORT bool IsCurrentSessionRemote();
250
251 // IsAppVerifierLoaded() indicates whether Application Verifier is *already*
252 // loaded into the current process.
253 BASE_EXPORT bool IsAppVerifierLoaded();
254
255 // Allows changing the domain enrolled state for the life time of the object.
256 // The original state is restored upon destruction.
257 class BASE_EXPORT ScopedDomainStateForTesting {
258 public:
259 explicit ScopedDomainStateForTesting(bool state);
260
261 ScopedDomainStateForTesting(const ScopedDomainStateForTesting&) = delete;
262 ScopedDomainStateForTesting& operator=(const ScopedDomainStateForTesting&) =
263 delete;
264
265 ~ScopedDomainStateForTesting();
266
267 private:
268 bool initial_state_;
269 };
270
271 // Allows changing the management registration state for the life time of the
272 // object. The original state is restored upon destruction.
273 class BASE_EXPORT ScopedDeviceRegisteredWithManagementForTesting {
274 public:
275 explicit ScopedDeviceRegisteredWithManagementForTesting(bool state);
276
277 ScopedDeviceRegisteredWithManagementForTesting(
278 const ScopedDeviceRegisteredWithManagementForTesting&) = delete;
279 ScopedDeviceRegisteredWithManagementForTesting& operator=(
280 const ScopedDeviceRegisteredWithManagementForTesting&) = delete;
281
282 ~ScopedDeviceRegisteredWithManagementForTesting();
283
284 private:
285 bool initial_state_;
286 };
287
288 // Allows changing the Azure Active Directory join state for the lifetime of the
289 // object. The original state is restored upon destruction.
290 class BASE_EXPORT ScopedAzureADJoinStateForTesting {
291 public:
292 explicit ScopedAzureADJoinStateForTesting(bool state);
293 ScopedAzureADJoinStateForTesting(const ScopedAzureADJoinStateForTesting&) =
294 delete;
295 ScopedAzureADJoinStateForTesting& operator=(
296 const ScopedAzureADJoinStateForTesting&) = delete;
297 ~ScopedAzureADJoinStateForTesting();
298
299 private:
300 const bool initial_state_;
301 };
302
303 } // namespace win
304 } // namespace base
305
306 #endif // BASE_WIN_WIN_UTIL_H_
307