win_util.h 13 KB

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