win_util.h 11 KB

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