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 // chrome_tab.cc : Implementation of DLL Exports.
7 // Need to include this before the ATL headers below.
8 #include "chrome_frame/chrome_tab.h"
10 #include <atlsecurity.h>
13 #include "base/at_exit.h"
14 #include "base/command_line.h"
15 #include "base/file_util.h"
16 #include "base/file_version_info.h"
17 #include "base/logging.h"
18 #include "base/logging_win.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/path_service.h"
21 #include "base/string16.h"
22 #include "base/string_number_conversions.h"
23 #include "base/string_piece.h"
24 #include "base/string_util.h"
25 #include "base/sys_string_conversions.h"
26 #include "base/utf_string_conversions.h"
27 #include "base/win/registry.h"
28 #include "base/win/windows_version.h"
29 #include "chrome/common/chrome_constants.h"
30 #include "chrome/common/chrome_switches.h"
31 #include "chrome/common/metrics/entropy_provider.h"
32 #include "chrome/installer/util/google_update_settings.h"
33 #include "chrome_frame/bho.h"
34 #include "chrome_frame/chrome_active_document.h"
35 #include "chrome_frame/chrome_frame_activex.h"
36 #include "chrome_frame/chrome_frame_automation.h"
37 #include "chrome_frame/chrome_frame_reporting.h"
38 #include "chrome_frame/chrome_launcher_utils.h"
39 #include "chrome_frame/chrome_protocol.h"
40 #include "chrome_frame/dll_redirector.h"
41 #include "chrome_frame/exception_barrier.h"
42 #include "chrome_frame/metrics_service.h"
43 #include "chrome_frame/resource.h"
44 #include "chrome_frame/utils.h"
45 #include "googleurl/src/url_util.h"
46 #include "grit/chrome_frame_resources.h"
48 using base::win::RegKey
;
51 // This function has the side effect of initializing an unprotected
52 // vector pointer inside GoogleUrl. If this is called during DLL loading,
53 // it has the effect of avoiding an initialization race on that pointer.
54 // TODO(siggi): fix GoogleUrl.
55 void InitGoogleUrl() {
56 static const char kDummyUrl
[] = "http://www.google.com";
58 url_util::IsStandard(kDummyUrl
,
59 url_parse::MakeRange(0, arraysize(kDummyUrl
)));
62 const wchar_t kInternetSettings
[] =
63 L
"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
65 const wchar_t kProtocolHandlers
[] =
66 L
"Software\\Classes\\Protocols\\Handler";
68 const wchar_t kRunOnce
[] =
69 L
"Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
71 const wchar_t kRunKeyName
[] = L
"ChromeFrameHelper";
73 const wchar_t kChromeFrameHelperExe
[] = L
"chrome_frame_helper.exe";
74 const wchar_t kChromeFrameHelperStartupArg
[] = L
"--startup";
76 // Window class and window names.
77 // TODO(robertshield): These and other constants need to be refactored into
78 // a common chrome_frame_constants.h|cc and built into a separate lib
79 // (either chrome_frame_utils or make another one).
80 const wchar_t kChromeFrameHelperWindowClassName
[] =
81 L
"ChromeFrameHelperWindowClass";
82 const wchar_t kChromeFrameHelperWindowName
[] =
83 L
"ChromeFrameHelperWindowName";
85 // {0562BFC3-2550-45b4-BD8E-A310583D3A6F}
86 static const GUID kChromeFrameProvider
=
87 { 0x562bfc3, 0x2550, 0x45b4,
88 { 0xbd, 0x8e, 0xa3, 0x10, 0x58, 0x3d, 0x3a, 0x6f } };
90 const wchar_t kPostPlatformUAKey
[] =
91 L
"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\"
92 L
"User Agent\\Post Platform";
93 const wchar_t kChromeFramePrefix
[] = L
"chromeframe/";
95 // See comments in DllGetClassObject.
96 LPFNGETCLASSOBJECT g_dll_get_class_object_redir_ptr
= NULL
;
98 class ChromeTabModule
: public CAtlDllModuleT
<ChromeTabModule
> {
100 typedef CAtlDllModuleT
<ChromeTabModule
> ParentClass
;
102 ChromeTabModule() : do_system_registration_(true) {}
104 DECLARE_LIBID(LIBID_ChromeTabLib
)
105 DECLARE_REGISTRY_APPID_RESOURCEID(IDR_CHROMETAB
,
106 "{FD9B1B31-F4D8-436A-8F4F-D3C2E36733D3}")
108 // Override to add our SYSTIME binary value to registry scripts.
109 // See chrome_frame_activex.rgs for usage.
110 virtual HRESULT
AddCommonRGSReplacements(IRegistrarBase
* registrar
) throw() {
111 HRESULT hr
= ParentClass::AddCommonRGSReplacements(registrar
);
114 SYSTEMTIME local_time
;
115 ::GetSystemTime(&local_time
);
116 std::string
hex(base::HexEncode(&local_time
, sizeof(local_time
)));
117 base::StringPiece
sp_hex(hex
);
118 hr
= registrar
->AddReplacement(L
"SYSTIME",
119 base::SysNativeMBToWide(sp_hex
).c_str());
120 DCHECK(SUCCEEDED(hr
));
125 chrome_launcher::GetChromeExecutablePath().DirName();
126 hr
= registrar
->AddReplacement(L
"CHROME_APPPATH",
127 app_path
.value().c_str());
128 DCHECK(SUCCEEDED(hr
));
132 hr
= registrar
->AddReplacement(L
"CHROME_APPNAME",
133 chrome::kBrowserProcessExecutableName
);
134 DCHECK(SUCCEEDED(hr
));
136 // Fill in VERSION from the VERSIONINFO stored in the DLL's resources.
137 scoped_ptr
<FileVersionInfo
> module_version_info(
138 FileVersionInfo::CreateFileVersionInfoForCurrentModule());
139 DCHECK(module_version_info
!= NULL
);
140 std::wstring
file_version(module_version_info
->file_version());
141 hr
= registrar
->AddReplacement(L
"VERSION", file_version
.c_str());
142 DCHECK(SUCCEEDED(hr
));
146 // Add the directory of chrome_launcher.exe. This will be the same
147 // as the directory for the current DLL.
148 std::wstring module_dir
;
149 FilePath module_path
;
150 if (PathService::Get(base::FILE_MODULE
, &module_path
)) {
151 module_dir
= module_path
.DirName().value();
155 hr
= registrar
->AddReplacement(L
"CHROME_LAUNCHER_APPPATH",
157 DCHECK(SUCCEEDED(hr
));
161 // Add the filename of chrome_launcher.exe
162 hr
= registrar
->AddReplacement(L
"CHROME_LAUNCHER_APPNAME",
163 chrome_launcher::kLauncherExeBaseName
);
164 DCHECK(SUCCEEDED(hr
));
168 // Add the registry hive to use.
169 // Note: This is ugly as hell. I'd rather use the pMapEntries parameter
170 // to CAtlModule::UpdateRegistryFromResource, unfortunately we have a
171 // few components that are registered by calling their
172 // static T::UpdateRegistry() methods directly, which doesn't allow
173 // pMapEntries to be passed through :-(
174 if (do_system_registration_
) {
175 hr
= registrar
->AddReplacement(L
"HIVE", L
"HKLM");
177 hr
= registrar
->AddReplacement(L
"HIVE", L
"HKCU");
179 DCHECK(SUCCEEDED(hr
));
183 // Add the Chrome Frame CLSID.
184 wchar_t cf_clsid
[64];
185 StringFromGUID2(CLSID_ChromeFrame
, &cf_clsid
[0], arraysize(cf_clsid
));
186 hr
= registrar
->AddReplacement(L
"CHROME_FRAME_CLSID", &cf_clsid
[0]);
192 // See comments in AddCommonRGSReplacements
193 bool do_system_registration_
;
196 ChromeTabModule _AtlModule
;
198 base::AtExitManager
* g_exit_manager
= NULL
;
199 base::FieldTrialList
* g_field_trial_list
= NULL
;
201 HRESULT
RefreshElevationPolicy() {
202 const wchar_t kIEFrameDll
[] = L
"ieframe.dll";
203 const char kIERefreshPolicy
[] = "IERefreshElevationPolicy";
204 HRESULT hr
= E_NOTIMPL
;
206 // Stick an SEH in the chain to prevent the VEH from picking up on first
207 // chance exceptions caused by loading ieframe.dll. Use the vanilla
208 // ExceptionBarrier to report any exceptions that do make their way to us
210 ExceptionBarrier barrier
;
212 HMODULE ieframe_module
= LoadLibrary(kIEFrameDll
);
213 if (ieframe_module
) {
214 typedef HRESULT (__stdcall
*IERefreshPolicy
)();
215 IERefreshPolicy ie_refresh_policy
= reinterpret_cast<IERefreshPolicy
>(
216 GetProcAddress(ieframe_module
, kIERefreshPolicy
));
218 if (ie_refresh_policy
) {
219 hr
= ie_refresh_policy();
221 hr
= HRESULT_FROM_WIN32(GetLastError());
224 FreeLibrary(ieframe_module
);
226 hr
= HRESULT_FROM_WIN32(GetLastError());
232 // Experimental boot prefetch optimization for Chrome Frame
234 // If chrome is warmed up during a single reboot, it gets paged
235 // in for subsequent reboots and the cold startup times essentially
236 // look like warm times thereafter! The 'warm up' is done by
237 // setting up a 'RunOnce' key during DLLRegisterServer of
238 // npchrome_frame.dll.
240 // This works because chrome prefetch becomes part of boot
241 // prefetch file ntosboot-b00dfaad.pf and paged in on subsequent
242 // reboots. As long as the sytem does not undergo significant
243 // memory pressure those pages remain in memory and we get pretty
244 // amazing startup times, down to about 300 ms from 1200 ms
247 // - Whether chrome frame is used or not, there's a read penalty
248 // (1200-300 =) 900 ms for every boot.
249 // - Heavy system memory usage after reboot will nullify the benefits
250 // but the user will still pay the cost.
251 // - Overall the time saved will always be less than total time spent
253 // - We are not sure when the chrome 'warm up' will age out from the
254 // boot prefetch file.
256 // The idea here is to try this out on chrome frame dev channel
257 // and see if it produces a significant drift in startup numbers.
258 HRESULT
SetupRunOnce() {
259 HRESULT result
= E_FAIL
;
261 string16 channel_name
;
262 if (base::win::GetVersion() < base::win::VERSION_VISTA
&&
263 GoogleUpdateSettings::GetChromeChannelAndModifiers(true, &channel_name
)) {
264 std::transform(channel_name
.begin(), channel_name
.end(),
265 channel_name
.begin(), tolower
);
266 // Use this only for the dev channel.
267 if (channel_name
.find(L
"dev") != string16::npos
) {
268 HKEY hive
= HKEY_CURRENT_USER
;
269 if (IsSystemProcess()) {
270 // For system installs, our updates will be running as SYSTEM which
271 // makes writing to a RunOnce key under HKCU not so terribly useful.
272 hive
= HKEY_LOCAL_MACHINE
;
276 LONG ret
= run_once
.Create(hive
, kRunOnce
, KEY_READ
| KEY_WRITE
);
277 if (ret
== ERROR_SUCCESS
) {
278 CommandLine
run_once_cmd(chrome_launcher::GetChromeExecutablePath());
279 run_once_cmd
.AppendSwitchASCII(switches::kAutomationClientChannelID
,
281 run_once_cmd
.AppendSwitch(switches::kChromeFrame
);
282 ret
= run_once
.WriteValue(L
"A",
283 run_once_cmd
.GetCommandLineString().c_str());
285 result
= HRESULT_FROM_WIN32(ret
);
290 // We're on a non-XP version of Windows or on a stable channel. Nothing
298 // Helper method called for user-level installs where we don't have admin
299 // permissions. Starts up the long running process and registers it to get it
300 // started at next boot.
301 HRESULT
SetupUserLevelHelper() {
304 // Remove existing run-at-startup entry.
305 base::win::RemoveCommandFromAutoRun(HKEY_CURRENT_USER
, kRunKeyName
);
307 // Build the chrome_frame_helper command line.
308 FilePath module_path
;
309 FilePath helper_path
;
310 if (PathService::Get(base::FILE_MODULE
, &module_path
)) {
311 module_path
= module_path
.DirName();
312 helper_path
= module_path
.Append(kChromeFrameHelperExe
);
313 if (!file_util::PathExists(helper_path
)) {
314 // If we can't find the helper in the current directory, try looking
315 // one up (this is the layout in the build output folder).
316 module_path
= module_path
.DirName();
317 helper_path
= module_path
.Append(kChromeFrameHelperExe
);
318 DCHECK(file_util::PathExists(helper_path
)) <<
319 "Could not find chrome_frame_helper.exe.";
322 // Find window handle of existing instance.
323 HWND old_window
= FindWindow(kChromeFrameHelperWindowClassName
,
324 kChromeFrameHelperWindowName
);
326 if (file_util::PathExists(helper_path
)) {
327 std::wstring
helper_path_cmd(L
"\"");
328 helper_path_cmd
+= helper_path
.value();
329 helper_path_cmd
+= L
"\" ";
330 helper_path_cmd
+= kChromeFrameHelperStartupArg
;
332 // Add new run-at-startup entry.
333 if (!base::win::AddCommandToAutoRun(HKEY_CURRENT_USER
, kRunKeyName
,
336 LOG(ERROR
) << "Could not add helper process to auto run key.";
339 // Start new instance.
340 base::LaunchOptions options
;
341 options
.start_hidden
= true;
342 bool launched
= base::LaunchProcess(helper_path
.value(), options
, NULL
);
345 PLOG(DFATAL
) << "Could not launch helper process.";
348 // Kill old instance using window handle.
349 if (IsWindow(old_window
)) {
350 BOOL result
= PostMessage(old_window
, WM_CLOSE
, 0, 0);
352 PLOG(ERROR
) << "Failed to post close message to old helper process: ";
356 hr
= HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND
);
366 // To delete the user agent, set value to NULL.
367 // The is_system parameter indicates whether this is a per machine or a per
368 // user installation.
369 HRESULT
SetChromeFrameUA(bool is_system
, const wchar_t* value
) {
371 HKEY parent_hive
= is_system
? HKEY_LOCAL_MACHINE
: HKEY_CURRENT_USER
;
374 LONG reg_result
= ua_key
.Create(parent_hive
, kPostPlatformUAKey
,
375 KEY_READ
| KEY_WRITE
);
376 if (reg_result
== ERROR_SUCCESS
) {
377 // Make sure that we unregister ChromeFrame UA strings registered previously
378 wchar_t value_name
[MAX_PATH
+ 1] = {};
379 wchar_t value_data
[MAX_PATH
+ 1] = {};
381 DWORD value_index
= 0;
382 while (value_index
< ua_key
.GetValueCount()) {
383 DWORD name_size
= arraysize(value_name
);
384 DWORD value_size
= arraysize(value_data
);
386 LRESULT ret
= ::RegEnumValue(ua_key
.Handle(), value_index
, value_name
,
387 &name_size
, NULL
, &type
,
388 reinterpret_cast<BYTE
*>(value_data
),
390 if (ret
== ERROR_SUCCESS
) {
391 if (StartsWith(value_name
, kChromeFramePrefix
, false)) {
392 ua_key
.DeleteValue(value_name
);
401 std::wstring chrome_frame_ua_value_name
= kChromeFramePrefix
;
402 chrome_frame_ua_value_name
+= GetCurrentModuleVersion();
404 ua_key
.WriteValue(chrome_frame_ua_value_name
.c_str(), value
);
408 DLOG(ERROR
) << __FUNCTION__
<< ": " << kPostPlatformUAKey
409 << ", error code = " << reg_result
;
410 hr
= HRESULT_FROM_WIN32(reg_result
);
415 class SecurityDescBackup
{
417 explicit SecurityDescBackup(const std::wstring
& backup_key
)
418 : backup_key_name_(backup_key
) {}
419 ~SecurityDescBackup() {}
421 // Save given security descriptor to the backup key.
422 bool SaveSecurity(const CSecurityDesc
& sd
) {
424 if (!sd
.ToString(&str
))
427 RegKey
backup_key(HKEY_LOCAL_MACHINE
, backup_key_name_
.c_str(),
428 KEY_READ
| KEY_WRITE
);
429 if (backup_key
.Valid()) {
430 return backup_key
.WriteValue(NULL
, str
.GetString()) == ERROR_SUCCESS
;
436 // Restore security descriptor from backup key to given key name.
437 bool RestoreSecurity(const wchar_t* key_name
) {
439 if (!ReadBackupKey(&sddl
))
442 // Create security descriptor from string.
444 if (!sd
.FromString(sddl
.c_str()))
448 // Restore DACL and Owner of the key from saved security descriptor.
454 DWORD error
= ::SetNamedSecurityInfo(const_cast<wchar_t*>(key_name
),
455 SE_REGISTRY_KEY
, OWNER_SECURITY_INFORMATION
| DACL_SECURITY_INFORMATION
,
456 const_cast<SID
*>(owner
.GetPSID()), NULL
,
457 const_cast<ACL
*>(dacl
.GetPACL()), NULL
);
460 return (error
== ERROR_SUCCESS
);
464 // Read SDDL string from backup key
465 bool ReadBackupKey(std::wstring
* sddl
) {
466 RegKey
backup_key(HKEY_LOCAL_MACHINE
, backup_key_name_
.c_str(), KEY_READ
);
467 if (!backup_key
.Valid())
471 DWORD reg_type
= REG_NONE
;
472 if (backup_key
.ReadValue(NULL
, NULL
, &len
, ®_type
) != ERROR_SUCCESS
)
474 DCHECK_EQ(0u, len
% sizeof(wchar_t));
476 if ((len
== 0) || (reg_type
!= REG_SZ
))
479 size_t wchar_count
= 1 + len
/ sizeof(wchar_t);
480 if (backup_key
.ReadValue(NULL
, WriteInto(sddl
, wchar_count
), &len
,
481 ®_type
) != ERROR_SUCCESS
) {
488 void DeleteBackupKey() {
489 ::RegDeleteKey(HKEY_LOCAL_MACHINE
, backup_key_name_
.c_str());
492 std::wstring backup_key_name_
;
495 struct TokenWithPrivileges
{
496 TokenWithPrivileges() {
497 token_
.GetEffectiveToken(TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
);
498 token_
.GetUser(&user_
);
501 ~TokenWithPrivileges() {
502 token_
.EnableDisablePrivileges(take_ownership_
);
503 token_
.EnableDisablePrivileges(restore_
);
506 bool EnablePrivileges() {
507 if (take_ownership_
.GetCount() == 0)
508 if (!token_
.EnablePrivilege(L
"SeTakeOwnershipPrivilege",
512 if (restore_
.GetCount() == 0)
513 if (!token_
.EnablePrivilege(L
"SeRestorePrivilege", &restore_
))
519 const CSid
& GetUser() const {
525 CTokenPrivileges take_ownership_
;
526 CTokenPrivileges restore_
;
530 HRESULT
SetOrDeleteMimeHandlerKey(bool set
, HKEY root_key
) {
531 std::wstring key_name
= kInternetSettings
;
532 key_name
.append(L
"\\Secure Mime Handlers");
533 RegKey
key(root_key
, key_name
.c_str(), KEY_READ
| KEY_WRITE
);
537 LONG result1
= ERROR_SUCCESS
;
538 LONG result2
= ERROR_SUCCESS
;
540 result1
= key
.WriteValue(L
"ChromeTab.ChromeActiveDocument", 1);
541 result2
= key
.WriteValue(L
"ChromeTab.ChromeActiveDocument.1", 1);
543 result1
= key
.DeleteValue(L
"ChromeTab.ChromeActiveDocument");
544 result2
= key
.DeleteValue(L
"ChromeTab.ChromeActiveDocument.1");
547 return result1
!= ERROR_SUCCESS
? HRESULT_FROM_WIN32(result1
) :
548 HRESULT_FROM_WIN32(result2
);
551 // Chrome Frame registration functions.
552 //-----------------------------------------------------------------------------
553 HRESULT
RegisterSecuredMimeHandler(bool enable
, bool is_system
) {
555 return SetOrDeleteMimeHandlerKey(enable
, HKEY_CURRENT_USER
);
556 } else if (base::win::GetVersion() < base::win::VERSION_VISTA
) {
557 return SetOrDeleteMimeHandlerKey(enable
, HKEY_LOCAL_MACHINE
);
560 std::wstring mime_key
= kInternetSettings
;
561 mime_key
.append(L
"\\Secure Mime Handlers");
562 std::wstring backup_key
= kInternetSettings
;
563 backup_key
.append(L
"\\__backup_SMH__");
564 std::wstring object_name
= L
"MACHINE\\";
565 object_name
.append(mime_key
);
567 TokenWithPrivileges token_
;
568 if (!token_
.EnablePrivileges())
569 return E_ACCESSDENIED
;
571 // If there is a backup key - something bad happened; try to restore
572 // security on "Secure Mime Handlers" from the backup.
573 SecurityDescBackup
backup(backup_key
);
574 backup
.RestoreSecurity(object_name
.c_str());
576 // Read old security descriptor of the Mime key first.
578 if (!AtlGetSecurityDescriptor(object_name
.c_str(), SE_REGISTRY_KEY
, &sd
)) {
582 backup
.SaveSecurity(sd
);
585 if (AtlSetOwnerSid(object_name
.c_str(), SE_REGISTRY_KEY
, token_
.GetUser())) {
588 sd
.GetDacl(&new_dacl
);
589 new_dacl
.AddAllowedAce(token_
.GetUser(), GENERIC_WRITE
| GENERIC_READ
);
590 if (AtlSetDacl(object_name
.c_str(), SE_REGISTRY_KEY
, new_dacl
)) {
591 hr
= SetOrDeleteMimeHandlerKey(enable
, HKEY_LOCAL_MACHINE
);
595 backup
.RestoreSecurity(object_name
.c_str());
599 HRESULT
RegisterActiveDoc(bool reg
, bool is_system
) {
600 // We have to call the static T::UpdateRegistry function instead of
601 // _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ACTIVEDOC, reg)
602 // because there is specific OLEMISC replacement.
603 return ChromeActiveDocument::UpdateRegistry(reg
);
606 HRESULT
RegisterActiveX(bool reg
, bool is_system
) {
607 // We have to call the static T::UpdateRegistry function instead of
608 // _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ACTIVEX, reg)
609 // because there is specific OLEMISC replacement.
610 return ChromeFrameActivex::UpdateRegistry(reg
);
613 HRESULT
RegisterElevationPolicy(bool reg
, bool is_system
) {
615 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
616 // Register the elevation policy. This must succeed for Chrome Frame to
617 // be able launch Chrome when running in low-integrity IE.
618 hr
= _AtlModule
.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ELEVATION
, reg
);
620 // Ignore failures since old versions of IE 7 (e.g., 7.0.6000.16386, which
621 // shipped with Vista RTM) do not export IERefreshElevationPolicy.
622 RefreshElevationPolicy();
628 HRESULT
RegisterProtocol(bool reg
, bool is_system
) {
629 return _AtlModule
.UpdateRegistryFromResourceS(IDR_CHROMEPROTOCOL
, reg
);
632 HRESULT
RegisterBhoClsid(bool reg
, bool is_system
) {
633 return Bho::UpdateRegistry(reg
);
636 HRESULT
RegisterBhoIE(bool reg
, bool is_system
) {
638 return _AtlModule
.UpdateRegistryFromResourceS(IDR_REGISTER_BHO
, reg
);
641 // Setup the long running process:
642 return SetupUserLevelHelper();
644 // Unschedule the user-level helper. Note that we don't kill it here
645 // so that during updates we don't have a time window with no running
646 // helper. Uninstalls and updates will explicitly kill the helper from
647 // within the installer. Unregister existing run-at-startup entry.
648 return base::win::RemoveCommandFromAutoRun(HKEY_CURRENT_USER
,
649 kRunKeyName
) ? S_OK
: E_FAIL
;
654 HRESULT
RegisterTypeLib(bool reg
, bool is_system
) {
655 if (reg
&& !is_system
) {
656 // Enables the RegisterTypeLib Function function to override default
657 // registry mappings under Windows Vista Service Pack 1 (SP1),
658 // Windows Server 2008, and later operating system versions
659 typedef void (WINAPI
* OaEnablePerUserTypeLibReg
)(void);
660 OaEnablePerUserTypeLibReg per_user_typelib_func
=
661 reinterpret_cast<OaEnablePerUserTypeLibReg
>(
662 GetProcAddress(GetModuleHandle(L
"oleaut32.dll"),
663 "OaEnablePerUserTLibRegistration"));
664 if (per_user_typelib_func
) {
665 (*per_user_typelib_func
)();
669 UtilRegisterTypeLib(_AtlComModule
.m_hInstTypeLib
,
671 UtilUnRegisterTypeLib(_AtlComModule
.m_hInstTypeLib
,
675 HRESULT
RegisterLegacyNPAPICleanup(bool reg
, bool is_system
) {
677 _AtlModule
.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_NPAPI
, reg
);
678 UtilRemovePersistentNPAPIMarker();
684 HRESULT
RegisterAppId(bool reg
, bool is_system
) {
685 return _AtlModule
.UpdateRegistryAppId(reg
);
688 HRESULT
RegisterUserAgent(bool reg
, bool is_system
) {
690 return SetChromeFrameUA(is_system
, L
"1");
692 return SetChromeFrameUA(is_system
, NULL
);
696 enum RegistrationStepId
{
697 kStepSecuredMimeHandler
= 0,
700 kStepElevationPolicy
= 3,
703 kStepBhoRegistration
= 6,
704 kStepRegisterTypeLib
= 7,
705 kStepNpapiCleanup
= 8,
711 enum RegistrationFlags
{
714 GCF_PROTOCOL
= 0x0004,
716 BHO_REGISTRATION
= 0x0010,
722 // Mux the failure step into the hresult. We take only the first four bits
723 // and stick those into the top four bits of the facility code. We also set the
724 // Customer bit to be polite. Graphically, we write our error code to the
725 // bits marked with ^:
726 // 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
727 // 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
728 // +---+-+-+-----------------------+-------------------------------+
729 // |Sev|C|R| Facility | Code |
730 // +---+-+-+-----------------------+-------------------------------+
732 // See http://msdn.microsoft.com/en-us/library/cc231198(PROT.10).aspx for
733 // more details on HRESULTS.
735 // The resulting error can be extracted by:
736 // error_code = (fiddled_hr & 0x07800000) >> 23
737 HRESULT
MuxErrorIntoHRESULT(HRESULT hr
, int error_code
) {
738 DCHECK_GE(error_code
, 0);
739 DCHECK_LT(error_code
, kStepEnd
);
740 COMPILE_ASSERT(kStepEnd
<= 0xF, update_error_muxing_too_many_steps
);
742 // Check that our four desired bits are clear.
743 // 0xF87FFFFF == 11111000011111111111111111111111
744 DCHECK_EQ(static_cast<HRESULT
>(hr
& 0xF87FFFFF), hr
);
746 HRESULT fiddled_hr
= ((error_code
& 0xF) << 23) | hr
;
747 fiddled_hr
|= 1 << 29; // Set the customer bit.
752 HRESULT
CustomRegistration(uint16 reg_flags
, bool reg
, bool is_system
) {
753 if (reg
&& (reg_flags
& (ACTIVEDOC
| ACTIVEX
)))
754 reg_flags
|= (TYPELIB
| GCF_PROTOCOL
);
756 // Set the flag that gets checked in AddCommonRGSReplacements before doing
757 // registration work.
758 _AtlModule
.do_system_registration_
= is_system
;
760 typedef HRESULT (*RegistrationFn
)(bool reg
, bool is_system
);
761 struct RegistrationStep
{
762 RegistrationStepId id
;
766 static const RegistrationStep registration_steps
[] = {
767 { kStepSecuredMimeHandler
, ACTIVEDOC
, &RegisterSecuredMimeHandler
},
768 { kStepActiveDoc
, ACTIVEDOC
, &RegisterActiveDoc
},
769 { kStepActiveX
, ACTIVEX
, &RegisterActiveX
},
770 { kStepElevationPolicy
, (ACTIVEDOC
| ACTIVEX
), &RegisterElevationPolicy
},
771 { kStepProtocol
, GCF_PROTOCOL
, &RegisterProtocol
},
772 { kStepBhoClsid
, BHO_CLSID
, &RegisterBhoClsid
},
773 { kStepBhoRegistration
, BHO_REGISTRATION
, &RegisterBhoIE
},
774 { kStepRegisterTypeLib
, TYPELIB
, &RegisterTypeLib
},
775 { kStepNpapiCleanup
, ALL
, &RegisterLegacyNPAPICleanup
},
776 { kStepAppId
, ALL
, &RegisterAppId
},
777 { kStepUserAgent
, ALL
, &RegisterUserAgent
}
782 bool rollback
= false;
783 int failure_step
= 0;
784 HRESULT step_hr
= S_OK
;
785 for (int step
= 0; step
< arraysize(registration_steps
); ++step
) {
786 if ((reg_flags
& registration_steps
[step
].condition
) != 0) {
787 step_hr
= registration_steps
[step
].func(reg
, is_system
);
788 if (FAILED(step_hr
)) {
789 // Store only the first failing HRESULT with the step value muxed in.
791 hr
= MuxErrorIntoHRESULT(step_hr
, step
);
794 // On registration if a step fails, we abort and rollback.
806 // Rollback the failing action and all preceding ones.
807 for (int step
= failure_step
; step
>= 0; --step
) {
808 registration_steps
[step
].func(!reg
, is_system
);
818 extern "C" BOOL WINAPI
DllMain(HINSTANCE instance
,
821 UNREFERENCED_PARAMETER(instance
);
822 if (reason
== DLL_PROCESS_ATTACH
) {
824 // Silence traces from the ATL registrar to reduce the log noise.
825 ATL::CTrace::s_trace
.ChangeCategory(atlTraceRegistrar
, 0,
826 ATLTRACESTATUS_DISABLED
);
830 g_exit_manager
= new base::AtExitManager();
831 CommandLine::Init(0, NULL
);
832 InitializeCrashReporting();
833 logging::InitLogging(
835 logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG
,
836 logging::LOCK_LOG_FILE
,
837 logging::DELETE_OLD_LOG_FILE
,
838 logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS
);
840 // Log the same items as Chrome.
841 logging::SetLogItems(true, // enable_process_id
842 true, // enable_thread_id
843 false, // enable_timestamp
844 true); // enable_tickcount
846 DllRedirector
* dll_redirector
= DllRedirector::GetInstance();
847 DCHECK(dll_redirector
);
849 if (!dll_redirector
->RegisterAsFirstCFModule()) {
850 // Someone else was here first, try and get a pointer to their
851 // DllGetClassObject export:
852 g_dll_get_class_object_redir_ptr
=
853 dll_redirector
->GetDllGetClassObjectPtr();
854 DCHECK(g_dll_get_class_object_redir_ptr
!= NULL
)
855 << "Found CF module with no DllGetClassObject export.";
858 // Enable trace control and transport through event tracing for Windows.
859 logging::LogEventProvider::Initialize(kChromeFrameProvider
);
861 // Initialize the field test infrastructure. Must be done somewhere that
862 // can only get called once. For Chrome Frame, that is here.
863 g_field_trial_list
= new base::FieldTrialList(
864 new metrics::SHA1EntropyProvider(MetricsService::GetClientID()));
865 } else if (reason
== DLL_PROCESS_DETACH
) {
866 delete g_field_trial_list
;
867 g_field_trial_list
= NULL
;
869 DllRedirector
* dll_redirector
= DllRedirector::GetInstance();
870 DCHECK(dll_redirector
);
871 dll_redirector
->UnregisterAsFirstCFModule();
873 g_patch_helper
.UnpatchIfNeeded();
875 delete g_exit_manager
;
876 g_exit_manager
= NULL
;
878 ShutdownCrashReporting();
880 return _AtlModule
.DllMain(reason
, reserved
);
883 // Used to determine whether the DLL can be unloaded by OLE
884 STDAPI
DllCanUnloadNow() {
885 return _AtlModule
.DllCanUnloadNow();
888 // Returns a class factory to create an object of the requested type
889 STDAPI
DllGetClassObject(REFCLSID rclsid
, REFIID riid
, LPVOID
* ppv
) {
890 // If we found another module present when we were loaded, then delegate to
892 if (g_dll_get_class_object_redir_ptr
) {
893 return g_dll_get_class_object_redir_ptr(rclsid
, riid
, ppv
);
896 // Enable sniffing and switching only if asked for BHO
897 // (we use BHO to get loaded in IE).
898 if (rclsid
== CLSID_ChromeFrameBHO
) {
899 g_patch_helper
.InitializeAndPatchProtocolsIfNeeded();
902 return _AtlModule
.DllGetClassObject(rclsid
, riid
, ppv
);
905 // DllRegisterServer - Adds entries to the system registry
906 STDAPI
DllRegisterServer() {
907 uint16 flags
= ACTIVEX
| ACTIVEDOC
| TYPELIB
| GCF_PROTOCOL
|
908 BHO_CLSID
| BHO_REGISTRATION
;
910 HRESULT hr
= CustomRegistration(flags
, true, true);
918 // DllUnregisterServer - Removes entries from the system registry
919 STDAPI
DllUnregisterServer() {
920 HRESULT hr
= CustomRegistration(ALL
, false, true);
924 // DllRegisterUserServer - Adds entries to the HKCU hive in the registry.
925 STDAPI
DllRegisterUserServer() {
926 UINT flags
= ACTIVEX
| ACTIVEDOC
| TYPELIB
| GCF_PROTOCOL
|
927 BHO_CLSID
| BHO_REGISTRATION
;
929 HRESULT hr
= CustomRegistration(flags
, TRUE
, false);
937 // DllUnregisterUserServer - Removes entries from the HKCU hive in the registry.
938 STDAPI
DllUnregisterUserServer() {
939 HRESULT hr
= CustomRegistration(ALL
, FALSE
, false);
943 // Object entries go here instead of with each object, so that we can move
944 // the objects to a lib. Also reduces magic.
945 OBJECT_ENTRY_AUTO(CLSID_ChromeFrameBHO
, Bho
)
946 OBJECT_ENTRY_AUTO(__uuidof(ChromeActiveDocument
), ChromeActiveDocument
)
947 OBJECT_ENTRY_AUTO(__uuidof(ChromeFrame
), ChromeFrameActivex
)
948 OBJECT_ENTRY_AUTO(__uuidof(ChromeProtocol
), ChromeProtocol
)