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.
5 #include "base/win/win_util.h"
13 #include <shobjidl.h> // Must be before propkey.
16 #include <propvarutil.h>
22 #include "base/lazy_instance.h"
23 #include "base/logging.h"
24 #include "base/memory/scoped_ptr.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/stringprintf.h"
27 #include "base/threading/thread_restrictions.h"
28 #include "base/win/metro.h"
29 #include "base/win/registry.h"
30 #include "base/win/scoped_co_mem.h"
31 #include "base/win/scoped_handle.h"
32 #include "base/win/scoped_propvariant.h"
33 #include "base/win/windows_version.h"
37 // Sets the value of |property_key| to |property_value| in |property_store|.
38 bool SetPropVariantValueForPropertyStore(
39 IPropertyStore
* property_store
,
40 const PROPERTYKEY
& property_key
,
41 const base::win::ScopedPropVariant
& property_value
) {
42 DCHECK(property_store
);
44 HRESULT result
= property_store
->SetValue(property_key
, property_value
.get());
46 result
= property_store
->Commit();
47 return SUCCEEDED(result
);
50 void __cdecl
ForceCrashOnSigAbort(int) {
54 const wchar_t kWindows8OSKRegPath
[] =
55 L
"Software\\Classes\\CLSID\\{054AAE20-4BEA-4347-8A35-64A533254A9D}"
58 // Returns true if a physical keyboard is detected on Windows 8 and up.
59 // Uses the Setup APIs to enumerate the attached keyboards and returns true
60 // if the keyboard count is more than 1. While this will work in most cases
61 // it won't work if there are devices which expose keyboard interfaces which
62 // are attached to the machine.
63 bool IsKeyboardPresentOnSlate() {
64 // This function is only supported for Windows 8 and up.
65 DCHECK(base::win::GetVersion() >= base::win::VERSION_WIN8
);
67 // This function should be only invoked for machines with touch screens.
68 if ((GetSystemMetrics(SM_DIGITIZER
) & NID_INTEGRATED_TOUCH
)
69 != NID_INTEGRATED_TOUCH
) {
73 const GUID KEYBOARD_CLASS_GUID
=
74 { 0x4D36E96B, 0xE325, 0x11CE,
75 { 0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18 } };
77 // Query for all the keyboard devices.
78 HDEVINFO device_info
=
79 SetupDiGetClassDevs(&KEYBOARD_CLASS_GUID
, NULL
, NULL
, DIGCF_PRESENT
);
80 if (device_info
== INVALID_HANDLE_VALUE
)
83 // Enumerate all keyboards and look for ACPI\PNP and HID\VID devices. If
84 // the count is more than 1 we assume that a keyboard is present. This is
85 // under the assumption that there will always be one keyboard device.
86 int keyboard_count
= 0;
87 for (DWORD i
= 0;; ++i
) {
88 SP_DEVINFO_DATA device_info_data
= { 0 };
89 device_info_data
.cbSize
= sizeof(device_info_data
);
90 if (!SetupDiEnumDeviceInfo(device_info
, i
, &device_info_data
))
93 wchar_t device_id
[MAX_DEVICE_ID_LEN
];
94 CONFIGRET status
= CM_Get_Device_ID(device_info_data
.DevInst
,
98 if (status
== CR_SUCCESS
) {
99 // To reduce the scope of the hack we only look for PNP and HID
101 if (StartsWith(L
"ACPI\\PNP", device_id
, false) ||
102 StartsWith(L
"HID\\VID", device_id
, false)) {
107 // On a Windows machine, the API's always report 1 keyboard at least
108 // regardless of whether the machine has a keyboard attached or not.
109 // The heuristic we are using is to check the count and return true
110 // if the API's report more than one keyboard. Please note that this
111 // will break for non keyboard devices which expose a keyboard PDO.
112 return keyboard_count
> 1;
120 static bool g_crash_on_process_detach
= false;
122 void GetNonClientMetrics(NONCLIENTMETRICS_XP
* metrics
) {
124 metrics
->cbSize
= sizeof(*metrics
);
125 const bool success
= !!SystemParametersInfo(
126 SPI_GETNONCLIENTMETRICS
,
128 reinterpret_cast<NONCLIENTMETRICS
*>(metrics
),
133 bool GetUserSidString(std::wstring
* user_sid
) {
134 // Get the current token.
136 if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY
, &token
))
138 base::win::ScopedHandle
token_scoped(token
);
140 DWORD size
= sizeof(TOKEN_USER
) + SECURITY_MAX_SID_SIZE
;
141 scoped_ptr
<BYTE
[]> user_bytes(new BYTE
[size
]);
142 TOKEN_USER
* user
= reinterpret_cast<TOKEN_USER
*>(user_bytes
.get());
144 if (!::GetTokenInformation(token
, TokenUser
, user
, size
, &size
))
150 // Convert the data to a string.
152 if (!::ConvertSidToStringSid(user
->User
.Sid
, &sid_string
))
155 *user_sid
= sid_string
;
157 ::LocalFree(sid_string
);
162 bool IsShiftPressed() {
163 return (::GetKeyState(VK_SHIFT
) & 0x8000) == 0x8000;
166 bool IsCtrlPressed() {
167 return (::GetKeyState(VK_CONTROL
) & 0x8000) == 0x8000;
170 bool IsAltPressed() {
171 return (::GetKeyState(VK_MENU
) & 0x8000) == 0x8000;
174 bool IsAltGrPressed() {
175 return (::GetKeyState(VK_MENU
) & 0x8000) == 0x8000 &&
176 (::GetKeyState(VK_CONTROL
) & 0x8000) == 0x8000;
179 bool UserAccountControlIsEnabled() {
180 // This can be slow if Windows ends up going to disk. Should watch this key
181 // for changes and only read it once, preferably on the file thread.
182 // http://code.google.com/p/chromium/issues/detail?id=61644
183 base::ThreadRestrictions::ScopedAllowIO allow_io
;
185 base::win::RegKey
key(HKEY_LOCAL_MACHINE
,
186 L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
189 if (key
.ReadValueDW(L
"EnableLUA", &uac_enabled
) != ERROR_SUCCESS
)
191 // Users can set the EnableLUA value to something arbitrary, like 2, which
192 // Vista will treat as UAC enabled, so we make sure it is not set to 0.
193 return (uac_enabled
!= 0);
196 bool SetBooleanValueForPropertyStore(IPropertyStore
* property_store
,
197 const PROPERTYKEY
& property_key
,
198 bool property_bool_value
) {
199 ScopedPropVariant property_value
;
200 if (FAILED(InitPropVariantFromBoolean(property_bool_value
,
201 property_value
.Receive()))) {
205 return SetPropVariantValueForPropertyStore(property_store
,
210 bool SetStringValueForPropertyStore(IPropertyStore
* property_store
,
211 const PROPERTYKEY
& property_key
,
212 const wchar_t* property_string_value
) {
213 ScopedPropVariant property_value
;
214 if (FAILED(InitPropVariantFromString(property_string_value
,
215 property_value
.Receive()))) {
219 return SetPropVariantValueForPropertyStore(property_store
,
224 bool SetAppIdForPropertyStore(IPropertyStore
* property_store
,
225 const wchar_t* app_id
) {
226 // App id should be less than 64 chars and contain no space. And recommended
227 // format is CompanyName.ProductName[.SubProduct.ProductNumber].
228 // See http://msdn.microsoft.com/en-us/library/dd378459%28VS.85%29.aspx
229 DCHECK(lstrlen(app_id
) < 64 && wcschr(app_id
, L
' ') == NULL
);
231 return SetStringValueForPropertyStore(property_store
,
232 PKEY_AppUserModel_ID
,
236 static const char16 kAutoRunKeyPath
[] =
237 L
"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
239 bool AddCommandToAutoRun(HKEY root_key
, const string16
& name
,
240 const string16
& command
) {
241 base::win::RegKey
autorun_key(root_key
, kAutoRunKeyPath
, KEY_SET_VALUE
);
242 return (autorun_key
.WriteValue(name
.c_str(), command
.c_str()) ==
246 bool RemoveCommandFromAutoRun(HKEY root_key
, const string16
& name
) {
247 base::win::RegKey
autorun_key(root_key
, kAutoRunKeyPath
, KEY_SET_VALUE
);
248 return (autorun_key
.DeleteValue(name
.c_str()) == ERROR_SUCCESS
);
251 bool ReadCommandFromAutoRun(HKEY root_key
,
252 const string16
& name
,
254 base::win::RegKey
autorun_key(root_key
, kAutoRunKeyPath
, KEY_QUERY_VALUE
);
255 return (autorun_key
.ReadValue(name
.c_str(), command
) == ERROR_SUCCESS
);
258 void SetShouldCrashOnProcessDetach(bool crash
) {
259 g_crash_on_process_detach
= crash
;
262 bool ShouldCrashOnProcessDetach() {
263 return g_crash_on_process_detach
;
266 void SetAbortBehaviorForCrashReporting() {
267 // Prevent CRT's abort code from prompting a dialog or trying to "report" it.
268 // Disabling the _CALL_REPORTFAULT behavior is important since otherwise it
269 // has the sideffect of clearing our exception filter, which means we
270 // don't get any crash.
271 _set_abort_behavior(0, _WRITE_ABORT_MSG
| _CALL_REPORTFAULT
);
273 // Set a SIGABRT handler for good measure. We will crash even if the default
274 // is left in place, however this allows us to crash earlier. And it also
275 // lets us crash in response to code which might directly call raise(SIGABRT)
276 signal(SIGABRT
, ForceCrashOnSigAbort
);
279 bool IsTabletDevice() {
280 if (GetSystemMetrics(SM_MAXIMUMTOUCHES
) == 0)
283 base::win::Version version
= base::win::GetVersion();
284 if (version
== base::win::VERSION_XP
)
285 return (GetSystemMetrics(SM_TABLETPC
) != 0);
287 // If the device is docked, the user is treating the device as a PC.
288 if (GetSystemMetrics(SM_SYSTEMDOCKED
) != 0)
291 // PlatformRoleSlate was only added in Windows 8, but prior to Win8 it is
292 // still possible to check for a mobile power profile.
293 POWER_PLATFORM_ROLE role
= PowerDeterminePlatformRole();
294 bool mobile_power_profile
= (role
== PlatformRoleMobile
);
295 bool slate_power_profile
= false;
296 if (version
>= base::win::VERSION_WIN8
)
297 slate_power_profile
= (role
== PlatformRoleSlate
);
299 if (mobile_power_profile
|| slate_power_profile
)
300 return (GetSystemMetrics(SM_CONVERTIBLESLATEMODE
) == 0);
305 bool DisplayVirtualKeyboard() {
306 if (base::win::GetVersion() < base::win::VERSION_WIN8
)
309 if (IsKeyboardPresentOnSlate())
312 static base::LazyInstance
<string16
>::Leaky osk_path
=
313 LAZY_INSTANCE_INITIALIZER
;
315 if (osk_path
.Get().empty()) {
316 // We need to launch TabTip.exe from the location specified under the
317 // LocalServer32 key for the {{054AAE20-4BEA-4347-8A35-64A533254A9D}}
319 // TabTip.exe is typically found at
320 // c:\program files\common files\microsoft shared\ink on English Windows.
321 // We don't want to launch TabTip.exe from
322 // c:\program files (x86)\common files\microsoft shared\ink. This path is
323 // normally found on 64 bit Windows.
324 base::win::RegKey
key(HKEY_LOCAL_MACHINE
,
326 KEY_READ
| KEY_WOW64_64KEY
);
327 DWORD osk_path_length
= 1024;
328 if (key
.ReadValue(NULL
,
329 WriteInto(&osk_path
.Get(), osk_path_length
),
331 NULL
) != ERROR_SUCCESS
) {
332 DLOG(WARNING
) << "Failed to read on screen keyboard path from registry";
335 size_t common_program_files_offset
=
336 osk_path
.Get().find(L
"%CommonProgramFiles%");
337 // Typically the path to TabTip.exe read from the registry will start with
338 // %CommonProgramFiles% which needs to be replaced with the corrsponding
340 // If the path does not begin with %CommonProgramFiles% we use it as is.
341 if (common_program_files_offset
!= string16::npos
) {
342 // Preserve the beginning quote in the path.
343 osk_path
.Get().erase(common_program_files_offset
,
344 wcslen(L
"%CommonProgramFiles%"));
345 // The path read from the registry contains the %CommonProgramFiles%
346 // environment variable prefix. On 64 bit Windows the SHGetKnownFolderPath
347 // function returns the common program files path with the X86 suffix for
348 // the FOLDERID_ProgramFilesCommon value.
349 // To get the correct path to TabTip.exe we first read the environment
350 // variable CommonProgramW6432 which points to the desired common
351 // files path. Failing that we fallback to the SHGetKnownFolderPath API.
353 // We then replace the %CommonProgramFiles% value with the actual common
354 // files path found in the process.
355 string16 common_program_files_path
;
356 scoped_ptr
<wchar_t[]> common_program_files_wow6432
;
358 GetEnvironmentVariable(L
"CommonProgramW6432", NULL
, 0);
360 common_program_files_wow6432
.reset(new wchar_t[buffer_size
]);
361 GetEnvironmentVariable(L
"CommonProgramW6432",
362 common_program_files_wow6432
.get(),
364 common_program_files_path
= common_program_files_wow6432
.get();
365 DCHECK(!common_program_files_path
.empty());
367 base::win::ScopedCoMem
<wchar_t> common_program_files
;
368 if (FAILED(SHGetKnownFolderPath(FOLDERID_ProgramFilesCommon
, 0, NULL
,
369 &common_program_files
))) {
372 common_program_files_path
= common_program_files
;
375 osk_path
.Get().insert(1, common_program_files_path
);
379 HINSTANCE ret
= ::ShellExecuteW(NULL
,
381 osk_path
.Get().c_str(),
385 return reinterpret_cast<int>(ret
) > 32;
388 bool DismissVirtualKeyboard() {
389 if (base::win::GetVersion() < base::win::VERSION_WIN8
)
392 // We dismiss the virtual keyboard by generating the ESC keystroke
394 const wchar_t kOSKClassName
[] = L
"IPTip_Main_Window";
395 HWND osk
= ::FindWindow(kOSKClassName
, NULL
);
396 if (::IsWindow(osk
) && ::IsWindowEnabled(osk
)) {
397 PostMessage(osk
, WM_SYSCOMMAND
, SC_CLOSE
, 0);
403 typedef HWND (*MetroRootWindow
) ();
405 enum DomainEnrollementState
{UNKNOWN
= -1, NOT_ENROLLED
, ENROLLED
};
406 static volatile long int g_domain_state
= UNKNOWN
;
408 bool IsEnrolledToDomain() {
409 // Doesn't make any sense to retry inside a user session because joining a
410 // domain will only kick in on a restart.
411 if (g_domain_state
== UNKNOWN
) {
413 NETSETUP_JOIN_STATUS join_status
;
414 if(::NetGetJoinInformation(NULL
, &domain
, &join_status
) != NERR_Success
)
416 ::NetApiBufferFree(domain
);
417 ::InterlockedCompareExchange(&g_domain_state
,
418 join_status
== ::NetSetupDomainName
?
419 ENROLLED
: NOT_ENROLLED
,
423 return g_domain_state
== ENROLLED
;
426 void SetDomainStateForTesting(bool state
) {
427 g_domain_state
= state
? ENROLLED
: NOT_ENROLLED
;
430 bool MaybeHasSHA256Support() {
431 const base::win::OSInfo
* os_info
= base::win::OSInfo::GetInstance();
433 if (os_info
->version() == base::win::VERSION_PRE_XP
)
434 return false; // Too old to have it and this OS is not supported anyway.
436 if (os_info
->version() == base::win::VERSION_XP
)
437 return os_info
->service_pack().major
>= 3; // Windows XP SP3 has it.
439 // Assume it is missing in this case, although it may not be. This category
440 // includes Windows XP x64, and Windows Server, where a hotfix could be
442 if (os_info
->version() == base::win::VERSION_SERVER_2003
)
445 DCHECK(os_info
->version() >= base::win::VERSION_VISTA
);
446 return true; // New enough to have SHA-256 support.