Fix some case-insensitive cases for StartsWith.
[chromium-blink-merge.git] / chrome / installer / util / install_util.cc
blob7d684174274aa4374b9ee82f3960ab67349629a0
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 // See the corresponding header file for description of the functions in this
6 // file.
8 #include "chrome/installer/util/install_util.h"
10 #include <shellapi.h>
11 #include <shlobj.h>
12 #include <shlwapi.h>
14 #include <algorithm>
16 #include "base/command_line.h"
17 #include "base/environment.h"
18 #include "base/files/file_util.h"
19 #include "base/logging.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/numerics/safe_conversions.h"
22 #include "base/path_service.h"
23 #include "base/process/launch.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/sys_info.h"
27 #include "base/values.h"
28 #include "base/version.h"
29 #include "base/win/metro.h"
30 #include "base/win/registry.h"
31 #include "base/win/windows_version.h"
32 #include "chrome/common/chrome_constants.h"
33 #include "chrome/common/chrome_paths.h"
34 #include "chrome/installer/util/browser_distribution.h"
35 #include "chrome/installer/util/google_update_constants.h"
36 #include "chrome/installer/util/helper.h"
37 #include "chrome/installer/util/installation_state.h"
38 #include "chrome/installer/util/l10n_string_util.h"
39 #include "chrome/installer/util/util_constants.h"
40 #include "chrome/installer/util/work_item_list.h"
42 using base::win::RegKey;
43 using installer::ProductState;
45 namespace {
47 const wchar_t kStageBinaryPatching[] = L"binary_patching";
48 const wchar_t kStageBuilding[] = L"building";
49 const wchar_t kStageConfiguringAutoLaunch[] = L"configuring_auto_launch";
50 const wchar_t kStageCopyingPreferencesFile[] = L"copying_prefs";
51 const wchar_t kStageCreatingShortcuts[] = L"creating_shortcuts";
52 const wchar_t kStageEnsemblePatching[] = L"ensemble_patching";
53 const wchar_t kStageExecuting[] = L"executing";
54 const wchar_t kStageFinishing[] = L"finishing";
55 const wchar_t kStagePreconditions[] = L"preconditions";
56 const wchar_t kStageRefreshingPolicy[] = L"refreshing_policy";
57 const wchar_t kStageRegisteringChrome[] = L"registering_chrome";
58 const wchar_t kStageRemovingOldVersions[] = L"removing_old_ver";
59 const wchar_t kStageRollingback[] = L"rollingback";
60 const wchar_t kStageUncompressing[] = L"uncompressing";
61 const wchar_t kStageUnpacking[] = L"unpacking";
62 const wchar_t kStageUpdatingChannels[] = L"updating_channels";
63 const wchar_t kStageCreatingVisualManifest[] = L"creating_visual_manifest";
64 const wchar_t kStageDeferringToHigherVersion[] = L"deferring_to_higher_version";
65 const wchar_t kStageUninstallingBinaries[] = L"uninstalling_binaries";
66 const wchar_t kStageUninstallingChromeFrame[] = L"uninstalling_chrome_frame";
68 const wchar_t* const kStages[] = {
69 NULL,
70 kStagePreconditions,
71 kStageUncompressing,
72 kStageEnsemblePatching,
73 kStageBinaryPatching,
74 kStageUnpacking,
75 kStageBuilding,
76 kStageExecuting,
77 kStageRollingback,
78 kStageRefreshingPolicy,
79 kStageUpdatingChannels,
80 kStageCopyingPreferencesFile,
81 kStageCreatingShortcuts,
82 kStageRegisteringChrome,
83 kStageRemovingOldVersions,
84 kStageFinishing,
85 kStageConfiguringAutoLaunch,
86 kStageCreatingVisualManifest,
87 kStageDeferringToHigherVersion,
88 kStageUninstallingBinaries,
89 kStageUninstallingChromeFrame,
92 COMPILE_ASSERT(installer::NUM_STAGES == arraysize(kStages),
93 kStages_disagrees_with_Stage_comma_they_must_match_bang);
95 // Creates a zero-sized non-decorated foreground window that doesn't appear
96 // in the taskbar. This is used as a parent window for calls to ShellExecuteEx
97 // in order for the UAC dialog to appear in the foreground and for focus
98 // to be returned to this process once the UAC task is dismissed. Returns
99 // NULL on failure, a handle to the UAC window on success.
100 HWND CreateUACForegroundWindow() {
101 HWND foreground_window = ::CreateWindowEx(WS_EX_TOOLWINDOW,
102 L"STATIC",
103 NULL,
104 WS_POPUP | WS_VISIBLE,
105 0, 0, 0, 0,
106 NULL, NULL,
107 ::GetModuleHandle(NULL),
108 NULL);
109 if (foreground_window) {
110 HMONITOR monitor = ::MonitorFromWindow(foreground_window,
111 MONITOR_DEFAULTTONEAREST);
112 if (monitor) {
113 MONITORINFO mi = {0};
114 mi.cbSize = sizeof(mi);
115 ::GetMonitorInfo(monitor, &mi);
116 RECT screen_rect = mi.rcWork;
117 int x_offset = (screen_rect.right - screen_rect.left) / 2;
118 int y_offset = (screen_rect.bottom - screen_rect.top) / 2;
119 ::MoveWindow(foreground_window,
120 screen_rect.left + x_offset,
121 screen_rect.top + y_offset,
122 0, 0, FALSE);
123 } else {
124 NOTREACHED() << "Unable to get default monitor";
126 ::SetForegroundWindow(foreground_window);
128 return foreground_window;
131 } // namespace
133 base::string16 InstallUtil::GetActiveSetupPath(BrowserDistribution* dist) {
134 static const wchar_t kInstalledComponentsPath[] =
135 L"Software\\Microsoft\\Active Setup\\Installed Components\\";
136 return kInstalledComponentsPath + dist->GetActiveSetupGuid();
139 void InstallUtil::TriggerActiveSetupCommand() {
140 base::string16 active_setup_reg(
141 GetActiveSetupPath(BrowserDistribution::GetDistribution()));
142 base::win::RegKey active_setup_key(
143 HKEY_LOCAL_MACHINE, active_setup_reg.c_str(), KEY_QUERY_VALUE);
144 base::string16 cmd_str;
145 LONG read_status = active_setup_key.ReadValue(L"StubPath", &cmd_str);
146 if (read_status != ERROR_SUCCESS) {
147 LOG(ERROR) << active_setup_reg << ", " << read_status;
148 // This should never fail if Chrome is registered at system-level, but if it
149 // does there is not much else to be done.
150 return;
153 base::CommandLine cmd(base::CommandLine::FromString(cmd_str));
154 // Force creation of shortcuts as the First Run beacon might land between now
155 // and the time setup.exe checks for it.
156 cmd.AppendSwitch(installer::switches::kForceConfigureUserSettings);
158 base::LaunchOptions launch_options;
159 if (base::win::IsMetroProcess())
160 launch_options.force_breakaway_from_job_ = true;
161 base::Process process =
162 base::LaunchProcess(cmd.GetCommandLineString(), launch_options);
163 if (!process.IsValid())
164 PLOG(ERROR) << cmd.GetCommandLineString();
167 bool InstallUtil::ExecuteExeAsAdmin(const base::CommandLine& cmd,
168 DWORD* exit_code) {
169 base::FilePath::StringType program(cmd.GetProgram().value());
170 DCHECK(!program.empty());
171 DCHECK_NE(program[0], L'\"');
173 base::CommandLine::StringType params(cmd.GetCommandLineString());
174 if (params[0] == '"') {
175 DCHECK_EQ('"', params[program.length() + 1]);
176 DCHECK_EQ(program, params.substr(1, program.length()));
177 params = params.substr(program.length() + 2);
178 } else {
179 DCHECK_EQ(program, params.substr(0, program.length()));
180 params = params.substr(program.length());
183 base::TrimWhitespace(params, base::TRIM_ALL, &params);
185 HWND uac_foreground_window = CreateUACForegroundWindow();
187 SHELLEXECUTEINFO info = {0};
188 info.cbSize = sizeof(SHELLEXECUTEINFO);
189 info.fMask = SEE_MASK_NOCLOSEPROCESS;
190 info.hwnd = uac_foreground_window;
191 info.lpVerb = L"runas";
192 info.lpFile = program.c_str();
193 info.lpParameters = params.c_str();
194 info.nShow = SW_SHOW;
196 bool success = false;
197 if (::ShellExecuteEx(&info) == TRUE) {
198 ::WaitForSingleObject(info.hProcess, INFINITE);
199 DWORD ret_val = 0;
200 if (::GetExitCodeProcess(info.hProcess, &ret_val)) {
201 success = true;
202 if (exit_code)
203 *exit_code = ret_val;
207 if (uac_foreground_window) {
208 DestroyWindow(uac_foreground_window);
211 return success;
214 base::CommandLine InstallUtil::GetChromeUninstallCmd(
215 bool system_install,
216 BrowserDistribution::Type distribution_type) {
217 ProductState state;
218 if (state.Initialize(system_install, distribution_type)) {
219 return state.uninstall_command();
221 return base::CommandLine(base::CommandLine::NO_PROGRAM);
224 void InstallUtil::GetChromeVersion(BrowserDistribution* dist,
225 bool system_install,
226 Version* version) {
227 DCHECK(dist);
228 RegKey key;
229 HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
230 LONG result = key.Open(reg_root,
231 dist->GetVersionKey().c_str(),
232 KEY_QUERY_VALUE | KEY_WOW64_32KEY);
234 base::string16 version_str;
235 if (result == ERROR_SUCCESS)
236 result = key.ReadValue(google_update::kRegVersionField, &version_str);
238 *version = Version();
239 if (result == ERROR_SUCCESS && !version_str.empty()) {
240 VLOG(1) << "Existing " << dist->GetDisplayName() << " version found "
241 << version_str;
242 *version = Version(base::UTF16ToASCII(version_str));
243 } else {
244 DCHECK_EQ(ERROR_FILE_NOT_FOUND, result);
245 VLOG(1) << "No existing " << dist->GetDisplayName()
246 << " install found.";
250 void InstallUtil::GetCriticalUpdateVersion(BrowserDistribution* dist,
251 bool system_install,
252 Version* version) {
253 DCHECK(dist);
254 RegKey key;
255 HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
256 LONG result = key.Open(reg_root,
257 dist->GetVersionKey().c_str(),
258 KEY_QUERY_VALUE | KEY_WOW64_32KEY);
260 base::string16 version_str;
261 if (result == ERROR_SUCCESS)
262 result = key.ReadValue(google_update::kRegCriticalVersionField,
263 &version_str);
265 *version = Version();
266 if (result == ERROR_SUCCESS && !version_str.empty()) {
267 VLOG(1) << "Critical Update version for " << dist->GetDisplayName()
268 << " found " << version_str;
269 *version = Version(base::UTF16ToASCII(version_str));
270 } else {
271 DCHECK_EQ(ERROR_FILE_NOT_FOUND, result);
272 VLOG(1) << "No existing " << dist->GetDisplayName()
273 << " install found.";
277 bool InstallUtil::IsOSSupported() {
278 // We do not support Win2K or older, or XP without service pack 2.
279 VLOG(1) << base::SysInfo::OperatingSystemName() << ' '
280 << base::SysInfo::OperatingSystemVersion();
281 base::win::Version version = base::win::GetVersion();
282 return (version > base::win::VERSION_XP) ||
283 ((version == base::win::VERSION_XP) &&
284 (base::win::OSInfo::GetInstance()->service_pack().major >= 2));
287 void InstallUtil::AddInstallerResultItems(
288 bool system_install,
289 const base::string16& state_key,
290 installer::InstallStatus status,
291 int string_resource_id,
292 const base::string16* const launch_cmd,
293 WorkItemList* install_list) {
294 DCHECK(install_list);
295 const HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
296 DWORD installer_result = (GetInstallReturnCode(status) == 0) ? 0 : 1;
297 install_list->AddCreateRegKeyWorkItem(root, state_key, KEY_WOW64_32KEY);
298 install_list->AddSetRegValueWorkItem(root,
299 state_key,
300 KEY_WOW64_32KEY,
301 installer::kInstallerResult,
302 installer_result,
303 true);
304 install_list->AddSetRegValueWorkItem(root,
305 state_key,
306 KEY_WOW64_32KEY,
307 installer::kInstallerError,
308 static_cast<DWORD>(status),
309 true);
310 if (string_resource_id != 0) {
311 base::string16 msg = installer::GetLocalizedString(string_resource_id);
312 install_list->AddSetRegValueWorkItem(root,
313 state_key,
314 KEY_WOW64_32KEY,
315 installer::kInstallerResultUIString,
316 msg,
317 true);
319 if (launch_cmd != NULL && !launch_cmd->empty()) {
320 install_list->AddSetRegValueWorkItem(
321 root,
322 state_key,
323 KEY_WOW64_32KEY,
324 installer::kInstallerSuccessLaunchCmdLine,
325 *launch_cmd,
326 true);
330 void InstallUtil::UpdateInstallerStage(bool system_install,
331 const base::string16& state_key_path,
332 installer::InstallerStage stage) {
333 DCHECK_LE(static_cast<installer::InstallerStage>(0), stage);
334 DCHECK_GT(installer::NUM_STAGES, stage);
335 const HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
336 RegKey state_key;
337 LONG result =
338 state_key.Open(root,
339 state_key_path.c_str(),
340 KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_WOW64_32KEY);
341 if (result == ERROR_SUCCESS) {
342 if (stage == installer::NO_STAGE) {
343 result = state_key.DeleteValue(installer::kInstallerExtraCode1);
344 LOG_IF(ERROR, result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND)
345 << "Failed deleting installer stage from " << state_key_path
346 << "; result: " << result;
347 } else {
348 const DWORD extra_code_1 = static_cast<DWORD>(stage);
349 result = state_key.WriteValue(installer::kInstallerExtraCode1,
350 extra_code_1);
351 LOG_IF(ERROR, result != ERROR_SUCCESS)
352 << "Failed writing installer stage to " << state_key_path
353 << "; result: " << result;
355 // TODO(grt): Remove code below here once we're convinced that our use of
356 // Google Update's new InstallerExtraCode1 value is good.
357 installer::ChannelInfo channel_info;
358 // This will return false if the "ap" value isn't present, which is fine.
359 channel_info.Initialize(state_key);
360 if (channel_info.SetStage(kStages[stage]) &&
361 !channel_info.Write(&state_key)) {
362 LOG(ERROR) << "Failed writing installer stage to " << state_key_path;
364 } else {
365 LOG(ERROR) << "Failed opening " << state_key_path
366 << " to update installer stage; result: " << result;
370 bool InstallUtil::IsPerUserInstall(const base::FilePath& exe_path) {
371 scoped_ptr<base::Environment> env(base::Environment::Create());
373 static const char kEnvProgramFilesPath[] = "CHROME_PROBED_PROGRAM_FILES_PATH";
374 std::string env_program_files_path;
375 // Check environment variable to find program files path.
376 base::FilePath program_files_path;
377 if (env->GetVar(kEnvProgramFilesPath, &env_program_files_path) &&
378 !env_program_files_path.empty()) {
379 program_files_path =
380 base::FilePath(base::UTF8ToWide(env_program_files_path));
381 } else {
382 const int kProgramFilesKey =
383 #if defined(_WIN64)
384 // TODO(wfh): Revise this when Chrome is/can be installed in the 64-bit
385 // program files directory.
386 base::DIR_PROGRAM_FILESX86;
387 #else
388 base::DIR_PROGRAM_FILES;
389 #endif
390 if (!PathService::Get(kProgramFilesKey, &program_files_path)) {
391 NOTREACHED();
392 return true;
394 env->SetVar(kEnvProgramFilesPath,
395 base::WideToUTF8(program_files_path.value()));
398 // Return true if the program files path is not a case-insensitive prefix of
399 // the exe path.
400 if (exe_path.value().size() < program_files_path.value().size())
401 return true;
402 DWORD prefix_len =
403 base::saturated_cast<DWORD>(program_files_path.value().size());
404 return ::CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE,
405 exe_path.value().data(), prefix_len,
406 program_files_path.value().data(), prefix_len) !=
407 CSTR_EQUAL;
410 bool InstallUtil::IsMultiInstall(BrowserDistribution* dist,
411 bool system_install) {
412 DCHECK(dist);
413 ProductState state;
414 return state.Initialize(system_install, dist) && state.is_multi_install();
417 bool CheckIsChromeSxSProcess() {
418 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
419 CHECK(command_line);
421 if (command_line->HasSwitch(installer::switches::kChromeSxS))
422 return true;
424 // Also return true if we are running from Chrome SxS installed path.
425 base::FilePath exe_dir;
426 PathService::Get(base::DIR_EXE, &exe_dir);
427 base::string16 chrome_sxs_dir(installer::kGoogleChromeInstallSubDir2);
428 chrome_sxs_dir.append(installer::kSxSSuffix);
430 // This is SxS if current EXE is in or under (possibly multiple levels under)
431 // |chrome_sxs_dir|\|installer::kInstallBinaryDir|
432 std::vector<base::FilePath::StringType> components;
433 exe_dir.GetComponents(&components);
434 // We need at least 1 element in the array for the behavior of the following
435 // loop to be defined. This should always be true, since we're splitting the
436 // path to our executable and one of the components will be the drive letter.
437 DCHECK(!components.empty());
438 typedef std::vector<base::FilePath::StringType>::const_reverse_iterator
439 ComponentsIterator;
440 for (ComponentsIterator current = components.rbegin(), parent = current + 1;
441 parent != components.rend(); current = parent++) {
442 if (base::FilePath::CompareEqualIgnoreCase(
443 *current, installer::kInstallBinaryDir) &&
444 base::FilePath::CompareEqualIgnoreCase(*parent, chrome_sxs_dir)) {
445 return true;
449 return false;
452 bool InstallUtil::IsChromeSxSProcess() {
453 static bool sxs = CheckIsChromeSxSProcess();
454 return sxs;
457 // static
458 bool InstallUtil::IsFirstRunSentinelPresent() {
459 // TODO(msw): Consolidate with first_run::internal::IsFirstRunSentinelPresent.
460 base::FilePath user_data_dir;
461 return !PathService::Get(chrome::DIR_USER_DATA, &user_data_dir) ||
462 base::PathExists(user_data_dir.Append(chrome::kFirstRunSentinel));
465 // static
466 bool InstallUtil::GetEULASentinelFilePath(base::FilePath* path) {
467 base::FilePath user_data_dir;
468 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
469 return false;
470 *path = user_data_dir.Append(installer::kEULASentinelFile);
471 return true;
474 // This method tries to delete a registry key and logs an error message
475 // in case of failure. It returns true if deletion is successful (or the key did
476 // not exist), otherwise false.
477 bool InstallUtil::DeleteRegistryKey(HKEY root_key,
478 const base::string16& key_path,
479 REGSAM wow64_access) {
480 VLOG(1) << "Deleting registry key " << key_path;
481 RegKey target_key;
482 LONG result = target_key.Open(root_key, key_path.c_str(),
483 KEY_READ | KEY_WRITE | wow64_access);
485 if (result == ERROR_FILE_NOT_FOUND)
486 return true;
488 if (result == ERROR_SUCCESS)
489 result = target_key.DeleteKey(L"");
491 if (result != ERROR_SUCCESS) {
492 LOG(ERROR) << "Failed to delete registry key: " << key_path
493 << " error: " << result;
494 return false;
496 return true;
499 // This method tries to delete a registry value and logs an error message
500 // in case of failure. It returns true if deletion is successful (or the key did
501 // not exist), otherwise false.
502 bool InstallUtil::DeleteRegistryValue(HKEY reg_root,
503 const base::string16& key_path,
504 REGSAM wow64_access,
505 const base::string16& value_name) {
506 RegKey key;
507 LONG result = key.Open(reg_root, key_path.c_str(),
508 KEY_SET_VALUE | wow64_access);
509 if (result == ERROR_SUCCESS)
510 result = key.DeleteValue(value_name.c_str());
511 if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) {
512 LOG(ERROR) << "Failed to delete registry value: " << value_name
513 << " error: " << result;
514 return false;
516 return true;
519 // static
520 InstallUtil::ConditionalDeleteResult InstallUtil::DeleteRegistryKeyIf(
521 HKEY root_key,
522 const base::string16& key_to_delete_path,
523 const base::string16& key_to_test_path,
524 const REGSAM wow64_access,
525 const wchar_t* value_name,
526 const RegistryValuePredicate& predicate) {
527 DCHECK(root_key);
528 ConditionalDeleteResult delete_result = NOT_FOUND;
529 RegKey key;
530 base::string16 actual_value;
531 if (key.Open(root_key, key_to_test_path.c_str(),
532 KEY_QUERY_VALUE | wow64_access) == ERROR_SUCCESS &&
533 key.ReadValue(value_name, &actual_value) == ERROR_SUCCESS &&
534 predicate.Evaluate(actual_value)) {
535 key.Close();
536 delete_result = DeleteRegistryKey(root_key,
537 key_to_delete_path,
538 wow64_access)
539 ? DELETED : DELETE_FAILED;
541 return delete_result;
544 // static
545 InstallUtil::ConditionalDeleteResult InstallUtil::DeleteRegistryValueIf(
546 HKEY root_key,
547 const wchar_t* key_path,
548 REGSAM wow64_access,
549 const wchar_t* value_name,
550 const RegistryValuePredicate& predicate) {
551 DCHECK(root_key);
552 DCHECK(key_path);
553 ConditionalDeleteResult delete_result = NOT_FOUND;
554 RegKey key;
555 base::string16 actual_value;
556 if (key.Open(root_key, key_path,
557 KEY_QUERY_VALUE | KEY_SET_VALUE | wow64_access)
558 == ERROR_SUCCESS &&
559 key.ReadValue(value_name, &actual_value) == ERROR_SUCCESS &&
560 predicate.Evaluate(actual_value)) {
561 LONG result = key.DeleteValue(value_name);
562 if (result != ERROR_SUCCESS) {
563 LOG(ERROR) << "Failed to delete registry value: "
564 << (value_name ? value_name : L"(Default)")
565 << " error: " << result;
566 delete_result = DELETE_FAILED;
568 delete_result = DELETED;
570 return delete_result;
573 bool InstallUtil::ValueEquals::Evaluate(const base::string16& value) const {
574 return value == value_to_match_;
577 // static
578 int InstallUtil::GetInstallReturnCode(installer::InstallStatus status) {
579 switch (status) {
580 case installer::FIRST_INSTALL_SUCCESS:
581 case installer::INSTALL_REPAIRED:
582 case installer::NEW_VERSION_UPDATED:
583 case installer::IN_USE_UPDATED:
584 case installer::UNUSED_BINARIES_UNINSTALLED:
585 return 0;
586 default:
587 return status;
591 // static
592 void InstallUtil::ComposeCommandLine(const base::string16& program,
593 const base::string16& arguments,
594 base::CommandLine* command_line) {
595 *command_line =
596 base::CommandLine::FromString(L"\"" + program + L"\" " + arguments);
599 // static
600 base::string16 InstallUtil::GetCurrentDate() {
601 static const wchar_t kDateFormat[] = L"yyyyMMdd";
602 wchar_t date_str[arraysize(kDateFormat)] = {0};
603 int len = GetDateFormatW(LOCALE_INVARIANT, 0, NULL, kDateFormat,
604 date_str, arraysize(date_str));
605 if (len) {
606 --len; // Subtract terminating \0.
607 } else {
608 PLOG(DFATAL) << "GetDateFormat";
611 return base::string16(date_str, len);
614 // Open |path| with minimal access to obtain information about it, returning
615 // true and populating |file| on success.
616 // static
617 bool InstallUtil::ProgramCompare::OpenForInfo(const base::FilePath& path,
618 base::File* file) {
619 DCHECK(file);
620 file->Initialize(path, base::File::FLAG_OPEN);
621 return file->IsValid();
624 // Populate |info| for |file|, returning true on success.
625 // static
626 bool InstallUtil::ProgramCompare::GetInfo(const base::File& file,
627 BY_HANDLE_FILE_INFORMATION* info) {
628 DCHECK(file.IsValid());
629 return GetFileInformationByHandle(file.GetPlatformFile(), info) != 0;
632 InstallUtil::ProgramCompare::ProgramCompare(const base::FilePath& path_to_match)
633 : path_to_match_(path_to_match),
634 file_info_() {
635 DCHECK(!path_to_match_.empty());
636 if (!OpenForInfo(path_to_match_, &file_)) {
637 PLOG(WARNING) << "Failed opening " << path_to_match_.value()
638 << "; falling back to path string comparisons.";
639 } else if (!GetInfo(file_, &file_info_)) {
640 PLOG(WARNING) << "Failed getting information for "
641 << path_to_match_.value()
642 << "; falling back to path string comparisons.";
643 file_.Close();
647 InstallUtil::ProgramCompare::~ProgramCompare() {
650 bool InstallUtil::ProgramCompare::Evaluate(const base::string16& value) const {
651 // Suss out the exe portion of the value, which is expected to be a command
652 // line kinda (or exactly) like:
653 // "c:\foo\bar\chrome.exe" -- "%1"
654 base::FilePath program(base::CommandLine::FromString(value).GetProgram());
655 if (program.empty()) {
656 LOG(WARNING) << "Failed to parse an executable name from command line: \""
657 << value << "\"";
658 return false;
661 return EvaluatePath(program);
664 bool InstallUtil::ProgramCompare::EvaluatePath(
665 const base::FilePath& path) const {
666 // Try the simple thing first: do the paths happen to match?
667 if (base::FilePath::CompareEqualIgnoreCase(path_to_match_.value(),
668 path.value()))
669 return true;
671 // If the paths don't match and we couldn't open the expected file, we've done
672 // our best.
673 if (!file_.IsValid())
674 return false;
676 // Open the program and see if it references the expected file.
677 base::File file;
678 BY_HANDLE_FILE_INFORMATION info = {};
680 return (OpenForInfo(path, &file) &&
681 GetInfo(file, &info) &&
682 info.dwVolumeSerialNumber == file_info_.dwVolumeSerialNumber &&
683 info.nFileIndexHigh == file_info_.nFileIndexHigh &&
684 info.nFileIndexLow == file_info_.nFileIndexLow);