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