crypto/nss_util: Get TPM slot id, do lookup by id instead of by name.
[chromium-blink-merge.git] / base / win / win_util.cc
blobcc64c650cb6580bbe41ee1438329b18f4875f6d2
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"
7 #include <aclapi.h>
8 #include <shellapi.h>
9 #include <shlobj.h>
10 #include <shobjidl.h> // Must be before propkey.
11 #include <initguid.h>
12 #include <propkey.h>
13 #include <propvarutil.h>
14 #include <sddl.h>
15 #include <signal.h>
16 #include <stdlib.h>
18 #include "base/lazy_instance.h"
19 #include "base/logging.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/threading/thread_restrictions.h"
24 #include "base/win/metro.h"
25 #include "base/win/registry.h"
26 #include "base/win/scoped_co_mem.h"
27 #include "base/win/scoped_handle.h"
28 #include "base/win/scoped_propvariant.h"
29 #include "base/win/windows_version.h"
31 namespace {
33 // Sets the value of |property_key| to |property_value| in |property_store|.
34 bool SetPropVariantValueForPropertyStore(
35 IPropertyStore* property_store,
36 const PROPERTYKEY& property_key,
37 const base::win::ScopedPropVariant& property_value) {
38 DCHECK(property_store);
40 HRESULT result = property_store->SetValue(property_key, property_value.get());
41 if (result == S_OK)
42 result = property_store->Commit();
43 return SUCCEEDED(result);
46 void __cdecl ForceCrashOnSigAbort(int) {
47 *((int*)0) = 0x1337;
50 const wchar_t kWindows8OSKRegPath[] =
51 L"Software\\Classes\\CLSID\\{054AAE20-4BEA-4347-8A35-64A533254A9D}"
52 L"\\LocalServer32";
54 } // namespace
56 namespace base {
57 namespace win {
59 static bool g_crash_on_process_detach = false;
61 #define NONCLIENTMETRICS_SIZE_PRE_VISTA \
62 SIZEOF_STRUCT_WITH_SPECIFIED_LAST_MEMBER(NONCLIENTMETRICS, lfMessageFont)
64 void GetNonClientMetrics(NONCLIENTMETRICS* metrics) {
65 DCHECK(metrics);
67 static const UINT SIZEOF_NONCLIENTMETRICS =
68 (base::win::GetVersion() >= base::win::VERSION_VISTA) ?
69 sizeof(NONCLIENTMETRICS) : NONCLIENTMETRICS_SIZE_PRE_VISTA;
70 metrics->cbSize = SIZEOF_NONCLIENTMETRICS;
71 const bool success = !!SystemParametersInfo(SPI_GETNONCLIENTMETRICS,
72 SIZEOF_NONCLIENTMETRICS, metrics,
73 0);
74 DCHECK(success);
77 bool GetUserSidString(std::wstring* user_sid) {
78 // Get the current token.
79 HANDLE token = NULL;
80 if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token))
81 return false;
82 base::win::ScopedHandle token_scoped(token);
84 DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
85 scoped_ptr<BYTE[]> user_bytes(new BYTE[size]);
86 TOKEN_USER* user = reinterpret_cast<TOKEN_USER*>(user_bytes.get());
88 if (!::GetTokenInformation(token, TokenUser, user, size, &size))
89 return false;
91 if (!user->User.Sid)
92 return false;
94 // Convert the data to a string.
95 wchar_t* sid_string;
96 if (!::ConvertSidToStringSid(user->User.Sid, &sid_string))
97 return false;
99 *user_sid = sid_string;
101 ::LocalFree(sid_string);
103 return true;
106 bool IsShiftPressed() {
107 return (::GetKeyState(VK_SHIFT) & 0x8000) == 0x8000;
110 bool IsCtrlPressed() {
111 return (::GetKeyState(VK_CONTROL) & 0x8000) == 0x8000;
114 bool IsAltPressed() {
115 return (::GetKeyState(VK_MENU) & 0x8000) == 0x8000;
118 bool IsAltGrPressed() {
119 return (::GetKeyState(VK_MENU) & 0x8000) == 0x8000 &&
120 (::GetKeyState(VK_CONTROL) & 0x8000) == 0x8000;
123 bool UserAccountControlIsEnabled() {
124 // This can be slow if Windows ends up going to disk. Should watch this key
125 // for changes and only read it once, preferably on the file thread.
126 // http://code.google.com/p/chromium/issues/detail?id=61644
127 base::ThreadRestrictions::ScopedAllowIO allow_io;
129 base::win::RegKey key(HKEY_LOCAL_MACHINE,
130 L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
131 KEY_READ);
132 DWORD uac_enabled;
133 if (key.ReadValueDW(L"EnableLUA", &uac_enabled) != ERROR_SUCCESS)
134 return true;
135 // Users can set the EnableLUA value to something arbitrary, like 2, which
136 // Vista will treat as UAC enabled, so we make sure it is not set to 0.
137 return (uac_enabled != 0);
140 bool SetBooleanValueForPropertyStore(IPropertyStore* property_store,
141 const PROPERTYKEY& property_key,
142 bool property_bool_value) {
143 ScopedPropVariant property_value;
144 if (FAILED(InitPropVariantFromBoolean(property_bool_value,
145 property_value.Receive()))) {
146 return false;
149 return SetPropVariantValueForPropertyStore(property_store,
150 property_key,
151 property_value);
154 bool SetStringValueForPropertyStore(IPropertyStore* property_store,
155 const PROPERTYKEY& property_key,
156 const wchar_t* property_string_value) {
157 ScopedPropVariant property_value;
158 if (FAILED(InitPropVariantFromString(property_string_value,
159 property_value.Receive()))) {
160 return false;
163 return SetPropVariantValueForPropertyStore(property_store,
164 property_key,
165 property_value);
168 bool SetAppIdForPropertyStore(IPropertyStore* property_store,
169 const wchar_t* app_id) {
170 // App id should be less than 64 chars and contain no space. And recommended
171 // format is CompanyName.ProductName[.SubProduct.ProductNumber].
172 // See http://msdn.microsoft.com/en-us/library/dd378459%28VS.85%29.aspx
173 DCHECK(lstrlen(app_id) < 64 && wcschr(app_id, L' ') == NULL);
175 return SetStringValueForPropertyStore(property_store,
176 PKEY_AppUserModel_ID,
177 app_id);
180 static const char16 kAutoRunKeyPath[] =
181 L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
183 bool AddCommandToAutoRun(HKEY root_key, const string16& name,
184 const string16& command) {
185 base::win::RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_SET_VALUE);
186 return (autorun_key.WriteValue(name.c_str(), command.c_str()) ==
187 ERROR_SUCCESS);
190 bool RemoveCommandFromAutoRun(HKEY root_key, const string16& name) {
191 base::win::RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_SET_VALUE);
192 return (autorun_key.DeleteValue(name.c_str()) == ERROR_SUCCESS);
195 bool ReadCommandFromAutoRun(HKEY root_key,
196 const string16& name,
197 string16* command) {
198 base::win::RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_QUERY_VALUE);
199 return (autorun_key.ReadValue(name.c_str(), command) == ERROR_SUCCESS);
202 void SetShouldCrashOnProcessDetach(bool crash) {
203 g_crash_on_process_detach = crash;
206 bool ShouldCrashOnProcessDetach() {
207 return g_crash_on_process_detach;
210 void SetAbortBehaviorForCrashReporting() {
211 // Prevent CRT's abort code from prompting a dialog or trying to "report" it.
212 // Disabling the _CALL_REPORTFAULT behavior is important since otherwise it
213 // has the sideffect of clearing our exception filter, which means we
214 // don't get any crash.
215 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
217 // Set a SIGABRT handler for good measure. We will crash even if the default
218 // is left in place, however this allows us to crash earlier. And it also
219 // lets us crash in response to code which might directly call raise(SIGABRT)
220 signal(SIGABRT, ForceCrashOnSigAbort);
223 bool IsTouchEnabledDevice() {
224 if (base::win::GetVersion() < base::win::VERSION_WIN7)
225 return false;
226 const int kMultiTouch = NID_INTEGRATED_TOUCH | NID_MULTI_INPUT | NID_READY;
227 int sm = GetSystemMetrics(SM_DIGITIZER);
228 if ((sm & kMultiTouch) == kMultiTouch) {
229 return true;
231 return false;
234 bool DisplayVirtualKeyboard() {
235 if (base::win::GetVersion() < base::win::VERSION_WIN8)
236 return false;
238 static base::LazyInstance<string16>::Leaky osk_path =
239 LAZY_INSTANCE_INITIALIZER;
241 if (osk_path.Get().empty()) {
242 // We need to launch TabTip.exe from the location specified under the
243 // LocalServer32 key for the {{054AAE20-4BEA-4347-8A35-64A533254A9D}}
244 // CLSID.
245 // TabTip.exe is typically found at
246 // c:\program files\common files\microsoft shared\ink on English Windows.
247 // We don't want to launch TabTip.exe from
248 // c:\program files (x86)\common files\microsoft shared\ink. This path is
249 // normally found on 64 bit Windows.
250 base::win::RegKey key(HKEY_LOCAL_MACHINE,
251 kWindows8OSKRegPath,
252 KEY_READ | KEY_WOW64_64KEY);
253 DWORD osk_path_length = 1024;
254 if (key.ReadValue(NULL,
255 WriteInto(&osk_path.Get(), osk_path_length),
256 &osk_path_length,
257 NULL) != ERROR_SUCCESS) {
258 DLOG(WARNING) << "Failed to read on screen keyboard path from registry";
259 return false;
261 size_t common_program_files_offset =
262 osk_path.Get().find(L"%CommonProgramFiles%");
263 // Typically the path to TabTip.exe read from the registry will start with
264 // %CommonProgramFiles% which needs to be replaced with the corrsponding
265 // expanded string.
266 // If the path does not begin with %CommonProgramFiles% we use it as is.
267 if (common_program_files_offset != string16::npos) {
268 // Preserve the beginning quote in the path.
269 osk_path.Get().erase(common_program_files_offset,
270 wcslen(L"%CommonProgramFiles%"));
271 // The path read from the registry contains the %CommonProgramFiles%
272 // environment variable prefix. On 64 bit Windows the SHGetKnownFolderPath
273 // function returns the common program files path with the X86 suffix for
274 // the FOLDERID_ProgramFilesCommon value.
275 // To get the correct path to TabTip.exe we first read the environment
276 // variable CommonProgramW6432 which points to the desired common
277 // files path. Failing that we fallback to the SHGetKnownFolderPath API.
279 // We then replace the %CommonProgramFiles% value with the actual common
280 // files path found in the process.
281 string16 common_program_files_path;
282 scoped_ptr<wchar_t[]> common_program_files_wow6432;
283 DWORD buffer_size =
284 GetEnvironmentVariable(L"CommonProgramW6432", NULL, 0);
285 if (buffer_size) {
286 common_program_files_wow6432.reset(new wchar_t[buffer_size]);
287 GetEnvironmentVariable(L"CommonProgramW6432",
288 common_program_files_wow6432.get(),
289 buffer_size);
290 common_program_files_path = common_program_files_wow6432.get();
291 DCHECK(!common_program_files_path.empty());
292 } else {
293 base::win::ScopedCoMem<wchar_t> common_program_files;
294 if (FAILED(SHGetKnownFolderPath(FOLDERID_ProgramFilesCommon, 0, NULL,
295 &common_program_files))) {
296 return false;
298 common_program_files_path = common_program_files;
301 osk_path.Get().insert(1, common_program_files_path);
305 HINSTANCE ret = ::ShellExecuteW(NULL,
306 L"",
307 osk_path.Get().c_str(),
308 NULL,
309 NULL,
310 SW_SHOW);
311 return reinterpret_cast<int>(ret) > 32;
314 bool DismissVirtualKeyboard() {
315 if (base::win::GetVersion() < base::win::VERSION_WIN8)
316 return false;
318 // We dismiss the virtual keyboard by generating the ESC keystroke
319 // programmatically.
320 const wchar_t kOSKClassName[] = L"IPTip_Main_Window";
321 HWND osk = ::FindWindow(kOSKClassName, NULL);
322 if (::IsWindow(osk) && ::IsWindowEnabled(osk)) {
323 PostMessage(osk, WM_SYSCOMMAND, SC_CLOSE, 0);
324 return true;
326 return false;
329 typedef HWND (*MetroRootWindow) ();
331 // As of this writing, GetMonitorInfo function seem to return wrong values
332 // for rcWork.left and rcWork.top in case of split screen situation inside
333 // metro mode. In order to get required values we query for core window screen
334 // coordinates.
335 // TODO(shrikant): Remove detour code once GetMonitorInfo is fixed for 8.1.
336 BOOL GetMonitorInfoWrapper(HMONITOR monitor, MONITORINFO* mi) {
337 BOOL ret = ::GetMonitorInfo(monitor, mi);
338 #if !defined(USE_ASH)
339 if (base::win::IsMetroProcess() &&
340 base::win::GetVersion() >= base::win::VERSION_WIN8_1) {
341 static MetroRootWindow root_window = NULL;
342 if (!root_window) {
343 HMODULE metro = base::win::GetMetroModule();
344 // There are apparently instances when current process is inside metro
345 // environment but metro driver dll is not loaded.
346 if (!metro) {
347 return ret;
349 root_window = reinterpret_cast<MetroRootWindow>(
350 ::GetProcAddress(metro, "GetRootWindow"));
352 ret = ::GetWindowRect(root_window(), &(mi->rcWork));
354 #endif
355 return ret;
358 } // namespace win
359 } // namespace base
361 #ifdef _MSC_VER
363 // There are optimizer bugs in x86 VS2012 pre-Update 1.
364 #if _MSC_VER == 1700 && defined _M_IX86 && _MSC_FULL_VER < 170051106
366 #pragma message("Relevant defines:")
367 #define __STR2__(x) #x
368 #define __STR1__(x) __STR2__(x)
369 #define __PPOUT__(x) "#define " #x " " __STR1__(x)
370 #if defined(_M_IX86)
371 #pragma message(__PPOUT__(_M_IX86))
372 #endif
373 #if defined(_M_X64)
374 #pragma message(__PPOUT__(_M_X64))
375 #endif
376 #if defined(_MSC_FULL_VER)
377 #pragma message(__PPOUT__(_MSC_FULL_VER))
378 #endif
380 #pragma message("Visual Studio 2012 x86 must be updated to at least Update 1")
381 #error Must install Update 1 to Visual Studio 2012.
382 #endif
384 #endif // _MSC_VER