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