win_util.h 12 KB

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